hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
01ec627dc040bd90fba63f91fa950bc4f4cc8f2e | 77,528 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.android.gms.internal.ads;
import android.media.MediaCodecInfo;
import android.util.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// Referenced classes of package com.google.android.gms.internal.ads:
// bhm, bht, bhw, bnw,
// bhv, bhy, bhx
public final class bhs
{
public static Pair a(String s)
{
byte byte0;
byte byte1;
String as[];
label0:
{
if(s == null)
//* 0 0:aload_0
//* 1 1:ifnonnull 6
return null;
// 2 4:aconst_null
// 3 5:areturn
as = s.split("\\.");
// 4 6:aload_0
// 5 7:ldc1 #143 <String "\\.">
// 6 9:invokevirtual #149 <Method String[] String.split(String)>
// 7 12:astore 4
byte0 = 0;
// 8 14:iconst_0
// 9 15:istore_1
String s1 = as[0];
// 10 16:aload 4
// 11 18:iconst_0
// 12 19:aaload
// 13 20:astore 5
int i = s1.hashCode();
// 14 22:aload 5
// 15 24:invokevirtual #153 <Method int String.hashCode()>
// 16 27:istore_3
byte1 = 2;
// 17 28:iconst_2
// 18 29:istore_2
switch(i)
//* 19 30:iload_3
{
default:
break;
//* 20 31:lookupswitch 4: default 72
// 3006243: 118
// 3006244: 103
// 3199032: 90
// 3214780: 75
//* 21 72:goto 133
case 3214780:
if(!s1.equals("hvc1"))
break;
// 22 75:aload 5
// 23 77:ldc1 #155 <String "hvc1">
// 24 79:invokevirtual #159 <Method boolean String.equals(Object)>
// 25 82:ifeq 133
byte0 = 1;
// 26 85:iconst_1
// 27 86:istore_1
break label0;
// 28 87:goto 135
case 3199032:
if(!s1.equals("hev1"))
//* 29 90:aload 5
//* 30 92:ldc1 #161 <String "hev1">
//* 31 94:invokevirtual #159 <Method boolean String.equals(Object)>
//* 32 97:ifeq 133
break;
// 33 100:goto 135
break label0;
case 3006244:
if(!s1.equals("avc2"))
break;
// 34 103:aload 5
// 35 105:ldc1 #163 <String "avc2">
// 36 107:invokevirtual #159 <Method boolean String.equals(Object)>
// 37 110:ifeq 133
byte0 = 3;
// 38 113:iconst_3
// 39 114:istore_1
break label0;
// 40 115:goto 135
case 3006243:
if(!s1.equals("avc1"))
break;
// 41 118:aload 5
// 42 120:ldc1 #165 <String "avc1">
// 43 122:invokevirtual #159 <Method boolean String.equals(Object)>
// 44 125:ifeq 133
byte0 = 2;
// 45 128:iconst_2
// 46 129:istore_1
break label0;
// 47 130:goto 135
}
byte0 = -1;
// 48 133:iconst_m1
// 49 134:istore_1
}
label1:
{
switch(byte0)
//* 50 135:iload_1
{
//* 51 136:tableswitch 0 3: default 168
// 0 177
// 1 177
// 2 170
// 3 170
default:
return null;
// 52 168:aconst_null
// 53 169:areturn
case 2: // '\002'
case 3: // '\003'
return a(s, as);
// 54 170:aload_0
// 55 171:aload 4
// 56 173:invokestatic #168 <Method Pair a(String, String[])>
// 57 176:areturn
case 0: // '\0'
case 1: // '\001'
break;
}
if(as.length < 4)
//* 58 177:aload 4
//* 59 179:arraylength
//* 60 180:iconst_4
//* 61 181:icmpge 225
{
s = String.valueOf(((Object) (s)));
// 62 184:aload_0
// 63 185:invokestatic #171 <Method String String.valueOf(Object)>
// 64 188:astore_0
if(s.length() != 0)
//* 65 189:aload_0
//* 66 190:invokevirtual #174 <Method int String.length()>
//* 67 193:ifeq 206
s = "Ignoring malformed HEVC codec string: ".concat(s);
// 68 196:ldc1 #176 <String "Ignoring malformed HEVC codec string: ">
// 69 198:aload_0
// 70 199:invokevirtual #180 <Method String String.concat(String)>
// 71 202:astore_0
else
//* 72 203:goto 216
s = new String("Ignoring malformed HEVC codec string: ");
// 73 206:new #145 <Class String>
// 74 209:dup
// 75 210:ldc1 #176 <String "Ignoring malformed HEVC codec string: ">
// 76 212:invokespecial #183 <Method void String(String)>
// 77 215:astore_0
Log.w("MediaCodecUtil", s);
// 78 216:ldc1 #185 <String "MediaCodecUtil">
// 79 218:aload_0
// 80 219:invokestatic #191 <Method int Log.w(String, String)>
// 81 222:pop
return null;
// 82 223:aconst_null
// 83 224:areturn
}
Matcher matcher = b.matcher(((CharSequence) (as[1])));
// 84 225:getstatic #43 <Field Pattern b>
// 85 228:aload 4
// 86 230:iconst_1
// 87 231:aaload
// 88 232:invokevirtual #195 <Method Matcher Pattern.matcher(CharSequence)>
// 89 235:astore 5
if(!matcher.matches())
//* 90 237:aload 5
//* 91 239:invokevirtual #201 <Method boolean Matcher.matches()>
//* 92 242:ifne 286
{
s = String.valueOf(((Object) (s)));
// 93 245:aload_0
// 94 246:invokestatic #171 <Method String String.valueOf(Object)>
// 95 249:astore_0
if(s.length() != 0)
//* 96 250:aload_0
//* 97 251:invokevirtual #174 <Method int String.length()>
//* 98 254:ifeq 267
s = "Ignoring malformed HEVC codec string: ".concat(s);
// 99 257:ldc1 #176 <String "Ignoring malformed HEVC codec string: ">
// 100 259:aload_0
// 101 260:invokevirtual #180 <Method String String.concat(String)>
// 102 263:astore_0
else
//* 103 264:goto 277
s = new String("Ignoring malformed HEVC codec string: ");
// 104 267:new #145 <Class String>
// 105 270:dup
// 106 271:ldc1 #176 <String "Ignoring malformed HEVC codec string: ">
// 107 273:invokespecial #183 <Method void String(String)>
// 108 276:astore_0
Log.w("MediaCodecUtil", s);
// 109 277:ldc1 #185 <String "MediaCodecUtil">
// 110 279:aload_0
// 111 280:invokestatic #191 <Method int Log.w(String, String)>
// 112 283:pop
return null;
// 113 284:aconst_null
// 114 285:areturn
}
s = matcher.group(1);
// 115 286:aload 5
// 116 288:iconst_1
// 117 289:invokevirtual #205 <Method String Matcher.group(int)>
// 118 292:astore_0
if("1".equals(((Object) (s))))
//* 119 293:ldc1 #207 <String "1">
//* 120 295:aload_0
//* 121 296:invokevirtual #159 <Method boolean String.equals(Object)>
//* 122 299:ifeq 307
{
byte0 = 1;
// 123 302:iconst_1
// 124 303:istore_1
} else
//* 125 304:goto 318
{
if(!"2".equals(((Object) (s))))
break label1;
// 126 307:ldc1 #209 <String "2">
// 127 309:aload_0
// 128 310:invokevirtual #159 <Method boolean String.equals(Object)>
// 129 313:ifeq 397
byte0 = byte1;
// 130 316:iload_2
// 131 317:istore_1
}
s = ((String) ((Integer)f.get(((Object) (as[3])))));
// 132 318:getstatic #67 <Field Map f>
// 133 321:aload 4
// 134 323:iconst_3
// 135 324:aaload
// 136 325:invokeinterface #213 <Method Object Map.get(Object)>
// 137 330:checkcast #71 <Class Integer>
// 138 333:astore_0
if(s == null)
//* 139 334:aload_0
//* 140 335:ifnonnull 384
{
s = String.valueOf(((Object) (matcher.group(1))));
// 141 338:aload 5
// 142 340:iconst_1
// 143 341:invokevirtual #205 <Method String Matcher.group(int)>
// 144 344:invokestatic #171 <Method String String.valueOf(Object)>
// 145 347:astore_0
if(s.length() != 0)
//* 146 348:aload_0
//* 147 349:invokevirtual #174 <Method int String.length()>
//* 148 352:ifeq 365
s = "Unknown HEVC level string: ".concat(s);
// 149 355:ldc1 #215 <String "Unknown HEVC level string: ">
// 150 357:aload_0
// 151 358:invokevirtual #180 <Method String String.concat(String)>
// 152 361:astore_0
else
//* 153 362:goto 375
s = new String("Unknown HEVC level string: ");
// 154 365:new #145 <Class String>
// 155 368:dup
// 156 369:ldc1 #215 <String "Unknown HEVC level string: ">
// 157 371:invokespecial #183 <Method void String(String)>
// 158 374:astore_0
Log.w("MediaCodecUtil", s);
// 159 375:ldc1 #185 <String "MediaCodecUtil">
// 160 377:aload_0
// 161 378:invokestatic #191 <Method int Log.w(String, String)>
// 162 381:pop
return null;
// 163 382:aconst_null
// 164 383:areturn
} else
{
return new Pair(((Object) (Integer.valueOf(((int) (byte0))))), ((Object) (s)));
// 165 384:new #217 <Class Pair>
// 166 387:dup
// 167 388:iload_1
// 168 389:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 169 392:aload_0
// 170 393:invokespecial #220 <Method void Pair(Object, Object)>
// 171 396:areturn
}
}
s = String.valueOf(((Object) (s)));
// 172 397:aload_0
// 173 398:invokestatic #171 <Method String String.valueOf(Object)>
// 174 401:astore_0
if(s.length() != 0)
//* 175 402:aload_0
//* 176 403:invokevirtual #174 <Method int String.length()>
//* 177 406:ifeq 419
s = "Unknown HEVC profile string: ".concat(s);
// 178 409:ldc1 #222 <String "Unknown HEVC profile string: ">
// 179 411:aload_0
// 180 412:invokevirtual #180 <Method String String.concat(String)>
// 181 415:astore_0
else
//* 182 416:goto 429
s = new String("Unknown HEVC profile string: ");
// 183 419:new #145 <Class String>
// 184 422:dup
// 185 423:ldc1 #222 <String "Unknown HEVC profile string: ">
// 186 425:invokespecial #183 <Method void String(String)>
// 187 428:astore_0
Log.w("MediaCodecUtil", s);
// 188 429:ldc1 #185 <String "MediaCodecUtil">
// 189 431:aload_0
// 190 432:invokestatic #191 <Method int Log.w(String, String)>
// 191 435:pop
return null;
// 192 436:aconst_null
// 193 437:areturn
}
private static Pair a(String s, String as[])
{
if(as.length < 2)
//* 0 0:aload_1
//* 1 1:arraylength
//* 2 2:iconst_2
//* 3 3:icmpge 47
{
s = String.valueOf(((Object) (s)));
// 4 6:aload_0
// 5 7:invokestatic #171 <Method String String.valueOf(Object)>
// 6 10:astore_0
if(s.length() != 0)
//* 7 11:aload_0
//* 8 12:invokevirtual #174 <Method int String.length()>
//* 9 15:ifeq 28
s = "Ignoring malformed AVC codec string: ".concat(s);
// 10 18:ldc1 #226 <String "Ignoring malformed AVC codec string: ">
// 11 20:aload_0
// 12 21:invokevirtual #180 <Method String String.concat(String)>
// 13 24:astore_0
else
//* 14 25:goto 38
s = new String("Ignoring malformed AVC codec string: ");
// 15 28:new #145 <Class String>
// 16 31:dup
// 17 32:ldc1 #226 <String "Ignoring malformed AVC codec string: ">
// 18 34:invokespecial #183 <Method void String(String)>
// 19 37:astore_0
Log.w("MediaCodecUtil", s);
// 20 38:ldc1 #185 <String "MediaCodecUtil">
// 21 40:aload_0
// 22 41:invokestatic #191 <Method int Log.w(String, String)>
// 23 44:pop
return null;
// 24 45:aconst_null
// 25 46:areturn
}
Integer integer;
if(as[1].length() != 6)
break MISSING_BLOCK_LABEL_98;
// 26 47:aload_1
// 27 48:iconst_1
// 28 49:aaload
// 29 50:invokevirtual #174 <Method int String.length()>
// 30 53:bipush 6
// 31 55:icmpne 98
int i = Integer.parseInt(as[1].substring(0, 2), 16);
// 32 58:aload_1
// 33 59:iconst_1
// 34 60:aaload
// 35 61:iconst_0
// 36 62:iconst_2
// 37 63:invokevirtual #230 <Method String String.substring(int, int)>
// 38 66:bipush 16
// 39 68:invokestatic #234 <Method int Integer.parseInt(String, int)>
// 40 71:istore_2
integer = Integer.valueOf(Integer.parseInt(as[1].substring(4), 16));
// 41 72:aload_1
// 42 73:iconst_1
// 43 74:aaload
// 44 75:iconst_4
// 45 76:invokevirtual #236 <Method String String.substring(int)>
// 46 79:bipush 16
// 47 81:invokestatic #234 <Method int Integer.parseInt(String, int)>
// 48 84:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 49 87:astore_3
as = ((String []) (Integer.valueOf(i)));
// 50 88:iload_2
// 51 89:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 52 92:astore_1
s = ((String) (integer));
// 53 93:aload_3
// 54 94:astore_0
break MISSING_BLOCK_LABEL_128;
// 55 95:goto 128
if(as.length < 3)
break MISSING_BLOCK_LABEL_271;
// 56 98:aload_1
// 57 99:arraylength
// 58 100:iconst_3
// 59 101:icmplt 271
integer = Integer.valueOf(Integer.parseInt(as[1]));
// 60 104:aload_1
// 61 105:iconst_1
// 62 106:aaload
// 63 107:invokestatic #239 <Method int Integer.parseInt(String)>
// 64 110:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 65 113:astore_3
as = ((String []) (Integer.valueOf(Integer.parseInt(as[2]))));
// 66 114:aload_1
// 67 115:iconst_2
// 68 116:aaload
// 69 117:invokestatic #239 <Method int Integer.parseInt(String)>
// 70 120:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 71 123:astore_1
s = ((String) (as));
// 72 124:aload_1
// 73 125:astore_0
as = ((String []) (integer));
// 74 126:aload_3
// 75 127:astore_1
Integer integer1 = Integer.valueOf(d.get(((Integer) (as)).intValue()));
// 76 128:getstatic #57 <Field SparseIntArray d>
// 77 131:aload_1
// 78 132:invokevirtual #242 <Method int Integer.intValue()>
// 79 135:invokevirtual #245 <Method int SparseIntArray.get(int)>
// 80 138:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 81 141:astore_3
if(integer1 == null)
//* 82 142:aload_3
//* 83 143:ifnonnull 194
{
s = String.valueOf(((Object) (as)));
// 84 146:aload_1
// 85 147:invokestatic #171 <Method String String.valueOf(Object)>
// 86 150:astore_0
as = ((String []) (new StringBuilder(String.valueOf(((Object) (s))).length() + 21)));
// 87 151:new #247 <Class StringBuilder>
// 88 154:dup
// 89 155:aload_0
// 90 156:invokestatic #171 <Method String String.valueOf(Object)>
// 91 159:invokevirtual #174 <Method int String.length()>
// 92 162:bipush 21
// 93 164:iadd
// 94 165:invokespecial #250 <Method void StringBuilder(int)>
// 95 168:astore_1
((StringBuilder) (as)).append("Unknown AVC profile: ");
// 96 169:aload_1
// 97 170:ldc1 #252 <String "Unknown AVC profile: ">
// 98 172:invokevirtual #256 <Method StringBuilder StringBuilder.append(String)>
// 99 175:pop
((StringBuilder) (as)).append(s);
// 100 176:aload_1
// 101 177:aload_0
// 102 178:invokevirtual #256 <Method StringBuilder StringBuilder.append(String)>
// 103 181:pop
Log.w("MediaCodecUtil", ((StringBuilder) (as)).toString());
// 104 182:ldc1 #185 <String "MediaCodecUtil">
// 105 184:aload_1
// 106 185:invokevirtual #260 <Method String StringBuilder.toString()>
// 107 188:invokestatic #191 <Method int Log.w(String, String)>
// 108 191:pop
return null;
// 109 192:aconst_null
// 110 193:areturn
}
as = ((String []) (Integer.valueOf(e.get(((Integer) (s)).intValue()))));
// 111 194:getstatic #63 <Field SparseIntArray e>
// 112 197:aload_0
// 113 198:invokevirtual #242 <Method int Integer.intValue()>
// 114 201:invokevirtual #245 <Method int SparseIntArray.get(int)>
// 115 204:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 116 207:astore_1
if(as == null)
//* 117 208:aload_1
//* 118 209:ifnonnull 261
{
s = String.valueOf(((Object) (s)));
// 119 212:aload_0
// 120 213:invokestatic #171 <Method String String.valueOf(Object)>
// 121 216:astore_0
as = ((String []) (new StringBuilder(String.valueOf(((Object) (s))).length() + 19)));
// 122 217:new #247 <Class StringBuilder>
// 123 220:dup
// 124 221:aload_0
// 125 222:invokestatic #171 <Method String String.valueOf(Object)>
// 126 225:invokevirtual #174 <Method int String.length()>
// 127 228:bipush 19
// 128 230:iadd
// 129 231:invokespecial #250 <Method void StringBuilder(int)>
// 130 234:astore_1
((StringBuilder) (as)).append("Unknown AVC level: ");
// 131 235:aload_1
// 132 236:ldc2 #262 <String "Unknown AVC level: ">
// 133 239:invokevirtual #256 <Method StringBuilder StringBuilder.append(String)>
// 134 242:pop
((StringBuilder) (as)).append(s);
// 135 243:aload_1
// 136 244:aload_0
// 137 245:invokevirtual #256 <Method StringBuilder StringBuilder.append(String)>
// 138 248:pop
Log.w("MediaCodecUtil", ((StringBuilder) (as)).toString());
// 139 249:ldc1 #185 <String "MediaCodecUtil">
// 140 251:aload_1
// 141 252:invokevirtual #260 <Method String StringBuilder.toString()>
// 142 255:invokestatic #191 <Method int Log.w(String, String)>
// 143 258:pop
return null;
// 144 259:aconst_null
// 145 260:areturn
} else
{
return new Pair(((Object) (integer1)), ((Object) (as)));
// 146 261:new #217 <Class Pair>
// 147 264:dup
// 148 265:aload_3
// 149 266:aload_1
// 150 267:invokespecial #220 <Method void Pair(Object, Object)>
// 151 270:areturn
}
try
{
as = ((String []) (String.valueOf(((Object) (s)))));
// 152 271:aload_0
// 153 272:invokestatic #171 <Method String String.valueOf(Object)>
// 154 275:astore_1
if(((String) (as)).length() != 0)
//* 155 276:aload_1
//* 156 277:invokevirtual #174 <Method int String.length()>
//* 157 280:ifeq 293
{
as = ((String []) ("Ignoring malformed AVC codec string: ".concat(((String) (as)))));
// 158 283:ldc1 #226 <String "Ignoring malformed AVC codec string: ">
// 159 285:aload_1
// 160 286:invokevirtual #180 <Method String String.concat(String)>
// 161 289:astore_1
break MISSING_BLOCK_LABEL_303;
// 162 290:goto 303
}
}
//* 163 293:new #145 <Class String>
//* 164 296:dup
//* 165 297:ldc1 #226 <String "Ignoring malformed AVC codec string: ">
//* 166 299:invokespecial #183 <Method void String(String)>
//* 167 302:astore_1
//* 168 303:ldc1 #185 <String "MediaCodecUtil">
//* 169 305:aload_1
//* 170 306:invokestatic #191 <Method int Log.w(String, String)>
//* 171 309:pop
//* 172 310:aconst_null
//* 173 311:areturn
//* 174 312:aload_0
//* 175 313:invokestatic #171 <Method String String.valueOf(Object)>
//* 176 316:astore_0
//* 177 317:aload_0
//* 178 318:invokevirtual #174 <Method int String.length()>
//* 179 321:ifeq 334
//* 180 324:ldc1 #226 <String "Ignoring malformed AVC codec string: ">
//* 181 326:aload_0
//* 182 327:invokevirtual #180 <Method String String.concat(String)>
//* 183 330:astore_0
//* 184 331:goto 344
//* 185 334:new #145 <Class String>
//* 186 337:dup
//* 187 338:ldc1 #226 <String "Ignoring malformed AVC codec string: ">
//* 188 340:invokespecial #183 <Method void String(String)>
//* 189 343:astore_0
//* 190 344:ldc1 #185 <String "MediaCodecUtil">
//* 191 346:aload_0
//* 192 347:invokestatic #191 <Method int Log.w(String, String)>
//* 193 350:pop
//* 194 351:aconst_null
//* 195 352:areturn
// Misplaced declaration of an exception variable
catch(String as[])
{
s = String.valueOf(((Object) (s)));
if(s.length() != 0)
s = "Ignoring malformed AVC codec string: ".concat(s);
else
s = new String("Ignoring malformed AVC codec string: ");
Log.w("MediaCodecUtil", s);
return null;
}
as = ((String []) (new String("Ignoring malformed AVC codec string: ")));
Log.w("MediaCodecUtil", ((String) (as)));
return null;
//* 196 353:astore_1
//* 197 354:goto 312
}
public static bhm a()
{
return a;
// 0 0:getstatic #33 <Field bhm a>
// 1 3:areturn
}
public static bhm a(String s, boolean flag)
{
s = ((String) (b(s, flag)));
// 0 0:aload_0
// 1 1:iload_1
// 2 2:invokestatic #267 <Method List b(String, boolean)>
// 3 5:astore_0
if(((List) (s)).isEmpty())
//* 4 6:aload_0
//* 5 7:invokeinterface #272 <Method boolean List.isEmpty()>
//* 6 12:ifeq 17
return null;
// 7 15:aconst_null
// 8 16:areturn
else
return (bhm)((List) (s)).get(0);
// 9 17:aload_0
// 10 18:iconst_0
// 11 19:invokeinterface #275 <Method Object List.get(int)>
// 12 24:checkcast #28 <Class bhm>
// 13 27:areturn
}
private static List a(bht bht1, bhw bhw1)
{
int i;
int j;
int k;
int l;
boolean flag;
boolean flag2;
boolean flag3;
android.media.MediaCodecInfo.CodecCapabilities codeccapabilities;
Object obj;
String s;
ArrayList arraylist;
String s1;
MediaCodecInfo mediacodecinfo;
String as[];
String s2;
String s3;
try
{
arraylist = new ArrayList();
// 0 0:new #280 <Class ArrayList>
// 1 3:dup
// 2 4:invokespecial #281 <Method void ArrayList()>
// 3 7:astore 11
s1 = bht1.a;
// 4 9:aload_0
// 5 10:getfield #286 <Field String bht.a>
// 6 13:astore 12
k = bhw1.a();
// 7 15:aload_1
// 8 16:invokeinterface #290 <Method int bhw.a()>
// 9 21:istore 4
flag2 = bhw1.b();
// 10 23:aload_1
// 11 24:invokeinterface #292 <Method boolean bhw.b()>
// 12 29:istore 7
}
//* 13 31:iconst_0
//* 14 32:istore_3
//* 15 33:iload_3
//* 16 34:iload 4
//* 17 36:icmpge 989
//* 18 39:aload_1
//* 19 40:iload_3
//* 20 41:invokeinterface #295 <Method MediaCodecInfo bhw.a(int)>
//* 21 46:astore 13
//* 22 48:aload 13
//* 23 50:invokevirtual #300 <Method String MediaCodecInfo.getName()>
//* 24 53:astore 10
//* 25 55:aload 13
//* 26 57:invokevirtual #303 <Method boolean MediaCodecInfo.isEncoder()>
//* 27 60:ifne 1028
//* 28 63:iload 7
//* 29 65:ifne 82
//* 30 68:aload 10
//* 31 70:ldc2 #305 <String ".secure">
//* 32 73:invokevirtual #309 <Method boolean String.endsWith(String)>
//* 33 76:ifeq 82
//* 34 79:goto 1028
//* 35 82:getstatic #313 <Field int bnw.a>
//* 36 85:bipush 21
//* 37 87:icmpge 159
//* 38 90:ldc2 #315 <String "CIPAACDecoder">
//* 39 93:aload 10
//* 40 95:invokevirtual #159 <Method boolean String.equals(Object)>
//* 41 98:ifne 1003
//* 42 101:ldc2 #317 <String "CIPMP3Decoder">
//* 43 104:aload 10
//* 44 106:invokevirtual #159 <Method boolean String.equals(Object)>
//* 45 109:ifne 1003
//* 46 112:ldc2 #319 <String "CIPVorbisDecoder">
//* 47 115:aload 10
//* 48 117:invokevirtual #159 <Method boolean String.equals(Object)>
//* 49 120:ifne 1003
//* 50 123:ldc2 #321 <String "CIPAMRNBDecoder">
//* 51 126:aload 10
//* 52 128:invokevirtual #159 <Method boolean String.equals(Object)>
//* 53 131:ifne 1003
//* 54 134:ldc2 #323 <String "AACDecoder">
//* 55 137:aload 10
//* 56 139:invokevirtual #159 <Method boolean String.equals(Object)>
//* 57 142:ifne 1003
//* 58 145:ldc2 #325 <String "MP3Decoder">
//* 59 148:aload 10
//* 60 150:invokevirtual #159 <Method boolean String.equals(Object)>
//* 61 153:ifeq 159
//* 62 156:goto 1003
//* 63 159:getstatic #313 <Field int bnw.a>
//* 64 162:bipush 18
//* 65 164:icmpge 183
//* 66 167:ldc2 #327 <String "OMX.SEC.MP3.Decoder">
//* 67 170:aload 10
//* 68 172:invokevirtual #159 <Method boolean String.equals(Object)>
//* 69 175:ifeq 183
//* 70 178:iconst_0
//* 71 179:istore_2
//* 72 180:goto 585
//* 73 183:getstatic #313 <Field int bnw.a>
//* 74 186:bipush 18
//* 75 188:icmpge 219
//* 76 191:ldc2 #329 <String "OMX.MTK.AUDIO.DECODER.AAC">
//* 77 194:aload 10
//* 78 196:invokevirtual #159 <Method boolean String.equals(Object)>
//* 79 199:ifeq 219
//* 80 202:ldc2 #331 <String "a70">
//* 81 205:getstatic #333 <Field String bnw.b>
//* 82 208:invokevirtual #159 <Method boolean String.equals(Object)>
//* 83 211:ifeq 219
//* 84 214:iconst_0
//* 85 215:istore_2
//* 86 216:goto 585
//* 87 219:getstatic #313 <Field int bnw.a>
//* 88 222:bipush 16
//* 89 224:icmpne 385
//* 90 227:ldc2 #335 <String "OMX.qcom.audio.decoder.mp3">
//* 91 230:aload 10
//* 92 232:invokevirtual #159 <Method boolean String.equals(Object)>
//* 93 235:ifeq 385
//* 94 238:ldc2 #337 <String "dlxu">
//* 95 241:getstatic #333 <Field String bnw.b>
//* 96 244:invokevirtual #159 <Method boolean String.equals(Object)>
//* 97 247:ifne 1008
//* 98 250:ldc2 #339 <String "protou">
//* 99 253:getstatic #333 <Field String bnw.b>
//* 100 256:invokevirtual #159 <Method boolean String.equals(Object)>
//* 101 259:ifne 1008
//* 102 262:ldc2 #341 <String "ville">
//* 103 265:getstatic #333 <Field String bnw.b>
//* 104 268:invokevirtual #159 <Method boolean String.equals(Object)>
//* 105 271:ifne 1008
//* 106 274:ldc2 #343 <String "villeplus">
//* 107 277:getstatic #333 <Field String bnw.b>
//* 108 280:invokevirtual #159 <Method boolean String.equals(Object)>
//* 109 283:ifne 1008
//* 110 286:ldc2 #345 <String "villec2">
//* 111 289:getstatic #333 <Field String bnw.b>
//* 112 292:invokevirtual #159 <Method boolean String.equals(Object)>
//* 113 295:ifne 1008
//* 114 298:getstatic #333 <Field String bnw.b>
//* 115 301:ldc2 #347 <String "gee">
//* 116 304:invokevirtual #350 <Method boolean String.startsWith(String)>
//* 117 307:ifne 1008
//* 118 310:ldc2 #352 <String "C6602">
//* 119 313:getstatic #333 <Field String bnw.b>
//* 120 316:invokevirtual #159 <Method boolean String.equals(Object)>
//* 121 319:ifne 1008
//* 122 322:ldc2 #354 <String "C6603">
//* 123 325:getstatic #333 <Field String bnw.b>
//* 124 328:invokevirtual #159 <Method boolean String.equals(Object)>
//* 125 331:ifne 1008
//* 126 334:ldc2 #356 <String "C6606">
//* 127 337:getstatic #333 <Field String bnw.b>
//* 128 340:invokevirtual #159 <Method boolean String.equals(Object)>
//* 129 343:ifne 1008
//* 130 346:ldc2 #358 <String "C6616">
//* 131 349:getstatic #333 <Field String bnw.b>
//* 132 352:invokevirtual #159 <Method boolean String.equals(Object)>
//* 133 355:ifne 1008
//* 134 358:ldc2 #360 <String "L36h">
//* 135 361:getstatic #333 <Field String bnw.b>
//* 136 364:invokevirtual #159 <Method boolean String.equals(Object)>
//* 137 367:ifne 1008
//* 138 370:ldc2 #362 <String "SO-02E">
//* 139 373:getstatic #333 <Field String bnw.b>
//* 140 376:invokevirtual #159 <Method boolean String.equals(Object)>
//* 141 379:ifeq 385
//* 142 382:goto 1008
//* 143 385:getstatic #313 <Field int bnw.a>
//* 144 388:bipush 16
//* 145 390:icmpne 455
//* 146 393:ldc2 #364 <String "OMX.qcom.audio.decoder.aac">
//* 147 396:aload 10
//* 148 398:invokevirtual #159 <Method boolean String.equals(Object)>
//* 149 401:ifeq 455
//* 150 404:ldc2 #366 <String "C1504">
//* 151 407:getstatic #333 <Field String bnw.b>
//* 152 410:invokevirtual #159 <Method boolean String.equals(Object)>
//* 153 413:ifne 1013
//* 154 416:ldc2 #368 <String "C1505">
//* 155 419:getstatic #333 <Field String bnw.b>
//* 156 422:invokevirtual #159 <Method boolean String.equals(Object)>
//* 157 425:ifne 1013
//* 158 428:ldc2 #370 <String "C1604">
//* 159 431:getstatic #333 <Field String bnw.b>
//* 160 434:invokevirtual #159 <Method boolean String.equals(Object)>
//* 161 437:ifne 1013
//* 162 440:ldc2 #372 <String "C1605">
//* 163 443:getstatic #333 <Field String bnw.b>
//* 164 446:invokevirtual #159 <Method boolean String.equals(Object)>
//* 165 449:ifeq 455
//* 166 452:goto 1013
//* 167 455:getstatic #313 <Field int bnw.a>
//* 168 458:bipush 19
//* 169 460:icmpgt 549
//* 170 463:ldc2 #374 <String "OMX.SEC.vp8.dec">
//* 171 466:aload 10
//* 172 468:invokevirtual #159 <Method boolean String.equals(Object)>
//* 173 471:ifeq 549
//* 174 474:ldc2 #376 <String "samsung">
//* 175 477:getstatic #378 <Field String bnw.c>
//* 176 480:invokevirtual #159 <Method boolean String.equals(Object)>
//* 177 483:ifeq 549
//* 178 486:getstatic #333 <Field String bnw.b>
//* 179 489:ldc2 #380 <String "d2">
//* 180 492:invokevirtual #350 <Method boolean String.startsWith(String)>
//* 181 495:ifne 1018
//* 182 498:getstatic #333 <Field String bnw.b>
//* 183 501:ldc2 #382 <String "serrano">
//* 184 504:invokevirtual #350 <Method boolean String.startsWith(String)>
//* 185 507:ifne 1018
//* 186 510:getstatic #333 <Field String bnw.b>
//* 187 513:ldc2 #384 <String "jflte">
//* 188 516:invokevirtual #350 <Method boolean String.startsWith(String)>
//* 189 519:ifne 1018
//* 190 522:getstatic #333 <Field String bnw.b>
//* 191 525:ldc2 #386 <String "santos">
//* 192 528:invokevirtual #350 <Method boolean String.startsWith(String)>
//* 193 531:ifne 1018
//* 194 534:getstatic #333 <Field String bnw.b>
//* 195 537:ldc2 #388 <String "t0">
//* 196 540:invokevirtual #350 <Method boolean String.startsWith(String)>
//* 197 543:ifeq 549
//* 198 546:goto 1018
//* 199 549:getstatic #313 <Field int bnw.a>
//* 200 552:bipush 19
//* 201 554:icmpgt 1023
//* 202 557:getstatic #333 <Field String bnw.b>
//* 203 560:ldc2 #384 <String "jflte">
//* 204 563:invokevirtual #350 <Method boolean String.startsWith(String)>
//* 205 566:ifeq 1023
//* 206 569:ldc2 #390 <String "OMX.qcom.video.decoder.vp8">
//* 207 572:aload 10
//* 208 574:invokevirtual #159 <Method boolean String.equals(Object)>
//* 209 577:ifeq 1023
//* 210 580:iconst_0
//* 211 581:istore_2
//* 212 582:goto 585
//* 213 585:iload_2
//* 214 586:ifeq 982
//* 215 589:aload 13
//* 216 591:invokevirtual #394 <Method String[] MediaCodecInfo.getSupportedTypes()>
//* 217 594:astore 14
//* 218 596:aload 14
//* 219 598:arraylength
//* 220 599:istore 5
//* 221 601:iconst_0
//* 222 602:istore_2
//* 223 603:iload_2
//* 224 604:iload 5
//* 225 606:icmpge 982
//* 226 609:aload 14
//* 227 611:iload_2
//* 228 612:aaload
//* 229 613:astore 15
//* 230 615:aload 15
//* 231 617:aload 12
//* 232 619:invokevirtual #397 <Method boolean String.equalsIgnoreCase(String)>
//* 233 622:istore 6
//* 234 624:iload 6
//* 235 626:ifeq 975
//* 236 629:aload 13
//* 237 631:aload 15
//* 238 633:invokevirtual #401 <Method android.media.MediaCodecInfo$CodecCapabilities MediaCodecInfo.getCapabilitiesForType(String)>
//* 239 636:astore 9
//* 240 638:aload_1
//* 241 639:aload 12
//* 242 641:aload 9
//* 243 643:invokeinterface #404 <Method boolean bhw.a(String, android.media.MediaCodecInfo$CodecCapabilities)>
//* 244 648:istore 8
//* 245 650:getstatic #313 <Field int bnw.a>
//* 246 653:bipush 22
//* 247 655:icmpgt 1039
//* 248 658:getstatic #406 <Field String bnw.d>
//* 249 661:ldc2 #408 <String "ODROID-XU3">
//* 250 664:invokevirtual #159 <Method boolean String.equals(Object)>
//* 251 667:ifne 682
//* 252 670:getstatic #406 <Field String bnw.d>
//* 253 673:ldc2 #410 <String "Nexus 10">
//* 254 676:invokevirtual #159 <Method boolean String.equals(Object)>
//* 255 679:ifeq 1039
//* 256 682:ldc2 #412 <String "OMX.Exynos.AVC.Decoder">
//* 257 685:aload 10
//* 258 687:invokevirtual #159 <Method boolean String.equals(Object)>
//* 259 690:ifne 1033
//* 260 693:ldc2 #414 <String "OMX.Exynos.AVC.Decoder.secure">
//* 261 696:aload 10
//* 262 698:invokevirtual #159 <Method boolean String.equals(Object)>
//* 263 701:ifeq 1039
//* 264 704:goto 1033
//* 265 707:iload 7
//* 266 709:ifeq 724
//* 267 712:aload_0
//* 268 713:getfield #417 <Field boolean bht.b>
//* 269 716:iload 8
//* 270 718:icmpeq 1045
//* 271 721:goto 724
//* 272 724:iload 7
//* 273 726:ifne 762
//* 274 729:aload_0
//* 275 730:getfield #417 <Field boolean bht.b>
//* 276 733:ifne 762
//* 277 736:goto 1045
//* 278 739:aload 11
//* 279 741:aload 10
//* 280 743:aload 12
//* 281 745:aload 9
//* 282 747:iload 6
//* 283 749:iconst_0
//* 284 750:invokestatic #420 <Method bhm bhm.a(String, String, android.media.MediaCodecInfo$CodecCapabilities, boolean, boolean)>
//* 285 753:invokeinterface #423 <Method boolean List.add(Object)>
//* 286 758:pop
//* 287 759:goto 975
//* 288 762:iload 7
//* 289 764:ifne 813
//* 290 767:iload 8
//* 291 769:ifeq 813
//* 292 772:aload 10
//* 293 774:invokestatic #171 <Method String String.valueOf(Object)>
//* 294 777:ldc2 #305 <String ".secure">
//* 295 780:invokevirtual #180 <Method String String.concat(String)>
//* 296 783:astore 16
//* 297 785:aload 11
//* 298 787:aload 16
//* 299 789:aload 12
//* 300 791:aload 9
//* 301 793:iload 6
//* 302 795:iconst_1
//* 303 796:invokestatic #420 <Method bhm bhm.a(String, String, android.media.MediaCodecInfo$CodecCapabilities, boolean, boolean)>
//* 304 799:invokeinterface #423 <Method boolean List.add(Object)>
//* 305 804:pop
//* 306 805:aload 11
//* 307 807:areturn
//* 308 808:astore 9
//* 309 810:goto 818
//* 310 813:goto 975
//* 311 816:astore 9
//* 312 818:getstatic #313 <Field int bnw.a>
//* 313 821:bipush 23
//* 314 823:icmpgt 896
//* 315 826:aload 11
//* 316 828:invokeinterface #272 <Method boolean List.isEmpty()>
//* 317 833:ifne 896
//* 318 836:new #247 <Class StringBuilder>
//* 319 839:dup
//* 320 840:aload 10
//* 321 842:invokestatic #171 <Method String String.valueOf(Object)>
//* 322 845:invokevirtual #174 <Method int String.length()>
//* 323 848:bipush 46
//* 324 850:iadd
//* 325 851:invokespecial #250 <Method void StringBuilder(int)>
//* 326 854:astore 9
//* 327 856:aload 9
//* 328 858:ldc2 #425 <String "Skipping codec ">
//* 329 861:invokevirtual #256 <Method StringBuilder StringBuilder.append(String)>
//* 330 864:pop
//* 331 865:aload 9
//* 332 867:aload 10
//* 333 869:invokevirtual #256 <Method StringBuilder StringBuilder.append(String)>
//* 334 872:pop
//* 335 873:aload 9
//* 336 875:ldc2 #427 <String " (failed to query capabilities)">
//* 337 878:invokevirtual #256 <Method StringBuilder StringBuilder.append(String)>
//* 338 881:pop
//* 339 882:ldc1 #185 <String "MediaCodecUtil">
//* 340 884:aload 9
//* 341 886:invokevirtual #260 <Method String StringBuilder.toString()>
//* 342 889:invokestatic #429 <Method int Log.e(String, String)>
//* 343 892:pop
//* 344 893:goto 975
//* 345 896:new #247 <Class StringBuilder>
//* 346 899:dup
//* 347 900:aload 10
//* 348 902:invokestatic #171 <Method String String.valueOf(Object)>
//* 349 905:invokevirtual #174 <Method int String.length()>
//* 350 908:bipush 25
//* 351 910:iadd
//* 352 911:aload 15
//* 353 913:invokestatic #171 <Method String String.valueOf(Object)>
//* 354 916:invokevirtual #174 <Method int String.length()>
//* 355 919:iadd
//* 356 920:invokespecial #250 <Method void StringBuilder(int)>
//* 357 923:astore_0
//* 358 924:aload_0
//* 359 925:ldc2 #431 <String "Failed to query codec ">
//* 360 928:invokevirtual #256 <Method StringBuilder StringBuilder.append(String)>
//* 361 931:pop
//* 362 932:aload_0
//* 363 933:aload 10
//* 364 935:invokevirtual #256 <Method StringBuilder StringBuilder.append(String)>
//* 365 938:pop
//* 366 939:aload_0
//* 367 940:ldc2 #433 <String " (">
//* 368 943:invokevirtual #256 <Method StringBuilder StringBuilder.append(String)>
//* 369 946:pop
//* 370 947:aload_0
//* 371 948:aload 15
//* 372 950:invokevirtual #256 <Method StringBuilder StringBuilder.append(String)>
//* 373 953:pop
//* 374 954:aload_0
//* 375 955:ldc2 #435 <String ")">
//* 376 958:invokevirtual #256 <Method StringBuilder StringBuilder.append(String)>
//* 377 961:pop
//* 378 962:ldc1 #185 <String "MediaCodecUtil">
//* 379 964:aload_0
//* 380 965:invokevirtual #260 <Method String StringBuilder.toString()>
//* 381 968:invokestatic #429 <Method int Log.e(String, String)>
//* 382 971:pop
//* 383 972:aload 9
//* 384 974:athrow
//* 385 975:iload_2
//* 386 976:iconst_1
//* 387 977:iadd
//* 388 978:istore_2
//* 389 979:goto 603
//* 390 982:iload_3
//* 391 983:iconst_1
//* 392 984:iadd
//* 393 985:istore_3
//* 394 986:goto 33
//* 395 989:aload 11
//* 396 991:areturn
// Misplaced declaration of an exception variable
catch(bht bht1)
//* 397 992:astore_0
{
throw new bhv(((Throwable) (bht1)), ((bhu) (null)));
// 398 993:new #437 <Class bhv>
// 399 996:dup
// 400 997:aload_0
// 401 998:aconst_null
// 402 999:invokespecial #440 <Method void bhv(Throwable, bhu)>
// 403 1002:athrow
}
j = 0;
if(j >= k) goto _L2; else goto _L1
_L1:
mediacodecinfo = bhw1.a(j);
s = mediacodecinfo.getName();
if(mediacodecinfo.isEncoder())
break MISSING_BLOCK_LABEL_1028;
if(flag2)
break MISSING_BLOCK_LABEL_82;
if(s.endsWith(".secure"))
break MISSING_BLOCK_LABEL_1028;
if(bnw.a >= 21 || !"CIPAACDecoder".equals(((Object) (s))) && !"CIPMP3Decoder".equals(((Object) (s))) && !"CIPVorbisDecoder".equals(((Object) (s))) && !"CIPAMRNBDecoder".equals(((Object) (s))) && !"AACDecoder".equals(((Object) (s))) && !"MP3Decoder".equals(((Object) (s)))) goto _L4; else goto _L3
_L4:
if(bnw.a >= 18 || !"OMX.SEC.MP3.Decoder".equals(((Object) (s)))) goto _L6; else goto _L5
_L5:
i = 0;
goto _L7
_L6:
if(bnw.a >= 18 || !"OMX.MTK.AUDIO.DECODER.AAC".equals(((Object) (s))) || !"a70".equals(((Object) (bnw.b)))) goto _L9; else goto _L8
_L8:
i = 0;
goto _L7
_L9:
if(bnw.a != 16 || !"OMX.qcom.audio.decoder.mp3".equals(((Object) (s))) || !"dlxu".equals(((Object) (bnw.b))) && !"protou".equals(((Object) (bnw.b))) && !"ville".equals(((Object) (bnw.b))) && !"villeplus".equals(((Object) (bnw.b))) && !"villec2".equals(((Object) (bnw.b))) && !bnw.b.startsWith("gee") && !"C6602".equals(((Object) (bnw.b))) && !"C6603".equals(((Object) (bnw.b))) && !"C6606".equals(((Object) (bnw.b))) && !"C6616".equals(((Object) (bnw.b))) && !"L36h".equals(((Object) (bnw.b))) && !"SO-02E".equals(((Object) (bnw.b)))) goto _L11; else goto _L10
_L11:
if(bnw.a != 16 || !"OMX.qcom.audio.decoder.aac".equals(((Object) (s))) || !"C1504".equals(((Object) (bnw.b))) && !"C1505".equals(((Object) (bnw.b))) && !"C1604".equals(((Object) (bnw.b))) && !"C1605".equals(((Object) (bnw.b)))) goto _L13; else goto _L12
_L13:
if(bnw.a > 19 || !"OMX.SEC.vp8.dec".equals(((Object) (s))) || !"samsung".equals(((Object) (bnw.c))) || !bnw.b.startsWith("d2") && !bnw.b.startsWith("serrano") && !bnw.b.startsWith("jflte") && !bnw.b.startsWith("santos") && !bnw.b.startsWith("t0")) goto _L15; else goto _L14
_L15:
if(bnw.a <= 19 && bnw.b.startsWith("jflte") && "OMX.qcom.video.decoder.vp8".equals(((Object) (s))))
i = 0;
else
//* 404 1003:iconst_0
//* 405 1004:istore_2
//* 406 1005:goto 585
//* 407 1008:iconst_0
//* 408 1009:istore_2
//* 409 1010:goto 585
//* 410 1013:iconst_0
//* 411 1014:istore_2
//* 412 1015:goto 585
//* 413 1018:iconst_0
//* 414 1019:istore_2
//* 415 1020:goto 585
i = 1;
// 416 1023:iconst_1
// 417 1024:istore_2
_L7:
if(i == 0)
continue; /* Loop/switch isn't completed */
as = mediacodecinfo.getSupportedTypes();
l = as.length;
i = 0;
_L18:
if(i >= l) goto _L17; else goto _L16
_L16:
s2 = as[i];
flag = s2.equalsIgnoreCase(s1);
if(!flag)
continue; /* Loop/switch isn't completed */
codeccapabilities = mediacodecinfo.getCapabilitiesForType(s2);
flag3 = bhw1.a(s1, codeccapabilities);
boolean flag1;
if(bnw.a <= 22 && (bnw.d.equals("ODROID-XU3") || bnw.d.equals("Nexus 10")) && ("OMX.Exynos.AVC.Decoder".equals(((Object) (s))) || "OMX.Exynos.AVC.Decoder.secure".equals(((Object) (s)))))
//* 418 1025:goto 585
//* 419 1028:iconst_0
//* 420 1029:istore_2
//* 421 1030:goto 585
flag1 = true;
// 422 1033:iconst_1
// 423 1034:istore 6
else
//* 424 1036:goto 707
flag1 = false;
// 425 1039:iconst_0
// 426 1040:istore 6
if(!flag2)
break MISSING_BLOCK_LABEL_724;
if(bht1.b == flag3)
break MISSING_BLOCK_LABEL_739;
if(flag2)
break MISSING_BLOCK_LABEL_762;
if(bht1.b)
break MISSING_BLOCK_LABEL_762;
try
{
((List) (arraylist)).add(((Object) (bhm.a(s, s1, codeccapabilities, flag1, false))));
continue; /* Loop/switch isn't completed */
}
// Misplaced declaration of an exception variable
catch(Object obj) { }
break MISSING_BLOCK_LABEL_818;
if(flag2 || !flag3)
continue; /* Loop/switch isn't completed */
s3 = String.valueOf(((Object) (s))).concat(".secure");
((List) (arraylist)).add(((Object) (bhm.a(s3, s1, codeccapabilities, flag1, true))));
return ((List) (arraylist));
obj;
if(bnw.a <= 23 && !((List) (arraylist)).isEmpty())
{
obj = ((Object) (new StringBuilder(String.valueOf(((Object) (s))).length() + 46)));
((StringBuilder) (obj)).append("Skipping codec ");
((StringBuilder) (obj)).append(s);
((StringBuilder) (obj)).append(" (failed to query capabilities)");
Log.e("MediaCodecUtil", ((StringBuilder) (obj)).toString());
continue; /* Loop/switch isn't completed */
}
bht1 = ((bht) (new StringBuilder(String.valueOf(((Object) (s))).length() + 25 + String.valueOf(((Object) (s2))).length())));
((StringBuilder) (bht1)).append("Failed to query codec ");
((StringBuilder) (bht1)).append(s);
((StringBuilder) (bht1)).append(" (");
((StringBuilder) (bht1)).append(s2);
((StringBuilder) (bht1)).append(")");
Log.e("MediaCodecUtil", ((StringBuilder) (bht1)).toString());
throw obj;
i++;
goto _L18
_L17:
j++;
break MISSING_BLOCK_LABEL_33;
_L2:
return ((List) (arraylist));
_L3:
i = 0;
continue; /* Loop/switch isn't completed */
_L10:
i = 0;
continue; /* Loop/switch isn't completed */
_L12:
i = 0;
continue; /* Loop/switch isn't completed */
_L14:
i = 0;
continue; /* Loop/switch isn't completed */
i = 0;
if(true) goto _L7; else goto _L19
_L19:
//* 427 1042:goto 707
//* 428 1045:goto 739
}
public static int b()
{
if(g == -1)
//* 0 0:getstatic #52 <Field int g>
//* 1 3:iconst_m1
//* 2 4:icmpne 342
{
int i = 0;
// 3 7:iconst_0
// 4 8:istore_0
int k = 0;
// 5 9:iconst_0
// 6 10:istore_2
bhm bhm1 = a("video/avc", false);
// 7 11:ldc2 #442 <String "video/avc">
// 8 14:iconst_0
// 9 15:invokestatic #444 <Method bhm a(String, boolean)>
// 10 18:astore 4
if(bhm1 != null)
//* 11 20:aload 4
//* 12 22:ifnull 338
{
android.media.MediaCodecInfo.CodecProfileLevel acodecprofilelevel[] = bhm1.a();
// 13 25:aload 4
// 14 27:invokevirtual #447 <Method android.media.MediaCodecInfo$CodecProfileLevel[] bhm.a()>
// 15 30:astore 4
int l = acodecprofilelevel.length;
// 16 32:aload 4
// 17 34:arraylength
// 18 35:istore_3
int j = 0;
// 19 36:iconst_0
// 20 37:istore_1
for(; k < l; k++)
//* 21 38:iload_2
//* 22 39:iload_3
//* 23 40:icmpge 313
{
switch(acodecprofilelevel[k].level)
//* 24 43:aload 4
//* 25 45:iload_2
//* 26 46:aaload
//* 27 47:getfield #452 <Field int android.media.MediaCodecInfo$CodecProfileLevel.level>
{
//* 28 50:lookupswitch 16: default 188
// 1: 296
// 2: 289
// 8: 282
// 16: 275
// 32: 268
// 64: 261
// 128: 254
// 256: 247
// 512: 240
// 1024: 233
// 2048: 227
// 4096: 221
// 8192: 214
// 16384: 207
// 32768: 200
// 65536: 193
default:
i = -1;
// 29 188:iconst_m1
// 30 189:istore_0
break;
//* 31 190:goto 300
case 65536:
i = 0x900000;
// 32 193:ldc2 #453 <Int 0x900000>
// 33 196:istore_0
break;
//* 34 197:goto 300
case 32768:
i = 0x900000;
// 35 200:ldc2 #453 <Int 0x900000>
// 36 203:istore_0
break;
//* 37 204:goto 300
case 16384:
i = 0x564000;
// 38 207:ldc2 #454 <Int 0x564000>
// 39 210:istore_0
break;
//* 40 211:goto 300
case 8192:
i = 0x220000;
// 41 214:ldc2 #455 <Int 0x220000>
// 42 217:istore_0
break;
//* 43 218:goto 300
case 4096:
i = 0x200000;
// 44 221:ldc1 #133 <Int 0x200000>
// 45 223:istore_0
break;
//* 46 224:goto 300
case 2048:
i = 0x200000;
// 47 227:ldc1 #133 <Int 0x200000>
// 48 229:istore_0
break;
//* 49 230:goto 300
case 1024:
i = 0x140000;
// 50 233:ldc2 #456 <Int 0x140000>
// 51 236:istore_0
break;
//* 52 237:goto 300
case 512:
i = 0xe1000;
// 53 240:ldc2 #457 <Int 0xe1000>
// 54 243:istore_0
break;
//* 55 244:goto 300
case 256:
i = 0x65400;
// 56 247:ldc2 #458 <Int 0x65400>
// 57 250:istore_0
break;
//* 58 251:goto 300
case 128:
i = 0x65400;
// 59 254:ldc2 #458 <Int 0x65400>
// 60 257:istore_0
break;
//* 61 258:goto 300
case 64: // '@'
i = 0x31800;
// 62 261:ldc2 #459 <Int 0x31800>
// 63 264:istore_0
break;
//* 64 265:goto 300
case 32: // ' '
i = 0x18c00;
// 65 268:ldc2 #460 <Int 0x18c00>
// 66 271:istore_0
break;
//* 67 272:goto 300
case 16: // '\020'
i = 0x18c00;
// 68 275:ldc2 #460 <Int 0x18c00>
// 69 278:istore_0
break;
//* 70 279:goto 300
case 8: // '\b'
i = 0x18c00;
// 71 282:ldc2 #460 <Int 0x18c00>
// 72 285:istore_0
break;
//* 73 286:goto 300
case 2: // '\002'
i = 25344;
// 74 289:sipush 25344
// 75 292:istore_0
break;
//* 76 293:goto 300
case 1: // '\001'
i = 25344;
// 77 296:sipush 25344
// 78 299:istore_0
break;
}
j = Math.max(i, j);
// 79 300:iload_0
// 80 301:iload_1
// 81 302:invokestatic #466 <Method int Math.max(int, int)>
// 82 305:istore_1
}
// 83 306:iload_2
// 84 307:iconst_1
// 85 308:iadd
// 86 309:istore_2
//* 87 310:goto 38
if(bnw.a >= 21)
//* 88 313:getstatic #313 <Field int bnw.a>
//* 89 316:bipush 21
//* 90 318:icmplt 328
i = 0x54600;
// 91 321:ldc2 #467 <Int 0x54600>
// 92 324:istore_0
else
//* 93 325:goto 332
i = 0x2a300;
// 94 328:ldc2 #468 <Int 0x2a300>
// 95 331:istore_0
i = Math.max(j, i);
// 96 332:iload_1
// 97 333:iload_0
// 98 334:invokestatic #466 <Method int Math.max(int, int)>
// 99 337:istore_0
}
g = i;
// 100 338:iload_0
// 101 339:putstatic #52 <Field int g>
}
return g;
// 102 342:getstatic #52 <Field int g>
// 103 345:ireturn
}
private static List b(String s, boolean flag)
{
com/google/android/gms/internal/ads/bhs;
// 0 0:ldc1 #2 <Class bhs>
JVM INSTR monitorenter ;
// 1 2:monitorenter
Object obj;
bht bht1;
bht1 = new bht(s, flag);
// 2 3:new #283 <Class bht>
// 3 6:dup
// 4 7:aload_0
// 5 8:iload_1
// 6 9:invokespecial #471 <Method void bht(String, boolean)>
// 7 12:astore 4
obj = ((Object) ((List)c.get(((Object) (bht1)))));
// 8 14:getstatic #50 <Field HashMap c>
// 9 17:aload 4
// 10 19:invokevirtual #472 <Method Object HashMap.get(Object)>
// 11 22:checkcast #269 <Class List>
// 12 25:astore_2
if(obj == null)
break MISSING_BLOCK_LABEL_35;
// 13 26:aload_2
// 14 27:ifnull 35
com/google/android/gms/internal/ads/bhs;
// 15 30:ldc1 #2 <Class bhs>
JVM INSTR monitorexit ;
// 16 32:monitorexit
return ((List) (obj));
// 17 33:aload_2
// 18 34:areturn
if(bnw.a >= 21)
//* 19 35:getstatic #313 <Field int bnw.a>
//* 20 38:bipush 21
//* 21 40:icmplt 55
{
obj = ((Object) (new bhy(flag)));
// 22 43:new #474 <Class bhy>
// 23 46:dup
// 24 47:iload_1
// 25 48:invokespecial #477 <Method void bhy(boolean)>
// 26 51:astore_2
break MISSING_BLOCK_LABEL_64;
// 27 52:goto 64
}
obj = ((Object) (new bhx(((bhu) (null)))));
// 28 55:new #479 <Class bhx>
// 29 58:dup
// 30 59:aconst_null
// 31 60:invokespecial #482 <Method void bhx(bhu)>
// 32 63:astore_2
List list = a(bht1, ((bhw) (obj)));
// 33 64:aload 4
// 34 66:aload_2
// 35 67:invokestatic #484 <Method List a(bht, bhw)>
// 36 70:astore_3
obj = ((Object) (list));
// 37 71:aload_3
// 38 72:astore_2
if(!flag)
break MISSING_BLOCK_LABEL_219;
// 39 73:iload_1
// 40 74:ifeq 219
obj = ((Object) (list));
// 41 77:aload_3
// 42 78:astore_2
if(!list.isEmpty())
break MISSING_BLOCK_LABEL_219;
// 43 79:aload_3
// 44 80:invokeinterface #272 <Method boolean List.isEmpty()>
// 45 85:ifeq 219
obj = ((Object) (list));
// 46 88:aload_3
// 47 89:astore_2
if(21 > bnw.a)
break MISSING_BLOCK_LABEL_219;
// 48 90:bipush 21
// 49 92:getstatic #313 <Field int bnw.a>
// 50 95:icmpgt 219
obj = ((Object) (list));
// 51 98:aload_3
// 52 99:astore_2
if(bnw.a > 23)
break MISSING_BLOCK_LABEL_219;
// 53 100:getstatic #313 <Field int bnw.a>
// 54 103:bipush 23
// 55 105:icmpgt 219
list = a(bht1, ((bhw) (new bhx(((bhu) (null))))));
// 56 108:aload 4
// 57 110:new #479 <Class bhx>
// 58 113:dup
// 59 114:aconst_null
// 60 115:invokespecial #482 <Method void bhx(bhu)>
// 61 118:invokestatic #484 <Method List a(bht, bhw)>
// 62 121:astore_3
obj = ((Object) (list));
// 63 122:aload_3
// 64 123:astore_2
if(list.isEmpty())
break MISSING_BLOCK_LABEL_219;
// 65 124:aload_3
// 66 125:invokeinterface #272 <Method boolean List.isEmpty()>
// 67 130:ifne 219
obj = ((Object) (((bhm)list.get(0)).a));
// 68 133:aload_3
// 69 134:iconst_0
// 70 135:invokeinterface #275 <Method Object List.get(int)>
// 71 140:checkcast #28 <Class bhm>
// 72 143:getfield #485 <Field String bhm.a>
// 73 146:astore_2
StringBuilder stringbuilder = new StringBuilder(String.valueOf(((Object) (s))).length() + 63 + String.valueOf(obj).length());
// 74 147:new #247 <Class StringBuilder>
// 75 150:dup
// 76 151:aload_0
// 77 152:invokestatic #171 <Method String String.valueOf(Object)>
// 78 155:invokevirtual #174 <Method int String.length()>
// 79 158:bipush 63
// 80 160:iadd
// 81 161:aload_2
// 82 162:invokestatic #171 <Method String String.valueOf(Object)>
// 83 165:invokevirtual #174 <Method int String.length()>
// 84 168:iadd
// 85 169:invokespecial #250 <Method void StringBuilder(int)>
// 86 172:astore 5
stringbuilder.append("MediaCodecList API didn't list secure decoder for: ");
// 87 174:aload 5
// 88 176:ldc2 #487 <String "MediaCodecList API didn't list secure decoder for: ">
// 89 179:invokevirtual #256 <Method StringBuilder StringBuilder.append(String)>
// 90 182:pop
stringbuilder.append(s);
// 91 183:aload 5
// 92 185:aload_0
// 93 186:invokevirtual #256 <Method StringBuilder StringBuilder.append(String)>
// 94 189:pop
stringbuilder.append(". Assuming: ");
// 95 190:aload 5
// 96 192:ldc2 #489 <String ". Assuming: ">
// 97 195:invokevirtual #256 <Method StringBuilder StringBuilder.append(String)>
// 98 198:pop
stringbuilder.append(((String) (obj)));
// 99 199:aload 5
// 100 201:aload_2
// 101 202:invokevirtual #256 <Method StringBuilder StringBuilder.append(String)>
// 102 205:pop
Log.w("MediaCodecUtil", stringbuilder.toString());
// 103 206:ldc1 #185 <String "MediaCodecUtil">
// 104 208:aload 5
// 105 210:invokevirtual #260 <Method String StringBuilder.toString()>
// 106 213:invokestatic #191 <Method int Log.w(String, String)>
// 107 216:pop
obj = ((Object) (list));
// 108 217:aload_3
// 109 218:astore_2
s = ((String) (Collections.unmodifiableList(((List) (obj)))));
// 110 219:aload_2
// 111 220:invokestatic #495 <Method List Collections.unmodifiableList(List)>
// 112 223:astore_0
c.put(((Object) (bht1)), ((Object) (s)));
// 113 224:getstatic #50 <Field HashMap c>
// 114 227:aload 4
// 115 229:aload_0
// 116 230:invokevirtual #496 <Method Object HashMap.put(Object, Object)>
// 117 233:pop
com/google/android/gms/internal/ads/bhs;
// 118 234:ldc1 #2 <Class bhs>
JVM INSTR monitorexit ;
// 119 236:monitorexit
return ((List) (s));
// 120 237:aload_0
// 121 238:areturn
s;
// 122 239:astore_0
//* 123 240:ldc1 #2 <Class bhs>
throw s;
// 124 242:monitorexit
// 125 243:aload_0
// 126 244:athrow
}
private static final bhm a = bhm.a("OMX.google.raw.decoder");
private static final Pattern b = Pattern.compile("^\\D?(\\d+)$");
private static final HashMap c = new HashMap();
private static final SparseIntArray d;
private static final SparseIntArray e;
private static final Map f;
private static int g = -1;
static
{
// 0 0:ldc1 #26 <String "OMX.google.raw.decoder">
// 1 2:invokestatic #31 <Method bhm bhm.a(String)>
// 2 5:putstatic #33 <Field bhm a>
// 3 8:ldc1 #35 <String "^\\D?(\\d+)$">
// 4 10:invokestatic #41 <Method Pattern Pattern.compile(String)>
// 5 13:putstatic #43 <Field Pattern b>
// 6 16:new #45 <Class HashMap>
// 7 19:dup
// 8 20:invokespecial #48 <Method void HashMap()>
// 9 23:putstatic #50 <Field HashMap c>
// 10 26:iconst_m1
// 11 27:putstatic #52 <Field int g>
Object obj = ((Object) (new SparseIntArray()));
// 12 30:new #54 <Class SparseIntArray>
// 13 33:dup
// 14 34:invokespecial #55 <Method void SparseIntArray()>
// 15 37:astore_0
d = ((SparseIntArray) (obj));
// 16 38:aload_0
// 17 39:putstatic #57 <Field SparseIntArray d>
((SparseIntArray) (obj)).put(66, 1);
// 18 42:aload_0
// 19 43:bipush 66
// 20 45:iconst_1
// 21 46:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
d.put(77, 2);
// 22 49:getstatic #57 <Field SparseIntArray d>
// 23 52:bipush 77
// 24 54:iconst_2
// 25 55:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
d.put(88, 4);
// 26 58:getstatic #57 <Field SparseIntArray d>
// 27 61:bipush 88
// 28 63:iconst_4
// 29 64:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
d.put(100, 8);
// 30 67:getstatic #57 <Field SparseIntArray d>
// 31 70:bipush 100
// 32 72:bipush 8
// 33 74:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
obj = ((Object) (new SparseIntArray()));
// 34 77:new #54 <Class SparseIntArray>
// 35 80:dup
// 36 81:invokespecial #55 <Method void SparseIntArray()>
// 37 84:astore_0
e = ((SparseIntArray) (obj));
// 38 85:aload_0
// 39 86:putstatic #63 <Field SparseIntArray e>
((SparseIntArray) (obj)).put(10, 1);
// 40 89:aload_0
// 41 90:bipush 10
// 42 92:iconst_1
// 43 93:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
e.put(11, 4);
// 44 96:getstatic #63 <Field SparseIntArray e>
// 45 99:bipush 11
// 46 101:iconst_4
// 47 102:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
e.put(12, 8);
// 48 105:getstatic #63 <Field SparseIntArray e>
// 49 108:bipush 12
// 50 110:bipush 8
// 51 112:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
e.put(13, 16);
// 52 115:getstatic #63 <Field SparseIntArray e>
// 53 118:bipush 13
// 54 120:bipush 16
// 55 122:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
e.put(20, 32);
// 56 125:getstatic #63 <Field SparseIntArray e>
// 57 128:bipush 20
// 58 130:bipush 32
// 59 132:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
e.put(21, 64);
// 60 135:getstatic #63 <Field SparseIntArray e>
// 61 138:bipush 21
// 62 140:bipush 64
// 63 142:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
e.put(22, 128);
// 64 145:getstatic #63 <Field SparseIntArray e>
// 65 148:bipush 22
// 66 150:sipush 128
// 67 153:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
e.put(30, 256);
// 68 156:getstatic #63 <Field SparseIntArray e>
// 69 159:bipush 30
// 70 161:sipush 256
// 71 164:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
e.put(31, 512);
// 72 167:getstatic #63 <Field SparseIntArray e>
// 73 170:bipush 31
// 74 172:sipush 512
// 75 175:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
e.put(32, 1024);
// 76 178:getstatic #63 <Field SparseIntArray e>
// 77 181:bipush 32
// 78 183:sipush 1024
// 79 186:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
e.put(40, 2048);
// 80 189:getstatic #63 <Field SparseIntArray e>
// 81 192:bipush 40
// 82 194:sipush 2048
// 83 197:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
e.put(41, 4096);
// 84 200:getstatic #63 <Field SparseIntArray e>
// 85 203:bipush 41
// 86 205:sipush 4096
// 87 208:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
e.put(42, 8192);
// 88 211:getstatic #63 <Field SparseIntArray e>
// 89 214:bipush 42
// 90 216:sipush 8192
// 91 219:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
e.put(50, 16384);
// 92 222:getstatic #63 <Field SparseIntArray e>
// 93 225:bipush 50
// 94 227:sipush 16384
// 95 230:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
e.put(51, 32768);
// 96 233:getstatic #63 <Field SparseIntArray e>
// 97 236:bipush 51
// 98 238:ldc1 #64 <Int 32768>
// 99 240:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
e.put(52, 0x10000);
// 100 243:getstatic #63 <Field SparseIntArray e>
// 101 246:bipush 52
// 102 248:ldc1 #65 <Int 0x10000>
// 103 250:invokevirtual #61 <Method void SparseIntArray.put(int, int)>
obj = ((Object) (new HashMap()));
// 104 253:new #45 <Class HashMap>
// 105 256:dup
// 106 257:invokespecial #48 <Method void HashMap()>
// 107 260:astore_0
f = ((Map) (obj));
// 108 261:aload_0
// 109 262:putstatic #67 <Field Map f>
((Map) (obj)).put("L30", ((Object) (Integer.valueOf(1))));
// 110 265:aload_0
// 111 266:ldc1 #69 <String "L30">
// 112 268:iconst_1
// 113 269:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 114 272:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 115 277:pop
f.put("L60", ((Object) (Integer.valueOf(4))));
// 116 278:getstatic #67 <Field Map f>
// 117 281:ldc1 #82 <String "L60">
// 118 283:iconst_4
// 119 284:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 120 287:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 121 292:pop
f.put("L63", ((Object) (Integer.valueOf(16))));
// 122 293:getstatic #67 <Field Map f>
// 123 296:ldc1 #84 <String "L63">
// 124 298:bipush 16
// 125 300:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 126 303:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 127 308:pop
f.put("L90", ((Object) (Integer.valueOf(64))));
// 128 309:getstatic #67 <Field Map f>
// 129 312:ldc1 #86 <String "L90">
// 130 314:bipush 64
// 131 316:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 132 319:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 133 324:pop
f.put("L93", ((Object) (Integer.valueOf(256))));
// 134 325:getstatic #67 <Field Map f>
// 135 328:ldc1 #88 <String "L93">
// 136 330:sipush 256
// 137 333:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 138 336:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 139 341:pop
f.put("L120", ((Object) (Integer.valueOf(1024))));
// 140 342:getstatic #67 <Field Map f>
// 141 345:ldc1 #90 <String "L120">
// 142 347:sipush 1024
// 143 350:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 144 353:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 145 358:pop
f.put("L123", ((Object) (Integer.valueOf(4096))));
// 146 359:getstatic #67 <Field Map f>
// 147 362:ldc1 #92 <String "L123">
// 148 364:sipush 4096
// 149 367:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 150 370:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 151 375:pop
f.put("L150", ((Object) (Integer.valueOf(16384))));
// 152 376:getstatic #67 <Field Map f>
// 153 379:ldc1 #94 <String "L150">
// 154 381:sipush 16384
// 155 384:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 156 387:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 157 392:pop
f.put("L153", ((Object) (Integer.valueOf(0x10000))));
// 158 393:getstatic #67 <Field Map f>
// 159 396:ldc1 #96 <String "L153">
// 160 398:ldc1 #65 <Int 0x10000>
// 161 400:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 162 403:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 163 408:pop
f.put("L156", ((Object) (Integer.valueOf(0x40000))));
// 164 409:getstatic #67 <Field Map f>
// 165 412:ldc1 #98 <String "L156">
// 166 414:ldc1 #99 <Int 0x40000>
// 167 416:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 168 419:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 169 424:pop
f.put("L180", ((Object) (Integer.valueOf(0x100000))));
// 170 425:getstatic #67 <Field Map f>
// 171 428:ldc1 #101 <String "L180">
// 172 430:ldc1 #102 <Int 0x100000>
// 173 432:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 174 435:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 175 440:pop
f.put("L183", ((Object) (Integer.valueOf(0x400000))));
// 176 441:getstatic #67 <Field Map f>
// 177 444:ldc1 #104 <String "L183">
// 178 446:ldc1 #105 <Int 0x400000>
// 179 448:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 180 451:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 181 456:pop
f.put("L186", ((Object) (Integer.valueOf(0x1000000))));
// 182 457:getstatic #67 <Field Map f>
// 183 460:ldc1 #107 <String "L186">
// 184 462:ldc1 #108 <Int 0x1000000>
// 185 464:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 186 467:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 187 472:pop
f.put("H30", ((Object) (Integer.valueOf(2))));
// 188 473:getstatic #67 <Field Map f>
// 189 476:ldc1 #110 <String "H30">
// 190 478:iconst_2
// 191 479:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 192 482:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 193 487:pop
f.put("H60", ((Object) (Integer.valueOf(8))));
// 194 488:getstatic #67 <Field Map f>
// 195 491:ldc1 #112 <String "H60">
// 196 493:bipush 8
// 197 495:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 198 498:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 199 503:pop
f.put("H63", ((Object) (Integer.valueOf(32))));
// 200 504:getstatic #67 <Field Map f>
// 201 507:ldc1 #114 <String "H63">
// 202 509:bipush 32
// 203 511:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 204 514:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 205 519:pop
f.put("H90", ((Object) (Integer.valueOf(128))));
// 206 520:getstatic #67 <Field Map f>
// 207 523:ldc1 #116 <String "H90">
// 208 525:sipush 128
// 209 528:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 210 531:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 211 536:pop
f.put("H93", ((Object) (Integer.valueOf(512))));
// 212 537:getstatic #67 <Field Map f>
// 213 540:ldc1 #118 <String "H93">
// 214 542:sipush 512
// 215 545:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 216 548:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 217 553:pop
f.put("H120", ((Object) (Integer.valueOf(2048))));
// 218 554:getstatic #67 <Field Map f>
// 219 557:ldc1 #120 <String "H120">
// 220 559:sipush 2048
// 221 562:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 222 565:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 223 570:pop
f.put("H123", ((Object) (Integer.valueOf(8192))));
// 224 571:getstatic #67 <Field Map f>
// 225 574:ldc1 #122 <String "H123">
// 226 576:sipush 8192
// 227 579:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 228 582:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 229 587:pop
f.put("H150", ((Object) (Integer.valueOf(32768))));
// 230 588:getstatic #67 <Field Map f>
// 231 591:ldc1 #124 <String "H150">
// 232 593:ldc1 #64 <Int 32768>
// 233 595:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 234 598:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 235 603:pop
f.put("H153", ((Object) (Integer.valueOf(0x20000))));
// 236 604:getstatic #67 <Field Map f>
// 237 607:ldc1 #126 <String "H153">
// 238 609:ldc1 #127 <Int 0x20000>
// 239 611:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 240 614:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 241 619:pop
f.put("H156", ((Object) (Integer.valueOf(0x80000))));
// 242 620:getstatic #67 <Field Map f>
// 243 623:ldc1 #129 <String "H156">
// 244 625:ldc1 #130 <Int 0x80000>
// 245 627:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 246 630:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 247 635:pop
f.put("H180", ((Object) (Integer.valueOf(0x200000))));
// 248 636:getstatic #67 <Field Map f>
// 249 639:ldc1 #132 <String "H180">
// 250 641:ldc1 #133 <Int 0x200000>
// 251 643:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 252 646:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 253 651:pop
f.put("H183", ((Object) (Integer.valueOf(0x800000))));
// 254 652:getstatic #67 <Field Map f>
// 255 655:ldc1 #135 <String "H183">
// 256 657:ldc1 #136 <Int 0x800000>
// 257 659:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 258 662:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 259 667:pop
f.put("H186", ((Object) (Integer.valueOf(0x2000000))));
// 260 668:getstatic #67 <Field Map f>
// 261 671:ldc1 #138 <String "H186">
// 262 673:ldc1 #139 <Int 0x2000000>
// 263 675:invokestatic #75 <Method Integer Integer.valueOf(int)>
// 264 678:invokeinterface #80 <Method Object Map.put(Object, Object)>
// 265 683:pop
//* 266 684:return
}
}
| 39.92173 | 562 | 0.53173 |
3610aa348f827725e132d1b8268607ea83f34788 | 14,440 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.google.uicd.backend.core.utils;
import com.google.common.base.Splitter;
import com.google.uicd.backend.core.config.UicdConfig;
import com.google.uicd.backend.core.exceptions.UicdExternalCommandException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.logging.LogManager;
import java.util.logging.Logger;
/** Helper functions executing adb command */
public class ADBCommandLineUtil {
private static final String DEFAULT_SCREEN_SIZE = "1080x1920";
// There are up to 3 ports we need allocate for each device when we run Uicd.
// dumperHostPort, minicapHostPort, minicapWebServerPort. It will be stored in Device object.
private static final int NUM_DYNAMIC_PORTS = 4;
private static final int MINIMUM_API_LEVEL_FOR_PERMISSION_GRANT_FLAG = 23;
private static final Logger logger = LogManager.getLogManager().getLogger("uicd");
private final CommandLineUtil commandLineUtil;
public ADBCommandLineUtil() {
this.commandLineUtil = new CommandLineUtil();
}
public Process executeReboot(String deviceId, List<String> output)
throws UicdExternalCommandException {
String adbShellPath = UicdConfig.getInstance().getAdbShellPath();
String adbPrefix = String.format("%s -s %s ", adbShellPath, deviceId);
String commandStr = adbPrefix + "reboot &&" + adbPrefix + " wait-for-device";
return commandLineUtil.execute(commandStr, output, true, 120);
}
public String constructAdbCommand(String commandLine, String deviceId) {
String adbShellPath = UicdConfig.getInstance().getAdbShellPath();
String adbPrefix = String.format("%s -s %s ", adbShellPath, deviceId);
if (deviceId.isEmpty()) {
adbPrefix = adbShellPath;
}
if (!commandLine.startsWith("adb")) {
commandLine = adbPrefix + " " + commandLine;
} else {
commandLine = commandLine.replace("adb", adbPrefix);
}
return commandLine;
}
public String constructAdbLogcatCommand(String commandLine, String deviceId) {
String adbPrefix =
String.format("%s -s %s ", UicdConfig.getInstance().getAdbShellPath(), deviceId);
if (commandLine.contains("logcat") && !commandLine.contains("logcat -d")) {
commandLine = commandLine.replace("logcat", "logcat -d");
}
if (commandLine.contains("adb")) {
return commandLine.replace("adb", adbPrefix);
} else {
return adbPrefix + commandLine;
}
}
public Process executeAdbLogcatCommand(
String commandLine, String deviceId, List<String> output, int timeout)
throws UicdExternalCommandException {
String adbLogcatCmd = constructAdbLogcatCommand(commandLine, deviceId);
return commandLineUtil.execute(adbLogcatCmd, output, true, timeout);
}
public Process executeAdb(String commandLine, String deviceId, boolean waitFor)
throws UicdExternalCommandException {
String cmd = constructAdbCommand(commandLine, deviceId);
List<String> output = new ArrayList<>();
return commandLineUtil.execute(cmd, output, waitFor);
}
public Process executeAdb(
String commandLine, String deviceId, List<String> output, boolean showDetailsLogging)
throws UicdExternalCommandException {
String cmd = constructAdbCommand(commandLine, deviceId);
return commandLineUtil.execute(cmd, output, true, showDetailsLogging);
}
public Process executeAdb(
String commandLine, String deviceId, List<String> output, int timeout)
throws UicdExternalCommandException {
String cmd = constructAdbCommand(commandLine, deviceId);
return commandLineUtil.execute(cmd, output, true, timeout);
}
public Process executeAdb(String commandLine, String deviceId)
throws UicdExternalCommandException {
List<String> output = new ArrayList<>();
return executeAdb(commandLine, deviceId, output);
}
public Process executeAdb(String commandLine, String deviceId, List<String> output)
throws UicdExternalCommandException {
String cmd = constructAdbCommand(commandLine, deviceId);
return commandLineUtil.execute(cmd, output, true);
}
public Process startXmlDumperServer(String deviceId, int hostPort, int devicePort)
throws UicdExternalCommandException {
// We already did the port forward in the initDevice, however for some action (RebootAction)
// need redo the port forward again after device reboot.
String forwardCmd = "forward tcp:%d tcp:%d";
executeAdb(String.format(forwardCmd, hostPort, devicePort), deviceId);
String xmldumperPackagePrefix = UicdConfig.getInstance().getXmldumperPackagePrefix();
String targetXmldumperVersion = UicdConfig.getInstance().getXmlDumperApkVersion();
String runnerPrefix = "android.support";
if (compareVersion(targetXmldumperVersion, "2.0.0") >= 0) {
runnerPrefix = "androidx";
}
String startXmlDumperServerCmd =
String.format(
"shell am instrument -w -e debug false -e class "
+ "'%s.DumperServerInstrumentation#startServer' %s.test/"
+ "%s.test.runner.AndroidJUnitRunner",
xmldumperPackagePrefix, xmldumperPackagePrefix, runnerPrefix);
// don't wait for the instrument command
return executeAdb(startXmlDumperServerCmd, deviceId, false);
}
// Version of xml dumper, version is in the "1.0.1" format
private static int compareVersion(String version1, String version2) {
return Integer.compare(versionToInt(version1), versionToInt(version2));
}
// To make it simple, the version can only be single digit.
private static int versionToInt(String version) {
if (version.isEmpty()) {
return 0;
}
if (version.startsWith("v")) {
version = version.substring(1);
}
List<String> strs = Splitter.on('.').splitToList(version);
int versionNum = 0;
for (String s : strs) {
versionNum *= 10;
versionNum += Integer.parseInt(s);
}
return versionNum;
}
public Optional<String> getXmlDumperApkVersion(String deviceId) {
String getDumperVersionCmd =
String.format(
"shell dumpsys package %s | grep versionName",
UicdConfig.getInstance().getXmldumperPackagePrefix());
List<String> dumperVersionOutputList = new ArrayList<>();
try {
executeAdb(getDumperVersionCmd, deviceId, dumperVersionOutputList);
} catch (UicdExternalCommandException e) {
return Optional.empty();
}
if (!dumperVersionOutputList.isEmpty()) {
// installed dumper Version from adb will be something like this: "versionName=1.0.0"
List<String> items = Splitter.on('=').splitToList(dumperVersionOutputList.get(0));
if (items.size() == 2) {
return Optional.of(items.get(1));
}
}
return Optional.empty();
}
public void updateXmlDumperApk(String deviceId, int apiLevel)
throws UicdExternalCommandException {
// if already installed, skip install apks
String listPackageAdbCmd = "shell pm list packages";
List<String> packageList = new ArrayList<>();
// During the frontend loading, we don't want to see the all the package names on the output
// dialog on the frontend.
executeAdb(listPackageAdbCmd, deviceId, packageList, false);
String xmldumperPackagePrefix = UicdConfig.getInstance().getXmldumperPackagePrefix();
if (packageList.contains(xmldumperPackagePrefix)) {
Optional<String> dumperApkVersion = getXmlDumperApkVersion(deviceId);
if (!UicdConfig.getInstance().getXmlDumperApkVersion().isEmpty()
&& dumperApkVersion.isPresent()
&& compareVersion(
UicdConfig.getInstance().getXmlDumperApkVersion(), dumperApkVersion.get())
> 0) {
logger.info("Found newer version of uicd xmldumper. Updating uicd xmldumper...");
String uninstallCmd1 = String.format("uninstall %s", xmldumperPackagePrefix);
String uninstallCmd2 = String.format("uninstall %s.test", xmldumperPackagePrefix);
executeAdb(uninstallCmd1, deviceId);
executeAdb(uninstallCmd2, deviceId);
installXmlDumperApk(deviceId, apiLevel);
} else {
logger.info("XML Dumper apk already installed, skip install step.");
}
} else {
logger.info("Cannot find uicd dumper apk, installing...");
installXmlDumperApk(deviceId, apiLevel);
}
}
private void installXmlDumperApk(String deviceId, int apiLevel)
throws UicdExternalCommandException {
// parameters for adb install
// -r replace existing application
// -d allow version code downgrade
// -t allow test packages
// -g grant permission
String installCmd = "install -r -d -t ";
if (apiLevel >= MINIMUM_API_LEVEL_FOR_PERMISSION_GRANT_FLAG) {
installCmd += "-g ";
}
String startDumperAdbCmd1 =
installCmd
+ Paths.get(
UicdConfig.getInstance().getXmlDumperAPKPath().toString(),
String.format(
"uicd-xmldumper-server-test-v%s.apk",
UicdConfig.getInstance().getXmlDumperApkVersion()));
String startDumperAdbCmd2 =
installCmd
+ Paths.get(
UicdConfig.getInstance().getXmlDumperAPKPath().toString(),
String.format(
"uicd-xmldumper-server-v%s.apk",
UicdConfig.getInstance().getXmlDumperApkVersion()));
executeAdb(startDumperAdbCmd1, deviceId);
executeAdb(startDumperAdbCmd2, deviceId);
}
public void turnOffAutoRotation(String deviceId) throws UicdExternalCommandException {
String turnOffCmd = "shell settings put system accelerometer_rotation 0";
executeAdb(turnOffCmd, deviceId, true);
}
public List<String> getDevicesList() throws UicdExternalCommandException {
List<String> commandLineOut = new ArrayList<>();
commandLineUtil.execute(
String.format("%s devices -l", UicdConfig.getInstance().getAdbShellPath()),
commandLineOut,
true /* waitFor */);
return commandLineOut;
}
/* get screen size of the devices */
public String getDeviceScreenSize(String deviceId) throws UicdExternalCommandException {
List<String> ret = new ArrayList<>();
executeAdb("shell wm size", deviceId, ret);
if (ret.isEmpty()) {
return "";
}
String sizeString = ret.get(0);
for (String str : ret) {
if (str.startsWith("Override size:")) {
sizeString = str;
}
}
return StringUtil.getPartFromString(sizeString, ":", 1, DEFAULT_SCREEN_SIZE);
}
// If more than one device is connected, some machines will show "error: unknown host service";
// need to provide a deviceId to prevent this. There will be one pitfall, allocating ports is
// not an atomic operation. There is a small chance of a race condition in MH. However, we
// don't have a easy way to solve it for now, it would require changes on the mobileharness side.
public int getFirstAvailablePortSlot(String deviceId, int startIndex, int deviceCount)
throws UicdExternalCommandException {
List<String> output = new ArrayList<>();
HashSet<Integer> existingPort = new HashSet<>();
String adbCommand = "forward --list";
executeAdb(adbCommand, deviceId, output);
// Sample output is like this:
// HT664020XXXX tcp:6790 tcp:6790
// 706KPKN00XXXX tcp:6793 tcp:6790
for (String s : output) {
List<String> items = Splitter.on(' ').splitToList(s);
if (items.size() == 3) {
int port = Integer.parseInt(items.get(1).replace("tcp:", ""));
existingPort.add(port);
}
}
// Find a slot that can fit X devices, where X is deviceCount. In total, we need 3*deviceCount
// ports. Only search up to startIndex + 10000.
int availableCnt = 0;
for (int i = startIndex; i < startIndex + 10000; i++) {
if (!existingPort.contains(i)) {
availableCnt++;
} else {
availableCnt = 0;
}
if (availableCnt == deviceCount * NUM_DYNAMIC_PORTS) {
return i - availableCnt + 1;
}
}
logger.severe("Can not allocate ports for adb forwarding.");
throw new UicdExternalCommandException("Can not allocate ports for adb forwarding.");
}
// Similar to adb forward, it only works on some machines when we provide the serial number.
public void removePortForwarding(String deviceId, int port) {
String adbCommand = String.format("forward --remove tcp:%d", port);
try {
executeAdb(adbCommand, deviceId);
} catch (UicdExternalCommandException e) {
logger.severe(e.getMessage());
}
}
public void forceStopXmlDumperOnDevice(String deviceId) {
String xmldumperPackagePrefix = UicdConfig.getInstance().getXmldumperPackagePrefix();
String adbCommand1 = String.format("shell am force-stop %s", xmldumperPackagePrefix);
String adbCommand2 = String.format("shell am force-stop %s.test", xmldumperPackagePrefix);
try {
executeAdb(adbCommand1, deviceId);
executeAdb(adbCommand2, deviceId);
} catch (UicdExternalCommandException e) {
logger.severe(e.getMessage());
}
}
/* get product name */
public String getDeviceProperty(String deviceId, String propertyName)
throws UicdExternalCommandException {
List<String> ret = new ArrayList<>();
String command = String.format("shell getprop %s", propertyName);
executeAdb(command, deviceId, ret);
return ret.isEmpty() ? "" : ret.get(0);
}
public int getDeviceApiLevel(String deviceId) throws UicdExternalCommandException {
return Integer.parseInt(getDeviceProperty(deviceId, "ro.build.version.sdk"));
}
public String getDeviceProductName(String deviceId) throws UicdExternalCommandException {
return getDeviceProperty(deviceId, "ro.build.product");
}
}
| 40.335196 | 99 | 0.699654 |
9e79c698ac049dca2867580daca078d3e2ddccb5 | 2,639 | package de.ayesolutions.gogs.client;
import de.ayesolutions.gogs.client.model.AccessToken;
import org.junit.Assume;
import org.junit.Before;
import java.io.IOException;
import java.net.URI;
import java.util.UUID;
/**
* @author Christian Aye - c.aye@aye-solutions.de
*/
public abstract class AbstractGogsTest {
protected final static String SSH_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDberous+OJrJGvyqiEKX7pH2RNHCh1XZIwzsat3nwtefGneG+9SUGNb909VCdPE2BU1zSAYOoDl/jtSIuKJ6TFbsAVgABVBnKJ44K0cdA64zGXBLFlFwPD9knZl3/okcPyXE/+TDokoQsCg8VNdipM8FiMDlfeUEfrTCXTy5qMREXBAbPqLqetQ5g8i57jH1P5rbI9nrMSpuI+mfrpPL8AiXRlZhkObLNRlNR/zhmItM3LmVKjC6MtPfz7TPVjtQaApSu1HlpvroMhR6m394l1m4wnckI+ogkcg9bY0FxkmWc0OwYGnqOcYvfv4DrCCz4rkxK1ZIHX1CGAoiBacqY4+gsQdWvYVNIUaxMeLFt/M3kT6h5k1znTXF7bEAJwJJPdOTM3Fzhx1GeUVeWQOORxYGU90ZTkrV5przAuJpbpv9GX0vAiCCq+c3u62tlv8v9X7o2PmVfDlGEUE6LPlSDAbqYI6kv/1mDJuxlsYKGFWhLiYhafswEe4Cgipw0s1WgQj//qI5+9A+9z6JlquSUcsl7elEVJaEBViRpTGye3pOaeJTnZM/aKy2B+Du+4QoRZXTZTjojTOb45DwIijLq+elVAip/B8M7ytzPFj/St/IKv7noar0kORmYYSBdaue9nqpSqJFqSyv2o67PmpN+ddqw4dgIWkL5XsypgXLHIJw== christianaye@HEIMDALL.local";
protected final static URI API_URI = URI.create("http://gogs.aye-solutions.de/api/v1");
protected final static URI API_URI_INVALID = URI.create("http://gogs.aye-solutions.de/apii/v1");
protected final static GogsClient API_ADMIN = new GogsClient(API_URI, "gogs-admin", "pass", "5a855f3bcccb41275c9508552e5d8a11321c21df");
protected final static GogsClient API_USER = new GogsClient(API_URI, "gogs-user", "pass", "486632a6c6fd07d9e4b0aad8c30c0c834d469a91");
protected final static GogsClient API_UNAUTHORIZED = new GogsClient(API_URI);
protected final static GogsClient API_INVALID = new GogsClient(API_URI_INVALID, new AccessToken(null, "4867d9e4b0aad8c30c0c834d469a91", "dd", "daa"));
protected final static String USERNAME_ADMIN = "gogs-admin";
protected final static String USERNAME_USER = "gogs-user";
protected final static String USERNAME_UNKNOWN = "unknown";
protected final static String GRAVATAR_URL = "https://secure.gravatar.com/avatar/";
public AbstractGogsTest() {
createDummyObjects();
}
@Before
public void beforeMethod() {
checkTestServer();
}
public static void checkTestServer() {
try {
API_URI.toURL().openConnection().connect();
} catch (IOException e) {
Assume.assumeTrue(false);
}
Assume.assumeTrue(true);
}
public abstract void createDummyObjects();
protected String generateGUID() {
return UUID.randomUUID().toString();
}
}
| 42.564516 | 799 | 0.78022 |
253332ef956ab246e615f7f865c8a12bf39c6e14 | 3,502 | /*
* Copyright 2016-present Open Networking Laboratory
*
* 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.onosproject.yms.app.ydt;
import org.onosproject.yangutils.datamodel.YangSchemaNode;
import org.onosproject.yms.app.ysr.DefaultYangSchemaRegistry;
import org.onosproject.yms.app.ysr.TestYangSchemaNodeProvider;
import org.onosproject.yms.app.ysr.YangSchemaRegistry;
import org.onosproject.yms.ysr.YangModuleIdentifier;
import org.onosproject.yms.ysr.YangModuleLibrary;
import static org.junit.Assert.assertEquals;
/**
* Represent Yang schema registry. Yang schema registry provides
* interface to an application to register its YANG
* schema with YMS. It provides YANG schema nodes to YDT, YNB and YSB.
*/
public class MockYangSchemaRegistry implements YangSchemaRegistry {
@Override
public void registerApplication(Object managerObject, Class<?> serviceClass) {
}
@Override
public void unRegisterApplication(Object managerObject,
Class<?> serviceClass) {
}
@Override
public Object getRegisteredApplication(YangSchemaNode yangSchemaNode) {
return null;
}
@Override
public YangSchemaNode getYangSchemaNodeUsingAppName(String schemaName) {
return null;
}
@Override
public YangSchemaNode getYangSchemaNodeUsingSchemaName(String appName) {
final String target = "target/TestYangSchemaNodeProvider";
TestYangSchemaNodeProvider testYangSchemaNodeProvider =
new TestYangSchemaNodeProvider();
String searchDir = "src/test/resources/ydtTestYangFiles/";
testYangSchemaNodeProvider.processSchemaRegistry(null);
DefaultYangSchemaRegistry registry = testYangSchemaNodeProvider
.getDefaultYangSchemaRegistry();
YangSchemaNode yangNode = registry
.getYangSchemaNodeUsingSchemaName(appName);
assertEquals(appName, yangNode.getName());
return yangNode;
}
@Override
public YangSchemaNode
getYangSchemaNodeUsingGeneratedRootNodeInterfaceFileName(
String rootInterfaceFileName) {
return null;
}
@Override
public YangSchemaNode getYangSchemaNodeUsingGeneratedRootNodeOpPramFileName(
String rootOpParamFileName) {
return null;
}
@Override
public YangSchemaNode getRootYangSchemaNodeForNotification(
String eventSubject) {
return null;
}
@Override
public Class<?> getRegisteredClass(YangSchemaNode schemaNode) {
return null;
}
@Override
public boolean verifyNotificationObject(Object appObj, Class<?> service) {
return false;
}
@Override
public void flushYsrData() {
}
@Override
public String getYangFile(YangModuleIdentifier moduleIdentifier) {
return null;
}
@Override
public void processModuleLibrary(String serviceName, YangModuleLibrary library) {
}
}
| 29.183333 | 85 | 0.718447 |
bbca9c2557d0e7c1d8f4326c2c2b16757a9f64c6 | 2,619 | /*
* Integrated Rule Inference System (IRIS):
* An extensible rule inference system for datalog with extensions.
*
* Copyright (C) 2009 ICT Institute - Dipartimento di Elettronica e Informazione (DEI),
* Politecnico di Milano, Via Ponzio 34/5, 20133 Milan, Italy.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.deri.iris.queryrewriting;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.log4j.Logger;
import org.deri.iris.EvaluationException;
import org.deri.iris.Expressivity;
import org.deri.iris.api.basics.IPosition;
import org.deri.iris.api.basics.IRule;
import org.deri.iris.queryrewriting.configuration.NCCheck;
import org.deri.iris.queryrewriting.configuration.SubCheckStrategy;
/**
* @author jd
*/
public class QueryRewriterFactory {
private final Logger LOGGER = Logger.getLogger(QueryRewriterFactory.class);
private static QueryRewriterFactory _INSTANCE;
public static QueryRewriterFactory getInstance() {
if ((_INSTANCE == null)) {
_INSTANCE = new QueryRewriterFactory();
}
return _INSTANCE;
}
private QueryRewriterFactory() {
super();
}
public QueryRewriter getRewriter(final IRule query, final List<IRule> rules, final Set<IRule> constraints,
final Map<Pair<IPosition, IPosition>, Set<List<IRule>>> posDeps, final Expressivity expr,
final SubCheckStrategy subchkStrategy, final NCCheck ncCheckStrategy) throws EvaluationException {
switch (expr) {
case LINEAR:
return new LinearRewriter(query, rules, constraints, posDeps, subchkStrategy, ncCheckStrategy);
case STICKY:
return new FORewriter(query, rules, constraints, posDeps, subchkStrategy, ncCheckStrategy);
default:
final String message = "Unable to rewrite a ".concat(expr.name()).concat("theory");
LOGGER.error(message);
throw new EvaluationException(message);
}
}
}
| 34.92 | 107 | 0.757159 |
9bbd6122f19bca2a810eb9859be1597cd360b851 | 8,198 | package com.rsun.andemo.Operation;
import android.content.Context;
import android.util.Log;
import com.rsun.Global.GlobalEnv;
import com.rsun.andemo.inf.RSunApi;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class LoginOpHelper {
private static final String TAG = "LoginOpHelper";
private static LoginOpHelper mHelper = null;
private Context mContext;
private LoginOpHelper(Context context) {
mContext = context;
}
public static LoginOpHelper getHelper(Context context) {
if (mHelper == null) {
mHelper = new LoginOpHelper(context);
}
return mHelper;
}
/**
* 设计一个token 格式 以便登陆业务可以使用
* token = android+phoneNumber+uuid+Brand+OSVersion+appName+appVersion+expireTime
*/
public static String genLoginTokenSeed(String phone){
String token = "";
if (GlobalEnv.GUID.length()!=0){
token = "android"+"_"+phone+"_"+ GlobalEnv.GUID+"_"+GlobalEnv.phoneBrand+"_"+GlobalEnv.OSVersion+"_"+GlobalEnv.packageName+"_"+GlobalEnv.appVersion;
}
return token;
}
public static String getSaltPasswd(String passwd){
return GlobalEnv.salt(GlobalEnv.GUID,passwd);
}
public interface LoginOpCallback{
void onResponse(boolean response);
void onFailure(Error error);
void challenge(String challenge);
}
public void getAuthCode(String phone, final LoginOpCallback callback){
Call<ResponseBody> challenge = GlobalEnv.getInstance(mContext).getRetrofit().create(RSunApi.class).getAuthCode(phone);
challenge.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
String t;
try {
t = response.body().string();
try {
JSONObject jsonResponse = new JSONObject(t);
boolean codeSend = jsonResponse.getBoolean("codeSend");
callback.onResponse(codeSend);
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable throwable) {
callback.onFailure(new Error("连接失败"));
}
});
}
public void registerUser(final String phone, final String passwd, final String authCode, final LoginOpCallback callback){
String TokenSeed = genLoginTokenSeed(phone);
if (TokenSeed.length()==0){
Log.d(TAG, "registerUser: fail to generate token seed");
return;
}
Call<ResponseBody> getLoginTokenQueue = GlobalEnv.getInstance(mContext).getRetrofit().create(RSunApi.class).getLoginToken(TokenSeed);
getLoginTokenQueue.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
String t;
try {
t = response.body().string();
try {
JSONObject jsonResponse = new JSONObject(t);
String token = jsonResponse.getString("token");
GlobalEnv.getInstance(mContext).setLoginToken(token);
Call<ResponseBody> registerUserQueue = GlobalEnv.getInstance(mContext).getRetrofit().create(RSunApi.class).registerUser(phone,token,passwd,authCode);
registerUserQueue.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
String r;
try {
r = response.body().string();
try {
JSONObject jsonObject = new JSONObject(r);
String lowKey = jsonObject.getString("low");
String highKey = jsonObject.getString("high");
GlobalEnv.getInstance(mContext).setLoginKey(lowKey);
GlobalEnv.getInstance(mContext).setPrivilegeKey(highKey);
callback.onResponse(true);
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
callback.onFailure(new Error("连接失败"));
}
});
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
callback.onFailure(new Error("连接失败"));
}
});
}
public void getChallenge(final String token, final LoginOpCallback callback){
Call<ResponseBody> getChallengeQueue = GlobalEnv.getInstance(mContext).getRetrofit().create(RSunApi.class).getChallenge(token);
getChallengeQueue.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
String t;
try {
t = response.body().string();
try {
JSONObject jsonResponse = new JSONObject(t);
String rand = jsonResponse.getString("rand");
callback.challenge(rand);
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
callback.onFailure(new Error("连接失败"));
}
});
}
public void verifySign(final String token, final String sign, final String passwd, final LoginOpCallback callback){
String pwd;
if (passwd==null){
pwd = "";
}
else{
pwd = passwd;
}
Call<ResponseBody> verifySignQueue = GlobalEnv.getInstance(mContext).getRetrofit().create(RSunApi.class).verifySign(token,sign,pwd);
verifySignQueue.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
String t;
try {
t = response.body().string();
try {
JSONObject jsonResponse = new JSONObject(t);
boolean verify = jsonResponse.getBoolean("verify");
callback.onResponse(verify);
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
callback.onFailure(new Error("连接失败"));
}
});
}
}
| 39.603865 | 173 | 0.519029 |
a1ce92507836f5d2178c6b4525fa29d0cdae91a6 | 682 | package com.sibisoft.faizaniftikhartdd;
public abstract class Money
{
abstract Money times(int multiplier);
protected String currency;
protected int amount;
public Money()
{
}
Money(int amount, String currency)
{
this.amount = amount;
this.currency = currency;
}
public boolean equals(Object object)
{
Money money= (Money) object;
return amount == money.amount && getClass().equals(money.getClass());
}
public static Money dollar(int amount)
{
return new Dollar(amount,"USD");
}
public static Money franc(int amount)
{
return new Franc(amount,"CHF");
}
String currency()
{
return currency;
}
}
| 17.487179 | 72 | 0.653959 |
9893cd9e67a9addd5e4c0c2ce3be555dc37b1503 | 1,915 | /**
* ip:
* 10 -> 15 -> 5 -> 20
* ^ |
* |----------|
* op: 10 -> 15 -> 5 -> 20
*
* ip: 10 -> 15 -> 5
* op: 10 -> 15 -> 5
*
* Approach:
* 1) detect loop using Floyds algo
* 2) Move slow ptr to beginning of LL and keep fastptr to meeting point (meeting point is point where slowptr & fastptr point to same node)
* 3) Now move both slowptr and fastptr by 1 node(at same speed)
* The point where they meet now is the first node of the loop
*/
class Node {
int data;
Node next;
Node(int x)
{
data = x;
next = null;
}
}
public class detectandremove {
public static void main(String[] args) {
Node head = new Node(10);
head.next = new Node(15);
head.next.next = new Node(5);
head.next.next.next = new Node(20);
head.next.next.next.next = head.next;
detectAndRemoveLoop(head);
printList(head);
}
public static void detectAndRemoveLoop(Node head) {
Node slowptr = head, fastptr = head;
// loop detection
while (fastptr != null && fastptr.next != null) {
slowptr = slowptr.next;
fastptr = fastptr.next.next;
if (slowptr == fastptr)
break;
}
// no loop
if (slowptr != fastptr)
return;
// loop removal
slowptr = head;
// NOTE: we are comparing next's nodes
// since we want to get hold of lastnode
while (slowptr.next != fastptr.next) {
slowptr = slowptr.next;
fastptr = fastptr.next;
}
fastptr.next = null;
}
public static void printList(Node head) {
Node traverse = head;
while (traverse != null) {
System.out.print(traverse.data + "->");
traverse = traverse.next;
}
System.out.print("null\n");
}
}
| 24.87013 | 141 | 0.52376 |
f669e4c05dffcf108a8e3f26b7c578308bc92958 | 6,755 | /*
* Copyright 2017-2020 original 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 io.micronaut.starter.feature.awslambdacustomruntime;
import com.fizzed.rocker.RockerModel;
import io.micronaut.context.exceptions.ConfigurationException;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.starter.application.ApplicationType;
import io.micronaut.starter.application.Project;
import io.micronaut.starter.application.generator.GeneratorContext;
import io.micronaut.starter.feature.ApplicationFeature;
import io.micronaut.starter.feature.Category;
import io.micronaut.starter.feature.FeatureContext;
import io.micronaut.starter.feature.Features;
import io.micronaut.starter.feature.awslambdacustomruntime.templates.awsCustomRuntimeReadme;
import io.micronaut.starter.feature.awslambdacustomruntime.templates.bookLambdaRuntimeGroovy;
import io.micronaut.starter.feature.awslambdacustomruntime.templates.bookLambdaRuntimeJava;
import io.micronaut.starter.feature.awslambdacustomruntime.templates.bookLambdaRuntimeKotlin;
import io.micronaut.starter.feature.awslambdacustomruntime.templates.bootstrap;
import io.micronaut.starter.feature.function.Cloud;
import io.micronaut.starter.feature.function.CloudFeature;
import io.micronaut.starter.feature.function.FunctionFeature;
import io.micronaut.starter.feature.function.awslambda.AwsLambda;
import io.micronaut.starter.feature.graalvm.GraalVM;
import io.micronaut.starter.feature.other.HttpClient;
import io.micronaut.starter.template.RockerTemplate;
import io.micronaut.starter.template.RockerWritable;
import javax.inject.Provider;
import javax.inject.Singleton;
@Singleton
public class AwsLambdaCustomRuntime implements FunctionFeature, ApplicationFeature, CloudFeature {
public static final String MAIN_CLASS_NAME = "io.micronaut.function.aws.runtime.MicronautLambdaRuntime";
public static final String FEATURE_NAME_AWS_LAMBDA_CUSTOM_RUNTIME = "aws-lambda-custom-runtime";
private final Provider<AwsLambda> awsLambda;
private final HttpClient httpClient;
public AwsLambdaCustomRuntime(Provider<AwsLambda> awsLambda, HttpClient httpClient) {
this.awsLambda = awsLambda;
this.httpClient = httpClient;
}
@Override
public void processSelectedFeatures(FeatureContext featureContext) {
AwsLambda awsLambda = this.awsLambda.get();
if (awsLambda.supports(featureContext.getApplicationType()) && !featureContext.isPresent(AwsLambda.class)) {
featureContext.addFeature(awsLambda);
}
if (!featureContext.isPresent(HttpClient.class)) {
featureContext.addFeature(httpClient);
}
}
@Override
public String getName() {
return FEATURE_NAME_AWS_LAMBDA_CUSTOM_RUNTIME;
}
@Override
public boolean isVisible() {
return true;
}
@Override
public String getTitle() {
return "Custom AWS Lambda runtime";
}
@Override
public String getDescription() {
return "Adds support for deploying a Micronaut Function to a Custom AWS Lambda Runtime";
}
@SuppressWarnings("EmptyBlock")
@Override
public void apply(GeneratorContext generatorContext) {
ApplicationFeature.super.apply(generatorContext);
ApplicationType applicationType = generatorContext.getApplicationType();
Project project = generatorContext.getProject();
if (shouldGenerateMainClassForRuntime(generatorContext)) {
addBookLambdaRuntime(generatorContext, project);
}
addBootstrap(generatorContext, applicationType);
if (generatorContext.getFeatures().isFeaturePresent(GraalVM.class)) {
generatorContext.addHelpTemplate(new RockerWritable(awsCustomRuntimeReadme.template()));
}
}
public boolean shouldGenerateMainClassForRuntime(GeneratorContext generatorContext) {
return generatorContext.getApplicationType() == ApplicationType.FUNCTION &&
generatorContext.getFeatures().isFeaturePresent(AwsLambda.class);
}
private void addBootstrap(GeneratorContext generatorContext, ApplicationType applicationType) {
RockerModel bootstrapRockerModel = bootstrap.template(
applicationType,
generatorContext.getProject(),
generatorContext.getBuildTool(),
generatorContext.getFeatures()
);
generatorContext.addTemplate("bootstrap", new RockerTemplate("bootstrap", bootstrapRockerModel));
}
@Override
@Nullable
public String mainClassName(GeneratorContext generatorContext) {
Features features = generatorContext.getFeatures();
if (features.isFeaturePresent(AwsLambda.class)) {
ApplicationType applicationType = generatorContext.getApplicationType();
if (applicationType == ApplicationType.DEFAULT) {
return AwsLambdaCustomRuntime.MAIN_CLASS_NAME;
} else if (applicationType == ApplicationType.FUNCTION) {
return generatorContext.getProject().getPackageName() + ".BookLambdaRuntime";
}
}
throw new ConfigurationException("aws-lambda-custom-runtime should be used together with aws-lambda or aws-gateway-lambda-proxy");
}
private void addBookLambdaRuntime(GeneratorContext generatorContext, Project project) {
String bookLambdaRuntime = generatorContext.getSourcePath("/{packagePath}/BookLambdaRuntime");
generatorContext.addTemplate("bookLambdaRuntime", bookLambdaRuntime,
bookLambdaRuntimeJava.template(project),
bookLambdaRuntimeKotlin.template(project),
bookLambdaRuntimeGroovy.template(project));
}
@Override
public String getCategory() {
return Category.SERVERLESS;
}
@Override
public Cloud getCloud() {
return Cloud.AWS;
}
@Override
public String getMicronautDocumentation() {
return "https://micronaut-projects.github.io/micronaut-aws/latest/guide/index.html#lambdaCustomRuntimes";
}
@Override
public String getThirdPartyDocumentation() {
return "https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html";
}
}
| 41.189024 | 138 | 0.743597 |
8eac79cada57362c0f44ce24a8f184b4c449cc4b | 1,784 | /*
* 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
* <p>
* 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 br.ufrn.imd.obd.commands.control;
import br.ufrn.imd.obd.commands.ObdCommand;
import br.ufrn.imd.obd.enums.AvailableCommand;
/**
* Time Traveled with MIL On.
*/
public class TimeSinceMILOnCommand extends ObdCommand {
private int value = 0;
/**
* Default constructor.
*/
public TimeSinceMILOnCommand() {
super(AvailableCommand.TIME_TRAVELED_MIL_ON);
}
/**
* Copy constructor.
*
* @param other a {@link TimeSinceMILOnCommand} object.
*/
public TimeSinceMILOnCommand(TimeSinceMILOnCommand other) {
super(other);
}
/**
* {@inheritDoc}
*/
@Override
protected void performCalculations() {
// ignore first two bytes [01 4D] of the response
value = buffer.get(2) * 256 + buffer.get(3);
}
/**
* {@inheritDoc}
*/
@Override
public String getFormattedResult() {
return getCalculatedResult() + getResultUnit();
}
/**
* {@inheritDoc}
*/
@Override
public String getCalculatedResult() {
return String.valueOf(value);
}
/**
* {@inheritDoc}
*/
@Override
public String getResultUnit() {
return "min";
}
}
| 23.473684 | 80 | 0.640695 |
a02156380e265b6387d82db2d71611489714bad8 | 351 | package com.aghajari.axvideotimelineview;
public interface AXTimelineViewListener {
void onLeftProgressChanged(float progress);
void onRightProgressChanged(float progress);
void onDurationChanged(long Duration);
void onPlayProgressChanged(float progress);
void onDraggingStateChanged(boolean isDragging);
} | 39 | 56 | 0.754986 |
a3398574553abb9fd7320aff4a102f34b8053576 | 287 | package com.zcwfeng.fastdev.ui.fragment.request.demo;
public class Contributor {
public final String login;
public final int contributions;
public Contributor(String login, int contributions) {
this.login = login;
this.contributions = contributions;
}
} | 26.090909 | 57 | 0.710801 |
76bb7303d04a35275efb45fddf80bb0dba8b9da3 | 6,395 | /**
* Copyright 2014 AnjLab
*
* 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.anjlab.tapestry5.services.quartz;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Properties;
import org.apache.tapestry5.ioc.MappedConfiguration;
import org.apache.tapestry5.ioc.Resource;
import org.apache.tapestry5.ioc.ServiceBinder;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Startup;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.ioc.services.PerthreadManager;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.listeners.JobListenerSupport;
import org.quartz.spi.JobFactory;
import org.slf4j.Logger;
public class QuartzModule
{
public static final String QUARTZ_PROPERTIES = "quartz.properties";
public static final String WAIT_FOR_JOBS_TO_COMPLETE = "org.quartz.scheduler.waitForJobsToComplete";
public static final String START_SCHEDULERS = "org.quartz.scheduler.start";
public static void bind(ServiceBinder binder)
{
binder.bind(JobFactory.class, QuatrzJobFactory.class);
}
public static void contributeFactoryDefaults(MappedConfiguration<String, Object> configuration)
{
configuration.add(WAIT_FOR_JOBS_TO_COMPLETE, "false");
configuration.add(START_SCHEDULERS, "true");
}
public static void contributeSchedulerFactory(MappedConfiguration<String, Object> configuration)
{
configuration.add("org.quartz.scheduler.skipUpdateCheck", "true");
configuration.add("org.quartz.scheduler.instanceName", "TapestryQuartz");
configuration.add("org.quartz.threadPool.threadCount", "3");
configuration.add("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore");
}
public static SchedulerFactory buildSchedulerFactory(
Map<String, Object> configuration) throws SchedulerException, IOException
{
StdSchedulerFactory sf = new StdSchedulerFactory();
if (configuration.containsKey(QUARTZ_PROPERTIES))
{
Object properties = configuration.get(QUARTZ_PROPERTIES);
if (properties instanceof String)
{
sf.initialize((String) properties);
}
else if (properties instanceof Properties)
{
sf.initialize((Properties) properties);
}
else if (properties instanceof InputStream)
{
sf.initialize((InputStream) properties);
}
else if (properties instanceof Resource)
{
sf.initialize(((Resource) properties).openStream());
}
else
{
throw new RuntimeException("Unsupported type of " + QUARTZ_PROPERTIES);
}
}
else
{
Properties properties = new Properties();
properties.putAll(configuration);
sf.initialize(properties);
}
return sf;
}
public static Scheduler buildScheduler(SchedulerFactory schedulerFactory, JobFactory jobFactory)
throws SchedulerException
{
Scheduler scheduler = schedulerFactory.getScheduler();
scheduler.setJobFactory(jobFactory);
return scheduler;
}
@Startup
public static void startup(
final Logger logger,
final SchedulerFactory schedulerFactory,
final PerthreadManager perthreadManager,
RegistryShutdownHub shutdownHub,
@Inject @Symbol(WAIT_FOR_JOBS_TO_COMPLETE)
final boolean waitForJobsToComplete,
@Inject @Symbol(START_SCHEDULERS)
final boolean startSchedulers) throws SchedulerException
{
final JobListenerSupport cleanupThread = new JobListenerSupport()
{
@Override
public String getName()
{
return "PerthreadManager.cleanup()";
}
@Override
public void jobWasExecuted(JobExecutionContext context,
JobExecutionException jobException)
{
perthreadManager.cleanup();
}
};
Collection<Scheduler> allSchedulers = new ArrayList<Scheduler>();
allSchedulers.addAll(schedulerFactory.getAllSchedulers());
allSchedulers.add(schedulerFactory.getScheduler());
for (Scheduler scheduler : allSchedulers)
{
if (!scheduler.isStarted())
{
scheduler.getListenerManager().addJobListener(cleanupThread);
if (startSchedulers)
{
scheduler.start();
}
}
}
shutdownHub.addRegistryWillShutdownListener(new Runnable()
{
@Override
public void run()
{
try
{
for (Scheduler scheduler : schedulerFactory.getAllSchedulers())
{
scheduler.shutdown(waitForJobsToComplete);
}
}
catch (SchedulerException e)
{
logger.error("Error shutting down scheduler", e);
}
}
});
}
}
| 34.945355 | 104 | 0.619703 |
6be741c0fb9505d98b065bc19f44ba02e4d32e9a | 2,212 | package com.linkedin.databus.client.registration;
/*
*
* Copyright 2013 LinkedIn Corp. 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.
*
*/
public class ClusterRegistrationStaticConfig
{
/**
* Cluster Name
*/
private final String _clusterName;
/**
* ZK HostPort config seperated by colon
*/
private final String _zkAddr;
/**
* Total number of partitions for this cluster.
*/
private final long _numPartitions;
/**
* Minimum number of nodes to be active before partitions can be allocated.
*/
private final long _quorum;
/**
* Number of checkpoints that can skipped before persisting the progress in ZooKeeper.
* This is an optimization to reduce the ZK overhead during checkpointing.
*/
private final int _maxCkptWritesSkipped;
public ClusterRegistrationStaticConfig(String clusterName, String zkAddr,
long numPartitions, long quorum, int maxCkptWritesSkipped) {
super();
this._clusterName = clusterName;
this._zkAddr = zkAddr;
this._numPartitions = numPartitions;
this._quorum = quorum;
this._maxCkptWritesSkipped = maxCkptWritesSkipped;
}
public String getClusterName() {
return _clusterName;
}
public String getZkAddr() {
return _zkAddr;
}
public long getNumPartitions() {
return _numPartitions;
}
public long getQuorum() {
return _quorum;
}
public int getMaxCkptWritesSkipped() {
return _maxCkptWritesSkipped;
}
@Override
public String toString() {
return "ClusterRegistrationStaticConfig [clusterName=" + _clusterName
+ ", zkAddr=" + _zkAddr + ", numPartitions=" + _numPartitions
+ ", quorum=" + _quorum + ", maxCkptWritesSkipped="
+ _maxCkptWritesSkipped + "]";
}
}
| 25.136364 | 87 | 0.729204 |
62e7d2f074159eafdd3381518d5e61f02143756d | 2,076 | /*
* This file is part of BlueMap, licensed under the MIT License (MIT).
*
* Copyright (c) Blue (Lukas Rieger) <https://bluecolored.de>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.bluecolored.bluemap.core.render;
import com.flowpowered.math.vector.Vector3i;
public class StaticRenderSettings implements RenderSettings {
private boolean excludeFacesWithoutSunlight;
private Vector3i min, max;
private boolean renderEdges;
public StaticRenderSettings(
boolean excludeFacesWithoutSunlight,
Vector3i min,
Vector3i max,
boolean renderEdges
) {
this.excludeFacesWithoutSunlight = excludeFacesWithoutSunlight;
this.min = min;
this.max = max;
this.renderEdges = renderEdges;
}
@Override
public boolean isExcludeFacesWithoutSunlight() {
return excludeFacesWithoutSunlight;
}
@Override
public Vector3i getMin() {
return min;
}
@Override
public Vector3i getMax() {
return max;
}
@Override
public boolean isRenderEdges() {
return renderEdges;
}
} | 30.985075 | 80 | 0.757225 |
518e55b4bd563cfeb499ce416561c453c9f3b963 | 10,155 | package com.project.askit.controller;
import com.project.askit.entity.Role;
import com.project.askit.entity.User;
import com.project.askit.model.ErrorModel;
import com.project.askit.model.MessageModel;
import com.project.askit.util.Pair;
import com.project.askit.util.Utility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
public abstract class AbstractPageController {
public final String NOT_LOGGED_IN = "Not logged in";
public final String NOT_AUTHORIZED = "Not authorized";
public final String REST_API_CALL_FAILED = "Rest API call failed";
public final String INVALID_FIELDS = "Invalid fields";
public final String ALREADY_EXISTS = "Already exists";
public final String INVALID_USER_ID = "Invalid user ID";
public final String PASSWORDS_NOT_MATCH = "Passwords do not match";
public final String INVALID_CREDENTIALS = "Invalid credentials";
public final String INVALID_PASSWORD = "Invalid password";
public final String INVALID_ACCOUNT = "Invalid account";
public final String INVALID_LINK = "Invalid link";
public final String ALREADY_ACTIVE = "Already active";
public final String NOT_FOUND = "Not found";
@Autowired
public AbstractPageController() {
}
protected User getSessionUser(HttpServletRequest request) {
return (User) request.getSession().getAttribute("user");
}
protected boolean isLoggedIn(HttpServletRequest request) {
return getSessionUser(request) != null;
}
protected boolean hasAccess(HttpServletRequest request,
String accessRole) {
if (!isLoggedIn(request)) return false;
for (Role role : getSessionUser(request).getRoles())
if (role.getName().equalsIgnoreCase(accessRole))
return true;
return false;
}
protected RedirectView handleNotLoggedIn(RedirectAttributes redirectAttributes) {
MessageModel messageModel = new MessageModel();
messageModel.setMessage(NOT_LOGGED_IN);
messageModel.setType(MessageModel.TYPE_WARNING);
List<Pair<String, String>> details = new ArrayList<>();
details.add(new Pair<>(null, "You must be logged in to access this page"));
messageModel.setDetails(details);
redirectAttributes.addFlashAttribute("messageModel", messageModel);
return new RedirectView("/login", true);
}
protected RedirectView handleRestApiCallFailed(RedirectAttributes redirectAttributes) {
ErrorModel errorModel = new ErrorModel();
errorModel.setCode(HttpStatus.SERVICE_UNAVAILABLE.value());
List<String> details = new ArrayList<>();
details.add("Something went wrong while processing your request");
errorModel.setDetails(details);
redirectAttributes.addFlashAttribute("errorModel", errorModel);
return new RedirectView("/error", true);
}
protected RedirectView handleSomethingWentWrong(RedirectAttributes redirectAttributes) {
ErrorModel errorModel = new ErrorModel();
errorModel.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
List<String> details = new ArrayList<>();
details.add("Something went wrong. Please try again.");
errorModel.setDetails(details);
redirectAttributes.addFlashAttribute("errorModel", errorModel);
return new RedirectView("/error", true);
}
protected RedirectView handleNotAuthorized(RedirectAttributes redirectAttributes) {
ErrorModel errorModel = new ErrorModel();
errorModel.setCode(HttpStatus.UNAUTHORIZED.value());
List<String> details = new ArrayList<>();
details.add("You do not have permission to access this page");
errorModel.setDetails(details);
redirectAttributes.addFlashAttribute("errorModel", errorModel);
return new RedirectView("/error", true);
}
protected void handleInvalidFields(RedirectAttributes redirectAttributes,
BindingResult result) {
// Create message
MessageModel messageModel = new MessageModel();
messageModel.setMessage(INVALID_FIELDS);
messageModel.setType(MessageModel.TYPE_ERROR);
List<Pair<String, String>> details = new ArrayList<>();
for (FieldError error : result.getFieldErrors()) {
details.add(new Pair<>(Utility.capitalizeAndSeparate(error.getField()), error.getDefaultMessage()));
}
messageModel.setDetails(details);
// Add data to redirect view
redirectAttributes.addFlashAttribute("messageModel", messageModel);
}
protected void handleAlreadyExists(RedirectAttributes redirectAttributes,
String objectName) {
// Create message
MessageModel messageModel = new MessageModel();
messageModel.setMessage(ALREADY_EXISTS);
messageModel.setType(MessageModel.TYPE_ERROR);
List<Pair<String, String>> details = new ArrayList<>();
details.add(new Pair<>(objectName, "already exists"));
messageModel.setDetails(details);
// Add data to redirect view
redirectAttributes.addFlashAttribute("messageModel", messageModel);
}
protected void handleInvalidUserId(RedirectAttributes redirectAttributes) {
// Create message
MessageModel messageModel = new MessageModel();
messageModel.setMessage(INVALID_USER_ID);
messageModel.setType(MessageModel.TYPE_ERROR);
List<Pair<String, String>> details = new ArrayList<>();
details.add(new Pair<>("User ID", "does not exist"));
messageModel.setDetails(details);
// Add data to redirect view
redirectAttributes.addFlashAttribute("messageModel", messageModel);
}
protected void handlePasswordsNotMatch(RedirectAttributes redirectAttributes) {
// Create message
MessageModel messageModel = new MessageModel();
messageModel.setMessage(INVALID_FIELDS);
messageModel.setType(MessageModel.TYPE_ERROR);
List<Pair<String, String>> details = new ArrayList<>();
details.add(new Pair<>(null, "Password and confirm password do not match"));
messageModel.setDetails(details);
// Add data to redirect view
redirectAttributes.addFlashAttribute("messageModel", messageModel);
}
protected void handleInvalidCredentials(RedirectAttributes redirectAttributes) {
// Create message
MessageModel messageModel = new MessageModel();
messageModel.setMessage(INVALID_CREDENTIALS);
messageModel.setType(MessageModel.TYPE_ERROR);
List<Pair<String, String>> details = new ArrayList<>();
details.add(new Pair<>(null, "Your email or password are incorrect"));
messageModel.setDetails(details);
// Add data to redirect view
redirectAttributes.addFlashAttribute("messageModel", messageModel);
}
protected void handleInvalidPassword(RedirectAttributes redirectAttributes) {
// Create message
MessageModel messageModel = new MessageModel();
messageModel.setMessage(INVALID_PASSWORD);
messageModel.setType(MessageModel.TYPE_ERROR);
List<Pair<String, String>> details = new ArrayList<>();
details.add(new Pair<>(null, "You password is not correct"));
messageModel.setDetails(details);
// Add data to redirect view
redirectAttributes.addFlashAttribute("messageModel", messageModel);
}
protected void handleInvalidAccount(RedirectAttributes redirectAttributes) {
// Create message
MessageModel messageModel = new MessageModel();
messageModel.setMessage(INVALID_ACCOUNT);
messageModel.setType(MessageModel.TYPE_ERROR);
List<Pair<String, String>> details = new ArrayList<>();
details.add(new Pair<>(null, "Your account is either inactive or blocked"));
messageModel.setDetails(details);
// Add data to redirect view
redirectAttributes.addFlashAttribute("messageModel", messageModel);
}
protected void handleInvalidLink(RedirectAttributes redirectAttributes) {
// Create message
MessageModel messageModel = new MessageModel();
messageModel.setMessage(INVALID_LINK);
messageModel.setType(MessageModel.TYPE_ERROR);
List<Pair<String, String>> details = new ArrayList<>();
details.add(new Pair<>(null, "The link is expired or incorrect"));
details.add(new Pair<>(null, "Please try to repeat the process"));
messageModel.setDetails(details);
// Add data to redirect view
redirectAttributes.addFlashAttribute("messageModel", messageModel);
}
protected void handleAlreadyActive(RedirectAttributes redirectAttributes) {
// Create message
MessageModel messageModel = new MessageModel();
messageModel.setMessage(ALREADY_ACTIVE);
messageModel.setType(MessageModel.TYPE_ERROR);
List<Pair<String, String>> details = new ArrayList<>();
details.add(new Pair<>(null, "Your account has already been activated"));
details.add(new Pair<>(null, "No further actions are required"));
messageModel.setDetails(details);
redirectAttributes.addFlashAttribute("messageModel", messageModel);
}
protected RedirectView handleNotFound(RedirectAttributes redirectAttributes) {
int code = HttpStatus.NOT_FOUND.value();
List<String> details = new ArrayList<>();
details.add("The resource could not be found");
redirectAttributes.addFlashAttribute("errorModel", new ErrorModel(code, details));
return new RedirectView("/error", true);
}
} | 39.057692 | 112 | 0.699852 |
40ce4f038ab79eee84d850bf551ebd149b313d13 | 3,126 | /*
* Copyright 2019 The Hekate Project
*
* The Hekate 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 io.hekate.rpc;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.CompletableFuture;
/**
* Enables broadcast on RPC interface's methods.
*
* <p>
* This annotation can be placed on a method of an @{@link Rpc}-enabled interface in order to execute such RPC method on all of the RPC
* cluster nodes in parallel.
* </p>
*
* <p>
* Methods that are annotated with {@link RpcBroadcast} must have a {@code void} (for synchronous calls) or a {@link CompletableFuture}
* (for asynchronous calls) return type. If method is declared as returning an a {@link CompletableFuture} then it is recommended to
* parametrise such future with {@code <?>} or {@code <Void>} as such futures are always get completed with a {@code null} value by the RPC
* service.
* </p>
*
* <p>
* Aggregation error handling policy can be specified in {@link #remoteErrors()} attribute:
* </p>
* <ul>
* <li>{@link RemoteErrors#IGNORE} - Ignore all remote errors and return whatever results were successfully aggregated or an empty result
* if
* RPC failed on all nodes.</li>
* <li>{@link RemoteErrors#WARN} - Same as {@link RemoteErrors#IGNORE} but also logs a WARN message for each failure.</li>
* <li>{@link RemoteErrors#FAIL} - In case of any error fail the whole aggregation with {@link RpcAggregateException}.</li>
* </ul>
*
* <p>
* For more details about the Remote Procedure Call API and its capabilities please see the documentation of the {@link RpcService}
* interface.
* </p>
*/
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RpcBroadcast {
/**
* Remote errors handling policy for RPC aggregation.
*/
enum RemoteErrors {
/**
* Ignore all remote errors.
*/
IGNORE,
/**
* Same as {@link #IGNORE} but also logs a WARN message for each failure.
*/
WARN,
/**
* In case of any error fail the whole aggregation with {@link RpcAggregateException}.
*
* @see RpcAggregateException#errors()
*/
FAIL
}
/**
* Remote errors handling policy (see description of {@link RemoteErrors}'s values).
*
* @return Remote errors handling policy.
*/
RemoteErrors remoteErrors() default RemoteErrors.FAIL;
}
| 34.733333 | 139 | 0.694818 |
f7cd19097b6a9ddc4a5a18bba55c0ea2ba8937ba | 21,221 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.ql.planner;
import org.elasticsearch.common.time.DateFormatter;
import org.elasticsearch.xpack.ql.QlIllegalArgumentException;
import org.elasticsearch.xpack.ql.expression.Expression;
import org.elasticsearch.xpack.ql.expression.Expressions;
import org.elasticsearch.xpack.ql.expression.FieldAttribute;
import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction;
import org.elasticsearch.xpack.ql.expression.function.scalar.string.StartsWith;
import org.elasticsearch.xpack.ql.expression.predicate.Range;
import org.elasticsearch.xpack.ql.expression.predicate.fulltext.MatchQueryPredicate;
import org.elasticsearch.xpack.ql.expression.predicate.fulltext.MultiMatchQueryPredicate;
import org.elasticsearch.xpack.ql.expression.predicate.fulltext.StringQueryPredicate;
import org.elasticsearch.xpack.ql.expression.predicate.logical.And;
import org.elasticsearch.xpack.ql.expression.predicate.logical.Not;
import org.elasticsearch.xpack.ql.expression.predicate.logical.Or;
import org.elasticsearch.xpack.ql.expression.predicate.nulls.IsNotNull;
import org.elasticsearch.xpack.ql.expression.predicate.nulls.IsNull;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparison;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.Equals;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.GreaterThan;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.GreaterThanOrEqual;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.In;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.LessThan;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.LessThanOrEqual;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.NotEquals;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.NullEquals;
import org.elasticsearch.xpack.ql.expression.predicate.regex.Like;
import org.elasticsearch.xpack.ql.expression.predicate.regex.RLike;
import org.elasticsearch.xpack.ql.expression.predicate.regex.RegexMatch;
import org.elasticsearch.xpack.ql.querydsl.query.BoolQuery;
import org.elasticsearch.xpack.ql.querydsl.query.ExistsQuery;
import org.elasticsearch.xpack.ql.querydsl.query.MatchQuery;
import org.elasticsearch.xpack.ql.querydsl.query.MultiMatchQuery;
import org.elasticsearch.xpack.ql.querydsl.query.NotQuery;
import org.elasticsearch.xpack.ql.querydsl.query.PrefixQuery;
import org.elasticsearch.xpack.ql.querydsl.query.Query;
import org.elasticsearch.xpack.ql.querydsl.query.QueryStringQuery;
import org.elasticsearch.xpack.ql.querydsl.query.RangeQuery;
import org.elasticsearch.xpack.ql.querydsl.query.RegexQuery;
import org.elasticsearch.xpack.ql.querydsl.query.ScriptQuery;
import org.elasticsearch.xpack.ql.querydsl.query.TermQuery;
import org.elasticsearch.xpack.ql.querydsl.query.TermsQuery;
import org.elasticsearch.xpack.ql.querydsl.query.WildcardQuery;
import org.elasticsearch.xpack.ql.tree.Source;
import org.elasticsearch.xpack.ql.type.DataType;
import org.elasticsearch.xpack.ql.type.DataTypes;
import org.elasticsearch.xpack.ql.util.Check;
import org.elasticsearch.xpack.ql.util.CollectionUtils;
import org.elasticsearch.xpack.ql.util.Holder;
import java.time.OffsetTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.TemporalAccessor;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public final class ExpressionTranslators {
public static final String DATE_FORMAT = "strict_date_optional_time_nanos";
public static final String TIME_FORMAT = "strict_hour_minute_second_fraction";
public static final List<ExpressionTranslator<?>> QUERY_TRANSLATORS = List.of(
new BinaryComparisons(),
new Ranges(),
new BinaryLogic(),
new IsNulls(),
new IsNotNulls(),
new Nots(),
new Likes(),
new InComparisons(),
new StringQueries(),
new Matches(),
new MultiMatches(),
new Scalars()
);
public static Query toQuery(Expression e) {
return toQuery(e, new QlTranslatorHandler());
}
public static Query toQuery(Expression e, TranslatorHandler handler) {
Query translation = null;
for (ExpressionTranslator<?> translator : QUERY_TRANSLATORS) {
translation = translator.translate(e, handler);
if (translation != null) {
return translation;
}
}
throw new QlIllegalArgumentException("Don't know how to translate {} {}", e.nodeName(), e);
}
public static Object valueOf(Expression e) {
if (e.foldable()) {
return e.fold();
}
throw new QlIllegalArgumentException("Cannot determine value for {}", e);
}
// TODO: see whether escaping is needed
@SuppressWarnings("rawtypes")
public static class Likes extends ExpressionTranslator<RegexMatch> {
@Override
protected Query asQuery(RegexMatch e, TranslatorHandler handler) {
return doTranslate(e, handler);
}
public static Query doTranslate(RegexMatch e, TranslatorHandler handler) {
Query q = null;
String targetFieldName = null;
if (e.field() instanceof FieldAttribute) {
targetFieldName = handler.nameOf(((FieldAttribute) e.field()).exactAttribute());
if (e instanceof Like) {
Like l = (Like) e;
q = new WildcardQuery(e.source(), targetFieldName, l.pattern().asLuceneWildcard(), l.caseInsensitive());
}
if (e instanceof RLike) {
String pattern = ((RLike) e).pattern().asJavaRegex();
q = new RegexQuery(e.source(), targetFieldName, pattern);
}
} else {
q = new ScriptQuery(e.source(), e.asScript());
}
return wrapIfNested(q, e.field());
}
}
public static class StringQueries extends ExpressionTranslator<StringQueryPredicate> {
@Override
protected Query asQuery(StringQueryPredicate q, TranslatorHandler handler) {
return doTranslate(q, handler);
}
public static Query doTranslate(StringQueryPredicate q, TranslatorHandler handler) {
return new QueryStringQuery(q.source(), q.query(), q.fields(), q);
}
}
public static class Matches extends ExpressionTranslator<MatchQueryPredicate> {
@Override
protected Query asQuery(MatchQueryPredicate q, TranslatorHandler handler) {
return doTranslate(q, handler);
}
public static Query doTranslate(MatchQueryPredicate q, TranslatorHandler handler) {
return new MatchQuery(q.source(), handler.nameOf(q.field()), q.query(), q);
}
}
public static class MultiMatches extends ExpressionTranslator<MultiMatchQueryPredicate> {
@Override
protected Query asQuery(MultiMatchQueryPredicate q, TranslatorHandler handler) {
return doTranslate(q, handler);
}
public static Query doTranslate(MultiMatchQueryPredicate q, TranslatorHandler handler) {
return new MultiMatchQuery(q.source(), q.query(), q.fields(), q);
}
}
public static class BinaryLogic extends ExpressionTranslator<org.elasticsearch.xpack.ql.expression.predicate.logical.BinaryLogic> {
@Override
protected Query asQuery(org.elasticsearch.xpack.ql.expression.predicate.logical.BinaryLogic e, TranslatorHandler handler) {
if (e instanceof And) {
return and(e.source(), toQuery(e.left(), handler), toQuery(e.right(), handler));
}
if (e instanceof Or) {
return or(e.source(), toQuery(e.left(), handler), toQuery(e.right(), handler));
}
return null;
}
}
public static class Nots extends ExpressionTranslator<Not> {
@Override
protected Query asQuery(Not not, TranslatorHandler handler) {
return doTranslate(not, handler);
}
public static Query doTranslate(Not not, TranslatorHandler handler) {
Expression e = not.field();
Query wrappedQuery = handler.asQuery(not.field());
Query q = wrappedQuery instanceof ScriptQuery ?
new ScriptQuery(not.source(), not.asScript()) :
new NotQuery(not.source(), wrappedQuery);
return wrapIfNested(q, e);
}
}
public static class IsNotNulls extends ExpressionTranslator<IsNotNull> {
@Override
protected Query asQuery(IsNotNull isNotNull, TranslatorHandler handler) {
return doTranslate(isNotNull, handler);
}
public static Query doTranslate(IsNotNull isNotNull, TranslatorHandler handler) {
Query query = null;
if (isNotNull.field() instanceof FieldAttribute) {
query = new ExistsQuery(isNotNull.source(), handler.nameOf(isNotNull.field()));
} else {
query = new ScriptQuery(isNotNull.source(), isNotNull.asScript());
}
return handler.wrapFunctionQuery(isNotNull, isNotNull.field(), query);
}
}
public static class IsNulls extends ExpressionTranslator<IsNull> {
@Override
protected Query asQuery(IsNull isNull, TranslatorHandler handler) {
return doTranslate(isNull, handler);
}
public static Query doTranslate(IsNull isNull, TranslatorHandler handler) {
Query query = null;
if (isNull.field() instanceof FieldAttribute) {
query = new NotQuery(isNull.source(), new ExistsQuery(isNull.source(), handler.nameOf(isNull.field())));
} else {
query = new ScriptQuery(isNull.source(), isNull.asScript());
}
return handler.wrapFunctionQuery(isNull, isNull.field(), query);
}
}
// assume the Optimizer properly orders the predicates to ease the translation
public static class BinaryComparisons extends ExpressionTranslator<BinaryComparison> {
@Override
protected Query asQuery(BinaryComparison bc, TranslatorHandler handler) {
return doTranslate(bc, handler);
}
public static void checkBinaryComparison(BinaryComparison bc) {
Check.isTrue(bc.right().foldable(),
"Line {}:{}: Comparisons against fields are not (currently) supported; offender [{}] in [{}]",
bc.right().sourceLocation().getLineNumber(), bc.right().sourceLocation().getColumnNumber(),
Expressions.name(bc.right()), bc.symbol());
}
public static Query doTranslate(BinaryComparison bc, TranslatorHandler handler) {
checkBinaryComparison(bc);
return handler.wrapFunctionQuery(bc, bc.left(), translate(bc, handler));
}
private static Query translate(BinaryComparison bc, TranslatorHandler handler) {
Source source = bc.source();
String name = handler.nameOf(bc.left());
Object value = valueOf(bc.right());
String format = handler.dateFormat(bc.left());
boolean isDateLiteralComparison = false;
// for a date constant comparison, we need to use a format for the date, to make sure that the format is the same
// no matter the timezone provided by the user
if ((value instanceof ZonedDateTime || value instanceof OffsetTime) && format == null) {
DateFormatter formatter;
if (value instanceof ZonedDateTime) {
formatter = DateFormatter.forPattern(DATE_FORMAT);
// RangeQueryBuilder accepts an Object as its parameter, but it will call .toString() on the ZonedDateTime instance
// which can have a slightly different format depending on the ZoneId used to create the ZonedDateTime
// Since RangeQueryBuilder can handle date as String as well, we'll format it as String and provide the format as well.
value = formatter.format((ZonedDateTime) value);
} else {
formatter = DateFormatter.forPattern(TIME_FORMAT);
value = formatter.format((OffsetTime) value);
}
format = formatter.pattern();
isDateLiteralComparison = true;
}
ZoneId zoneId = null;
if (DataTypes.isDateTime(bc.left().dataType())) {
zoneId = bc.zoneId();
}
if (bc instanceof GreaterThan) {
return new RangeQuery(source, name, value, false, null, false, format, zoneId);
}
if (bc instanceof GreaterThanOrEqual) {
return new RangeQuery(source, name, value, true, null, false, format, zoneId);
}
if (bc instanceof LessThan) {
return new RangeQuery(source, name, null, false, value, false, format, zoneId);
}
if (bc instanceof LessThanOrEqual) {
return new RangeQuery(source, name, null, false, value, true, format, zoneId);
}
if (bc instanceof Equals || bc instanceof NullEquals || bc instanceof NotEquals) {
if (bc.left() instanceof FieldAttribute) {
// equality should always be against an exact match
// (which is important for strings)
name = ((FieldAttribute) bc.left()).exactAttribute().name();
}
Query query;
if (isDateLiteralComparison) {
// dates equality uses a range query because it's the one that has a "format" parameter
query = new RangeQuery(source, name, value, true, value, true, format, zoneId);
} else {
query = new TermQuery(source, name, value);
}
if (bc instanceof NotEquals) {
query = new NotQuery(source, query);
}
return query;
}
throw new QlIllegalArgumentException("Don't know how to translate binary comparison [{}] in [{}]", bc.right().nodeString(),
bc);
}
}
public static class Ranges extends ExpressionTranslator<Range> {
@Override
protected Query asQuery(Range r, TranslatorHandler handler) {
return doTranslate(r, handler);
}
public static Query doTranslate(Range r, TranslatorHandler handler) {
Expression val = r.value();
Query query = null;
Holder<Object> lower = new Holder<>(valueOf(r.lower()));
Holder<Object> upper = new Holder<>(valueOf(r.upper()));
Holder<String> format = new Holder<>(handler.dateFormat(val));
// for a date constant comparison, we need to use a format for the date, to make sure that the format is the same
// no matter the timezone provided by the user
if (format.get() == null) {
DateFormatter formatter = null;
if (lower.get() instanceof ZonedDateTime || upper.get() instanceof ZonedDateTime) {
formatter = DateFormatter.forPattern(DATE_FORMAT);
} else if (lower.get() instanceof OffsetTime || upper.get() instanceof OffsetTime) {
formatter = DateFormatter.forPattern(TIME_FORMAT);
}
if (formatter != null) {
// RangeQueryBuilder accepts an Object as its parameter, but it will call .toString() on the ZonedDateTime
// instance which can have a slightly different format depending on the ZoneId used to create the ZonedDateTime
// Since RangeQueryBuilder can handle date as String as well, we'll format it as String and provide the format.
if (lower.get() instanceof ZonedDateTime || lower.get() instanceof OffsetTime) {
lower.set(formatter.format((TemporalAccessor) lower.get()));
}
if (upper.get() instanceof ZonedDateTime || upper.get() instanceof OffsetTime) {
upper.set(formatter.format((TemporalAccessor) upper.get()));
}
format.set(formatter.pattern());
}
}
query = handler.wrapFunctionQuery(r, val, new RangeQuery(r.source(), handler.nameOf(val), lower.get(), r.includeLower(),
upper.get(), r.includeUpper(), format.get(), r.zoneId()));
return query;
}
}
public static class InComparisons extends ExpressionTranslator<In> {
@Override
protected Query asQuery(In in, TranslatorHandler handler) {
return doTranslate(in, handler);
}
public static Query doTranslate(In in, TranslatorHandler handler) {
Query q;
if (in.value() instanceof FieldAttribute) {
// equality should always be against an exact match (which is important for strings)
FieldAttribute fa = (FieldAttribute) in.value();
DataType dt = fa.dataType();
List<Expression> list = in.list();
Set<Object> set = new LinkedHashSet<>(CollectionUtils.mapSize(list.size()));
list.forEach(e -> {
// TODO: this needs to be handled inside the optimizer
if (DataTypes.isNull(e.dataType()) == false) {
set.add(handler.convert(valueOf(e), dt));
}
});
if (DataTypes.isDateTime(dt)) {
DateFormatter formatter = DateFormatter.forPattern(DATE_FORMAT);
q = null;
for (Object o : set) {
assert o instanceof ZonedDateTime : "expected a ZonedDateTime, but got: " + o.getClass().getName();
// see comment in Ranges#doTranslate() as to why formatting as String is required
String zdt = formatter.format((ZonedDateTime) o);
RangeQuery right = new RangeQuery(in.source(), fa.exactAttribute().name(),
zdt, true, zdt, true, formatter.pattern(), in.zoneId());
q = q == null ? right : new BoolQuery(in.source(), false, q, right);
}
} else {
q = new TermsQuery(in.source(), fa.exactAttribute().name(), set);
}
} else {
q = new ScriptQuery(in.source(), in.asScript());
}
return handler.wrapFunctionQuery(in, in.value(), q);
}
}
public static class Scalars extends ExpressionTranslator<ScalarFunction> {
@Override
protected Query asQuery(ScalarFunction f, TranslatorHandler handler) {
return doTranslate(f, handler);
}
public static Query doTranslate(ScalarFunction f, TranslatorHandler handler) {
Query q = doKnownTranslate(f, handler);
if (q != null) {
return q;
}
return handler.wrapFunctionQuery(f, f, new ScriptQuery(f.source(), f.asScript()));
}
public static Query doKnownTranslate(ScalarFunction f, TranslatorHandler handler) {
if (f instanceof StartsWith) {
StartsWith sw = (StartsWith) f;
if (sw.input() instanceof FieldAttribute && sw.pattern().foldable()) {
String targetFieldName = handler.nameOf(((FieldAttribute) sw.input()).exactAttribute());
String pattern = (String) sw.pattern().fold();
return new PrefixQuery(f.source(), targetFieldName, pattern, sw.isCaseInsensitive());
}
}
return null;
}
}
public static Query or(Source source, Query left, Query right) {
return boolQuery(source, left, right, false);
}
public static Query and(Source source, Query left, Query right) {
return boolQuery(source, left, right, true);
}
private static Query boolQuery(Source source, Query left, Query right, boolean isAnd) {
Check.isTrue(left != null || right != null, "Both expressions are null");
if (left == null) {
return right;
}
if (right == null) {
return left;
}
return new BoolQuery(source, isAnd, left, right);
}
}
| 44.770042 | 139 | 0.627869 |
e4e67a5a13407c7256a62953bc13cd975c882e7c | 140 | package com.zenith.elixer.specification.image;
public interface IImage {
public IImage setColor(int x, int y, int r, int g, int b);
}
| 20 | 62 | 0.721429 |
167a8e2e05286a8e42c125f3d16cb7952be597af | 3,942 | /**
* (c) raptor_MVK, 2015. All rights reserved.
*/
package ru.mvk.iluvatar.javafx.field;
import javafx.scene.Parent;
import javafx.scene.control.DatePicker;
import javafx.scene.layout.VBox;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Assert;
import org.junit.Test;
import ru.mvk.iluvatar.descriptor.field.DateFieldInfo;
import ru.mvk.iluvatar.descriptor.field.TemporalDescriptor;
import ru.mvk.iluvatar.test.FieldValueTester;
import ru.mvk.iluvatar.utils.UITests;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateFieldUITests extends UITests<DateField> {
@NotNull
private static VBox root = new VBox();
@NotNull
private static final String ID = "fieldId";
@NotNull
private final FieldValueTester<LocalDate> fieldValueTester = new FieldValueTester<>();
@NotNull
private final LocalDate defaultDate = LocalDate.of(2000, 1, 1);
@NotNull
private final String datePattern = "dd.MM.yy";
@Test
public void input_ShouldSetFieldValue() {
@NotNull String inputText = "15.02.12";
safeClickById(ID).type(inputText);
runAndWait(root::requestFocus);
@Nullable LocalDate fieldValue = fieldValueTester.getValue();
@NotNull DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(datePattern);
Assert.assertEquals("input date should set corresponding field value",
LocalDate.parse(inputText, dateFormatter), fieldValue);
}
@Test
public void input_ShouldSetFieldText() {
@NotNull String inputText = "15.02.12";
safeClickById(ID).type(inputText);
runAndWait(root::requestFocus);
@Nullable String fieldText = ((DateField) safeFindById(ID)).getEditor().getText();
Assert.assertEquals("input date should set corresponding field value",
inputText, fieldText);
}
@Test
public void wrongInput_ShouldSetFieldValueToDefaultDate() {
@NotNull String inputText = "12.05.02";
safeClickById(ID).type(inputText);
runAndWait(root::requestFocus);
emptyField(ID);
type("43.25.12");
runAndWait(root::requestFocus);
@Nullable LocalDate fieldValue = fieldValueTester.getValue();
Assert.assertEquals("wrong input should set field value to default date", defaultDate,
fieldValue);
}
@Test
public void wrongInput_ShouldSetValueToDefaultDate() {
@NotNull String inputText = "07.08.11";
safeClickById(ID).type(inputText);
runAndWait(root::requestFocus);
emptyField(ID);
type("12.25.43");
runAndWait(root::requestFocus);
@Nullable LocalDate fieldValue = ((DatePicker) safeFindById(ID)).getValue();
Assert.assertEquals("wrong input should set value to default date", defaultDate,
fieldValue);
}
@Test
public void emptyField_ShouldSetFieldValueToDefaultDate() {
@NotNull String inputText = "25.01.14";
safeClickById(ID).type(inputText);
runAndWait(root::requestFocus);
emptyField(ID);
runAndWait(root::requestFocus);
@Nullable LocalDate fieldValue = fieldValueTester.getValue();
Assert.assertEquals("empty field should set field value to default date", defaultDate,
fieldValue);
}
@Test
public void emptyField_ShouldSetValueToDefaultDate() {
@NotNull String inputText = "27.02.00";
safeClickById(ID).type(inputText);
runAndWait(root::requestFocus);
emptyField(ID);
runAndWait(root::requestFocus);
@Nullable LocalDate fieldValue = ((DatePicker) safeFindById(ID)).getValue();
Assert.assertEquals("empty field should set value to default date", defaultDate,
fieldValue);
}
@NotNull
@Override
protected Parent getRootNode() {
root = new VBox();
@NotNull TemporalDescriptor<LocalDate> temporalDescriptor =
new TemporalDescriptor<>(defaultDate, datePattern);
@NotNull DateFieldInfo dateFieldInfo = new DateFieldInfo("date", temporalDescriptor);
@NotNull DateField field = new DateField(dateFieldInfo);
field.setFieldUpdater(fieldValueTester::setValue);
field.setId(ID);
root.getChildren().addAll(field);
return root;
}
}
| 33.40678 | 88 | 0.762811 |
a143a1e9851c87280a1e6bdd2478e666c898f88f | 15,895 | package services;
import Bean.CachLyBean;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import models.CachLyModel;
import models.ChungMinhThuModel;
import models.NhanKhauModel;
import utility.DateString;
/**
*
* @author Bang
*/
public class CachLyService {
/*
*
*
*/
public CachLyBean getCachLy(int nhanKhauID){
CachLyBean cachLyBean= new CachLyBean();
try {
Connection connection = MysqlConnection.getMysqlConnection();
String query = "SELECT nk.hoTen,nk.namSinh,nk.noiThuongTru,nk.gioiTinh,\n" +
"cmt.ID cmtID,cmt.soCMT,cmt.ngayCap,cmt.noiCap\n" +
"FROM nhan_khau nk JOIN chung_minh_thu cmt ON cmt.idNhanKhau=nk.ID\n"+
"WHERE nk.ID = '"+String.valueOf(nhanKhauID)
+ "';"
;
PreparedStatement preparedStatement = (PreparedStatement)connection.prepareStatement(query);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()){
NhanKhauModel nhanKhau = cachLyBean.getNhanKhauModel();
nhanKhau.setID(nhanKhauID);
nhanKhau.setHoTen(rs.getString("hoTen"));
nhanKhau.setGioiTinh(rs.getString("gioiTinh"));
nhanKhau.setNamSinh(rs.getDate("namSinh"));
nhanKhau.setNoiThuongTru(rs.getString("noiThuongTru"));
ChungMinhThuModel chungMinhThuModel = cachLyBean.getChungMinhThuModel();
chungMinhThuModel.setID(rs.getInt("cmtID"));
chungMinhThuModel.setIdNhanKhau(nhanKhauID);
chungMinhThuModel.setSoCMT(rs.getString("soCMT"));
chungMinhThuModel.setNgayCap(rs.getDate("ngayCap"));
chungMinhThuModel.setNoiCap(rs.getString("noiCap"));
}
preparedStatement.close();
query = "SELECT cachLyID,nhanKhauID,ngayBatDauCachLy,noiCachLy,soNgayCachLy,"
+ "mucDoCachLy, hinhThucCachLy, nguoiChamSoc, lyDoCachLy \n" +
"FROM cach_ly\n" +
"WHERE nhanKhauID= " +String.valueOf(nhanKhauID)+
";";
preparedStatement = (PreparedStatement)connection.prepareStatement(query);
rs = preparedStatement.executeQuery();
while (rs.next()){
CachLyModel cachLyModel= new CachLyModel();
cachLyModel.setCachLyID(rs.getInt("cachLyID"));
cachLyModel.setNhanKhauID(rs.getInt("nhanKhauID"));
cachLyModel.setNgayBatDauCachLy(rs.getDate("ngayBatDauCachLy"));
cachLyModel.setNoiCachLy(rs.getString("noiCachLy"));
cachLyModel.setSoNgayCachLy(rs.getInt("soNgayCachLy"));
cachLyModel.setMucDoCachLy(rs.getString("mucDoCachLy"));
cachLyModel.setHinhThucCachLy(rs.getString("hinhThucCachLy"));
cachLyModel.setNguoiChamSoc(rs.getString("nguoiChamSoc"));
cachLyModel.setLyDoCachLy(rs.getString("lyDoCachLy"));
cachLyBean.getListCachLyModels().add(cachLyModel);
}
connection.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return cachLyBean;
}
public List<CachLyBean> getListCachLy(){
List<CachLyBean> list = new ArrayList<>();
try {
Connection connection = MysqlConnection.getMysqlConnection();
String query = "SELECT cl.cachLyID,cl.nhanKhauID,cl.ngayBatDauCachLy, cl.noiCachLy, cl.soNgayCachLy, "
+ "cl.mucDoCachLy, cl.hinhThucCachLy,cl.nguoiChamSoc, cl.lyDoCachLy,nk.hoTen,nk.namSinh,"
+ "nk.noiThuongTru,nk.gioiTinh, cmt.ID cmtID, "
+ "cmt.soCMT,cmt.ngayCap,cmt.noiCap \n"
+ "FROM cach_ly cl JOIN nhan_khau nk ON cl.nhanKhauID=nk.ID \n"
+ "JOIN chung_minh_thu cmt ON nk.ID= cmt.idNhanKhau \n"
+ "JOIN (SELECT cachLyID, max(ngayBatDauCachLy) FROM cach_ly GROUP BY nhanKhauID) maxcl ON cl.cachLyID=maxcl.cachLyID\n"
+";";
PreparedStatement preparedStatement = (PreparedStatement)connection.prepareStatement(query);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()){
CachLyBean cachLyBean =new CachLyBean();
CachLyModel cachLyModel= new CachLyModel();
cachLyModel.setCachLyID(rs.getInt("cachLyID"));
cachLyModel.setNhanKhauID(rs.getInt("nhanKhauID"));
cachLyModel.setNgayBatDauCachLy(rs.getDate("ngayBatDauCachLy"));
cachLyModel.setNoiCachLy(rs.getString("noiCachLy"));
cachLyModel.setSoNgayCachLy(rs.getInt("soNgayCachLy"));
cachLyModel.setMucDoCachLy(rs.getString("mucDoCachLy"));
cachLyModel.setHinhThucCachLy(rs.getString("hinhThucCachLy"));
cachLyModel.setNguoiChamSoc(rs.getString("nguoiChamSoc"));
cachLyModel.setLyDoCachLy(rs.getString("lyDoCachLy"));
cachLyBean.getListCachLyModels().add(cachLyModel);
NhanKhauModel nhanKhau = cachLyBean.getNhanKhauModel();
nhanKhau.setID(rs.getInt("nhanKhauID"));
nhanKhau.setHoTen(rs.getString("hoTen"));
nhanKhau.setGioiTinh(rs.getString("gioiTinh"));
nhanKhau.setNamSinh(rs.getDate("namSinh"));
nhanKhau.setNoiThuongTru(rs.getString("noiThuongTru"));
ChungMinhThuModel chungMinhThuModel = cachLyBean.getChungMinhThuModel();
chungMinhThuModel.setID(rs.getInt("cmtID"));
chungMinhThuModel.setIdNhanKhau(rs.getInt("nhanKhauID"));
chungMinhThuModel.setSoCMT(rs.getString("soCMT"));
chungMinhThuModel.setNgayCap(rs.getDate("ngayCap"));
chungMinhThuModel.setNoiCap(rs.getString("noiCap"));
list.add(cachLyBean);
}
preparedStatement.close();
connection.close();
} catch (Exception e) {
System.out.println("Loi tai dong 135 Cach Ly Service");
}
return list;
}
public List<CachLyBean> findListCachLy(String field,String value){
List<CachLyBean> list = new ArrayList<>();
try {
Connection connection = MysqlConnection.getMysqlConnection();
String query = "SELECT cl.cachLyID,cl.nhanKhauID,cl.ngayBatDauCachLy, cl.noiCachLy, cl.soNgayCachLy, "
+ "cl.mucDoCachLy, cl.hinhThucCachLy,cl.nguoiChamSoc, cl.lyDoCachLy,nk.hoTen,nk.namSinh,"
+ "nk.noiThuongTru,nk.gioiTinh, cmt.ID cmtID, "
+ "cmt.soCMT,cmt.ngayCap,cmt.noiCap \n"
+ "FROM cach_ly cl JOIN nhan_khau nk ON cl.nhanKhauID=nk.ID \n"
+ "JOIN chung_minh_thu cmt ON nk.ID= cmt.idNhanKhau \n"
+ "JOIN (SELECT cachLyID, max(ngayBatDauCachLy) FROM cach_ly GROUP BY nhanKhauID) maxcl ON cl.cachLyID=maxcl.cachLyID\n"
+ "WHERE "+field +" LIKE '%"+value+"%' "
+"\n;";
PreparedStatement preparedStatement = (PreparedStatement)connection.prepareStatement(query);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()){
CachLyBean cachLyBean =new CachLyBean();
CachLyModel cachLyModel= new CachLyModel();
cachLyModel.setCachLyID(rs.getInt("cachLyID"));
cachLyModel.setNhanKhauID(rs.getInt("nhanKhauID"));
cachLyModel.setNgayBatDauCachLy(rs.getDate("ngayBatDauCachLy"));
cachLyModel.setNoiCachLy(rs.getString("noiCachLy"));
cachLyModel.setSoNgayCachLy(rs.getInt("soNgayCachLy"));
cachLyModel.setMucDoCachLy(rs.getString("mucDoCachLy"));
cachLyModel.setHinhThucCachLy(rs.getString("hinhThucCachLy"));
cachLyModel.setNguoiChamSoc(rs.getString("nguoiChamSoc"));
cachLyModel.setLyDoCachLy(rs.getString("lyDoCachLy"));
cachLyBean.getListCachLyModels().add(cachLyModel);
NhanKhauModel nhanKhau = cachLyBean.getNhanKhauModel();
nhanKhau.setID(rs.getInt("nhanKhauID"));
nhanKhau.setHoTen(rs.getString("hoTen"));
nhanKhau.setGioiTinh(rs.getString("gioiTinh"));
nhanKhau.setNamSinh(rs.getDate("namSinh"));
nhanKhau.setNoiThuongTru(rs.getString("noiThuongTru"));
ChungMinhThuModel chungMinhThuModel = cachLyBean.getChungMinhThuModel();
chungMinhThuModel.setID(rs.getInt("cmtID"));
chungMinhThuModel.setIdNhanKhau(rs.getInt("nhanKhauID"));
chungMinhThuModel.setSoCMT(rs.getString("soCMT"));
chungMinhThuModel.setNgayCap(rs.getDate("ngayCap"));
chungMinhThuModel.setNoiCap(rs.getString("noiCap"));
list.add(cachLyBean);
}
preparedStatement.close();
connection.close();
} catch (Exception e) {
System.out.println("Loi tai dong 187 Cach Ly Service");
}
return list;
}
/*
Hàm thống kê trong đó có cách tham số truyền vào:
boolCheckbox là list gồm 4 phần tử trả về của 4 lựa chọn là ngày bất đầu,ngày kết thúc,mức độ, hình thức
date là list gồm 4 phần tử kiểu Date tương ứng với 2 ngày bắt đầu và 2 ngày kết thức
mucdo la list các string dc chon trong {"Chưa rõ","F0","F1","F2"}
lydo là list các string đc chọn trong {"tiếp xúc","dương tính","khác"}
*/
public List<CachLyBean> thongKeListCachLy(List<Boolean> boolCheckbox, List<Date> date,List<String> mucdo,List<String> lydo){
List<CachLyBean> list = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
DateString dateString =new DateString();
try {
Connection connection = MysqlConnection.getMysqlConnection();
String query = "SELECT cl.cachLyID,cl.nhanKhauID,cl.ngayBatDauCachLy, cl.noiCachLy, cl.soNgayCachLy, "
+ "cl.mucDoCachLy, cl.hinhThucCachLy,cl.nguoiChamSoc, cl.lyDoCachLy,nk.hoTen,nk.namSinh,"
+ "nk.noiThuongTru,nk.gioiTinh, cmt.ID cmtID, "
+ "cmt.soCMT,cmt.ngayCap,cmt.noiCap \n"
+ "FROM cach_ly cl JOIN nhan_khau nk ON cl.nhanKhauID=nk.ID \n"
+ "JOIN chung_minh_thu cmt ON nk.ID= cmt.idNhanKhau \n"
+ "JOIN (SELECT cachLyID, max(ngayBatDauCachLy) FROM cach_ly GROUP BY nhanKhauID) maxcl ON cl.cachLyID=maxcl.cachLyID\n"
;
List<String> liststr=new ArrayList<String>();
if(boolCheckbox.get(0)){
String str="( ngayBatDauCachLy >= '";
calendar.setTime(date.get(0));
str+= String.valueOf(calendar.get(Calendar.YEAR))+"-"+
String.valueOf(calendar.get(Calendar.MONTH)+1)+"-"+
String.valueOf(calendar.get(Calendar.DATE));
str+="' AND ngayBatDauCachLy <= '";
calendar.setTime(date.get(1));
str+= String.valueOf(calendar.get(Calendar.YEAR))+"-"+
String.valueOf(calendar.get(Calendar.MONTH)+1)+"-"+
String.valueOf(calendar.get(Calendar.DATE));
str+="' )";
liststr.add(str);
}
if(boolCheckbox.get(1)){
String str ="( ngayBatDauCachLy >= '"
+dateString.dateToString(date.get(0))
+"' AND ngayBatDauCachLy <= '"
+dateString.dateToString(date.get(1))
+"' )";
liststr.add(str);
}
if(boolCheckbox.get(1)){
String str="( ngayBatDauCachLy >= '"
+dateString.dateToString(date.get(2))
+"' AND ngayBatDauCachLy <= '"
+dateString.dateToString(date.get(3))
+"' )";
liststr.add(str);
}
if(boolCheckbox.get(2)&& !mucdo.isEmpty()){
String str="( mucDoCachLy IN (";
str+=" '"+mucdo.get(0) +"' ";
for(int i=1;i<mucdo.size();i++)str+=", '"+mucdo.get(i)+"' ";
str+=") )";
liststr.add(str);
}
if(boolCheckbox.get(3)&& !lydo.isEmpty()){
for(int i=0;i<lydo.size();i++){
if(lydo.get(i).equalsIgnoreCase("khác"))
lydo.set(i, "( lyDoCachLy NOT LIKE '%tiếp xúc%' AND lyDoCachLy NOT LIKE '%dương tính%' )");
else
lydo.set(i,"( lyDoCachLy LiKE '%"+lydo.get(i)+ "%' )");
}
liststr.add("( "+String.join(" OR ", lydo)+" )" );
}
if(!liststr.isEmpty())query=query+"WHERE "+String.join(" AND ",liststr );
query+="\n;";
PreparedStatement preparedStatement = (PreparedStatement)connection.prepareStatement(query);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()){
CachLyBean cachLyBean =new CachLyBean();
CachLyModel cachLyModel= new CachLyModel();
cachLyModel.setCachLyID(rs.getInt("cachLyID"));
cachLyModel.setNhanKhauID(rs.getInt("nhanKhauID"));
cachLyModel.setNgayBatDauCachLy(rs.getDate("ngayBatDauCachLy"));
cachLyModel.setNoiCachLy(rs.getString("noiCachLy"));
cachLyModel.setSoNgayCachLy(rs.getInt("soNgayCachLy"));
cachLyModel.setMucDoCachLy(rs.getString("mucDoCachLy"));
cachLyModel.setHinhThucCachLy(rs.getString("hinhThucCachLy"));
cachLyModel.setNguoiChamSoc(rs.getString("nguoiChamSoc"));
cachLyModel.setLyDoCachLy(rs.getString("lyDoCachLy"));
cachLyBean.getListCachLyModels().add(cachLyModel);
NhanKhauModel nhanKhau = cachLyBean.getNhanKhauModel();
nhanKhau.setID(rs.getInt("nhanKhauID"));
nhanKhau.setHoTen(rs.getString("hoTen"));
nhanKhau.setGioiTinh(rs.getString("gioiTinh"));
nhanKhau.setNamSinh(rs.getDate("namSinh"));
nhanKhau.setNoiThuongTru(rs.getString("noiThuongTru"));
ChungMinhThuModel chungMinhThuModel = cachLyBean.getChungMinhThuModel();
chungMinhThuModel.setID(rs.getInt("cmtID"));
chungMinhThuModel.setIdNhanKhau(rs.getInt("nhanKhauID"));
chungMinhThuModel.setSoCMT(rs.getString("soCMT"));
chungMinhThuModel.setNgayCap(rs.getDate("ngayCap"));
chungMinhThuModel.setNoiCap(rs.getString("noiCap"));
list.add(cachLyBean);
}
preparedStatement.close();
connection.close();
} catch (Exception e) {
System.out.println("Loi tai dong 300 Cach Ly Service");
}
return list;
}
/*
* Ham sử lý ngoại lệ : thông báo ra lỗi nhận được
*/
private void exceptionHandle(String message) {
JOptionPane.showMessageDialog(null, message, "Warning", JOptionPane.ERROR_MESSAGE);
}
}
| 51.440129 | 141 | 0.577477 |
e7df47680dfa788ceecd8913a03601dd167b1a96 | 3,521 | /*
* Marketing API
* Marketing API
*
* OpenAPI spec version: 1.3
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.tencent.ads.container;
import com.google.inject.Inject;
import com.tencent.ads.ApiContainer;
import com.tencent.ads.ApiException;
import com.tencent.ads.anno.*;
import com.tencent.ads.api.LocalStoresApi;
import com.tencent.ads.exception.TencentAdsResponseException;
import com.tencent.ads.model.FilteringStruct;
import com.tencent.ads.model.LocalStoresAddRequest;
import com.tencent.ads.model.LocalStoresAddResponse;
import com.tencent.ads.model.LocalStoresAddResponseData;
import com.tencent.ads.model.LocalStoresDeleteRequest;
import com.tencent.ads.model.LocalStoresDeleteResponse;
import com.tencent.ads.model.LocalStoresDeleteResponseData;
import com.tencent.ads.model.LocalStoresGetResponse;
import com.tencent.ads.model.LocalStoresGetResponseData;
import com.tencent.ads.model.LocalStoresUpdateRequest;
import com.tencent.ads.model.LocalStoresUpdateResponse;
import com.tencent.ads.model.LocalStoresUpdateResponseData;
import java.util.List;
public class LocalStoresApiContainer extends ApiContainer {
@Inject LocalStoresApi api;
/**
* 批量录入门店
*
* @param data (required)
* @return LocalStoresAddResponse
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the
* response body
*/
public LocalStoresAddResponseData localStoresAdd(LocalStoresAddRequest data)
throws ApiException, TencentAdsResponseException {
LocalStoresAddResponse resp = api.localStoresAdd(data);
handleResponse(gson.toJson(resp));
return resp.getData();
}
/**
* 批量删除门店信息
*
* @param data (required)
* @return LocalStoresDeleteResponse
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the
* response body
*/
public LocalStoresDeleteResponseData localStoresDelete(LocalStoresDeleteRequest data)
throws ApiException, TencentAdsResponseException {
LocalStoresDeleteResponse resp = api.localStoresDelete(data);
handleResponse(gson.toJson(resp));
return resp.getData();
}
/**
* 查询门店信息
*
* @param accountId (required)
* @param filtering (optional)
* @param page (optional)
* @param pageSize (optional)
* @param fields (optional)
* @return LocalStoresGetResponse
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the
* response body
*/
public LocalStoresGetResponseData localStoresGet(
Long accountId,
List<FilteringStruct> filtering,
Long page,
Long pageSize,
List<String> fields)
throws ApiException, TencentAdsResponseException {
LocalStoresGetResponse resp = api.localStoresGet(accountId, filtering, page, pageSize, fields);
handleResponse(gson.toJson(resp));
return resp.getData();
}
/**
* 批量更新门店信息
*
* @param data (required)
* @return LocalStoresUpdateResponse
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the
* response body
*/
public LocalStoresUpdateResponseData localStoresUpdate(LocalStoresUpdateRequest data)
throws ApiException, TencentAdsResponseException {
LocalStoresUpdateResponse resp = api.localStoresUpdate(data);
handleResponse(gson.toJson(resp));
return resp.getData();
}
}
| 32.601852 | 99 | 0.752059 |
dfa96c0db739a1c5c501782b96b147e4040146a5 | 1,431 | package org.rookit.dm.album.release;
import com.google.common.base.MoreObjects;
import org.rookit.api.dm.album.TypeRelease;
import org.rookit.dm.utils.DataModelValidator;
import org.rookit.utils.log.validator.Validator;
import javax.annotation.Nullable;
import java.time.LocalDate;
import java.util.Optional;
final class MutableReleaseImpl implements MutableRelease {
private static final Validator VALIDATOR = DataModelValidator.getDefault();
private static final long serialVersionUID = -8787468551172246738L;
private final TypeRelease type;
@Nullable
private LocalDate date;
MutableReleaseImpl(final TypeRelease type) {
this(type, null);
}
MutableReleaseImpl(final TypeRelease type, final LocalDate date) {
this.type = type;
this.date = date;
}
@Override
public void setReleaseDate(final LocalDate releaseDate) {
VALIDATOR.checkArgument().isNotNull(releaseDate, "releaseDate");
this.date = releaseDate;
}
@Override
public TypeRelease type() {
return this.type;
}
@Override
public Optional<LocalDate> date() {
return Optional.ofNullable(this.date);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("releaseType", this.type)
.add("date", Optional.ofNullable(this.date))
.toString();
}
}
| 26.018182 | 79 | 0.685535 |
65dc80168a030efdb86767e618c341a97194aa11 | 522 | package miscelleneous_problems.math.number_system;
public class AnyBaseToDecimalConversion {
public static int getValueInDecimal(int n, int b){
return convertAnyBaseToDecimal(n, b);
}
private static int convertAnyBaseToDecimal(int num, int base){
int res = 0, power = 1;
int tempNum = num;
while(tempNum != 0){
int rem = tempNum % 10;
tempNum /= 10;
res += (rem * power);
power *= base;
}
return res;
}
}
| 22.695652 | 66 | 0.570881 |
f668880948bededdfd1115e37836e32559552cd2 | 117 | public class MuteQuack extends QuackBehavior{
void quack() {
System.out.println(this+" cant speak!");
}
} | 19.5 | 45 | 0.666667 |
59bf4c69d89598057e0bb922a445ac6e090b4e03 | 1,328 | package com.github.fanzezhen.demo.logweb.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.fanzezhen.common.core.model.dto.PageDto;
import com.github.fanzezhen.demo.logbiz.facade.LogLoginServiceFacade;
import com.github.fanzezhen.common.log.foundation.entity.LogLogin;
import com.github.fanzezhen.common.log.model.dto.LogLoginDto;
import com.github.fanzezhen.common.log.model.vo.LogLoginVo;
import io.swagger.annotations.Api;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* <p>
* 登录日志表 前端控制器
* </p>
*
* @author fanzezhen
* @since 2020-06-11
*/
@Api("登录日志")
@Controller
@RequestMapping("/log/login")
public class LogLoginController {
@Resource
private LogLoginServiceFacade logLoginServiceFacade;
@ResponseBody
@PostMapping("/add")
public boolean add(LogLoginDto logLoginDto) {
return logLoginServiceFacade.add(logLoginDto);
}
@GetMapping("/page")
public String page(ModelMap modelMap) {
return "log_login";
}
@ResponseBody
@PostMapping("/page")
public IPage<LogLoginVo> page(@RequestBody PageDto<LogLoginDto, LogLogin> page) {
return logLoginServiceFacade.page(page);
}
}
| 26.56 | 85 | 0.749247 |
d3624fcd8ac29009ca407941d7ec74dfbe2d8634 | 10,004 | package com.genie.schedule.service;
import com.genie.schedule.MicroServerApp;
import com.genie.schedule.service.dto.CronJobInfo;
import com.genie.schedule.service.dto.JobDetailDTO;
import com.genie.schedule.service.dto.SimpleJobInfo;
import com.genie.schedule.utils.QuartzUtil;
import com.genie.schedule.utils.TaskHistory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.JobDataMap;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.*;
import static org.quartz.TriggerBuilder.newTrigger;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MicroServerApp.class}
// ,properties = {"spring.profiles.active=prod",
// "quartz.enabled=true",
// "quartz.properties.org.quartz.scheduler.instanceName=QuartzScheduler",
// "quartz.properties.org.quartz.scheduler.instanceId=AUTO",
// "quartz.properties.org.quartz.scheduler.rmi.proxy=false",
// "quartz.properties.org.quartz.scheduler.skipUpdateCheck=true",
// "quartz.properties.org.quartz.scheduler.jmx.export=true",
// "quartz.properties.org.quartz.scheduler.wrapJobExecutionInUserTransaction=false",
// "quartz.properties.org.quartz.scheduler.dbFailureRetryInterval=1500",
// "quartz.properties.org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool",
// "quartz.properties.org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true",
// "quartz.properties.org.quartz.threadPool.threadCount=5",
// "quartz.properties.org.quartz.threadPool.threadPriority=5",
// "quartz.properties.org.quartz.jobStore.class=com.novemberain.quartz.mongodb.MongoDBJobStore",
// "quartz.properties.org.quartz.jobStore.mongoUri=${spring.data.mongodb.uri}",
// "quartz.properties.org.quartz.jobStore.dbName=${spring.data.mongodb.database}",
// "quartz.properties.org.quartz.jobStore.collectionPrefix=QRTZ_"}
)
public class QuartzTaskServiceTest {
@Autowired
private QuartzTaskService quartzTaskService;
private Trigger trigger;
private CronJobInfo cronJobInfo = new CronJobInfo();
@Test
public void scheduleJobs() throws SchedulerException, InterruptedException {
String executionTime = "2 * * * * ?";
cronJobInfo.setJobGroup("Test");
cronJobInfo.setJobName("id");
cronJobInfo.getJobData().put("campaignId", "id");
cronJobInfo.getJobData().put("taskId", "id");
cronJobInfo.setCronExpression(executionTime);
trigger = QuartzUtil.getJobTrigger(cronJobInfo);
quartzTaskService.scheduleJobs(trigger, cronJobInfo, TaskHistory.class);
SimpleJobInfo simpleJobInfo = new SimpleJobInfo();
Date startTime = new Date(0);
Date endTime = new Date(1000);
simpleJobInfo.setStartTime(startTime);
simpleJobInfo.setEndTime(endTime);
simpleJobInfo.setRate("1");
simpleJobInfo.setTimes("1");
simpleJobInfo.setJobName("id7");
simpleJobInfo.setJobGroup("Test");
simpleJobInfo.setJobType("TaskHistory");
String rate = simpleJobInfo.getRate();
String times = simpleJobInfo.getTimes();
String type = simpleJobInfo.getJobType();
String[] argsNane = simpleJobInfo.getArgsNames();
String[] argsValues = simpleJobInfo.getArgsValues();
String jobType = simpleJobInfo.getJobType();
endTime = simpleJobInfo.getEndTime();
startTime = simpleJobInfo.getStartTime();
Date date = new Date();
SimpleTrigger simpleTrigger = (SimpleTrigger) newTrigger()
.withIdentity("trigger1", "Test")
.startAt(date)
.forJob("id7", "Test")
.build();
Long count = simpleTrigger.getRepeatInterval();
quartzTaskService.scheduleJobs(simpleTrigger, simpleJobInfo, TaskHistory.class);
}
@Test
public void rescheduleJob() throws SchedulerException, InterruptedException {
String executionTime = "2 10 10 10 OCT ?";
cronJobInfo.setJobGroup("Test");
cronJobInfo.setJobName("id1");
cronJobInfo.getJobData().put("campaignId", "id");
cronJobInfo.getJobData().put("taskId", "id");
cronJobInfo.setCronExpression(executionTime);
trigger = QuartzUtil.getJobTrigger(cronJobInfo);
quartzTaskService.scheduleJobs(trigger, cronJobInfo, TaskHistory.class);
quartzTaskService.rescheduleJob(trigger, cronJobInfo, TaskHistory.class);
}
@Test
public void queryJob() throws SchedulerException, InterruptedException {
String executionTime = "2 10 10 10 OCT ?";
cronJobInfo.setJobGroup("Test");
cronJobInfo.setJobName("id2");
cronJobInfo.getJobData().put("campaignId", "id");
cronJobInfo.getJobData().put("taskId", "id");
cronJobInfo.setCronExpression(executionTime);
cronJobInfo.setSecondField("2");
cronJobInfo.setMinutesField("10");
cronJobInfo.setHourField("10");
cronJobInfo.setDayField("10");
cronJobInfo.setMonthField("10");
String secondField = cronJobInfo.getSecondField();
String minutesField = cronJobInfo.getMinutesField();
String hoursField = cronJobInfo.getHourField();
String daysField = cronJobInfo.getDayField();
String monthField = cronJobInfo.getMonthField();
trigger = QuartzUtil.getJobTrigger(cronJobInfo);
quartzTaskService.scheduleJobs(trigger, cronJobInfo, TaskHistory.class);
List list = quartzTaskService.queryJob();
assertEquals(list.get(0), "Test");
}
@Test
public void getJobs() throws SchedulerException, InterruptedException {
String executionTime = "2 10 10 10 OCT ?";
cronJobInfo.setJobGroup("Test");
cronJobInfo.setJobName("id3");
cronJobInfo.getJobData().put("campaignId", "id");
cronJobInfo.getJobData().put("taskId", "id");
cronJobInfo.setCronExpression(executionTime);
trigger = QuartzUtil.getJobTrigger(cronJobInfo);
quartzTaskService.scheduleJobs(trigger, cronJobInfo, TaskHistory.class);
Set<JobDetailDTO> jobDetailDTOS = quartzTaskService.getJobs("Test", "id3");
assertEquals(jobDetailDTOS.size(), 1);
List list = new ArrayList(jobDetailDTOS);
JobDetailDTO jobDetailDTO = (JobDetailDTO) list.get(0);
assertEquals(jobDetailDTO.getKey().toString(), "Test.id3");
assertNull(jobDetailDTO.getDescription());
assertEquals(jobDetailDTO.getJobClass(), TaskHistory.class);
assertFalse(jobDetailDTO.isDurability());
JobDataMap jobDataMap = jobDetailDTO.getJobDataMap();
assertNull(jobDataMap.get("id4"));
assertFalse(jobDetailDTO.isShouldRecover());
assertNull(jobDetailDTO.getStatus());
SimpleJobInfo simpleJobInfo = new SimpleJobInfo();
simpleJobInfo.setRate("1");
simpleJobInfo.setTimes("1");
simpleJobInfo.setJobName("id8");
simpleJobInfo.setJobGroup("Test");
simpleJobInfo.setJobType("TaskHistory");
Date date = new Date();
SimpleTrigger simpleTrigger = (SimpleTrigger) newTrigger()
.withIdentity("trigger2", "Test")
.startAt(date)
.forJob("id8", "Test")
.build();
quartzTaskService.scheduleJobs(simpleTrigger, simpleJobInfo, TaskHistory.class);
jobDetailDTOS = quartzTaskService.getJobs("Test", "id8");
list = new ArrayList(jobDetailDTOS);
jobDetailDTO = (JobDetailDTO) list.get(0);
assertEquals(jobDetailDTO.getKey().toString(), "Test.id8");
}
@Test
public void deleteJob() throws SchedulerException {
quartzTaskService.deleteJob("Test", "id");
}
@Test
public void resumeJob() throws SchedulerException, InterruptedException {
String executionTime = "2 10 10 10 OCT ?";
cronJobInfo.setJobGroup("Test");
cronJobInfo.setJobName("id4");
cronJobInfo.getJobData().put("campaignId", "id");
cronJobInfo.getJobData().put("taskId", "id");
cronJobInfo.setCronExpression(executionTime);
trigger = QuartzUtil.getJobTrigger(cronJobInfo);
quartzTaskService.scheduleJobs(trigger, cronJobInfo, TaskHistory.class);
quartzTaskService.resumeJob("Test", "id4");
}
@Test
public void executeOnce() throws SchedulerException,InterruptedException {
String executionTime = "2 10 10 10 OCT ?";
cronJobInfo.setJobGroup("Test");
cronJobInfo.setJobName("id5");
cronJobInfo.getJobData().put("campaignId", "id");
cronJobInfo.getJobData().put("taskId", "id");
cronJobInfo.setCronExpression(executionTime);
trigger = QuartzUtil.getJobTrigger(cronJobInfo);
quartzTaskService.scheduleJobs(trigger, cronJobInfo, TaskHistory.class);
quartzTaskService.executeOnce("Test", "id5");
}
@Test
public void pauseJob() throws SchedulerException, InterruptedException {
String executionTime = "2 10 10 10 OCT ?";
cronJobInfo.setJobGroup("Test");
cronJobInfo.setJobName("id6");
cronJobInfo.getJobData().put("campaignId", "id");
cronJobInfo.getJobData().put("taskId", "id");
cronJobInfo.setCronExpression(executionTime);
trigger = QuartzUtil.getJobTrigger(cronJobInfo);
quartzTaskService.scheduleJobs(trigger, cronJobInfo, TaskHistory.class);
quartzTaskService.pauseJob("Test", "id6");
}
}
| 45.472727 | 118 | 0.680328 |
a63905f3ac90656c1621c966c26fa96444bbc930 | 3,341 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package io.github.kandefromparis.generator.cheer;
import io.vertx.core.AbstractVerticle;
import io.vertx.ext.web.RoutingContext;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author csabourdin
*/
class ProbVerticle extends AbstractVerticle {
Integer livenesscounter = 0;
Integer readinessCounter = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
public void getLiveness(RoutingContext routingContext) {
getOK(routingContext, livenesscounter++);
}
public void getReadiness(RoutingContext routingContext) {
getOK(routingContext, readinessCounter++);
}
public void getOK(RoutingContext routingContext, Integer count) {
if ((System.getenv("CHEER_LOG_LEVEL") != null)
&& (System.getenv("CHEER_LOG_LEVEL").equals("INFO") || System.getenv("CHEER_LOG_LEVEL").equals("DEBUG"))) {
if (count > Integer.MAX_VALUE - 5) {
count = 0;
System.out.println("Varibale count tend to Max, Rolling count to 0");
}
System.out.println(sdf.format(Date.from(Instant.now()))+" "+routingContext.request().absoluteURI() + ("OK - " + count + " times"));
}
if (isAPositiveReasonableNumeric(System.getenv("CHEER_SLOW_READINESS")) &&
routingContext.request().path().equals(ConfAPICall.READINESS)) {
Integer duration = Integer.parseInt(System.getenv("CHEER_SLOW_READINESS"));
System.out.println(sdf.format(Date.from(Instant.now()))+" "+"Waiting " + duration + " micro-secondes before respond to readiness prob");
try {
Thread.sleep(duration * 100);
} catch (InterruptedException ex) {
Logger.getLogger(ProbVerticle.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (isAPositiveReasonableNumeric(System.getenv("CHEER_SLOW_LIVENESS")) &&
routingContext.request().path().equals(ConfAPICall.LIVENESS)) {
Integer duration = Integer.parseInt(System.getenv("CHEER_SLOW_LIVENESS"));
System.out.println(sdf.format(Date.from(Instant.now()))+" "+"Waiting " + duration + " micro-secondes before respond to liveness prob");
try {
Thread.sleep(duration * 100);
} catch (InterruptedException ex) {
Logger.getLogger(ProbVerticle.class.getName()).log(Level.SEVERE, null, ex);
}
}
routingContext.response()
.putHeader("content-type", "text/html; charset=utf-8")
.setStatusCode(200)
.end("OK - " + count + " times");
}
public static boolean isAPositiveReasonableNumeric(String str) {
if (str == null) {
return false;
}
try {
Integer d = Integer.parseInt(str);
if (d <= 1) {
return false;
}
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
}
| 37.539326 | 148 | 0.61748 |
9adbaa477e279f2ecc91ebfe94cbf77352ae68b0 | 5,467 | /**
* Copyright (C) 2010-2013 Andrei Pozolotin <Andrei.Pozolotin@gmail.com>
*
* All rights reserved. Licensed under the OSI BSD License.
*
* http://www.opensource.org/licenses/bsd-license.php
*/
package com.jwrapper.maven.cfn;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.maven.plugin.MojoFailureException;
import com.amazonaws.services.cloudformation.model.Output;
import com.amazonaws.services.cloudformation.model.Stack;
import com.amazonaws.services.cloudformation.model.StackStatus;
import com.jwrapper.maven.util.Util;
/**
* cloud formation:
*
* <b><a href=
* "http://docs.amazonwebservices.com/AWSCloudFormation/latest/APIReference/API_CreateStack.html"
* >create stack</a></b>
*
* based on:
*
* <b>stack name</b>,
*
* <b><a href=
* "http://aws.amazon.com/cloudformation/aws-cloudformation-templates" >stack
* template</a></b>
*
* ({@link #stackTemplateFile}),
*
* <b><a href=
* "http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html"
* >stack parameters</a></b>
*
* ({@link #stackPropertiesInputFile} + {@link #stackInputParams}),
*
* and produce a
*
* <b><a href=
* "http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/concept-outputs.html"
* >stack output</a></b>
*
* ({@link #stackPropertiesOutputFile})
*
* as well as inject output into into project.properties
*
* ; wait for completion or fail ({@link #stackTimeout});
*
* @goal cloud-formation-create
*
* @phase prepare-package
*
* @inheritByDefault true
*
* @requiresDependencyResolution test
*
*/
public class CloudFormCreateStack extends CloudForm {
/**
* AWS CloudFormation
*
* <a href=
* "http://aws.amazon.com/cloudformation/aws-cloudformation-templates"
* >template</a>
*
* file
*
* @required
* @parameter default-value="./target/formation/formation.template"
*/
protected File stackTemplateFile;
/**
* AWS CloudFormation
*
* <a href=
* "http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html"
* >Parameters Declaration</a>
*
* stack template input parameters; optional; overrides settings from
* #stackPropertiesInputFile
*
* @parameter
*/
protected Map<String, String> stackInputParams = new HashMap<String, String>();
/**
* AWS CloudFormation stack create execution
*
* <a href=
* "http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html"
* >Parameters Declaration</a>
*
* input properties file;
*
* will be overridden by #stackInputParams if any
*
* @parameter default-value="./target/formation/formation-input.properties"
*/
protected File stackPropertiesInputFile;
/**
* AWS CloudFormation stack create execution result
*
* <a href=
* "http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/concept-outputs.html"
* >Outputs Section</a>
*
* output properties file
*
* @parameter default-value="./target/formation/formation-output.properties"
*/
protected File stackPropertiesOutputFile;
/**
* should inject stack operation output into the project.properties?
*
* @parameter default-value="true"
*/
protected boolean stackIsInjectOutputProperties;
/**
* should persist stack operation output into
* {@link #stackPropertiesOutputFile}
*
* @parameter default-value="true"
*/
protected boolean stackIsPersistOutputProperties;
/**
* {@inheritDoc}
*/
@Override
public void execute() throws MojoFailureException {
try {
getLog().info("stack create init [" + stackName() + "]");
final Properties stackInputProps = Util.propsLoad(getLog(),
stackPropertiesInputFile);
final Map<String, String> pluginProps = mergePluginProps(
stackInputProps, stackInputParams);
final Map<String, String> stackTemplateParams = loadTemplateParameters(
stackTemplateFile, pluginProps);
final CarrotCloudForm formation = newCloudFormation(
stackTemplateFile, stackTemplateParams);
formation.logParamList();
final Stack stack = formation.stackCreate();
final StackStatus status = StackStatus.fromValue(stack
.getStackStatus());
switch (status) {
case CREATE_COMPLETE:
break;
default:
throw new IllegalStateException("stack create failed");
}
//
getLog().info("stack create stack=\n" + stack);
getLog().info("stack create output:");
final List<Output> outputList = stack.getOutputs();
final Properties outputProps = new Properties();
for (final Output output : outputList) {
final String key = output.getOutputKey();
final String value = output.getOutputValue();
outputProps.put(key, value);
getLog().info("\t" + key + "=" + value);
}
if (stackIsInjectOutputProperties) {
project().getProperties().putAll(outputProps);
getLog().info(
"stack create output is injected in project.properties]");
}
if (stackIsPersistOutputProperties) {
Util.propsSave(getLog(), outputProps, stackPropertiesOutputFile);
getLog().info(
"stack create output is persisted to : "
+ stackPropertiesOutputFile);
}
//
getLog().info("stack create done [" + stackName() + "]");
} catch (final Exception e) {
throw new MojoFailureException("bada-boom", e);
}
}
}
| 23.873362 | 108 | 0.699287 |
61bfcffe37353a0b1b96fa2946129a80b3067569 | 13,492 | /*
* Copyright 1999-2011 Alibaba Group.
*
* 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.alibaba.dubbo.monitor.simple;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
import com.alibaba.dubbo.common.utils.ConcurrentHashSet;
import com.alibaba.dubbo.common.utils.ConfigUtils;
import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.dubbo.container.Container;
import com.alibaba.dubbo.container.spring.SpringContainer;
import com.alibaba.dubbo.registry.NotifyListener;
import com.alibaba.dubbo.registry.RegistryService;
/**
* RegistryContainer
*
* @author william.liangf
*/
public class RegistryContainer implements Container {
public static final String REGISTRY_ADDRESS = "dubbo.registry.address";
private final Set<String> applications = new ConcurrentHashSet<String>();
private final Map<String, Set<String>> providerServiceApplications = new ConcurrentHashMap<String, Set<String>>();
private final Map<String, Set<String>> providerApplicationServices = new ConcurrentHashMap<String, Set<String>>();
private final Map<String, Set<String>> consumerServiceApplications = new ConcurrentHashMap<String, Set<String>>();
private final Map<String, Set<String>> consumerApplicationServices = new ConcurrentHashMap<String, Set<String>>();
private final Set<String> services = new ConcurrentHashSet<String>();
private final Map<String, List<URL>> serviceProviders = new ConcurrentHashMap<String, List<URL>>();
private final Map<String, List<URL>> serviceConsumers = new ConcurrentHashMap<String, List<URL>>();
private RegistryService registry;
private static RegistryContainer INSTANCE = null;
public RegistryContainer() {
INSTANCE = this;
}
public static RegistryContainer getInstance() {
if (INSTANCE == null) {
ExtensionLoader.getExtensionLoader(Container.class).getExtension("registry");
}
return INSTANCE;
}
public RegistryService getRegistry() {
return registry;
}
public Set<String> getApplications() {
return Collections.unmodifiableSet(applications);
}
public Set<String> getDependencies(String application, boolean reverse) {
if (reverse) {
Set<String> dependencies = new HashSet<String>();
Set<String> services = providerApplicationServices.get(application);
if (services != null && services.size() > 0) {
for (String service : services) {
Set<String> applications = consumerServiceApplications.get(service);
if (applications != null && applications.size() > 0) {
dependencies.addAll(applications);
}
}
}
return dependencies;
} else {
Set<String> dependencies = new HashSet<String>();
Set<String> services = consumerApplicationServices.get(application);
if (services != null && services.size() > 0) {
for (String service : services) {
Set<String> applications = providerServiceApplications.get(service);
if (applications != null && applications.size() > 0) {
dependencies.addAll(applications);
}
}
}
return dependencies;
}
}
public Set<String> getServices() {
return Collections.unmodifiableSet(services);
}
public Map<String, List<URL>> getServiceProviders() {
return Collections.unmodifiableMap(serviceProviders);
}
public List<URL> getProvidersByService(String service) {
List<URL> urls = serviceProviders.get(service);
return urls == null ? null : Collections.unmodifiableList(urls);
}
public List<URL> getProvidersByHost(String host) {
List<URL> urls = new ArrayList<URL>();
if (host != null && host.length() > 0) {
for (List<URL> providers : serviceProviders.values()) {
for (URL url : providers) {
if (host.equals(url.getHost())) {
urls.add(url);
}
}
}
}
return urls;
}
public List<URL> getProvidersByApplication(String application) {
List<URL> urls = new ArrayList<URL>();
if (application != null && application.length() > 0) {
for (List<URL> providers : serviceProviders.values()) {
for (URL url : providers) {
if (application.equals(url.getParameter(Constants.APPLICATION_KEY))) {
urls.add(url);
}
}
}
}
return urls;
}
public Set<String> getHosts() {
Set<String> addresses = new HashSet<String>();
for (List<URL> providers : serviceProviders.values()) {
for (URL url : providers) {
addresses.add(url.getHost());
}
}
for (List<URL> providers : serviceConsumers.values()) {
for (URL url : providers) {
addresses.add(url.getHost());
}
}
return addresses;
}
public Map<String, List<URL>> getServiceConsumers() {
return Collections.unmodifiableMap(serviceConsumers);
}
public List<URL> getConsumersByService(String service) {
List<URL> urls = serviceConsumers.get(service);
return urls == null ? null : Collections.unmodifiableList(urls);
}
public List<URL> getConsumersByHost(String host) {
List<URL> urls = new ArrayList<URL>();
if (host != null && host.length() > 0) {
for (List<URL> consumers : serviceConsumers.values()) {
for (URL url : consumers) {
if (host.equals(url.getHost())) {
urls.add(url);
}
}
}
}
return Collections.unmodifiableList(urls);
}
public List<URL> getConsumersByApplication(String application) {
List<URL> urls = new ArrayList<URL>();
if (application != null && application.length() > 0) {
for (List<URL> consumers : serviceConsumers.values()) {
for (URL url : consumers) {
if (application.equals(url.getParameter(Constants.APPLICATION_KEY))) {
urls.add(url);
}
}
}
}
return urls;
}
public void start() {
String url = ConfigUtils.getProperty(REGISTRY_ADDRESS);
if (url == null || url.length() == 0) {
throw new IllegalArgumentException("Please set java start argument: -D" + REGISTRY_ADDRESS + "=zookeeper://127.0.0.1:2181");
}
registry = (RegistryService) SpringContainer.getContext().getBean("registryService");
URL subscribeUrl = new URL(Constants.ADMIN_PROTOCOL, NetUtils.getLocalHost(), 0, "",
Constants.INTERFACE_KEY, Constants.ANY_VALUE,
Constants.GROUP_KEY, Constants.ANY_VALUE,
Constants.VERSION_KEY, Constants.ANY_VALUE,
Constants.CLASSIFIER_KEY, Constants.ANY_VALUE,
Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY + ","
+ Constants.CONSUMERS_CATEGORY,
Constants.CHECK_KEY, String.valueOf(false));
registry.subscribe(subscribeUrl, new NotifyListener() {
public void notify(List<URL> urls) {
if (urls == null || urls.size() == 0) {
return;
}
Map<String, List<URL>> proivderMap = new HashMap<String, List<URL>>();
Map<String, List<URL>> consumerMap = new HashMap<String, List<URL>>();
for (URL url : urls) {
String application = url.getParameter(Constants.APPLICATION_KEY);
if (application != null && application.length() > 0) {
applications.add(application);
}
String service = url.getServiceInterface();
services.add(service);
String category = url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY);
if (Constants.PROVIDERS_CATEGORY.equals(category)) {
if (Constants.EMPTY_PROTOCOL.equals(url.getProtocol())) {
serviceProviders.remove(service);
} else {
List<URL> list = proivderMap.get(service);
if (list == null) {
list = new ArrayList<URL>();
proivderMap.put(service, list);
}
list.add(url);
if (application != null && application.length() > 0) {
Set<String> serviceApplications = providerServiceApplications.get(service);
if (serviceApplications == null) {
providerServiceApplications.put(service, new ConcurrentHashSet<String>());
serviceApplications = providerServiceApplications.get(service);
}
serviceApplications.add(application);
Set<String> applicationServices = providerApplicationServices.get(application);
if (applicationServices == null) {
providerApplicationServices.put(application, new ConcurrentHashSet<String>());
applicationServices = providerApplicationServices.get(application);
}
applicationServices.add(service);
}
}
} else if (Constants.CONSUMERS_CATEGORY.equals(category)) {
if (Constants.EMPTY_PROTOCOL.equals(url.getProtocol())) {
serviceConsumers.remove(service);
} else {
List<URL> list = consumerMap.get(service);
if (list == null) {
list = new ArrayList<URL>();
consumerMap.put(service, list);
}
list.add(url);
if (application != null && application.length() > 0) {
Set<String> serviceApplications = consumerServiceApplications.get(service);
if (serviceApplications == null) {
consumerServiceApplications.put(service, new ConcurrentHashSet<String>());
serviceApplications = consumerServiceApplications.get(service);
}
serviceApplications.add(application);
Set<String> applicationServices = consumerApplicationServices.get(application);
if (applicationServices == null) {
consumerApplicationServices.put(application, new ConcurrentHashSet<String>());
applicationServices = consumerApplicationServices.get(application);
}
applicationServices.add(service);
}
}
}
}
if (proivderMap != null && proivderMap.size() > 0) {
serviceProviders.putAll(proivderMap);
}
if (consumerMap != null && consumerMap.size() > 0) {
serviceConsumers.putAll(consumerMap);
}
}
});
}
public void stop() {
}
} | 44.381579 | 137 | 0.533798 |
23c61a9a54a3b79eb85acb896ebd69a94c4e2eba | 1,387 | import java.util.Arrays;
/**
* Given an array <tt>A</tt> of non-negative integers, return an array consisting of all the even elements of
* <tt>A</tt>, followed by all the odd elements of <tt>A</tt>.
* <p>
* You may return any answer array that satisfies this condition.
* <p>
* <b>Example 1:</b>
* <pre>
* Input: [3,1,2,4]
* Output: [2,4,3,1]
* The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
* </pre>
* <ol>
* <b>Note:</b>
* <li><tt>1 <= A.length <= 5000</tt></li>
* <li><tt>0 <= A[i] <= 5000</tt></li>
* </ol>
*
* @author Oleg Cherednik
* @since 21.08.2020
*/
public class Solution {
public static void main(String... args) {
System.out.println(Arrays.toString(sortArrayByParity(new int[] { 3, 1, 2, 4 }))); // [4, 2, 1, 3]
}
public static int[] sortArrayByParity(int[] A) {
for (int i = 0, j = A.length - 1; i < j; ) {
if (isEven(A[i]))
i++;
else if (isOdd(A[j]))
j--;
else
swap(A, i, j);
}
return A;
}
private static boolean isEven(int val) {
return (val & 0x1) == 0;
}
private static boolean isOdd(int val) {
return (val & 0x1) == 1;
}
private static void swap(int[] A, int i, int j) {
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
| 23.913793 | 109 | 0.503965 |
0d301c0af83c126d9f92bfdee2432ea42d059011 | 2,247 | package cn.smile.smilemall.search;
import cn.smile.smilemall.search.config.ElasticSearchConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest
@Slf4j
class SmilemallSearchApplicationTests {
@Autowired
private RestHighLevelClient restHighLevelClient;
/**
* @description 保存索引
* @author Smile
* @date 2021/2/14/014
* @param
* @return void
*/
@Test
public void indexData() throws Exception {
IndexRequest indexRequest = new IndexRequest("person");
ObjectMapper objectMapper = new ObjectMapper();
String person = objectMapper.writeValueAsString(new Person("张三", 18, "男"));
indexRequest.source(person, XContentType.JSON);
IndexResponse index = restHighLevelClient.index(indexRequest, ElasticSearchConfig.getCommonOptions());
log.trace("index", index);
}
@Test
public void searchData() throws IOException {
// 搜索请求
SearchRequest searchRequest = new SearchRequest("person");
// 请求条件构造
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
// 指定检索条件
searchRequest.source(searchSourceBuilder);
SearchResponse search = restHighLevelClient.search(searchRequest, ElasticSearchConfig.getCommonOptions());
log.trace("search", search);
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Person {
private String name;
private Integer age;
private String gender;
}
@Test
void contextLoads() {
System.out.println(restHighLevelClient);
}
}
| 28.807692 | 108 | 0.793057 |
adf4a309202dcdfe8c492751fc2534d9bdfe1538 | 193 | /**
*
*/
package com.rains.proxy.core.algorithm.impl.support;
/**
* @author liubing
*
*/
public interface RedisWeight {
/**
* 获取权重比例
* @return
*/
public int getWeight();
}
| 9.65 | 52 | 0.585492 |
4ea1778615add8684767e7bdc8fb670f422e906a | 3,310 | /**
* 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 io.hops.resolvingcache;
import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.server.namenode.INode;
import org.apache.hadoop.hdfs.server.namenode.INodeDirectory;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class InMemoryCache extends Cache{
private ConcurrentLinkedHashMap<String, Integer> cache;
private int CACHE_MAXIMUM_SIZE;
@Override
protected void setConfiguration(Configuration conf) throws IOException {
CACHE_MAXIMUM_SIZE = conf.getInt(DFSConfigKeys.DFS_INMEMORY_CACHE_MAX_SIZE,
DFSConfigKeys.DFS_INMEMORY_CACHE_MAX_SIZE_DEFAULT);
super.setConfiguration(conf);
}
@Override
protected void startInternal() throws IOException {
cache = new ConcurrentLinkedHashMap.Builder().maximumWeightedCapacity
(CACHE_MAXIMUM_SIZE).build();
}
@Override
protected void stopInternal() {
}
@Override
protected void setInternal(String path, List<INode> inodes) {
for(INode iNode : inodes){
if(iNode != null) {
cache.put(iNode.nameParentKey(), iNode.getId());
}
}
}
@Override
protected int[] getInternal(String path) throws IOException {
String[] pathComponents = INode.getPathNames(path);
int[] inodeIds = new int[pathComponents.length];
int parentId = INodeDirectory.ROOT_PARENT_ID;
int index = 0;
while(index <pathComponents.length){
String cmp = pathComponents[index];
Integer inodeId = cache.get(INode.nameParentKey(parentId, cmp));
if(inodeId != null){
parentId = inodeId;
inodeIds[index] = inodeId;
}else{
break;
}
index++;
}
//only the root was found
if(index <= 1)
return null;
return Arrays.copyOf(inodeIds, index);
}
@Override
protected void setInternal(INode inode) {
throw new UnsupportedOperationException();
}
@Override
protected void deleteInternal(String path) {
throw new UnsupportedOperationException();
}
@Override
protected void deleteInternal(INode inode) {
cache.remove(inode.nameParentKey());
}
@Override
protected void flushInternal() {
cache.clear();
}
@Override
protected int getRoundTrips(String path) {
return INode.getPathNames(path).length;
}
@Override
protected int getRoundTrips(List<INode> inodes) {
return inodes.size();
}
}
| 28.290598 | 79 | 0.722054 |
813b0d7f250bb0134b825a3e1148c671eef5b040 | 4,033 | package com.example.android.miwok;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
public class FamilyActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private AudioManager mAudioManager;
AudioManager.OnAudioFocusChangeListener afChangeListener = new AudioManager.OnAudioFocusChangeListener(){
public void onAudioFocusChange(int FocusChange){
if(FocusChange== mAudioManager.AUDIOFOCUS_LOSS_TRANSIENT || FocusChange== mAudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK){
mediaPlayer.pause();
mediaPlayer.seekTo(0);
}
else if(FocusChange == mAudioManager.AUDIOFOCUS_GAIN){
mediaPlayer.start();
}
else if(FocusChange == mAudioManager.AUDIOFOCUS_LOSS){
releaseMedia();
}
}
};
private MediaPlayer.OnCompletionListener mCompletion = new MediaPlayer.OnCompletionListener(){
@Override
public void onCompletion(MediaPlayer mp){
releaseMedia();
}
};
@Override
protected void onStop() {
super.onStop();
releaseMedia();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_common);
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
final ArrayList<word> NumberList = new ArrayList<word>();
NumberList.add(new word("Father","apa", R.drawable.family_father, R.raw.family_father));
NumberList.add(new word("Mother","ata", R.drawable.family_mother, R.raw.family_mother));
NumberList.add(new word("Son","angsi",R.drawable.family_son, R.raw.family_son));
NumberList.add(new word("Daughter","tune",R.drawable.family_daughter, R.raw.family_daughter));
NumberList.add(new word("Elder Brother","taachi",R.drawable.family_older_brother, R.raw.family_older_brother));
NumberList.add(new word("Younger Brother","chalitti",R.drawable.family_younger_brother, R.raw.family_younger_brother));
NumberList.add(new word("Elder Sister","tete",R.drawable.family_older_sister, R.raw.family_older_sister));
NumberList.add(new word("Younger Sister","kolitti",R.drawable.family_younger_sister, R.raw.family_younger_sister));
NumberList.add(new word("Grandmother","amma",R.drawable.family_grandmother, R.raw.family_grandmother));
NumberList.add(new word("Grandfather","pappa",R.drawable.family_grandfather, R.raw.family_grandfather));
wordAdapter itemsAdapter = new wordAdapter (this ,NumberList, R.color.category_family);
ListView listView= (ListView) findViewById(R.id.activity_numbers);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view , int position , long id){
word wrd = NumberList.get(position);
releaseMedia();
int result = mAudioManager.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC , AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
if(result==AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mediaPlayer = MediaPlayer.create(FamilyActivity.this, wrd.getmAudioResourceId());
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(mCompletion);
}
}
});
}
private void releaseMedia(){
if(mediaPlayer != null){
mediaPlayer.release();
mediaPlayer = null;
mAudioManager.abandonAudioFocus(afChangeListener);
}
}
}
| 41.57732 | 147 | 0.682618 |
a63129918d78f426cde5cf67bcdf6e0c6a2110c2 | 4,207 | /*
@@author shihaoyap
*/
package seedu.address.logic.commands.schedule;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.address.commons.core.Messages.MESSAGE_EVENTS_LISTED_OVERVIEW;
import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess;
import static seedu.address.testutil.TypicalEvents.BIRTHDAY_PARTY;
import static seedu.address.testutil.TypicalEvents.MUSICAL_COMPETITION;
import static seedu.address.testutil.TypicalEvents.getTypicalEventBook;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collections;
import org.junit.jupiter.api.Test;
import seedu.address.model.Model;
import seedu.address.model.ModelManager;
import seedu.address.model.UserPrefs;
import seedu.address.model.event.EventContainsKeyYearMonthPredicate;
/**
* Contains integration tests (interaction with the Model) for {@code DisplayScheduleForYearMonthCommand}.
*/
public class DisplayScheduleForYearMonthCommandTest {
public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("MM/yyyy");
private Model model = new ModelManager(getTypicalEventBook(), new UserPrefs());
private Model expectedModel = new ModelManager(getTypicalEventBook(), new UserPrefs());
@Test
public void equals() {
EventContainsKeyYearMonthPredicate firstPredicate =
new EventContainsKeyYearMonthPredicate(YearMonth.parse("12/2019", FORMATTER));
EventContainsKeyYearMonthPredicate secondPredicate =
new EventContainsKeyYearMonthPredicate(YearMonth.parse("11/2019", FORMATTER));
DisplayScheduleForYearMonthCommand displayFirstCommand =
new DisplayScheduleForYearMonthCommand(firstPredicate);
DisplayScheduleForYearMonthCommand displaySecondCommand =
new DisplayScheduleForYearMonthCommand(secondPredicate);
// same object -> returns true
assertTrue(displayFirstCommand.equals(displayFirstCommand));
// same values -> returns true
DisplayScheduleForYearMonthCommand displayFirstCommandCopy =
new DisplayScheduleForYearMonthCommand(firstPredicate);
assertTrue(displayFirstCommand.equals(displayFirstCommandCopy));
// different types -> returns false
assertFalse(displayFirstCommand.equals(1));
// null -> returns false
assertFalse(displayFirstCommand.equals(null));
// different event -> returns false
assertFalse(displayFirstCommand.equals(displaySecondCommand));
}
@Test
public void execute_validYearMonthKeywordInput_noEventFound() {
String expectedMessage = String.format(MESSAGE_EVENTS_LISTED_OVERVIEW, 0);
EventContainsKeyYearMonthPredicate predicate = preparePredicate("01/2019");
DisplayScheduleForYearMonthCommand command = new DisplayScheduleForYearMonthCommand(predicate);
expectedModel.updateFilteredScheduledEventList(predicate);
assertCommandSuccess(command, model, expectedMessage, expectedModel);
assertEquals(Collections.emptyList(), model.getFilteredScheduledEventList());
}
@Test
public void execute_validYearMonthKeywordInput_multipleEventFound() {
String expectedMessage = String.format(MESSAGE_EVENTS_LISTED_OVERVIEW, 2);
EventContainsKeyYearMonthPredicate predicate = preparePredicate("10/2019");
DisplayScheduleForYearMonthCommand command = new DisplayScheduleForYearMonthCommand(predicate);
expectedModel.updateFilteredScheduledEventList(predicate);
assertCommandSuccess(command, model, expectedMessage, expectedModel);
assertEquals(Arrays.asList(MUSICAL_COMPETITION, BIRTHDAY_PARTY), model.getFilteredScheduledEventList());
}
/**
* Parses {@code userInput} into a {@code EventContainsKeyYearMonthPredicate}.
*/
private EventContainsKeyYearMonthPredicate preparePredicate(String userInput) {
return new EventContainsKeyYearMonthPredicate(YearMonth.parse(userInput, FORMATTER));
}
}
| 44.284211 | 112 | 0.772997 |
fd1e3e576f4d09e56e43a6599c3e10486a1be49e | 1,359 | package in.aos.service;
import java.sql.SQLException;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import in.aos.bean.Facilities;
import in.aos.bean.GalleryBean;
import in.aos.bean.NewsAndEventBean;
import in.aos.dao.MainUIDao;
import in.aos.dao.MainUIDaoImpl;
public class MainUIServiceImpl implements MainUIService{
ApplicationContext context = new ClassPathXmlApplicationContext("../spring-mvc-config.xml");
MainUIDao mainUIDao = null;
public MainUIServiceImpl() {
mainUIDao = (MainUIDaoImpl) context.getBean("MainUIDaoBean");
}
@Override
public List<GalleryBean> getSliderImages() throws SQLException {
return mainUIDao.getSliderImages();
}
@Override
public boolean saveAdmissionEnquiryDetails() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public List<Facilities> getExtraCurricularActivities() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Facilities> getFacilities() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public List<NewsAndEventBean> getNewsEvents() throws SQLException {
return mainUIDao.getNewsEvents();
}
}
| 26.647059 | 95 | 0.756439 |
fcc901c7260f185d57a7e406b122e46222d13273 | 977 | public class Soultion110 {
public static void main(String[] args) {
TreeNode p = new TreeNode(3);
p.left = new TreeNode(9);
p.right = new TreeNode(20);
p.left.left = new TreeNode(15);
// p.left.right = new TreeNode(7);
p.left.left.left = new TreeNode(4);
// p.left.left.right = new TreeNode(4);
// p.right.left = new TreeNode(15);
p.right.right = new TreeNode(7);
p.right.right.right = new TreeNode(1);
// TreeNode p = null;
System.out.println(isBalanced(p));
}
static boolean flag = true;
public static boolean isBalanced(TreeNode root) {
height(root);
return flag;
}
private static int height(TreeNode root) {
if(root==null)
return 0;
int left = height(root.left);
int right = height(root.right);
if(Math.abs(left-right)>1)
flag = false;
return Math.max(left,right)+1;
}
}
| 29.606061 | 53 | 0.558854 |
74ef38fba19e06411685064d1e48d9cf5324ab34 | 1,915 | package de.elnarion.ddlutils.alteration;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.List;
import de.elnarion.ddlutils.model.Table;
/**
* Defines a predicate that allows platforms to state whether all of the given table definition
* changes (i.e. column changes and primary key changes) are supported by the platform or not.
*
* @version $Revision: $
*/
public interface TableDefinitionChangesPredicate
{
/**
* Evaluates the given list of table changes and determines whether they are supported.
*
* @param intermediateTable The current table object which has certain non-table-definition
* changes already applied (those that would come before the give
* list of changes in the result of
* {@link ModelComparator#compare(de.elnarion.ddlutils.model.Database, de.elnarion.ddlutils.model.Database)}
* @param changes The non-empty list of changes
* @return <code>true</code> if the current plaform supports them
*/
public boolean areSupported(Table intermediateTable, List<TableChange> changes);
}
| 41.630435 | 137 | 0.716449 |
3c40cfe23b9bddbec13179aa7d68639c790fb876 | 331 | package org.nse.battleship;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by Tom on 23.07.2015.
*/
public class GameWonActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.win);
}
} | 22.066667 | 53 | 0.712991 |
617af4cbfce765dd1916a5a474bc84d503a94562 | 1,434 | package com.francelabs.datafari.handler.parsed;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.solr.common.params.UpdateParams;
import org.apache.solr.common.util.ContentStream;
import org.apache.solr.handler.extraction.ExtractionDateUtil;
import org.apache.solr.handler.loader.ContentStreamLoader;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.update.AddUpdateCommand;
import org.apache.solr.update.processor.UpdateRequestProcessor;
public class ParsedDocumentLoader extends ContentStreamLoader {
@Override
public void load(final SolrQueryRequest req, final SolrQueryResponse rsp, final ContentStream stream, final UpdateRequestProcessor processor)
throws Exception {
// TODO Auto-generated method stub
final InputStream is = stream.getStream();
try {
final ParsedContentHandler tch = new ParsedContentHandler(req.getParams(), req.getSchema(), is, ExtractionDateUtil.DEFAULT_DATE_FORMATS);
final AddUpdateCommand templateAdd = new AddUpdateCommand(req);
templateAdd.overwrite = req.getParams().getBool(UpdateParams.OVERWRITE, true);
templateAdd.commitWithin = req.getParams().getInt(UpdateParams.COMMIT_WITHIN, -1);
templateAdd.solrDoc = tch.newDocument();
processor.processAdd(templateAdd);
} finally {
IOUtils.closeQuietly(is);
}
}
}
| 36.769231 | 143 | 0.783821 |
6c3871c95e446402c2753db170e866b3798a8d1f | 452 | package enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
@AllArgsConstructor
@Getter
@ToString
public enum RpcErrorMessageEnum {
CLIENT_CONNECT_SERVER_FAILURE("客户端连接服务端失败"),
SERVICE_INVOCATION_FAILURE("服务调用失败"),
SERVICE_CAN_NOT_BE_FOUND("没有找到指定的服务"),
SERVICE_NOT_IMPLEMENT_ANY_INTERFACE("注册的服务没有实现任何接口"),
REQUEST_NOT_MATCH_RESPONSE("返回结果错误!请求和返回的相应不匹配");
private final String message;
} | 23.789474 | 57 | 0.798673 |
30675b3350d94a55d6de2abc001ba6dab66f1c89 | 515 | package old.readwrite;
import java.util.Map;
import java.util.Scanner;
import old.core.exceptions.FileReadException;
import old.core.exceptions.FormatNotSupportedException;
import old.datatypes.DataType;
import org.w3c.dom.Element;
public interface DataReader {
public Map<String, String[]> getValidReadFormats();
public DataType read(String format, Scanner s) throws FormatNotSupportedException, FileReadException;
public DataType readXML(Element e) throws FormatNotSupportedException, FileReadException;
}
| 30.294118 | 102 | 0.829126 |
da2a900faa7c09c9fd301e5233c3d50cc2ad197b | 206 | package com.understand.concurrency.task6;
public class Main {
public static void main(String[] args) {
ExecutorTask executorTask = new ExecutorTask();
executorTask.execute();
}
}
| 18.727273 | 55 | 0.674757 |
48dcd64052321d8d665def0d4324fadd28f3d610 | 58 | /**
*
*/
/**
* @author jron
*
*/
package exampleTwo; | 7.25 | 19 | 0.465517 |
4aa288b0a4ae5b9b05c0a29096278e2d2044292e | 1,682 | package oracle.pgql.lang;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class Experimental extends AbstractPgqlTest {
@Test
public void testReferencesToSelectExpression1() throws Exception {
String query = "SELECT n.age * 2 AS doubleAge "//
+ " FROM MATCH (n) ON g "//
+ " WHERE doubleAge = n.age + n.age "//
+ "GROUP BY doubleAge "//
+ " HAVING doubleAge = n.age * 2 "//
+ "ORDER BY 2 * doubleAge ASC, 2 * (n.age * 2) DESC";
PgqlResult result = pgql.parse(query);
assertTrue(result.isQueryValid());
}
@Test
public void testReferencesToSelectExpression2() throws Exception {
String query = "SELECT n.age * 2 AS doubleAge "//
+ " FROM MATCH (n) ON g "//
+ " WHERE doubleAge = n.age + n.age "//
+ "GROUP BY n.age * 2 "//
+ " HAVING doubleAge = n.age * 2 "//
+ "ORDER BY 2* doubleAge ASC, 2 * (n.age * 2) DESC";
PgqlResult result = pgql.parse(query);
assertTrue(result.isQueryValid());
}
@Test
public void testImplicitPropertyReferences1() throws Exception {
String query = "SELECT n.prop"//
+ " FROM MATCH (n) ON g"//
+ " ORDER BY prop";
PgqlResult result = pgql.parse(query);
assertTrue(result.isQueryValid());
}
@Test
public void testImplicitPropertyReferences2() throws Exception {
String query = "SELECT n.prop"//
+ " FROM MATCH (n) ON g"//
+ " WHERE prop = 3"//
+ " GROUP BY prop"//
+ " HAVING prop > 10";
PgqlResult result = pgql.parse(query);
assertTrue(result.isQueryValid());
}
}
| 31.735849 | 68 | 0.579667 |
fa76639a47f6cd5ce337023cd150eefdf53c4c65 | 1,186 | package org.drools.core.factmodel.traits;
import org.drools.core.util.Triple;
import org.drools.core.util.TripleFactory;
import org.drools.core.util.TripleImpl;
import org.drools.core.util.TripleStore;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
public class TripleBasedBean extends TripleBasedStruct {
protected Object object;
public TripleBasedBean() {
}
public TripleBasedBean( Object o, TripleStore store, TripleFactory factory ) {
super();
this.store = store;
this.storeId = store.getId();
this.object = o;
this.tripleFactory = factory;
}
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal( out );
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal( in );
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
@Override
public String toString() {
return "TripleBasedBean{" +
"object=" + object +
'}';
}
}
| 23.254902 | 89 | 0.655987 |
16219e07ce8eb7084015f512f053780fd1839c97 | 1,730 | package edu.southwestern.tasks.megaman;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import edu.southwestern.tasks.megaman.levelgenerators.MegaManGANGenerator.SEGMENT_TYPE;
public class MegaManTrackSegmentType {
public static int numRight = 0;
public static int numLeft = 0;
public static int numUp = 0;
public static int numDown = 0;
public static int numCorner = 0;
public static int numDistinctSegments = 0;
/**
* takes in a single segment type and adds to the total of that type
* @param segmentType the type of segment used in the placement of one segment
* @param distinct
* @param segment
*/
public void findSegmentData(SEGMENT_TYPE segmentType, List<List<Integer>> segment, HashSet<List<List<Integer>>> distinct) {
distinct.add(segment);
numDistinctSegments = distinct.size();
switch(segmentType) {
case UP:
numUp++;
break;
case DOWN:
numDown++;
break;
case RIGHT:
numRight++;
break;
case LEFT:
numLeft++;
break;
case TOP_LEFT:
numCorner++;
break;
case TOP_RIGHT:
numCorner++;
break;
case BOTTOM_RIGHT:
numCorner++;
break;
case BOTTOM_LEFT:
numCorner++;
break;
default: throw new IllegalArgumentException("Valid SEGMENT_TYPE not specified");
}
}
public HashMap<String, Integer> findMiscSegments(){
HashMap<String, Integer> j = new HashMap<>();
j.put("numUp", numUp);
j.put("numDown", numDown);
j.put("numRight", numRight);
j.put("numLeft", numLeft);
j.put("numCorner", numCorner);
j.put("numDistinctSegments", numDistinctSegments);
numRight = 0;
numLeft = 0;
numUp = 0;
numDown = 0;
numCorner = 0;
numDistinctSegments = 0;
return j;
}
}
| 22.179487 | 124 | 0.691329 |
2abf6d5380f3d0369debd79dbe957b98bff28c52 | 519 | package com.aks.commons.controller;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;
public interface BaseController<
Request extends BaseRequest,
Response extends BaseResponse,
ID> {
Optional<Response> update(@Valid Request requestModel);
Optional<Response> insert(@Valid Request requestModel);
Optional<Response> getById(@Valid ID id);
List<Response> getAll();
void deleteById(@Valid ID id);
void softDeleteById(@Valid ID id);
}
| 21.625 | 59 | 0.714836 |
c002c7eeaefe45834fb336020f0fa95568ca8094 | 747 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rs.fon.eklub.core.entities;
/**
*
* @author milos
*/
public class Stat {
private String label;
private String value;
public Stat() {
}
public Stat(String label, String value) {
this.label = label;
this.value = value;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| 17.372093 | 79 | 0.597055 |
d3f76fcdfa5630310b1bcd43c5cd833ea01a6e17 | 19,273 | /*
* Copyright 2014 Thomas Hoffmann
*
* 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 de.j4velin.pedometer.ui;
import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceFragment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.RadioGroup;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Locale;
import de.j4velin.pedometer.Database;
import de.j4velin.pedometer.PowerReceiver;
import de.j4velin.pedometer.R;
import de.j4velin.pedometer.SensorListener2;
import de.j4velin.pedometer.util.API23Wrapper;
import de.j4velin.pedometer.util.PlaySettingsWrapper;
public class Fragment_Settings extends PreferenceFragment implements OnPreferenceClickListener {
final static int DEFAULT_GOAL = 10000;
final static float DEFAULT_STEP_SIZE = Locale.getDefault() == Locale.US ? 2.5f : 75f;
final static String DEFAULT_STEP_UNIT = Locale.getDefault() == Locale.US ? "ft" : "cm";
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
findPreference("import").setOnPreferenceClickListener(this);
findPreference("export").setOnPreferenceClickListener(this);
findPreference("theme")
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
getActivity().recreate();
return true;
}
});
findPreference("notification")
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(final Preference preference,
final Object newValue) {
getActivity().getSharedPreferences("pedometer", Context.MODE_PRIVATE).edit()
.putBoolean("notification", (Boolean) newValue).commit();
getActivity().startService(new Intent(getActivity(), SensorListener2.class)
.setAction(SensorListener2.ACTION_UPDATE_NOTIFICATION));
return true;
}
});
findPreference("pause_on_power")
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(final Preference preference,
final Object newValue) {
getActivity().getPackageManager().setComponentEnabledSetting(
new ComponentName(getActivity(), PowerReceiver.class),
((Boolean) newValue) ?
PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
return true;
}
});
Preference account = findPreference("account");
PlaySettingsWrapper
.setupAccountSetting(account, savedInstanceState, (Activity_Main) getActivity());
final SharedPreferences prefs =
getActivity().getSharedPreferences("pedometer", Context.MODE_PRIVATE);
Preference goal = findPreference("goal");
goal.setOnPreferenceClickListener(this);
goal.setSummary(getString(R.string.goal_summary, prefs.getInt("goal", DEFAULT_GOAL)));
Preference stepsize = findPreference("stepsize");
stepsize.setOnPreferenceClickListener(this);
stepsize.setSummary(getString(R.string.step_size_summary,
prefs.getFloat("stepsize_value", DEFAULT_STEP_SIZE),
prefs.getString("stepsize_unit", DEFAULT_STEP_UNIT)));
setHasOptionsMenu(true);
}
@Override
public void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
PlaySettingsWrapper.onSavedInstance(outState, (Activity_Main) getActivity());
}
@Override
public void onResume() {
super.onResume();
getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
}
@Override
public void onPrepareOptionsMenu(final Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.action_settings).setVisible(false);
menu.findItem(R.id.action_pause).setVisible(false);
menu.findItem(R.id.action_split_count).setVisible(false);
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
return ((Activity_Main) getActivity()).optionsItemSelected(item);
}
@Override
public boolean onPreferenceClick(final Preference preference) {
AlertDialog.Builder builder;
View v;
final SharedPreferences prefs =
getActivity().getSharedPreferences("pedometer", Context.MODE_PRIVATE);
switch (preference.getTitleRes()) {
case R.string.goal:
builder = new AlertDialog.Builder(getActivity());
final NumberPicker np = new NumberPicker(getActivity());
np.setMinValue(1);
np.setMaxValue(100000);
np.setValue(prefs.getInt("goal", 10000));
builder.setView(np);
builder.setTitle(R.string.set_goal);
builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
np.clearFocus();
prefs.edit().putInt("goal", np.getValue()).commit();
preference.setSummary(getString(R.string.goal_summary, np.getValue()));
dialog.dismiss();
getActivity().startService(new Intent(getActivity(), SensorListener2.class)
.setAction(SensorListener2.ACTION_UPDATE_NOTIFICATION));
}
});
builder.setNegativeButton(android.R.string.cancel, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = builder.create();
dialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
break;
case R.string.step_size:
builder = new AlertDialog.Builder(getActivity());
v = getActivity().getLayoutInflater().inflate(R.layout.stepsize, null);
final RadioGroup unit = (RadioGroup) v.findViewById(R.id.unit);
final EditText value = (EditText) v.findViewById(R.id.value);
unit.check(
prefs.getString("stepsize_unit", DEFAULT_STEP_UNIT).equals("cm") ? R.id.cm :
R.id.ft);
value.setText(String.valueOf(prefs.getFloat("stepsize_value", DEFAULT_STEP_SIZE)));
builder.setView(v);
builder.setTitle(R.string.set_step_size);
builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
prefs.edit().putFloat("stepsize_value",
Float.valueOf(value.getText().toString()))
.putString("stepsize_unit",
unit.getCheckedRadioButtonId() == R.id.cm ? "cm" : "ft")
.apply();
preference.setSummary(getString(R.string.step_size_summary,
Float.valueOf(value.getText().toString()),
unit.getCheckedRadioButtonId() == R.id.cm ? "cm" : "ft"));
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
dialog.dismiss();
}
});
builder.setNegativeButton(android.R.string.cancel, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
break;
case R.string.import_title:
case R.string.export_title:
if (hasWriteExternalPermission()) {
if (preference.getTitleRes() == R.string.import_title) {
importCsv();
} else {
exportCsv();
}
} else if (Build.VERSION.SDK_INT >= 23) {
API23Wrapper.requestPermission(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE});
} else {
Toast.makeText(getActivity(), R.string.permission_external_storage,
Toast.LENGTH_SHORT).show();
}
break;
}
return false;
}
private boolean hasWriteExternalPermission() {
return getActivity().getPackageManager()
.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
getActivity().getPackageName()) == PackageManager.PERMISSION_GRANTED;
}
/**
* Creates the CSV file containing data about past days and the steps taken on them
* <p/>
* Requires external storage to be writeable
*/
private void exportCsv() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
final File f = new File(Environment.getExternalStorageDirectory(), "Pedometer.csv");
if (f.exists()) {
new AlertDialog.Builder(getActivity()).setMessage(R.string.file_already_exists)
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
writeToFile(f);
}
}).setNegativeButton(android.R.string.cancel, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
} else {
writeToFile(f);
}
} else {
new AlertDialog.Builder(getActivity())
.setMessage(R.string.error_external_storage_not_available)
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
}
/**
* Imports previously exported data from a csv file
* <p/>
* Requires external storage to be readable. Overwrites days for which there is already an entry in the database
*/
private void importCsv() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File f = new File(Environment.getExternalStorageDirectory(), "Pedometer.csv");
if (!f.exists() || !f.canRead()) {
new AlertDialog.Builder(getActivity())
.setMessage(getString(R.string.file_cant_read, f.getAbsolutePath()))
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
return;
}
Database db = Database.getInstance(getActivity());
String line;
String[] data;
int ignored = 0, inserted = 0, overwritten = 0;
BufferedReader in;
try {
in = new BufferedReader(new FileReader(f));
while ((line = in.readLine()) != null) {
data = line.split(";");
try {
if (db.insertDayFromBackup(Long.valueOf(data[0]),
Integer.valueOf(data[1]))) {
inserted++;
} else {
overwritten++;
}
} catch (Exception nfe) {
ignored++;
}
}
in.close();
} catch (IOException e) {
new AlertDialog.Builder(getActivity())
.setMessage(getString(R.string.error_file, e.getMessage()))
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
e.printStackTrace();
return;
} finally {
db.close();
}
String message = getString(R.string.entries_imported, inserted + overwritten);
if (overwritten > 0)
message += "\n\n" + getString(R.string.entries_overwritten, overwritten);
if (ignored > 0) message += "\n\n" + getString(R.string.entries_ignored, ignored);
new AlertDialog.Builder(getActivity()).setMessage(message)
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
} else {
new AlertDialog.Builder(getActivity())
.setMessage(R.string.error_external_storage_not_available)
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
}
private void writeToFile(final File f) {
BufferedWriter out;
try {
f.createNewFile();
out = new BufferedWriter(new FileWriter(f));
} catch (IOException e) {
new AlertDialog.Builder(getActivity())
.setMessage(getString(R.string.error_file, e.getMessage()))
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
e.printStackTrace();
return;
}
Database db = Database.getInstance(getActivity());
Cursor c =null;
// db.query(new String[]{"date", "steps"}, "date > 0", null, null, null, "date", null);
try {
if (c != null && c.moveToFirst()) {
while (!c.isAfterLast()) {
out.append(c.getString(0)).append(";")
.append(String.valueOf(Math.max(0, c.getInt(1)))).append("\n");
c.moveToNext();
}
}
out.flush();
out.close();
} catch (IOException e) {
new AlertDialog.Builder(getActivity())
.setMessage(getString(R.string.error_file, e.getMessage()))
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
e.printStackTrace();
return;
} finally {
if (c != null) c.close();
db.close();
}
new AlertDialog.Builder(getActivity())
.setMessage(getString(R.string.data_saved, f.getAbsolutePath()))
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
}
| 44.613426 | 116 | 0.543766 |
43b7c927cbfbb23a3964747b128323ae49351c5a | 3,875 | /**
* Copyright (c) 2019,2020 honintech
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package cn.weforward.common;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import cn.weforward.common.sys.IdGenerator;
import cn.weforward.common.util.AntPathPattern;
import cn.weforward.common.util.Bytes;
import cn.weforward.common.util.UriMatcher;
public class TestUtils {
@Test
public void benchmarkAntPathPattern() {
AntPathPattern ap1 = AntPathPattern.valueOf("/**/*.jsp");
AntPathPattern ap2 = AntPathPattern.valueOf("/**/a*b?.*");
AntPathPattern ap3 = AntPathPattern.valueOf("/**/a*b?.*");
AntPathPattern ap4 = AntPathPattern.valueOf("/app/**/dir/file.*");
AntPathPattern ap5 = AntPathPattern.valueOf("/app/**/dir/file.*");
AntPathPattern ap6 = AntPathPattern.valueOf("/**abc.*");
AntPathPattern ap7 = AntPathPattern.valueOf("/**/*");
AntPathPattern ap8 = AntPathPattern.valueOf("/abc/*");
AntPathPattern ap9 = AntPathPattern.valueOf("/abc/*");
AntPathPattern ap10 = AntPathPattern.valueOf("/**/?");
AntPathPattern ap11 = AntPathPattern.valueOf("/**/?");
AntPathPattern ap12 = AntPathPattern.valueOf("abc/*.jsp");
AntPathPattern ap13 = AntPathPattern.valueOf("/abc////def.*");
AntPathPattern ap14 = AntPathPattern.valueOf("/abc/def.jsp/**/**");
for (int i = 0; i < 1000000; i++) {
ap1.match("/bs/ts/aa.jsp");
ap2.match("/bs/ts/aab.jsp");
ap3.match("/bs/ts/abc.jsp");
ap4.match("/app/foo/dir/file.html");
ap5.match("/app/foo/bar/dir/file.pdf");
ap6.match("/app/foo/abc.pdf");
ap7.match("/app/foo/abc/");
ap8.match("/abc/a");
ap9.match("/abc/a/");
ap10.match("/app/foo/abc/");
ap11.match("/app/f");
ap12.match("bb/aa.jsp");
ap13.match("/abc/def.jsp");
ap14.match("/abc/def.jsp");
}
}
// @Test
public void testBytes() {
String readable = "2000m";
long v = Bytes.parseHumanReadable(readable);
System.out.println(v);
System.out.println(v >= Bytes.UNIT_GB);
}
// @Test
public void testTimestamp() {
IdGenerator.Tick tick = new IdGenerator.Tick("x000a");
System.out.println(tick.genId(""));
System.out.println(tick.genId(""));
}
// @Test
public void testUriMatcher() {
List<String> uris = Arrays.asList("/abc/(**)", "/ab-(**)", "/ticket/*.jspx", "/ticket/**",
"/ticket/abc/*.jspx", "/wx-*", "/wx-**", "**");
UriMatcher matcher = new UriMatcher(uris);
System.out.println(matcher.match("/abc/b.jspx"));
System.out.println(matcher.match("/ab-b.jspx"));
System.out.println(matcher.match("/ticket/b.jspx"));
System.out.println(matcher.match("/ticket/abc/a.jspx"));
System.out.println(matcher.match("/ticket/abc/b/a.jspx"));
System.out.println(matcher.match("/wx-a001b"));
System.out.println(matcher.match("/wx-a001b/a.jspx"));
System.out.println(matcher.match("/dir/file"));
System.out.println(matcher.match("/2dir/3-file"));
}
}
| 43.055556 | 463 | 0.698839 |
ecfd8bc8d024d6b99f5561d30c41f76194f6fadd | 6,730 | /*
* Copyright (C) 2016 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 com.example.android.miwok;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
public class ColorsActivity extends AppCompatActivity {
ListView listView;
MediaPlayer mediaPlayer;
int focusChange;
private AudioManager mAudioManager;
/**
* the following code snippet,
* is for playback and mediaplayer objects if the audio is trasient
* and resume it when regain the focus. if the loss is permenant
* it unregister the media button event receiver
* and stops monitoring the changes
*/
AudioManager.OnAudioFocusChangeListener AfterChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int i) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
//for pause playback
mediaPlayer.pause();
//resume
mediaPlayer.seekTo(0);
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
//regain /resume the playback
mediaPlayer.start();
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
//stop playback n clean source code
releaseMediaPlayer();
// mAudioManager.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
// mAudioManager.abandonAudioFocus(AfterChangeListener);
//
}
}
};
//this listener gets triggered when the link mediaplayer has completed playing diff audio
private MediaPlayer.OnCompletionListener mCompletionListener = (new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
//stop activity , release media player resources
// for we wont be using it anymore
releaseMediaPlayer();
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colors);
//create and set link audioManager to request audio focus
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//created a list of array
final ArrayList<Word> words = new ArrayList<Word>();
words.add(new Word(getResources().getString(R.string.red), "wetetti", R.drawable.color_red, R.raw.color_red));
words.add(new Word(getResources().getString(R.string.mustardyellow), "chiwiitә", R.drawable.color_mustard_yellow, R.raw.color_mustard_yellow));
words.add(new Word(getResources().getString(R.string.dustyyellow), "topiisә", R.drawable.color_dusty_yellow, R.raw.color_dusty_yellow));
words.add(new Word(getResources().getString(R.string.green), "chokokki", R.drawable.color_green, R.raw.color_green));
words.add(new Word(getResources().getString(R.string.brown), "takaakki", R.drawable.color_brown, R.raw.color_brown));
words.add(new Word(getResources().getString(R.string.gray), "topoppi", R.drawable.color_gray, R.raw.color_gray));
words.add(new Word(getResources().getString(R.string.black), "kululli", R.drawable.color_black, R.raw.color_black));
words.add(new Word(getResources().getString(R.string.white), "kelelli", R.drawable.color_white, R.raw.color_white));
//set adapter.............
WordAdapter adapter = new WordAdapter(this, words, R.color.category_numbers);
listView = (ListView) findViewById(R.id.GridL);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//the above we use it to read rather than use of mp3 and the below is for the mp3 raw file
Word word = words.get(position);
///request audio focus for play back
int results = mAudioManager.requestAudioFocus(AfterChangeListener,
//use the music stream
AudioManager.STREAM_MUSIC,
//request permanent focus
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);//because our audio are short otherwise gain.
if (results == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// mAudioManager.registerMediaButtonEventReceiver(RemoteControlReceiver);
//here we have audio focus
mediaPlayer = MediaPlayer.create(ColorsActivity.this, word.getmAudioResourceId());
//start aud play
mediaPlayer.start();
// set listener on media ply inorder to stop and release the mediaplyt onc sound hs finished
mediaPlayer.setOnCompletionListener(mCompletionListener);
}
}
});
}
@Override
protected void onStop() {
super.onStop();
//when the activity is stopped, relaese the mediaplayer resources because we won't
//be playing any more sounds
releaseMediaPlayer();
}
/**
* Connects with the initial onclick methods
*/
//clean up media player
private void releaseMediaPlayer() {
if (mediaPlayer != null) {
//regardless of current state of media player since we no longer need it
mediaPlayer.release();
//set the media player back to null. for code we decide to set media player to null (nat playing)
mediaPlayer = null;
//abandon the audio focus when playback complete
mAudioManager.abandonAudioFocus(AfterChangeListener);
}
}
}
| 38.022599 | 151 | 0.659287 |
aaf6ca59c2186c11e48bd815047a4fabc9069c50 | 3,235 | /*
* 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.ignite.internal.processors.cache.datastructures;
import org.apache.ignite.*;
import java.util.*;
/**
* Basic tests for atomic reference.
*/
public abstract class GridCacheAtomicReferenceApiSelfAbstractTest extends IgniteAtomicsAbstractTest {
/** {@inheritDoc} */
@Override protected int gridCount() {
return 1;
}
/**
* JUnit.
*
* @throws Exception If failed.
*/
public void testPrepareAtomicReference() throws Exception {
/** Name of first atomic. */
String atomicName1 = UUID.randomUUID().toString();
/** Name of second atomic. */
String atomicName2 = UUID.randomUUID().toString();
String initVal = "1";
IgniteAtomicReference<String> atomic1 = grid(0).atomicReference(atomicName1, initVal, true);
IgniteAtomicReference<String> atomic2 = grid(0).atomicReference(atomicName2, null, true);
assertNotNull(atomic1);
assertNotNull(atomic2);
atomic1.close();
atomic2.close();
atomic1.close();
atomic2.close();
assertNull(grid(0).atomicReference(atomicName1, null, false));
assertNull(grid(0).atomicReference(atomicName2, null, false));
try {
atomic1.get();
fail();
}
catch (IllegalStateException e) {
info("Caught expected exception: " + e.getMessage());
}
}
/**
* JUnit.
*
* @throws Exception If failed.
*/
public void testSetAndGet() throws Exception {
String atomicName = UUID.randomUUID().toString();
String initVal = "qwerty";
IgniteAtomicReference<String> atomic = grid(0).atomicReference(atomicName, initVal, true);
assertEquals(initVal, atomic.get());
atomic.set(null);
assertEquals(null, atomic.get());
}
/**
* JUnit.
*
* @throws Exception If failed.
*/
public void testCompareAndSetSimpleValue() throws Exception {
String atomicName = UUID.randomUUID().toString();
String initVal = "qwerty";
IgniteAtomicReference<String> atomic = grid(0).atomicReference(atomicName, initVal, true);
assertEquals(initVal, atomic.get());
atomic.compareAndSet("h", "j");
assertEquals(initVal, atomic.get());
atomic.compareAndSet(initVal, null);
assertEquals(null, atomic.get());
}
}
| 28.628319 | 101 | 0.649459 |
c106bb04e36ad8e7f9517a3b022bb70a4d99c15f | 7,241 | package com.poppinjay13.grind.Adapters;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.golovin.fluentstackbar.FluentSnackbar;
import com.google.android.material.snackbar.Snackbar;
import com.poppinjay13.grind.Database.GrindRoomDatabase;
import com.poppinjay13.grind.Entities.Event;
import com.poppinjay13.grind.EventActivity;
import com.poppinjay13.grind.R;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class EventsAdapter extends RecyclerView.Adapter<EventsAdapter.MyViewHolder> {
private List<Event> myEvents;
private Context mContext;
private View mSnackbar;
private Event deleted;
private int deletePos;
private GrindRoomDatabase grindRoomDatabase;
private String myFormat = "dd/MM/yyyy";
private SimpleDateFormat sdformat = new SimpleDateFormat(myFormat, Locale.UK);
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView month, date, title, description;
CardView card;
MyViewHolder(View v) {
super(v);
grindRoomDatabase = GrindRoomDatabase.getDatabase(mContext);
month = v.findViewById(R.id.month);
date = v.findViewById(R.id.date);
title = v.findViewById(R.id.title);
description = v.findViewById(R.id.description);
card = v.findViewById(R.id.event);
card.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int eventId = myEvents.get(getAdapterPosition()).getId();
Intent intent = new Intent(mContext, EventActivity.class);
intent.putExtra("EventId",eventId);
mContext.startActivity(intent);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public EventsAdapter(Context context, View snackbar) {
mContext = context;
mSnackbar = snackbar;
}
public void setEvents(List<Event> myEvents){
this.myEvents = myEvents;
}
// Create new views (invoked by the layout manager)
@NonNull
@Override
public EventsAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
CardView v = (CardView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.event, parent, false);
return new MyViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
try {
Event event = myEvents.get(position);
holder.title.setText(event.getTitle());
if(event.getStatus() == 1){
holder.title.setPaintFlags(holder.title.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.title.setTextColor(mContext.getResources().getColor(R.color.colorHints));
}
holder.description.setText(event.getDescription());
holder.month.setText("---");
holder.date.setText("--");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdformat.parse(myEvents.get(position).getStart_date()));
holder.month.setText(new SimpleDateFormat("MMM", Locale.UK).format(calendar.getTime()));
holder.date.setText(new SimpleDateFormat("dd", Locale.UK).format(calendar.getTime()));
} catch (Exception ex) {
//Log.e("ADAPTER",""+ex);
}
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return myEvents.size();
}
public void deleteEvent(int position) {
try {
deleted = myEvents.get(position);
deletePos = position;
grindRoomDatabase.EventDAO().deleteEvent(myEvents.get(position).getId());
myEvents.remove(position);
notifyItemRemoved(position);
FluentSnackbar fluentSnackbar = FluentSnackbar.create(mSnackbar);
fluentSnackbar.create("Event Deleted")
.maxLines(1)
.backgroundColorRes(R.color.colorPrimary)
.textColorRes(R.color.colorWhite)
.duration(Snackbar.LENGTH_LONG)
.actionText("Undo")
.actionTextColorRes(R.color.colorWhite)
.important(true)
.action(new View.OnClickListener() {
@Override
public void onClick(View v) {
grindRoomDatabase.EventDAO().InsertEvent(deleted);
myEvents.add(deletePos, deleted);
notifyItemInserted(deletePos);
}
})
.show();
}catch (Exception ex){
//Log.e("ADAPTER",""+ex);
}
}
public void completeEvent(final int position) {
try {
FluentSnackbar fluentSnackbar = FluentSnackbar.create(mSnackbar);
if(myEvents.get(position).getStatus() == 1){
fluentSnackbar.create("Event Already Complete :)")
.maxLines(1)
.backgroundColorRes(R.color.colorPrimary)
.textColorRes(R.color.colorWhite)
.duration(Snackbar.LENGTH_LONG)
.important(true)
.show();
notifyItemChanged(position);
return;
}
grindRoomDatabase.EventDAO().completeEvent(myEvents.get(position).getId());
//mainActivity.notifyChange(position);
//notifyItemChanged(position);
fluentSnackbar.create("Event Marked as Complete")
.maxLines(1)
.backgroundColorRes(R.color.colorPrimary)
.textColorRes(R.color.colorWhite)
.duration(Snackbar.LENGTH_LONG)
.actionText("Undo")
.actionTextColorRes(R.color.colorWhite)
.important(true)
.action(new View.OnClickListener() {
@Override
public void onClick(View v) {
grindRoomDatabase.EventDAO().completeEventUndo(myEvents.get(position).getId());
notifyItemChanged(position);
}
})
.show();
}catch (Exception ex){
//Log.e("ADAPTER",""+ex);
}
}
public Context getContext(){
return mContext;
}
} | 39.140541 | 107 | 0.591907 |
bf48a8466578694f699e516b599eb9282b39ecda | 3,681 | package br.com.qyon.atualizadorPostgres;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
/**
* Hello world!
*
*/
public class atualizador {
private static final String schema = "atualizador_postgres";
private static final String tabela = "atualizado";
public static void main(String[] args) throws IOException {
// Busca
File migration = new File("./migration");
if (!migration.exists() || !migration.isDirectory())
migration.mkdir();
// throw new RuntimeException(
// "É necessario criar um folder chamado migration, e colocar todos os arquivos
// \".sql\" dentro dele");
if (args.length != 4)
throw new RuntimeException(
"Por favor coloque as seguintes propriedades na sequencia: [url de conexao BD SEM NENHUMA BASE] [usuario do BD] [senha do BD] [pesquisa dos bancos de dados, usando like]");
if (!args[0].endsWith("/"))
args[0] += "/";
String dbInicial = args[0];
String usuario = args[1];
String senha = args[2];
String inicioDatabase = args[3];
try (Connection connection = DriverManager.getConnection(dbInicial, usuario, senha)) {
System.out.println("Connected to PostgreSQL database!");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(
"select datname from pg_catalog.pg_database pd where datname like '" + inicioDatabase + "'");
System.out.println("Lendo os bancos de dados com like: " + inicioDatabase);
while (resultSet.next()) {
String banco = resultSet.getString("datname");
System.out.println("Connecting to database: " + banco);
try (Connection connection2 = DriverManager.getConnection(dbInicial + banco, usuario, senha)) {
Statement statement2 = connection2.createStatement();
// Ordena por nome todos os arquivos dentro do folder
List<File> sqls = Arrays.asList(migration.listFiles());
sqls.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
for (File sql : sqls) {
if (!sql.getName().endsWith(".sql"))
continue;
// Cria uma table que garante que não irá rodar o mesmo arquivo mais de uma vez
statement2.execute("Create schema if not exists " + schema + ";\r\n" //
+ " create table IF NOT EXISTS " + schema + "." + tabela
+ "(\"id\" SERIAL PRIMARY KEY, \"script\" varchar not null, \"data\" timestamp not null, constraint \"unique_script\" unique (\"script\"));");
String script = sql.getName();
ResultSet resultSet2 = statement2.executeQuery(
"select script from " + schema + "." + tabela + " where script like '" + script + "'");
if (resultSet2.next()) {
// Pula para o próximo arquivo
continue;
}
System.out.println("Atualizando o script " + script);
try (BufferedReader reader = new BufferedReader(new FileReader(sql));) {
String currentLine;
StringBuilder sb = new StringBuilder();
while ((currentLine = reader.readLine()) != null) {
sb.append(currentLine + "\r\n");
}
System.out.println(sb.toString());
statement2.execute(sb.toString());
// TODO salvar o nome do arquivo salvo
statement2.execute("insert into " + schema + "." + tabela + "(script, data) values ('"
+ script + "', current_timestamp)");
}
}
}
}
} catch (SQLException e) {
System.out.println("Ocorreu um problema durante a atualização.");
e.printStackTrace();
}
}
}
| 34.401869 | 177 | 0.664765 |
398b3b0a509bd6583c5218fb5cf16633048332bd | 4,654 | package com.solverpeng.controller;
import com.solverpeng.bean.Order;
import com.solverpeng.bean.Person;
import com.solverpeng.bean.Trade;
import com.solverpeng.bean.User;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.format.Formatter;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.number.NumberStyleFormatter;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.ServletRequestParameterPropertyValues;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditor;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Locale;
@Controller
@RequestMapping("/dataBinder")
public class DataBinderController {
@InitBinder("user")
public void disAllowedUserName(WebDataBinder dataBinder) {
// 不绑定"name"属性
dataBinder.setDisallowedFields("name");
}
// 注册自定义编辑器
@InitBinder("user")
public void userBirthEditor(WebDataBinder dataBinder) {
// 对日期类通过自定义编辑器进行格式化
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
dateFormatter.setLenient(false);
PropertyEditor propertyEditor = new CustomDateEditor(dateFormatter, true);
dataBinder.registerCustomEditor(Date.class, "dateOfBirth", propertyEditor);
}
/**
* 自定义格式化器
*/
@InitBinder("trade")
public void formatter(WebDataBinder dataBinder) {
DateFormatter dateFormatter = new DateFormatter();
dateFormatter.setPattern("yyyy-MM-dd");
dataBinder.addCustomFormatter(new Formatter<LocalDate>() {
@Override
public LocalDate parse(String text, Locale locale) throws ParseException {
return LocalDate.parse(text, DateTimeFormatter.ISO_DATE);
}
@Override
public String print(LocalDate date, Locale locale) {
return DateTimeFormatter.ISO_DATE.format(date);
}
}, "tradeDate");
NumberStyleFormatter numberFormatter = new NumberStyleFormatter("#,###,###,###.##");
dataBinder.addCustomFormatter(numberFormatter, "amount");
}
// @InitBinder
public void initBinder(WebDataBinder binder, HttpServletRequest request) {
PropertyValues pvs = new ServletRequestParameterPropertyValues(request);
binder.bind(pvs);
binder.addCustomFormatter(null);
binder.addValidators(null);
binder.initBeanPropertyAccess();
binder.setValidator(null);
binder.setRequiredFields();
binder.setConversionService(null);
binder.setAllowedFields();
binder.setDisallowedFields();
binder.setBindingErrorProcessor(null);
binder.setMessageCodesResolver(null);
binder.replaceValidators();
binder.registerCustomEditor(null, null, null);
binder.convertIfNecessary(null, null);
}
@ResponseBody
@GetMapping("/bindRequestParamToModelAttribute")
public String bindRequestParamToModelAttribute(@ModelAttribute("user") User user, BindingResult result) {
if(result.hasErrors()) {
List<ObjectError> allErrors = result.getAllErrors();
if(!CollectionUtils.isEmpty(allErrors)) {
for(ObjectError allError : allErrors) {
System.out.println("error: " + allError.getDefaultMessage());
}
}
}
return "dataBinder->bindRequestParamToModelAttribute:" + user;
}
/**
* 默认也会进行绑定
*/
@ResponseBody
@GetMapping("/dataBinderWithMethodArgs")
public String DataBinderWithMethodArgs(@ModelAttribute("person") Person person) {
return "dataBinderWithMethodArgs" + person;
}
@ResponseBody
@GetMapping("/dataBindWithFormatter")
public String dataBindWithFormatter(Trade trade, BindingResult result) {
return "dataBindWithFormatter->trade:" + trade;
}
@ResponseBody
@GetMapping("/dataBindWithAnnotationFormatter")
public String dataBindWithAnnotationFormatter(Order order, BindingResult result) {
return "dataBindWithFormatter->order:" + order;
}
}
| 35.8 | 109 | 0.710142 |
2ccb279eb2c8b453ca0cb6ebfbf0eff5e416d2bd | 1,027 | package com.skyseraph.xknife.c13_3_2;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
import rx.Observable;
/**
* Created by SkySeraph on 2016/5/4.
*/
public interface IDataApi {
/**
* 获取热门电影
*
* @return hot movie
*/
@GET("movie/in_theaters")
Observable<DataModel> getHotMovie();
/**
* 获取豆瓣电影Top 100
*
* @param start the start
* @param count the count
* @return top movie
*/
@GET("movie/top100")
Observable<DataModel> getTopMovie(@Query("start") int start, @Query("count") int count);
/**
* 根据id获取电影信息
*
* @param id 路径参数:电影id
* @return movie detail
*/
@GET("movie/subject/{id}")
Observable<DataModel> getMovieDetail(@Path("id") String id);
/**
* 根据关键字搜索电影
*
* @param q 参数:关键字
* @return search movie
*/
@GET("movie/search")
Observable<DataModel> getSearchMovie(@Query("q") String q);
}
| 20.54 | 93 | 0.566699 |
29d74523b9795295e2d39951af54e10fe5c4d869 | 7,731 | // connect 4 game in java
import java.awt.*;
import java.awt.Image;
import java.awt.image.*;
import java.applet.*;
public class con4 extends Applet
{
// variables
private Rectangle dropMarker1,dropMarker2,dropMarker3,dropMarker4,dropMarker5,dropMarker6, dropMarker7, ywindet, rwindet;
private boolean myTurn;
private boolean ywins, rwins;
private boolean [] swp;
private int [] table;
// setup
public void init()
{
// init
ywins = rwins = false;
// init
swp = new boolean[8];
for (int i = 0; i < 7; i++)
swp[i] = false;
// init table
table = new int[50];
for (int xr = 0; xr < 7; xr++)
for (int yr = 0; yr < 6; yr++)
table[xr * 6 + yr] = 0;
// player first
myTurn = true;
// mouse event listeners
dropMarker1 = new Rectangle(0,0,100,100);
dropMarker2 = new Rectangle(100,0,100,100);
dropMarker3 = new Rectangle(200,0,100,100);
dropMarker4 = new Rectangle(300,0,100,100);
dropMarker5 = new Rectangle(400,0,100,100);
dropMarker6 = new Rectangle(500,0,100,100);
dropMarker7 = new Rectangle(600,0,100,100);
ywindet = new Rectangle(0,0,700,700);
rwindet = new Rectangle(0,0,700,700);
};
public int getPiece(int xcoord, int ycoord)
{
// get piece in specified coordinate
if ((xcoord < 0) || (ycoord < 0)) return -1;
if ((xcoord < 7) && (ycoord < 6))
return table[xcoord * 6 + ycoord];
else
return -1;
}
public void setPiece(int xcoord, int ycoord, int player)
{
// set piece in specified coordinate
if ((xcoord < 7) && (ycoord < 6))
table[xcoord * 6 + ycoord] = player;
}
public void checkWin(int xr, int yr)
{
// checks for the winner
int count = 0, pc = 0;
int [] querry = new int[9];
boolean [] dirblock = new boolean[9];
for (int i = 0; i < 9; i++)
dirblock[i] = false;
if ((xr > 7) && (yr > 6))
return;
if (getPiece(xr,yr) > 0)
{
pc = getPiece(xr,yr);
for (int con = 1; con <= 3; con++)
{
// check 3 layers
for (int dir = 0; dir < 8; dir ++)
{
// check if direction is not blocked
if (dirblock[dir]) continue;
// check all 8 directions
switch(dir)
{
case 0:
{
// check N
if ((yr + con) >= 6) break;
if (getPiece(xr,yr + con) != pc) dirblock[0] = true;
querry[0] += (getPiece(xr,yr + con) == pc)? 1:0;
break;
}
case 1:
{
// check NE
if (((xr + con) >= 7) || ((yr + con) >= 6)) break;
if (getPiece(xr + con,yr + con) != pc) dirblock[1] = true;
querry[1] += (getPiece(xr + con,yr + con) == pc)? 1:0;
break;
}
case 2:
{
// check E
if (((xr + con) >= 7)) break;
if (getPiece(xr + con,yr) != pc) dirblock[2] = true;
querry[2] += (getPiece(xr + con,yr) == pc)? 1:0;
break;
}
case 3:
{
// check SE
if (((xr + con) >= 7) || ((yr - con) < 0)) break;
if (getPiece(xr + con,yr - con) != pc) dirblock[3] = true;
querry[3] += (getPiece(xr + con,yr - con) == pc)? 1:0;
break;
}
case 4:
{
// check S
if (((yr - con) < 0)) break;
if (getPiece(xr,yr - con) != pc) dirblock[4] = true;
querry[4] += (getPiece(xr,yr - con) == pc)? 1:0;
break;
}
case 5:
{
// check SW
if (((xr - con) < 0) || ((yr - con) < 0)) break;
if (getPiece(xr - con,yr - con) != pc) dirblock[5] = true;
querry[5] += (getPiece(xr - con,yr - con) == pc)? 1:0;
break;
}
case 6:
{
// check W
if (((xr - con) < 0)) break;
if (getPiece(xr - con,yr) != pc) dirblock[6] = true;
querry[6] += (getPiece(xr - con,yr) == pc)? 1:0;
break;
}
case 7:
{
// check NW
if (((xr - con) < 0) || ((yr + con) >= 6)) break;
if (getPiece(xr - con,yr + con) != pc) dirblock[7] = true;
querry[7] += (getPiece(xr - con,yr + con) == pc)? 1:0;
break;
}
}
}
}
// recurse through tallies
int [] totalStat = new int[5];
totalStat[0] = querry[0] + querry[4];
totalStat[1] = querry[1] + querry[5];
totalStat[2] = querry[2] + querry[6];
totalStat[3] = querry[3] + querry[7];
for (int re = 0; re < 4; re++)
{
if (totalStat[re] >= 3)
{
// winner
if (pc == 1)
ywins = true;
else
rwins = true;
}
}
}
}
// draw things
public void paint(Graphics main)
{
BufferedImage buff = new BufferedImage(700,700, BufferedImage.TYPE_INT_RGB);
Graphics g = buff.getGraphics();
g.fillRect(0,0, 700,100);
// create drop markers
for (int i = 0; i < 7; i++)
{
if (myTurn)
g.setColor(Color.yellow); // set color
else
g.setColor(Color.red);
g.fillOval((100 * i) + 5, 0, 90,90);
g.setColor(Color.black); // set color
g.drawOval((100 * i) + 5,0, 90,90);
};
// create the table
for (int i = 0; i < 7; i++)
for (int j = 1; j <= 6; j++)
{
g.setColor(Color.blue);
g.fillRect((100 * i),(100 * j),100,100);
g.setColor(Color.black);
g.drawRect((100 * i),(100 * j),100,100);
g.setColor(Color.white);
g.fillOval((100 * i) + 5,(100 * j) + 5,90,90);
g.setColor(Color.black);
g.drawOval((100 * i) + 5,(100 * j) + 5,90,90);
}
// redraw pieces
for (int xr = 0; xr < 7; xr++)
for (int yr = 0; yr < 6; yr++)
if (getPiece(xr,yr) != 0)
drawPiece(g,xr,yr);
// draw new pieces
for (int x = 0; x < 7; x++)
{
if (swp[x] == true)
{
repaint();
dropPiece(g, x);
swp[x] = false;
}
}
// draw win frame
if (ywins)
{
// yellow wins
g.setColor(Color.yellow);
g.fillRect(0,0,700,700); // pseudo clear screen
g.setColor(Color.black);
g.setFont(new Font("Arial", Font.PLAIN, 40));
g.drawString("Yellow Wins!!!", 50,50);
} else if (rwins)
{
// red wins
g.setColor(Color.red);
g.fillRect(0,0,700,700); // pseudo clear screen
g.setColor(Color.black);
g.setFont(new Font("Arial", Font.PLAIN, 40));
g.drawString("Red Wins!!!", 50,50);
}
// draw everything
Image frame = (Image)buff;
main.drawImage(frame, 0,0, this);
};
public void resetGame()
{
// like what it says...
// reset who won
ywins = rwins = false;
// reset piece check
swp = new boolean[8];
for (int i = 0; i < 7; i++)
swp[i] = false;
// reset table
table = new int[50];
for (int xr = 0; xr < 7; xr++)
for (int yr = 0; yr < 6; yr++)
table[xr * 6 + yr] = 0;
// make yellow player first
myTurn = true;
}
public void drawPiece(Graphics g, int xcoord, int ycoord)
{
// draws piece
if (getPiece(xcoord, ycoord) == 1)
g.setColor(Color.yellow);
else
g.setColor(Color.red);
g.fillOval((100 * (xcoord)) + 5, (600 - (100 * ycoord)) + 5, 90,90);
g.setColor(Color.black);
g.drawOval((100 * (xcoord)) + 5, (600 - (100 * ycoord)) + 5, 90,90);
}
public void dropPiece(Graphics g, int xc)
{
// draws the piece and updates the logic
for (int i = 0; i < 6; i++)
{
if (getPiece(xc, i) == 0)
{
if (myTurn)
setPiece(xc,i,1);
else
setPiece(xc,i,2);
drawPiece(g, xc, i);
checkWin(xc,i);
break;
}
}
if (myTurn)
myTurn = false;
else
myTurn = true;
}
public boolean mouseDown(Event e, int x, int y)
{
if (dropMarker1.inside(x,y))
swp[0] = true;
if (dropMarker2.inside(x,y))
swp[1] = true;
if (dropMarker3.inside(x,y))
swp[2] = true;
if (dropMarker4.inside(x,y))
swp[3] = true;
if (dropMarker5.inside(x,y))
swp[4] = true;
if (dropMarker6.inside(x,y))
swp[5] = true;
if (dropMarker7.inside(x,y))
swp[6] = true;
if (ywins && ywindet.inside(x,y))
resetGame();
if (rwins && rwindet.inside(x,y))
resetGame();
repaint();
return true;
}
}; | 25.430921 | 122 | 0.536671 |
d120e698aa975436d4f936e980523a4e86f9c693 | 316 |
public class variable_length {
public static void main(String args[]){
System.out.println(average(2,43,6,33,56,32));
}
public static int average (int ...numbers){
int total=0;
for(int x : numbers){
total+=x;
}
return total/numbers.length;
}
}
| 11.703704 | 48 | 0.550633 |
1b9e525470b883e49505922634b1bdc27d178540 | 1,603 | package demosoft;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import javax.enterprise.context.ApplicationScoped;
import static org.apache.camel.builder.endpoint.StaticEndpointBuilders.amqp;
import static org.apache.camel.builder.endpoint.StaticEndpointBuilders.timer;
@ApplicationScoped
public class DemoRouteBuilder extends RouteBuilder {
@Override
public void configure() {
from(timer("demo").repeatCount(1))
.routeId("timer-dsl-route")
.setBody(simple("Message #${exchangeProperty.CamelTimerCounter}"))
.log("${body}")
.to("amqp:queue:{{queue.name}}")
.log("message sent to queue ${body}")
;
from(amqp("queue:{{queue.name}}").transacted(true).getUri())
.routeId("amqp-redelivery-route")
.to("log:info?showHeaders=true")
.choice()
.when(e -> Integer.parseInt(e.getIn().getHeader("JMSXDeliveryCount").toString()) < 2)
.throwException(new RuntimeException("nopes:" + System.nanoTime())).endChoice()
.otherwise()
.process(e -> {
final Long jmsTimestamp = e.getIn().getHeader("JMSTimestamp", Long.class);
final long processTimeInMillis = System.currentTimeMillis() - jmsTimestamp;
e.getIn().setHeader("processTime", processTimeInMillis);
})
.log(LoggingLevel.ERROR, "got from amqp: ${body}, took ${headers.processTime} ms")
;
}
}
| 39.097561 | 101 | 0.603244 |
8640e2adcfa4068d5acfb9e7107ddc2b8e47c1a9 | 1,008 | package T06objectsAndClasses.exercise.P03OpinionPollv2;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int lines = Integer.parseInt(scan.nextLine());
List<Person> peopleList = new ArrayList<>();
for (int i = 0; i < lines; i++) {
String[] personalInfo = scan.nextLine().split("\\s+");
String name = personalInfo[0];
int age = Integer.parseInt(personalInfo[1]);
Person person = new Person(name, age);
peopleList.add(person);
}
peopleList = peopleList.stream().filter(p -> p.getAge() > 30)
.collect(Collectors.toList());
peopleList.sort(Comparator.comparing(Person::getName));
for (Person person : peopleList) {
System.out.println(person);
}
}
}
| 34.758621 | 69 | 0.616071 |
ef6a08573dbdd8fc44e77af1ee846c9989efd6e2 | 756 | package com.skywin.cloudadmin.vsphere.task;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
import cn.com.skywin.cloudadmin.api.vsphere.info.template.UploadTemplateDto;
import cn.com.skywin.cloudadmin.commons.UUIDGenerator;
import cn.com.skywin.cloudadmin.vsphere.task.CreateImageTask;
/**
* @author zwj
* @date 2020/11/23
*/
public class CreateImageTaskTest extends BaseTaskTest {
@Test
public void testCreateImageTask() throws Exception {
CreateImageTask task = new CreateImageTask(
client,
UUIDGenerator.gen(), "test1", "linux", "datacenter-2",
"datastore-19", "D:/1.txt");
UploadTemplateDto dto = task.process();
System.out.println(JSON.toJSONString(dto));
}
}
| 27 | 76 | 0.699735 |
d6f012b5c20148438a9ff5724b0a744d46bac97d | 922 | package com.dennis.nio;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NioTest04 {
public static void main(String[] args) throws Exception {
FileOutputStream outputStream = new FileOutputStream("output.txt");
FileInputStream inputStream = new FileInputStream("input.txt");
FileChannel outChannel = outputStream.getChannel();
FileChannel inChannel = inputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(512);
while (true) {
byteBuffer.clear();
int read = inChannel.read(byteBuffer);
if (read == -1) {
break;
}
byteBuffer.flip();
outChannel.write(byteBuffer);
}
inChannel.close();
outChannel.close();
}
}
| 28.8125 | 76 | 0.60846 |
72e790f1b75b4169b4f8e004b64f888a6eb4c277 | 1,494 | package io.micronaut.docs.config.value;
import io.micronaut.context.ApplicationContext;
import io.micronaut.context.DefaultApplicationContext;
import io.micronaut.context.env.PropertySource;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.junit.Test;
import spock.lang.Specification;
import java.util.LinkedHashMap;
import static org.junit.Assert.assertEquals;
public class VehicleSpec {
@Test
public void testStartVehicleWithConfiguration() {
// tag::start[]
ApplicationContext applicationContext = new DefaultApplicationContext("test");
LinkedHashMap<String, Object> map = new LinkedHashMap(1);
map.put("my.engine.cylinders", "8");
applicationContext.getEnvironment().addPropertySource(PropertySource.of("test", map));
applicationContext.start();
Vehicle vehicle = applicationContext.getBean(Vehicle.class);
DefaultGroovyMethods.println(this, vehicle.start());
// end::start[]
assertEquals("Starting V8 Engine", vehicle.start());
}
@Test
public void testStartVehicleWithoutConfiguration() {
// tag::start[]
ApplicationContext applicationContext = new DefaultApplicationContext("test");
applicationContext.start();
Vehicle vehicle = applicationContext.getBean(Vehicle.class);
DefaultGroovyMethods.println(this, vehicle.start());
// end::start[]
assertEquals("Starting V6 Engine", vehicle.start());
}
}
| 32.478261 | 94 | 0.714859 |
9fb1f386236209f25c8a2e6a3f37e0e024ee2a4c | 820 | package com.muscleape.excel.test.listen;
import com.muscleape.excel.context.AnalysisContext;
import com.muscleape.excel.event.AnalysisEventListener;
import java.util.ArrayList;
import java.util.List;
public class ExcelListener extends AnalysisEventListener {
private List<Object> data = new ArrayList<Object>();
@Override
public void invoke(Object object, AnalysisContext context) {
System.out.println(context.getCurrentSheet());
data.add(object);
if(data.size()>=100){
doSomething();
data = new ArrayList<Object>();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
doSomething();
}
public void doSomething(){
for (Object o:data) {
System.out.println(o);
}
}
}
| 24.117647 | 64 | 0.653659 |
dec3f9708835f26805fe9068e3cdfbb474d93836 | 538 | package com.example;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "greeter")
public class GreeterConfigProperties {
private String message = "message";
private String name = "name";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 19.925926 | 75 | 0.663569 |
3becc8a1329cd80fba82647e39a1ad5d3d267c3c | 286 | package designpatterns;
class Singleton {
private static Singleton s = new Singleton();
private Singleton() {
}
public static Singleton createInstance() {
return s;
}
}
class Driver {
public static void main(String [] args){
Singleton s = Singleton.createInstance();
}
} | 15.052632 | 46 | 0.706294 |
0d48c56a51ec83e11f00ed4239bd952c4b370952 | 3,339 | package com.war3.nova.core.actuator.node.artificialapproval;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.war3.nova.Constants;
import com.war3.nova.NovaException;
import com.war3.nova.Result;
import com.war3.nova.annotation.NovaMapper;
import com.war3.nova.beans.NvInsApproval;
import com.war3.nova.beans.NvMulti;
import com.war3.nova.beans.NvNode;
import com.war3.nova.core.ProcessConfigContext;
import com.war3.nova.core.customized.ObjectActuator;
import com.war3.nova.core.enumeration.ApproverType;
import com.war3.nova.core.enumeration.ExecutionMode;
import com.war3.nova.core.enumeration.MultiRuleType;
import com.war3.nova.core.factory.RunnerFactory;
import com.war3.nova.core.service.util.Approvals;
import com.war3.nova.core.util.SpringContexts;
import com.war3.nova.core.util.Strings;
/**
* 会签审批提交
*
* @author Cytus_
* @since 2018年12月28日 下午3:17:16
* @version 1.0
*/
@NovaMapper(enumClass = ApproverType.class, enumValue = "MULTI", mapperName = Constants.ARTIFICIAL_APPROVAL_SUBMIT_SERVICE)
public class MultiJoinSignArtiAprvSubmitService implements ArtificialApprovalSubmitService {
private final static Logger logger = LoggerFactory.getLogger(MultiJoinSignArtiAprvSubmitService.class);
@Override
@SuppressWarnings("unchecked")
public ArtificialApprovalSubmitResult doSubmit(String processInstId, String nodeInstId) throws NovaException {
Result<?> runnerResult ;
NvNode nvNode = ProcessConfigContext.getContext().getCurrentNode();
NvMulti nvMulti = nvNode.getApproval().getMulit();
List<NvInsApproval> insApprovals = Approvals.getNodeAllApproval(nodeInstId);
MultiJoinSignParameter parameter = new MultiJoinSignParameter(
ProcessConfigContext.getContext().getProcess().getId(), processInstId, nvNode.getId(), nodeInstId, insApprovals);
if (MultiRuleType.compare(MultiRuleType.SYSTEM, nvMulti.getRuleType())) {
String beanName = SystemMultiRuleType.valueOf(nvMulti.getValue()).getValue();
CustomizedMultiJoinSignRule rule = SpringContexts.getBean(beanName, CustomizedMultiJoinSignRule.class);
logger.debug("节点实例[{}], 节点[{}]使用系统预定义会签规则执行开始", nodeInstId, nvNode.getId());
runnerResult = rule.execute(parameter);
} else {
logger.debug("节点实例[{}], 节点[{}]自定义会签规则执行开始", nodeInstId, nvNode.getId());
ObjectActuator<MultiJoinSignParameter, Result<?>> runner = (ObjectActuator<MultiJoinSignParameter, Result<?>>)
RunnerFactory.factory().getObjectActuator(ExecutionMode.get(nvMulti.getExecutionMode()));
runnerResult = runner.run(nvMulti.getValue(), parameter);
}
if (!runnerResult.isSuccess()) {
throw new NovaException(runnerResult.errorCode(), runnerResult.errorMessage());
} else {
boolean result = Boolean.valueOf(Strings.replaceNullByObj(runnerResult.getResult()));
logger.info("节点实例[{}], 节点[{}], 为审批提交,审批结果为:{}", nodeInstId, nvNode.getId(), result ? "拒绝" : "通过");
return result ? ArtificialApprovalSubmitResult.PASS : ArtificialApprovalSubmitResult.REFUSE;
}
}
}
| 45.739726 | 130 | 0.704103 |
1e195cdbe26cd961dbd62b735cdff7274ba60b3e | 8,135 | // Copyright (c) 2012 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.testshell;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import org.chromium.base.MemoryPressureListener;
import org.chromium.chrome.browser.DevToolsServer;
import org.chromium.chrome.testshell.sync.SyncController;
import org.chromium.content.browser.ActivityContentVideoViewClient;
import org.chromium.content.browser.BrowserStartupController;
import org.chromium.content.browser.ContentVideoViewClient;
import org.chromium.content.browser.ContentView;
import org.chromium.content.browser.ContentViewClient;
import org.chromium.content.browser.DeviceUtils;
import org.chromium.content.common.CommandLine;
import org.chromium.sync.signin.ChromeSigninController;
import org.chromium.ui.ActivityWindowAndroid;
import org.chromium.ui.WindowAndroid;
/**
* The {@link android.app.Activity} component of a basic test shell to test Chrome features.
*/
public class ChromiumTestShellActivity extends Activity implements MenuHandler {
private static final String TAG = "ChromiumTestShellActivity";
private WindowAndroid mWindow;
private TabManager mTabManager;
private DevToolsServer mDevToolsServer;
private SyncController mSyncController;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ChromiumTestShellApplication.initCommandLine();
waitForDebuggerIfNeeded();
DeviceUtils.addDeviceSpecificUserAgentSwitch(this);
BrowserStartupController.StartupCallback callback =
new BrowserStartupController.StartupCallback() {
@Override
public void onSuccess(boolean alreadyStarted) {
finishInitialization(savedInstanceState);
}
@Override
public void onFailure() {
Toast.makeText(ChromiumTestShellActivity.this,
R.string.browser_process_initialization_failed,
Toast.LENGTH_SHORT).show();
Log.e(TAG, "Chromium browser process initialization failed");
finish();
}
};
BrowserStartupController.get(this).startBrowserProcessesAsync(callback);
}
private void finishInitialization(final Bundle savedInstanceState) {
setContentView(R.layout.testshell_activity);
mTabManager = (TabManager) findViewById(R.id.tab_manager);
String startupUrl = getUrlFromIntent(getIntent());
if (!TextUtils.isEmpty(startupUrl)) {
mTabManager.setStartupUrl(startupUrl);
}
TestShellToolbar mToolbar = (TestShellToolbar) findViewById(R.id.toolbar);
mToolbar.setMenuHandler(this);
mWindow = new ActivityWindowAndroid(this);
mWindow.restoreInstanceState(savedInstanceState);
mTabManager.setWindow(mWindow);
mDevToolsServer = new DevToolsServer("chromium_testshell");
mDevToolsServer.setRemoteDebuggingEnabled(true);
mSyncController = SyncController.get(this);
// In case this method is called after the first onStart(), we need to inform the
// SyncController that we have started.
mSyncController.onStart();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mDevToolsServer != null)
mDevToolsServer.destroy();
mDevToolsServer = null;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO(dtrainor): Save/restore the tab state.
mWindow.saveInstanceState(outState);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
TestShellTab tab = getActiveTab();
if (tab != null && tab.getContentView().canGoBack()) {
tab.getContentView().goBack();
return true;
}
}
return super.onKeyUp(keyCode, event);
}
@Override
protected void onNewIntent(Intent intent) {
if (MemoryPressureListener.handleDebugIntent(this, intent.getAction())) return;
String url = getUrlFromIntent(intent);
if (!TextUtils.isEmpty(url)) {
TestShellTab tab = getActiveTab();
if (tab != null) tab.loadUrlWithSanitization(url);
}
}
@Override
protected void onStop() {
super.onStop();
ContentView view = getActiveContentView();
if (view != null) view.onHide();
}
@Override
protected void onStart() {
super.onStart();
ContentView view = getActiveContentView();
if (view != null) view.onShow();
if (mSyncController != null) {
mSyncController.onStart();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
mWindow.onActivityResult(requestCode, resultCode, data);
}
/**
* @return The {@link TestShellTab} that is currently visible.
*/
public TestShellTab getActiveTab() {
return mTabManager != null ? mTabManager.getCurrentTab() : null;
}
/**
* @return The ContentView of the active tab.
*/
public ContentView getActiveContentView() {
TestShellTab tab = getActiveTab();
return tab != null ? tab.getContentView() : null;
}
/**
* Creates a {@link TestShellTab} with a URL specified by {@code url}.
*
* @param url The URL the new {@link TestShellTab} should start with.
*/
public void createTab(String url) {
mTabManager.createTab(url);
getActiveContentView().setContentViewClient(new ContentViewClient() {
@Override
public ContentVideoViewClient getContentVideoViewClient() {
return new ActivityContentVideoViewClient(ChromiumTestShellActivity.this);
}
});
}
/**
* From {@link MenuHandler}.
*/
@Override
public void showPopupMenu() {
openOptionsMenu();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.signin:
if (ChromeSigninController.get(this).isSignedIn())
SyncController.openSignOutDialog(getFragmentManager());
else
SyncController.openSigninDialog(getFragmentManager());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.setGroupVisible(R.id.MAIN_MENU, true);
MenuItem signinItem = menu.findItem(R.id.signin);
if (ChromeSigninController.get(this).isSignedIn())
signinItem.setTitle(ChromeSigninController.get(this).getSignedInAccountName());
else
signinItem.setTitle(R.string.signin_sign_in);
return true;
}
private void waitForDebuggerIfNeeded() {
if (CommandLine.getInstance().hasSwitch(CommandLine.WAIT_FOR_JAVA_DEBUGGER)) {
Log.e(TAG, "Waiting for Java debugger to connect...");
android.os.Debug.waitForDebugger();
Log.e(TAG, "Java debugger connected. Resuming execution.");
}
}
private static String getUrlFromIntent(Intent intent) {
return intent != null ? intent.getDataString() : null;
}
}
| 34.037657 | 92 | 0.651998 |
f7da4d1ccd54b4a19d58a2292a13e0c721734a5e | 4,972 | package android.net;
import android.annotation.Nullable;
import android.content.ComponentName;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Objects;
/**
* Holds metadata about a discovered network scorer/recommendation application.
*
* TODO: delete this class once robolectric supports Android O
*/
public final class NetworkScorerAppData implements Parcelable {
/** UID of the scorer app. */
public final int packageUid;
private final ComponentName mRecommendationService;
/** User visible label in Settings for the recommendation service. */
private final String mRecommendationServiceLabel;
/**
* The {@link ComponentName} of the Activity to start before enabling the "connect to open
* wifi networks automatically" feature.
*/
private final ComponentName mEnableUseOpenWifiActivity;
/**
* The {@link android.app.NotificationChannel} ID used by {@link #mRecommendationService} to
* post open network notifications.
*/
private final String mNetworkAvailableNotificationChannelId;
public NetworkScorerAppData(int packageUid, ComponentName recommendationServiceComp,
String recommendationServiceLabel, ComponentName enableUseOpenWifiActivity,
String networkAvailableNotificationChannelId) {
this.packageUid = packageUid;
this.mRecommendationService = recommendationServiceComp;
this.mRecommendationServiceLabel = recommendationServiceLabel;
this.mEnableUseOpenWifiActivity = enableUseOpenWifiActivity;
this.mNetworkAvailableNotificationChannelId = networkAvailableNotificationChannelId;
}
protected NetworkScorerAppData(Parcel in) {
packageUid = in.readInt();
mRecommendationService = ComponentName.readFromParcel(in);
mRecommendationServiceLabel = in.readString();
mEnableUseOpenWifiActivity = ComponentName.readFromParcel(in);
mNetworkAvailableNotificationChannelId = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(packageUid);
ComponentName.writeToParcel(mRecommendationService, dest);
dest.writeString(mRecommendationServiceLabel);
ComponentName.writeToParcel(mEnableUseOpenWifiActivity, dest);
dest.writeString(mNetworkAvailableNotificationChannelId);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<NetworkScorerAppData> CREATOR =
new Creator<NetworkScorerAppData>() {
@Override
public NetworkScorerAppData createFromParcel(Parcel in) {
return new NetworkScorerAppData(in);
}
@Override
public NetworkScorerAppData[] newArray(int size) {
return new NetworkScorerAppData[size];
}
};
public String getRecommendationServicePackageName() {
return mRecommendationService.getPackageName();
}
public ComponentName getRecommendationServiceComponent() {
return mRecommendationService;
}
@Nullable
public ComponentName getEnableUseOpenWifiActivity() {
return mEnableUseOpenWifiActivity;
}
@Nullable
public String getRecommendationServiceLabel() {
return mRecommendationServiceLabel;
}
@Nullable
public String getNetworkAvailableNotificationChannelId() {
return mNetworkAvailableNotificationChannelId;
}
@Override
public String toString() {
return "NetworkScorerAppData{" +
"packageUid=" + packageUid +
", mRecommendationService=" + mRecommendationService +
", mRecommendationServiceLabel=" + mRecommendationServiceLabel +
", mEnableUseOpenWifiActivity=" + mEnableUseOpenWifiActivity +
", mNetworkAvailableNotificationChannelId=" +
mNetworkAvailableNotificationChannelId +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NetworkScorerAppData that = (NetworkScorerAppData) o;
return packageUid == that.packageUid &&
Objects.equals(mRecommendationService, that.mRecommendationService) &&
Objects.equals(mRecommendationServiceLabel, that.mRecommendationServiceLabel) &&
Objects.equals(mEnableUseOpenWifiActivity, that.mEnableUseOpenWifiActivity) &&
Objects.equals(mNetworkAvailableNotificationChannelId,
that.mNetworkAvailableNotificationChannelId);
}
@Override
public int hashCode() {
return Objects.hash(packageUid, mRecommendationService, mRecommendationServiceLabel,
mEnableUseOpenWifiActivity, mNetworkAvailableNotificationChannelId);
}
}
| 37.954198 | 96 | 0.694087 |
55b31e0774585f230ec89a8e03bfc3739ed0ef76 | 481 | package com.epicodus.kloutulator.models;
/**
* Created by Guest on 5/10/16.
*/
public class Influencer {
String name;
String score;
public Influencer(String name) {
this.name = name;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 16.033333 | 40 | 0.577963 |
7571c626c22b195645a19403d486b97c6f4c8317 | 110 | /**
* Filters to select classes and methods for runtime suites.
*/
package com.dhemery.runtimesuite.filters; | 27.5 | 60 | 0.763636 |
271e58d83e8ae7ef006a894c86bbac59446ded6e | 2,242 | package com.javarush.task.task18.task1808;
/*
Разделение файла
*/
import java.io.*;
public class Solution {
public static void main(String[] args) throws IOException {
// C:\Users\Dimka\Documents\JavaRushHomeWork\JavaRushHomeWork_2_0\JavaRushTasks\2.JavaCore\src\com\javarush\task\task18\task1801\File1.txt
// C:\Users\Dimka\Documents\JavaRushHomeWork\JavaRushHomeWork_2_0\JavaRushTasks\2.JavaCore\src\com\javarush\task\task18\task1801\File2.txt
// C:\Users\Dimka\Documents\JavaRushHomeWork\JavaRushHomeWork_2_0\JavaRushTasks\2.JavaCore\src\com\javarush\task\task18\task1801\File3.txt
FileInputStream file1InputStream = new FileInputStream(new BufferedReader(new InputStreamReader(System.in)).readLine());// C:\Users\Dimka\Documents\JavaRushHomeWork\JavaRushHomeWork_2_0\JavaRushTasks\2.JavaCore\src\com\javarush\task\task18\task1801\File1.txt
FileOutputStream file2InputStream = new FileOutputStream(new BufferedReader(new InputStreamReader(System.in)).readLine());
FileOutputStream file3InputStream = new FileOutputStream(new BufferedReader(new InputStreamReader(System.in)).readLine());
int size = file1InputStream.available();
int i=0;
if(size%2==1)
{
while(file1InputStream.available()>0)
{
if(i<((size/2)+1))
{
file2InputStream.write(file1InputStream.read());
i++;
}else
{
file3InputStream.write(file1InputStream.read());
i++;
}
}
}else
{
while(file1InputStream.available()>0)
{
if(i<(size/2))
{
file2InputStream.write(file1InputStream.read());
i++;
}else
{
file3InputStream.write(file1InputStream.read());
i++;
}
}
}
//закрыли потоки
file1InputStream.close();
file2InputStream.close();
file3InputStream.close();
}
}
| 39.333333 | 267 | 0.575825 |
5649302af86d100f517e4a158ac561a92e054e7c | 6,872 | /*
*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development and Distribution
* License, Version 1.0 only (the "License"). You may not use this file except in compliance with
* the License.
*
* You can obtain a copy of the license at license/ESCIDOC.LICENSE or
* http://www.escidoc.org/license. See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and include the License
* file at license/ESCIDOC.LICENSE. If applicable, add the following below this CDDL HEADER, with
* the fields enclosed by brackets "[]" replaced with your own identifying information: Portions
* Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2006-2012 Fachinformationszentrum Karlsruhe Gesellschaft für
* wissenschaftlich-technische Information mbH and Max-Planck- Gesellschaft zur Förderung der
* Wissenschaft e.V. All rights reserved. Use is subject to license terms.
*/
package de.mpg.mpdl.inge.model.valueobjects.metadata;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import de.mpg.mpdl.inge.model.valueobjects.IgnoreForCleanup;
import de.mpg.mpdl.inge.model.valueobjects.ValueObject;
/**
* @revised by MuJ: 29.08.2007
* @version $Revision$ $LastChangedDate$ by $Author$
* @updated 22-Okt-2007 15:26:37
*/
@JsonInclude(value = Include.NON_EMPTY)
public class EventVO extends ValueObject implements Cloneable {
/**
* Fixed serialVersionUID to prevent java.io.InvalidClassExceptions like
* 'de.mpg.mpdl.inge.model.valueobjects.ItemVO; local class incompatible: stream classdesc
* serialVersionUID = 8587635524303981401, local class serialVersionUID = -2285753348501257286'
* that occur after JiBX enhancement of VOs. Without the fixed serialVersionUID, the VOs have to
* be compiled twice for testing (once for the Application Server, once for the local test).
*
* @author Johannes Mueller
*/
private static final long serialVersionUID = 1L;
/**
* The possible invitation status of the event.
*
* @updated 22-Okt-2007 15:26:37
*/
public enum InvitationStatus
{
INVITED
}
private java.util.List<AlternativeTitleVO> alternativeTitles = new java.util.ArrayList<AlternativeTitleVO>();
private String endDate;
@IgnoreForCleanup
private InvitationStatus invitationStatus;
private String place;
private String startDate;
private String title;
/**
* Get the alternativeTitles. The event may have one or several alternative forms of the title
* (e.g. an abbreviated title).
*/
public java.util.List<AlternativeTitleVO> getAlternativeTitles() {
return alternativeTitles;
}
/**
* Delivers the end date of the event.
*/
public String getEndDate() {
return endDate;
}
/**
* Delivers the invitations status of the event. The invitation status is the information whether
* the creator was explicitly invited.
*/
public InvitationStatus getInvitationStatus() {
return invitationStatus;
}
/**
* Delivers the place of the event.
*/
public String getPlace() {
return place;
}
/**
* Delivers the start date of the event.
*/
public String getStartDate() {
return startDate;
}
/**
* Delivers the title of the event.
*/
public String getTitle() {
return title;
}
/**
* Sets the invitations status of the event. The invitation status is the information whether the
* creator was explicitly invited.
*
* @param newVal
*/
public void setInvitationStatus(InvitationStatus newVal) {
invitationStatus = newVal;
}
/**
* Sets the place of the event.
*
* @param newVal newVal
*/
public void setPlace(String newVal) {
place = newVal;
}
/**
* Sets the title of the event.
*
* @param newVal newVal
*/
public void setTitle(String newVal) {
title = newVal;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#clone()
*/
@Override
public Object clone() {
EventVO clone = new EventVO();
if (getTitle() != null) {
clone.setTitle(getTitle());
}
for (AlternativeTitleVO altTitle : getAlternativeTitles()) {
clone.getAlternativeTitles().add((AlternativeTitleVO) altTitle.clone());
}
if (getEndDate() != null) {
clone.setEndDate(getEndDate());
}
if (getStartDate() != null) {
clone.setStartDate(getStartDate());
}
clone.setInvitationStatus(getInvitationStatus());
if (getPlace() != null) {
clone.setPlace(getPlace());
}
return clone;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((alternativeTitles == null) ? 0 : alternativeTitles.hashCode());
result = prime * result + ((endDate == null) ? 0 : endDate.hashCode());
result = prime * result + ((invitationStatus == null) ? 0 : invitationStatus.hashCode());
result = prime * result + ((place == null) ? 0 : place.hashCode());
result = prime * result + ((startDate == null) ? 0 : startDate.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EventVO other = (EventVO) obj;
if (alternativeTitles == null) {
if (other.alternativeTitles != null)
return false;
} else if (other.alternativeTitles == null)
return false;
else if (!alternativeTitles.containsAll(other.alternativeTitles) //
|| !other.alternativeTitles.containsAll(alternativeTitles)) {
return false;
}
if (endDate == null) {
if (other.endDate != null)
return false;
} else if (!endDate.equals(other.endDate))
return false;
if (invitationStatus != other.invitationStatus)
return false;
if (place == null) {
if (other.place != null)
return false;
} else if (!place.equals(other.place))
return false;
if (startDate == null) {
if (other.startDate != null)
return false;
} else if (!startDate.equals(other.startDate))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
/**
* Sets the end date of the event.
*
* @param newVal
*/
public void setEndDate(String newVal) {
endDate = newVal;
}
/**
* Sets the start date of the event.
*
* @param newVal
*/
public void setStartDate(String newVal) {
startDate = newVal;
}
}
| 26.84375 | 111 | 0.665454 |
e1ea8772e050bb6cdbb3392921f82f9e9ebad85c | 554 | package org.quickclient.classes;
/**
*
* @author Administrator
*/
public class QListItem {
private String rObjectId;
private String name;
public String getRObjectId() {
return rObjectId;
}
public void setRObjectId(String rObjectId) {
this.rObjectId = rObjectId;
}
public String getName() {
return name;
}
public void setName(String Name) {
this.name = Name;
}
@Override
public String toString() {
return name;
}
} | 17.3125 | 49 | 0.559567 |
631376f662a226af589241a17203f95aa0b21a4b | 4,677 | package br.com.zup.polyana.propostas.proposta;
import br.com.zup.polyana.propostas.proposta.criptografia.CriptografaDocumento;
import br.com.zup.polyana.propostas.validation.ApiErrorException;
import feign.FeignException;
import io.opentracing.Span;
import io.opentracing.Tracer;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import javax.transaction.Transactional;
import javax.validation.Valid;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
@RestController
public class PropostaController {
private PropostaRepository propostaRepository;
private SolicitacaoAnaliseClient encaminhaSolicitacaoAnalise;
private final Tracer tracer;
public PropostaController(PropostaRepository propostaRepository, SolicitacaoAnaliseClient encaminhaSolicitacaoAnalise,
Tracer tracer) {
this.propostaRepository = propostaRepository;
this.encaminhaSolicitacaoAnalise = encaminhaSolicitacaoAnalise;
this.tracer = tracer;
}
@RequestMapping(method = RequestMethod.POST, value = "/api/proposta")
@Transactional
public ResponseEntity<?> cadastrar(@RequestBody @Valid PropostaRequest propostaRequest,
UriComponentsBuilder uriBuilder){
Span activeSpan = tracer.activeSpan();
activeSpan.setTag("user.email",propostaRequest.getEmail());
//activeSpan.setBaggageItem("user.email", propostaRequest.getEmail());
//activeSpan.log("Meu log");
Optional<Proposta> optionalProposta = propostaRepository.findByDocumento(propostaRequest.getDocumento());
if(documentoExiste(propostaRequest.getDocumento())){
throw new ApiErrorException(HttpStatus.UNPROCESSABLE_ENTITY, "Permitida somente uma proposta por pessoa." );
}
//começa como não elegível antes da verificação
Proposta proposta = propostaRequest.converter(EstadoProposta.NÃO_ELEGÍVEL);
//salva antes da análise
propostaRepository.save(proposta);
URI uri = uriBuilder.path("/api/proposta/{idProposta}").buildAndExpand(proposta.getIdProposta()).toUri();
try {
//tenta atualizar o estado se não houver restrição após análise
proposta.atualizaEstado(proposta.executaAnalise(encaminhaSolicitacaoAnalise)
.getResultadoSolicitacao(),
propostaRepository);
}catch (FeignException.UnprocessableEntity e) {
//status 422 se houver restrição
proposta.atualizaEstado(
RestricaoAnalise.COM_RESTRICAO,
propostaRepository);
throw new ApiErrorException(HttpStatus.UNPROCESSABLE_ENTITY, "Proposta restrita: " + uri);
}
//retorna 201 com uri caso estiver elegível
return ResponseEntity
.created(uri)
.body(uri);
}
@Transactional
@RequestMapping(method = RequestMethod.GET, value = "/api/proposta/{id}")
public ResponseEntity<?> consultar(@PathVariable String id) {
Optional<Proposta> propostaObject = propostaRepository.findByIdProposta(id);
if(propostaObject.isPresent()) {
Proposta proposta = propostaObject.get();
return ResponseEntity.ok(new PropostaResponse(proposta));
}
return ResponseEntity
.notFound()
.build();
}
@RequestMapping(method = RequestMethod.DELETE, value = "/api/proposta/{id}")
@Transactional
public ResponseEntity<?> remover(@PathVariable String id) {
Optional<Proposta> proposta = propostaRepository.findByIdProposta(id);
if(proposta.isPresent()) {
propostaRepository.deleteByIdProposta(id);
return ResponseEntity
.ok()
.build();
}
return ResponseEntity
.notFound()
.build();
}
private Boolean documentoExiste(String documento){
List<Proposta> propostas = propostaRepository.findAll();
AtomicReference<Boolean> existe = new AtomicReference<>(false);
propostas.forEach(proposta->{
String documentoLimpo = CriptografaDocumento.decode(proposta.getDocumento());
if(documentoLimpo.equals(documento)){
existe.set(true);
}else{
existe.set(false);
}
});
return existe.get();
}
} | 37.416 | 122 | 0.670301 |
31825a2771cc894c09ca637042bf1bc7530c3441 | 678 | package edu.virginia.psyc.kaiser.persistence;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.mindtrails.domain.questionnaire.LinkedQuestionnaireData;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
@Table(name="AssessingProgram")
@EqualsAndHashCode(callSuper = true)
@Data
public class AssessingProgram extends LinkedQuestionnaireData {
@NotNull
@Size(min=1)
String worthPerWeek;
@NotNull
@Size(min=1)
@Lob /// Allow them to enter more than 255 characters!
String compareToOthers;
}
| 22.6 | 67 | 0.783186 |
174deec7e11a0631935f42517bb5677bdadf8955 | 161 | package acmtree;
public class Enrichment {
// ENRICHMENT
public static final boolean Enable = true;
public static final boolean Disable = false;
}
| 17.888889 | 46 | 0.714286 |
491a23143d4abde38872ca1532b76f084d1a1c37 | 8,176 | /*
* Copyright (c) 2011-2013, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.factory.feature.detect.line;
import boofcv.abst.feature.detect.line.DetectLineHoughFoot;
import boofcv.abst.feature.detect.line.DetectLineHoughFootSubimage;
import boofcv.abst.feature.detect.line.DetectLineHoughPolar;
import boofcv.abst.feature.detect.line.DetectLineSegmentsGridRansac;
import boofcv.abst.filter.derivative.ImageGradient;
import boofcv.alg.feature.detect.line.ConnectLinesGrid;
import boofcv.alg.feature.detect.line.GridRansacLineDetector;
import boofcv.alg.feature.detect.line.gridline.*;
import boofcv.factory.filter.derivative.FactoryDerivative;
import boofcv.struct.image.ImageFloat32;
import boofcv.struct.image.ImageSInt16;
import boofcv.struct.image.ImageSingleBand;
import georegression.struct.line.LinePolar2D_F32;
import org.ddogleg.fitting.modelset.ModelMatcher;
import org.ddogleg.fitting.modelset.ransac.Ransac;
/**
* Factory for creating line and line segment detectors.
*
* @author Peter Abeles
*/
public class FactoryDetectLineAlgs {
/**
* Detects line segments inside an image using the {@link DetectLineSegmentsGridRansac} algorithm.
*
* @see DetectLineSegmentsGridRansac
*
* @param regionSize Size of the region considered. Try 40 and tune.
* @param thresholdEdge Threshold for determining which pixels belong to an edge or not. Try 30 and tune.
* @param thresholdAngle Tolerance in angle for allowing two edgels to be paired up, in radians. Try 2.36
* @param connectLines Should lines be connected and optimized.
* @param imageType Type of single band input image.
* @param derivType Image derivative type.
* @return Line segment detector
*/
public static <I extends ImageSingleBand, D extends ImageSingleBand>
DetectLineSegmentsGridRansac<I,D> lineRansac(int regionSize ,
double thresholdEdge ,
double thresholdAngle ,
boolean connectLines,
Class<I> imageType ,
Class<D> derivType ) {
ImageGradient<I,D> gradient = FactoryDerivative.sobel(imageType,derivType);
GridLineModelDistance distance = new GridLineModelDistance((float)thresholdAngle);
GridLineModelFitter fitter = new GridLineModelFitter((float)thresholdAngle);
ModelMatcher<LinePolar2D_F32, Edgel> matcher =
new Ransac<LinePolar2D_F32,Edgel>(123123,fitter,distance,25,1);
GridRansacLineDetector<D> alg;
if( derivType == ImageFloat32.class ) {
alg = (GridRansacLineDetector)new ImplGridRansacLineDetector_F32(regionSize,10,matcher);
} else if( derivType == ImageSInt16.class ) {
alg = (GridRansacLineDetector)new ImplGridRansacLineDetector_S16(regionSize,10,matcher);
} else {
throw new IllegalArgumentException("Unsupported derivative type");
}
ConnectLinesGrid connect = null;
if( connectLines )
connect = new ConnectLinesGrid(Math.PI*0.01,1,8);
return new DetectLineSegmentsGridRansac<I,D>(alg,connect,gradient,thresholdEdge,imageType,derivType);
}
/**
* Detects lines using the foot of norm parametrization, see {@link DetectLineHoughFoot}. The polar
* parametrization is more common, but more difficult to tune.
*
* @see DetectLineHoughFoot
*
* @param localMaxRadius Lines in transform space must be a local max in a region with this radius. Try 5;
* @param minCounts Minimum number of counts/votes inside the transformed image. Try 5.
* @param minDistanceFromOrigin Lines which are this close to the origin of the transformed image are ignored. Try 5.
* @param thresholdEdge Threshold for classifying pixels as edge or not. Try 30.
* @param maxLines Maximum number of lines to return. If <= 0 it will return them all.
* @param imageType Type of single band input image.
* @param derivType Image derivative type.
* @param <I> Input image type.
* @param <D> Image derivative type.
* @return Line detector.
*/
public static <I extends ImageSingleBand, D extends ImageSingleBand>
DetectLineHoughFoot<I,D> houghFoot(int localMaxRadius,
int minCounts ,
int minDistanceFromOrigin ,
float thresholdEdge ,
int maxLines ,
Class<I> imageType ,
Class<D> derivType ) {
ImageGradient<I,D> gradient = FactoryDerivative.sobel(imageType,derivType);
return new DetectLineHoughFoot<I,D>(localMaxRadius,minCounts,minDistanceFromOrigin,thresholdEdge,maxLines,gradient);
}
/**
* Detects lines using a foot of norm parametrization and sub images to reduce degenerate
* configurations, see {@link DetectLineHoughFootSubimage} for details.
*
* @see DetectLineHoughFootSubimage
*
* @param localMaxRadius Lines in transform space must be a local max in a region with this radius. Try 5;
* @param minCounts Minimum number of counts/votes inside the transformed image. Try 5.
* @param minDistanceFromOrigin Lines which are this close to the origin of the transformed image are ignored. Try 5.
* @param thresholdEdge Threshold for classifying pixels as edge or not. Try 30.
* @param maxLines Maximum number of lines to return. If <= 0 it will return them all.
* @param totalHorizontalDivisions Number of sub-images in horizontal direction Try 2
* @param totalVerticalDivisions Number of sub images in vertical direction. Try 2
* @param imageType Type of single band input image.
* @param derivType Image derivative type.
* @param <I> Input image type.
* @param <D> Image derivative type.
* @return Line detector.
*/
public static <I extends ImageSingleBand, D extends ImageSingleBand>
DetectLineHoughFootSubimage<I,D> houghFootSub(int localMaxRadius,
int minCounts ,
int minDistanceFromOrigin ,
float thresholdEdge ,
int maxLines ,
int totalHorizontalDivisions ,
int totalVerticalDivisions ,
Class<I> imageType ,
Class<D> derivType ) {
ImageGradient<I,D> gradient = FactoryDerivative.sobel(imageType,derivType);
return new DetectLineHoughFootSubimage<I,D>(localMaxRadius,
minCounts,minDistanceFromOrigin,thresholdEdge,
totalHorizontalDivisions,totalVerticalDivisions,maxLines,gradient);
}
/**
* Creates a Hough line detector based on polar parametrization.
*
* @see DetectLineHoughPolar
*
* @param localMaxRadius Radius for local maximum suppression. Try 2.
* @param minCounts Minimum number of counts for detected line. Critical tuning parameter and image dependent.
* @param resolutionRange Resolution of line range in pixels. Try 2
* @param resolutionAngle Resolution of line angle in radius. Try PI/180
* @param thresholdEdge Edge detection threshold. Try 50.
* @param maxLines Maximum number of lines to return. If <= 0 it will return them all.
* @param imageType Type of single band input image.
* @param derivType Image derivative type.
* @param <I> Input image type.
* @param <D> Image derivative type.
* @return Line detector.
*/
public static <I extends ImageSingleBand, D extends ImageSingleBand>
DetectLineHoughPolar<I,D> houghPolar(int localMaxRadius,
int minCounts,
double resolutionRange ,
double resolutionAngle ,
float thresholdEdge,
int maxLines ,
Class<I> imageType ,
Class<D> derivType ) {
ImageGradient<I,D> gradient = FactoryDerivative.sobel(imageType,derivType);
return new DetectLineHoughPolar<I,D>(localMaxRadius,minCounts,resolutionRange,resolutionAngle,thresholdEdge,maxLines,gradient);
}
}
| 42.583333 | 129 | 0.739604 |
c04ef1307deb4d9172e47ea1a86840cee5ad4f06 | 266 | package com.solitardj9.apiService.utils;
import org.apache.commons.lang3.StringUtils;
public class RouteFilterStringUtils {
public static Boolean isNullOrEmpty(String str) {
return StringUtils.isEmpty(str) || StringUtils.isBlank(str);
}
} | 26.6 | 69 | 0.733083 |
e839c3d34d25444e13356d6ffc5c10a0dd3a9a65 | 3,212 | /*
* Voicebase V3 API
* APIs for speech recognition and speech analytics, powering insights every business needs.
*
* OpenAPI spec version: 3.0.1
* Contact: support@voicebase.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.voicebase.sample.v3client.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.ArrayList;
import com.voicebase.sample.v3client.model.VbOccurrence;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* VbDetectedSegment
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-10-12T18:19:19.705-07:00")
public class VbDetectedSegment {
@JsonProperty("speakerName")
private String speakerName = null;
@JsonProperty("occurrences")
private java.util.List<VbOccurrence> occurrences = new java.util.ArrayList<VbOccurrence>();
public VbDetectedSegment speakerName(String speakerName) {
this.speakerName = speakerName;
return this;
}
/**
* Get speakerName
* @return speakerName
**/
@ApiModelProperty(example = "null", value = "")
public String getSpeakerName() {
return speakerName;
}
public void setSpeakerName(String speakerName) {
this.speakerName = speakerName;
}
public VbDetectedSegment occurrences(java.util.List<VbOccurrence> occurrences) {
this.occurrences = occurrences;
return this;
}
public VbDetectedSegment addOccurrencesItem(VbOccurrence occurrencesItem) {
this.occurrences.add(occurrencesItem);
return this;
}
/**
* Get occurrences
* @return occurrences
**/
@ApiModelProperty(example = "null", value = "")
public java.util.List<VbOccurrence> getOccurrences() {
return occurrences;
}
public void setOccurrences(java.util.List<VbOccurrence> occurrences) {
this.occurrences = occurrences;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
VbDetectedSegment vbDetectedSegment = (VbDetectedSegment) o;
return Objects.equals(this.speakerName, vbDetectedSegment.speakerName) &&
Objects.equals(this.occurrences, vbDetectedSegment.occurrences);
}
@Override
public int hashCode() {
return Objects.hash(speakerName, occurrences);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class VbDetectedSegment {\n");
sb.append(" speakerName: ").append(toIndentedString(speakerName)).append("\n");
sb.append(" occurrences: ").append(toIndentedString(occurrences)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 26.766667 | 125 | 0.7033 |
7fc3645b66addd4797a8f9f1fa0533565b92512f | 8,750 | /*
* Copyright (c) 2018, Lotto <https://github.com/devLotto>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.puzzlesolver;
import com.google.inject.Provides;
import java.awt.Color;
import java.util.Arrays;
import javax.inject.Inject;
import javax.inject.Singleton;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.api.events.GameTick;
import net.runelite.api.events.MenuOptionClicked;
import net.runelite.api.events.WidgetLoaded;
import net.runelite.api.util.Text;
import net.runelite.api.widgets.Widget;
import net.runelite.api.widgets.WidgetID;
import net.runelite.api.widgets.WidgetInfo;
import static net.runelite.api.widgets.WidgetInfo.LIGHT_BOX_BUTTON_A;
import static net.runelite.api.widgets.WidgetInfo.LIGHT_BOX_BUTTON_B;
import static net.runelite.api.widgets.WidgetInfo.LIGHT_BOX_BUTTON_C;
import static net.runelite.api.widgets.WidgetInfo.LIGHT_BOX_BUTTON_D;
import static net.runelite.api.widgets.WidgetInfo.LIGHT_BOX_BUTTON_E;
import static net.runelite.api.widgets.WidgetInfo.LIGHT_BOX_BUTTON_F;
import static net.runelite.api.widgets.WidgetInfo.LIGHT_BOX_BUTTON_G;
import static net.runelite.api.widgets.WidgetInfo.LIGHT_BOX_BUTTON_H;
import static net.runelite.api.widgets.WidgetInfo.TO_GROUP;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.events.ConfigChanged;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.plugins.PluginType;
import net.runelite.client.plugins.puzzlesolver.lightbox.Combination;
import net.runelite.client.plugins.puzzlesolver.lightbox.LightBox;
import net.runelite.client.plugins.puzzlesolver.lightbox.LightboxSolution;
import net.runelite.client.plugins.puzzlesolver.lightbox.LightboxSolver;
import net.runelite.client.plugins.puzzlesolver.lightbox.LightboxState;
import net.runelite.client.ui.overlay.OverlayManager;
import net.runelite.client.util.ColorUtil;
@PluginDescriptor(
name = "Puzzle Solver",
description = "Show you where to click to solve puzzle boxes",
tags = {"clues", "scrolls", "overlay"},
type = PluginType.UTILITY
)
@Slf4j
@Singleton
public class PuzzleSolverPlugin extends Plugin
{
private static final Color CORRECT_MUSEUM_PUZZLE_ANSWER_COLOR = new Color(0, 248, 128);
@Inject
private OverlayManager overlayManager;
@Inject
private PuzzleSolverOverlay overlay;
@Inject
private Client client;
@Inject
private PuzzleSolverConfig config;
private LightboxState lightbox;
private final LightboxState[] changes = new LightboxState[LightBox.COMBINATIONS_POWER];
private Combination lastClick;
private boolean lastClickInvalid;
@Getter(AccessLevel.PACKAGE)
private boolean displaySolution;
@Getter(AccessLevel.PACKAGE)
private boolean displayRemainingMoves;
@Getter(AccessLevel.PACKAGE)
private boolean drawDots;
@Override
protected void startUp()
{
updateConfig();
overlayManager.add(overlay);
}
@Override
protected void shutDown()
{
overlayManager.remove(overlay);
}
@Provides
PuzzleSolverConfig provideConfig(ConfigManager configManager)
{
return configManager.getConfig(PuzzleSolverConfig.class);
}
@Subscribe
private void onWidgetLoaded(WidgetLoaded widget)
{
if (widget.getGroupId() != WidgetID.VARROCK_MUSEUM_QUIZ_GROUP_ID)
{
return;
}
final Widget questionWidget = client.getWidget(WidgetInfo.VARROCK_MUSEUM_QUESTION);
if (questionWidget == null)
{
return;
}
final Widget answerWidget = VarrockMuseumAnswer.findCorrect(
client,
questionWidget.getText(),
WidgetInfo.VARROCK_MUSEUM_FIRST_ANSWER,
WidgetInfo.VARROCK_MUSEUM_SECOND_ANSWER,
WidgetInfo.VARROCK_MUSEUM_THIRD_ANSWER);
if (answerWidget == null)
{
return;
}
final String answerText = answerWidget.getText();
if (answerText.equals(Text.removeTags(answerText)))
{
answerWidget.setText(ColorUtil.wrapWithColorTag(answerText, CORRECT_MUSEUM_PUZZLE_ANSWER_COLOR));
}
}
@Subscribe
private void onMenuOptionClicked(MenuOptionClicked menuOptionClicked)
{
int widgetId = menuOptionClicked.getParam1();
if (TO_GROUP(widgetId) != WidgetID.LIGHT_BOX_GROUP_ID)
{
return;
}
Combination combination;
if (widgetId == LIGHT_BOX_BUTTON_A.getId())
{
combination = Combination.A;
}
else if (widgetId == LIGHT_BOX_BUTTON_B.getId())
{
combination = Combination.B;
}
else if (widgetId == LIGHT_BOX_BUTTON_C.getId())
{
combination = Combination.C;
}
else if (widgetId == LIGHT_BOX_BUTTON_D.getId())
{
combination = Combination.D;
}
else if (widgetId == LIGHT_BOX_BUTTON_E.getId())
{
combination = Combination.E;
}
else if (widgetId == LIGHT_BOX_BUTTON_F.getId())
{
combination = Combination.F;
}
else if (widgetId == LIGHT_BOX_BUTTON_G.getId())
{
combination = Combination.G;
}
else if (widgetId == LIGHT_BOX_BUTTON_H.getId())
{
combination = Combination.H;
}
else
{
return;
}
if (lastClick != null)
{
lastClickInvalid = true;
}
else
{
lastClick = combination;
}
}
@Subscribe
public void onGameTick(GameTick event)
{
Widget lightboxWidget = client.getWidget(WidgetInfo.LIGHT_BOX_CONTENTS);
if (lightboxWidget == null)
{
if (lightbox != null)
{
lastClick = null;
lastClickInvalid = false;
lightbox = null;
Arrays.fill(changes, null);
}
return;
}
// get current state from widget
LightboxState lightboxState = new LightboxState();
int index = 0;
for (Widget light : lightboxWidget.getDynamicChildren())
{
boolean lit = light.getItemId() == LightBox.LIGHT_BULB_ON;
lightboxState.setState(index / LightBox.WIDTH, index % LightBox.HEIGHT, lit);
index++;
}
if (lightboxState.equals(lightbox))
{
return; // no change
}
log.debug("Lightbox changed!");
LightboxState prev = lightbox;
lightbox = lightboxState;
if (lastClick == null || lastClickInvalid)
{
lastClick = null;
lastClickInvalid = false;
return;
}
LightboxState diff = lightboxState.diff(prev);
changes[lastClick.ordinal()] = diff;
log.debug("Recorded diff for {}", lastClick);
lastClick = null;
// try to solve
LightboxSolver solver = new LightboxSolver();
solver.setInitial(lightbox);
int idx = 0;
for (LightboxState state : changes)
{
if (state != null)
{
Combination combination = Combination.values()[idx];
solver.setSwitchChange(combination, state);
}
++idx;
}
LightboxSolution solution = solver.solve();
if (solution != null)
{
log.debug("Got solution: {}", solution);
}
// Set solution to title
Widget lightbox = client.getWidget(WidgetInfo.LIGHT_BOX);
if (lightbox != null)
{
Widget title = lightbox.getChild(1);
if (solution != null && solution.numMoves() > 0)
{
title.setText("Light box - Solution: " + solution);
}
else if (solution != null)
{
title.setText("Light box - Solution: solved!");
}
else
{
title.setText("Light box - Solution: unknown");
}
}
}
@Subscribe
private void onConfigChanged(ConfigChanged event)
{
if (event.getGroup().equals("puzzlesolver"))
{
updateConfig();
}
}
private void updateConfig()
{
this.displaySolution = config.displaySolution();
this.displayRemainingMoves = config.displayRemainingMoves();
this.drawDots = config.drawDots();
}
}
| 27.429467 | 100 | 0.747429 |
e7144f7c2395474648f43f160b03c3e2cfb48c90 | 1,775 | /* Class255 - Decompiled by JODE
* Visit http://jode.sourceforge.net/
*/
final class Class255 {
static int anInt3499;
static long aLong3500;
static int[] anIntArray3501 = { 0, 2, 2, 2, 1, 1, 3, 3, 1, 3, 3, 4, 4 };
static int anInt3502;
static int anInt3503 = 0;
static int anInt3504;
static final void method1632(int i, boolean bool, int i_0_) {
try {
anInt3504++;
Class11_Sub45_Sub15 class11_sub45_sub15 = Packet.method3421(
-652872096, 1, i_0_);
class11_sub45_sub15.method3661(0);
if (bool != false)
method1635(null, -68, null);
((Class11_Sub45_Sub15) class11_sub45_sub15).anInt9363 = i;
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, ("mea.A(" + i + ','
+ bool + ',' + i_0_ + ')'));
}
}
static final int method1633(int i) {
try {
if (i != 1)
anInt3503 = 30;
anInt3499++;
return Class120.method784(-73, false);
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, "mea.B(" + i + ')');
}
}
public static void method1634(byte i) {
try {
if (i > -13)
aLong3500 = -83L;
anIntArray3501 = null;
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, "mea.D(" + i + ')');
}
}
static final void method1635(String string, int i, String string_1_) {
try {
Class108_Sub23.anInt7766 = -1;
Class11_Sub45_Sub1_Sub2.anInt9885 = RunClient.ENABLE_LOBBY ? 1 : 2;
anInt3502++;
Class11_Sub2_Sub4.method3352(string, false, 0, string_1_);
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, ("mea.C("
+ (string != null ? "{...}" : "null") + ',' + i + ','
+ (string_1_ != null ? "{...}" : "null") + ')'));
}
}
}
| 28.629032 | 73 | 0.64507 |
2e4ef2acb0dca8a8f864ce238b81561cb39a16c7 | 2,086 | /************************************************************************
UpdatedServicesEvent.java is part of Ti4j 3.1.0 Copyright 2013 Emitrom LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
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.emitrom.ti4j.mobile.client.core.events;
import java.util.ArrayList;
import com.emitrom.ti4j.core.client.JsoHelper;
import com.emitrom.ti4j.mobile.client.network.BonjourService;
import com.google.gwt.core.client.JavaScriptObject;
public class UpdatedServicesEvent extends TiEvent {
public static final String UPDATED_SERVICES = "updatedServices";
protected UpdatedServicesEvent() {
}
/**
* An array of BonjourService objects corresponding to currently available
* services. If you cache this value, including using it as table data, be
* aware that it could become out of date at any time due to the
* asynchronous nature of Bonjour service discovery.
*/
public ArrayList<BonjourService> getServices() {
ArrayList<BonjourService> services = new ArrayList<BonjourService>();
JavaScriptObject array = _getServices();
int length = JsoHelper.getJavaScriptObjectArraySize(array);
for (int i = 0; i < length; i++) {
services.add(new BonjourService(JsoHelper.getValueFromJavaScriptObjectArray(array, i)));
}
return services;
}
public native JavaScriptObject _getServices() /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
return jso.services;
}-*/;
}
| 37.25 | 100 | 0.678332 |
2b1770c4a2dfe7c831439a0b15ad5143183398d4 | 2,131 | /*
* Copyright (C) 2019 Red Hat, 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.jboss.pnc.deliverablesanalyzer.rest;
import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyOrNullString;
import static org.hamcrest.Matchers.not;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jboss.pnc.deliverablesanalyzer.Version;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
@QuarkusTest
class AppTest {
private static final Logger LOGGER = LoggerFactory.getLogger(AppTest.class);
@BeforeAll
static void init() {
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
}
@Test
void testVersion() {
String version = given().log()
.all()
.accept(MediaType.TEXT_PLAIN)
.when()
.get("/api/version")
.then()
.log()
.all()
.statusCode(Response.Status.OK.getStatusCode())
.body(
not(is(emptyOrNullString())),
not(containsString("unknown")),
containsString(Version.getVersion()))
.extract()
.response()
.asString();
LOGGER.info("Version: {}", version);
}
}
| 31.80597 | 80 | 0.652745 |
3b1527b12c5f036770f59ba596bc9b4384e41e56 | 643 | package com.fbi.engine.domain.schema;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class ConnectionPropertiesSchema implements Serializable {
/*
Derived instance of ConnectionDetails class that is associated with this connection properties schma
*/
private String connectionDetailsClass;
/*
@type that is used for JSON polymorphic (de)serialization
*/
private String connectionDetailsType;
/*
File system path or url of image that is displayed.
*/
private String imagePath;
private List<ConnectionProperty> connectionProperties;
}
| 21.433333 | 108 | 0.727838 |
aaa3a3b059b5912b6ed360711fd4fd6912335977 | 11,320 | /*
* Copyright (C) 2020, Peter Abeles. All Rights Reserved.
*
* This file is part of Geometric Regression Library (GeoRegression).
*
* 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 georegression.geometry;
import georegression.metric.UtilAngle;
import georegression.misc.GrlConstants;
import georegression.struct.line.LineGeneral2D_F64;
import georegression.struct.line.LineParametric2D_F64;
import georegression.struct.line.LinePolar2D_F64;
import georegression.struct.line.LineSegment2D_F64;
import georegression.struct.point.Point2D_F64;
import org.ejml.UtilEjml;
import org.junit.jupiter.api.Test;
import java.util.Random;
import static georegression.geometry.UtilLine2D_F64.acuteAngle;
import static georegression.geometry.UtilLine2D_F64.acuteAngleN;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author Peter Abeles
*/
public class TestUtilLine2D_F64 {
private final Random rand = new Random(234234);
@Test void acuteAngle_general() {
assertEquals(0, acuteAngle(new LineGeneral2D_F64(1, 0, 0.5), new LineGeneral2D_F64(1, 0, 6)),
GrlConstants.TEST_F64);
assertEquals(0, acuteAngle(new LineGeneral2D_F64(0, 2, 0.5), new LineGeneral2D_F64(0, 2, 6)),
GrlConstants.TEST_F64);
assertEquals(Math.PI, acuteAngle(new LineGeneral2D_F64(2, 2, 0.5), new LineGeneral2D_F64(-3, -3, 6)),
GrlConstants.TEST_F64);
assertEquals(Math.PI/2, acuteAngle(new LineGeneral2D_F64(2, 2, 0.5), new LineGeneral2D_F64(-4, 4, 6)),
GrlConstants.TEST_F64);
// pathological cause with numerical round off. acos( -1.000000000123 )
double a = Math.cos(Math.PI/4.0);
assertEquals(Math.PI, acuteAngle(new LineGeneral2D_F64(a, a, 0.5), new LineGeneral2D_F64(-a, -a, 6)),
GrlConstants.TEST_F64);
}
@Test void acuteAngleN_general() {
double a = Math.cos(Math.PI/4.0);
double tol = GrlConstants.TEST_F64 *10.0;// float case needs more tolerance
assertEquals(0, acuteAngleN(new LineGeneral2D_F64(1, 0, 0.5), new LineGeneral2D_F64(1, 0, 6)),tol);
assertEquals(0, acuteAngleN(new LineGeneral2D_F64(0, 1, 0.5), new LineGeneral2D_F64(0, 1, 6)),tol);
assertEquals(Math.PI, acuteAngleN(new LineGeneral2D_F64(a, a, 0.5), new LineGeneral2D_F64(-a, -a, 6)),tol);
assertEquals(Math.PI/2, acuteAngleN(new LineGeneral2D_F64(a, a, 0.5), new LineGeneral2D_F64(-a, a, 6)),tol);
}
@Test void convert_segment_parametric() {
LineSegment2D_F64 segment = new LineSegment2D_F64();
LineParametric2D_F64 para = new LineParametric2D_F64();
segment.a.setTo(1,2);
segment.b.setTo(5,0);
UtilLine2D_F64.convert(segment,para);
assertEquals(para.p.x,1, GrlConstants.TEST_F64);
assertEquals(para.p.y,2, GrlConstants.TEST_F64);
assertEquals(para.slope.x,4, GrlConstants.TEST_F64);
assertEquals(para.slope.y,-2, GrlConstants.TEST_F64);
}
@Test void convert_segment_general() {
LineSegment2D_F64 segment = new LineSegment2D_F64();
segment.a.setTo(0,2);
segment.b.setTo(5,6);
LineGeneral2D_F64 general = UtilLine2D_F64.convert(segment,(LineGeneral2D_F64)null);
// see if the two end points lie on the general line
assertEquals(0,general.evaluate(segment.a.x,segment.a.y), GrlConstants.TEST_F64);
assertEquals(0,general.evaluate(segment.b.x,segment.b.y), GrlConstants.TEST_F64);
}
@Test void convert_segment2pt_general() {
Point2D_F64 a = new Point2D_F64(2,6);
Point2D_F64 b = new Point2D_F64(7,8);
LineGeneral2D_F64 general = UtilLine2D_F64.convert(a,b,(LineGeneral2D_F64)null);
// see if the two end points lie on the general line
assertEquals(0,general.evaluate(a.x,a.y), GrlConstants.TEST_F64);
assertEquals(0,general.evaluate(b.x,b.y), GrlConstants.TEST_F64);
}
@Test void convert_segment2pt_parametric() {
Point2D_F64 a = new Point2D_F64(2,6);
Point2D_F64 b = new Point2D_F64(7,8);
LineParametric2D_F64 para = UtilLine2D_F64.convert(a,b,(LineParametric2D_F64) null);
assertEquals(para.p.x,2, GrlConstants.TEST_F64);
assertEquals(para.p.y,6, GrlConstants.TEST_F64);
assertEquals(para.slope.x,5, GrlConstants.TEST_F64);
assertEquals(para.slope.y,2, GrlConstants.TEST_F64);
}
@Test void convert_pt_angle_parametric() {
Point2D_F64 a = new Point2D_F64(2,6);
double angle = Math.PI;
LineParametric2D_F64 para = UtilLine2D_F64.convert(a,angle,(LineParametric2D_F64) null);
assertEquals(para.p.x,2, GrlConstants.TEST_F64);
assertEquals(para.p.y,6, GrlConstants.TEST_F64);
assertEquals(para.slope.x,-1, GrlConstants.TEST_F64);
assertEquals(para.slope.y,0, GrlConstants.TEST_F64);
}
@Test void convert_polar_parametric() {
LinePolar2D_F64 polar = new LinePolar2D_F64();
LineParametric2D_F64 para = new LineParametric2D_F64();
polar.distance = 5;
polar.angle = Math.PI/2;
UtilLine2D_F64.convert(polar,para);
assertEquals(para.p.x,0, GrlConstants.TEST_F64);
assertEquals(para.p.y,5, GrlConstants.TEST_F64);
assertEquals(Math.abs(para.slope.x),1, GrlConstants.TEST_F64);
assertEquals(para.slope.y,0, GrlConstants.TEST_F64);
}
@Test void convert_polar_general() {
LinePolar2D_F64 polar = new LinePolar2D_F64();
polar.distance = 5;
polar.angle = Math.PI/3.0;
LineGeneral2D_F64 found = UtilLine2D_F64.convert(polar,(LineGeneral2D_F64)null);
LineParametric2D_F64 para = UtilLine2D_F64.convert(polar,(LineParametric2D_F64)null);
LineGeneral2D_F64 expected = UtilLine2D_F64.convert(para,(LineGeneral2D_F64)null);
expected.normalize();
// handle the sign ambiguity
if( expected.A*found.A < 0 || expected.B*found.B < 0) {
found.A *= -1;
found.B *= -1;
found.C *= -1;
}
assertEquals(expected.A,found.A,GrlConstants.TEST_F64);
assertEquals(expected.B,found.B,GrlConstants.TEST_F64);
assertEquals(expected.C,found.C,GrlConstants.TEST_F64);
}
@Test void convert_general_polar() {
LineGeneral2D_F64 general = new LineGeneral2D_F64(2,-3,-5);
LinePolar2D_F64 found = UtilLine2D_F64.convert(general,(LinePolar2D_F64)null);
// find two points on the line using the polar equation
double c = (double) Math.cos(found.angle);
double s = (double) Math.sin(found.angle);
double x0 = c*found.distance;
double y0 = s*found.distance;
double x1 = x0 - s;
double y1 = y0 + c;
// see if they are also on the general line equation
assertEquals(0,general.evaluate(x0,y0), GrlConstants.TEST_F64);
assertEquals(0,general.evaluate(x1,y1), GrlConstants.TEST_F64);
}
@Test void convert_parametric_polar() {
LineParametric2D_F64 para = new LineParametric2D_F64();
LinePolar2D_F64 polar = new LinePolar2D_F64();
para.slope.setTo(1,0);
para.setPoint(0,5);
UtilLine2D_F64.convert(para,polar);
assertEquals(polar.distance,5, GrlConstants.TEST_F64);
assertEquals(polar.angle,Math.PI/2, GrlConstants.TEST_F64);
para.slope.setTo(1,-1);
para.setPoint(-5,-5);
UtilLine2D_F64.convert(para,polar);
assertEquals(polar.distance,5*Math.sqrt(2), GrlConstants.TEST_F64);
assertEquals(polar.angle,-Math.PI+Math.PI/4, GrlConstants.TEST_F64);
}
@Test void convert_BackAndForth_parametric_polar() {
LineParametric2D_F64 para = new LineParametric2D_F64();
LinePolar2D_F64 polar = new LinePolar2D_F64();
LinePolar2D_F64 found = new LinePolar2D_F64();
for (int i = 0; i < 100; i++) {
polar.distance = (rand.nextDouble() - 0.5) * 3;
polar.angle = 2.0*(rand.nextDouble() - 0.5) * Math.PI;
UtilLine2D_F64.convert(polar, para);
UtilLine2D_F64.convert(para, found);
normalize(polar);
normalize(found);
assertEquals(polar.angle, found.angle, GrlConstants.TEST_F64);
assertEquals(polar.distance,found.distance,GrlConstants.TEST_F64);
}
}
private void normalize( LinePolar2D_F64 l ) {
if( l.distance < 0 ) {
l.distance = -l.distance;
l.angle = UtilAngle.bound(l.angle + Math.PI);
}
}
@Test void convert_parametric_general() {
LineParametric2D_F64 para = new LineParametric2D_F64();
LineGeneral2D_F64 general = new LineGeneral2D_F64();
para.slope.setTo(1,0.5);
para.p.setTo(0.75,0.34);
// pick a point on the line
Point2D_F64 p = new Point2D_F64(para.p.x + para.slope.x*2,para.p.y + para.slope.y*2);
// convert to general notation
UtilLine2D_F64.convert(para,general);
// test the basic properties of this line equation
double val = general.A*p.x + general.B*p.y + general.C;
assertEquals(0,val, GrlConstants.TEST_F64);
}
@Test void convert_general_parametric() {
LineGeneral2D_F64 general = new LineGeneral2D_F64();
LineParametric2D_F64 para = new LineParametric2D_F64();
// pick some arbitrary line
general.setTo(1,2,3);
// convert to parametric notation
UtilLine2D_F64.convert(general,para);
// pick a point on the parametric line
Point2D_F64 p = new Point2D_F64(para.p.x + para.slope.x*2,para.p.y + para.slope.y*2);
// See if that same point is on the general equation
double val = general.A*p.x + general.B*p.y + general.C;
assertEquals(0,val, GrlConstants.TEST_F64);
}
@Test void area2() {
assertEquals( 2.0*4.0, UtilLine2D_F64.area2(cr(1,1), cr(3,1), cr(3,5)), UtilEjml.TEST_F64);
assertEquals(-2.0*4.0, UtilLine2D_F64.area2(cr(3,5), cr(3,1), cr(1,1)), UtilEjml.TEST_F64);
}
@Test void isColinear() {
assertFalse(UtilLine2D_F64.isColinear(cr(1,1), cr(3,1), cr(3,5), UtilEjml.TEST_F64));
assertFalse(UtilLine2D_F64.isColinear(cr(1,1), cr(3,1), cr(-3,-5), UtilEjml.TEST_F64));
assertTrue(UtilLine2D_F64.isColinear(cr(1,1), cr(2,1), cr(5,1), UtilEjml.TEST_F64));
assertTrue(UtilLine2D_F64.isColinear(cr(1,1), cr(1,2), cr(1,5), UtilEjml.TEST_F64));
// Test the tolerance
assertTrue(UtilLine2D_F64.isColinear(cr(1,1), cr(2,1), cr(5,1.0999), 0.1));
assertFalse(UtilLine2D_F64.isColinear(cr(1,1), cr(2,1), cr(5,1.10001), 0.1));
}
@Test void isBetweenColinear() {
assertFalse(UtilLine2D_F64.isBetweenColinear(cr(1,1), cr(2,1), cr(5,1)));
assertTrue(UtilLine2D_F64.isBetweenColinear(cr(1,1), cr(2,1), cr(1.5,1)));
assertFalse(UtilLine2D_F64.isBetweenColinear(cr(1,1), cr(1,2), cr(1,5)));
assertTrue(UtilLine2D_F64.isBetweenColinear(cr(1,1), cr(1,2), cr(1,1.5)));
assertTrue(UtilLine2D_F64.isBetweenColinear(cr(1,1), cr(1,2), cr(1,1)));
assertTrue(UtilLine2D_F64.isBetweenColinear(cr(1,1), cr(1,2), cr(1,2)));
}
@Test void isBetweenColinearExclusive() {
assertFalse(UtilLine2D_F64.isBetweenColinearExclusive(cr(1, 1), cr(2, 1), cr(5, 1)));
assertTrue(UtilLine2D_F64.isBetweenColinearExclusive(cr(1, 1), cr(2, 1), cr(1.5, 1)));
assertFalse(UtilLine2D_F64.isBetweenColinearExclusive(cr(1, 1), cr(1, 2), cr(1, 5)));
assertTrue(UtilLine2D_F64.isBetweenColinearExclusive(cr(1, 1), cr(1, 2), cr(1, 1.5)));
assertFalse(UtilLine2D_F64.isBetweenColinearExclusive(cr(1,1), cr(1,2), cr(1,1)));
assertFalse(UtilLine2D_F64.isBetweenColinearExclusive(cr(1,1), cr(1,2), cr(1,2)));
}
/** short hand */
private static Point2D_F64 cr(double x , double y) {
return new Point2D_F64(x,y);
}
}
| 36.166134 | 110 | 0.733039 |
acd8afeee19387d7566ce0e8eded52998bf8b1f8 | 20,124 | package org.wycliffeassociates.translationrecorder.ProjectManager.activities;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import org.wycliffeassociates.translationrecorder.FilesPage.Export.Export;
import org.wycliffeassociates.translationrecorder.FilesPage.Export.ExportTaskFragment;
import org.wycliffeassociates.translationrecorder.ProjectManager.Project;
import org.wycliffeassociates.translationrecorder.ProjectManager.adapters.ProjectAdapter;
import org.wycliffeassociates.translationrecorder.ProjectManager.dialogs.ProjectInfoDialog;
import org.wycliffeassociates.translationrecorder.ProjectManager.tasks.ExportSourceAudioTask;
import org.wycliffeassociates.translationrecorder.ProjectManager.tasks.resync.ProjectListResyncTask;
import org.wycliffeassociates.translationrecorder.R;
import org.wycliffeassociates.translationrecorder.Recording.RecordingScreen;
import org.wycliffeassociates.translationrecorder.Reporting.Logger;
import org.wycliffeassociates.translationrecorder.SettingsPage.Settings;
import org.wycliffeassociates.translationrecorder.SplashScreen;
import org.wycliffeassociates.translationrecorder.database.ProjectDatabaseHelper;
import org.wycliffeassociates.translationrecorder.project.ProjectWizardActivity;
import org.wycliffeassociates.translationrecorder.utilities.Task;
import org.wycliffeassociates.translationrecorder.utilities.TaskFragment;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
/**
* Created by sarabiaj on 6/23/2016.
*/
public class ActivityProjectManager extends AppCompatActivity implements ProjectInfoDialog.InfoDialogCallback,
ProjectInfoDialog.ExportDelegator, Export.ProgressUpdateCallback,
ProjectInfoDialog.SourceAudioDelegator, TaskFragment.OnTaskComplete {
LinearLayout mProjectLayout;
Button mNewProjectButton;
ImageView mAddProject;
ListView mProjectList;
SharedPreferences pref;
ListAdapter mAdapter;
private int mNumProjects = 0;
private ProgressDialog mPd;
private volatile int mProgress = 0;
private volatile boolean mZipping = false;
private volatile boolean mExporting = false;
private ExportTaskFragment mExportTaskFragment;
private TaskFragment mTaskFragment;
public static final int SOURCE_AUDIO_TASK = Task.FIRST_TASK;
private static final int DATABASE_RESYNC_TASK = Task.FIRST_TASK + 1;
public static final int EXPORT_TASK = Task.FIRST_TASK + 2;
private final String TAG_EXPORT_TASK_FRAGMENT = "export_task_fragment";
private final String TAG_TASK_FRAGMENT = "task_fragment";
private final String STATE_EXPORTING = "was_exporting";
private final String STATE_ZIPPING = "was_zipping";
private final String STATE_RESYNC = "db_resync";
private final String STATE_PROGRESS = "upload_progress";
public static final int PROJECT_WIZARD_REQUEST = RESULT_FIRST_USER;
public static final int SAVE_SOURCE_AUDIO_REQUEST = RESULT_FIRST_USER + 1;
private boolean mDbResyncing = false;
private File mSourceAudioFile;
private Project mProjectToExport;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_project_management);
Toolbar mToolbar = (Toolbar) findViewById(R.id.project_management_toolbar);
setSupportActionBar(mToolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("Project Management");
}
pref = PreferenceManager.getDefaultSharedPreferences(this);
if (savedInstanceState != null) {
mZipping = savedInstanceState.getBoolean(STATE_ZIPPING, false);
mExporting = savedInstanceState.getBoolean(STATE_EXPORTING, false);
mProgress = savedInstanceState.getInt(STATE_PROGRESS, 0);
mDbResyncing = savedInstanceState.getBoolean(STATE_RESYNC, false);
}
}
//This code exists here rather than onResume due to the potential for onResume() -> onResume()
//This scenario occurs when the user begins to create a new project and backs out. Calling onResume()
//twice will result in two background processes trying to sync the database, and only one reference
//will be kept in the activity- thus leaking the reference to the first dialog causing in it never closing
@Override
protected void onStart() {
super.onStart();
//Moved this section to onResume so that these dialogs pop up above the dialog info fragment
//check if fragment was retained from a screen rotation
FragmentManager fm = getFragmentManager();
mExportTaskFragment = (ExportTaskFragment) fm.findFragmentByTag(TAG_EXPORT_TASK_FRAGMENT);
mTaskFragment = (TaskFragment) fm.findFragmentByTag(TAG_TASK_FRAGMENT);
//TODO: refactor export to fit the new taskfragment
if (mExportTaskFragment == null) {
mExportTaskFragment = new ExportTaskFragment();
fm.beginTransaction().add(mExportTaskFragment, TAG_EXPORT_TASK_FRAGMENT).commit();
fm.executePendingTransactions();
} else {
if (mZipping) {
zipProgress(mProgress);
} else if (mExporting) {
exportProgress(mProgress);
}
}
if (mTaskFragment == null) {
mTaskFragment = new TaskFragment();
fm.beginTransaction().add(mTaskFragment, TAG_TASK_FRAGMENT).commit();
fm.executePendingTransactions();
}
//still need to track whether a db resync was issued so as to not issue them in the middle of another
if (!mDbResyncing) {
mDbResyncing = true;
ProjectListResyncTask task = new ProjectListResyncTask(DATABASE_RESYNC_TASK, getBaseContext(), getFragmentManager());
mTaskFragment.executeRunnable(task, "Resyncing Database", "Please wait...", true);
}
}
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
if (mPd != null) {
savedInstanceState.putInt(STATE_PROGRESS, mPd.getProgress());
}
savedInstanceState.putBoolean(STATE_EXPORTING, mExporting);
savedInstanceState.putBoolean(STATE_ZIPPING, mZipping);
savedInstanceState.putBoolean(STATE_RESYNC, mDbResyncing);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.project_management_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_logout:
logout();
return true;
case R.id.action_settings:
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void initializeViews() {
mProjectLayout = (LinearLayout) findViewById(R.id.project_list_layout);
mNewProjectButton = (Button) findViewById(R.id.new_project_button);
mAddProject = (ImageView) findViewById(R.id.new_project_fab);
mProjectList = (ListView) findViewById(R.id.project_list);
mAddProject.setOnClickListener(btnClick);
mNewProjectButton.setOnClickListener(btnClick);
hideProjectsIfEmpty(mNumProjects);
if (mNumProjects > 0) {
initializeRecentProject();
if (mNumProjects > 1) {
populateProjectList();
}
} else {
mProjectList.setVisibility(View.GONE);
}
}
public void initializeRecentProject() {
Project project = null;
if (!pref.getString(Settings.KEY_PREF_LANG, "").equals("")
&& !pref.getString(Settings.KEY_PREF_BOOK, "").equals("")) {
project = Project.getProjectFromPreferences(this);
Logger.w(this.toString(), "Recent Project: language " + project.getTargetLanguage()
+ " book " + project.getSlug() + " version "
+ project.getVersion() + " mode " + project.getMode());
} else {
ProjectDatabaseHelper db = new ProjectDatabaseHelper(this);
List<Project> projects = db.getAllProjects();
if (projects.size() > 0) {
project = projects.get(0);
}
}
if (project != null) {
ProjectDatabaseHelper db = new ProjectDatabaseHelper(this);
ProjectAdapter.initializeProjectCard(this, project, db, findViewById(R.id.recent_project));
} else {
findViewById(R.id.recent_project).setVisibility(View.GONE);
}
}
public void hideProjectsIfEmpty(int numProjects) {
if (numProjects > 0) {
mNewProjectButton.setVisibility(View.GONE);
} else {
mProjectLayout.setVisibility(View.GONE);
mNewProjectButton.setVisibility(View.VISIBLE);
}
}
private void removeProjectFromPreferences(Project project) {
Map<String, ?> vals = pref.getAll();
String prefLang = (String) vals.get(Settings.KEY_PREF_LANG);
String prefSource = (String) vals.get(Settings.KEY_PREF_VERSION);
String prefProject = (String) vals.get(Settings.KEY_PREF_ANTHOLOGY);
String prefBook = (String) vals.get(Settings.KEY_PREF_BOOK);
if (prefLang != null && prefLang.equals(project.getTargetLanguage())) {
pref.edit().putString(Settings.KEY_PREF_LANG, "").commit();
}
if (prefSource != null && prefSource.equals(project.getVersion())) {
pref.edit().putString(Settings.KEY_PREF_VERSION, "").commit();
}
if (prefProject != null && prefProject.equals(project.getAnthology())) {
pref.edit().putString(Settings.KEY_PREF_ANTHOLOGY, "").commit();
}
if (prefBook != null && prefBook.equals(project.getSlug())) {
pref.edit().putString(Settings.KEY_PREF_BOOK, "").commit();
}
}
private void populateProjectList() {
final ProjectDatabaseHelper db = new ProjectDatabaseHelper(this);
final List<Project> projects = db.getAllProjects();
for (Project p : projects) {
Logger.w(this.toString(), "Project: language " + p.getTargetLanguage() + " book " + p.getSlug() + " version " + p.getVersion() + " mode " + p.getMode());
}
mAdapter = new ProjectAdapter(this, projects);
mProjectList.setAdapter(mAdapter);
}
//sets the profile in the preferences to "" then returns to the splash screen
private void logout() {
pref.edit().putString(Settings.KEY_PROFILE, "").commit();
finishAffinity();
Intent intent = new Intent(this, SplashScreen.class);
startActivity(intent);
}
private void createNewProject() {
startActivityForResult(new Intent(getBaseContext(), ProjectWizardActivity.class), PROJECT_WIZARD_REQUEST);
}
private void loadProject(Project project) {
pref.edit().putString("resume", "resume").commit();
pref.edit().putString(Settings.KEY_PREF_BOOK, project.getSlug()).commit();
pref.edit().putString(Settings.KEY_PREF_BOOK_NUM, project.getBookNumber()).commit();
pref.edit().putString(Settings.KEY_PREF_LANG, project.getTargetLanguage()).commit();
pref.edit().putString(Settings.KEY_PREF_VERSION, project.getVersion()).commit();
pref.edit().putString(Settings.KEY_PREF_ANTHOLOGY, project.getAnthology()).commit();
pref.edit().putString(Settings.KEY_PREF_CHUNK_VERSE, project.getMode()).commit();
pref.edit().putString(Settings.KEY_PREF_LANG_SRC, project.getSourceLanguage()).commit();
//FIXME: find the last place worked on?
pref.edit().putString(Settings.KEY_PREF_CHAPTER, "1").commit();
pref.edit().putString(Settings.KEY_PREF_START_VERSE, "1").commit();
pref.edit().putString(Settings.KEY_PREF_END_VERSE, "1").commit();
pref.edit().putString(Settings.KEY_PREF_CHUNK, "1").commit();
}
private boolean addProjectToDatabase(Project project) {
ProjectDatabaseHelper db = new ProjectDatabaseHelper(this);
if(db.projectExists(project)) {
ProjectWizardActivity.displayProjectExists(this);
return false;
} else {
db.addProject(project);
return true;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PROJECT_WIZARD_REQUEST: {
if (resultCode == RESULT_OK) {
Project project = data.getParcelableExtra(Project.PROJECT_EXTRA);
if (addProjectToDatabase(project)) {
loadProject(project);
finish();
//TODO: should find place left off at?
Intent intent = RecordingScreen.getNewRecordingIntent(this, project, 1, 1);
startActivity(intent);
} else {
onResume();
}
} else {
onResume();
}
break;
}
case SAVE_SOURCE_AUDIO_REQUEST: {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
OutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = getContentResolver().openOutputStream(uri, "w");
bos = new BufferedOutputStream(fos);
//sending output streams to the task to run in a thread means they cannot be closed in a finally block here
ExportSourceAudioTask task = new ExportSourceAudioTask(SOURCE_AUDIO_TASK, mProjectToExport, mProjectToExport.getProjectDirectory(mProjectToExport), getFilesDir(), bos);
mTaskFragment.executeRunnable(task, "Exporting Source Audio", "Please wait...", false);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
}
default:
}
}
private View.OnClickListener btnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.new_project_button:
case R.id.new_project_fab:
createNewProject();
break;
}
}
};
@Override
public void onDelete(final Project project) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setTitle("Delete Project")
.setMessage("Deleting this project will remove all associated verse and chunk " +
"recordings.\n\nAre you sure?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == dialog.BUTTON_POSITIVE) {
Logger.w(this.toString(), "Delete Project: language " + project.getTargetLanguage()
+ " book " + project.getSlug() + " version "
+ project.getVersion() + " mode " + project.getMode());
Project.deleteProject(ActivityProjectManager.this, project);
populateProjectList();
hideProjectsIfEmpty(mAdapter.getCount());
removeProjectFromPreferences(project);
mNumProjects--;
initializeViews();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
public void exportProgress(int progress) {
mPd = new ProgressDialog(this);
mPd.setTitle("Uploading...");
mPd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mPd.setProgress(progress);
mPd.setCancelable(false);
mPd.show();
}
public void zipProgress(int progress) {
mPd = new ProgressDialog(this);
mPd.setTitle("Packaging files to export.");
mPd.setMessage("Please wait...");
mPd.setProgress(progress);
mPd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mPd.setCancelable(false);
mPd.show();
}
public void dismissProgress() {
mPd.dismiss();
}
public void incrementProgress(int progress) {
mPd.incrementProgressBy(progress);
}
public void setUploadProgress(int progress) {
mPd.setProgress(progress);
}
public void showProgress(boolean mode) {
if (mode == true) {
zipProgress(0);
} else {
exportProgress(0);
}
}
@Override
public void setZipping(boolean zipping) {
mZipping = zipping;
}
@Override
public void setExporting(boolean exporting) {
mExporting = exporting;
}
@Override
public void setCurrentFile(String currentFile) {
mPd.setMessage(currentFile);
}
@Override
public void onPause() {
super.onPause();
dismissExportProgressDialog();
}
private void dismissExportProgressDialog() {
if (mPd != null && mPd.isShowing()) {
mPd.dismiss();
mPd = null;
}
}
@Override
public void delegateExport(Export exp) {
exp.setFragmentContext(mExportTaskFragment);
mExportTaskFragment.delegateExport(exp);
}
@Override
public void delegateSourceAudio(Project project) {
mProjectToExport = project;
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
mSourceAudioFile = new File(getFilesDir(), project.getTargetLanguage() + "_" + project.getVersion() + "_" + project.getSlug() + ".tr");
intent.putExtra(Intent.EXTRA_TITLE, mSourceAudioFile.getName());
startActivityForResult(intent, SAVE_SOURCE_AUDIO_REQUEST);
}
@Override
public void onTaskComplete(int taskTag, int resultCode) {
if (resultCode == TaskFragment.STATUS_OK) {
if (taskTag == DATABASE_RESYNC_TASK) {
ProjectDatabaseHelper db = new ProjectDatabaseHelper(this);
mNumProjects = db.getNumProjects();
mDbResyncing = false;
initializeViews();
}
}
}
}
| 41.407407 | 192 | 0.642815 |
f5d91894a8663335777947fe4f5e131cf5f7a4f3 | 2,327 | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2012 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.cs.util;
import java.io.File;
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.zimbra.common.localconfig.LC;
import com.zimbra.cs.util.SpoolingCache;
public class SpoolingCacheTest {
@BeforeClass
public static void init() throws Exception {
new File("build/test").mkdirs();
LC.zimbra_tmp_directory.setDefault("build/test");
}
@AfterClass
public static void destroy() throws Exception {
new File("build/test").delete();
}
private static final String[] STRINGS = new String[] { "foo", "bar", "baz" };
private void test(SpoolingCache<String> scache, boolean shouldSpool) throws IOException {
for (String v : STRINGS) {
scache.add(v);
}
Assert.assertEquals("spooled", shouldSpool, scache.isSpooled());
Assert.assertEquals("entry count matches", STRINGS.length, scache.size());
int i = 0;
for (String v : scache) {
Assert.assertEquals("entry matched: #" + i, STRINGS[i++], v);
}
Assert.assertEquals("correct number of items iterated", STRINGS.length, i);
}
@Test
public void memory() throws Exception {
SpoolingCache<String> scache = new SpoolingCache<String>(STRINGS.length + 3);
test(scache, false);
scache.cleanup();
}
@Test
public void disk() throws Exception {
SpoolingCache<String> scache = new SpoolingCache<String>(0);
test(scache, true);
scache.cleanup();
}
@Test
public void both() throws Exception {
SpoolingCache<String> scache = new SpoolingCache<String>(1);
test(scache, true);
scache.cleanup();
}
}
| 29.0875 | 93 | 0.649764 |
2d2ffc4de4aaeba3d2669bfdb57142b12a9c59c2 | 5,104 | /*
* Constellation - An open source and standard compliant SDI
* http://www.constellation-sdi.org
*
* Copyright 2014 Geomatys.
*
* 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.constellation.metadata.factory;
import org.constellation.configuration.DataSourceType;
import org.constellation.filter.FilterParser;
import org.constellation.generic.database.Automatic;
import org.constellation.metadata.harvest.CatalogueHarvester;
import org.constellation.metadata.io.CSWMetadataReader;
import org.constellation.metadata.io.MetadataIoException;
import org.constellation.metadata.io.MetadataReader;
import org.constellation.metadata.io.MetadataWriter;
import org.constellation.metadata.security.MetadataSecurityFilter;
import org.geotoolkit.lucene.IndexingException;
import org.geotoolkit.lucene.index.AbstractIndexer;
import org.geotoolkit.lucene.index.LuceneIndexSearcher;
import java.io.File;
import java.util.List;
import java.util.Map;
import org.apache.sis.xml.MarshallerPool;
// constellation dependencies
// Geotoolkit dependencies
/**
* Factory used to load various implementation of metadata reader/writer, and Lucene indexer/searcher.
*
* @author Guilhem Legal (Geomatys)
*/
public interface AbstractCSWFactory {
/**
* Return true if the factory can return an implementation for the specified type.
*/
boolean factoryMatchType(final DataSourceType type);
/**
* Return a list of supported datasource type
*/
List<DataSourceType> availableType();
/**
* Return a Metadata reader for the specified dataSource type.
*
* @param configuration A configuration object containing all the information to use the dataSource.
* @param serviceID
*
* @return a Metadata reader for the specified dataSource type.
* @throws MetadataIoException
*/
CSWMetadataReader getMetadataReader(final Automatic configuration, final String serviceID) throws MetadataIoException;
/**
* Return a Metadata Writer for the specified dataSource type.
*
* @param configuration A configuration object containing all the information to use the dataSource.
* @param indexer A metadata Indexer use by the metadata writer to add new metadata to the Lucene index.
*
* @return a Metadata Writer for the specified dataSource type.
* @throws org.constellation.metadata.io.MetadataIoException
*/
MetadataWriter getMetadataWriter(final Automatic configuration, final AbstractIndexer indexer, final String serviceID) throws MetadataIoException;
/**
* Return a Lucene indexer for the specified dataSource type.
*
* @param configuration A configuration object containing all the information to use the dataSource.
* @param reader A metadata reader to access the dataSource.
* @param serviceID An identifier of the service/index.
* @param additionalQueryable A map of additional queryable element.
*
* @return A Lucene indexer for the specified dataSource type.
* @throws IndexingException
*/
AbstractIndexer getIndexer(final Automatic configuration, final MetadataReader reader, final String serviceID,
final Map<String, List<String>> additionalQueryable) throws IndexingException;
/**
* Return a Lucene index searcher for the specified dataSource type.
*
* @param configDir The directory containing the lucene index.
* @param serviceID An identifier of the service/index.
*
* @return a Lucene index searcher for the specified dataSource type.
* @throws IndexingException
*/
LuceneIndexSearcher getIndexSearcher(final File configDir, final String serviceID) throws IndexingException;
/**
* Return a catalog harvester in the specified implementation type.
*
* @param configuration A configuration object containing all the information about the chosen harvester implementation.
* @param writer A metadata writer to store the harvested metadata into the dataSource.
*
* @return A Catalog harvester implementation.
* @throws MetadataIoException
*/
CatalogueHarvester getCatalogueHarvester(final Automatic configuration, final MetadataWriter writer) throws MetadataIoException;
FilterParser getLuceneFilterParser();
FilterParser getSQLFilterParser();
MetadataSecurityFilter getSecurityFilter();
Map<String, List<String>> getBriefFieldMap();
MarshallerPool getMarshallerPool();
String getTemplateName(final String metaID, final String type);
}
| 39.261538 | 150 | 0.747845 |
5cbe2ccabca7a3e44a614a3c53aac5191b5b528a | 5,760 | package org.tanrabad.survey.nearby;
import org.junit.Test;
import org.tanrabad.survey.domain.place.PlaceRepository;
import org.tanrabad.survey.entity.Place;
import org.tanrabad.survey.entity.field.Location;
import org.tanrabad.survey.nearby.repository.ImpNearbyPlaceRepository;
import org.tanrabad.survey.nearby.repository.NearbyPlaceRepository;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class NearbyPlaceTest {
@Test public void testFindNearByPlaces() {
Place tuStadium = new Place(UUID.nameUUIDFromBytes("1".getBytes()), "สนามกีฬาธรรมศาสตร์");
tuStadium.setLocation(new Location(14.067960, 100.598828)); //1.2กม.
tuStadium.setSubdistrictCode("130201");
Place tuHospital =
new Place(UUID.nameUUIDFromBytes("2".getBytes()), "โรงพยาบาลธรรมศาสตร์เฉลิมพระเกียรติ");
tuHospital.setLocation(new Location(14.074163, 100.614696)); //1.4กม.
tuHospital.setSubdistrictCode("130201");
Place navanakhon = new Place(UUID.nameUUIDFromBytes("3".getBytes()), "นิคมอุตสาหกรรมนวนคร");
navanakhon.setLocation(new Location(14.1119521, 100.6020252)); //4กม.
navanakhon.setSubdistrictCode("130201");
Place vru = new Place(UUID.nameUUIDFromBytes("4".getBytes()), "มหาวิทยาลัยราชภัฏวไลยอลงกรณ์");
vru.setLocation(new Location(14.1280585, 100.6048577)); // 6กม.
vru.setSubdistrictCode("130201");
Place chiangrakStation = new Place(UUID.nameUUIDFromBytes("5".getBytes()), "สถานีรถไฟเชียงราก");
chiangrakStation.setLocation(new Location(14.0490811, 100.6012871)); //2กม.
chiangrakStation.setSubdistrictCode("130201");
Place bangpainPalace = new Place(UUID.nameUUIDFromBytes("11".getBytes()), "พระราชวังบางปะอิน");
bangpainPalace.setLocation(new Location(14.2278557, 100.5768217)); // 6กม.
bangpainPalace.setSubdistrictCode("140601");
Place tuPrimarySchool =
new Place(UUID.nameUUIDFromBytes("6".getBytes()), "โรงเรียนประถมศึกษาธรรมศาสตร์");
tuPrimarySchool.setSubdistrictCode("130201");
Place chiangraknoiStation = new Place(UUID.nameUUIDFromBytes("7".getBytes()), "สถานีรถไฟเชียงรากน้อย");
chiangraknoiStation.setSubdistrictCode("140602");
Place thaithaniDorm = new Place(UUID.nameUUIDFromBytes("8".getBytes()), "หอพักไทยธานี");
thaithaniDorm.setSubdistrictCode("130201");
Place pratunamPhraInPoliceStation =
new Place(UUID.nameUUIDFromBytes("9".getBytes()), "สภ.ประตูน้ำพระอินทร์");
pratunamPhraInPoliceStation.setSubdistrictCode("140602");
Place tuKindergarten = new Place(UUID.nameUUIDFromBytes("10".getBytes()), "โรงเรียนอนุบาลธรรมศาสตร์");
tuKindergarten.setSubdistrictCode("130201");
Place taladThai = new Place(UUID.nameUUIDFromBytes("13".getBytes()), "ตลาดไท");
taladThai.setSubdistrictCode("130201");
Place racha1School =
new Place(UUID.nameUUIDFromBytes("12".getBytes()), "โรงเรียนบางปะอิน \"ราชานุเคราะห์ ๑\"");
racha1School.setSubdistrictCode("140601");
Place tuPostOffice =
new Place(UUID.nameUUIDFromBytes("14".getBytes()), "ไปรษณีย์มหาวิทยาลัยธรรมศาสตร์ ศูนย์รังสิต");
tuPostOffice.setSubdistrictCode("130201");
Place tuCanteen =
new Place(UUID.nameUUIDFromBytes("15".getBytes()), "โรงอาหารกลางธรรมศาสตร์");
tuCanteen.setSubdistrictCode("130201");
Place medicalTu =
new Place(UUID.nameUUIDFromBytes("16".getBytes()), "คณะแพทยศาสตร์ มหาวิทยาลัยธรรมศาสตร์");
medicalTu.setSubdistrictCode("130201");
List<Place> allPlaces = new ArrayList<>();
allPlaces.add(tuStadium);
allPlaces.add(tuHospital);
allPlaces.add(navanakhon);
allPlaces.add(vru);
allPlaces.add(chiangrakStation);
allPlaces.add(chiangraknoiStation);
allPlaces.add(thaithaniDorm);
allPlaces.add(pratunamPhraInPoliceStation);
allPlaces.add(tuPrimarySchool);
allPlaces.add(tuKindergarten);
allPlaces.add(racha1School);
allPlaces.add(bangpainPalace);
allPlaces.add(taladThai);
allPlaces.add(tuPostOffice);
allPlaces.add(tuCanteen);
allPlaces.add(medicalTu);
final List<Place> nearbyPlaces = new ArrayList<>();
nearbyPlaces.add(tuStadium);
nearbyPlaces.add(tuHospital);
nearbyPlaces.add(chiangrakStation);
nearbyPlaces.add(navanakhon);
nearbyPlaces.add(tuCanteen);
nearbyPlaces.add(tuPostOffice);
nearbyPlaces.add(medicalTu);
nearbyPlaces.add(tuPrimarySchool);
nearbyPlaces.add(tuKindergarten);
nearbyPlaces.add(thaithaniDorm);
nearbyPlaces.add(taladThai);
PlaceRepository repository = mock(PlaceRepository.class);
when(repository.find()).thenReturn(allPlaces);
NearbyPlaceRepository nearbyPlaceRepository =
new ImpNearbyPlaceRepository(repository, 5);
MergeAndSortNearbyPlaces mergeAndSortNearbyPlaces = new ImpMergeAndSortNearbyPlaces();
NearbyPlacePresenter presenter = mock(NearbyPlacePresenter.class);
NearbyPlacesFinderController nearbyPlacesFinderController =
new NearbyPlacesFinderController(nearbyPlaceRepository, mergeAndSortNearbyPlaces, presenter);
nearbyPlacesFinderController.findNearbyPlaces(new Location(14.077756, 100.601380));
verify(presenter, times(2)).displayNearbyPlaces(any(List.class));
}
}
| 48.403361 | 112 | 0.699132 |
f98285173a2e42baa2110e47355b36f2bbc010f5 | 2,691 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
DECL|package|org.apache.camel.component.crypto.cms.common
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|crypto
operator|.
name|cms
operator|.
name|common
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|spi
operator|.
name|UriParam
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|spi
operator|.
name|UriParams
import|;
end_import
begin_class
annotation|@
name|UriParams
DECL|class|DefaultCryptoCmsUnMarshallerConfiguration
specifier|public
class|class
name|DefaultCryptoCmsUnMarshallerConfiguration
extends|extends
name|DefaultCryptoCmsConfiguration
implements|implements
name|CryptoCmsUnMarshallerConfiguration
block|{
annotation|@
name|UriParam
argument_list|(
name|label
operator|=
literal|"decrypt_verify"
argument_list|)
DECL|field|fromBase64
specifier|private
name|boolean
name|fromBase64
decl_stmt|;
DECL|method|DefaultCryptoCmsUnMarshallerConfiguration ()
specifier|public
name|DefaultCryptoCmsUnMarshallerConfiguration
parameter_list|()
block|{ }
annotation|@
name|Override
DECL|method|isFromBase64 ()
specifier|public
name|boolean
name|isFromBase64
parameter_list|()
block|{
return|return
name|fromBase64
return|;
block|}
comment|/** * If<tt>true</tt> then the CMS message is base 64 encoded and must be * decoded during the processing. Default value is<code>false</code>. */
DECL|method|setFromBase64 (boolean base64)
specifier|public
name|void
name|setFromBase64
parameter_list|(
name|boolean
name|base64
parameter_list|)
block|{
name|this
operator|.
name|fromBase64
operator|=
name|base64
expr_stmt|;
block|}
block|}
end_class
end_unit
| 23.198276 | 810 | 0.797473 |
86b97cf4a709651c8ee5589af2a687778403ad15 | 1,238 | package org.quickstart.metrics.yammer;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Histogram;
import com.yammer.metrics.reporting.ConsoleReporter;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class LearnHistogram {
private List<String> stringList = new LinkedList<String>();
private Histogram histogram = Metrics.newHistogram(LearnHistogram.class, "size-histogram");
public void push(String input) {
stringList.add(input);
}
public void pop(String output) {
stringList.remove(output);
}
public void updateHisto() {
histogram.update(stringList.size());
}
public static void main(String[] args) throws InterruptedException {
ConsoleReporter.enable(1, TimeUnit.SECONDS);
LearnHistogram learnHistogram = new LearnHistogram();
for (int time = 0; time < 100000; time++) {
learnHistogram.push(String.valueOf(time));
if (time % 10 == 0) {
learnHistogram.updateHisto();
}
if (time % 2 == 2) {
learnHistogram.pop(String.valueOf(time));
}
Thread.sleep(1);
}
}
}
| 25.791667 | 95 | 0.638126 |
f1f8a863c92265f377437242ddb056ab438b3740 | 1,328 | package org.cyclops.integrateddynamics.core.evaluate.variable;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
/**
* A list of NBT tags.
*/
public class ValueTypeListProxyNbtValueListTag extends ValueTypeListProxyNbtValueListGeneric<NBTTagList, ValueTypeNbt, ValueTypeNbt.ValueNbt> {
public ValueTypeListProxyNbtValueListTag(String key, NBTTagCompound tag) {
super(ValueTypeListProxyFactories.NBT_VALUE_LIST_TAG.getName(), ValueTypes.NBT, key, tag);
}
@Override
protected int getLength(NBTTagList tag) {
return tag.tagCount();
}
@Override
protected ValueTypeNbt.ValueNbt get(NBTTagList tag, int index) {
return ValueTypeNbt.ValueNbt.of(tag.getCompoundTagAt(index));
}
@Override
protected NBTTagList getDefault() {
return new NBTTagList();
}
public static class Factory extends ValueTypeListProxyNbtValueListGeneric.Factory<ValueTypeListProxyNbtValueListTag, NBTTagList, ValueTypeNbt, ValueTypeNbt.ValueNbt> {
@Override
public String getName() {
return "nbt.listValueTag";
}
@Override
protected ValueTypeListProxyNbtValueListTag create(String key, NBTTagCompound tag) {
return new ValueTypeListProxyNbtValueListTag(key, tag);
}
}
}
| 30.883721 | 171 | 0.724398 |
a9148d957a3c53b061ffe71f596d7133adb65099 | 3,506 | import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
public class Customer {
// variables
private int numOrders;
private double amount;
private long customerID;
private long uniqueID;
private int[] leftHalf = new int[10];
private int[] rightHalf = new int[10];
private Random rn = new Random();
private HashMap<Integer, Integer> right = new HashMap<Integer, Integer>();
private HashMap<Integer, Integer> left = new HashMap<Integer, Integer>();
public Customer(int numOrd, double amt, long id) {
numOrders = numOrd;
amount = amt;
customerID = id;
uniqueID = rn.nextLong();
}
public void getLeft() {
for (int i = 0; i < leftHalf.length; i++) {
System.out.print(leftHalf[i] + " ");
}
System.out.println();
}
public void getRight() {
for (int i = 0; i < rightHalf.length; i++) {
System.out.print(rightHalf[i] + " ");
}
System.out.println();
}
public String getInfo() {
return customerID + " " + numOrders + " " + amount;
}
// Generate N money orders and assign a different random uniqueness string
// number for each of the N ecash money orders
// Secret splitting
public void sercretSplit() {
for (int i = 0; i < 10; i++) {
rightHalf[i] = rn.nextInt();
leftHalf[i] = (int) (customerID ^ rightHalf[i]);
}
}
// Bit commitment
public void bitCommitment() {
int r1 = 0;
int r2 = 0;
for (int i = 0; i < rightHalf.length; i++) {
r1 = rn.nextInt();
r2 = rn.nextInt();
// right.put(Integer.toString((rightHalf[i] ^ r1 ^ r2)).hashCode(),
// r1);
right.put(hashFunction(rightHalf[i], r1, r2), r1);
}
for (int j = 0; j < leftHalf.length; j++) {
r1 = rn.nextInt();
r2 = rn.nextInt();
left.put((hashFunction(leftHalf[j], r1, r2)), r1);
}
}
private int hashFunction(int x, int y, int z) {
// return Integer.toString(x).hashCode() ^
// Integer.toString(y).hashCode() ^ Integer.toString(z).hashCode();
return Integer.toString(x ^ y ^ z).hashCode();
}
public void getIDs() {
// Get a set of the entries
Set<Entry<Integer, Integer>> leftSet = left.entrySet();
Set<Entry<Integer, Integer>> rightSet = right.entrySet();
// Get an iterator
Iterator<Entry<Integer, Integer>> l = leftSet.iterator();
Iterator<Entry<Integer, Integer>> r = rightSet.iterator();
// Display elements
while (l.hasNext()) {
Map.Entry me = (Map.Entry) l.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
while (r.hasNext()) {
Map.Entry me = (Map.Entry) r.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
}
// Blind signature protocol
public void blind() {
double k = rn.nextDouble();
double e = rn.nextDouble();
double n = rn.nextDouble();
double result = Math.pow(k, e) % n;
uniqueID = (long) ((uniqueID * result) % n);
amount = (amount * result) % n;
for (Integer key : right.keySet()) {
key = (int) ((key * result) % n);
}
for (Integer value : right.values()) {
value = (int) ((value * result) % n);
}
for (Integer key : left.keySet()) {
key = (int) ((key * result) % n);
}
for (Integer value : left.values()) {
value = (int) ((value * result) % n);
}
}
// Reveal chosen half of identity string
public int revealHalf(int num, int index) {
if (num == 0) {
// reveal leftHalf
return leftHalf[index];
} else {
// reveal rightHalf
return rightHalf[index];
}
}
}
| 25.405797 | 75 | 0.62607 |
179b75ce0567a33a70372445205d65dec4a01a3f | 827 | import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Redis {
private static IRedisClient client;
public static void initialize(IRedisClient client)
{
Redis.client = client;
}
public static IRedisClient getClient()
{
return client;
}
public static Timer startPingTimer(int secondsFrequency)
{
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
Logging.write("P");
getClient().ping();
} catch (Exception ex) {
//do nothing. Non-fatal if a ping command errors out.
}
}
}, 0, secondsFrequency*1000);
return timer;
}
}
| 23.628571 | 74 | 0.533253 |
f1350b12a33123f52444a87484f0edcfb095da19 | 3,167 | /*
* Copyright 2020-2022 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.data.redis.test.condition;
import static org.junit.jupiter.api.extension.ConditionEvaluationResult.*;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.platform.commons.function.Try;
import org.junit.platform.commons.util.AnnotationUtils;
import org.junit.platform.commons.util.ReflectionUtils;
import org.springframework.data.redis.connection.RedisConnectionFactory;
/**
* {@link ExecutionCondition} for {@link EnabledOnRedisDriverCondition @EnabledOnRedisDriver}.
*
* @author Mark Paluch
* @author Christoph Strobl
* @see EnabledOnRedisDriver
*/
class EnabledOnRedisDriverCondition implements ExecutionCondition {
private static final ConditionEvaluationResult ENABLED_BY_DEFAULT = enabled("@EnabledOnRedisDriver is not present");
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
Optional<EnabledOnRedisDriver> optional = AnnotationUtils.findAnnotation(context.getElement(),
EnabledOnRedisDriver.class);
if (!optional.isPresent()) {
return ENABLED_BY_DEFAULT;
}
EnabledOnRedisDriver annotation = optional.get();
Class<?> testClass = context.getRequiredTestClass();
List<Field> annotatedFields = AnnotationUtils.findAnnotatedFields(testClass,
EnabledOnRedisDriver.DriverQualifier.class, it -> RedisConnectionFactory.class.isAssignableFrom(it.getType()));
if (annotatedFields.isEmpty()) {
throw new IllegalStateException(
"@EnabledOnRedisDriver requires a field of type RedisConnectionFactory annotated with @DriverQualifier!");
}
for (Field field : annotatedFields) {
Try<Object> fieldValue = ReflectionUtils.tryToReadFieldValue(field, context.getRequiredTestInstance());
RedisConnectionFactory value = (RedisConnectionFactory) fieldValue
.getOrThrow(e -> new IllegalStateException("Cannot read field " + field, e));
boolean foundMatch = false;
for (RedisDriver redisDriver : annotation.value()) {
if (redisDriver.matches(value)) {
foundMatch = true;
}
}
if (!foundMatch) {
return disabled(String.format("Driver %s not supported. Supported driver(s): %s", value,
Arrays.toString(annotation.value())));
}
}
return enabled("Found enabled driver(s): " + Arrays.toString(annotation.value()));
}
}
| 35.58427 | 117 | 0.770761 |
a4c73f9e92df166d65f6bd18d7eb692dabab6ccf | 3,962 | package org.zerhusen.ams.rest;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zerhusen.ams.model.AmsAppointments;
import org.zerhusen.ams.model.AmsAppointmentsForReview;
import org.zerhusen.ams.model.AmsDoctorSuggestion;
import org.zerhusen.ams.model.Ams_Services_available;
import org.zerhusen.ams.model.Ams_patient_users;
import org.zerhusen.ams.model.security.User;
import org.zerhusen.ams.repository.AmsAppointmentForReviewRepository;
import org.zerhusen.ams.repository.AmsAppointmentsRepository;
import org.zerhusen.ams.repository.AmsDoctorSuggestionRepository;
import org.zerhusen.ams.repository.AmsPatientUsersRepository;
import org.zerhusen.ams.repository.AmsServicesRepository;
import org.zerhusen.ams.repository.security.AuthorityRepository;
import org.zerhusen.ams.repository.security.UserRepository;
import org.zerhusen.security.JwtTokenUtil;
@RestController
@CrossOrigin(origins="*")
public class DashboardRest {
@Autowired
public AmsAppointmentsRepository appointmentRepo;
@Autowired
public AuthorityRepository roleRepo;
@Autowired
public AmsPatientUsersRepository userrepo;
@Autowired
public AmsServicesRepository serviceRepo;
@Autowired
private AmsDoctorSuggestionRepository doctorRepo;
@Value("${jwt.header}")
private String tokenHeader;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
@Qualifier("jwtUserDetailsService")
private UserDetailsService userDetailsService;
@Autowired
private AmsAppointmentForReviewRepository reviewRepository;
@GetMapping("/getPatientwiseAppointment")
public Iterable<AmsAppointments> getPatientwiseAppointment(HttpServletRequest req){
LocalDate today = LocalDate.now();
String token = req.getHeader(tokenHeader).substring(7);
String username = jwtTokenUtil.getUsernameFromToken(token);
Ams_patient_users user = userrepo.findByEmail(username);
return appointmentRepo.findAll().stream().filter(i->i.isActive()== true && i.getPatientUser() != null && i.getPatientUser().equals(user) && (i.getDate().equals(today) || i.getDate().isAfter(today)) && i.isRescheduled() == false).collect(Collectors.toList());
}
@GetMapping(value="/getDoctors")
public Iterable<AmsDoctorSuggestion> getdoctors(){
return doctorRepo.findAll().stream().filter(i->i.isActive()== true).collect(Collectors.toList());
}
@GetMapping("/getServices")
public Iterable<Ams_Services_available> getServices(){
return serviceRepo.findAll().stream().filter(i->i.isActive()==true).collect(Collectors.toList());
}
@GetMapping("/getReviewDatesPatientWise")
public Iterable<AmsAppointmentsForReview> getReviewDatePatientWise(HttpServletRequest req){
String token = req.getHeader(tokenHeader).substring(7);
String username = jwtTokenUtil.getUsernameFromToken(token);
Ams_patient_users user = userrepo.findByEmail(username);
List<AmsAppointmentsForReview> result = new ArrayList<AmsAppointmentsForReview>();
List<AmsAppointments> appointments = appointmentRepo.findAll().stream().filter(i->i.isActive()==true && i.getPatientUser()!=null && i.getPatientUser().equals(user)).collect(Collectors.toList());
LocalDate date = LocalDate.now();
for(AmsAppointments appmnts : appointments) {
AmsAppointmentsForReview review = reviewRepository.findByAppointment(appmnts);
if(review != null) {
if(review.getReviewDate().isAfter(date) || review.getReviewDate().equals(date) ) {
result.add(review);
}
}
}
return result;
}
}
| 33.863248 | 259 | 0.80944 |
ee45bd5ad843af9d98796d111b2718b022e801d9 | 1,019 | /**
* <copyright>
* </copyright>
*
*
*/
package eu.hyvar.feature.mapping.resource.hymapping.ui;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
/**
* A class for RGB-based color objects.
*/
public class HymappingColorManager {
protected Map<RGB, Color> fColorTable = new LinkedHashMap<RGB, Color>(10);
/**
* Disposes all colors in the cache.
*/
public void dispose() {
Iterator<Color> e = fColorTable.values().iterator();
while (e.hasNext()) {
e.next().dispose();
}
}
/**
* <p>
* Constructs and caches the given color.
* </p>
*
* @param rgb The color as RGB
*
* @return The color (from cache or newly constructed)
*/
public Color getColor(RGB rgb) {
Color color = fColorTable.get(rgb);
if (color == null) {
color = new Color(Display.getCurrent(), rgb);
fColorTable.put(rgb, color);
}
return color;
}
}
| 19.980392 | 75 | 0.664377 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.