hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e121e47c20a28b868a5f42b7f02e5d58da1b2c8
2,693
java
Java
wave/src/test/java/org/waveprotocol/wave/model/experimental/schema/RegularExpressionCheckerTest.java
ADSempere/incubator-retired-wave
1231ce99afb54491005f37183b25b3def010b68d
[ "Apache-2.0" ]
163
2015-04-21T15:48:00.000Z
2020-04-29T17:03:26.000Z
test/org/waveprotocol/wave/model/experimental/schema/RegularExpressionCheckerTest.java
comunes/Wiab.pro
b492a98d1ca5eeb5c0249c03d22ca18c05fedb97
[ "Apache-2.0" ]
236
2015-05-07T13:03:10.000Z
2018-08-29T18:15:23.000Z
test/org/waveprotocol/wave/model/experimental/schema/RegularExpressionCheckerTest.java
comunes/Wiab.pro
b492a98d1ca5eeb5c0249c03d22ca18c05fedb97
[ "Apache-2.0" ]
52
2015-01-25T02:11:06.000Z
2018-11-28T12:00:21.000Z
32.059524
76
0.669514
7,634
/** * 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.waveprotocol.wave.model.experimental.schema; import junit.framework.TestCase; /** * Tests for RegularExpressionChecker. * */ public class RegularExpressionCheckerTest extends TestCase { /** * Tests that valid regular expressions cause no exception to be thrown. */ public void testValidRegularExpressions() throws InvalidSchemaException { checkValid(""); checkValid("valid"); checkValid("ab*c"); checkValid("a.*b"); checkValid("hello|world"); checkValid("ab(cd|ef)gh"); checkValid("ab(c*|.d)ef"); checkValid("ab(c|d)*ef"); checkValid("ab()*cd"); checkValid("ab(cde(fg)(hi()j(k)lm)n)op"); } /** * Tests that invalid regular expressions cause an * <code>InvalidSchemaException</code> to be thrown. */ public void testInvalidRegularExpressions() { checkInvalid("*abcd"); // begins with '*' checkInvalid("?abcd"); // begins with '?' checkInvalid(")abcd"); // begins with ')' checkInvalid("ab(*cd)ef"); // unexpected '*' checkInvalid("ab(?cd)ef"); // unexpected '?' checkInvalid("ab(cd"); // unmatched '(' checkInvalid("ab)cd"); // unexpected ')' checkInvalid("a((b(()()c)d"); // unmatched '(' checkInvalid("a(b()())c))d"); // unexpected ')' checkInvalid("abcd\\"); // ends with '\\' } /** * A convenience method for checking valid regular expressions. */ private static void checkValid(String re) throws InvalidSchemaException { RegularExpressionChecker.checkRegularExpression(re); } /** * Checks that a regular expression is invalid. */ private static void checkInvalid(String re) { try { RegularExpressionChecker.checkRegularExpression(re); fail("The expected InvalidSchemaException was not thrown for: " + re); } catch (InvalidSchemaException e) { } } }
3e121e927f32b294ff092d613e4c8a9545631bf5
1,487
java
Java
Original Files/source/src/com/sina/weibo/sdk/api/share/ProvideMessageForWeiboResponse.java
vishnudevk/MiBandDecompiled
2c12ea0a68e55d776551ad70ed4ef26b0ed87a70
[ "Apache-2.0" ]
40
2015-03-28T16:47:39.000Z
2021-04-28T19:37:32.000Z
Original Files/source/src/com/sina/weibo/sdk/api/share/ProvideMessageForWeiboResponse.java
omusico/MiBandDecompiled
2c12ea0a68e55d776551ad70ed4ef26b0ed87a70
[ "Apache-2.0" ]
null
null
null
Original Files/source/src/com/sina/weibo/sdk/api/share/ProvideMessageForWeiboResponse.java
omusico/MiBandDecompiled
2c12ea0a68e55d776551ad70ed4ef26b0ed87a70
[ "Apache-2.0" ]
14
2015-05-22T23:07:12.000Z
2019-10-18T22:57:14.000Z
24.377049
81
0.670477
7,635
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.sina.weibo.sdk.api.share; import android.content.Context; import android.os.Bundle; import com.sina.weibo.sdk.api.WeiboMessage; // Referenced classes of package com.sina.weibo.sdk.api.share: // BaseResponse, VersionCheckHandler public class ProvideMessageForWeiboResponse extends BaseResponse { public WeiboMessage message; public ProvideMessageForWeiboResponse() { } public ProvideMessageForWeiboResponse(Bundle bundle) { fromBundle(bundle); } final boolean check(Context context, VersionCheckHandler versioncheckhandler) { if (message != null) goto _L2; else goto _L1 _L1: return false; _L2: if (versioncheckhandler == null) { break; /* Loop/switch isn't completed */ } versioncheckhandler.setPackageName(reqPackageName); if (!versioncheckhandler.check(context, message)) goto _L1; else goto _L3 _L3: return message.checkArgs(); } public void fromBundle(Bundle bundle) { super.fromBundle(bundle); message = new WeiboMessage(bundle); } public int getType() { return 2; } public void toBundle(Bundle bundle) { super.toBundle(bundle); bundle.putAll(message.toBundle(bundle)); } }
3e121ea73ff6eaec0f64569a4f799f7bc4946d9c
11,006
java
Java
src/test/java/fr/qparis/romeo/sql/HSQLManagerTest.java
qparis/romeo
05e0be73be3de0e4225ff5cd1517dbfe2ed9586e
[ "MIT" ]
2
2017-02-04T16:07:07.000Z
2020-10-24T21:15:51.000Z
src/test/java/fr/qparis/romeo/sql/HSQLManagerTest.java
qparis/romeo
05e0be73be3de0e4225ff5cd1517dbfe2ed9586e
[ "MIT" ]
null
null
null
src/test/java/fr/qparis/romeo/sql/HSQLManagerTest.java
qparis/romeo
05e0be73be3de0e4225ff5cd1517dbfe2ed9586e
[ "MIT" ]
null
null
null
36.203947
168
0.545248
7,636
package fr.qparis.romeo.sql; import fr.qparis.romeo.excel.ExcelColumn; import fr.qparis.romeo.excel.ExcelContent; import fr.qparis.romeo.excel.ExcelWorkbook; import fr.qparis.romeo.excel.ExcelWorksheet; import org.junit.Test; import java.math.BigDecimal; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; public class HSQLManagerTest { private final Connection connection = DriverManager.getConnection("jdbc:hsqldb:mem:mymemdb;sql.syntax_pgs=true", "SA", ""); private final HSQLManager hsqlManager = new HSQLManager(connection); public HSQLManagerTest() throws SQLException { } @Test public void testInitializeDatabase_onlyStrings() throws SQLException { ExcelWorkbook workbook = initializeWorkbookWith( Arrays.asList("Col1", "Col2"), Arrays.asList( Arrays.asList("A", "B"), Arrays.asList("C", "D") ) ); hsqlManager.initializeDatabase( workbook, throwable -> { throw new IllegalStateException(throwable); } ); assertEquals(2L, hsqlManager.executeQuery("SELECT count(*) FROM MyWorkbook.MyWorksheet").getResults().get(0).get("C1")); } @Test public void testInitializeDatabase_onlyNumbers() throws SQLException { ExcelWorkbook workbook = initializeWorkbookWith( Arrays.asList("Col1", "Col2"), Arrays.asList( Arrays.asList(1, 2), Arrays.asList(3, 4) ) ); hsqlManager.initializeDatabase( workbook, throwable -> { throw new IllegalStateException(throwable); } ); assertEquals(2L, hsqlManager.executeQuery("SELECT count(*) FROM MyWorkbook.MyWorksheet").getResults().get(0).get("C1")); } @Test public void testInitializeDatabase_onlyNumbers_whereEqualStatement() throws SQLException { ExcelWorkbook workbook = initializeWorkbookWith( Arrays.asList("Col1", "Col2"), Arrays.asList( Arrays.asList(1, 2), Arrays.asList(1, 4), Arrays.asList(1, 5), Arrays.asList(2, 4) ) ); hsqlManager.initializeDatabase( workbook, throwable -> { throw new IllegalStateException(throwable); } ); assertEquals(3L, hsqlManager.executeQuery("SELECT count(*) FROM MyWorkbook.MyWorksheet WHERE Col1 = 1").getResults().get(0).get("C1")); } @Test public void testInitializeDatabase_onlyNumbers_whereComparisonStatement() throws SQLException { ExcelWorkbook workbook = initializeWorkbookWith( Arrays.asList("Col1", "Col2"), Arrays.asList( Arrays.asList(1, 2), Arrays.asList(2, 4), Arrays.asList(3, 5), Arrays.asList(4, 4), Arrays.asList(1, 4), Arrays.asList(2, 4), Arrays.asList(-1, 4) ) ); hsqlManager.initializeDatabase( workbook, throwable -> { throw new IllegalStateException(throwable); } ); assertEquals(5L, hsqlManager.executeQuery("SELECT count(*) FROM MyWorkbook.MyWorksheet WHERE Col1 <= 2").getResults().get(0).get("C1")); } @Test public void testInitializeDatabase_onlyNumbers_largeDataSet() throws SQLException { final List<Object> largeListOrder = new ArrayList<>(); final List<List<Object>> largeListReverseOrder = new ArrayList<>(); for (int i = 0; i < 100_000; i++) { largeListOrder.add(new BigDecimal(i)); largeListReverseOrder.add(Collections.singletonList(i)); } ExcelWorkbook workbook = initializeWorkbookWith( Collections.singletonList("Col1"), largeListReverseOrder ); hsqlManager.initializeDatabase( workbook, throwable -> { throw new IllegalStateException(throwable); } ); final List<Object> col1 = collectColumn(hsqlManager.executeQuery("SELECT * FROM MyWorkbook.MyWorksheet ORDER BY Col1 ASC") .getResults(), "COL1"); assertListEquals(largeListOrder, col1); } @Test public void testInitializeDatabase_onlyDate_largeDataSet() throws SQLException { final List<List<Object>> largeListReverseOrder = new ArrayList<>(); for (int i = 0; i < 100_000; i++) { largeListReverseOrder.add(Arrays.asList(new BigDecimal(i), new Date(91, 5, 26))); } ExcelWorkbook workbook = initializeWorkbookWith( Arrays.asList("Col1", "Col2"), largeListReverseOrder ); hsqlManager.initializeDatabase( workbook, throwable -> { throw new IllegalStateException(throwable); } ); final List<Object> years = collectColumn(hsqlManager.executeQuery("SELECT COL1, COL2, YEAR(COL2) as YEARS FROM MyWorkbook.MyWorksheet ORDER BY YEAR(COL2) DESC") .getResults(), "YEARS"); assertEquals(1991, years.get(0)); } @Test public void testInitializeDatabase_onlyNumbers_whereIntegerComparisonStatement() throws SQLException { ExcelWorkbook workbook = initializeWorkbookWith( Arrays.asList("Col1", "Col2"), Arrays.asList( Arrays.asList(1, 2), Arrays.asList(10, 4), Arrays.asList(11, 5), Arrays.asList(2, 4), Arrays.asList(3, 4), Arrays.asList(4, 4), Arrays.asList(5, 4) ) ); hsqlManager.initializeDatabase( workbook, throwable -> { throw new IllegalStateException(throwable); } ); assertEquals(2L, hsqlManager.executeQuery("SELECT count(*) FROM MyWorkbook.MyWorksheet WHERE Col1 <= 2").getResults().get(0).get("C1")); } @Test public void testInitializeDatabase_onlyNumbers_orberByCorrect() throws SQLException { ExcelWorkbook workbook = initializeWorkbookWith( Arrays.asList("Col1", "Col2"), Arrays.asList( Arrays.asList(1, 2), Arrays.asList(10, 4), Arrays.asList(11, 5), Arrays.asList(2, 4), Arrays.asList(3, 4), Arrays.asList(4, 4), Arrays.asList(5, 4) ) ); hsqlManager.initializeDatabase( workbook, throwable -> { throw new IllegalStateException(throwable); } ); final List<Object> col1 = collectColumn(hsqlManager.executeQuery("SELECT * FROM MyWorkbook.MyWorksheet ORDER BY Col1 ASC") .getResults(), "COL1"); assertListEquals(Stream.of(1, 2, 3, 4, 5, 10, 11).map(BigDecimal::new).collect(Collectors.toList()), col1); } @Test public void testInitializeDatabase_mixOfNumberAndStrings_orberByAlphaNumerical() throws SQLException { ExcelWorkbook workbook = initializeWorkbookWith( Arrays.asList("Col1", "Col2"), Arrays.asList( Arrays.asList(1, 2), Arrays.asList(10, 4), Arrays.asList(11, 5), Arrays.asList(2, 4), Arrays.asList(3, 4), Arrays.asList(4, 4), Arrays.asList(5, 4), Arrays.asList("a", 10) ) ); hsqlManager.initializeDatabase( workbook, throwable -> { throw new IllegalStateException(throwable); } ); final List<Object> col1 = collectColumn(hsqlManager.executeQuery("SELECT * FROM MyWorkbook.MyWorksheet ORDER BY Col1 ASC") .getResults(), "COL1"); assertListEquals(Stream.of("1", "10", "11", "2", "3", "4", "5", "a").collect(Collectors.toList()), col1); } @Test public void testInitializeDatabase_withOneDate_canExtractItsYear() throws SQLException { ExcelWorkbook workbook = initializeWorkbookWith( Arrays.asList("Col1"), Arrays.asList( Arrays.asList(new Date(91, 5, 26)) ) ); hsqlManager.initializeDatabase( workbook, throwable -> { throw new IllegalStateException(throwable); } ); final List<Object> years = collectColumn(hsqlManager.executeQuery("SELECT COL1, YEAR(COL1) as YEARS" + " FROM MyWorkbook.MyWorksheet ORDER BY Col1 ASC") .getResults(), "YEARS"); assertEquals(1991, years.get(0)); } private void assertListEquals(List<Object> l1, List<Object> l2) { assertEquals(l1.size(), l2.size()); for (int i = 0; i < l1.size(); i++) { if(l1.get(i) instanceof BigDecimal && l2.get(i) instanceof BigDecimal) { assertEquals(((BigDecimal) l1.get(i)).toPlainString(), ((BigDecimal) l2.get(i)).toPlainString()); } else { assertEquals(l1.get(i), l2.get(i)); } } } private List<Object> collectColumn(List<Map<String, Object>> results, String columnName) { final List<Object> collected = new ArrayList<>(); for (Map<String, Object> result : results) { collected.add(result.get(columnName)); } return collected; } private ExcelWorkbook initializeWorkbookWith(List<String> columns, List<List<Object>> data) { ExcelWorkbook workbook = new ExcelWorkbook("MyWorkbook", null, Arrays.asList( new ExcelWorksheet("MyWorksheet", "MyWorkbook.MyWorksheet", columns.stream().map(ExcelColumn::new).collect(Collectors.toList()), null ) ) ); workbook.getWorksheets().get(0).setContent( new ExcelContent( columns, data ) ); return workbook; } }
3e121eb1507290f0326504787c468e720d7aa3d7
2,397
java
Java
javar/jdk8-analysis/src/com/sun/xml/internal/org/jvnet/mimepull/FileData.java
vitahlin/kennen
b0de36d3b6e766b59291d885a0699b6be59318a7
[ "MIT" ]
12
2018-04-04T12:47:40.000Z
2022-01-02T04:36:38.000Z
openjdk-8u45-b14/jaxws/src/share/jaxws_classes/com/sun/xml/internal/org/jvnet/mimepull/FileData.java
ams-ts-ikvm-bag/ikvm-src
60009f5bdb4c9db68121f393b8b4c790a326bd32
[ "Zlib" ]
2
2020-07-19T08:29:50.000Z
2020-07-21T01:20:56.000Z
openjdk-8u45-b14/jaxws/src/share/jaxws_classes/com/sun/xml/internal/org/jvnet/mimepull/FileData.java
ams-ts-ikvm-bag/ikvm-src
60009f5bdb4c9db68121f393b8b4c790a326bd32
[ "Zlib" ]
1
2020-11-04T07:02:06.000Z
2020-11-04T07:02:06.000Z
30.341772
79
0.680434
7,637
/* * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.xml.internal.org.jvnet.mimepull; import java.nio.ByteBuffer; /** * Keeps the Part's partial content data in a file. * * @author Kohsuke Kawaguchi * @author Jitendra Kotamraju */ final class FileData implements Data { private final DataFile file; private final long pointer; // read position private final int length; FileData(DataFile file, ByteBuffer buf) { this(file, file.writeTo(buf.array(), 0, buf.limit()), buf.limit()); } FileData(DataFile file, long pointer, int length) { this.file = file; this.pointer = pointer; this.length = length; } @Override public byte[] read() { byte[] buf = new byte[length]; file.read(pointer, buf, 0, length); return buf; } /* * This shouldn't be called */ @Override public long writeTo(DataFile file) { throw new IllegalStateException(); } @Override public int size() { return length; } /* * Always create FileData */ @Override public Data createNext(DataHead dataHead, ByteBuffer buf) { return new FileData(file, buf); } }
3e121f7866db0b40a4fc60af235bf689a5c6ccc7
847
java
Java
app/src/main/java/org/andstatus/app/graphics/CacheName.java
xcorail/andstatus
63d53380291b5f46e868b9d604b92008910e09c3
[ "Apache-2.0" ]
null
null
null
app/src/main/java/org/andstatus/app/graphics/CacheName.java
xcorail/andstatus
63d53380291b5f46e868b9d604b92008910e09c3
[ "Apache-2.0" ]
null
null
null
app/src/main/java/org/andstatus/app/graphics/CacheName.java
xcorail/andstatus
63d53380291b5f46e868b9d604b92008910e09c3
[ "Apache-2.0" ]
null
null
null
29.206897
75
0.710744
7,638
/* * Copyright (c) 2017 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.graphics; public enum CacheName { ATTACHED_IMAGE("Attached images"), AVATAR("Avatars"); final String title; CacheName(String title) { this.title = title; } }
3e121fa88106819c889f232c2a2df5e9179fe9d0
407
java
Java
src/main/java/io/github/thiagolvlsantos/json/predicate/value/impl/PredicateNotEquals.java
thiagolvlsantos/json-predicate
b32c2cd00bb8d7af6b0877f3461d30e5d5925fbc
[ "Apache-2.0" ]
1
2021-06-30T09:48:47.000Z
2021-06-30T09:48:47.000Z
src/main/java/io/github/thiagolvlsantos/json/predicate/value/impl/PredicateNotEquals.java
thiagolvlsantos/json-predicate
b32c2cd00bb8d7af6b0877f3461d30e5d5925fbc
[ "Apache-2.0" ]
null
null
null
src/main/java/io/github/thiagolvlsantos/json/predicate/value/impl/PredicateNotEquals.java
thiagolvlsantos/json-predicate
b32c2cd00bb8d7af6b0877f3461d30e5d5925fbc
[ "Apache-2.0" ]
null
null
null
23.941176
72
0.783784
7,639
package io.github.thiagolvlsantos.json.predicate.value.impl; import com.fasterxml.jackson.databind.JsonNode; import io.github.thiagolvlsantos.json.predicate.IAccess; public class PredicateNotEquals extends PredicateEquals { public PredicateNotEquals(String key, JsonNode value, IAccess access) { super(key, value, access); } @Override public boolean test(Object t) { return !super.test(t); } }
3e121faf308a050ca7465b9fca5ee626903b4ad6
7,999
java
Java
ExtractedJars/Ibotta_com.ibotta.android/javafiles/com/digits/sdk/android/CountryListSpinner$DialogPopup.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
3
2019-05-01T09:22:08.000Z
2019-07-06T22:21:59.000Z
ExtractedJars/Ibotta_com.ibotta.android/javafiles/com/digits/sdk/android/CountryListSpinner$DialogPopup.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
null
null
null
ExtractedJars/Ibotta_com.ibotta.android/javafiles/com/digits/sdk/android/CountryListSpinner$DialogPopup.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
1
2020-11-26T12:22:02.000Z
2020-11-26T12:22:02.000Z
39.210784
210
0.579447
7,640
// 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.digits.sdk.android; import android.app.AlertDialog; import android.content.DialogInterface; import android.widget.ListView; // Referenced classes of package com.digits.sdk.android: // CountryListSpinner, CountryListAdapter, CountryInfo public class CountryListSpinner$DialogPopup implements android.content. { public void dismiss() { AlertDialog alertdialog = dialog; // 0 0:aload_0 // 1 1:getfield #30 <Field AlertDialog dialog> // 2 4:astore_1 if(alertdialog != null) //* 3 5:aload_1 //* 4 6:ifnull 18 { alertdialog.dismiss(); // 5 9:aload_1 // 6 10:invokevirtual #34 <Method void AlertDialog.dismiss()> dialog = null; // 7 13:aload_0 // 8 14:aconst_null // 9 15:putfield #30 <Field AlertDialog dialog> } // 10 18:return } public boolean isShowing() { AlertDialog alertdialog = dialog; // 0 0:aload_0 // 1 1:getfield #30 <Field AlertDialog dialog> // 2 4:astore_1 return alertdialog != null && alertdialog.isShowing(); // 3 5:aload_1 // 4 6:ifnull 18 // 5 9:aload_1 // 6 10:invokevirtual #38 <Method boolean AlertDialog.isShowing()> // 7 13:ifeq 18 // 8 16:iconst_1 // 9 17:ireturn // 10 18:iconst_0 // 11 19:ireturn } public void onClick(DialogInterface dialoginterface, int i) { dialoginterface = ((DialogInterface) ((CountryInfo)listAdapter.getItem(i))); // 0 0:aload_0 // 1 1:getfield #26 <Field CountryListAdapter listAdapter> // 2 4:iload_2 // 3 5:invokevirtual #46 <Method Object CountryListAdapter.getItem(int)> // 4 8:checkcast #48 <Class CountryInfo> // 5 11:astore_1 CountryListSpinner.access$002(CountryListSpinner.this, ((CountryInfo) (dialoginterface)).country); // 6 12:aload_0 // 7 13:getfield #21 <Field CountryListSpinner this$0> // 8 16:aload_1 // 9 17:getfield #52 <Field String CountryInfo.country> // 10 20:invokestatic #56 <Method String CountryListSpinner.access$002(CountryListSpinner, String)> // 11 23:pop CountryListSpinner.access$100(CountryListSpinner.this, ((CountryInfo) (dialoginterface)).countryCode, ((CountryInfo) (dialoginterface)).country); // 12 24:aload_0 // 13 25:getfield #21 <Field CountryListSpinner this$0> // 14 28:aload_1 // 15 29:getfield #60 <Field int CountryInfo.countryCode> // 16 32:aload_1 // 17 33:getfield #52 <Field String CountryInfo.country> // 18 36:invokestatic #64 <Method void CountryListSpinner.access$100(CountryListSpinner, int, String)> dismiss(); // 19 39:aload_0 // 20 40:invokevirtual #65 <Method void dismiss()> // 21 43:return } public void show(final int selected) { if(listAdapter == null) //* 0 0:aload_0 //* 1 1:getfield #26 <Field CountryListAdapter listAdapter> //* 2 4:ifnonnull 8 { return; // 3 7:return } else { dialog = (new android.app.AlertDialog.Builder(getContext())).setSingleChoiceItems(((android.widget.ListAdapter) (listAdapter)), 0, ((android.content.) (this))).create(); // 4 8:aload_0 // 5 9:new #69 <Class android.app.AlertDialog$Builder> // 6 12:dup // 7 13:aload_0 // 8 14:getfield #21 <Field CountryListSpinner this$0> // 9 17:invokevirtual #73 <Method android.content.Context CountryListSpinner.getContext()> // 10 20:invokespecial #76 <Method void android.app.AlertDialog$Builder(android.content.Context)> // 11 23:aload_0 // 12 24:getfield #26 <Field CountryListAdapter listAdapter> // 13 27:iconst_0 // 14 28:aload_0 // 15 29:invokevirtual #80 <Method android.app.AlertDialog$Builder android.app.AlertDialog$Builder.setSingleChoiceItems(android.widget.ListAdapter, int, android.content.DialogInterface$OnClickListener)> // 16 32:invokevirtual #84 <Method AlertDialog android.app.AlertDialog$Builder.create()> // 17 35:putfield #30 <Field AlertDialog dialog> dialog.setCanceledOnTouchOutside(true); // 18 38:aload_0 // 19 39:getfield #30 <Field AlertDialog dialog> // 20 42:iconst_1 // 21 43:invokevirtual #88 <Method void AlertDialog.setCanceledOnTouchOutside(boolean)> final ListView listView = dialog.getListView(); // 22 46:aload_0 // 23 47:getfield #30 <Field AlertDialog dialog> // 24 50:invokevirtual #92 <Method ListView AlertDialog.getListView()> // 25 53:astore_2 listView.setFastScrollEnabled(true); // 26 54:aload_2 // 27 55:iconst_1 // 28 56:invokevirtual #97 <Method void ListView.setFastScrollEnabled(boolean)> listView.postDelayed(new Runnable() { public void run() { listView.setSelection(selected); // 0 0:aload_0 // 1 1:getfield #26 <Field ListView val$listView> // 2 4:aload_0 // 3 5:getfield #28 <Field int val$selected> // 4 8:invokevirtual #38 <Method void ListView.setSelection(int)> // 5 11:return } final CountryListSpinner.DialogPopup this$1; final ListView val$listView; final int val$selected; { this$1 = CountryListSpinner.DialogPopup.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #24 <Field CountryListSpinner$DialogPopup this$1> listView = listview; // 3 5:aload_0 // 4 6:aload_2 // 5 7:putfield #26 <Field ListView val$listView> selected = i; // 6 10:aload_0 // 7 11:iload_3 // 8 12:putfield #28 <Field int val$selected> super(); // 9 15:aload_0 // 10 16:invokespecial #31 <Method void Object()> // 11 19:return } } , 10L); // 29 59:aload_2 // 30 60:new #11 <Class CountryListSpinner$DialogPopup$1> // 31 63:dup // 32 64:aload_0 // 33 65:aload_2 // 34 66:iload_1 // 35 67:invokespecial #100 <Method void CountryListSpinner$DialogPopup$1(CountryListSpinner$DialogPopup, ListView, int)> // 36 70:ldc2w #101 <Long 10L> // 37 73:invokevirtual #106 <Method boolean ListView.postDelayed(Runnable, long)> // 38 76:pop dialog.show(); // 39 77:aload_0 // 40 78:getfield #30 <Field AlertDialog dialog> // 41 81:invokevirtual #108 <Method void AlertDialog.show()> return; // 42 84:return } } private AlertDialog dialog; private final CountryListAdapter listAdapter; final CountryListSpinner this$0; CountryListSpinner$DialogPopup(CountryListAdapter countrylistadapter) { this$0 = CountryListSpinner.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #21 <Field CountryListSpinner this$0> super(); // 3 5:aload_0 // 4 6:invokespecial #24 <Method void Object()> listAdapter = countrylistadapter; // 5 9:aload_0 // 6 10:aload_2 // 7 11:putfield #26 <Field CountryListAdapter listAdapter> // 8 14:return } }
3e12205555f029940bb11fee939d031f57913156
218
java
Java
src/abench/function/NLogSqrNFunction.java
rafalrusin/abench
4c4fd4905909c0456f10cb57287f8c0d6289c7e9
[ "Apache-2.0" ]
null
null
null
src/abench/function/NLogSqrNFunction.java
rafalrusin/abench
4c4fd4905909c0456f10cb57287f8c0d6289c7e9
[ "Apache-2.0" ]
null
null
null
src/abench/function/NLogSqrNFunction.java
rafalrusin/abench
4c4fd4905909c0456f10cb57287f8c0d6289c7e9
[ "Apache-2.0" ]
null
null
null
19.818182
54
0.674312
7,641
package abench.function; import abench.core.Function; public class NLogSqrNFunction implements Function { @Override public float eval(float x) { return (float) (Math.pow(Math.log(x), 2) * x); } }
3e1221031c53aa129920bfb429cf83086d95fbdb
10,428
java
Java
src/main/java/de/linus/deepltranslator/DeepLTranslatorBase.java
Linus789/DeepLTranslator
c9627002d8ff2979392402df6b072c8cd98e723e
[ "Apache-2.0" ]
49
2018-07-27T08:32:50.000Z
2022-03-19T09:40:19.000Z
src/main/java/de/linus/deepltranslator/DeepLTranslatorBase.java
Linus789/DeepLTranslator
c9627002d8ff2979392402df6b072c8cd98e723e
[ "Apache-2.0" ]
10
2018-10-05T04:10:42.000Z
2021-08-25T09:27:26.000Z
src/main/java/de/linus/deepltranslator/DeepLTranslatorBase.java
Linus789/DeepLTranslator
c9627002d8ff2979392402df6b072c8cd98e723e
[ "Apache-2.0" ]
21
2018-06-28T21:47:40.000Z
2022-03-17T20:31:07.000Z
37.242857
131
0.607691
7,642
package de.linus.deepltranslator; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; /** * API for the DeepL Translator */ class DeepLTranslatorBase { /** * For asynchronous translating. * * @see DeepLTranslator#translateAsync(String, SourceLanguage, TargetLanguage) */ final ExecutorService executor = Executors.newCachedThreadPool(); /** * All executors used for asynchronous translating. */ static final List<ExecutorService> EXECUTOR_LIST = new ArrayList<>(); /** * For cleaning up the input field on the DeepL site. * * @see DeepLTranslator#translate(String, SourceLanguage, TargetLanguage) */ static final ExecutorService CLEANUP_EXECUTOR = Executors.newCachedThreadPool(); /** * All browser instances created. */ static final List<WebDriver> GLOBAL_INSTANCES = new ArrayList<>(); /** * Available browser instances for this configuration. */ private static final LinkedBlockingQueue<WebDriver> AVAILABLE_INSTANCES = new LinkedBlockingQueue<>(); /** * User-Agent for WebDriver. */ private static final String USER_AGENT; /** * Script to disable animations on a website. * <p> * Source: https://github.com/dcts/remove-CSS-animations */ private static final String DISABLE_ANIMATIONS_SCRIPT = "document.querySelector('html > head').insertAdjacentHTML(\"beforeend\", \"" + "<style>\\n" + "* {\\n" + " -o-transition-property: none !important;\\n" + " -moz-transition-property: none !important;\\n" + " -ms-transition-property: none !important;\\n" + " -webkit-transition-property: none !important;\\n" + " transition-property: none !important;\\n" + "}\\n" + "* {\\n" + " -o-transform: none !important;\\n" + " -moz-transform: none !important;\\n" + " -ms-transform: none !important;\\n" + " -webkit-transform: none !important;\\n" + " transform: none !important;\\n" + "}\\n" + "* {\\n" + " -webkit-animation: none !important;\\n" + " -moz-animation: none !important;\\n" + " -o-animation: none !important;\\n" + " -ms-animation: none !important;\\n" + " animation: none !important;\\n" + "}\\n" + "</style>\\n" + "\");"; /** * For debugging purposes. */ public static boolean HEADLESS = true; static { // Set default user agent ChromeDriver dummyDriver = newWebDriver(); String userAgent = (String) dummyDriver.executeScript("return navigator.userAgent"); USER_AGENT = userAgent.replace("HeadlessChrome", "Chrome"); dummyDriver.close(); } /** * All settings. */ private final DeepLConfiguration configuration; /** * With default settings. */ DeepLTranslatorBase() { this.configuration = new DeepLConfiguration.Builder().build(); EXECUTOR_LIST.add(executor); } /** * With custom settings. */ DeepLTranslatorBase(DeepLConfiguration configuration) { this.configuration = configuration; EXECUTOR_LIST.add(executor); } /** * Checks if all arguments are valid, if not, an exception is thrown. */ void isValid(String text, SourceLanguage from, TargetLanguage to) throws IllegalStateException { if(text == null || text.trim().isEmpty()) { throw new IllegalStateException("Text is null or empty"); } else if(from == null || to == null) { throw new IllegalStateException("Language is null"); } else if(text.length() > 5000) { throw new IllegalStateException("Text length is limited to 5000 characters"); } } /** * Generates a request with all settings like timeout etc. * and returns the translation if succeeded. */ String getTranslation(String text, SourceLanguage from, TargetLanguage to) throws TimeoutException { long timeoutMillisEnd = System.currentTimeMillis() + configuration.getTimeout().toMillis(); WebDriver driver = AVAILABLE_INSTANCES.poll(); try { if (driver == null) { driver = newWebDriver(); driver.manage().timeouts().pageLoadTimeout(Duration.ofMillis(timeoutMillisEnd - System.currentTimeMillis())); GLOBAL_INSTANCES.add(driver); driver.get("https://www.deepl.com/translator"); ((ChromeDriver) driver).executeScript(DISABLE_ANIMATIONS_SCRIPT); } } catch (TimeoutException e) { GLOBAL_INSTANCES.remove(driver); driver.close(); throw e; } try { // Source language button driver.findElements(By.className("lmt__language_select__active")).get(0).click(); By srcButtonBy = By.xpath("//button[@dl-test='" + from.getAttributeValue() + "']"); WebDriverWait waitSource = new WebDriverWait(driver, Duration.ofMillis(timeoutMillisEnd - System.currentTimeMillis())); waitSource.until(ExpectedConditions.visibilityOfElementLocated(srcButtonBy)); driver.findElement(srcButtonBy).click(); // Target language button driver.findElements(By.className("lmt__language_select__active")).get(1).click(); By targetButtonBy = By.xpath("//button[@dl-test='" + to.getAttributeValue() + "']"); WebDriverWait waitTarget = new WebDriverWait(driver, Duration.ofMillis(timeoutMillisEnd - System.currentTimeMillis())); waitTarget.until(ExpectedConditions.visibilityOfElementLocated(targetButtonBy)); driver.findElement(targetButtonBy).click(); } catch (TimeoutException e) { AVAILABLE_INSTANCES.offer(driver); throw e; } String result = null; TimeoutException timeoutException = null; By targetTextBy = By.id("target-dummydiv"); try { // Source text driver.findElement(By.className("lmt__source_textarea")).sendKeys(text); // Target text WebDriverWait waitText = new WebDriverWait(driver, Duration.ofMillis(timeoutMillisEnd - System.currentTimeMillis())); waitText.pollingEvery(Duration.ofMillis(100)); ExpectedCondition<Boolean> textCondition; if (text.contains("[...]")) { textCondition = ExpectedConditions.and( DriverWaitUtils.attributeNotBlank(targetTextBy, "innerHTML"), DriverWaitUtils.attributeNotChanged(targetTextBy, "innerHTML", Duration.ofMillis(1000)) ); } else { textCondition = ExpectedConditions.and( DriverWaitUtils.attributeNotBlank(targetTextBy, "innerHTML"), DriverWaitUtils.attributeNotContains(targetTextBy, "innerHTML", "[...]"), DriverWaitUtils.attributeNotChanged(targetTextBy, "innerHTML", Duration.ofMillis(1000)) ); } waitText.until(textCondition); result = driver.findElement(targetTextBy).getAttribute("innerHTML"); } catch (TimeoutException e) { timeoutException = e; } WebDriver finalDriver = driver; CLEANUP_EXECUTOR.submit(() -> { By buttonClearBy = By.className("lmt__clear_text_button"); By sourceText = By.id("source-dummydiv"); try { finalDriver.findElement(buttonClearBy).click(); } catch (NoSuchElementException ignored) {} WebDriverWait waitCleared = new WebDriverWait(finalDriver, Duration.ofSeconds(10)); try { waitCleared.until(ExpectedConditions.and( DriverWaitUtils.attributeBlank(sourceText, "innerHTML"), DriverWaitUtils.attributeBlank(targetTextBy, "innerHTML") )); AVAILABLE_INSTANCES.offer(finalDriver); } catch (TimeoutException e) { GLOBAL_INSTANCES.remove(finalDriver); finalDriver.close(); } }); if (timeoutException != null) throw timeoutException; // Post-processing if(result != null && configuration.isPostProcessingEnabled()) { result = result .trim() .replaceAll("\\s{2,}", " "); } return result; } /** * The settings. */ public DeepLConfiguration getConfiguration() { return configuration; } /** * Create new WebDriver instance. */ private static ChromeDriver newWebDriver() { ChromeOptions options = new ChromeOptions(); if (HEADLESS) { options.addArguments("--headless"); } options.addArguments("--disable-gpu", "--window-size=1920,1080"); options.addArguments("--disable-blink-features=AutomationControlled"); if (USER_AGENT != null) { options.addArguments("--user-agent=" + USER_AGENT); } ChromeDriver driver = new ChromeDriver(options); driver.executeScript("Object.defineProperty(screen, 'height', {value: 1080, configurable: true, writeable: true});"); driver.executeScript("Object.defineProperty(screen, 'width', {value: 1920, configurable: true, writeable: true});"); driver.executeScript("Object.defineProperty(screen, 'availWidth', {value: 1920, configurable: true, writeable: true});"); driver.executeScript("Object.defineProperty(screen, 'availHeight', {value: 1080, configurable: true, writeable: true});"); return driver; } }
3e12216986ab0aaca79cf6873b8d6d5fb94b2010
499
java
Java
src/main/java/org/tensa/tensada/matrix/ParOrdenado.java
marceloftorresvega/tensada
5ba37d94b4ff8d3b3e7a0544e5c8651ebfe0300f
[ "MIT" ]
null
null
null
src/main/java/org/tensa/tensada/matrix/ParOrdenado.java
marceloftorresvega/tensada
5ba37d94b4ff8d3b3e7a0544e5c8651ebfe0300f
[ "MIT" ]
3
2020-02-28T15:33:48.000Z
2021-03-15T15:09:47.000Z
src/main/java/org/tensa/tensada/matrix/ParOrdenado.java
marceloftorresvega/tensada
5ba37d94b4ff8d3b3e7a0544e5c8651ebfe0300f
[ "MIT" ]
null
null
null
14.676471
51
0.58517
7,643
package org.tensa.tensada.matrix; import java.io.Serializable; /** * * @author mtorres */ public interface ParOrdenado extends Serializable { @Override boolean equals(Object obj); /** * Get the value of columna * * @return the value of columna */ Integer getColumna(); /** * Get the value of fila * * @return the value of fila */ Integer getFila(); @Override int hashCode(); ParOrdenado transpuesta(); }
3e1222807fd261547ff520ca613d801791c10046
1,029
java
Java
src/test/java/com/wesabe/grendel/util/tests/HashCodeTest.java
aellerton/grendel
fcb5a242a8d81b2e4ca123aa94e0be85da0fad64
[ "MIT" ]
20
2015-04-22T01:58:16.000Z
2019-05-01T15:31:15.000Z
src/test/java/com/wesabe/grendel/util/tests/HashCodeTest.java
aellerton/grendel
fcb5a242a8d81b2e4ca123aa94e0be85da0fad64
[ "MIT" ]
null
null
null
src/test/java/com/wesabe/grendel/util/tests/HashCodeTest.java
aellerton/grendel
fcb5a242a8d81b2e4ca123aa94e0be85da0fad64
[ "MIT" ]
6
2016-01-09T22:00:31.000Z
2019-05-08T05:33:38.000Z
28.583333
90
0.718173
7,644
package com.wesabe.grendel.util.tests; import static org.fest.assertions.Assertions.*; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import com.wesabe.grendel.util.HashCode; @RunWith(Enclosed.class) public class HashCodeTest { public static class Calculating_A_Hash_Code { @Test public void itHandlesNullValues() throws Exception { assertThat(HashCode.calculate(null, null)).isEqualTo(961); assertThat(HashCode.calculate(null, null, null)).isEqualTo(29791); } @Test public void itHandlesArrays() throws Exception { assertThat(HashCode.calculate(null, new int[] { 1, 2, 3 })).isEqualTo(31778); assertThat(HashCode.calculate(null, new int[] { 1, 2, 4 })).isEqualTo(31779); } @Test public void itHandlesObjects() throws Exception { assertThat(HashCode.calculate(null, new int[] { 1, 2, 3 }, "blah")).isEqualTo(4011535); assertThat(HashCode.calculate(null, new int[] { 1, 2, 3 }, "blar")).isEqualTo(4011545); } } }
3e12235c12449ce8b57f07072e3ac3a7a02f571c
691
java
Java
src/main/java/jp/ac/nii/prl/mape/kb/properties/HaskellProperties.java
prl-tokyo/MAPE-knowledge-base-service
5add55a229cdb569d4499e498e0af3acd805c663
[ "MIT" ]
null
null
null
src/main/java/jp/ac/nii/prl/mape/kb/properties/HaskellProperties.java
prl-tokyo/MAPE-knowledge-base-service
5add55a229cdb569d4499e498e0af3acd805c663
[ "MIT" ]
3
2016-04-12T05:35:08.000Z
2016-04-13T05:08:51.000Z
src/main/java/jp/ac/nii/prl/mape/kb/properties/HaskellProperties.java
prl-tokyo/MAPE-knowledge-base-service
5add55a229cdb569d4499e498e0af3acd805c663
[ "MIT" ]
null
null
null
18.675676
75
0.758321
7,645
package jp.ac.nii.prl.mape.kb.properties; import javax.validation.Valid; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @ConfigurationProperties("app.haskell") @Component public class HaskellProperties { @NotEmpty @Valid private String executable = ""; @NotEmpty @Valid private String path = ""; public String getExecutable() { return executable; } public String getPath() { return path; } public void setExecutable(String executable) { this.executable = executable; } public void setPath(String path) { this.path = path; } }
3e12238b2b897f05602a3ae0def5a717b0b1e41a
1,737
java
Java
src/main/java/org/atlasapi/remotesite/health/ScheduleLivenessHealthController.java
atlasapi/atlas
ab0f7c2e27e0c9819ec6cd6109efcc7492332115
[ "Apache-2.0" ]
14
2015-02-24T15:07:41.000Z
2022-03-23T11:06:55.000Z
src/main/java/org/atlasapi/remotesite/health/ScheduleLivenessHealthController.java
atlasapi/atlas
ab0f7c2e27e0c9819ec6cd6109efcc7492332115
[ "Apache-2.0" ]
258
2015-01-06T11:47:58.000Z
2021-12-18T18:32:56.000Z
src/main/java/org/atlasapi/remotesite/health/ScheduleLivenessHealthController.java
atlasapi/atlas
ab0f7c2e27e0c9819ec6cd6109efcc7492332115
[ "Apache-2.0" ]
11
2015-01-01T21:47:14.000Z
2022-03-23T11:06:57.000Z
33.403846
128
0.800806
7,646
package org.atlasapi.remotesite.health; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.metabroadcast.common.media.MimeType; import com.metabroadcast.common.security.HttpBasicAuthChecker; import com.metabroadcast.common.security.UsernameAndPassword; import com.metabroadcast.common.webapp.health.HealthController; @Controller public class ScheduleLivenessHealthController { private HealthController main; private HttpBasicAuthChecker checker; public ScheduleLivenessHealthController(HealthController main, String username, String password) { this.main = main; if (!Strings.isNullOrEmpty(password)) { this.checker = new HttpBasicAuthChecker( ImmutableList.of(new UsernameAndPassword(username, password))); } else { this.checker = null; } } @RequestMapping("health/pa/schedule-liveness") public String scheduleLiveness(HttpServletRequest request, HttpServletResponse response) throws IOException { if (checker == null) { response.setContentType(MimeType.TEXT_PLAIN.toString()); response.getOutputStream().print( "No password set up, health page cannot be viewed"); return null; } boolean allowed = checker.check(request); if (allowed) { return main.showHealthPageForSlugs(response, ImmutableSet.of(ScheduleLivenessHealthProbe.SCHEDULE_HEALTH_PROBE_SLUG), false); } HttpBasicAuthChecker.requestAuth(response, "Heath Page"); return null; } }
3e1224694b4f06f79df6aa5cd86c89a30512d37c
1,787
java
Java
Core/src/main/jaxb/org/openestate/is24/restapi/xml/common/SupplyType.java
OpenEstate/OpenEstate-IS24-REST
b0a5c78f3ac7b8702558f1111571e53b42996b44
[ "Apache-2.0" ]
8
2015-05-11T17:26:34.000Z
2019-01-07T15:20:03.000Z
Core/src/main/jaxb/org/openestate/is24/restapi/xml/common/SupplyType.java
OpenEstate/OpenEstate-IS24-REST
b0a5c78f3ac7b8702558f1111571e53b42996b44
[ "Apache-2.0" ]
12
2015-03-16T15:28:54.000Z
2021-08-15T18:46:02.000Z
Core/src/main/jaxb/org/openestate/is24/restapi/xml/common/SupplyType.java
OpenEstate/OpenEstate-IS24-REST
b0a5c78f3ac7b8702558f1111571e53b42996b44
[ "Apache-2.0" ]
3
2016-09-19T23:39:06.000Z
2021-09-28T13:24:09.000Z
19.215054
111
0.592613
7,647
package org.openestate.is24.restapi.xml.common; import javax.annotation.Generated; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for SupplyType. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="SupplyType"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="NO_INFORMATION"/&gt; * &lt;enumeration value="DIRECT_APPROACH"/&gt; * &lt;enumeration value="NO_DIRECT_APPROACH"/&gt; * &lt;enumeration value="CAR_APPROACH"/&gt; * &lt;enumeration value="APPROACH_TO_THE_FRONT"/&gt; * &lt;enumeration value="APPROACH_TO_THE_BACK"/&gt; * &lt;enumeration value="FULL_TIME"/&gt; * &lt;enumeration value="FORENOON"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "SupplyType") @XmlEnum @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T09:44:49+02:00", comments = "JAXB RI v2.3.0") public enum SupplyType { /** * Keine Angabe * */ NO_INFORMATION, /** * Direkter Zugang * */ DIRECT_APPROACH, /** * Keine direkte Anfahrt * */ NO_DIRECT_APPROACH, /** * PKW-Zufahrt * */ CAR_APPROACH, /** * Anfahrt von vorne * */ APPROACH_TO_THE_FRONT, /** * Anfahrt von hinten * */ APPROACH_TO_THE_BACK, /** * Ganzt\u00e4gig * */ FULL_TIME, /** * Vormittags * */ FORENOON; public String value() { return name(); } public static SupplyType fromValue(String v) { return valueOf(v); } }
3e122537c438fcf0dfb1b5a50ff0ae688c736eab
2,291
java
Java
http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/FutureCancelHandler.java
kellertk/aws-sdk-java-v2
94e7bab182d3e125f723ac4c520046b72b1148ca
[ "Apache-2.0" ]
2
2022-03-02T16:51:16.000Z
2022-03-03T08:27:21.000Z
http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/FutureCancelHandler.java
kellertk/aws-sdk-java-v2
94e7bab182d3e125f723ac4c520046b72b1148ca
[ "Apache-2.0" ]
33
2021-04-15T23:54:55.000Z
2022-03-14T06:15:34.000Z
http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/FutureCancelHandler.java
kellertk/aws-sdk-java-v2
94e7bab182d3e125f723ac4c520046b72b1148ca
[ "Apache-2.0" ]
4
2021-09-17T19:40:01.000Z
2021-09-22T11:49:35.000Z
35.246154
101
0.725447
7,648
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.EXECUTION_ID_KEY; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.REQUEST_CONTEXT_KEY; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import java.io.IOException; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Closes the channel if the execution future has been cancelled. */ @SdkInternalApi @ChannelHandler.Sharable public final class FutureCancelHandler extends ChannelInboundHandlerAdapter { private static final FutureCancelHandler INSTANCE = new FutureCancelHandler(); private FutureCancelHandler() { } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { if (cancelled(ctx, e)) { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); requestContext.handler().onError(e); ctx.fireExceptionCaught(new IOException("Request cancelled")); ctx.close(); requestContext.channelPool().release(ctx.channel()); } else { ctx.fireExceptionCaught(e); } } public static FutureCancelHandler getInstance() { return INSTANCE; } private boolean cancelled(ChannelHandlerContext ctx, Throwable t) { if (!(t instanceof FutureCancelledException)) { return false; } FutureCancelledException e = (FutureCancelledException) t; return e.getExecutionId() == ctx.channel().attr(EXECUTION_ID_KEY).get(); } }
3e1226112f42d9e41feaa311ada19996eab05c2f
347
java
Java
backdoored/client/modules/impl/t.java
RIPBackdoored/Backdoored-1.7-Deobf-Source-Leak
942bb61216fbb47f7909372d5c733e13d103e0ed
[ "MIT" ]
3
2019-11-19T15:30:49.000Z
2020-11-26T18:01:15.000Z
backdoored/client/modules/impl/t.java
RIPBackdoored/Backdoored-1.7-Deobf-Source-Leak
942bb61216fbb47f7909372d5c733e13d103e0ed
[ "MIT" ]
1
2019-11-18T01:05:41.000Z
2019-11-18T23:28:24.000Z
backdoored/client/modules/impl/t.java
RIPBackdoored/Backdoored-1.7-Deobf-Source-Leak
942bb61216fbb47f7909372d5c733e13d103e0ed
[ "MIT" ]
1
2021-06-07T22:14:35.000Z
2021-06-07T22:14:35.000Z
19.277778
49
0.642651
7,649
package l.c.h.j; import java.util.Comparator; class t implements Comparator { public static final boolean fub; public int k(w var1, w var2) { return var1.gw.compareTo(var2.gw); } // $FF: synthetic method // $FF: bridge method public int compare(Object var1, Object var2) { return this.k((w)var1, (w)var2); } }
3e12268caddac0d873e57a7f1e265864291e277f
19,429
java
Java
pushpull/src/main/java/org/apache/oodt/cas/pushpull/daemon/Daemon.java
lewismc/oodt
1ae92425ec3e7e0d0f026cbcc142ab17988cd071
[ "Apache-2.0" ]
null
null
null
pushpull/src/main/java/org/apache/oodt/cas/pushpull/daemon/Daemon.java
lewismc/oodt
1ae92425ec3e7e0d0f026cbcc142ab17988cd071
[ "Apache-2.0" ]
null
null
null
pushpull/src/main/java/org/apache/oodt/cas/pushpull/daemon/Daemon.java
lewismc/oodt
1ae92425ec3e7e0d0f026cbcc142ab17988cd071
[ "Apache-2.0" ]
null
null
null
33.730903
91
0.574193
7,650
/* * 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.oodt.cas.pushpull.daemon; //OODT imports import org.apache.oodt.cas.pushpull.config.Config; import org.apache.oodt.cas.pushpull.config.DaemonInfo; import org.apache.oodt.cas.pushpull.config.SiteInfo; import org.apache.oodt.cas.pushpull.protocol.RemoteSite; import org.apache.oodt.cas.pushpull.retrievalsystem.RetrievalSetup; //JDK imports import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.lang.management.ManagementFactory; import java.net.MalformedURLException; import java.rmi.AlreadyBoundException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.server.UnicastRemoteObject; import java.util.Date; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; //JMX imports import javax.management.MBeanServer; import javax.management.ObjectName; /** * Controls the execution times of the Crawler it is given. The Crawler is * specified by the properties file passed in. A Crawler will be created per the * properties file and executed at six hour intervals. This class can be * controlled by CrawlDaemonController after is has been started up. * * @author bfoster */ public class Daemon extends UnicastRemoteObject implements DaemonRmiInterface, DaemonMBean { private static final long serialVersionUID = 7660972939723142802L; private DaemonListener daemonListener; /* our log stream */ private static final Logger LOG = Logger.getLogger(Daemon.class.getName()); /** * Keeps track of whether the Crawler is running or not */ private boolean isRunning; /** * If set to false the CrawlDaemon will terminate after the Crawler finishes * crawling its current site. */ private boolean keepRunning; /** * The time at which the Constructor is called */ private long daemonCreationTime; /** * The total time during which the Crawl is actually running -- wait() time * is not included. */ private long daemonTotalRuntime; /** * Total number of times the Crawler has been run */ private int numberOfCrawls; private File propFilesDir; private int daemonID; private RetrievalSetup rs; private Config config; private DaemonInfo daemonInfo; private MBeanServer mbs; private int rmiRegPort; /** * Constructor * * @throws RemoteException * @throws RemoteException * @throws InstantiationException * @throws IOException * @throws SecurityException */ public Daemon(int rmiRegPort, int daemonID, Config config, DaemonInfo daemonInfo, SiteInfo siteInfo) throws RemoteException { super(); this.rmiRegPort = rmiRegPort; this.daemonID = daemonID; rs = new RetrievalSetup(config, siteInfo); this.config = config; this.daemonInfo = daemonInfo; daemonCreationTime = System.currentTimeMillis(); daemonTotalRuntime = 0; numberOfCrawls = 0; isRunning = false; try { registerRMIServer(); } catch (Exception e) { LOG.log(Level.SEVERE, "Failed to bind to RMI server : " + e.getMessage()); } try { // registry CrawlDaemon as MBean so it can be used with jconsole mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName( "org.apache.oodt.cas.pushpull.daemon:type=Daemon" + this.getDaemonID()); mbs.registerMBean(this, name); } catch (Exception e) { LOG.log(Level.SEVERE, "Failed to register CrawlDaemon as a MBean Object : " + e.getMessage()); } } public String getName() { return "Daemon" + this.getDaemonID(); } private void registerRMIServer() throws RemoteException { try { Naming.bind("//localhost:" + this.rmiRegPort + "/daemon" + this.getDaemonID(), this); LOG.log(Level.INFO, "Created Daemon ID = " + this.getDaemonID() + " on RMI registry port " + this.rmiRegPort); } catch (Exception e) { LOG.log(Level.SEVERE, e.getMessage()); throw new RemoteException("Failed to bind Daemon with ID = " + this.getDaemonID() + " to RMI registry at port " + this.rmiRegPort); } } public void registerDaemonListener(DaemonListener daemonListener) { this.daemonListener = daemonListener; this.daemonListener.wasRegisteredWith(this); } /** * Loads and executes the Crawler specified by the properties file. It will * crawl the URLs specified in the properties file in the sequence * given--one at a time. * * @throws DirStructException */ public void startDaemon() { new Thread(new Runnable() { public void run() { // check if Daemon should sleep first long timeTilNextRun; if ((timeTilNextRun = Daemon.this.calculateTimeTilNextRun()) != 0 && !(Daemon.this.beforeToday(daemonInfo .getFirstRunDateTime()) && daemonInfo .runOnReboot())) { sleep(timeTilNextRun); } for (keepRunning = true; keepRunning;) { long startTime = System.currentTimeMillis(); // get permission to run Daemon.this.notifyDaemonListenerOfStart(); if (!keepRunning) { Daemon.this.notifyDaemonListenerOfFinish(); System.out.println("BREAKING OUT"); break; } // run Daemon.this.isRunning = true; try { rs.retrieveFiles(daemonInfo.getPropFilesInfo(), daemonInfo.getDataFilesInfo()); } catch (Exception e) { LOG.log(Level.SEVERE, e.getMessage()); } finally { numberOfCrawls++; } Daemon.this.isRunning = false; // calculate performance and sleep Daemon.this.notifyDaemonListenerOfFinish(); Daemon.this.calculateAndStoreElapsedTime(startTime); if (Daemon.this.keepRunning && daemonInfo.getTimeIntervalInMilliseconds() >= 0) { sleep(Daemon.this.calculateTimeTilNextRun()); } else { break; } } LOG.log(Level.INFO, "Daemon with ID = " + Daemon.this.getDaemonID() + " on RMI registry port " + Daemon.this.rmiRegPort + " is shutting down"); Daemon.this.unregister(); } }).start(); } private void unregister() { try { // unregister CrawlDaemon from RMI registry Naming.unbind("//localhost:" + this.rmiRegPort + "/daemon" + this.getDaemonID()); this.mbs.unregisterMBean(new ObjectName( "org.apache.oodt.cas.pushpull.daemon:type=Daemon" + this.getDaemonID())); UnicastRemoteObject.unexportObject(this, true); this.daemonListener.wasUnregisteredWith(this); } catch (Exception e) { LOG.log(Level.SEVERE, e.getMessage()); } } public int getDaemonID() { return Integer.parseInt(this.rmiRegPort + "" + this.daemonID); } private long calculateTimeTilNextRun() { GregorianCalendar now = new GregorianCalendar(); GregorianCalendar gcStartDateTime = new GregorianCalendar(); gcStartDateTime.setTime(daemonInfo.getFirstRunDateTime()); long diff = now.getTimeInMillis() - gcStartDateTime.getTimeInMillis(); if (Math.abs(diff) <= daemonInfo.getEpsilonInMilliseconds()) { return 0; } else if (diff < 0) { return gcStartDateTime.getTimeInMillis() - now.getTimeInMillis(); } else if (daemonInfo.getTimeIntervalInMilliseconds() == 0) { return 0; } else { int numOfPeriods = (int) (diff / daemonInfo .getTimeIntervalInMilliseconds()); long nextRunTime = gcStartDateTime.getTimeInMillis() + ((numOfPeriods + 1) * daemonInfo .getTimeIntervalInMilliseconds()); return nextRunTime - now.getTimeInMillis(); } } private boolean beforeToday(Date date) { return date.before(new Date(System.currentTimeMillis())); } private void notifyDaemonListenerOfStart() { if (this.daemonListener != null) { this.daemonListener.daemonStarting(this); } } private void notifyDaemonListenerOfFinish() { if (this.daemonListener != null) { this.daemonListener.daemonFinished(this); } } private void sleep(long length) { if (length > 0) { LOG.log(Level.INFO, "Daemon with ID = " + this.getDaemonID() + " on RMI registry port " + this.rmiRegPort + " is going to sleep until " + new Date(System.currentTimeMillis() + length)); synchronized (this) { try { wait(length); } catch (InterruptedException ignored) { } } } } private long calculateAndStoreElapsedTime(long startTime) { long elapsedTime = System.currentTimeMillis() - startTime; daemonTotalRuntime += elapsedTime; return elapsedTime; } public synchronized void pauseDaemon() { try { LOG.log(Level.INFO, "Daemon with ID = " + this.getDaemonID() + " on RMI registry port " + this.rmiRegPort + " has been stopped"); this.wait(0); } catch (Exception ignored) { } LOG.log(Level.INFO, "Daemon with ID = " + this.getDaemonID() + " on RMI registry port " + this.rmiRegPort + " has resumed"); } /** * Wakes up the CrawlDaemon if it is sleeping */ public synchronized void resume() { notify(); } /** * Will terminate the CrawlDaemon. If its Crawler is crawling a site when * this method is called, the terminate won't take place until after the * Crawler has complete crawling that site. */ public synchronized void quit() { keepRunning = false; resume(); } /** * Can be used to determine if Crawler is presently running * * @return true if Crawler is runnning * @uml.property name="isRunning" */ public boolean isRunning() { return isRunning; } /** * Average runtime for the Crawler * * @return average runtime for the Crawler */ public long getAverageRunTime() { return daemonTotalRuntime / numberOfCrawls; } /** * Gets the total crawling time of the Crawler * * @return Total crawling time of Crawler */ public long getMillisCrawling() { return daemonTotalRuntime; } /** * Gets the time between the start of Crawler executions * * @return Time interval between Crawler start times */ public long getTimeInterval() { return daemonInfo.getTimeIntervalInMilliseconds(); } /** * Gets the total number of times the Crawler has been run * * @return The number of times Crawler has run */ public int getNumCrawls() { return numberOfCrawls; } public String[] downloadedFilesInStagingArea() { return this.daemonInfo.getDataFilesInfo().getDownloadInfo() .getStagingArea().list(new FilenameFilter() { public boolean accept(File dir, String name) { return !name.startsWith("Downloading_") && !(name.endsWith("info.tmp") || name .endsWith("cas")); } }); } public String[] downloadingFilesInStagingArea() { return this.daemonInfo.getDataFilesInfo().getDownloadInfo() .getStagingArea().list(new FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith("Downloading_") && !(name.endsWith("info.tmp") || name .endsWith("cas")); } }); } public int numberOfFilesDownloadingInStagingArea() { return this.downloadingFilesInStagingArea().length; } public int numberOfFilesDownloadedInStagingArea() { return this.downloadedFilesInStagingArea().length; } // ***************DaemonInfo****************** public long getTimeIntervalInMilliseconds() { return this.daemonInfo.getTimeIntervalInMilliseconds(); } public long getEpsilonInMilliseconds() { return this.daemonInfo.getEpsilonInMilliseconds(); } public boolean getRunOnReboot() { return this.daemonInfo.runOnReboot(); } public Date getFirstRunDateTime() { return this.daemonInfo.getFirstRunDateTime(); } // ***************DaemonInfo****************** // ***************DataFilesInfo******************* public String getDataFilesRemoteSite() { RemoteSite remoteSite = this.daemonInfo.getDataFilesInfo() .getDownloadInfo().getRemoteSite(); return (remoteSite == null) ? "" : remoteSite.toString(); } public String getDataFilesRenamingConv() { return this.daemonInfo.getDataFilesInfo().getDownloadInfo() .getRenamingConv(); } public boolean getDeleteDataFilesFromServer() { return this.daemonInfo.getDataFilesInfo().getDownloadInfo() .deleteFromServer(); } public String getQueryMetadataElementName() { String element = this.daemonInfo.getDataFilesInfo() .getQueryMetadataElementName(); if (element == null || element.equals("")) { element = "Filename"; } return this.daemonInfo.getDataFilesInfo().getQueryMetadataElementName(); } public File getDataFilesStagingArea() { return this.daemonInfo.getDataFilesInfo().getDownloadInfo() .getStagingArea(); } public boolean getAllowAliasOverride() { return this.daemonInfo.getDataFilesInfo().getDownloadInfo() .isAllowAliasOverride(); } // **************DataFilesInfo******************** // **************PropFilesInfo******************** public String getPropertyFilesRemoteSite() { RemoteSite remoteSite = this.daemonInfo.getPropFilesInfo() .getDownloadInfo().getRemoteSite(); return (remoteSite == null) ? "" : remoteSite.toString(); } public String getPropertyFilesRenamingConv() { return this.daemonInfo.getPropFilesInfo().getDownloadInfo() .getRenamingConv(); } public boolean getDeletePropertyFilesFromServer() { return this.daemonInfo.getPropFilesInfo().getDownloadInfo() .deleteFromServer(); } public String getPropertyFilesOnSuccessDir() { File successDir = this.daemonInfo.getPropFilesInfo().getOnSuccessDir(); return successDir == null ? "" : successDir.getAbsolutePath(); } public String getPropertyFilesOnFailDir() { File failDir = this.daemonInfo.getPropFilesInfo().getOnFailDir(); return failDir == null ? "" : failDir.getAbsolutePath(); } public File getPropertyFilesLocalDir() { return this.daemonInfo.getPropFilesInfo().getLocalDir(); } // **************PropFilesInfo******************** /** * Gets the time in milliseconds for when the CrawlDaemon constructor was * invoked. * * @return * @uml.property name="daemonCreationTime" */ public long getDaemonCreationTime() { return daemonCreationTime; } public boolean getHasBeenToldToQuit() { return !this.keepRunning; } public String toString() { return this.getName(); } /** * Starts the program * * @param args * Not Used * @throws IOException * @throws SecurityException */ public static void main(String[] args) { try { int rmiPort = -1; boolean waitForCrawlNotification = false; for (int i = 0; i < args.length; ++i) { if (args[i].equals("--rmiPort")) { rmiPort = Integer.parseInt(args[++i]); } else if (args[i].equals("--waitForNotification")) { waitForCrawlNotification = true; } } LocateRegistry.createRegistry(rmiPort); try { // registry CrawlDaemon as MBean so it can be used with jconsole MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName( "org.apache.oodt.cas.pushpull.daemon:type=Daemon"); } catch (Exception e) { LOG.log(Level.SEVERE, "Failed to register CrawlDaemon as a MBean Object : " + e.getMessage()); } } catch (Exception e) { LOG.log(Level.SEVERE, "Failed to create CrawlDaemon : " + e.getMessage()); } finally { // terminate the CrawlDaemon LOG.log(Level.INFO, "Terminating CrawlDaemon"); } } }
3e122821302503c9c8d50533de6db2305cbba780
556
java
Java
src/main/java/com/yzy/demo/base/People.java
utf-24/java-summary
13e8ee89383cfeb7d42c504d57c30512cf06c81d
[ "MIT" ]
null
null
null
src/main/java/com/yzy/demo/base/People.java
utf-24/java-summary
13e8ee89383cfeb7d42c504d57c30512cf06c81d
[ "MIT" ]
null
null
null
src/main/java/com/yzy/demo/base/People.java
utf-24/java-summary
13e8ee89383cfeb7d42c504d57c30512cf06c81d
[ "MIT" ]
null
null
null
19.172414
47
0.591727
7,651
package com.yzy.demo.base; import lombok.Data; /** * @author young * @date 2019/10/19 10:32 */ @Data public class People { private int age; private String name; public static void main(String[] args) { People people = new People(); people.setAge(10); people.setName("a"); System.out.println("before: "+people); changePeople(people); System.out.println("after: " + people); } static void changePeople(People people){ people.setName("b"); people.setAge(11); } }
3e1228caa82dc075466989e0d62e3b9beb2be8f2
241
java
Java
src/main/java/com/opzpy123/mapper/AuthUserMapper.java
opzpy123/opzpy123
fb26ec864631476a02f25b49a7aa12570ff97024
[ "Apache-2.0" ]
2
2020-03-18T04:48:00.000Z
2021-11-23T03:01:30.000Z
src/main/java/com/opzpy123/mapper/AuthUserMapper.java
opzpy123/opzpy123
fb26ec864631476a02f25b49a7aa12570ff97024
[ "Apache-2.0" ]
null
null
null
src/main/java/com/opzpy123/mapper/AuthUserMapper.java
opzpy123/opzpy123
fb26ec864631476a02f25b49a7aa12570ff97024
[ "Apache-2.0" ]
1
2021-11-02T12:43:21.000Z
2021-11-02T12:43:21.000Z
24.1
62
0.829876
7,652
package com.opzpy123.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.opzpy123.model.AuthUser; import org.apache.ibatis.annotations.Mapper; @Mapper public interface AuthUserMapper extends BaseMapper<AuthUser> { }
3e1229648b9f4daafd438e6b5aa63d365b0fa27f
2,378
java
Java
ltr4l-solr/src/main/java/org/ltr4l/lucene/solr/server/TrainingDataReader.java
Kamulau/ltr4l
0fbf987bc11852fcf3e70a479efd4327908411c1
[ "Apache-2.0" ]
38
2018-02-20T08:24:52.000Z
2021-07-01T14:57:26.000Z
ltr4l-solr/src/main/java/org/ltr4l/lucene/solr/server/TrainingDataReader.java
Kamulau/ltr4l
0fbf987bc11852fcf3e70a479efd4327908411c1
[ "Apache-2.0" ]
139
2018-02-22T02:01:46.000Z
2020-08-03T06:46:02.000Z
ltr4l-solr/src/main/java/org/ltr4l/lucene/solr/server/TrainingDataReader.java
Kamulau/ltr4l
0fbf987bc11852fcf3e70a479efd4327908411c1
[ "Apache-2.0" ]
10
2018-02-20T02:33:40.000Z
2020-06-18T14:43:10.000Z
29.358025
100
0.675778
7,653
/* * Copyright 2018 org.LTR4L * * 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.ltr4l.lucene.solr.server; import java.io.IOException; import java.util.List; import java.util.Map; public class TrainingDataReader extends AbstractConfigReader { private final QueryDataDesc[] queryDataDescs; private final String idField; private final int totalDocs; public TrainingDataReader(String content) throws IOException { super(content); idField = (String)configMap.get("idField"); List<? extends Map> queriesData = (List)configMap.get("queries"); queryDataDescs = new QueryDataDesc[queriesData.size()]; int i = 0; int totalDocs = 0; for(Map queryData: queriesData){ int qid = (Integer)queryData.get("qid"); String queryStr = (String)queryData.get("query"); List<String> docs = (List)queryData.get("docs"); totalDocs += docs.size(); queryDataDescs[i++] = new QueryDataDesc(qid, queryStr, docs.toArray(new String[docs.size()])); } this.totalDocs = totalDocs; } public String getIdField(){ return idField; } public QueryDataDesc[] getQueryDataDescs(){ return queryDataDescs; } public int getTotalDocs(){ return totalDocs; } public static class QueryDataDesc { public final int qid; public final String queryStr; public final String[] docs; public QueryDataDesc(int qid, String queryStr, String[] docs){ this.qid = qid; this.queryStr = queryStr; this.docs = docs; } @Override public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("qid=").append(qid).append(",query=").append(queryStr).append(",docs=["); for(int i = 0; i < docs.length; i++){ if(i > 0) sb.append(','); sb.append(docs[i]); } sb.append("]"); return sb.toString(); } } }
3e1229a5ca8b5902c264546902df168265230b72
983
java
Java
src/main/java/com/luo/leetcode/tree/ConnectNode.java
luoxn28/luo-leetcode
78b0e83c772382837839cb1c9092ca99030871c4
[ "Apache-2.0" ]
3
2020-12-31T03:01:13.000Z
2021-11-26T08:29:33.000Z
src/main/java/com/luo/leetcode/tree/ConnectNode.java
luoxn28/luo-leetcode
78b0e83c772382837839cb1c9092ca99030871c4
[ "Apache-2.0" ]
null
null
null
src/main/java/com/luo/leetcode/tree/ConnectNode.java
luoxn28/luo-leetcode
78b0e83c772382837839cb1c9092ca99030871c4
[ "Apache-2.0" ]
12
2020-10-21T11:25:05.000Z
2022-01-04T08:56:00.000Z
23.97561
80
0.572737
7,654
package com.luo.leetcode.tree; import com.luo.leetcode.tree.base.Node; /** * 填充每个节点的下一个右侧节点指针 * https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/ * * @author luoxiangnan * @date 2020-10-02 */ public class ConnectNode { public Node connect(Node root) { if (root != null) { connectTowNode(root.left, root.right); } return root; } /** * 递归,确定边界条件&&确定当前递归层次所做事情 */ public void connectTowNode(Node left, Node right) { if (left == null && right == null) { return; } else if (left == null) { connectTowNode(right.left, right.right); return; } else if (right == null) { connectTowNode(left.left, left.right); return; } left.next = right; connectTowNode(left.left, left.right); connectTowNode(right.left, right.right); connectTowNode(left.right, right.left); } }
3e1229e21f22b0e723ae4e1184e4907abd4724f6
1,710
java
Java
apiGateway/api-gateway/src/test/java/io/example/apigateway/api/UsersApiControllerIntegrationTest.java
artpdr/microservices-example
ce87277a86ee31ca4501f8fbbb209ce17a20b80f
[ "Apache-2.0" ]
null
null
null
apiGateway/api-gateway/src/test/java/io/example/apigateway/api/UsersApiControllerIntegrationTest.java
artpdr/microservices-example
ce87277a86ee31ca4501f8fbbb209ce17a20b80f
[ "Apache-2.0" ]
null
null
null
apiGateway/api-gateway/src/test/java/io/example/apigateway/api/UsersApiControllerIntegrationTest.java
artpdr/microservices-example
ce87277a86ee31ca4501f8fbbb209ce17a20b80f
[ "Apache-2.0" ]
null
null
null
31.666667
81
0.740351
7,655
package io.example.apigateway.api; import io.example.apigateway.model.User; import java.util.*; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest public class UsersApiControllerIntegrationTest { @Autowired private UsersApi api; @Test public void createUserTest() throws Exception { User body = new User(); ResponseEntity<Void> responseEntity = api.createUser(body); assertEquals(HttpStatus.NOT_IMPLEMENTED, responseEntity.getStatusCode()); } @Test public void deleteUserTest() throws Exception { String username = "username_example"; ResponseEntity<Void> responseEntity = api.deleteUser(username); assertEquals(HttpStatus.NOT_IMPLEMENTED, responseEntity.getStatusCode()); } @Test public void readUserTest() throws Exception { String username = "username_example"; ResponseEntity<User> responseEntity = api.readUser(username); assertEquals(HttpStatus.NOT_IMPLEMENTED, responseEntity.getStatusCode()); } @Test public void updateUserTest() throws Exception { User body = new User(); String username = "username_example"; ResponseEntity<Void> responseEntity = api.updateUser(body, username); assertEquals(HttpStatus.NOT_IMPLEMENTED, responseEntity.getStatusCode()); } }
3e1229f9cd8de235c1038dde7caf818abbdf6dce
4,023
java
Java
src/test/java/org/docksidestage/dockside/dbflute/whitebox/bhv/WxBhvLoadReferrerNestedTest.java
little-forest/dbflute-test-active-dockside
e2924a810bac3bf75995f8082b54ac0d72b85e53
[ "Apache-2.0" ]
null
null
null
src/test/java/org/docksidestage/dockside/dbflute/whitebox/bhv/WxBhvLoadReferrerNestedTest.java
little-forest/dbflute-test-active-dockside
e2924a810bac3bf75995f8082b54ac0d72b85e53
[ "Apache-2.0" ]
null
null
null
src/test/java/org/docksidestage/dockside/dbflute/whitebox/bhv/WxBhvLoadReferrerNestedTest.java
little-forest/dbflute-test-active-dockside
e2924a810bac3bf75995f8082b54ac0d72b85e53
[ "Apache-2.0" ]
null
null
null
46.77907
105
0.552821
7,656
package org.docksidestage.dockside.dbflute.whitebox.bhv; import java.util.List; import org.dbflute.cbean.result.ListResultBean; import org.docksidestage.dockside.dbflute.exbhv.MemberBhv; import org.docksidestage.dockside.dbflute.exbhv.MemberServiceBhv; import org.docksidestage.dockside.dbflute.exbhv.ServiceRankBhv; import org.docksidestage.dockside.dbflute.exentity.Member; import org.docksidestage.dockside.dbflute.exentity.MemberService; import org.docksidestage.dockside.dbflute.exentity.MemberStatus; import org.docksidestage.dockside.dbflute.exentity.Purchase; import org.docksidestage.dockside.dbflute.exentity.ServiceRank; import org.docksidestage.dockside.unit.UnitContainerTestCase; /** * @author jflute * @since 1.0.5F (2014/05/06 Tuesday) */ public class WxBhvLoadReferrerNestedTest extends UnitContainerTestCase { // =================================================================================== // Attribute // ========= private MemberBhv memberBhv; private ServiceRankBhv serviceRankBhv; private MemberServiceBhv memberServiceBhv; // =================================================================================== // Basic // ===== public void test_loadReferrer_one_entity() { // ## Arrange ## ListResultBean<ServiceRank> rankList = serviceRankBhv.selectList(cb -> { /* ## Act ## */ }); // ServiceRank // |-MemberService -> Member // |-Purchase // // if Java8 // serviceRankBhv.loadMemberService(rankList, serviceCB -> { // serviceCB.setupSelect_Member().withMemberStatus(); // serviceCB.query().queryMember().setMemberStatusCode_Equal_Formalized(); // }).withNestedReferrer(serviceList -> { // List<Member> memberList = memberServiceBhv.pulloutMember(serviceList); // memberBhv.loadPurchase(memberList, purchaseCB -> { // purchaseCB.query().setPurchasePrice_GreaterEqual(1000); // }); // }); serviceRankBhv.loadMemberService(rankList, cb -> { cb.setupSelect_Member().withMemberStatus(); cb.query().queryMember().setMemberStatusCode_Equal_Formalized(); }).withNestedReferrer(serviceList -> { List<Member> memberList = memberServiceBhv.pulloutMember(serviceList); memberBhv.loadPurchase(memberList, purchaseCB -> { purchaseCB.query().setPurchasePrice_GreaterEqual(1000); }); }); // ## Assert ## assertHasAnyElement(rankList); for (ServiceRank rank : rankList) { log(rank.getServiceRankName()); List<MemberService> serviceList = rank.getMemberServiceList(); for (MemberService service : serviceList) { service.getMember().alwaysPresent(member -> { Integer memberId = member.getMemberId(); String memberName = member.getMemberName(); MemberStatus status = member.getMemberStatus().get(); String rankCode = service.getServiceRankCode(); Integer pointCount = service.getServicePointCount(); log(" " + memberId, memberName, status.getMemberStatusName(), rankCode, pointCount); List<Purchase> purchaseList = member.getPurchaseList(); for (Purchase purchase : purchaseList) { log(" " + purchase.getMemberId(), purchase.getPurchasePrice()); markHere("exists"); } }); } } assertMarked("exists"); } }
3e1229fab65af85abfccebcc93bd085aa717c6d7
4,878
java
Java
remappedSrc/com/kwpugh/ward_blocks/util/WardBlocksLootTables.java
kwpugh/Ward-Blocks
c1fe83c11a6e9d2607ee9553c73d46e7b02c5e4b
[ "CC0-1.0" ]
1
2020-10-03T11:28:05.000Z
2020-10-03T11:28:05.000Z
src/main/java/com/kwpugh/ward_blocks/util/WardBlocksLootTables.java
kwpugh/Ward-Blocks
c1fe83c11a6e9d2607ee9553c73d46e7b02c5e4b
[ "CC0-1.0" ]
4
2020-08-13T17:59:41.000Z
2021-10-17T23:36:00.000Z
remappedSrc/com/kwpugh/ward_blocks/util/WardBlocksLootTables.java
kwpugh/Ward-Blocks
c1fe83c11a6e9d2607ee9553c73d46e7b02c5e4b
[ "CC0-1.0" ]
2
2021-03-09T10:19:10.000Z
2021-06-19T02:41:13.000Z
29.209581
117
0.749692
7,657
package com.kwpugh.ward_blocks.util; import java.util.List; import net.minecraft.loot.provider.number.ConstantLootNumberProvider; import org.apache.commons.lang3.ArrayUtils; import com.google.common.collect.Lists; import com.kwpugh.ward_blocks.init.BlockInit; import net.fabricmc.fabric.api.loot.v1.FabricLootPoolBuilder; import net.fabricmc.fabric.api.loot.v1.FabricLootSupplierBuilder; import net.fabricmc.fabric.api.loot.v1.event.LootTableLoadingCallback; import net.minecraft.loot.condition.RandomChanceLootCondition; import net.minecraft.loot.entry.ItemEntry; import net.minecraft.util.Identifier; public class WardBlocksLootTables { private static final List<LootTableInsert> INSERTS = Lists.newArrayList(); public static void init() { FabricLootPoolBuilder GROWTH_WARD_BLOCK = FabricLootPoolBuilder.builder() .rolls(ConstantLootNumberProvider.create(1)) .with(ItemEntry.builder(BlockInit.GROWTH_WARD_BLOCK)) .withCondition(RandomChanceLootCondition.builder(0.05F).build()); insert(new LootTableInsert(GROWTH_WARD_BLOCK, new Identifier("minecraft", "chests/buried_treasure") )); LootTableLoadingCallback.EVENT.register(((resourceManager, lootManager, identifier, supplier, lootTableSetter) -> { INSERTS.forEach(i->{ if(ArrayUtils.contains(i.tables, identifier)) { i.insert(supplier); } }); })); FabricLootPoolBuilder HEALTH_WARD_BLOCK = FabricLootPoolBuilder.builder() .rolls(ConstantLootNumberProvider.create(1)) .with(ItemEntry.builder(BlockInit.HEALTH_WARD_BLOCK)) .withCondition(RandomChanceLootCondition.builder(0.05F).build()); insert(new LootTableInsert(HEALTH_WARD_BLOCK, new Identifier("minecraft", "chests/buried_treasure") )); LootTableLoadingCallback.EVENT.register(((resourceManager, lootManager, identifier, supplier, lootTableSetter) -> { INSERTS.forEach(i->{ if(ArrayUtils.contains(i.tables, identifier)) { i.insert(supplier); } }); })); FabricLootPoolBuilder DEFENSE_WARD_BLOCK = FabricLootPoolBuilder.builder() .rolls(ConstantLootNumberProvider.create(1)) .with(ItemEntry.builder(BlockInit.DEFENSE_WARD_BLOCK)) .withCondition(RandomChanceLootCondition.builder(0.05F).build()); insert(new LootTableInsert(DEFENSE_WARD_BLOCK, new Identifier("minecraft", "chests/pillager_outpost") )); LootTableLoadingCallback.EVENT.register(((resourceManager, lootManager, identifier, supplier, lootTableSetter) -> { INSERTS.forEach(i->{ if(ArrayUtils.contains(i.tables, identifier)) { i.insert(supplier); } }); })); FabricLootPoolBuilder EXP_WARD_BLOCK = FabricLootPoolBuilder.builder() .rolls(ConstantLootNumberProvider.create(1)) .with(ItemEntry.builder(BlockInit.EXP_WARD_BLOCK)) .withCondition(RandomChanceLootCondition.builder(0.10F).build()); insert(new LootTableInsert(EXP_WARD_BLOCK, new Identifier("minecraft", "chests/stronghold_library") )); LootTableLoadingCallback.EVENT.register(((resourceManager, lootManager, identifier, supplier, lootTableSetter) -> { INSERTS.forEach(i->{ if(ArrayUtils.contains(i.tables, identifier)) { i.insert(supplier); } }); })); FabricLootPoolBuilder ATTACK_WARD_BLOCK = FabricLootPoolBuilder.builder() .rolls(ConstantLootNumberProvider.create(1)) .with(ItemEntry.builder(BlockInit.ATTACK_WARD_BLOCK)) .withCondition(RandomChanceLootCondition.builder(0.10F).build()); insert(new LootTableInsert(ATTACK_WARD_BLOCK, new Identifier("minecraft", "chests/bastion_treasure") )); LootTableLoadingCallback.EVENT.register(((resourceManager, lootManager, identifier, supplier, lootTableSetter) -> { INSERTS.forEach(i->{ if(ArrayUtils.contains(i.tables, identifier)) { i.insert(supplier); } }); })); FabricLootPoolBuilder LOOT_WARD_BLOCK = FabricLootPoolBuilder.builder() .rolls(ConstantLootNumberProvider.create(1)) .with(ItemEntry.builder(BlockInit.LOOT_WARD_BLOCK)) .withCondition(RandomChanceLootCondition.builder(0.10F).build()); insert(new LootTableInsert(LOOT_WARD_BLOCK, new Identifier("minecraft", "chests/end_city_treasure") )); LootTableLoadingCallback.EVENT.register(((resourceManager, lootManager, identifier, supplier, lootTableSetter) -> { INSERTS.forEach(i->{ if(ArrayUtils.contains(i.tables, identifier)) { i.insert(supplier); } }); })); } public static void insert(LootTableInsert insert) { INSERTS.add(insert); } public static class LootTableInsert { public final Identifier[] tables; public final FabricLootPoolBuilder lootPool; public LootTableInsert(FabricLootPoolBuilder lootPool, Identifier... tables) { this.tables = tables; this.lootPool = lootPool; } public void insert(FabricLootSupplierBuilder supplier) { supplier.pool(lootPool); } } }
3e122a51993f388152e8f7f848d34311b01d43b0
2,394
java
Java
travisjr/src/main/java/com/lonepulse/travisjr/service/FetchingLogsFailedException.java
sahan/Travis-Jr
1d0c83b1857a5080ebf0f7d51dbd94ba8fcbdb69
[ "Apache-2.0" ]
9
2015-02-17T17:07:31.000Z
2021-01-09T17:46:44.000Z
travisjr/src/main/java/com/lonepulse/travisjr/service/FetchingLogsFailedException.java
sahan/Travis-Jr
1d0c83b1857a5080ebf0f7d51dbd94ba8fcbdb69
[ "Apache-2.0" ]
1
2015-09-22T18:45:47.000Z
2015-09-22T18:45:47.000Z
travisjr/src/main/java/com/lonepulse/travisjr/service/FetchingLogsFailedException.java
sahan/Travis-Jr
1d0c83b1857a5080ebf0f7d51dbd94ba8fcbdb69
[ "Apache-2.0" ]
3
2015-09-10T17:04:39.000Z
2018-09-05T01:16:25.000Z
27.872093
99
0.712557
7,658
package com.lonepulse.travisjr.service; /* * #%L * Travis Jr. * %% * Copyright (C) 2013 Lonepulse * %% * 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. * #L% */ import com.lonepulse.travisjr.TravisJrRuntimeException; import com.lonepulse.travisjr.model.BuildInfo; import com.lonepulse.travisjr.model.Repo; /** * <p>This exception is thrown when the logs for a {@link BuildInfo} cannot be retrieved. * * @version 1.1.0 * <br><br> * @author <a href="mailto:efpyi@example.com">Lahiru Sahan Jayasinghe</a> */ public class FetchingLogsFailedException extends TravisJrRuntimeException { private static final long serialVersionUID = -3826393213196417026L; /** * <p>Prints a detailed message which specifies the ID of the {@link Repo} * whose builds were unavailable. * * @param buildInfo * the {@link BuildInfo} whose logs failed to be fetched * * @param rootCause * the root cause of this exception * * @since 1.1.0 */ public FetchingLogsFailedException(BuildInfo buildInfo, Throwable rootCause) { this("Failed to fetch the logs for the build with ID " + buildInfo.getId() + " on repository " + buildInfo.getRepository_id() + " by " + buildInfo.getAuthor_name() + ". ", rootCause); } /** * <p>See {@link TravisJrRuntimeException#TravisJrRuntimeException(String)}. * * @since 1.1.0 */ public FetchingLogsFailedException(String detailMessage) { super(detailMessage); } /** * <p>See {@link TravisJrRuntimeException#TravisJrRuntimeException(Throwable)}. * * @since 1.1.0 */ public FetchingLogsFailedException(Throwable throwable) { super(throwable); } /** * <p>See {@link TravisJrRuntimeException#TravisJrRuntimeException(String, Throwable)}. * * @since 1.1.0 */ public FetchingLogsFailedException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } }
3e122d84c95780cc0212489c16c72be730e958f9
2,140
java
Java
_Eclipse/_SpigotDecompiled/work/decompile-cf6b1333/net/minecraft/server/CriterionProgress.java
MarioMatschgi/Minecraft-Plugins
b1363d06b6d741337dc0c6c7e1c1231778356be4
[ "MIT" ]
1
2021-03-24T12:20:04.000Z
2021-03-24T12:20:04.000Z
_Eclipse/_SpigotDecompiled/work/decompile-cf6b1333/net/minecraft/server/CriterionProgress.java
MarioMatschgi/Minecraft-Plugins
b1363d06b6d741337dc0c6c7e1c1231778356be4
[ "MIT" ]
null
null
null
_Eclipse/_SpigotDecompiled/work/decompile-cf6b1333/net/minecraft/server/CriterionProgress.java
MarioMatschgi/Minecraft-Plugins
b1363d06b6d741337dc0c6c7e1c1231778356be4
[ "MIT" ]
2
2021-03-27T15:43:42.000Z
2021-03-27T15:50:42.000Z
28.918919
123
0.672897
7,659
package net.minecraft.server; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSyntaxException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class CriterionProgress { private static final SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); private final AdvancementProgress b; private Date c; public CriterionProgress(AdvancementProgress advancementprogress) { this.b = advancementprogress; } public boolean a() { return this.c != null; } public void b() { this.c = new Date(); } public void c() { this.c = null; } public Date getDate() { return this.c; } public String toString() { return "CriterionProgress{obtained=" + (this.c == null ? "false" : this.c) + '}'; } public void a(PacketDataSerializer packetdataserializer) { packetdataserializer.writeBoolean(this.c != null); if (this.c != null) { packetdataserializer.a(this.c); } } public JsonElement e() { return (JsonElement) (this.c != null ? new JsonPrimitive(CriterionProgress.a.format(this.c)) : JsonNull.INSTANCE); } public static CriterionProgress a(PacketDataSerializer packetdataserializer, AdvancementProgress advancementprogress) { CriterionProgress criterionprogress = new CriterionProgress(advancementprogress); if (packetdataserializer.readBoolean()) { criterionprogress.c = packetdataserializer.m(); } return criterionprogress; } public static CriterionProgress a(AdvancementProgress advancementprogress, String s) { CriterionProgress criterionprogress = new CriterionProgress(advancementprogress); try { criterionprogress.c = CriterionProgress.a.parse(s); return criterionprogress; } catch (ParseException parseexception) { throw new JsonSyntaxException("Invalid datetime: " + s, parseexception); } } }
3e122e4d76e17be56f1d6ab9c79fee0764464f93
4,677
java
Java
core/src/main/java/com/douban/rexxar/utils/io/stream/StringBuilderWriter.java
BetterIgor/rexxar-android
f1fb7a19979c6f4d3d869ae3f2ed13bae8485a56
[ "MIT" ]
733
2016-10-09T10:02:55.000Z
2022-02-18T11:53:45.000Z
core/src/main/java/com/douban/rexxar/utils/io/stream/StringBuilderWriter.java
douban/Rexxar-Android
0717af0e1eb66e4a5fbf124efa969d09052cd622
[ "MIT" ]
36
2016-10-14T04:06:42.000Z
2020-11-24T02:02:44.000Z
core/src/main/java/com/douban/rexxar/utils/io/stream/StringBuilderWriter.java
douban/Rexxar-Android
0717af0e1eb66e4a5fbf124efa969d09052cd622
[ "MIT" ]
122
2016-10-09T10:35:43.000Z
2021-07-12T09:00:25.000Z
29.049689
84
0.617276
7,660
/* * 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 com.douban.rexxar.utils.io.stream; import java.io.Serializable; import java.io.Writer; /** * {@link Writer} implementation that outputs to a {@link StringBuilder}. * <p> * <strong>NOTE:</strong> This implementation, as an alternative to * <code>java.io.StringWriter</code>, provides an <i>un-synchronized</i> * (i.e. for use in a single thread) implementation for better performance. * For safe usage with multiple {@link Thread}s then * <code>java.io.StringWriter</code> should be used. * * @version $Id: StringBuilderWriter.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 2.0 */ public class StringBuilderWriter extends Writer implements Serializable { private final StringBuilder builder; /** * Construct a new {@link StringBuilder} instance with default capacity. */ public StringBuilderWriter() { this.builder = new StringBuilder(); } /** * Construct a new {@link StringBuilder} instance with the specified capacity. * * @param capacity The initial capacity of the underlying {@link StringBuilder} */ public StringBuilderWriter(int capacity) { this.builder = new StringBuilder(capacity); } /** * Construct a new instance with the specified {@link StringBuilder}. * * @param builder The String builder */ public StringBuilderWriter(StringBuilder builder) { this.builder = builder != null ? builder : new StringBuilder(); } /** * Append a single character to this Writer. * * @param value The character to append * @return This writer instance */ @Override public Writer append(char value) { builder.append(value); return this; } /** * Append a character sequence to this Writer. * * @param value The character to append * @return This writer instance */ @Override public Writer append(CharSequence value) { builder.append(value); return this; } /** * Append a portion of a character sequence to the {@link StringBuilder}. * * @param value The character to append * @param start The index of the first character * @param end The index of the last character + 1 * @return This writer instance */ @Override public Writer append(CharSequence value, int start, int end) { builder.append(value, start, end); return this; } /** * Closing this writer has no effect. */ @Override public void close() { } /** * Flushing this writer has no effect. */ @Override public void flush() { } /** * Write a String to the {@link StringBuilder}. * * @param value The value to write */ @Override public void write(String value) { if (value != null) { builder.append(value); } } /** * Write a portion of a character array to the {@link StringBuilder}. * * @param value The value to write * @param offset The index of the first character * @param length The number of characters to write */ @Override public void write(char[] value, int offset, int length) { if (value != null) { builder.append(value, offset, length); } } /** * Return the underlying builder. * * @return The underlying builder */ public StringBuilder getBuilder() { return builder; } /** * Returns {@link StringBuilder#toString()}. * * @return The contents of the String builder. */ @Override public String toString() { return builder.toString(); } }
3e122f13b6831a50aae20fd937c36e287ec1c4fc
498
java
Java
cat-adoption-batch-after/src/main/java/com/example/cat/adoption/step/FilterReportProcessor.java
ammbra/kube-batch
ba73b4ac010167b5a0ab8f9c6bd83be6285c1b47
[ "MIT" ]
2
2020-09-30T22:36:04.000Z
2020-11-18T02:08:31.000Z
cat-adoption-batch-after/src/main/java/com/example/cat/adoption/step/FilterReportProcessor.java
ammbra/kube-batch
ba73b4ac010167b5a0ab8f9c6bd83be6285c1b47
[ "MIT" ]
null
null
null
cat-adoption-batch-after/src/main/java/com/example/cat/adoption/step/FilterReportProcessor.java
ammbra/kube-batch
ba73b4ac010167b5a0ab8f9c6bd83be6285c1b47
[ "MIT" ]
null
null
null
26.210526
91
0.789157
7,661
package com.example.cat.adoption.step; import com.example.cat.adoption.model.Report; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.item.ItemProcessor; public class FilterReportProcessor implements ItemProcessor<Report, Report> { private static final Logger LOGGER = LoggerFactory.getLogger(FilterReportProcessor.class); @Override public Report process(Report item) throws Exception { if(item.getAge()==1){ return null; } return item; } }
3e122f26bbc22d159b9044d68860c8de1dcf7a86
3,621
java
Java
jonix-onix2/src/main/java/com/tectonica/jonix/onix2/PromotionContact.java
prafullkotecha/on.x
0544feb4b1ac8fd7dfd52e34e3f84d46eae5749e
[ "Apache-2.0" ]
null
null
null
jonix-onix2/src/main/java/com/tectonica/jonix/onix2/PromotionContact.java
prafullkotecha/on.x
0544feb4b1ac8fd7dfd52e34e3f84d46eae5749e
[ "Apache-2.0" ]
null
null
null
jonix-onix2/src/main/java/com/tectonica/jonix/onix2/PromotionContact.java
prafullkotecha/on.x
0544feb4b1ac8fd7dfd52e34e3f84d46eae5749e
[ "Apache-2.0" ]
null
null
null
30.2
119
0.631347
7,662
/* * Copyright (C) 2012 Zach Melamed * * Latest version available online at https://github.com/zach-m/jonix * Contact me at upchh@example.com * * 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.tectonica.jonix.onix2; import java.io.Serializable; import com.tectonica.jonix.JPU; import com.tectonica.jonix.OnixElement; import com.tectonica.jonix.codelist.LanguageCodes; import com.tectonica.jonix.codelist.RecordSourceTypes; import com.tectonica.jonix.codelist.TextCaseFlags; import com.tectonica.jonix.codelist.TextFormats; import com.tectonica.jonix.codelist.TransliterationSchemes; /* * NOTE: THIS IS AN AUTO-GENERATED FILE, DON'T EDIT MANUALLY */ /** * <h1>Promotion contact details</h1> * <p> * Free text giving the name, department, phone number, email address <em>etc</em> for a promotional contact person for * the product. Optional and non-repeating. * </p> * <table border='1' cellpadding='3'> * <tr> * <td>Format</td> * <td>Variable-length text, suggested maximum length 300 characters</td> * </tr> * <tr> * <td>Reference name</td> * <td>&lt;PromotionContact&gt;</td> * </tr> * <tr> * <td>Short tag</td> * <td>&lt;k166&gt;</td> * </tr> * <tr> * <td>Example</td> * <td>&#160;</td> * </tr> * </table> */ public class PromotionContact implements OnixElement, Serializable { private static final long serialVersionUID = 1L; public static final String refname = "PromotionContact"; public static final String shortname = "k166"; // /////////////////////////////////////////////////////////////////////////////// // ATTRIBUTES // /////////////////////////////////////////////////////////////////////////////// public TextFormats textformat; public TextCaseFlags textcase; public LanguageCodes language; public TransliterationSchemes transliteration; /** * (type: DateOrDateTime) */ public String datestamp; public RecordSourceTypes sourcetype; public String sourcename; // /////////////////////////////////////////////////////////////////////////////// // VALUE MEMBER // /////////////////////////////////////////////////////////////////////////////// /** * Raw Format: Variable-length text, suggested maximum length 300 characters * <p> * (type: NonEmptyString) */ public String value; // /////////////////////////////////////////////////////////////////////////////// // SERVICES // /////////////////////////////////////////////////////////////////////////////// public PromotionContact() {} public PromotionContact(org.w3c.dom.Element element) { textformat = TextFormats.byCode(JPU.getAttribute(element, "textformat")); textcase = TextCaseFlags.byCode(JPU.getAttribute(element, "textcase")); language = LanguageCodes.byCode(JPU.getAttribute(element, "language")); transliteration = TransliterationSchemes.byCode(JPU.getAttribute(element, "transliteration")); datestamp = JPU.getAttribute(element, "datestamp"); sourcetype = RecordSourceTypes.byCode(JPU.getAttribute(element, "sourcetype")); sourcename = JPU.getAttribute(element, "sourcename"); value = JPU.getContentAsString(element); } }
3e122f653fbf1dfbe1c4d3871d2791c4076f3fe3
358
java
Java
samples/virtualan-spring-boot/src/main/java/io/virtualan/configuration/HomeController.java
virtualansoftware/virtualan
c5835876cc265ed4c89f809a9485929e31da39af
[ "Apache-2.0" ]
14
2020-07-15T11:28:29.000Z
2022-03-06T23:15:38.000Z
samples/virtualan-spring-boot/src/main/java/io/virtualan/configuration/HomeController.java
virtualansoftware/virtualan
c5835876cc265ed4c89f809a9485929e31da39af
[ "Apache-2.0" ]
316
2020-07-19T17:42:45.000Z
2022-03-27T18:48:28.000Z
samples/virtualan-spring-boot/src/main/java/io/virtualan/configuration/HomeController.java
virtualansoftware/virtualan
c5835876cc265ed4c89f809a9485929e31da39af
[ "Apache-2.0" ]
2
2020-08-27T14:18:17.000Z
2021-01-26T16:05:55.000Z
17.9
62
0.734637
7,663
package io.virtualan.configuration; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * Home redirection to OpenAPI api documentation */ @Controller public class HomeController { @RequestMapping("/") public String index() { return "redirect:swagger-ui.html"; } }
3e122f7459867f66c3a3a3c2a16be0afd1b54454
1,268
java
Java
storage/src/main/java/fk/prof/storage/AsyncStorage.java
Flipkart/fk-prof
ed801c32a8c3704204be670e16c6465297431e1a
[ "Apache-2.0", "MIT" ]
7
2017-01-17T11:29:08.000Z
2021-06-07T10:36:59.000Z
storage/src/main/java/fk/prof/storage/AsyncStorage.java
Flipkart/fk-prof
ed801c32a8c3704204be670e16c6465297431e1a
[ "Apache-2.0", "MIT" ]
106
2017-01-12T04:38:40.000Z
2017-10-04T11:12:54.000Z
storage/src/main/java/fk/prof/storage/AsyncStorage.java
Flipkart/fk-prof
ed801c32a8c3704204be670e16c6465297431e1a
[ "Apache-2.0", "MIT" ]
4
2016-12-22T08:56:27.000Z
2018-07-26T17:13:42.000Z
32.512821
95
0.710568
7,664
package fk.prof.storage; import java.io.InputStream; import java.util.Set; import java.util.concurrent.CompletableFuture; /** * Interface for a async load/store storage. * @author gaurav.ashok */ public interface AsyncStorage { /** * Store the content to the specified path. StorageException while storing * needs to be taken care of by the implementation. * @param path path where the content is to stored * @param content the content as inputstream * @return Future to indicate completion */ CompletableFuture<Void> storeAsync(String path, InputStream content, long length); /** * Retrieves the content from the specified path. * @param path path from where content is to fetched * @return Future object for the content. */ CompletableFuture<InputStream> fetchAsync(String path); /** * Lists all objects from the specified prefix of the path with options to list recursively * * @param prefixPath prefix of path from where objects are to be listed * @param recursive true if listing is to be recursive * @return Future object for the set containing the object names */ CompletableFuture<Set<String>> listAsync(String prefixPath, boolean recursive); }
3e122f9cbaf7988798697b515c39f618511de86c
754
java
Java
105/Solution.java
starforever/leet-code
d38b4d8f11971e385c92191d586105ebb8ea8829
[ "MIT" ]
null
null
null
105/Solution.java
starforever/leet-code
d38b4d8f11971e385c92191d586105ebb8ea8829
[ "MIT" ]
null
null
null
105/Solution.java
starforever/leet-code
d38b4d8f11971e385c92191d586105ebb8ea8829
[ "MIT" ]
null
null
null
18.390244
59
0.580902
7,665
public class Solution { int N; int[] preorder; int[] inorder; HashMap<Integer, Integer> pos; int next; void buildPos () { pos = new HashMap<Integer, Integer>(); for (int i = 0; i < N; ++i) pos.put(inorder[i], i); } TreeNode construct (int start, int end) { if (end - start == 0) return null; int cur = preorder[next++]; TreeNode root = new TreeNode(cur); int mid = pos.get(cur); root.left = construct(start, mid); root.right = construct(mid + 1, end); return root; } public TreeNode buildTree (int[] preorder, int[] inorder) { N = preorder.length; this.preorder = preorder; this.inorder = inorder; buildPos(); next = 0; return construct(0, N); } }
3e122fc5f1a499b7a4cfe816f1649305c5973082
634
java
Java
third_party/ijar/test/package-info.java
LinkinParkBoy/trunk
785c91b1e56a8f21de4054dc8d21a9c250aaf4cb
[ "Apache-2.0" ]
142
2017-06-14T11:39:55.000Z
2022-03-20T15:08:39.000Z
third_party/ijar/test/package-info.java
xiaoqiyu/DERIQT
57c20c40a692a4f877296a39ed91aeab8e4c6d66
[ "Apache-2.0" ]
17
2015-07-13T02:37:55.000Z
2017-05-02T07:12:33.000Z
third_party/ijar/test/package-info.java
turkdevops/bazel
0fda3b97907553cabadf04d7be7af89bf2ae4c05
[ "Apache-2.0" ]
54
2015-04-20T07:27:43.000Z
2017-04-27T21:17:32.000Z
42.266667
75
0.742902
7,666
// Copyright 2015 Google Inc. 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. /** Empty package-info */
3e122ffe33361069ffa1b64691208daf5a78f6ce
7,947
java
Java
LayoutManagerExJobb/src/main/java/com/bluebrim/layoutmanager/CoInterval.java
goranstack/bluebrim
eb6edbeada72ed7fd1294391396432cb25575fe0
[ "Apache-2.0" ]
null
null
null
LayoutManagerExJobb/src/main/java/com/bluebrim/layoutmanager/CoInterval.java
goranstack/bluebrim
eb6edbeada72ed7fd1294391396432cb25575fe0
[ "Apache-2.0" ]
null
null
null
LayoutManagerExJobb/src/main/java/com/bluebrim/layoutmanager/CoInterval.java
goranstack/bluebrim
eb6edbeada72ed7fd1294391396432cb25575fe0
[ "Apache-2.0" ]
null
null
null
23.864865
95
0.698628
7,667
package com.bluebrim.layoutmanager; /** * Represent a intervall with a start and a stop value. * Creation date: (2000-06-06 09:16:57) * @author: Arvid Berg & Masod Jalalian */ import java.util.*; public class CoInterval implements Comparable{ protected double m_start; protected double m_stop; public final static CoInterval ZERO=new CoInterval(0.0,0.0); /** * Constructs a Intervall with start and stop set to zero. */ public CoInterval() { super(); m_start=0; m_stop=0; } /** * Construct a intervall with start and stop acordingly. * Creation date: (2000-06-06 09:18:32) * @param start double * @param stop double */ public CoInterval(double start, double stop) { m_start=Math.min(start,stop); m_stop=Math.max(start,stop); } /** * Creates a new intervall with the same values as param * Creation date: (2000-06-07 15:29:49) * @param param columnalg.server.Intervall */ public CoInterval(CoInterval param) { m_start=param.getStart(); m_stop=param.getStop(); } /** * Compares this object with obj return 1 0 -1 depending if this > = < obj. * Creation date: (2000-06-06 09:22:28) * @return int * @param intervall columnalg.Intervall */ public int compareTo(Object obj) { double start=m_start-((CoInterval)obj).m_start; if( start!=0 ) return (int)start; else { double stop=m_stop-((CoInterval)obj).m_stop; if(stop!=0) return (int)stop; } return 0; } /** * Returns a collection of intervalls representng the result if intervall is removed form this. * Creation date: (2000-06-07 15:08:12) * @return columnalg.server.Intervall * @param intervall columnalg.server.Intervall */ public Collection difference(CoInterval intervall) { Collection result=new LinkedList(); double difStart = Math.min(m_stop,intervall.m_start) - m_start; double difStop = m_stop - Math.max(m_start,intervall.m_stop); if(difStart > 0) result.add(new CoInterval(m_start,Math.min(m_stop,intervall.m_start))); if(difStop > 0) result.add(new CoInterval(Math.max(m_start,intervall.m_stop),m_stop)); return result; } /** * Checks if this are equal to obj. * Creation date: (2000-06-08 09:26:54) * @return boolean * @param obj java.lang.Object */ public boolean equals(Object obj) { double start=m_start-((CoInterval)obj).m_start; double stop=m_stop-((CoInterval)obj).m_stop; if( start==0 && stop==0) return true; return false; } /** * return the size of the intervall * Creation date: (2000-06-07 10:00:46) * @return double */ public double getSize() { return Math.abs(m_stop-m_start); } /** * returns the start value. * Creation date: (2000-06-07 14:29:14) * @return double */ public double getStart() { return m_start; } /** * Return the stop value. * Creation date: (2000-06-07 14:29:14) * @return double */ public double getStop() { return m_stop; } /** * Return a collection of intervall as a result of the curent * intervall intersection with intervall. * Creation date: (2000-06-06 10:05:54) * @return columnalg.Intervall * @param intervall columnalg.Intervall */ public Collection intersection(CoInterval intervall) { Collection result=new LinkedList(); double start=Math.max(m_start,intervall.m_start); double stop =Math.min(m_stop, intervall.m_stop); if(stop <=start) ; else result.add(new CoInterval(start,stop)); return result; } /** * Static method to invert a list of intervall with the universa defined by range. * Creation date: (2000-06-06 14:43:18) * @return java.util.List * @param list java.util.List * @param range Intervall a intervall from the top to the bottom of the * list */ public static List invert(List list,CoInterval range) { if(range==null) range=new CoInterval(0,1000); List newlist=null; boolean isempty; sort(list); newlist=new ArrayList(); CoInterval obj1,obj2; Iterator iter=list.iterator(); if(iter.hasNext()) { obj1=(CoInterval)iter.next(); newlist.add(new CoInterval(range.m_start,obj1.m_start)); while(iter.hasNext()) { obj2=(CoInterval)iter.next(); newlist.add(new CoInterval(obj1.m_stop,obj2.m_start)); obj1=obj2; } newlist.add(new CoInterval(obj1.m_stop,range.m_stop)); } else { newlist.add(new CoInterval(range.m_start,range.m_stop)); } return newlist; } /** * Return true if the intervall is empty. * Creation date: (2000-06-06 11:56:12) * @return boolean */ public boolean isEmpty() { if(m_start==m_stop) return true; return false; } /** * Creates a newlist from list where all intersections have been removed. * Creation date: (2000-06-06 09:38:30) * @return java.util.Collection * @param col java.util.Collection */ public static List merge(List list) { List newlist=null; boolean isempty; Comparator comp=new com.bluebrim.layoutmanager.CoIntervalComparator(); java.util.Collections.sort(list,comp); isempty=false; newlist=list; do { isempty=false; list=newlist; newlist=new ArrayList(); CoInterval obj1,obj2; for (int i = 0; i < list.size(); i++) { obj1=(CoInterval)list.get(i); for(int j=i+1;j<list.size();j++) { isempty=true; obj2=(CoInterval)list.get(j); newlist.addAll(obj1.intersection(obj2)); } } }while(isempty || list.size()!=newlist.size()); return newlist; } /** * Return a new list where all intervall from list2 have been added to list and all * intersections have been removed. * Creation date: (2000-06-06 09:38:30) * @return java.util.Collection * @param col java.util.Collection */ public static List merge(List list,List list2) { List newlist=null; boolean isempty; //Comparator comp=new ComparatorIntervall(); //java.util.Collections.sort(list,comp); newlist=new ArrayList(); Iterator iterL1=list.iterator(); while(iterL1.hasNext()) { CoInterval obj1=(CoInterval)iterL1.next(); Iterator iterL2=list2.iterator(); while(iterL2.hasNext()) { CoInterval obj2=(CoInterval)iterL2.next(); newlist.addAll(obj1.intersection(obj2)); } } return newlist; } /** * Removes an Intervall represented by intervall from a list of intervalls. * Creation date: (2000-06-14 13:42:47) * @return java.util.List * @param list java.util.List * @param intervall columnalg.server.Intervall */ public static List remove(List list, CoInterval intervall) { List tempList=new LinkedList(); Iterator iter=list.iterator(); while(iter.hasNext()) { CoInterval curentIntervall=(CoInterval)iter.next(); Collection tempIntervall=curentIntervall.intersection(intervall); if(tempIntervall.size()!=0 ) { tempList.addAll(curentIntervall.difference(intervall)); } else tempList.add(curentIntervall); } return tempList; } /** * Orders the elements in the collection in a specified order. * Currently the ordering criterion is the area of the shape with * the elements in the list being arranged in the descending order * of priority **/ public static void sort(List list) { // loop through the list for(int i = 0; i < list.size()-1; i++) { for(int j = i + 1; j < list.size(); j++) { // check if the adjacent elements are out of order if( (((Comparable)list.get(j)).compareTo(list.get(i)))>0 ) { // if so, the swap the shapes Object temp = list.get(j); list.set(j,list.get(i)); list.set(i,temp); } // if } // for } // for } // sort() /** * Return the union between this intervall and intervall. * Creation date: (2000-06-06 14:23:15) * @return columnalg.server.Intervall * @param intervall columnalg.server.Intervall */ public Collection union(CoInterval intervall) { CoInterval first,second; Collection result=new LinkedList(); if(this.compareTo(intervall)>0) { second=this; first=intervall; } else { second=intervall; first=this; } if( second.m_start <= first.m_stop ) { result.add(new CoInterval(Math.min(first.m_start,second.m_start), Math.max(first.m_stop,second.m_stop ))); } else { result.add(first); result.add(second); } return result; } }
3e12303ef3e25d0767c9fc51d0e8ffcbfacf32e3
676
java
Java
src/main/java/scripts/CreateTablesScript.java
admirf/rms
8fc1524ee825a71f9c4ef20b5c3c2ce2f21c4f97
[ "Apache-2.0" ]
1
2019-12-16T13:35:02.000Z
2019-12-16T13:35:02.000Z
src/main/java/scripts/CreateTablesScript.java
admirf/rms
8fc1524ee825a71f9c4ef20b5c3c2ce2f21c4f97
[ "Apache-2.0" ]
null
null
null
src/main/java/scripts/CreateTablesScript.java
admirf/rms
8fc1524ee825a71f9c4ef20b5c3c2ce2f21c4f97
[ "Apache-2.0" ]
null
null
null
26
94
0.677515
7,668
package scripts; import model.Tables; import repository.DefaultSessionFactory; import repository.TablesRepository; import java.security.NoSuchAlgorithmException; /** * A script to create the 11 tables of our restaurant */ public class CreateTablesScript { public static void main(String[] args) throws NoSuchAlgorithmException { TablesRepository userRepo = new TablesRepository(DefaultSessionFactory.getInstance()); for(int i = 0; i <= 10; ++i) { Tables table = new Tables(); table.setName(i); table.setOccupied(false); userRepo.create(table); } DefaultSessionFactory.close(); } }
3e123089dcca1261274e26ee888006c147c0511a
2,740
java
Java
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableDoOnRequestTest.java
nian8/RxJava
2cab59dba496c81695cd965d42b4d237dcdcd224
[ "Apache-2.0" ]
47,529
2015-01-01T05:12:36.000Z
2022-03-31T17:58:27.000Z
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableDoOnRequestTest.java
nian8/RxJava
2cab59dba496c81695cd965d42b4d237dcdcd224
[ "Apache-2.0" ]
4,592
2015-01-01T09:47:45.000Z
2022-03-31T04:30:45.000Z
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableDoOnRequestTest.java
nian8/RxJava
2cab59dba496c81695cd965d42b4d237dcdcd224
[ "Apache-2.0" ]
9,287
2015-01-04T08:03:18.000Z
2022-03-31T22:22:39.000Z
30.786517
112
0.520803
7,669
/* * Copyright (c) 2016-present, RxJava Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.rxjava3.internal.operators.flowable; import static org.junit.Assert.*; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import io.reactivex.rxjava3.core.*; import io.reactivex.rxjava3.functions.*; import io.reactivex.rxjava3.subscribers.DefaultSubscriber; public class FlowableDoOnRequestTest extends RxJavaTest { @Test public void unsubscribeHappensAgainstParent() { final AtomicBoolean unsubscribed = new AtomicBoolean(false); Flowable.just(1).concatWith(Flowable.<Integer>never()) // .doOnCancel(new Action() { @Override public void run() { unsubscribed.set(true); } }) // .doOnRequest(new LongConsumer() { @Override public void accept(long n) { // do nothing } }) // .subscribe().dispose(); assertTrue(unsubscribed.get()); } @Test public void doRequest() { final List<Long> requests = new ArrayList<>(); Flowable.range(1, 5) // .doOnRequest(new LongConsumer() { @Override public void accept(long n) { requests.add(n); } }) // .subscribe(new DefaultSubscriber<Integer>() { @Override public void onStart() { request(3); } @Override public void onComplete() { } @Override public void onError(Throwable e) { } @Override public void onNext(Integer t) { request(t); } }); assertEquals(Arrays.asList(3L, 1L, 2L, 3L, 4L, 5L), requests); } }
3e1231548ad626f76fbfdd00d19ab0358bbafb98
1,598
java
Java
src/main/java/net/kyori/limbo/discord/action/Action.java
KyoriPowered/limbo
0e53d1a9a15dba6e9682d373e7698f3c28116adc
[ "MIT" ]
7
2018-01-30T19:09:57.000Z
2021-09-20T11:20:20.000Z
src/main/java/net/kyori/limbo/discord/action/Action.java
KyoriPowered/limbo
0e53d1a9a15dba6e9682d373e7698f3c28116adc
[ "MIT" ]
4
2018-05-08T02:36:16.000Z
2020-05-14T22:16:03.000Z
src/main/java/net/kyori/limbo/discord/action/Action.java
KyoriPowered/limbo
0e53d1a9a15dba6e9682d373e7698f3c28116adc
[ "MIT" ]
null
null
null
39.95
81
0.762829
7,670
/* * This file is part of limbo, licensed under the MIT License. * * Copyright (c) 2017-2019 KyoriPowered * * 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 net.kyori.limbo.discord.action; import net.kyori.feature.FeatureDefinition; import net.kyori.kassel.channel.message.embed.Embed; import net.kyori.mu.Maybe; import org.checkerframework.checker.nullness.qual.NonNull; public interface Action extends FeatureDefinition { @NonNull Maybe<Message> message(); interface Message { @NonNull String content(); @NonNull Maybe<Embed> embed(); } }
3e1231655815388d66e5edc92bed85a621703b7f
2,898
java
Java
src/metrics/src/main/java/org/geogit/metrics/MeteredCommandHook.java
markles/GeoGit
fb8e08084eaaf7b70f8b919c9f1607000e23c200
[ "BSD-3-Clause" ]
1
2015-09-21T18:46:15.000Z
2015-09-21T18:46:15.000Z
src/metrics/src/main/java/org/geogit/metrics/MeteredCommandHook.java
markles/GeoGit
fb8e08084eaaf7b70f8b919c9f1607000e23c200
[ "BSD-3-Clause" ]
null
null
null
src/metrics/src/main/java/org/geogit/metrics/MeteredCommandHook.java
markles/GeoGit
fb8e08084eaaf7b70f8b919c9f1607000e23c200
[ "BSD-3-Clause" ]
null
null
null
34.915663
101
0.654589
7,671
package org.geogit.metrics; import static org.geogit.metrics.MetricsModule.COMMAND_STACK_LOGGER; import static org.geogit.metrics.MetricsModule.METRICS_ENABLED; import static org.geogit.metrics.MetricsModule.METRICS_LOGGER; import java.util.concurrent.TimeUnit; import org.geogit.api.AbstractGeoGitOp; import org.geogit.api.Platform; import org.geogit.api.hooks.CannotRunGeogitOperationException; import org.geogit.api.hooks.CommandHook; import org.geogit.api.porcelain.ConfigException; import org.geogit.api.porcelain.ConfigException.StatusCode; import org.geogit.storage.ConfigDatabase; public class MeteredCommandHook implements CommandHook { private static final double toMillisFactor = 1.0 / TimeUnit.MILLISECONDS.toNanos(1L); /** * @return {@code true}, applies to all ops */ @Override public boolean appliesTo(Class<? extends AbstractGeoGitOp> clazz) { return true; } @Override public <C extends AbstractGeoGitOp<?>> C pre(C command) throws CannotRunGeogitOperationException { Boolean enabled; if (command.context().repository() == null) { return command; } ConfigDatabase configDb = command.context().configDatabase(); try { enabled = configDb.get(METRICS_ENABLED, Boolean.class).or(Boolean.FALSE); } catch (ConfigException e) { if (StatusCode.INVALID_LOCATION.equals(e.statusCode)) { enabled = Boolean.FALSE; } else { throw e; } } if (!enabled.booleanValue()) { return command; } final Platform platform = command.context().platform(); final long startTime = platform.currentTimeMillis(); final long nanoTime = platform.nanoTime(); final String name = command.getClass().getSimpleName(); CallStack stack = CallStack.push(name, startTime, nanoTime); command.getClientData().put("metrics.callStack", stack); return command; } @Override public <T> T post(AbstractGeoGitOp<T> command, Object retVal, boolean success) throws Exception { CallStack stack = (CallStack) command.getClientData().get("metrics.callStack"); if (stack == null || command.context().repository() == null) { return (T) retVal; } final Platform platform = command.context().platform(); long endTime = platform.nanoTime(); stack = CallStack.pop(endTime, success); long ellapsed = stack.getEllapsedNanos(); double millis = endTime * toMillisFactor; METRICS_LOGGER.info("{}, {}, {}, {}", stack.getName(), stack.getStartTimeMillis(), millis, success); if (stack.isRoot()) { COMMAND_STACK_LOGGER.info("{}", stack.toString(TimeUnit.MILLISECONDS)); } return (T) retVal; } }
3e1232a4516faf0e030baa3facd7f1c1e5341908
820
java
Java
rolevm-examples/src/main/java/rolevm/examples/noop/NoopCompartment.java
martinmo/rolevm
53f82de6a9e45b4dea668116d703048996b61ec0
[ "BSD-3-Clause" ]
1
2020-10-31T05:36:47.000Z
2020-10-31T05:36:47.000Z
rolevm-examples/src/main/java/rolevm/examples/noop/NoopCompartment.java
martinmo/rolevm
53f82de6a9e45b4dea668116d703048996b61ec0
[ "BSD-3-Clause" ]
null
null
null
rolevm-examples/src/main/java/rolevm/examples/noop/NoopCompartment.java
martinmo/rolevm
53f82de6a9e45b4dea668116d703048996b61ec0
[ "BSD-3-Clause" ]
null
null
null
31.538462
110
0.676829
7,672
package rolevm.examples.noop; import rolevm.api.Compartment; import rolevm.api.DispatchContext; import rolevm.api.OverrideBase; import rolevm.api.Role; public class NoopCompartment extends Compartment { public @Role class NoopRole { @OverrideBase public Object noArgs(DispatchContext ctx, BaseType base) throws Throwable { return ctx.proceed().invoke(ctx, base); } @OverrideBase public Object referenceArgAndReturn(DispatchContext ctx, BaseType base, Object o) throws Throwable { return ctx.proceed().invoke(ctx, base, o); } @OverrideBase public int primitiveArgsAndReturn(DispatchContext ctx, BaseType base, int x, int y) throws Throwable { return (int) ctx.proceed().invoke(ctx, base, x, y); } } }
3e1232b6a24e2a3465058b0c612b6777316bf0cb
305
java
Java
com.evolveum.midpoint.eclipse.parent/com.evolveum.midpoint.eclipse.runtime/src/com/evolveum/midpoint/eclipse/runtime/api/resp/NotApplicableServerResponse.java
Evolveum/midpoint-ide-plugins
9390b678dcf701db1f6f9d3026a66fc9fd179e0d
[ "Apache-2.0" ]
null
null
null
com.evolveum.midpoint.eclipse.parent/com.evolveum.midpoint.eclipse.runtime/src/com/evolveum/midpoint/eclipse/runtime/api/resp/NotApplicableServerResponse.java
Evolveum/midpoint-ide-plugins
9390b678dcf701db1f6f9d3026a66fc9fd179e0d
[ "Apache-2.0" ]
null
null
null
com.evolveum.midpoint.eclipse.parent/com.evolveum.midpoint.eclipse.runtime/src/com/evolveum/midpoint/eclipse/runtime/api/resp/NotApplicableServerResponse.java
Evolveum/midpoint-ide-plugins
9390b678dcf701db1f6f9d3026a66fc9fd179e0d
[ "Apache-2.0" ]
null
null
null
19.0625
66
0.737705
7,673
package com.evolveum.midpoint.eclipse.runtime.api.resp; public class NotApplicableServerResponse extends ServerResponse { private String message; public NotApplicableServerResponse(String message) { this.message = message; } public String getMessage() { return message; } }
3e12331e7da615b064bf82aa43a69aa78eda1bdf
780
java
Java
src/main/java/com/example/houjie/studyapk/studyadapter/dao/LeftType.java
UremSept/StudyAPk
928bcb48e90b45e9a420883137ad78f626439f34
[ "Apache-2.0" ]
null
null
null
src/main/java/com/example/houjie/studyapk/studyadapter/dao/LeftType.java
UremSept/StudyAPk
928bcb48e90b45e9a420883137ad78f626439f34
[ "Apache-2.0" ]
null
null
null
src/main/java/com/example/houjie/studyapk/studyadapter/dao/LeftType.java
UremSept/StudyAPk
928bcb48e90b45e9a420883137ad78f626439f34
[ "Apache-2.0" ]
null
null
null
19.02439
68
0.637179
7,674
package com.example.houjie.studyapk.studyadapter.dao; import com.example.houjie.studyapk.studyadapter.adapter.ChatAdapter; import com.example.houjie.studyapk.studyadapter.bean.Type; /** * Created by houjie on 2016/4/8. */ public class LeftType implements Type { private int image; public int getImage() { return image; } public void setImage(int image) { this.image = image; } public String getmText() { return mText; } public void setmText(String mText) { this.mText = mText; } public LeftType(int image, String mText) { this.image = image; this.mText = mText; } private String mText; @Override public int getType() { return ChatAdapter.LEFTTYPE; } }
3e12337c501c908331a3a2fcf21ab74fdb797b61
789
java
Java
src/main/java/com/mindfire/review/web/repositories/ReviewBookRepository.java
pratyasam/review-app
eaa8329e168b62051bddf689e4b8e00bd5323c32
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mindfire/review/web/repositories/ReviewBookRepository.java
pratyasam/review-app
eaa8329e168b62051bddf689e4b8e00bd5323c32
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mindfire/review/web/repositories/ReviewBookRepository.java
pratyasam/review-app
eaa8329e168b62051bddf689e4b8e00bd5323c32
[ "Apache-2.0" ]
null
null
null
18.348837
79
0.647655
7,675
/** * */ package com.mindfire.review.web.repositories; import com.mindfire.review.web.models.Book; import com.mindfire.review.web.models.ReviewBook; import com.mindfire.review.web.models.User; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * @author pratyasa */ public interface ReviewBookRepository extends JpaRepository<ReviewBook, Long> { /** * @param user * @return */ List<ReviewBook> findByUser(User user); /** * @param book * @return */ List<ReviewBook> findByBook(Book book); /** * @param id * @return */ ReviewBook findByReviewBookId(Long id); /** * @param user,book * @return */ ReviewBook findByUserAndBook(User user, Book book); }
3e123470cfadf1cbd0e0797c3b2962413971c11c
247
java
Java
TSS.Java/src/tss/tpm/TPMU_CAPABILITIES.java
bterlson/TSS.MSR
49795340c4cb493df1a4bd67c50aa659298d78f6
[ "MIT" ]
2
2019-05-21T07:09:21.000Z
2019-09-03T11:58:27.000Z
TSS.Java/src/tss/tpm/TPMU_CAPABILITIES.java
bterlson/TSS.MSR
49795340c4cb493df1a4bd67c50aa659298d78f6
[ "MIT" ]
2
2020-07-10T19:25:36.000Z
2021-08-13T15:37:06.000Z
TSS.Java/src/tss/tpm/TPMU_CAPABILITIES.java
bterlson/TSS.MSR
49795340c4cb493df1a4bd67c50aa659298d78f6
[ "MIT" ]
1
2020-11-14T17:54:15.000Z
2020-11-14T17:54:15.000Z
14.529412
59
0.619433
7,676
package tss.tpm; import tss.*; // -----------This is an auto-generated file: do not edit //>>> /** * Table 110 Definition of TPMU_CAPABILITIES Union (OUT) */ public interface TPMU_CAPABILITIES extends TpmMarshaller { } //<<<
3e12365c57f8541f2e31ab86bdeff12cb2f9020b
7,299
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/NerdArmMove.java
sms-robotics/SkyStone2019
39e74032adccff628169b4a6e4e80fbb19cf8ced
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/NerdArmMove.java
sms-robotics/SkyStone2019
39e74032adccff628169b4a6e4e80fbb19cf8ced
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/NerdArmMove.java
sms-robotics/SkyStone2019
39e74032adccff628169b4a6e4e80fbb19cf8ced
[ "MIT" ]
null
null
null
33.791667
114
0.536375
7,677
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.util.ElapsedTime; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.util.ElapsedTime; import com.qualcomm.robotcore.util.RobotLog; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import org.firstinspires.ftc.robotcore.external.navigation.Position; import org.firstinspires.ftc.robotcore.external.navigation.Velocity; import com.qualcomm.robotcore.hardware.HardwareMap; public class NerdArmMove { public DcMotor rearMotor; public DcMotor frontMotor; private HardwareMap hardwareMap; LinearOpMode opmode; public NerdArmMove(LinearOpMode opmode) { this.opmode = opmode; this.hardwareMap = opmode.hardwareMap; } public void initHardware() { //frontMotor = hardwareMap.dcMotor.get("frontMotor"); //rearMotor = hardwareMap.dcMotor.get("rearMotor"); //rearMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); //frontMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); opmode.sleep(500); //rearMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); //frontMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); } private ElapsedTime FPIDTime = new ElapsedTime(); private ElapsedTime RPIDTime = new ElapsedTime(); private ElapsedTime PIDTime = new ElapsedTime(); public ElapsedTime Timeout = new ElapsedTime(); private double RPrevError = 0; private double FPrevError = 0; private double RTotalError = 0; private double FTotalError = 0; public double RSpeed = 0; public double FSpeed = 0; // private double FkP = 0.012; //0.012 // private double FkI = 0.001; //0.006 // private double FkD = 0.001;//0.0012 // // private double RkP = 0.0085; //0.009 // private double RkI = 0.000; //0.006 // private double RkD = 0.0009;//0.0008 private double FkP = 0.01; //0.012 private double FkI = 0.000; //0.001 private double FkD = 0.00;//0.001 private double RkP = 0.01; //0.0085 private double RkI = 0.000; //0.000 private double RkD = 0.000;//0.0009 private double MaxSpeedR = 0.8; private double MaxSpeedF = 0.5; public double MaxTimeOut = 0.5; private boolean EndConditionArmF = false; private boolean EndConditionArmR = false; public void ArmLoop(double TarPosR, double TarPosF, double MSR, double MSF) { RPrevError = 0; FPrevError = 0; RTotalError = 0; FTotalError = 0; RSpeed = 0; FSpeed = 0; EndConditionArmF = false; EndConditionArmR = false; Timeout.reset(); FPIDTime.reset(); RPIDTime.reset(); Timeout.reset(); while(Timeout.seconds() < MaxTimeOut) { PIDArm(rearMotor.getCurrentPosition(), TarPosR, RkP, RkI, RkD, 0, MSR); PIDArm(frontMotor.getCurrentPosition(), TarPosF, FkP, FkI, FkD, 1,MSF); rearMotor.setPower(RSpeed); frontMotor.setPower(FSpeed); } } public void UseTheForce() { rearMotor.setPower(-0.5); } //0 is rearMotor 1 is frontMotor \/ public void PIDArm(double EV, double TPos, double kP, double kI, double kD, int motor, double MaxSpeed) { double DError = 0; int DBanMin = -1; int DBanMax = 1; int MaxError = 10; double error = 0; double speed = 0; double TotalError = 0; double PrevError = 0; boolean EndConditionArm = false; if(motor == 0) { TotalError = RTotalError; PrevError = RPrevError; PIDTime = RPIDTime; EndConditionArm = EndConditionArmR; } else if(motor == 1){ TotalError = FTotalError; PrevError = FPrevError; PIDTime = FPIDTime; EndConditionArm = EndConditionArmF; } //calculate error (Proportional) error = TPos - EV; //Calculate Total error (Integral) TotalError = (error * PIDTime.seconds()) + TotalError; if(error < 5 && error > -5) {EndConditionArm = true;} else {EndConditionArm = false;} //do deadband if(DBanMax > error && error > DBanMin) { error = 0; //TotalError = 0; } //calculate delta error (Derivative) DError = (error - PrevError) / PIDTime.seconds(); //reset elapsed timer PIDTime.reset(); //Max total error if(Math.abs(TotalError) > MaxError) { if(TotalError > 0) { TotalError = MaxError; } else { TotalError = -MaxError; } } //Calculate final speed speed = (error * kP) + (TotalError * kI) + (DError * kD); //Make sure speed is no larger than MaxSpeed if(Math.abs(speed) > MaxSpeed) { if(speed > 0) { speed = MaxSpeed; } else { speed = -MaxSpeed; } } PrevError = error; if(motor == 0) { RSpeed = speed; RPrevError = PrevError; RTotalError = TotalError; EndConditionArmR = EndConditionArm; } else if(motor == 1) { FSpeed = speed; FPrevError = PrevError; FTotalError = TotalError; EndConditionArmF = EndConditionArm; } //set previous error to error //add telemetry } public void resetArm(){ this.RPrevError = 0; this.FPrevError = 0; this.RTotalError = 0; this.FTotalError = 0; this.RSpeed = 0; this.FSpeed = 0; this.EndConditionArmF = false; this.EndConditionArmR = false; this.Timeout.reset(); this.FPIDTime.reset(); this.RPIDTime.reset(); this.Timeout.reset(); } }
3e1236ee6ca2fbbdbae6078c2b5c301e68c37965
665
java
Java
reference/SoftReferenceTest.java
Tanglong9344/jl
8cb5afbc8770b5408d149abe42d675bb75560f8e
[ "MIT" ]
1
2018-01-05T05:50:07.000Z
2018-01-05T05:50:07.000Z
reference/SoftReferenceTest.java
Tanglong9344/JavaBasic
8cb5afbc8770b5408d149abe42d675bb75560f8e
[ "MIT" ]
null
null
null
reference/SoftReferenceTest.java
Tanglong9344/JavaBasic
8cb5afbc8770b5408d149abe42d675bb75560f8e
[ "MIT" ]
null
null
null
26.6
80
0.601504
7,678
import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.List; public class SoftReferenceTest{ public static void main(String[] args) { //List<House> houses = new ArrayList<>(); List<SoftReference> houses = new ArrayList<>(); int i = 0; while(true) { //houses.add(new House()); SoftReference<House> buyer2= new SoftReference<House>(new House()) ; houses.add(buyer2); System.out.println("i=" + (++i)); } } } class House { private static final Integer DOOR_NUMBER =2000; public Door[] doors = new Door[DOOR_NUMBER]; class Door {} }
3e1239ca3dfeafb48b671d7997770510dcda1c4b
6,139
java
Java
src/main/java/edu/utd/minecraft/mod/polycraft/entity/entityliving/ResearchAssistantEntity.java
PolycraftWorld/polycraft-world
cf4436277016033455307821f0d4d84a26f1ce48
[ "BSD-3-Clause" ]
null
null
null
src/main/java/edu/utd/minecraft/mod/polycraft/entity/entityliving/ResearchAssistantEntity.java
PolycraftWorld/polycraft-world
cf4436277016033455307821f0d4d84a26f1ce48
[ "BSD-3-Clause" ]
null
null
null
src/main/java/edu/utd/minecraft/mod/polycraft/entity/entityliving/ResearchAssistantEntity.java
PolycraftWorld/polycraft-world
cf4436277016033455307821f0d4d84a26f1ce48
[ "BSD-3-Clause" ]
null
null
null
44.485507
115
0.761036
7,679
package edu.utd.minecraft.mod.polycraft.entity.entityliving; import java.util.ArrayList; import java.util.Random; import net.minecraftforge.fml.common.registry.GameData; import edu.utd.minecraft.mod.polycraft.PolycraftMod; import edu.utd.minecraft.mod.polycraft.config.Armor; import edu.utd.minecraft.mod.polycraft.config.Inventory; import edu.utd.minecraft.mod.polycraft.config.PolycraftEntity; import edu.utd.minecraft.mod.polycraft.config.Tool; import edu.utd.minecraft.mod.polycraft.crafting.PolycraftContainerType; import edu.utd.minecraft.mod.polycraft.inventory.PolycraftInventory; import edu.utd.minecraft.mod.polycraft.inventory.computer.ComputerBlock; import edu.utd.minecraft.mod.polycraft.inventory.computer.ComputerInventory; import edu.utd.minecraft.mod.polycraft.item.ArmorSlot; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAIAttackOnCollide; import net.minecraft.entity.ai.EntityAIHurtByTarget; import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAINearestAttackableTarget; import net.minecraft.entity.ai.EntityAIOpenDoor; import net.minecraft.entity.ai.EntityAISwimming; import net.minecraft.entity.ai.EntityAIWander; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.passive.EntityTameable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.World; public class ResearchAssistantEntity extends EntityMob{ private static PolycraftEntity config; private static Random rngesus = new Random(); private static ArrayList<ItemSword> swords = null; private static ArrayList<ItemArmor[]> armors = null; private boolean inLab; public ResearchAssistantEntity(World p_i1738_1_, boolean lab) { super(p_i1738_1_); this.inLab = lab; //this.getNavigator().setBreakDoors(true); this.tasks.addTask(0, new EntityAISwimming(this)); this.tasks.addTask(1, new EntityAIOpenDoor(this, false)); this.tasks.addTask(2, new EntityAIAttackOnCollide(this, EntityPlayer.class, 1.0D, true)); this.tasks.addTask(4, new EntityAIAttackOnCollide(this, EntityTameable.class, 1.0D, true)); this.tasks.addTask(7, new EntityAIWander(this, 1.0D)); this.tasks.addTask(8, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F)); this.tasks.addTask(8, new EntityAILookIdle(this)); // Note: boolean val determines if to call for help. Should be false. this.targetTasks.addTask(0, new EntityAIHurtByTarget(this, false)); // Note: boolean val determines if LoS is required. this.targetTasks.addTask(1, new EntityAINearestAttackableTarget(this, EntityPlayer.class, false, true)); this.targetTasks.addTask(2, new EntityAINearestAttackableTarget(this, EntityTameable.class, false, true)); this.targetTasks.addTask(3, new EntityAINearestAttackableTarget(this, EntityPlayer.class, false, false)); if (armors == null) setEquipment(); ItemSword hold = swords.get(rngesus.nextInt(swords.size())); if (hold != null) this.setCurrentItemOrArmor(0, new ItemStack(hold)); ItemArmor[] wear = armors.get(rngesus.nextInt(armors.size())); if (wear[0] != null) for (int i = 0; i < 4; i++) this.setCurrentItemOrArmor(i + 1, new ItemStack(wear[i])); this.equipmentDropChances = new float[] { 0.5F, 0.1F, 0.1F, 0.1F, 0.1F }; } public ResearchAssistantEntity(World p_i1738_1_) { this(p_i1738_1_, false); } @Override protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(64.0D); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.5D); } @Override public boolean canDespawn() { return !inLab; } /** * Checks if the entity's current position is a valid location to spawn this * entity. */ @Override public boolean getCanSpawnHere() { return this.worldObj.getDifficulty() != EnumDifficulty.PEACEFUL && this.worldObj.checkNoEntityCollision(this.getEntityBoundingBox()) && this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox()).isEmpty() && !this.worldObj.isAnyLiquid(this.getEntityBoundingBox()); } @Override public boolean isAIDisabled() { return false; } private static void setEquipment() { armors = new ArrayList<ItemArmor[]>(Armor.registry.size() + 1); armors.add(new ItemArmor[] { null, null, null, null }); swords = new ArrayList<ItemSword>(Tool.registry.size() + 1); swords.add(null); for (Armor armor : Armor.registry.values()) { ItemArmor[] armorSet = new ItemArmor[4]; armorSet[ArmorSlot.HEAD.getInventoryArmorSlot()] = (ItemArmor) GameData.getItemRegistry() .getObject(PolycraftMod.getAssetName(armor.componentGameIDs[ArmorSlot.HEAD.getValue()])); armorSet[ArmorSlot.CHEST.getInventoryArmorSlot()] = (ItemArmor) GameData.getItemRegistry() .getObject(PolycraftMod.getAssetName(armor.componentGameIDs[ArmorSlot.CHEST.getValue()])); armorSet[ArmorSlot.LEGS.getInventoryArmorSlot()] = (ItemArmor) GameData.getItemRegistry() .getObject(PolycraftMod.getAssetName(armor.componentGameIDs[ArmorSlot.LEGS.getValue()])); armorSet[ArmorSlot.FEET.getInventoryArmorSlot()] = (ItemArmor) GameData.getItemRegistry() .getObject(PolycraftMod.getAssetName(armor.componentGameIDs[ArmorSlot.FEET.getValue()])); armors.add(armorSet); } for (Tool tool : Tool.registry.values()) { ItemSword sword = (ItemSword) GameData.getItemRegistry() .getObject(PolycraftMod.getAssetName(tool.typeGameIDs[Tool.Type.SWORD.ordinal()])); swords.add(sword); } } public static final void register(final PolycraftEntity polycraftEntity) { ResearchAssistantEntity.config = polycraftEntity; PolycraftEntityLiving.register(ResearchAssistantEntity.class, config.entityID, config.name, 0xFFFFFF, 0x88D7FC); } }
3e123a107f6b9396af2110d72ef254a9d9576e8f
17,543
java
Java
src/nom/tam/util/ByteParser.java
suvarchal/ramadda
3c3dd266aa4b290a003f202471a41e953f7ee5e7
[ "Apache-2.0" ]
null
null
null
src/nom/tam/util/ByteParser.java
suvarchal/ramadda
3c3dd266aa4b290a003f202471a41e953f7ee5e7
[ "Apache-2.0" ]
null
null
null
src/nom/tam/util/ByteParser.java
suvarchal/ramadda
3c3dd266aa4b290a003f202471a41e953f7ee5e7
[ "Apache-2.0" ]
null
null
null
28.618271
92
0.47489
7,680
package nom.tam.util; import java.io.UnsupportedEncodingException; import java.util.logging.Level; import java.util.logging.Logger; /** * This class provides routines * for efficient parsing of data stored in a byte array. * This routine is optimized (in theory at least!) for efficiency * rather than accuracy. The values read in for doubles or floats * may differ in the last bit or so from the standard input * utilities, especially in the case where a float is specified * as a very long string of digits (substantially longer than * the precision of the type). * <p> * The get methods generally are available with or without a length * parameter specified. When a length parameter is specified only * the bytes with the specified range from the current offset will * be search for the number. If no length is specified, the entire * buffer from the current offset will be searched. * <p> * The getString method returns a string with leading and trailing * white space left intact. For all other get calls, leading * white space is ignored. If fillFields is set, then the get * methods check that only white space follows valid data and a * FormatException is thrown if that is not the case. If * fillFields is not set and valid data is found, then the * methods return having read as much as possible. E.g., for * the sequence "T123.258E13", a getBoolean, getInteger and * getFloat call would return true, 123, and 2.58e12 when * called in succession. * */ public class ByteParser { /** Array being parsed */ private byte[] input; /** Current offset into input. */ private int offset; /** Length of last parsed value */ private int numberLength; /** Did we find a sign last time we checked? */ private boolean foundSign; /** Do we fill up fields? */ private boolean fillFields = false; /** * Construct a parser. * @param input The byte array to be parsed. * Note that the array can be re-used by * refilling its contents and resetting the offset. */ public ByteParser(byte[] input) { this.input = input; this.offset = 0; } /** * Set the buffer for the parser * * @param buf _more_ */ public void setBuffer(byte[] buf) { this.input = buf; this.offset = 0; } /** * Get the buffer being used by the parser * * @return _more_ */ public byte[] getBuffer() { return input; } /** * Set the offset into the array. * @param offset The desired offset from the beginning * of the array. */ public void setOffset(int offset) { this.offset = offset; } /** * Do we require a field to completely fill up the specified * length (with optional leading and trailing white space. * @param flag Is filling required? */ public void setFillFields(boolean flag) { fillFields = flag; } /** * Get the current offset * @return The current offset within the buffer. */ public int getOffset() { return offset; } /** * Get the number of characters used to parse the previous * number (or the length of the previous String returned). * * @return _more_ */ public int getNumberLength() { return numberLength; } /** * Read in the buffer until a double is read. This will read * the entire buffer if fillFields is set. * @return The value found. * * @throws FormatException _more_ */ public double getDouble() throws FormatException { return getDouble(input.length - offset); } /** * Look for a double in the buffer. * Leading spaces are ignored. * @param length The maximum number of characters * used to parse this number. If fillFields * is specified then exactly only whitespace may follow * a valid double value. * * @return _more_ * * @throws FormatException _more_ */ public double getDouble(int length) throws FormatException { int startOffset = offset; boolean error = true; double number = 0; int i = 0; // Skip initial blanks. length -= skipWhite(length); if (length == 0) { numberLength = offset - startOffset; return 0; } double mantissaSign = checkSign(); if (foundSign) { length -= 1; } // Look for the special strings NaN, Inf, if ((length >= 3) && ((input[offset] == 'n') || (input[offset] == 'N')) && ((input[offset + 1] == 'a') || (input[offset + 1] == 'A')) && ((input[offset + 2] == 'n') || (input[offset + 2] == 'N'))) { number = Double.NaN; length -= 3; offset += 3; // Look for the longer string first then try the shorter. } else if ((length >= 8) && ((input[offset] == 'i') || (input[offset] == 'I')) && ((input[offset + 1] == 'n') || (input[offset + 1] == 'N')) && ((input[offset + 2] == 'f') || (input[offset + 2] == 'F')) && ((input[offset + 3] == 'i') || (input[offset + 3] == 'I')) && ((input[offset + 4] == 'n') || (input[offset + 4] == 'N')) && ((input[offset + 5] == 'i') || (input[offset + 5] == 'I')) && ((input[offset + 6] == 't') || (input[offset + 6] == 'T')) && ((input[offset + 7] == 'y') || (input[offset + 7] == 'Y'))) { number = Double.POSITIVE_INFINITY; length -= 8; offset += 8; } else if ((length >= 3) && ((input[offset] == 'i') || (input[offset] == 'I')) && ((input[offset + 1] == 'n') || (input[offset + 1] == 'N')) && ((input[offset + 2] == 'f') || (input[offset + 2] == 'F'))) { number = Double.POSITIVE_INFINITY; length -= 3; offset += 3; } else { number = getBareInteger(length); // This will update offset length -= numberLength; // Set by getBareInteger if (numberLength > 0) { error = false; } // Check for fractional values after decimal if ((length > 0) && (input[offset] == '.')) { offset += 1; length -= 1; double numerator = getBareInteger(length); if (numerator > 0) { number += numerator / Math.pow(10., numberLength); } length -= numberLength; if (numberLength > 0) { error = false; } } if (error) { offset = startOffset; numberLength = 0; throw new FormatException("Invalid real field"); } // Look for an exponent if (length > 0) { // Our Fortran heritage means that we allow 'D' for the exponent indicator. if ((input[offset] == 'e') || (input[offset] == 'E') || (input[offset] == 'd') || (input[offset] == 'D')) { offset += 1; length -= 1; if (length > 0) { int sign = checkSign(); if (foundSign) { length -= 1; } int exponent = (int) getBareInteger(length); // For very small numbers we try to miminize // effects of denormalization. if (exponent * sign > -300) { number *= Math.pow(10., exponent * sign); } else { number = 1.e-300 * (number * Math.pow(10., exponent * sign + 300)); } length -= numberLength; } } } } if (fillFields && (length > 0)) { if (isWhite(length)) { offset += length; } else { numberLength = 0; offset = startOffset; throw new FormatException("Non-blanks following real."); } } numberLength = offset - startOffset; return mantissaSign * number; } /** * Get a floating point value from the buffer. (see getDouble(int()) * * @return _more_ * * @throws FormatException _more_ */ public float getFloat() throws FormatException { return (float) getDouble(input.length - offset); } /** * Get a floating point value in a region of the buffer * * @param length _more_ * * @return _more_ * * @throws FormatException _more_ */ public float getFloat(int length) throws FormatException { return (float) getDouble(length); } /** * Convert a region of the buffer to an integer * * @param length _more_ * * @return _more_ * * @throws FormatException _more_ */ public int getInt(int length) throws FormatException { int startOffset = offset; length -= skipWhite(length); if (length == 0) { numberLength = offset - startOffset; return 0; } int number = 0; boolean error = true; int sign = checkSign(); if (foundSign) { length -= 1; } while ((length > 0) && (input[offset] >= '0') && (input[offset] <= '9')) { number = number * 10 + input[offset] - '0'; offset += 1; length -= 1; error = false; } if (error) { numberLength = 0; offset = startOffset; throw new FormatException("Invalid Integer"); } if ((length > 0) && fillFields) { if (isWhite(length)) { offset += length; } else { numberLength = 0; offset = startOffset; throw new FormatException("Non-white following integer"); } } numberLength = offset - startOffset; return sign * number; } /** * Look for an integer at the beginning of the buffer * * @return _more_ * * @throws FormatException _more_ */ public int getInt() throws FormatException { return getInt(input.length - offset); } /** * Look for a long in a specified region of the buffer * * @param length _more_ * * @return _more_ * * @throws FormatException _more_ */ public long getLong(int length) throws FormatException { int startOffset = offset; // Skip white space. length -= skipWhite(length); if (length == 0) { numberLength = offset - startOffset; return 0; } long number = 0; boolean error = true; long sign = checkSign(); if (foundSign) { length -= 1; } while ((length > 0) && (input[offset] >= '0') && (input[offset] <= '9')) { number = number * 10 + input[offset] - '0'; error = false; offset += 1; length -= 1; } if (error) { numberLength = 0; offset = startOffset; throw new FormatException("Invalid long number"); } if ((length > 0) && fillFields) { if (isWhite(length)) { offset += length; } else { offset = startOffset; numberLength = 0; throw new FormatException("Non-white following long"); } } numberLength = offset - startOffset; return sign * number; } /** * Get a string * @param length The length of the string. * * @return _more_ */ public String getString(int length) { String s = AsciiFuncs.asciiString(input, offset, length); offset += length; numberLength = length; return s; } /** * Get a boolean value from the beginning of the buffer * * @return _more_ * * @throws FormatException _more_ */ public boolean getBoolean() throws FormatException { return getBoolean(input.length - offset); } /** * Get a boolean value from a specified region of the buffer * * @param length _more_ * * @return _more_ * * @throws FormatException _more_ */ public boolean getBoolean(int length) throws FormatException { int startOffset = offset; length -= skipWhite(length); if (length == 0) { throw new FormatException("Blank boolean field"); } boolean value = false; if ((input[offset] == 'T') || (input[offset] == 't')) { value = true; } else if ((input[offset] != 'F') && (input[offset] != 'f')) { numberLength = 0; offset = startOffset; throw new FormatException("Invalid boolean value"); } offset += 1; length -= 1; if (fillFields && (length > 0)) { if (isWhite(length)) { offset += length; } else { numberLength = 0; offset = startOffset; throw new FormatException("Non-white following boolean"); } } numberLength = offset - startOffset; return value; } /** * Skip bytes in the buffer * * @param nBytes _more_ */ public void skip(int nBytes) { offset += nBytes; } /** * Get the integer value starting at the current position. * This routine returns a double rather than an int/long * to enable it to read very long integers (with reduced * precision) such as 111111111111111111111111111111111111111111. * Note that this routine does set numberLength. * * @param length The maximum number of characters to use. * * @return _more_ */ private double getBareInteger(int length) { int startOffset = offset; double number = 0; while ((length > 0) && (input[offset] >= '0') && (input[offset] <= '9')) { number *= 10; number += input[offset] - '0'; offset += 1; length -= 1; } numberLength = offset - startOffset; return number; } /** * Skip white space. This routine skips with space in * the input and returns the number of character skipped. * White space is defined as ' ', '\t', '\n' or '\r' * * @param length The maximum number of characters to skip. * * @return _more_ */ public int skipWhite(int length) { int i; for (i = 0; i < length; i += 1) { if ((input[offset + i] != ' ') && (input[offset + i] != '\t') && (input[offset + i] != '\n') && (input[offset + i] != '\r')) { break; } } offset += i; return i; } /** * Find the sign for a number . * This routine looks for a sign (+/-) at the current location * and return +1/-1 if one is found, or +1 if not. * The foundSign boolean is set if a sign is found and offset is * incremented. * * @return _more_ */ private int checkSign() { foundSign = false; if (input[offset] == '+') { foundSign = true; offset += 1; return 1; } else if (input[offset] == '-') { foundSign = true; offset += 1; return -1; } return 1; } /** * Is a region blank? * @param length The length of the region to be tested * * @return _more_ */ private boolean isWhite(int length) { int oldOffset = offset; boolean value = skipWhite(length) == length; offset = oldOffset; return value; } }
3e123ae8fdf8b1d8f351dadf30a3924711190653
647
java
Java
src/main/java/weixin/popular/bean/shakearound/statistics/page/StatisticsPage.java
evanyangg/weixin-popular
646afc7e6ef8899c56e8d5db8094f308426d568f
[ "Apache-2.0" ]
2,606
2015-01-15T09:45:11.000Z
2022-03-31T09:22:18.000Z
src/main/java/weixin/popular/bean/shakearound/statistics/page/StatisticsPage.java
evanyangg/weixin-popular
646afc7e6ef8899c56e8d5db8094f308426d568f
[ "Apache-2.0" ]
202
2015-01-06T08:59:45.000Z
2022-02-16T03:18:14.000Z
src/main/java/weixin/popular/bean/shakearound/statistics/page/StatisticsPage.java
evanyangg/weixin-popular
646afc7e6ef8899c56e8d5db8094f308426d568f
[ "Apache-2.0" ]
1,175
2015-01-05T14:36:48.000Z
2022-03-31T02:09:53.000Z
16.175
70
0.636785
7,681
/** * */ package weixin.popular.bean.shakearound.statistics.page; import weixin.popular.bean.shakearound.statistics.AbstractStatistics; import com.alibaba.fastjson.annotation.JSONField; /** * 微信摇一摇周边-以页面为维度的数据统计接口 * @author Moyq5 * @date 2016年7月31日 */ public class StatisticsPage extends AbstractStatistics { /** * 页面ID<br> * 必填 */ @JSONField(name = "page_id") private Integer pageId; /** * @return 页面ID */ public Integer getPageId() { return pageId; } /** * 页面ID<br> * 必填 * @param pageId 页面ID */ public void setPageId(Integer pageId) { this.pageId = pageId; } }
3e123b083987376542fcaf60f09437a872a356ba
16,164
java
Java
apis/api-core/api-core-common/src/main/java/org/hoteia/qalingo/core/domain/ProductMarketing.java
AppSecAI-TEST/qalingo-engine
7380084369034012d9ad6cb1ab4973ce7960aa2d
[ "Apache-2.0" ]
321
2015-01-04T08:13:13.000Z
2021-12-29T02:27:29.000Z
apis/api-core/api-core-common/src/main/java/org/hoteia/qalingo/core/domain/ProductMarketing.java
AppSecAI-TEST/qalingo-engine
7380084369034012d9ad6cb1ab4973ce7960aa2d
[ "Apache-2.0" ]
24
2021-04-02T13:21:00.000Z
2022-02-10T09:22:15.000Z
apis/api-core/api-core-common/src/main/java/org/hoteia/qalingo/core/domain/ProductMarketing.java
Rostov1991/qalingo-engine
cd48ffe14fe2a6a14e3fbb777b3e2ce6a7454621
[ "Apache-2.0" ]
220
2015-01-04T08:04:53.000Z
2022-01-25T06:46:44.000Z
33.261317
169
0.635076
7,682
/** * Most of the code in the Qalingo project is copyrighted Hoteia and licensed * under the Apache License Version 2.0 (release version 0.8.0) * http://www.apache.org/licenses/LICENSE-2.0 * * Copyright (c) Hoteia, 2012-2014 * http://www.hoteia.com - http://twitter.com/hoteia - hzdkv@example.com * */ package org.hoteia.qalingo.core.domain; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.persistence.Version; import org.apache.commons.lang.StringUtils; import org.hibernate.Hibernate; import org.hoteia.qalingo.core.annotation.CacheEntityInformation; import org.hoteia.qalingo.core.domain.impl.DomainEntity; @Entity @Table(name="TECO_PRODUCT_MARKETING") @CacheEntityInformation(cacheName="web_cache_product_marketing") public class ProductMarketing extends AbstractExtendEntity<ProductMarketing, ProductMarketingAttribute> implements DomainEntity { /** * Generated UID */ private static final long serialVersionUID = 5408836788685407465L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ID", nullable = false) private Long id; @Version @Column(name = "VERSION", nullable = false) // , columnDefinition = "int(11) default 1" private int version; @Column(name = "SCORING", nullable = false) // , columnDefinition = "default 1" private long scoring; @Column(name = "CODE", unique = true, nullable = false) private String code; @Column(name = "NAME") private String name; @Column(name = "DESCRIPTION") @Lob private String description; @Column(name = "IS_DEFAULT", nullable = false) // , columnDefinition = "tinyint(1) default 0" private boolean isDefault = false; @Column(name = "IS_ENABLED_B2B", nullable = false) // , columnDefinition = "tinyint(1) default 0" private boolean enabledB2B = false; @Column(name = "IS_ENABLED_B2C", nullable = false) // , columnDefinition = "tinyint(1) default 0" private boolean enabledB2C = false; @ManyToOne(fetch = FetchType.LAZY, targetEntity = org.hoteia.qalingo.core.domain.ProductBrand.class) @JoinColumn(name = "PRODUCT_BRAND_ID", insertable = true, updatable = true) private ProductBrand productBrand; @ManyToOne(fetch = FetchType.LAZY, targetEntity = org.hoteia.qalingo.core.domain.ProductMarketingType.class) @JoinColumn(name = "PRODUCT_MARKETING_TYPE_ID", insertable = true, updatable = true) private ProductMarketingType productMarketingType; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity = org.hoteia.qalingo.core.domain.ProductMarketingAttribute.class) @JoinColumn(name = "PRODUCT_MARKETING_ID") private Set<ProductMarketingAttribute> attributes = new HashSet<ProductMarketingAttribute>(); @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity = org.hoteia.qalingo.core.domain.ProductSku.class) @JoinColumn(name = "PRODUCT_MARKETING_ID") private Set<ProductSku> productSkus = new HashSet<ProductSku>(); @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity = org.hoteia.qalingo.core.domain.ProductAssociationLink.class) @JoinColumn(name = "PRODUCT_MARKETING_ID") private Set<ProductAssociationLink> productAssociationLinks = new HashSet<ProductAssociationLink>(); @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity = org.hoteia.qalingo.core.domain.Asset.class) @JoinColumn(name = "PRODUCT_MARKETING_ID") private Set<Asset> assets = new HashSet<Asset>(); @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity = org.hoteia.qalingo.core.domain.ProductMarketingCustomerRate.class) @JoinColumn(name = "PRODUCT_MARKETING_ID") private Set<ProductMarketingCustomerRate> customerRates = new HashSet<ProductMarketingCustomerRate>(); @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity = org.hoteia.qalingo.core.domain.ProductMarketingCustomerComment.class) @JoinColumn(name = "PRODUCT_MARKETING_ID") private Set<ProductMarketingCustomerComment> customerComments = new HashSet<ProductMarketingCustomerComment>(); @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity = org.hoteia.qalingo.core.domain.ProductMarketingTagRel.class) @JoinColumn(name = "PRODUCT_MARKETING_ID") private Set<ProductMarketingTagRel> tagRels = new HashSet<ProductMarketingTagRel>(); @Transient private int ranking; @Temporal(TemporalType.TIMESTAMP) @Column(name = "DATE_CREATE") private Date dateCreate; @Temporal(TemporalType.TIMESTAMP) @Column(name = "DATE_UPDATE") private Date dateUpdate; public ProductMarketing(){ this.dateCreate = new Date(); this.dateUpdate = new Date(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public long getScoring() { return scoring; } public void setScoring(long scoring) { this.scoring = scoring; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isDefault() { return isDefault; } public void setDefault(boolean isDefault) { this.isDefault = isDefault; } public boolean isEnabledB2B() { return enabledB2B; } public void setEnabledB2B(boolean enabledB2B) { this.enabledB2B = enabledB2B; } public boolean isEnabledB2C() { return enabledB2C; } public void setEnabledB2C(boolean enabledB2C) { this.enabledB2C = enabledB2C; } public boolean isSalableB2B() { if(productSkus != null && Hibernate.isInitialized(productSkus) && !productSkus.isEmpty()){ for (Iterator<ProductSku> iterator = productSkus.iterator(); iterator.hasNext();) { ProductSku productSku = (ProductSku) iterator.next(); if(productSku.isSalableB2B()){ return true; } } } return false; } public boolean isSalableB2C() { if(productSkus != null && Hibernate.isInitialized(productSkus) && !productSkus.isEmpty()){ for (Iterator<ProductSku> iterator = productSkus.iterator(); iterator.hasNext();) { ProductSku productSku = (ProductSku) iterator.next(); if(productSku.isSalableB2C()){ return true; } } } return false; } public ProductBrand getProductBrand() { return productBrand; } public void setProductBrand(ProductBrand productBrand) { this.productBrand = productBrand; } public ProductMarketingType getProductMarketingType() { return productMarketingType; } public void setProductMarketingType(ProductMarketingType productMargetingType) { this.productMarketingType = productMargetingType; } public Set<ProductMarketingAttribute> getAttributes() { return attributes; } public void setAttributes(Set<ProductMarketingAttribute> attributes) { this.attributes = attributes; } public Set<ProductSku> getProductSkus() { return productSkus; } public ProductSku getDefaultProductSku() { ProductSku defaultProductSku = null; if(productSkus != null && Hibernate.isInitialized(productSkus) && !productSkus.isEmpty()){ for (Iterator<ProductSku> iterator = productSkus.iterator(); iterator.hasNext();) { ProductSku productSku = (ProductSku) iterator.next(); if(productSku.isDefault()){ defaultProductSku = productSku; } } if(defaultProductSku == null){ defaultProductSku = (ProductSku) productSkus.iterator().next(); } } return defaultProductSku; } public List<String> getSkuCodes() { List<String> skuCodes = new ArrayList<String>(); if(productSkus != null && Hibernate.isInitialized(productSkus) && !productSkus.isEmpty()){ for (Iterator<ProductSku> iterator = getProductSkus().iterator(); iterator.hasNext();) { ProductSku sku = (ProductSku) iterator.next(); skuCodes.add(sku.getCode()); } } return skuCodes; } public void setProductSkus(Set<ProductSku> productSkus) { this.productSkus = productSkus; } public Set<ProductAssociationLink> getProductAssociationLinks() { return productAssociationLinks; } public void setProductAssociationLinks(Set<ProductAssociationLink> productAssociationLinks) { this.productAssociationLinks = productAssociationLinks; } public Set<Asset> getAssets() { return assets; } public void setAssets(Set<Asset> assets) { this.assets = assets; } public List<Asset> getAssetsIsGlobal() { List<Asset> assetsIsGlobal = null; if (assets != null && Hibernate.isInitialized(assets)) { assetsIsGlobal = new ArrayList<Asset>(); for (Iterator<Asset> iterator = assets.iterator(); iterator.hasNext();) { Asset asset = (Asset) iterator.next(); if (asset != null && asset.isGlobal()) { assetsIsGlobal.add(asset); } } } return assetsIsGlobal; } public List<Asset> getAssetsByMarketArea() { List<Asset> assetsByMarketArea = null; if (assets != null && Hibernate.isInitialized(assets)) { assetsByMarketArea = new ArrayList<Asset>(); for (Iterator<Asset> iterator = assets.iterator(); iterator.hasNext();) { Asset asset = (Asset) iterator.next(); if (asset != null && !asset.isGlobal()) { assetsByMarketArea.add(asset); } } } return assetsByMarketArea; } public Set<ProductMarketingCustomerRate> getCustomerRates() { return customerRates; } public void setCustomerRates(Set<ProductMarketingCustomerRate> customerRates) { this.customerRates = customerRates; } public Set<ProductMarketingCustomerComment> getCustomerComments() { return customerComments; } public void setCustomerComments(Set<ProductMarketingCustomerComment> customerComments) { this.customerComments = customerComments; } public Set<ProductMarketingTagRel> getTagRels() { return tagRels; } public List<Tag> getTags() { List<Tag> tags = null; if (Hibernate.isInitialized(tagRels) && !tagRels.isEmpty()) { tags = new ArrayList<Tag>(); for (Iterator<ProductMarketingTagRel> iterator = tagRels.iterator(); iterator.hasNext();) { ProductMarketingTagRel productMarketingTagRel = (ProductMarketingTagRel) iterator.next(); if(Hibernate.isInitialized(productMarketingTagRel.getPk().getTag()) && productMarketingTagRel.getPk().getTag() != null){ tags.add(productMarketingTagRel.getProductMarketingTag()); } } } return tags; } public void setTagRels(Set<ProductMarketingTagRel> tagRels) { this.tagRels = tagRels; } public int getRanking() { return ranking; } public void setRanking(int ranking) { this.ranking = ranking; } public Date getDateCreate() { return dateCreate; } public void setDateCreate(Date dateCreate) { this.dateCreate = dateCreate; } public Date getDateUpdate() { return dateUpdate; } public void setDateUpdate(Date dateUpdate) { this.dateUpdate = dateUpdate; } // Attributes public Object getValue(String attributeCode, Long marketAreaId, String localizationCode) { AbstractAttribute attribute = getAttribute(attributeCode, marketAreaId, localizationCode); if(attribute != null) { return attribute.getValue(); } return null; } public String getI18nName(String localizationCode) { String i18nName = (String) getValue(ProductMarketingAttribute.PRODUCT_MARKETING_ATTRIBUTE_I18N_NAME, null, localizationCode); if (StringUtils.isEmpty(i18nName)) { i18nName = getName(); } return i18nName; } public String getI18nDescription(String localizationCode) { String i18Description = (String) getValue(ProductMarketingAttribute.PRODUCT_MARKETING_ATTRIBUTE_I18N_DESCRIPTION, null, localizationCode); if (StringUtils.isNotEmpty(i18Description)) { return i18Description; } return description; } public Boolean isFeatured() { Boolean isFeatured = (Boolean) getValue(ProductMarketingAttribute.PRODUCT_MARKETING_ATTRIBUTE_FEATURED, null, null); if (isFeatured == null) { return Boolean.FALSE; } else { return isFeatured; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((code == null) ? 0 : code.hashCode()); result = prime * result + ((dateCreate == null) ? 0 : dateCreate.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object sourceObj) { Object obj = deproxy(sourceObj); if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ProductMarketing other = (ProductMarketing) obj; if (code == null) { if (other.code != null) return false; } else if (!code.equals(other.code)) return false; if (dateCreate == null) { if (other.dateCreate != null) return false; } else if (!dateCreate.equals(other.dateCreate)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public String toString() { return "ProductMarketing [id=" + id + ", version=" + version + ", name=" + name + ", description=" + description + ", isDefault=" + isDefault + ", code=" + code + ", dateCreate=" + dateCreate + ", dateUpdate=" + dateUpdate + "]"; } }
3e123b210a84adebe3841026ba31a85e383ab496
662
java
Java
src/main/java/com/ag/grid/enterprise/oracle/demo/filter/NumberColumnFilter.java
golovan/ag-grid-server-side-oracle-example
4d9d50028c143458768bbb9a39c41273e0c5cff7
[ "MIT" ]
14
2018-11-01T14:02:08.000Z
2021-09-08T07:56:00.000Z
src/main/java/com/ag/grid/enterprise/oracle/demo/filter/NumberColumnFilter.java
golovan/ag-grid-server-side-oracle-example
4d9d50028c143458768bbb9a39c41273e0c5cff7
[ "MIT" ]
1
2021-03-31T22:28:07.000Z
2021-03-31T22:28:07.000Z
src/main/java/com/ag/grid/enterprise/oracle/demo/filter/NumberColumnFilter.java
golovan/ag-grid-server-side-oracle-example
4d9d50028c143458768bbb9a39c41273e0c5cff7
[ "MIT" ]
25
2018-05-14T19:35:36.000Z
2022-03-02T15:43:29.000Z
20.6875
78
0.641994
7,683
package com.ag.grid.enterprise.oracle.demo.filter; public class NumberColumnFilter extends ColumnFilter { private String type; private Integer filter; private Integer filterTo; public NumberColumnFilter() {} public NumberColumnFilter(String type, Integer filter, Integer filterTo) { this.type = type; this.filter = filter; this.filterTo = filterTo; } public String getFilterType() { return filterType; } public String getType() { return type; } public Integer getFilter() { return filter; } public Integer getFilterTo() { return filterTo; } }
3e123c2199fd18a61c5cf81533b1b5087c99f09d
3,917
java
Java
src/main/java/net/minecraft/block/BlockEnderChest.java
AspireWorld-Project/AspireCore
61dfc4f6cc7bca4ed7fd4de1413b7c8030a72042
[ "WTFPL" ]
null
null
null
src/main/java/net/minecraft/block/BlockEnderChest.java
AspireWorld-Project/AspireCore
61dfc4f6cc7bca4ed7fd4de1413b7c8030a72042
[ "WTFPL" ]
null
null
null
src/main/java/net/minecraft/block/BlockEnderChest.java
AspireWorld-Project/AspireCore
61dfc4f6cc7bca4ed7fd4de1413b7c8030a72042
[ "WTFPL" ]
null
null
null
28.384058
107
0.730917
7,684
package net.minecraft.block; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.inventory.InventoryEnderChest; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityEnderChest; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import java.util.Random; public class BlockEnderChest extends BlockContainer { protected BlockEnderChest() { super(Material.rock); setCreativeTab(CreativeTabs.tabDecorations); setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); } @Override public boolean isOpaqueCube() { return false; } @Override public boolean renderAsNormalBlock() { return false; } @Override public int getRenderType() { return 22; } @Override public Item getItemDropped(int p_149650_1_, Random p_149650_2_, int p_149650_3_) { return Item.getItemFromBlock(Blocks.obsidian); } @Override public int quantityDropped(Random p_149745_1_) { return 8; } @Override protected boolean canSilkHarvest() { return true; } @Override public void onBlockPlacedBy(World p_149689_1_, int p_149689_2_, int p_149689_3_, int p_149689_4_, EntityLivingBase p_149689_5_, ItemStack p_149689_6_) { byte b0 = 0; int l = MathHelper.floor_double(p_149689_5_.rotationYaw * 4.0F / 360.0F + 0.5D) & 3; if (l == 0) { b0 = 2; } if (l == 1) { b0 = 5; } if (l == 2) { b0 = 3; } if (l == 3) { b0 = 4; } p_149689_1_.setBlockMetadataWithNotify(p_149689_2_, p_149689_3_, p_149689_4_, b0, 2); } @Override public boolean onBlockActivated(World p_149727_1_, int p_149727_2_, int p_149727_3_, int p_149727_4_, EntityPlayer p_149727_5_, int p_149727_6_, float p_149727_7_, float p_149727_8_, float p_149727_9_) { InventoryEnderChest inventoryenderchest = p_149727_5_.getInventoryEnderChest(); TileEntityEnderChest tileentityenderchest = (TileEntityEnderChest) p_149727_1_.getTileEntity(p_149727_2_, p_149727_3_, p_149727_4_); if (inventoryenderchest != null && tileentityenderchest != null) { if (p_149727_1_.getBlock(p_149727_2_, p_149727_3_ + 1, p_149727_4_).isNormalCube()) return true; else if (p_149727_1_.isRemote) return true; else { inventoryenderchest.func_146031_a(tileentityenderchest); p_149727_5_.displayGUIChest(inventoryenderchest); return true; } } else return true; } @Override public TileEntity createNewTileEntity(World p_149915_1_, int p_149915_2_) { return new TileEntityEnderChest(); } @Override @SideOnly(Side.CLIENT) public void randomDisplayTick(World p_149734_1_, int p_149734_2_, int p_149734_3_, int p_149734_4_, Random p_149734_5_) { for (int l = 0; l < 3; ++l) { p_149734_5_.nextFloat(); double d1 = p_149734_3_ + p_149734_5_.nextFloat(); // p_149734_4_ + p_149734_5_.nextFloat(); double d3 = 0.0D; double d4 = 0.0D; double d5 = 0.0D; int i1 = p_149734_5_.nextInt(2) * 2 - 1; int j1 = p_149734_5_.nextInt(2) * 2 - 1; d3 = (p_149734_5_.nextFloat() - 0.5D) * 0.125D; d4 = (p_149734_5_.nextFloat() - 0.5D) * 0.125D; d5 = (p_149734_5_.nextFloat() - 0.5D) * 0.125D; double d2 = p_149734_4_ + 0.5D + 0.25D * j1; d5 = p_149734_5_.nextFloat() * 1.0F * j1; double d0 = p_149734_2_ + 0.5D + 0.25D * i1; d3 = p_149734_5_.nextFloat() * 1.0F * i1; p_149734_1_.spawnParticle("portal", d0, d1, d2, d3, d4, d5); } } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister p_149651_1_) { blockIcon = p_149651_1_.registerIcon("obsidian"); } }
3e123c962d1135bf701c2c2f5f0d9cbcb8a3f69e
20,898
java
Java
java/com/android/dialer/calllog/datasources/systemcalllog/SystemCallLogDataSource.java
unknownyard/packages_apps_Dialer
889165652e2bf4688593d590bc36741740be8890
[ "Apache-2.0" ]
34
2017-01-17T07:05:15.000Z
2022-03-04T02:45:13.000Z
java/com/android/dialer/calllog/datasources/systemcalllog/SystemCallLogDataSource.java
unknownyard/packages_apps_Dialer
889165652e2bf4688593d590bc36741740be8890
[ "Apache-2.0" ]
10
2017-01-14T02:21:01.000Z
2020-01-19T17:08:11.000Z
java/com/android/dialer/calllog/datasources/systemcalllog/SystemCallLogDataSource.java
unknownyard/packages_apps_Dialer
889165652e2bf4688593d590bc36741740be8890
[ "Apache-2.0" ]
285
2016-12-28T19:54:49.000Z
2022-03-26T09:24:56.000Z
39.881679
100
0.718107
7,685
/* * Copyright (C) 2017 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.android.dialer.calllog.datasources.systemcalllog; import android.Manifest.permission; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.provider.CallLog; import android.provider.CallLog.Calls; import android.provider.VoicemailContract; import android.provider.VoicemailContract.Voicemails; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.annotation.VisibleForTesting; import android.support.annotation.WorkerThread; import android.telephony.PhoneNumberUtils; import android.text.TextUtils; import android.util.ArraySet; import com.android.dialer.DialerPhoneNumber; import com.android.dialer.calllog.database.AnnotatedCallLogDatabaseHelper; import com.android.dialer.calllog.database.contract.AnnotatedCallLogContract.AnnotatedCallLog; import com.android.dialer.calllog.datasources.CallLogDataSource; import com.android.dialer.calllog.datasources.CallLogMutations; import com.android.dialer.calllog.observer.MarkDirtyObserver; import com.android.dialer.common.Assert; import com.android.dialer.common.LogUtil; import com.android.dialer.common.concurrent.Annotations.BackgroundExecutor; import com.android.dialer.compat.android.provider.VoicemailCompat; import com.android.dialer.duo.Duo; import com.android.dialer.inject.ApplicationContext; import com.android.dialer.phonenumberproto.DialerPhoneNumberUtil; import com.android.dialer.storage.Unencrypted; import com.android.dialer.util.PermissionsUtil; import com.google.common.collect.Iterables; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import javax.inject.Inject; import javax.inject.Singleton; /** * Responsible for defining the rows in the annotated call log and maintaining the columns in it * which are derived from the system call log. */ @Singleton @SuppressWarnings("MissingPermission") public class SystemCallLogDataSource implements CallLogDataSource { @VisibleForTesting static final String PREF_LAST_TIMESTAMP_PROCESSED = "systemCallLogLastTimestampProcessed"; private final Context appContext; private final ListeningExecutorService backgroundExecutorService; private final MarkDirtyObserver markDirtyObserver; private final SharedPreferences sharedPreferences; private final AnnotatedCallLogDatabaseHelper annotatedCallLogDatabaseHelper; private final Duo duo; @Nullable private Long lastTimestampProcessed; private boolean isCallLogContentObserverRegistered = false; @Inject SystemCallLogDataSource( @ApplicationContext Context appContext, @BackgroundExecutor ListeningExecutorService backgroundExecutorService, MarkDirtyObserver markDirtyObserver, @Unencrypted SharedPreferences sharedPreferences, AnnotatedCallLogDatabaseHelper annotatedCallLogDatabaseHelper, Duo duo) { this.appContext = appContext; this.backgroundExecutorService = backgroundExecutorService; this.markDirtyObserver = markDirtyObserver; this.sharedPreferences = sharedPreferences; this.annotatedCallLogDatabaseHelper = annotatedCallLogDatabaseHelper; this.duo = duo; } @Override public void registerContentObservers() { LogUtil.enterBlock("SystemCallLogDataSource.registerContentObservers"); if (!PermissionsUtil.hasCallLogReadPermissions(appContext)) { LogUtil.i("SystemCallLogDataSource.registerContentObservers", "no call log permissions"); return; } // The system call log has a last updated timestamp, but deletes are physical (the "deleted" // column is unused). This means that we can't detect deletes without scanning the entire table, // which would be too slow. So, we just rely on content observers to trigger rebuilds when any // change is made to the system call log. appContext .getContentResolver() .registerContentObserver(CallLog.Calls.CONTENT_URI_WITH_VOICEMAIL, true, markDirtyObserver); isCallLogContentObserverRegistered = true; if (!PermissionsUtil.hasAddVoicemailPermissions(appContext)) { LogUtil.i("SystemCallLogDataSource.registerContentObservers", "no add voicemail permissions"); return; } // TODO(uabdullah): Need to somehow register observers if user enables permission after launch? appContext .getContentResolver() .registerContentObserver(VoicemailContract.Status.CONTENT_URI, true, markDirtyObserver); } @Override public void unregisterContentObservers() { appContext.getContentResolver().unregisterContentObserver(markDirtyObserver); isCallLogContentObserverRegistered = false; } @Override public ListenableFuture<Void> clearData() { ListenableFuture<Void> deleteSharedPref = backgroundExecutorService.submit( () -> { sharedPreferences.edit().remove(PREF_LAST_TIMESTAMP_PROCESSED).apply(); return null; }); return Futures.transform( Futures.allAsList(deleteSharedPref, annotatedCallLogDatabaseHelper.delete()), unused -> null, MoreExecutors.directExecutor()); } @Override public String getLoggingName() { return "SystemCallLogDataSource"; } @Override public ListenableFuture<Boolean> isDirty() { // This can happen if the call log permission is enabled after the application is started. if (!isCallLogContentObserverRegistered && PermissionsUtil.hasCallLogReadPermissions(appContext)) { registerContentObservers(); // Consider the data source dirty because calls could have been missed while the content // observer wasn't registered. return Futures.immediateFuture(true); } return backgroundExecutorService.submit(this::isDirtyInternal); } @Override public ListenableFuture<Void> fill(CallLogMutations mutations) { return backgroundExecutorService.submit(() -> fillInternal(mutations)); } @Override public ListenableFuture<Void> onSuccessfulFill() { return backgroundExecutorService.submit(this::onSuccessfulFillInternal); } @WorkerThread private boolean isDirtyInternal() { Assert.isWorkerThread(); /* * The system call log has a last updated timestamp, but deletes are physical (the "deleted" * column is unused). This means that we can't detect deletes without scanning the entire table, * which would be too slow. So, we just rely on content observers to trigger rebuilds when any * change is made to the system call log. * * Just return false unless the table has never been written to. */ return !sharedPreferences.contains(PREF_LAST_TIMESTAMP_PROCESSED); } @WorkerThread private Void fillInternal(CallLogMutations mutations) { Assert.isWorkerThread(); lastTimestampProcessed = null; if (!PermissionsUtil.hasPermission(appContext, permission.READ_CALL_LOG)) { LogUtil.i("SystemCallLogDataSource.fill", "no call log permissions"); return null; } // This data source should always run first so the mutations should always be empty. Assert.checkArgument(mutations.isEmpty()); Set<Long> annotatedCallLogIds = getAnnotatedCallLogIds(appContext); LogUtil.i( "SystemCallLogDataSource.fill", "found %d existing annotated call log ids", annotatedCallLogIds.size()); handleInsertsAndUpdates(appContext, mutations, annotatedCallLogIds); handleDeletes(appContext, annotatedCallLogIds, mutations); return null; } @WorkerThread private Void onSuccessfulFillInternal() { // If a fill operation was a no-op, lastTimestampProcessed could still be null. if (lastTimestampProcessed != null) { sharedPreferences .edit() .putLong(PREF_LAST_TIMESTAMP_PROCESSED, lastTimestampProcessed) .apply(); } return null; } private void handleInsertsAndUpdates( Context appContext, CallLogMutations mutations, Set<Long> existingAnnotatedCallLogIds) { long previousTimestampProcessed = sharedPreferences.getLong(PREF_LAST_TIMESTAMP_PROCESSED, 0L); DialerPhoneNumberUtil dialerPhoneNumberUtil = new DialerPhoneNumberUtil(); // TODO(zachh): Really should be getting last 1000 by timestamp, not by last modified. try (Cursor cursor = appContext .getContentResolver() .query( Calls.CONTENT_URI_WITH_VOICEMAIL, getProjection(), Calls.LAST_MODIFIED + " > ? AND " + Voicemails.DELETED + " = 0", new String[] {String.valueOf(previousTimestampProcessed)}, Calls.LAST_MODIFIED + " DESC LIMIT 1000")) { if (cursor == null) { LogUtil.e("SystemCallLogDataSource.handleInsertsAndUpdates", "null cursor"); return; } if (!cursor.moveToFirst()) { LogUtil.i("SystemCallLogDataSource.handleInsertsAndUpdates", "no entries to insert/update"); return; } LogUtil.i( "SystemCallLogDataSource.handleInsertsAndUpdates", "found %d entries to insert/update", cursor.getCount()); int idColumn = cursor.getColumnIndexOrThrow(Calls._ID); int dateColumn = cursor.getColumnIndexOrThrow(Calls.DATE); int lastModifiedColumn = cursor.getColumnIndexOrThrow(Calls.LAST_MODIFIED); int numberColumn = cursor.getColumnIndexOrThrow(Calls.NUMBER); int presentationColumn = cursor.getColumnIndexOrThrow(Calls.NUMBER_PRESENTATION); int typeColumn = cursor.getColumnIndexOrThrow(Calls.TYPE); int countryIsoColumn = cursor.getColumnIndexOrThrow(Calls.COUNTRY_ISO); int durationsColumn = cursor.getColumnIndexOrThrow(Calls.DURATION); int dataUsageColumn = cursor.getColumnIndexOrThrow(Calls.DATA_USAGE); int transcriptionColumn = cursor.getColumnIndexOrThrow(Calls.TRANSCRIPTION); int voicemailUriColumn = cursor.getColumnIndexOrThrow(Calls.VOICEMAIL_URI); int isReadColumn = cursor.getColumnIndexOrThrow(Calls.IS_READ); int newColumn = cursor.getColumnIndexOrThrow(Calls.NEW); int geocodedLocationColumn = cursor.getColumnIndexOrThrow(Calls.GEOCODED_LOCATION); int phoneAccountComponentColumn = cursor.getColumnIndexOrThrow(Calls.PHONE_ACCOUNT_COMPONENT_NAME); int phoneAccountIdColumn = cursor.getColumnIndexOrThrow(Calls.PHONE_ACCOUNT_ID); int featuresColumn = cursor.getColumnIndexOrThrow(Calls.FEATURES); int postDialDigitsColumn = cursor.getColumnIndexOrThrow(Calls.POST_DIAL_DIGITS); // The cursor orders by LAST_MODIFIED DESC, so the first result is the most recent timestamp // processed. lastTimestampProcessed = cursor.getLong(lastModifiedColumn); do { long id = cursor.getLong(idColumn); long date = cursor.getLong(dateColumn); String numberAsStr = cursor.getString(numberColumn); int type; if (cursor.isNull(typeColumn) || (type = cursor.getInt(typeColumn)) == 0) { // CallLog.Calls#TYPE lists the allowed values, which are non-null and non-zero. throw new IllegalStateException("call type is missing"); } int presentation; if (cursor.isNull(presentationColumn) || (presentation = cursor.getInt(presentationColumn)) == 0) { // CallLog.Calls#NUMBER_PRESENTATION lists the allowed values, which are non-null and // non-zero. throw new IllegalStateException("presentation is missing"); } String countryIso = cursor.getString(countryIsoColumn); int duration = cursor.getInt(durationsColumn); int dataUsage = cursor.getInt(dataUsageColumn); String transcription = cursor.getString(transcriptionColumn); String voicemailUri = cursor.getString(voicemailUriColumn); int isRead = cursor.getInt(isReadColumn); int isNew = cursor.getInt(newColumn); String geocodedLocation = cursor.getString(geocodedLocationColumn); String phoneAccountComponentName = cursor.getString(phoneAccountComponentColumn); String phoneAccountId = cursor.getString(phoneAccountIdColumn); int features = cursor.getInt(featuresColumn); String postDialDigits = cursor.getString(postDialDigitsColumn); // Exclude Duo audio calls. if (isDuoAudioCall(phoneAccountComponentName, features)) { continue; } ContentValues contentValues = new ContentValues(); contentValues.put(AnnotatedCallLog.TIMESTAMP, date); if (!TextUtils.isEmpty(numberAsStr)) { String numberWithPostDialDigits = postDialDigits == null ? numberAsStr : numberAsStr + postDialDigits; DialerPhoneNumber dialerPhoneNumber = dialerPhoneNumberUtil.parse(numberWithPostDialDigits, countryIso); contentValues.put(AnnotatedCallLog.NUMBER, dialerPhoneNumber.toByteArray()); String formattedNumber = PhoneNumberUtils.formatNumber(numberWithPostDialDigits, countryIso); if (formattedNumber == null) { formattedNumber = numberWithPostDialDigits; } contentValues.put(AnnotatedCallLog.FORMATTED_NUMBER, formattedNumber); } else { contentValues.put( AnnotatedCallLog.NUMBER, DialerPhoneNumber.getDefaultInstance().toByteArray()); } contentValues.put(AnnotatedCallLog.NUMBER_PRESENTATION, presentation); contentValues.put(AnnotatedCallLog.CALL_TYPE, type); contentValues.put(AnnotatedCallLog.IS_READ, isRead); contentValues.put(AnnotatedCallLog.NEW, isNew); contentValues.put(AnnotatedCallLog.GEOCODED_LOCATION, geocodedLocation); contentValues.put(AnnotatedCallLog.PHONE_ACCOUNT_COMPONENT_NAME, phoneAccountComponentName); contentValues.put(AnnotatedCallLog.PHONE_ACCOUNT_ID, phoneAccountId); contentValues.put(AnnotatedCallLog.FEATURES, features); contentValues.put(AnnotatedCallLog.DURATION, duration); contentValues.put(AnnotatedCallLog.DATA_USAGE, dataUsage); contentValues.put(AnnotatedCallLog.TRANSCRIPTION, transcription); contentValues.put(AnnotatedCallLog.VOICEMAIL_URI, voicemailUri); contentValues.put(AnnotatedCallLog.CALL_MAPPING_ID, String.valueOf(date)); setTranscriptionState(cursor, contentValues); if (existingAnnotatedCallLogIds.contains(id)) { mutations.update(id, contentValues); } else { mutations.insert(id, contentValues); } } while (cursor.moveToNext()); } } /** * Returns true if the phone account component name and the features belong to a Duo audio call. * * <p>Characteristics of a Duo audio call are as follows. * * <ul> * <li>The phone account is {@link Duo#isDuoAccount(String)}; and * <li>The features don't include {@link Calls#FEATURES_VIDEO}. * </ul> * * <p>It is the caller's responsibility to ensure the phone account component name and the * features come from the same call log entry. */ private boolean isDuoAudioCall(@Nullable String phoneAccountComponentName, int features) { return duo.isDuoAccount(phoneAccountComponentName) && ((features & Calls.FEATURES_VIDEO) != Calls.FEATURES_VIDEO); } private void setTranscriptionState(Cursor cursor, ContentValues contentValues) { if (VERSION.SDK_INT >= VERSION_CODES.O) { int transcriptionStateColumn = cursor.getColumnIndexOrThrow(VoicemailCompat.TRANSCRIPTION_STATE); int transcriptionState = cursor.getInt(transcriptionStateColumn); contentValues.put(VoicemailCompat.TRANSCRIPTION_STATE, transcriptionState); } } private static final String[] PROJECTION_PRE_O = new String[] { Calls._ID, Calls.DATE, Calls.LAST_MODIFIED, Calls.NUMBER, Calls.NUMBER_PRESENTATION, Calls.TYPE, Calls.COUNTRY_ISO, Calls.DURATION, Calls.DATA_USAGE, Calls.TRANSCRIPTION, Calls.VOICEMAIL_URI, Calls.IS_READ, Calls.NEW, Calls.GEOCODED_LOCATION, Calls.PHONE_ACCOUNT_COMPONENT_NAME, Calls.PHONE_ACCOUNT_ID, Calls.FEATURES, Calls.POST_DIAL_DIGITS }; @RequiresApi(VERSION_CODES.O) private static final String[] PROJECTION_O_AND_LATER; static { List<String> projectionList = new ArrayList<>(Arrays.asList(PROJECTION_PRE_O)); projectionList.add(VoicemailCompat.TRANSCRIPTION_STATE); PROJECTION_O_AND_LATER = projectionList.toArray(new String[projectionList.size()]); } private String[] getProjection() { if (VERSION.SDK_INT >= VERSION_CODES.O) { return PROJECTION_O_AND_LATER; } return PROJECTION_PRE_O; } private static void handleDeletes( Context appContext, Set<Long> existingAnnotatedCallLogIds, CallLogMutations mutations) { Set<Long> systemCallLogIds = getIdsFromSystemCallLogThatMatch(appContext, existingAnnotatedCallLogIds); LogUtil.i( "SystemCallLogDataSource.handleDeletes", "found %d matching entries in system call log", systemCallLogIds.size()); Set<Long> idsInAnnotatedCallLogNoLongerInSystemCallLog = new ArraySet<>(); idsInAnnotatedCallLogNoLongerInSystemCallLog.addAll(existingAnnotatedCallLogIds); idsInAnnotatedCallLogNoLongerInSystemCallLog.removeAll(systemCallLogIds); LogUtil.i( "SystemCallLogDataSource.handleDeletes", "found %d call log entries to remove", idsInAnnotatedCallLogNoLongerInSystemCallLog.size()); for (long id : idsInAnnotatedCallLogNoLongerInSystemCallLog) { mutations.delete(id); } } private static Set<Long> getAnnotatedCallLogIds(Context appContext) { ArraySet<Long> ids = new ArraySet<>(); try (Cursor cursor = appContext .getContentResolver() .query( AnnotatedCallLog.CONTENT_URI, new String[] {AnnotatedCallLog._ID}, null, null, null)) { if (cursor == null) { LogUtil.e("SystemCallLogDataSource.getAnnotatedCallLogIds", "null cursor"); return ids; } if (cursor.moveToFirst()) { int idColumn = cursor.getColumnIndexOrThrow(AnnotatedCallLog._ID); do { ids.add(cursor.getLong(idColumn)); } while (cursor.moveToNext()); } } return ids; } private static Set<Long> getIdsFromSystemCallLogThatMatch( Context appContext, Set<Long> matchingIds) { ArraySet<Long> ids = new ArraySet<>(); // Batch the select statements into chunks of 999, the maximum size for SQLite selection args. Iterable<List<Long>> batches = Iterables.partition(matchingIds, 999); for (List<Long> idsInBatch : batches) { String[] questionMarks = new String[idsInBatch.size()]; Arrays.fill(questionMarks, "?"); String whereClause = (Calls._ID + " in (") + TextUtils.join(",", questionMarks) + ")"; String[] whereArgs = new String[idsInBatch.size()]; int i = 0; for (long id : idsInBatch) { whereArgs[i++] = String.valueOf(id); } try (Cursor cursor = appContext .getContentResolver() .query( Calls.CONTENT_URI_WITH_VOICEMAIL, new String[] {Calls._ID}, whereClause, whereArgs, null)) { if (cursor == null) { LogUtil.e("SystemCallLogDataSource.getIdsFromSystemCallLog", "null cursor"); return ids; } if (cursor.moveToFirst()) { int idColumn = cursor.getColumnIndexOrThrow(Calls._ID); do { ids.add(cursor.getLong(idColumn)); } while (cursor.moveToNext()); } } } return ids; } }
3e123d087471196ed1928fde1a41204de2e3ca4f
2,384
java
Java
maven-model-builder/src/main/java/org/apache/maven/model/building/ModelSource2.java
zly123987123/maven
d75bea415457b2eba7815bb9c3e9cd4e14b47fce
[ "Apache-2.0" ]
3,222
2015-01-04T10:24:28.000Z
2022-03-31T12:05:28.000Z
maven-model-builder/src/main/java/org/apache/maven/model/building/ModelSource2.java
zly123987123/maven
d75bea415457b2eba7815bb9c3e9cd4e14b47fce
[ "Apache-2.0" ]
442
2015-01-02T19:29:11.000Z
2022-03-31T13:32:02.000Z
maven-model-builder/src/main/java/org/apache/maven/model/building/ModelSource2.java
zly123987123/maven
d75bea415457b2eba7815bb9c3e9cd4e14b47fce
[ "Apache-2.0" ]
2,670
2015-01-06T12:47:05.000Z
2022-03-31T15:07:55.000Z
41.824561
120
0.721896
7,686
package org.apache.maven.model.building; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.net.URI; /** * Provides access to the contents of a POM independently of the backing store (e.g. file system, database, memory). * <p> * Unlike {@link ModelSource}, this interface supports loading of parent POM(s) from the same backing store and allows * construction of MavenProject instances without the need to have parent POM(s) available from local or remote * repositories. * <p> * ModelSource2 instances are cached in {@link ModelBuildingRequest#getModelCache()}. Implementations must guarantee * that the connection to the backing store remains active until request's {@link ModelCache} is discarded or flushed. */ public interface ModelSource2 extends ModelSource { /** * Returns model source identified by a path relative to this model source POM. Implementation <strong>MUST</strong> * be able to accept <code>relPath</code> parameter values that * <ul> * <li>use either / or \ file path separator</li> * <li>have .. parent directory references</li> * <li>point either at file or directory, in the latter case POM file name 'pom.xml' needs to be used by the * requested model source.</li> * </ul> * * @param relPath is the path of the requested model source relative to this model source POM. * @return related model source or <code>null</code> if no such model source. */ ModelSource2 getRelatedSource( String relPath ); /** * Returns location of the POM, never <code>null</code>. */ URI getLocationURI(); }
3e123d5415abb49622ba86c58d9a93e1571ca0a8
678
java
Java
src/main/java/nl/miwgroningen/se6/gardengnomes/Igadi/model/PatchTask.java
MIW-G-C6/Igadi
c23668b9e6ecf04c7814286ae98bb743bce7ce17
[ "MIT" ]
null
null
null
src/main/java/nl/miwgroningen/se6/gardengnomes/Igadi/model/PatchTask.java
MIW-G-C6/Igadi
c23668b9e6ecf04c7814286ae98bb743bce7ce17
[ "MIT" ]
null
null
null
src/main/java/nl/miwgroningen/se6/gardengnomes/Igadi/model/PatchTask.java
MIW-G-C6/Igadi
c23668b9e6ecf04c7814286ae98bb743bce7ce17
[ "MIT" ]
null
null
null
22.866667
86
0.705539
7,687
package nl.miwgroningen.se6.gardengnomes.Igadi.model; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import javax.persistence.*; /** * @author Lukas de Ruiter <hzdkv@example.com> * * These tasks are coupled to a specific patch, which in turn is part of a garden. */ @Entity @PrimaryKeyJoinColumn(name = "task_taskId") public class PatchTask extends Task { @ManyToOne() @OnDelete(action = OnDeleteAction.CASCADE) @JoinColumn(name = "patch_patchId") private Patch patch; public Patch getPatch() { return patch; } public void setPatch(Patch patch) { this.patch = patch; } }
3e123d88c96e6e1a3cd26e5186a39f684aa8e217
866
java
Java
tools.bugs/src/main/java/com/aqnote/shared/bugs/sof/StackOverflow_EXP1.java
aqnotecom/java.tools
4a60d37f51e141f9cffa0ea89582402991fa89e5
[ "Apache-2.0" ]
null
null
null
tools.bugs/src/main/java/com/aqnote/shared/bugs/sof/StackOverflow_EXP1.java
aqnotecom/java.tools
4a60d37f51e141f9cffa0ea89582402991fa89e5
[ "Apache-2.0" ]
null
null
null
tools.bugs/src/main/java/com/aqnote/shared/bugs/sof/StackOverflow_EXP1.java
aqnotecom/java.tools
4a60d37f51e141f9cffa0ea89582402991fa89e5
[ "Apache-2.0" ]
null
null
null
31.777778
93
0.728438
7,688
/* * Copyright (C) 2013-2016 Peng Li<kenaa@example.com>. * 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; */ package com.aqnote.shared.bugs.sof; /** * StackOverflow.java desc:TODO * * @author "Peng Li"<kenaa@example.com> Jun 10, 2014 4:19:43 PM */ public class StackOverflow_EXP1 { public static void main(String[] args) { main(args); } } /** Exception in thread "main" java.lang.StackOverflowError at com.aqnote.shared.bugs.sof.StackOverflow.main(StackOverflow.java:16) at com.aqnote.shared.bugs.sof.StackOverflow.main(StackOverflow.java:16) at com.aqnote.shared.bugs.sof.StackOverflow.main(StackOverflow.java:16) at com.aqnote.shared.bugs.sof.StackOverflow.main(StackOverflow.java:16) */
3e123dd5313d9fceb7c5bd989a354e6f495dc402
937
java
Java
src/liars/console/Console.java
mwhite317/liars-dice
9c0343d451368e3e1e1b620a6fdac4beb03c7e4c
[ "Apache-2.0" ]
null
null
null
src/liars/console/Console.java
mwhite317/liars-dice
9c0343d451368e3e1e1b620a6fdac4beb03c7e4c
[ "Apache-2.0" ]
null
null
null
src/liars/console/Console.java
mwhite317/liars-dice
9c0343d451368e3e1e1b620a6fdac4beb03c7e4c
[ "Apache-2.0" ]
null
null
null
16.438596
67
0.722519
7,689
package liars.console; import liars.Bid; import liars.Game; import liars.Player; public interface Console { Bid getPlayerBid(Player player, Bid lastBid, int numberOfDice); String getPlayerChoice(Player player); void addDelay(); void displayEnterPlayerNames(); void displayStartGame(); void displayOnesWild(); void displaySettingUpLanguage(); void displayGameState(Game game); void displayEndOfBidTurn(Game game, Bid bid); void displayRoundChoice(); void displayInvalidChoiceError(); void displayDice(String name, int[] dice2Ints); void displayRemovingLoser(); void displayMakeInitialBid(); void displayChallengeMade(Game game); void displayChallengeResults(boolean valid, Player player); void displayNextTurn(Game game); void displayDiceRerolled(int nextRound); void displayEndGame(Game game); void displayEnterAgentNames(); }
3e123f8863cbdf21087018755fd9cab209e36ad6
2,727
java
Java
src/test/java/org/abubusoft/reversi/server/web/MatchSimulationPlayer2IsOutTest.java
xcesco/reversi-backend
9897118ee5e7d9da51eece24f476f61d2adad5d7
[ "Apache-2.0" ]
2
2020-07-29T07:32:36.000Z
2021-08-01T07:39:20.000Z
src/test/java/org/abubusoft/reversi/server/web/MatchSimulationPlayer2IsOutTest.java
xcesco/reversi-backend
9897118ee5e7d9da51eece24f476f61d2adad5d7
[ "Apache-2.0" ]
9
2020-06-19T07:26:18.000Z
2020-07-03T10:05:43.000Z
src/test/java/org/abubusoft/reversi/server/web/MatchSimulationPlayer2IsOutTest.java
xcesco/reversi-backend
9897118ee5e7d9da51eece24f476f61d2adad5d7
[ "Apache-2.0" ]
1
2021-02-02T07:13:59.000Z
2021-02-02T07:13:59.000Z
37.356164
140
0.781445
7,690
package org.abubusoft.reversi.server.web; import it.fmt.games.reversi.model.GameStatus; import it.fmt.games.reversi.model.Piece; import org.abubusoft.reversi.messages.UserRegistration; import org.abubusoft.reversi.server.model.User; import org.junit.jupiter.api.Test; import org.springframework.http.HttpMethod; import org.springframework.messaging.simp.stomp.StompHeaders; import org.springframework.messaging.simp.stomp.StompSession; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.TestPropertySource; import java.lang.reflect.Type; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @ActiveProfiles("test") @TestPropertySource( locations = "classpath:application-client.properties") public class MatchSimulationPlayer2IsOutTest extends AbstractWebTest { private User user1; private User user2; private UserSubscriptionFrameHandler frameHandlerPlayer1; @Test public void testMatch() throws Exception { UserRegistration user1Registration = new UserRegistration("user1"); UserRegistration user2Registration = new UserRegistration("user1"); logger.debug("base url is {}",baseUrl); user1 = restTemplate.postForEntity(baseUrl + "api/v1/public/users", user1Registration, User.class).getBody(); user2 = restTemplate.postForEntity(baseUrl + "api/v1/public/users", user2Registration, User.class).getBody(); frameHandlerPlayer1=new UserSubscriptionFrameHandler(user1.getId(), Piece.PLAYER_1, this); connectOnWebsocket(); assert user1 != null; assert user2 != null; user1 = restTemplate.patchForObject(baseUrl + String.format("api/v1/public/users/%s/ready", user1.getId()), HttpMethod.PUT, User.class); user2 = restTemplate.patchForObject(baseUrl + String.format("api/v1/public/users/%s/ready", user2.getId()), HttpMethod.PUT, User.class); assertNotNull(user1.getId()); assertNotNull(user2.getId()); executor.getThreadPoolExecutor().awaitTermination(timeOut, TimeUnit.SECONDS); // assertTrue(frameHandlerPlayer1.getResult()== GameStatus.PLAYER1_WIN); } @Override protected Type onSessionPayLoadType(StompHeaders headers) { return null; } @Override protected void onSessionHandleFrame(StompHeaders headers, Object payload) { } @Override protected void onSessionAfterConnected(StompSession session, StompHeaders connectedHeaders) { session.subscribe(StompSender.buildUserTopic(user1.getId()), frameHandlerPlayer1); //session.subscribe(StompSender.buildUserTopic(user2.getId()), new UserSubscriptionFrameHandler(user2.getId(), Piece.PLAYER_2, this)); } }
3e123fde46a0cc93724139aedb3959e9954b6759
650
java
Java
platform/src/main/java/io/pocketbox/engine/GameConfig.java
m-semibratov/pocket-box-engine
24a395729c3752fc0e0a35a61b249b3e1e399c48
[ "Apache-2.0" ]
null
null
null
platform/src/main/java/io/pocketbox/engine/GameConfig.java
m-semibratov/pocket-box-engine
24a395729c3752fc0e0a35a61b249b3e1e399c48
[ "Apache-2.0" ]
null
null
null
platform/src/main/java/io/pocketbox/engine/GameConfig.java
m-semibratov/pocket-box-engine
24a395729c3752fc0e0a35a61b249b3e1e399c48
[ "Apache-2.0" ]
null
null
null
30.952381
56
0.704615
7,691
package io.pocketbox.engine; public class GameConfig { public static float WORLD_WIDTH, WORLD_HEIGHT; public static float GUI_WIDTH, GUI_HEIGHT; public static float PIXEL_2_UNIT; static final float HALF_TAP_SQUARE_SIZE = 20.0f; static final float TAP_COUNT_INTERVAL = 0.4f; static final float LONG_PRESS_DURATION = 1.1f; static final float MAX_FLING_DELAY = 0.15f; public GameConfig(float guiWidth, float guiHeight) { GUI_WIDTH = guiWidth; GUI_HEIGHT = guiHeight; WORLD_WIDTH = guiWidth / 100f; WORLD_HEIGHT = guiHeight / 100f; PIXEL_2_UNIT = WORLD_WIDTH / guiWidth; } }
3e1241ff1a54bc82f638a3068ad94baecd65c697
1,044
java
Java
Java/A.11_LastElm/src/LastElm.java
MohanadSinan/coderhub.sa
d8d7e134f57f5951e40ac9b14926435386c1d51f
[ "MIT" ]
3
2021-09-15T02:07:42.000Z
2022-01-21T20:10:25.000Z
Java/A.11_LastElm/src/LastElm.java
OsDroidi/coderhub.sa
cb5f8f8d00ef8b9a77799d0c6b9faddbd3be082b
[ "MIT" ]
null
null
null
Java/A.11_LastElm/src/LastElm.java
OsDroidi/coderhub.sa
cb5f8f8d00ef8b9a77799d0c6b9faddbd3be082b
[ "MIT" ]
3
2021-09-15T02:05:30.000Z
2022-01-21T20:11:04.000Z
29
84
0.500958
7,692
import java.util.Arrays; public class LastElm { public static int lastElm(int[] arr) { // write your code here return arr[arr.length - 1]; } public static void main(String[] args) { System.out.println("array\t\t\t\t\tOutput\n------------------------------"); int[] array = new int[]{2 , 4 , 9 , 23 , 435}; int R = lastElm(array); System.out.println(Arrays.toString(array) + "\t\t " + R); array = new int[]{32 , 44 , 9 , 3 , 8}; R = lastElm(array); System.out.println(Arrays.toString(array) + "\t\t " + R); array = new int[]{99 , 314 , 8 , 200 , 23}; R = lastElm(array); System.out.println(Arrays.toString(array) + "\t " + R); array = new int[]{72 , 86 , 23 , 70 , 1}; R = lastElm(array); System.out.println(Arrays.toString(array) + "\t\t " + R); array = new int[]{55 , 64 , 0 , 11 , 4}; R = lastElm(array); System.out.println(Arrays.toString(array) + "\t\t " + R); } }
3e12425c60595114c6f64b4fe146d24aa3cb94b1
1,879
java
Java
inventoryGame/src/student/Main.java
AlexMachin1997/First-Java-Game
9f83f6683360314ed0fc42e0281943e3bf4e5dcb
[ "MIT" ]
null
null
null
inventoryGame/src/student/Main.java
AlexMachin1997/First-Java-Game
9f83f6683360314ed0fc42e0281943e3bf4e5dcb
[ "MIT" ]
null
null
null
inventoryGame/src/student/Main.java
AlexMachin1997/First-Java-Game
9f83f6683360314ed0fc42e0281943e3bf4e5dcb
[ "MIT" ]
null
null
null
26.097222
83
0.618414
7,693
/* * 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 student; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import teacher.*; import javafx.scene.image.Image; /** * * @author james */ public class Main extends Application { private MapPane mp; private InventoryPane ip; private ControlPane cp; @Override public void start(Stage primaryStage) { //NPC npc = new NPC(); PC pc = new PC(); pc.setLocation(Helpers.cantorCompression(15, 15)); CharacterManager.getInstance().setCharacter(pc); InventoryManager.getInstance().setCurrentObject(pc); //Creates items in the createInvItem method which is from class CreateItem CreateItem CreateItem = new CreateItem(); CreateItem.createInvItem(); mp = new MapPane(); mp.addObject(pc); ip = new InventoryPane(); cp = new ControlPane(); cp.addMovementObserver(mp); InventoryManager.getInstance().addInventoryObserver(ip); GridPane root = new GridPane(); Scene scene = new Scene(root, 515, 340); root.add(mp, 0,1); root.add(ip,1,1); root.add(cp, 0,2,2,1); //Primary Stage Configuration primaryStage.setTitle("Witcher 3: Wild Hunt Inventory Manager"); primaryStage.getIcons().add(new Image("/Assets/favicon.png")); primaryStage.setScene(scene); primaryStage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
3e12426c882afc3dd067b039c61fe742c8f33648
2,649
java
Java
java/com/google/copybara/testing/DummyChecker.java
twitter-forks/copybara
b881dad771920e4650ca0c0d85a4775aac370817
[ "Apache-2.0" ]
1
2022-03-01T21:37:05.000Z
2022-03-01T21:37:05.000Z
java/com/google/copybara/testing/DummyChecker.java
twitter-forks/copybara
b881dad771920e4650ca0c0d85a4775aac370817
[ "Apache-2.0" ]
null
null
null
java/com/google/copybara/testing/DummyChecker.java
twitter-forks/copybara
b881dad771920e4650ca0c0d85a4775aac370817
[ "Apache-2.0" ]
null
null
null
31.915663
102
0.693847
7,694
/* * Copyright (C) 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.copybara.testing; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.copybara.checks.Checker; import com.google.copybara.checks.CheckerException; import com.google.copybara.util.console.Console; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map.Entry; import net.starlark.java.annot.StarlarkBuiltin; /** * A dummy, not very efficient, checker for tests. * * <p>TODO(danielromero): Promote to a real transform that uses regex */ @StarlarkBuiltin(name = "dummy_checker", doc = "A dummy checker for tests") public class DummyChecker implements Checker { private final ImmutableSet<String> badWords; /** * Creates a new checker. * * @param badWords Case-insensitive set of bad words */ public DummyChecker(ImmutableSet<String> badWords) { this.badWords = badWords.stream().map(String::toLowerCase).collect(ImmutableSet.toImmutableSet()); } /** * Fails on first bad word found. */ @Override public void doCheck(ImmutableMap<String, String> fields, Console console) throws CheckerException { for (Entry<String, String> entry : fields.entrySet()) { for (String badWord : badWords) { if (entry.getValue().toLowerCase().contains(badWord)) { throw new CheckerException( String.format("Bad word '%s' found: field '%s'", badWord, entry.getKey())); } } } } /** * Does a line by line check. Does not detect bad words if multi-line. Fails on first bad word * found. */ @Override public void doCheck(Path target, Console console) throws CheckerException, IOException { int lineNum = 0; for (String line : Files.readAllLines(target)) { lineNum++; for (String badWord : badWords) { if (line.toLowerCase().contains(badWord)) { throw new CheckerException( String.format("Bad word '%s' found: %s:%d", badWord, target, lineNum)); } } } } }
3e1242e87e712802b26956d53c15a17925deb29d
307
java
Java
Mall/src/main/java/com/atusoft/newmall/event/order/OrderPaidEvent.java
zhouquan2k/newmall
bd030ef7ac10b37743ccb84f80f00aad199a3f94
[ "Apache-2.0" ]
null
null
null
Mall/src/main/java/com/atusoft/newmall/event/order/OrderPaidEvent.java
zhouquan2k/newmall
bd030ef7ac10b37743ccb84f80f00aad199a3f94
[ "Apache-2.0" ]
null
null
null
Mall/src/main/java/com/atusoft/newmall/event/order/OrderPaidEvent.java
zhouquan2k/newmall
bd030ef7ac10b37743ccb84f80f00aad199a3f94
[ "Apache-2.0" ]
2
2021-08-23T01:27:55.000Z
2022-02-01T04:01:56.000Z
17.055556
47
0.76873
7,695
package com.atusoft.newmall.event.order; import com.atusoft.infrastructure.BaseEvent; import com.atusoft.newmall.dto.order.OrderDTO; public class OrderPaidEvent extends BaseEvent { OrderDTO order; protected OrderPaidEvent() { } public OrderPaidEvent(OrderDTO order) { this.order=order; } }
3e12431d3a5ce0511ec1895dc7c9cc3aa8ea3959
1,714
java
Java
app/src/main/java/com/uteamtec/heartcool/service/ecg/EcgQueue.java
wlanwei/aerocardio-android
7f4be4ed6f8ef4f59b74fd8ebee0e890d33573c9
[ "Apache-2.0" ]
1
2017-05-25T10:01:36.000Z
2017-05-25T10:01:36.000Z
app/src/main/java/com/uteamtec/heartcool/service/ecg/EcgQueue.java
wlanwei/aerocardio-android
7f4be4ed6f8ef4f59b74fd8ebee0e890d33573c9
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/uteamtec/heartcool/service/ecg/EcgQueue.java
wlanwei/aerocardio-android
7f4be4ed6f8ef4f59b74fd8ebee0e890d33573c9
[ "Apache-2.0" ]
null
null
null
28.566667
91
0.666278
7,696
package com.uteamtec.heartcool.service.ecg; import com.uteamtec.algorithm.types.Ecg; import com.uteamtec.heartcool.MainConstant; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * Created by wd */ public final class EcgQueue { private BlockingQueue<Ecg> ecgRaw; // 原始ecg数据,采用阻塞queue private BlockingQueue<Ecg> ecgFiltered; // 滤波之后的ecg,采用阻塞queue private BlockingQueue<Ecg> ecgDisplay; // 传递到Main activity的信号波形 private EcgQueue() { ecgRaw = new ArrayBlockingQueue<>(MainConstant.DEFAULT_QUEUE_SIZE); ecgFiltered = new ArrayBlockingQueue<>(MainConstant.DEFAULT_QUEUE_SIZE); ecgDisplay = new ArrayBlockingQueue<>(MainConstant.DEFAULT_QUEUE_SIZE); } private static EcgQueue _queue; private static EcgQueue getQueue() { if (_queue == null) { synchronized (EcgQueue.class) { if (_queue == null) { _queue = new EcgQueue(); } } } return _queue; } public static BlockingQueue<Ecg> getRaw() { return getQueue().ecgRaw; } synchronized protected static void resetRaw() { getQueue().ecgRaw.clear(); getQueue().ecgRaw = new ArrayBlockingQueue<>(MainConstant.DEFAULT_QUEUE_SIZE); } public static BlockingQueue<Ecg> getFiltered() { return getQueue().ecgFiltered; } synchronized protected static void resetFiltered() { getQueue().ecgFiltered.clear(); getQueue().ecgFiltered = new ArrayBlockingQueue<>(MainConstant.DEFAULT_QUEUE_SIZE); } public static BlockingQueue<Ecg> getDisplay() { return getQueue().ecgDisplay; } }
3e1244176674119fb47e1874683176cb0114dc84
1,458
java
Java
xtext-dsl-implementation/at.fhj.gaar.androidapp.dsl/src-gen/at/fhj/gaar/androidapp/appDsl/ActionStartActivity.java
nohum/android-meta-modeling
4a9eccc562746e8693088fdbdef24036f9346fdc
[ "Apache-2.0" ]
1
2015-02-27T18:15:07.000Z
2015-02-27T18:15:07.000Z
xtext-dsl-implementation/at.fhj.gaar.androidapp.dsl/src-gen/at/fhj/gaar/androidapp/appDsl/ActionStartActivity.java
nohum/android-meta-modeling
4a9eccc562746e8693088fdbdef24036f9346fdc
[ "Apache-2.0" ]
null
null
null
xtext-dsl-implementation/at.fhj.gaar.androidapp.dsl/src-gen/at/fhj/gaar/androidapp/appDsl/ActionStartActivity.java
nohum/android-meta-modeling
4a9eccc562746e8693088fdbdef24036f9346fdc
[ "Apache-2.0" ]
null
null
null
28.588235
127
0.648834
7,697
/** */ package at.fhj.gaar.androidapp.appDsl; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Action Start Activity</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link at.fhj.gaar.androidapp.appDsl.ActionStartActivity#getActivity <em>Activity</em>}</li> * </ul> * </p> * * @see at.fhj.gaar.androidapp.appDsl.AppDslPackage#getActionStartActivity() * @model * @generated */ public interface ActionStartActivity extends LayoutElementClickAction, BroadcastReceiverAction { /** * Returns the value of the '<em><b>Activity</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Activity</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Activity</em>' reference. * @see #setActivity(Activity) * @see at.fhj.gaar.androidapp.appDsl.AppDslPackage#getActionStartActivity_Activity() * @model * @generated */ Activity getActivity(); /** * Sets the value of the '{@link at.fhj.gaar.androidapp.appDsl.ActionStartActivity#getActivity <em>Activity</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Activity</em>' reference. * @see #getActivity() * @generated */ void setActivity(Activity value); } // ActionStartActivity
3e124422325ce69e9c0ba88685244192c5746a17
3,887
java
Java
mpi/src/main/java/com/ghostflow/services/UserServiceImpl.java
chebykinn/university
49491b4d942cedbda1c178d5634c5109f1b81a81
[ "MIT" ]
2
2016-12-25T14:21:43.000Z
2016-12-28T08:17:10.000Z
mpi/src/main/java/com/ghostflow/services/UserServiceImpl.java
chebykinn/university
49491b4d942cedbda1c178d5634c5109f1b81a81
[ "MIT" ]
null
null
null
mpi/src/main/java/com/ghostflow/services/UserServiceImpl.java
chebykinn/university
49491b4d942cedbda1c178d5634c5109f1b81a81
[ "MIT" ]
3
2017-10-22T18:58:10.000Z
2017-12-16T23:55:26.000Z
42.714286
135
0.741189
7,698
package com.ghostflow.services; import com.ghostflow.GhostFlowException; import com.ghostflow.database.Employees; import com.ghostflow.database.UserRepository; import com.ghostflow.database.postgres.entities.UserEntity; import com.ghostflow.http.security.GhostFlowAccessDeniedException; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.Optional; import java.util.concurrent.TimeUnit; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; @Slf4j @Service("userService") public class UserServiceImpl implements UserService { private final LoadingCache<String, Optional<UserEntity>> USER_CACHE = CacheBuilder.newBuilder() .expireAfterWrite(10, TimeUnit.MINUTES) .build(new CacheLoader<String, Optional<UserEntity>>() { @Override public Optional<UserEntity> load(String email) throws Exception { return userRepository.find(email); } }); private final UserRepository userRepository; private final BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired public UserServiceImpl(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder) { this.userRepository = userRepository; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } @Override public void create(String email, String name, String password, UserEntity.Role role) { checkArgument(!(email == null || email.trim().isEmpty()), "email is empty"); checkArgument(!(name == null || name.trim().isEmpty()), "name is empty"); checkArgument(!(password == null || password.trim().isEmpty()), "password is empty"); checkNotNull(role, "role is null"); checkArgument(role != UserEntity.Role.ADMIN, "unable to create admin account"); checkArgument(!userRepository.find(email).isPresent(), "user already exists"); userRepository.create(new UserEntity(email, name, bCryptPasswordEncoder.encode(password), role)); USER_CACHE.invalidate(email); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Optional<UserEntity> optionalUser = userRepository.find(username); if (!optionalUser.isPresent()) { throw new UsernameNotFoundException(username); } return new User(optionalUser.get().getEmail(), optionalUser.get().getPassword(), Collections.emptyList()); } @Override public UserEntity get(String email) { return USER_CACHE.getUnchecked(email).orElseThrow(() -> new GhostFlowException("unknown user id")); } @Override public Employees getEmployees(String email, long limit, long offset) { checkArgument(get(email).getRole() == UserEntity.Role.ADMIN, new GhostFlowAccessDeniedException()); return userRepository.allEmployees(limit, offset); } @Override public UserEntity update(String email, long userId, boolean approved) { checkArgument(get(email).getRole() == UserEntity.Role.ADMIN, new GhostFlowAccessDeniedException()); UserEntity result = userRepository.update(userId, approved).orElseThrow(() -> new IllegalArgumentException("Unknown user id")); USER_CACHE.invalidate(email); return result; } }
3e12450069829ce797dac7a67d70390b56bd588d
581
java
Java
src/main/java/com/lnzz/dto/DeptLevelDto.java
yyuguang/permission
066afc69be75c7e1ed63d4be839a39e16204415b
[ "MIT" ]
null
null
null
src/main/java/com/lnzz/dto/DeptLevelDto.java
yyuguang/permission
066afc69be75c7e1ed63d4be839a39e16204415b
[ "MIT" ]
1
2020-09-09T19:50:02.000Z
2020-09-09T19:50:02.000Z
src/main/java/com/lnzz/dto/DeptLevelDto.java
yyuguang/permission
066afc69be75c7e1ed63d4be839a39e16204415b
[ "MIT" ]
null
null
null
20.034483
63
0.703959
7,699
package com.lnzz.dto; import com.google.common.collect.Lists; import com.lnzz.pojo.SysDept; import lombok.Data; import org.springframework.beans.BeanUtils; import java.util.List; /** * ClassName:DeptLevelDto * * @author 冷暖自知 * @version 1.0 * @date 2020/4/2 16:46 * @Description: */ @Data public class DeptLevelDto extends SysDept { private List<DeptLevelDto> deptList = Lists.newArrayList(); public static DeptLevelDto adapt(SysDept dept) { DeptLevelDto dto = new DeptLevelDto(); BeanUtils.copyProperties(dept, dto); return dto; } }
3e124505f28071a7b4847faa0f0c47966b3aa829
199
java
Java
OperateSystem/Ex1/src/com/jhttpserver/interfaces/Execution.java
Jayin/ComputerScience
1a065420d1b049fdac35c1ae6047460e3d435c29
[ "MIT" ]
null
null
null
OperateSystem/Ex1/src/com/jhttpserver/interfaces/Execution.java
Jayin/ComputerScience
1a065420d1b049fdac35c1ae6047460e3d435c29
[ "MIT" ]
null
null
null
OperateSystem/Ex1/src/com/jhttpserver/interfaces/Execution.java
Jayin/ComputerScience
1a065420d1b049fdac35c1ae6047460e3d435c29
[ "MIT" ]
null
null
null
22.111111
50
0.81407
7,700
package com.jhttpserver.interfaces; import com.jhttpserver.entity.Request; import com.jhttpserver.entity.Response; public interface Execution { public void onExecute(Request req, Response res); }
3e124542588add168a76c142bed12ef869fa7125
31,815
java
Java
projects/OG-Core/src/main/java/com/opengamma/core/obligor/definition/Obligor.java
UbuntuEvangelist/OG-Platform
0aac9675ff92fd702d2e53a991de085388bfdc83
[ "Apache-2.0" ]
12
2017-03-10T13:56:52.000Z
2021-10-03T01:21:20.000Z
projects/OG-Core/src/main/java/com/opengamma/core/obligor/definition/Obligor.java
UbuntuEvangelist/OG-Platform
0aac9675ff92fd702d2e53a991de085388bfdc83
[ "Apache-2.0" ]
1
2021-08-02T17:20:43.000Z
2021-08-02T17:20:43.000Z
projects/OG-Core/src/main/java/com/opengamma/core/obligor/definition/Obligor.java
UbuntuEvangelist/OG-Platform
0aac9675ff92fd702d2e53a991de085388bfdc83
[ "Apache-2.0" ]
16
2017-01-12T10:31:58.000Z
2019-04-19T08:17:33.000Z
35.587248
187
0.645419
7,701
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.core.obligor.definition; import java.util.Map; import org.joda.beans.Bean; import org.joda.beans.BeanBuilder; import org.joda.beans.BeanDefinition; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaProperty; import org.joda.beans.Property; import org.joda.beans.PropertyDefinition; import org.joda.beans.impl.direct.DirectBean; import org.joda.beans.impl.direct.DirectBeanBuilder; import org.joda.beans.impl.direct.DirectMetaBean; import org.joda.beans.impl.direct.DirectMetaProperty; import org.joda.beans.impl.direct.DirectMetaPropertyMap; import com.opengamma.core.obligor.CreditRating; import com.opengamma.core.obligor.CreditRatingFitch; import com.opengamma.core.obligor.CreditRatingMoodys; import com.opengamma.core.obligor.CreditRatingStandardAndPoors; import com.opengamma.core.obligor.Region; import com.opengamma.core.obligor.Sector; import com.opengamma.util.ArgumentChecker; /** * Class for defining the characteristics of an obligor in a derivative contract * In the credit derivative context obligors can be protection buyers, protection sellers or the reference entity * More generally an obligor is someone to whom one has counterparty risk */ @BeanDefinition public class Obligor extends DirectBean { // ---------------------------------------------------------------------------------------------------------------------------------------- // TODO : Need to be able to allow the user to add user-defined fields to the definition of an obligor on an ad-hoc basis (each user will have different ways of representing an obligor) // TODO : Should we include the recovery rate model as part of the obligors composition (private final RecoveryRateModel _recoveryRateModel;)? // NOTE : There should be no market data within this objects definition (should only have the obligor characteristics) // ---------------------------------------------------------------------------------------------------------------------------------------- // Private member variables // The obligor identifiers @PropertyDefinition(validate = "notNull") private String _obligorTicker; @PropertyDefinition(validate = "notNull") private String _obligorShortName; @PropertyDefinition(validate = "notNull") private String _obligorREDCode; // The obligor credit rating (MarkIt fields) @PropertyDefinition(validate = "notNull") private CreditRating _compositeRating; @PropertyDefinition(validate = "notNull") private CreditRating _impliedRating; // The obligor credit rating (Moodys, S&P and Fitch classifications) @PropertyDefinition(validate = "notNull") private CreditRatingMoodys _moodysCreditRating; @PropertyDefinition(validate = "notNull") private CreditRatingStandardAndPoors _standardAndPoorsCreditRating; @PropertyDefinition(validate = "notNull") private CreditRatingFitch _fitchCreditRating; // Explicit flag to determine if the obligor has already defaulted prior to the current time @PropertyDefinition(validate = "notNull") private boolean _hasDefaulted; // The obligor industrial sector classification @PropertyDefinition(validate = "notNull") private Sector _sector; // The regional domicile of the obligor @PropertyDefinition(validate = "notNull") private Region _region; // The country of domicile of the obligor @PropertyDefinition(validate = "notNull") private String _country; // ---------------------------------------------------------------------------------------------------------------------------------------- // Obligor constructor private Obligor() { } public Obligor(final String obligorTicker, final String obligorShortName, final String obligorREDCode, final CreditRating compositeRating, final CreditRating impliedRating, final CreditRatingMoodys moodysCreditRating, final CreditRatingStandardAndPoors standardAndPoorsCreditRating, final CreditRatingFitch fitchCreditRating, final boolean hasDefaulted, final Sector sector, final Region region, final String country) { // ---------------------------------------------------------------------------------------------------------------------------------------- // Check the validity of the input arguments ArgumentChecker.notNull(obligorTicker, "Obligor ticker"); ArgumentChecker.isFalse(obligorTicker.isEmpty(), "Obligor ticker"); ArgumentChecker.notNull(obligorShortName, "Obligor short name"); ArgumentChecker.isFalse(obligorShortName.isEmpty(), "Obligor short name"); ArgumentChecker.notNull(obligorREDCode, "Obligor RED code"); ArgumentChecker.isFalse(obligorREDCode.isEmpty(), "Obligor RED code"); ArgumentChecker.notNull(compositeRating, "Composite rating field is null"); ArgumentChecker.notNull(impliedRating, "Implied rating field is null"); ArgumentChecker.notNull(moodysCreditRating, "Moodys credit rating"); ArgumentChecker.notNull(standardAndPoorsCreditRating, "S&P credit rating"); ArgumentChecker.notNull(fitchCreditRating, "Fitch credit rating"); ArgumentChecker.notNull(sector, "Sector field"); ArgumentChecker.notNull(region, "Region field"); ArgumentChecker.notNull(country, "Country field"); ArgumentChecker.isFalse(country.isEmpty(), "Country field"); // Assign the member variables for the obligor object _obligorTicker = obligorTicker; _obligorShortName = obligorShortName; _obligorREDCode = obligorREDCode; _compositeRating = compositeRating; _impliedRating = impliedRating; _moodysCreditRating = moodysCreditRating; _standardAndPoorsCreditRating = standardAndPoorsCreditRating; _fitchCreditRating = fitchCreditRating; _hasDefaulted = hasDefaulted; _sector = sector; _region = region; _country = country; } //------------------------- AUTOGENERATED START ------------------------- ///CLOVER:OFF /** * The meta-bean for {@code Obligor}. * @return the meta-bean, not null */ public static Obligor.Meta meta() { return Obligor.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(Obligor.Meta.INSTANCE); } @Override public Obligor.Meta metaBean() { return Obligor.Meta.INSTANCE; } //----------------------------------------------------------------------- /** * Gets the obligorTicker. * @return the value of the property, not null */ public String getObligorTicker() { return _obligorTicker; } /** * Sets the obligorTicker. * @param obligorTicker the new value of the property, not null */ public void setObligorTicker(String obligorTicker) { JodaBeanUtils.notNull(obligorTicker, "obligorTicker"); this._obligorTicker = obligorTicker; } /** * Gets the the {@code obligorTicker} property. * @return the property, not null */ public final Property<String> obligorTicker() { return metaBean().obligorTicker().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the obligorShortName. * @return the value of the property, not null */ public String getObligorShortName() { return _obligorShortName; } /** * Sets the obligorShortName. * @param obligorShortName the new value of the property, not null */ public void setObligorShortName(String obligorShortName) { JodaBeanUtils.notNull(obligorShortName, "obligorShortName"); this._obligorShortName = obligorShortName; } /** * Gets the the {@code obligorShortName} property. * @return the property, not null */ public final Property<String> obligorShortName() { return metaBean().obligorShortName().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the obligorREDCode. * @return the value of the property, not null */ public String getObligorREDCode() { return _obligorREDCode; } /** * Sets the obligorREDCode. * @param obligorREDCode the new value of the property, not null */ public void setObligorREDCode(String obligorREDCode) { JodaBeanUtils.notNull(obligorREDCode, "obligorREDCode"); this._obligorREDCode = obligorREDCode; } /** * Gets the the {@code obligorREDCode} property. * @return the property, not null */ public final Property<String> obligorREDCode() { return metaBean().obligorREDCode().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the compositeRating. * @return the value of the property, not null */ public CreditRating getCompositeRating() { return _compositeRating; } /** * Sets the compositeRating. * @param compositeRating the new value of the property, not null */ public void setCompositeRating(CreditRating compositeRating) { JodaBeanUtils.notNull(compositeRating, "compositeRating"); this._compositeRating = compositeRating; } /** * Gets the the {@code compositeRating} property. * @return the property, not null */ public final Property<CreditRating> compositeRating() { return metaBean().compositeRating().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the impliedRating. * @return the value of the property, not null */ public CreditRating getImpliedRating() { return _impliedRating; } /** * Sets the impliedRating. * @param impliedRating the new value of the property, not null */ public void setImpliedRating(CreditRating impliedRating) { JodaBeanUtils.notNull(impliedRating, "impliedRating"); this._impliedRating = impliedRating; } /** * Gets the the {@code impliedRating} property. * @return the property, not null */ public final Property<CreditRating> impliedRating() { return metaBean().impliedRating().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the moodysCreditRating. * @return the value of the property, not null */ public CreditRatingMoodys getMoodysCreditRating() { return _moodysCreditRating; } /** * Sets the moodysCreditRating. * @param moodysCreditRating the new value of the property, not null */ public void setMoodysCreditRating(CreditRatingMoodys moodysCreditRating) { JodaBeanUtils.notNull(moodysCreditRating, "moodysCreditRating"); this._moodysCreditRating = moodysCreditRating; } /** * Gets the the {@code moodysCreditRating} property. * @return the property, not null */ public final Property<CreditRatingMoodys> moodysCreditRating() { return metaBean().moodysCreditRating().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the standardAndPoorsCreditRating. * @return the value of the property, not null */ public CreditRatingStandardAndPoors getStandardAndPoorsCreditRating() { return _standardAndPoorsCreditRating; } /** * Sets the standardAndPoorsCreditRating. * @param standardAndPoorsCreditRating the new value of the property, not null */ public void setStandardAndPoorsCreditRating(CreditRatingStandardAndPoors standardAndPoorsCreditRating) { JodaBeanUtils.notNull(standardAndPoorsCreditRating, "standardAndPoorsCreditRating"); this._standardAndPoorsCreditRating = standardAndPoorsCreditRating; } /** * Gets the the {@code standardAndPoorsCreditRating} property. * @return the property, not null */ public final Property<CreditRatingStandardAndPoors> standardAndPoorsCreditRating() { return metaBean().standardAndPoorsCreditRating().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the fitchCreditRating. * @return the value of the property, not null */ public CreditRatingFitch getFitchCreditRating() { return _fitchCreditRating; } /** * Sets the fitchCreditRating. * @param fitchCreditRating the new value of the property, not null */ public void setFitchCreditRating(CreditRatingFitch fitchCreditRating) { JodaBeanUtils.notNull(fitchCreditRating, "fitchCreditRating"); this._fitchCreditRating = fitchCreditRating; } /** * Gets the the {@code fitchCreditRating} property. * @return the property, not null */ public final Property<CreditRatingFitch> fitchCreditRating() { return metaBean().fitchCreditRating().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the hasDefaulted. * @return the value of the property, not null */ public boolean isHasDefaulted() { return _hasDefaulted; } /** * Sets the hasDefaulted. * @param hasDefaulted the new value of the property, not null */ public void setHasDefaulted(boolean hasDefaulted) { JodaBeanUtils.notNull(hasDefaulted, "hasDefaulted"); this._hasDefaulted = hasDefaulted; } /** * Gets the the {@code hasDefaulted} property. * @return the property, not null */ public final Property<Boolean> hasDefaulted() { return metaBean().hasDefaulted().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the sector. * @return the value of the property, not null */ public Sector getSector() { return _sector; } /** * Sets the sector. * @param sector the new value of the property, not null */ public void setSector(Sector sector) { JodaBeanUtils.notNull(sector, "sector"); this._sector = sector; } /** * Gets the the {@code sector} property. * @return the property, not null */ public final Property<Sector> sector() { return metaBean().sector().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the region. * @return the value of the property, not null */ public Region getRegion() { return _region; } /** * Sets the region. * @param region the new value of the property, not null */ public void setRegion(Region region) { JodaBeanUtils.notNull(region, "region"); this._region = region; } /** * Gets the the {@code region} property. * @return the property, not null */ public final Property<Region> region() { return metaBean().region().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the country. * @return the value of the property, not null */ public String getCountry() { return _country; } /** * Sets the country. * @param country the new value of the property, not null */ public void setCountry(String country) { JodaBeanUtils.notNull(country, "country"); this._country = country; } /** * Gets the the {@code country} property. * @return the property, not null */ public final Property<String> country() { return metaBean().country().createProperty(this); } //----------------------------------------------------------------------- @Override public Obligor clone() { return JodaBeanUtils.cloneAlways(this); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { Obligor other = (Obligor) obj; return JodaBeanUtils.equal(getObligorTicker(), other.getObligorTicker()) && JodaBeanUtils.equal(getObligorShortName(), other.getObligorShortName()) && JodaBeanUtils.equal(getObligorREDCode(), other.getObligorREDCode()) && JodaBeanUtils.equal(getCompositeRating(), other.getCompositeRating()) && JodaBeanUtils.equal(getImpliedRating(), other.getImpliedRating()) && JodaBeanUtils.equal(getMoodysCreditRating(), other.getMoodysCreditRating()) && JodaBeanUtils.equal(getStandardAndPoorsCreditRating(), other.getStandardAndPoorsCreditRating()) && JodaBeanUtils.equal(getFitchCreditRating(), other.getFitchCreditRating()) && (isHasDefaulted() == other.isHasDefaulted()) && JodaBeanUtils.equal(getSector(), other.getSector()) && JodaBeanUtils.equal(getRegion(), other.getRegion()) && JodaBeanUtils.equal(getCountry(), other.getCountry()); } return false; } @Override public int hashCode() { int hash = getClass().hashCode(); hash = hash * 31 + JodaBeanUtils.hashCode(getObligorTicker()); hash = hash * 31 + JodaBeanUtils.hashCode(getObligorShortName()); hash = hash * 31 + JodaBeanUtils.hashCode(getObligorREDCode()); hash = hash * 31 + JodaBeanUtils.hashCode(getCompositeRating()); hash = hash * 31 + JodaBeanUtils.hashCode(getImpliedRating()); hash = hash * 31 + JodaBeanUtils.hashCode(getMoodysCreditRating()); hash = hash * 31 + JodaBeanUtils.hashCode(getStandardAndPoorsCreditRating()); hash = hash * 31 + JodaBeanUtils.hashCode(getFitchCreditRating()); hash = hash * 31 + JodaBeanUtils.hashCode(isHasDefaulted()); hash = hash * 31 + JodaBeanUtils.hashCode(getSector()); hash = hash * 31 + JodaBeanUtils.hashCode(getRegion()); hash = hash * 31 + JodaBeanUtils.hashCode(getCountry()); return hash; } @Override public String toString() { StringBuilder buf = new StringBuilder(416); buf.append("Obligor{"); int len = buf.length(); toString(buf); if (buf.length() > len) { buf.setLength(buf.length() - 2); } buf.append('}'); return buf.toString(); } protected void toString(StringBuilder buf) { buf.append("obligorTicker").append('=').append(JodaBeanUtils.toString(getObligorTicker())).append(',').append(' '); buf.append("obligorShortName").append('=').append(JodaBeanUtils.toString(getObligorShortName())).append(',').append(' '); buf.append("obligorREDCode").append('=').append(JodaBeanUtils.toString(getObligorREDCode())).append(',').append(' '); buf.append("compositeRating").append('=').append(JodaBeanUtils.toString(getCompositeRating())).append(',').append(' '); buf.append("impliedRating").append('=').append(JodaBeanUtils.toString(getImpliedRating())).append(',').append(' '); buf.append("moodysCreditRating").append('=').append(JodaBeanUtils.toString(getMoodysCreditRating())).append(',').append(' '); buf.append("standardAndPoorsCreditRating").append('=').append(JodaBeanUtils.toString(getStandardAndPoorsCreditRating())).append(',').append(' '); buf.append("fitchCreditRating").append('=').append(JodaBeanUtils.toString(getFitchCreditRating())).append(',').append(' '); buf.append("hasDefaulted").append('=').append(JodaBeanUtils.toString(isHasDefaulted())).append(',').append(' '); buf.append("sector").append('=').append(JodaBeanUtils.toString(getSector())).append(',').append(' '); buf.append("region").append('=').append(JodaBeanUtils.toString(getRegion())).append(',').append(' '); buf.append("country").append('=').append(JodaBeanUtils.toString(getCountry())).append(',').append(' '); } //----------------------------------------------------------------------- /** * The meta-bean for {@code Obligor}. */ public static class Meta extends DirectMetaBean { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code obligorTicker} property. */ private final MetaProperty<String> _obligorTicker = DirectMetaProperty.ofReadWrite( this, "obligorTicker", Obligor.class, String.class); /** * The meta-property for the {@code obligorShortName} property. */ private final MetaProperty<String> _obligorShortName = DirectMetaProperty.ofReadWrite( this, "obligorShortName", Obligor.class, String.class); /** * The meta-property for the {@code obligorREDCode} property. */ private final MetaProperty<String> _obligorREDCode = DirectMetaProperty.ofReadWrite( this, "obligorREDCode", Obligor.class, String.class); /** * The meta-property for the {@code compositeRating} property. */ private final MetaProperty<CreditRating> _compositeRating = DirectMetaProperty.ofReadWrite( this, "compositeRating", Obligor.class, CreditRating.class); /** * The meta-property for the {@code impliedRating} property. */ private final MetaProperty<CreditRating> _impliedRating = DirectMetaProperty.ofReadWrite( this, "impliedRating", Obligor.class, CreditRating.class); /** * The meta-property for the {@code moodysCreditRating} property. */ private final MetaProperty<CreditRatingMoodys> _moodysCreditRating = DirectMetaProperty.ofReadWrite( this, "moodysCreditRating", Obligor.class, CreditRatingMoodys.class); /** * The meta-property for the {@code standardAndPoorsCreditRating} property. */ private final MetaProperty<CreditRatingStandardAndPoors> _standardAndPoorsCreditRating = DirectMetaProperty.ofReadWrite( this, "standardAndPoorsCreditRating", Obligor.class, CreditRatingStandardAndPoors.class); /** * The meta-property for the {@code fitchCreditRating} property. */ private final MetaProperty<CreditRatingFitch> _fitchCreditRating = DirectMetaProperty.ofReadWrite( this, "fitchCreditRating", Obligor.class, CreditRatingFitch.class); /** * The meta-property for the {@code hasDefaulted} property. */ private final MetaProperty<Boolean> _hasDefaulted = DirectMetaProperty.ofReadWrite( this, "hasDefaulted", Obligor.class, Boolean.TYPE); /** * The meta-property for the {@code sector} property. */ private final MetaProperty<Sector> _sector = DirectMetaProperty.ofReadWrite( this, "sector", Obligor.class, Sector.class); /** * The meta-property for the {@code region} property. */ private final MetaProperty<Region> _region = DirectMetaProperty.ofReadWrite( this, "region", Obligor.class, Region.class); /** * The meta-property for the {@code country} property. */ private final MetaProperty<String> _country = DirectMetaProperty.ofReadWrite( this, "country", Obligor.class, String.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap( this, null, "obligorTicker", "obligorShortName", "obligorREDCode", "compositeRating", "impliedRating", "moodysCreditRating", "standardAndPoorsCreditRating", "fitchCreditRating", "hasDefaulted", "sector", "region", "country"); /** * Restricted constructor. */ protected Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case 896190372: // obligorTicker return _obligorTicker; case -1066272179: // obligorShortName return _obligorShortName; case -823370556: // obligorREDCode return _obligorREDCode; case 957861636: // compositeRating return _compositeRating; case 1421672549: // impliedRating return _impliedRating; case 1016935655: // moodysCreditRating return _moodysCreditRating; case 1963211373: // standardAndPoorsCreditRating return _standardAndPoorsCreditRating; case 1612838220: // fitchCreditRating return _fitchCreditRating; case 1706701094: // hasDefaulted return _hasDefaulted; case -906274970: // sector return _sector; case -934795532: // region return _region; case 957831062: // country return _country; } return super.metaPropertyGet(propertyName); } @Override public BeanBuilder<? extends Obligor> builder() { return new DirectBeanBuilder<Obligor>(new Obligor()); } @Override public Class<? extends Obligor> beanType() { return Obligor.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return _metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code obligorTicker} property. * @return the meta-property, not null */ public final MetaProperty<String> obligorTicker() { return _obligorTicker; } /** * The meta-property for the {@code obligorShortName} property. * @return the meta-property, not null */ public final MetaProperty<String> obligorShortName() { return _obligorShortName; } /** * The meta-property for the {@code obligorREDCode} property. * @return the meta-property, not null */ public final MetaProperty<String> obligorREDCode() { return _obligorREDCode; } /** * The meta-property for the {@code compositeRating} property. * @return the meta-property, not null */ public final MetaProperty<CreditRating> compositeRating() { return _compositeRating; } /** * The meta-property for the {@code impliedRating} property. * @return the meta-property, not null */ public final MetaProperty<CreditRating> impliedRating() { return _impliedRating; } /** * The meta-property for the {@code moodysCreditRating} property. * @return the meta-property, not null */ public final MetaProperty<CreditRatingMoodys> moodysCreditRating() { return _moodysCreditRating; } /** * The meta-property for the {@code standardAndPoorsCreditRating} property. * @return the meta-property, not null */ public final MetaProperty<CreditRatingStandardAndPoors> standardAndPoorsCreditRating() { return _standardAndPoorsCreditRating; } /** * The meta-property for the {@code fitchCreditRating} property. * @return the meta-property, not null */ public final MetaProperty<CreditRatingFitch> fitchCreditRating() { return _fitchCreditRating; } /** * The meta-property for the {@code hasDefaulted} property. * @return the meta-property, not null */ public final MetaProperty<Boolean> hasDefaulted() { return _hasDefaulted; } /** * The meta-property for the {@code sector} property. * @return the meta-property, not null */ public final MetaProperty<Sector> sector() { return _sector; } /** * The meta-property for the {@code region} property. * @return the meta-property, not null */ public final MetaProperty<Region> region() { return _region; } /** * The meta-property for the {@code country} property. * @return the meta-property, not null */ public final MetaProperty<String> country() { return _country; } //----------------------------------------------------------------------- @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case 896190372: // obligorTicker return ((Obligor) bean).getObligorTicker(); case -1066272179: // obligorShortName return ((Obligor) bean).getObligorShortName(); case -823370556: // obligorREDCode return ((Obligor) bean).getObligorREDCode(); case 957861636: // compositeRating return ((Obligor) bean).getCompositeRating(); case 1421672549: // impliedRating return ((Obligor) bean).getImpliedRating(); case 1016935655: // moodysCreditRating return ((Obligor) bean).getMoodysCreditRating(); case 1963211373: // standardAndPoorsCreditRating return ((Obligor) bean).getStandardAndPoorsCreditRating(); case 1612838220: // fitchCreditRating return ((Obligor) bean).getFitchCreditRating(); case 1706701094: // hasDefaulted return ((Obligor) bean).isHasDefaulted(); case -906274970: // sector return ((Obligor) bean).getSector(); case -934795532: // region return ((Obligor) bean).getRegion(); case 957831062: // country return ((Obligor) bean).getCountry(); } return super.propertyGet(bean, propertyName, quiet); } @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { switch (propertyName.hashCode()) { case 896190372: // obligorTicker ((Obligor) bean).setObligorTicker((String) newValue); return; case -1066272179: // obligorShortName ((Obligor) bean).setObligorShortName((String) newValue); return; case -823370556: // obligorREDCode ((Obligor) bean).setObligorREDCode((String) newValue); return; case 957861636: // compositeRating ((Obligor) bean).setCompositeRating((CreditRating) newValue); return; case 1421672549: // impliedRating ((Obligor) bean).setImpliedRating((CreditRating) newValue); return; case 1016935655: // moodysCreditRating ((Obligor) bean).setMoodysCreditRating((CreditRatingMoodys) newValue); return; case 1963211373: // standardAndPoorsCreditRating ((Obligor) bean).setStandardAndPoorsCreditRating((CreditRatingStandardAndPoors) newValue); return; case 1612838220: // fitchCreditRating ((Obligor) bean).setFitchCreditRating((CreditRatingFitch) newValue); return; case 1706701094: // hasDefaulted ((Obligor) bean).setHasDefaulted((Boolean) newValue); return; case -906274970: // sector ((Obligor) bean).setSector((Sector) newValue); return; case -934795532: // region ((Obligor) bean).setRegion((Region) newValue); return; case 957831062: // country ((Obligor) bean).setCountry((String) newValue); return; } super.propertySet(bean, propertyName, newValue, quiet); } @Override protected void validate(Bean bean) { JodaBeanUtils.notNull(((Obligor) bean)._obligorTicker, "obligorTicker"); JodaBeanUtils.notNull(((Obligor) bean)._obligorShortName, "obligorShortName"); JodaBeanUtils.notNull(((Obligor) bean)._obligorREDCode, "obligorREDCode"); JodaBeanUtils.notNull(((Obligor) bean)._compositeRating, "compositeRating"); JodaBeanUtils.notNull(((Obligor) bean)._impliedRating, "impliedRating"); JodaBeanUtils.notNull(((Obligor) bean)._moodysCreditRating, "moodysCreditRating"); JodaBeanUtils.notNull(((Obligor) bean)._standardAndPoorsCreditRating, "standardAndPoorsCreditRating"); JodaBeanUtils.notNull(((Obligor) bean)._fitchCreditRating, "fitchCreditRating"); JodaBeanUtils.notNull(((Obligor) bean)._hasDefaulted, "hasDefaulted"); JodaBeanUtils.notNull(((Obligor) bean)._sector, "sector"); JodaBeanUtils.notNull(((Obligor) bean)._region, "region"); JodaBeanUtils.notNull(((Obligor) bean)._country, "country"); } } ///CLOVER:ON //-------------------------- AUTOGENERATED END -------------------------- }
3e1245493890c78aaedf0b4abb00fef0cabb5fae
7,930
java
Java
app/src/main/java/com/github/hailouwang/demosforapi/shortvideo/list/ShortVideoRecyclerViewFragment.java
linliff/AndroidGo
44468571181dc11559a82f2904c8a1c5b9ef1b22
[ "Apache-2.0" ]
33
2020-04-10T10:37:42.000Z
2022-03-08T09:17:44.000Z
app/src/main/java/com/github/hailouwang/demosforapi/shortvideo/list/ShortVideoRecyclerViewFragment.java
lichang2464/AndroidGo
cdd5583c6aa34414ae59528357b9b20545b36d4b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/github/hailouwang/demosforapi/shortvideo/list/ShortVideoRecyclerViewFragment.java
lichang2464/AndroidGo
cdd5583c6aa34414ae59528357b9b20545b36d4b
[ "Apache-2.0" ]
13
2020-04-24T01:54:44.000Z
2022-03-08T09:17:57.000Z
31.975806
115
0.675158
7,702
package com.github.hailouwang.demosforapi.shortvideo.list; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.dueeeke.dkplayer.activity.MainActivity; import com.dueeeke.dkplayer.adapter.VideoRecyclerViewAdapter; import com.dueeeke.dkplayer.adapter.listener.OnItemChildClickListener; import com.dueeeke.dkplayer.bean.VideoBean; import com.dueeeke.dkplayer.util.DataUtil; import com.dueeeke.dkplayer.util.ProgressManagerImpl; import com.dueeeke.dkplayer.util.Tag; import com.dueeeke.dkplayer.util.Utils; import com.dueeeke.videocontroller.StandardVideoController; import com.dueeeke.videocontroller.component.CompleteView; import com.dueeeke.videocontroller.component.ErrorView; import com.dueeeke.videocontroller.component.GestureView; import com.dueeeke.videocontroller.component.TitleView; import com.dueeeke.videocontroller.component.VodControlView; import com.dueeeke.videoplayer.player.VideoView; import com.github.hailouwang.demosforapi.R; import com.github.hailouwang.demosforapi.shortvideo.BaseShortVideoFragment; import java.util.ArrayList; import java.util.List; /** * 视频播放列表 * - 单 播放实例 */ public class ShortVideoRecyclerViewFragment extends BaseShortVideoFragment implements OnItemChildClickListener { protected List<VideoBean> mVideos = new ArrayList<>(); protected VideoRecyclerViewAdapter mAdapter; protected RecyclerView mRecyclerView; protected LinearLayoutManager mLinearLayoutManager; protected VideoView mVideoView; protected StandardVideoController mController; protected ErrorView mErrorView; protected CompleteView mCompleteView; protected TitleView mTitleView; /** * 当前播放的位置 */ protected int mCurPos = -1; /** * 上次播放的位置,用于页面切回来之后恢复播放 */ protected int mLastPos = mCurPos; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onStart() { super.onStart(); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } @Override public void onStop() { super.onStop(); } @Override public void onDestroy() { super.onDestroy(); } @Override protected int getLayoutResId() { return R.layout.dueeeke_fragment_recycler_view; } @Override public void onDestroyView() { super.onDestroyView(); } @Override protected void initView() { super.initView(); initVideoView(); //保存进度 mVideoView.setProgressManager(new ProgressManagerImpl()); mRecyclerView = findViewById(com.dueeeke.dkplayer.R.id.rv); mLinearLayoutManager = new LinearLayoutManager(getContext()); mRecyclerView.setLayoutManager(mLinearLayoutManager); mAdapter = new VideoRecyclerViewAdapter(mVideos); mAdapter.setOnItemChildClickListener(this); mRecyclerView.setAdapter(mAdapter); mRecyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() { @Override public void onChildViewAttachedToWindow(@NonNull View view) { } @Override public void onChildViewDetachedFromWindow(@NonNull View view) { FrameLayout playerContainer = view.findViewById(com.dueeeke.dkplayer.R.id.player_container); View v = playerContainer.getChildAt(0); if (v != null && v == mVideoView && !mVideoView.isFullScreen()) { releaseVideoView(); } } }); View view = findViewById(com.dueeeke.dkplayer.R.id.add); view.setVisibility(View.VISIBLE); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAdapter.addData(DataUtil.getVideoList()); } }); } protected void initVideoView() { mVideoView = new VideoView(getActivity()); mVideoView.setOnStateChangeListener(new VideoView.SimpleOnStateChangeListener() { @Override public void onPlayStateChanged(int playState) { //监听VideoViewManager释放,重置状态 if (playState == VideoView.STATE_IDLE) { Utils.removeViewFormParent(mVideoView); mLastPos = mCurPos; mCurPos = -1; } } }); mController = new StandardVideoController(getActivity()); mErrorView = new ErrorView(getActivity()); mController.addControlComponent(mErrorView); mCompleteView = new CompleteView(getActivity()); mController.addControlComponent(mCompleteView); mTitleView = new TitleView(getActivity()); mController.addControlComponent(mTitleView); mController.addControlComponent(new VodControlView(getActivity())); mController.addControlComponent(new GestureView(getActivity())); mController.setEnableOrientation(true); mVideoView.setVideoController(mController); } @Override protected void initData() { super.initData(); List<VideoBean> videoList = DataUtil.getVideoList(); mVideos.addAll(videoList); mAdapter.notifyDataSetChanged(); } @Override protected boolean isLazyLoad() { return true; } /** * 由于onResume必须调用super。故增加此方法, * 子类将会重写此方法,改变onResume的逻辑 */ protected void resume() { if (mLastPos == -1) return; if (MainActivity.mCurrentIndex != 1) return; //恢复上次播放的位置 startPlay(mLastPos); } /** * PrepareView被点击 */ @Override public void onItemChildClick(int position) { startPlay(position); } /** * 开始播放 * @param position 列表位置 */ protected void startPlay(int position) { if (mCurPos == position) return; if (mCurPos != -1) { releaseVideoView(); } VideoBean videoBean = mVideos.get(position); //边播边存 // String proxyUrl = ProxyVideoCacheManager.getProxy(getActivity()).getProxyUrl(videoBean.getUrl()); // mVideoView.setUrl(proxyUrl); mVideoView.setUrl(videoBean.getUrl()); mTitleView.setTitle(videoBean.getTitle()); View itemView = mLinearLayoutManager.findViewByPosition(position); if (itemView == null) return; VideoRecyclerViewAdapter.VideoHolder viewHolder = (VideoRecyclerViewAdapter.VideoHolder) itemView.getTag(); //把列表中预置的PrepareView添加到控制器中,注意isPrivate此处只能为true。 mController.addControlComponent(viewHolder.mPrepareView, true); Utils.removeViewFormParent(mVideoView); viewHolder.mPlayerContainer.addView(mVideoView, 0); //播放之前将VideoView添加到VideoViewManager以便在别的页面也能操作它 getVideoViewManager().add(mVideoView, Tag.LIST); mVideoView.start(); mCurPos = position; } private void releaseVideoView() { mVideoView.release(); if (mVideoView.isFullScreen()) { mVideoView.stopFullScreen(); } if(getActivity().getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } mCurPos = -1; } }
3e1245d2e1cfe3cb088a3db6a5a4615b8bc3573e
2,034
java
Java
piccolo-common/src/main/java/io/github/ukuz/piccolo/common/message/UnbindUserMessage.java
cheese8/piccolo
5f1cdba39e67607a9b90d276689907a93d6cce41
[ "Apache-2.0" ]
18
2019-09-05T15:23:27.000Z
2021-12-24T04:54:12.000Z
piccolo-common/src/main/java/io/github/ukuz/piccolo/common/message/UnbindUserMessage.java
cheese8/piccolo
5f1cdba39e67607a9b90d276689907a93d6cce41
[ "Apache-2.0" ]
13
2020-03-21T02:02:03.000Z
2021-10-16T08:31:05.000Z
piccolo-common/src/main/java/io/github/ukuz/piccolo/common/message/UnbindUserMessage.java
cheese8/piccolo
5f1cdba39e67607a9b90d276689907a93d6cce41
[ "Apache-2.0" ]
15
2019-10-18T07:12:45.000Z
2021-12-23T08:11:25.000Z
30.358209
90
0.665192
7,703
/* * Copyright 2019 ukuz90 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.ukuz.piccolo.common.message; import io.github.ukuz.piccolo.api.connection.Connection; import io.github.ukuz.piccolo.api.exchange.support.ByteBufMessage; import static io.github.ukuz.piccolo.common.constants.CommandType.UNBIND_USER; import io.netty.buffer.ByteBuf; /** * @author ukuz90 */ public class UnbindUserMessage extends ByteBufMessage { public String userId; public String tags; public String data; public UnbindUserMessage(Connection connection) { super(connection, UNBIND_USER.getCmd()); } @Override protected void decodeBody0(ByteBuf buf) { userId = readString(buf); tags = readString(buf); data = readString(buf); } @Override protected void encodeBody0(ByteBuf buf) { writeString(buf, userId); writeString(buf, tags); writeString(buf, data); } public static UnbindUserMessage from(Connection connection, BindUserMessage bindMsg) { UnbindUserMessage unbindMsg = new UnbindUserMessage(connection); unbindMsg.data = bindMsg.data; unbindMsg.userId = bindMsg.userId; unbindMsg.tags = bindMsg.tags; return unbindMsg; } @Override public String toString() { return "UnbindUserMessage{" + "userId='" + userId + '\'' + ", tags='" + tags + '\'' + ", data='" + data + '\'' + '}'; } }
3e12466eaf84301875a54de8071159d019f5df53
900
java
Java
gde-integral-service/src/main/java/com/gde/integral/service/dispose/service/IntegralAlterInfoService.java
bingdaosdu/scoresystem
d9847f514201bc27ad4042279d5da290bb968def
[ "Apache-2.0" ]
null
null
null
gde-integral-service/src/main/java/com/gde/integral/service/dispose/service/IntegralAlterInfoService.java
bingdaosdu/scoresystem
d9847f514201bc27ad4042279d5da290bb968def
[ "Apache-2.0" ]
null
null
null
gde-integral-service/src/main/java/com/gde/integral/service/dispose/service/IntegralAlterInfoService.java
bingdaosdu/scoresystem
d9847f514201bc27ad4042279d5da290bb968def
[ "Apache-2.0" ]
null
null
null
23.076923
143
0.661111
7,704
package com.gde.integral.service.dispose.service; import java.util.Date; /** * 积分变更服务接口 * * @author ~ * @date 2019/6/25 */ public interface IntegralAlterInfoService { /** * 积分修改 * * @param name 名字 * @param w3id w3id * @param alterValue 变更的值 * @param alterReason 变更理由 * @param startDate 数据开始日期 * @param recordTime 数据记录日期 * @param operator 操作者 * @return 返回修改是否成功 */ boolean integralAlter(String name, String w3id, double alterValue, String alterReason, String startDate, Date recordTime, String operator); /** * 根据w3id获取指定数据记录日期指定变更理由的积分变更信息数据的数量 * * @param w3id w3id * @param alterReason 变更理由 * @param startRecordTime 开始记录时间 * @param endRecordTime 结束记录时间 * @return 返回数量 */ int countByW3idAndRecordTime(String w3id, String alterReason, Date startRecordTime, Date endRecordTime); }
3e1247678b48c62dcd7fe94d2a6333033f6669bd
786
java
Java
aa_presentation/src/main/java/de/mpg/mpdl/inge/aa/web/client/IngeAaLogoutClient.java
MPDL/INGe
0df50701dd5ed3d12e63ad859a38a83dbe5f3d5a
[ "Apache-2.0" ]
5
2018-01-24T15:57:58.000Z
2022-03-31T13:27:10.000Z
aa_presentation/src/main/java/de/mpg/mpdl/inge/aa/web/client/IngeAaLogoutClient.java
MPDL-Collections/INGe
d4281410835fdaf5a2f388d15bdfc77b5d4ecae1
[ "Apache-2.0" ]
21
2018-04-26T07:44:52.000Z
2022-02-16T00:54:31.000Z
aa_presentation/src/main/java/de/mpg/mpdl/inge/aa/web/client/IngeAaLogoutClient.java
MPDL-Collections/INGe
d4281410835fdaf5a2f388d15bdfc77b5d4ecae1
[ "Apache-2.0" ]
1
2021-01-06T13:32:15.000Z
2021-01-06T13:32:15.000Z
24.5625
108
0.727735
7,705
package de.mpg.mpdl.inge.aa.web.client; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import de.mpg.mpdl.inge.aa.Aa; /** * * @author haarlaender * */ public class IngeAaLogoutClient extends LogoutClient { @Override protected String getLogoutUrl(HttpServletRequest request, HttpServletResponse response) throws Exception { String originalTarget = request.getParameter("target"); Aa aa = new Aa(request); if (aa.getAuthenticationVO() != null) { IngeAaClientFinish.logoutInInge(aa.getAuthenticationVO().getToken()); } HttpSession session = request.getSession(false); if (session != null) { session.invalidate(); } return originalTarget; } }
3e124777a5f22505eb6481e118e048dcc8f2438c
4,239
java
Java
de.mhus.inka.constgenerator/src/main/java/de/mhus/inka/constgenerator/CGFileConst.java
mhus/mhus-inka
dbb9e908700b3d922849b2ead1ba2409f08cb4a3
[ "Apache-2.0" ]
1
2021-07-01T11:50:17.000Z
2021-07-01T11:50:17.000Z
de.mhus.inka.constgenerator/src/main/java/de/mhus/inka/constgenerator/CGFileConst.java
mhus/mhus-inka
dbb9e908700b3d922849b2ead1ba2409f08cb4a3
[ "Apache-2.0" ]
null
null
null
de.mhus.inka.constgenerator/src/main/java/de/mhus/inka/constgenerator/CGFileConst.java
mhus/mhus-inka
dbb9e908700b3d922849b2ead1ba2409f08cb4a3
[ "Apache-2.0" ]
null
null
null
59.704225
121
0.80184
7,706
package de.mhus.inka.constgenerator; // auto generated public class CGFileConst { public static final String CLASS_DE_MHUS_INKA_SOURCECODEGENERATOR_SCGFILE = "de_mhus_inka_sourcecodegenerator_SCGFile"; public static final String CLASS_METHODVISITOR = "MethodVisitor"; public static final String ID_CU = "cu"; public static final String ID_CURRENTCLASS = "currentClass"; public static final String ID_CURRENTCLASS_l = "currentclass"; public static final String ID_CURRENTCLASS_u = "CURRENTCLASS"; public static final String ID_CURRENTMETHOD = "currentMethod"; public static final String ID_CURRENTMETHOD_l = "currentmethod"; public static final String ID_CURRENTMETHOD_u = "CURRENTMETHOD"; public static final String ID_CU_l = "cu"; public static final String ID_CU_u = "CU"; public static final String ID_DEBUG = "Debug"; public static final String ID_DEBUG_l = "debug"; public static final String ID_DEBUG_u = "DEBUG"; public static final String ID_DE_MHUS_INKA_SOURCECODEGENERATOR = "de_mhus_inka_sourcecodegenerator"; public static final String ID_DE_MHUS_INKA_SOURCECODEGENERATOR_SCGFILE = "de_mhus_inka_sourcecodegenerator_SCGFile"; public static final String ID_DE_MHUS_INKA_SOURCECODEGENERATOR_SCGFILE_l = "de_mhus_inka_sourcecodegenerator_scgfile"; public static final String ID_DE_MHUS_INKA_SOURCECODEGENERATOR_SCGFILE_u = "DE_MHUS_INKA_SOURCECODEGENERATOR_SCGFILE"; public static final String ID_DE_MHUS_INKA_SOURCECODEGENERATOR_l = "de_mhus_inka_sourcecodegenerator"; public static final String ID_DE_MHUS_INKA_SOURCECODEGENERATOR_u = "DE_MHUS_INKA_SOURCECODEGENERATOR"; public static final String ID_ENTRIES = "Entries"; public static final String ID_ENTRIES_l = "entries"; public static final String ID_ENTRIES_u = "ENTRIES"; public static final String ID_LIST = "list"; public static final String ID_LIST_l = "list"; public static final String ID_LIST_u = "LIST"; public static final String ID_MAINCLASS = "MainClass"; public static final String ID_MAINCLASS_l = "mainclass"; public static final String ID_MAINCLASS_u = "MAINCLASS"; public static final String ID_METHODVISITOR = "MethodVisitor"; public static final String ID_METHODVISITOR_VISIT = "MethodVisitor_visit"; public static final String ID_METHODVISITOR_VISIT_l = "methodvisitor_visit"; public static final String ID_METHODVISITOR_VISIT_u = "METHODVISITOR_VISIT"; public static final String ID_METHODVISITOR_l = "methodvisitor"; public static final String ID_METHODVISITOR_u = "METHODVISITOR"; public static final String ID_PACK = "pack"; public static final String ID_PACKAGE = "Package"; public static final String ID_PACKAGE_l = "package"; public static final String ID_PACKAGE_u = "PACKAGE"; public static final String ID_PACK_l = "pack"; public static final String ID_PACK_u = "PACK"; public static final String ID_PARSE = "Parse"; public static final String ID_PARSE_l = "parse"; public static final String ID_PARSE_u = "PARSE"; public static final String ID_SHOULDPROCEED = "shouldProceed"; public static final String ID_SHOULDPROCEED_l = "shouldproceed"; public static final String ID_SHOULDPROCEED_u = "SHOULDPROCEED"; public static final String METHOD_DOPARSE = "doParse"; public static final String METHOD_GETENTRIES = "getEntries"; public static final String METHOD_GETMAINCLASS = "getMainClass"; public static final String METHOD_GETPACKAGE = "getPackage"; public static final String METHOD_ISDEBUG = "isDebug"; public static final String METHOD_METHODVISITOR_VISIT = "MethodVisitor_visit"; public static final String METHOD_SETDEBUG = "setDebug"; public static final String METHOD_SHOULDPROCEED = "shouldProceed"; public static final String PACKAGE_DE_MHUS_INKA_SOURCECODEGENERATOR = "de_mhus_inka_sourcecodegenerator"; public static final String VARIABLE_CU = "cu"; public static final String VARIABLE_CURRENTCLASS = "currentClass"; public static final String VARIABLE_CURRENTMETHOD = "currentMethod"; public static final String VARIABLE_DEBUG = "debug"; public static final String VARIABLE_LIST = "list"; public static final String VARIABLE_MAINCLASS = "mainClass"; public static final String VARIABLE_PACK = "pack"; }
3e124785dcb0f498340313722b340c16a580a062
23,544
java
Java
source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/framework/resources/Resources.java
benzman81/team-explorer-everywhere
eb3985c7cb629af9b0ff1c3678403f5c910b7d06
[ "MIT" ]
86
2019-05-13T02:21:26.000Z
2022-02-06T17:43:29.000Z
source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/framework/resources/Resources.java
benzman81/team-explorer-everywhere
eb3985c7cb629af9b0ff1c3678403f5c910b7d06
[ "MIT" ]
82
2019-05-14T06:34:16.000Z
2022-03-23T20:20:19.000Z
source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/framework/resources/Resources.java
benzman81/team-explorer-everywhere
eb3985c7cb629af9b0ff1c3678403f5c910b7d06
[ "MIT" ]
61
2019-05-10T19:34:33.000Z
2022-03-18T06:29:06.000Z
43.359116
139
0.641225
7,707
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the repository root. package com.microsoft.tfs.client.common.framework.resources; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import com.microsoft.tfs.client.common.framework.resources.filter.ResourceFilter; import com.microsoft.tfs.util.Check; /** * {@link Resources} is a helper class containing static utility methods for * working with {@link IResource} objects. */ public class Resources { /** * <p> * Obtains the absolute locations ({@link IResource#getLocation()}) of an * array of resources. Each location is represented as a {@link String} * using the platform-dependent separator character ( * {@link IPath#toOSString()}). * </p> * * <p> * For some resources, a location is not available. The * {@link LocationUnavailablePolicy} parameter determines the behavior in * this case. If the policy is {@link LocationUnavailablePolicy#THROW}, an * exception will be thrown if a resources does not have a location. If the * policy is {@link LocationUnavailablePolicy#IGNORE_RESOURCE}, a resource * that does not have a location will be ignored and will not have a * corresponding element in the returned array. * </p> * * @param resources * the input array of {@link IResource}s - must not be * <code>null</code>, and must not contain any <code>null</code> * elements * @param locationUnavailablePolicy * a {@link LocationUnavailablePolicy} specifying what to do if one * of the input {@link IResource}s does not have a location (must not * be <code>null</code>) * @return an array of {@link String} locations as described above */ public static String[] getLocations( final IResource[] resources, final LocationUnavailablePolicy locationUnavailablePolicy) { Check.notNull(resources, "resources"); //$NON-NLS-1$ Check.notNull(locationUnavailablePolicy, "locationUnavailablePolicy"); //$NON-NLS-1$ final List locations = new ArrayList(); for (int i = 0; i < resources.length; i++) { if (resources[i] == null) { throw new IllegalArgumentException("element " + i + " in the passed IResource array was null"); //$NON-NLS-1$ //$NON-NLS-2$ } final String location = getLocation(resources[i], locationUnavailablePolicy); if (location != null) { locations.add(location); } } return (String[]) locations.toArray(new String[locations.size()]); } /** * <p> * Obtains the absolute location ({@link IResource#getLocation()}) of a * resource. The location is represented as a {@link String} using the * platform-dependent separator character ({@link IPath#toOSString()}). * </p> * * <p> * For some resources, a location is not available. The * {@link LocationUnavailablePolicy} parameter determines the behavior in * this case. If the policy is {@link LocationUnavailablePolicy#THROW}, an * exception will be thrown if the resource does not have a location. If the * policy is {@link LocationUnavailablePolicy#IGNORE_RESOURCE}, * <code>null</code> will be returned from this method if the resource does * not have a location. * </p> * * @param resource * the input {@link IResource} - must not be <code>null</code> * @param locationUnavailablePolicy * a {@link LocationUnavailablePolicy} specifying what to do if the * input {@link IResource} does not have a location (must not be * <code>null</code>) * @return the {@link String} location as described above */ public static String getLocation( final IResource resource, final LocationUnavailablePolicy locationUnavailablePolicy) { Check.notNull(resource, "resource"); //$NON-NLS-1$ Check.notNull(locationUnavailablePolicy, "locationUnavailablePolicy"); //$NON-NLS-1$ final IPath locationPath = resource.getLocation(); if (locationPath == null) { if (LocationUnavailablePolicy.THROW == locationUnavailablePolicy) { final String messageFormat = "the resource [{0}] does not have a location"; //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, resource); throw new RuntimeException(message); } return null; } return locationPath.toOSString(); } /** * <p> * Given an absolute location on the local file system, attempts to find a * workspace file resource that corresponds to that location. * <b>Important:</b> this method will not find resources that are linked or * that are the children of linked resources. * </p> * * <p> * This method will only return an existing resource. If the specified * location corresponds to a location inside a project in the workspace, but * no file resource currently exists at that location, <code>null</code> is * returned. * </p> * * <p> * This method will only return file resources. If there is not a file * resource at the specified location, <code>null</code> is returned (even * if there is a container resource at the location). * </p> * * @param location * an absolute location on the local file system (must not be * <code>null</code>) * @return an {@link IFile} that corresponds to the specified file system * location, or <code>null</code> if the location did not map to any * resource or if <code>mustExist</code> is <code>true</code> and * the location did not map to an existing resource */ public static IFile getFileForLocation(final String location) { return (IFile) getResourceForLocation(location, ResourceType.FILE, true); } /** * <p> * Given an absolute location on the local file system, attempts to find a * workspace file resource that corresponds to that location. * <b>Important:</b> this method will not find resources that are linked or * that are the children of linked resources. * </p> * * <p> * If the <code>mustExist</code> parameter is <code>false</code>, this * method could return a resource handle that corresponds to a non-existing * resource. If <code>mustExist</code> is <code>true</code>, a non- * <code>null</code> return value can be assumed to exist. * </p> * * <p> * This method will only return file resources. If there is not a file * resource at the specified location, <code>null</code> is returned (even * if there is a container resource at the location). * </p> * * @param location * an absolute location on the local file system (must not be * <code>null</code>) <code>null</code>) * @param mustExist * if <code>true</code>, this method will only return an existing * resource; if <code>false</code>, the returned resource may not * actually exist in the workspace * @return an {@link IFile} that corresponds to the specified file system * location, or <code>null</code> if the location did not map to any * file resource or if <code>mustExist</code> is <code>true</code> * and the location did not map to an existing resource */ public static IFile getFileForLocation(final String location, final boolean mustExist) { return (IFile) getResourceForLocation(location, ResourceType.FILE, mustExist); } /** * <p> * Given an absolute location on the local file system, attempts to find a * workspace container resource that corresponds to that location. * <b>Important:</b> this method will not find resources that are linked or * that are the children of linked resources. * </p> * * <p> * This method will only return an existing resource. If the specified * location corresponds to a location inside a project in the workspace, but * no container resource currently exists at that location, * <code>null</code> is returned. * </p> * * <p> * This method will only return container resources. If there is not a * container resource at the specified location, <code>null</code> is * returned (even if there is a file resource at the location). * </p> * * @param location * an absolute location on the local file system (must not be * <code>null</code>) * @return an {@link IContainer} that corresponds to the specified file * system location, or <code>null</code> if the location did not map * to any resource or if <code>mustExist</code> is <code>true</code> * and the location did not map to an existing resource */ public static IContainer getContainerForLocation(final String location) { return (IContainer) getResourceForLocation(location, ResourceType.CONTAINER, true); } /** * <p> * Given an absolute location on the local file system, attempts to find a * workspace container resource that corresponds to that location. * <b>Important:</b> this method will not find resources that are linked or * that are the children of linked resources. * </p> * * <p> * If the <code>mustExist</code> parameter is <code>false</code>, this * method could return a resource handle that corresponds to a non-existing * resource. If <code>mustExist</code> is <code>true</code>, a non- * <code>null</code> return value can be assumed to exist. * </p> * * <p> * This method will only return container resources. If there is not a * container resource at the specified location, <code>null</code> is * returned (even if there is a file resource at the location). * </p> * * @param location * an absolute location on the local file system (must not be * <code>null</code>) <code>null</code>) * @param mustExist * if <code>true</code>, this method will only return an existing * resource; if <code>false</code>, the returned resource may not * actually exist in the workspace * @return an {@link IContainer} that corresponds to the specified file * system location, or <code>null</code> if the location did not map * to any container resource or if <code>mustExist</code> is * <code>true</code> and the location did not map to an existing * resource */ public static IContainer getContainerForLocation(final String location, final boolean mustExist) { return (IContainer) getResourceForLocation(location, ResourceType.CONTAINER, mustExist); } /** * <p> * Given an absolute location on the local file system, attempts to find a * workspace resource that corresponds to that location. <b>Important:</b> * this method will not find resources that are linked or that are the * children of linked resources. * </p> * * <p> * This method will only return an existing resource. If the specified * location corresponds to a location inside a project in the workspace, but * no resource currently exists at that location, <code>null</code> is * returned. * </p> * * <p> * This method should only be used when the desired type of resource is * unknown - for example, when processing user input. If the desired * resource type is known, call an overload that takes a * {@link ResourceType} instead. * </p> * * @param location * an absolute location on the local file system (must not be * <code>null</code>) * @return an {@link IResource} that corresponds to the specified file * system location, or <code>null</code> if the location did not map * to any existing resource */ public static IResource getResourceForLocation(final String location) { return getResourceForLocation(location, ResourceType.ANY, true); } /** * <p> * Given an absolute location on the local file system, attempts to find a * workspace resource that corresponds to that location. <b>Important:</b> * this method will not find resources that are linked or that are the * children of linked resources. * </p> * * <p> * This method will only return an existing resource. If the specified * location corresponds to a location inside a project in the workspace, but * no resource currently exists at that location, <code>null</code> is * returned. * </p> * * <p> * The {@link ResourceType} parameter is used to determine what type of * resource (file or container) to look for. Whenever the desired resource * type is known, the appropriate {@link ResourceType} should be passed for * efficiency. If the desired resource type is not known, * {@link ResourceType#ANY} can be passed to indicate that any type of * returned resource is acceptable. * </p> * * @param location * an absolute location on the local file system (must not be * <code>null</code>) * @param resourceType * determines what type of resource to look for (must not be * <code>null</code>) * @return an {@link IResource} that corresponds to the specified file * system location, or <code>null</code> if the location did not map * to any existing resource */ public static IResource getResourceForLocation(final String location, final ResourceType resourceType) { return getResourceForLocation(location, resourceType, true); } /** * <p> * Given an absolute location on the local file system, attempts to find a * workspace resource that corresponds to that location. <b>Important:</b> * this method will not find resources that are linked or that are the * children of linked resources. * </p> * * <p> * If the <code>mustExist</code> parameter is <code>false</code>, this * method could return a resource handle that corresponds to a non-existing * resource. If <code>mustExist</code> is <code>true</code>, a non- * <code>null</code> return value can be assumed to exist. * </p> * * <p> * The {@link ResourceType} parameter is used to determine what type of * resource (file or container) to look for. Whenever the desired resource * type is known, the appropriate {@link ResourceType} should be passed for * efficiency. If the desired resource type is not known, * {@link ResourceType#ANY} can be passed to indicate that any type of * returned resource is acceptable. However, if <code>mustExist</code> is * <code>false</code>, {@link ResourceType#ANY} is illegal to pass since * this is ambiguous. * </p> * * @param location * an absolute location on the local file system (must not be * <code>null</code>) * @param resourceType * determines what type of resource to look for (must not be * <code>null</code>) * @param mustExist * if <code>true</code>, this method will only return an existing * resource; if <code>false</code>, the returned resource may not * actually exist in the workspace * @return an {@link IResource} that corresponds to the specified file * system location, or <code>null</code> if the location did not map * to any resource or if <code>mustExist</code> is <code>true</code> * and the location did not map to an existing resource */ public static IResource getResourceForLocation( final String location, final ResourceType resourceType, final boolean mustExist) { Check.notNull(location, "location"); //$NON-NLS-1$ Check.notNull(resourceType, "resourceType"); //$NON-NLS-1$ final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); final IPath path = new Path(location); return resourceType.getResourceForLocation(path, root, mustExist); } /** * <p> * Given an absolute location on the local file system, attempts to find all * workspace resource that corresponds to that location. <b>Important:</b> * this method will not find resources that are linked or that are the * children of linked resources. * </p> * * <p> * If the <code>mustExist</code> parameter is <code>false</code>, this * method could return a resource handle that corresponds to a non-existing * resource. If <code>mustExist</code> is <code>true</code>, a non- * <code>null</code> return value can be assumed to exist. * </p> * * <p> * The {@link ResourceType} parameter is used to determine what type of * resource (file or container) to look for. Whenever the desired resource * type is known, the appropriate {@link ResourceType} should be passed for * efficiency. If the desired resource type is not known, * {@link ResourceType#ANY} can be passed to indicate that any type of * returned resource is acceptable. However, if <code>mustExist</code> is * <code>false</code>, {@link ResourceType#ANY} is illegal to pass since * this is ambiguous. * </p> * * @param location * an absolute location on the local file system (must not be * <code>null</code>) * @param resourceType * determines what type of resource to look for (must not be * <code>null</code>) * @param mustExist * if <code>true</code>, this method will only return an existing * resource; if <code>false</code>, the returned resource may not * actually exist in the workspace * @return all {@link IResource}s that corresponds to the specified file * system location, or <code>null</code> if the location did not map * to any resource or if <code>mustExist</code> is <code>true</code> * and the location did not map to any existing resources */ public static IResource[] getAllResourcesForLocation( final String location, final ResourceType resourceType, final boolean mustExist) { Check.notNull(location, "location"); //$NON-NLS-1$ Check.notNull(resourceType, "resourceType"); //$NON-NLS-1$ final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); final IPath path = new Path(location); return resourceType.getAllResourcesForLocation(path, root, mustExist); } public static LocationInfo getLocationInfo(final String location) { Check.notNull(location, "location"); //$NON-NLS-1$ final IPath path = new Path(location); return new LocationInfo(path); } /** * Selects a subset of the input array of {@link IResource}s using an * {@link ResourceFilter}. * * @param resources * the input array of {@link IResource}s - must not be * <code>null</code>, and must not contain any <code>null</code> * elements * @param filter * an {@link ResourceFilter} used to select the returned resources * (must not be <code>null</code>) * @return an array of {@link IResource}s which is never <code>null</code> * and is a subset of the resources passed to this method */ public static IResource[] filter(final IResource[] resources, final ResourceFilter filter) { Check.notNull(resources, "resources"); //$NON-NLS-1$ Check.notNull(filter, "filter"); //$NON-NLS-1$ final List results = new ArrayList(); for (int i = 0; i < resources.length; i++) { if (resources[i] == null) { throw new IllegalArgumentException("element " + i + " in the passed IResource array was null"); //$NON-NLS-1$ //$NON-NLS-2$ } if (filter.filter(resources[i]).isAccept()) { results.add(resources[i]); } } return (IResource[]) results.toArray(new IResource[results.size()]); } /** * Equivalent to calling {@link IContainer#members()} on the specified * container, and then running all members through a {@link ResourceFilter}. * Any members that are accepted by the filter will be returned from this * method. * * @param container * the container to call {@link IContainer#members(int)} on (must not * be <code>null</code>) * @param resourceFilter * the {@link ResourceFilter} to use to filter the members (must not * be <code>null</code>) * @return the filtered members of the container (never <code>null</code>) * @throws CoreException */ public static IResource[] getFilteredMembers(final IContainer container, final ResourceFilter resourceFilter) throws CoreException { return getFilteredMembers(container, IResource.NONE, resourceFilter); } /** * Equivalent to calling {@link IContainer#members(int)} on the specified * container, and then running all members through a {@link ResourceFilter}. * Any members that are accepted by the filter will be returned from this * method. * * @param container * the container to call {@link IContainer#members(int)} on (must not * be <code>null</code>) * @param memberFlags * the flags to pass to {@link IContainer#members(int)} * @param resourceFilter * the {@link ResourceFilter} to use to filter the members (must not * be <code>null</code>) * @return the filtered members of the container (never <code>null</code>) * @throws CoreException */ public static IResource[] getFilteredMembers( final IContainer container, final int memberFlags, final ResourceFilter resourceFilter) throws CoreException { Check.notNull(container, "container"); //$NON-NLS-1$ Check.notNull(resourceFilter, "resourceFilter"); //$NON-NLS-1$ final IResource[] allMembers = container.members(memberFlags); final List filteredMembers = new ArrayList(); for (int i = 0; i < allMembers.length; i++) { if (resourceFilter.filter(allMembers[i]).isAccept()) { filteredMembers.add(allMembers[i]); } } return (IResource[]) filteredMembers.toArray(new IResource[filteredMembers.size()]); } }
3e1247d5fc4940b3c0348b6b8ccae10c07c45a2d
1,744
java
Java
src/main/java/dev/ejolie/base64example/util/FileUtil.java
ejolie/spring-base64-example
cc3278dd188e3257b2930b7d40b91e8f1e2a612d
[ "MIT" ]
null
null
null
src/main/java/dev/ejolie/base64example/util/FileUtil.java
ejolie/spring-base64-example
cc3278dd188e3257b2930b7d40b91e8f1e2a612d
[ "MIT" ]
null
null
null
src/main/java/dev/ejolie/base64example/util/FileUtil.java
ejolie/spring-base64-example
cc3278dd188e3257b2930b7d40b91e8f1e2a612d
[ "MIT" ]
null
null
null
32.90566
98
0.705849
7,708
package dev.ejolie.base64example.util; import org.springframework.util.StringUtils; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.net.FileNameMap; import java.net.URLConnection; import java.util.Base64; import java.util.Set; public final class FileUtil { private static final Set<String> UNSUPPORTED_EXT = Set.of("TIF", "TIFF", "tif", "tiff"); private FileUtil() { throw new IllegalStateException("FileUtil class"); } public static String convertImageToBase64(byte[] bytes) { return Base64.getEncoder().encodeToString(bytes); } public static String getExtension(String filename) throws Exception { if (!StringUtils.hasText(filename) || !filename.contains(".")) { throw new Exception("Not valid filename."); } return filename.substring(filename.lastIndexOf(".") + 1); } public static String getMimeType(String filename) { FileNameMap fileNameMap = URLConnection.getFileNameMap(); return fileNameMap.getContentTypeFor(filename); } public static boolean isUnsupportedExt(String filename) throws Exception { return UNSUPPORTED_EXT.contains(getExtension(filename)); } public static byte[] getByteArrayOfFormat(final File file, String format) throws IOException { final BufferedImage origin = ImageIO.read(file); byte[] bytes; try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { ImageIO.write(origin, format, byteArrayOutputStream); bytes = byteArrayOutputStream.toByteArray(); } return bytes; } }
3e1247f43e457dcfb9832bc3ff09661f899c7ed7
89
java
Java
src/main/java/org/jconverter/converter/catalog/array/package-info.java
jconverter/jconverter
0e737efed8741149417e38203c4eda2a98cca7e4
[ "Apache-2.0" ]
null
null
null
src/main/java/org/jconverter/converter/catalog/array/package-info.java
jconverter/jconverter
0e737efed8741149417e38203c4eda2a98cca7e4
[ "Apache-2.0" ]
null
null
null
src/main/java/org/jconverter/converter/catalog/array/package-info.java
jconverter/jconverter
0e737efed8741149417e38203c4eda2a98cca7e4
[ "Apache-2.0" ]
null
null
null
11.125
47
0.606742
7,709
/** * */ /** * @author sergioc * */ package org.jconverter.converter.catalog.array;
3e124812cba3e5b08942047c567357d9503eae23
1,348
java
Java
07-Design/src/game/CardDeck.java
StEvUgnIn/Java-HS17
66dc5b5122dea0abc079281f8892a6f3b01d9ddd
[ "MIT" ]
null
null
null
07-Design/src/game/CardDeck.java
StEvUgnIn/Java-HS17
66dc5b5122dea0abc079281f8892a6f3b01d9ddd
[ "MIT" ]
null
null
null
07-Design/src/game/CardDeck.java
StEvUgnIn/Java-HS17
66dc5b5122dea0abc079281f8892a6f3b01d9ddd
[ "MIT" ]
null
null
null
18.216216
57
0.588279
7,710
package game; import java.util.ArrayList; import java.util.Random; public class CardDeck { public static final int CARDS_PER_SUIT = 13; private static Random rd; private ArrayList<Card> deck; CardDeck() { deck = new ArrayList<Card>(); } public void fill () { for (Suit s : Suit.values()) { for (int i = 0; i <= CARDS_PER_SUIT; i++) { deck.add(new Card(i, s)); } } shuffle(); } private void shuffle() { ArrayList<Card> shuffleDeck = new ArrayList<>(); while (deck.size() > 0) { shuffleDeck.add(deck.remove(rd.nextInt(deck.size()))); } while (shuffleDeck.size() > 0) { deck.add(deck.remove(rd.nextInt(shuffleDeck.size()))); } } public Card take () { return deck.remove(0); } public boolean add (Card card) { return deck.add(card); } public boolean hasCardsFromEachSuit (int n, Suit suit) { int count = 0; for (Card c : deck) { if (c.getSuit() == suit) { ++count; } } return count >= n; } public boolean hasCardsFromEachSuit(int n) { for (Suit s : Suit.values()) { if(!hasCardsFromEachSuit(n, s)) { return false; } } return true; } @Override public String toString () { String s = ""; for (Card c : deck) { s += c + "\n"; } return s; } public enum Suit {SPADE,HEART,CLUB,DIAMOND}; }
3e124e1b7cbb663a089393fabce8712bdf3d06e0
4,830
java
Java
component/src/main/java/io/siddhi/extension/execution/streamingml/bayesian/util/LinearRegression.java
niruhan/siddhi-execution-streamingml
ccb828b531ee98f97b7da7ebd01d92a8778752bb
[ "Apache-2.0" ]
1
2021-05-06T06:36:25.000Z
2021-05-06T06:36:25.000Z
component/src/main/java/io/siddhi/extension/execution/streamingml/bayesian/util/LinearRegression.java
niruhan/siddhi-execution-streamingml
ccb828b531ee98f97b7da7ebd01d92a8778752bb
[ "Apache-2.0" ]
null
null
null
component/src/main/java/io/siddhi/extension/execution/streamingml/bayesian/util/LinearRegression.java
niruhan/siddhi-execution-streamingml
ccb828b531ee98f97b7da7ebd01d92a8778752bb
[ "Apache-2.0" ]
null
null
null
36.315789
108
0.68323
7,711
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.siddhi.extension.execution.streamingml.bayesian.util; import io.siddhi.extension.execution.streamingml.bayesian.model.NormalDistribution; import org.apache.log4j.Logger; import org.nd4j.autodiff.samediff.SDVariable; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import java.util.Arrays; /** * implements Bayesian Linear regression model. * <p> * minimize the negative ELBO * ELBO = E[log(P(yIn|xIn,weights)] - D_KL[weights,prior] */ public class LinearRegression extends BayesianModel { private static final Logger logger = Logger.getLogger(LinearRegression.class.getName()); private static final long serialVersionUID = -5112177245729410690L; private NormalDistribution weights; private SDVariable likelihoodScale; private SDVariable loss; public LinearRegression() { super(); } public LinearRegression(LinearRegression model) { super(model); // likelihoodScale = model.likelihoodScale; } @Override SDVariable[] specifyModel() { // initiateModel placeholders this.xIn = sd.var("xIn", 1, numFeatures); this.yIn = sd.var("yIn", 1); // initiateModel trainable variables SDVariable weightLocVar, weightScaleVar, likelihoodScaleVar; weightLocVar = sd.var("wLocVar", numFeatures, 1); weightScaleVar = sd.var("wScaleVar", numFeatures, 1); // softplus ensures non-zero scale likelihoodScaleVar = sd.var("likScaleVar", 1, 1); likelihoodScale = sd.softplus(likelihoodScaleVar); // construct the variational distribution for weights weights = new NormalDistribution(weightLocVar, sd.softplus(weightScaleVar), sd); // construct the prior distribution for weigths // NormalDistribution prior = new NormalDistribution(sd.var(Nd4j.ones(numFeatures, 1).mul(priorLoc)), // sd.var(Nd4j.ones(numFeatures, 1).mul(priorScale)), sd); // computing the log-likelihood loss SDVariable[] logpArr = new SDVariable[numSamples]; for (int i = 0; i < numSamples; i++) { SDVariable mu = xIn.mmul(weights.sample()); // linear regression NormalDistribution likelihood = new NormalDistribution(mu, likelihoodScale, sd); logpArr[i] = likelihood.logProbability(yIn); } SDVariable logpLoss = sd.neg(sd.mergeAvg(logpArr)); loss = logpLoss; return new SDVariable[]{weightLocVar, weightScaleVar, likelihoodScaleVar}; // try { // SDVariable klLoss = weights.klDivergence(prior); // loss = logpLoss.add(klLoss); // } catch (SiddhiAppCreationException e) { // loss = logpLoss; // } // setting the updaters } @Override double predictionFromPredictiveDensity(INDArray predictiveDistribution) { return predictiveDistribution.mean(1).toDoubleVector()[0]; } @Override double confidenceFromPredictiveDensity(INDArray predictiveDistribution) { return 1 / (predictiveDistribution.std(1).toDoubleVector()[0]); } @Override protected double[][] getUpdatedWeights() { logger.debug(Arrays.toString(weights.getLoc().getArr().toDoubleVector())); return new double[][]{weights.getLoc().getArr().toDoubleVector(), weights.getScale().getArr().toDoubleVector()}; } @Override public double evaluate(double[] features, Object expected) { return 0; } @Override INDArray estimatePredictiveDistribution(INDArray features, int nSamples) { INDArray loc, scale, scalePrediction; loc = this.weights.getLoc().getArr(); scale = this.weights.getScale().getArr(); scalePrediction = this.likelihoodScale.getArr(); INDArray zSamples = Nd4j.randn(new long[]{numFeatures, nSamples}); INDArray samplesLik = Nd4j.randn(new long[]{1, nSamples}); INDArray weights = zSamples.mulColumnVector(scale).addColumnVector(loc); INDArray locPrediction = features.mmul(weights); return locPrediction.add(samplesLik.mul(scalePrediction)); } }
3e124e3746152cf6ba76ab4d2e82ffff4085f8f6
2,247
java
Java
src/main/java/io/choerodon/devops/api/controller/v1/GitlabWebHookController.java
yifanyou/devops-service
795dae08ef6191d8ed0de75587404d3da61cee5b
[ "Apache-2.0" ]
null
null
null
src/main/java/io/choerodon/devops/api/controller/v1/GitlabWebHookController.java
yifanyou/devops-service
795dae08ef6191d8ed0de75587404d3da61cee5b
[ "Apache-2.0" ]
null
null
null
src/main/java/io/choerodon/devops/api/controller/v1/GitlabWebHookController.java
yifanyou/devops-service
795dae08ef6191d8ed0de75587404d3da61cee5b
[ "Apache-2.0" ]
null
null
null
37.45
113
0.759235
7,712
package io.choerodon.devops.api.controller.v1; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Map; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import io.choerodon.core.iam.InitRoleCode; import io.choerodon.core.iam.ResourceLevel; import io.choerodon.devops.app.service.ApplicationInstanceService; import io.choerodon.devops.app.service.GitlabWebHookService; import io.choerodon.swagger.annotation.Permission; @RestController @RequestMapping(value = "/webhook") public class GitlabWebHookController { @Autowired private GitlabWebHookService gitlabWebHookService; @Autowired private ApplicationInstanceService applicationInstanceService; @Permission(permissionPublic = true) @ApiOperation(value = "webhook转发") @PostMapping public ResponseEntity forwardGitlabWebHook(HttpServletRequest httpServletRequest, @RequestBody String body) { gitlabWebHookService.forwardingEventToPortal(body, httpServletRequest.getHeader("X-Gitlab-Token")); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Permission(permissionPublic = true) @ApiOperation(value = "gitops webhook转发") @PostMapping(value = "/git_ops") public ResponseEntity gitOpsWebHook(HttpServletRequest httpServletRequest, @RequestBody String body) { gitlabWebHookService.gitOpsWebHook(body, httpServletRequest.getHeader("X-Gitlab-Token")); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } /** * 查询自动化测试应用实例状态 * @param testReleases */ @ApiOperation(value = "查询自动化测试应用实例状态") @Permission(level = ResourceLevel.PROJECT, roles = {InitRoleCode.PROJECT_OWNER, InitRoleCode.PROJECT_MEMBER}) @PostMapping("/get_test_status") public void getTestStatus( @ApiParam(value = "releaseName", required = true) @RequestBody Map<Long, List<String>> testReleases) { applicationInstanceService.getTestAppStatus(testReleases); } }
3e124e6e125407350cea8bcd9b9ab0ec194bfb25
480
java
Java
src/main/java/cn/liuawen/pojo/OrderItem.java
liuawen/pinduoduo
0c4c58fe341003c76b2452136655fe7b0b87fa9c
[ "Apache-2.0" ]
1
2020-06-03T11:31:15.000Z
2020-06-03T11:31:15.000Z
src/main/java/cn/liuawen/pojo/OrderItem.java
liuawen/pindongdong
0c4c58fe341003c76b2452136655fe7b0b87fa9c
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/liuawen/pojo/OrderItem.java
liuawen/pindongdong
0c4c58fe341003c76b2452136655fe7b0b87fa9c
[ "Apache-2.0" ]
null
null
null
15.483871
40
0.733333
7,713
package cn.liuawen.pojo; import lombok.Data; import java.math.BigDecimal; import java.util.Date; @Data public class OrderItem { private Integer id; private Integer userId; private Long orderNo; private Integer productId; private String productName; private String productImage; private BigDecimal currentUnitPrice; private Integer quantity; private BigDecimal totalPrice; private Date createTime; private Date updateTime; }
3e124f6a1054776947ef04b1fa512fb99d5ae2bb
865
java
Java
bpm-engine-impl/src/main/java/io/takari/bpm/form/InMemFormStorage.java
muhammad-wasi-confiz/bpm
c2bf50a6bf7eb09791196cfa0e64d5d304ba4acc
[ "Apache-2.0" ]
3
2021-04-22T13:17:15.000Z
2022-02-24T17:40:56.000Z
bpm-engine-impl/src/main/java/io/takari/bpm/form/InMemFormStorage.java
muhammad-wasi-confiz/bpm
c2bf50a6bf7eb09791196cfa0e64d5d304ba4acc
[ "Apache-2.0" ]
4
2020-04-23T20:04:06.000Z
2021-12-09T21:47:22.000Z
bpm-engine-impl/src/main/java/io/takari/bpm/form/InMemFormStorage.java
muhammad-wasi-confiz/bpm
c2bf50a6bf7eb09791196cfa0e64d5d304ba4acc
[ "Apache-2.0" ]
null
null
null
22.763158
73
0.647399
7,714
package io.takari.bpm.form; import io.takari.bpm.api.ExecutionException; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class InMemFormStorage implements FormStorage { private final Map<UUID, Form> forms = new HashMap<>(); @Override public void save(Form form) throws ExecutionException { synchronized (forms) { forms.put(form.getFormInstanceId(), form); } } @Override public void complete(UUID formInstanceId) throws ExecutionException { synchronized (forms) { forms.remove(formInstanceId); } } @Override public Form get(UUID formInstanceId) throws ExecutionException { synchronized (forms) { return forms.get(formInstanceId); } } public Map<UUID, Form> getForms() { return forms; } }
3e124fbd20d20080c5e39a8e1f464734e7fe76eb
2,349
java
Java
plugins/eCommerce/src/main/java/com/skytala/eCommerce/domain/order/relations/orderShipment/query/FindOrderShipmentsBy.java
ArcticReal/eCommerce
ea4c82442acdc9e663571e2d07e1f1ddc844f135
[ "Apache-2.0" ]
1
2020-09-28T08:23:11.000Z
2020-09-28T08:23:11.000Z
plugins/eCommerce/src/main/java/com/skytala/eCommerce/domain/order/relations/orderShipment/query/FindOrderShipmentsBy.java
ArcticReal/eCommerce
ea4c82442acdc9e663571e2d07e1f1ddc844f135
[ "Apache-2.0" ]
null
null
null
plugins/eCommerce/src/main/java/com/skytala/eCommerce/domain/order/relations/orderShipment/query/FindOrderShipmentsBy.java
ArcticReal/eCommerce
ea4c82442acdc9e663571e2d07e1f1ddc844f135
[ "Apache-2.0" ]
null
null
null
27.635294
93
0.783738
7,715
package com.skytala.eCommerce.domain.order.relations.orderShipment.query; import java.util.ArrayList; import java.util.List; import java.util.Iterator; import java.util.Map; import java.util.LinkedList; import org.apache.ofbiz.entity.Delegator; import org.apache.ofbiz.entity.DelegatorFactory; import org.apache.ofbiz.entity.GenericEntityException; import org.apache.ofbiz.entity.GenericValue; import com.skytala.eCommerce.framework.pubsub.Broker; import com.skytala.eCommerce.framework.pubsub.Query; import com.skytala.eCommerce.framework.pubsub.Event; import com.skytala.eCommerce.framework.exceptions.RecordNotFoundException; import com.skytala.eCommerce.domain.order.relations.orderShipment.event.OrderShipmentFound; import com.skytala.eCommerce.domain.order.relations.orderShipment.mapper.OrderShipmentMapper; import com.skytala.eCommerce.domain.order.relations.orderShipment.model.OrderShipment; public class FindOrderShipmentsBy extends Query { Map<String, String> filter; public FindOrderShipmentsBy(Map<String, String> filter) { this.filter = filter; } @Override public Event execute(){ Delegator delegator = DelegatorFactory.getDelegator("default"); List<OrderShipment> foundOrderShipments = new ArrayList<OrderShipment>(); try{ List<GenericValue> buf = new LinkedList<>(); if(filter.size()==1&&filter.containsKey("orderShipmentId")) { GenericValue foundElement = delegator.findOne("OrderShipment", false, filter); if(foundElement != null) { buf.add(foundElement); }else { throw new RecordNotFoundException(OrderShipment.class); } }else { buf = delegator.findAll("OrderShipment", false); } for (int i = 0; i < buf.size(); i++) { if(applysToFilter(buf.get(i))) { foundOrderShipments.add(OrderShipmentMapper.map(buf.get(i))); } } }catch(GenericEntityException e) { e.printStackTrace(); } Event resultingEvent = new OrderShipmentFound(foundOrderShipments); Broker.instance().publish(resultingEvent); return resultingEvent; } public boolean applysToFilter(GenericValue val) { Iterator<String> iterator = filter.keySet().iterator(); while(iterator.hasNext()) { String key = iterator.next(); if(val.get(key) == null) { return false; } if((val.get(key).toString()).contains(filter.get(key))) { }else { return false; } } return true; } public void setFilter(Map<String, String> newFilter) { this.filter = newFilter; } }
3e12500a3d931bbbbf3dd8a5402006361d2624d5
9,374
java
Java
cnd/cnd.makeproject.ui/src/org/netbeans/modules/cnd/makeproject/ui/wizards/SourceFoldersPanel.java
leginee/netbeans
814ad30e2d0a094f4aa3813bcbb5323a95a0b1d6
[ "Apache-2.0" ]
null
null
null
cnd/cnd.makeproject.ui/src/org/netbeans/modules/cnd/makeproject/ui/wizards/SourceFoldersPanel.java
leginee/netbeans
814ad30e2d0a094f4aa3813bcbb5323a95a0b1d6
[ "Apache-2.0" ]
null
null
null
cnd/cnd.makeproject.ui/src/org/netbeans/modules/cnd/makeproject/ui/wizards/SourceFoldersPanel.java
leginee/netbeans
814ad30e2d0a094f4aa3813bcbb5323a95a0b1d6
[ "Apache-2.0" ]
null
null
null
51.224044
175
0.743119
7,716
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.cnd.makeproject.ui.wizards; import org.netbeans.modules.cnd.makeproject.api.ui.wizard.WizardConstants; import java.util.ArrayList; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.netbeans.modules.cnd.makeproject.api.MakeProjectOptions; import org.netbeans.modules.cnd.makeproject.api.configurations.MakeConfigurationDescriptor; import org.netbeans.modules.cnd.utils.FSPath; import org.openide.WizardDescriptor; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; /*package*/ final class SourceFoldersPanel extends javax.swing.JPanel implements HelpCtx.Provider { private final SourceFoldersDescriptorPanel controller; private final SourceFilesPanel sourceFilesPanel; private boolean firstTime = true; public SourceFoldersPanel(SourceFoldersDescriptorPanel controller) { initComponents(); this.controller = controller; sourceFilesPanel = new SourceFilesPanel(controller); java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; headerFoldersOuterPanel.add(sourceFilesPanel, gridBagConstraints); instructionsTextArea.setBackground(instructionPanel.getBackground()); getAccessibleContext().setAccessibleDescription(getString("SourceFoldersPanel_AD")); } @Override public HelpCtx getHelpCtx() { return new HelpCtx(SourceFoldersPanel.class); } void read(WizardDescriptor settings) { if (firstTime) { FSPath wd = WizardConstants.PROPERTY_PROJECT_FOLDER.get(settings); //sourceFilesPanel.setSeed(workingdir, workingdir); sourceFilesPanel.getSourceListData().add(new FolderEntry(wd, wd.getPath())); sourceFilesPanel.setFoldersFilter(MakeConfigurationDescriptor.DEFAULT_IGNORE_FOLDERS_PATTERN_EXISTING_PROJECT); sourceFilesPanel.setResolveSymLinks(MakeProjectOptions.getResolveSymbolicLinks()); firstTime = false; } } void store(WizardDescriptor wizardDescriptor) { WizardConstants.PROPERTY_SOURCE_FOLDERS.put(wizardDescriptor, sourceFilesPanel.getSourceListData().iterator()); // NOI18N WizardConstants.PROPERTY_SOURCE_FOLDERS_LIST.put(wizardDescriptor, new ArrayList<>(sourceFilesPanel.getSourceListData())); // NOI18N if (sourceFilesPanel.getFoldersFilter().trim().length() == 0) { // change empty pattern on "no ignore folder pattern" WizardConstants.PROPERTY_SOURCE_FOLDERS_FILTER.put(wizardDescriptor, MakeConfigurationDescriptor.DEFAULT_NO_IGNORE_FOLDERS_PATTERN); // NOI18N } else { WizardConstants.PROPERTY_SOURCE_FOLDERS_FILTER.put(wizardDescriptor, sourceFilesPanel.getFoldersFilter()); // NOI18N } WizardConstants.PROPERTY_RESOLVE_SYM_LINKS.put(wizardDescriptor, sourceFilesPanel.getResolveSymLinks()); WizardConstants.PROPERTY_TEST_FOLDERS.put(wizardDescriptor, sourceFilesPanel.getTestListData().iterator()); // NOI18N WizardConstants.PROPERTY_TEST_FOLDERS_LIST.put(wizardDescriptor, new ArrayList<>(sourceFilesPanel.getTestListData())); // NOI18N } boolean valid(WizardDescriptor settings) { String regex = sourceFilesPanel.getFoldersFilter(); try { Pattern.compile(regex); } catch (PatternSyntaxException e) { settings.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, e.getMessage()); return false; } return true; } /** * This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; headerFoldersOuterPanel = new javax.swing.JPanel(); instructionPanel = new javax.swing.JPanel(); instructionsTextArea = new javax.swing.JTextArea(); setPreferredSize(new java.awt.Dimension(450, 350)); setLayout(new java.awt.GridBagLayout()); headerFoldersOuterPanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(headerFoldersOuterPanel, gridBagConstraints); instructionPanel.setLayout(new java.awt.GridBagLayout()); instructionsTextArea.setEditable(false); instructionsTextArea.setLineWrap(true); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/netbeans/modules/cnd/makeproject/ui/wizards/Bundle"); // NOI18N instructionsTextArea.setText(bundle.getString("SourceFilesInstructions")); // NOI18N instructionsTextArea.setWrapStyleWord(true); instructionsTextArea.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; instructionPanel.add(instructionsTextArea, gridBagConstraints); instructionsTextArea.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(SourceFoldersPanel.class, "SourceFoldersInfo_AN")); // NOI18N instructionsTextArea.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(SourceFoldersPanel.class, "SourceFoldersInfo_AD")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(24, 0, 0, 0); add(instructionPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel headerFoldersOuterPanel; private javax.swing.JPanel instructionPanel; private javax.swing.JTextArea instructionsTextArea; // End of variables declaration//GEN-END:variables private static String getString(String s) { return NbBundle.getMessage(PanelProjectLocationVisual.class, s); } }
3e125044d079b66bac4a35831c7a232dcb7bf42c
13,315
java
Java
projects/OG-Component/src/main/java/com/opengamma/component/factory/master/CombinedSecurityMasterComponentFactory.java
UbuntuEvangelist/OG-Platform
0aac9675ff92fd702d2e53a991de085388bfdc83
[ "Apache-2.0" ]
12
2017-03-10T13:56:52.000Z
2021-10-03T01:21:20.000Z
projects/OG-Component/src/main/java/com/opengamma/component/factory/master/CombinedSecurityMasterComponentFactory.java
UbuntuEvangelist/OG-Platform
0aac9675ff92fd702d2e53a991de085388bfdc83
[ "Apache-2.0" ]
1
2021-08-02T17:20:43.000Z
2021-08-02T17:20:43.000Z
projects/OG-Component/src/main/java/com/opengamma/component/factory/master/CombinedSecurityMasterComponentFactory.java
UbuntuEvangelist/OG-Platform
0aac9675ff92fd702d2e53a991de085388bfdc83
[ "Apache-2.0" ]
16
2017-01-12T10:31:58.000Z
2019-04-19T08:17:33.000Z
35.986486
137
0.674352
7,717
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.component.factory.master; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import org.joda.beans.Bean; import org.joda.beans.BeanBuilder; import org.joda.beans.BeanDefinition; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaProperty; import org.joda.beans.Property; import org.joda.beans.PropertyDefinition; import org.joda.beans.impl.direct.DirectBeanBuilder; import org.joda.beans.impl.direct.DirectMetaProperty; import org.joda.beans.impl.direct.DirectMetaPropertyMap; import com.opengamma.component.ComponentInfo; import com.opengamma.component.ComponentRepository; import com.opengamma.component.factory.AbstractComponentFactory; import com.opengamma.component.factory.ComponentInfoAttributes; import com.opengamma.master.security.SecurityMaster; import com.opengamma.master.security.impl.DataSecurityMasterResource; import com.opengamma.master.security.impl.DelegatingSecurityMaster; import com.opengamma.master.security.impl.RemoteSecurityMaster; /** * Component factory for the combined security master. * <p> * The delegate security masters are specify by securityMaster<index> = SecurityMaster::<classifier> in the .ini config file */ @BeanDefinition public class CombinedSecurityMasterComponentFactory extends AbstractComponentFactory { /** * The classifier that the factory should publish under. */ @PropertyDefinition(validate = "notNull") private String _classifier; /** * The flag determining whether the component should be published by REST (default true). */ @PropertyDefinition private boolean _publishRest = true; /** * The default security master. */ @PropertyDefinition(validate = "notNull") private SecurityMaster _defaultSecurityMaster; //------------------------------------------------------------------------- @Override public void init(ComponentRepository repo, LinkedHashMap<String, String> configuration) { Map<String, SecurityMaster> map = new HashMap<>(); final String defaultSecurityScheme = repo.getInfo(getDefaultSecurityMaster()).getAttribute(ComponentInfoAttributes.UNIQUE_ID_SCHEME); map.put(defaultSecurityScheme, getDefaultSecurityMaster()); // all additional PositionMaster instances Map<String, ComponentInfo> infos = repo.findInfos(configuration); for (Entry<String, ComponentInfo> entry : infos.entrySet()) { String key = entry.getKey(); ComponentInfo info = entry.getValue(); if (key.matches("securityMaster[0-9]+") && info.getType() == SecurityMaster.class) { SecurityMaster securityMaster = (SecurityMaster) repo.getInstance(info); String uniqueIdScheme = repo.getInfo(securityMaster).getAttribute(ComponentInfoAttributes.UNIQUE_ID_SCHEME); map.put(uniqueIdScheme, securityMaster); configuration.remove(key); } } SecurityMaster master = new DelegatingSecurityMaster(getDefaultSecurityMaster(), map); // register ComponentInfo info = new ComponentInfo(SecurityMaster.class, getClassifier()); info.addAttribute(ComponentInfoAttributes.LEVEL, 2); info.addAttribute(ComponentInfoAttributes.REMOTE_CLIENT_JAVA, RemoteSecurityMaster.class); repo.registerComponent(info, master); if (isPublishRest()) { repo.getRestComponents().publish(info, new DataSecurityMasterResource(master)); } } //------------------------- AUTOGENERATED START ------------------------- ///CLOVER:OFF /** * The meta-bean for {@code CombinedSecurityMasterComponentFactory}. * @return the meta-bean, not null */ public static CombinedSecurityMasterComponentFactory.Meta meta() { return CombinedSecurityMasterComponentFactory.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(CombinedSecurityMasterComponentFactory.Meta.INSTANCE); } @Override public CombinedSecurityMasterComponentFactory.Meta metaBean() { return CombinedSecurityMasterComponentFactory.Meta.INSTANCE; } //----------------------------------------------------------------------- /** * Gets the classifier that the factory should publish under. * @return the value of the property, not null */ public String getClassifier() { return _classifier; } /** * Sets the classifier that the factory should publish under. * @param classifier the new value of the property, not null */ public void setClassifier(String classifier) { JodaBeanUtils.notNull(classifier, "classifier"); this._classifier = classifier; } /** * Gets the the {@code classifier} property. * @return the property, not null */ public final Property<String> classifier() { return metaBean().classifier().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the flag determining whether the component should be published by REST (default true). * @return the value of the property */ public boolean isPublishRest() { return _publishRest; } /** * Sets the flag determining whether the component should be published by REST (default true). * @param publishRest the new value of the property */ public void setPublishRest(boolean publishRest) { this._publishRest = publishRest; } /** * Gets the the {@code publishRest} property. * @return the property, not null */ public final Property<Boolean> publishRest() { return metaBean().publishRest().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the default security master. * @return the value of the property, not null */ public SecurityMaster getDefaultSecurityMaster() { return _defaultSecurityMaster; } /** * Sets the default security master. * @param defaultSecurityMaster the new value of the property, not null */ public void setDefaultSecurityMaster(SecurityMaster defaultSecurityMaster) { JodaBeanUtils.notNull(defaultSecurityMaster, "defaultSecurityMaster"); this._defaultSecurityMaster = defaultSecurityMaster; } /** * Gets the the {@code defaultSecurityMaster} property. * @return the property, not null */ public final Property<SecurityMaster> defaultSecurityMaster() { return metaBean().defaultSecurityMaster().createProperty(this); } //----------------------------------------------------------------------- @Override public CombinedSecurityMasterComponentFactory clone() { return JodaBeanUtils.cloneAlways(this); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { CombinedSecurityMasterComponentFactory other = (CombinedSecurityMasterComponentFactory) obj; return JodaBeanUtils.equal(getClassifier(), other.getClassifier()) && (isPublishRest() == other.isPublishRest()) && JodaBeanUtils.equal(getDefaultSecurityMaster(), other.getDefaultSecurityMaster()) && super.equals(obj); } return false; } @Override public int hashCode() { int hash = 7; hash = hash * 31 + JodaBeanUtils.hashCode(getClassifier()); hash = hash * 31 + JodaBeanUtils.hashCode(isPublishRest()); hash = hash * 31 + JodaBeanUtils.hashCode(getDefaultSecurityMaster()); return hash ^ super.hashCode(); } @Override public String toString() { StringBuilder buf = new StringBuilder(128); buf.append("CombinedSecurityMasterComponentFactory{"); int len = buf.length(); toString(buf); if (buf.length() > len) { buf.setLength(buf.length() - 2); } buf.append('}'); return buf.toString(); } @Override protected void toString(StringBuilder buf) { super.toString(buf); buf.append("classifier").append('=').append(JodaBeanUtils.toString(getClassifier())).append(',').append(' '); buf.append("publishRest").append('=').append(JodaBeanUtils.toString(isPublishRest())).append(',').append(' '); buf.append("defaultSecurityMaster").append('=').append(JodaBeanUtils.toString(getDefaultSecurityMaster())).append(',').append(' '); } //----------------------------------------------------------------------- /** * The meta-bean for {@code CombinedSecurityMasterComponentFactory}. */ public static class Meta extends AbstractComponentFactory.Meta { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code classifier} property. */ private final MetaProperty<String> _classifier = DirectMetaProperty.ofReadWrite( this, "classifier", CombinedSecurityMasterComponentFactory.class, String.class); /** * The meta-property for the {@code publishRest} property. */ private final MetaProperty<Boolean> _publishRest = DirectMetaProperty.ofReadWrite( this, "publishRest", CombinedSecurityMasterComponentFactory.class, Boolean.TYPE); /** * The meta-property for the {@code defaultSecurityMaster} property. */ private final MetaProperty<SecurityMaster> _defaultSecurityMaster = DirectMetaProperty.ofReadWrite( this, "defaultSecurityMaster", CombinedSecurityMasterComponentFactory.class, SecurityMaster.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap( this, (DirectMetaPropertyMap) super.metaPropertyMap(), "classifier", "publishRest", "defaultSecurityMaster"); /** * Restricted constructor. */ protected Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case -281470431: // classifier return _classifier; case -614707837: // publishRest return _publishRest; case 163592803: // defaultSecurityMaster return _defaultSecurityMaster; } return super.metaPropertyGet(propertyName); } @Override public BeanBuilder<? extends CombinedSecurityMasterComponentFactory> builder() { return new DirectBeanBuilder<CombinedSecurityMasterComponentFactory>(new CombinedSecurityMasterComponentFactory()); } @Override public Class<? extends CombinedSecurityMasterComponentFactory> beanType() { return CombinedSecurityMasterComponentFactory.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return _metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code classifier} property. * @return the meta-property, not null */ public final MetaProperty<String> classifier() { return _classifier; } /** * The meta-property for the {@code publishRest} property. * @return the meta-property, not null */ public final MetaProperty<Boolean> publishRest() { return _publishRest; } /** * The meta-property for the {@code defaultSecurityMaster} property. * @return the meta-property, not null */ public final MetaProperty<SecurityMaster> defaultSecurityMaster() { return _defaultSecurityMaster; } //----------------------------------------------------------------------- @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case -281470431: // classifier return ((CombinedSecurityMasterComponentFactory) bean).getClassifier(); case -614707837: // publishRest return ((CombinedSecurityMasterComponentFactory) bean).isPublishRest(); case 163592803: // defaultSecurityMaster return ((CombinedSecurityMasterComponentFactory) bean).getDefaultSecurityMaster(); } return super.propertyGet(bean, propertyName, quiet); } @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { switch (propertyName.hashCode()) { case -281470431: // classifier ((CombinedSecurityMasterComponentFactory) bean).setClassifier((String) newValue); return; case -614707837: // publishRest ((CombinedSecurityMasterComponentFactory) bean).setPublishRest((Boolean) newValue); return; case 163592803: // defaultSecurityMaster ((CombinedSecurityMasterComponentFactory) bean).setDefaultSecurityMaster((SecurityMaster) newValue); return; } super.propertySet(bean, propertyName, newValue, quiet); } @Override protected void validate(Bean bean) { JodaBeanUtils.notNull(((CombinedSecurityMasterComponentFactory) bean)._classifier, "classifier"); JodaBeanUtils.notNull(((CombinedSecurityMasterComponentFactory) bean)._defaultSecurityMaster, "defaultSecurityMaster"); super.validate(bean); } } ///CLOVER:ON //-------------------------- AUTOGENERATED END -------------------------- }
3e125116634eb1b43fdbfa63e916beac85995b9d
8,779
java
Java
src/com/tehelee/jumpPads/JumpPad.java
Tehelee/Spigot-JumpPads
92f76e84ed2cb4016a13707ef8e1869591bca51c
[ "MIT" ]
null
null
null
src/com/tehelee/jumpPads/JumpPad.java
Tehelee/Spigot-JumpPads
92f76e84ed2cb4016a13707ef8e1869591bca51c
[ "MIT" ]
null
null
null
src/com/tehelee/jumpPads/JumpPad.java
Tehelee/Spigot-JumpPads
92f76e84ed2cb4016a13707ef8e1869591bca51c
[ "MIT" ]
null
null
null
23.410667
129
0.667502
7,718
package com.tehelee.jumpPads; import java.io.File; import java.io.IOException; import java.util.Hashtable; import java.util.UUID; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.World; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; public class JumpPad { private static ConfigurationSection defaults; private static Hashtable<String,JumpPad> register = new Hashtable<String,JumpPad>(); public static void writeDefaultConfig() { if (!Main.config.isConfigurationSection("Defaults")) { defaults = Main.config.createSection("Defaults"); defaults.set("JumpHeight", 10.0); defaults.set("JumpLength", 7.0); defaults.set("JumpDuration", 1); defaults.set("Sound", "ENTITY_GHAST_SHOOT"); defaults.set("Effect", "SMOKE"); } else { defaults = Main.config.getConfigurationSection("Defaults"); } } public static void populateRegister() { File file = new File(Main.instance.getDataFolder(), "//" + "jump_pads.yml"); FileConfiguration yaml = YamlConfiguration.loadConfiguration(file); for (String compressedLocation : yaml.getKeys(false)) { ConfigurationSection config; String id = compressedLocation; if (yaml.isConfigurationSection(id)) config = yaml.getConfigurationSection(id); else continue; if (register.containsKey(compressedLocation)) continue; Location loc = extractLocation(config.getString("Location")); if ((loc == null) || (loc.getWorld() == null)) continue; JumpPad pad = new JumpPad(loc); pad.setHeight(config.getDouble("JumpHeight")); pad.setLength(config.getDouble("JumpLength")); pad.setDuration(config.getInt("JumpDuration")); pad.setSound(config.getString("Sound")); pad.setEffect(config.getString("Effect")); pad.setForceDirection(config.getString("ForceDirection")); register.put(compressedLocation, pad); } } public static String compressLocation(Location loc) { return String.format("%1$s %2$.0f %3$.0f %4$.0f", loc.getWorld().getUID().toString(), loc.getX(), loc.getY(), loc.getZ()); } public static Location extractLocation(String str) { String[] split = str.split(" "); if (split.length != 4) return null; World world = Main.server.getWorld(UUID.fromString(split[0])); if (world == null) return null; Location loc = new Location(world, Double.parseDouble(split[1]), Double.parseDouble(split[2]), Double.parseDouble(split[3])); return loc; } public static Location getBlockLocation(Location original) { return new Location(original.getWorld(), original.getBlockX(), original.getBlockY(), original.getBlockZ()); } public static JumpPad createJumpPad(Location loc) { JumpPad existing = null; Location blockLoc = getBlockLocation(loc); String compressed = compressLocation(blockLoc); if (register.containsKey(compressed)) existing = register.get(compressed); JumpPad pad = (existing != null) ? existing : new JumpPad(blockLoc); pad.save(); register.put(compressed, pad); return pad; } public static void removeJumpPad(JumpPad pad) { if (register.containsKey(pad.compressedLocation)) { register.remove(pad.compressedLocation); File file = new File(Main.instance.getDataFolder(), "//" + "jump_pads.yml"); FileConfiguration yaml = YamlConfiguration.loadConfiguration(file); yaml.set(pad.compressedLocation, null); try { yaml.save(file); } catch (IOException e) { Main.message(null, "Failed to remove jump pad @: " + pad.compressedLocation); } } } public static JumpPad getJumpPad(Location loc) { String compressedLocation = compressLocation(getBlockLocation(loc)); return register.containsKey(compressedLocation) ? register.get(compressedLocation) : null; } public static boolean isPressurePlate(Material m) { switch(m) { case WOOD_PLATE: case STONE_PLATE: case IRON_PLATE: case GOLD_PLATE: return true; default: return false; } } private double height, length; private int duration; private Sound sound; private Effect effect; private ForceDirection forceDirection = ForceDirection.NONE; private Location location; private String compressedLocation; public JumpPad(Location location) { height = defaults.getDouble("JumpHeight"); length = defaults.getDouble("JumpLength"); duration = defaults.getInt("JumpDuration"); setSound(defaults.getString("Sound")); setEffect(defaults.getString("Effect")); this.location = location; compressedLocation = compressLocation(location); } public JumpPad(String compressedLocation) { height = defaults.getDouble("JumpHeight"); length = defaults.getDouble("JumpLength"); duration = defaults.getInt("JumpDuration"); setSound(defaults.getString("Sound")); setEffect(defaults.getString("Effect")); location = extractLocation(compressedLocation); this.compressedLocation = compressedLocation; } public void clone(JumpPad master) { height = master.height; length = master.length; duration = master.duration; sound = master.sound; effect = master.effect; forceDirection = master.forceDirection; save(); } private void save() { File file = new File(Main.instance.getDataFolder(), "//" + "jump_pads.yml"); FileConfiguration yaml = YamlConfiguration.loadConfiguration(file); ConfigurationSection config; String id = compressedLocation; if (yaml.isConfigurationSection(id)) config = yaml.getConfigurationSection(id); else config = yaml.createSection(id); config.set("JumpHeight", height); config.set("JumpLength", length); config.set("JumpDuration", duration); config.set("Sound", (sound == null ? "NONE" : sound.toString())); config.set("Effect", (effect == null ? "NONE" : effect.toString())); config.set("ForceDirection", forceDirection.name()); config.set("Location", compressedLocation); try { yaml.save(file); } catch (IOException e) { Main.message(null, "Failed to save jump pad @: " + compressedLocation); } } public Location getLocation() { return this.location; } public String getCompressedLocation() { return this.compressedLocation; } public void setHeight(double height) { setHeight(height, false); } public void setHeight(double height, boolean save) { this.height = Math.min(20, Math.max(0, height)); if (save) this.save(); } public void setLength(double length) { setLength(length, false); } public void setLength(double length, boolean save) { this.length = Math.min(20, Math.max(0, length)); if (save) this.save(); } public void setDuration(int duration) { setDuration(duration, false); } public void setDuration(int duration, boolean save) { this.duration = duration; if (save) this.save(); } public void setSound(String sound) { setSound(sound, false); } public void setSound(String sound, boolean save) { if ((sound == null) || sound.isEmpty() || sound.equalsIgnoreCase("NONE")) { this.sound = null; } else { try { this.sound = Sound.valueOf(sound); } catch (IllegalArgumentException ex) { this.sound = null; } } if (save) this.save(); } public void setEffect(String effect) { setEffect(effect, false); } public void setEffect(String effect, boolean save) { if ((effect == null) || effect.isEmpty() || effect.equalsIgnoreCase("NONE")) { this.effect = null; } else { try { this.effect = Effect.valueOf(effect); } catch (IllegalArgumentException ex) { this.effect = null; } } } public void setForceDirection(String forceDirection) { setForceDirection(forceDirection, false); } public void setForceDirection(String forceDirection, boolean save) { this.forceDirection = ForceDirection.fromString(forceDirection); if (save) this.save(); } public double getHeight() { return height; } public double getLength() { return length; } public int getDuration() { return duration; } public Sound getSound() { return sound; } public Effect getEffect() { return effect; } public ForceDirection getForceDirection() { return forceDirection; } }
3e1251bc88db8aec1d6dbdf307ac4379e9fe0fb9
1,536
java
Java
src/main/java/dev/flashcards/server/deck/web/DeckController.java
DrBloke/flashcards-server
b642411b8a44bba09fbdc0de9e21affa5e815b5d
[ "MIT" ]
1
2020-11-30T11:04:15.000Z
2020-11-30T11:04:15.000Z
src/main/java/dev/flashcards/server/deck/web/DeckController.java
DrBloke/flashcards-server
b642411b8a44bba09fbdc0de9e21affa5e815b5d
[ "MIT" ]
2
2020-10-27T19:05:53.000Z
2020-11-29T22:25:40.000Z
src/main/java/dev/flashcards/server/deck/web/DeckController.java
DrBloke/flashcards-server
b642411b8a44bba09fbdc0de9e21affa5e815b5d
[ "MIT" ]
null
null
null
31.346939
72
0.700521
7,719
package dev.flashcards.server.deck.web; import dev.flashcards.server.deck.Deck; import dev.flashcards.server.deck.DeckBuilder; import dev.flashcards.server.deck.web.requests.DeckRequest; import dev.flashcards.server.deck.web.responses.DeckResponse; import dev.flashcards.server.deck.web.service.DeckService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import java.util.stream.Collectors; @RestController @RequestMapping("/api/deck") public class DeckController { private final DeckService service; private final DeckMapper deckMapper; @Autowired public DeckController(DeckService service, DeckMapper deckMapper) { this.service = service; this.deckMapper = deckMapper; } @PostMapping @ResponseStatus(HttpStatus.CREATED) public DeckResponse create(@RequestBody DeckRequest request) { var newDeck = deckMapper.fromRequest(request); return deckMapper.toResponse(service.save(newDeck)); } @GetMapping public Iterable<DeckResponse> findAll() { return service.findAll().stream() .map(d -> deckMapper.toResponse(d)) .collect(Collectors.toList()); } @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void delete(@PathVariable("id") Integer id) { var builder = new DeckBuilder(); service.delete(id); } }
3e1251f4562f15552824d63983012d160581165f
932
java
Java
argos-service-domain/src/main/java/com/rabobank/argos/service/domain/security/LocalPermissionCheckData.java
frankbezema/argos-parent
e9ce9d8fec7f6222014c7ae444c85ad74fe18226
[ "Apache-2.0" ]
3
2020-01-07T14:12:10.000Z
2020-01-10T16:52:53.000Z
argos-service-domain/src/main/java/com/rabobank/argos/service/domain/security/LocalPermissionCheckData.java
frankbezema/argos-parent
e9ce9d8fec7f6222014c7ae444c85ad74fe18226
[ "Apache-2.0" ]
2
2019-11-20T14:43:03.000Z
2019-12-11T11:48:07.000Z
argos-service-domain/src/main/java/com/rabobank/argos/service/domain/security/LocalPermissionCheckData.java
frankbezema/argos-parent
e9ce9d8fec7f6222014c7ae444c85ad74fe18226
[ "Apache-2.0" ]
2
2020-01-24T15:34:42.000Z
2021-07-16T03:48:39.000Z
28.242424
75
0.744635
7,720
/* * Copyright (C) 2019 - 2020 Rabobank Nederland * * 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.rabobank.argos.service.domain.security; import lombok.Builder; import lombok.Getter; import lombok.ToString; import java.util.HashSet; import java.util.Set; @Builder @Getter @ToString public class LocalPermissionCheckData { @Builder.Default private Set<String> labelIds = new HashSet<>(); }
3e1252bd9ca6e20eba4651b429b9c2ca1a3c1dbc
2,874
java
Java
proto-google-cloud-websecurityscanner-v1beta/src/main/java/com/google/cloud/websecurityscanner/v1beta/ListScanRunsResponseOrBuilder.java
suztomo/java-websecurityscanner
e9da745e695777873e06e8dac0b23abc44ae7b12
[ "Apache-2.0" ]
4
2020-09-19T12:37:13.000Z
2022-03-23T10:45:53.000Z
proto-google-cloud-websecurityscanner-v1beta/src/main/java/com/google/cloud/websecurityscanner/v1beta/ListScanRunsResponseOrBuilder.java
suztomo/java-websecurityscanner
e9da745e695777873e06e8dac0b23abc44ae7b12
[ "Apache-2.0" ]
481
2019-10-16T00:03:39.000Z
2022-03-29T18:25:44.000Z
proto-google-cloud-websecurityscanner-v1beta/src/main/java/com/google/cloud/websecurityscanner/v1beta/ListScanRunsResponseOrBuilder.java
suztomo/java-websecurityscanner
e9da745e695777873e06e8dac0b23abc44ae7b12
[ "Apache-2.0" ]
13
2019-10-18T16:09:13.000Z
2021-10-07T04:30:32.000Z
27.371429
110
0.679193
7,721
/* * 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 * * 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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/websecurityscanner/v1beta/web_security_scanner.proto package com.google.cloud.websecurityscanner.v1beta; public interface ListScanRunsResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.websecurityscanner.v1beta.ListScanRunsResponse) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * The list of ScanRuns returned. * </pre> * * <code>repeated .google.cloud.websecurityscanner.v1beta.ScanRun scan_runs = 1;</code> */ java.util.List<com.google.cloud.websecurityscanner.v1beta.ScanRun> getScanRunsList(); /** * * * <pre> * The list of ScanRuns returned. * </pre> * * <code>repeated .google.cloud.websecurityscanner.v1beta.ScanRun scan_runs = 1;</code> */ com.google.cloud.websecurityscanner.v1beta.ScanRun getScanRuns(int index); /** * * * <pre> * The list of ScanRuns returned. * </pre> * * <code>repeated .google.cloud.websecurityscanner.v1beta.ScanRun scan_runs = 1;</code> */ int getScanRunsCount(); /** * * * <pre> * The list of ScanRuns returned. * </pre> * * <code>repeated .google.cloud.websecurityscanner.v1beta.ScanRun scan_runs = 1;</code> */ java.util.List<? extends com.google.cloud.websecurityscanner.v1beta.ScanRunOrBuilder> getScanRunsOrBuilderList(); /** * * * <pre> * The list of ScanRuns returned. * </pre> * * <code>repeated .google.cloud.websecurityscanner.v1beta.ScanRun scan_runs = 1;</code> */ com.google.cloud.websecurityscanner.v1beta.ScanRunOrBuilder getScanRunsOrBuilder(int index); /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no * more results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ java.lang.String getNextPageToken(); /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no * more results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ com.google.protobuf.ByteString getNextPageTokenBytes(); }
3e1252c6ebf4edfa6db96402c4c5af1275093d28
7,835
java
Java
src/main/java/csdev/couponstash/model/coupon/savings/MonetaryAmount.java
ChesterSim/main
e48193328b699e6328df9302bbd8b327fd76be2a
[ "MIT" ]
null
null
null
src/main/java/csdev/couponstash/model/coupon/savings/MonetaryAmount.java
ChesterSim/main
e48193328b699e6328df9302bbd8b327fd76be2a
[ "MIT" ]
null
null
null
src/main/java/csdev/couponstash/model/coupon/savings/MonetaryAmount.java
ChesterSim/main
e48193328b699e6328df9302bbd8b327fd76be2a
[ "MIT" ]
null
null
null
37.132701
93
0.624633
7,722
package csdev.couponstash.model.coupon.savings; import static csdev.couponstash.commons.util.AppUtil.checkArgument; import java.util.Objects; /** * Represents a monetary amount that * can be saved by a coupon. * Immutable. */ public class MonetaryAmount implements Comparable<MonetaryAmount> { public static final String MESSAGE_CONSTRAINTS = "Invalid format for monetary amount! " + "Monetary amount should be positive, and accurate to at most 2 decimal places"; private final int integerAmount; private final int decimalAmount; /** * Constructs a MonetaryAmount, only if the integer amount * and decimal amount specified are valid. Integer amount * has to be a non-negative integer, and decimal amount can * only be from 0 to 99 (inclusive). * * @param integerAmount The integer amount which represents * whole units of currency (e.g. dollars, * pounds, euros). * @param decimalAmount The decimal amount which represents * decimal units of currency (e.g. cents, * pennies, centavos). */ public MonetaryAmount(int integerAmount, int decimalAmount) { checkArgument(MonetaryAmount.isValidMonetaryAmount(integerAmount, decimalAmount), MonetaryAmount.MESSAGE_CONSTRAINTS); this.integerAmount = integerAmount; this.decimalAmount = decimalAmount; } /** * Constructs a MonetaryAmount using a double argument. This * will convert the double into two integers, and round the * value if it is not exact to 2 decimal places. * * This is used by the storage component, as MonetaryAmounts * are stored as a double within the couponStash JSON file. * * @param monetaryAmount The double to be used. */ public MonetaryAmount(double monetaryAmount) { int intAmount = (int) Math.floor(monetaryAmount); // get rid of decimal int decAmount = ((int) Math.round(monetaryAmount * 100)) % 100; checkArgument(MonetaryAmount.isValidMonetaryAmount(intAmount, decAmount), MonetaryAmount.MESSAGE_CONSTRAINTS); this.integerAmount = intAmount; this.decimalAmount = decAmount; } /** * Constructs a MonetaryAmount using a String. This will * attempt to parse the integer amount and decimal amount * separately, and throw an error if this fails. * * @param monetaryAmount The String to be used. */ public MonetaryAmount(String monetaryAmount) { String[] intAndDecimalAmounts = monetaryAmount.split("\\."); if (intAndDecimalAmounts.length == 0 || intAndDecimalAmounts.length > 2 // throw exception if dot present with nothing after || monetaryAmount.endsWith(".")) { throw new IllegalArgumentException(MonetaryAmount.MESSAGE_CONSTRAINTS); } int intAmount; int decAmount; try { intAmount = Integer.parseInt(intAndDecimalAmounts[0]); if (intAndDecimalAmounts.length == 1) { decAmount = 0; } else if (intAndDecimalAmounts[1].length() == 1) { // add a zero, so that 8.3 means 8.30 instead of 8.03 decAmount = Integer.parseInt(intAndDecimalAmounts[1] + "0"); } else if (intAndDecimalAmounts[1].length() > 2) { // restrict monetary amounts to 1 or 2 decimal places throw new IllegalArgumentException(MonetaryAmount.MESSAGE_CONSTRAINTS); } else { decAmount = Integer.parseInt(intAndDecimalAmounts[1]); } } catch (NumberFormatException e) { throw new IllegalArgumentException(MonetaryAmount.MESSAGE_CONSTRAINTS); } checkArgument(MonetaryAmount.isValidMonetaryAmount(intAmount, decAmount), MonetaryAmount.MESSAGE_CONSTRAINTS); this.integerAmount = intAmount; this.decimalAmount = decAmount; } /** * Cloning constructor for an MonetaryAmount. * * @param ma The MonetaryAmount to be cloned. */ public MonetaryAmount(MonetaryAmount ma) { this.integerAmount = ma.integerAmount; this.decimalAmount = ma.decimalAmount; } /** * Gets the value of this MonetaryAmount * as a non-negative double that has only * 2 decimal places at most. * * @return Double representing MonetaryAmount. */ public double getValue() { if (this.decimalAmount < 10) { return Double.parseDouble(this.integerAmount + ".0" + this.decimalAmount); } else { return Double.parseDouble(this.integerAmount + "." + this.decimalAmount); } } /** * Checks if this double is suitable for use * in the MonetaryAmount (should be at most * 2 decimal places). * * @param integerAmount The integer amount which represents * whole units of currency (e.g. dollars, * pounds, euros). * @param decimalAmount The decimal amount which represents * decimal units of currency (e.g. cents, * pennies, centavos). */ public static boolean isValidMonetaryAmount(int integerAmount, int decimalAmount) { return integerAmount >= 0 && decimalAmount >= 0 && decimalAmount < 100; } /** * Adds this MonetaryAmount to another MonetaryAmount, * resulting in a new MonetaryAmount with value * greater than the original two. * * If this results in integer overflow, return this * monetary amount, unchanged. * * @param ma The other MonetaryAmount to add to. * @return Returns a new MonetaryAmount with * value that was obtained by adding both * original MonetaryAmounts. */ public MonetaryAmount add(MonetaryAmount ma) { int newIntAmount = this.integerAmount + ma.integerAmount; int newDecimalAmount = this.decimalAmount + ma.decimalAmount; // check for overflow if (newIntAmount < 0) { return this; } if (newDecimalAmount >= 100) { newIntAmount = newIntAmount + newDecimalAmount / 100; newDecimalAmount = newDecimalAmount % 100; } return new MonetaryAmount(newIntAmount, newDecimalAmount); } /** * Given a custom money symbol, represent this * MonetaryAmount as a String using that money * symbol (e.g. "$2.50", "£4.20"). * @param symbol String representing money symbol * to be used in the final String. * @return Returns a String that has the amount * set to 2 decimal places, and prefixed by * the given money symbol in String symbol. */ public String getStringWithMoneySymbol(String symbol) { return symbol + String.format("%.2f", this.getValue()); } @Override public int compareTo(MonetaryAmount m) { return (int) Math.signum(this.getValue() - m.getValue()); } @Override public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof MonetaryAmount) { MonetaryAmount ma = (MonetaryAmount) o; return this.integerAmount == ma.integerAmount && this.decimalAmount == ma.decimalAmount; } else { return false; } } @Override public int hashCode() { return Objects.hash(this.integerAmount, this.decimalAmount); } @Override public String toString() { // use $ as default symbol just to denote a monetary amount return this.getStringWithMoneySymbol("$"); } }
3e125331dd2ac594a325f11695e15fe60f231d74
9,336
java
Java
jigsaw/src/main/java/io/github/zekerzhayard/forgewrapper/installer/util/ModuleUtil.java
ZekerZhayard/ForgeWrapper
3ee6633a8536fdc72395536dd98b2b5e6363240e
[ "MIT" ]
52
2020-02-09T08:19:59.000Z
2022-02-13T17:23:00.000Z
jigsaw/src/main/java/io/github/zekerzhayard/forgewrapper/installer/util/ModuleUtil.java
ZekerZhayard/ForgeWrapper
3ee6633a8536fdc72395536dd98b2b5e6363240e
[ "MIT" ]
9
2020-03-20T01:18:20.000Z
2022-01-08T17:16:11.000Z
jigsaw/src/main/java/io/github/zekerzhayard/forgewrapper/installer/util/ModuleUtil.java
ZekerZhayard/ForgeWrapper
3ee6633a8536fdc72395536dd98b2b5e6363240e
[ "MIT" ]
11
2020-03-18T15:05:22.000Z
2021-12-20T16:47:40.000Z
56.240964
467
0.708119
7,723
package io.github.zekerzhayard.forgewrapper.installer.util; import java.io.File; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.module.Configuration; import java.lang.module.ModuleFinder; import java.lang.module.ModuleReference; import java.lang.module.ResolvedModule; import java.lang.reflect.Field; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import io.github.zekerzhayard.forgewrapper.util.CheckedLambdaUtil; import sun.misc.Unsafe; public class ModuleUtil { private final static MethodHandles.Lookup IMPL_LOOKUP = getImplLookup(); private static MethodHandles.Lookup getImplLookup() { try { // Get theUnsafe Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe"); unsafeField.setAccessible(true); Unsafe unsafe = (Unsafe) unsafeField.get(null); // Get IMPL_LOOKUP Field implLookupField = MethodHandles.Lookup.class.getDeclaredField("IMPL_LOOKUP"); return (MethodHandles.Lookup) unsafe.getObject(unsafe.staticFieldBase(implLookupField), unsafe.staticFieldOffset(implLookupField)); } catch (Throwable t) { throw new RuntimeException(t); } } /** * add module-path at runtime */ @SuppressWarnings("unchecked") public static void addModules(String modulePath) throws Throwable { // Find all extra modules, exclude all existing modules ModuleFinder finder = ModuleFinder.of(Stream.of(modulePath.split(File.pathSeparator)).map(Paths::get).filter(p -> ModuleFinder.of(p).findAll().stream().noneMatch(mref -> ModuleLayer.boot().findModule(mref.descriptor().name()).isPresent())).toArray(Path[]::new)); MethodHandle loadModuleMH = IMPL_LOOKUP.findVirtual(Class.forName("jdk.internal.loader.BuiltinClassLoader"), "loadModule", MethodType.methodType(void.class, ModuleReference.class)); // Resolve modules to a new config and load all extra modules in system class loader (unnamed modules for now) Configuration config = Configuration.resolveAndBind(finder, List.of(ModuleLayer.boot().configuration()), finder, finder.findAll().stream().filter(mref -> !ModuleLayer.boot().findModule(mref.descriptor().name()).isPresent()).peek(CheckedLambdaUtil.wrapConsumer(mref -> loadModuleMH.invokeWithArguments(ClassLoader.getSystemClassLoader(), mref))).map(mref -> mref.descriptor().name()).collect(Collectors.toList())); // Copy the new config graph to boot module layer config MethodHandle graphGetter = IMPL_LOOKUP.findGetter(Configuration.class, "graph", Map.class); HashMap<ResolvedModule, Set<ResolvedModule>> graphMap = new HashMap<>((Map<ResolvedModule, Set<ResolvedModule>>) graphGetter.invokeWithArguments(config)); MethodHandle cfSetter = IMPL_LOOKUP.findSetter(ResolvedModule.class, "cf", Configuration.class); // Reset all extra resolved modules config to boot module layer config graphMap.forEach(CheckedLambdaUtil.wrapBiConsumer((k, v) -> { cfSetter.invokeWithArguments(k, ModuleLayer.boot().configuration()); v.forEach(CheckedLambdaUtil.wrapConsumer(m -> cfSetter.invokeWithArguments(m, ModuleLayer.boot().configuration()))); })); graphMap.putAll((Map<ResolvedModule, Set<ResolvedModule>>) graphGetter.invokeWithArguments(ModuleLayer.boot().configuration())); IMPL_LOOKUP.findSetter(Configuration.class, "graph", Map.class).invokeWithArguments(ModuleLayer.boot().configuration(), new HashMap<>(graphMap)); // Reset boot module layer resolved modules as new config resolved modules to prepare define modules Set<ResolvedModule> oldBootModules = ModuleLayer.boot().configuration().modules(); MethodHandle modulesSetter = IMPL_LOOKUP.findSetter(Configuration.class, "modules", Set.class); HashSet<ResolvedModule> modulesSet = new HashSet<>(config.modules()); modulesSetter.invokeWithArguments(ModuleLayer.boot().configuration(), new HashSet<>(modulesSet)); // Prepare to add all the new config "nameToModule" to boot module layer config MethodHandle nameToModuleGetter = IMPL_LOOKUP.findGetter(Configuration.class, "nameToModule", Map.class); HashMap<String, ResolvedModule> nameToModuleMap = new HashMap<>((Map<String, ResolvedModule>) nameToModuleGetter.invokeWithArguments(ModuleLayer.boot().configuration())); nameToModuleMap.putAll((Map<String, ResolvedModule>) nameToModuleGetter.invokeWithArguments(config)); IMPL_LOOKUP.findSetter(Configuration.class, "nameToModule", Map.class).invokeWithArguments(ModuleLayer.boot().configuration(), new HashMap<>(nameToModuleMap)); // Define all extra modules and add all the new config "nameToModule" to boot module layer config ((Map<String, Module>) IMPL_LOOKUP.findGetter(ModuleLayer.class, "nameToModule", Map.class).invokeWithArguments(ModuleLayer.boot())).putAll((Map<String, Module>) IMPL_LOOKUP.findStatic(Module.class, "defineModules", MethodType.methodType(Map.class, Configuration.class, Function.class, ModuleLayer.class)).invokeWithArguments(ModuleLayer.boot().configuration(), (Function<String, ClassLoader>) name -> ClassLoader.getSystemClassLoader(), ModuleLayer.boot())); // Add all of resolved modules modulesSet.addAll(oldBootModules); modulesSetter.invokeWithArguments(ModuleLayer.boot().configuration(), new HashSet<>(modulesSet)); // Reset cache of boot module layer IMPL_LOOKUP.findSetter(ModuleLayer.class, "modules", Set.class).invokeWithArguments(ModuleLayer.boot(), null); IMPL_LOOKUP.findSetter(ModuleLayer.class, "servicesCatalog", Class.forName("jdk.internal.module.ServicesCatalog")).invokeWithArguments(ModuleLayer.boot(), null); // Add reads from extra modules to jdk modules MethodHandle implAddReadsMH = IMPL_LOOKUP.findVirtual(Module.class, "implAddReads", MethodType.methodType(void.class, Module.class)); config.modules().forEach(rm -> ModuleLayer.boot().findModule(rm.name()).ifPresent(m -> oldBootModules.forEach(brm -> ModuleLayer.boot().findModule(brm.name()).ifPresent(CheckedLambdaUtil.wrapConsumer(bm -> implAddReadsMH.invokeWithArguments(m, bm)))))); } public static void addExports(List<String> exports) { TypeToAdd.EXPORTS.implAdd(exports); } public static void addOpens(List<String> opens) { TypeToAdd.OPENS.implAdd(opens); } private enum TypeToAdd { EXPORTS("Exports"), OPENS("Opens"); private final MethodHandle implAddMH; private final MethodHandle implAddToAllUnnamedMH; TypeToAdd(String name) { try { this.implAddMH = IMPL_LOOKUP.findVirtual(Module.class, "implAdd" + name, MethodType.methodType(void.class, String.class, Module.class)); this.implAddToAllUnnamedMH = IMPL_LOOKUP.findVirtual(Module.class, "implAdd" + name + "ToAllUnnamed", MethodType.methodType(void.class, String.class)); } catch (Throwable t) { throw new RuntimeException(t); } } void implAdd(List<String> extras) { extras.stream().map(ModuleUtil::parseModuleExtra).filter(Optional::isPresent).map(Optional::get).forEach(CheckedLambdaUtil.wrapConsumer(data -> ModuleLayer.boot().findModule(data.module).ifPresent(CheckedLambdaUtil.wrapConsumer(m -> { if ("ALL-UNNAMED".equals(data.target)) { this.implAddToAllUnnamedMH.invokeWithArguments(m, data.packages); } else { ModuleLayer.boot().findModule(data.target).ifPresent(CheckedLambdaUtil.wrapConsumer(tm -> this.implAddMH.invokeWithArguments(m, data.packages, tm))); } })))); } } // <module>/<package>=<target> private static Optional<ParserData> parseModuleExtra(String extra) { String[] all = extra.split("=", 2); if (all.length < 2) { return Optional.empty(); } String[] source = all[0].split("/", 2); if (source.length < 2) { return Optional.empty(); } return Optional.of(new ParserData(source[0], source[1], all[1])); } private static class ParserData { final String module; final String packages; final String target; ParserData(String module, String packages, String target) { this.module = module; this.packages = packages; this.target = target; } } // ForgeWrapper need some extra settings to invoke BootstrapLauncher. public static Class<?> setupBootstrapLauncher(Class<?> mainClass) throws Throwable { if (!mainClass.getModule().isOpen(mainClass.getPackageName(), ModuleUtil.class.getModule())) { TypeToAdd.OPENS.implAddMH.invokeWithArguments(mainClass.getModule(), mainClass.getPackageName(), ModuleUtil.class.getModule()); } return mainClass; } }
3e12533c2369fbeec3ad1fa096fa6f2b4b94a3f9
2,319
java
Java
examples/group-data-r2dbc-postgresql/data-r2dbc-postgresql-request-id-supplier/src/main/java/io/rxmicro/examples/data/r2dbc/postgresql/request/id/supplier/UpdateDataRepository.java
rxmicro/rxmicro-usage
0a34f063cb3f63171f69555ce595405160262848
[ "Apache-2.0" ]
5
2020-03-20T12:27:25.000Z
2022-03-30T08:36:59.000Z
examples/group-data-r2dbc-postgresql/data-r2dbc-postgresql-request-id-supplier/src/main/java/io/rxmicro/examples/data/r2dbc/postgresql/request/id/supplier/UpdateDataRepository.java
rxmicro/rxmicro-usage
0a34f063cb3f63171f69555ce595405160262848
[ "Apache-2.0" ]
2
2021-11-06T10:52:06.000Z
2021-11-06T10:52:06.000Z
examples/group-data-r2dbc-postgresql/data-r2dbc-postgresql-request-id-supplier/src/main/java/io/rxmicro/examples/data/r2dbc/postgresql/request/id/supplier/UpdateDataRepository.java
rxmicro/rxmicro-usage
0a34f063cb3f63171f69555ce595405160262848
[ "Apache-2.0" ]
null
null
null
38.65
127
0.715395
7,724
/* * Copyright (c) 2020. https://rxmicro.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.rxmicro.examples.data.r2dbc.postgresql.request.id.supplier; import io.rxmicro.data.sql.VariableValues; import io.rxmicro.data.sql.model.EntityFieldMap; import io.rxmicro.data.sql.operation.Update; import io.rxmicro.data.sql.r2dbc.postgresql.PostgreSQLRepository; import io.rxmicro.examples.data.r2dbc.postgresql.request.id.supplier.model.Account; import io.rxmicro.logger.RequestIdSupplier; import java.util.concurrent.CompletableFuture; // tag::content[] @PostgreSQLRepository public interface UpdateDataRepository { @Update CompletableFuture<Boolean> update1(RequestIdSupplier requestIdSupplier, Account account); @Update("UPDATE ${table} SET first_name=?, last_name=? WHERE id=?") // <1> @VariableValues({ "${table}", "account" }) CompletableFuture<Integer> update2(RequestIdSupplier requestIdSupplier, String firstName, String lastName, Long id); @Update("UPDATE ${table} SET first_name=?, last_name=? WHERE ${by-id-filter} RETURNING *") CompletableFuture<Account> update3(String firstName, String lastName, Long id); @Update( value = "UPDATE ${table} SET first_name=?, last_name=? " + "WHERE id = ?", entityClass = Account.class ) CompletableFuture<Integer> update4(RequestIdSupplier requestIdSupplier, String firstName, String lastName, Long id); @Update( value = "UPDATE ${table} SET first_name=?, last_name=? " + "WHERE ${by-id-filter} RETURNING *", entityClass = Account.class ) CompletableFuture<EntityFieldMap> update5(RequestIdSupplier requestIdSupplier, String firstName, String lastName, Long id); } // end::content[]
3e1253d81ae5eee85259caaf55f955efa236b456
791
java
Java
app/src/main/java/com/shuangwei/application/ui/tab_bar/fragment/TabBar2Fragment.java
Zakkoree/jiaoyuwuyou
d69ca0186efb3d8efd6d0d70525a8e2b489a34e1
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/shuangwei/application/ui/tab_bar/fragment/TabBar2Fragment.java
Zakkoree/jiaoyuwuyou
d69ca0186efb3d8efd6d0d70525a8e2b489a34e1
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/shuangwei/application/ui/tab_bar/fragment/TabBar2Fragment.java
Zakkoree/jiaoyuwuyou
d69ca0186efb3d8efd6d0d70525a8e2b489a34e1
[ "Apache-2.0" ]
null
null
null
25.516129
125
0.759798
7,725
package com.shuangwei.application.ui.tab_bar.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.ViewGroup; import com.shuangwei.application.BR; import com.shuangwei.application.R; import me.goldze.mvvmhabit.base.BaseFragment; import me.goldze.mvvmhabit.base.BaseViewModel; public class TabBar2Fragment extends BaseFragment { @Override public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return R.layout.fragment_tab_bar_2; } @Override public int initVariableId() { return BR.viewModel; } @Override public BaseViewModel initViewModel() { return new BaseViewModel(); } }
3e1254473179397acc044042ed8f9e2cd3a526bd
3,594
java
Java
TRTCSDK/Android/TRTCScenesDemo/trtcvoiceroomdemo/src/main/java/com/tencent/liteav/trtcvoiceroom/ui/room/AudienceListAdapter.java
aliyunvideo/Queen_SDK_Android
e46e32e16f8a6ecf3746a5c397a6a1f36189e93c
[ "Apache-2.0" ]
2
2021-07-06T03:32:25.000Z
2021-12-17T02:24:16.000Z
TRTCSDK/Android/TRTCScenesDemo/trtcvoiceroomdemo/src/main/java/com/tencent/liteav/trtcvoiceroom/ui/room/AudienceListAdapter.java
aliyunvideo/Queen_SDK_Android
e46e32e16f8a6ecf3746a5c397a6a1f36189e93c
[ "Apache-2.0" ]
null
null
null
TRTCSDK/Android/TRTCScenesDemo/trtcvoiceroomdemo/src/main/java/com/tencent/liteav/trtcvoiceroom/ui/room/AudienceListAdapter.java
aliyunvideo/Queen_SDK_Android
e46e32e16f8a6ecf3746a5c397a6a1f36189e93c
[ "Apache-2.0" ]
1
2022-03-31T09:07:26.000Z
2022-03-31T09:07:26.000Z
29.95
95
0.65192
7,726
package com.tencent.liteav.trtcvoiceroom.ui.room; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.squareup.picasso.Picasso; import com.tencent.liteav.trtcvoiceroom.R; import com.tencent.liteav.trtcvoiceroom.ui.widget.msg.AudienceEntity; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import de.hdodenhof.circleimageview.CircleImageView; public class AudienceListAdapter extends RecyclerView.Adapter<AudienceListAdapter.ViewHolder> { private static final String TAG = AudienceListAdapter.class.getSimpleName(); private Context mContext; private LinkedList<AudienceEntity> mDataList; private HashMap<String, AudienceEntity> mChatSalonMap; public AudienceListAdapter(Context context, LinkedList<AudienceEntity> list) { this.mContext = context; this.mDataList = list; mChatSalonMap = new HashMap<>(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.trtcvoiceroom_item_audience, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { AudienceEntity item = mDataList.get(position); holder.bind(mContext, item); } @Override public int getItemCount() { return mDataList.size(); } public void addMember(AudienceEntity entity) { if (entity == null) { return; } if (entity.userId == null) { return; } if (!mChatSalonMap.containsKey(entity.userId)) { mDataList.addFirst(entity); mChatSalonMap.put(entity.userId, entity); notifyDataSetChanged(); } } public void removeMember(String userId) { if (TextUtils.isEmpty(userId)) { return; } AudienceEntity localUserInfo = mChatSalonMap.get(userId); if (localUserInfo != null) { mDataList.remove(localUserInfo); mChatSalonMap.remove(userId); notifyDataSetChanged(); } } public void addMembers(List<AudienceEntity> list) { if (list != null) { for (AudienceEntity entity : list) { addMember(entity); } } notifyDataSetChanged(); } public HashMap<String, AudienceEntity> getChatSalonMap() { return mChatSalonMap; } public interface OnItemClickListener { void onItemClick(int position); } public class ViewHolder extends RecyclerView.ViewHolder { public CircleImageView mImgHead; public ViewHolder(View itemView) { super(itemView); initView(itemView); } public void bind(final Context context, final AudienceEntity entity) { if (!TextUtils.isEmpty(entity.userAvatar)) { Picasso.get().load(entity.userAvatar).into(mImgHead); } else { mImgHead.setImageResource(R.drawable.trtcvoiceroom_ic_head); } } private void initView(@NonNull final View itemView) { mImgHead = (CircleImageView) itemView.findViewById(R.id.img_head); } } }
3e125496518ae3f5106b068f5c3fb528e3c8d818
305
java
Java
mission-control-gui/src/main/java/de/qaware/theo/mc/gui/ObjectMapperProducer.java
Pink-Ponyhof/mission-control
3b2f8a09a29fefdccd4326ef64167fffc2bdda2a
[ "MIT" ]
null
null
null
mission-control-gui/src/main/java/de/qaware/theo/mc/gui/ObjectMapperProducer.java
Pink-Ponyhof/mission-control
3b2f8a09a29fefdccd4326ef64167fffc2bdda2a
[ "MIT" ]
null
null
null
mission-control-gui/src/main/java/de/qaware/theo/mc/gui/ObjectMapperProducer.java
Pink-Ponyhof/mission-control
3b2f8a09a29fefdccd4326ef64167fffc2bdda2a
[ "MIT" ]
null
null
null
16.944444
51
0.72459
7,727
package de.qaware.theo.mc.gui; import com.fasterxml.jackson.databind.ObjectMapper; import javax.enterprise.inject.Produces; /** * @author andreas.janning */ public class ObjectMapperProducer { @Produces public ObjectMapper produceObjectMapper() { return new ObjectMapper(); } }
3e1254ccc7f5b21a421cf24ba22ee2d5012ad599
5,895
java
Java
webrtc/src/main/java/dev/onvoid/webrtc/media/video/NativeI420Buffer.java
rmberne/webrtc-java
eb87168eec690f3aa7b54000030feeae1888bd87
[ "BSD-3-Clause" ]
110
2019-12-25T11:54:02.000Z
2022-03-16T06:27:05.000Z
webrtc/src/main/java/dev/onvoid/webrtc/media/video/NativeI420Buffer.java
averyzhong/webrtc-java
fd987e9af7fdd9762fbb2d3d392377ed23334065
[ "Apache-2.0" ]
54
2020-04-09T06:57:10.000Z
2022-03-28T16:29:39.000Z
webrtc/src/main/java/dev/onvoid/webrtc/media/video/NativeI420Buffer.java
internet-of-presence/webrtc-java
26ab2091f962533288e2267a16980008d7008528
[ "Apache-2.0" ]
37
2019-12-26T10:12:11.000Z
2022-03-10T18:06:23.000Z
30.544041
110
0.719423
7,728
/* * Copyright 2019 Alex Andres * * 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 dev.onvoid.webrtc.media.video; import dev.onvoid.webrtc.internal.RefCountedObject; import java.nio.ByteBuffer; /** * This class wraps the native WebRTC I420BufferInterface. */ public class NativeI420Buffer extends RefCountedObject implements I420Buffer { private final ByteBuffer dataY; private final ByteBuffer dataU; private final ByteBuffer dataV; private final int strideY; private final int strideU; private final int strideV; private final int width; private final int height; private NativeI420Buffer(int width, int height, ByteBuffer dataY, int strideY, ByteBuffer dataU, int strideU, ByteBuffer dataV, int strideV) { this.width = width; this.height = height; this.dataY = dataY; this.strideY = strideY; this.dataU = dataU; this.strideU = strideU; this.dataV = dataV; this.strideV = strideV; } @Override public ByteBuffer getDataY() { // Return a slice to prevent relative reads from changing the position. return dataY.slice(); } @Override public ByteBuffer getDataU() { // Return a slice to prevent relative reads from changing the position. return dataU.slice(); } @Override public ByteBuffer getDataV() { // Return a slice to prevent relative reads from changing the position. return dataV.slice(); } @Override public int getStrideY() { return strideY; } @Override public int getStrideU() { return strideU; } @Override public int getStrideV() { return strideV; } @Override public int getWidth() { return width; } @Override public int getHeight() { return height; } @Override public I420Buffer toI420() { retain(); return this; } @Override public VideoFrameBuffer cropAndScale(int cropX, int cropY, int cropWidth, int cropHeight, int scaleWidth, int scaleHeight) { return cropAndScale(this, cropX, cropY, cropWidth, cropHeight, scaleWidth, scaleHeight); } @Override public String toString() { return String.format("%s@%d [width=%s, height=%s]", NativeI420Buffer.class.getSimpleName(), hashCode(), width, height); } /** * Allocates an empty I420Buffer suitable for an image of the given dimensions. */ public static native NativeI420Buffer allocate(int width, int height); /** * Wraps existing ByteBuffers into NativeI420Buffer object without copying the * contents. */ private static I420Buffer wrap(int width, int height, ByteBuffer dataY, int strideY, ByteBuffer dataU, int strideU, ByteBuffer dataV, int strideV) { if (dataY == null || dataU == null || dataV == null) { throw new IllegalArgumentException("Data buffers cannot be null"); } if (!dataY.isDirect() || !dataU.isDirect() || !dataV.isDirect()) { throw new IllegalArgumentException("Data buffers must be direct byte buffers"); } // Slice the buffers to prevent external modifications to the position / limit // of the buffer. // Note that this doesn't protect the contents of the buffers from modifications. dataY = dataY.slice(); dataU = dataU.slice(); dataV = dataV.slice(); final int chromaWidth = (width + 1) / 2; final int chromaHeight = (height + 1) / 2; checkCapacity(dataY, width, height, strideY); checkCapacity(dataU, chromaWidth, chromaHeight, strideU); checkCapacity(dataV, chromaWidth, chromaHeight, strideV); return new NativeI420Buffer(width, height, dataY, strideY, dataU, strideU, dataV, strideV); } private static VideoFrameBuffer cropAndScale(final I420Buffer buffer, int cropX, int cropY, int cropWidth, int cropHeight, int scaleWidth, int scaleHeight) { if (cropWidth == scaleWidth && cropHeight == scaleHeight) { // No scaling. ByteBuffer dataY = buffer.getDataY(); ByteBuffer dataU = buffer.getDataU(); ByteBuffer dataV = buffer.getDataV(); dataY.position(cropX + cropY * buffer.getStrideY()); dataU.position(cropX / 2 + cropY / 2 * buffer.getStrideU()); dataV.position(cropX / 2 + cropY / 2 * buffer.getStrideV()); buffer.retain(); return wrap(scaleWidth, scaleHeight, dataY.slice(), buffer.getStrideY(), dataU.slice(), buffer.getStrideU(), dataV.slice(), buffer.getStrideV()); } I420Buffer newBuffer = allocate(scaleWidth, scaleHeight); cropAndScale(buffer.getDataY(), buffer.getStrideY(), buffer.getDataU(), buffer.getStrideU(), buffer.getDataV(), buffer.getStrideV(), cropX, cropY, cropWidth, cropHeight, newBuffer.getDataY(), newBuffer.getStrideY(), newBuffer.getDataU(), newBuffer.getStrideU(), newBuffer.getDataV(), newBuffer.getStrideV(), scaleWidth, scaleHeight); return newBuffer; } private static void checkCapacity(ByteBuffer data, int width, int height, int stride) { // The last row does not necessarily need padding. final int minCapacity = stride * (height - 1) + width; if (data.capacity() < minCapacity) { throw new IllegalArgumentException("Buffer must be at least " + minCapacity + " bytes, but was " + data.capacity()); } } private static native void cropAndScale(ByteBuffer srcY, int srcStrideY, ByteBuffer srcU, int srcStrideU, ByteBuffer srcV, int srcStrideV, int cropX, int cropY, int cropWidth, int cropHeight, ByteBuffer dstY, int dstStrideY, ByteBuffer dstU, int dstStrideU, ByteBuffer dstV, int dstStrideV, int scaleWidth, int scaleHeight); }
3e1255444099e8b930e5fb0ca55bab2bbcdd87b9
2,917
java
Java
src/test/java/com/endava/cats/fuzzer/contract/HttpStatusCodeInValidRangeFuzzerTest.java
productinfo/cats
b9d04d549e9fac3b59d7db01251e04ff3e516de0
[ "Apache-2.0" ]
2
2020-09-10T22:37:09.000Z
2020-09-14T10:15:55.000Z
src/test/java/com/endava/cats/fuzzer/contract/HttpStatusCodeInValidRangeFuzzerTest.java
productinfo/cats
b9d04d549e9fac3b59d7db01251e04ff3e516de0
[ "Apache-2.0" ]
null
null
null
src/test/java/com/endava/cats/fuzzer/contract/HttpStatusCodeInValidRangeFuzzerTest.java
productinfo/cats
b9d04d549e9fac3b59d7db01251e04ff3e516de0
[ "Apache-2.0" ]
null
null
null
36.012346
164
0.766884
7,729
package com.endava.cats.fuzzer.contract; import com.endava.cats.io.TestCaseExporter; import com.endava.cats.model.FuzzingData; import com.endava.cats.report.ExecutionStatisticsListener; import com.endava.cats.report.TestCaseListener; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.mockito.Mockito; import org.springframework.boot.info.BuildProperties; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) class HttpStatusCodeInValidRangeFuzzerTest { @SpyBean private TestCaseListener testCaseListener; @MockBean private ExecutionStatisticsListener executionStatisticsListener; @MockBean private TestCaseExporter testCaseExporter; @SpyBean private BuildProperties buildProperties; private HttpStatusCodeInValidRangeFuzzer httpStatusCodeInValidRangeFuzzer; @BeforeAll static void init() { System.setProperty("name", "cats"); System.setProperty("version", "4.3.2"); System.setProperty("time", "100011111"); } @BeforeEach void setup() { httpStatusCodeInValidRangeFuzzer = new HttpStatusCodeInValidRangeFuzzer(testCaseListener); } @ParameterizedTest @CsvSource({"100", "200", "599", "default"}) void shouldReportInfoWhenAllResponseCodesAreValid(String responseCode) { FuzzingData data = ContractFuzzerDataUtil.prepareFuzzingData("PetStore", responseCode); httpStatusCodeInValidRangeFuzzer.fuzz(data); Mockito.verify(testCaseListener, Mockito.times(1)).reportInfo(Mockito.any(), Mockito.eq("All defined response codes are valid!")); } @ParameterizedTest @CsvSource({"99", "1", "600"}) void shouldReportErrorWhenAllResponseCodesAreValid(String responseCode) { FuzzingData data = ContractFuzzerDataUtil.prepareFuzzingData("PetStore", responseCode); httpStatusCodeInValidRangeFuzzer.fuzz(data); Mockito.verify(testCaseListener, Mockito.times(1)).reportError(Mockito.any(), Mockito.eq("The following response codes are not valid: {}"), Mockito.any()); } @Test void shouldReturnSimpleClassNameForToString() { Assertions.assertThat(httpStatusCodeInValidRangeFuzzer).hasToString(httpStatusCodeInValidRangeFuzzer.getClass().getSimpleName()); } @Test void shouldReturnMeaningfulDescription() { Assertions.assertThat(httpStatusCodeInValidRangeFuzzer.description()).isEqualTo("verifies that all HTTP response codes are within the range of 100 to 599"); } }
3e1255bb081b39d89f29b87c089f665ede8994cf
1,660
java
Java
src/main/java/com/mediamath/terminalone/models/TPASCreativeBatch.java
MediaMath/t1-java
0e747f53c66fc4e8d26874a8e6dfdde119ffdcf0
[ "Apache-2.0" ]
5
2016-12-21T03:14:46.000Z
2022-01-19T11:41:56.000Z
src/main/java/com/mediamath/terminalone/models/TPASCreativeBatch.java
MediaMath/t1-java
0e747f53c66fc4e8d26874a8e6dfdde119ffdcf0
[ "Apache-2.0" ]
28
2016-12-07T04:30:03.000Z
2017-11-22T06:04:52.000Z
src/main/java/com/mediamath/terminalone/models/TPASCreativeBatch.java
MediaMath/t1-java
0e747f53c66fc4e8d26874a8e6dfdde119ffdcf0
[ "Apache-2.0" ]
11
2016-12-20T15:34:46.000Z
2019-04-08T17:56:36.000Z
25.151515
80
0.646988
7,730
/******************************************************************************* * Copyright 2016 MediaMath * * 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.mediamath.terminalone.models; public class TPASCreativeBatch { private String filename; private String user_id; private String id; private String total; private TPASCreativeBatchPlacements placements; public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTotal() { return total; } public void setTotal(String total) { this.total = total; } public TPASCreativeBatchPlacements getPlacements() { return placements; } public void setPlacements(TPASCreativeBatchPlacements placements) { this.placements = placements; } }
3e1255bb23b6a5f2cceb4f3c6bd56e89e286044f
5,769
java
Java
vahub-model/src/main/java/com/acuity/visualisations/rawdatamodel/service/plots/ExposureLineChartService.java
digital-ECMT/acuity-vahub
244eb7ec0f56cdac81ac6a8245ba2959b012b246
[ "Apache-2.0" ]
7
2022-01-25T18:12:19.000Z
2022-03-22T18:31:08.000Z
vahub-model/src/main/java/com/acuity/visualisations/rawdatamodel/service/plots/ExposureLineChartService.java
digital-ECMT/acuity-vahub
244eb7ec0f56cdac81ac6a8245ba2959b012b246
[ "Apache-2.0" ]
null
null
null
vahub-model/src/main/java/com/acuity/visualisations/rawdatamodel/service/plots/ExposureLineChartService.java
digital-ECMT/acuity-vahub
244eb7ec0f56cdac81ac6a8245ba2959b012b246
[ "Apache-2.0" ]
1
2022-03-28T15:20:09.000Z
2022-03-28T15:20:09.000Z
57.69
135
0.694054
7,731
/* * Copyright 2021 The University of Manchester * * 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.acuity.visualisations.rawdatamodel.service.plots; import com.acuity.visualisations.rawdatamodel.trellis.grouping.ChartGroupByOptions; import com.acuity.visualisations.rawdatamodel.trellis.grouping.ChartSelection; import com.acuity.visualisations.rawdatamodel.trellis.grouping.ChartSelectionItem; import com.acuity.visualisations.rawdatamodel.trellis.grouping.ExposureGroupByOptions; import com.acuity.visualisations.rawdatamodel.trellis.grouping.GroupByKey; import com.acuity.visualisations.rawdatamodel.util.ObjectUtil; import com.acuity.visualisations.rawdatamodel.vo.GroupByOption; import com.acuity.visualisations.rawdatamodel.vo.plots.ErrorLineChartEntry; import com.acuity.visualisations.rawdatamodel.vo.plots.LineChartEntry; import com.acuity.visualisations.rawdatamodel.vo.wrappers.Exposure; import java.util.stream.Collectors; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Predicate; import static com.acuity.visualisations.rawdatamodel.trellis.grouping.ChartGroupByOptions.ChartGroupBySetting.COLOR_BY; import static com.acuity.visualisations.rawdatamodel.trellis.grouping.ChartGroupByOptions.ChartGroupBySetting.NAME; import static com.acuity.visualisations.rawdatamodel.trellis.grouping.ChartGroupByOptions.ChartGroupBySetting.ORDER_BY; import static com.acuity.visualisations.rawdatamodel.trellis.grouping.ChartGroupByOptions.ChartGroupBySetting.STANDARD_DEVIATION; import static com.acuity.visualisations.rawdatamodel.trellis.grouping.ChartGroupByOptions.ChartGroupBySetting.X_AXIS; import static com.acuity.visualisations.rawdatamodel.trellis.grouping.ChartGroupByOptions.ChartGroupBySetting.Y_AXIS; import static com.acuity.visualisations.rawdatamodel.util.ObjectUtil.toDouble; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; @Service public class ExposureLineChartService extends LineChartService<Exposure, ExposureGroupByOptions> { //assuming there will be only doubles on x axis, getting code faster @Override public Predicate<GroupByKey<Exposure, ExposureGroupByOptions>> getSelectionMatchPredicate( ChartSelection<Exposure, ExposureGroupByOptions, ChartSelectionItem<Exposure, ExposureGroupByOptions>> selection) { final List<ChartSelectionItem<Exposure, ExposureGroupByOptions>> normalized = selection.getSelectionItems().stream().map(i -> { final Map<ExposureGroupByOptions, Object> selectedTrellises = i.getSelectedTrellises().entrySet().stream() .collect(toMap(e -> e.getKey(), e -> Objects.toString(e.getValue()))); final Map<ChartGroupByOptions.ChartGroupBySetting, Object> selectedItems = i.getSelectedItems().entrySet().stream() .collect(toMap(e -> e.getKey(), e -> e.getKey() == ChartGroupByOptions.ChartGroupBySetting.X_AXIS ? toDouble(e.getValue()) : Objects.toString(e.getValue()))); return ChartSelectionItem.of(selectedTrellises, selectedItems); }).collect(toList()); return e -> normalized.parallelStream() .anyMatch(selectionItem -> ObjectUtil.keysEquals(selectionItem.getSelectedTrellises(), e.getTrellisByValues()) && keysEquals(selectionItem.getSelectedItems(), e.getValues())); } private static <K> boolean keysEquals(Map<K, Object> o1, Map<K, Object> o2) { return (o1.size() == 0 && o2.size() == 0) || (o1.size() == o2.size() && o1.entrySet().stream().allMatch( e -> { final Object v1 = e.getValue() == null ? null : (e.getKey() == ChartGroupByOptions.ChartGroupBySetting.X_AXIS ? (Double) e.getValue() : Objects.toString(e.getValue())); final Object o = o2.get(e.getKey()); final Object v2 = o == null ? null : (e.getKey() == ChartGroupByOptions.ChartGroupBySetting.X_AXIS ? (Double) o : Objects.toString(o)); return Objects.equals(v1, v2); } )); } @Override protected <T, G extends Enum<G> & GroupByOption<T>> List<LineChartEntry> getSeries(List<GroupByKey<T, G>> combined) { return combined.stream() .map(key -> { final Object x = key.getValue(X_AXIS); final Object y = key.getValue(Y_AXIS); final Object name = key.getValue(NAME); final Object colorBy = key.getValue(COLOR_BY); final Object orderBy = key.getValues().containsKey(ORDER_BY) ? key.getValue(ORDER_BY) : x; final Double standardDeviation = (Double) key.getValue(STANDARD_DEVIATION); return new ErrorLineChartEntry(x, y, name, colorBy, orderBy, standardDeviation); }) .sorted() .collect(Collectors.toList()); } }
3e12563e5dae3f50383193bba0aaa865f38b602c
105
java
Java
sdk/sdk-java/src/main/java/cn/torna/sdk/param/IParam.java
torna-group/torna
6f9291f8ea54706061bd9406b21d60ae31a46a95
[ "Apache-2.0" ]
3
2021-10-30T02:31:00.000Z
2021-11-18T11:46:21.000Z
sdk/sdk-java/src/main/java/cn/torna/sdk/param/IParam.java
torna-group/torna
6f9291f8ea54706061bd9406b21d60ae31a46a95
[ "Apache-2.0" ]
1
2022-03-25T07:24:26.000Z
2022-03-25T07:24:26.000Z
sdk/sdk-java/src/main/java/cn/torna/sdk/param/IParam.java
torna-group/torna
6f9291f8ea54706061bd9406b21d60ae31a46a95
[ "Apache-2.0" ]
1
2022-01-25T05:43:07.000Z
2022-01-25T05:43:07.000Z
11.666667
27
0.647619
7,732
package cn.torna.sdk.param; /** * @author tanghc */ public interface IParam { String getName(); }
3e12566f9ec5d4ce0f03ac34f8bed083db0c59a9
7,222
java
Java
src/main/java/za/co/kmotsepe/tasuku/aspectj/AspectJUnit4Runner.java
kmotsepe/tasuku
134a8a99bd04d6b337d663a103a595084013137f
[ "MIT" ]
null
null
null
src/main/java/za/co/kmotsepe/tasuku/aspectj/AspectJUnit4Runner.java
kmotsepe/tasuku
134a8a99bd04d6b337d663a103a595084013137f
[ "MIT" ]
2
2017-07-21T08:40:28.000Z
2019-05-11T19:38:26.000Z
src/main/java/za/co/kmotsepe/tasuku/aspectj/AspectJUnit4Runner.java
kmotsepe/tasuku
134a8a99bd04d6b337d663a103a595084013137f
[ "MIT" ]
null
null
null
27.564885
80
0.591526
7,733
/** * AspectJ classes - Currently for checking the CheckStyleListener AuditEvent */ package za.co.kmotsepe.tasuku.aspectj; import java.io.IOException; import java.lang.annotation.Annotation; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import org.apache.log4j.Logger; import org.aspectj.weaver.loadtime.WeavingURLClassLoader; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.internal.runners.statements.RunAfters; import org.junit.internal.runners.statements.RunBefores; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import org.junit.runners.model.TestClass; /** * <p> * Use this JUnit Runner if you want to enable AspectJ load time weaving in your * test. To use this runner place this annotation on your test class:</p> * <p> * {@code @RunWith(AspectJUnit4Runner.class)}</p> * * @see AspectJConfig * @author David Zhang */ public class AspectJUnit4Runner extends BlockJUnit4ClassRunner { /** * Application logger */ private static final Logger LOGGER = Logger.getLogger(AspectJUnit4Runner.class); /** * */ private WeavingURLClassLoader cl; /** * */ private TestClass testClass; /** * * @param clazz * @throws InitializationError */ public AspectJUnit4Runner(final Class<?> clazz) throws InitializationError { super(clazz); LOGGER.info("AspectJunit4Runner class loaded"); } /** * * @param clazz * @return */ @Override protected final TestClass createTestClass(Class<?> clazz) { URL[] classpath = computeClasspath(clazz); cl = new WeavingURLClassLoader(classpath, null); clazz = loadClassFromClassLoader(clazz, cl); testClass = new TestClass(clazz); return testClass; } /** * * @param clazz * @return */ private URL[] computeClasspath(final Class<?> clazz) { URLClassLoader originalClassLoader = (URLClassLoader) clazz.getClassLoader(); URL[] classpath = originalClassLoader.getURLs(); AspectJConfig config = clazz.getAnnotation(AspectJConfig.class); if (config != null) { classpath = appendToClasspath(classpath, config.classpathAdditions()); } return classpath; } /** * * @param classpath * @param urls * @return */ private URL[] appendToClasspath(final URL[] classpath, final String[] urls) { URL[] extended = Arrays.copyOf(classpath, classpath.length + urls.length); for (int i = 0; i < urls.length; i++) { URL url; try { url = Paths.get(urls[i]).toAbsolutePath().toUri().toURL(); } catch (MalformedURLException e) { throw new RuntimeException(e); } extended[classpath.length + i] = url; } return extended; } /** * * @return */ @Override protected final List<FrameworkMethod> computeTestMethods() { Class<? extends Annotation> test = loadClassFromClassLoader(Test.class, cl); return getTestClass().getAnnotatedMethods(test); } /** * * @param notifier */ @Override public final void run(final RunNotifier notifier) { Throwable firstException = null; try { super.run(notifier); } catch (Exception e) { firstException = e; throw e; } finally { try { cl.close(); } catch (IOException e) { String exceptionMsg = "Failed to close AspectJ classloader."; RuntimeException rte = new RuntimeException(exceptionMsg, e); if (firstException != null) { rte.addSuppressed(firstException); } throw rte; } } } /** * * @param statement * @return */ @Override protected final Statement withBeforeClasses(final Statement statement) { Class<? extends Annotation> beforeClass = loadClassFromClassLoader(BeforeClass.class, cl); List<FrameworkMethod> befores = testClass.getAnnotatedMethods(beforeClass); if (befores.isEmpty()) { return statement; } else { return new RunBefores(statement, befores, null); } } /** * * @param statement * @return */ @Override protected final Statement withAfterClasses(final Statement statement) { Class<? extends Annotation> afterClass = loadClassFromClassLoader(AfterClass.class, cl); List<FrameworkMethod> afters = testClass.getAnnotatedMethods(afterClass); if (afters.isEmpty()) { return statement; } else { return new RunAfters(statement, afters, null); } } /** * * @param method * @param target * @param statement * @return */ @Override protected final Statement withBefores(final FrameworkMethod method, final Object target, final Statement statement) { Class<? extends Annotation> before = loadClassFromClassLoader(Before.class, cl); List<FrameworkMethod> befores = getTestClass().getAnnotatedMethods(before); if (befores.isEmpty()) { return statement; } else { return new RunBefores(statement, befores, target); } } /** * * @param method * @param target * @param statement * @return */ @Override protected final Statement withAfters(final FrameworkMethod method, final Object target, final Statement statement) { Class<? extends Annotation> after = loadClassFromClassLoader(After.class, cl); List<FrameworkMethod> afters = getTestClass().getAnnotatedMethods(after); if (afters.isEmpty()) { return statement; } else { return new RunAfters(statement, afters, target); } } /** * * @param <T> * @param clazz * @param cl * @return */ @SuppressWarnings("unchecked") private static <T> Class<T> loadClassFromClassLoader(final Class<T> clazz, final ClassLoader cl) { Class<T> loaded; try { loaded = (Class<T>) Class.forName(clazz.getName(), true, cl); LOGGER.info("Class " + loaded.getCanonicalName()); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } return loaded; } }