max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
3,600
<reponame>duxinyu03/moco package com.github.dreamhead.moco.rest; import com.github.dreamhead.moco.Moco; import com.github.dreamhead.moco.RequestMatcher; import com.github.dreamhead.moco.RestIdMatcher; import static com.github.dreamhead.moco.Moco.uri; import static com.github.dreamhead.moco.util.Preconditions.checkNotNullOrEmpty; import static com.github.dreamhead.moco.util.URLs.join; import static com.github.dreamhead.moco.util.URLs.resourceRoot; public final class RestIdMatchers { public static RestIdMatcher anyId() { return new BaseRestIdMatcher("[^/]*"); } public static RestIdMatcher eq(final String id) { return new BaseRestIdMatcher(checkNotNullOrEmpty(id, "ID should not be null or empty")); } public static RestIdMatcher match(final String uri) { return new BaseRestIdMatcher(checkNotNullOrEmpty(uri, "Match target should not be null or empty")); } private static class BaseRestIdMatcher implements RestIdMatcher { private final String uriPart; BaseRestIdMatcher(final String uriPart) { this.uriPart = uriPart; } @Override public String resourceUri() { return this.uriPart; } @Override public RequestMatcher matcher(final RestIdMatcher resourceName) { return Moco.match(uri(subResourceUri(resourceName))); } private String subResourceUri(final RestIdMatcher resourceName) { return join(resourceRoot(resourceName.resourceUri()), this.uriPart); } } private RestIdMatchers() { } }
622
3,274
<reponame>tyang513/QLExpress package com.ql.util.express.instruction.op; import com.ql.util.express.ArraySwap; import com.ql.util.express.InstructionSetContext; import com.ql.util.express.OperateData; import com.ql.util.express.instruction.OperateDataCacheManager; import com.ql.util.express.instruction.opdata.OperateDataLocalVar; import com.ql.util.express.instruction.opdata.OperateDataVirClass; public class OperatorDef extends OperatorBase { public OperatorDef(String aName) { this.name = aName; } public OperatorDef(String aAliasName, String aName, String aErrorInfo) { this.name = aName; this.aliasName = aAliasName; this.errorInfo = aErrorInfo; } public OperateData executeInner(InstructionSetContext context, ArraySwap list) throws Exception { Object type = list.get(0).getObject(context); String varName = (String)list.get(1).getObject(context); Class<?> tmpClass = null; if(type instanceof Class ){ tmpClass = (Class<?>) type; }else{ tmpClass = OperateDataVirClass.class; } OperateDataLocalVar result = OperateDataCacheManager.fetchOperateDataLocalVar(varName,tmpClass); context.addSymbol(varName, result); return result; } }
410
4,036
package bsh; public class EvalError extends Exception { }
21
1,602
<reponame>jhh67/chapel<filename>test/trivial/shannon/gentest/compTest.c<gh_stars>1000+ #include <stdio.h> main() { int m = 2; int n = 3; int o = 5; int answer = 0; printf("* and * permutations\n"); printf("=========================\n"); answer = m * n * o; printf("%d\n", answer); answer = (m * n) * o; printf("%d\n", answer); answer = m * (n * o); printf("%d\n\n", answer); printf("* and / permutations\n"); printf("=========================\n"); answer = m * n / o; printf("%d\n", answer); answer = (m * n) / o; printf("%d\n", answer); answer = m * (n / o); printf("%d\n\n", answer); printf("* and %% permutations\n"); printf("=========================\n"); answer = m * n % o; printf("%d\n", answer); answer = (m * n) % o; printf("%d\n", answer); answer = m * (n % o); printf("%d\n\n", answer); printf("* and + permutations\n"); printf("=========================\n"); answer = m * n + o; printf("%d\n", answer); answer = (m * n) + o; printf("%d\n", answer); answer = m * (n + o); printf("%d\n\n", answer); printf("* and - permutations\n"); printf("=========================\n"); answer = m * n - o; printf("%d\n", answer); answer = (m * n) - o; printf("%d\n", answer); answer = m * (n - o); printf("%d\n\n", answer); printf("* and < permutations\n"); printf("=========================\n"); answer = m * n < o; printf("%d\n", answer); answer = (m * n) < o; printf("%d\n", answer); answer = m * (n < o); printf("%d\n\n", answer); printf("* and <= permutations\n"); printf("=========================\n"); answer = m * n <= o; printf("%d\n", answer); answer = (m * n) <= o; printf("%d\n", answer); answer = m * (n <= o); printf("%d\n\n", answer); printf("* and > permutations\n"); printf("=========================\n"); answer = m * n > o; printf("%d\n", answer); answer = (m * n) > o; printf("%d\n", answer); answer = m * (n > o); printf("%d\n\n", answer); printf("* and >= permutations\n"); printf("=========================\n"); answer = m * n >= o; printf("%d\n", answer); answer = (m * n) >= o; printf("%d\n", answer); answer = m * (n >= o); printf("%d\n\n", answer); printf("* and == permutations\n"); printf("=========================\n"); answer = m * n == o; printf("%d\n", answer); answer = (m * n) == o; printf("%d\n", answer); answer = m * (n == o); printf("%d\n\n", answer); printf("* and != permutations\n"); printf("=========================\n"); answer = m * n != o; printf("%d\n", answer); answer = (m * n) != o; printf("%d\n", answer); answer = m * (n != o); printf("%d\n\n", answer); printf("* and & permutations\n"); printf("=========================\n"); answer = m * n & o; printf("%d\n", answer); answer = (m * n) & o; printf("%d\n", answer); answer = m * (n & o); printf("%d\n\n", answer); printf("* and ^ permutations\n"); printf("=========================\n"); answer = m * n ^ o; printf("%d\n", answer); answer = (m * n) ^ o; printf("%d\n", answer); answer = m * (n ^ o); printf("%d\n\n", answer); printf("* and | permutations\n"); printf("=========================\n"); answer = m * n | o; printf("%d\n", answer); answer = (m * n) | o; printf("%d\n", answer); answer = m * (n | o); printf("%d\n\n", answer); printf("* and && permutations\n"); printf("=========================\n"); answer = m * n && o; printf("%d\n", answer); answer = (m * n) && o; printf("%d\n", answer); answer = m * (n && o); printf("%d\n\n", answer); printf("* and || permutations\n"); printf("=========================\n"); answer = m * n || o; printf("%d\n", answer); answer = (m * n) || o; printf("%d\n", answer); answer = m * (n || o); printf("%d\n\n", answer); printf("/ and * permutations\n"); printf("=========================\n"); answer = m / n * o; printf("%d\n", answer); answer = (m / n) * o; printf("%d\n", answer); answer = m / (n * o); printf("%d\n\n", answer); printf("/ and / permutations\n"); printf("=========================\n"); answer = m / n / o; printf("%d\n", answer); answer = (m / n) / o; printf("%d\n", answer); n = 10; answer = m / (n / o); printf("%d\n\n", answer); n = 3; printf("/ and %% permutations\n"); printf("=========================\n"); answer = m / n % o; printf("%d\n", answer); answer = (m / n) % o; printf("%d\n", answer); answer = m / (n % o); printf("%d\n\n", answer); printf("/ and + permutations\n"); printf("=========================\n"); answer = m / n + o; printf("%d\n", answer); answer = (m / n) + o; printf("%d\n", answer); answer = m / (n + o); printf("%d\n\n", answer); printf("/ and - permutations\n"); printf("=========================\n"); answer = m / n - o; printf("%d\n", answer); answer = (m / n) - o; printf("%d\n", answer); answer = m / (n - o); printf("%d\n\n", answer); printf("/ and < permutations\n"); printf("=========================\n"); answer = m / n < o; printf("%d\n", answer); answer = (m / n) < o; printf("%d\n", answer); answer = m / (n < o); printf("%d\n\n", answer); printf("/ and <= permutations\n"); printf("=========================\n"); answer = m / n <= o; printf("%d\n", answer); answer = (m / n) <= o; printf("%d\n", answer); answer = m / (n <= o); printf("%d\n\n", answer); printf("/ and > permutations\n"); printf("=========================\n"); answer = m / n > o; printf("%d\n", answer); answer = (m / n) > o; printf("%d\n", answer); n = 10; answer = m / (n > o); printf("%d\n\n", answer); n = 3; printf("/ and >= permutations\n"); printf("=========================\n"); answer = m / n >= o; printf("%d\n", answer); answer = (m / n) >= o; printf("%d\n", answer); n = 10; answer = m / (n >= o); printf("%d\n\n", answer); n = 3; printf("/ and == permutations\n"); printf("=========================\n"); answer = m / n == o; printf("%d\n", answer); answer = (m / n) == o; printf("%d\n", answer); n = 5; answer = m / (n == o); printf("%d\n\n", answer); n = 3; printf("/ and != permutations\n"); printf("=========================\n"); answer = m / n != o; printf("%d\n", answer); answer = (m / n) != o; printf("%d\n", answer); answer = m / (n != o); printf("%d\n\n", answer); printf("/ and & permutations\n"); printf("=========================\n"); answer = m / n & o; printf("%d\n", answer); answer = (m / n) & o; printf("%d\n", answer); answer = m / (n & o); printf("%d\n\n", answer); printf("/ and ^ permutations\n"); printf("=========================\n"); answer = m / n ^ o; printf("%d\n", answer); answer = (m / n) ^ o; printf("%d\n", answer); answer = m / (n ^ o); printf("%d\n\n", answer); printf("/ and | permutations\n"); printf("=========================\n"); answer = m / n | o; printf("%d\n", answer); answer = (m / n) | o; printf("%d\n", answer); answer = m / (n | o); printf("%d\n\n", answer); printf("/ and && permutations\n"); printf("=========================\n"); answer = m / n && o; printf("%d\n", answer); answer = (m / n) && o; printf("%d\n", answer); answer = m / (n && o); printf("%d\n\n", answer); printf("/ and || permutations\n"); printf("=========================\n"); answer = m / n || o; printf("%d\n", answer); answer = (m / n) || o; printf("%d\n", answer); answer = m / (n || o); printf("%d\n\n", answer); printf("%% and * permutations\n"); printf("=========================\n"); answer = m % n * o; printf("%d\n", answer); answer = (m % n) * o; printf("%d\n", answer); answer = m % (n * o); printf("%d\n\n", answer); printf("%% and / permutations\n"); printf("=========================\n"); answer = m % n / o; printf("%d\n", answer); answer = (m % n) / o; printf("%d\n", answer); n = 10; answer = m % (n / o); printf("%d\n\n", answer); n = 3; printf("%% and %% permutations\n"); printf("=========================\n"); answer = m % n % o; printf("%d\n", answer); answer = (m % n) % o; printf("%d\n", answer); answer = m % (n % o); printf("%d\n\n", answer); printf("%% and + permutations\n"); printf("=========================\n"); answer = m % n + o; printf("%d\n", answer); answer = (m % n) + o; printf("%d\n", answer); answer = m % (n + o); printf("%d\n\n", answer); printf("%% and - permutations\n"); printf("=========================\n"); answer = m % n - o; printf("%d\n", answer); answer = (m % n) - o; printf("%d\n", answer); answer = m % (n - o); printf("%d\n\n", answer); printf("%% and < permutations\n"); printf("=========================\n"); answer = m % n < o; printf("%d\n", answer); answer = (m % n) < o; printf("%d\n", answer); answer = m % (n < o); printf("%d\n\n", answer); printf("%% and <= permutations\n"); printf("=========================\n"); answer = m % n <= o; printf("%d\n", answer); answer = (m % n) <= o; printf("%d\n", answer); answer = m % (n <= o); printf("%d\n\n", answer); printf("%% and > permutations\n"); printf("=========================\n"); answer = m % n > o; printf("%d\n", answer); answer = (m % n) > o; printf("%d\n", answer); n = 10; answer = m % (n > o); printf("%d\n\n", answer); n = 3; printf("%% and >= permutations\n"); printf("=========================\n"); answer = m % n >= o; printf("%d\n", answer); answer = (m % n) >= o; printf("%d\n", answer); n = 10; answer = m % (n >= o); printf("%d\n\n", answer); n = 3; printf("%% and == permutations\n"); printf("=========================\n"); answer = m % n == o; printf("%d\n", answer); answer = (m % n) == o; printf("%d\n", answer); n = 5; answer = m % (n == o); printf("%d\n\n", answer); n = 3; printf("%% and != permutations\n"); printf("=========================\n"); answer = m % n != o; printf("%d\n", answer); answer = (m % n) != o; printf("%d\n", answer); answer = m % (n != o); printf("%d\n\n", answer); printf("%% and & permutations\n"); printf("=========================\n"); answer = m % n & o; printf("%d\n", answer); answer = (m % n) & o; printf("%d\n", answer); answer = m % (n & o); printf("%d\n\n", answer); printf("%% and ^ permutations\n"); printf("=========================\n"); answer = m % n ^ o; printf("%d\n", answer); answer = (m % n) ^ o; printf("%d\n", answer); answer = m % (n ^ o); printf("%d\n\n", answer); printf("%% and | permutations\n"); printf("=========================\n"); answer = m % n | o; printf("%d\n", answer); answer = (m % n) | o; printf("%d\n", answer); answer = m % (n | o); printf("%d\n\n", answer); printf("%% and && permutations\n"); printf("=========================\n"); answer = m % n && o; printf("%d\n", answer); answer = (m % n) && o; printf("%d\n", answer); answer = m % (n && o); printf("%d\n\n", answer); printf("%% and || permutations\n"); printf("=========================\n"); answer = m % n || o; printf("%d\n", answer); answer = (m % n) || o; printf("%d\n", answer); answer = m % (n || o); printf("%d\n\n", answer); printf("+ and * permutations\n"); printf("=========================\n"); answer = m + n * o; printf("%d\n", answer); answer = (m + n) * o; printf("%d\n", answer); answer = m + (n * o); printf("%d\n\n", answer); printf("+ and / permutations\n"); printf("=========================\n"); answer = m + n / o; printf("%d\n", answer); answer = (m + n) / o; printf("%d\n", answer); answer = m + (n / o); printf("%d\n\n", answer); printf("+ and %% permutations\n"); printf("=========================\n"); answer = m + n % o; printf("%d\n", answer); answer = (m + n) % o; printf("%d\n", answer); answer = m + (n % o); printf("%d\n\n", answer); printf("+ and + permutations\n"); printf("=========================\n"); answer = m + n + o; printf("%d\n", answer); answer = (m + n) + o; printf("%d\n", answer); answer = m + (n + o); printf("%d\n\n", answer); printf("+ and - permutations\n"); printf("=========================\n"); answer = m + n - o; printf("%d\n", answer); answer = (m + n) - o; printf("%d\n", answer); answer = m + (n - o); printf("%d\n\n", answer); printf("+ and < permutations\n"); printf("=========================\n"); answer = m + n < o; printf("%d\n", answer); answer = (m + n) < o; printf("%d\n", answer); answer = m + (n < o); printf("%d\n\n", answer); printf("+ and <= permutations\n"); printf("=========================\n"); answer = m + n <= o; printf("%d\n", answer); answer = (m + n) <= o; printf("%d\n", answer); answer = m + (n <= o); printf("%d\n\n", answer); printf("+ and > permutations\n"); printf("=========================\n"); answer = m + n > o; printf("%d\n", answer); answer = (m + n) > o; printf("%d\n", answer); answer = m + (n > o); printf("%d\n\n", answer); printf("+ and >= permutations\n"); printf("=========================\n"); answer = m + n >= o; printf("%d\n", answer); answer = (m + n) >= o; printf("%d\n", answer); answer = m + (n >= o); printf("%d\n\n", answer); printf("+ and == permutations\n"); printf("=========================\n"); answer = m + n == o; printf("%d\n", answer); answer = (m + n) == o; printf("%d\n", answer); answer = m + (n == o); printf("%d\n\n", answer); printf("+ and != permutations\n"); printf("=========================\n"); answer = m + n != o; printf("%d\n", answer); answer = (m + n) != o; printf("%d\n", answer); answer = m + (n != o); printf("%d\n\n", answer); printf("+ and & permutations\n"); printf("=========================\n"); answer = m + n & o; printf("%d\n", answer); answer = (m + n) & o; printf("%d\n", answer); answer = m + (n & o); printf("%d\n\n", answer); printf("+ and ^ permutations\n"); printf("=========================\n"); answer = m + n ^ o; printf("%d\n", answer); answer = (m + n) ^ o; printf("%d\n", answer); answer = m + (n ^ o); printf("%d\n\n", answer); printf("+ and | permutations\n"); printf("=========================\n"); answer = m + n | o; printf("%d\n", answer); answer = (m + n) | o; printf("%d\n", answer); answer = m + (n | o); printf("%d\n\n", answer); printf("+ and && permutations\n"); printf("=========================\n"); answer = m + n && o; printf("%d\n", answer); answer = (m + n) && o; printf("%d\n", answer); answer = m + (n && o); printf("%d\n\n", answer); printf("+ and || permutations\n"); printf("=========================\n"); answer = m + n || o; printf("%d\n", answer); answer = (m + n) || o; printf("%d\n", answer); answer = m + (n || o); printf("%d\n\n", answer); printf("- and * permutations\n"); printf("=========================\n"); answer = m - n * o; printf("%d\n", answer); answer = (m - n) * o; printf("%d\n", answer); answer = m - (n * o); printf("%d\n\n", answer); printf("- and / permutations\n"); printf("=========================\n"); answer = m - n / o; printf("%d\n", answer); answer = (m - n) / o; printf("%d\n", answer); answer = m - (n / o); printf("%d\n\n", answer); printf("- and %% permutations\n"); printf("=========================\n"); answer = m - n % o; printf("%d\n", answer); answer = (m - n) % o; printf("%d\n", answer); answer = m - (n % o); printf("%d\n\n", answer); printf("- and + permutations\n"); printf("=========================\n"); answer = m - n + o; printf("%d\n", answer); answer = (m - n) + o; printf("%d\n", answer); answer = m - (n + o); printf("%d\n\n", answer); printf("- and - permutations\n"); printf("=========================\n"); answer = m - n - o; printf("%d\n", answer); answer = (m - n) - o; printf("%d\n", answer); answer = m - (n - o); printf("%d\n\n", answer); printf("- and < permutations\n"); printf("=========================\n"); answer = m - n < o; printf("%d\n", answer); answer = (m - n) < o; printf("%d\n", answer); answer = m - (n < o); printf("%d\n\n", answer); printf("- and <= permutations\n"); printf("=========================\n"); answer = m - n <= o; printf("%d\n", answer); answer = (m - n) <= o; printf("%d\n", answer); answer = m - (n <= o); printf("%d\n\n", answer); printf("- and > permutations\n"); printf("=========================\n"); answer = m - n > o; printf("%d\n", answer); answer = (m - n) > o; printf("%d\n", answer); answer = m - (n > o); printf("%d\n\n", answer); printf("- and >= permutations\n"); printf("=========================\n"); answer = m - n >= o; printf("%d\n", answer); answer = (m - n) >= o; printf("%d\n", answer); answer = m - (n >= o); printf("%d\n\n", answer); printf("- and == permutations\n"); printf("=========================\n"); answer = m - n == o; printf("%d\n", answer); answer = (m - n) == o; printf("%d\n", answer); answer = m - (n == o); printf("%d\n\n", answer); printf("- and != permutations\n"); printf("=========================\n"); answer = m - n != o; printf("%d\n", answer); answer = (m - n) != o; printf("%d\n", answer); answer = m - (n != o); printf("%d\n\n", answer); printf("- and & permutations\n"); printf("=========================\n"); answer = m - n & o; printf("%d\n", answer); answer = (m - n) & o; printf("%d\n", answer); answer = m - (n & o); printf("%d\n\n", answer); printf("- and ^ permutations\n"); printf("=========================\n"); answer = m - n ^ o; printf("%d\n", answer); answer = (m - n) ^ o; printf("%d\n", answer); answer = m - (n ^ o); printf("%d\n\n", answer); printf("- and | permutations\n"); printf("=========================\n"); answer = m - n | o; printf("%d\n", answer); answer = (m - n) | o; printf("%d\n", answer); answer = m - (n | o); printf("%d\n\n", answer); printf("- and && permutations\n"); printf("=========================\n"); answer = m - n && o; printf("%d\n", answer); answer = (m - n) && o; printf("%d\n", answer); answer = m - (n && o); printf("%d\n\n", answer); printf("- and || permutations\n"); printf("=========================\n"); answer = m - n || o; printf("%d\n", answer); answer = (m - n) || o; printf("%d\n", answer); answer = m - (n || o); printf("%d\n\n", answer); printf("< and * permutations\n"); printf("=========================\n"); answer = m < n * o; printf("%d\n", answer); answer = (m < n) * o; printf("%d\n", answer); answer = m < (n * o); printf("%d\n\n", answer); printf("< and / permutations\n"); printf("=========================\n"); answer = m < n / o; printf("%d\n", answer); answer = (m < n) / o; printf("%d\n", answer); answer = m < (n / o); printf("%d\n\n", answer); printf("< and %% permutations\n"); printf("=========================\n"); answer = m < n % o; printf("%d\n", answer); answer = (m < n) % o; printf("%d\n", answer); answer = m < (n % o); printf("%d\n\n", answer); printf("< and + permutations\n"); printf("=========================\n"); answer = m < n + o; printf("%d\n", answer); answer = (m < n) + o; printf("%d\n", answer); answer = m < (n + o); printf("%d\n\n", answer); printf("< and - permutations\n"); printf("=========================\n"); answer = m < n - o; printf("%d\n", answer); answer = (m < n) - o; printf("%d\n", answer); answer = m < (n - o); printf("%d\n\n", answer); printf("< and < permutations\n"); printf("=========================\n"); answer = m < n < o; printf("%d\n", answer); answer = (m < n) < o; printf("%d\n", answer); answer = m < (n < o); printf("%d\n\n", answer); printf("< and <= permutations\n"); printf("=========================\n"); answer = m < n <= o; printf("%d\n", answer); answer = (m < n) <= o; printf("%d\n", answer); answer = m < (n <= o); printf("%d\n\n", answer); printf("< and > permutations\n"); printf("=========================\n"); answer = m < n > o; printf("%d\n", answer); answer = (m < n) > o; printf("%d\n", answer); answer = m < (n > o); printf("%d\n\n", answer); printf("< and >= permutations\n"); printf("=========================\n"); answer = m < n >= o; printf("%d\n", answer); answer = (m < n) >= o; printf("%d\n", answer); answer = m < (n >= o); printf("%d\n\n", answer); printf("< and == permutations\n"); printf("=========================\n"); answer = m < n == o; printf("%d\n", answer); answer = (m < n) == o; printf("%d\n", answer); answer = m < (n == o); printf("%d\n\n", answer); printf("< and != permutations\n"); printf("=========================\n"); answer = m < n != o; printf("%d\n", answer); answer = (m < n) != o; printf("%d\n", answer); answer = m < (n != o); printf("%d\n\n", answer); printf("< and & permutations\n"); printf("=========================\n"); answer = m < n & o; printf("%d\n", answer); answer = (m < n) & o; printf("%d\n", answer); answer = m < (n & o); printf("%d\n\n", answer); printf("< and ^ permutations\n"); printf("=========================\n"); answer = m < n ^ o; printf("%d\n", answer); answer = (m < n) ^ o; printf("%d\n", answer); answer = m < (n ^ o); printf("%d\n\n", answer); printf("< and | permutations\n"); printf("=========================\n"); answer = m < n | o; printf("%d\n", answer); answer = (m < n) | o; printf("%d\n", answer); answer = m < (n | o); printf("%d\n\n", answer); printf("< and && permutations\n"); printf("=========================\n"); answer = m < n && o; printf("%d\n", answer); answer = (m < n) && o; printf("%d\n", answer); answer = m < (n && o); printf("%d\n\n", answer); printf("< and || permutations\n"); printf("=========================\n"); answer = m < n || o; printf("%d\n", answer); answer = (m < n) || o; printf("%d\n", answer); answer = m < (n || o); printf("%d\n\n", answer); printf("<= and * permutations\n"); printf("=========================\n"); answer = m <= n * o; printf("%d\n", answer); answer = (m <= n) * o; printf("%d\n", answer); answer = m <= (n * o); printf("%d\n\n", answer); printf("<= and / permutations\n"); printf("=========================\n"); answer = m <= n / o; printf("%d\n", answer); answer = (m <= n) / o; printf("%d\n", answer); answer = m <= (n / o); printf("%d\n\n", answer); printf("<= and %% permutations\n"); printf("=========================\n"); answer = m <= n % o; printf("%d\n", answer); answer = (m <= n) % o; printf("%d\n", answer); answer = m <= (n % o); printf("%d\n\n", answer); printf("<= and + permutations\n"); printf("=========================\n"); answer = m <= n + o; printf("%d\n", answer); answer = (m <= n) + o; printf("%d\n", answer); answer = m <= (n + o); printf("%d\n\n", answer); printf("<= and - permutations\n"); printf("=========================\n"); answer = m <= n - o; printf("%d\n", answer); answer = (m <= n) - o; printf("%d\n", answer); answer = m <= (n - o); printf("%d\n\n", answer); printf("<= and < permutations\n"); printf("=========================\n"); answer = m <= n < o; printf("%d\n", answer); answer = (m <= n) < o; printf("%d\n", answer); answer = m <= (n < o); printf("%d\n\n", answer); printf("<= and <= permutations\n"); printf("=========================\n"); answer = m <= n <= o; printf("%d\n", answer); answer = (m <= n) <= o; printf("%d\n", answer); answer = m <= (n <= o); printf("%d\n\n", answer); printf("<= and > permutations\n"); printf("=========================\n"); answer = m <= n > o; printf("%d\n", answer); answer = (m <= n) > o; printf("%d\n", answer); answer = m <= (n > o); printf("%d\n\n", answer); printf("<= and >= permutations\n"); printf("=========================\n"); answer = m <= n >= o; printf("%d\n", answer); answer = (m <= n) >= o; printf("%d\n", answer); answer = m <= (n >= o); printf("%d\n\n", answer); printf("<= and == permutations\n"); printf("=========================\n"); answer = m <= n == o; printf("%d\n", answer); answer = (m <= n) == o; printf("%d\n", answer); answer = m <= (n == o); printf("%d\n\n", answer); printf("<= and != permutations\n"); printf("=========================\n"); answer = m <= n != o; printf("%d\n", answer); answer = (m <= n) != o; printf("%d\n", answer); answer = m <= (n != o); printf("%d\n\n", answer); printf("<= and & permutations\n"); printf("=========================\n"); answer = m <= n & o; printf("%d\n", answer); answer = (m <= n) & o; printf("%d\n", answer); answer = m <= (n & o); printf("%d\n\n", answer); printf("<= and ^ permutations\n"); printf("=========================\n"); answer = m <= n ^ o; printf("%d\n", answer); answer = (m <= n) ^ o; printf("%d\n", answer); answer = m <= (n ^ o); printf("%d\n\n", answer); printf("<= and | permutations\n"); printf("=========================\n"); answer = m <= n | o; printf("%d\n", answer); answer = (m <= n) | o; printf("%d\n", answer); answer = m <= (n | o); printf("%d\n\n", answer); printf("<= and && permutations\n"); printf("=========================\n"); answer = m <= n && o; printf("%d\n", answer); answer = (m <= n) && o; printf("%d\n", answer); answer = m <= (n && o); printf("%d\n\n", answer); printf("<= and || permutations\n"); printf("=========================\n"); answer = m <= n || o; printf("%d\n", answer); answer = (m <= n) || o; printf("%d\n", answer); answer = m <= (n || o); printf("%d\n\n", answer); printf("> and * permutations\n"); printf("=========================\n"); answer = m > n * o; printf("%d\n", answer); answer = (m > n) * o; printf("%d\n", answer); answer = m > (n * o); printf("%d\n\n", answer); printf("> and / permutations\n"); printf("=========================\n"); answer = m > n / o; printf("%d\n", answer); answer = (m > n) / o; printf("%d\n", answer); answer = m > (n / o); printf("%d\n\n", answer); printf("> and %% permutations\n"); printf("=========================\n"); answer = m > n % o; printf("%d\n", answer); answer = (m > n) % o; printf("%d\n", answer); answer = m > (n % o); printf("%d\n\n", answer); printf("> and + permutations\n"); printf("=========================\n"); answer = m > n + o; printf("%d\n", answer); answer = (m > n) + o; printf("%d\n", answer); answer = m > (n + o); printf("%d\n\n", answer); printf("> and - permutations\n"); printf("=========================\n"); answer = m > n - o; printf("%d\n", answer); answer = (m > n) - o; printf("%d\n", answer); answer = m > (n - o); printf("%d\n\n", answer); printf("> and < permutations\n"); printf("=========================\n"); answer = m > n < o; printf("%d\n", answer); answer = (m > n) < o; printf("%d\n", answer); answer = m > (n < o); printf("%d\n\n", answer); printf("> and <= permutations\n"); printf("=========================\n"); answer = m > n <= o; printf("%d\n", answer); answer = (m > n) <= o; printf("%d\n", answer); answer = m > (n <= o); printf("%d\n\n", answer); printf("> and > permutations\n"); printf("=========================\n"); answer = m > n > o; printf("%d\n", answer); answer = (m > n) > o; printf("%d\n", answer); answer = m > (n > o); printf("%d\n\n", answer); printf("> and >= permutations\n"); printf("=========================\n"); answer = m > n >= o; printf("%d\n", answer); answer = (m > n) >= o; printf("%d\n", answer); answer = m > (n >= o); printf("%d\n\n", answer); printf("> and == permutations\n"); printf("=========================\n"); answer = m > n == o; printf("%d\n", answer); answer = (m > n) == o; printf("%d\n", answer); answer = m > (n == o); printf("%d\n\n", answer); printf("> and != permutations\n"); printf("=========================\n"); answer = m > n != o; printf("%d\n", answer); answer = (m > n) != o; printf("%d\n", answer); answer = m > (n != o); printf("%d\n\n", answer); printf("> and & permutations\n"); printf("=========================\n"); answer = m > n & o; printf("%d\n", answer); answer = (m > n) & o; printf("%d\n", answer); answer = m > (n & o); printf("%d\n\n", answer); printf("> and ^ permutations\n"); printf("=========================\n"); answer = m > n ^ o; printf("%d\n", answer); answer = (m > n) ^ o; printf("%d\n", answer); answer = m > (n ^ o); printf("%d\n\n", answer); printf("> and | permutations\n"); printf("=========================\n"); answer = m > n | o; printf("%d\n", answer); answer = (m > n) | o; printf("%d\n", answer); answer = m > (n | o); printf("%d\n\n", answer); printf("> and && permutations\n"); printf("=========================\n"); answer = m > n && o; printf("%d\n", answer); answer = (m > n) && o; printf("%d\n", answer); answer = m > (n && o); printf("%d\n\n", answer); printf("> and || permutations\n"); printf("=========================\n"); answer = m > n || o; printf("%d\n", answer); answer = (m > n) || o; printf("%d\n", answer); answer = m > (n || o); printf("%d\n\n", answer); printf(">= and * permutations\n"); printf("=========================\n"); answer = m >= n * o; printf("%d\n", answer); answer = (m >= n) * o; printf("%d\n", answer); answer = m >= (n * o); printf("%d\n\n", answer); printf(">= and / permutations\n"); printf("=========================\n"); answer = m >= n / o; printf("%d\n", answer); answer = (m >= n) / o; printf("%d\n", answer); answer = m >= (n / o); printf("%d\n\n", answer); printf(">= and %% permutations\n"); printf("=========================\n"); answer = m >= n % o; printf("%d\n", answer); answer = (m >= n) % o; printf("%d\n", answer); answer = m >= (n % o); printf("%d\n\n", answer); printf(">= and + permutations\n"); printf("=========================\n"); answer = m >= n + o; printf("%d\n", answer); answer = (m >= n) + o; printf("%d\n", answer); answer = m >= (n + o); printf("%d\n\n", answer); printf(">= and - permutations\n"); printf("=========================\n"); answer = m >= n - o; printf("%d\n", answer); answer = (m >= n) - o; printf("%d\n", answer); answer = m >= (n - o); printf("%d\n\n", answer); printf(">= and < permutations\n"); printf("=========================\n"); answer = m >= n < o; printf("%d\n", answer); answer = (m >= n) < o; printf("%d\n", answer); answer = m >= (n < o); printf("%d\n\n", answer); printf(">= and <= permutations\n"); printf("=========================\n"); answer = m >= n <= o; printf("%d\n", answer); answer = (m >= n) <= o; printf("%d\n", answer); answer = m >= (n <= o); printf("%d\n\n", answer); printf(">= and > permutations\n"); printf("=========================\n"); answer = m >= n > o; printf("%d\n", answer); answer = (m >= n) > o; printf("%d\n", answer); answer = m >= (n > o); printf("%d\n\n", answer); printf(">= and >= permutations\n"); printf("=========================\n"); answer = m >= n >= o; printf("%d\n", answer); answer = (m >= n) >= o; printf("%d\n", answer); answer = m >= (n >= o); printf("%d\n\n", answer); printf(">= and == permutations\n"); printf("=========================\n"); answer = m >= n == o; printf("%d\n", answer); answer = (m >= n) == o; printf("%d\n", answer); answer = m >= (n == o); printf("%d\n\n", answer); printf(">= and != permutations\n"); printf("=========================\n"); answer = m >= n != o; printf("%d\n", answer); answer = (m >= n) != o; printf("%d\n", answer); answer = m >= (n != o); printf("%d\n\n", answer); printf(">= and & permutations\n"); printf("=========================\n"); answer = m >= n & o; printf("%d\n", answer); answer = (m >= n) & o; printf("%d\n", answer); answer = m >= (n & o); printf("%d\n\n", answer); printf(">= and ^ permutations\n"); printf("=========================\n"); answer = m >= n ^ o; printf("%d\n", answer); answer = (m >= n) ^ o; printf("%d\n", answer); answer = m >= (n ^ o); printf("%d\n\n", answer); printf(">= and | permutations\n"); printf("=========================\n"); answer = m >= n | o; printf("%d\n", answer); answer = (m >= n) | o; printf("%d\n", answer); answer = m >= (n | o); printf("%d\n\n", answer); printf(">= and && permutations\n"); printf("=========================\n"); answer = m >= n && o; printf("%d\n", answer); answer = (m >= n) && o; printf("%d\n", answer); answer = m >= (n && o); printf("%d\n\n", answer); printf(">= and || permutations\n"); printf("=========================\n"); answer = m >= n || o; printf("%d\n", answer); answer = (m >= n) || o; printf("%d\n", answer); answer = m >= (n || o); printf("%d\n\n", answer); printf("== and * permutations\n"); printf("=========================\n"); answer = m == n * o; printf("%d\n", answer); answer = (m == n) * o; printf("%d\n", answer); answer = m == (n * o); printf("%d\n\n", answer); printf("== and / permutations\n"); printf("=========================\n"); answer = m == n / o; printf("%d\n", answer); answer = (m == n) / o; printf("%d\n", answer); answer = m == (n / o); printf("%d\n\n", answer); printf("== and %% permutations\n"); printf("=========================\n"); answer = m == n % o; printf("%d\n", answer); answer = (m == n) % o; printf("%d\n", answer); answer = m == (n % o); printf("%d\n\n", answer); printf("== and + permutations\n"); printf("=========================\n"); answer = m == n + o; printf("%d\n", answer); answer = (m == n) + o; printf("%d\n", answer); answer = m == (n + o); printf("%d\n\n", answer); printf("== and - permutations\n"); printf("=========================\n"); answer = m == n - o; printf("%d\n", answer); answer = (m == n) - o; printf("%d\n", answer); answer = m == (n - o); printf("%d\n\n", answer); printf("== and < permutations\n"); printf("=========================\n"); answer = m == n < o; printf("%d\n", answer); answer = (m == n) < o; printf("%d\n", answer); answer = m == (n < o); printf("%d\n\n", answer); printf("== and <= permutations\n"); printf("=========================\n"); answer = m == n <= o; printf("%d\n", answer); answer = (m == n) <= o; printf("%d\n", answer); answer = m == (n <= o); printf("%d\n\n", answer); printf("== and > permutations\n"); printf("=========================\n"); answer = m == n > o; printf("%d\n", answer); answer = (m == n) > o; printf("%d\n", answer); answer = m == (n > o); printf("%d\n\n", answer); printf("== and >= permutations\n"); printf("=========================\n"); answer = m == n >= o; printf("%d\n", answer); answer = (m == n) >= o; printf("%d\n", answer); answer = m == (n >= o); printf("%d\n\n", answer); printf("== and == permutations\n"); printf("=========================\n"); answer = m == n == o; printf("%d\n", answer); answer = (m == n) == o; printf("%d\n", answer); answer = m == (n == o); printf("%d\n\n", answer); printf("== and != permutations\n"); printf("=========================\n"); answer = m == n != o; printf("%d\n", answer); answer = (m == n) != o; printf("%d\n", answer); answer = m == (n != o); printf("%d\n\n", answer); printf("== and & permutations\n"); printf("=========================\n"); answer = m == n & o; printf("%d\n", answer); answer = (m == n) & o; printf("%d\n", answer); answer = m == (n & o); printf("%d\n\n", answer); printf("== and ^ permutations\n"); printf("=========================\n"); answer = m == n ^ o; printf("%d\n", answer); answer = (m == n) ^ o; printf("%d\n", answer); answer = m == (n ^ o); printf("%d\n\n", answer); printf("== and | permutations\n"); printf("=========================\n"); answer = m == n | o; printf("%d\n", answer); answer = (m == n) | o; printf("%d\n", answer); answer = m == (n | o); printf("%d\n\n", answer); printf("== and && permutations\n"); printf("=========================\n"); answer = m == n && o; printf("%d\n", answer); answer = (m == n) && o; printf("%d\n", answer); answer = m == (n && o); printf("%d\n\n", answer); printf("== and || permutations\n"); printf("=========================\n"); answer = m == n || o; printf("%d\n", answer); answer = (m == n) || o; printf("%d\n", answer); answer = m == (n || o); printf("%d\n\n", answer); printf("!= and * permutations\n"); printf("=========================\n"); answer = m != n * o; printf("%d\n", answer); answer = (m != n) * o; printf("%d\n", answer); answer = m != (n * o); printf("%d\n\n", answer); printf("!= and / permutations\n"); printf("=========================\n"); answer = m != n / o; printf("%d\n", answer); answer = (m != n) / o; printf("%d\n", answer); answer = m != (n / o); printf("%d\n\n", answer); printf("!= and %% permutations\n"); printf("=========================\n"); answer = m != n % o; printf("%d\n", answer); answer = (m != n) % o; printf("%d\n", answer); answer = m != (n % o); printf("%d\n\n", answer); printf("!= and + permutations\n"); printf("=========================\n"); answer = m != n + o; printf("%d\n", answer); answer = (m != n) + o; printf("%d\n", answer); answer = m != (n + o); printf("%d\n\n", answer); printf("!= and - permutations\n"); printf("=========================\n"); answer = m != n - o; printf("%d\n", answer); answer = (m != n) - o; printf("%d\n", answer); answer = m != (n - o); printf("%d\n\n", answer); printf("!= and < permutations\n"); printf("=========================\n"); answer = m != n < o; printf("%d\n", answer); answer = (m != n) < o; printf("%d\n", answer); answer = m != (n < o); printf("%d\n\n", answer); printf("!= and <= permutations\n"); printf("=========================\n"); answer = m != n <= o; printf("%d\n", answer); answer = (m != n) <= o; printf("%d\n", answer); answer = m != (n <= o); printf("%d\n\n", answer); printf("!= and > permutations\n"); printf("=========================\n"); answer = m != n > o; printf("%d\n", answer); answer = (m != n) > o; printf("%d\n", answer); answer = m != (n > o); printf("%d\n\n", answer); printf("!= and >= permutations\n"); printf("=========================\n"); answer = m != n >= o; printf("%d\n", answer); answer = (m != n) >= o; printf("%d\n", answer); answer = m != (n >= o); printf("%d\n\n", answer); printf("!= and == permutations\n"); printf("=========================\n"); answer = m != n == o; printf("%d\n", answer); answer = (m != n) == o; printf("%d\n", answer); answer = m != (n == o); printf("%d\n\n", answer); printf("!= and != permutations\n"); printf("=========================\n"); answer = m != n != o; printf("%d\n", answer); answer = (m != n) != o; printf("%d\n", answer); answer = m != (n != o); printf("%d\n\n", answer); printf("!= and & permutations\n"); printf("=========================\n"); answer = m != n & o; printf("%d\n", answer); answer = (m != n) & o; printf("%d\n", answer); answer = m != (n & o); printf("%d\n\n", answer); printf("!= and ^ permutations\n"); printf("=========================\n"); answer = m != n ^ o; printf("%d\n", answer); answer = (m != n) ^ o; printf("%d\n", answer); answer = m != (n ^ o); printf("%d\n\n", answer); printf("!= and | permutations\n"); printf("=========================\n"); answer = m != n | o; printf("%d\n", answer); answer = (m != n) | o; printf("%d\n", answer); answer = m != (n | o); printf("%d\n\n", answer); printf("!= and && permutations\n"); printf("=========================\n"); answer = m != n && o; printf("%d\n", answer); answer = (m != n) && o; printf("%d\n", answer); answer = m != (n && o); printf("%d\n\n", answer); printf("!= and || permutations\n"); printf("=========================\n"); answer = m != n || o; printf("%d\n", answer); answer = (m != n) || o; printf("%d\n", answer); answer = m != (n || o); printf("%d\n\n", answer); printf("& and * permutations\n"); printf("=========================\n"); answer = m & n * o; printf("%d\n", answer); answer = (m & n) * o; printf("%d\n", answer); answer = m & (n * o); printf("%d\n\n", answer); printf("& and / permutations\n"); printf("=========================\n"); answer = m & n / o; printf("%d\n", answer); answer = (m & n) / o; printf("%d\n", answer); answer = m & (n / o); printf("%d\n\n", answer); printf("& and %% permutations\n"); printf("=========================\n"); answer = m & n % o; printf("%d\n", answer); answer = (m & n) % o; printf("%d\n", answer); answer = m & (n % o); printf("%d\n\n", answer); printf("& and + permutations\n"); printf("=========================\n"); answer = m & n + o; printf("%d\n", answer); answer = (m & n) + o; printf("%d\n", answer); answer = m & (n + o); printf("%d\n\n", answer); printf("& and - permutations\n"); printf("=========================\n"); answer = m & n - o; printf("%d\n", answer); answer = (m & n) - o; printf("%d\n", answer); answer = m & (n - o); printf("%d\n\n", answer); printf("& and < permutations\n"); printf("=========================\n"); answer = m & n < o; printf("%d\n", answer); answer = (m & n) < o; printf("%d\n", answer); answer = m & (n < o); printf("%d\n\n", answer); printf("& and <= permutations\n"); printf("=========================\n"); answer = m & n <= o; printf("%d\n", answer); answer = (m & n) <= o; printf("%d\n", answer); answer = m & (n <= o); printf("%d\n\n", answer); printf("& and > permutations\n"); printf("=========================\n"); answer = m & n > o; printf("%d\n", answer); answer = (m & n) > o; printf("%d\n", answer); answer = m & (n > o); printf("%d\n\n", answer); printf("& and >= permutations\n"); printf("=========================\n"); answer = m & n >= o; printf("%d\n", answer); answer = (m & n) >= o; printf("%d\n", answer); answer = m & (n >= o); printf("%d\n\n", answer); printf("& and == permutations\n"); printf("=========================\n"); answer = m & n == o; printf("%d\n", answer); answer = (m & n) == o; printf("%d\n", answer); answer = m & (n == o); printf("%d\n\n", answer); printf("& and != permutations\n"); printf("=========================\n"); answer = m & n != o; printf("%d\n", answer); answer = (m & n) != o; printf("%d\n", answer); answer = m & (n != o); printf("%d\n\n", answer); printf("& and & permutations\n"); printf("=========================\n"); answer = m & n & o; printf("%d\n", answer); answer = (m & n) & o; printf("%d\n", answer); answer = m & (n & o); printf("%d\n\n", answer); printf("& and ^ permutations\n"); printf("=========================\n"); answer = m & n ^ o; printf("%d\n", answer); answer = (m & n) ^ o; printf("%d\n", answer); answer = m & (n ^ o); printf("%d\n\n", answer); printf("& and | permutations\n"); printf("=========================\n"); answer = m & n | o; printf("%d\n", answer); answer = (m & n) | o; printf("%d\n", answer); answer = m & (n | o); printf("%d\n\n", answer); printf("& and && permutations\n"); printf("=========================\n"); answer = m & n && o; printf("%d\n", answer); answer = (m & n) && o; printf("%d\n", answer); answer = m & (n && o); printf("%d\n\n", answer); printf("& and || permutations\n"); printf("=========================\n"); answer = m & n || o; printf("%d\n", answer); answer = (m & n) || o; printf("%d\n", answer); answer = m & (n || o); printf("%d\n\n", answer); printf("^ and * permutations\n"); printf("=========================\n"); answer = m ^ n * o; printf("%d\n", answer); answer = (m ^ n) * o; printf("%d\n", answer); answer = m ^ (n * o); printf("%d\n\n", answer); printf("^ and / permutations\n"); printf("=========================\n"); answer = m ^ n / o; printf("%d\n", answer); answer = (m ^ n) / o; printf("%d\n", answer); answer = m ^ (n / o); printf("%d\n\n", answer); printf("^ and %% permutations\n"); printf("=========================\n"); answer = m ^ n % o; printf("%d\n", answer); answer = (m ^ n) % o; printf("%d\n", answer); answer = m ^ (n % o); printf("%d\n\n", answer); printf("^ and + permutations\n"); printf("=========================\n"); answer = m ^ n + o; printf("%d\n", answer); answer = (m ^ n) + o; printf("%d\n", answer); answer = m ^ (n + o); printf("%d\n\n", answer); printf("^ and - permutations\n"); printf("=========================\n"); answer = m ^ n - o; printf("%d\n", answer); answer = (m ^ n) - o; printf("%d\n", answer); answer = m ^ (n - o); printf("%d\n\n", answer); printf("^ and < permutations\n"); printf("=========================\n"); answer = m ^ n < o; printf("%d\n", answer); answer = (m ^ n) < o; printf("%d\n", answer); answer = m ^ (n < o); printf("%d\n\n", answer); printf("^ and <= permutations\n"); printf("=========================\n"); answer = m ^ n <= o; printf("%d\n", answer); answer = (m ^ n) <= o; printf("%d\n", answer); answer = m ^ (n <= o); printf("%d\n\n", answer); printf("^ and > permutations\n"); printf("=========================\n"); answer = m ^ n > o; printf("%d\n", answer); answer = (m ^ n) > o; printf("%d\n", answer); answer = m ^ (n > o); printf("%d\n\n", answer); printf("^ and >= permutations\n"); printf("=========================\n"); answer = m ^ n >= o; printf("%d\n", answer); answer = (m ^ n) >= o; printf("%d\n", answer); answer = m ^ (n >= o); printf("%d\n\n", answer); printf("^ and == permutations\n"); printf("=========================\n"); answer = m ^ n == o; printf("%d\n", answer); answer = (m ^ n) == o; printf("%d\n", answer); answer = m ^ (n == o); printf("%d\n\n", answer); printf("^ and != permutations\n"); printf("=========================\n"); answer = m ^ n != o; printf("%d\n", answer); answer = (m ^ n) != o; printf("%d\n", answer); answer = m ^ (n != o); printf("%d\n\n", answer); printf("^ and & permutations\n"); printf("=========================\n"); answer = m ^ n & o; printf("%d\n", answer); answer = (m ^ n) & o; printf("%d\n", answer); answer = m ^ (n & o); printf("%d\n\n", answer); printf("^ and ^ permutations\n"); printf("=========================\n"); answer = m ^ n ^ o; printf("%d\n", answer); answer = (m ^ n) ^ o; printf("%d\n", answer); answer = m ^ (n ^ o); printf("%d\n\n", answer); printf("^ and | permutations\n"); printf("=========================\n"); answer = m ^ n | o; printf("%d\n", answer); answer = (m ^ n) | o; printf("%d\n", answer); answer = m ^ (n | o); printf("%d\n\n", answer); printf("^ and && permutations\n"); printf("=========================\n"); answer = m ^ n && o; printf("%d\n", answer); answer = (m ^ n) && o; printf("%d\n", answer); answer = m ^ (n && o); printf("%d\n\n", answer); printf("^ and || permutations\n"); printf("=========================\n"); answer = m ^ n || o; printf("%d\n", answer); answer = (m ^ n) || o; printf("%d\n", answer); answer = m ^ (n || o); printf("%d\n\n", answer); printf("| and * permutations\n"); printf("=========================\n"); answer = m | n * o; printf("%d\n", answer); answer = (m | n) * o; printf("%d\n", answer); answer = m | (n * o); printf("%d\n\n", answer); printf("| and / permutations\n"); printf("=========================\n"); answer = m | n / o; printf("%d\n", answer); answer = (m | n) / o; printf("%d\n", answer); answer = m | (n / o); printf("%d\n\n", answer); printf("| and %% permutations\n"); printf("=========================\n"); answer = m | n % o; printf("%d\n", answer); answer = (m | n) % o; printf("%d\n", answer); answer = m | (n % o); printf("%d\n\n", answer); printf("| and + permutations\n"); printf("=========================\n"); answer = m | n + o; printf("%d\n", answer); answer = (m | n) + o; printf("%d\n", answer); answer = m | (n + o); printf("%d\n\n", answer); printf("| and - permutations\n"); printf("=========================\n"); answer = m | n - o; printf("%d\n", answer); answer = (m | n) - o; printf("%d\n", answer); answer = m | (n - o); printf("%d\n\n", answer); printf("| and < permutations\n"); printf("=========================\n"); answer = m | n < o; printf("%d\n", answer); answer = (m | n) < o; printf("%d\n", answer); answer = m | (n < o); printf("%d\n\n", answer); printf("| and <= permutations\n"); printf("=========================\n"); answer = m | n <= o; printf("%d\n", answer); answer = (m | n) <= o; printf("%d\n", answer); answer = m | (n <= o); printf("%d\n\n", answer); printf("| and > permutations\n"); printf("=========================\n"); answer = m | n > o; printf("%d\n", answer); answer = (m | n) > o; printf("%d\n", answer); answer = m | (n > o); printf("%d\n\n", answer); printf("| and >= permutations\n"); printf("=========================\n"); answer = m | n >= o; printf("%d\n", answer); answer = (m | n) >= o; printf("%d\n", answer); answer = m | (n >= o); printf("%d\n\n", answer); printf("| and == permutations\n"); printf("=========================\n"); answer = m | n == o; printf("%d\n", answer); answer = (m | n) == o; printf("%d\n", answer); answer = m | (n == o); printf("%d\n\n", answer); printf("| and != permutations\n"); printf("=========================\n"); answer = m | n != o; printf("%d\n", answer); answer = (m | n) != o; printf("%d\n", answer); answer = m | (n != o); printf("%d\n\n", answer); printf("| and & permutations\n"); printf("=========================\n"); answer = m | n & o; printf("%d\n", answer); answer = (m | n) & o; printf("%d\n", answer); answer = m | (n & o); printf("%d\n\n", answer); printf("| and ^ permutations\n"); printf("=========================\n"); answer = m | n ^ o; printf("%d\n", answer); answer = (m | n) ^ o; printf("%d\n", answer); answer = m | (n ^ o); printf("%d\n\n", answer); printf("| and | permutations\n"); printf("=========================\n"); answer = m | n | o; printf("%d\n", answer); answer = (m | n) | o; printf("%d\n", answer); answer = m | (n | o); printf("%d\n\n", answer); printf("| and && permutations\n"); printf("=========================\n"); answer = m | n && o; printf("%d\n", answer); answer = (m | n) && o; printf("%d\n", answer); answer = m | (n && o); printf("%d\n\n", answer); printf("| and || permutations\n"); printf("=========================\n"); answer = m | n || o; printf("%d\n", answer); answer = (m | n) || o; printf("%d\n", answer); answer = m | (n || o); printf("%d\n\n", answer); printf("&& and * permutations\n"); printf("=========================\n"); answer = m && n * o; printf("%d\n", answer); answer = (m && n) * o; printf("%d\n", answer); answer = m && (n * o); printf("%d\n\n", answer); printf("&& and / permutations\n"); printf("=========================\n"); answer = m && n / o; printf("%d\n", answer); answer = (m && n) / o; printf("%d\n", answer); answer = m && (n / o); printf("%d\n\n", answer); printf("&& and %% permutations\n"); printf("=========================\n"); answer = m && n % o; printf("%d\n", answer); answer = (m && n) % o; printf("%d\n", answer); answer = m && (n % o); printf("%d\n\n", answer); printf("&& and + permutations\n"); printf("=========================\n"); answer = m && n + o; printf("%d\n", answer); answer = (m && n) + o; printf("%d\n", answer); answer = m && (n + o); printf("%d\n\n", answer); printf("&& and - permutations\n"); printf("=========================\n"); answer = m && n - o; printf("%d\n", answer); answer = (m && n) - o; printf("%d\n", answer); answer = m && (n - o); printf("%d\n\n", answer); printf("&& and < permutations\n"); printf("=========================\n"); answer = m && n < o; printf("%d\n", answer); answer = (m && n) < o; printf("%d\n", answer); answer = m && (n < o); printf("%d\n\n", answer); printf("&& and <= permutations\n"); printf("=========================\n"); answer = m && n <= o; printf("%d\n", answer); answer = (m && n) <= o; printf("%d\n", answer); answer = m && (n <= o); printf("%d\n\n", answer); printf("&& and > permutations\n"); printf("=========================\n"); answer = m && n > o; printf("%d\n", answer); answer = (m && n) > o; printf("%d\n", answer); answer = m && (n > o); printf("%d\n\n", answer); printf("&& and >= permutations\n"); printf("=========================\n"); answer = m && n >= o; printf("%d\n", answer); answer = (m && n) >= o; printf("%d\n", answer); answer = m && (n >= o); printf("%d\n\n", answer); printf("&& and == permutations\n"); printf("=========================\n"); answer = m && n == o; printf("%d\n", answer); answer = (m && n) == o; printf("%d\n", answer); answer = m && (n == o); printf("%d\n\n", answer); printf("&& and != permutations\n"); printf("=========================\n"); answer = m && n != o; printf("%d\n", answer); answer = (m && n) != o; printf("%d\n", answer); answer = m && (n != o); printf("%d\n\n", answer); printf("&& and & permutations\n"); printf("=========================\n"); answer = m && n & o; printf("%d\n", answer); answer = (m && n) & o; printf("%d\n", answer); answer = m && (n & o); printf("%d\n\n", answer); printf("&& and ^ permutations\n"); printf("=========================\n"); answer = m && n ^ o; printf("%d\n", answer); answer = (m && n) ^ o; printf("%d\n", answer); answer = m && (n ^ o); printf("%d\n\n", answer); printf("&& and | permutations\n"); printf("=========================\n"); answer = m && n | o; printf("%d\n", answer); answer = (m && n) | o; printf("%d\n", answer); answer = m && (n | o); printf("%d\n\n", answer); printf("&& and && permutations\n"); printf("=========================\n"); answer = m && n && o; printf("%d\n", answer); answer = (m && n) && o; printf("%d\n", answer); answer = m && (n && o); printf("%d\n\n", answer); printf("&& and || permutations\n"); printf("=========================\n"); answer = m && n || o; printf("%d\n", answer); answer = (m && n) || o; printf("%d\n", answer); answer = m && (n || o); printf("%d\n\n", answer); printf("|| and * permutations\n"); printf("=========================\n"); answer = m || n * o; printf("%d\n", answer); answer = (m || n) * o; printf("%d\n", answer); answer = m || (n * o); printf("%d\n\n", answer); printf("|| and / permutations\n"); printf("=========================\n"); answer = m || n / o; printf("%d\n", answer); answer = (m || n) / o; printf("%d\n", answer); answer = m || (n / o); printf("%d\n\n", answer); printf("|| and %% permutations\n"); printf("=========================\n"); answer = m || n % o; printf("%d\n", answer); answer = (m || n) % o; printf("%d\n", answer); answer = m || (n % o); printf("%d\n\n", answer); printf("|| and + permutations\n"); printf("=========================\n"); answer = m || n + o; printf("%d\n", answer); answer = (m || n) + o; printf("%d\n", answer); answer = m || (n + o); printf("%d\n\n", answer); printf("|| and - permutations\n"); printf("=========================\n"); answer = m || n - o; printf("%d\n", answer); answer = (m || n) - o; printf("%d\n", answer); answer = m || (n - o); printf("%d\n\n", answer); printf("|| and < permutations\n"); printf("=========================\n"); answer = m || n < o; printf("%d\n", answer); answer = (m || n) < o; printf("%d\n", answer); answer = m || (n < o); printf("%d\n\n", answer); printf("|| and <= permutations\n"); printf("=========================\n"); answer = m || n <= o; printf("%d\n", answer); answer = (m || n) <= o; printf("%d\n", answer); answer = m || (n <= o); printf("%d\n\n", answer); printf("|| and > permutations\n"); printf("=========================\n"); answer = m || n > o; printf("%d\n", answer); answer = (m || n) > o; printf("%d\n", answer); answer = m || (n > o); printf("%d\n\n", answer); printf("|| and >= permutations\n"); printf("=========================\n"); answer = m || n >= o; printf("%d\n", answer); answer = (m || n) >= o; printf("%d\n", answer); answer = m || (n >= o); printf("%d\n\n", answer); printf("|| and == permutations\n"); printf("=========================\n"); answer = m || n == o; printf("%d\n", answer); answer = (m || n) == o; printf("%d\n", answer); answer = m || (n == o); printf("%d\n\n", answer); printf("|| and != permutations\n"); printf("=========================\n"); answer = m || n != o; printf("%d\n", answer); answer = (m || n) != o; printf("%d\n", answer); answer = m || (n != o); printf("%d\n\n", answer); printf("|| and & permutations\n"); printf("=========================\n"); answer = m || n & o; printf("%d\n", answer); answer = (m || n) & o; printf("%d\n", answer); answer = m || (n & o); printf("%d\n\n", answer); printf("|| and ^ permutations\n"); printf("=========================\n"); answer = m || n ^ o; printf("%d\n", answer); answer = (m || n) ^ o; printf("%d\n", answer); answer = m || (n ^ o); printf("%d\n\n", answer); printf("|| and | permutations\n"); printf("=========================\n"); answer = m || n | o; printf("%d\n", answer); answer = (m || n) | o; printf("%d\n", answer); answer = m || (n | o); printf("%d\n\n", answer); printf("|| and && permutations\n"); printf("=========================\n"); answer = m || n && o; printf("%d\n", answer); answer = (m || n) && o; printf("%d\n", answer); answer = m || (n && o); printf("%d\n\n", answer); printf("|| and || permutations\n"); printf("=========================\n"); answer = m || n || o; printf("%d\n", answer); answer = (m || n) || o; printf("%d\n", answer); answer = m || (n || o); printf("%d\n\n", answer); }
24,035
442
<reponame>danqiusheng/spring-framework-5.1.x<filename>spring-websocket/src/main/java/org/springframework/web/socket/client/standard/StandardWebSocketClient.java /* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.socket.client.standard; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URI; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.Callable; import javax.websocket.ClientEndpointConfig; import javax.websocket.ClientEndpointConfig.Configurator; import javax.websocket.ContainerProvider; import javax.websocket.Endpoint; import javax.websocket.Extension; import javax.websocket.HandshakeResponse; import javax.websocket.WebSocketContainer; import org.springframework.core.task.AsyncListenableTaskExecutor; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.core.task.TaskExecutor; import org.springframework.http.HttpHeaders; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureTask; import org.springframework.web.socket.WebSocketExtension; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter; import org.springframework.web.socket.adapter.standard.StandardWebSocketSession; import org.springframework.web.socket.adapter.standard.WebSocketToStandardExtensionAdapter; import org.springframework.web.socket.client.AbstractWebSocketClient; /** * A WebSocketClient based on standard Java WebSocket API. * * @author <NAME> * @since 4.0 */ public class StandardWebSocketClient extends AbstractWebSocketClient { private final WebSocketContainer webSocketContainer; private final Map<String,Object> userProperties = new HashMap<>(); @Nullable private AsyncListenableTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor(); /** * Default constructor that calls {@code ContainerProvider.getWebSocketContainer()} * to obtain a (new) {@link WebSocketContainer} instance. Also see constructor * accepting existing {@code WebSocketContainer} instance. */ public StandardWebSocketClient() { this.webSocketContainer = ContainerProvider.getWebSocketContainer(); } /** * Constructor accepting an existing {@link WebSocketContainer} instance. * <p>For XML configuration, see {@link WebSocketContainerFactoryBean}. For Java * configuration, use {@code ContainerProvider.getWebSocketContainer()} to obtain * the {@code WebSocketContainer} instance. */ public StandardWebSocketClient(WebSocketContainer webSocketContainer) { Assert.notNull(webSocketContainer, "WebSocketContainer must not be null"); this.webSocketContainer = webSocketContainer; } /** * The standard Java WebSocket API allows passing "user properties" to the * server via {@link ClientEndpointConfig#getUserProperties() userProperties}. * Use this property to configure one or more properties to be passed on * every handshake. */ public void setUserProperties(@Nullable Map<String, Object> userProperties) { if (userProperties != null) { this.userProperties.putAll(userProperties); } } /** * The configured user properties. */ public Map<String, Object> getUserProperties() { return this.userProperties; } /** * Set an {@link AsyncListenableTaskExecutor} to use when opening connections. * If this property is set to {@code null}, calls to any of the * {@code doHandshake} methods will block until the connection is established. * <p>By default, an instance of {@code SimpleAsyncTaskExecutor} is used. */ public void setTaskExecutor(@Nullable AsyncListenableTaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } /** * Return the configured {@link TaskExecutor}. */ @Nullable public AsyncListenableTaskExecutor getTaskExecutor() { return this.taskExecutor; } @Override protected ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler webSocketHandler, HttpHeaders headers, final URI uri, List<String> protocols, List<WebSocketExtension> extensions, Map<String, Object> attributes) { int port = getPort(uri); InetSocketAddress localAddress = new InetSocketAddress(getLocalHost(), port); InetSocketAddress remoteAddress = new InetSocketAddress(uri.getHost(), port); final StandardWebSocketSession session = new StandardWebSocketSession(headers, attributes, localAddress, remoteAddress); final ClientEndpointConfig endpointConfig = ClientEndpointConfig.Builder.create() .configurator(new StandardWebSocketClientConfigurator(headers)) .preferredSubprotocols(protocols) .extensions(adaptExtensions(extensions)).build(); endpointConfig.getUserProperties().putAll(getUserProperties()); final Endpoint endpoint = new StandardWebSocketHandlerAdapter(webSocketHandler, session); Callable<WebSocketSession> connectTask = () -> { this.webSocketContainer.connectToServer(endpoint, endpointConfig, uri); return session; }; if (this.taskExecutor != null) { return this.taskExecutor.submitListenable(connectTask); } else { ListenableFutureTask<WebSocketSession> task = new ListenableFutureTask<>(connectTask); task.run(); return task; } } private static List<Extension> adaptExtensions(List<WebSocketExtension> extensions) { List<Extension> result = new ArrayList<>(); for (WebSocketExtension extension : extensions) { result.add(new WebSocketToStandardExtensionAdapter(extension)); } return result; } private InetAddress getLocalHost() { try { return InetAddress.getLocalHost(); } catch (UnknownHostException ex) { return InetAddress.getLoopbackAddress(); } } private int getPort(URI uri) { if (uri.getPort() == -1) { String scheme = uri.getScheme().toLowerCase(Locale.ENGLISH); return ("wss".equals(scheme) ? 443 : 80); } return uri.getPort(); } private class StandardWebSocketClientConfigurator extends Configurator { private final HttpHeaders headers; public StandardWebSocketClientConfigurator(HttpHeaders headers) { this.headers = headers; } @Override public void beforeRequest(Map<String, List<String>> requestHeaders) { requestHeaders.putAll(this.headers); if (logger.isTraceEnabled()) { logger.trace("Handshake request headers: " + requestHeaders); } } @Override public void afterResponse(HandshakeResponse response) { if (logger.isTraceEnabled()) { logger.trace("Handshake response headers: " + response.getHeaders()); } } } }
2,228
1,350
<reponame>Manny27nyc/azure-sdk-for-java<filename>sdk/security/azure-resourcemanager-security/src/main/java/com/azure/resourcemanager/security/fluent/models/SecurityTaskInner.java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.security.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.JsonFlatten; import com.azure.core.management.ProxyResource; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.security.models.SecurityTaskParameters; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.OffsetDateTime; /** Security task that we recommend to do in order to strengthen security. */ @JsonFlatten @Fluent public class SecurityTaskInner extends ProxyResource { @JsonIgnore private final ClientLogger logger = new ClientLogger(SecurityTaskInner.class); /* * State of the task (Active, Resolved etc.) */ @JsonProperty(value = "properties.state", access = JsonProperty.Access.WRITE_ONLY) private String state; /* * The time this task was discovered in UTC */ @JsonProperty(value = "properties.creationTimeUtc", access = JsonProperty.Access.WRITE_ONLY) private OffsetDateTime creationTimeUtc; /* * Changing set of properties, depending on the task type that is derived * from the name field */ @JsonProperty(value = "properties.securityTaskParameters") private SecurityTaskParameters securityTaskParameters; /* * The time this task's details were last changed in UTC */ @JsonProperty(value = "properties.lastStateChangeTimeUtc", access = JsonProperty.Access.WRITE_ONLY) private OffsetDateTime lastStateChangeTimeUtc; /* * Additional data on the state of the task */ @JsonProperty(value = "properties.subState", access = JsonProperty.Access.WRITE_ONLY) private String subState; /** * Get the state property: State of the task (Active, Resolved etc.). * * @return the state value. */ public String state() { return this.state; } /** * Get the creationTimeUtc property: The time this task was discovered in UTC. * * @return the creationTimeUtc value. */ public OffsetDateTime creationTimeUtc() { return this.creationTimeUtc; } /** * Get the securityTaskParameters property: Changing set of properties, depending on the task type that is derived * from the name field. * * @return the securityTaskParameters value. */ public SecurityTaskParameters securityTaskParameters() { return this.securityTaskParameters; } /** * Set the securityTaskParameters property: Changing set of properties, depending on the task type that is derived * from the name field. * * @param securityTaskParameters the securityTaskParameters value to set. * @return the SecurityTaskInner object itself. */ public SecurityTaskInner withSecurityTaskParameters(SecurityTaskParameters securityTaskParameters) { this.securityTaskParameters = securityTaskParameters; return this; } /** * Get the lastStateChangeTimeUtc property: The time this task's details were last changed in UTC. * * @return the lastStateChangeTimeUtc value. */ public OffsetDateTime lastStateChangeTimeUtc() { return this.lastStateChangeTimeUtc; } /** * Get the subState property: Additional data on the state of the task. * * @return the subState value. */ public String subState() { return this.subState; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (securityTaskParameters() != null) { securityTaskParameters().validate(); } } }
1,373
390
/*! @file WinAsm.h @brief Windows specific MASM-written functions. @author <NAME> @copyright Copyright (c) 2020 - , <NAME>. All rights reserved. */ #pragma once #include "WinCommon.h" /*! @brief Reads the value of LDTR. @return The value of LDTR. */ UINT16 AsmReadLdtr ( ); /*! @brief Reads the value of TR. @return The value of TR. */ UINT16 AsmReadTr ( ); /*! @brief Reads the value of ES. @return The value of ES. */ UINT16 AsmReadEs ( ); /*! @brief Reads the value of CS. @return The value of CS. */ UINT16 AsmReadCs ( ); /*! @brief Reads the value of SS. @return The value of SS. */ UINT16 AsmReadSs ( ); /*! @brief Reads the value of DS. @return The value of DS. */ UINT16 AsmReadDs ( ); /*! @brief Reads the value of FS. @return The value of FS. */ UINT16 AsmReadFs ( ); /*! @brief Reads the value of GS. @return The value of GS. */ UINT16 AsmReadGs ( ); /*! @brief Writes the value to TR. @param[in] TaskSelector - The value to write to TR. */ VOID AsmWriteTr ( _In_ UINT16 TaskSelector );
516
1,148
"""ERC-20 compatibility.""" from web3.contract import Contract def test_erc20_interface(token: Contract, token_owner: str, empty_address: str): """Token satisfies ERC-20 interface.""" # https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20.sol assert token.functions.balanceOf(empty_address).call() == 0 assert token.functions.allowance(token_owner, empty_address).call() == 0 # Event # We follow OpenZeppelin - in the ERO20 issue names are _from, _to, _value transfer = token._find_matching_event_abi("Transfer", ["from", "to", "value"]) assert transfer approval = token._find_matching_event_abi("Approval", ["owner", "spender", "value"]) assert approval
244
3,442
<reponame>wcicola/jitsi /* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.java.sip.communicator.service.protocol; /** * The supported proxy types and properties used to store the values * in the configuration service. * * @author <NAME> */ public class ProxyInfo { /** * Enum which stores possible proxy types */ public static enum ProxyType { /** * Proxy is not used. */ NONE, /** * HTTP proxy type. */ HTTP, /** * Proxy type socks4. */ SOCKS4, /** * Proxy type socks5. */ SOCKS5 } /** * Stores in the configuration the connection proxy type. */ public final static String CONNECTION_PROXY_TYPE_PROPERTY_NAME = "net.java.sip.communicator.service.connectionProxyType"; /** * Stores in the configuration the connection proxy address. */ public final static String CONNECTION_PROXY_ADDRESS_PROPERTY_NAME = "net.java.sip.communicator.service.connectionProxyAddress"; /** * Stores in the configuration the connection proxy port. */ public final static String CONNECTION_PROXY_PORT_PROPERTY_NAME = "net.java.sip.communicator.service.connectionProxyPort"; /** * Stores in the configuration the connection proxy username. */ public final static String CONNECTION_PROXY_USERNAME_PROPERTY_NAME = "net.java.sip.communicator.service.connectionProxyUsername"; /** * Stores in the configuration the connection proxy password. */ public final static String CONNECTION_PROXY_PASSWORD_PROPERTY_NAME = "net.java.sip.communicator.service.connectionProxyPassword"; /** * Stores in the configuration the connection dns forwarding is it enabled. */ public final static String CONNECTION_PROXY_FORWARD_DNS_PROPERTY_NAME = "net.java.sip.communicator.service.connectionProxyForwardDNS"; /** * Stores in the configuration the connection dns forwarding address. */ public final static String CONNECTION_PROXY_FORWARD_DNS_ADDRESS_PROPERTY_NAME = "net.java.sip.communicator.service.connectionProxyForwardDNSAddress"; /** * Stores in the configuration the connection dns forwarding port. */ public final static String CONNECTION_PROXY_FORWARD_DNS_PORT_PROPERTY_NAME = "net.java.sip.communicator.service.connectionProxyForwardDNSPort"; }
1,107
785
/* * Copyright 2016-2021 Pnoker. 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. */ package org.openscada.opc.dcom.da; import org.jinterop.dcom.common.JIException; import org.jinterop.dcom.core.*; public class OPCITEMDEF { private String accessPath = ""; private String itemID = ""; private boolean active = true; private int clientHandle; private short requestedDataType = JIVariant.VT_EMPTY; private short reserved; public String getAccessPath() { return this.accessPath; } public void setAccessPath(final String accessPath) { this.accessPath = accessPath; } public int getClientHandle() { return this.clientHandle; } public void setClientHandle(final int clientHandle) { this.clientHandle = clientHandle; } public boolean isActive() { return this.active; } public void setActive(final boolean active) { this.active = active; } public String getItemID() { return this.itemID; } public void setItemID(final String itemID) { this.itemID = itemID; } public short getRequestedDataType() { return this.requestedDataType; } public void setRequestedDataType(final short requestedDataType) { this.requestedDataType = requestedDataType; } public short getReserved() { return this.reserved; } public void setReserved(final short reserved) { this.reserved = reserved; } /** * Convert to structure to a J-Interop structure * * @return the j-interop structe * @throws JIException */ public JIStruct toStruct() throws JIException { final JIStruct struct = new JIStruct(); struct.addMember(new JIString(getAccessPath(), JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)); struct.addMember(new JIString(getItemID(), JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)); struct.addMember(new Integer(isActive() ? 1 : 0)); struct.addMember(Integer.valueOf(getClientHandle())); struct.addMember(Integer.valueOf(0)); // blob size struct.addMember(new JIPointer(null)); // blob struct.addMember(Short.valueOf(getRequestedDataType())); struct.addMember(Short.valueOf(getReserved())); return struct; } }
1,023
1,338
<filename>src/apps/haikudepot/server/LocalRepositoryUpdateProcess.h /* * Copyright 2018-2020, <NAME> <<EMAIL>>. * All rights reserved. Distributed under the terms of the MIT License. */ #ifndef LOCAL_REPOSITORY_UPDATE_PROCESS__H #define LOCAL_REPOSITORY_UPDATE_PROCESS__H #include "AbstractProcess.h" #include <File.h> #include <Path.h> #include <String.h> #include <Url.h> #include <package/Context.h> #include <package/PackageRoster.h> #include <package/RepositoryCache.h> #include "Model.h" #include "PackageInfo.h" /*! This process is intended to, for each repository configured on the host, retrieve an updated set of data for the repository from the remote repository site. This is typically HPKR data copied over to the local machine. From there, a latter process will process this data by using the facilities of the Package Kit. */ class LocalRepositoryUpdateProcess : public AbstractProcess { public: LocalRepositoryUpdateProcess( Model *model, bool force = false); virtual ~LocalRepositoryUpdateProcess(); const char* Name() const; const char* Description() const; protected: virtual status_t RunInternal(); private: bool _ShouldRunForRepositoryName( const BString& repoName, BPackageKit::BPackageRoster& roster, BPackageKit::BRepositoryCache* cache); status_t _RunForRepositoryName(const BString& repoName, BPackageKit::BContext& context, BPackageKit::BPackageRoster& roster, BPackageKit::BRepositoryCache* cache); void _NotifyError(const BString& error) const; void _NotifyError(const BString& error, const BString& details) const; private: Model* fModel; bool fForce; }; #endif // LOCAL_REPOSITORY_UPDATE_PROCESS__H
665
12,278
<reponame>rajeev02101987/arangodb // Copyright <NAME> 2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/parameter/config.hpp> #if (BOOST_PARAMETER_MAX_ARITY < 10) #error Define BOOST_PARAMETER_MAX_ARITY as 10 or greater. #endif #include <boost/parameter.hpp> namespace test { BOOST_PARAMETER_NAME(in(lrc0)) BOOST_PARAMETER_NAME(out(lr0)) BOOST_PARAMETER_NAME(in(rrc0)) #if defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING) BOOST_PARAMETER_NAME(consume(rr0)) #else BOOST_PARAMETER_NAME(rr0) #endif BOOST_PARAMETER_NAME(in(lrc1)) BOOST_PARAMETER_NAME(out(lr1)) BOOST_PARAMETER_NAME(in(rrc1)) BOOST_PARAMETER_NAME(in(lrc2)) BOOST_PARAMETER_NAME(out(lr2)) BOOST_PARAMETER_NAME(rr2) struct g_parameters : boost::parameter::parameters< boost::parameter::required<test::tag::lrc0> , boost::parameter::required<test::tag::lr0> , boost::parameter::required<test::tag::rrc0> , boost::parameter::required<test::tag::rr0> , boost::parameter::required<test::tag::lrc1> , boost::parameter::required<test::tag::lr1> , boost::parameter::required<test::tag::rrc1> , boost::parameter::optional<test::tag::lrc2> , boost::parameter::optional<test::tag::lr2> , boost::parameter::optional<test::tag::rr2> > { }; } // namespace test #include <boost/parameter/macros.hpp> #include <boost/core/lightweight_test.hpp> #include "evaluate_category.hpp" namespace test { struct C { BOOST_PARAMETER_MEMFUN(static int, evaluate, 7, 10, g_parameters) { BOOST_TEST_EQ( test::passed_by_lvalue_reference_to_const , U::evaluate_category<0>(p[test::_lrc0]) ); BOOST_TEST_EQ( test::passed_by_lvalue_reference , U::evaluate_category<0>(p[test::_lr0]) ); BOOST_TEST_EQ( test::passed_by_lvalue_reference_to_const , U::evaluate_category<1>(p[test::_lrc1]) ); BOOST_TEST_EQ( test::passed_by_lvalue_reference , U::evaluate_category<1>(p[test::_lr1]) ); BOOST_TEST_EQ( test::passed_by_lvalue_reference_to_const , U::evaluate_category<2>( p[test::_lrc2 | test::lvalue_const_bitset<2>()] ) ); BOOST_TEST_EQ( test::passed_by_lvalue_reference , U::evaluate_category<2>( p[test::_lr2 || test::lvalue_bitset_function<2>()] ) ); #if defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING) BOOST_TEST_EQ( test::passed_by_rvalue_reference_to_const , U::evaluate_category<0>(p[test::_rrc0]) ); BOOST_TEST_EQ( test::passed_by_rvalue_reference , U::evaluate_category<0>(p[test::_rr0]) ); BOOST_TEST_EQ( test::passed_by_rvalue_reference_to_const , U::evaluate_category<1>(p[test::_rrc1]) ); BOOST_TEST_EQ( test::passed_by_rvalue_reference , U::evaluate_category<2>( p[test::_rr2 || test::rvalue_bitset_function<2>()] ) ); #else // !defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING) BOOST_TEST_EQ( test::passed_by_lvalue_reference_to_const , U::evaluate_category<0>(p[test::_rrc0]) ); BOOST_TEST_EQ( test::passed_by_lvalue_reference_to_const , U::evaluate_category<0>(p[test::_rr0]) ); BOOST_TEST_EQ( test::passed_by_lvalue_reference_to_const , U::evaluate_category<1>(p[test::_rrc1]) ); BOOST_TEST_EQ( test::passed_by_lvalue_reference_to_const , U::evaluate_category<2>( p[test::_rr2 || test::rvalue_bitset_function<2>()] ) ); #endif // BOOST_PARAMETER_HAS_PERFECT_FORWARDING return 0; } }; } // namespace test #if !defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING) #include <boost/core/ref.hpp> #endif int main() { #if defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING) || \ (10 < BOOST_PARAMETER_EXPONENTIAL_OVERLOAD_THRESHOLD_ARITY) test::C::evaluate( test::lvalue_const_bitset<0>() , test::lvalue_bitset<0>() , test::rvalue_const_bitset<0>() , test::rvalue_bitset<0>() , test::lvalue_const_bitset<1>() , test::lvalue_bitset<1>() , test::rvalue_const_bitset<1>() ); test::C::evaluate( test::lvalue_const_bitset<0>() , test::lvalue_bitset<0>() , test::rvalue_const_bitset<0>() , test::rvalue_bitset<0>() , test::lvalue_const_bitset<1>() , test::lvalue_bitset<1>() , test::rvalue_const_bitset<1>() , test::lvalue_const_bitset<2>() , test::lvalue_bitset<2>() , test::rvalue_bitset<2>() ); #else // no perfect forwarding support and no exponential overloads test::C::evaluate( test::lvalue_const_bitset<0>() , boost::ref(test::lvalue_bitset<0>()) , test::rvalue_const_bitset<0>() , test::rvalue_bitset<0>() , test::lvalue_const_bitset<1>() , boost::ref(test::lvalue_bitset<1>()) , test::rvalue_const_bitset<1>() ); test::C::evaluate( test::lvalue_const_bitset<0>() , boost::ref(test::lvalue_bitset<0>()) , test::rvalue_const_bitset<0>() , test::rvalue_bitset<0>() , test::lvalue_const_bitset<1>() , boost::ref(test::lvalue_bitset<1>()) , test::rvalue_const_bitset<1>() , test::lvalue_const_bitset<2>() , boost::ref(test::lvalue_bitset<2>()) , test::rvalue_bitset<2>() ); #endif // perfect forwarding support, or exponential overloads return boost::report_errors(); }
3,362
32,544
<reponame>DBatOWL/tutorials package com.baeldung.validations.functional.model; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @AllArgsConstructor @NoArgsConstructor @Getter @Setter public class AnnotatedRequestEntity { @NotNull private String user; @NotNull @Size(min = 4, max = 7) private String password; }
181
809
/** * @file * * @brief * * @date 03.07.2012 * @author <NAME> */ #ifndef FRAMEWORK_MOD_OPTIONS_H_ #define FRAMEWORK_MOD_OPTIONS_H_ #include <util/macro.h> #define __OPTION_MODULE_GET(mod,type,name) \ OPTION_##type##_##mod##__##name #define OPTION_MODULE_GET(mod,type,name) \ __OPTION_MODULE_GET(mod,type,name) #define OPTION_GET(type,name) \ OPTION_MODULE_GET(__EMBUILD_MOD__,type,name) #define __OPTION_MODULE_DEFINED(mod,type,name) \ defined(OPTION_##type##_##mod##__##name) #define OPTION_MODULE_DEFINED(mod,type,name) \ __OPTION_MODULE_DEFINED(mod,type,name) #define OPTION_DEFINED(type,name) \ OPTION_MODULE_DEFINED(__EMBUILD_MOD__,type,name) /* Performs additional stringification, handy in string options */ #define OPTION_MODULE_STRING_GET(mod,name) \ MACRO_STRING(OPTION_MODULE_GET(mod,STRING,name)) #define OPTION_STRING_GET(name) \ OPTION_MODULE_STRING_GET(__EMBUILD_MOD__,name) #endif /* FRAMEWORK_MOD_OPTIONS_H_ */
422
12,706
from __future__ import absolute_import import sys import unittest from testutils import ADMIN_CLIENT, suppress_urllib3_warning from testutils import harbor_server from testutils import TEARDOWN import library.repository import library.cnab from library.project import Project from library.user import User from library.repository import Repository from library.artifact import Artifact from library.scan import Scan class TestCNAB(unittest.TestCase): @suppress_urllib3_warning def setUp(self): print("Setup") @unittest.skipIf(TEARDOWN == False, "Test data won't be erased.") def do_tearDown(self): """ Tear down: 1. Delete repository(RA) by user(UA); 2. Delete project(PA); 3. Delete user(UA); """ #1. Delete repository(RA) by user(UA); TestCNAB.repo.delete_repository(TestCNAB.project_name, TestCNAB.cnab_repo_name, **TestCNAB.USER_CLIENT) #2. Delete project(PA); TestCNAB.project.delete_project(TestCNAB.project_id, **TestCNAB.USER_CLIENT) #3. Delete user(UA). TestCNAB.user.delete_user(TestCNAB.user_id, **ADMIN_CLIENT) def test_01_PushBundleByCnab(self): """ Test case: Push Bundle By Cnab Test step and expected result: 1. Create a new user(UA); 2. Create a new project(PA) by user(UA); 3. Push bundle to harbor as repository(RA); 4. Get repository from Harbor successfully; 5. Verfiy bundle name; 6. Get artifact by sha256; 7. Verify artifact information. """ TestCNAB.project= Project() TestCNAB.user= User() TestCNAB.artifact = Artifact() TestCNAB.repo= Repository() TestCNAB.scan = Scan() TestCNAB.url = ADMIN_CLIENT["endpoint"] TestCNAB.user_push_cnab_password = "<PASSWORD>" TestCNAB.cnab_repo_name = "test_cnab" TestCNAB.cnab_tag = "test_cnab_tag" TestCNAB.project_name = None TestCNAB.artifacts_config_ref_child_list = None TestCNAB.artifacts_ref_child_list = None #1. Create a new user(UA); TestCNAB.user_id, TestCNAB.user_name = TestCNAB.user.create_user(user_password = <PASSWORD>.user_push_cnab_password, **ADMIN_CLIENT) TestCNAB.USER_CLIENT=dict(endpoint = TestCNAB.url, username = TestCNAB.user_name, password = <PASSWORD>AB.user_push_cnab_password, with_scan_overview = True) #2. Create a new project(PA) by user(UA); TestCNAB.project_id, TestCNAB.project_name = TestCNAB.project.create_project(metadata = {"public": "false"}, **TestCNAB.USER_CLIENT) #3. Push bundle to harbor as repository(RA); target = harbor_server + "/" + TestCNAB.project_name + "/" + TestCNAB.cnab_repo_name + ":" + TestCNAB.cnab_tag TestCNAB.reference_sha256 = library.cnab.push_cnab_bundle(harbor_server, TestCNAB.user_name, TestCNAB.user_push_cnab_password, "goharbor/harbor-log:v1.10.0", "kong:latest", target) #4. Get repository from Harbor successfully; TestCNAB.cnab_bundle_data = TestCNAB.repo.get_repository(TestCNAB.project_name, TestCNAB.cnab_repo_name, **TestCNAB.USER_CLIENT) print(TestCNAB.cnab_bundle_data) #4.1 Get refs of CNAB bundle; TestCNAB.artifacts = TestCNAB.artifact.list_artifacts(TestCNAB.project_name, TestCNAB.cnab_repo_name, **TestCNAB.USER_CLIENT) print("artifacts:", TestCNAB.artifacts) TestCNAB.artifacts_ref_child_list = [] TestCNAB.artifacts_config_ref_child_list = [] for ref in TestCNAB.artifacts[0].references: if ref.annotations["io.cnab.manifest.type"] != 'config': TestCNAB.artifacts_ref_child_list.append(ref.child_digest) else: TestCNAB.artifacts_config_ref_child_list.append(ref.child_digest) self.assertEqual(len(TestCNAB.artifacts_ref_child_list), 2, msg="Image artifact count should be 2.") self.assertEqual(len(TestCNAB.artifacts_config_ref_child_list), 1, msg="Bundle count should be 1.") print(TestCNAB.artifacts_ref_child_list) #4.2 Cnab bundle can be pulled by ctr successfully; # This step might not successful since ctr does't support cnab fully, it might be uncomment sometime in future. # Please keep them in comment! #library.containerd.ctr_images_pull(TestCNAB.user_name, TestCNAB.user_push_cnab_password, target) #library.containerd.ctr_images_list(oci_ref = target) #5. Verfiy bundle name; self.assertEqual(TestCNAB.cnab_bundle_data.name, TestCNAB.project_name + "/" + TestCNAB.cnab_repo_name) #6. Get artifact by sha256; artifact = TestCNAB.artifact.get_reference_info(TestCNAB.project_name, TestCNAB.cnab_repo_name, TestCNAB.reference_sha256, **TestCNAB.USER_CLIENT) #7. Verify artifact information; self.assertEqual(artifact.type, 'CNAB') self.assertEqual(artifact.digest, TestCNAB.reference_sha256) def test_02_ScanCNAB(self): """ Test case: Scan CNAB Test step and expected result: 1. Scan config artifact, it should be failed with 400 status code; 2. Scan 1st child artifact, it should be scanned, the other should be not scanned, repository should not be scanned; 3. Scan 2cn child artifact, it should be scanned, repository should not be scanned; 4. Scan repository, it should be scanned; Tear down: """ #1. Scan config artifact, it should be failed with 400 status code; TestCNAB.scan.scan_artifact(TestCNAB.project_name, TestCNAB.cnab_repo_name, TestCNAB.artifacts_config_ref_child_list[0], expect_status_code = 400, **TestCNAB.USER_CLIENT) #2. Scan 1st child artifact, it should be scanned, the other should be not scanned, repository should not be scanned; TestCNAB.scan.scan_artifact(TestCNAB.project_name, TestCNAB.cnab_repo_name, TestCNAB.artifacts_ref_child_list[0], **TestCNAB.USER_CLIENT) TestCNAB.artifact.check_image_scan_result(TestCNAB.project_name, TestCNAB.cnab_repo_name, TestCNAB.artifacts_ref_child_list[0], **TestCNAB.USER_CLIENT) TestCNAB.artifact.check_image_scan_result(TestCNAB.project_name, TestCNAB.cnab_repo_name, TestCNAB.artifacts_ref_child_list[1], expected_scan_status = "Not Scanned", **TestCNAB.USER_CLIENT) TestCNAB.artifact.check_image_scan_result(TestCNAB.project_name, TestCNAB.cnab_repo_name, TestCNAB.artifacts_config_ref_child_list[0], expected_scan_status = "No Scan Overview", **TestCNAB.USER_CLIENT) TestCNAB.artifact.check_image_scan_result(TestCNAB.project_name, TestCNAB.cnab_repo_name, TestCNAB.artifacts[0].digest, expected_scan_status = "Not Scanned", **TestCNAB.USER_CLIENT) #3. Scan 2cn child artifact, it should be scanned, repository should not be scanned; TestCNAB.scan.scan_artifact(TestCNAB.project_name, TestCNAB.cnab_repo_name, TestCNAB.artifacts_ref_child_list[1], **TestCNAB.USER_CLIENT) TestCNAB.artifact.check_image_scan_result(TestCNAB.project_name, TestCNAB.cnab_repo_name, TestCNAB.artifacts_ref_child_list[1], **TestCNAB.USER_CLIENT) TestCNAB.artifact.check_image_scan_result(TestCNAB.project_name, TestCNAB.cnab_repo_name, TestCNAB.artifacts_config_ref_child_list[0], expected_scan_status = "No Scan Overview", **TestCNAB.USER_CLIENT) TestCNAB.artifact.check_image_scan_result(TestCNAB.project_name, TestCNAB.cnab_repo_name, TestCNAB.artifacts[0].digest, expected_scan_status = "Not Scanned", **TestCNAB.USER_CLIENT) #4. Scan repository, it should be scanned; TestCNAB.scan.scan_artifact(TestCNAB.project_name, TestCNAB.cnab_repo_name, TestCNAB.artifacts[0].digest, **TestCNAB.USER_CLIENT) TestCNAB.artifact.check_image_scan_result(TestCNAB.project_name, TestCNAB.cnab_repo_name, TestCNAB.artifacts[0].digest, **TestCNAB.USER_CLIENT) self.do_tearDown() if __name__ == '__main__': suite = unittest.TestSuite(unittest.makeSuite(TestCNAB)) result = unittest.TextTestRunner(sys.stdout, verbosity=2, failfast=True).run(suite) if not result.wasSuccessful(): raise Exception(r"CNAB test failed: {}".format(result))
3,561
17,104
/* * Tencent is pleased to support the open source community by making Mars available. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.mars.sample.statistic; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.RadioButton; import android.widget.RadioGroup; import com.tencent.mars.sample.R; import com.tencent.mars.sample.wrapper.remote.MarsServiceProxy; import utils.bindsimple.BindSimple; import utils.bindsimple.BindView; public class ReportDisplayActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener { public static String TAG = ReportDisplayActivity.class.getSimpleName(); @BindView(R.id.main_sheet) RadioGroup mainSheet; @BindView(R.id.display_toolbar) Toolbar toolbar; FragmentManager fragmentManager; FlowReportFragment flowReportFragment; SdtReportFragment sdtReportFragment; TaskReportFragment taskReportFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_report_display); BindSimple.bind(this); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(false); //是否显示显示返回箭头 getSupportActionBar().setDisplayShowTitleEnabled(false); //是否显示标题 fragmentManager = getSupportFragmentManager(); ((RadioButton) mainSheet.getChildAt(0)).setChecked(true); onCheckedChanged(mainSheet, 1); mainSheet.setOnCheckedChangeListener(this); } @Override public void onResume() { super.onResume(); MarsServiceProxy.inst.setForeground(true); } public void onPause() { super.onPause(); MarsServiceProxy.inst.setForeground(false); } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { FragmentTransaction fragmentTrans = fragmentManager.beginTransaction(); hideFragments(fragmentTrans); int id = (checkedId % 3 == 0 ? 3 : (checkedId % 3)); switch (id) { case 1: if (taskReportFragment == null) { taskReportFragment = new TaskReportFragment(); fragmentTrans.add(R.id.dis_ll_fragment, taskReportFragment); } else { fragmentTrans.show(taskReportFragment); } break; case 2: if (flowReportFragment == null) { flowReportFragment = new FlowReportFragment(); fragmentTrans.add(R.id.dis_ll_fragment, flowReportFragment); } else { fragmentTrans.show(flowReportFragment); } break; case 3: if (sdtReportFragment == null) { sdtReportFragment = new SdtReportFragment(); fragmentTrans.add(R.id.dis_ll_fragment, sdtReportFragment); } else { fragmentTrans.show(sdtReportFragment); } break; default: break; } fragmentTrans.commit(); } private void hideFragments(FragmentTransaction transaction) { if (flowReportFragment != null) { transaction.hide(flowReportFragment); } if (sdtReportFragment != null) { transaction.hide(sdtReportFragment); } if (taskReportFragment != null) { transaction.hide(taskReportFragment); } } }
1,764
617
<reponame>RamboWu/pokerstove<gh_stars>100-1000 #include "PokerHandEvaluator.h" #include <gtest/gtest.h> TEST(PokerHandEvaluator, OmahaHigh) { using namespace pokerstove; boost::shared_ptr<PokerHandEvaluator> evaluator = PokerHandEvaluator::alloc("O"); EXPECT_EQ(true, evaluator->usesSuits()); EXPECT_EQ(5, evaluator->boardSize()); }
151
1,144
/* * Copyright 2006,2007 <NAME>, <NAME> This file is part of * CheckboxTree. CheckboxTree is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at your * option) any later version. CheckboxTree is distributed in the hope that it * will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. You should have received a copy of the GNU * General Public License along with CheckboxTree; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA */ package it.cnr.imaa.essi.lablib.gui.checkboxtree; /* * #%L * de.metas.adempiere.libero.libero * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import javax.swing.tree.TreePath; /** * PropagateUpWhiteTreeCheckingMode define a TreeCheckingMode with down * recursion of the check when nodes are clicked and up only when uncheck. The * check is propagated, like the Propagate mode to descendants. If a user * unchecks a checkbox the uncheck will also be propagated to ancestors. * * @author Boldrini */ public class PropagateUpWhiteTreeCheckingMode extends TreeCheckingMode { PropagateUpWhiteTreeCheckingMode(DefaultTreeCheckingModel model) { super(model); } @Override public void checkPath(TreePath path) { // check is propagated to children this.model.checkSubTree(path); // check all the ancestors with subtrees checked TreePath[] parents = new TreePath[path.getPathCount()]; parents[0] = path; TreePath parentPath = path; // uncheck is propagated to parents, too while ((parentPath = parentPath.getParentPath()) != null) { this.model.updatePathGreyness(parentPath); } } @Override public void uncheckPath(TreePath path) { // uncheck is propagated to children this.model.uncheckSubTree(path); TreePath parentPath = path; // uncheck is propagated to parents, too while ((parentPath = parentPath.getParentPath()) != null) { this.model.removeFromCheckedPathsSet(parentPath); this.model.updatePathGreyness(parentPath); } } /* * (non-Javadoc) * * @see it.cnr.imaa.essi.lablib.gui.checkboxtree.TreeCheckingMode#updateCheckAfterChildrenInserted(javax.swing.tree.TreePath) */ @Override public void updateCheckAfterChildrenInserted(TreePath parent) { if (this.model.isPathChecked(parent)) { checkPath(parent); } else { uncheckPath(parent); } } /* * (non-Javadoc) * * @see it.cnr.imaa.essi.lablib.gui.checkboxtree.TreeCheckingMode#updateCheckAfterChildrenRemoved(javax.swing.tree.TreePath) */ @Override public void updateCheckAfterChildrenRemoved(TreePath parent) { if (!this.model.isPathChecked(parent)) { // System.out.println(parent +" was removed (not checked)"); if (this.model.getChildrenPath(parent).length != 0) { if (!this.model.pathHasChildrenWithValue(parent, false)) { // System.out.println("uncheking it"); checkPath(parent); } } } this.model.updatePathGreyness(parent); this.model.updateAncestorsGreyness(parent); } /* * (non-Javadoc) * * @see it.cnr.imaa.essi.lablib.gui.checkboxtree.TreeCheckingMode#updateCheckAfterStructureChanged(javax.swing.tree.TreePath) */ @Override public void updateCheckAfterStructureChanged(TreePath parent) { if (this.model.isPathChecked(parent)) { checkPath(parent); } else { uncheckPath(parent); } } }
1,491
5,169
{ "name": "SideMenuDrawer", "version": "1.0.0", "summary": "This framework is used to create slidemenu.", "description": "This framework is used to create slidemenu as in android", "homepage": "https://github.com/sawanmind/SideMenuDrawer", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "social_media_url": "http://twitter.com/sawanmind", "platforms": { "ios": "11.0" }, "source": { "git": "https://github.com/sawanmind/SideMenuDrawer.git", "tag": "1.0.0" }, "source_files": "SideMenuDrawer/**/*", "frameworks": [ "UIKit", "Foundation" ], "pushed_with_swift_version": "4.0" }
262
339
<reponame>ljw23/ConvLab-2 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ """ import multiprocessing as mp import threading as th class LockBase(object): def __init__(self): self.locks = [] def enter(self): for lock in self.locks: lock.acquire() def leave(self): for lock in self.locks[::-1]: # Release in inverse order of acquisition lock.release() def __enter__(self): # print("enter") self.enter() def __exit__(self, *exc): self.leave() # print("leave") class GlobalLock(LockBase): def __init__(self, name: str = 'lock', is_rlock=False): super().__init__() cls = type(self) mp_name = 'mp_' + name th_name = 'th_' + name cls.create_mp_lock(mp_name, is_rlock) cls.create_th_lock(th_name, is_rlock) self.locks = [lk for lk in [getattr(cls, mp_name), getattr(cls, th_name)] if lk is not None] @classmethod def create_mp_lock(cls, name, is_rlock): if not hasattr(cls, name): try: if is_rlock: setattr(cls, name, mp.RLock()) # multiprocessing lock else: setattr(cls, name, mp.Lock()) # multiprocessing lock except ImportError: # pragma: no cover setattr(cls, name, None) except OSError: # pragma: no cover setattr(cls, name, None) @classmethod def create_th_lock(cls, name, is_rlock): if not hasattr(cls, name): try: if is_rlock: setattr(cls, name, th.RLock()) # thread lock else: setattr(cls, name, th.Lock()) # thread lock except OSError: # pragma: no cover setattr(cls, name, None) class GlobalSemaphore(LockBase): def __init__(self, value: int = 1, name: str = 'sem'): super().__init__() cls = type(self) mp_name = 'mp_' + name th_name = 'th_' + name cls.create_mp_sem(mp_name, value) cls.create_th_sem(th_name, value) self.locks = [lk for lk in [getattr(cls, mp_name), getattr(cls, th_name)] if lk is not None] @classmethod def create_mp_sem(cls, name, value): if not hasattr(cls, name): try: setattr(cls, name, mp.Semaphore(value)) # multiprocessing lock except ImportError: # pragma: no cover setattr(cls, name, None) except OSError: # pragma: no cover setattr(cls, name, None) @classmethod def create_th_sem(cls, name, value): if not hasattr(cls, name): try: setattr(cls, name, th.Semaphore(value)) # thread lock except OSError: # pragma: no cover setattr(cls, name, None) class MyLock(LockBase): def __init__(self, is_rlock=False): super().__init__() mp_lock = self.create_mp_lock(is_rlock) th_lock = self.create_th_lock(is_rlock) self.locks = [lk for lk in [mp_lock, th_lock] if lk is not None] @staticmethod def create_mp_lock(is_rlock): try: if is_rlock: mp_lock = mp.RLock() # multiprocessing lock else: mp_lock = mp.Lock() # multiprocessing lock except ImportError: # pragma: no cover mp_lock = None except OSError: # pragma: no cover mp_lock = None return mp_lock @staticmethod def create_th_lock(is_rlock): try: if is_rlock: th_lock = th.RLock() # thread lock else: th_lock = th.Lock() # thread lock except OSError: # pragma: no cover th_lock = None return th_lock class MySemaphore(LockBase): def __init__(self, value: int = 1): super().__init__() mp_sem = self.create_mp_sem(value) th_sem = self.create_th_sem(value) self.locks = [lk for lk in [mp_sem, th_sem] if lk is not None] @staticmethod def create_mp_sem(value): try: mp_lock = mp.Semaphore(value) # multiprocessing lock except ImportError: # pragma: no cover mp_lock = None except OSError: # pragma: no cover mp_lock = None return mp_lock @staticmethod def create_th_sem(value): try: th_lock = th.Semaphore(value) # thread lock except OSError: # pragma: no cover th_lock = None return th_lock class ResourceLock(object): def __init__(self, value: int = 1): self.sema = MySemaphore(value) self.lock = MyLock() self.used = [0 for _ in range(value)] def res_catch(self): self.sema.enter() with self.lock: unused_idx = self.used.index(0) self.used[unused_idx] = 1 return unused_idx def res_leave(self, idx): with self.lock: self.used[idx] = 0 self.sema.leave() if __name__ == '__main__': lock = GlobalLock(is_rlock=False) with lock: print("running") with lock: print("running")
2,702
777
<reponame>google-ar/chromium // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/android/java_interfaces_impl.h" #include <jni.h> #include <utility> #include "base/android/context_utils.h" #include "base/android/jni_android.h" #include "base/memory/singleton.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/web_contents.h" #include "jni/InterfaceRegistrarImpl_jni.h" #include "mojo/public/cpp/system/message_pipe.h" #include "services/service_manager/public/cpp/interface_provider.h" namespace content { namespace { class JavaInterfaceProviderHolder { public: JavaInterfaceProviderHolder() { service_manager::mojom::InterfaceProviderPtr provider; JNIEnv* env = base::android::AttachCurrentThread(); Java_InterfaceRegistrarImpl_createInterfaceRegistryForContext( env, mojo::MakeRequest(&provider).PassMessagePipe().release().value(), base::android::GetApplicationContext()); interface_provider_.Bind(std::move(provider)); } static JavaInterfaceProviderHolder* GetInstance() { DCHECK_CURRENTLY_ON(BrowserThread::UI); return base::Singleton<JavaInterfaceProviderHolder>::get(); } service_manager::InterfaceProvider* GetJavaInterfaces() { return &interface_provider_; } private: service_manager::InterfaceProvider interface_provider_; }; } // namespace service_manager::InterfaceProvider* GetGlobalJavaInterfaces() { return JavaInterfaceProviderHolder::GetInstance()->GetJavaInterfaces(); } void BindInterfaceRegistryForWebContents( service_manager::mojom::InterfaceProviderRequest request, WebContents* web_contents) { JNIEnv* env = base::android::AttachCurrentThread(); Java_InterfaceRegistrarImpl_createInterfaceRegistryForWebContents( env, request.PassMessagePipe().release().value(), web_contents->GetJavaWebContents().obj()); } } // namespace content
643
407
package com.alibaba.tesla.gateway.common.utils; import org.junit.Test; import static org.junit.Assert.*; /** * @author <EMAIL> */ public class ServerNameCheckUtilTest { @Test public void check() { String url = "lb://fass.test.1233%alibaba/test_test"; ServerNameCheckUtil.check(url); } }
132
435
<reponame>amaajemyfren/data<filename>pydata-berlin-2017/videos/tal-perry-a-word-is-worth-a-thousand-pictures-convolutional-methods-for-text.json { "copyright_text": "Standard YouTube License", "description": "Link to slides: https://www.slideshare.net/secret/2a5Xz9Sgc3D5GU\n\nDescription\nThose folks in computer vision keep publishing amazing ideas about you to apply convolutions to images. What about those of us who work with text? Can't we enjoy convolutions as well? In this talk I'll review some convolutional architectures that worked great for images and were adapted to text and confront the hardest parts of getting them to work in Tensorflow .\n\n**Abstract**\n\nThe go to architecture for deep learning on sequences such as text is the RNN and particularly LSTM variants. While remarkably effective, RNNs are painfully slow due their sequential nature. Convolutions allow us to process a whole sequence in parallel greatly reducing the time required to train and infer. One of the most important advances in convolutional architectures has been the use of gating to concur the vanishing gradient problem thus allowing arbitrarily deep networks to be trained efficiently.\n\nIn this talk we'll review the key innovations in the DenseNet architecture and show how to adapt it to text. We'll go over \"deconvolution\" operators and dilated convolutions as means of handling long range dependencies. Finally we'll look at convolutions applied to [translation] (https://arxiv.org/abs/1610.10099) at the character level.\n\nThe goal of this talk is to demonstrate the practical advantages and relative ease with which these methods can be applied, as such we will focus on the ideas and implementations (in tensorflow) more than on the math.\n\n", "duration": 1933, "language": "eng", "recorded": "2017-06-30", "related_urls": [ { "label": "schedule", "url": "https://pydata.org/berlin2017/schedule/" }, { "label": "slides", "url": "https://www.slideshare.net/secret/2a5Xz9Sgc3D5GU" }, { "label": "Neural Machine Translation in Linear Time", "url": "https://arxiv.org/abs/1610.10099" } ], "speakers": [ "<NAME>" ], "tags": [], "thumbnail_url": "https://i.ytimg.com/vi/cYDuHxNLIjg/maxresdefault.jpg", "title": "A word is worth a thousand pictures: Convolutional methods for text", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=cYDuHxNLIjg" } ] }
779
671
<gh_stars>100-1000 typedef NS_ENUM(NSInteger, NYAlertViewControllerTransitionStyle) { /** Fade in the alert view */ NYAlertViewControllerTransitionStyleFade, /** Slide the alert view from the top of the view */ NYAlertViewControllerTransitionStyleSlideFromTop, /** Slide the alert view from the bottom of the view */ NYAlertViewControllerTransitionStyleSlideFromBottom };
121
839
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.tools.corba.processors.wsdl; import java.io.File; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; import javax.wsdl.Definition; import javax.xml.bind.JAXBException; import org.apache.cxf.common.i18n.Message; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.tools.common.ToolConstants; import org.apache.cxf.tools.common.ToolException; import org.apache.cxf.tools.corba.common.ProcessorEnvironment; import org.apache.cxf.tools.corba.common.ToolCorbaConstants; import org.apache.cxf.tools.corba.common.WSDLUtils; public class WSDLToCorbaProcessor extends WSDLToProcessor { protected static final Logger LOG = LogUtils.getL7dLogger(WSDLToCorbaProcessor.class); WSDLToCorbaBinding wsdlToCorbaBinding; WSDLToIDLAction idlAction; Definition definition; String bindName; String outputfile; String outputdir = "."; String wsdlOutput; String idlOutput; ProcessorEnvironment env; public void process() throws ToolException { Definition def = null; env = getEnvironment(); try { // if the corba option is specified - generates wsdl if (env.optionSet(ToolCorbaConstants.CFG_CORBA)) { wsdlToCorbaBinding = new WSDLToCorbaBinding(); } if (env.optionSet(ToolCorbaConstants.CFG_IDL)) { // if idl option specified it generated idl idlAction = new WSDLToIDLAction(); } if (wsdlToCorbaBinding == null && idlAction == null) { wsdlToCorbaBinding = new WSDLToCorbaBinding(); idlAction = new WSDLToIDLAction(); } setOutputFile(); String filename = getFileBase(env.get("wsdlurl").toString()); if ((wsdlOutput == null) && (wsdlToCorbaBinding != null)) { wsdlOutput = filename + "-corba.wsdl"; } if ((idlOutput == null) && (idlAction != null)) { idlOutput = filename + ".idl"; } if (wsdlToCorbaBinding != null) { wsdltoCorba(); def = wsdlToCorbaBinding.generateCORBABinding(); writeToWSDL(def); } if (idlAction != null) { wsdltoIdl(); idlAction.generateIDL(def); writeToIDL(def); } } catch (ToolException ex) { throw ex; } catch (JAXBException ex) { throw new ToolException(ex); } catch (Exception ex) { throw new ToolException(ex); } } private void writeToWSDL(Definition def) throws ToolException { try { WSDLUtils.writeWSDL(def, outputdir, wsdlOutput); } catch (Throwable t) { Message msg = new Message("FAIL_TO_WRITE_WSDL", LOG); throw new ToolException(msg, t); } } private void writeToIDL(Definition def) throws ToolException { } public void wsdltoCorba() { if (env.optionSet(ToolConstants.CFG_BINDING)) { wsdlToCorbaBinding.setBindingName(env.get("binding").toString()); } if (env.optionSet(ToolConstants.CFG_PORTTYPE)) { wsdlToCorbaBinding.addInterfaceName(env.get("porttype").toString()); } if ((env.optionSet(ToolConstants.CFG_PORTTYPE)) && env.optionSet(ToolConstants.CFG_BINDING)) { wsdlToCorbaBinding.mapBindingToInterface(env.get("porttype").toString(), env.get("binding") .toString()); } if ((!env.optionSet(ToolConstants.CFG_PORTTYPE)) && !env.optionSet(ToolConstants.CFG_BINDING)) { wsdlToCorbaBinding.setAllBindings(true); } if (env.optionSet(ToolConstants.CFG_WSDLURL)) { wsdlToCorbaBinding.setWsdlFile(env.get("wsdlurl").toString()); } if (env.optionSet(ToolConstants.CFG_NAMESPACE)) { wsdlToCorbaBinding.setNamespace(env.get("namespace").toString()); } if (env.optionSet(ToolCorbaConstants.CFG_ADDRESS)) { wsdlToCorbaBinding.setAddress(env.get("address").toString()); } if (env.optionSet(ToolCorbaConstants.CFG_ADDRESSFILE)) { wsdlToCorbaBinding.setAddressFile(env.get("addressfile").toString()); } // need to add wrapped wsdlToCorbaBinding.setOutputDirectory(getOutputDir()); wsdlToCorbaBinding.setOutputFile(wsdlOutput); } private void wsdltoIdl() { if (env.optionSet(ToolConstants.CFG_BINDING)) { idlAction.setBindingName(env.get("binding").toString()); } else { if (wsdlToCorbaBinding != null) { if (env.optionSet(ToolConstants.CFG_PORTTYPE)) { String portType = env.get("porttype").toString(); if (portType != null) { String bindingName = wsdlToCorbaBinding.getMappedBindingName(portType); if (bindingName != null) { idlAction.setBindingName(bindingName); } } } else { //try to get the binding name from the wsdlToCorbaBinding java.util.List<String> bindingNames = wsdlToCorbaBinding.getGeneratedBindingNames(); if ((bindingNames != null) && (!bindingNames.isEmpty())) { idlAction.setBindingName(bindingNames.get(0)); if (bindingNames.size() > 1) { System.err.println("Warning: Generating idl only for the binding " + bindingNames.get(0)); } } else { // generate idl for all bindings. idlAction.setGenerateAllBindings(true); } } } else { idlAction.setGenerateAllBindings(true); } } if (env.optionSet(ToolConstants.CFG_WSDLURL)) { String name = env.get("wsdlurl").toString(); idlAction.setWsdlFile(name); } if (env.optionSet(ToolConstants.CFG_VERBOSE)) { idlAction.setVerboseOn(Boolean.TRUE); } idlAction.setOutputDirectory(getOutputDir()); idlAction.setOutputFile(idlOutput); } private String getOutputDir() { if (env.optionSet(ToolConstants.CFG_OUTPUTDIR)) { outputdir = env.get("outputdir").toString(); File fileOutputDir = new File(outputdir); if (!fileOutputDir.exists()) { fileOutputDir.mkdir(); } } return outputdir; } private void setOutputFile() { wsdlOutput = (String)env.get(ToolCorbaConstants.CFG_WSDLOUTPUTFILE); idlOutput = (String)env.get(ToolCorbaConstants.CFG_IDLOUTPUTFILE); if ((wsdlOutput == null) && (idlOutput == null)) { LOG.log(Level.WARNING, "Using default wsdl/idl filenames..."); } } public String getFileBase(String wsdlUrl) { String fileBase = wsdlUrl; StringTokenizer tok = new StringTokenizer(wsdlUrl, "\\/"); while (tok.hasMoreTokens()) { fileBase = tok.nextToken(); } if (fileBase.endsWith(".wsdl")) { fileBase = fileBase.substring(0, fileBase.length() - 5); } return fileBase; } }
4,000
496
import os import anglepy.data import h5py path = os.environ['ML_DATA_PATH']+'/mnist_binarized/' # MNIST binarized dataset from <NAME> def load_numpy(size=28): train_x = h5py.File(path+"binarized_mnist-train.h5")['data'][:].T valid_x = h5py.File(path+"binarized_mnist-valid.h5")['data'][:].T test_x = h5py.File(path+"binarized_mnist-test.h5")['data'][:].T return train_x, valid_x, test_x
187
1,068
<gh_stars>1000+ package com.github.jknack.handlebars.cache; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import org.junit.Test; import com.github.jknack.handlebars.Parser; import com.github.jknack.handlebars.Template; import com.github.jknack.handlebars.io.TemplateSource; public class NullTemplateCacheTest { @Test public void clear() { NullTemplateCache.INSTANCE.clear(); } @Test public void evict() { TemplateSource source = mock(TemplateSource.class); NullTemplateCache.INSTANCE.evict(source); } @Test public void get() throws IOException { TemplateSource source = mock(TemplateSource.class); Template template = mock(Template.class); Parser parser = mock(Parser.class); when(parser.parse(source)).thenReturn(template); Template result = NullTemplateCache.INSTANCE.get(source, parser); assertEquals(template, result); verify(parser).parse(source); } }
358
2,179
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.infra.federation.optimizer.converter.type; import org.apache.calcite.sql.fun.SqlStdOperatorTable; import org.apache.shardingsphere.sql.parser.sql.common.constant.CombineType; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public final class CombineOperatorConverterTest { @Test public void assertConvertSuccess() { assertThat(CombineOperatorConverter.convert(CombineType.UNION_ALL), is(SqlStdOperatorTable.UNION_ALL)); assertThat(CombineOperatorConverter.convert(CombineType.UNION), is(SqlStdOperatorTable.UNION)); assertThat(CombineOperatorConverter.convert(CombineType.INTERSECT_ALL), is(SqlStdOperatorTable.INTERSECT_ALL)); assertThat(CombineOperatorConverter.convert(CombineType.INTERSECT), is(SqlStdOperatorTable.INTERSECT)); assertThat(CombineOperatorConverter.convert(CombineType.EXCEPT_ALL), is(SqlStdOperatorTable.EXCEPT_ALL)); assertThat(CombineOperatorConverter.convert(CombineType.EXCEPT), is(SqlStdOperatorTable.EXCEPT)); } @Test(expected = IllegalStateException.class) public void assertConvertFailure() { CombineOperatorConverter.convert(CombineType.MINUS); } }
682
342
{ "__class__": "<class 'rl_agents.agents.control.linear_feedback.LinearFeedbackAgent'>", "K": [[1e-1, 2, 0, 1]] }
54
634
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.progress.util; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.util.ui.EDT; /** * An interface that can be implemented by the ProgressIndicator to be called from CheckCanceledHook interface. */ public interface PingProgress { void interact(); /** * When on UI thread under a PingProgress, invoke its {@link #interact()}. This might, for example, repaint the progress * to give the user feedback that the IDE is working on a long-running operation and not frozen. */ static void interactWithEdtProgress() { ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator(); if (indicator instanceof PingProgress && EDT.isCurrentThreadEdt()) { ((PingProgress)indicator).interact(); } } }
407
575
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_MEDIA_HISTORY_MEDIA_HISTORY_ORIGIN_TABLE_H_ #define CHROME_BROWSER_MEDIA_HISTORY_MEDIA_HISTORY_ORIGIN_TABLE_H_ #include <string> #include "base/updateable_sequenced_task_runner.h" #include "chrome/browser/media/history/media_history_table_base.h" #include "sql/init_status.h" namespace url { class Origin; } // namespace url namespace media_history { class MediaHistoryOriginTable : public MediaHistoryTableBase { public: static const char kTableName[]; // Returns the origin as a string for storage. static std::string GetOriginForStorage(const url::Origin& origin); private: friend class MediaHistoryStore; explicit MediaHistoryOriginTable( scoped_refptr<base::UpdateableSequencedTaskRunner> db_task_runner); ~MediaHistoryOriginTable() override; // MediaHistoryTableBase: sql::InitStatus CreateTableIfNonExistent() override; // Returns a flag indicating whether the origin id was created successfully. bool CreateOriginId(const url::Origin& origin); // Returns a flag indicating whether watchtime was increased successfully. bool IncrementAggregateAudioVideoWatchTime(const url::Origin& origin, const base::TimeDelta& time); // Recalculates the aggregate audio+video watchtime and returns a flag as to // whether this was successful. bool RecalculateAggregateAudioVideoWatchTime(const url::Origin& origin); // Deletes an origin from the database and returns a flag as to whether this // was successful. bool Delete(const url::Origin& origin); // Gets the origins which have watchtime above the given threshold. std::vector<url::Origin> GetHighWatchTimeOrigins( const base::TimeDelta& audio_video_watchtime_min); DISALLOW_COPY_AND_ASSIGN(MediaHistoryOriginTable); }; } // namespace media_history #endif // CHROME_BROWSER_MEDIA_HISTORY_MEDIA_HISTORY_ORIGIN_TABLE_H_
641
648
{"resourceType":"DataElement","id":"Condition.category","meta":{"lastUpdated":"2017-04-19T07:44:43.294+10:00"},"url":"http://hl7.org/fhir/DataElement/Condition.category","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"id":"Condition.category","path":"Condition.category","short":"problem-list-item | encounter-diagnosis","definition":"A category assigned to the condition.","comment":"The categorization is often highly contextual and may appear poorly differentiated or not very useful in other contexts.","min":0,"max":"*","type":[{"code":"CodeableConcept"}],"binding":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/elementdefinition-bindingName","valueString":"ConditionCategory"}],"strength":"example","description":"A category assigned to the condition.","valueSetReference":{"reference":"http://hl7.org/fhir/ValueSet/condition-category"}},"mapping":[{"identity":"sct-concept","map":"< 404684003 |Clinical finding|"},{"identity":"v2","map":"'problem' if from PRB-3. 'diagnosis' if from DG1 segment in PV1 message"},{"identity":"rim","map":".code"},{"identity":"w5","map":"class"}]}]}
297
665
<filename>core/internaltestsupport/src/main/java/org/apache/isis/core/internaltestsupport/jmocking/JMockActions.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.core.internaltestsupport.jmocking; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import org.hamcrest.Description; import org.jmock.api.Action; import org.jmock.api.Invocation; public final class JMockActions { private JMockActions() { } @SafeVarargs public static <T> Action returnEach(final T... values) { return new ReturnEachAction<T>(values); } public static Action returnArgument(final int i) { return new ReturnArgumentJMockAction(i); } private static class ReturnEachAction<T> implements Action { private final Collection<T> collection; private final Iterator<T> iterator; ReturnEachAction(Collection<T> collection) { this.collection = collection; this.iterator = collection.iterator(); } @SafeVarargs private ReturnEachAction(T... array) { this(Arrays.asList(array)); } @Override public T invoke(Invocation invocation) throws Throwable { return iterator.next(); } @Override public void describeTo(Description description) { description.appendValueList("return iterator.next() over ", ", ", "", collection); } } private static final class ReturnArgumentJMockAction implements Action { private final int i; private ReturnArgumentJMockAction(final int i) { this.i = i; } @Override public void describeTo(final Description description) { description.appendText("parameter #" + i + " "); } @Override public Object invoke(final Invocation invocation) throws Throwable { return invocation.getParameter(i); } } }
966
5,169
{ "name": "CameraResolutionHelper", "platforms": { "ios": "8.0" }, "authors": "<NAME>", "version": "1.0", "requires_arc": true, "summary": "CameraResolutionHelper allows you to obtain resolutions of different cameras while maintaining the aspect ratio.", "homepage": "https://github.com/adrianAlvarezFernandez/CameraResolutionHelper/blob/master/README.md", "license": { "type": "MIT", "file": "LICENSE" }, "source": { "git": "https://github.com/adrianAlvarezFernandez/CameraResolutionHelper.git", "tag": "1.0" }, "source_files": "CameraResolutionHelper/*.{swift}", "dependencies": { "SocketRocket": [ "~> 0.5.1" ] }, "pushed_with_swift_version": "3.2" }
282
321
/** * Most of the code in the Qalingo project is copyrighted Hoteia and licensed * under the Apache License Version 2.0 (release version 0.8.0) * http://www.apache.org/licenses/LICENSE-2.0 * * Copyright (c) Hoteia, 2012-2014 * http://www.hoteia.com - http://twitter.com/hoteia - <EMAIL> * */ package org.hoteia.qalingo.core.web.mvc.viewbean; import java.util.HashMap; import java.util.Map; public class SecurityViewBean extends AbstractViewBean { /** * Generated UID */ private static final long serialVersionUID = -6903293893445728139L; private String loginUrl; private String submitLoginUrl; private String forgottenPasswordUrl; private String resetPasswordUrl; private String createAccountUrl; // OAUTH / OPENID URLS private Map<String, String> urls = new HashMap<String, String>(); public String getLoginUrl() { return loginUrl; } public void setLoginUrl(String loginUrl) { this.loginUrl = loginUrl; } public String getSubmitLoginUrl() { return submitLoginUrl; } public void setSubmitLoginUrl(String submitLoginUrl) { this.submitLoginUrl = submitLoginUrl; } public String getForgottenPasswordUrl() { return forgottenPasswordUrl; } public void setForgottenPasswordUrl(String forgottenPasswordUrl) { this.forgottenPasswordUrl = forgottenPasswordUrl; } public String getResetPasswordUrl() { return resetPasswordUrl; } public void setResetPasswordUrl(String resetPasswordUrl) { this.resetPasswordUrl = resetPasswordUrl; } public String getCreateAccountUrl() { return createAccountUrl; } public void setCreateAccountUrl(String createAccountUrl) { this.createAccountUrl = createAccountUrl; } public Map<String, String> getUrls() { return urls; } public void setUrls(Map<String, String> urls) { this.urls = urls; } }
698
6,992
package sample; import static org.junit.Assert.*; import org.junit.Test; public class TheClassTest { TheClass theClass = new TheClass(); @Test public void doStuffWhenTrueThenTrue() { assertTrue(theClass.doStuff(true)); } @Test public void doStuffWhenTrueThenFalse() { assertFalse(theClass.doStuff(false)); } }
117
652
"""Controller class. Represents a Gamepad or Joystick controller. """ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. from .widget import Widget, register, widget_serialization from traitlets import Bool, Int, Float, Unicode, List, Instance @register('IPython.ControllerButton') class Button(Widget): """Represents a gamepad or joystick button""" value = Float(min=0.0, max=1.0, read_only=True, sync=True) pressed = Bool(read_only=True, sync=True) _view_name = Unicode('ControllerButton', sync=True) @register('IPython.ControllerAxis') class Axis(Widget): """Represents a gamepad or joystick axis""" value = Float(min=-1.0, max=1.0, read_only=True, sync=True) _view_name = Unicode('ControllerAxis', sync=True) @register('IPython.Controller') class Controller(Widget): """Represents a game controller""" index = Int(sync=True) # General information about the gamepad, button and axes mapping, name. # These values are all read-only and set by the JavaScript side. name = Unicode(read_only=True, sync=True) mapping = Unicode(read_only=True, sync=True) connected = Bool(read_only=True, sync=True) timestamp = Float(read_only=True, sync=True) # Buttons and axes - read-only buttons = List(trait=Instance(Button), read_only=True, sync=True, **widget_serialization) axes = List(trait=Instance(Axis), read_only=True, sync=True, **widget_serialization) _view_name = Unicode('ControllerView', sync=True) _model_name = Unicode('Controller', sync=True)
558
945
<filename>Wrapping/Generators/Java/Tests/notYetUsable/VoronoiSegmentation.java /*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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. * *=========================================================================*/ /** * Example on the use of the VoronoiSegmentationImageFilter. * */ import InsightToolkit.*; public class VoronoiSegmentation { public static void main( String argv[] ) { System.out.println("VoronoiSegmentationImageFilter Example"); itkImageFileReaderUC2_Pointer readerInput = itkImageFileReaderUC2.itkImageFileReaderUC2_New(); itkImageFileReaderUC2_Pointer readerPrior = itkImageFileReaderUC2.itkImageFileReaderUC2_New(); readerInput.SetFileName( argv[0] ); readerPrior.SetFileName( argv[1] ); readerInput.Update(); readerPrior.Update(); itkVoronoiSegmentationImageFilterUC2UC2UC2_Pointer filter = itkVoronoiSegmentationImageFilterUC2UC2UC2.itkVoronoiSegmentationImageFilterUC2UC2UC2_New(); filter.SetInput( readerInput.GetOutput() ); filter.TakeAPrior( readerPrior.GetOutput() ); filter.SetMeanPercentError( Double.parseDouble( argv[3] ) ); filter.SetSTDPercentError( Double.parseDouble( argv[4] ) ); itkImageFileWriterUC2_Pointer writer = itkImageFileWriterUC2.itkImageFileWriterUC2_New(); writer.SetInput( filter.GetOutput() ); writer.SetFileName( argv[2] ); writer.Update(); } }
646
3,799
<filename>car/app/app/src/main/java/androidx/car/app/connection/CarConnectionTypeLiveData.java /* * Copyright 2021 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. */ package androidx.car.app.connection; import static androidx.car.app.connection.CarConnection.ACTION_CAR_CONNECTION_UPDATED; import static androidx.car.app.connection.CarConnection.CAR_CONNECTION_STATE; import static androidx.car.app.utils.LogTags.TAG_CONNECTION_TO_CAR; import android.content.AsyncQueryHandler; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.net.Uri; import android.util.Log; import androidx.annotation.VisibleForTesting; import androidx.car.app.connection.CarConnection.ConnectionType; import androidx.lifecycle.LiveData; /** * A {@link LiveData} that will query once while being observed and only again if it gets updates * via a broadcast. */ final class CarConnectionTypeLiveData extends LiveData<@ConnectionType Integer> { @VisibleForTesting static final String CAR_CONNECTION_AUTHORITY = "androidx.car.app.connection"; private static final int QUERY_TOKEN = 42; private static final Uri PROJECTION_HOST_URI = new Uri.Builder().scheme("content").authority( CAR_CONNECTION_AUTHORITY).build(); private final Context mContext; private final AsyncQueryHandler mQueryHandler; private final CarConnectionBroadcastReceiver mBroadcastReceiver; CarConnectionTypeLiveData(Context context) { mContext = context; mQueryHandler = new CarConnectionQueryHandler( context.getContentResolver()); mBroadcastReceiver = new CarConnectionBroadcastReceiver(); } @Override public void onActive() { mContext.registerReceiver(mBroadcastReceiver, new IntentFilter(ACTION_CAR_CONNECTION_UPDATED)); queryForState(); } @Override public void onInactive() { mContext.unregisterReceiver(mBroadcastReceiver); mQueryHandler.cancelOperation(QUERY_TOKEN); } void queryForState() { mQueryHandler.startQuery(/* token= */ QUERY_TOKEN, /* cookie= */ null, /* uri */ PROJECTION_HOST_URI, /* projection= */ new String[]{CAR_CONNECTION_STATE}, /* selection= */ null, /* selectionArgs= */ null, /* orderBy= */ null); } class CarConnectionQueryHandler extends AsyncQueryHandler { CarConnectionQueryHandler(ContentResolver resolver) { super(resolver); } @Override protected void onQueryComplete(int token, Object cookie, Cursor response) { if (response == null) { Log.w(TAG_CONNECTION_TO_CAR, "Null response from content provider when checking " + "connection to the car, treating as disconnected"); postValue(CarConnection.CONNECTION_TYPE_NOT_CONNECTED); return; } int carConnectionTypeColumn = response.getColumnIndex(CAR_CONNECTION_STATE); if (carConnectionTypeColumn < 0) { Log.e(TAG_CONNECTION_TO_CAR, "Connection to car response is missing the " + "connection type, treating as disconnected"); postValue(CarConnection.CONNECTION_TYPE_NOT_CONNECTED); return; } if (!response.moveToNext()) { Log.e(TAG_CONNECTION_TO_CAR, "Connection to car response is empty, treating as " + "disconnected"); postValue(CarConnection.CONNECTION_TYPE_NOT_CONNECTED); return; } postValue(response.getInt(carConnectionTypeColumn)); } } class CarConnectionBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { queryForState(); } } }
1,712
504
#include <localize.h> #include "codepage.h" #define DEFAULT_CODEPAGE CP_WESTEUROPE #define SHUTDOWN_CODEPAGE CP_NIL wchar RTFCodePageToGeos(wchar ch); wchar RTFGeosToCodePage(wchar ch); void RTFSetCodePage(DosCodePage nCP);
100
585
import os import pytest import shutil from nipype.interfaces.dcm2nii import Dcm2niix no_dcm2niix = not bool(Dcm2niix().version) no_datalad = False try: from datalad import api # to pull and grab data from datalad.support.exceptions import IncompleteResultsError except ImportError: no_datalad = True DICOM_DIR = "http://datasets-tests.datalad.org/dicoms/dcm2niix-tests" @pytest.fixture def fetch_data(): def _fetch_data(datadir, dicoms): try: """Fetches some test DICOMs using datalad""" api.install(path=datadir, source=DICOM_DIR) data = os.path.join(datadir, dicoms) api.get(path=data, dataset=datadir) except IncompleteResultsError as exc: pytest.skip("Failed to fetch test data: %s" % str(exc)) return data return _fetch_data @pytest.mark.skipif(no_datalad, reason="Datalad required") @pytest.mark.skipif(no_dcm2niix, reason="Dcm2niix required") def test_dcm2niix_dti(fetch_data, tmpdir): tmpdir.chdir() datadir = tmpdir.mkdir("data").strpath dicoms = fetch_data(datadir, "Siemens_Sag_DTI_20160825_145811") def assert_dti(res): "Some assertions we will make" assert res.outputs.converted_files assert res.outputs.bvals assert res.outputs.bvecs outputs = [y for x, y in res.outputs.get().items()] if res.inputs.get("bids_format"): # ensure all outputs are of equal lengths assert len(set(map(len, outputs))) == 1 else: assert not res.outputs.bids dcm = Dcm2niix() dcm.inputs.source_dir = dicoms dcm.inputs.out_filename = "%u%z" assert_dti(dcm.run()) # now run specifying output directory and removing BIDS option outdir = tmpdir.mkdir("conversion").strpath dcm.inputs.output_dir = outdir dcm.inputs.bids_format = False assert_dti(dcm.run())
852
403
/* * Camunda Platform REST API * OpenApi Spec for Camunda Platform REST API. * * The version of the OpenAPI document: 7.16.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.camunda.consulting.openapi.client.model; import com.camunda.consulting.openapi.client.model.HistoricProcessInstanceQueryDtoSorting; import com.camunda.consulting.openapi.client.model.VariableQueryParameterDto; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * Model tests for HistoricProcessInstanceQueryDto */ public class HistoricProcessInstanceQueryDtoTest { private final HistoricProcessInstanceQueryDto model = new HistoricProcessInstanceQueryDto(); /** * Model tests for HistoricProcessInstanceQueryDto */ @Test public void testHistoricProcessInstanceQueryDto() { // TODO: test HistoricProcessInstanceQueryDto } /** * Test the property 'processInstanceId' */ @Test public void processInstanceIdTest() { // TODO: test processInstanceId } /** * Test the property 'processInstanceIds' */ @Test public void processInstanceIdsTest() { // TODO: test processInstanceIds } /** * Test the property 'processDefinitionId' */ @Test public void processDefinitionIdTest() { // TODO: test processDefinitionId } /** * Test the property 'processDefinitionKey' */ @Test public void processDefinitionKeyTest() { // TODO: test processDefinitionKey } /** * Test the property 'processDefinitionKeyIn' */ @Test public void processDefinitionKeyInTest() { // TODO: test processDefinitionKeyIn } /** * Test the property 'processDefinitionName' */ @Test public void processDefinitionNameTest() { // TODO: test processDefinitionName } /** * Test the property 'processDefinitionNameLike' */ @Test public void processDefinitionNameLikeTest() { // TODO: test processDefinitionNameLike } /** * Test the property 'processDefinitionKeyNotIn' */ @Test public void processDefinitionKeyNotInTest() { // TODO: test processDefinitionKeyNotIn } /** * Test the property 'processInstanceBusinessKey' */ @Test public void processInstanceBusinessKeyTest() { // TODO: test processInstanceBusinessKey } /** * Test the property 'processInstanceBusinessKeyLike' */ @Test public void processInstanceBusinessKeyLikeTest() { // TODO: test processInstanceBusinessKeyLike } /** * Test the property 'rootProcessInstances' */ @Test public void rootProcessInstancesTest() { // TODO: test rootProcessInstances } /** * Test the property 'finished' */ @Test public void finishedTest() { // TODO: test finished } /** * Test the property 'unfinished' */ @Test public void unfinishedTest() { // TODO: test unfinished } /** * Test the property 'withIncidents' */ @Test public void withIncidentsTest() { // TODO: test withIncidents } /** * Test the property 'withRootIncidents' */ @Test public void withRootIncidentsTest() { // TODO: test withRootIncidents } /** * Test the property 'incidentType' */ @Test public void incidentTypeTest() { // TODO: test incidentType } /** * Test the property 'incidentStatus' */ @Test public void incidentStatusTest() { // TODO: test incidentStatus } /** * Test the property 'incidentMessage' */ @Test public void incidentMessageTest() { // TODO: test incidentMessage } /** * Test the property 'incidentMessageLike' */ @Test public void incidentMessageLikeTest() { // TODO: test incidentMessageLike } /** * Test the property 'startedBefore' */ @Test public void startedBeforeTest() { // TODO: test startedBefore } /** * Test the property 'startedAfter' */ @Test public void startedAfterTest() { // TODO: test startedAfter } /** * Test the property 'finishedBefore' */ @Test public void finishedBeforeTest() { // TODO: test finishedBefore } /** * Test the property 'finishedAfter' */ @Test public void finishedAfterTest() { // TODO: test finishedAfter } /** * Test the property 'executedActivityAfter' */ @Test public void executedActivityAfterTest() { // TODO: test executedActivityAfter } /** * Test the property 'executedActivityBefore' */ @Test public void executedActivityBeforeTest() { // TODO: test executedActivityBefore } /** * Test the property 'executedJobAfter' */ @Test public void executedJobAfterTest() { // TODO: test executedJobAfter } /** * Test the property 'executedJobBefore' */ @Test public void executedJobBeforeTest() { // TODO: test executedJobBefore } /** * Test the property 'startedBy' */ @Test public void startedByTest() { // TODO: test startedBy } /** * Test the property 'superProcessInstanceId' */ @Test public void superProcessInstanceIdTest() { // TODO: test superProcessInstanceId } /** * Test the property 'subProcessInstanceId' */ @Test public void subProcessInstanceIdTest() { // TODO: test subProcessInstanceId } /** * Test the property 'superCaseInstanceId' */ @Test public void superCaseInstanceIdTest() { // TODO: test superCaseInstanceId } /** * Test the property 'subCaseInstanceId' */ @Test public void subCaseInstanceIdTest() { // TODO: test subCaseInstanceId } /** * Test the property 'caseInstanceId' */ @Test public void caseInstanceIdTest() { // TODO: test caseInstanceId } /** * Test the property 'tenantIdIn' */ @Test public void tenantIdInTest() { // TODO: test tenantIdIn } /** * Test the property 'withoutTenantId' */ @Test public void withoutTenantIdTest() { // TODO: test withoutTenantId } /** * Test the property 'executedActivityIdIn' */ @Test public void executedActivityIdInTest() { // TODO: test executedActivityIdIn } /** * Test the property 'activeActivityIdIn' */ @Test public void activeActivityIdInTest() { // TODO: test activeActivityIdIn } /** * Test the property 'active' */ @Test public void activeTest() { // TODO: test active } /** * Test the property 'suspended' */ @Test public void suspendedTest() { // TODO: test suspended } /** * Test the property 'completed' */ @Test public void completedTest() { // TODO: test completed } /** * Test the property 'externallyTerminated' */ @Test public void externallyTerminatedTest() { // TODO: test externallyTerminated } /** * Test the property 'internallyTerminated' */ @Test public void internallyTerminatedTest() { // TODO: test internallyTerminated } /** * Test the property 'variables' */ @Test public void variablesTest() { // TODO: test variables } /** * Test the property 'variableNamesIgnoreCase' */ @Test public void variableNamesIgnoreCaseTest() { // TODO: test variableNamesIgnoreCase } /** * Test the property 'variableValuesIgnoreCase' */ @Test public void variableValuesIgnoreCaseTest() { // TODO: test variableValuesIgnoreCase } /** * Test the property 'orQueries' */ @Test public void orQueriesTest() { // TODO: test orQueries } /** * Test the property 'sorting' */ @Test public void sortingTest() { // TODO: test sorting } }
3,486
1,844
/* * Copyright 2010-2013 Ning, Inc. * Copyright 2014-2018 Groupon, Inc * Copyright 2014-2018 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.billing.catalog; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import java.util.Collection; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlIDREF; import org.killbill.billing.catalog.api.Limit; import org.killbill.billing.catalog.api.Product; import org.killbill.billing.catalog.api.ProductCategory; import org.killbill.billing.catalog.api.StaticCatalog; import org.killbill.xmlloader.ValidatingConfig; import org.killbill.xmlloader.ValidationError; import org.killbill.xmlloader.ValidationErrors; @XmlAccessorType(XmlAccessType.NONE) public class DefaultProduct extends ValidatingConfig<StandaloneCatalog> implements Product, Externalizable { @XmlAttribute(required = true) @XmlID private String name; @XmlAttribute(required = false) private String prettyName; @XmlElement(required = true) private ProductCategory category; @XmlElementWrapper(name = "included", required = false) @XmlIDREF @XmlElement(type = DefaultProduct.class, name = "addonProduct", required = false) private CatalogEntityCollection<Product> included; @XmlElementWrapper(name = "available", required = false) @XmlIDREF @XmlElement(type = DefaultProduct.class, name = "addonProduct", required = false) private CatalogEntityCollection<Product> available; @XmlElementWrapper(name = "limits", required = false) @XmlElement(name = "limit", required = false) private DefaultLimit[] limits; // Not included in XML private String catalogName; @Override public String getCatalogName() { return catalogName; } @Override public ProductCategory getCategory() { return category; } @Override public Collection<Product> getIncluded() { return included.getEntries(); } @Override public StaticCatalog getCatalog() { return getRoot(); } @Override public Collection<Product> getAvailable() { return available.getEntries(); } public CatalogEntityCollection<Product> getCatalogEntityCollectionAvailable() { return available; } // Required for deserialization public DefaultProduct() { this.included = new CatalogEntityCollection<Product>(); this.available = new CatalogEntityCollection<Product>(); this.limits = new DefaultLimit[0]; } public DefaultProduct(final String name, final ProductCategory category) { this.included = new CatalogEntityCollection<Product>(); this.available = new CatalogEntityCollection<Product>(); this.category = category; this.name = name; } @Override public String getName() { return name; } @Override public String getPrettyName() { return prettyName; } public boolean isIncluded(final DefaultProduct addon) { for (final Product p : included.getEntries()) { if (addon == p) { return true; } } return false; } public boolean isAvailable(final DefaultProduct addon) { for (final Product p : included.getEntries()) { if (addon == p) { return true; } } return false; } @Override public DefaultLimit[] getLimits() { return limits; } protected Limit findLimit(String unit) { for (Limit limit : limits) { if (limit.getUnit().getName().equals(unit)) { return limit; } } return null; } @Override public boolean compliesWithLimits(String unit, double value) { Limit l = findLimit(unit); if (l == null) { return true; } return l.compliesWith(value); } @Override public void initialize(final StandaloneCatalog catalog) { super.initialize(catalog); CatalogSafetyInitializer.initializeNonRequiredNullFieldsWithDefaultValue(this); for (final DefaultLimit cur : limits) { cur.initialize(catalog); } if (prettyName == null) { this.prettyName = name; } catalogName = catalog.getCatalogName(); } @Override public ValidationErrors validate(final StandaloneCatalog catalog, final ValidationErrors errors) { if (catalogName == null || !catalogName.equals(catalog.getCatalogName())) { errors.add(new ValidationError(String.format("Invalid catalogName for product '%s'", name), DefaultProduct.class, "")); } //TODO: MDW validation: inclusion and exclusion lists can only contain addon products //TODO: MDW validation: a given product can only be in, at most, one of inclusion and exclusion lists return errors; } public DefaultProduct setName(final String name) { this.name = name; return this; } public DefaultProduct setPrettyName(final String prettyName) { this.prettyName = prettyName; return this; } public DefaultProduct setCatagory(final ProductCategory category) { this.category = category; return this; } public DefaultProduct setCategory(final ProductCategory category) { this.category = category; return this; } public DefaultProduct setIncluded(final Collection<Product> included) { this.included = new CatalogEntityCollection<Product>(included); return this; } public DefaultProduct setAvailable(final Collection<Product> available) { this.available = new CatalogEntityCollection<Product>(available); return this; } public DefaultProduct setCatalogName(final String catalogName) { this.catalogName = catalogName; return this; } @Override public String toString() { return "DefaultProduct{" + "name='" + name + '\'' + ", category=" + category + ", included=" + included + ", available=" + available + ", limits=" + Arrays.toString(limits) + ", catalogName='" + catalogName + '\'' + '}'; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof DefaultProduct)) { return false; } final DefaultProduct product = (DefaultProduct) o; if (name != null ? !name.equals(product.name) : product.name != null) { return false; } if (category != product.category) { return false; } if (included != null ? !included.equals(product.included) : product.included != null) { return false; } if (available != null ? !available.equals(product.available) : product.available != null) { return false; } // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(limits, product.limits)) { return false; } return catalogName != null ? catalogName.equals(product.catalogName) : product.catalogName == null; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (category != null ? category.hashCode() : 0); result = 31 * result + (included != null ? included.hashCode() : 0); result = 31 * result + (available != null ? available.hashCode() : 0); result = 31 * result + Arrays.hashCode(limits); result = 31 * result + (catalogName != null ? catalogName.hashCode() : 0); return result; } @Override public void writeExternal(final ObjectOutput out) throws IOException { out.writeBoolean(catalogName != null); if (catalogName != null) { out.writeUTF(catalogName); } out.writeBoolean(name != null); if (name != null) { out.writeUTF(name); } out.writeBoolean(prettyName != null); if (prettyName != null) { out.writeUTF(prettyName); } out.writeBoolean(category != null); if (category != null) { out.writeUTF(category.name()); } out.writeObject(included); out.writeObject(available); out.writeObject(limits); } @Override public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { this.catalogName = in.readBoolean() ? in.readUTF() : null; this.name = in.readBoolean() ? in.readUTF() : null; this.prettyName = in.readBoolean() ? in.readUTF() : null; this.category = in.readBoolean() ? ProductCategory.valueOf(in.readUTF()) : null; this.included = (CatalogEntityCollection<Product>) in.readObject(); this.available = (CatalogEntityCollection<Product>) in.readObject(); this.limits = (DefaultLimit[]) in.readObject(); } }
3,853
369
<filename>cdap-app-fabric/src/main/java/io/cdap/cdap/internal/pipeline/StageContext.java /* * Copyright © 2014 <NAME>, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.cdap.internal.pipeline; import io.cdap.cdap.pipeline.Context; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * Concrete implementation of {@link Context} for moving data from downstream * and to upstream stages. */ public final class StageContext implements Context { private final Map<String, Object> properties; private final Object upStream; private Object downStream; /** * Creates a new instance by copying the given {@link StageContext} downstream object as the new upstream object. * It also copy all the properties from the given {@link StageContext}. */ public static StageContext next(StageContext context) { return new StageContext(context.downStream, context.properties); } /** * Constructor constructed when the result is available from upstream. * * @param upStream Object data */ public StageContext(Object upStream) { this(upStream, Collections.<String, Object>emptyMap()); } private StageContext(Object upStream, Map<String, Object> properties) { this.upStream = upStream; this.properties = new HashMap<>(properties); } /** * Sets result to be sent to downstream from the current stage. * * @param downStream Object to be sent to downstream */ @Override public void setDownStream(Object downStream) { this.downStream = downStream; } /** * @return Object received from upstream */ @Override public Object getUpStream() { return upStream; } /** * @return Object to be sent to downstream. */ @Override public Object getDownStream() { return downStream; } @Nullable @Override @SuppressWarnings("unchecked") public <T> T getProperty(String key) { return (T) properties.get(key); } @Override public <T> void setProperty(String key, T value) { properties.put(key, value); } @Override public Set<String> getPropertyKeys() { return Collections.unmodifiableSet(properties.keySet()); } }
821
420
<reponame>duclmdev/TachiyomiServer /* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.duktape; import kotlin.NotImplementedError; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import java.io.Closeable; /** A simple EMCAScript (Javascript) interpreter. */ public final class Duktape implements Closeable, AutoCloseable { private ScriptEngineManager factory = new ScriptEngineManager(); private ScriptEngine engine = factory.getEngineByName("JavaScript"); /** * Create a new interpreter instance. Calls to this method <strong>must</strong> matched with * calls to {@link #close()} on the returned instance to avoid leaking native memory. */ public static Duktape create() { return new Duktape(); } private Duktape() {} /** * Evaluate {@code script} and return a result. {@code fileName} will be used in error * reporting. Note that the result must be one of the supported Java types or the call will * return null. * * @throws DuktapeException if there is an error evaluating the script. */ public synchronized Object evaluate(String script, String fileName) { throw new NotImplementedError("Not implemented!"); } /** * Evaluate {@code script} and return a result. Note that the result must be one of the * supported Java types or the call will return null. * * @throws DuktapeException if there is an error evaluating the script. */ public synchronized Object evaluate(String script) { try { return engine.eval(script); } catch (ScriptException e) { throw new DuktapeException(e.getMessage()); } } /** * Provides {@code object} to JavaScript as a global object called {@code name}. {@code type} * defines the interface implemented by {@code object} that will be accessible to JavaScript. * {@code type} must be an interface that does not extend any other interfaces, and cannot define * any overloaded methods. * <p>Methods of the interface may return {@code void} or any of the following supported argument * types: {@code boolean}, {@link Boolean}, {@code int}, {@link Integer}, {@code double}, * {@link Double}, {@link String}. */ public synchronized <T> void set(String name, Class<T> type, T object) { throw new NotImplementedError("Not implemented!"); } /** * Attaches to a global JavaScript object called {@code name} that implements {@code type}. * {@code type} defines the interface implemented in JavaScript that will be accessible to Java. * {@code type} must be an interface that does not extend any other interfaces, and cannot define * any overloaded methods. * <p>Methods of the interface may return {@code void} or any of the following supported argument * types: {@code boolean}, {@link Boolean}, {@code int}, {@link Integer}, {@code double}, * {@link Double}, {@link String}. */ public synchronized <T> T get(final String name, final Class<T> type) { throw new NotImplementedError("Not implemented!"); } /** * Release the native resources associated with this object. You <strong>must</strong> call this * method for each instance to avoid leaking native memory. */ @Override public synchronized void close() {} }
1,187
7,158
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #ifndef _OPENCV_OR_VECTOR_HPP_ #define _OPENCV_OR_VECTOR_HPP_ #ifdef __CUDACC__ #define __CV_CUDA_HOST_DEVICE__ __host__ __device__ __forceinline__ #else #define __CV_CUDA_HOST_DEVICE__ #endif namespace cv { namespace hfs { namespace orutils { template <class T> struct Vector2_ { T x, y; }; template <class T> struct Vector4_ { T x, y, z, w; }; template <class T> class Vector2 : public Vector2_ < T > { public: __CV_CUDA_HOST_DEVICE__ Vector2() {} __CV_CUDA_HOST_DEVICE__ Vector2(const T v0, const T v1) { this->x = v0; this->y = v1; } __CV_CUDA_HOST_DEVICE__ Vector2(const Vector2_<T> &v) { this->x = v.x; this->y = v.y; } __CV_CUDA_HOST_DEVICE__ friend Vector2<T> &operator /= (Vector2<T> &lhs, T d) { if (d == 0) { return lhs; } lhs.x /= d; lhs.y /= d; return lhs; } __CV_CUDA_HOST_DEVICE__ friend Vector2<T>& operator += (Vector2<T> &lhs, const Vector2<T> &rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } }; template <class T> class Vector4 : public Vector4_ < T > { public: __CV_CUDA_HOST_DEVICE__ Vector4() {} __CV_CUDA_HOST_DEVICE__ Vector4(const T v0, const T v1, const T v2, const T v3) { this->x = v0; this->y = v1; this->z = v2; this->w = v3; } __CV_CUDA_HOST_DEVICE__ friend Vector4<T> &operator /= (Vector4<T> &lhs, T d) { lhs.x /= d; lhs.y /= d; lhs.z /= d; lhs.w /= d; return lhs; } __CV_CUDA_HOST_DEVICE__ friend Vector4<T>& operator += (Vector4<T> &lhs, const Vector4<T> &rhs) { lhs.x += rhs.x; lhs.y += rhs.y; lhs.z += rhs.z; lhs.w += rhs.w; return lhs; } }; }}} #endif
1,072
1,511
{ "name": "alfandega", "epoch": null, "version": "2.0", "release": "1.7.3", "arch": "noarch", "os": "linux", "summary": "A perl modules for iptables firewall control.", "description": null, "distribution": null, "vendor": null, "license": "GPL", "packager": "<NAME> <<EMAIL>>", "group": "Applications/Networking/Security", "url": "http://alfandega.sourceforge.net/", "source_rpm": "alfandega-2.0-1.7.3.src.rpm", "dist_url": null, "is_binary": true }
230
328
package com.dragon.flow.service.flowable; import com.dragon.flow.model.org.Personal; import com.dragon.flow.vo.flowable.processinstance.InstanceQueryParamsVo; import com.dragon.flow.vo.flowable.processinstance.ProcessInstanceVo; import com.dragon.flow.vo.flowable.runtime.StartProcessInstanceVo; import com.dragon.flow.vo.flowable.processinstance.EndVo; import com.dragon.tools.pager.PagerModel; import com.dragon.tools.pager.Query; import com.dragon.tools.vo.ReturnVo; import org.flowable.engine.runtime.ProcessInstance; import java.util.Map; /** * @program: flow * @description: 流程实例service * @author: Bruce.Liu * @create: 2021-04-20 14:20 **/ public interface IFlowableProcessInstanceService { /** * 启动流程 * * @param params 启动参数 * @return 流程实例 */ ReturnVo<ProcessInstance> startProcessInstanceByKey(StartProcessInstanceVo params); /** * @param params 启动参数 * @param personal 发起人 * @return */ Map<String, Object> getStartVariables(StartProcessInstanceVo params, Personal personal); /** * 查询我的流程列表 * * @param paramsVo 查询参数 * @return * @throws Exception */ PagerModel<ProcessInstanceVo> findMyProcessinstancesPagerModel(InstanceQueryParamsVo paramsVo, Query query); /** * 终止流程 * * @param endVo 基本参数 * @return */ ReturnVo<String> stopProcess(EndVo endVo); }
593
312
<gh_stars>100-1000 /******************************************************************************* * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.sail.lucene.config; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.sail.lucene.LuceneSail; /** * Defines constants for the LuceneSail schema which is used by * {@link org.eclipse.rdf4j.sail.lucene.config.LuceneSailFactory}s to initialize {@link LuceneSail}s. */ public class LuceneSailConfigSchema { /** * The LuceneSail schema namespace ( <tt>http://www.openrdf.org/config/sail/lucene#</tt>). */ public static final String NAMESPACE = "http://www.openrdf.org/config/sail/lucene#"; public static final IRI INDEX_DIR; static { ValueFactory factory = SimpleValueFactory.getInstance(); INDEX_DIR = factory.createIRI(NAMESPACE, "indexDir"); } }
413
1,821
<reponame>hangqiu/pixie /* * Copyright 2018- The Pixie Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ #include "src/carnot/planner/distributed/splitter/presplit_optimizer/limit_push_down_rule.h" #include "src/carnot/planner/distributed/splitter/executor_utils.h" namespace px { namespace carnot { namespace planner { namespace distributed { // Get new locations for the input limit node. // A single limit may be cloned and pushed up to multiple branches. StatusOr<absl::flat_hash_set<OperatorIR*>> LimitPushdownRule::NewLimitParents( OperatorIR* current_node) { // Maps we can simply push up the chain. if (Match(current_node, Map())) { DCHECK_EQ(1, current_node->parents().size()); // Don't push a Limit earlier than a PEM-only Map, because we need to ensure that after // splitting on Limit nodes, we don't end up with a PEM-only map on the Kelvin side of // the distributed plan. PL_ASSIGN_OR_RETURN( auto has_pem_only_udf, HasFuncWithExecutor(compiler_state_, current_node, udfspb::UDFSourceExecutor::UDF_PEM)); if (!has_pem_only_udf) { return NewLimitParents(current_node->parents()[0]); } } // Unions will need at most N records from each source. if (Match(current_node, Union())) { absl::flat_hash_set<OperatorIR*> results; // We want 1 Limit node after each union, and one before // each of its branches. results.insert(current_node); for (OperatorIR* parent : current_node->parents()) { PL_ASSIGN_OR_RETURN(auto parent_results, NewLimitParents(parent)); for (OperatorIR* parent_result : parent_results) { results.insert(parent_result); } } return results; } return absl::flat_hash_set<OperatorIR*>{current_node}; } StatusOr<bool> LimitPushdownRule::Apply(IRNode* ir_node) { if (!Match(ir_node, Limit())) { return false; } auto graph = ir_node->graph(); LimitIR* limit = static_cast<LimitIR*>(ir_node); DCHECK_EQ(1, limit->parents().size()); OperatorIR* limit_parent = limit->parents()[0]; PL_ASSIGN_OR_RETURN(auto new_parents, NewLimitParents(limit_parent)); // If we don't push the limit up at all, just return. if (new_parents.size() == 1 && new_parents.find(limit_parent) != new_parents.end()) { return false; } // Remove the limit from its previous location. for (OperatorIR* child : limit->Children()) { PL_RETURN_IF_ERROR(child->ReplaceParent(limit, limit_parent)); } PL_RETURN_IF_ERROR(limit->RemoveParent(limit_parent)); // Add the limit to its new location(s). for (OperatorIR* new_parent : new_parents) { PL_ASSIGN_OR_RETURN(LimitIR * new_limit, graph->CopyNode(limit)); // The parent's children should now be the children of the limit. for (OperatorIR* former_child : new_parent->Children()) { PL_RETURN_IF_ERROR(former_child->ReplaceParent(new_parent, new_limit)); } // The limit should now be a child of the parent. PL_RETURN_IF_ERROR(new_limit->AddParent(new_parent)); // Ensure we inherit the relation of the parent. PL_RETURN_IF_ERROR(new_limit->SetResolvedType(new_parent->resolved_type())); } PL_RETURN_IF_ERROR(graph->DeleteNode(limit->id())); return true; } } // namespace distributed } // namespace planner } // namespace carnot } // namespace px
1,324
1,900
/* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ehcache.clustered.client.internal.service; import org.ehcache.Cache; import org.ehcache.PersistentCacheManager; import org.ehcache.clustered.client.config.builders.TimeoutsBuilder; import org.ehcache.clustered.client.internal.UnitTestConnectionService; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.internal.resilience.ThrowingResilienceStrategy; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.terracotta.connection.Connection; import org.terracotta.connection.ConnectionPropertyNames; import java.net.URI; import java.time.Duration; import java.util.Collection; import java.util.Properties; import static org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder.clusteredDedicated; import static org.ehcache.clustered.client.config.builders.ClusteringServiceConfigurationBuilder.cluster; import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder; import static org.ehcache.config.builders.CacheManagerBuilder.newCacheManagerBuilder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.terracotta.utilities.test.matchers.Eventually.within; public class ConnectionClosedTest { private static final URI CLUSTER_URI = URI.create("terracotta://connection.com:9540/timeout"); @Before public void definePassthroughServer() { UnitTestConnectionService.add(CLUSTER_URI, new UnitTestConnectionService.PassthroughServerBuilder() .resource("primary-server-resource", 64, MemoryUnit.MB) .build()); } @After public void removePassthroughServer() { try { UnitTestConnectionService.remove(CLUSTER_URI); } catch (IllegalStateException e) { assertThat(e.getMessage(), is("Connection already closed")); } } @Test public void testCacheOperationThrowsAfterConnectionClosed() throws Exception { ResourcePoolsBuilder resourcePoolsBuilder = ResourcePoolsBuilder.newResourcePoolsBuilder() .with(clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)); CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = newCacheManagerBuilder() .with(cluster(CLUSTER_URI) .timeouts(TimeoutsBuilder .timeouts() .connection(Duration.ofSeconds(20)) .build()) .autoCreate(c -> c)) .withCache("clustered-cache", newCacheConfigurationBuilder(Long.class, String.class, resourcePoolsBuilder).withResilienceStrategy(new ThrowingResilienceStrategy<>())); try (PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) { Cache<Long, String> cache = cacheManager.getCache("clustered-cache", Long.class, String.class); Collection<Properties> connectionProperties = UnitTestConnectionService.getConnectionProperties(CLUSTER_URI); assertThat(connectionProperties.size(), is(1)); Properties properties = connectionProperties.iterator().next(); assertThat(properties.getProperty(ConnectionPropertyNames.CONNECTION_TIMEOUT), is("20000")); cache.put(1L, "value"); assertThat(cache.get(1L), is("value")); Collection<Connection> connections = UnitTestConnectionService.getConnections(CLUSTER_URI); assertThat(connections.size(), is(1)); connections.iterator().next().close(); assertThat(() -> cache.get(1L), within(Duration.ofSeconds(60)).is("value")); } } }
1,516
4,047
#include<lua.h> #include<stdio.h> #include<stdlib.h> #include<png.h> #include<string.h> #if !defined(_MSC_VER) #include<unistd.h> #endif static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; (void)osize; if (nsize == 0) { free(ptr); return NULL; } else { return realloc(ptr, nsize); } } void open_image(const char *fname) { png_image image; memset(&image, 0, (sizeof image)); image.version = PNG_IMAGE_VERSION; if(png_image_begin_read_from_file(&image, fname) != 0) { png_bytep buffer; image.format = PNG_FORMAT_RGBA; buffer = malloc(PNG_IMAGE_SIZE(image)); if(png_image_finish_read(&image, NULL, buffer, 0, NULL) != 0) { printf("Image %s read failed: %s\n", fname, image.message); } // png_free_image(&image); free(buffer); } else { printf("Image %s open failed: %s", fname, image.message); } } int printer(lua_State *l) { if(!lua_isstring(l, 1)) { fprintf(stderr, "Incorrect call.\n"); return 0; } open_image(lua_tostring(l, 1)); return 0; } int main(int argc, char **argv) { lua_State *l = lua_newstate(l_alloc, NULL); if(!l) { printf("Lua state allocation failed.\n"); return 1; } lua_register(l, "printer", printer); lua_getglobal(l, "printer"); lua_pushliteral(l, "foobar.png"); lua_call(l, 1, 0); lua_close(l); return 0; }
738
1,100
<filename>Exercise_18/Exercise_18_21/Exercise_18_21.java /********************************************************************************* * (Decimal to binary) Write a recursive method that converts a decimal number * * into a binary number as a string. The method header is: * * * * public static String dec2Bin(int value) * * * * Write a test program that prompts the user to enter a decimal number and * * displays its binary equivalent. * *********************************************************************************/ import java.util.Scanner; public class Exercise_18_21 { /** Main method */ public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Prompt the user to enter a decimal number System.out.print("Enter a decimal number: "); int value = input.nextInt(); // Display the value's binary equivalent System.out.println("The binary equivalent of " + value + " is " + dec2Bin(value)); } /** Methods converts a decimal number * into a binary number as a string */ public static String dec2Bin(int value) { String result = ""; return dec2Bin(value, result); } /** Recursive helper method */ public static String dec2Bin(int value, String result) { if (value / 2 == 0) // Base case return (value % 2) + result; else return dec2Bin(value / 2, (value % 2) + result); // Recursive call } }
679
3,710
<reponame>rozhuk-im/opentoonz<filename>toonz/sources/toonz/scanpopup.h #pragma once #ifndef SCANPOPUP_H #define SCANPOPUP_H #include "toonzqt/dvdialog.h" #include "tscanner.h" #include "scanlist.h" // forward declaration namespace DVGui { class DoubleField; class IntField; class CheckBox; } class QComboBox; class ProgressDialog; //============================================================================= // MyScannerListener //----------------------------------------------------------------------------- class MyScannerListener final : public QObject, public TScannerListener { Q_OBJECT int m_current; int m_inc; ScanList m_scanList; bool m_isCanceled, m_isPreview; DVGui::ProgressDialog *m_progressDialog; public: MyScannerListener(const ScanList &scanList); void onImage(const TRasterImageP &) override; void onError() override; void onNextPaper() override; void onAutomaticallyNextPaper() override; bool isCanceled() override; protected slots: void cancelButtonPressed(); }; //============================================================================= // DefineScannerPopup //----------------------------------------------------------------------------- class DefineScannerPopup final : public DVGui::Dialog { Q_OBJECT QComboBox *m_scanDriverOm; public: DefineScannerPopup(); public slots: void accept() override; }; //============================================================================= // ScanSettingsPopup //----------------------------------------------------------------------------- class ScanSettingsPopup final : public DVGui::Dialog { Q_OBJECT QLabel *m_scannerNameLbl; DVGui::CheckBox *m_reverseOrderCB; DVGui::CheckBox *m_paperFeederCB; QComboBox *m_modeOm; DVGui::DoubleField *m_dpi; DVGui::IntField *m_threshold; DVGui::IntField *m_brightness; QComboBox *m_paperFormatOm; QLabel *m_formatLbl; QLabel *m_modeLbl; QLabel *m_thresholdLbl; QLabel *m_brightnessLbl; QLabel *m_dpiLbl; public: ScanSettingsPopup(); protected: void showEvent(QShowEvent *event) override; void hideEvent(QHideEvent *event) override; void connectAll(); void disconnectAll(); public slots: void updateUI(); void onToggle(int); void onPaperChanged(const QString &format); void onValueChanged(bool); void onModeChanged(const QString &mode); }; #ifdef LINETEST //============================================================================= // AutocenterPopup //----------------------------------------------------------------------------- class AutocenterPopup final : public DVGui::Dialog { Q_OBJECT DVGui::CheckBox *m_autocenter; QComboBox *m_pegbarHoles; QComboBox *m_fieldGuide; public: AutocenterPopup(); protected: void showEvent(QShowEvent *event); protected slots: void onAutocenterToggled(bool); void onPegbarHolesChanged(const QString &); void onFieldGuideChanged(const QString &); }; #endif // LINETEST #endif // SCANPOPUP_H
907
1,405
package com.lenovo.lps.reaper.sdk.request; import com.lenovo.lps.reaper.sdk.api.DispatchCallback; import com.lenovo.lps.reaper.sdk.util.TLog; public final class WorkerTask implements Runnable { private static final String a = WorkerTask.class.getName(); private final DispatchCallback b; public WorkerTask(DispatchCallback dispatchCallback) { this.b = dispatchCallback; } public final void run() { try { this.b.dispatch(); } catch (Exception ex) { TLog.e(a, "Error when report events to server. " + ex.getMessage()); } } }
239
422
from all_models.models import TbSource class SourceService(object): @staticmethod def updateSource(sourceData): tbModel = TbSource.objects.filter(id=sourceData["id"]) tbModel.update(**sourceData)
83
488
<filename>CTCWordBeamSearch-master/cpp/test.hpp #pragma once // test the classes and functions of this project void test();
39
544
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.submarine.commons.runtime.api; import com.google.common.collect.Lists; import java.util.List; import java.util.stream.Collectors; /** * Represents the type of Runtime. */ public enum Runtime { TONY(Constants.TONY), YARN_SERVICE(Constants.YARN_SERVICE); private String value; Runtime(String value) { this.value = value; } public String getValue() { return value; } public static Runtime parseByValue(String value) { for (Runtime rt : Runtime.values()) { if (rt.value.equalsIgnoreCase(value)) { return rt; } } return null; } public static String getValues() { List<String> values = Lists.newArrayList(Runtime.values()).stream() .map(rt -> rt.value).collect(Collectors.toList()); return String.join(",", values); } public static class Constants { public static final String TONY = "tony"; public static final String YARN_SERVICE = "yarnservice"; } }
544
435
<filename>pycon-thailand-2018/videos/studying-thai-with-programming.json { "copyright_text": "Creative Commons Attribution license (reuse allowed)", "description": "I'm an educator with a background in computer science. I've worked as a firmware engineer at a large corporation and as a software developer at a small firm and taught at innovative high schools teaching mathematics and CS. I'm currently teaching at an international school in Bangkok. I am part Thai but born and raised in America in the state of Kentucky.", "duration": 251, "language": "tha", "recorded": "2018-06-16", "related_urls": [ { "label": "Conference schedule", "url": "https://th.pycon.org/en/schedule/" } ], "speakers": [ "<NAME>" ], "tags": [ "lightning talk" ], "thumbnail_url": "https://i.ytimg.com/vi/4SJXvbsACwo/maxresdefault.jpg", "title": "Studying Thai with programming", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=4SJXvbsACwo" } ] }
355
741
import dkim def bs64encode(value): import base64 return b"=?utf-8?B?"+ base64.b64encode(value) + b"?=" def quoted_printable(value): import quopri return b"=?utf-8?Q?"+ quopri.encodestring(value) + b"?=" def id_generator(size=6): import random import string chars=string.ascii_uppercase + string.digits return (''.join(random.choice(chars) for _ in range(size))).encode("utf-8") def get_date(): from time import gmtime, strftime mdate= strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) return (mdate).encode("utf-8") def query_mx_record(domain): import dns.resolver try: mx_answers = dns.resolver.query(domain, 'MX') for rdata in mx_answers: a_answers = dns.resolver.query(rdata.exchange, 'A') for data in a_answers: return str(data) except Exception as e: import traceback traceback.print_exc() def get_mail_server_from_email_address(e): domain = e.split(b"@")[1] return query_mx_record(domain.decode("utf-8")) def recursive_fixup(input, old, new): if isinstance(input, dict): items = list(input.items()) elif isinstance(input, (list, tuple)): items = enumerate(input) else: return input.replace(old, new) # now call ourself for every value and replace in the input for key, value in items: input[key] = recursive_fixup(value, old, new) return input def generate_dkim_header(dkim_msg, dkim_para): d = dkim.DKIM(dkim_msg) dkim_header = d.sign(dkim_para["s"], dkim_para["d"], open("dkimkey","rb").read(), canonicalize=(b'simple',b'relaxed'), include_headers=[b"from"]).strip()+b"\r\n" return dkim_header
682
2,030
import json import os import threading import unittest from http.server import BaseHTTPRequestHandler, HTTPServer from test.support import EnvironmentVarGuard from urllib.parse import urlparse from kaggle_web_client import (KaggleWebClient, _KAGGLE_URL_BASE_ENV_VAR_NAME, _KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME, _KAGGLE_IAP_TOKEN_ENV_VAR_NAME, CredentialError, BackendError) from kaggle_datasets import KaggleDatasets, _KAGGLE_TPU_NAME_ENV_VAR_NAME _TEST_JWT = '<PASSWORD>' _TEST_IAP = 'IAP_TOKEN' _TPU_GCS_BUCKET = 'gs://kds-tpu-ea1971a458ffd4cd51389e7574c022ecc0a82bb1b52ccef08c8a' _AUTOML_GCS_BUCKET = 'gs://kds-automl-ea1971a458ffd4cd51389e7574c022ecc0a82bb1b52ccef08c8a' class GcsDatasetsHTTPHandler(BaseHTTPRequestHandler): def set_request(self): raise NotImplementedError() def get_response(self): raise NotImplementedError() def do_HEAD(s): s.send_response(200) def do_POST(s): s.set_request() s.send_response(200) s.send_header("Content-type", "application/json") s.end_headers() s.wfile.write(json.dumps(s.get_response()).encode("utf-8")) class TestDatasets(unittest.TestCase): SERVER_ADDRESS = urlparse(os.getenv(_KAGGLE_URL_BASE_ENV_VAR_NAME, default="http://127.0.0.1:8001")) def _test_client(self, client_func, expected_path, expected_body, is_tpu=True, success=True, iap_token=False): _request = {} class GetGcsPathHandler(GcsDatasetsHTTPHandler): def set_request(self): _request['path'] = self.path content_len = int(self.headers.get('Content-Length')) _request['body'] = json.loads(self.rfile.read(content_len)) _request['headers'] = self.headers def get_response(self): if success: gcs_path = _TPU_GCS_BUCKET if is_tpu else _AUTOML_GCS_BUCKET return {'result': { 'destinationBucket': gcs_path, 'destinationPath': None}, 'wasSuccessful': "true"} else: return {'wasSuccessful': "false"} env = EnvironmentVarGuard() env.set(_KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME, _TEST_JWT) if is_tpu: env.set(_KAGGLE_TPU_NAME_ENV_VAR_NAME, 'FAKE_TPU') if iap_token: env.set(_KAGGLE_IAP_TOKEN_ENV_VAR_NAME, _TEST_IAP) with env: with HTTPServer((self.SERVER_ADDRESS.hostname, self.SERVER_ADDRESS.port), GetGcsPathHandler) as httpd: threading.Thread(target=httpd.serve_forever).start() try: client_func() finally: httpd.shutdown() path, headers, body = _request['path'], _request['headers'], _request['body'] self.assertEqual( path, expected_path, msg="Fake server did not receive the right request from the KaggleDatasets client.") self.assertEqual( body, expected_body, msg="Fake server did not receive the right body from the KaggleDatasets client.") self.assertIn('Content-Type', headers.keys(), msg="Fake server did not receive a Content-Type header from the KaggleDatasets client.") self.assertEqual('application/json', headers.get('Content-Type'), msg="Fake server did not receive an application/json content type header from the KaggleDatasets client.") self.assertIn('X-Kaggle-Authorization', headers.keys(), msg="Fake server did not receive an X-Kaggle-Authorization header from the KaggleDatasets client.") if iap_token: self.assertEqual(f'Bearer {_TEST_IAP}', headers.get('Authorization'), msg="Fake server did not receive an Authorization header from the KaggleDatasets client.") else: self.assertNotIn('Authorization', headers.keys(), msg="Fake server received an Authorization header from the KaggleDatasets client. It shouldn't.") self.assertEqual(f'Bearer {_TEST_JWT}', headers.get('X-Kaggle-Authorization'), msg="Fake server did not receive the right X-Kaggle-Authorization header from the KaggleDatasets client.") def test_no_token_fails(self): env = EnvironmentVarGuard() env.unset(_KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME) with env: with self.assertRaises(CredentialError): client = KaggleDatasets() def test_get_gcs_path_tpu_succeeds(self): def call_get_gcs_path(): client = KaggleDatasets() gcs_path = client.get_gcs_path() self.assertEqual(gcs_path, _TPU_GCS_BUCKET) self._test_client(call_get_gcs_path, '/requests/CopyDatasetVersionToKnownGcsBucketRequest', {'MountSlug': None, 'IntegrationType': 2}, is_tpu=True) def test_get_gcs_path_automl_succeeds(self): def call_get_gcs_path(): client = KaggleDatasets() gcs_path = client.get_gcs_path() self.assertEqual(gcs_path, _AUTOML_GCS_BUCKET) self._test_client(call_get_gcs_path, '/requests/CopyDatasetVersionToKnownGcsBucketRequest', {'MountSlug': None, 'IntegrationType': 1}, is_tpu=False) def test_get_gcs_path_handles_unsuccessful(self): def call_get_gcs_path(): client = KaggleDatasets() with self.assertRaises(BackendError): gcs_path = client.get_gcs_path() self._test_client(call_get_gcs_path, '/requests/CopyDatasetVersionToKnownGcsBucketRequest', {'MountSlug': None, 'IntegrationType': 2}, is_tpu=True, success=False) def test_iap_token(self): def call_get_gcs_path(): client = KaggleDatasets() gcs_path = client.get_gcs_path() self._test_client(call_get_gcs_path, '/requests/CopyDatasetVersionToKnownGcsBucketRequest', {'MountSlug': None, 'IntegrationType': 1}, is_tpu=False, iap_token=True)
3,444
591
<gh_stars>100-1000 // Copyright(c) 2015-present, <NAME> & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) #pragma once #ifdef _WIN32 #error tcp_client not supported under windows yet #endif // tcp client helper #include <spdlog/common.h> #include <spdlog/details/os.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <netdb.h> #include <netinet/tcp.h> #include <string> namespace spdlog { namespace details { class tcp_client { int socket_ = -1; public: bool is_connected() const { return socket_ != -1; } void close() { if (is_connected()) { ::close(socket_); socket_ = -1; } } int fd() const { return socket_; } ~tcp_client() { close(); } // try to connect or throw on failure void connect(const std::string &host, int port) { close(); struct addrinfo hints {}; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_INET; // IPv4 hints.ai_socktype = SOCK_STREAM; // TCP hints.ai_flags = AI_NUMERICSERV; // port passed as as numeric value hints.ai_protocol = 0; auto port_str = std::to_string(port); struct addrinfo *addrinfo_result; auto rv = ::getaddrinfo(host.c_str(), port_str.c_str(), &hints, &addrinfo_result); if (rv != 0) { auto msg = fmt::format("::getaddrinfo failed: {}", gai_strerror(rv)); SPDLOG_THROW(spdlog::spdlog_ex(msg)); } // Try each address until we successfully connect(2). int last_errno = 0; for (auto *rp = addrinfo_result; rp != nullptr; rp = rp->ai_next) { #ifdef SPDLOG_PREVENT_CHILD_FD int const flags = SOCK_CLOEXEC; #else int const flags = 0; #endif socket_ = ::socket(rp->ai_family, rp->ai_socktype | flags, rp->ai_protocol); if (socket_ == -1) { last_errno = errno; continue; } rv = ::connect(socket_, rp->ai_addr, rp->ai_addrlen); if (rv == 0) { break; } else { last_errno = errno; ::close(socket_); socket_ = -1; } } ::freeaddrinfo(addrinfo_result); if (socket_ == -1) { SPDLOG_THROW(spdlog::spdlog_ex("::connect failed", last_errno)); } // set TCP_NODELAY int enable_flag = 1; ::setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, (char *)&enable_flag, sizeof(enable_flag)); // prevent sigpipe on systems where MSG_NOSIGNAL is not available #if defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL) ::setsockopt(socket_, SOL_SOCKET, SO_NOSIGPIPE, (char *)&enable_flag, sizeof(enable_flag)); #endif #if !defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL) #error "tcp_sink would raise SIGPIPE since niether SO_NOSIGPIPE nor MSG_NOSIGNAL are available" #endif } // Send exactly n_bytes of the given data. // On error close the connection and throw. void send(const char *data, size_t n_bytes) { size_t bytes_sent = 0; while (bytes_sent < n_bytes) { #if defined(MSG_NOSIGNAL) const int send_flags = MSG_NOSIGNAL; #else const int send_flags = 0; #endif auto write_result = ::send(socket_, data + bytes_sent, n_bytes - bytes_sent, send_flags); if (write_result < 0) { close(); SPDLOG_THROW(spdlog::spdlog_ex("write(2) failed", errno)); } if (write_result == 0) // (probably should not happen but in any case..) { break; } bytes_sent += static_cast<size_t>(write_result); } } }; } // namespace details } // namespace spdlog
2,018
544
// // CountryViewItem.h // TogglDesktop // // Created by <NAME> on 16/05/2018. // Copyright © 2018 Alari. All rights reserved. // #import <Foundation/Foundation.h> @interface CountryViewItem : NSObject @property (assign, nonatomic) uint64_t ID; @property (assign, nonatomic) BOOL VatApplicable; @property (copy, nonatomic) NSString *Text; @property (copy, nonatomic) NSString *Name; @property (copy, nonatomic) NSString *VatPercentage; @property (copy, nonatomic) NSString *VatRegex; @property (copy, nonatomic) NSString *Code; + (NSMutableArray *)loadAll:(TogglCountryView *)first; - (void)load:(TogglCountryView *)data; @end
220
1,909
<gh_stars>1000+ /* * Copyright 2006-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.batch.item.file; import java.io.File; import java.io.IOException; import java.util.List; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStreamException; import org.springframework.batch.item.support.AbstractItemStreamItemWriter; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** * Wraps a {@link ResourceAwareItemWriterItemStream} and creates a new output * resource when the count of items written in current resource exceeds * {@link #setItemCountLimitPerResource(int)}. Suffix creation can be customized * with {@link #setResourceSuffixCreator(ResourceSuffixCreator)}. * * Note that new resources are created only at chunk boundaries i.e. the number * of items written into one resource is between the limit set by * {@link #setItemCountLimitPerResource(int)} and (limit + chunk size). * * @param <T> item type * * @author <NAME> */ public class MultiResourceItemWriter<T> extends AbstractItemStreamItemWriter<T> { final static private String RESOURCE_INDEX_KEY = "resource.index"; final static private String CURRENT_RESOURCE_ITEM_COUNT = "resource.item.count"; private Resource resource; private ResourceAwareItemWriterItemStream<? super T> delegate; private int itemCountLimitPerResource = Integer.MAX_VALUE; private int currentResourceItemCount = 0; private int resourceIndex = 1; private ResourceSuffixCreator suffixCreator = new SimpleResourceSuffixCreator(); private boolean saveState = true; private boolean opened = false; public MultiResourceItemWriter() { this.setExecutionContextName(ClassUtils.getShortName(MultiResourceItemWriter.class)); } @Override public void write(List<? extends T> items) throws Exception { if (!opened) { File file = setResourceToDelegate(); // create only if write is called file.createNewFile(); Assert.state(file.canWrite(), "Output resource " + file.getAbsolutePath() + " must be writable"); delegate.open(new ExecutionContext()); opened = true; } delegate.write(items); currentResourceItemCount += items.size(); if (currentResourceItemCount >= itemCountLimitPerResource) { delegate.close(); resourceIndex++; currentResourceItemCount = 0; setResourceToDelegate(); opened = false; } } /** * Allows customization of the suffix of the created resources based on the * index. * * @param suffixCreator {@link ResourceSuffixCreator} to be used by the writer. */ public void setResourceSuffixCreator(ResourceSuffixCreator suffixCreator) { this.suffixCreator = suffixCreator; } /** * After this limit is exceeded the next chunk will be written into newly * created resource. * * @param itemCountLimitPerResource int item threshold used to determine when a new * resource should be created. */ public void setItemCountLimitPerResource(int itemCountLimitPerResource) { this.itemCountLimitPerResource = itemCountLimitPerResource; } /** * Delegate used for actual writing of the output. * * @param delegate {@link ResourceAwareItemWriterItemStream} that will be used * to write the output. */ public void setDelegate(ResourceAwareItemWriterItemStream<? super T> delegate) { this.delegate = delegate; } /** * Prototype for output resources. Actual output files will be created in * the same directory and use the same name as this prototype with appended * suffix (according to * {@link #setResourceSuffixCreator(ResourceSuffixCreator)}. * * @param resource The prototype resource. */ public void setResource(Resource resource) { this.resource = resource; } /** * Indicates that the state of the reader will be saved after each commit. * * @param saveState true the state is saved. */ public void setSaveState(boolean saveState) { this.saveState = saveState; } @Override public void close() throws ItemStreamException { super.close(); resourceIndex = 1; currentResourceItemCount = 0; if (opened) { delegate.close(); } } @Override public void open(ExecutionContext executionContext) throws ItemStreamException { super.open(executionContext); resourceIndex = executionContext.getInt(getExecutionContextKey(RESOURCE_INDEX_KEY), 1); currentResourceItemCount = executionContext.getInt(getExecutionContextKey(CURRENT_RESOURCE_ITEM_COUNT), 0); try { setResourceToDelegate(); } catch (IOException e) { throw new ItemStreamException("Couldn't assign resource", e); } if (executionContext.containsKey(getExecutionContextKey(CURRENT_RESOURCE_ITEM_COUNT))) { // It's a restart delegate.open(executionContext); opened = true; } else { opened = false; } } @Override public void update(ExecutionContext executionContext) throws ItemStreamException { super.update(executionContext); if (saveState) { if (opened) { delegate.update(executionContext); } executionContext.putInt(getExecutionContextKey(CURRENT_RESOURCE_ITEM_COUNT), currentResourceItemCount); executionContext.putInt(getExecutionContextKey(RESOURCE_INDEX_KEY), resourceIndex); } } /** * Create output resource (if necessary) and point the delegate to it. */ private File setResourceToDelegate() throws IOException { String path = resource.getFile().getAbsolutePath() + suffixCreator.getSuffix(resourceIndex); File file = new File(path); delegate.setResource(new FileSystemResource(file)); return file; } }
1,877
1,444
<filename>restclient-ui/src/main/java/org/wiztools/restclient/ui/AuthHelper.java package org.wiztools.restclient.ui; import java.util.List; import org.wiztools.restclient.bean.HTTPAuthMethod; /** * * @author subwiz */ public class AuthHelper { public static final String NONE = "None"; public static final String BASIC = "BASIC"; public static final String DIGEST = "DIGEST"; public static final String NTLM = "NTLM"; public static final String OAUTH2_BEARER = "OAuth2 Bearer"; private static final String[] ALL = new String[]{NONE, BASIC, DIGEST, NTLM, OAUTH2_BEARER}; public static String[] getAll() { return ALL; } public static boolean isBasicOrDigest(List<HTTPAuthMethod> authMethods) { return authMethods.contains(HTTPAuthMethod.BASIC) || authMethods.contains(HTTPAuthMethod.DIGEST); } public static boolean isNtlm(List<HTTPAuthMethod> authMethods) { return authMethods.contains(HTTPAuthMethod.NTLM); } public static boolean isBearer(List<HTTPAuthMethod> authMethods) { return authMethods.contains(HTTPAuthMethod.OAUTH_20_BEARER); } // String methods: public static boolean isNone(String input) { return NONE.equals(input); } public static boolean isBasicOrDigest(String input) { return isBasic(input) || isDigest(input); } public static boolean isBasic(String input) { return BASIC.equals(input); } public static boolean isDigest(String input) { return DIGEST.equals(input); } public static boolean isNtlm(String input) { return NTLM.equals(input); } public static boolean isBearer(String input) { return OAUTH2_BEARER.equals(input); } }
743
416
// // INPayBillIntent.h // Intents // // Copyright (c) 2016-2017 Apple Inc. All rights reserved. // #import <Intents/INIntent.h> #import <Intents/INIntentResolutionResult.h> #import <Intents/INBillType.h> @class INBillPayee; @class INBillPayeeResolutionResult; @class INBillTypeResolutionResult; @class INDateComponentsRange; @class INDateComponentsRangeResolutionResult; @class INPaymentAccount; @class INPaymentAccountResolutionResult; @class INPaymentAmount; @class INPaymentAmountResolutionResult; @class INStringResolutionResult; NS_ASSUME_NONNULL_BEGIN API_AVAILABLE(ios(10.3), watchos(3.2)) API_UNAVAILABLE(macosx) @interface INPayBillIntent : INIntent - (instancetype)initWithBillPayee:(nullable INBillPayee *)billPayee fromAccount:(nullable INPaymentAccount *)fromAccount transactionAmount:(nullable INPaymentAmount *)transactionAmount transactionScheduledDate:(nullable INDateComponentsRange *)transactionScheduledDate transactionNote:(nullable NSString *)transactionNote billType:(INBillType)billType dueDate:(nullable INDateComponentsRange *)dueDate NS_DESIGNATED_INITIALIZER; @property (readonly, copy, nullable, NS_NONATOMIC_IOSONLY) INBillPayee *billPayee; @property (readonly, copy, nullable, NS_NONATOMIC_IOSONLY) INPaymentAccount *fromAccount; @property (readonly, copy, nullable, NS_NONATOMIC_IOSONLY) INPaymentAmount *transactionAmount; @property (readonly, copy, nullable, NS_NONATOMIC_IOSONLY) INDateComponentsRange *transactionScheduledDate; @property (readonly, copy, nullable, NS_NONATOMIC_IOSONLY) NSString *transactionNote; @property (readonly, assign, NS_NONATOMIC_IOSONLY) INBillType billType; @property (readonly, copy, nullable, NS_NONATOMIC_IOSONLY) INDateComponentsRange *dueDate; @end @class INPayBillIntentResponse; /*! @abstract Protocol to declare support for handling an INPayBillIntent. By implementing this protocol, a class can provide logic for resolving, confirming and handling the intent. @discussion The minimum requirement for an implementing class is that it should be able to handle the intent. The resolution and confirmation methods are optional. The handling method is always called last, after resolving and confirming the intent. */ API_AVAILABLE(ios(10.3), watchos(3.2)) API_UNAVAILABLE(macosx) @protocol INPayBillIntentHandling <NSObject> @required /*! @abstract Handling method - Execute the task represented by the INPayBillIntent that's passed in @discussion Called to actually execute the intent. The app must return a response for this intent. @param intent The input intent @param completion The response handling block takes a INPayBillIntentResponse containing the details of the result of having executed the intent @see INPayBillIntentResponse */ - (void)handlePayBill:(INPayBillIntent *)intent completion:(void (^)(INPayBillIntentResponse *response))completion NS_SWIFT_NAME(handle(intent:completion:)); @optional /*! @abstract Confirmation method - Validate that this intent is ready for the next step (i.e. handling) @discussion Called prior to asking the app to handle the intent. The app should return a response object that contains additional information about the intent, which may be relevant for the system to show the user prior to handling. If unimplemented, the system will assume the intent is valid following resolution, and will assume there is no additional information relevant to this intent. @param intent The input intent @param completion The response block contains an INPayBillIntentResponse containing additional details about the intent that may be relevant for the system to show the user prior to handling. @see INPayBillIntentResponse */ - (void)confirmPayBill:(INPayBillIntent *)intent completion:(void (^)(INPayBillIntentResponse *response))completion NS_SWIFT_NAME(confirm(intent:completion:)); /*! @abstract Resolution methods - Determine if this intent is ready for the next step (confirmation) @discussion Called to make sure the app extension is capable of handling this intent in its current form. This method is for validating if the intent needs any further fleshing out. @param intent The input intent @param completion The response block contains an INIntentResolutionResult for the parameter being resolved @see INIntentResolutionResult */ - (void)resolveBillPayeeForPayBill:(INPayBillIntent *)intent withCompletion:(void (^)(INBillPayeeResolutionResult *resolutionResult))completion NS_SWIFT_NAME(resolveBillPayee(for:with:)); - (void)resolveFromAccountForPayBill:(INPayBillIntent *)intent withCompletion:(void (^)(INPaymentAccountResolutionResult *resolutionResult))completion NS_SWIFT_NAME(resolveFromAccount(for:with:)); - (void)resolveTransactionAmountForPayBill:(INPayBillIntent *)intent withCompletion:(void (^)(INPaymentAmountResolutionResult *resolutionResult))completion NS_SWIFT_NAME(resolveTransactionAmount(for:with:)); - (void)resolveTransactionScheduledDateForPayBill:(INPayBillIntent *)intent withCompletion:(void (^)(INDateComponentsRangeResolutionResult *resolutionResult))completion NS_SWIFT_NAME(resolveTransactionScheduledDate(for:with:)); - (void)resolveTransactionNoteForPayBill:(INPayBillIntent *)intent withCompletion:(void (^)(INStringResolutionResult *resolutionResult))completion NS_SWIFT_NAME(resolveTransactionNote(for:with:)); - (void)resolveBillTypeForPayBill:(INPayBillIntent *)intent withCompletion:(void (^)(INBillTypeResolutionResult *resolutionResult))completion NS_SWIFT_NAME(resolveBillType(for:with:)); - (void)resolveDueDateForPayBill:(INPayBillIntent *)intent withCompletion:(void (^)(INDateComponentsRangeResolutionResult *resolutionResult))completion NS_SWIFT_NAME(resolveDueDate(for:with:)); @end NS_ASSUME_NONNULL_END
1,931
543
<reponame>CoenRijsdijk/Bytecoder<filename>classlib/java.desktop/src/main/resources/META-INF/modules/java.desktop/classes/javax/print/StreamPrintService.java /* * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.print; import java.io.OutputStream; /** * This class extends {@link PrintService} and represents a print service that * prints data in different formats to a client-provided output stream. This is * principally intended for services where the output format is a document type * suitable for viewing or archiving. The output format must be declared as a * mime type. This is equivalent to an output document flavor where the * representation class is always "java.io.OutputStream" An instance of the * {@code StreamPrintService} class is obtained from a * {@link StreamPrintServiceFactory} instance. * <p> * Note that a {@code StreamPrintService} is different from a * {@code PrintService}, which supports a * {@link javax.print.attribute.standard.Destination Destination} attribute. A * {@code StreamPrintService} always requires an output stream, whereas a * {@code PrintService} optionally accepts a {@code Destination}. A * {@code StreamPrintService} has no default destination for its formatted * output. Additionally a {@code StreamPrintService} is expected to generate * output in a format useful in other contexts. {@code StreamPrintService}'s are * not expected to support the {@code Destination} attribute. */ public abstract class StreamPrintService implements PrintService { /** * The output stream to which this service will send formatted print data. */ private OutputStream outStream; /** * Whether or not this {@code StreamPrintService} has been disposed. */ private boolean disposed = false; /** * Constructs a {@code StreamPrintService} object. */ private StreamPrintService() { }; /** * Constructs a {@code StreamPrintService} object. * * @param out stream to which to send formatted print data */ protected StreamPrintService(OutputStream out) { this.outStream = out; } /** * Gets the output stream. * * @return the stream to which this service will send formatted print data */ public OutputStream getOutputStream() { return outStream; } /** * Returns the document format emitted by this print service. Must be in * mimetype format, compatible with the mime type components of * {@code DocFlavors} * * @return mime type identifying the output format * @see DocFlavor */ public abstract String getOutputFormat(); /** * Disposes this {@code StreamPrintService}. If a stream service cannot be * re-used, it must be disposed to indicate this. Typically the client will * call this method. Services which write data which cannot meaningfully be * appended to may also dispose the stream. This does not close the stream. * It just marks it as not for further use by this service. */ public void dispose() { disposed = true; } /** * Returns a {@code boolean} indicating whether or not this * {@code StreamPrintService} has been disposed. If this object has been * disposed, will return {@code true}. Used by services and client * applications to recognize streams to which no further data should be * written. * * @return {@code true} if this {@code StreamPrintService} has been * disposed; {@code false} otherwise */ public boolean isDisposed() { return disposed; } }
1,392
4,126
// ImageComposingCallback // Declares the cImageComposingCallback class that implements a subset of cCallback for composing per-region images #pragma once #include "Callback.h" /** Implements the plumbing for composing per-region images from multiple chunks. To use this class, create a descendant that writes the image data using SetPixel() or SetPixelURow() functions. For the purpose of this class the image data is indexed U (horz) * V (vert), to avoid confusion with other coords. The image is a 32bpp raw imagedata, written into a BMP file. */ class cImageComposingCallback : public cCallback { public: enum { INVALID_REGION_COORD = 99999, ///< Used for un-assigned region coords IMAGE_WIDTH = 32 * 16, IMAGE_HEIGHT = 32 * 16, PIXEL_COUNT = IMAGE_WIDTH * IMAGE_HEIGHT, ///< Total pixel count of the image data } ; cImageComposingCallback(const AString & a_FileNamePrefix); virtual ~cImageComposingCallback(); // cCallback overrides: virtual bool OnNewRegion(int a_RegionX, int a_RegionZ) override; virtual void OnRegionFinished(int a_RegionX, int a_RegionZ) override; // New introduced overridable functions: /** Called when a file is about to be saved, to generate the filename */ virtual AString GetFileName(int a_RegionX, int a_RegionZ); /** Called before the file is saved */ virtual void OnBeforeImageSaved(int a_RegionX, int a_RegionZ, const AString & a_FileName) {} /** Called after the image is saved to a file */ virtual void OnAfterImageSaved(int a_RegionX, int a_RegionZ, const AString & a_FileName) {} /** Called when a new region is beginning, to erase the image data */ virtual void OnEraseImage(void); // Functions for manipulating the image: /** Erases the entire image with the specified color */ void EraseImage(int a_Color); /** Erases the specified chunk's portion of the image with the specified color. Note that chunk coords are relative to the current region */ void EraseChunk(int a_Color, int a_RelChunkX, int a_RelChunkZ); /** Returns the current region X coord */ int GetCurrentRegionX(void) const { return m_CurrentRegionX; } /** Returns the current region Z coord */ int GetCurrentRegionZ(void) const { return m_CurrentRegionZ; } /** Sets the pixel at the specified UV coords to the specified color */ void SetPixel(int a_RelU, int a_RelV, int a_Color); /** Returns the color of the pixel at the specified UV coords; -1 if outside */ int GetPixel(int a_RelU, int a_RelV); /** Sets a row of pixels. a_Pixels is expected to be a_CountU pixels wide. a_RelUStart + a_CountU is assumed less than image width */ void SetPixelURow(int a_RelUStart, int a_RelV, int a_CountU, int * a_Pixels); /** "Shades" the given color based on the shade amount given Shade amount 0 .. 63 shades the color from black to a_Color. Shade amount 64 .. 127 shades the color from a_Color to white. All other shade amounts have undefined results. */ static int ShadeColor(int a_Color, int a_Shade); /** Mixes the two colors in the specified ratio; a_Ratio is between 0 and 256, 0 returning a_Src */ static int MixColor(int a_Src, int a_Dest, int a_Ratio); protected: /** Prefix for the filenames, when generated by the default GetFileName() function */ AString m_FileNamePrefix; /** Coords of the currently processed region */ int m_CurrentRegionX, m_CurrentRegionZ; /** Raw image data; 1 MiB worth of data, therefore unsuitable for stack allocation. [u + IMAGE_WIDTH * v] */ int * m_ImageData; void SaveImage(const AString & a_FileName); } ;
1,079
1,853
#include <cstdio> int main() { unsigned int a = 5; unsigned int b = 4; printf("a %% b: %d %% %d = %d\n", a, b, (a%b)); signed int c = -5; signed int d = 4; printf("c %% d: %d %% %d = %d\n", c, d, (c%d)); signed int e = 5; signed int f = -4; printf("e %% f: %d %% %d = %d\n", e, f, (e%f)); signed char g = -5; unsigned char h = 4; printf("g %% h: %d %% %d = %d\n", g, h, (g%h)); signed int i = -5; unsigned int j = 4; printf("i %% j: %d %% %d = %d\n", i, j, (i%j)); printf("i %% j: %#x %% %#x = %#x\n", i, j, (i%j)); }
274
1,375
<filename>sw/device/lib/dif/autogen/dif_aon_timer_autogen.c // Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // THIS FILE HAS BEEN GENERATED, DO NOT EDIT MANUALLY. COMMAND: // util/make_new_dif.py --mode=regen --only=autogen #include "sw/device/lib/dif/autogen/dif_aon_timer_autogen.h" #include <stdint.h> #include "aon_timer_regs.h" // Generated. #include <assert.h> static_assert(AON_TIMER_INTR_STATE_WKUP_TIMER_EXPIRED_BIT == AON_TIMER_INTR_TEST_WKUP_TIMER_EXPIRED_BIT, "Expected IRQ bit offsets to match across STATE/TEST regs."); static_assert(AON_TIMER_INTR_STATE_WDOG_TIMER_BARK_BIT == AON_TIMER_INTR_TEST_WDOG_TIMER_BARK_BIT, "Expected IRQ bit offsets to match across STATE/TEST regs."); OT_WARN_UNUSED_RESULT dif_result_t dif_aon_timer_init(mmio_region_t base_addr, dif_aon_timer_t *aon_timer) { if (aon_timer == NULL) { return kDifBadArg; } aon_timer->base_addr = base_addr; return kDifOk; } dif_result_t dif_aon_timer_alert_force(const dif_aon_timer_t *aon_timer, dif_aon_timer_alert_t alert) { if (aon_timer == NULL) { return kDifBadArg; } bitfield_bit32_index_t alert_idx; switch (alert) { case kDifAonTimerAlertFatalFault: alert_idx = AON_TIMER_ALERT_TEST_FATAL_FAULT_BIT; break; default: return kDifBadArg; } uint32_t alert_test_reg = bitfield_bit32_write(0, alert_idx, true); mmio_region_write32(aon_timer->base_addr, AON_TIMER_ALERT_TEST_REG_OFFSET, alert_test_reg); return kDifOk; } /** * Get the corresponding interrupt register bit offset of the IRQ. If the IP's * HJSON does NOT have a field "no_auto_intr_regs = true", then the * "<ip>_INTR_COMMON_<irq>_BIT" macro can be used. Otherwise, special cases * will exist, as templated below. */ static bool aon_timer_get_irq_bit_index(dif_aon_timer_irq_t irq, bitfield_bit32_index_t *index_out) { switch (irq) { case kDifAonTimerIrqWkupTimerExpired: *index_out = AON_TIMER_INTR_STATE_WKUP_TIMER_EXPIRED_BIT; break; case kDifAonTimerIrqWdogTimerBark: *index_out = AON_TIMER_INTR_STATE_WDOG_TIMER_BARK_BIT; break; default: return false; } return true; } OT_WARN_UNUSED_RESULT dif_result_t dif_aon_timer_irq_get_state( const dif_aon_timer_t *aon_timer, dif_aon_timer_irq_state_snapshot_t *snapshot) { if (aon_timer == NULL || snapshot == NULL) { return kDifBadArg; } *snapshot = mmio_region_read32(aon_timer->base_addr, AON_TIMER_INTR_STATE_REG_OFFSET); return kDifOk; } OT_WARN_UNUSED_RESULT dif_result_t dif_aon_timer_irq_is_pending(const dif_aon_timer_t *aon_timer, dif_aon_timer_irq_t irq, bool *is_pending) { if (aon_timer == NULL || is_pending == NULL) { return kDifBadArg; } bitfield_bit32_index_t index; if (!aon_timer_get_irq_bit_index(irq, &index)) { return kDifBadArg; } uint32_t intr_state_reg = mmio_region_read32(aon_timer->base_addr, AON_TIMER_INTR_STATE_REG_OFFSET); *is_pending = bitfield_bit32_read(intr_state_reg, index); return kDifOk; } OT_WARN_UNUSED_RESULT dif_result_t dif_aon_timer_irq_acknowledge_all( const dif_aon_timer_t *aon_timer) { if (aon_timer == NULL) { return kDifBadArg; } // Writing to the register clears the corresponding bits (Write-one clear). mmio_region_write32(aon_timer->base_addr, AON_TIMER_INTR_STATE_REG_OFFSET, UINT32_MAX); return kDifOk; } OT_WARN_UNUSED_RESULT dif_result_t dif_aon_timer_irq_acknowledge(const dif_aon_timer_t *aon_timer, dif_aon_timer_irq_t irq) { if (aon_timer == NULL) { return kDifBadArg; } bitfield_bit32_index_t index; if (!aon_timer_get_irq_bit_index(irq, &index)) { return kDifBadArg; } // Writing to the register clears the corresponding bits (Write-one clear). uint32_t intr_state_reg = bitfield_bit32_write(0, index, true); mmio_region_write32(aon_timer->base_addr, AON_TIMER_INTR_STATE_REG_OFFSET, intr_state_reg); return kDifOk; } OT_WARN_UNUSED_RESULT dif_result_t dif_aon_timer_irq_force(const dif_aon_timer_t *aon_timer, dif_aon_timer_irq_t irq) { if (aon_timer == NULL) { return kDifBadArg; } bitfield_bit32_index_t index; if (!aon_timer_get_irq_bit_index(irq, &index)) { return kDifBadArg; } uint32_t intr_test_reg = bitfield_bit32_write(0, index, true); mmio_region_write32(aon_timer->base_addr, AON_TIMER_INTR_TEST_REG_OFFSET, intr_test_reg); return kDifOk; }
2,438
1,732
# # Execute watson on a session # import argparse from lib import shellcode __description__ = "Show missing KBs and suggest exploits for priv esc" __author__ = "@Flangvik, @_RastaMouse" __type__ = "enumeration" # identify the task as shellcode execute USERCD_EXEC_ID = 0x3000 # location of Watson binary WATSON_BIN = "/root/shad0w/bin/SharpCollection/NetFramework_4.5_x86/Watson.exe" class DummyClass(object): # little hack but lets us pass the args to Donut def __init__(self): pass def watson_callback(shad0w, data): print(data) return "" def main(shad0w, args): # check we actually have a beacon if shad0w.current_beacon is None: shad0w.debug.log("ERROR: No active beacon.", log=True) return watson_args = ' '.join(args[1:]) # kind of a hack to make sure we integrate nice with the shellcode generator args = DummyClass() if len(watson_args) != 0: args.param = watson_args else: args.param = False watson_args = False args.cls = False args.method = False args.runtime = False args.appdomain = False # Generate Donut base64 shellcode with "AnyCpu" as target, local bin is x86 b64_comp_data = shellcode.generate(WATSON_BIN, args, watson_args) shad0w.beacons[shad0w.current_beacon]["task"] = (USERCD_EXEC_ID, b64_comp_data) shad0w.beacons[shad0w.current_beacon]["callback"] = watson_callback
565
884
<reponame>rt112000/CDM # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. from typing import TYPE_CHECKING if TYPE_CHECKING: from cdm.objectmodel import CdmAttributeContext, CdmAttributeResolutionGuidanceDefinition from cdm.resolvedmodel import ResolvedAttribute from cdm.utilities import ResolveOptions class ApplierContext: def __init__(self, **kwargs): self.state = kwargs.get('state', None) # type: str self.res_opt = kwargs.get('res_opt', None) # type: ResolveOptions self.att_ctx = kwargs.get('att_ctx', None) # type: CdmAttributeContext self.res_guide = kwargs.get('res_guide', None) # type: CdmAttributeResolutionGuidanceDefinition self.res_att_source = kwargs.get('res_att_source', None) # type: ResolvedAttribute self.res_att_new = kwargs.get('res_att_new', None) # type: ResolvedAttribute self.res_guide_new = kwargs.get('res_guide_new', None) # type: CdmAttributeResolutionGuidanceDefinition self.is_continue = kwargs.get('is_continue', False) # type: bool
422
9,541
<filename>benchmark/top_tweet/rapidjson.h<gh_stars>1000+ #pragma once #ifdef SIMDJSON_COMPETITION_RAPIDJSON #include "top_tweet.h" namespace top_tweet { using namespace rapidjson; struct rapidjson_base { using StringType=std::string_view; Document doc{}; bool run(Document &root, int64_t max_retweet_count, top_tweet_result<StringType> &result) { result.retweet_count = -1; // Loop over the tweets if (root.HasParseError() || !root.IsObject()) { return false; } const auto &statuses = root.FindMember("statuses"); if (statuses == root.MemberEnd() || !statuses->value.IsArray()) { return false; } for (const Value &tweet : statuses->value.GetArray()) { if (!tweet.IsObject()) { return false; } // Check if this tweet has a higher retweet count than the current top tweet const auto &retweet_count_json = tweet.FindMember("retweet_count"); if (retweet_count_json == tweet.MemberEnd() || !retweet_count_json->value.IsInt64()) { return false; } int64_t retweet_count = retweet_count_json->value.GetInt64(); if (retweet_count <= max_retweet_count && retweet_count >= result.retweet_count) { result.retweet_count = retweet_count; // TODO I can't figure out if there's a way to keep the Value to use outside the loop ... // Get text and screen_name of top tweet const auto &text = tweet.FindMember("text"); if (text == tweet.MemberEnd() || !text->value.IsString()) { return false; } result.text = { text->value.GetString(), text->value.GetStringLength() }; const auto &user = tweet.FindMember("user"); if (user == tweet.MemberEnd() || !user->value.IsObject()) { return false; } const auto &screen_name = user->value.FindMember("screen_name"); if (screen_name == user->value.MemberEnd() || !screen_name->value.IsString()) { return false; } result.screen_name = { screen_name->value.GetString(), screen_name->value.GetStringLength() }; } } return result.retweet_count != -1; } }; struct rapidjson : rapidjson_base { bool run(simdjson::padded_string &json, int64_t max_retweet_count, top_tweet_result<StringType> &result) { return rapidjson_base::run(doc.Parse<kParseValidateEncodingFlag>(json.data()), max_retweet_count, result); } }; BENCHMARK_TEMPLATE(top_tweet, rapidjson)->UseManualTime(); struct rapidjson_insitu : rapidjson_base { bool run(simdjson::padded_string &json, int64_t max_retweet_count, top_tweet_result<StringType> &result) { return rapidjson_base::run(doc.ParseInsitu<kParseValidateEncodingFlag>(json.data()), max_retweet_count, result); } }; BENCHMARK_TEMPLATE(top_tweet, rapidjson_insitu)->UseManualTime(); } // namespace top_tweet #endif // SIMDJSON_COMPETITION_RAPIDJSON
1,024
3,372
<gh_stars>1000+ /* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.mediaconnect.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * A pricing agreement for a discounted rate for a specific outbound bandwidth that your MediaConnect account will use * each month over a specific time period. The discounted rate in the reservation applies to outbound bandwidth for all * flows from your account until your account reaches the amount of bandwidth in your reservation. If you use more * outbound bandwidth than the agreed upon amount in a single month, the overage is charged at the on-demand rate. * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/mediaconnect-2018-11-14/Reservation" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class Reservation implements Serializable, Cloneable, StructuredPojo { /** The type of currency that is used for billing. The currencyCode used for your reservation is US dollars. */ private String currencyCode; /** The length of time that this reservation is active. MediaConnect defines this value in the offering. */ private Integer duration; /** The unit of measurement for the duration of the reservation. MediaConnect defines this value in the offering. */ private String durationUnits; /** * The day and time that this reservation expires. This value is calculated based on the start date and time that * you set and the offering's duration. */ private String end; /** The Amazon Resource Name (ARN) that MediaConnect assigns to the offering. */ private String offeringArn; /** A description of the offering. MediaConnect defines this value in the offering. */ private String offeringDescription; /** * The cost of a single unit. This value, in combination with priceUnits, makes up the rate. MediaConnect defines * this value in the offering. */ private String pricePerUnit; /** * The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up the * rate. MediaConnect defines this value in the offering. */ private String priceUnits; /** The Amazon Resource Name (ARN) that MediaConnect assigns to the reservation when you purchase an offering. */ private String reservationArn; /** The name that you assigned to the reservation when you purchased the offering. */ private String reservationName; /** The status of your reservation. */ private String reservationState; /** * A definition of the amount of outbound bandwidth that you would be reserving if you purchase the offering. * MediaConnect defines the values that make up the resourceSpecification in the offering. */ private ResourceSpecification resourceSpecification; /** The day and time that the reservation becomes active. You set this value when you purchase the offering. */ private String start; /** * The type of currency that is used for billing. The currencyCode used for your reservation is US dollars. * * @param currencyCode * The type of currency that is used for billing. The currencyCode used for your reservation is US dollars. */ public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } /** * The type of currency that is used for billing. The currencyCode used for your reservation is US dollars. * * @return The type of currency that is used for billing. The currencyCode used for your reservation is US dollars. */ public String getCurrencyCode() { return this.currencyCode; } /** * The type of currency that is used for billing. The currencyCode used for your reservation is US dollars. * * @param currencyCode * The type of currency that is used for billing. The currencyCode used for your reservation is US dollars. * @return Returns a reference to this object so that method calls can be chained together. */ public Reservation withCurrencyCode(String currencyCode) { setCurrencyCode(currencyCode); return this; } /** * The length of time that this reservation is active. MediaConnect defines this value in the offering. * * @param duration * The length of time that this reservation is active. MediaConnect defines this value in the offering. */ public void setDuration(Integer duration) { this.duration = duration; } /** * The length of time that this reservation is active. MediaConnect defines this value in the offering. * * @return The length of time that this reservation is active. MediaConnect defines this value in the offering. */ public Integer getDuration() { return this.duration; } /** * The length of time that this reservation is active. MediaConnect defines this value in the offering. * * @param duration * The length of time that this reservation is active. MediaConnect defines this value in the offering. * @return Returns a reference to this object so that method calls can be chained together. */ public Reservation withDuration(Integer duration) { setDuration(duration); return this; } /** * The unit of measurement for the duration of the reservation. MediaConnect defines this value in the offering. * * @param durationUnits * The unit of measurement for the duration of the reservation. MediaConnect defines this value in the * offering. * @see DurationUnits */ public void setDurationUnits(String durationUnits) { this.durationUnits = durationUnits; } /** * The unit of measurement for the duration of the reservation. MediaConnect defines this value in the offering. * * @return The unit of measurement for the duration of the reservation. MediaConnect defines this value in the * offering. * @see DurationUnits */ public String getDurationUnits() { return this.durationUnits; } /** * The unit of measurement for the duration of the reservation. MediaConnect defines this value in the offering. * * @param durationUnits * The unit of measurement for the duration of the reservation. MediaConnect defines this value in the * offering. * @return Returns a reference to this object so that method calls can be chained together. * @see DurationUnits */ public Reservation withDurationUnits(String durationUnits) { setDurationUnits(durationUnits); return this; } /** * The unit of measurement for the duration of the reservation. MediaConnect defines this value in the offering. * * @param durationUnits * The unit of measurement for the duration of the reservation. MediaConnect defines this value in the * offering. * @return Returns a reference to this object so that method calls can be chained together. * @see DurationUnits */ public Reservation withDurationUnits(DurationUnits durationUnits) { this.durationUnits = durationUnits.toString(); return this; } /** * The day and time that this reservation expires. This value is calculated based on the start date and time that * you set and the offering's duration. * * @param end * The day and time that this reservation expires. This value is calculated based on the start date and time * that you set and the offering's duration. */ public void setEnd(String end) { this.end = end; } /** * The day and time that this reservation expires. This value is calculated based on the start date and time that * you set and the offering's duration. * * @return The day and time that this reservation expires. This value is calculated based on the start date and time * that you set and the offering's duration. */ public String getEnd() { return this.end; } /** * The day and time that this reservation expires. This value is calculated based on the start date and time that * you set and the offering's duration. * * @param end * The day and time that this reservation expires. This value is calculated based on the start date and time * that you set and the offering's duration. * @return Returns a reference to this object so that method calls can be chained together. */ public Reservation withEnd(String end) { setEnd(end); return this; } /** * The Amazon Resource Name (ARN) that MediaConnect assigns to the offering. * * @param offeringArn * The Amazon Resource Name (ARN) that MediaConnect assigns to the offering. */ public void setOfferingArn(String offeringArn) { this.offeringArn = offeringArn; } /** * The Amazon Resource Name (ARN) that MediaConnect assigns to the offering. * * @return The Amazon Resource Name (ARN) that MediaConnect assigns to the offering. */ public String getOfferingArn() { return this.offeringArn; } /** * The Amazon Resource Name (ARN) that MediaConnect assigns to the offering. * * @param offeringArn * The Amazon Resource Name (ARN) that MediaConnect assigns to the offering. * @return Returns a reference to this object so that method calls can be chained together. */ public Reservation withOfferingArn(String offeringArn) { setOfferingArn(offeringArn); return this; } /** * A description of the offering. MediaConnect defines this value in the offering. * * @param offeringDescription * A description of the offering. MediaConnect defines this value in the offering. */ public void setOfferingDescription(String offeringDescription) { this.offeringDescription = offeringDescription; } /** * A description of the offering. MediaConnect defines this value in the offering. * * @return A description of the offering. MediaConnect defines this value in the offering. */ public String getOfferingDescription() { return this.offeringDescription; } /** * A description of the offering. MediaConnect defines this value in the offering. * * @param offeringDescription * A description of the offering. MediaConnect defines this value in the offering. * @return Returns a reference to this object so that method calls can be chained together. */ public Reservation withOfferingDescription(String offeringDescription) { setOfferingDescription(offeringDescription); return this; } /** * The cost of a single unit. This value, in combination with priceUnits, makes up the rate. MediaConnect defines * this value in the offering. * * @param pricePerUnit * The cost of a single unit. This value, in combination with priceUnits, makes up the rate. MediaConnect * defines this value in the offering. */ public void setPricePerUnit(String pricePerUnit) { this.pricePerUnit = pricePerUnit; } /** * The cost of a single unit. This value, in combination with priceUnits, makes up the rate. MediaConnect defines * this value in the offering. * * @return The cost of a single unit. This value, in combination with priceUnits, makes up the rate. MediaConnect * defines this value in the offering. */ public String getPricePerUnit() { return this.pricePerUnit; } /** * The cost of a single unit. This value, in combination with priceUnits, makes up the rate. MediaConnect defines * this value in the offering. * * @param pricePerUnit * The cost of a single unit. This value, in combination with priceUnits, makes up the rate. MediaConnect * defines this value in the offering. * @return Returns a reference to this object so that method calls can be chained together. */ public Reservation withPricePerUnit(String pricePerUnit) { setPricePerUnit(pricePerUnit); return this; } /** * The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up the * rate. MediaConnect defines this value in the offering. * * @param priceUnits * The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up * the rate. MediaConnect defines this value in the offering. * @see PriceUnits */ public void setPriceUnits(String priceUnits) { this.priceUnits = priceUnits; } /** * The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up the * rate. MediaConnect defines this value in the offering. * * @return The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up * the rate. MediaConnect defines this value in the offering. * @see PriceUnits */ public String getPriceUnits() { return this.priceUnits; } /** * The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up the * rate. MediaConnect defines this value in the offering. * * @param priceUnits * The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up * the rate. MediaConnect defines this value in the offering. * @return Returns a reference to this object so that method calls can be chained together. * @see PriceUnits */ public Reservation withPriceUnits(String priceUnits) { setPriceUnits(priceUnits); return this; } /** * The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up the * rate. MediaConnect defines this value in the offering. * * @param priceUnits * The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up * the rate. MediaConnect defines this value in the offering. * @return Returns a reference to this object so that method calls can be chained together. * @see PriceUnits */ public Reservation withPriceUnits(PriceUnits priceUnits) { this.priceUnits = priceUnits.toString(); return this; } /** * The Amazon Resource Name (ARN) that MediaConnect assigns to the reservation when you purchase an offering. * * @param reservationArn * The Amazon Resource Name (ARN) that MediaConnect assigns to the reservation when you purchase an offering. */ public void setReservationArn(String reservationArn) { this.reservationArn = reservationArn; } /** * The Amazon Resource Name (ARN) that MediaConnect assigns to the reservation when you purchase an offering. * * @return The Amazon Resource Name (ARN) that MediaConnect assigns to the reservation when you purchase an * offering. */ public String getReservationArn() { return this.reservationArn; } /** * The Amazon Resource Name (ARN) that MediaConnect assigns to the reservation when you purchase an offering. * * @param reservationArn * The Amazon Resource Name (ARN) that MediaConnect assigns to the reservation when you purchase an offering. * @return Returns a reference to this object so that method calls can be chained together. */ public Reservation withReservationArn(String reservationArn) { setReservationArn(reservationArn); return this; } /** * The name that you assigned to the reservation when you purchased the offering. * * @param reservationName * The name that you assigned to the reservation when you purchased the offering. */ public void setReservationName(String reservationName) { this.reservationName = reservationName; } /** * The name that you assigned to the reservation when you purchased the offering. * * @return The name that you assigned to the reservation when you purchased the offering. */ public String getReservationName() { return this.reservationName; } /** * The name that you assigned to the reservation when you purchased the offering. * * @param reservationName * The name that you assigned to the reservation when you purchased the offering. * @return Returns a reference to this object so that method calls can be chained together. */ public Reservation withReservationName(String reservationName) { setReservationName(reservationName); return this; } /** * The status of your reservation. * * @param reservationState * The status of your reservation. * @see ReservationState */ public void setReservationState(String reservationState) { this.reservationState = reservationState; } /** * The status of your reservation. * * @return The status of your reservation. * @see ReservationState */ public String getReservationState() { return this.reservationState; } /** * The status of your reservation. * * @param reservationState * The status of your reservation. * @return Returns a reference to this object so that method calls can be chained together. * @see ReservationState */ public Reservation withReservationState(String reservationState) { setReservationState(reservationState); return this; } /** * The status of your reservation. * * @param reservationState * The status of your reservation. * @return Returns a reference to this object so that method calls can be chained together. * @see ReservationState */ public Reservation withReservationState(ReservationState reservationState) { this.reservationState = reservationState.toString(); return this; } /** * A definition of the amount of outbound bandwidth that you would be reserving if you purchase the offering. * MediaConnect defines the values that make up the resourceSpecification in the offering. * * @param resourceSpecification * A definition of the amount of outbound bandwidth that you would be reserving if you purchase the offering. * MediaConnect defines the values that make up the resourceSpecification in the offering. */ public void setResourceSpecification(ResourceSpecification resourceSpecification) { this.resourceSpecification = resourceSpecification; } /** * A definition of the amount of outbound bandwidth that you would be reserving if you purchase the offering. * MediaConnect defines the values that make up the resourceSpecification in the offering. * * @return A definition of the amount of outbound bandwidth that you would be reserving if you purchase the * offering. MediaConnect defines the values that make up the resourceSpecification in the offering. */ public ResourceSpecification getResourceSpecification() { return this.resourceSpecification; } /** * A definition of the amount of outbound bandwidth that you would be reserving if you purchase the offering. * MediaConnect defines the values that make up the resourceSpecification in the offering. * * @param resourceSpecification * A definition of the amount of outbound bandwidth that you would be reserving if you purchase the offering. * MediaConnect defines the values that make up the resourceSpecification in the offering. * @return Returns a reference to this object so that method calls can be chained together. */ public Reservation withResourceSpecification(ResourceSpecification resourceSpecification) { setResourceSpecification(resourceSpecification); return this; } /** * The day and time that the reservation becomes active. You set this value when you purchase the offering. * * @param start * The day and time that the reservation becomes active. You set this value when you purchase the offering. */ public void setStart(String start) { this.start = start; } /** * The day and time that the reservation becomes active. You set this value when you purchase the offering. * * @return The day and time that the reservation becomes active. You set this value when you purchase the offering. */ public String getStart() { return this.start; } /** * The day and time that the reservation becomes active. You set this value when you purchase the offering. * * @param start * The day and time that the reservation becomes active. You set this value when you purchase the offering. * @return Returns a reference to this object so that method calls can be chained together. */ public Reservation withStart(String start) { setStart(start); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getCurrencyCode() != null) sb.append("CurrencyCode: ").append(getCurrencyCode()).append(","); if (getDuration() != null) sb.append("Duration: ").append(getDuration()).append(","); if (getDurationUnits() != null) sb.append("DurationUnits: ").append(getDurationUnits()).append(","); if (getEnd() != null) sb.append("End: ").append(getEnd()).append(","); if (getOfferingArn() != null) sb.append("OfferingArn: ").append(getOfferingArn()).append(","); if (getOfferingDescription() != null) sb.append("OfferingDescription: ").append(getOfferingDescription()).append(","); if (getPricePerUnit() != null) sb.append("PricePerUnit: ").append(getPricePerUnit()).append(","); if (getPriceUnits() != null) sb.append("PriceUnits: ").append(getPriceUnits()).append(","); if (getReservationArn() != null) sb.append("ReservationArn: ").append(getReservationArn()).append(","); if (getReservationName() != null) sb.append("ReservationName: ").append(getReservationName()).append(","); if (getReservationState() != null) sb.append("ReservationState: ").append(getReservationState()).append(","); if (getResourceSpecification() != null) sb.append("ResourceSpecification: ").append(getResourceSpecification()).append(","); if (getStart() != null) sb.append("Start: ").append(getStart()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Reservation == false) return false; Reservation other = (Reservation) obj; if (other.getCurrencyCode() == null ^ this.getCurrencyCode() == null) return false; if (other.getCurrencyCode() != null && other.getCurrencyCode().equals(this.getCurrencyCode()) == false) return false; if (other.getDuration() == null ^ this.getDuration() == null) return false; if (other.getDuration() != null && other.getDuration().equals(this.getDuration()) == false) return false; if (other.getDurationUnits() == null ^ this.getDurationUnits() == null) return false; if (other.getDurationUnits() != null && other.getDurationUnits().equals(this.getDurationUnits()) == false) return false; if (other.getEnd() == null ^ this.getEnd() == null) return false; if (other.getEnd() != null && other.getEnd().equals(this.getEnd()) == false) return false; if (other.getOfferingArn() == null ^ this.getOfferingArn() == null) return false; if (other.getOfferingArn() != null && other.getOfferingArn().equals(this.getOfferingArn()) == false) return false; if (other.getOfferingDescription() == null ^ this.getOfferingDescription() == null) return false; if (other.getOfferingDescription() != null && other.getOfferingDescription().equals(this.getOfferingDescription()) == false) return false; if (other.getPricePerUnit() == null ^ this.getPricePerUnit() == null) return false; if (other.getPricePerUnit() != null && other.getPricePerUnit().equals(this.getPricePerUnit()) == false) return false; if (other.getPriceUnits() == null ^ this.getPriceUnits() == null) return false; if (other.getPriceUnits() != null && other.getPriceUnits().equals(this.getPriceUnits()) == false) return false; if (other.getReservationArn() == null ^ this.getReservationArn() == null) return false; if (other.getReservationArn() != null && other.getReservationArn().equals(this.getReservationArn()) == false) return false; if (other.getReservationName() == null ^ this.getReservationName() == null) return false; if (other.getReservationName() != null && other.getReservationName().equals(this.getReservationName()) == false) return false; if (other.getReservationState() == null ^ this.getReservationState() == null) return false; if (other.getReservationState() != null && other.getReservationState().equals(this.getReservationState()) == false) return false; if (other.getResourceSpecification() == null ^ this.getResourceSpecification() == null) return false; if (other.getResourceSpecification() != null && other.getResourceSpecification().equals(this.getResourceSpecification()) == false) return false; if (other.getStart() == null ^ this.getStart() == null) return false; if (other.getStart() != null && other.getStart().equals(this.getStart()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getCurrencyCode() == null) ? 0 : getCurrencyCode().hashCode()); hashCode = prime * hashCode + ((getDuration() == null) ? 0 : getDuration().hashCode()); hashCode = prime * hashCode + ((getDurationUnits() == null) ? 0 : getDurationUnits().hashCode()); hashCode = prime * hashCode + ((getEnd() == null) ? 0 : getEnd().hashCode()); hashCode = prime * hashCode + ((getOfferingArn() == null) ? 0 : getOfferingArn().hashCode()); hashCode = prime * hashCode + ((getOfferingDescription() == null) ? 0 : getOfferingDescription().hashCode()); hashCode = prime * hashCode + ((getPricePerUnit() == null) ? 0 : getPricePerUnit().hashCode()); hashCode = prime * hashCode + ((getPriceUnits() == null) ? 0 : getPriceUnits().hashCode()); hashCode = prime * hashCode + ((getReservationArn() == null) ? 0 : getReservationArn().hashCode()); hashCode = prime * hashCode + ((getReservationName() == null) ? 0 : getReservationName().hashCode()); hashCode = prime * hashCode + ((getReservationState() == null) ? 0 : getReservationState().hashCode()); hashCode = prime * hashCode + ((getResourceSpecification() == null) ? 0 : getResourceSpecification().hashCode()); hashCode = prime * hashCode + ((getStart() == null) ? 0 : getStart().hashCode()); return hashCode; } @Override public Reservation clone() { try { return (Reservation) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.mediaconnect.model.transform.ReservationMarshaller.getInstance().marshall(this, protocolMarshaller); } }
10,121
801
import numpy as np from sklearn import datasets from sklearn.model_selection import StratifiedKFold from neupy.algorithms import PNN dataset = datasets.load_iris() data, target = dataset.data, dataset.target print("> Start classify iris dataset") skfold = StratifiedKFold(n_splits=10) for i, (train, test) in enumerate(skfold.split(data, target), start=1): x_train, x_test = data[train], data[test] y_train, y_test = target[train], target[test] pnn_network = PNN(std=0.1, verbose=False) pnn_network.train(x_train, y_train) result = pnn_network.predict(x_test) n_predicted_correctly = np.sum(result == y_test) n_test_samples = test.size print("Test #{:<2}: Guessed {} out of {}".format( i, n_predicted_correctly, n_test_samples))
301
1,764
<filename>test/data/70.py class Foo: class Bar: def baz(self): pass
49
1,992
#include "test/cross_compile/lib/embed.h" #include <stdlib.h> int GetAnswer() { return atoi(embed_start()); }
46
323
{ "type": "deactivate", "didSuffix": "<KEY>", "revealValue": "EiB-dib5oumdaDGH47TB17Qg1nHza036bTIGibQOKFUY2A", "signedData": "<KEY>" }
75
506
// https://codeforces.com/contest/1131/problem/F #include<bits/stdc++.h> using namespace std; using vi = vector<int>; using vvi = vector<vi>; vi p; vvi r; int find(int i) { if (i == p[i]) return i; return p[i] = find(p[i]); }; void unite(int i, int j) { i = find(i); j = find(j); if (i == j) return; if (r[i].size() < r[j].size()) swap(i,j); for (int x : r[j]) r[i].push_back(x); p[j] = i; }; int main() { ios::sync_with_stdio(0); cin.tie(0); int n, m, u, v; cin >> n; p = vi(n), r = vvi(n); for(int i = 0; i < n; i++) p[i] = i, r[i] = vi(1, i + 1); for(int i = 0; i < n - 1; i++) { cin >> u >> v; u--, v--; unite(u, v); } vi &x = r[find(0)]; for (int i = 0; i < n; i++) cout << x[i] << " \n"[i == n-1]; }
395
370
try: from mechanize import Request, urlopen, URLError, HTTPError,ProxyHandler, build_opener, install_opener, Browser except ImportError: print "\n[X] Please install mechanize module:" print " http://wwwsearch.sourceforge.net/mechanize/\n" exit() import re import random import threading from lxml import etree import os from core.javascript import Javascript from core.constants import USER_AGENTS SOURCES_RE = re.compile("""/(location\s*[\[.])|([.\[]\s*["']?\s*(arguments|dialogArguments|innerHTML|write(ln)?|open(Dialog)?|showModalDialog|cookie|URL|documentURI|baseURI|referrer|name|opener|parent|top|content|self|frames)\W)|(localStorage|sessionStorage|Database)/""") SINKS_RE = re.compile("""/((src|href|data|location|code|value|action)\s*["'\]]*\s*\+?\s*=)|((replace|assign|navigate|getResponseHeader|open(Dialog)?|showModalDialog|eval|evaluate|execCommand|execScript|setTimeout|setInterval)\s*["'\]]*\s*\()/""") class DOMScanner(threading.Thread): def __init__(self, engine, queue): threading.Thread.__init__(self) self.queue = queue self.engine = engine self.errors = {} self.results = [] self.javascript = [] self.whitelisted_js = [] self.whitelist = [] self.browser = Browser() self._setProxies() self._setHeaders() self._getWhitelist() def _setHeaders(self): if self.engine.getOption('ua') is not None: if self.engine.getOption('ua') is "RANDOM": self.browser.addheaders = [('User-Agent', random.choice(USER_AGENTS))] else: self.browser.addheaders = [('User-Agent', self.engine.getOption('ua'))] if self.engine.getOption("cookie") is not None: self.browser.addheaders = [("Cookie", self.engine.getOption("cookie"))] def _setProxies(self): if self.engine.getOption('http-proxy') is not None: self.browser.set_proxies({'http': self.engine.getOption('http-proxy')}) def _addError(self, key, value): if self.errors.has_key(key): self.errors[key].append(value) else: self.errors[key] = [value] def _getWhitelist(self): path = os.path.split(os.path.realpath(__file__))[0] path = os.path.join(path, "../lib/whitelist.xml") f = open(path, "rb") xml = f.read() root = etree.XML(xml) for element in root.iterfind("javascript"): el = { 'hash' : element.find("hash").text, 'description': element.find("description").text, 'reference': element.find("reference").text } self.whitelist.append(el) def _parseJavascript(self, target): if self.engine.getOption("ua") is "RANDOM": self._setHeaders() url = target.getFullUrl() try: to = 10 if self.engine.getOption('http-proxy') is None else 20 response = self.browser.open(url, timeout=to) #urlopen(req, timeout=to) except HTTPError, e: self._addError(e.code, target.getAbsoluteUrl()) return except URLError, e: self._addError(e.reason, target.getAbsoluteUrl()) return except: self._addError('Unknown', target.getAbsoluteUrl()) return else: embedded = [] linked = [] # Parse the page for embedded javascript response = response.read() index = 0 intag = False inscript = False insrc = False ek = 0 lk = 0 while index <= len(response)-1: if response[index:index+7].lower() == "<script": intag = True index += 7 continue if response[index:index+4].lower() == "src=" and intag: insrc = True linked.append("") index += 4 continue if (response[index] == "\"" or response[index] == "'") and insrc: index += 1 continue if (response[index] == "\" " or response[index] == "' ") and insrc: insrc = False lk += 1 index += 2 continue if (response[index] == "\">" or response[index] == "'>") and insrc and intag: insrc = False intag = False lk += 1 index += 2 continue if response[index] == " " and insrc: insrc = False lk += 1 index += 1 continue if response[index] == ">" and insrc and intag: insrc = False intag = False inscript = True embedded.append("") lk += 1 index += 1 continue if response[index] == ">" and intag: intag = False inscript = True embedded.append("") index += 1 continue if response[index:index+9].lower() == "</script>" and inscript: inscript = False ek += 1 index += 9 continue if inscript: embedded[ek] += response[index] if insrc: linked[lk] += response[index] index += 1 # Parse the linked javascripts new_linked = [] for link in linked: if link == "": continue if link[0:len(target.getBaseUrl())] == target.getBaseUrl(): new_linked.append(link) continue elif (link[0:7] == "http://" or link[0:4] == "www." or link[0:8] == "https://" or link[0:2] == "//"): if link[0:2] == "//": link = "http:" + link new_linked.append(link) continue elif link[0] == "/": new_linked.append(target.getBaseUrl() + link) continue else: new_linked.append(target.getBaseUrl() + "/" + link) # Remove duplicates linked = list(set(new_linked)) # Return all javascript retrieved # javascript = [ [target, content], ... ] for link in linked: try: to = 10 if self.engine.getOption('http-proxy') is None else 20 response = self.browser.open(link, timeout=to) except HTTPError, e: self._addError(e.code, link) continue except URLError, e: self._addError(e.reason, link) continue except: self._addError('Unknown', link) continue else: j = Javascript(link, response.read()) self.javascript.append(j) for r in embedded: if r is not "": j = Javascript(target.getAbsoluteUrl(), r, True) self.javascript.append(j) def _analyzeJavascript(self): for js in self.javascript: #print "\n[+] Analyzing:\t %s" % js.link # Check if the javascript is whitelisted # and eventually skip the analysis skip = False for wl in self.whitelist: if wl["hash"] == js.js_hash: self.whitelisted_js.append(wl) skip = True break if skip: continue for k, line in enumerate(js.body.split("\n")): for pattern in re.finditer(SOURCES_RE, line): for grp in pattern.groups(): if grp is None: continue js.addSource(k, grp) #print "[Line: %s] Possible Source: %s" % (k, grp) for pattern in re.finditer(SINKS_RE, line): for grp in pattern.groups(): if grp is None: continue js.addSink(k, grp) #print "[Line: %s] Possible Sink: %s" % (k, grp) def run(self): """ Main code of the thread """ while True: try: target = self.queue.get(timeout = 1) except: try: self.queue.task_done() except ValueError: pass else: self._parseJavascript(target) self._analyzeJavascript() # Scan complete try: self.queue.task_done() except ValueError: pass
5,320
14,668
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/peerconnection/rtc_encoded_video_underlying_sink.h" #include "base/memory/scoped_refptr.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_tester.h" #include "third_party/blink/renderer/bindings/core/v8/to_v8_traits.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" #include "third_party/blink/renderer/bindings/core/v8/v8_dom_exception.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_rtc_encoded_video_frame.h" #include "third_party/blink/renderer/core/dom/dom_exception.h" #include "third_party/blink/renderer/core/streams/writable_stream.h" #include "third_party/blink/renderer/core/streams/writable_stream_default_writer.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_encoded_video_frame.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_encoded_video_frame_delegate.h" #include "third_party/blink/renderer/modules/peerconnection/testing/mock_transformable_video_frame.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/peerconnection/rtc_encoded_video_stream_transformer.h" #include "third_party/blink/renderer/platform/testing/testing_platform_support.h" #include "third_party/webrtc/api/frame_transformer_interface.h" #include "third_party/webrtc/api/scoped_refptr.h" #include "third_party/webrtc/rtc_base/ref_counted_object.h" using testing::_; using testing::NiceMock; using testing::Return; namespace blink { namespace { const uint32_t kSSRC = 1; class MockWebRtcTransformedFrameCallback : public webrtc::TransformedFrameCallback { public: MOCK_METHOD1(OnTransformedFrame, void(std::unique_ptr<webrtc::TransformableFrameInterface>)); }; bool IsDOMException(ScriptState* script_state, ScriptValue value, DOMExceptionCode code) { auto* dom_exception = V8DOMException::ToImplWithTypeCheck( script_state->GetIsolate(), value.V8Value()); if (!dom_exception) return false; return dom_exception->code() == static_cast<uint16_t>(code); } } // namespace class RTCEncodedVideoUnderlyingSinkTest : public testing::Test { public: RTCEncodedVideoUnderlyingSinkTest() : main_task_runner_( blink::scheduler::GetSingleThreadTaskRunnerForTesting()), webrtc_callback_( new rtc::RefCountedObject<MockWebRtcTransformedFrameCallback>()), transformer_(main_task_runner_) {} void SetUp() override { EXPECT_FALSE(transformer_.HasTransformedFrameSinkCallback(kSSRC)); transformer_.RegisterTransformedFrameSinkCallback(webrtc_callback_, kSSRC); EXPECT_TRUE(transformer_.HasTransformedFrameSinkCallback(kSSRC)); } void TearDown() override { platform_->RunUntilIdle(); transformer_.UnregisterTransformedFrameSinkCallback(kSSRC); EXPECT_FALSE(transformer_.HasTransformedFrameSinkCallback(kSSRC)); } RTCEncodedVideoUnderlyingSink* CreateSink( ScriptState* script_state, webrtc::TransformableFrameInterface::Direction expected_direction = webrtc::TransformableFrameInterface::Direction::kSender) { return MakeGarbageCollected<RTCEncodedVideoUnderlyingSink>( script_state, WTF::BindRepeating(&RTCEncodedVideoUnderlyingSinkTest::GetTransformer, WTF::Unretained(this)), expected_direction); } RTCEncodedVideoUnderlyingSink* CreateNullCallbackSink( ScriptState* script_state) { return MakeGarbageCollected<RTCEncodedVideoUnderlyingSink>( script_state, WTF::BindRepeating( []() -> RTCEncodedVideoStreamTransformer* { return nullptr; }), webrtc::TransformableFrameInterface::Direction::kSender); } RTCEncodedVideoStreamTransformer* GetTransformer() { return &transformer_; } ScriptValue CreateEncodedVideoFrameChunk( ScriptState* script_state, webrtc::TransformableFrameInterface::Direction direction = webrtc::TransformableFrameInterface::Direction::kSender) { auto mock_frame = std::make_unique<NiceMock<MockTransformableVideoFrame>>(); ON_CALL(*mock_frame.get(), GetSsrc).WillByDefault(Return(kSSRC)); ON_CALL(*mock_frame.get(), GetDirection).WillByDefault(Return(direction)); RTCEncodedVideoFrame* frame = MakeGarbageCollected<RTCEncodedVideoFrame>(std::move(mock_frame)); return ScriptValue( script_state->GetIsolate(), ToV8Traits<RTCEncodedVideoFrame>::ToV8(script_state, frame) .ToLocalChecked()); } protected: ScopedTestingPlatformSupport<TestingPlatformSupport> platform_; scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_; rtc::scoped_refptr<MockWebRtcTransformedFrameCallback> webrtc_callback_; RTCEncodedVideoStreamTransformer transformer_; }; TEST_F(RTCEncodedVideoUnderlyingSinkTest, WriteToStreamForwardsToWebRtcCallback) { V8TestingScope v8_scope; ScriptState* script_state = v8_scope.GetScriptState(); auto* sink = CreateSink(script_state); auto* stream = WritableStream::CreateWithCountQueueingStrategy(script_state, sink, 1u); NonThrowableExceptionState exception_state; auto* writer = stream->getWriter(script_state, exception_state); EXPECT_CALL(*webrtc_callback_, OnTransformedFrame(_)); ScriptPromiseTester write_tester( script_state, writer->write(script_state, CreateEncodedVideoFrameChunk(script_state), exception_state)); EXPECT_FALSE(write_tester.IsFulfilled()); writer->releaseLock(script_state); ScriptPromiseTester close_tester( script_state, stream->close(script_state, exception_state)); close_tester.WaitUntilSettled(); // Writing to the sink after the stream closes should fail. DummyExceptionStateForTesting dummy_exception_state; sink->write(script_state, CreateEncodedVideoFrameChunk(script_state), nullptr, dummy_exception_state); EXPECT_TRUE(dummy_exception_state.HadException()); EXPECT_EQ(dummy_exception_state.Code(), static_cast<ExceptionCode>(DOMExceptionCode::kInvalidStateError)); } TEST_F(RTCEncodedVideoUnderlyingSinkTest, WriteInvalidDataFails) { V8TestingScope v8_scope; ScriptState* script_state = v8_scope.GetScriptState(); auto* sink = CreateSink(script_state); ScriptValue v8_integer = ScriptValue::From(script_state, 0); // Writing something that is not an RTCEncodedVideoFrame integer to the sink // should fail. DummyExceptionStateForTesting dummy_exception_state; sink->write(script_state, v8_integer, nullptr, dummy_exception_state); EXPECT_TRUE(dummy_exception_state.HadException()); } TEST_F(RTCEncodedVideoUnderlyingSinkTest, WriteToNullCallbackSinkFails) { V8TestingScope v8_scope; ScriptState* script_state = v8_scope.GetScriptState(); auto* sink = CreateNullCallbackSink(script_state); auto* stream = WritableStream::CreateWithCountQueueingStrategy(script_state, sink, 1u); NonThrowableExceptionState exception_state; auto* writer = stream->getWriter(script_state, exception_state); EXPECT_CALL(*webrtc_callback_, OnTransformedFrame(_)).Times(0); ScriptPromiseTester write_tester( script_state, writer->write(script_state, CreateEncodedVideoFrameChunk(script_state), exception_state)); write_tester.WaitUntilSettled(); EXPECT_TRUE(write_tester.IsRejected()); EXPECT_TRUE(IsDOMException(script_state, write_tester.Value(), DOMExceptionCode::kInvalidStateError)); } TEST_F(RTCEncodedVideoUnderlyingSinkTest, WriteInvalidDirectionFails) { V8TestingScope v8_scope; ScriptState* script_state = v8_scope.GetScriptState(); auto* sink = CreateSink( script_state, webrtc::TransformableFrameInterface::Direction::kSender); // Write an encoded chunk with direction set to Receiver should fail as it // doesn't match the expected direction of our sink. DummyExceptionStateForTesting dummy_exception_state; sink->write(script_state, CreateEncodedVideoFrameChunk( script_state, webrtc::TransformableFrameInterface::Direction::kReceiver), nullptr, dummy_exception_state); EXPECT_TRUE(dummy_exception_state.HadException()); } } // namespace blink
3,174
360
<filename>bower.json { "name": "vminpoly", "main": "vminpoly.js", "version": "0.1.0", "homepage": "https://github.com/saabi/vminpoly", "authors": [ "<NAME> <<EMAIL>>" ], "description": "A polyfill for CSS units vw, vh & vmin and now some media queries to boot.", "keywords": [ "polyfill", "css", "units", "vmin", "vmax", "vw", "vh", "media-queries" ], "license": "MIT", "ignore": [ "*.html", "*.css", "*.coffee" ] }
231
4,538
<gh_stars>1000+ /* * Copyright (C) 2015-2020 Alibaba Group Holding Limited * */ #ifndef __UVOICE_MLIST_H__ #define __UVOICE_MLIST_H__ /** @defgroup uvoice_mlist_api uvoice_mlist * @ingroup uvoice_aos_api * @{ */ /** * 显示播放列表 * * @retrun 成功返回0,失败返回非0. */ int mlist_source_show(void); /** * 扫描本地音频文件,更新播放列表 * * @retrun 成功返回0,失败返回非0. */ int mlist_source_scan(void); /** * 获取播放列表 * * @param[in] index 播放列表中音频文件序号 * @param[out] path 音频文件路径 * @param[in] len 音频文件路径长度 * @retrun 成功返回0,失败返回非0. */ int mlist_source_get(int index, char *path, int len); /** * 删除播放列表中某个音频文件 * * @param[in] index 播放列表序号为index的音频文件 * @retrun 成功返回0,失败返回非0. */ int mlist_source_del(int index); /** * 获取播放列表中正在播放音频文件的列表序号 * * @param[out] index 播放列表中音频文件序号 * @retrun 成功返回0,失败返回非0. */ int mlist_index_get(int *index); /** * 设置当前正在播放音频文件的列表序号 * * @param[in] index 播放列表序号 * @retrun 成功返回0,失败返回非0. */ int mlist_index_set(int index); /** * @} */ #endif /* __UVOICE_MLIST_H__ */
882
657
<filename>lib/slack/web/docs/channels.kick.json<gh_stars>100-1000 { "desc": "Removes a user from a channel.", "args": { "channel": { "type" : "channel", "required" : true, "desc" : "Channel to remove user from." }, "user": { "type" : "user", "required" : true, "desc" : "User to remove from channel." } }, "errors": { "channel_not_found" : "Value passed for `channel` was invalid.", "user_not_found" : "Value passed for `user` was invalid.", "cant_kick_self" : "Authenticated user can't kick themselves from a channel.", "not_in_channel" : "User was not in the channel.", "cant_kick_from_general": "User cannot be removed from #general.", "cant_kick_from_last_channel": "User cannot be removed from the last channel they're in.", "restricted_action" : "A team preference prevents the authenticated user from kicking." } }
327
2,225
{ "fontId": "dseg14", "fontName": "DSEG14", "subsets": ["classic", "classic-mini", "modern", "modern-mini"], "weights": [300, 400, 700], "styles": ["italic", "normal"], "defSubset": "classic", "variable": false, "lastModified": "2020-08-02", "version": "v0.46", "category": "other", "source": "https://github.com/keshikan/DSEG", "license": "https://github.com/keshikan/DSEG/blob/master/DSEG-LICENSE.txt", "type": "other" }
187
1,646
package com.litesuits.orm.kvdb; public interface FileDataCahe { }
32
984
/* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.dse.driver.internal.core.data.geometry; import static org.assertj.core.api.Assertions.assertThat; import com.datastax.dse.driver.api.core.data.geometry.Geometry; import com.datastax.oss.protocol.internal.util.Bytes; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SerializationUtils { public static Object serializeAndDeserialize(Geometry geometry) throws IOException, ClassNotFoundException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(geometry); byte[] bytes = baos.toByteArray(); if (!(geometry instanceof Distance)) { byte[] wkb = Bytes.getArray(geometry.asWellKnownBinary()); assertThat(bytes).containsSequence(wkb); } ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes)); return in.readObject(); } }
491
2,206
<reponame>Celebrate-future/deeplearning4j /* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.autodiff.listeners; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.nd4j.autodiff.listeners.records.EvaluationRecord; import org.nd4j.autodiff.listeners.records.LossCurve; import org.nd4j.autodiff.samediff.SameDiff; import org.nd4j.autodiff.samediff.internal.SameDiffOp; import org.nd4j.evaluation.IEvaluation; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.dataset.api.MultiDataSet; public abstract class BaseEvaluationListener extends BaseListener { private Map<String, List<IEvaluation>> trainingEvaluations = new HashMap<>(); private Map<String, List<IEvaluation>> validationEvaluations = new HashMap<>(); /** * Return the requested evaluations. New instances of these evaluations will be made each time they are used */ public abstract ListenerEvaluations evaluations(); @Override public final ListenerVariables requiredVariables(SameDiff sd) { return evaluations().requiredVariables().merge(otherRequiredVariables(sd)); } /** * Return any requested variables that are not part of the evaluations */ public ListenerVariables otherRequiredVariables(SameDiff sd){ return ListenerVariables.empty(); } @Override public final void epochStart(SameDiff sd, At at) { trainingEvaluations = new HashMap<>(); for(Map.Entry<String, List<IEvaluation>> entry : evaluations().trainEvaluations().entrySet()){ List<IEvaluation> evals = new ArrayList<>(); for(IEvaluation ie : entry.getValue()) evals.add(ie.newInstance()); trainingEvaluations.put(entry.getKey(), evals); } validationEvaluations = new HashMap<>(); for(Map.Entry<String, List<IEvaluation>> entry : evaluations().validationEvaluations().entrySet()){ List<IEvaluation> evals = new ArrayList<>(); for(IEvaluation ie : entry.getValue()) evals.add(ie.newInstance()); validationEvaluations.put(entry.getKey(), evals); } epochStartEvaluations(sd, at); } /** * See {@link Listener#epochStart(SameDiff, At)} */ public void epochStartEvaluations(SameDiff sd, At at){ //No op } @Override public final ListenerResponse epochEnd(SameDiff sd, At at, LossCurve lossCurve, long epochTimeMillis) { return epochEndEvaluations(sd, at, lossCurve, epochTimeMillis, new EvaluationRecord(trainingEvaluations)); } /** * See {@link Listener#epochEnd(SameDiff, At, LossCurve, long)}, also provided the requested evaluations */ public ListenerResponse epochEndEvaluations(SameDiff sd, At at, LossCurve lossCurve, long epochTimeMillis, EvaluationRecord evaluations) { //No op return ListenerResponse.CONTINUE; } @Override public final ListenerResponse validationDone(SameDiff sd, At at, long validationTimeMillis) { return validationDoneEvaluations(sd, at, validationTimeMillis, new EvaluationRecord(validationEvaluations)); } /** * See {@link Listener#validationDone(SameDiff, At, long)}, also provided the requested evaluations */ public ListenerResponse validationDoneEvaluations(SameDiff sd, At at, long validationTimeMillis, EvaluationRecord evaluations) { //No op return ListenerResponse.CONTINUE; } @Override public final void activationAvailable(SameDiff sd, At at, MultiDataSet batch, SameDiffOp op, String varName, INDArray activation) { if(at.operation() == Operation.TRAINING) { if (trainingEvaluations.containsKey(varName)) { INDArray labels = batch.getLabels(evaluations().trainEvaluationLabels().get(varName)); INDArray mask = batch.getLabelsMaskArray(evaluations().trainEvaluationLabels().get(varName)); for (IEvaluation e : trainingEvaluations.get(varName)) e.eval(labels, activation, mask); } } else if(at.operation() == Operation.TRAINING_VALIDATION) { if (validationEvaluations.containsKey(varName)) { INDArray labels = batch.getLabels(evaluations().validationEvaluationLabels().get(varName)); INDArray mask = batch.getLabelsMaskArray(evaluations().validationEvaluationLabels().get(varName)); for (IEvaluation e : validationEvaluations.get(varName)) e.eval(labels, activation, mask); } } activationAvailableEvaluations(sd, at, batch, op, varName, activation); } /** * See {@link Listener#activationAvailable(SameDiff, At, MultiDataSet, SameDiffOp, String, INDArray)} */ public void activationAvailableEvaluations(SameDiff sd, At at, MultiDataSet batch, SameDiffOp op, String varName, INDArray activation){ //No op } }
2,123
3,274
<filename>src/test/java/com/ql/util/express/bugfix/TestOverFlow.java<gh_stars>1000+ package com.ql.util.express.bugfix; import org.junit.Test; public class TestOverFlow { public class Result{ private int a = 0; private String b = "我是一个长长的字符串"; public int getA() { return a; } public void setA(int a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } } private int count = 0; public void fun(){ count ++; fun(); } public void fun_a(int a){ count ++; fun_a(a); } public int funReturn(){ count ++; int a = funReturn(); return 1 + a + 1; } public Result funBigReturn(){ count ++; Result a = funBigReturn(); a.setA(1); return a; } public void fun_abc(int a,int b,int c){ count ++; fun_abc(a+1,b+1,c+1); } public void fun_abc2(int a,int b,int c){ count ++; fun_a(a,b,c); } public void fun_a(int a,int b,int c){ count ++; fun_abc2(a+1,b,c); } public void fun_b(int a,int b,int c){ count ++; fun_abc2(a,b+1,c); } public void fun_c(int a,int b,int c){ count ++; fun_abc2(a,b,c+1); } public void test(){ try{ this.count = 0; fun(); }catch(Throwable e){ System.out.println("fun() 最大栈深度:"+count); } } public void test_a(){ try{ this.count = 0; fun_a(1); }catch(Throwable e){ System.out.println("fun_a() 最大栈深度:"+count); } } public void testReturn(){ try{ this.count = 0; funReturn(); }catch(Throwable e){ System.out.println("funReturn() 最大栈深度:"+count); } try{ this.count = 0; funBigReturn(); }catch(Throwable e){ System.out.println("funBigReturn() 最大栈深度:"+count); } } public void test_abc() { try { this.count = 0; fun_abc(1, 1, 1); } catch (Throwable e) { System.out.println("fun_abc() 最大栈深度:" + count); } } public void test_abc2(){ try{ this.count = 0; fun_abc2(1,1,1); }catch(Throwable e){ System.out.println("fun_abc2() 最大栈深度:"+count); } } public void testOverFlow() { test(); test_a(); testReturn(); test_abc(); test_abc2(); } @Test public void testOverflow(){ new TestOverFlow().testOverFlow(); } }
1,614
380
from the_pile.utils import * import random import os from tqdm import tqdm import shutil import zstandard import io import json import sys f = sys.argv[1] fout = 'tmp' def readf(f): with open(f, 'rb') as fh: cctx = zstandard.ZstdDecompressor() reader = io.BufferedReader(cctx.stream_reader(fh)) yield from tqdm(reader) def writef(f, lines): with open(f, 'wb') as fh: cctx = zstandard.ZstdCompressor(level=3, threads=8) compressor = cctx.stream_writer(fh) for line in tqdm(lines): compressor.write(line) compressor.flush(zstandard.FLUSH_FRAME) def despace(x): res = [] for i, char in enumerate(x): if i % 2 == 1: if char != '\n': print(x) raise AssertionError() else: res.append(char) return ''.join(res) def fix(x): # optimization if b'DM Mathematics' not in x: return x ob = json.loads(x) if ob['meta']['pile_set_name'] != 'DM Mathematics': return x ob['text'] = despace(ob['text']) return (json.dumps(ob).strip() + '\n').encode('utf-8') writef(fout, map(fix, readf(f))) sh('mv tmp ' + f)
563
1,006
/**************************************************************************** * arch/arm/src/nrf52/nrf52_rng.c * * 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <stdint.h> #include <stdbool.h> #include <stdio.h> #include <string.h> #include <debug.h> #include <errno.h> #include <fcntl.h> #include <nuttx/fs/fs.h> #include <nuttx/irq.h> #include <nuttx/arch.h> #include <nuttx/semaphore.h> #include <nuttx/fs/ioctl.h> #include <nuttx/drivers/drivers.h> #include "arm_arch.h" #include "chip.h" #include "hardware/nrf52_utils.h" #include "hardware/nrf52_rng.h" #include "arm_internal.h" #if defined(CONFIG_NRF52_RNG) #if defined(CONFIG_DEV_RANDOM) || defined(CONFIG_DEV_URANDOM_ARCH) /**************************************************************************** * Private Function Prototypes ****************************************************************************/ static int nrf52_rng_initialize(void); static int nrf52_rng_irqhandler(int irq, void *context, FAR void *arg); static ssize_t nrf52_rng_read(FAR struct file *filep, FAR char *buffer, size_t buflen); static int nrf52_rng_open(FAR struct file *filep); /**************************************************************************** * Private Types ****************************************************************************/ struct rng_dev_s { uint8_t *rd_buf; size_t rd_count; size_t buflen; sem_t rd_sem; /* semaphore for read RNG data */ sem_t excl_sem; /* semaphore for access RNG dev */ }; /**************************************************************************** * Private Data ****************************************************************************/ static struct rng_dev_s g_rngdev; static const struct file_operations g_rngops = { .open = nrf52_rng_open, /* open */ .read = nrf52_rng_read, /* read */ }; /**************************************************************************** * Private functions ****************************************************************************/ static void nrf52_rng_start(void) { irqstate_t flag; flag = enter_critical_section(); nrf52_event_clear(NRF52_RNG_EVENTS_RDY); putreg32(1, NRF52_RNG_CONFIG); nrf52_interrupt_enable(NRF52_RNG_INTSET, RNG_INT_RDY); nrf52_task_trigger(NRF52_RNG_TASKS_START); up_enable_irq(NRF52_IRQ_RNG); leave_critical_section(flag); } static void nrf52_rng_stop(void) { irqstate_t flag; flag = enter_critical_section(); up_disable_irq(NRF52_IRQ_RNG); nrf52_task_trigger(NRF52_RNG_TASKS_STOP); nrf52_interrupt_disable(NRF52_RNG_INTCLR, RNG_INT_RDY); nrf52_event_clear(NRF52_RNG_EVENTS_RDY); leave_critical_section(flag); } static int nrf52_rng_initialize(void) { static bool first_flag = true; if (false == first_flag) return OK; first_flag = false; _info("Initializing RNG\n"); memset(&g_rngdev, 0, sizeof(struct rng_dev_s)); nxsem_init(&g_rngdev.rd_sem, 0, 0); nxsem_set_protocol(&g_rngdev.rd_sem, SEM_PRIO_NONE); nxsem_init(&g_rngdev.excl_sem, 0, 1); nxsem_set_protocol(&g_rngdev.excl_sem, SEM_PRIO_NONE); _info("Ready to stop\n"); nrf52_rng_stop(); if (irq_attach(NRF52_IRQ_RNG, nrf52_rng_irqhandler, NULL) != 0) { /* We could not attach the ISR to the interrupt */ _warn("Could not attach NRF52_IRQ_RNG.\n"); return -EAGAIN; } return OK; } static int nrf52_rng_irqhandler(int irq, FAR void *context, FAR void *arg) { FAR struct rng_dev_s *priv = (struct rng_dev_s *) &g_rngdev; uint8_t *addr; if (getreg32(NRF52_RNG_EVENTS_RDY) == RNG_INT_RDY) { nrf52_event_clear(NRF52_RNG_EVENTS_RDY); if (priv->rd_count < priv->buflen) { addr = priv->rd_buf + priv->rd_count++; *addr = getreg32(NRF52_RNG_VALUE); irqwarn("%d\n", *addr); } if (priv->rd_count == priv->buflen) { nrf52_rng_stop(); nxsem_post(&priv->rd_sem); } } return OK; } /**************************************************************************** * Name: nrf52_rng_open ****************************************************************************/ static int nrf52_rng_open(FAR struct file *filep) { /* O_NONBLOCK is not supported */ if (filep->f_oflags & O_NONBLOCK) { _err("nRF52 rng didn't support O_NONBLOCK mode.\n"); return -EPERM; } return OK; } /**************************************************************************** * Name: nrf52_rng_read ****************************************************************************/ static ssize_t nrf52_rng_read(FAR struct file *filep, FAR char *buffer, size_t buflen) { FAR struct rng_dev_s *priv = (struct rng_dev_s *)&g_rngdev; ssize_t read_len; if (nxsem_wait(&priv->excl_sem) != OK) { return -EBUSY; } priv->rd_buf = (uint8_t *) buffer; priv->buflen = buflen; priv->rd_count = 0; /* start RNG and Wait until the buffer is filled */ nrf52_rng_start(); nxsem_wait(&priv->rd_sem); read_len = priv->rd_count; if (priv->rd_count > priv->buflen) { _err("Bad rd_count: Too much data, exceeds buffer size: %d\n", priv->rd_count); } /* Now , got data, and release rd_sem for next read */ nxsem_post(&priv->excl_sem); return read_len; } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: devrandom_register * * Description: * Initialize the RNG hardware and register the /dev/random driver. * Must be called BEFORE devurandom_register. * * Input Parameters: * None * * Returned Value: * None * ****************************************************************************/ #ifdef CONFIG_DEV_RANDOM void devrandom_register(void) { nrf52_rng_initialize(); register_driver("/dev/random", FAR & g_rngops, 0444, NULL); } #endif /**************************************************************************** * Name: devurandom_register * * Description: * Register /dev/urandom * * Input Parameters: * None * * Returned Value: * None * ****************************************************************************/ #ifdef CONFIG_DEV_URANDOM_ARCH void devurandom_register(void) { #ifndef CONFIG_DEV_RANDOM nrf52_rng_initialize(); #endif register_driver("dev/urandom", FAR & g_rngops, 0444, NULL); } #endif #endif /* CONFIG_DEV_RANDOM || CONFIG_DEV_URANDOM_ARCH */ #endif /* CONFIG_NRF52_RNG */
2,675
1,481
package apoc.data.url; import apoc.util.TestUtil; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.neo4j.test.rule.DbmsRule; import org.neo4j.test.rule.ImpermanentDbmsRule; import java.util.HashMap; import java.util.Map; import static apoc.util.MapUtil.map; import static apoc.util.TestUtil.testCall; import static org.junit.Assert.assertEquals; public class ExtractURLTest { @ClassRule public static DbmsRule db = new ImpermanentDbmsRule(); private static HashMap<String,Map<String,Object>> testCases; @BeforeClass public static void setUp() throws Exception { TestUtil.registerProcedure(db, ExtractURL.class); // Test cases map URLs to an array of strings representing what their correct answers should // be for components: // protocol, user, host, port, path, file, query, anchor. // Ordering must match "methods" above. testCases = new HashMap<>(); testCases.put("http://simple.com/", map( "protocol","http", "user",null, "host","simple.com", "port",null, "path","/", "file","/", "query",null, "anchor",null) ); // Something kinda complicated... testCases.put("https://user:secret@localhost:666/path/to/file.html?x=1#b", map( "protocol","https", "user","user:secret", "host","localhost", "port",666L, "path","/path/to/file.html", "file","/path/to/file.html?x=1","query", "x=1", "anchor","b")); // This is a malformed URL testCases.put("google.com", null); // Real-world semi complex URL. So meta! :) testCases.put("https://github.com/neo4j-contrib/neo4j-apoc-procedures/commit/31cf4b60236ef5e08f7b231ed03f3d8ace511fd2#diff-a084b794bc0759e7a6b77810e01874f2", map ("protocol", "https", "user",null, "host","github.com", "port",null, "path","/neo4j-contrib/neo4j-apoc-procedures/commit/31cf4b60236ef5e08f7b231ed03f3d8ace511fd2", "file","/neo4j-contrib/neo4j-apoc-procedures/commit/31cf4b60236ef5e08f7b231ed03f3d8ace511fd2", "anchor","diff-a084b794bc0759e7a6b77810e01874f2", "query", null )); // non standard protocol testCases.put("neo4j://graphapps/neo4j-browser?cmd=play&arg=cypher", map( "protocol","neo4j", "user", null, "host","graphapps", "port",null, "path","/neo4j-browser", "file","/neo4j-browser?cmd=play&arg=cypher", "query","cmd=play&arg=cypher", "anchor",null) ); } @Test public void testByCase() { for(String url : testCases.keySet()) { Map<String,Object> answers = testCases.get(url); testCall(db, "RETURN apoc.data.url($url) AS value",map("url",url), row -> { Map value = (Map) row.get("value"); if (answers != null) { for (Map.Entry o : answers.entrySet()) { assertEquals(o.getKey().toString(), o.getValue(), value.get(o.getKey())); } } assertEquals(answers, value); }); } testCall(db, "RETURN apoc.data.url(null) AS value", row -> { assertEquals(null, row.get("value")); }); } /* Previous test cases matching the deprecated Extract class' requirements are below */ @Test public void testNull() { testCall(db, "RETURN apoc.data.url(null).host AS value", row -> assertEquals(null, row.get("value"))); } @Test public void testBadString() { testCall(db, "RETURN apoc.data.url('asdsgawe4ge').host AS value", row -> assertEquals(null, row.get("value"))); } @Test public void testEmptyString() { testCall(db, "RETURN apoc.data.url('').host AS value", row -> assertEquals(null, row.get("value"))); } @Test public void testUrl() { testCall(db, "RETURN apoc.data.url('http://www.example.com/lots-of-stuff').host AS value", row -> assertEquals("www.example.com", row.get("value"))); } @Test public void testQueryParameter() { testCall(db, "RETURN apoc.data.url($param).host AS value", map("param", "http://www.foo.bar/baz"), row -> assertEquals("www.foo.bar", row.get("value"))); } @Test public void testShorthandURL() { testCall(db, "RETURN apoc.data.url($param).host AS value", map("param", "partial.com/foobar"), row -> assertEquals(null, row.get("value"))); } }
2,122
1,083
<filename>src/dale/Form/Proc/Dereference/Dereference.cpp #include "Dereference.h" #include <string> #include <vector> #include "../../../Function/Function.h" #include "../../../Node/Node.h" #include "../../../Operation/Destruct/Destruct.h" #include "../../../ParseResult/ParseResult.h" #include "../../../Units/Units.h" #include "../../../llvm_Function.h" #include "../Inst/Inst.h" using namespace dale::ErrorInst; namespace dale { bool FormProcDereferenceParse(Units *units, Function *fn, llvm::BasicBlock *block, Node *node, bool get_address, bool prefixed_with_core, ParseResult *pr) { Context *ctx = units->top()->ctx; if (!ctx->er->assertArgNums("@", node, 1, 1)) { return false; } std::vector<Node *> *lst = node->list; Node *ptr = (*lst)[1]; ParseResult ptr_pr; bool res = FormProcInstParse(units, fn, block, ptr, false, false, NULL, &ptr_pr); if (!res) { return false; } Type *ptr_type = ptr_pr.type; if (!ptr_type->points_to) { std::string type_str; ptr_type->toString(&type_str); Error *e = new Error(CannotDereferenceNonPointer, node, type_str.c_str()); ctx->er->addError(e); return false; } if (ptr_type->points_to->base_type == BaseType::Void) { Error *e = new Error(CannotDereferenceVoidPointer, node); ctx->er->addError(e); return false; } pr->set(ptr_pr.block, NULL, NULL); if (!get_address) { pr->address_of_value = ptr_pr.getValue(ctx); pr->value_is_lvalue = true; pr->type_of_address_of_value = ptr_type; pr->set(pr->block, ptr_type->points_to, NULL); } else { pr->set(pr->block, ptr_type, ptr_pr.getValue(ctx)); } /* Core dereference call results should not be copied. Otherwise, * an overloaded setf that calls @ on the pointer to the * underlying value will not be able to work, because even (core @ * x) will return a pointee to x, which will be copied to the * caller of this function. */ if (prefixed_with_core) { pr->do_not_copy_with_setf = true; } ParseResult destruct_pr; res = Operation::Destruct(ctx, &ptr_pr, &destruct_pr); if (!res) { return false; } pr->block = destruct_pr.block; return true; } }
1,122
704
<reponame>ozyb/novel-cloud package com.java2nb.novel.file.schedule; import com.java2nb.novel.book.entity.Book; import com.java2nb.novel.common.utils.Constants; import com.java2nb.novel.common.utils.FileUtil; import com.java2nb.novel.file.feign.BookFeignClient; import com.java2nb.novel.file.service.FileService; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.io.File; import java.util.List; /** * 将爬取的网络图片转存到OSS任务 * * @author xiongxiaoyang * @version 1.0 * @since 2020/6/2 */ @Service @RequiredArgsConstructor @Slf4j public class CrawlPicTransSchedule { private final BookFeignClient bookFeignClient; private final RedissonClient redissonClient; private final FileService fileService; /** * 10分钟转一次 */ @Scheduled(fixedRate = 1000 * 60 * 10) @SneakyThrows public void trans() { RLock lock = redissonClient.getLock("crawlPicTrans"); lock.lock(); try { List<Book> networkPicBooks = bookFeignClient.queryNetworkPicBooks(Constants.LOCAL_PIC_PREFIX, 100); for (Book book : networkPicBooks) { String filePath = "/images/default.gif"; File file = FileUtil.networkPic2Temp(book.getPicUrl()); if (file != null) { filePath = fileService.uploadFile(file); } bookFeignClient.updateBookPic(filePath, book.getId()); //3秒钟转化一张图片,10分钟转化200张 Thread.sleep(3000); } } catch (Exception e) { log.error(e.getMessage(), e); } lock.unlock(); } }
872
391
<filename>clai/server/plugins/manpage_agent/manpage_agent.py<gh_stars>100-1000 # # Copyright (C) 2020 IBM. All Rights Reserved. # # See LICENSE.txt file in the root directory # of this source tree for licensing information. # import requests import os import json from pathlib import Path from clai.server.agent import Agent from clai.server.command_message import Action, State from clai.server.plugins.manpage_agent.question_detection import QuestionDetection from clai.server.plugins.manpage_agent import tldr_wrapper class ManPageAgent(Agent): def __init__(self): super(ManPageAgent, self).__init__() self.question_detection_mod = QuestionDetection() self._config = None self._API_URL = None self.read_config() def read_config(self): curdir = str(Path(__file__).parent.absolute()) config_path = os.path.join(curdir, 'config.json') with open(config_path, 'r') as f: self._config = json.load(f) self._API_URL = self._config['API_URL'] def __call_api__(self, search_text): payload = { 'text': search_text, 'result_count': 1 } headers = {'Content-Type': "application/json"} r = requests.post(self._API_URL, params=payload, headers=headers) if r.status_code == 200: return r.json() return None def get_next_action(self, state: State) -> Action: cmd = state.command is_question = self.question_detection_mod.is_question(cmd) if not is_question: return Action( suggested_command=state.command, confidence=0.0 ) response = None try: response = self.__call_api__(cmd) except Exception: pass if response is None or response['status'] != 'success': return Action( suggested_command=state.command, confidence=0.0 ) command = response['commands'][-1] confidence = response['dists'][-1] try: cmd_tldr = tldr_wrapper.get_command_tldr(command) except Exception as err: print('Exception: ' + str(err)) cmd_tldr = '' return Action( suggested_command="man {}".format(command), confidence=confidence, description=cmd_tldr )
1,075
14,668
<reponame>zealoussnow/chromium // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.continuous_search; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Activity; import android.widget.LinearLayout; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.mockito.quality.Strictness; import org.chromium.base.FeatureList; import org.chromium.base.supplier.ObservableSupplierImpl; import org.chromium.base.test.BaseActivityTestRule; import org.chromium.base.test.util.Batch; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.JniMocker; import org.chromium.chrome.browser.browser_controls.BrowserControlsStateProvider; import org.chromium.chrome.browser.continuous_search.ContinuousSearchContainerCoordinator.VisibilitySettings; import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.theme.ThemeColorProvider; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.components.url_formatter.UrlFormatter; import org.chromium.components.url_formatter.UrlFormatterJni; import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.ui.test.util.DummyUiActivity; import org.chromium.url.GURL; import org.chromium.url.JUnitTestGURLs; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeoutException; /** * Tests for Continuous Search UI. */ @RunWith(ChromeJUnit4ClassRunner.class) @Batch(Batch.UNIT_TESTS) public class ContinuousSearchUiTest { @ClassRule public static BaseActivityTestRule<DummyUiActivity> sActivityTestRule = new BaseActivityTestRule<>(DummyUiActivity.class); private static Activity sActivity; private VisibilitySettings mVisibilitySettings; private ContinuousSearchListCoordinator mCoordinator; private ObservableSupplierImpl<Tab> mTabSupplier; private LinearLayout mLayout; @Mock private Tab mTabMock; @Mock private BrowserControlsStateProvider mStateProviderMock; @Mock private ThemeColorProvider mThemeProviderMock; @Mock private ContinuousNavigationUserDataImpl mUserDataMock; @Mock private UrlFormatter.Natives mUrlFormatterJniMock; @Captor private ArgumentCaptor<ContinuousNavigationUserDataObserver> mObserverCaptor; @Rule public JniMocker mJniMocker = new JniMocker(); @Rule public MockitoRule mMockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); @BeforeClass public static void setupSuite() { sActivityTestRule.launchActivity(null); TestThreadUtils.runOnUiThreadBlocking( () -> { sActivity = sActivityTestRule.getActivity(); }); } @Before public void setUpTest() throws Exception { FeatureList.TestValues testValues = new FeatureList.TestValues(); testValues.addFeatureFlagOverride(ChromeFeatureList.CONTINUOUS_SEARCH, true); testValues.addFieldTrialParamOverride(ChromeFeatureList.CONTINUOUS_SEARCH, ContinuousSearchListMediator.TRIGGER_MODE_PARAM, "0"); testValues.addFieldTrialParamOverride(ChromeFeatureList.CONTINUOUS_SEARCH, ContinuousSearchListMediator.SHOW_RESULT_TITLE_PARAM, "false"); mJniMocker.mock(UrlFormatterJni.TEST_HOOKS, mUrlFormatterJniMock); when(mUrlFormatterJniMock.formatUrlForSecurityDisplay(any(), anyInt())) .thenAnswer((invocation) -> { return ((GURL) invocation.getArguments()[0]).getSpec(); }); TestThreadUtils.runOnUiThreadBlocking(() -> { FeatureList.setTestValues(testValues); mTabSupplier = new ObservableSupplierImpl<Tab>(); mCoordinator = new ContinuousSearchListCoordinator(mStateProviderMock, mTabSupplier, this::updateVisibility, mThemeProviderMock, sActivity); mLayout = new LinearLayout(sActivity); mLayout.setLayoutParams( new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); sActivity.setContentView(mLayout); mCoordinator.initializeLayout(mLayout); ContinuousNavigationUserDataImpl.setInstanceForTesting(mUserDataMock); mTabSupplier.set(mTabMock); }); verify(mUserDataMock).addObserver(mObserverCaptor.capture()); } /** * Tests that scroll to selected works without setting the scrolled condition. */ @Test @SmallTest public void testScrollToSelected() throws TimeoutException { GURL srpUrl = JUnitTestGURLs.getGURL(JUnitTestGURLs.SEARCH_URL); GURL result1Url = JUnitTestGURLs.getGURL(JUnitTestGURLs.RED_1); GURL result2Url = JUnitTestGURLs.getGURL(JUnitTestGURLs.RED_2); GURL result3Url = JUnitTestGURLs.getGURL(JUnitTestGURLs.RED_3); GURL result4Url = JUnitTestGURLs.getGURL(JUnitTestGURLs.BLUE_1); List<PageGroup> groups = new ArrayList<PageGroup>(); List<PageItem> results = new ArrayList<PageItem>(); results.add(new PageItem(result1Url, "Red 1")); results.add(new PageItem(result2Url, "Red 2")); results.add(new PageItem(result3Url, "Red 3")); results.add(new PageItem(result4Url, "Blue 1")); groups.add(new PageGroup("Red Group", false, results)); ContinuousNavigationMetadata metadata = new ContinuousNavigationMetadata( srpUrl, "Foo", new ContinuousNavigationMetadata.Provider(1, null, 0), groups); ContinuousNavigationUserDataObserver observer = mObserverCaptor.getValue(); TestThreadUtils.runOnUiThreadBlocking(() -> { observer.onUpdate(metadata); observer.onUrlChanged(result4Url, false); }); Assert.assertNotNull(mVisibilitySettings); Assert.assertTrue(mVisibilitySettings.isVisible()); CallbackHelper callbackHelper = new CallbackHelper(); TestThreadUtils.runOnUiThreadBlocking(() -> { RecyclerView recyclerView = mLayout.findViewById(R.id.recycler_view); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView view, int newState) { if (newState == RecyclerView.SCROLL_STATE_IDLE) { callbackHelper.notifyCalled(); } } }); mVisibilitySettings.getOnFinishRunnable().run(); }); callbackHelper.waitForFirst("UI Didn't finish scroll."); Assert.assertFalse(mCoordinator.getMediatorForTesting().mScrolled); TestThreadUtils.runOnUiThreadBlocking(() -> { RecyclerView recyclerView = mLayout.findViewById(R.id.recycler_view); Assert.assertTrue("First fully visible item is unexpected.", ((LinearLayoutManager) recyclerView.getLayoutManager()) .findFirstCompletelyVisibleItemPosition() > 0); }); } private void updateVisibility(VisibilitySettings visibilitySettings) { mVisibilitySettings = visibilitySettings; } }
3,203
448
<gh_stars>100-1000 #include "LibunwindWrapper.h" #include "Main.h" #include <stdio.h> #include <vector> using namespace std; LibunwindWrapper* wrapper; int main(int argc, char** argv) { if (argc != 3) { printf("2 arguments required.\r\n"); return 1; } printf("Launching with args %s,%s\r\n", argv[1], argv[2]); fflush(stdout); init(argv[1], argv[2]); printf("Threads: %d\r\n", getNumberOfThreads()); fflush(stdout); printf("Thread ID: %d\r\n", getThreadId()); fflush(stdout); printf("Auxv 15 (PLAT): %s\r\n", getAuxvString(15)); fflush(stdout); printf("Auxv 31 (EXEC): %s\r\n", getAuxvString(31)); fflush(stdout); return 0; } MYAPI void init(const char* filepath, const char* workingDir) { wrapper = new LibunwindWrapper(filepath, workingDir); } MYAPI void addBackingFileAtAddr(const char* filename, unsigned long address) { wrapper->addBackingFileAtAddr(filename, address); } MYAPI void addBackingFilesFromNotes() { wrapper->addBackingFilesFromNotes(); } MYAPI int getNumberOfThreads() { return wrapper->getNumberOfThreads(); } MYAPI int getThreadId() { return wrapper->getThreadId(); } MYAPI void selectThread(int threadNumber) { wrapper->selectThread(threadNumber); } MYAPI unsigned long getInstructionPointer() { return wrapper->getInstructionPointer(); } MYAPI unsigned long getStackPointer() { return wrapper->getStackPointer(); } MYAPI char* getProcedureName() { return wrapper->getProcedureName(); } MYAPI unsigned long getProcedureOffset() { return wrapper->getProcedureOffset(); } MYAPI bool step() { return wrapper->step(); } MYAPI unsigned long getAuxvValue(int type) { return wrapper->getAuxvValue(type); } MYAPI const char* getAuxvString(int type) { return wrapper->getAuxvString(type); } MYAPI int getSignalNumber(int thread_no) { return wrapper->getSignalNo(thread_no); } MYAPI int getSignalErrorNo(int thread_no) { return wrapper->getSignalErrorNo(thread_no); } MYAPI unsigned long getSignalAddress(int thread_no) { return wrapper->getSignalAddress(thread_no); } MYAPI const char* getFileName() { return wrapper->getFileName(); } MYAPI const char* getArgs() { return wrapper->getArgs(); } MYAPI int is64Bit() { return wrapper->is64Bit(); } MYAPI void destroy() { delete wrapper; }
832
1,144
<reponame>gokhanForesight/metasfresh package de.metas.invoicecandidate.api.impl.aggregationEngine; /* * #%L * de.metas.swat.base * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import ch.qos.logback.classic.Level; import de.metas.bpartner.BPartnerLocationId; import de.metas.bpartner.service.IBPartnerBL; import de.metas.bpartner.service.impl.BPartnerBL; import de.metas.business.BusinessTestHelper; import de.metas.greeting.GreetingRepository; import de.metas.inout.model.I_M_InOut; import de.metas.inout.model.I_M_InOutLine; import de.metas.invoicecandidate.AbstractICTestSupport; import de.metas.invoicecandidate.api.IInvoiceCandAggregate; import de.metas.invoicecandidate.api.IInvoiceHeader; import de.metas.invoicecandidate.api.IInvoiceLineRW; import de.metas.invoicecandidate.api.InvoiceCandidateInOutLineToUpdate; import de.metas.invoicecandidate.api.impl.AggregationEngine; import de.metas.invoicecandidate.model.I_C_ILCandHandler; import de.metas.invoicecandidate.model.I_C_InvoiceCandidate_InOutLine; import de.metas.invoicecandidate.model.I_C_Invoice_Candidate; import de.metas.invoicecandidate.spi.impl.ManualCandidateHandler; import de.metas.logging.LogManager; import de.metas.money.CurrencyId; import de.metas.pricing.PriceListVersionId; import de.metas.pricing.service.IPriceListDAO; import de.metas.quantity.StockQtyAndUOMQty; import de.metas.user.UserRepository; import de.metas.util.Services; import lombok.NonNull; import org.adempiere.ad.wrapper.POJOWrapper; import org.adempiere.model.InterfaceWrapperHelper; import org.adempiere.test.AdempiereTestWatcher; import org.compiere.SpringContextHolder; import org.compiere.model.I_C_BPartner; import org.compiere.model.I_C_BPartner_Location; import org.compiere.model.I_M_PriceList; import org.compiere.util.Env; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TestWatcher; import javax.annotation.OverridingMethodsMustInvokeSuper; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; import static org.hamcrest.Matchers.comparesEqualTo; import static org.hamcrest.Matchers.lessThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; public abstract class AbstractAggregationEngineTestBase extends AbstractICTestSupport { protected I_C_ILCandHandler manualHandler; @Rule public TestWatcher testWatchman = new AdempiereTestWatcher(); @Before @OverridingMethodsMustInvokeSuper public void init() { final Properties ctx = Env.getCtx(); Env.setContext(ctx, Env.CTXNAME_AD_Client_ID, 1); Env.setContext(ctx, Env.CTXNAME_AD_Language, "de_CH"); manualHandler = InterfaceWrapperHelper.newInstance(I_C_ILCandHandler.class); manualHandler.setTableName(ManualCandidateHandler.MANUAL); manualHandler.setClassname(ManualCandidateHandler.class.getName()); InterfaceWrapperHelper.save(manualHandler); // registerModelInterceptors(); doesn't work well with the legacy tests. Only register then in AbstractNewAggregationEngineTests LogManager.setLevel(Level.DEBUG); Services.registerService(IBPartnerBL.class, new BPartnerBL(new UserRepository())); SpringContextHolder.registerJUnitBean(new GreetingRepository()); } protected final List<IInvoiceLineRW> getInvoiceLines(final IInvoiceHeader invoice) { final List<IInvoiceLineRW> result = new ArrayList<>(); for (final IInvoiceCandAggregate lineAgg : invoice.getLines()) { result.addAll(lineAgg.getAllLines()); } return result; } protected final IInvoiceLineRW getInvoiceLineByCandidate(final IInvoiceHeader invoice, final I_C_Invoice_Candidate ic) { final List<IInvoiceLineRW> result = new ArrayList<>(); for (final IInvoiceCandAggregate lineAgg : invoice.getLines()) { result.addAll(lineAgg.getLinesForOrEmpty(ic)); } if (result.isEmpty()) { return null; } else if (result.size() > 1) { throw new IllegalStateException("Only one invoice line was expected for " + ic + ": " + result); } return result.get(0); } protected List<I_C_Invoice_Candidate> test_2StepShipment_CommonSetup_Step01( final boolean isSOTrx, final BigDecimal priceEntered_Override) { final I_C_BPartner bPartner = BusinessTestHelper.createBPartner("test-bp"); final I_C_BPartner_Location bPartnerLocation = BusinessTestHelper.createBPartnerLocation(bPartner); final BPartnerLocationId billBPartnerAndLocationId = BPartnerLocationId.ofRepoId(bPartnerLocation.getC_BPartner_ID(), bPartnerLocation.getC_BPartner_Location_ID()); return createInvoiceCandidate() .setInstanceName("ic") .setBillBPartnerAndLocationId(billBPartnerAndLocationId) .setPriceEntered(1) .setPriceEntered_Override(priceEntered_Override) .setQtyOrdered(40) .setDiscount(0) .setManual(false) .setSOTrx(isSOTrx) .setOrderDocNo("order1") .setOrderLineDescription("orderline1_1") .buildAsSigletonList(); } protected AggregationEngine test_2StepShipment_CommonSetup_Step02(final String invoiceRuleOverride, final I_C_Invoice_Candidate ic, final StockQtyAndUOMQty partialQty1, final StockQtyAndUOMQty partialQty2) { // // Partially invoice both at the same time final I_M_InOut inOut1; { final String inOutDocumentNo = "1"; inOut1 = createInOut(ic.getBill_BPartner_ID(), ic.getC_Order_ID(), inOutDocumentNo); // DocumentNo createInvoiceCandidateInOutLine(ic, inOut1, partialQty1, inOutDocumentNo); // inOutLineDescription completeInOut(inOut1); } final I_M_InOut inOut2; { final String inOutDocumentNo = "2"; inOut2 = createInOut(ic.getBill_BPartner_ID(), ic.getC_Order_ID(), inOutDocumentNo); // DocumentNo createInvoiceCandidateInOutLine(ic, inOut2, partialQty2, inOutDocumentNo); // inOutLineDescription completeInOut(inOut2); } ic.setInvoiceRule_Override(invoiceRuleOverride); InterfaceWrapperHelper.save(ic); updateInvalidCandidates(); InterfaceWrapperHelper.refresh(ic); // guard; this is tested more in-depth in InvoiceCandBLUpdateInvalidCandidatesTest final StockQtyAndUOMQty summedQty = partialQty1.add(partialQty2); assertThat("Invalid QtyToDeliver on the IC level", ic.getQtyDelivered(), comparesEqualTo(summedQty.getStockQty().toBigDecimal())); assertThat("Invalid QtyToInvoice on the IC level", ic.getQtyToInvoice(), comparesEqualTo(summedQty.getStockQty().toBigDecimal())); final AggregationEngine engine = AggregationEngine.newInstance(); engine.addInvoiceCandidate(ic); return engine; } protected final IInvoiceHeader removeInvoiceHeaderForInOutId(final List<IInvoiceHeader> invoices, final int inOutId) { final Iterator<IInvoiceHeader> it = invoices.iterator(); while (it.hasNext()) { final IInvoiceHeader invoice = it.next(); if (invoice.getM_InOut_ID() == inOutId) { it.remove(); return invoice; } } Assert.fail("No Invoice was found for M_InOut_ID=" + inOutId + " in " + invoices); return null; // shall not reach this point } protected final List<IInvoiceLineRW> getForInOutLine(final List<IInvoiceLineRW> invoiceLines, final I_M_InOutLine iol) { final ArrayList<IInvoiceLineRW> result = new ArrayList<>(); for (final IInvoiceLineRW il : invoiceLines) { for (final int icIolId : il.getC_InvoiceCandidate_InOutLine_IDs()) { final I_C_InvoiceCandidate_InOutLine icIol = InterfaceWrapperHelper.create( InterfaceWrapperHelper.getCtx(iol), icIolId, I_C_InvoiceCandidate_InOutLine.class, InterfaceWrapperHelper.getTrxName(iol)); if (icIol.getM_InOutLine_ID() == iol.getM_InOutLine_ID()) { result.add(il); } } } return result; } protected final IInvoiceLineRW getSingleForInOutLine(final List<IInvoiceLineRW> invoiceLines, final I_M_InOutLine iol) { final List<IInvoiceLineRW> result = getForInOutLine(invoiceLines, iol); assertThat(result.size(), lessThan(2)); if (result.isEmpty()) { return null; } return result.get(0); } protected final List<IInvoiceHeader> invokeAggregationEngine(@NonNull final AggregationEngine engine) { return engine.aggregate(); } public final void validateInvoiceHeader(final String message, final IInvoiceHeader invoice, final I_C_Invoice_Candidate fromIC) { final boolean invoiceReferencesOrder = true; validateInvoiceHeader(message, invoice, fromIC, invoiceReferencesOrder); } public final void validateInvoiceHeader(final String message, final IInvoiceHeader invoice, final I_C_Invoice_Candidate fromIC, final boolean invoiceReferencesOrder) { final IPriceListDAO priceListDAO = Services.get(IPriceListDAO.class); final String messagePrefix = message + " - IC=" + POJOWrapper.getInstanceName(fromIC); assertEquals(messagePrefix + " - Invalid AD_Org_ID", fromIC.getAD_Org_ID(), invoice.getOrgId().getRepoId()); if (fromIC.getM_PriceList_Version_ID() > 0) { final I_M_PriceList priceList = priceListDAO.getPriceListByPriceListVersionId(PriceListVersionId.ofRepoId(fromIC.getM_PriceList_Version_ID())); // if our IC had a M_PriceListVersion_ID, we want that PLV's M_PriceList to be in the invoice assertEquals(messagePrefix + " - Invalid M_PriceList_ID(", priceList.getM_PriceList_ID(), invoice.getM_PriceList_ID()); } assertEquals(messagePrefix + " - Invalid Bill_BPartner_ID", fromIC.getBill_BPartner_ID(), invoice.getBillTo().getBpartnerId().getRepoId()); assertEquals(messagePrefix + " - Invalid Bill_Location_ID", fromIC.getBill_Location_ID(), invoice.getBillTo().getBpartnerLocationId().getRepoId()); // task 08241: we want to aggregate candidates with different Bill_User_IDs into one invoice // this commented-out check is synchronized with ICHeaderAggregationKeyValueHandler // assertEquals(messagePrefix + " - Invalid Bill_User_ID", fromIC.getBill_User_ID(), invoice.getBill_User_ID()); assertEquals(messagePrefix + " - Invalid C_Currency_ID", fromIC.getC_Currency_ID(), CurrencyId.toRepoId(invoice.getCurrencyId())); if (invoiceReferencesOrder) { assertEquals(messagePrefix + " - Invalid C_Order_ID", fromIC.getC_Order_ID(), invoice.getC_Order_ID()); } assertEquals(messagePrefix + " - Invalid isSOTrx", fromIC.isSOTrx(), invoice.isSOTrx()); } protected InvoiceCandidateInOutLineToUpdate retrieveIcIolToUpdateIfExists(final IInvoiceLineRW invoiceLineRW, final I_M_InOutLine iol) { for (final InvoiceCandidateInOutLineToUpdate icIolToUpdate : invoiceLineRW.getInvoiceCandidateInOutLinesToUpdate()) { if (iol.equals(icIolToUpdate.getC_InvoiceCandidate_InOutLine().getM_InOutLine())) { return icIolToUpdate; } } return null; } }
4,059
416
package org.simpleflatmapper.reflect.asm; import org.simpleflatmapper.ow2asm.ClassWriter; import org.simpleflatmapper.ow2asm.MethodVisitor; import org.simpleflatmapper.reflect.Instantiator; import static org.simpleflatmapper.ow2asm.Opcodes.ACC_BRIDGE; import static org.simpleflatmapper.ow2asm.Opcodes.ACC_FINAL; import static org.simpleflatmapper.ow2asm.Opcodes.ACC_PUBLIC; import static org.simpleflatmapper.ow2asm.Opcodes.ACC_SUPER; import static org.simpleflatmapper.ow2asm.Opcodes.ACC_SYNTHETIC; import static org.simpleflatmapper.ow2asm.Opcodes.ALOAD; import static org.simpleflatmapper.ow2asm.Opcodes.ARETURN; import static org.simpleflatmapper.ow2asm.Opcodes.CHECKCAST; import static org.simpleflatmapper.ow2asm.Opcodes.DUP; import static org.simpleflatmapper.ow2asm.Opcodes.INVOKESPECIAL; import static org.simpleflatmapper.ow2asm.Opcodes.INVOKEVIRTUAL; import static org.simpleflatmapper.ow2asm.Opcodes.NEW; import static org.simpleflatmapper.ow2asm.Opcodes.RETURN; import static org.simpleflatmapper.ow2asm.Opcodes.V1_6; public class ConstructorBuilder { public static byte[] createEmptyConstructor(final String className, final Class<?> sourceClass, final Class<?> targetClass) throws Exception { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); MethodVisitor mv; String targetType = AsmUtils.toAsmType(targetClass); String sourceType = AsmUtils.toAsmType(sourceClass); String classType = AsmUtils.toAsmType(className); String instantiatorType = AsmUtils.toAsmType(Instantiator.class); cw.visit(V1_6, ACC_PUBLIC + ACC_FINAL + ACC_SUPER, classType, "Ljava/lang/Object;L" + instantiatorType + "<L" + targetType + ";>;", "java/lang/Object", new String[] { instantiatorType }); { mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv.visitInsn(RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC, "newInstance", "(L" + sourceType + ";)L" + targetType + ";", null, new String[] { "java/lang/Exception" }); mv.visitCode(); mv.visitTypeInsn(NEW, targetType); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, targetType, "<init>", "()V", false); mv.visitInsn(ARETURN); mv.visitMaxs(2, 2); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC + ACC_BRIDGE + ACC_SYNTHETIC, "newInstance", "(Ljava/lang/Object;)Ljava/lang/Object;", null, new String[] { "java/lang/Exception" }); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, sourceType); mv.visitMethodInsn(INVOKEVIRTUAL, classType, "newInstance", "(L" + sourceType + ";)L" + targetType + ";", false); mv.visitInsn(ARETURN); mv.visitMaxs(2, 2); mv.visitEnd(); } cw.visitEnd(); return AsmUtils.writeClassToFile(className, cw.toByteArray()); } }
1,279
369
/** @file @brief Header @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef INCLUDED_ViewerEye_h_GUID_B895D9B8_5FF1_4991_D174_4AF145F83172 #define INCLUDED_ViewerEye_h_GUID_B895D9B8_5FF1_4991_D174_4AF145F83172 // Internal Includes #include <osvr/Util/ClientOpaqueTypesC.h> #include <osvr/Util/RenderingTypesC.h> #include <osvr/Client/Export.h> #include <osvr/Client/InternalInterfaceOwner.h> #include <osvr/Util/Pose3C.h> #include <osvr/Util/EigenCoreGeometry.h> #include <osvr/Util/Rect.h> #include <osvr/Util/MatrixConventionsC.h> #include <osvr/Util/RadialDistortionParametersC.h> #include <osvr/Util/Angles.h> // Library/third-party includes #include <boost/optional.hpp> // Standard includes #include <vector> #include <stdexcept> #include <utility> namespace osvr { namespace client { class DisplayConfigFactory; struct Viewport { int32_t left; int32_t bottom; int32_t width; int32_t height; }; struct NoPoseYet : std::runtime_error { NoPoseYet() : std::runtime_error("No pose data yet for the interface!") {} }; class ViewerEye { public: ViewerEye(ViewerEye const &) = delete; ViewerEye &operator=(ViewerEye const &) = delete; ViewerEye(ViewerEye &&other) : m_pose(std::move(other.m_pose)), m_offset(other.m_offset), m_viewport(other.m_viewport), m_unitBounds(std::move(other.m_unitBounds)), m_rot180(other.m_rot180), m_pitchTilt(other.m_pitchTilt), m_radDistortParams(std::move(other.m_radDistortParams)), m_displayInputIdx(other.m_displayInputIdx), m_opticalAxisOffsetY(other.m_opticalAxisOffsetY) {} inline OSVR_SurfaceCount size() const { return 1; } #if 0 inline OSVR_SurfaceCount size() const { return static_cast<OSVR_SurfaceCount>(m_surfaces.size()); } inline ViewerEyeSurface &operator[](OSVR_SurfaceCount index) { return m_surfaces[index]; } inline ViewerEyeSurface const & operator[](OSVR_SurfaceCount index) const { return m_surfaces[index]; } #endif OSVR_CLIENT_EXPORT OSVR_Pose3 getPose() const; OSVR_CLIENT_EXPORT bool hasPose() const; OSVR_CLIENT_EXPORT Eigen::Matrix4d getView() const; bool wantDistortion() const { return m_radDistortParams.is_initialized(); } boost::optional<OSVR_RadialDistortionParameters> getRadialDistortionParams() const { return m_radDistortParams; } OSVR_DistortionPriority getRadialDistortionPriority() const { return (m_radDistortParams.is_initialized()) ? 1 : OSVR_DISTORTION_PRIORITY_UNAVAILABLE; } /// @brief Gets a matrix that takes in row vectors in a right-handed /// system and outputs signed Z. OSVR_CLIENT_EXPORT Eigen::Matrix4d getProjection(double near, double far) const; OSVR_CLIENT_EXPORT Eigen::Matrix4d getProjection(double near, double far, OSVR_MatrixConventions flags) const; /// @brief Gets clipping planes for a given surface OSVR_CLIENT_EXPORT util::Rectd getRect() const; Viewport getDisplayRelativeViewport() const { return m_viewport; } OSVR_DisplayInputCount getDisplayInputIdx() const { return m_displayInputIdx; } private: friend class DisplayConfigFactory; ViewerEye( OSVR_ClientContext ctx, Eigen::Vector3d const &offset, const char path[], Viewport &&viewport, util::Rectd &&unitBounds, bool rot180, double pitchTilt, boost::optional<OSVR_RadialDistortionParameters> radDistortParams, OSVR_DisplayInputCount displayInputIdx, util::Angle opticalAxisOffsetY = 0. * util::radians); util::Rectd m_getRect(double near, double far) const; Eigen::Isometry3d getPoseIsometry() const; InternalInterfaceOwner m_pose; Eigen::Vector3d m_offset; #if 0 std::vector<ViewerEyeSurface> m_surfaces; #endif Viewport m_viewport; util::Rectd m_unitBounds; bool m_rot180; double m_pitchTilt; boost::optional<OSVR_RadialDistortionParameters> m_radDistortParams; OSVR_DisplayInputCount m_displayInputIdx; util::Angle m_opticalAxisOffsetY; }; } // namespace client } // namespace osvr #endif // INCLUDED_ViewerEye_h_GUID_B895D9B8_5FF1_4991_D174_4AF145F83172
2,337