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
92300a3258932d958857343b03b78841523939f7
2,540
java
Java
jira-dvcs-connector-plugin/src/main/java/com/atlassian/jira/plugins/dvcs/querydsl/v3/QIssueToBranchMapping.java
markphip/testing
44a39b08af5964aa3e4c33467c8b7362f667f9b1
[ "BSD-2-Clause" ]
null
null
null
jira-dvcs-connector-plugin/src/main/java/com/atlassian/jira/plugins/dvcs/querydsl/v3/QIssueToBranchMapping.java
markphip/testing
44a39b08af5964aa3e4c33467c8b7362f667f9b1
[ "BSD-2-Clause" ]
null
null
null
jira-dvcs-connector-plugin/src/main/java/com/atlassian/jira/plugins/dvcs/querydsl/v3/QIssueToBranchMapping.java
markphip/testing
44a39b08af5964aa3e4c33467c8b7362f667f9b1
[ "BSD-2-Clause" ]
null
null
null
36.285714
146
0.732283
995,349
package com.atlassian.jira.plugins.dvcs.querydsl.v3; import com.atlassian.pocketknife.api.querydsl.SchemaProvider; import com.mysema.query.sql.ColumnMetadata; import com.mysema.query.sql.RelationalPathBase; import com.mysema.query.types.expr.SimpleExpression; import com.mysema.query.types.path.NumberPath; import com.mysema.query.types.path.StringPath; import java.sql.Types; import static com.mysema.query.types.PathMetadataFactory.forVariable; /** * Generated by https://bitbucket.org/atlassian/querydsl-ao-code-gen * * Changes made by hand: * Map and FK mappings to integers * Map Booleans to BooleanPaths * Map Dates as DateTimePath&lt;Date&gt; * * Future approach is documented at https://extranet.atlassian.com/x/AAuQj */ public class QIssueToBranchMapping extends RelationalPathBase<QIssueToBranchMapping> implements IssueKeyedMapping { private static final long serialVersionUID = 130563614L; public static final String AO_TABLE_NAME = "AO_E8B6CC_ISSUE_TO_BRANCH"; public static final QIssueToBranchMapping withSchema(SchemaProvider schemaProvider) { String schema = schemaProvider.getSchema(AO_TABLE_NAME); return new QIssueToBranchMapping("ISSUE_TO_BRANCH", schema, AO_TABLE_NAME); } /** * Database Columns */ public final NumberPath<Integer> ID = createNumber("ID", Integer.class); public final StringPath ISSUE_KEY = createString("ISSUE_KEY"); public final NumberPath<Integer> BRANCH_ID = createNumber("BRANCH_ID", Integer.class); public final com.mysema.query.sql.PrimaryKey<QIssueToBranchMapping> ISSUETOBRANCH_PK = createPrimaryKey(ID); public QIssueToBranchMapping(String variable, String schema, String table) { super(QIssueToBranchMapping.class, forVariable(variable), schema, table); addMetadata(); } private void addMetadata() { /** * Database Metadata is not yet used by QueryDSL but it might one day. */ addMetadata(ID, ColumnMetadata.named("ID").ofType(Types.INTEGER)); // .withSize(0).withNotNull()); // until detect primitive types, int .. addMetadata(ISSUE_KEY, ColumnMetadata.named("ISSUE_KEY").ofType(Types.VARCHAR)); // .withSize(0)); // until detect primitive types, int .. addMetadata(BRANCH_ID, ColumnMetadata.named("BRANCH_ID").ofType(Types.INTEGER)); // .withSize(0)); // until detect primitive types, int .. } @Override public SimpleExpression getIssueKeyExpression() { return ISSUE_KEY; } }
92300a61f9d8a4b3b368332045111d90633e9706
990
java
Java
src/test/java/com/octo/softshake/crunch/stock/StockJobIntTest.java
pkernevez/CrunchTDD
e9b25c255a3e369940619839dcf37667b2f043fd
[ "Apache-2.0" ]
null
null
null
src/test/java/com/octo/softshake/crunch/stock/StockJobIntTest.java
pkernevez/CrunchTDD
e9b25c255a3e369940619839dcf37667b2f043fd
[ "Apache-2.0" ]
null
null
null
src/test/java/com/octo/softshake/crunch/stock/StockJobIntTest.java
pkernevez/CrunchTDD
e9b25c255a3e369940619839dcf37667b2f043fd
[ "Apache-2.0" ]
null
null
null
26.052632
87
0.688889
995,350
package com.octo.softshake.crunch.stock; import org.apache.commons.io.FileUtils; import org.apache.crunch.impl.mem.OctoMemPipeline; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.assertj.core.api.CrunchAssertions.assertThat; import static org.junit.Assert.*; public class StockJobIntTest { String in_stock = "src/test/resources/stock.txt"; String in_mvt = "src/test/resources/mvt.txt"; String out = "target/test/result"; @Before public void setUp() throws Exception { FileUtils.deleteDirectory(new File(out)); } @Test public void run_nominalCase() throws IOException { // Given StockJob job = new StockJob(); // When int returnCode = job.run(OctoMemPipeline.getInstance(), in_stock, in_mvt, out); // Then assertEquals(0, returnCode); assertThat(out + "/out.txt").isEqualTo("src/test/resources/expected.txt"); } }
92300a7df123c7b98274b3a6fbe761185e35c3b5
3,569
java
Java
shardingsphere-features/shardingsphere-readwrite-splitting/shardingsphere-readwrite-splitting-core/src/main/java/org/apache/shardingsphere/readwritesplitting/strategy/ReadwriteSplittingStrategyFactory.java
jiangtao69039/shardingsphere
82ff0e3dba7ca8908d6076eb1544fa215c1bc4a1
[ "Apache-2.0" ]
4,372
2019-01-16T03:07:05.000Z
2020-04-17T11:16:15.000Z
shardingsphere-features/shardingsphere-readwrite-splitting/shardingsphere-readwrite-splitting-core/src/main/java/org/apache/shardingsphere/readwritesplitting/strategy/ReadwriteSplittingStrategyFactory.java
jiangtao69039/shardingsphere
82ff0e3dba7ca8908d6076eb1544fa215c1bc4a1
[ "Apache-2.0" ]
3,040
2019-01-16T01:18:40.000Z
2020-04-17T12:53:05.000Z
shardingsphere-features/shardingsphere-readwrite-splitting/shardingsphere-readwrite-splitting-core/src/main/java/org/apache/shardingsphere/readwritesplitting/strategy/ReadwriteSplittingStrategyFactory.java
jiangtao69039/shardingsphere
82ff0e3dba7ca8908d6076eb1544fa215c1bc4a1
[ "Apache-2.0" ]
1,515
2019-01-16T08:44:17.000Z
2020-04-17T09:07:53.000Z
53.268657
145
0.788736
995,351
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.readwritesplitting.strategy; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.base.Strings; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.apache.shardingsphere.infra.datasource.strategy.DynamicDataSourceStrategy; import org.apache.shardingsphere.infra.datasource.strategy.DynamicDataSourceStrategyFactory; import org.apache.shardingsphere.readwritesplitting.strategy.type.DynamicReadwriteSplittingStrategy; import org.apache.shardingsphere.readwritesplitting.strategy.type.StaticReadwriteSplittingStrategy; import java.util.List; import java.util.Optional; import java.util.Properties; /** * Readwrite splitting strategy factory. */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class ReadwriteSplittingStrategyFactory { /** * Create new instance of readwrite splitting strategy. * * @param type type of readwrite splitting strategy * @param props properties of readwrite splitting strategy * @return created instance */ public static ReadwriteSplittingStrategy newInstance(final String type, final Properties props) { return "STATIC".equalsIgnoreCase(type) ? createStaticReadwriteSplittingStrategy(props) : createDynamicReadwriteSplittingStrategy(props); } private static StaticReadwriteSplittingStrategy createStaticReadwriteSplittingStrategy(final Properties props) { String writeDataSourceName = props.getProperty("write-data-source-name"); Preconditions.checkArgument(!Strings.isNullOrEmpty(writeDataSourceName), "Write data source name is required."); Preconditions.checkArgument(!Strings.isNullOrEmpty(props.getProperty("read-data-source-names")), "Read data source names are required."); List<String> readDataSourceNames = Splitter.on(",").trimResults().splitToList(props.getProperty("read-data-source-names")); return new StaticReadwriteSplittingStrategy(writeDataSourceName, readDataSourceNames); } private static DynamicReadwriteSplittingStrategy createDynamicReadwriteSplittingStrategy(final Properties props) { String autoAwareDataSourceName = props.getProperty("auto-aware-data-source-name"); Preconditions.checkArgument(!Strings.isNullOrEmpty(autoAwareDataSourceName), "Auto aware data source name is required."); Optional<DynamicDataSourceStrategy> dynamicDataSourceStrategy = DynamicDataSourceStrategyFactory.findInstance(); Preconditions.checkArgument(dynamicDataSourceStrategy.isPresent(), "Dynamic data source strategy is required."); return new DynamicReadwriteSplittingStrategy(autoAwareDataSourceName, dynamicDataSourceStrategy.get()); } }
92300bfe6863e7f789c92f9ce291b9e4c5e25586
188
java
Java
athlete/src/com/lambdaschool/solution/BaseballAthleteCreator.java
amguenoun/java-athletes
671640e2625ceb0346a1e4cc0b4c7722aafbb485
[ "MIT" ]
null
null
null
athlete/src/com/lambdaschool/solution/BaseballAthleteCreator.java
amguenoun/java-athletes
671640e2625ceb0346a1e4cc0b4c7722aafbb485
[ "MIT" ]
null
null
null
athlete/src/com/lambdaschool/solution/BaseballAthleteCreator.java
amguenoun/java-athletes
671640e2625ceb0346a1e4cc0b4c7722aafbb485
[ "MIT" ]
null
null
null
20.888889
63
0.787234
995,352
package com.lambdaschool.solution; public class BaseballAthleteCreator implements AthleteCreator { @Override public void printAthlete() { System.out.println("Baseball Athlete"); } }
92300def5d367fb6ae11959238ae3fff4cdf9727
5,289
java
Java
src/test/java/uk/gov/hmcts/ccd/domain/service/casedataaccesscontrol/RoleAssignmentFilteringResultTest.java
duranfatih/ccd-data-store-api
6cee6dfc97c1be0b3c2e8d08ede6799aacd35a28
[ "MIT" ]
15
2018-03-28T14:47:53.000Z
2022-01-07T17:58:38.000Z
src/test/java/uk/gov/hmcts/ccd/domain/service/casedataaccesscontrol/RoleAssignmentFilteringResultTest.java
duranfatih/ccd-data-store-api
6cee6dfc97c1be0b3c2e8d08ede6799aacd35a28
[ "MIT" ]
1,294
2018-05-01T09:00:27.000Z
2022-03-25T11:47:58.000Z
src/test/java/uk/gov/hmcts/ccd/domain/service/casedataaccesscontrol/RoleAssignmentFilteringResultTest.java
duranfatih/ccd-data-store-api
6cee6dfc97c1be0b3c2e8d08ede6799aacd35a28
[ "MIT" ]
37
2018-04-10T11:34:22.000Z
2022-03-03T13:56:07.000Z
40.068182
95
0.741917
995,353
package uk.gov.hmcts.ccd.domain.service.casedataaccesscontrol; import org.junit.jupiter.api.Test; import uk.gov.hmcts.ccd.domain.model.casedataaccesscontrol.RoleAssignment; import java.util.HashMap; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class RoleAssignmentFilteringResultTest { private static final RoleAssignment roleAssignment = RoleAssignment.builder().build(); @Test void testHasPassedFilteringReturnsTrue() { Map<String, Boolean> filteringResults = new HashMap<>(); filteringResults.put("roleMatcher1", Boolean.TRUE); filteringResults.put("roleMatcher2", Boolean.TRUE); filteringResults.put("roleMatcher3", Boolean.TRUE); filteringResults.put("roleMatcher4", Boolean.TRUE); filteringResults.put("roleMatcher5", Boolean.TRUE); RoleAssignmentFilteringResult roleAssignmentFilteringResult = new RoleAssignmentFilteringResult(roleAssignment, filteringResults); assertTrue(roleAssignmentFilteringResult.hasPassedFiltering()); } @Test void testHasPassedFilteringReturnsFalse() { Map<String, Boolean> filteringResults = new HashMap<>(); filteringResults.put("roleMatcher1", Boolean.TRUE); filteringResults.put("roleMatcher2", Boolean.FALSE); filteringResults.put("roleMatcher3", Boolean.TRUE); filteringResults.put("roleMatcher4", Boolean.TRUE); filteringResults.put("roleMatcher5", Boolean.TRUE); RoleAssignmentFilteringResult roleAssignmentFilteringResult = new RoleAssignmentFilteringResult(roleAssignment, filteringResults); assertFalse(roleAssignmentFilteringResult.hasPassedFiltering()); } @Test void testHasPassedFilteringReturnsFalseWhenFilteringResultsEmpty() { RoleAssignmentFilteringResult roleAssignmentFilteringResult = new RoleAssignmentFilteringResult(roleAssignment, new HashMap<>()); assertFalse(roleAssignmentFilteringResult.hasPassedFiltering()); } @Test void hasFailedFilteringOnRegionAndOrBaseLocation() { Map<String, Boolean> filteringResults = new HashMap<>(); filteringResults.put("roleMatcher1", Boolean.TRUE); filteringResults.put("RegionMatcher", Boolean.FALSE); filteringResults.put("roleMatcher3", Boolean.TRUE); filteringResults.put("roleMatcher4", Boolean.TRUE); filteringResults.put("LocationMatcher", Boolean.FALSE); RoleAssignmentFilteringResult roleAssignmentFilteringResult = new RoleAssignmentFilteringResult(roleAssignment, filteringResults); assertTrue(roleAssignmentFilteringResult.hasFailedFilteringOnRegionAndBaseLocation()); } @Test void hasFailedFilteringOnRegion() { Map<String, Boolean> filteringResults = new HashMap<>(); filteringResults.put("roleMatcher1", Boolean.TRUE); filteringResults.put("RegionMatcher", Boolean.FALSE); filteringResults.put("roleMatcher3", Boolean.TRUE); filteringResults.put("roleMatcher4", Boolean.TRUE); filteringResults.put("LocationMatcher", Boolean.TRUE); RoleAssignmentFilteringResult roleAssignmentFilteringResult = new RoleAssignmentFilteringResult(roleAssignment, filteringResults); assertTrue(roleAssignmentFilteringResult.hasFailedFilteringOnRegionAndBaseLocation()); } @Test void hasFailedFilteringOnLocation() { Map<String, Boolean> filteringResults = new HashMap<>(); filteringResults.put("roleMatcher1", Boolean.TRUE); filteringResults.put("RegionMatcher", Boolean.TRUE); filteringResults.put("roleMatcher3", Boolean.TRUE); filteringResults.put("roleMatcher4", Boolean.TRUE); filteringResults.put("LocationMatcher", Boolean.FALSE); RoleAssignmentFilteringResult roleAssignmentFilteringResult = new RoleAssignmentFilteringResult(roleAssignment, filteringResults); assertTrue(roleAssignmentFilteringResult.hasFailedFilteringOnRegionAndBaseLocation()); } @Test void hasFailedFilteringBasedOnRegionAndLocationAndOtherMatchers() { Map<String, Boolean> filteringResults = new HashMap<>(); filteringResults.put("roleMatcher1", Boolean.FALSE); filteringResults.put("RegionMatcher", Boolean.FALSE); filteringResults.put("roleMatcher3", Boolean.TRUE); filteringResults.put("roleMatcher4", Boolean.TRUE); filteringResults.put("LocationMatcher", Boolean.FALSE); RoleAssignmentFilteringResult roleAssignmentFilteringResult = new RoleAssignmentFilteringResult(roleAssignment, filteringResults); assertFalse(roleAssignmentFilteringResult.hasFailedFilteringOnRegionAndBaseLocation()); } @Test void hasFailedFilteringBasedOnRegionAndLocationReturnsFalseWhenNoFilteringResults() { Map<String, Boolean> filteringResults = new HashMap<>(); RoleAssignmentFilteringResult roleAssignmentFilteringResult = new RoleAssignmentFilteringResult(roleAssignment, filteringResults); assertFalse(roleAssignmentFilteringResult.hasFailedFilteringOnRegionAndBaseLocation()); } }
92300ec76e4f42efde44a818dae9f7964788aa21
2,256
java
Java
core/target/java/org/apache/spark/TaskState.java
jessicarychen/598project
0ef1eb6f10539fadaf69d3474cebb0a4f90e14c0
[ "BSD-3-Clause-Open-MPI", "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT", "MIT-0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause-Clear", "PostgreSQL", "BSD-3-Clause" ]
null
null
null
core/target/java/org/apache/spark/TaskState.java
jessicarychen/598project
0ef1eb6f10539fadaf69d3474cebb0a4f90e14c0
[ "BSD-3-Clause-Open-MPI", "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT", "MIT-0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause-Clear", "PostgreSQL", "BSD-3-Clause" ]
null
null
null
core/target/java/org/apache/spark/TaskState.java
jessicarychen/598project
0ef1eb6f10539fadaf69d3474cebb0a4f90e14c0
[ "BSD-3-Clause-Open-MPI", "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT", "MIT-0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause-Clear", "PostgreSQL", "BSD-3-Clause" ]
null
null
null
83.555556
127
0.743794
995,354
package org.apache.spark; public class TaskState { static public scala.Enumeration.Value LAUNCHING () { throw new RuntimeException(); } static public scala.Enumeration.Value RUNNING () { throw new RuntimeException(); } static public scala.Enumeration.Value FINISHED () { throw new RuntimeException(); } static public scala.Enumeration.Value FAILED () { throw new RuntimeException(); } static public scala.Enumeration.Value KILLED () { throw new RuntimeException(); } static public scala.Enumeration.Value LOST () { throw new RuntimeException(); } static private scala.collection.immutable.Set<scala.Enumeration.Value> FINISHED_STATES () { throw new RuntimeException(); } static public boolean isFailed (scala.Enumeration.Value state) { throw new RuntimeException(); } static public boolean isFinished (scala.Enumeration.Value state) { throw new RuntimeException(); } static protected java.lang.Object readResolve () { throw new RuntimeException(); } static public java.lang.String toString () { throw new RuntimeException(); } static public scala.Enumeration.ValueSet values () { throw new RuntimeException(); } static protected int nextId () { throw new RuntimeException(); } static protected void nextId_$eq (int x$1) { throw new RuntimeException(); } static protected scala.collection.Iterator<java.lang.String> nextName () { throw new RuntimeException(); } static protected void nextName_$eq (scala.collection.Iterator<java.lang.String> x$1) { throw new RuntimeException(); } static public final int maxId () { throw new RuntimeException(); } static public final scala.Enumeration.Value apply (int x) { throw new RuntimeException(); } static public final scala.Enumeration.Value withName (java.lang.String s) { throw new RuntimeException(); } static protected final scala.Enumeration.Value Value () { throw new RuntimeException(); } static protected final scala.Enumeration.Value Value (int i) { throw new RuntimeException(); } static protected final scala.Enumeration.Value Value (java.lang.String name) { throw new RuntimeException(); } static protected final scala.Enumeration.Value Value (int i, java.lang.String name) { throw new RuntimeException(); } }
92300f9f3e9cab03dc9888d34707cc2af603375f
896
java
Java
wechat-mp/src/main/java/wechat/mp/api/impl/WxMpServiceAbstractImpl.java
xuechuan3411/WeChat
0617386fc33c34d7429c4e3493346f9cb8dca5de
[ "Apache-2.0" ]
null
null
null
wechat-mp/src/main/java/wechat/mp/api/impl/WxMpServiceAbstractImpl.java
xuechuan3411/WeChat
0617386fc33c34d7429c4e3493346f9cb8dca5de
[ "Apache-2.0" ]
null
null
null
wechat-mp/src/main/java/wechat/mp/api/impl/WxMpServiceAbstractImpl.java
xuechuan3411/WeChat
0617386fc33c34d7429c4e3493346f9cb8dca5de
[ "Apache-2.0" ]
null
null
null
23.578947
95
0.777902
995,355
package wechat.mp.api.impl; import com.google.gson.JsonParser; import wechat.common.exception.WxErrorException; import wechat.common.util.http.RequestHttp; import wechat.mp.api.WxMpConfigStorage; import wechat.mp.api.WxMpService; public abstract class WxMpServiceAbstractImpl<H, P> implements WxMpService, RequestHttp<H, P> { private static final JsonParser JSON_PARSER = new JsonParser(); private WxMpConfigStorage wxMpConfigStorage; private int retrySleepMillis = 1000; private int maxRetryTimes = 5; @Override public String getAccessToken() throws WxErrorException { return getAccessToken(false); } @Override public WxMpConfigStorage getWxMpConfigStorage() { return this.wxMpConfigStorage; } @Override public void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider) { this.wxMpConfigStorage = wxConfigProvider; this.initHttp(); } }
9230103970361a06d4c0fb77c7afaa6117f79664
2,099
java
Java
src/Java/src/PoeditSmarty.java
hokascha/PoeditSmarty
6f102311bde328fd886f6752b0cab6b95b00b9ea
[ "MIT" ]
11
2016-01-04T08:31:05.000Z
2020-12-05T18:21:02.000Z
src/Java/src/PoeditSmarty.java
hokascha/PoeditSmarty
6f102311bde328fd886f6752b0cab6b95b00b9ea
[ "MIT" ]
9
2015-12-28T04:22:21.000Z
2021-07-15T08:14:36.000Z
src/Java/src/PoeditSmarty.java
hokascha/PoeditSmarty
6f102311bde328fd886f6752b0cab6b95b00b9ea
[ "MIT" ]
4
2016-01-15T17:35:40.000Z
2021-07-15T13:43:07.000Z
21.639175
119
0.545021
995,356
/** * Imports library */ import core.Logger; import core.Graphic; import core.PotFile; import parse.ParseData; import parse.ParseFiles; import arguments.RenderArguments; /** * Imports 3'd parts library */ import java.util.Arrays; /** * Poedit parser */ public class PoeditSmarty { /** * static classes assign */ private static final Logger _log = new Logger("log"); /** * CLI press args */ private static final RenderArguments _commandLine = new RenderArguments(_log); /** * Entry point * @param args String arrays of args */ public static void main(String[] args) { PotFile file; Graphic.clearDisplay(); Graphic.printHeader("3.0.0"); Graphic.printText(36, Arrays.toString(args), "info"); if(_commandLine.parse(args) || _commandLine.has("h")) { _commandLine.help(); Graphic.println(""); return; } if(_commandLine.getByKey("k") == null) { ParseData.renderPatternKeywords(); } else { ParseData.renderPatternKeywords(_commandLine.getByKey("k").getArgs()); } if (_commandLine.getByKey("c") == null) { file = new PotFile(_commandLine.getByKey("o").getFirsArg(), _log); } else { file = new PotFile(_commandLine.getByKey("o").getFirsArg(), _commandLine.getByKey("c").getFirsArg(), _log); } new ParseFiles(_commandLine.getByKey("f").getArgs(), file, _log); file.save(); beforeClose(); } /** * do before close */ private static void beforeClose() { try { if(_commandLine.has("d")) { _log.getResult(); Thread.sleep(500); } if(!_commandLine.has("l")) { _log.deleteAndClose(); } else { _log.close(); } Graphic.clearColor(); } catch (InterruptedException e) { _log.warning(e.toString()); } Graphic.println(""); } }
923011956b471ee521b86844afecca188ed4df81
3,419
java
Java
src/gui/SimulationPanel.java
thekristopl/Project-Simulation
b48fdeb514a55dc2ccbae467d16541cd0491ee5a
[ "FTL" ]
null
null
null
src/gui/SimulationPanel.java
thekristopl/Project-Simulation
b48fdeb514a55dc2ccbae467d16541cd0491ee5a
[ "FTL" ]
1
2021-01-12T18:42:00.000Z
2021-01-12T18:42:00.000Z
src/gui/SimulationPanel.java
thekristopl/Project-Simulation
b48fdeb514a55dc2ccbae467d16541cd0491ee5a
[ "FTL" ]
null
null
null
31.657407
162
0.550746
995,357
package gui; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.util.HashMap; import javax.swing.JPanel; public class SimulationPanel extends JPanel { public HashMap<Integer, Line> lines; private static int rs = 40; public boolean antiAlias = true; public SimulationPanel() { super(); lines = new HashMap<>(); this.setDoubleBuffered(true); } public void putLine(Line l) { this.lines.put(l.getLineID(), l); } void drawLines(Graphics g) { Graphics2D g2d = (Graphics2D) g; if(this.antiAlias) { g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } for(Line line : lines.values()) { g2d.setColor(Color.BLACK); g2d.setStroke(new BasicStroke(10f)); g2d.drawLine((int) line.getStart().getX() +rs, (int) line.getStart().getY() +rs, (int) line.getEnd().getX() +rs, (int) line.getEnd().getY() +rs); g2d.setStroke(new BasicStroke(4f)); g2d.setColor(line.getStartColor()); g2d.drawLine((int) line.getStart().getX() +rs, (int) line.getStart().getY() +rs, (int) line.getCenter().getX() +rs, (int) line.getCenter().getY()+rs); g2d.setColor(line.getEndColor()); g2d.drawLine((int) line.getCenter().getX()+rs, (int) line.getCenter().getY()+rs, (int) line.getEnd().getX()+rs, (int) line.getEnd().getY()+rs); } } @Override public void paintComponent(Graphics g) { super.paintComponent(g); drawLines(g); } public void removeAllComponents() { this.lines = new HashMap<>(); } public void removeLineByRouterID(int rID) { HashMap<Integer, Line> newMap = new HashMap<>(); for(Line line : lines.values()) { if(line.routerStartID != rID && line.routerEndID != rID) { newMap.put(line.getLineID(), line); } } lines = newMap; MainFrame.INSTANCE.refreshMap(); } public void removeLineBySocketID(int rID, String socket) { HashMap<Integer, Line> newMap = new HashMap<>(); for(Line line : lines.values()) { if(line.routerStartID != rID && line.routerEndID != rID) { newMap.put(line.getLineID(), line); } else { if(!line.socketStartID.equals(socket) && line.routerStartID == rID) { newMap.put(line.getLineID(), line); } if(line.routerEndID == rID && !line.socketEndID.equals(socket)) { newMap.put(line.getLineID(), line); } } } lines = newMap; MainFrame.INSTANCE.refreshMap(); } public void regenerateLinks() { for(Line line : lines.values()) { line.regnerate(); } } public void removeLineByLineID(int linkID) { HashMap<Integer, Line> newMap = new HashMap<>(); for(Line line : lines.values()) { if(line.getLineID() != linkID) { newMap.put(line.getLineID(), line); } } lines = newMap; MainFrame.INSTANCE.refreshMap(); } }
92301215b171ac08fb2b88d6158b63b443bfa7e7
841
java
Java
src/test/java/com/daniel/example/jetbrains/WrapInObjectPostfixTemplateTest.java
khun84/intellij-ruby-aasm-plugin
8dd933511d4315f461ce1e29b0cf4a750467167a
[ "MIT" ]
null
null
null
src/test/java/com/daniel/example/jetbrains/WrapInObjectPostfixTemplateTest.java
khun84/intellij-ruby-aasm-plugin
8dd933511d4315f461ce1e29b0cf4a750467167a
[ "MIT" ]
null
null
null
src/test/java/com/daniel/example/jetbrains/WrapInObjectPostfixTemplateTest.java
khun84/intellij-ruby-aasm-plugin
8dd933511d4315f461ce1e29b0cf4a750467167a
[ "MIT" ]
null
null
null
33.64
83
0.712247
995,358
package com.daniel.example.jetbrains; import com.intellij.json.JsonFileType; import com.intellij.psi.PsiFile; import com.intellij.testFramework.fixtures.BasePlatformTestCase; import org.jetbrains.plugins.ruby.ruby.lang.RubyFileType; import org.junit.Assert; public class WrapInObjectPostfixTemplateTest extends BasePlatformTestCase { public void testWrapWithArray() throws Exception { // assertWrapping("{\n 123\n}", "123"); // assertWrapping("{\n null\n}", "null"); } /** * Asserts that the expansion of {@code content} by .o equals {@code expected}. */ private void assertWrapping(String expected, String content) { PsiFile file = myFixture.configureByText(JsonFileType.INSTANCE, content); myFixture.type(".o\t"); Assert.assertEquals(expected, file.getText()); } }
9230123a6ec8c4c85d66792af05db4d10312c403
522
java
Java
feign-consumer/src/main/java/com/example/feignconsumer/FeignConsumerApplication.java
icyfang/springcloud-trial
4635a2872947764d418a87b863010e7698c82cf3
[ "MIT" ]
null
null
null
feign-consumer/src/main/java/com/example/feignconsumer/FeignConsumerApplication.java
icyfang/springcloud-trial
4635a2872947764d418a87b863010e7698c82cf3
[ "MIT" ]
null
null
null
feign-consumer/src/main/java/com/example/feignconsumer/FeignConsumerApplication.java
icyfang/springcloud-trial
4635a2872947764d418a87b863010e7698c82cf3
[ "MIT" ]
null
null
null
30.705882
72
0.835249
995,359
package com.example.feignconsumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients public class FeignConsumerApplication { public static void main(String[] args) { SpringApplication.run(FeignConsumerApplication.class, args); } }
923012aa5323913d1e40946a7f3dde9a14a0108e
7,477
java
Java
src/etf/checkers/ui/CheckersBoardModel.java
markic/checkers-players
cd402a56b2b383af34e200fa3acd7fcb4b502d25
[ "Info-ZIP" ]
null
null
null
src/etf/checkers/ui/CheckersBoardModel.java
markic/checkers-players
cd402a56b2b383af34e200fa3acd7fcb4b502d25
[ "Info-ZIP" ]
null
null
null
src/etf/checkers/ui/CheckersBoardModel.java
markic/checkers-players
cd402a56b2b383af34e200fa3acd7fcb4b502d25
[ "Info-ZIP" ]
null
null
null
26.052265
87
0.555303
995,360
package etf.checkers.ui; import static etf.checkers.CheckersConsts.*; import java.util.*; import java.awt.event.*; import javax.swing.event.*; import etf.checkers.*; /** * This is the model of the {@link CheckersBoard CheckersBoard} widget. * @see CheckersBoard CheckersBoard * @author DD */ public class CheckersBoardModel { protected int enable; protected int[] bs, pbs; protected int[] hint; protected MutableMove pmove; protected Map<Integer, Integer> removedPieces; public CheckersBoardModel() { this(Utils.INITIAL_BOARDSTATE); } public CheckersBoardModel(int[] bs) { this.bs = bs.clone(); this.enable = NEITHER; this.pmove = new MutableMove(); this.pbs = bs.clone(); this.hint = new int[W * H]; this.removedPieces = new HashMap<Integer, Integer>(); } public boolean isSelection() { return pmove.size() > 0; } public void boardPressed() { fireActionPerformed(); } public void squarePressed(int b) { appendPartialMove(b); } public void appendPartialMove(int b) { pmove.add(b); if (!PMoveUtils.isValidPartialMove(bs, enable, pmove)) { pmove.remove(pmove.size() - 1); if (pmove.size() > 0 && pmove.get(pmove.size() - 1) == b) { pmove.remove(pmove.size() - 1); } else if (bs[b] % 4 == enable) { pmove.clear(); pmove.add(b); } else if (pmove.contains(b)) { pmove.subList(pmove.lastIndexOf(b) + 1, pmove.size()).clear(); } } updateBoardState(); updateHintState(); fireStateChanged(); } public void clearPartialMove() { pmove.clear(); updateBoardState(); updateHintState(); fireStateChanged(); } public MutableMove getPartialMove() { return pmove; } public void setPartialMove(MutableMove pmove) { this.pmove = pmove; updateBoardState(); updateHintState(); fireStateChanged(); } protected void updateBoardState() { removedPieces.clear(); pbs = bs.clone(); List<int[]> ops = Utils.convertMoveToPairwise(pmove); if (Utils.isWalk(pmove)) { int[] op = ops.get(0); Utils.walk(pbs, op[0], op[1]); } else { for (int[] op : ops) { int mid = (op[0] + op[1]) / 2; removedPieces.put(mid, pbs[mid]); Utils.jump(pbs, op[0], op[1]); } } if (Utils.isValidMove(bs, enable, new Move(pmove))) { Move move = new Move(pmove); pmove.clear(); pbs = bs.clone(); setEnabled(NEITHER); fireMoveSelected(move); } } public static final int HINT_NONE = 0; public static final int HINT_VALID = 1; public static final int HINT_INVALID = 2; /* * pbs must be updated before this * pmove cannot be a valid move, i.e. must be partial */ protected void updateHintState() { /* Clear hints */ for (int i = 0; i < H * W; i++) hint[i] = HINT_NONE; if (pmove.size() == 0) return; int a = pmove.get(pmove.size() - 1); if ( pmove.size() > 1 || Utils.isForcedJump(pbs, enable) ) for (int d : Utils.DIAG) { int b = a + 2 * d; if (Utils.canJump(pbs, a, b)) hint[b] = HINT_VALID; } else if (pmove.size() == 1) for (int d : Utils.DIAG) { int b = a + d; if (Utils.canWalk(pbs, a, b)) hint[b] = HINT_VALID; } if ( pmove.size() == 1 && Utils.isForcedJump(pbs, enable) ) for (int d : Utils.DIAG) { int b = a + d; if (Utils.canWalk(pbs, a, b)) hint[b] = HINT_INVALID; } } public int[] getBoardState() { return pbs.clone(); } public void setBoardState(int[] bs) { if (Arrays.equals(this.bs, bs)) return; this.bs = bs.clone(); pmove.clear(); updateBoardState(); updateHintState(); fireStateChanged(); } public int getPiece(int index) { if (removedPieces.containsKey(index)) return removedPieces.get(index); else return pbs[index]; } public int getHint(int index) { return hint[index]; } public int getEnabled() { return enable; } public void setEnabled(int enable) { if (this.enable == enable) return; clearPartialMove(); this.enable = enable; fireStateChanged(); } protected EventListenerList listenerList = new EventListenerList(); /** * Adds a move listener to this component. * @param listener the MoveListener to be added */ public void addMoveListener(MoveListener listener) { listenerList.add(MoveListener.class, listener); } /** * Removes a move listener to this component. * @param listener the MoveListener to be removed */ public void removeMoveListener(MoveListener listener) { listenerList.remove(MoveListener.class, listener); } /** * Adds a change listener to this component. * @param listener the ChangeListener to be added */ public void addChangeListener(ChangeListener listener) { listenerList.add(ChangeListener.class, listener); } /** * Removes a change listener to this component. * @param listener the ChangeListener to be removed */ public void removeChangeListener(ChangeListener listener) { listenerList.remove(ChangeListener.class, listener); } /** * Adds an action listener to this component. * @param listener the ActionListener to be added */ public void addActionListener(ActionListener listener) { listenerList.add(ActionListener.class, listener); } /** * Removes an action listener to this component. * @param listener the ActionListener to be removed */ public void removeActionListener(ActionListener listener) { listenerList.remove(ActionListener.class, listener); } /** * Runs each MoveListener's moveSelected method. */ protected void fireMoveSelected(Move move) { MoveEvent e = new MoveEvent(this, move); for (MoveListener listener : listenerList.getListeners(MoveListener.class)) listener.moveSelected(e); } /** * Runs each ChangeListener's stateChanged method. */ protected void fireStateChanged() { ChangeEvent e = new ChangeEvent(this); for (ChangeListener listener : listenerList.getListeners(ChangeListener.class)) listener.stateChanged(e); } /** * Runs each ActionListener's actionPerformed method. */ protected void fireActionPerformed() { ActionEvent e = new ActionEvent(this, 0, "asdf"); for (ActionListener listener : listenerList.getListeners(ActionListener.class)) listener.actionPerformed(e); } }
9230143298477c8eda24c17e3fb5fc66af7043c1
377
java
Java
Server/src/main/java/sample/Module/Share/Massage/Authlog.java
Vivid-Wang/Clear-Evipreserve
add4f638c6feb88b92d24665c4b19c0cc192aca8
[ "Apache-2.0" ]
2
2017-06-22T14:43:09.000Z
2017-06-22T14:43:13.000Z
Server/src/main/java/sample/Module/Share/Massage/Authlog.java
Dvs-Wang/Clear-Evipreserve
add4f638c6feb88b92d24665c4b19c0cc192aca8
[ "Apache-2.0" ]
null
null
null
Server/src/main/java/sample/Module/Share/Massage/Authlog.java
Dvs-Wang/Clear-Evipreserve
add4f638c6feb88b92d24665c4b19c0cc192aca8
[ "Apache-2.0" ]
1
2022-02-15T12:12:31.000Z
2022-02-15T12:12:31.000Z
18.85
46
0.644562
995,361
package sample.Module.Share.Massage; /** * Created by WangMingming on 2017/5/7. */ public class Authlog extends Message { private String password; public Authlog(){ this.setType(MsgType.AUTHLOG); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
923015b1cfd9149b1e730abee8f82dc3a9eaee79
3,598
java
Java
store-shop-web/store-shop-web-login/src/main/java/com/qf/store/shop/web/login/controller/LoginController.java
17371275854/shoppingStore
7db3b0171e7935e7a45e23b7b69707c1a51e13f4
[ "Apache-2.0" ]
null
null
null
store-shop-web/store-shop-web-login/src/main/java/com/qf/store/shop/web/login/controller/LoginController.java
17371275854/shoppingStore
7db3b0171e7935e7a45e23b7b69707c1a51e13f4
[ "Apache-2.0" ]
null
null
null
store-shop-web/store-shop-web-login/src/main/java/com/qf/store/shop/web/login/controller/LoginController.java
17371275854/shoppingStore
7db3b0171e7935e7a45e23b7b69707c1a51e13f4
[ "Apache-2.0" ]
null
null
null
32.125
97
0.606726
995,362
package com.qf.store.shop.web.login.controller; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.qf.constant.RegistConstant; import com.qf.dto.ResultBean; import com.qf.dto.UserDTO; import com.qf.store.shop.web.login.service.LoginRedisService; import com.qf.store.shop.web.login.service.LoginUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.util.UUID; @RestController @RequestMapping("login") public class LoginController implements RegistConstant { @Autowired private LoginRedisService loginRedisService; @Autowired private LoginUserService loginUserService; @RequestMapping(path = "user",method = RequestMethod.POST) public ResultBean userLogin(@RequestParam String username, @RequestParam String password, @CookieValue(value = REDIS_USER_KEY,required = false)String uuid, HttpServletResponse response){ ResultBean resultBean = null; String redisKey = ""; Boolean newRedisKeyFlag = false; //请求中是否带有uuid if (uuid != null && !uuid.equals("")){ String redisKey1 = new StringBuilder().append(REDIS_USER_KEY) .append("=") .append(uuid).toString(); //组织键后 看从redis中能否取用户,能取到则表示已登陆, resultBean = loginRedisService.getUserInfoByKey(redisKey1); redisKey = redisKey1; } //如果从redis中没有取到 if (resultBean == null || resultBean.getErrno() == 1){ //从数据库中获取用户 if (username.contains("@")){ //邮件登陆 resultBean = loginUserService.userLogin("email", username); }else { resultBean = loginUserService.userLogin("phone", username); } if (resultBean.getErrno() == 1){ return resultBean; } newRedisKeyFlag = true; } //数据库中没有该用户 if (resultBean.getErrno() == 1){ return resultBean; } Object data = resultBean.getData(); ObjectMapper objectMapper = new ObjectMapper(); UserDTO userDTO = objectMapper.convertValue(data, new TypeReference<UserDTO>() { }); //校验密码 if (!userDTO.getPassword().equals(password)){ return ResultBean.error("密码错误"); } if (newRedisKeyFlag){ //需要重新生成用户信息键值对,并存到redis中 String new_uuid = UUID.randomUUID().toString(); String redisKey2 = new StringBuilder().append(REDIS_USER_KEY) .append("=") .append(new_uuid).toString(); redisKey = redisKey2; //将新的用户信息存到redis中 loginRedisService.setUserInfo(redisKey,userDTO); //将redis中的key放到cookie中,设置生存时间 Cookie cookie = new Cookie(REDIS_USER_KEY,new_uuid); cookie.setMaxAge(86400); cookie.setPath("/"); response.addCookie(cookie); }else { //不需要重新生成用户信息键值对,重置redis中用户的生存时间 loginRedisService.setUserInfo(redisKey,userDTO); //并重置cookie生存时间 Cookie cookie = new Cookie(REDIS_USER_KEY,uuid); cookie.setMaxAge(86400); cookie.setPath("/"); response.addCookie(cookie); } return ResultBean.success("登陆成功"); } }
92301706082f2ba803e25a274180bb048028befe
443
java
Java
src/main/java/Dao/BabyMapper.java
zxuu/SSMDemo
bb37cde118932780a5c56fe53e2ba3959435bb34
[ "Apache-2.0" ]
null
null
null
src/main/java/Dao/BabyMapper.java
zxuu/SSMDemo
bb37cde118932780a5c56fe53e2ba3959435bb34
[ "Apache-2.0" ]
2
2021-12-10T01:21:32.000Z
2021-12-14T21:32:04.000Z
src/main/java/Dao/BabyMapper.java
zxuu/SSMDemo
bb37cde118932780a5c56fe53e2ba3959435bb34
[ "Apache-2.0" ]
1
2019-09-02T05:12:40.000Z
2019-09-02T05:12:40.000Z
20.136364
49
0.69526
995,363
package Dao; import Entity.Baby; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface BabyMapper { String getId(String name); int getMale(); int getFemale(); int getTotal(); void addBaby(Baby baby); void deleteBaby(int id); void updateBaby(Baby baby); Baby getBaby(int id); List<Baby> list(int start, int count); List<Baby> selectBabys(Baby baby); }
923018bfe02fd8d372be4822a54d86b07ac55f5d
3,371
java
Java
mozu-javaasync-core/src/main/java/com/mozu/api/contracts/productruntime/Category.java
bhewett/mozu-java
ea3697897d90c6e8a157176475f1b2ca0c2fb49a
[ "MIT" ]
null
null
null
mozu-javaasync-core/src/main/java/com/mozu/api/contracts/productruntime/Category.java
bhewett/mozu-java
ea3697897d90c6e8a157176475f1b2ca0c2fb49a
[ "MIT" ]
null
null
null
mozu-javaasync-core/src/main/java/com/mozu/api/contracts/productruntime/Category.java
bhewett/mozu-java
ea3697897d90c6e8a157176475f1b2ca0c2fb49a
[ "MIT" ]
null
null
null
26.131783
359
0.756452
995,364
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.contracts.productruntime; import java.util.List; import org.joda.time.DateTime; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.joda.time.DateTime; import com.mozu.api.contracts.productruntime.CategoryContent; import com.mozu.api.contracts.productruntime.Category; /** * A descriptive container that groups products. A category is merchant defined with associated products and discounts as configured. GThe storefront displays products in a hierarchy of categories. As such, categories can include a nesting of sub-categories to organize products and product options per set guidelines such as color, brand, material, and size. */ @JsonIgnoreProperties(ignoreUnknown = true) public class Category implements Serializable { // Default Serial Version UID private static final long serialVersionUID = 1L; /** * External unique identifier of the category. */ protected String categoryCode; public String getCategoryCode() { return this.categoryCode; } public void setCategoryCode(String categoryCode) { this.categoryCode = categoryCode; } /** * Unique identifier for the storefront container used to organize products. */ protected Integer categoryId; public Integer getCategoryId() { return this.categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } /** * The number of facet results for a product search. */ protected Integer count; public Integer getCount() { return this.count; } public void setCount(Integer count) { this.count = count; } /** * Indicates if the object is displayed on the storefront. If true, the admin product category is displayed in the store. If true, the category is not displayed. */ protected Boolean isDisplayed; public Boolean getIsDisplayed() { return this.isDisplayed; } public void setIsDisplayed(Boolean isDisplayed) { this.isDisplayed = isDisplayed; } /** * The numeric order of objects, used by a vocabulary value defined for an extensible attribute, images, and categories. */ protected Integer sequence; public Integer getSequence() { return this.sequence; } public void setSequence(Integer sequence) { this.sequence = sequence; } /** * Complex type that contains content for a language specified by LocaleCode. */ protected CategoryContent content; public CategoryContent getContent() { return this.content; } public void setContent(CategoryContent content) { this.content = content; } /** * List of the subcategories in the hierarchy for the specified categories. */ protected List<Category> childrenCategories; public List<Category> getChildrenCategories() { return this.childrenCategories; } public void setChildrenCategories(List<Category> childrenCategories) { this.childrenCategories = childrenCategories; } /** * If applicable, the parent category in the hierarchy for the specified category. */ protected Category parentCategory; public Category getParentCategory() { return this.parentCategory; } public void setParentCategory(Category parentCategory) { this.parentCategory = parentCategory; } }
92301925d3772e5d13162b78b14fc946c393a4f9
452
java
Java
webapp/src/main/java/com/example/webapp/entities/Image.java
KeHusky/ccwebapp
408ea98b4c381f217b4ca9fe8bed4e068a9d9038
[ "Apache-2.0" ]
null
null
null
webapp/src/main/java/com/example/webapp/entities/Image.java
KeHusky/ccwebapp
408ea98b4c381f217b4ca9fe8bed4e068a9d9038
[ "Apache-2.0" ]
null
null
null
webapp/src/main/java/com/example/webapp/entities/Image.java
KeHusky/ccwebapp
408ea98b4c381f217b4ca9fe8bed4e068a9d9038
[ "Apache-2.0" ]
1
2020-04-01T03:59:11.000Z
2020-04-01T03:59:11.000Z
19.652174
37
0.679204
995,365
package com.example.webapp.entities; import lombok.Data; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @Entity @Data public class Image { @Id @Column(length = 125) private String id; @Column(length = 1000) private String url; private String recipeId; private String md5; private long size; private String type; private String fileName; }
923019379ef4ecb59f4c05913e8efa1912b22375
6,667
java
Java
app/src/main/java/com/example/bookshop/Activity/DetailCategoryActivity.java
mamad2050/BookShop
836ff958706367ed61e6da8a62a7a370878ee2b6
[ "MIT" ]
null
null
null
app/src/main/java/com/example/bookshop/Activity/DetailCategoryActivity.java
mamad2050/BookShop
836ff958706367ed61e6da8a62a7a370878ee2b6
[ "MIT" ]
null
null
null
app/src/main/java/com/example/bookshop/Activity/DetailCategoryActivity.java
mamad2050/BookShop
836ff958706367ed61e6da8a62a7a370878ee2b6
[ "MIT" ]
null
null
null
29.5
131
0.678566
995,366
package com.example.bookshop.Activity; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.example.bookshop.Adapter.BookOfferCategoryAdapter; import com.example.bookshop.Adapter.DetailCategoryAdapter; import com.example.bookshop.Adapter.BookAdapter; import com.example.bookshop.Global.Constants; import com.example.bookshop.Global.Key; import com.example.bookshop.Model.Book; import com.example.bookshop.R; import com.google.gson.Gson; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class DetailCategoryActivity extends AppCompatActivity { private static final String TAG = "DetailCategoryActivity"; RequestQueue requestQueue; /*Toolbar*/ TextView title_toolbar; Bundle bundle; /* popular books recyclerview*/ RecyclerView recyclerPopulars; BookAdapter bookAdapter; List<Book> popularBooks = new ArrayList<>(); /* new books recyclerview*/ RecyclerView newBookRecyclerview; BookAdapter newBookAdapter; List<Book> newBooks = new ArrayList<>(); /* offer books recyclerview*/ RecyclerView offerRecyclerView; BookOfferCategoryAdapter bookOfferCategoryAdapter; List<Book> offBooks = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_category); initialize(); // getAllSubs(); getPopulars(); getNewBooks(); getOfferBook(); bookOfferCategoryAdapter.setListener(book -> { Intent intent = new Intent(DetailCategoryActivity.this, BookActivity.class); intent.putExtra(Key.ID, book.getId()); intent.putExtra(Key.CATEGORY_ID, book.getCategory_id()); startActivity(intent); }); } private void initialize() { bundle = getIntent().getExtras(); title_toolbar = findViewById(R.id.detailCategory_activity_toolbar_txt); title_toolbar.setText(bundle.getString(Key.TITLE)); requestQueue = Volley.newRequestQueue(this); /* Initialize all subs recyclerview*/ /* Initialize populars recyclerview*/ recyclerPopulars = findViewById(R.id.activity_all_category_popular_recyclerview); recyclerPopulars.setHasFixedSize(true); recyclerPopulars.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); bookAdapter = new BookAdapter(this, popularBooks); recyclerPopulars.setAdapter(bookAdapter); /* Initialize New recyclerview*/ newBookRecyclerview = findViewById(R.id.activity_detail_category_newsRecyclerview); newBookRecyclerview.setHasFixedSize(true); newBookRecyclerview.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)); newBookAdapter = new BookAdapter(this, newBooks); newBookRecyclerview.setAdapter(newBookAdapter); /* Initialize Offer recyclerview*/ offerRecyclerView = findViewById(R.id.activity_detail_category_offRecyclerview); offerRecyclerView.setHasFixedSize(true); offerRecyclerView.setLayoutManager(new LinearLayoutManager(this)); bookOfferCategoryAdapter = new BookOfferCategoryAdapter(this, offBooks); offerRecyclerView.setAdapter(bookOfferCategoryAdapter); } private void getPopulars() { Response.Listener<String> listener = response -> { Gson gson = new Gson(); Book[] populars = gson.fromJson(response, Book[].class); popularBooks.addAll(Arrays.asList(populars)); bookAdapter.notifyDataSetChanged(); }; Response.ErrorListener errorListener = error -> Log.e(TAG, "getNewBooksResponse: " + error.getMessage()); StringRequest request = new StringRequest(Request.Method.POST, Constants.LINK_POPULARS, listener, errorListener) { @Nullable @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String, String> map = new HashMap<>(); map.put(Key.ID, bundle.getString(Key.ID)); return map; } }; requestQueue.add(request); } private void getNewBooks() { Response.Listener<String> listener = response -> { Gson gson = new Gson(); Book[] news = gson.fromJson(response, Book[].class); newBooks.addAll(Arrays.asList(news)); newBookAdapter.notifyDataSetChanged(); }; Response.ErrorListener errorListener = error -> Log.e(TAG, "getNewBooksResponse: " + error.getMessage()); StringRequest request = new StringRequest(Request.Method.POST, Constants.LINK_NEWS_FOR_CATEGORY, listener, errorListener) { @Nullable @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String, String> map = new HashMap<>(); map.put(Key.ID, bundle.getString(Key.ID)); return map; } }; requestQueue.add(request); } private void getOfferBook() { Response.Listener<String> listener = response -> { Gson gson = new Gson(); Book[] offers = gson.fromJson(response, Book[].class); offBooks.addAll(Arrays.asList(offers)); bookOfferCategoryAdapter.notifyDataSetChanged(); }; Response.ErrorListener errorListener = error -> Log.e(TAG, "getNewBooksResponse: " + error.getMessage()); StringRequest request = new StringRequest(Request.Method.POST, Constants.LINK_OFFER_CATEGORY, listener, errorListener) { @Nullable @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String, String> map = new HashMap<>(); map.put(Key.ID, bundle.getString(Key.ID)); return map; } }; requestQueue.add(request); } }
923019601e2c953f54c18666131eac3dd7e8060f
740
java
Java
src/main/java/com/github/radm/theories/runner/TheoriesWrapper.java
richard-melvin/junit-theory-suite
a9bea3a1f37abeafd9086261b5190908bf9ff175
[ "MIT" ]
5
2015-06-23T21:14:04.000Z
2018-10-17T12:31:23.000Z
src/main/java/com/github/radm/theories/runner/TheoriesWrapper.java
richard-melvin/junit-theory-suite
a9bea3a1f37abeafd9086261b5190908bf9ff175
[ "MIT" ]
9
2015-06-23T10:11:48.000Z
2018-06-10T23:28:26.000Z
src/main/java/com/github/radm/theories/runner/TheoriesWrapper.java
richard-melvin/junit-theory-suite
a9bea3a1f37abeafd9086261b5190908bf9ff175
[ "MIT" ]
null
null
null
22.424242
71
0.675676
995,367
package com.github.radm.theories.runner; import java.util.List; import org.junit.contrib.theories.Theories; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; /** * Simple wrapper to allow reuse of validation logic. */ public class TheoriesWrapper extends Theories { /** * Instantiates a new theories wrapper. * * @param klass * the klass * @throws InitializationError * the initialization error */ public TheoriesWrapper(Class<?> klass) throws InitializationError { super(klass); } @Override public List<FrameworkMethod> computeTestMethods() { return super.computeTestMethods(); } }
92301977d49ba1babe22881ed8d7b3b7dba97c5a
367
java
Java
instrumentation/jaxws/jaxws-2.0/javaagent/src/test/java/io/opentelemetry/javaagent/instrumentation/jaxws/v2_0/SoapProvider.java
Zane-XY/opentelemetry-java-instrumentation
bf23b122da4f56f20e41dc013aa1de2813840bc6
[ "Apache-2.0" ]
683
2020-05-30T19:20:06.000Z
2022-03-30T22:08:23.000Z
instrumentation/jaxws/jaxws-2.0/javaagent/src/test/java/io/opentelemetry/javaagent/instrumentation/jaxws/v2_0/SoapProvider.java
Zane-XY/opentelemetry-java-instrumentation
bf23b122da4f56f20e41dc013aa1de2813840bc6
[ "Apache-2.0" ]
2,736
2020-05-30T20:21:17.000Z
2022-03-31T18:26:35.000Z
instrumentation/jaxws/jaxws-2.0/javaagent/src/test/java/io/opentelemetry/javaagent/instrumentation/jaxws/v2_0/SoapProvider.java
Zane-XY/opentelemetry-java-instrumentation
bf23b122da4f56f20e41dc013aa1de2813840bc6
[ "Apache-2.0" ]
350
2020-05-30T09:34:34.000Z
2022-03-31T14:34:28.000Z
19.315789
69
0.757493
995,368
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.javaagent.instrumentation.jaxws.v2_0; import javax.xml.ws.Provider; public class SoapProvider implements Provider<SoapProvider.Message> { @Override public Message invoke(Message message) { return message; } public static class Message {} }
92301988fb54a6204bc8440ee870b9a0b47c6758
1,798
java
Java
src/main/java/com/worldql/client/listeners/utils/ItemTools.java
SERVER-G-Repo/mammoth
b822e796527955abdf067918a28aff6c2562ff2a
[ "MIT" ]
770
2021-09-02T19:54:42.000Z
2022-03-31T21:29:05.000Z
src/main/java/com/worldql/client/listeners/utils/ItemTools.java
SERVER-G-Repo/mammoth
b822e796527955abdf067918a28aff6c2562ff2a
[ "MIT" ]
53
2021-09-02T19:19:24.000Z
2022-03-16T18:38:03.000Z
src/main/java/com/worldql/client/listeners/utils/ItemTools.java
SERVER-G-Repo/mammoth
b822e796527955abdf067918a28aff6c2562ff2a
[ "MIT" ]
52
2021-09-02T20:26:02.000Z
2022-03-31T05:59:51.000Z
35.254902
93
0.652948
995,369
package com.worldql.client.listeners.utils; import org.apache.commons.io.output.ByteArrayOutputStream; import org.bukkit.inventory.ItemStack; import org.bukkit.util.io.BukkitObjectInputStream; import org.bukkit.util.io.BukkitObjectOutputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.ByteBuffer; public class ItemTools { public static byte[] serializeItemStack(ItemStack[] items) throws IllegalStateException { // TODO: Make this serialization more efficient try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); dataOutput.writeInt(items.length); for (ItemStack item : items) { dataOutput.writeObject(item); } dataOutput.close(); return outputStream.toByteArray(); } catch (Exception e) { throw new IllegalStateException("Unable to save item stacks.", e); } } public static ItemStack[] deserializeItemStack(ByteBuffer buf) throws IOException { byte[] bytes = new byte[buf.remaining()]; buf.get(bytes); try { ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); ItemStack[] items = new ItemStack[dataInput.readInt()]; for (int i = 0; i < items.length; i++) { items[i] = (ItemStack) dataInput.readObject(); } dataInput.close(); return items; } catch (ClassNotFoundException e) { throw new IOException("Unable to decode class type.", e); } } }
923019cf06e3edab15e050513be9a3bf9800e4a8
6,577
java
Java
android/LeValleyLibrary/src/main/java/com/lecloud/valley/leecoSdk/LeReactPushViewManager.java
littlethree/LeDemo
adccc5e540fde81f9cdfff3afe0456d8b87bb82d
[ "MIT" ]
3
2016-09-05T19:47:49.000Z
2016-12-28T12:34:33.000Z
android/LeValleyLibrary/src/main/java/com/lecloud/valley/leecoSdk/LeReactPushViewManager.java
littlethree/LeDemo
adccc5e540fde81f9cdfff3afe0456d8b87bb82d
[ "MIT" ]
null
null
null
android/LeValleyLibrary/src/main/java/com/lecloud/valley/leecoSdk/LeReactPushViewManager.java
littlethree/LeDemo
adccc5e540fde81f9cdfff3afe0456d8b87bb82d
[ "MIT" ]
1
2016-12-16T03:57:45.000Z
2016-12-16T03:57:45.000Z
40.826087
111
0.656321
995,370
/************************************************************************* * Description: 乐视直播推流组件 * Author: raojia * Mail: efpyi@example.com * Created Time: 2017-02-05 ************************************************************************/ package com.lecloud.valley.leecoSdk; import android.os.Bundle; import android.util.Log; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.common.MapBuilder; import com.facebook.react.uimanager.SimpleViewManager; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.annotations.ReactProp; import com.lecloud.valley.common.Events; import com.lecloud.valley.utils.LogUtils; import java.util.Map; import javax.annotation.Nullable; import static com.lecloud.valley.common.Constants.PROP_CAMERA; import static com.lecloud.valley.common.Constants.PROP_FILTER; import static com.lecloud.valley.common.Constants.PROP_FLASH; import static com.lecloud.valley.common.Constants.PROP_PUSH; import static com.lecloud.valley.common.Constants.PROP_PUSH_PARA; import static com.lecloud.valley.common.Constants.PROP_PUSH_TYPE; import static com.lecloud.valley.common.Constants.PROP_VOLUME; import static com.lecloud.valley.common.Constants.PUSH_TYPE_LECLOUD; import static com.lecloud.valley.common.Constants.PUSH_TYPE_MOBILE; import static com.lecloud.valley.common.Constants.PUSH_TYPE_MOBILE_URI; import static com.lecloud.valley.common.Constants.PUSH_TYPE_NONE; import static com.lecloud.valley.common.Constants.REACT_CLASS_PUSH_VIEW; import static com.lecloud.valley.utils.LogUtils.TAG; /** * Created by JiaRao on 2017/02/05. */ public class LeReactPushViewManager extends SimpleViewManager<LeReactPushView> { private ThemedReactContext mReactContext; @Override public String getName() { return REACT_CLASS_PUSH_VIEW; } @Override protected LeReactPushView createViewInstance(ThemedReactContext reactContext) { Log.d(TAG, LogUtils.getTraceInfo() + "生命周期事件 createViewInstance 调起!"); mReactContext = reactContext; return new LeReactPushView(mReactContext); } @Override public void onDropViewInstance(LeReactPushView videoView) { Log.d(TAG, LogUtils.getTraceInfo() + "生命周期事件 onDropViewInstance 调起!"); super.onDropViewInstance(videoView); } @Override @Nullable public Map getExportedCustomDirectEventTypeConstants() { MapBuilder.Builder builder = MapBuilder.builder(); for (Events event : Events.values()) { builder.put(event.toString(), MapBuilder.of("registrationName", event.toString())); } return builder.build(); } @Override @Nullable public Map getExportedViewConstants() { return MapBuilder.of( "PUSH_TYPE_MOBILE_URI", PUSH_TYPE_MOBILE_URI, "PUSH_TYPE_MOBILE", PUSH_TYPE_MOBILE, "PUSH_TYPE_LECLOUD", PUSH_TYPE_LECLOUD, "PUSH_TYPE_NONE", PUSH_TYPE_NONE ); } /** * 设置推流类型和参数 * * @param para 数据源包 */ @ReactProp(name = PROP_PUSH_PARA) public void setPushPara(final LeReactPushView pushView, final ReadableMap para) { if (para == null || !para.hasKey(PROP_PUSH_TYPE) || para.getInt(PROP_PUSH_TYPE) == PUSH_TYPE_NONE) { return; } int pushType = para.getInt(PROP_PUSH_TYPE); Bundle bundle; switch (pushType) { case PUSH_TYPE_MOBILE_URI: bundle = new Bundle(); bundle.putInt(PROP_PUSH_TYPE, PUSH_TYPE_MOBILE_URI); bundle.putString("url", para.hasKey("url") ? para.getString("url") : ""); bundle.putBoolean("landscape", para.hasKey("landscape") && para.getBoolean("landscape")); bundle.putBoolean("frontCamera", para.hasKey("frontCamera") && para.getBoolean("frontCamera")); bundle.putBoolean("focus", para.hasKey("focus") && para.getBoolean("focus")); pushView.setTarget(bundle); break; case PUSH_TYPE_MOBILE: bundle = new Bundle(); bundle.putInt(PROP_PUSH_TYPE, PUSH_TYPE_MOBILE); bundle.putString("domainName", para.hasKey("domainName") ? para.getString("domainName") : ""); bundle.putString("streamName", para.hasKey("streamName") ? para.getString("streamName") : ""); bundle.putString("appkey", para.hasKey("appkey") ? para.getString("appkey") : ""); bundle.putBoolean("landscape", para.hasKey("landscape") && para.getBoolean("landscape")); bundle.putBoolean("frontCamera", para.hasKey("frontCamera") && para.getBoolean("frontCamera")); bundle.putBoolean("focus", para.hasKey("focus") && para.getBoolean("focus")); pushView.setTarget(bundle); break; case PUSH_TYPE_LECLOUD: bundle = new Bundle(); bundle.putInt(PROP_PUSH_TYPE, PUSH_TYPE_LECLOUD); bundle.putString("activityId", para.hasKey("activityId") ? para.getString("activityId") : ""); bundle.putString("userId", para.hasKey("userId") ? para.getString("userId") : ""); bundle.putString("secretKey", para.hasKey("secretKey") ? para.getString("secretKey") : ""); bundle.putBoolean("landscape", para.hasKey("landscape") && para.getBoolean("landscape")); bundle.putBoolean("frontCamera", para.hasKey("frontCamera") && para.getBoolean("frontCamera")); bundle.putBoolean("focus", para.hasKey("focus") && para.getBoolean("focus")); pushView.setTarget(bundle); break; } } @ReactProp(name = PROP_PUSH, defaultBoolean = false) public void setPush(final LeReactPushView pushView, final boolean push) { pushView.setPush(push); } @ReactProp(name = PROP_CAMERA) public void setCamera(final LeReactPushView pushView, final int times) { pushView.setCamera(times); } @ReactProp(name = PROP_FLASH, defaultBoolean = false) public void setFlash(final LeReactPushView pushView, final boolean flash) { pushView.setFlash(flash); } @ReactProp(name = PROP_FILTER) public void setFilter(final LeReactPushView pushView, final int filter) { pushView.setFilter(filter); } @ReactProp(name = PROP_VOLUME) public void setVolume(final LeReactPushView pushView, final int volume) { pushView.setVolume(volume); } }
923019cfd2bad35bf5a76d9c8d17665c2d0bdad4
826
java
Java
demo/src/main/java/com/example/demo/service/Classroom_service.java
mybanking/database_SelectClassSystem
357f29866759416b0b3ddb75a0763f882ab370e7
[ "Apache-2.0" ]
null
null
null
demo/src/main/java/com/example/demo/service/Classroom_service.java
mybanking/database_SelectClassSystem
357f29866759416b0b3ddb75a0763f882ab370e7
[ "Apache-2.0" ]
null
null
null
demo/src/main/java/com/example/demo/service/Classroom_service.java
mybanking/database_SelectClassSystem
357f29866759416b0b3ddb75a0763f882ab370e7
[ "Apache-2.0" ]
null
null
null
35.913043
135
0.817191
995,371
package com.example.demo.service; import com.alibaba.fastjson.JSONObject; import com.example.demo.bean.Classroom; import com.example.demo.bean.Take; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Service; @Service public interface Classroom_service { JSONObject load_classroom(String id,String type); JSONObject apply_classroom(Take t); JSONObject selected_classroom(String id,String type); JSONObject search_selected_classroom(String id,String type,String year,String week,String building,String classroomid); JSONObject search_specclassroom(String id,String type,String year,String week,String building,String classroomid); JSONObject cancel_apply(String takeid,String classroomId,String takeDate,String start_time,String end_time,String week,String day); }
92301bc538f0d5eea7ee1feca04dff660b8e39bf
4,151
java
Java
src/test/java/com/github/alexisjehan/javanilla/util/iteration/PrimitiveIterableTest.java
alexisjehan/javanilla
3bef8ba77b886c0842cd54f7b134bee0fddfa725
[ "MIT" ]
3
2018-04-23T18:53:06.000Z
2021-08-21T14:19:34.000Z
src/test/java/com/github/alexisjehan/javanilla/util/iteration/PrimitiveIterableTest.java
alexisjehan/javanilla
3bef8ba77b886c0842cd54f7b134bee0fddfa725
[ "MIT" ]
null
null
null
src/test/java/com/github/alexisjehan/javanilla/util/iteration/PrimitiveIterableTest.java
alexisjehan/javanilla
3bef8ba77b886c0842cd54f7b134bee0fddfa725
[ "MIT" ]
null
null
null
36.412281
107
0.762949
995,372
/* * MIT License * * Copyright (c) 2018-2021 Alexis Jehan * * 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 com.github.alexisjehan.javanilla.util.iteration; import com.github.alexisjehan.javanilla.lang.array.DoubleArrays; import com.github.alexisjehan.javanilla.lang.array.IntArrays; import com.github.alexisjehan.javanilla.lang.array.LongArrays; import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.DoubleAdder; import java.util.concurrent.atomic.LongAdder; import java.util.function.DoubleConsumer; import java.util.function.IntConsumer; import java.util.function.LongConsumer; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNullPointerException; /** * <p>{@link PrimitiveIterable} unit tests.</p> */ final class PrimitiveIterableTest { private static final int[] INT_ELEMENTS = IntArrays.of(1, 2, 3); private static final long[] LONG_ELEMENTS = LongArrays.of(1L, 2L, 3L); private static final double[] DOUBLE_ELEMENTS = DoubleArrays.of(1.0d, 2.0d, 3.0d); @Test void testOfInt() { final var primitiveIterable = Iterables.ofInt(INT_ELEMENTS); for (var i = 0; i < 2; ++i) { assertThat(primitiveIterable).containsExactly(IntArrays.toBoxed(INT_ELEMENTS)); } } @Test void testOfIntForEach() { final var primitiveIterable = Iterables.ofInt(INT_ELEMENTS); final var adder = new LongAdder(); primitiveIterable.forEach((IntConsumer) adder::add); assertThat(adder.intValue()).isEqualTo(IntStream.of(INT_ELEMENTS).sum()); } @Test void testOfIntForEachInvalid() { assertThatNullPointerException().isThrownBy(() -> Iterables.EMPTY_INT.forEach((IntConsumer) null)); } @Test void testOfLong() { final var primitiveIterable = Iterables.ofLong(LONG_ELEMENTS); for (var i = 0; i < 2; ++i) { assertThat(primitiveIterable).containsExactly(LongArrays.toBoxed(LONG_ELEMENTS)); } } @Test void testOfLongForEach() { final var primitiveIterable = Iterables.ofLong(LONG_ELEMENTS); final var adder = new LongAdder(); primitiveIterable.forEach((LongConsumer) adder::add); assertThat(adder.longValue()).isEqualTo(LongStream.of(LONG_ELEMENTS).sum()); } @Test void testOfLongForEachInvalid() { assertThatNullPointerException().isThrownBy(() -> Iterables.EMPTY_LONG.forEach((LongConsumer) null)); } @Test void testOfDouble() { final var primitiveIterable = Iterables.ofDouble(DOUBLE_ELEMENTS); for (var i = 0; i < 2; ++i) { assertThat(primitiveIterable).containsExactly(DoubleArrays.toBoxed(DOUBLE_ELEMENTS)); } } @Test void testOfDoubleForEach() { final var primitiveIterable = Iterables.ofDouble(DOUBLE_ELEMENTS); final var adder = new DoubleAdder(); primitiveIterable.forEach((DoubleConsumer) adder::add); assertThat(adder.doubleValue()).isEqualTo(DoubleStream.of(DOUBLE_ELEMENTS).sum()); } @Test void testOfDoubleForEachInvalid() { assertThatNullPointerException().isThrownBy(() -> Iterables.EMPTY_DOUBLE.forEach((DoubleConsumer) null)); } }
92301c1272c7eb383faa0e3ab446131de2ebaab1
2,645
java
Java
revolsys-swing/src/main/java/com/revolsys/swing/map/layer/record/RecordLayerActions.java
pauldaustin/gba-revolsys
561c5a2f858b54ab4503e7ae5cffeac11d5d8952
[ "Apache-2.0" ]
5
2015-02-23T04:53:44.000Z
2021-03-03T17:18:24.000Z
revolsys-swing/src/main/java/com/revolsys/swing/map/layer/record/RecordLayerActions.java
pauldaustin/gba-revolsys
561c5a2f858b54ab4503e7ae5cffeac11d5d8952
[ "Apache-2.0" ]
5
2021-08-13T23:45:14.000Z
2022-03-31T19:59:23.000Z
revolsys-swing/src/main/java/com/revolsys/swing/map/layer/record/RecordLayerActions.java
pauldaustin/gba-revolsys
561c5a2f858b54ab4503e7ae5cffeac11d5d8952
[ "Apache-2.0" ]
8
2015-02-23T04:53:45.000Z
2022-03-26T22:35:36.000Z
37.253521
97
0.758412
995,373
package com.revolsys.swing.map.layer.record; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.util.function.Consumer; import javax.swing.JLabel; import org.jeometry.common.data.type.DataTypes; import com.revolsys.geometry.model.Geometry; import com.revolsys.geometry.simplify.DouglasPeuckerSimplifier; import com.revolsys.record.Record; import com.revolsys.swing.SwingUtil; import com.revolsys.swing.component.BasePanel; import com.revolsys.swing.component.ValueField; import com.revolsys.swing.field.NumberTextField; public class RecordLayerActions { public static void generalize(final AbstractRecordLayer layer, final Integer recordCount, final Consumer<Consumer<LayerRecord>> forEachRecord) { final Double distanceTolerance = generalizeGetDistance(layer); if (distanceTolerance != null) { final Consumer<LayerRecord> action = record -> generalizeRecord(record, distanceTolerance); layer.processTasks("Generalize", recordCount, forEachRecord, action); } } public static Double generalizeGetDistance(final AbstractRecordLayer layer) { final double defaultValue = layer.getGeneralizeGeometryTolerance(); return getDistanceTolerance(layer, "Generalize Vertices", defaultValue); } public static void generalizeRecord(final Record record, final double distanceTolerance) { final Geometry geometry = record.getGeometry(); if (geometry != null) { final Geometry newGeometry = DouglasPeuckerSimplifier.simplify(geometry, distanceTolerance, true); record.setGeometryValue(newGeometry); } if (record instanceof LayerRecord) { final LayerRecord layerRecord = (LayerRecord)record; final AbstractRecordLayer layer = layerRecord.getLayer(); layer.postProcess(layerRecord); } } public static Double getDistanceTolerance(final AbstractRecordLayer layer, final String title, final double defaultValue) { final ValueField dialog = new ValueField(new BorderLayout()); dialog.setTitle(title); final NumberTextField distanceField = new NumberTextField(DataTypes.DOUBLE, 10, 2); distanceField.setFieldValue(defaultValue); dialog.add(distanceField); final String unit = layer.getHorizontalCoordinateSystem().getLengthUnit().toString(); final JLabel label = SwingUtil.newLabel("Distance Tolerance (" + unit + ")"); final BasePanel fieldPanel = new BasePanel(new FlowLayout(), label, distanceField); dialog.add(fieldPanel, BorderLayout.CENTER); dialog.showDialog(); if (dialog.isSaved()) { return distanceField.getFieldValue(); } else { return null; } } }
92301c4a467af990cdb308a21e2fb676356104e0
3,537
java
Java
jmetal-core/src/main/java/org/uma/jmetal/solution/AbstractSolution.java
matthieu-vergne/jMetal
45a260c46aa62f396794485f5a80488edfd4102f
[ "MIT" ]
2
2020-07-20T15:02:05.000Z
2020-08-21T01:57:39.000Z
jmetal-core/src/main/java/org/uma/jmetal/solution/AbstractSolution.java
matthieu-vergne/jMetal
45a260c46aa62f396794485f5a80488edfd4102f
[ "MIT" ]
3
2020-07-20T18:57:42.000Z
2020-07-23T11:59:46.000Z
jmetal-core/src/main/java/org/uma/jmetal/solution/AbstractSolution.java
matthieu-vergne/jMetal
45a260c46aa62f396794485f5a80488edfd4102f
[ "MIT" ]
4
2020-07-20T18:01:41.000Z
2020-11-26T18:07:38.000Z
21.185629
79
0.653759
995,374
package org.uma.jmetal.solution; import org.uma.jmetal.util.JMetalException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Abstract class representing a generic solution * * @author Antonio J. Nebro <dycjh@example.com> */ @SuppressWarnings("serial") public abstract class AbstractSolution<T> implements Solution<T> { private double[] objectives; private List<T> variables; private double[] constraints; protected Map<Object, Object> attributes; /** Constructor */ protected AbstractSolution(int numberOfVariables, int numberOfObjectives) { this(numberOfVariables, numberOfObjectives, 0); } /** Constructor */ protected AbstractSolution( int numberOfVariables, int numberOfObjectives, int numberOfConstraints) { attributes = new HashMap<>(); variables = new ArrayList<>(numberOfVariables); for (int i = 0; i < numberOfVariables; i++) { variables.add(i, null); } objectives = new double[numberOfObjectives]; for (int i = 0; i < numberOfObjectives; i++) { objectives[i] = 0.0; } constraints = new double[numberOfConstraints]; for (int i = 0; i < numberOfConstraints; i++) { constraints[i] = 0.0; } attributes = new HashMap<Object, Object>(); } @Override public double[] getObjectives() { return objectives; } @Override public List<T> getVariables() { return variables; } @Override public double[] getConstraints() { return constraints ; } @Override public void setAttribute(Object id, Object value) { attributes.put(id, value); } @Override public Object getAttribute(Object id) { return attributes.get(id); } @Override public boolean hasAttribute(Object id) { return attributes.containsKey(id); } @Override public void setObjective(int index, double value) { objectives[index] = value; } @Override public double getObjective(int index) { return objectives[index]; } @Override public T getVariable(int index) { return variables.get(index); } @Override public void setVariable(int index, T value) { variables.set(index, value); } @Override public double getConstraint(int index) { return constraints[index] ; } @Override public void setConstraint(int index, double value) { constraints[index] = value ; } @Override public int getNumberOfVariables() { return variables.size(); } @Override public int getNumberOfObjectives() { return objectives.length; } @Override public int getNumberOfConstraints() { return constraints.length ; } @Override public String toString() { String result = "Variables: "; for (T var : variables) { result += "" + var + " "; } result += "Objectives: "; for (Double obj : objectives) { result += "" + obj + " "; } result += "Constraints: "; for (Double obj : constraints) { result += "" + obj + " "; } result += "\t"; result += "AlgorithmAttributes: " + attributes + "\n"; return result; } @Override public boolean equals(Object o) { if (o == null) { throw new JMetalException("The solution to compare is null"); } Solution<T> solution = (Solution<T>) o; return this.getVariables().equals(solution.getVariables()); } @Override public int hashCode() { return variables.hashCode(); } @Override public Map<Object, Object> getAttributes() { return attributes; } }
92301cb6daa0540b54f85296b298df8692d59e73
1,823
java
Java
testbench/testsolutions/editor.menus.tests/test_gen/jetbrains/mps/lang/editor/menus/tests/SubstituteMenu_ConvertToContribution_Test.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
testbench/testsolutions/editor.menus.tests/test_gen/jetbrains/mps/lang/editor/menus/tests/SubstituteMenu_ConvertToContribution_Test.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
testbench/testsolutions/editor.menus.tests/test_gen/jetbrains/mps/lang/editor/menus/tests/SubstituteMenu_ConvertToContribution_Test.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
39.630435
240
0.80362
995,375
package jetbrains.mps.lang.editor.menus.tests; /*Generated by MPS */ import jetbrains.mps.MPSLaunch; import jetbrains.mps.lang.test.runtime.BaseTransformationTest; import org.junit.ClassRule; import jetbrains.mps.lang.test.runtime.TestParametersCache; import org.junit.Test; import jetbrains.mps.lang.test.runtime.BaseEditorTestBody; import jetbrains.mps.lang.test.runtime.TransformationTest; import org.jetbrains.mps.openapi.language.SConcept; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; @MPSLaunch public class SubstituteMenu_ConvertToContribution_Test extends BaseTransformationTest { @ClassRule public static final TestParametersCache ourParamCache = new TestParametersCache(SubstituteMenu_ConvertToContribution_Test.class, "${mps_home}", "r:4f8193a2-048e-4ddf-b505-dfca00e8c910(jetbrains.mps.lang.editor.menus.tests@tests)", false); public SubstituteMenu_ConvertToContribution_Test() { super(ourParamCache); } @Test public void test_SubstituteMenu_ConvertToContribution() throws Throwable { new TestBody(this).testMethod(); } /*package*/ static class TestBody extends BaseEditorTestBody { /*package*/ TestBody(TransformationTest owner) { super(owner); } @Override public void testMethodImpl() throws Exception { initEditorComponent("1149574124334462207", "1149574124334462211"); invokeParameterizedIntention("jetbrains.mps.lang.editor.intentions.ConvertSubstituteMenu_Intention", CONCEPTS.SubstituteMenu_Contribution$s3, myStart.getNode()); } } private static final class CONCEPTS { /*package*/ static final SConcept SubstituteMenu_Contribution$s3 = MetaAdapterFactory.getConcept(0x18bc659203a64e29L, 0xa83a7ff23bde13baL, 0x2de9c932f4e5cb53L, "jetbrains.mps.lang.editor.structure.SubstituteMenu_Contribution"); } }
92301fc2300b075cfa92df8373940997009d95a9
1,863
java
Java
noark-game/src/main/java/xyz/noark/game/monitor/impl/NettyDirectMemoryMonitorService.java
397786756/noark3
1371ba824c92f803f6095b278439967b328d5add
[ "MulanPSL-1.0" ]
17
2018-10-16T08:39:55.000Z
2022-03-13T07:41:30.000Z
noark-game/src/main/java/xyz/noark/game/monitor/impl/NettyDirectMemoryMonitorService.java
397786756/noark3
1371ba824c92f803f6095b278439967b328d5add
[ "MulanPSL-1.0" ]
8
2020-11-10T06:58:52.000Z
2020-11-11T11:37:09.000Z
noark-game/src/main/java/xyz/noark/game/monitor/impl/NettyDirectMemoryMonitorService.java
397786756/noark3
1371ba824c92f803f6095b278439967b328d5add
[ "MulanPSL-1.0" ]
8
2019-04-30T07:31:49.000Z
2022-03-22T07:56:18.000Z
27.80597
124
0.718733
995,376
/* * Copyright © 2018 www.noark.xyz All Rights Reserved. * * 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ! * 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件: * * http://www.noark.xyz/LICENSE * * 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播; * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本; * 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利; * 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明! */ package xyz.noark.game.monitor.impl; import io.netty.util.internal.PlatformDependent; import xyz.noark.core.util.FieldUtils; import xyz.noark.core.util.FileUtils; import xyz.noark.game.monitor.AbstractMonitorService; import java.lang.reflect.Field; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import static xyz.noark.log.LogHelper.logger; /** * Netty堆外内存监控服务. * * @author 小流氓[176543888@qq.com] * @since 3.3.5 */ public class NettyDirectMemoryMonitorService extends AbstractMonitorService { /** * Netty堆外内存。 * <p> * 请参考io.netty.util.internal.PlatformDependent#DIRECT_MEMORY_COUNTER */ private final AtomicLong DIRECT_MEMORY_COUNTER; public NettyDirectMemoryMonitorService() { Field field = FieldUtils.getField(PlatformDependent.class, "DIRECT_MEMORY_COUNTER"); this.DIRECT_MEMORY_COUNTER = (AtomicLong) FieldUtils.readField(null, field); } @Override protected long getInitialDelay() { return 60; } @Override protected long getDelay() { return 60; } @Override protected TimeUnit getUnit() { return TimeUnit.SECONDS; } @Override protected void exe() throws Exception { final long cur = DIRECT_MEMORY_COUNTER.get(); final long max = PlatformDependent.maxDirectMemory(); logger.info("netty direct memory cur={}, max={}", FileUtils.readableFileSize(cur), FileUtils.readableFileSize(max)); } }
9230231146feaa90fc3de702f9f3c605b679406a
3,584
java
Java
entdiy-module/entdiy-module-common/src/main/java/com/entdiy/support/service/SerialNumberService.java
JLLeitschuh/s2jh4net
4c66bc4a5454f750c4a0b4284b4d04cad5498a9d
[ "Apache-2.0" ]
192
2015-03-04T13:11:26.000Z
2021-12-22T02:07:45.000Z
entdiy-module/entdiy-module-common/src/main/java/com/entdiy/support/service/SerialNumberService.java
JLLeitschuh/s2jh4net
4c66bc4a5454f750c4a0b4284b4d04cad5498a9d
[ "Apache-2.0" ]
30
2015-08-05T01:57:43.000Z
2020-06-03T06:06:30.000Z
entdiy-module/entdiy-module-common/src/main/java/com/entdiy/support/service/SerialNumberService.java
JLLeitschuh/s2jh4net
4c66bc4a5454f750c4a0b4284b4d04cad5498a9d
[ "Apache-2.0" ]
188
2015-03-05T01:51:18.000Z
2021-08-13T06:45:13.000Z
34.461538
100
0.676618
995,377
/** * Copyright © 2015 - 2017 EntDIY JavaEE Development Framework * 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.entdiy.support.service; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import java.time.Instant; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.SignStyle; import java.util.Date; import static java.time.temporal.ChronoField.*; @Service public class SerialNumberService { private final Logger logger = LoggerFactory.getLogger(SerialNumberService.class); private static final DateTimeFormatter LOCAL_DATETIME_FORMATTER = new DateTimeFormatterBuilder() .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD) .appendValue(MONTH_OF_YEAR, 2) .appendValue(DAY_OF_MONTH, 2) .appendValue(HOUR_OF_DAY, 2) .appendValue(MINUTE_OF_HOUR, 2) .appendValue(SECOND_OF_MINUTE, 2) .toFormatter(); @Autowired(required = false) private RedisTemplate redisTemplate; /** * 定义流水号工单默认前缀 */ private static final String SERIAL_NUMBER = "serial:generator:"; /** * 生成业务流水单号 * * @param bizCode 业务前缀代码 * @param serialNumLength 流水号位数 * @return */ public String generate(String bizCode, int serialNumLength) { Assert.isTrue(StringUtils.isNotBlank(bizCode), "流水号业务类型不能为空"); LocalDateTime now = LocalDateTime.now(); //构造redis的key String key = SERIAL_NUMBER + ":" + bizCode; //判断key是否存在 Boolean exists = redisTemplate.hasKey(key); Long incr = redisTemplate.opsForValue().increment(key, 1); if (incr <= 0 || incr >= Math.pow(10, serialNumLength)) { logger.debug("Resetting Redis serial number to " + incr + " of " + key); incr = 1L; redisTemplate.opsForValue().set(key, incr); } //设置过期时间 if (!exists) { //构造redis过期时间 UnixMillis //设置过期时间为当天的最后一秒 LocalTime time = LocalTime.of(23, 59, 59); LocalDateTime expireAt = LocalDateTime.of(now.toLocalDate(), time); ZoneId zone = ZoneId.systemDefault(); Instant instant = expireAt.atZone(zone).toInstant(); redisTemplate.expireAt(key, Date.from(instant)); } //默认编码需要5位,位数不够前面补0 String formattNum = String.format("%0" + serialNumLength + "d", incr); StringBuilder sb = new StringBuilder(20); //获取当前时间,返回格式字符串 String date = now.format(LOCAL_DATETIME_FORMATTER); //转换成业务需要的格式 bizCode + date + incr sb.append(bizCode).append(date).append(formattNum); return sb.toString(); } }
92302736cfa12595622f94a51ec8ffe45397ebf5
1,501
java
Java
src/com/chenjin/smis/util/DruidUtils.java
Tremble666/Face-Recognition
62931caf7e4ad31d51aa3f8327e2e662eb5e0999
[ "MIT" ]
2
2018-09-14T08:34:32.000Z
2021-12-13T12:15:36.000Z
src/com/chenjin/smis/util/DruidUtils.java
Tremble666/Face-Recognition
62931caf7e4ad31d51aa3f8327e2e662eb5e0999
[ "MIT" ]
null
null
null
src/com/chenjin/smis/util/DruidUtils.java
Tremble666/Face-Recognition
62931caf7e4ad31d51aa3f8327e2e662eb5e0999
[ "MIT" ]
null
null
null
20.847222
73
0.67022
995,378
package com.chenjin.smis.util; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Properties; import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; public class DruidUtils { private static Properties pro = new Properties(); private static DataSource ds = null; private DruidUtils() { }; static { ClassLoader cl = Thread.currentThread().getContextClassLoader(); InputStream in = null; try { in = cl.getResourceAsStream("Druid.properties"); pro.load(in); //ds = BasicDataSourceFactory.createDataSource(pro); ds = DruidDataSourceFactory.createDataSource(pro); } catch (Exception e1) { throw new RuntimeException("读取配置文件出现异常"); } } public static Connection getConn() { try { return ds.getConnection(); } catch (Exception e) { e.printStackTrace(); } throw new RuntimeException("数据库连接异�?"); } public static void close(Connection conn, Statement sta, ResultSet rs) { try { if (conn != null) { conn.close(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (sta != null) { sta.close(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } } catch (Exception e) { e.printStackTrace(); } } } } }
9230284d88f11d97695e252146313764a2a420fa
3,515
java
Java
src/application/math/Vector2.java
Minitte/ozma-engine
09d382d457e78ecfbcbcbc245a1040b0fa5b3eab
[ "MIT" ]
null
null
null
src/application/math/Vector2.java
Minitte/ozma-engine
09d382d457e78ecfbcbcbc245a1040b0fa5b3eab
[ "MIT" ]
null
null
null
src/application/math/Vector2.java
Minitte/ozma-engine
09d382d457e78ecfbcbcbc245a1040b0fa5b3eab
[ "MIT" ]
null
null
null
17.063107
86
0.607966
995,379
package application.math; public class Vector2 { private float x, y; /** * Default constructor */ public Vector2() { } /** * Constructor * @param x * @param y */ public Vector2(float x, float y) { super(); this.x = x; this.y = y; } /** * Dot product operation between this and the other vector * @param other * @return */ public float dot(Vector2 other) { return (x * other.x) + (y * other.y); } /** * Adds another vector to this vector * @param other * @return returns itself to allow chains of operations */ public Vector2 add(Vector2 other) { x += other.x; y += other.y; return this; } /** * Minus another vector to this vector * @param other * @return returns itself to allow chains of operations */ public Vector2 minus(Vector2 other) { x -= other.x; y -= other.y; return this; } /** * Reduces x and y by the amount of x and y of other. * The reduction is in the direction of zero if values are positive. * Negatives will have an opposite effect of getting further away from zero * @param other * @return returns itself to allow chains of operations */ public Vector2 reduce(Vector2 other) { if (x > 0) { x -= other.x; } else if (x < 0) { x += other.x; } if (y > 0) { y -= other.y; } else if (y < 0) { y += other.y; } return this; } /** * multiplies both x and y with the given scale factor * @param scale * @return returns itself to allow chains of operations */ public Vector2 linearMutliply(float scale) { x *= scale; y *= scale; return this; } /** * multiplies both x and y with the x and y in other * @param other * @return returns itself to allow chains of operations */ public Vector2 multiply(Vector2 other) { x *= other.x; y *= other.y; return this; } /** * divdes both x and y by the given denominator * @param denominator * @return returns itself to allow chains of operations */ public Vector2 linearDivide(float denominator) { x /= denominator; y /= denominator; return this; } /** * divides both x and y by the x and y in other * @param other * @return returns itself to allow chains of operations */ public Vector2 divide(Vector2 other) { x /= other.x; y /= other.y; return this; } /** * Creates a new vector2 with the same values */ public Vector2 clone() { return new Vector2(x, y); } /** * Creates a new vector representing the normal * @return */ public Vector2 getNormal() { return new Vector2(-y, x); } /** * makes the length to 1 * @return returns itself to allow chains of operations */ public Vector2 Normalize() { float len = getLength(); linearDivide(len); return this; } /** * the length of the vector by calculating the hypotenuse * @return */ public float getLength() { return (float)Math.sqrt((x * x) + (y * y)); } /** * the length of the vector by calculating the hypotenuse without doing the sqrt step * @return */ public float getLengthSquared() { return (x * x) + (y * y); } /** * @return the x */ public float getX() { return x; } /** * @param x the x to set */ public void setX(float x) { this.x = x; } /** * @return the y */ public float getY() { return y; } /** * @param y the y to set */ public void setY(float y) { this.y = y; } @Override public String toString() { return String.format("Vector2[%f, %f]", x, y); } }
9230284fbbbb3ec7eee4a9ef91e4e63829cae00f
2,237
java
Java
app/src/main/java/com/raslib/rasdroid/DataManager.java
antoninhrlt/rasdroid
6a3eaf05dd1411ea3e77bcc98c5a1b9f22bc49b3
[ "MIT" ]
null
null
null
app/src/main/java/com/raslib/rasdroid/DataManager.java
antoninhrlt/rasdroid
6a3eaf05dd1411ea3e77bcc98c5a1b9f22bc49b3
[ "MIT" ]
null
null
null
app/src/main/java/com/raslib/rasdroid/DataManager.java
antoninhrlt/rasdroid
6a3eaf05dd1411ea3e77bcc98c5a1b9f22bc49b3
[ "MIT" ]
null
null
null
30.643836
103
0.581582
995,380
package com.raslib.rasdroid; import android.content.Context; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Data Manager class to get/save data in file */ public class DataManager { /** * Save data in file from filename and Application context * @param filename - File to save data * @param object - Data to save * @param context - Application context */ public static void saveData(String filename, Object object, Context context) { try { FileOutputStream fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); ObjectOutputStream outputStream; try { outputStream = new ObjectOutputStream(fileOutputStream); outputStream.writeObject(object); outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * Get data in file from filename and Application context * @param filename - File to get data * @param context - Application context * @return object - retrieved data - returns null on error */ public static Object getData(String filename, Context context) { try { FileInputStream fileInputStream = context.openFileInput(filename); ObjectInputStream inputStream; try { inputStream = new ObjectInputStream(fileInputStream); try { Object object = inputStream.readObject(); inputStream.close(); return object; } catch (ClassNotFoundException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } }
9230285cf8f0492d64ec427467b756278cb8229b
2,475
java
Java
compiler/src/main/java/net/jbock/context/OptionStatesMethod.java
h908714124/jbock
0b2316778e971672e0c97cd6f963eee1f85e985a
[ "MIT" ]
45
2017-04-24T11:05:53.000Z
2021-05-09T21:27:00.000Z
compiler/src/main/java/net/jbock/context/OptionStatesMethod.java
h908714124/jbock
0b2316778e971672e0c97cd6f963eee1f85e985a
[ "MIT" ]
10
2017-05-28T15:35:50.000Z
2021-05-09T14:40:50.000Z
compiler/src/main/java/net/jbock/context/OptionStatesMethod.java
h908714124/jbock
0b2316778e971672e0c97cd6f963eee1f85e985a
[ "MIT" ]
4
2019-05-21T09:12:04.000Z
2020-11-12T14:21:45.000Z
36.397059
124
0.690909
995,381
package net.jbock.context; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import net.jbock.annotated.AnnotatedOption; import net.jbock.convert.Mapping; import net.jbock.parse.OptionState; import net.jbock.parse.OptionStateModeFlag; import net.jbock.parse.OptionStateNonRepeatable; import net.jbock.parse.OptionStateRepeatable; import net.jbock.processor.SourceElement; import javax.inject.Inject; import java.util.EnumMap; import java.util.List; import static javax.lang.model.element.Modifier.PRIVATE; import static net.jbock.common.Constants.mapOf; @ContextScope public final class OptionStatesMethod extends Cached<MethodSpec> { private final List<Mapping<AnnotatedOption>> namedOptions; private final SourceElement sourceElement; private final CommonFields commonFields; @Inject OptionStatesMethod( List<Mapping<AnnotatedOption>> namedOptions, SourceElement sourceElement, CommonFields commonFields) { this.namedOptions = namedOptions; this.sourceElement = sourceElement; this.commonFields = commonFields; } @Override MethodSpec define() { ParameterSpec result = ParameterSpec.builder( mapOf(commonFields.optType(), ClassName.get(OptionState.class)), "result").build(); CodeBlock.Builder code = CodeBlock.builder(); code.addStatement("$T $N = new $T<>($T.class)", result.type, result, EnumMap.class, sourceElement.optionEnumType()); for (Mapping<AnnotatedOption> namedOption : namedOptions) { code.addStatement("$N.put($T.$L, new $T())", result, sourceElement.optionEnumType(), namedOption.enumName(), optionParserType(namedOption)); } code.addStatement("return $N", result); return MethodSpec.methodBuilder("optionStates") .addCode(code.build()) .returns(result.type) .addModifiers(PRIVATE) .build(); } private ClassName optionParserType(Mapping<AnnotatedOption> param) { if (param.isRepeatable()) { return ClassName.get(OptionStateRepeatable.class); } if (param.isModeFlag()) { return ClassName.get(OptionStateModeFlag.class); } return ClassName.get(OptionStateNonRepeatable.class); } }
923028ea9c8566120ab460cf05340ecada83754b
3,348
java
Java
server/src/com/desertkun/brainout/bot/TaskDestroyBlocks.java
artemking4/brainout
ee8d26d53c6fadaca3bc48d89b1d227650e9bba4
[ "MIT" ]
31
2022-03-20T18:52:44.000Z
2022-03-28T17:40:28.000Z
server/src/com/desertkun/brainout/bot/TaskDestroyBlocks.java
artemking4/brainout
ee8d26d53c6fadaca3bc48d89b1d227650e9bba4
[ "MIT" ]
4
2022-03-21T19:23:21.000Z
2022-03-30T04:48:20.000Z
server/src/com/desertkun/brainout/bot/TaskDestroyBlocks.java
artemking4/brainout
ee8d26d53c6fadaca3bc48d89b1d227650e9bba4
[ "MIT" ]
15
2022-03-20T23:34:29.000Z
2022-03-31T11:31:45.000Z
25.557252
113
0.507168
995,382
package com.desertkun.brainout.bot; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Queue; import com.desertkun.brainout.Constants; import com.desertkun.brainout.data.Map; import com.desertkun.brainout.data.WayPointMap; import com.desertkun.brainout.data.block.BlockData; import com.desertkun.brainout.utils.RandomValue; public class TaskDestroyBlocks extends Task { private final RandomValue fireTime; private final RandomValue firePauseTime; private float timer; private final Queue<WayPointMap.BlockCoordinates> blocks; private float fireTimer, firePauseTimer; public TaskDestroyBlocks(TaskStack stack, Queue<WayPointMap.BlockCoordinates> blocks) { super(stack); this.blocks = blocks; this.fireTime = new RandomValue(0.5f, 1.0f); this.firePauseTime = new RandomValue(0.25f, 0.5f); } @Override protected void update(float dt) { timer -= dt; if (timer > 0) return; timer = 0.1f; getController().stopFollowing(); if (checkWeapons(false)) return; setAim(true); openFire(false); for (WayPointMap.BlockCoordinates block : blocks) { BlockData blockData = getMap().getBlock(block.x, block.y, Constants.Layers.BLOCK_LAYER_FOREGROUND); if (blockData == null) continue; float dst2 = Vector2.dst2(getPlayerData().getX(), getPlayerData().getY(), block.x, block.y); float randomness; if (dst2 > 8 * 8) { randomness = 1.5f; } else if (dst2 > 4 * 4) { randomness = 0.5f; } else { randomness = 0.25f; } if (!getController().checkVisibility(block.x + 0.5f, block.y + 0.5f, this::checkBlock)) { pop(); return; } float targetX = block.x + 0.5f, targetY = block.y + 0.5f + MathUtils.random(-randomness, randomness); if (getController().lerpAngle(targetX, targetY)) { fireTimer -= dt; if (fireTimer <= 0) { if (fireTimer < -firePauseTimer) { resetTimers(); openFire(true); } else { openFire(false); } } else { openFire(true); } } else { openFire(false); } return; } openFire(false); setAim(false); pop(); } private boolean checkBlock(int blockX, int blockY) { for (WayPointMap.BlockCoordinates coordinates : blocks) { if (blockX == coordinates.x && blockY == coordinates.y) { return false; } } return true; } private void resetTimers() { this.fireTimer = fireTime.getValue(); this.firePauseTimer = firePauseTime.getValue(); } }
923029c976c57bf8991ddcc70f0d21da50cb2984
1,095
java
Java
app/src/main/java/namofo/org/jiesehelper/adapter/ArticlePagerAdapter.java
zhengjiong/JieSeHelper
e52a71380ed19c9c82615dfbf35dcee553a57e67
[ "Apache-2.0" ]
null
null
null
app/src/main/java/namofo/org/jiesehelper/adapter/ArticlePagerAdapter.java
zhengjiong/JieSeHelper
e52a71380ed19c9c82615dfbf35dcee553a57e67
[ "Apache-2.0" ]
null
null
null
app/src/main/java/namofo/org/jiesehelper/adapter/ArticlePagerAdapter.java
zhengjiong/JieSeHelper
e52a71380ed19c9c82615dfbf35dcee553a57e67
[ "Apache-2.0" ]
null
null
null
25.465116
109
0.678539
995,383
package namofo.org.jiesehelper.adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import java.util.ArrayList; import java.util.List; import namofo.org.jiesehelper.bean.ArticleCategory; /** * create by zhengjiong * Date: 2015-06-13 * Time: 22:57 */ public class ArticlePagerAdapter extends FragmentPagerAdapter { private List<ArticleCategory> mTitles = new ArrayList<>(); private List<Fragment> mFragments = new ArrayList<>(); public ArticlePagerAdapter(FragmentManager fm, List<ArticleCategory> titles, List<Fragment> fragments) { super(fm); this.mTitles = titles; this.mFragments = fragments; } @Override public Fragment getItem(int position) { return mFragments.get(position); } @Override public int getCount() { return mTitles.size(); } @Override public CharSequence getPageTitle(int position) { return mTitles.get(position).getName(); } }
92302a267cafdda979334f0ff46f60287476ff06
695
java
Java
updater/testSrc/com/intellij/updater/RunnerTest.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
updater/testSrc/com/intellij/updater/RunnerTest.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
173
2018-07-05T13:59:39.000Z
2018-08-09T01:12:03.000Z
updater/testSrc/com/intellij/updater/RunnerTest.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
2
2020-03-15T08:57:37.000Z
2020-04-07T04:48:14.000Z
43.4375
140
0.723741
995,384
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.updater; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class RunnerTest { @Test public void testExtractingFiles() { String[] args = {"bar", "ignored=xxx;yyy;zzz/zzz", "critical=", "ignored=aaa", "baz", "critical=ccc"}; assertThat(Runner.extractArguments(args, "ignored")).containsExactly("xxx", "yyy", "zzz/zzz", "aaa"); assertThat(Runner.extractArguments(args, "critical")).containsExactly("ccc"); assertThat(Runner.extractArguments(args, "unknown")).isEmpty(); } }
92302a5a3eb7c21d98e8107d8425bf4f6db74ce8
802
java
Java
src/premon/PremonPatDots.java
asajeffrey/asaj.org
e50bcbdf91d668b2a240eec84f2649ac5fe85c9b
[ "CC0-1.0" ]
null
null
null
src/premon/PremonPatDots.java
asajeffrey/asaj.org
e50bcbdf91d668b2a240eec84f2649ac5fe85c9b
[ "CC0-1.0" ]
null
null
null
src/premon/PremonPatDots.java
asajeffrey/asaj.org
e50bcbdf91d668b2a240eec84f2649ac5fe85c9b
[ "CC0-1.0" ]
null
null
null
20.05
67
0.5798
995,385
/** * A pattern (<i>p</i><code>...</code><i>q</i>). * This has no categorical significance, but is used to draw graphs * containing ellipses. * @author Alan Jeffrey * @version v1.0 1998/06/03 */ public class PremonPatDots extends PremonPat { private PremonPat P; private PremonPat Q; /** * The pattern <i>P</i><code>...</code><i>Q</i>. * @param P the lh pattern * @param Q the rh pattern */ public PremonPatDots (PremonPat P, PremonPat Q) { this.P = P; this.Q = Q; type = new PremonTypeDots (P.type, Q.type); bind = P.bind.comp (Q.bind); } public void print (Printer p) { p.printString ("("); p.print (P); p.printString (" ... "); p.print (Q); p.printString (")"); } public void printB (Printer p) { print (p); } }
92302bee61a5a30188ed9e9dfb9de5ed0f0fce84
1,398
java
Java
hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/bulk/imprt/model/ParsedBulkImportRecord.java
ShahimEssaid/hapi-fhir
06030094c803deac725be5bf63e4d1ce7bb26b6d
[ "Apache-2.0" ]
1,194
2015-01-01T23:22:15.000Z
2020-12-12T19:27:42.000Z
hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/bulk/imprt/model/ParsedBulkImportRecord.java
ShahimEssaid/hapi-fhir
06030094c803deac725be5bf63e4d1ce7bb26b6d
[ "Apache-2.0" ]
1,994
2015-01-04T10:06:26.000Z
2020-12-13T22:19:41.000Z
hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/bulk/imprt/model/ParsedBulkImportRecord.java
ShahimEssaid/hapi-fhir
06030094c803deac725be5bf63e4d1ce7bb26b6d
[ "Apache-2.0" ]
1,088
2015-01-04T19:31:43.000Z
2020-12-12T20:56:04.000Z
26.377358
101
0.748927
995,386
package ca.uhn.fhir.jpa.bulk.imprt.model; /*- * #%L * HAPI FHIR Storage api * %% * Copyright (C) 2014 - 2022 Smile CDR, 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. * #L% */ import org.hl7.fhir.instance.model.api.IBaseResource; import java.io.Serializable; public class ParsedBulkImportRecord implements Serializable { private static final long serialVersionUID = 1L; private final String myTenantName; private final IBaseResource myRowContent; private final int myLineIndex; public ParsedBulkImportRecord(String theTenantName, IBaseResource theRowContent, int theLineIndex) { myTenantName = theTenantName; myRowContent = theRowContent; myLineIndex = theLineIndex; } public int getLineIndex() { return myLineIndex; } public String getTenantName() { return myTenantName; } public IBaseResource getRowContent() { return myRowContent; } }
92302c2c7f42314f831ddce36a97f24283d7ea44
7,408
java
Java
core/src/test/java/org/apache/calcite/test/catalog/Fixture.java
sreev/incubator-calcite
fbe69824ffb13f847d1db6e26f0030ddec7b0e8c
[ "Apache-2.0" ]
2,984
2015-10-29T03:04:33.000Z
2022-03-31T09:56:30.000Z
core/src/test/java/org/apache/calcite/test/catalog/Fixture.java
sreev/incubator-calcite
fbe69824ffb13f847d1db6e26f0030ddec7b0e8c
[ "Apache-2.0" ]
1,374
2015-10-28T03:21:38.000Z
2022-03-30T06:23:43.000Z
core/src/test/java/org/apache/calcite/test/catalog/Fixture.java
sreev/incubator-calcite
fbe69824ffb13f847d1db6e26f0030ddec7b0e8c
[ "Apache-2.0" ]
1,736
2015-10-27T20:18:37.000Z
2022-03-31T06:37:04.000Z
43.83432
92
0.731506
995,387
/* * 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.calcite.test.catalog; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeComparability; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.rel.type.RelDataTypeFieldImpl; import org.apache.calcite.rel.type.StructKind; import org.apache.calcite.sql.SqlIdentifier; import org.apache.calcite.sql.parser.SqlParserPos; import org.apache.calcite.sql.type.ObjectSqlType; import org.apache.calcite.sql.type.SqlTypeName; import java.util.Arrays; /** Types used during initialization. */ final class Fixture extends AbstractFixture { final RelDataType intType = sqlType(SqlTypeName.INTEGER); final RelDataType intTypeNull = nullable(intType); final RelDataType bigintType = sqlType(SqlTypeName.BIGINT); final RelDataType decimalType = sqlType(SqlTypeName.DECIMAL); final RelDataType varcharType = sqlType(SqlTypeName.VARCHAR); final RelDataType varcharTypeNull = nullable(varcharType); final RelDataType varchar5Type = sqlType(SqlTypeName.VARCHAR, 5); final RelDataType varchar10Type = sqlType(SqlTypeName.VARCHAR, 10); final RelDataType varchar10TypeNull = nullable(varchar10Type); final RelDataType varchar20Type = sqlType(SqlTypeName.VARCHAR, 20); final RelDataType varchar20TypeNull = nullable(varchar20Type); final RelDataType timestampType = sqlType(SqlTypeName.TIMESTAMP); final RelDataType timestampTypeNull = nullable(timestampType); final RelDataType dateType = sqlType(SqlTypeName.DATE); final RelDataType booleanType = sqlType(SqlTypeName.BOOLEAN); final RelDataType booleanTypeNull = nullable(booleanType); final RelDataType rectilinearCoordType = typeFactory.builder() .add("X", intType) .add("Y", intType) .build(); final RelDataType rectilinearPeekCoordType = typeFactory.builder() .add("X", intType) .add("Y", intType) .add("unit", varchar20Type) .kind(StructKind.PEEK_FIELDS) .build(); final RelDataType rectilinearPeekCoordMultisetType = typeFactory.createMultisetType(rectilinearPeekCoordType, -1); final RelDataType rectilinearPeekNoExpandCoordType = typeFactory.builder() .add("M", intType) .add("SUB", typeFactory.builder() .add("A", intType) .add("B", intType) .kind(StructKind.PEEK_FIELDS_NO_EXPAND) .build()) .kind(StructKind.PEEK_FIELDS_NO_EXPAND) .build(); final RelDataType abRecordType = typeFactory.builder() .add("A", varchar10Type) .add("B", varchar10Type) .build(); final RelDataType skillRecordType = typeFactory.builder() .add("TYPE", varchar10Type) .add("DESC", varchar20Type) .add("OTHERS", abRecordType) .build(); final RelDataType empRecordType = typeFactory.builder() .add("EMPNO", intType) .add("ENAME", varchar10Type) .add("DETAIL", typeFactory.builder() .add("SKILLS", array(skillRecordType)).build()) .kind(StructKind.PEEK_FIELDS) .build(); final RelDataType empListType = array(empRecordType); final ObjectSqlType addressType = new ObjectSqlType(SqlTypeName.STRUCTURED, new SqlIdentifier("ADDRESS", SqlParserPos.ZERO), false, Arrays.asList( new RelDataTypeFieldImpl("STREET", 0, varchar20Type), new RelDataTypeFieldImpl("CITY", 1, varchar20Type), new RelDataTypeFieldImpl("ZIP", 2, intType), new RelDataTypeFieldImpl("STATE", 3, varchar20Type)), RelDataTypeComparability.NONE); // Row(f0 int, f1 varchar) final RelDataType recordType1 = typeFactory.createStructType( Arrays.asList(intType, varcharType), Arrays.asList("f0", "f1")); // Row(f0 int not null, f1 varchar null) final RelDataType recordType2 = typeFactory.createStructType( Arrays.asList(intType, nullable(varcharType)), Arrays.asList("f0", "f1")); // Row(f0 Row(ff0 int not null, ff1 varchar null) null, f1 timestamp not null) final RelDataType recordType3 = typeFactory.createStructType( Arrays.asList( nullable( typeFactory.createStructType(Arrays.asList(intType, varcharTypeNull), Arrays.asList("ff0", "ff1"))), timestampType), Arrays.asList("f0", "f1")); // Row(f0 bigint not null, f1 decimal null) array final RelDataType recordType4 = array( typeFactory.createStructType( Arrays.asList(bigintType, nullable(decimalType)), Arrays.asList("f0", "f1"))); // Row(f0 varchar not null, f1 timestamp null) multiset final RelDataType recordType5 = typeFactory.createMultisetType( typeFactory.createStructType( Arrays.asList(varcharType, timestampTypeNull), Arrays.asList("f0", "f1")), -1); final RelDataType intArrayType = array(intType); final RelDataType varchar5ArrayType = array(varchar5Type); final RelDataType intArrayArrayType = array(intArrayType); final RelDataType varchar5ArrayArrayType = array(varchar5ArrayType); final RelDataType intMultisetType = typeFactory.createMultisetType(intType, -1); final RelDataType varchar5MultisetType = typeFactory.createMultisetType(varchar5Type, -1); final RelDataType intMultisetArrayType = array(intMultisetType); final RelDataType varchar5MultisetArrayType = array(varchar5MultisetType); final RelDataType intArrayMultisetType = typeFactory.createMultisetType(intArrayType, -1); // Row(f0 int array multiset, f1 varchar(5) array) array multiset final RelDataType rowArrayMultisetType = typeFactory.createMultisetType( array( typeFactory.createStructType( Arrays.asList(intArrayMultisetType, varchar5ArrayType), Arrays.asList("f0", "f1"))), -1); Fixture(RelDataTypeFactory typeFactory) { super(typeFactory); } private RelDataType nullable(RelDataType type) { return typeFactory.createTypeWithNullability(type, true); } private RelDataType sqlType(SqlTypeName typeName, int... args) { assert args.length < 3 : "unknown size of additional int args"; return args.length == 2 ? typeFactory.createSqlType(typeName, args[0], args[1]) : args.length == 1 ? typeFactory.createSqlType(typeName, args[0]) : typeFactory.createSqlType(typeName); } private RelDataType array(RelDataType type) { return typeFactory.createArrayType(type, -1); } } /** * Just a little trick to store factory ref before field init in fixture. */ abstract class AbstractFixture { final RelDataTypeFactory typeFactory; AbstractFixture(RelDataTypeFactory typeFactory) { this.typeFactory = typeFactory; } }
92302c61562e3494871dada801160823ffa95fc5
1,589
java
Java
bankdroid-legacy/src/main/java/eu/nullbyte/android/urllib/CertPinningTrustManager.java
DanielNgandu/android-bankdroid-master
34cbecdf3d9100bdeb896a6930614a8955612e4b
[ "Apache-2.0" ]
85
2015-01-02T10:55:43.000Z
2022-02-05T11:58:33.000Z
bankdroid-legacy/src/main/java/eu/nullbyte/android/urllib/CertPinningTrustManager.java
DanielNgandu/android-bankdroid-master
34cbecdf3d9100bdeb896a6930614a8955612e4b
[ "Apache-2.0" ]
309
2015-01-07T07:31:30.000Z
2021-10-17T12:23:03.000Z
bankdroid-legacy/src/main/java/eu/nullbyte/android/urllib/CertPinningTrustManager.java
DanielNgandu/android-bankdroid-master
34cbecdf3d9100bdeb896a6930614a8955612e4b
[ "Apache-2.0" ]
99
2015-01-30T10:51:27.000Z
2022-03-24T03:32:57.000Z
31.78
87
0.672121
995,388
package eu.nullbyte.android.urllib; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Arrays; import javax.net.ssl.X509TrustManager; public class CertPinningTrustManager implements X509TrustManager { private Certificate[] certificates; private String host; public CertPinningTrustManager(Certificate[] certificates, String host) { this.certificates = certificates; this.host = host; } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { throw new CertificateException("Client authentication not implemented."); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { for (X509Certificate certificate : chain) { byte[] publicKey = certificate.getPublicKey().getEncoded(); for (Certificate pinnedCert : certificates) { if (Arrays.equals(publicKey, pinnedCert.getPublicKey().getEncoded())) { return; } } } throw new CertificateException(host == null ? "Server certificate not trusted." : String.format("Server certificate not trusted for host: %s.", host)); } public void setHost(String host) { this.host = host; } }
92302d4a9b2775a99e5b979d9e05b9e217847310
1,119
java
Java
java/brusselnieuws-rss/brusselnieuws-rss-datastore-model/src/test/java/be/seriousbusiness/brusselnieuws/rss/datastore/model/dto/impl/AuthorDTOImplTest.java
seriousbusinessbe/java-brusselnieuws-rss
a18183e1122fce6f5389446b096085ff081b98c3
[ "MIT" ]
null
null
null
java/brusselnieuws-rss/brusselnieuws-rss-datastore-model/src/test/java/be/seriousbusiness/brusselnieuws/rss/datastore/model/dto/impl/AuthorDTOImplTest.java
seriousbusinessbe/java-brusselnieuws-rss
a18183e1122fce6f5389446b096085ff081b98c3
[ "MIT" ]
null
null
null
java/brusselnieuws-rss/brusselnieuws-rss-datastore-model/src/test/java/be/seriousbusiness/brusselnieuws/rss/datastore/model/dto/impl/AuthorDTOImplTest.java
seriousbusinessbe/java-brusselnieuws-rss
a18183e1122fce6f5389446b096085ff081b98c3
[ "MIT" ]
null
null
null
28.692308
133
0.772118
995,389
package be.seriousbusiness.brusselnieuws.rss.datastore.model.dto.impl; import java.math.BigInteger; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import be.seriousbusiness.brusselnieuws.rss.datastore.model.dto.AbstractAuthorDTOTest; /** * {@link AuthorDTOImpl} test implementation. * @author Serious Business * @author Stefan Borghys * @version 1.0 * @since 1.0 */ public class AuthorDTOImplTest extends AbstractAuthorDTOTest<AuthorDTOImpl> { public AuthorDTOImplTest() { super(BigInteger.valueOf(121121121l),"© brusselnieuws.be"); } @Override public AuthorDTOImpl create() { return new AuthorDTOImpl.Builder().build(); } @Ignore @Test public void testCLoneable() { final AuthorDTOImpl clonedAuthorDTOImpl=(AuthorDTOImpl) getDTO().clone(); Assert.assertEquals("The clone should be equal to the one it's cloned from",getDTO(),clonedAuthorDTOImpl); clonedAuthorDTOImpl.setName(String.valueOf(System.currentTimeMillis())); Assert.assertNotEquals("The clone should not be equal to the one it's cloned from after altering it",getDTO(),clonedAuthorDTOImpl); } }
92302d859333238ee317fb71666e6f0b07e8b353
2,528
java
Java
tesuto-placement-services/tesuto-placement-core/src/main/java/org/cccnext/tesuto/placement/repository/jpa/PlacementRepository.java
apereo-tesuto/tesuto
90ed26311b1baa15cd90d67bb55e7d4c613bdc53
[ "Apache-2.0" ]
4
2020-06-17T16:44:40.000Z
2020-08-20T18:36:40.000Z
tesuto-placement-services/tesuto-placement-core/src/main/java/org/cccnext/tesuto/placement/repository/jpa/PlacementRepository.java
apereo-tesuto/tesuto
90ed26311b1baa15cd90d67bb55e7d4c613bdc53
[ "Apache-2.0" ]
1
2020-12-22T20:56:35.000Z
2020-12-22T20:56:35.000Z
tesuto-placement-services/tesuto-placement-core/src/main/java/org/cccnext/tesuto/placement/repository/jpa/PlacementRepository.java
apereo-tesuto/tesuto
90ed26311b1baa15cd90d67bb55e7d4c613bdc53
[ "Apache-2.0" ]
1
2019-11-21T21:04:26.000Z
2019-11-21T21:04:26.000Z
42.847458
115
0.738133
995,390
/******************************************************************************* * Copyright © 2019 by California Community Colleges Chancellor's Office * * 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.cccnext.tesuto.placement.repository.jpa; import java.util.Collection; import org.cccnext.tesuto.placement.model.Placement; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; // NOTE: Placements are not audited since they are immutable public interface PlacementRepository extends JpaRepository<Placement, String> { Collection<Placement> findByCccid(String cccid); Placement findByCccidAndCreatedOnIsNull(String cccid); @Query("from Placement pl join fetch pl.placementComponents where pl.id = ?1") Placement getOneWithComponents(String placementId); Collection<Placement> findByCollegeId(String misCode); Collection<Placement> findByCollegeIdAndCccid(String misCode, String cccid); Collection<Placement> findByCollegeIdAndCccidAndDisciplineId(String misCode, String cccid, Integer disciplineId); @Modifying @Query("update Placement set isAssigned = false where cccid = ?1 and collegeId = ?2 and disciplineId = ?3 ") void unassignPlacementForStudentAndCollegeIdAndDisciplineId(String cccid, String collegeId, Integer disciplineId); @Modifying @Query("update Placement set isAssigned = true where id = ?1") void assignPlacement(String placementId); // TODO: after upgrading to Spring Data JPA 1.11, we can remove that annotation @Query(nativeQuery=true, value="select exists(select 1 from Placement p where p.college_id = ?1)") boolean existsByCollegeId(String collegeId); // TODO: after upgrading to Spring Data JPA 1.11, we can remove that annotation @Modifying @Query("delete from Placement p where p.collegeId = ?1") int deleteByCollegeId(String collegeId); }
92302eaef2168646e3635a7729b7a06f5ebddfce
404
java
Java
app/src/main/java/com/devband/tronwalletforandroid/ui/token/transfer/TransferModule.java
lky1001/tron-android-wallet
571f30591108fd3d91308d26a0a0f5837732bb76
[ "Apache-2.0" ]
33
2018-06-01T10:56:06.000Z
2022-03-26T23:20:10.000Z
app/src/main/java/com/devband/tronwalletforandroid/ui/token/transfer/TransferModule.java
kqtqk93/tron-android-wallet
571f30591108fd3d91308d26a0a0f5837732bb76
[ "Apache-2.0" ]
28
2018-04-15T08:53:20.000Z
2019-06-27T11:11:03.000Z
app/src/main/java/com/devband/tronwalletforandroid/ui/token/transfer/TransferModule.java
kqtqk93/tron-android-wallet
571f30591108fd3d91308d26a0a0f5837732bb76
[ "Apache-2.0" ]
21
2018-04-25T01:56:01.000Z
2021-10-18T07:10:30.000Z
28.857143
73
0.831683
995,391
package com.devband.tronwalletforandroid.ui.token.transfer; import com.devband.tronwalletforandroid.di.FragmentScoped; import dagger.Module; import dagger.android.ContributesAndroidInjector; @Module public abstract class TransferModule { @FragmentScoped @ContributesAndroidInjector(modules = {TransferFragmentModule.class}) public abstract TransferFragment contributeTransferFragment(); }
9230300a380c8960904f12f23aa48ffb3329cc7d
2,798
java
Java
app/src/main/java/com/example/hbhims/model/entity/CustomSysUserProfessional.java
1962247851/hbhims_android
840545aeac2d70bd1311b5b229ba4c37e32267e1
[ "MIT" ]
2
2020-09-14T09:02:07.000Z
2021-04-20T07:49:25.000Z
app/src/main/java/com/example/hbhims/model/entity/CustomSysUserProfessional.java
1962247851/hbhims_android
840545aeac2d70bd1311b5b229ba4c37e32267e1
[ "MIT" ]
null
null
null
app/src/main/java/com/example/hbhims/model/entity/CustomSysUserProfessional.java
1962247851/hbhims_android
840545aeac2d70bd1311b5b229ba4c37e32267e1
[ "MIT" ]
1
2021-08-14T09:02:22.000Z
2021-08-14T09:02:22.000Z
28.845361
122
0.686562
995,392
package com.example.hbhims.model.entity; import androidx.annotation.NonNull; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.example.hbhims.model.common.Constant; import com.example.hbhims.model.common.entity.JsonResult; import com.example.hbhims.model.common.util.http.Http; import com.example.hbhims.model.common.util.http.HttpCallBack; import com.example.hbhims.model.common.util.http.RequestCallBack; import com.youth.xframe.utils.XNetworkUtils; import org.jetbrains.annotations.NotNull; import java.util.List; /** * 用于查询所有专业人员 * * @author qq1962247851 * @date 2020/5/10 14:24 */ public class CustomSysUserProfessional { private Long id; private String username; private Double meanEvaluationScore; private Integer totalSuggestionCount; public CustomSysUserProfessional() { } public CustomSysUserProfessional(Long id, String username, Double meanEvaluationScore, Integer totalSuggestionCount) { this.id = id; this.username = username; this.meanEvaluationScore = meanEvaluationScore; this.totalSuggestionCount = totalSuggestionCount; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Double getMeanEvaluationScore() { return meanEvaluationScore; } public void setMeanEvaluationScore(Double meanEvaluationScore) { this.meanEvaluationScore = meanEvaluationScore; } public Integer getTotalSuggestionCount() { return totalSuggestionCount; } public void setTotalSuggestionCount(Integer totalSuggestionCount) { this.totalSuggestionCount = totalSuggestionCount; } @NonNull @Override public String toString() { return JSONObject.toJSONString(this); } public static void queryAll(RequestCallBack<List<CustomSysUserProfessional>> requestCallBack) { if (XNetworkUtils.isAvailable()) { Http.obtain().get(Constant.USER_QUERY_ALL_PROFESSIONAL, null, new HttpCallBack<JsonResult<JSONArray>>() { @Override public void onSuccess(@NotNull JsonResult<JSONArray> jsonArrayJsonResult) { requestCallBack.onSuccess(jsonArrayJsonResult.getData().toJavaList(CustomSysUserProfessional.class)); } @Override public void onFailed(@NotNull Integer errorCode, @NotNull String error) { requestCallBack.onFailed(errorCode, error); } }); } else { requestCallBack.onNoNetWork(); } } }
92303051d02672673eb6ce55b4b33247fcacba9d
3,029
java
Java
src/test/java/uk/co/cameronhunter/aws/glacier/actions/UploadTest.java
cameronhunter/glacier-cli
eee41ab32edf0d5dd1a4e2d42f88552632e12266
[ "MIT" ]
18
2015-03-01T05:31:03.000Z
2021-04-12T19:57:47.000Z
src/test/java/uk/co/cameronhunter/aws/glacier/actions/UploadTest.java
cameronhunter/glacier-cli
eee41ab32edf0d5dd1a4e2d42f88552632e12266
[ "MIT" ]
4
2017-07-01T16:17:21.000Z
2021-11-27T11:13:48.000Z
src/test/java/uk/co/cameronhunter/aws/glacier/actions/UploadTest.java
cameronhunter/glacier-cli
eee41ab32edf0d5dd1a4e2d42f88552632e12266
[ "MIT" ]
3
2016-04-21T09:02:41.000Z
2021-02-08T21:18:51.000Z
29.407767
95
0.640475
995,393
package uk.co.cameronhunter.aws.glacier.actions; import com.amazonaws.services.glacier.transfer.ArchiveTransferManager; import com.amazonaws.services.glacier.transfer.UploadResult; import org.jmock.Expectations; import org.junit.Before; import org.junit.Test; import uk.co.cameronhunter.aws.glacier.domain.Archive; import uk.co.cameronhunter.aws.glacier.test.utils.MockTestHelper; import java.io.File; import java.io.FileNotFoundException; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; public class UploadTest extends MockTestHelper { private File archive; private ArchiveTransferManager transferManager; @Before public void setUp() { archive = mock(File.class); transferManager = mock(ArchiveTransferManager.class); expectThat(new Expectations() { { allowing(archive).length(); allowing(archive).getAbsolutePath(); } }); } @Test(expected = IllegalArgumentException.class) public void upload_requiresFileToExist() throws Exception { expectThat(archiveExists(false)); new Upload(transferManager, "vault", archive); } @Test(expected = IllegalArgumentException.class) public void upload_requiresArchiveToBeFile() throws Exception { expectThat(archiveExists(true)); expectThat(archiveIsFile(false)); new Upload(transferManager, "vault", archive); } @Test public void upload() throws Exception { String vault = "vault"; String archiveName = "archive.zip"; expectThat(archiveExists(true)); expectThat(archiveIsFile(true)); expectThat(archiveIsCalled(archiveName)); expectThat(archiveIsUploadedTo(vault)); Archive uploadedArchive = new Upload(transferManager, vault, archive).call(); assertThat(uploadedArchive.archiveId, is(notNullValue())); assertThat(uploadedArchive.name, is(equalTo(archiveName))); } private Expectations archiveExists(final boolean exists) { return new Expectations() { { one(archive).exists(); will(returnValue(exists)); } }; } private Expectations archiveIsFile(final boolean isFile) { return new Expectations() { { one(archive).isFile(); will(returnValue(isFile)); } }; } private Expectations archiveIsCalled(final String filename) { return new Expectations() { { allowing(archive).getName(); will(returnValue(filename)); } }; } private Expectations archiveIsUploadedTo(final String vault) throws FileNotFoundException { return new Expectations() { { one(transferManager).upload(vault, archive.getName(), archive); will(returnValue(new UploadResult("archive-id"))); } }; } }
9230305be6575b9619c3969fb7889211917aff02
355
java
Java
src/main/java/com/model/sys/Role.java
niefansheng/cooljava
c7284c5f845cb7d0c9265a285c2cf83940a81ca2
[ "Apache-2.0" ]
2
2020-07-10T16:18:30.000Z
2021-04-26T08:24:54.000Z
src/main/java/com/model/sys/Role.java
niefansheng/cooljava
c7284c5f845cb7d0c9265a285c2cf83940a81ca2
[ "Apache-2.0" ]
10
2020-03-04T23:46:49.000Z
2022-02-01T01:00:51.000Z
src/main/java/com/model/sys/Role.java
DYKGUILTY/dyk
aca71de37098801f9cc7e637fc1b2190c0ea5f4a
[ "Apache-2.0" ]
1
2021-04-26T08:24:55.000Z
2021-04-26T08:24:55.000Z
14.791667
41
0.701408
995,394
package com.model.sys; import com.model.page.PageDto; public class Role extends PageDto{ String name; String useable; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUseable() { return useable; } public void setUseable(String useable) { this.useable = useable; } }
92303420a17c52bfbfd95dc4835997d40e8a0cdc
6,731
java
Java
src/pw/skidrevenant/fiona/checks/other/Interact.java
MinecraftMan101/shrek-anticheat
6e3ed10f205855f912ec611b65c0fabb93d69565
[ "Unlicense" ]
null
null
null
src/pw/skidrevenant/fiona/checks/other/Interact.java
MinecraftMan101/shrek-anticheat
6e3ed10f205855f912ec611b65c0fabb93d69565
[ "Unlicense" ]
null
null
null
src/pw/skidrevenant/fiona/checks/other/Interact.java
MinecraftMan101/shrek-anticheat
6e3ed10f205855f912ec611b65c0fabb93d69565
[ "Unlicense" ]
1
2021-07-07T10:00:45.000Z
2021-07-07T10:00:45.000Z
44.873333
727
0.539296
995,395
package pw.skidrevenant.fiona.checks.other; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.player.PlayerInteractEvent; import pw.skidrevenant.fiona.Fiona; import pw.skidrevenant.fiona.detections.Checks; import pw.skidrevenant.fiona.detections.ChecksListener; import pw.skidrevenant.fiona.detections.ChecksType; import pw.skidrevenant.fiona.user.User; import pw.skidrevenant.fiona.utils.CancelType; import pw.skidrevenant.fiona.utils.Color; @ChecksListener(events = { BlockPlaceEvent.class, PlayerInteractEvent.class }) public class Interact extends Checks { private Map<UUID, Integer> verbose; public Interact() { super("Interact", ChecksType.OTHER, Fiona.getAC(), 100, true, false); this.verbose = new HashMap<UUID, Integer>(); } @Override protected void onEvent(final Event event) { if (!this.getState()) { return; } if (event instanceof PlayerInteractEvent) { final PlayerInteractEvent e = (PlayerInteractEvent)event; if (e.isCancelled() || (e.getAction() != Action.RIGHT_CLICK_BLOCK && e.getAction() != Action.LEFT_CLICK_BLOCK)) { return; } boolean isValid = false; final Player player = e.getPlayer(); final User user = Fiona.getUserManager().getUser(player.getUniqueId()); int verbose = this.verbose.getOrDefault(player.getUniqueId(), 0); final Location scanLocation = e.getClickedBlock().getRelative(e.getBlockFace()).getLocation(); final double x = scanLocation.getX(); final double y = scanLocation.getY(); final double z = scanLocation.getZ(); for (double sX = x; sX < x + 2.0; ++sX) { for (double sY = y; sY < y + 2.0; ++sY) { for (double sZ = z; sZ < z + 2.0; ++sZ) { final Location relative = new Location(scanLocation.getWorld(), sX, sY, sZ); final List<Location> blocks = this.rayTrace(player.getLocation(), relative); boolean valid = true; for (final Location l : blocks) { if (!this.checkPhase(l.getBlock().getType())) { valid = false; } } if (valid) { isValid = true; } } } } if (!isValid && !e.getItem().getType().equals((Object)Material.ENDER_PEARL)) { ++verbose; user.setCancelled(this, CancelType.INTERACT); } else { verbose = ((verbose > 0) ? (verbose - 1) : 0); } if (verbose > 2) { user.setVL(this, user.getVL(this) + 1); user.setCancelled(this, CancelType.INTERACT); this.Alert(player, Color.Gray + "Reason: " + Color.Green + "Interact"); } this.verbose.put(player.getUniqueId(), verbose); } if (event instanceof BlockPlaceEvent) { final BlockPlaceEvent e2 = (BlockPlaceEvent)event; if (e2.isCancelled()) { return; } final Player player2 = e2.getPlayer(); final User user2 = Fiona.getUserManager().getUser(player2.getUniqueId()); int verbose2 = this.verbose.getOrDefault(player2.getUniqueId(), 0); if (user2.getLastBlockPlaced() == null) { return; } if (e2.getBlockPlaced().getLocation().distance(user2.getLastBlockPlaced().getLocation()) < 1.2 && e2.getPlayer().getLocation().getBlockY() - e2.getBlock().getLocation().getY() == 1.0 && e2.getPlayer().getLocation().clone().subtract(0.0, 1.0, 0.0).distance(e2.getBlock().getLocation()) > 2.0) { if (++verbose2 > 2) { user2.setCancelled(this, CancelType.BLOCK); } } else { verbose2 = ((verbose2 > 0) ? (verbose2 - 1) : verbose2); } if (verbose2 > 5) { user2.setVL(this, user2.getVL(this) + 1); user2.setCancelled(this, CancelType.BLOCK); this.Alert(player2, Color.Gray + "Reason: " + Color.Green + "PLACE_REACH"); } this.verbose.put(player2.getUniqueId(), verbose2); } } private List<Location> rayTrace(final Location from, final Location to) { final List<Location> a = new ArrayList<Location>(); if (from == null || to == null) { return a; } if (!from.getWorld().equals(to.getWorld())) { return a; } if (from.distance(to) > 10.0) { return a; } double x1 = from.getX(); double y1 = from.getY() + 1.62; double z1 = from.getZ(); final double x2 = to.getX(); final double y2 = to.getY(); final double z2 = to.getZ(); for (boolean scanning = true; scanning; scanning = false) { a.add(new Location(from.getWorld(), x1, y1, z1)); x1 += (x2 - x1) / 10.0; y1 += (y2 - y1) / 10.0; z1 += (z2 - z1) / 10.0; if (Math.abs(x1 - x2) < 0.01 && Math.abs(y1 - y2) < 0.01 && Math.abs(z1 - z2) < 0.01) {} } return a; } public boolean checkPhase(final Material m) { final int[] array; final int[] whitelist = array = new int[] { 355, 196, 194, 197, 195, 193, 64, 96, 187, 184, 186, 107, 185, 183, 192, 189, 139, 191, 85, 101, 190, 113, 188, 160, 102, 163, 157, 0, 145, 49, 77, 135, 108, 67, 164, 136, 114, 156, 180, 128, 143, 109, 134, 53, 126, 44, 416, 8, 425, 138, 26, 397, 372, 13, 135, 117, 108, 39, 81, 92, 71, 171, 141, 118, 144, 54, 139, 67, 127, 59, 115, 330, 164, 151, 178, 32, 28, 93, 94, 175, 122, 116, 130, 119, 120, 51, 140, 147, 154, 148, 136, 65, 10, 69, 31, 105, 114, 372, 33, 34, 36, 29, 90, 142, 27, 104, 156, 66, 40, 330, 38, 180, 149, 150, 75, 76, 55, 128, 6, 295, 323, 63, 109, 78, 88, 134, 176, 11, 9, 44, 70, 182, 83, 50, 146, 132, 131, 106, 177, 68, 8, 111, 30, 72, 53, 126, 37 }; for (final int ids : array) { if (m.getId() == ids) { return true; } } return false; } }
923034f57589595bb2992a6bf8156b71062d2470
397
java
Java
jbehave-support-core/src/main/java/org/jbehavesupport/core/internal/converters/LocalDateTimeConverter.java
mbocek/jbehave-support
bb2e3fe97ce938957239aae969b56024a1e0138d
[ "MIT" ]
4
2019-04-03T08:18:24.000Z
2020-05-25T10:09:16.000Z
jbehave-support-core/src/main/java/org/jbehavesupport/core/internal/converters/LocalDateTimeConverter.java
mbocek/jbehave-support
bb2e3fe97ce938957239aae969b56024a1e0138d
[ "MIT" ]
328
2018-10-03T05:37:21.000Z
2022-03-12T19:36:14.000Z
jbehave-support-core/src/main/java/org/jbehavesupport/core/internal/converters/LocalDateTimeConverter.java
Hebcak/jbehave-support
b4d6c7c6e08188bf7696fc2162e1d0bd92f7e643
[ "MIT" ]
14
2018-10-02T21:37:29.000Z
2021-06-29T15:31:13.000Z
26.466667
113
0.79597
995,396
package org.jbehavesupport.core.internal.converters; import java.time.LocalDateTime; import org.springframework.core.convert.converter.Converter; public class LocalDateTimeConverter extends AbstractChronoConverter implements Converter<String, LocalDateTime> { @Override public LocalDateTime convert(final String source) { return LocalDateTime.from(parseBest(source)); } }
9230355408af442d8ddf486385282fa129d51f53
573
java
Java
src/hackerrank_solutions-master/Superreduced_string.java
TheAlgo/AlgoDS
de40f78943c830209dfe662eaf3e5b237cca0484
[ "MIT" ]
null
null
null
src/hackerrank_solutions-master/Superreduced_string.java
TheAlgo/AlgoDS
de40f78943c830209dfe662eaf3e5b237cca0484
[ "MIT" ]
null
null
null
src/hackerrank_solutions-master/Superreduced_string.java
TheAlgo/AlgoDS
de40f78943c830209dfe662eaf3e5b237cca0484
[ "MIT" ]
2
2020-03-20T11:40:36.000Z
2020-03-24T16:05:17.000Z
23.875
63
0.52356
995,397
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); StringBuffer s = new StringBuffer(stdin.nextLine()); for(int i = 1; i < s.length(); i++) { if(s.charAt(i) == s.charAt(i-1)) { s.delete(i-1, i+1); i = 0; } } if(s.length() == 0) System.out.println("Empty String"); else System.out.println(s); } }
923036d16eb9e8db2fdaccf0752549ee034c336a
1,405
java
Java
api/java/src/test/java/com/navercorp/redis/cluster/async/BackgroundPoolTest.java
lynix94/nbase-arc
4de3c20ebd2f5ed13ab83dbc6a608f44e812ca78
[ "Apache-2.0" ]
176
2015-12-30T08:44:30.000Z
2022-03-15T08:10:39.000Z
api/java/src/test/java/com/navercorp/redis/cluster/async/BackgroundPoolTest.java
lynix94/nbase-arc
4de3c20ebd2f5ed13ab83dbc6a608f44e812ca78
[ "Apache-2.0" ]
35
2016-03-24T08:29:51.000Z
2021-12-09T20:06:39.000Z
api/java/src/test/java/com/navercorp/redis/cluster/async/BackgroundPoolTest.java
lynix94/nbase-arc
4de3c20ebd2f5ed13ab83dbc6a608f44e812ca78
[ "Apache-2.0" ]
65
2015-12-30T09:05:13.000Z
2022-03-15T08:10:43.000Z
27.54902
79
0.646263
995,398
/* * Copyright 2015 NAVER Corp. * * 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.navercorp.redis.cluster.async; import java.util.concurrent.CountDownLatch; import org.junit.Test; /** * @author jaehong.kim */ public class BackgroundPoolTest { @Test public void action() throws Exception { BackgroundPool pool = new BackgroundPool(1); final CountDownLatch latch = new CountDownLatch(1); AsyncResultHandler<String> handler = new AsyncResultHandler<String>() { public void handle(AsyncResult<String> result) { System.out.println(result.getResult()); latch.countDown(); } }; pool.getPool().execute(new Runnable() { public void run() { latch.countDown(); } }); latch.await(); pool.shutdown(); } }
9230373e64810cac9288b7e96ce4df6da2806cdb
13,576
java
Java
drools-eclipse/drools-eclipse-plugin/src/main/java/org/drools/eclipse/flow/ruleflow/editor/RuleFlowPaletteFactory.java
bobmcwhirter/drools
62a0a5907ca1f4505cea2f4c55302da846b1cc75
[ "Apache-2.0" ]
13
2016-05-08T12:40:40.000Z
2017-01-09T05:02:36.000Z
drools-eclipse/drools-eclipse-plugin/src/main/java/org/drools/eclipse/flow/ruleflow/editor/RuleFlowPaletteFactory.java
rapidan/drools
62a0a5907ca1f4505cea2f4c55302da846b1cc75
[ "Apache-2.0" ]
7
2020-06-30T23:18:02.000Z
2022-02-01T01:05:08.000Z
drools-eclipse/drools-eclipse-plugin/src/main/java/org/drools/eclipse/flow/ruleflow/editor/RuleFlowPaletteFactory.java
rapidan/drools
62a0a5907ca1f4505cea2f4c55302da846b1cc75
[ "Apache-2.0" ]
6
2015-12-04T06:09:37.000Z
2019-07-19T07:20:44.000Z
46.844828
146
0.644093
995,399
package org.drools.eclipse.flow.ruleflow.editor; /* * Copyright 2005 JBoss 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. */ import java.util.ArrayList; import java.util.List; import org.drools.eclipse.DroolsEclipsePlugin; import org.drools.eclipse.flow.common.editor.core.ElementConnectionFactory; import org.drools.eclipse.flow.ruleflow.core.ActionWrapper; import org.drools.eclipse.flow.ruleflow.core.CompositeContextNodeWrapper; import org.drools.eclipse.flow.ruleflow.core.ConnectionWrapper; import org.drools.eclipse.flow.ruleflow.core.ConnectionWrapperFactory; import org.drools.eclipse.flow.ruleflow.core.EndNodeWrapper; import org.drools.eclipse.flow.ruleflow.core.EventNodeWrapper; import org.drools.eclipse.flow.ruleflow.core.ForEachNodeWrapper; import org.drools.eclipse.flow.ruleflow.core.HumanTaskNodeWrapper; import org.drools.eclipse.flow.ruleflow.core.JoinWrapper; import org.drools.eclipse.flow.ruleflow.core.MilestoneWrapper; import org.drools.eclipse.flow.ruleflow.core.RuleSetNodeWrapper; import org.drools.eclipse.flow.ruleflow.core.SplitWrapper; import org.drools.eclipse.flow.ruleflow.core.StartNodeWrapper; import org.drools.eclipse.flow.ruleflow.core.SubProcessWrapper; import org.drools.eclipse.flow.ruleflow.core.TimerWrapper; import org.eclipse.gef.palette.CombinedTemplateCreationEntry; import org.eclipse.gef.palette.ConnectionCreationToolEntry; import org.eclipse.gef.palette.MarqueeToolEntry; import org.eclipse.gef.palette.PaletteContainer; import org.eclipse.gef.palette.PaletteDrawer; import org.eclipse.gef.palette.PaletteGroup; import org.eclipse.gef.palette.PaletteRoot; import org.eclipse.gef.palette.SelectionToolEntry; import org.eclipse.gef.palette.ToolEntry; import org.eclipse.gef.requests.CreationFactory; import org.eclipse.gef.requests.SimpleFactory; import org.eclipse.jface.resource.ImageDescriptor; /** * Factory for creating a RuleFlow palette. * * @author <a href="mailto:anpch@example.com">Kris Verlaenen</a> */ public class RuleFlowPaletteFactory { public static PaletteRoot createPalette() { PaletteRoot flowPalette = new PaletteRoot(); flowPalette.addAll(createCategories(flowPalette)); return flowPalette; } private static List createCategories(PaletteRoot root) { List categories = new ArrayList(); categories.add(createControlGroup(root)); categories.add(createComponentsDrawer()); categories.add(createWorkNodesDrawer()); return categories; } private static PaletteContainer createComponentsDrawer() { PaletteDrawer drawer = new PaletteDrawer("Components", null); List entries = new ArrayList(); CombinedTemplateCreationEntry combined = new CombinedTemplateCreationEntry( "Start", "Create a new Start", StartNodeWrapper.class, new SimpleFactory(StartNodeWrapper.class), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/process_start.gif")), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/process_start.gif")) ); entries.add(combined); combined = new CombinedTemplateCreationEntry( "End", "Create a new End", EndNodeWrapper.class, new SimpleFactory(EndNodeWrapper.class), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/process_stop.gif")), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/process_stop.gif")) ); entries.add(combined); combined = new CombinedTemplateCreationEntry( "RuleFlowGroup", "Create a new RuleFlowGroup", RuleSetNodeWrapper.class, new SimpleFactory(RuleSetNodeWrapper.class), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/activity.gif")), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/activity.gif")) ); entries.add(combined); combined = new CombinedTemplateCreationEntry( "Split", "Create a new Split", SplitWrapper.class, new SimpleFactory(SplitWrapper.class), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/split.gif")), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/split.gif")) ); entries.add(combined); combined = new CombinedTemplateCreationEntry( "Join", "Create a new Join", JoinWrapper.class, new SimpleFactory(JoinWrapper.class), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/join.gif")), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/join.gif")) ); entries.add(combined); combined = new CombinedTemplateCreationEntry( "Event Wait", "Create a new Event Wait", MilestoneWrapper.class, new SimpleFactory(MilestoneWrapper.class), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/question.gif")), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/question.gif")) ); entries.add(combined); combined = new CombinedTemplateCreationEntry( "SubFlow", "Create a new SubFlow", SubProcessWrapper.class, new SimpleFactory(SubProcessWrapper.class), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/process.gif")), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/process.gif")) ); entries.add(combined); combined = new CombinedTemplateCreationEntry( "Action", "Create a new Action", ActionWrapper.class, new SimpleFactory(ActionWrapper.class), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/action.gif")), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/action.gif")) ); entries.add(combined); combined = new CombinedTemplateCreationEntry( "Timer", "Create a new Timer", TimerWrapper.class, new SimpleFactory(TimerWrapper.class), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/timer.gif")), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/timer.gif")) ); entries.add(combined); combined = new CombinedTemplateCreationEntry( "Event", "Create a new Event Node", EventNodeWrapper.class, new SimpleFactory(EventNodeWrapper.class), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/event.gif")), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/event.gif")) ); entries.add(combined); combined = new CombinedTemplateCreationEntry( "Human Task", "Create a new Human Task", HumanTaskNodeWrapper.class, new SimpleFactory(HumanTaskNodeWrapper.class), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/human_task.gif")), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/human_task.gif")) ); entries.add(combined); combined = new CombinedTemplateCreationEntry( "Composite", "Create a new Composite Node", CompositeContextNodeWrapper.class, new SimpleFactory(CompositeContextNodeWrapper.class), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/composite.gif")), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/composite.gif")) ); entries.add(combined); combined = new CombinedTemplateCreationEntry( "For Each", "Create a new ForEach Node", ForEachNodeWrapper.class, new SimpleFactory(ForEachNodeWrapper.class), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/composite.gif")), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/composite.gif")) ); entries.add(combined); drawer.addAll(entries); return drawer; } private static PaletteContainer createWorkNodesDrawer() { PaletteDrawer drawer = new PaletteDrawer("Work Items", null); // List entries = new ArrayList(); // // for (Iterator iterator = WorkItemDefinitions.getWorkDefinitions().iterator(); iterator.hasNext(); ) { // final WorkDefinition workDefinition = (WorkDefinition) iterator.next(); // final String label; // String description = workDefinition.getName(); // String icon = null; // if (workDefinition instanceof WorkDefinitionExtension) { // WorkDefinitionExtension extension = (WorkDefinitionExtension) workDefinition; // label = extension.getDisplayName(); // description = extension.getExplanationText(); // icon = extension.getIcon(); // } else { // label = workDefinition.getName(); // } // // CombinedTemplateCreationEntry combined = new CombinedTemplateCreationEntry( // label, // description, // WorkItemWrapper.class, // new SimpleFactory(WorkItemWrapper.class) { // public Object getNewObject() { // WorkItemWrapper taskWrapper = (WorkItemWrapper) super.getNewObject(); // taskWrapper.setName(label); // taskWrapper.getWorkItemNode().setName(label); // taskWrapper.getWorkItemNode().setWork(new WorkImpl()); // taskWrapper.getWorkItemNode().getWork().setName(workDefinition.getName()); // return taskWrapper; // } // }, // ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry(icon == null? "icons/action.gif" : icon)), // ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry(icon == null? "icons/action.gif" : icon)) // ); // entries.add(combined); // } // // drawer.addAll(entries); return drawer; } private static PaletteContainer createControlGroup(PaletteRoot root) { PaletteGroup controlGroup = new PaletteGroup("Control Group"); List entries = new ArrayList(); ToolEntry tool = new SelectionToolEntry(); entries.add(tool); root.setDefaultEntry(tool); tool = new MarqueeToolEntry(); entries.add(tool); final ElementConnectionFactory normalConnectionFactory = new ConnectionWrapperFactory(); tool = new ConnectionCreationToolEntry( "Connection Creation", "Creating connections", new CreationFactory() { public Object getNewObject() { return normalConnectionFactory.createElementConnection(); } public Object getObjectType() { return ConnectionWrapper.class; } }, ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/connection.gif")), ImageDescriptor.createFromURL(DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/connection.gif")) ); entries.add(tool); controlGroup.addAll(entries); return controlGroup; } }
923037821214b2deb86cf6228ba3f39af0665a7d
9,271
java
Java
src/test/java/org/tsers/junitquest/testmethods/ArithmeticMethods.java
lhartikk/JunitQuest
481c1934b4c2b49c43e8f48418d268bf3249fb72
[ "Apache-2.0" ]
16
2015-07-17T03:56:15.000Z
2021-09-28T10:42:21.000Z
src/test/java/org/tsers/junitquest/testmethods/ArithmeticMethods.java
lhartikk/JunitQuest
481c1934b4c2b49c43e8f48418d268bf3249fb72
[ "Apache-2.0" ]
1
2019-02-27T16:03:59.000Z
2019-02-27T16:03:59.000Z
src/test/java/org/tsers/junitquest/testmethods/ArithmeticMethods.java
lhartikk/JunitQuest
481c1934b4c2b49c43e8f48418d268bf3249fb72
[ "Apache-2.0" ]
null
null
null
24.333333
86
0.420127
995,400
package org.tsers.junitquest.testmethods; public class ArithmeticMethods { public static void arithmeticMethod(int a) { a = a + 1000; if (a == 0) { System.out.println("branch 1"); } else { System.out.println("branch 2"); } } public static void arithmeticMethod2(int a) { if (a == 0) { System.out.println("branch 1"); } else { System.out.println("branch 2"); } } public static void arithmeticMethod3(int a) { a = a + 1000; a = a + 2000; a = a + 3000; if (a == 0) { System.out.println("branch 1"); } else { System.out.println("branch 2"); } } public static void arithmeticMethod4(int a) { if (a == 0) { System.out.println("branch 1"); } else if (a == 9999) { System.out.println("branch 2"); } else if (a == 19999) { System.out.println("branch 3"); } else { System.out.println("branch 4"); } } public static void arithmeticMethod5(int a) { a = a + 1000; a = a + 2000; a = a + 5000; if (a == 0) { System.out.println("branch 1"); } else if (a == 9999) { System.out.println("branch 2"); } else if (a == 19999) { System.out.println("branch 3"); } else { System.out.println("branch 4"); } } public static void arithmeticMethod6(int a) { if (a == 0) { System.out.println("branch 1"); } a = a + 1000; if (a == 9999) { System.out.println("branch 2"); } a = a + 2000; if (a == 19999) { System.out.println("branch 3"); } else { System.out.println("branch 4"); } } public static void arithmeticMethod7(int a) { if (a == 0) { System.out.println("branch 1"); } else if (a == 1000) { System.out.println("branch 2"); } else { System.out.println("branch 3"); } } public static void arithmeticMethod8(int a) { if (a == 0) { System.out.println("branch 1"); } else if (a == -1) { System.out.println("branch 2"); } else if (a == 1) { System.out.println("branch 3"); } else if (a == 2) { System.out.println("branch 4"); } else if (a == 3) { System.out.println("branch 5"); } else if (a == 4) { System.out.println("branch 6"); ; } else if (a == 5) { System.out.println("branch 7"); } else { System.out.println("branch 8"); } } public static void arithmeticMethod9(int a) { int c = 1000 + 2000; c = c + 1; a = a + c; a = a + 1; if (a == 0) { System.out.println("branch 1"); } else if (a == 5000) { System.out.println("branch 2"); } else { System.out.println("branch 3"); } } public static void arithmeticMethod10(int a) { a = a + 10; if (a == 0) { System.out.println("branch 1"); } else if (a == 5000) { System.out.println("branch 2"); } else { System.out.println("branch 3"); } } public static void arithmeticMethod11(int a) { if (a == 0) { System.out.println("branch 1"); } else { if (a == 5000) { System.out.println("branch 2"); } else { if (a == 1) { System.out.println("branch 3"); } } } } public static void arithmeticMethod12(int a, int b) { if (a == 123) { System.out.println("branch 1"); } if (b == 321) { System.out.println("branch 2"); } } public static void arithmeticMethod13(int a, int b, int c) { a = a + 100; b = b + 100; c = c + 100; if (a == 123) { System.out.println("branch 1"); } if (b == 321) { System.out.println("branch 2"); } if (c == 999) { System.out.println("branch 3"); } } public static void arithmeticMethod14(int a, int b, int c) { if (a == 123) { System.out.println("branch 1"); } else if (a == 124 && b != 123 && c != 123) { System.out.println("branch 2"); } int d = 1000; a = a + 100; b = b + 100; c = c + 100; a = a + d; if (a == 1000) { if (b == 1000) { System.out.println("branch 3"); } } } public static void arithmeticMethod15(int a) { switch (a) { case 0: System.out.println("branch 1"); break; case 1: System.out.println("branch 2"); break; default: System.out.println("branch 3"); break; } } public static void arithmeticMethod16(int a) { switch (a) { case 0: System.out.println("branch 1"); break; case 1: System.out.println("branch 2"); break; default: System.out.println("branch 3"); break; } if (a == 10) { System.out.println("branch 4"); } } public void intComparisons(int a, int b) { if (b == 1) { System.out.println("branch 1"); return; } if (a == 1) { System.out.println("branch 2"); return; } if (a == 0 || b == 0) { System.out.println("branch 3"); return; } } public void intComparisons2(String s, int value, int lowerBound, int upperBound) { if ((value < lowerBound) || (value > upperBound)) { System.out.println("branch 1"); } else { System.out.println("branch 2"); } } public void longComparisons(long a, long b) { if (b == 1) { System.out.println("branch 1"); return; } if (a == 1) { System.out.println("branch 2"); return; } if (a == 0 || b == 0) { System.out.println("branch 3"); return; } System.out.println("branch 4"); } public void ambiguousVariables(int a, int b, int c) { if (a + b + c > 0) { System.out.println("branch 1"); } int d = a * b * c; if (d > 0) { System.out.println("branch 2"); } } public void longParameter(long a, int b) { if (b == 123) { System.out.println("branch 1"); } else { System.out.println("branch 2"); } } public void longlonglonglongParameter(long a, long b, long c, long d) { if (a == 123) { System.out.println("branch 1"); } if (b == 555123) { System.out.println("branch 2"); } if (c == 6663) { System.out.println("branch 3"); } if (d == 12355) { System.out.println("branch 4"); } } public void longintlongintParameter(long a, int b, int c, long d) { if (a == 123) { System.out.println("branch 1"); } if (b == 555123) { System.out.println("branch 2"); } if (c == 6663) { System.out.println("branch 3"); } if (d == 12355) { System.out.println("branch 4"); } } public void longMaxValue(long a) { if (a == Long.MAX_VALUE) { System.out.println("branch 1"); } } public void doubleEquation(double a) { if (a == 2) { System.out.println("branch 1"); } } public void doubleEquation2(double a, double b) { if (a == 2) { System.out.println("branch 1"); b = b + 9000; b = b - 2000; b = b + 0; b = b + 1; b = b + 2; b = b + 3; if (b == 124) { System.out.println("branch 2"); } } } public void floatEquation(float a) { if (a == 1242) { System.out.println("branch 1"); } } public void floatEquation2(float a, float b) { if (a == 2) { System.out.println("branch 1"); b = b + 9000; b = b - 2000; b = b + 0; b = b + 1; b = b + 2; b = b + 3; if (b == 124) { System.out.println("branch 2"); } } } public void shortEquation(short a) { if (a == 2) { System.out.println("branch 1"); } System.out.println("branch 2"); } }
923037bda568adaaa522ba308ffba997da6e2f87
4,468
java
Java
Ref-Finder/code/src/lsclipse/rules/ReplaceTypeCodeWithState.java
UCLA-SEAL/RefFinder
40849cf928b9a2425efe6c1ec5ffa465b1ee2a76
[ "BSD-3-Clause" ]
null
null
null
Ref-Finder/code/src/lsclipse/rules/ReplaceTypeCodeWithState.java
UCLA-SEAL/RefFinder
40849cf928b9a2425efe6c1ec5ffa465b1ee2a76
[ "BSD-3-Clause" ]
null
null
null
Ref-Finder/code/src/lsclipse/rules/ReplaceTypeCodeWithState.java
UCLA-SEAL/RefFinder
40849cf928b9a2425efe6c1ec5ffa465b1ee2a76
[ "BSD-3-Clause" ]
null
null
null
36.325203
75
0.676589
995,401
/* * Ref-Finder * Copyright (C) <2015> <PLSE_UCLA> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ReplaceTypeCodeWithState.java * * This class is used to test a tyRuBa result set for adherence * to the "replace_type_code_with_state" logical refactoring rule. * * author: Napol Rachatasumrit * created: 8/8/2010 */ package lsclipse.rules; import lsclipse.RefactoringQuery; import lsclipse.utils.CodeCompare; import tyRuBa.tdbc.ResultSet; import tyRuBa.tdbc.TyrubaException; public class ReplaceTypeCodeWithState implements Rule { private String name_; public ReplaceTypeCodeWithState() { name_ = "replace_type_code_with_state"; } @Override public String checkAdherence(ResultSet rs) throws TyrubaException { String fShortName1 = rs.getString("?fShortName1"); String fShortName2 = rs.getString("?fShortName2"); String tCodeShortName1 = rs.getString("?tCodeShortName1"); String tCodeShortName2 = rs.getString("?tCodeShortName2"); String tCodeShortName = rs.getString("?tCodeShortName"); String tShortName = rs.getString("?tShortName"); fShortName1 = fShortName1.toLowerCase(); fShortName2 = fShortName2.toLowerCase(); tCodeShortName1 = tCodeShortName1.toLowerCase(); tCodeShortName2 = tCodeShortName2.toLowerCase(); tCodeShortName = tCodeShortName.toLowerCase(); tShortName = tShortName.toLowerCase(); if ((CodeCompare.compare(fShortName1, tCodeShortName1) && CodeCompare.compare(fShortName2, tCodeShortName2)) || (CodeCompare.compare(fShortName1, tCodeShortName2) && CodeCompare.compare(fShortName2, tCodeShortName1)) && CodeCompare.compare(tCodeShortName, tShortName)) { String writeTo = getName() + "(\"" + rs.getString("?tFullName") + "\",\"" + rs.getString("?tCodeFullName") + "\")"; return writeTo; // fix to check that it's different. } return null; } private String getQueryString() { return "deleted_field(" + "?old_fFullName1, ?fShortName1, ?tFullName), " + "deleted_field(" + "?old_fFullName2, ?fShortName2, ?tFullName), " + "NOT(equals(?fShortName1, ?fShortName2)), " + "before_fieldmodifier(" + "?old_fFullName1, \"static\"), " + "before_fieldmodifier(" + "?old_fFullName2, \"static\"), " + "before_fieldmodifier(" + "?old_fFullName1, \"final\"), " + "before_fieldmodifier(" + "?old_fFullName2, \"final\"), " + "modified_type(" + "?tFullName, ?tShortName, ?), " + "added_field(" + "?new_fFullName1, ?fShortName1, ?tCodeFullName), " + "added_field(" + "?new_fFullName2, ?fShortName2, ?tCodeFullName), " + "after_fieldmodifier(" + "?new_fFullName1, \"static\"), " + "after_fieldmodifier(" + "?new_fFullName2, \"static\"), " + "after_fieldmodifier(" + "?new_fFullName1, \"final\"), " + "after_fieldmodifier(" + "?new_fFullName2, \"final\"), " + "deleted_fieldoftype(" + "?tCodefieldFullName, ?), " + "added_fieldoftype(" + "?tCodefieldFullName, ?tCodeFullName), " + "added_type(" + "?tCodeFullName, ?tCodeShortName, ?), " + "added_type(" + "?tCodeFullName1, ?tCodeShortName1, ?), " + "added_type(" + "?tCodeFullName2, ?tCodeShortName2, ?), " + "added_subtype(" + "?tCodeFullName, ?tCodeFullName1), " + "added_subtype(" + "?tCodeFullName, ?tCodeFullName2)," + "NOT(equals(?tCodeShortName1, ?tCodeShortName2))"; // could check after_accesses facts to make it less general } @Override public String getName() { return name_; } @Override public RefactoringQuery getRefactoringQuery() { RefactoringQuery repl = new RefactoringQuery(getName(), getQueryString()); return repl; } @Override public String getRefactoringString() { return getName() + "(?tFullName, ?tCodeFullName)"; } }
9230383e959b5f400cc5646c196f51489299175f
1,092
java
Java
ml4j-datasets-api/src/main/java/org/ml4j/nn/datasets/exceptions/FeatureExtractionRuntimeException.java
ml4j/ml4j-api
cbd2db2fcde5d6f9ea87d133eb2c57df8066a241
[ "Apache-2.0" ]
1
2018-07-24T21:14:28.000Z
2018-07-24T21:14:28.000Z
ml4j-datasets-api/src/main/java/org/ml4j/nn/datasets/exceptions/FeatureExtractionRuntimeException.java
ml4j/ml4j-api
cbd2db2fcde5d6f9ea87d133eb2c57df8066a241
[ "Apache-2.0" ]
6
2017-10-24T17:55:47.000Z
2020-01-07T13:19:06.000Z
ml4j-datasets-api/src/main/java/org/ml4j/nn/datasets/exceptions/FeatureExtractionRuntimeException.java
ml4j/ml4j-api
cbd2db2fcde5d6f9ea87d133eb2c57df8066a241
[ "Apache-2.0" ]
3
2017-09-29T14:44:58.000Z
2018-03-07T07:38:02.000Z
31.2
100
0.763736
995,402
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * 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.ml4j.nn.datasets.exceptions; /** * A runtime exception occurring during Feature extraction using a * FeatureExtractor. * * @author Michael Lavelle * */ public class FeatureExtractionRuntimeException extends RuntimeException { /** * Default serialization id */ private static final long serialVersionUID = 1L; public FeatureExtractionRuntimeException(String message, Exception featureExtractionException) { super(message, featureExtractionException); } }
9230387abc812913a50cbd50b9f20f2fe9cbbc84
11,035
java
Java
src/main/java/se/trixon/ttc/MainApp.java
trixon/ttc
4d5f3e5f923c66510f5648b97efe06768c41b5e0
[ "Apache-2.0" ]
null
null
null
src/main/java/se/trixon/ttc/MainApp.java
trixon/ttc
4d5f3e5f923c66510f5648b97efe06768c41b5e0
[ "Apache-2.0" ]
null
null
null
src/main/java/se/trixon/ttc/MainApp.java
trixon/ttc
4d5f3e5f923c66510f5648b97efe06768c41b5e0
[ "Apache-2.0" ]
null
null
null
40.127273
159
0.678296
995,403
/* * Copyright 2019 Patrik Karlström. * * 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 se.trixon.ttc; import com.dlsc.workbenchfx.Workbench; import com.dlsc.workbenchfx.model.WorkbenchDialog; import com.dlsc.workbenchfx.view.controls.ToolbarItem; import de.codecentric.centerdevice.MenuToolkit; import javafx.application.Application; import javafx.collections.ObservableMap; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.image.Image; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.stage.Stage; import javafx.stage.WindowEvent; import org.apache.commons.lang3.SystemUtils; import org.controlsfx.control.action.Action; import org.controlsfx.control.action.ActionUtils; import se.trixon.almond.util.AboutModel; import se.trixon.almond.util.Dict; import se.trixon.almond.util.PomInfo; import se.trixon.almond.util.SystemHelper; import se.trixon.almond.util.fx.AlmondFx; import se.trixon.almond.util.fx.FxHelper; import se.trixon.almond.util.fx.dialogs.about.AboutPane; import se.trixon.almond.util.icons.material.MaterialIcon; import se.trixon.ttc.tools.fbd.FileByDate; import se.trixon.ttc.tools.fbd.ui.FbdModule; import se.trixon.ttc.tools.mapollage.ui.MapollageModule; /** * * @author Patrik Karlström */ public class MainApp extends Application { public static final String APP_TITLE = "Trixon Tool Collection"; public static final int ICON_SIZE_PROFILE = 32; public static final int ICON_SIZE_TOOLBAR = 40; public static final int ICON_SIZE_DRAWER = ICON_SIZE_TOOLBAR / 2; public static final int MODULE_ICON_SIZE = 32; private static final boolean IS_MAC = SystemUtils.IS_OS_MAC; private Action mAboutAction; private final AlmondFx mAlmondFX = AlmondFx.getInstance(); private FbdModule mFbdModule; private Action mHelpAction; private MapollageModule mMapollageModule; private Action mOptionsAction; private ToolbarItem mOptionsToolbarItem; private PreferencesModule mPreferencesModule; private Stage mStage; private Workbench mWorkbench; /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) throws Exception { mStage = stage; stage.getIcons().add(new Image(MainApp.class.getResourceAsStream("logo.png"))); mAlmondFX.addStageWatcher(stage, MainApp.class); createUI(); if (IS_MAC) { initMac(); } mStage.setTitle(APP_TITLE); mStage.show(); initAccelerators(); //mWorkbench.openModule(mPreferencesModule); } private void activateModule(int moduleIndexOnPage) { if (moduleIndexOnPage == 0) { moduleIndexOnPage = 10; } int pageIndex = 0;//TODO get actual page index int moduleIndex = pageIndex * mWorkbench.getModulesPerPage() + moduleIndexOnPage - 1; try { mWorkbench.openModule(mWorkbench.getModules().get(moduleIndex)); } catch (IndexOutOfBoundsException e) { //nvm } } private void activateOpenModule(int moduleIndexOnPage) { if (moduleIndexOnPage == 0) { moduleIndexOnPage = 10; } try { mWorkbench.openModule(mWorkbench.getOpenModules().get(moduleIndexOnPage - 1)); } catch (IndexOutOfBoundsException e) { //nvm } } private void createUI() { mPreferencesModule = new PreferencesModule(); mFbdModule = new FbdModule(); mMapollageModule = new MapollageModule(); mWorkbench = Workbench.builder(mFbdModule, mMapollageModule, mPreferencesModule).build(); mWorkbench.getStylesheets().add(MainApp.class.getResource("customTheme.css").toExternalForm()); initToolbar(); initWorkbenchDrawer(); Scene scene = new Scene(mWorkbench); // scene.getStylesheets().add("css/modena_dark.css"); mStage.setScene(scene); } private void displayOptions() { mWorkbench.openModule(mPreferencesModule); } private void initAccelerators() { final ObservableMap<KeyCombination, Runnable> accelerators = mStage.getScene().getAccelerators(); for (int i = 0; i < 10; i++) { final int index = i; accelerators.put(new KeyCodeCombination(KeyCode.valueOf("DIGIT" + i), KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN), (Runnable) () -> { activateModule(index); }); accelerators.put(new KeyCodeCombination(KeyCode.valueOf("NUMPAD" + i), KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN), (Runnable) () -> { activateModule(index); }); accelerators.put(new KeyCodeCombination(KeyCode.valueOf("DIGIT" + i), KeyCombination.SHORTCUT_DOWN), (Runnable) () -> { activateOpenModule(index); }); accelerators.put(new KeyCodeCombination(KeyCode.valueOf("NUMPAD" + i), KeyCombination.SHORTCUT_DOWN), (Runnable) () -> { activateOpenModule(index); }); } accelerators.put(new KeyCodeCombination(KeyCode.Q, KeyCombination.SHORTCUT_DOWN), (Runnable) () -> { mStage.fireEvent(new WindowEvent(mStage, WindowEvent.WINDOW_CLOSE_REQUEST)); }); accelerators.put(new KeyCodeCombination(KeyCode.W, KeyCombination.SHORTCUT_DOWN), (Runnable) () -> { if (mWorkbench.getActiveModule() != null) { mWorkbench.closeModule(mWorkbench.getActiveModule()); } }); if (!IS_MAC) { accelerators.put(new KeyCodeCombination(KeyCode.COMMA, KeyCombination.SHORTCUT_DOWN), (Runnable) () -> { displayOptions(); }); } } private void initMac() { MenuToolkit menuToolkit = MenuToolkit.toolkit(); Menu applicationMenu = menuToolkit.createDefaultApplicationMenu(APP_TITLE); menuToolkit.setApplicationMenu(applicationMenu); applicationMenu.getItems().remove(0); MenuItem aboutMenuItem = new MenuItem(String.format(Dict.ABOUT_S.toString(), APP_TITLE)); aboutMenuItem.setOnAction(mAboutAction); MenuItem settingsMenuItem = new MenuItem(Dict.PREFERENCES.toString()); settingsMenuItem.setOnAction(mOptionsAction); settingsMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.COMMA, KeyCombination.SHORTCUT_DOWN)); applicationMenu.getItems().add(0, aboutMenuItem); applicationMenu.getItems().add(2, settingsMenuItem); int cnt = applicationMenu.getItems().size(); applicationMenu.getItems().get(cnt - 1).setText(String.format("%s %s", Dict.QUIT.toString(), APP_TITLE)); } private void initToolbar() { mOptionsToolbarItem = new ToolbarItem(Dict.OPTIONS.toString(), MaterialIcon._Action.SETTINGS.getImageView(ICON_SIZE_TOOLBAR, Color.LIGHTGRAY), event -> { mWorkbench.openModule(mPreferencesModule); } ); mWorkbench.getToolbarControlsRight().addAll(mOptionsToolbarItem); } private void initWorkbenchDrawer() { //options mOptionsAction = new Action(Dict.OPTIONS.toString(), (ActionEvent event) -> { mWorkbench.hideNavigationDrawer(); displayOptions(); }); mOptionsAction.setAccelerator(new KeyCodeCombination(KeyCode.COMMA, KeyCombination.SHORTCUT_DOWN)); mOptionsAction.setGraphic(MaterialIcon._Action.SETTINGS.getImageView(ICON_SIZE_DRAWER)); //help mHelpAction = new Action(Dict.HELP.toString(), (ActionEvent event) -> { mWorkbench.hideNavigationDrawer(); SystemHelper.desktopBrowse("https://trixon.se/projects/ttc/documentation/"); }); //mHelpAction.setAccelerator(new KeyCodeCombination(KeyCode.F1, KeyCombination.SHORTCUT_ANY)); mHelpAction.setAccelerator(KeyCombination.keyCombination("F1")); //about Action aboutAction = new Action(Dict.ABOUT.toString(), (ActionEvent event) -> { mWorkbench.hideNavigationDrawer(); PomInfo pomInfo = new PomInfo(FileByDate.class, "se.trixon", "ttc"); AboutModel aboutModel = new AboutModel( SystemHelper.getBundle(getClass(), "about"), SystemHelper.getResourceAsImageView(MainApp.class, "logo.png") ); aboutModel.setAppVersion(pomInfo.getVersion()); AboutPane aboutPane = new AboutPane(aboutModel); double scaledFontSize = FxHelper.getScaledFontSize(); Label appLabel = new Label(aboutModel.getAppName()); appLabel.setFont(new Font(scaledFontSize * 1.8)); Label verLabel = new Label(String.format("%s %s", Dict.VERSION.toString(), aboutModel.getAppVersion())); verLabel.setFont(new Font(scaledFontSize * 1.2)); Label dateLabel = new Label(aboutModel.getAppDate()); dateLabel.setFont(new Font(scaledFontSize * 1.2)); VBox box = new VBox(appLabel, verLabel, dateLabel); box.setAlignment(Pos.CENTER_LEFT); box.setPadding(new Insets(0, 0, 0, 22)); BorderPane topBorderPane = new BorderPane(box); topBorderPane.setLeft(aboutModel.getImageView()); topBorderPane.setPadding(new Insets(22)); BorderPane mainBorderPane = new BorderPane(aboutPane); mainBorderPane.setTop(topBorderPane); WorkbenchDialog dialog = WorkbenchDialog.builder(Dict.ABOUT.toString(), mainBorderPane, ButtonType.CLOSE).build(); mWorkbench.showDialog(dialog); }); mWorkbench.getNavigationDrawerItems().setAll( ActionUtils.createMenuItem(mHelpAction), ActionUtils.createMenuItem(aboutAction) ); if (!IS_MAC) { mOptionsAction.setAccelerator(new KeyCodeCombination(KeyCode.COMMA, KeyCombination.SHORTCUT_DOWN)); } } }
92303938cea540c1ab75770914d2f034c1c0d0e0
4,649
java
Java
src/main/java/org/greports/annotations/Column.java
IhorPatychenko/report-engine
4e67b2dcb61cedba824aaf7b9a062a1d064a394f
[ "MIT" ]
null
null
null
src/main/java/org/greports/annotations/Column.java
IhorPatychenko/report-engine
4e67b2dcb61cedba824aaf7b9a062a1d064a394f
[ "MIT" ]
1
2021-03-14T14:25:59.000Z
2021-03-14T14:25:59.000Z
src/main/java/org/greports/annotations/Column.java
IhorPatychenko/report-engine
4e67b2dcb61cedba824aaf7b9a062a1d064a394f
[ "MIT" ]
null
null
null
30.993333
122
0.635405
995,404
package org.greports.annotations; import org.apache.commons.lang3.StringUtils; import org.greports.converters.NotImplementedConverter; import org.greports.engine.ValueType; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE}) @Repeatable(Column.List.class) @Inherited @Documented public @interface Column { /** * Indicates the report's name which contains the column. * * @return {@link String} */ String[] reportName(); /** * Position of column in the report. * The columns will be ordered from lowest to highest position index. * In case of need to add a new column among the existing ones, * the floating part can be used to indicate the desired position. * * @return {@code float} */ float position(); /** * The value used to target attributes in a nested class. * @return {@link String} */ String target() default StringUtils.EMPTY; /** * An array of {@link CellValidator} to be applied to the column. * * @return {@link CellValidator} */ CellValidator[] cellValidators() default {}; /** * An array of {@link ColumnValidator} to be applied to the column. * * @return {@link ColumnValidator} */ ColumnValidator[] columnValidators() default {}; /** * A converter to be applied when the column value is being obtained. * * @return {@link Converter} */ Converter getterConverter() default @Converter(converterClass = NotImplementedConverter.class); /** * A converter to be applied when the data is being loaded. * * @return {@link Converter} */ Converter setterConverter() default @Converter(converterClass = NotImplementedConverter.class); /** * Column title. This text string will be used to search for * the corresponding translation in the translation file located in * the directory provided by the {@link Configuration#translationsDir()} * * @return {@link String} */ String title() default StringUtils.EMPTY; /** * Visualisation format to be displayed. * You can find information on how to create your own org.greports.styles * by going through this <a href="http://poi.apache.org/components/spreadsheet/quick-guide.html#DataFormats">link</a> * * @return {@link String} */ String format() default StringUtils.EMPTY; /** * The {@link ValueType} of the column. * * @return {@link ValueType} */ ValueType valueType() default ValueType.PLAIN_VALUE; /** * Column ID which will be used by other column if that one * is of formula type. Also can be used by {@link SpecialColumn} and {@link SpecialRowCell} * * @see ValueType#FORMULA * @return {@link String} */ String id() default StringUtils.EMPTY; /** * The value indicates whether the column has to fit the width of the longest cell. * This functionality is very expensive due to the large number of calculations to be performed. * Use only when necessary. * * @return {@code boolean} */ boolean autoSizeColumn() default false; /** * This value indicates the number of merged cells. * A count of merged cells needs to be grater o equals than 1. * If the value is greater than 1 means that the column will merge * cells of his right. Example: * position = 1 (first column), columnWidth = 2. In this case * the row will have the cells A1 and B1 merged in only one cell * which will be placed into A1 cell. * @return {@code int} */ int columnWidth() default 1; /** * The value of this attribute allows to enable the translation * of the cell content. * @return {@code boolean} */ boolean translate() default false; /** * Defines several {@link Column} annotations on the same element. * @see Column */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @Inherited @Documented @interface List { /** * @return {@link Column} array */ Column[] value(); } }
923039dbf7e58efc1b5205f2bc6c9519152532e1
7,349
java
Java
src/main/java/legalthings/lto_api/lto/core/Account.java
legendary614/lto-api.java
dfc2f2bf15cba43918af19cf8cdf3519772f5280
[ "MIT" ]
null
null
null
src/main/java/legalthings/lto_api/lto/core/Account.java
legendary614/lto-api.java
dfc2f2bf15cba43918af19cf8cdf3519772f5280
[ "MIT" ]
null
null
null
src/main/java/legalthings/lto_api/lto/core/Account.java
legendary614/lto-api.java
dfc2f2bf15cba43918af19cf8cdf3519772f5280
[ "MIT" ]
null
null
null
28.265385
144
0.636277
995,405
package legalthings.lto_api.lto.core; import legalthings.lto_api.utils.core.JsonObject; import legalthings.lto_api.utils.main.CryptoUtil; import legalthings.lto_api.utils.main.StringUtil; public class Account { /** * Account public address * @var string */ public byte[] address; /** * Sign kyes * @var object */ public JsonObject sign; /** * Encryption keys * @var object */ public JsonObject encrypt; /** * Get a random nonce * @codeCoverageIgnore * * @return string */ protected byte[] getNonce() { return CryptoUtil.random_bytes(CryptoUtil.crypto_box_noncebytes()); } /** * Get base58 encoded address * * @param string encoding 'raw', 'base58' or 'base64' * @return string */ public String getAddress(String encoding) { return address != null ? encode(address, encoding) : null; } public String getAddress() { return getAddress("base58"); } /** * Get base58 encoded public sign key * * @param string $encoding 'raw', 'base58' or 'base64' * @return string */ public String getPublicSignKey(String encoding) { return sign != null ? encode(sign.getByte("publickey"), encoding) : null; } public String getPublicSignKey() { return getPublicSignKey("base58"); } /** * Get base58 encoded public encryption key * * @param string $encoding 'raw', 'base58' or 'base64' * @return string */ public String getPublicEncryptKey(String encoding) { return encrypt != null ? encode(encrypt.getByte("publickey"), encoding) : null; } public String getPublicEncryptKey() { return getPublicEncryptKey("base58"); } /** * Create an encoded signature of a message. * * @param string $message * @param string $encoding 'raw', 'base58' or 'base64' * @return string */ public String sign(String message, String encoding) { if (sign == null || sign.getByte("secretkey") == null) { throw new RuntimeException("Unable to sign message; no secret sign key"); } byte[] signature = CryptoUtil.crypto_sign_detached(message.getBytes(), sign.getByte("secretkey")); return encode(signature, encoding); } public String sign(String message) { if (sign == null || sign.getByte("secretkey") == null) { throw new RuntimeException("Unable to sign message; no secret sign key"); } byte[] signature = CryptoUtil.crypto_sign_detached(message.getBytes(), sign.getByte("secretkey")); return encode(signature, "base58"); } /** * Sign an event * * @param Event $event * @return $event */ public Event signEvent(Event event) { event.signkey = getPublicSignKey(); event.signature = sign(event.getMessage()); event.hash = event.getHash(); return event; } /** * Verify a signature of a message * * @param string $signature * @param string $message * @param string $encoding signature encoding 'raw', 'base58' or 'base64' * @return boolean */ public boolean verify(String signature, String message, String encoding) { if (sign == null || sign.getByte("publickey") == null) { throw new RuntimeException("Unable to verify message; no public sign key"); } byte[] rawSignature = decode(signature, encoding); return rawSignature.length == CryptoUtil.crypto_sign_bytes() && sign.getByte("publickey").length == CryptoUtil.crypto_sign_publickeybytes() && CryptoUtil.crypto_sign_verify_detached(rawSignature, message.getBytes(), sign.getByte("publickey")); } public boolean verify(String signature, String message) { return verify(signature, message, "base58"); } /** * Encrypt a message for another account. * The nonce is appended. * * @param Account $recipient * @param string $message * @return string */ public byte[] encryptFor(Account recipient, String message) { if (encrypt == null || encrypt.getByte("secretkey") == null) { throw new RuntimeException("Unable to encrypt message; no secret encryption key"); } if (recipient.encrypt == null || recipient.encrypt.getByte("publickey") == null) { throw new RuntimeException("Unable to encrypt message; no public encryption key for recipient"); } byte[] nonce = getNonce(); byte[] retEncrypt = CryptoUtil.crypto_box(nonce, message.getBytes(), recipient.encrypt.getByte("publickey"), encrypt.getByte("secretkey")); byte[] ret = new byte[retEncrypt.length + nonce.length]; System.arraycopy(retEncrypt, 0, ret, 0, retEncrypt.length); System.arraycopy(nonce, 0, ret, retEncrypt.length, nonce.length); return ret; } /** * Decrypt a message from another account. * * @param Account $sender * @param string $cyphertext * @return string */ public byte[] decryptFrom(Account sender, byte[] ciphertext) { if (encrypt == null || encrypt.getByte("secretkey") == null) { throw new RuntimeException("Unable to decrypt message; no secret encryption key"); } if (sender.encrypt == null || sender.encrypt.getByte("publickey") == null) { throw new RuntimeException("Unable to decrypt message; no public encryption key for recipient"); } byte[] encryptedMessage = new byte[ciphertext.length - 24]; System.arraycopy(ciphertext, 0, encryptedMessage, 0, ciphertext.length - 24); byte[] nonce = new byte[24]; System.arraycopy(ciphertext, ciphertext.length - 24, nonce, 0, 24); return CryptoUtil.crypto_box_open(nonce, encryptedMessage, encrypt.getByte("publickey"), sender.encrypt.getByte("secretkey")); } /** * Create a new event chain for this account * * @return EventChain * @throws \BadMethodCallException */ public EventChain createEventChain() { EventChain chain = new EventChain(); chain.initFor(this); return chain; } protected static String encode(String string, String encoding ) { if (encoding == "base58") { string = StringUtil.base58Encode(string); } if (encoding == "base64" ) { string = StringUtil.base64Encode(string); } return string; } protected static String encode(byte[] string, String encoding ) { if (encoding == "base58") { return StringUtil.base58Encode(string); } if (encoding == "base64" ) { return StringUtil.base64Encode(string); } return null; } protected static String encode(String string) { return encode(string, "base58"); } protected static String encode(byte[] string) { return encode(string, "base58"); } /** * Base58 or base64 decode a string * * @param string $string * @param string $encoding 'raw', 'base58' or 'base64' * @return string */ protected static byte[] decode(String string, String encoding) { if (encoding == "base58" ) { return StringUtil.base58Decode(string); } if (encoding == "base64" ) { return StringUtil.base64Decode(string); } return null; } protected static byte[] decode(String string) { return decode(string, "base58"); } }
92303c11465d29d4cc2b54ebf37d061bfc9524fc
1,396
java
Java
src/SmartPanelDemo/EmpDept/src/test/hr/common/EmpViewRowImplMsgBundle_it.java
amruth006/adf-samples-master
72636df21c9df5ddcc78752ff9e8da51928d033e
[ "UPL-1.0" ]
38
2017-11-05T11:52:29.000Z
2022-03-20T15:19:44.000Z
src/SmartPanelDemo/EmpDept/src/test/hr/common/EmpViewRowImplMsgBundle_it.java
amruth006/adf-samples-master
72636df21c9df5ddcc78752ff9e8da51928d033e
[ "UPL-1.0" ]
null
null
null
src/SmartPanelDemo/EmpDept/src/test/hr/common/EmpViewRowImplMsgBundle_it.java
amruth006/adf-samples-master
72636df21c9df5ddcc78752ff9e8da51928d033e
[ "UPL-1.0" ]
37
2017-10-10T00:01:08.000Z
2022-03-07T01:43:39.000Z
36.736842
93
0.632521
995,406
/* Copyright 2010, 2017, Oracle and/or its affiliates. All rights reserved. */ package test.hr.common; import oracle.jbo.common.JboResourceBundle; // --------------------------------------------------------------- // --- File generated by Oracle Business Components for Java. // --------------------------------------------------------------- public class EmpViewRowImplMsgBundle_it extends JboResourceBundle { /** * * This is the default constructor (do not remove) */ public EmpViewRowImplMsgBundle_it() { } /** * * @return an array of key-value pairs. */ public Object[][] getContents() { return super.getMergedArray(sMessageStrings, super.getContents()); } static final Object[][] sMessageStrings = { {"SalaryPercentageOfManager_TOOLTIP", "Percentuale dello stipendio del responsabile"}, {"ManagersSalary_LABEL", "Stipendio del Responsabile"}, {"SalaryPercentageOfManager_LABEL", "Pct del Responsabile"}, {"WorksInDeptno_TOOLTIP", "Il dipartimento in cui lavora questo impiegato"}, {"SalaryPercentageOfManager_FMT_FORMATTER", "oracle.jbo.format.DefaultNumberFormatter"}, {"SalaryPercentageOfManager_FMT_FORMAT", "0.00%"}, {"Mgr_LABEL", "Responsabile"}, {"ManagersSalary_TOOLTIP", "Stipendio mensile lordo del responsabile"}, {"WorksInDeptno_LABEL", "Dipartimento"}}; }
92303c1b2a7081b400682ba180a01355c1d824de
26,215
java
Java
output/dc8bc1d624b947e5b0b4b1f27d8b97e1.java
comprakt/comprakt-fuzz-tests
c0082d105d7c54ad31ab4ea461c3b8319358eaaa
[ "Apache-2.0", "MIT" ]
null
null
null
output/dc8bc1d624b947e5b0b4b1f27d8b97e1.java
comprakt/comprakt-fuzz-tests
c0082d105d7c54ad31ab4ea461c3b8319358eaaa
[ "Apache-2.0", "MIT" ]
null
null
null
output/dc8bc1d624b947e5b0b4b1f27d8b97e1.java
comprakt/comprakt-fuzz-tests
c0082d105d7c54ad31ab4ea461c3b8319358eaaa
[ "Apache-2.0", "MIT" ]
null
null
null
40.022901
317
0.496548
995,407
class jid { public static void A0g (String[] rxsm) { boolean[][] dqBNoopgi; ; ; ; } public static void iEs54eSA9I7ud (String[] OpJC_reaCzK8) { ; ; jGH BEAT7jDB5H6_a = !VGCF_Gl.RyhQyHrR_h() = LrzJjDdsn.Hg3T0Ov9kE; boolean[][][] o5bkh5KiDp = -cP7h().dW7(); } public int[][] si; public void XI; public int[][] nrC2t8; public static void xFgr16tuDB (String[] Hr6FFUdYXaQzrV) { boolean Qp = !!!!( !TYSEQempz.Aiy5GsU_9REw()).EdYV = ( this.gsxvwJlgGgN).pI9EJ1vJJgMg; return --false[ -XdBLt[ -t[ !new hTeWxjIXc6qCS[ new E7XGzLkmErhxh[ -this.bN5IF0p][ ( !9.tYamAwhQrXHHJD).YHoWc84Z()]][ !!---!!!!-cVaJ.GphTN()]]]]; ; int[] zo6_xU = null[ !!!true.EybSlUU()] = -new ECT99laTA().GJThEbaZ(); while ( !-!xeB30BKg8MeGU()[ this.z4n0Zg]) while ( -( !---!null[ -qaSivLR3vMJ5P5()[ null.EnD0VMAWNn]]).asYzjKyfTe) ; LbB2YZ q = -( new int[ !false.Mp1d_()].cgJC()).Tm7GxumFAfagk = -!-true.fLT4q(); int[][][] tHigmXn3qJM; boolean dkKK_EV; ; boolean A_z2 = FKpdYQbt3j().gRA = -new M1[ -false[ false[ !!null[ !--false[ new wh7dZ9Bv7Bc[ 46663244.o28OGD7LjnaK_K].wD]]]]].e_xbI(); { void EqJE; void[] y4wL; SHFMNhx19coKi[] zqqHJ3cLFCPf; int r; return; void[][] YcAI0HQg9n4891; int[][] MlXrZErsKDSX5; int RM1XGjcqnOVf; return; boolean nyO; void[][] ESeDNKDM; return; Y_EJkvo1FAh Ck0oKyk; boolean Y_kx_rKqPXOzB; ; false.oWzPY(); while ( -null.pJn) if ( -DUIjuUIUI[ !4689.ZAOmOTMpFU7LkD()]) ; int[][] AKQ8OcN9t5; boolean V8FsAOfoZ; if ( ----sU()[ rM9D32ID23._()]) while ( AUM57X().AIJHZsx) while ( -new iG9gG3[ ----!!true.XoVLR()].WE()) new q6CJB6EaTOd5w()[ -_hNaAsLJ3d()[ false.bZme8PuWqr]]; } boolean Z9B9P = null.XX_fx2w5amwMt(); tbwpJOmwbKarZu[][][][] gyJYp98rtpmfWM; int[][] iiQARdmRvPJ2; boolean VeVdbQ; } public void[][][] IeB3fraIpE4 (void[][] bzKjetC, boolean oZg3, int[] aapNFYofzDZiEj, boolean[] SPUPv_) throws DfkEAa { { { if ( false.EoUtIv2Pk()) { e[] xvYMlR; } } GfRAuUpN7RkLqX DUVHQvPRgM0; } boolean z; CH eeozL2We; int z0ITB = !!zX().HFghST0Fiz = ocU.FweiAAOdP7; ; ; { { boolean[] ag5E0AQ1; } } true[ !-true[ -( rnKv5Gmo2().i1X)[ --SD[ --!!this.Ir()]]]]; X_djkp zeJQK8pigy0V7 = -new Tv()[ this.QIo84NCZYsvOu] = !-false.pednv6B; ZFCu W1BeA3; return true.mUz1H; ; boolean[][] zEwI; { kccHKf6ORhDf[] OOIs67pHHbVq; boolean Mhjx5p8; void[] fqZ; while ( ( -( -( !-!( !671159178.TITr3BU__bbG()).tYINWLNPq9e())[ !!046.QWeB6Iv]).V()).jdbK3P8oGG_5_y) while ( 95847.e9IP4r1iL_i) ; int uzat7Ju; FzXlVuM0nfj Rx9a9ZhceONWlM; } if ( null.XdcCNxQQ()) while ( ---073.XlLHTuoq) !Bi()[ false[ -e4()[ new int[ !true.Tl1NogBc][ --( new Tra[ new ch()[ false.SalR8CkAisk()]].jpORiIC4).bxdg]]]]; while ( ( ( X6b().rdZdW).WJmbQS5rC()).yzSIiwabB) ; { ; boolean jg5GmMMXL4; { boolean[][] pEQaiunaw; } ; VZFrNllSJx9blo()[ -new AXDasAYlWQ51bn[ -new Vmli_().hRFqtz].enUBsdu_iZc()]; !-false[ -8[ -!-null.jT6N()]]; int EHfTghdfnJ; z_WP9F6yKulPa7[][][][][] NIxzx; while ( true.XaDZ8a_tEjG1j) if ( !null.Q1Ujld_Uo()) ; UCiYXa vbh1Md; ; { while ( -true.Shx9R3LndUCE9_()) !--wL5RDIr99h2gXx().A7jS_x1AE1arth(); } if ( 38904.XuGbdEhyELc) { int ElIaTNh; } ; int[] IGt; int[] mZtte6D; return; if ( -4812.Hd()) ; } if ( true.LsAk8OF9zTJ0ZP()) ; } public static void U (String[] O7NPCH) throws flBu5v8g { return; } public static void ATZ (String[] FSbumkXc) throws M2_9g { void[][] c9p7bbncp_ = ZF6().o90U2EWQ; !new WsO8Zpw48ct1t()[ -new TojG9().OlagDGrQ3dh9()]; return null.qfpNaRe6V8r1L(); ; { return; boolean[] Rh9GBGD4vC7pY; return; if ( -!---!!false.MQTtDn4q6K) while ( -!!null[ !this.Yldm4md]) while ( new qYu8Aedj6g[ true.hQ9gufNsirs8F()].dbFrl4f) { return; } void[] sQpqlfj5; int lv5dXeyik2cD4s; void m; Qr0rrFRQDTm6g[] jRWoJVRQ28s; } boolean SH; { void[] CcuwCY0J2NTM1w; return; } return; void aufccvbYiCJ4 = !-04.tKbLDz() = -!!4113.d5TJaBO4Fn(); boolean O0a0lrYHrwW0lm = ( true[ -429361572[ null[ 79805.k3n0DOyw()]]]).vl(); while ( -631.gec5YqV2f()) ; !--true.LgyKuZQtIujU; ; lw8m3E zC1AfX = new boolean[ -!!( new kwS()[ null[ true[ new IUPvef9T().TVRuq9QM()]]]).K763()].N837xR9Rvb6Cl = -09052._YcEwtv(); { while ( 4.Hf3mT01IlqS) if ( !true.udWsCWk7SStTG) if ( -!this.ls9()) if ( -!new NC6zuFrq6JUz_()[ false.Y]) return; v6DOAwHF_pB5[][][] QbAfDvOj; ; boolean V9UMtmoL6p; if ( -true.hzQvDdBXcc()) null[ this.ZS9T4w]; void Lfh; while ( this.OC()) false.bNlDJ0ATLTK; { int[] BMio9i; } } return !!new boolean[ !true.Fgkv()]._; int zdFQkSxBbgc = new void[ new X[ false.X2()].qWU()][ y7a_dMTnfEn.DXu5bmhKpq]; { boolean[][] V; int Bf0U; int[] Y; { int yvXU6CEaJL; } while ( new int[ false.S9].L67ujZYuC()) while ( gMWzqH[ this[ this[ -this.g7N8vI]]]) !true[ -( !this.P()).DG6VoQe6fNP]; void Is4KL1gD; ; xfC1wf6lurz[][] GI9oeQ5aa; while ( -!false.r6EllS) while ( new void[ pZ1PmK1dBDb().puf9I37DFLjmI()].w1r8S) if ( this[ !!-new dCWao().p1MXu()]) { int mYNZCA_QQ5XF; } { int[][] sba4EEa; } if ( !!!new void[ !-!null.pOLh()].LYb7nq4yx) ; !null.jTb6aHzIy26d9; { int lf; } int[][] sjrH; ; } } public boolean TANZOH06a2d; } class IXsfVBhC { public AI0r[] HA; public static void TCaZrK (String[] heAL) throws BovD { ; int[] eNSchtQjt5B99t = new int[ !!-!this[ vRe()[ -null[ ( !-false[ new HVjo75uHzR().SUhhDnZyCrKr])[ !45473[ !!!!false.mp()]]]]]][ --SFlU4tA1So[ null.xApr1qE7__O()]] = 610625770[ ---HGNfS0Se().PCVlfVxiwvyN()]; return false[ this.hvSPO()]; o OUkVY8GKtO; boolean I; ; if ( ---!( -new boolean[ ( new Gtd()[ new IU_l().lESIeBZ]).sG0Q][ --false.Zuca4IBxp])[ !t8OQNI0Pu()[ !!-this[ !new u7b2[ icltr().brEPZ8Rp0EG3i8][ false[ ---!new void[ new Px0U1ES3().SFuq()][ new Xk9aV()[ false.uYXMcIQu]]]]]]]) return;else ----!( !--null[ ( this.BOatcDJeh6RgmB).wBnNIHHiy5mkWg]).U5EbGL489M(); yPvkxz[][][][] K5cc2; while ( -!new qsRMc9().ob8n8Y()) ; return; ; ; int[][] DcmdXdhX; while ( ( -this.MnU).Ff2vy) return; Z0ei20r().Fi6(); } public static void Kt (String[] nth0PanpzrhHK) { if ( new int[ -new EYvzVJ().Uo5peUAoMyAZR][ !baK3qvxwz520V[ !-!-!true.qdG]]) if ( new tQ8N8JSS().x) -true.U(); ; while ( 104105934[ !null.fF7TfUExojb3()]) { this.ZKh; } void[][] dtXX48xNJJoH; boolean iifvBRwYmFYtF = new boolean[ -null.AAp()][ --new MYTW[ !new int[ false.G6glaJAc()].s()].LaY5xFWh6k]; return ( ( -!false[ !false[ -false[ -!lWkM()[ -null.CWOFathg4pg60()]]]]).uaVi()).yRHbEsVWs81rR3; while ( new XpKHDphLNb().E2oZzGjyOlZGwf()) while ( new xLba9[ this[ -new DtN9h4v65szld().i957HJiY()]].obGUH) true[ false.n]; while ( -!!FGCtvH().wlg()) new int[ this.diP()][ null[ !new f8eU8z().jn]]; return; if ( -!( !!new MkJsrPzQkcMcYj().edY6ayy5()).bpa) while ( -!Yg8V().FgojzH()) while ( 7[ 6.mLWAPvB()]) while ( !new y8UFsrZ1cB8()[ kFY.wbeMX0]) while ( xU8zlDeLqjIy[ !new boolean[ !pJTyoEnU8jqmn.Ct()].XgktQe()]) ; int Rl21a8mS = !03950507.Eg2uw = -----QCf7zXm2C.vfOSYahgza7EXA; return; { x es8SVV; void[][] Wr9BvYz; y_skU[] X52d; boolean[][][] aGJag1UFN1; int[] NnEhOw; { null.X0q1r(); } ; if ( false.Sd_wR0nxVJfTk) if ( !-!54.IgJ5vjhq800xK()) !false.e0yjl4_Dfsylzm(); { while ( --new int[ this[ -this[ --true.mYm]]].L4zZwk2fUo2) if ( -this.USDeRYXd()) if ( !----848.gwgqcIfMVchhZH()) ; } fffFrzI kCAkvp3hxb; !true.aieMAljd(); AkoD0LL().YLt4g5t86mUXAg; void[][] mmER9; while ( false.U) -true[ !!-null.bLI()]; ; -12625[ !true.LlqxGxQbefU_TE()]; } void telpe; boolean EnI2 = -false.YfsGmvpguy5QY_; l1IlqcCncO[][][][] NL = !!Wmoj.iho6U2(); ; boolean d20D5alz = ( !834.U()).V3hc1gbsK(); void[] rg17y = !---null.B3n3QVqH5vSMZV; true[ --this.aUJzvB]; } public int[] v2fzY (tsw G7QSGCN2wCt) throws la { int[][] xkxC; while ( -!qGM().dx8) -null.u6Jj85tWM2jzlZ(); int[] zGbG; if ( -!-!( !new iEcI()[ !!-!--true[ false.sjPVuif()]])[ !17151.lZLVJznsNX]) return; int b_HBr2fR; void[][][][] Yb6TgRnuusMiV; boolean jJDjTZVqv3 = -k0iZhGfd0xqp5.RoiF6xysrj4() = 2050.jt9_qUgqtv; if ( QexJy2MPXNrQ().sJeTso97_8) ; { int uVbeWg4Wu5wDd; U41G nKZd; void ut59; int qc; ; return; tI Fn22cFLVSn; void NZRK_5mTCt; void[][] WbD2MetV7e; } return !!!!!--!Qxy.dxYsgq8BVF; return !!-null[ !( !new Q1()[ !false.BCB2eplpDQ]).fG38LPaH6m]; boolean DqNoavQfXheaH = -GX()[ !!!new int[ true.D0pN][ --bX2TxNWaoI().sBqGZit25nuY0y()]]; while ( --true.zlSwUfnWnk()) while ( !null.ke) { return; } return; return !!31.EwuB8BLFJHQAB(); while ( 06.cxC3HNb()) false.W(); ; } public void[][][] KdkTlH_Lr; public int WJqdWIG5L; public int[] zrcw5O3 (int ZnD1eR5, boolean B, pNA DcEK1f5NKkkf, YFCSdpeAG PICLZV, void[][][] iNpUOHyR7e, void g9lp) { void[] Ny8JKL9iTH; ; int wdy4CE6bNQSI; return; if ( 41979805.o3oq1uy_pbMw) while ( new Qn().dJL()) -!-false.QwUDiPw2q_cYtZ;else while ( false.MGv) { boolean[][] cW_1HyXsm; } return; void[] SGPWfPcMZS1YQB; void[][] Dw2Jo_V; -!!!this.Cm8t(); return; void[][] Jgqz047zy = jDEMbjWhf().XGQXkoSe = !_JTZ2vOooD18JN.rXI(); boolean[] rts1b_8Q; } public void ed7quKN (int xx8F2ZUZV) throws FuaKM_23 { { ( 4831[ -( false.L70vIii7GDHwL).XDSGhfA875cM()]).jvMFORODU7W; return; int Jz0ss; { return; } if ( --null.V1()) { while ( -this.panwYSyE) { boolean[][][] Dc7NcpScuLnrT; } } return; void[][][] FQe_K; } int s = !-!!-!!!-null.yaE7AYGOixzyL(); while ( false[ new void[ new Td0b().sS1()][ new NPuww5g().L()]]) ; return 4416950[ true.o6PXiRRT()]; _z7 zAe0lLFAgwp = -!-!!this.k4WJrp7VcOd(); return -_H5vA8BXqN[ !!053340[ -!Q4uD5Hqg1qPLq[ --!!false[ this.ZGSANVS9jRtMGL]]]]; if ( 4283[ Etilpj2zg0id[ -this[ false.EVWdZjd()]]]) return;else while ( !true.kqBX1yymDvV()) while ( ---new rm0cS2P().plPHhQcn) if ( true.q) { return; } void[] Ypw4FDlBT2; TtsrqJ8XK wIR8s = -this.wPcOc1JKM() = !!3392.MBHX84S; wrksTzMtKM qEcdFbMg85mU; boolean[][][] x = -!true.UnUOMREiBA(); boolean vQ9bjEjFaLsP1 = !false[ false.cxBnYIG]; int[] xbabZ_bl1V5w; if ( RQauvIfW5pS5oj().u6JE8f()) while ( ( -false.GDonwJLv2())[ false.LCa5]) !-!true.OytEjMtI(); while ( !new iMEn5VwSMHQ().zXR42Ud8()) -this.wc2pXLC422b(); int[] hDlI70ApuJnjhv = !new WicTjWs4wA[ false.fAU5P9NtuG()].r5; int vZ3kWQBhqEa_u = --new T6Blw0w()[ !-this[ null.ExoFPwmi4hntZG]]; if ( -!new boolean[ !null[ ( -new int[ 6246823.wk9d29][ -uoae_datn5MA()[ --!-this.MZB0MIiTAYzc]]).uQS()]].bRG0X()) ;else while ( VsTCjfD[ !false.TW()]) while ( true.O1JW5SeumR7oR) ; int[][] e51j7R2r; } public void sIR; public static void P9YQxxaC0rYF (String[] t) { while ( -true[ -new q7WtuoUgz().HQWrRNEMQ5Y()]) if ( -!8942.lpnj) { boolean HC; } VGVXnLW YIKRT1DjnluKRS = new ZAT4H().Vz8(); boolean MxIUMhCN = new xkFteD8RAhG7().mjLv8PnXyDG = -null.w; void[][][][][][][] ZurSYNY6vTVQY = !this[ vrByN9_N7Y[ -( -!!new ax9mxXrSFF().G4XZDv).U3WEjHO7w]]; } public int[][] BBEyVksK11; public void[][] du8k9qW_b; } class h8y { } class JoKm_cF9r1jL { public boolean Cb1p9B; public static void LVBrU (String[] qtINcid5VR1) { while ( !--!null.OBS) ; ; while ( !false.h67E()) !( RaBf7BabY0iH[ new ITT7zp().FpO6()]).vwfpmQ9cyKVhF; M Wfn = ( !P77HWyOH0nVh().fhX94F_p9ZSsoT).siGpzAaN7 = -!!!new void[ ia2NCH[ -161513[ new boolean[ -new va9X()[ false.UuzyFi()]][ !!new Uweb3dqm().lGd5SHel()]]]].Zjapg83GR; return !-!false.ZtMx; boolean uI = true.q6CPRwEr() = new AqLGkG2TLOmA().PcKrEQJfyZeEBZ(); if ( null.vJBtWJ8h) eBKz0nJSwY7V_y()[ !!new gSMdFt59d().GO];else return; new boolean[ !true[ -!-new vWt8Q39V()[ 787078[ !!3903102[ new hG().rXncdbf]]]]].p(); void[][][] SNXifp8WwZY = 29804313[ false.sAn()]; int[][] fspKKmknpRF; int _cCGO0B5qwUm8u = new boolean[ new gAXyKdxkhtT().oS()][ new QLypBrfdBJR4M8()[ 237910663[ this.BMH5QI()]]] = OTIDQiUTBbJFF()[ -true.IRZ7TP()]; boolean[][] ful; if ( !!--!( -87383303.TvVpIG)[ -!!!!8[ -!this.dE()]]) if ( --HDAmUkI6yT0EhN().shcjvr5) !false.yLcy7E; int N_EP; -!( null.gGSZtTbRN9jFd).x6; } public NmeexsMLAAw[] FoDbUh () { return; while ( ---!!-!-( !false.AlHOr3OJwgQ).wU80mMJR()) while ( ( v4DEanC().QwzLzVawFGtvL)[ ( new void[ this.t].SQbC3m()).rEqz3bAJg_()]) while ( -!!this.Bc7mOq_f()) { int[][] yrpJ; } J0vuPbFL_TQum6 l0HW59JZy; Yf w6y; yo[][][] dd; ; return; int khG; OK9lpdD Il = null.CrqDEAI7sHn; BHFuvyLBNKwY[][] nc5MAbGINuOcE; void[] RsDMO; cC5K5x afUv1HjipWp4; void AI1mMG4J31; void[] qWo07gcqNrft; while ( 21.f) while ( !etv0l0CEL9I().qme2UQnxAaI2) ; return --!true[ LR5Ii[ -!!!01738.jfO58Y7DRat()]]; jxbtTPQB8Tjr[][][][] peg7_vmwsRZV7Y; while ( --new d[ !false[ -null.g7V01Yex()]][ !PbJoV.EVWBsOWEMR()]) skBYBniBSx0tMi().uudlnI4HE(); if ( -true.rtsg3) if ( !new x_2897RPQ().p1ldeMMQZiusZ()) new Q2asCEh().HxFw4lb1kpO3N(); } public static void Fi434YE (String[] AnHv) throws J { int[][][][][][][] cdCR; WOWBLeutEHfls[] M = !this.JpN9Mdv3G9Q() = -!reWK().CCyncBqLGAKysN; if ( !!q8y9sPw8.RPkbWz5DbcD2) return;else return; return; boolean[] s0k7irVPp_Xs3 = -new fHdlIEa()[ -WC[ !-false[ ( ( !669175626.DQ)[ !_KUZx()[ false.y]]).VbfY65DS4Eo]]] = 33081503.Wpv; yu7QJSjPutl_ Gt = this.X_rXo = true.kHYYn5u9(); return false.E; if ( null.F3E8HLCV7()) return;else return; V6 t_2 = null.Fe4NzU22AUKV; void Rpwgsz = true.b3r9tglr() = -!oh4AopDyp.r6bYu; void[] G11LBuzrtBsp = ( new boolean[ FxbWiesv.U3qIBdc()].XIOk88En5()).NwCb = Fvw0HuZQClQ().G; Hefw[][][] vmYc; int[] aT; return; ywg_TFc KyX8fRo6 = 534915.kX5KCA2WdiJRc = false.InY5ZZFEqeelz(); void QVGfuVEENUaP; while ( 810059605[ --28784[ wMId4q5I8dm7SX().XJKgieg0f943]]) ; ac[] K; return wwXTJ[ new JAw3lca0zVX2P()[ !new hnO[ !-new boolean[ -!-new void[ !true.gmI4wI9JVKW0][ ---rXmLVegCh8gRp.d8aIn45ZP]].HybiTjnj()][ !kwR2HMJ3LI()[ 267825.UAH390()]]]]; false.wb8SpqFs; } public void[] Lnde4PG3q (int RRzcpNgmiG, boolean fmWhoGgrra1FU, void[] yPBqHgfm, dwof7JJ3k tRQjac0EkVJ, void qsgWK455ha3f) { ; int B = ------true.Z = !-true[ -kpN2td9bPMT()[ --!-!-new int[ !--( ---LJbWb80.z9QL)[ false[ !this.qbPKRLrqnbwooQ]]].UpQzFw158L]]; while ( new vHUeDrXYwDw_().O3h5_tgTzS9RU_) while ( new sA().JCyTqxsfFFS) { { if ( !!new void[ !!true.AJSN0vHA08Rdm()].gpWKxe) while ( new void[ nrQux6Q0FN.h_mlZtgD][ -null.GKr7yY2aR7AN92()]) ; } } if ( ( -827512503[ -new boolean[ !new CAsnAWOv[ !new int[ this[ false.lQ53GG59Kzkdht]]._9lxb()][ -------this.nBk_XJ6()]].GAY()])[ !-!( 39270132.wIx())[ !false[ !lWmcs().wmlImb_]]]) ; } } class Ukuav0kKP9GSUI { } class LDEmG { public boolean CfyxmQK; public YKPjS60[] C3su6Bc5 () { boolean bL = -( -!-!-!null.TQLS_xHkOpnU).U62JNfuqd2_6v(); void qzbwQU1f2 = HgHAeja19.TSN29D; { void NL; false.Yod6T7aWJArn(); q65YmM3ru0sh hNQfGAcE; int[][][] rmQ; void[][] Nx1; return; boolean Vnb; -new HZ0NehxNInW().WQqHLA0; nh804EpsHae oZ3iHNl_YV; if ( !!476[ new int[ !-null.TE0QFVoWw1EHx].jVth2gtplo]) !-!!695369[ ( !-!true[ new Tw().jnPWF]).ee0b]; kw dgolFKkB; while ( true[ --this.Ws721OFIwwRZi()]) !!new boolean[ -( Ve().DkYkohur1QiIi)[ new Dpye29wcfdI1zz[ false.W3lnipjsWSFMB][ !!-!!new Q().Ck0rwOuS5QK()]]].skGm9_; } void L6n8ZOftce4U = new int[ bM.aB5iPLDH7xvHGZ()].KclAO3H(); RFlL().DvWMvg3mC89Srx(); ; void oJp = -this.sxnQARCwEipmzx(); ; fRF13mQrwA_bdf[] mVW9uMKq2Mr = -CwBTTOdTjCK7n().CEXXNLs() = new HHbwC()[ h9oUdY()._q03YFhk3()]; ys ITeQ1U; return; while ( this.nuWRTQ5_BNmIY()) -null[ Zcl7cFdRIOW[ !--XcjSVR().TYnH()]]; { WGMp5uvMCrut[][] BTFA1; int[] iR1; ; return; !!VTPHjT1().pH(); int S; } } public kYq2PwThQ[] x8z12IPdT2t; public int oY; public void[] U3 (H_20qIz[][][] JN, int[][][][][][] f6Ny3SXuow, void[] cTSx40vlSuA, int TerwcCENq6J, boolean[][] T54fbHUBg8fiOw) { { { ; } UtgK6hCVAUG WuL1HnX9IuO; void[] U9; if ( ( true[ !null.dsrpvk]).UshFF) ; return; int[] NIeFytA2FB; this.umU8moZMK; if ( -c.nEUj6LiOV3rI) while ( true.jLvu()) if ( -!-null.rnP) return; while ( !this[ xQzXa_m6_to()[ ( !this.lC7vqq847gk8C5()).BgW]]) --new SAlkRvOCS[ !( new ZeWC[ this.dh][ true.Tg8zPHK3SP()]).SMv5cg_q0O3TU].er7R5gFai(); void NGmZC2wa; -!-this.GgWTUIyY; mO_Wwv8FgrnWJq[][][] pC0zX4; boolean hMXCco; while ( true.sffuccyS) if ( !-false[ ZA().jmAtfUkoKiAg]) ; return; void bri5lF3EGEi3j; mTz9f[] XpArpKFYd4U; ; new boolean[ LtejsV[ !72[ TWC5.UyB5r_0Wj]]].O9Y39fnx7B1rw(); } ; return 389163[ !!( !false.h).vUSbYvXGsf]; ; { boolean[][][] bmnf5M; { return; } return; } return !true.MGimOAUXH92I; ; int GDb6Og = this.XJa8fI_MCXs() = f7t.N2Uu(); void uBPlFAZzeagmF = 790405[ !null.d4rLGvb71()]; { boolean pe6lUC5Y6OlYWF; while ( this[ new LFWAzCd1()[ new boolean[ ---new void[ this.F5qt()].u()].uQw]]) { { { pGwwsXSQ0i[][] j; } } } ; while ( -!this.aJzrX4mQO) return; new TzUZlQN5k843().E; boolean wij; --( new NkwuZO7Cq()[ new int[ !-!KZ5TZz7KohIN9()[ null[ true.L()]]][ new j7wou9aK[ 88233842.ri47uI7].r1XS()]]).mlBvORdZVWpY; while ( -!!null.h5miZrUIco()) ; { while ( ---!!( !new int[ null.Yi][ -!!new void[ true.od_M].b4uNqLWp0FTApt]).n) while ( new AMn3_1eU7VMr5[ new wDjORzbwAkYnh[ !-!!-this.h8up()].XPVWzigDR()].YRP4ZVivQ()) ; } !!-eZ4VfH().a3mmKSUcT; V6CQQU6b().sHIt; void[] ZkJfu__B; void paWjL7gKsp; { ; } } return; boolean wotf1VkC = -92941.WJ7 = --22.hTdyXK(); ; { Q_P[][][] y2s; return; int[] IR981tItdJ9mAD; int[][][] kIHPJmS8Ty3d; true.GKXGYUvO; void[] QbvF; void[][] g1nUg; ; ; Qr Ai; { void[][][] oVyKa; } ; void gcfG; ; boolean Jb2TJ; boolean[][] PtdYq; } while ( -OnALxv2vX3qr().Zun_oCBze) !!uJSU7JK0j5FI4.RV9Rd4ksx6UM(); void zRZip9b = -new BYq2().QQFVI2Kseo00() = !xZ().lZfUolPbuLkCVK(); if ( -LsdG5S_[ !T2Wm.WKOhZxJFPo8]) while ( this.q6lNjCI9eiC()) return; ; } public static void yTuc25Gx (String[] uNX3fc2IGjkqyE) throws vmiDr7c { boolean[][][][][][][][][][][] luEVe; int[][] kDz3Jz8ty72; void[][] XJ = true.Q() = gfd2iVAWiR[ new nm().q17()]; while ( v().g6V1X9FBhD()) if ( 853.N_OzftLU()) if ( ( null.cao8I())[ !-U2AO().xiJQx]) !-null[ -false.h]; boolean uUUss7pJ5IY0o0; boolean[] EibgvZMBHWVIDz; if ( ( true[ --850[ false.Qz]]).YisbJZsz()) ;else { while ( -( bYadh()[ -FQ28.UrmoUrXunJ])[ !!null.aD0oDs]) { return; } } boolean suqzGG; { while ( -null.A()) !!!QZ().TJYPeO8uuv; mDl[][][][] we; j55UJV04[][] GsGtF8vTN2N; int[] ir; void[] eIr; } while ( this.Vu6InDgFj()) -false.joEozaV; void EeP32Oq; int V1j = !( D93r[ this[ -HjhMpRlpX_.XB4bVc0Yxprgl]]).jvdwWU1jp5; void M8UKv__; if ( --( 87119914[ !new _z1ep()[ !!!xwOIz[ !this[ -!this.VWH8]]]]).B_pP5tD0lO) !new arT().Y9FAHZ; if ( false.laOh1LATrpH9B) new Gy().AWf9X;else if ( ( j().l2f71OVYC).mNf) ; -68.uZQcvsz(); } public static void sc37UAfxp21cyP (String[] lLFr) { return; boolean[][] vyDD8wFw9i; boolean QejdWyJlqpcTv = -true.M4; void vmKq = false.GvLsWYV0 = !-this.stpv5FdBG(); d2oQ45Acrk[][] ZsPDT = ( new int[ new void[ new mcOXvdu().zemW7UgoPI4()].Q7ZiI84Z()][ true.a9sW4eq()])[ Dw.tDqq17L7_ak]; if ( _teGG0().t()) { boolean[][] H19S; }else ; int tBoaph; while ( -!-d_YsPtI0dh[ false.VfkEX1]) return; int xR5STJT7wNIgJ; boolean[] QzDRoOpX; void[] h8bcnRDmt2r = new void[ -( -Vn0JEFdP0k6MB[ new Y4[ -this.uW1zOCWS2()].Mp])[ -!new void[ new void[ _z1LmhN().pGar][ ( !new qOa9().X1UeNCoxaKb)[ ---( true.v5FhC())[ -false.DRyBuIo2Y]]]].Y()]].N = c0VpLb_hy().CT; new cyDkXj().kO_Z_p9RcF3D_(); int[] R2Qbvfvz; } public static void vkqwHdf (String[] eoeuCoHx) throws kffKjdWFH { void uf1f = -new w426()[ --!!null.Diy()] = -new DIsM_4O42()[ new int[ -false[ ( true[ tJVzzwAbM()[ null.UXKFUyG]]).SL5V_bcB()]].uZ]; int[][][] wxm0TST3S8X0; while ( this.mtXGFk) while ( -false.UDJlo()) { boolean[] OV5sry5V13Y6uJ; } !( this[ !( !null.lWpliJnk7i)[ ( 44117858.muWBMJ9XnyOwg).XsIRbX()]])[ !-!null.vqZzZ5i3DIjkE()]; if ( OQi53JbiTu7x[ --!true.nDzjtlV]) ; boolean f8; ; Q4LTrw4j4 bPvuuTjH; boolean cW668qJA6dl = new o6BIJnK0SqSOV[ !-new boolean[ 772456572.Pl()].JN()].CRWys43p0V(); } public static void J (String[] C6) throws xYhVQ_WLBDh { boolean[][] QGvLfE7 = !true[ -xQdLGoOp().lJI()] = !false.JrdH(); int AZzD = false.JW3pJljoB; boolean[] eL = null.I = !true.XKEm4xLqD; while ( !--Xs.NGddd_LZc3Z) return; int GJuGK; return; ; yD3VQ[] Ior_1aaqBK; int[] XmQil66vhl5 = izV7iq[ -!!!true.PH] = 1289532.Xlb7lgTHVD5(); return -!-true.Wj_STuNfy(); } public boolean RctTAnBFJ; public S1AM9_NH5N19s[][] CLheMIUBo () { void[] bu; int[][] vFl1Owiq; int[] BojdFblEEMg = new YQ()[ 094677003.hILnndIjsv] = !xOKe4WOV0JzGu()[ !!--!new int[ 13.agvf].ndqfBD3O()]; while ( 849519.v) ; 61.gxGu(); } public void tAyZ6E; } class U071bPuUrmC { }
92303c2e1cf88f11848585fa48d80bc6b8e341a4
7,074
java
Java
clover-android-sdk/src/main/java/com/clover/sdk/v1/printer/job/ImagePrintJob.java
clover/clover-android-sdk
d9aaed6d6f590e378d8ac384f48a33c1df9e52e2
[ "Apache-2.0" ]
79
2015-02-05T08:09:30.000Z
2022-01-22T19:39:45.000Z
clover-android-sdk/src/main/java/com/clover/sdk/v1/printer/job/ImagePrintJob.java
clover/clover-android-sdk
d9aaed6d6f590e378d8ac384f48a33c1df9e52e2
[ "Apache-2.0" ]
38
2015-06-12T11:16:46.000Z
2022-02-23T22:25:38.000Z
clover-android-sdk/src/main/java/com/clover/sdk/v1/printer/job/ImagePrintJob.java
clover/clover-android-sdk
d9aaed6d6f590e378d8ac384f48a33c1df9e52e2
[ "Apache-2.0" ]
85
2015-01-22T07:50:27.000Z
2022-03-08T13:38:43.000Z
30.102128
155
0.667656
995,408
/* * Copyright (C) 2016 Clover Network, 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.clover.sdk.v1.printer.job; import android.accounts.Account; import android.content.Context; import android.graphics.Bitmap; import android.os.AsyncTask; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import android.util.Pair; import com.clover.sdk.internal.util.BitmapUtils; import com.clover.sdk.v1.printer.Category; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * This class requires WRITE_EXTERNAL_STORAGE permission. Declare the permission in your AndroidManifest.xml * <code> * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> * </code> * * @deprecated Use {@link ImagePrintJob2}. This class writes files into external storage that * are not cleaned up and can eventually exhaust the device's storage. */ @Deprecated public class ImagePrintJob extends PrintJob implements Parcelable { private static final String TAG = "ImagePrintJob"; private static final int WIDTH_MAX = 600; public static final int MAX_RECEIPT_WIDTH = 576; private static BitmapUtils mBitmapUtils = new BitmapUtils(); public static class Builder extends PrintJob.Builder { protected Bitmap bitmap; protected String urlString; public Builder bitmap(Bitmap bitmap) { this.bitmap = bitmap; return this; } public Builder urlString(String urlString) { this.urlString = urlString; return this; } /** * Forces the provided bitmap to be scaled down to the maximum allowed width. * <p/> * If used, this method must be invoked after the {@link #bitmap(Bitmap)} method. This method * performs possibly time-consuming calulations so it must be invoked on a background thread. */ public Builder maxWidth() { if (bitmap == null) { return this; } int width = bitmap.getWidth(); int height = bitmap.getHeight(); float scale = (float) WIDTH_MAX / width; int scaledHeight = (int) (height * scale); bitmap = Bitmap.createScaledBitmap(bitmap, WIDTH_MAX, scaledHeight, false); return this; } /** * Builds an instance. Performs some blocking IO so it must be invoked on a background thread. */ @Override public PrintJob build() { return new ImagePrintJob(this); } } public final File imageFile; protected String urlString; private static final String BUNDLE_KEY_IMAGE_FILE = "i"; @Deprecated protected ImagePrintJob(Bitmap bitmap, int flags) { this((ImagePrintJob.Builder) new Builder().bitmap(bitmap).flags(flags)); } protected ImagePrintJob(Builder builder) { super(builder); this.urlString = builder.urlString; File f = null; if (builder.bitmap != null) { try { f = writeImageFile(builder.bitmap); builder.bitmap.recycle(); } catch (IOException e) { Log.e(TAG, "unable to write image file", e); } } else { try { f = generateImageFileObject(); } catch (IOException e) { Log.e(TAG, "unable to create image file", e); } } imageFile = f; } @Override public Category getPrinterCategory() { return Category.RECEIPT; } public void print(Context context, Account account) { Log.w(TAG, "Using deprecated ImagePrintJob class, please switch to ImagePrintJob2"); Pair<Context, Account> params = new Pair<>(context,account); if (this.urlString != null) { new AsyncTask<Pair<Context, Account>, Void, Pair<Context, Account>>() { @Override protected Pair<Context, Account> doInBackground(Pair<Context, Account>... params) { try { Bitmap bitmap = mBitmapUtils.decodeSampledBitmapFromURL(urlString, MAX_RECEIPT_WIDTH); writeImageFile(imageFile, bitmap); return params[0]; } catch(Exception excep) { Log.e(TAG, "Error writing image to disk from url - " + urlString, excep); } return null; } @Override protected void onPostExecute(Pair<Context, Account> pair) { if(pair != null) { ImagePrintJob.super.print(pair.first, pair.second, null); } else { Log.e(TAG, "Print job aborted, error writing image to disk."); } } }.execute(params); } else { super.print(context, account, null); } } public static final Parcelable.Creator<ImagePrintJob> CREATOR = new Parcelable.Creator<ImagePrintJob>() { public ImagePrintJob createFromParcel(Parcel in) { return new ImagePrintJob(in); } public ImagePrintJob[] newArray(int size) { return new ImagePrintJob[size]; } }; protected ImagePrintJob(Parcel in) { super(in); Bundle bundle = in.readBundle(((Object)this).getClass().getClassLoader()); imageFile = new File(bundle.getString(BUNDLE_KEY_IMAGE_FILE)); // Add more data here, but remember old apps might not provide it! } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); Bundle bundle = new Bundle(); bundle.putString(BUNDLE_KEY_IMAGE_FILE, imageFile.getAbsolutePath()); // Add more stuff here dest.writeBundle(bundle); } private static File generateImageFileObject() throws IOException { File dir = new File("/sdcard", "clover" + File.separator + "image-print"); if (!dir.exists()) { if (!dir.mkdirs()) { Log.e(TAG, "Unable to create dir for ImagePrintJob. Did you forget to declare WRITE_EXTERNAL_STORAGE permission in your AndroidManifest.xml?"); } } File imageFile = File.createTempFile("image-", ".png", dir); return imageFile; } private static File writeImageFile(Bitmap bitmap) throws IOException { File imageFile = generateImageFileObject(); writeImageFile(imageFile, bitmap); return imageFile; } private static void writeImageFile(File imageFile, Bitmap bitmap) throws IOException { OutputStream os = null; try { os = new FileOutputStream(imageFile); bitmap.compress(Bitmap.CompressFormat.PNG, 100, os); } finally { if (os != null) { try { os.close(); } catch (IOException e) { } } } } @Override public void cancel() { if (imageFile != null) { imageFile.delete(); } } }
92303d8601cc97d69e29ec9a51d0c43f6ae18c1a
44,978
java
Java
KOST-Val/src/main/java/ch/kostceco/tools/kostval/validation/modulesiard/impl/ValidationEcolumnModuleImpl.java
rebplu/KOST-VAL
1537125425068d5faec3bc4f5263df715956ae76
[ "BSD-3-Clause-No-Nuclear-Warranty" ]
null
null
null
KOST-Val/src/main/java/ch/kostceco/tools/kostval/validation/modulesiard/impl/ValidationEcolumnModuleImpl.java
rebplu/KOST-VAL
1537125425068d5faec3bc4f5263df715956ae76
[ "BSD-3-Clause-No-Nuclear-Warranty" ]
null
null
null
KOST-Val/src/main/java/ch/kostceco/tools/kostval/validation/modulesiard/impl/ValidationEcolumnModuleImpl.java
rebplu/KOST-VAL
1537125425068d5faec3bc4f5263df715956ae76
[ "BSD-3-Clause-No-Nuclear-Warranty" ]
null
null
null
42.795433
101
0.702744
995,409
/* == KOST-Val ================================================================================== * The KOST-Val application is used for validate TIFF, SIARD, PDF/A, JP2, JPEG-Files and Submission * Information Package (SIP). Copyright (C) 2012-2018 Claire Roethlisberger (KOST-CECO), Christian * Eugster, Olivier Debenath, Peter Schneider (Staatsarchiv Aargau), Markus Hahn (coderslagoon), * Daniel Ludin (BEDAG AG) * ----------------------------------------------------------------------------------------------- * KOST-Val is a development of the KOST-CECO. All rights rest with the KOST-CECO. This application * is free software: you can redistribute it and/or modify it under the terms of the GNU General * Public License as published by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. BEDAG AG and Daniel Ludin hereby disclaims all copyright * interest in the program SIP-Val v0.2.0 written by Daniel Ludin (BEDAG AG). Switzerland, 1 March * 2011. This application 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 follow GNU General Public License for more details. You should have received a * copy of the GNU General Public License along with this program; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or see * <http://www.gnu.org/licenses/>. * ============================================================================================== */ package ch.kostceco.tools.kostval.validation.modulesiard.impl; import java.io.File; import java.util.Map; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.jdom2.*; import org.jdom2.input.SAXBuilder; import ch.enterag.utils.zip.EntryInputStream; import ch.enterag.utils.zip.FileEntry; import ch.enterag.utils.zip.Zip64File; import ch.kostceco.tools.kostval.exception.modulesiard.ValidationEcolumnException; import ch.kostceco.tools.kostval.validation.ValidationModuleImpl; import ch.kostceco.tools.kostval.validation.bean.SiardTable; import ch.kostceco.tools.kostval.validation.bean.ValidationContext; import ch.kostceco.tools.kostval.validation.modulesiard.ValidationEcolumnModule; /** Validierungsschritt E (Spalten-Validierung) Wurden die Angaben aus metadata.xml korrekt in die * tableZ.xsd-Dateien �bertragen? valid --> gleiche Spaltendefinitionen (Anzahl, Type, Nullable) * * * The module <code>ValidationEcolumnModule</code> validates the columns specified in the file * <code>metadata.xml</code> against the according XML schema files. * * <p> * The column validation process consists of three steps. a) The validation of the attribute count, * b) the validation of the attribute's occurrence - which conforms to the nullable attribute of the * table definition - and c) the validation of the attribute's type. The table columns are only * valid if - and only if - the three validation steps are completed successfully. * * The table and their columns are described in the file <code>metadata.xml</code> The element * <code> &lt;table&gt</code> and its children are decisive for the table description: <blockquote> * * <pre> * <code>&lt;table&gt</code> * <code>&lt;name&gtTABLE_NAME&lt;/name&gt</code> * <code>&lt;folder&gtFOLDER_NAME&lt;/folder&gt</code> * <code>&lt;description&gtDESCRIPTION&lt;/description&gt</code> * <code>&lt;columns&gt</code> * <code>&lt;column&gt</code> * <code>&lt;name&gtCOLUMN_NAME&lt;/name&gt</code> * <code>&lt;type&gtCOLUMN_TYPE&lt;/type&gt</code> * <code>&lt;typeOriginal&gtCOLUMN_ORIGINAL_TYPE&lt;/typeOriginal&gt</code> * <code>&lt;nullable&gt</code>COLUMN_MINIMAL_OCCURRENCE<code>&lt;nullable&gt</code> * <code>&lt;description&gt</code>COLUMN_DESCRIPTION<code>&lt;description&gt</code> * <code>&lt;/column&gt</code> * <code>&lt;/columns&gt</code> * <code>&lt;/table&gt</code> * </pre> * * </blockquote * * @author Do Olivier Debenath * @author Rc Claire Roethlisberger, KOST-CECO */ public class ValidationEcolumnModuleImpl extends ValidationModuleImpl implements ValidationEcolumnModule { // TODO: schema1 aus Beispiel funktioniert noch nicht (null) /* Validation Context */ private ValidationContext validationContext; /* Service related properties */ /* Validation error related properties */ private StringBuilder incongruentColumnCount; private StringBuilder incongruentColumnOccurrence; private StringBuilder incongruentColumnType; private StringBuilder warningColumnType; private StringBuilder incongruentColumnSequence; public static Map<String, String> configMapFinal = null; boolean udtColumn = false; /** Start of the column validation. The <code>validate</code> method act as a controller. First it * initializes the validation by calling the <code>validationPrepare()</code> method and * subsequently it starts the validation process by executing the validation subroutines: * <code>validateAttributeCount()</code>, <code>validateAttributeOccurrence()</code> and finally * <code>validateAttributeType()</code>. * * @param SIARD * archive containing the tables whose columns are to be validated * @exception ValidationEcolumnException * if the representation of the columns is invalid */ @Override public boolean validate( File valDatei, File directoryOfLogfile, Map<String, String> configMap ) throws ValidationEcolumnException { configMapFinal = configMap; // Informationen zur Darstellung "onWork" holen String onWork = configMap.get( "ShowProgressOnWork" ); /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim * entsprechenden Modul die property anzugeben: <property name="configurationService" * ref="configurationService" /> */ if ( onWork.equals( "no" ) ) { // keine Ausgabe } else { // Ausgabe SIP-Modul Ersichtlich das KOST-Val arbeitet System.out.print( "E " ); System.out.print( "\b\b\b\b\b" ); } // All over validation flag boolean valid = true; // Important validation flag boolean congruentColumnCount = false; ValidationContext validationContext = new ValidationContext(); validationContext.setSiardArchive( valDatei ); this.setValidationContext( validationContext ); try { // Initialize the validation context valid = (prepareValidation( this.getValidationContext() ) == false ? false : true); // Get the prepared SIARD tables from the validation context valid = (this.getValidationContext().getSiardTables() == null ? false : true); // Validates the number of the attributes congruentColumnCount = validateColumnCount( this.getValidationContext(), configMap ); if ( congruentColumnCount == false ) { valid = false; getMessageService().logError( getTextResourceService().getText( MESSAGE_XML_MODUL_E_SIARD ) + getTextResourceService().getText( MESSAGE_XML_E_INVALID_ATTRIBUTE_COUNT, this.getIncongruentColumnCount() ) ); } // Validates the nullable property in metadata.xml if ( validateColumnOccurrence( this.getValidationContext(), configMap ) == false ) { valid = false; getMessageService().logError( getTextResourceService().getText( MESSAGE_XML_MODUL_E_SIARD ) + getTextResourceService().getText( MESSAGE_XML_E_INVALID_ATTRIBUTE_OCCURRENCE, this.getIncongruentColumnOccurrence() ) ); } // Validates the type of table attributes in metadata.xml if ( validateColumnType( this.getValidationContext(), configMap ) == false ) { valid = false; getMessageService().logError( getTextResourceService().getText( MESSAGE_XML_MODUL_E_SIARD ) + getTextResourceService().getText( MESSAGE_XML_E_INVALID_ATTRIBUTE_TYPE, this.getIncongruentColumnType() ) ); if ( udtColumn ) { // UDT-Warning mit ausgeben wenn vorhanden: MESSAGE_XML_E_TYPE_NOT_VALIDATED getMessageService().logError( getTextResourceService().getText( MESSAGE_XML_MODUL_E_SIARD ) + getTextResourceService().getText( MESSAGE_XML_E_TYPE_NOT_VALIDATED, this.getWarningColumnType() ) ); } } else { if ( udtColumn ) { // UDT-Warning mit ausgeben wenn vorhanden: MESSAGE_XML_E_TYPE_NOT_VALIDATED getMessageService().logError( getTextResourceService().getText( MESSAGE_XML_MODUL_E_SIARD ) + getTextResourceService().getText( MESSAGE_XML_E_TYPE_NOT_VALIDATED, this.getWarningColumnType() ) ); } } } catch ( Exception e ) { valid = false; getMessageService().logError( getTextResourceService().getText( MESSAGE_XML_MODUL_E_SIARD ) + getTextResourceService().getText( ERROR_XML_UNKNOWN, e.getMessage() ) ); } return valid; } /* [E.0]Prepares the validation process by executing the following steps and stores the resultsto * the validation context:- Getting the Properties- Initializing the SIARD path configuration- * Extracting the SIARD package- Pick up the metadata.xml- Prepares the XML Access (without * XPath)- Prepares the table information from metadata.xml */ @Override public boolean prepareValidation( ValidationContext validationContext ) throws IOException, JDOMException, Exception { // All over preparation flag boolean prepared = true; // Load the Java properties to the validation context boolean propertiesLoaded = initializeProperties(); if ( propertiesLoaded == false ) { prepared = false; getMessageService().logError( getTextResourceService().getText( MESSAGE_XML_MODUL_E_SIARD ) + getTextResourceService().getText( MESSAGE_XML_E_PROPERTIES_ERROR ) ); } // Initialize internal path configuration of the SIARD archive boolean pathInitialized = initializePath( validationContext, configMapFinal ); if ( pathInitialized == false ) { prepared = false; getMessageService().logError( getTextResourceService().getText( MESSAGE_XML_MODUL_E_SIARD ) + getTextResourceService().getText( MESSAGE_XML_E_PATH_ERROR ) ); } // Extract the SIARD archive and distribute the content to the validation context boolean siardArchiveExtracted = extractSiardArchive( validationContext, configMapFinal ); if ( siardArchiveExtracted == false ) { prepared = false; getMessageService().logError( getTextResourceService().getText( MESSAGE_XML_MODUL_E_SIARD ) + getTextResourceService().getText( MESSAGE_XML_E_EXTRACT_ERROR ) ); } // Pick the metadata.xml and load it to the validation context boolean metadataXMLpicked = pickMetadataXML( validationContext, configMapFinal ); if ( metadataXMLpicked == false ) { prepared = false; getMessageService().logError( getTextResourceService().getText( MESSAGE_XML_MODUL_E_SIARD ) + getTextResourceService().getText( MESSAGE_XML_E_METADATA_ACCESS_ERROR ) ); } // Prepare the XML configuration and store it to the validation context boolean xmlAccessPrepared = prepareXMLAccess( validationContext ); if ( xmlAccessPrepared == false ) { prepared = false; getMessageService().logError( getTextResourceService().getText( MESSAGE_XML_MODUL_E_SIARD ) + getTextResourceService().getText( MESSAGE_XML_E_XML_ACCESS_ERROR ) ); } // Prepare the data to be validated such as metadata.xml and the according XML schemas boolean validationDataPrepared = prepareValidationData( validationContext, configMapFinal ); if ( validationDataPrepared == false ) { prepared = false; getMessageService().logError( getTextResourceService().getText( MESSAGE_XML_MODUL_E_SIARD ) + getTextResourceService().getText( MESSAGE_XML_E_PREVALIDATION_ERROR ) ); } return prepared; } /* [E.1]Counts the columns in metadata.xml and compares it to the number of columns in the * according XML schema files */ private boolean validateColumnCount( ValidationContext validationContext, Map<String, String> configMap ) throws Exception { boolean showOnWork = true; int onWork = 410; // Informationen zur Darstellung "onWork" holen String onWorkConfig = configMap.get( "ShowProgressOnWork" ); if ( onWorkConfig.equals( "no" ) ) { // keine Ausgabe showOnWork = false; } else { // Ausgabe SIP-Modul Ersichtlich das KOST-Val arbeitet System.out.print( "E " ); System.out.print( "\b\b\b\b\b" ); } boolean validDatabase = true; StringBuilder namesOfInvalidTables = new StringBuilder(); List<SiardTable> siardTables = validationContext.getSiardTables(); // Initializing validation Logging // Iteratic over all SIARD tables to count the table attributes // and compare it to the number of registered attributes in the // according XML schemas for ( SiardTable siardTable : siardTables ) { int metadataXMLColumnsCount = siardTable.getMetadataXMLElements().size(); int tableXSDColumnsCount = siardTable.getTableXSDElements().size(); // Checks whether the columns count is correct if ( metadataXMLColumnsCount != tableXSDColumnsCount ) { int columnsDifference = metadataXMLColumnsCount - tableXSDColumnsCount; validDatabase = false; namesOfInvalidTables.append( (namesOfInvalidTables.length() > 0) ? ", " : "" ); namesOfInvalidTables.append( siardTable.getTableName() ); namesOfInvalidTables.append( ".xsd" ); namesOfInvalidTables.append( "(" ); namesOfInvalidTables.append( (columnsDifference > 0 ? "+" + columnsDifference : columnsDifference) ); namesOfInvalidTables.append( ")" ); } if ( showOnWork ) { if ( onWork == 410 ) { onWork = 2; System.out.print( "E- " ); System.out.print( "\b\b\b\b\b" ); } else if ( onWork == 110 ) { onWork = onWork + 1; System.out.print( "E\\ " ); System.out.print( "\b\b\b\b\b" ); } else if ( onWork == 210 ) { onWork = onWork + 1; System.out.print( "E| " ); System.out.print( "\b\b\b\b\b" ); } else if ( onWork == 310 ) { onWork = onWork + 1; System.out.print( "E/ " ); System.out.print( "\b\b\b\b\b" ); } else { onWork = onWork + 1; } } } // Writing back error log this.setIncongruentColumnCount( namesOfInvalidTables ); // Return the current validation state return validDatabase; } /* [E.2]Compares the <nullable> Element of the metadata.xml to the minOccurs attributesin the * according XML schemata */ private boolean validateColumnOccurrence( ValidationContext validationContext, Map<String, String> configMap ) throws Exception { boolean showOnWork = true; int onWork = 410; // Informationen zur Darstellung "onWork" holen String onWorkConfig = configMap.get( "ShowProgressOnWork" ); if ( onWorkConfig.equals( "no" ) ) { // keine Ausgabe showOnWork = false; } else { // Ausgabe SIP-Modul Ersichtlich das KOST-Val arbeitet System.out.print( "E " ); System.out.print( "\b\b\b\b\b" ); } boolean validTable; boolean validDatabase; List<SiardTable> siardTables = validationContext.getSiardTables(); StringBuilder namesOfInvalidTables = new StringBuilder(); StringBuilder namesOfInvalidColumns = new StringBuilder(); validDatabase = true; // Iterate over the SIARD tables and verify the nullable attribute for ( SiardTable siardTable : siardTables ) { String minOccurs = new String(); validTable = true; // Number of attributes in metadata.xml int metadataXMLColumnsCount = siardTable.getMetadataXMLElements().size(); // Number of attributes in schema.xsd int tableXSDColumnsCount = siardTable.getTableXSDElements().size(); /* Counter. In order to prevent indexOutOfBorder errors columnsCounter is assigned to the * smaller number of columns */ int columnCount = (metadataXMLColumnsCount >= tableXSDColumnsCount) ? tableXSDColumnsCount : metadataXMLColumnsCount; // Element/Attributes of the actual SIARD table List<Element> xmlElements = siardTable.getMetadataXMLElements(); // Elements/Attributes of the according XML schema List<Element> xsdElements = siardTable.getTableXSDElements(); Namespace xmlNamespace = validationContext.getXmlNamespace(); for ( int i = 0; i < columnCount; i++ ) { String nullable = new String(); // Actual Element of the metadata.xml Element xmlElement = xmlElements.get( i ); // Actual Element of the according XML schema Element xsdElement = xsdElements.get( i ); String nullableElementDescription = "nullable"; String minuOccursAttributeDescription = "minOccurs"; String nameAttributeDescription = "name"; // Value of the minOccurs attribute in the according XML schema if ( xsdElement.getAttributeValue( minuOccursAttributeDescription ) == null ) { minOccurs = "1"; } else { minOccurs = xsdElement.getAttributeValue( minuOccursAttributeDescription ); } if ( xmlElement.getChild( nullableElementDescription, xmlNamespace ) == null ) { nullable = "true"; } else { // Value of the nullable Element in metadata.xml nullable = xmlElement.getChild( nullableElementDescription, xmlNamespace ).getValue(); } // If the nullable Element is set to true and the minOccurs attribute is null if ( nullable.equalsIgnoreCase( "true" ) && minOccurs.equalsIgnoreCase( "1" ) ) { validTable = false; validDatabase = false; namesOfInvalidColumns.append( (namesOfInvalidColumns.length() > 0) ? ", " : "" ); namesOfInvalidColumns.append( xsdElement.getAttributeValue( nameAttributeDescription ) ); // If the nullable Element is set to true and the minOccurs attribute is set to zero } else if ( nullable.equalsIgnoreCase( "true" ) && minOccurs.equalsIgnoreCase( "0" ) ) { } else if ( nullable.equalsIgnoreCase( "false" ) && minOccurs.equalsIgnoreCase( "1" ) ) { } else if ( nullable.equalsIgnoreCase( "false" ) && minOccurs.equalsIgnoreCase( "0" ) ) { validTable = false; validDatabase = false; namesOfInvalidColumns.append( (namesOfInvalidColumns.length() > 0) ? ", " : "" ); namesOfInvalidColumns.append( xsdElement.getAttributeValue( nameAttributeDescription ) ); } } if ( validTable == false ) { namesOfInvalidTables.append( (namesOfInvalidTables.length() > 0) ? ", " : "" ); namesOfInvalidTables.append( siardTable.getTableName() ); namesOfInvalidTables.append( ".xsd" ); namesOfInvalidTables.append( "(" ); namesOfInvalidTables.append( namesOfInvalidColumns ); namesOfInvalidTables.append( ")" ); namesOfInvalidColumns = null; namesOfInvalidColumns = new StringBuilder(); } if ( showOnWork ) { if ( onWork == 410 ) { onWork = 2; System.out.print( "E- " ); System.out.print( "\b\b\b\b\b" ); } else if ( onWork == 110 ) { onWork = onWork + 1; System.out.print( "E\\ " ); System.out.print( "\b\b\b\b\b" ); } else if ( onWork == 210 ) { onWork = onWork + 1; System.out.print( "E| " ); System.out.print( "\b\b\b\b\b" ); } else if ( onWork == 310 ) { onWork = onWork + 1; System.out.print( "E/ " ); System.out.print( "\b\b\b\b\b" ); } else { onWork = onWork + 1; } } } // Writing back error log this.setIncongruentColumnOccurrence( namesOfInvalidTables ); return validDatabase; } /* [E.3]Compares the column types in the metadata.xml to the accordingXML schemata */ private boolean validateColumnType( ValidationContext validationContext, Map<String, String> configMap ) throws Exception { boolean showOnWork = true; int onWork = 410; // Informationen zur Darstellung "onWork" holen String onWorkConfig = configMap.get( "ShowProgressOnWork" ); if ( onWorkConfig.equals( "no" ) ) { // keine Ausgabe showOnWork = false; } else { // Ausgabe SIP-Modul Ersichtlich das KOST-Val arbeitet System.out.print( "E " ); System.out.print( "\b\b\b\b\b" ); } boolean validTable; udtColumn = false; boolean validDatabase; Properties properties = validationContext.getValidationProperties(); List<SiardTable> siardTables = validationContext.getSiardTables(); StringBuilder namesOfInvalidTables = new StringBuilder(); StringBuilder namesOfInvalidColumns = new StringBuilder(); StringBuilder namesOfUdtTables = new StringBuilder(); StringBuilder namesOfUdtColumns = new StringBuilder(); // List of all XML column elements to verify the allover sequence List<String> xmlElementSequence = new ArrayList<String>(); // List of all XSD column elements List<String> xsdElementSequence = new ArrayList<String>(); // Iterate over the SIARD tables and verify the column types validDatabase = true; for ( SiardTable siardTable : siardTables ) { // Elements of the actual SIARD table List<Element> xmlElements = siardTable.getMetadataXMLElements(); // Elements of the according XML schema List<Element> xsdElements = siardTable.getTableXSDElements(); // Number of attributes in metadata.xml int metadataXMLColumnsCount = xmlElements.size(); // Number of attributes in schema.xsd int tableXSDColumnsCount = xsdElements.size(); /* Counter. In order to prevent indexOutOfBorder errors columnsCounter is assigned to the * smaller number of columns */ int columnCount = (metadataXMLColumnsCount >= tableXSDColumnsCount) ? tableXSDColumnsCount : metadataXMLColumnsCount; validTable = true; udtColumn = false; // Verify whether the number of column elements in XML and XSD are equal for ( int i = 0; i < columnCount; i++ ) { Element xmlElement = xmlElements.get( i ); Element xsdElement = xsdElements.get( i ); // Retrieve the Elements name String xmlTypeElementName = "type"; String xsdTypeAttribute = "type"; String xsdAttribute = "name"; String leftSide = ""; String rightSide = ""; String columnName = xsdElement.getAttributeValue( xsdAttribute ); Namespace xmlNamespace = validationContext.getXmlNamespace(); if ( xmlElement.getChild( xmlTypeElementName, xmlNamespace ) == null || xmlElement.getChild( xmlTypeElementName, xmlNamespace ).getValue() == null ) { /* TODO: bei UDT stehen beide typen in den subelementen (beide null). UDT koennen wiederum * Array oder UDT enthalen und diese mehrfach. Entsprechend wird das noch nicht * unterstützt! */ udtColumn = true; // validDatabase = unverändert -> nur Warnung namesOfUdtColumns.append( (namesOfUdtColumns.length() > 0) ? ", " : "" ); namesOfUdtColumns.append( columnName ); // Keine Typenvalidierung dieser Spalte } else { // Typenvalidierung der Spalte möglich // Retrieve the original column type from metadata.xml leftSide = xmlElement.getChild( xmlTypeElementName, xmlNamespace ).getValue(); // Retrieve the original column type from table.xsd rightSide = xsdElement.getAttributeValue( xsdTypeAttribute ); if ( rightSide == null || rightSide == "" ) { /* null bei Array, weil type in jedem subelement steht (alle muessen gleich sein) */ List<Element> childListElement = xsdElement.getChildren(); for ( int y = 0; y < childListElement.size(); y++ ) { Element subElement = childListElement.get( y ); List<Element> arrayListElement = subElement.getChildren(); for ( int x = 0; x < arrayListElement.size(); x++ ) { Element subSubElement = arrayListElement.get( x ); List<Element> array2ListElement = subSubElement.getChildren(); String array0 = ""; String arrays = ""; for ( int z = 0; z < array2ListElement.size(); z++ ) { Element arrayElement = array2ListElement.get( z ); arrays = arrayElement.getAttributeValue( "type" ); if ( array0.equals( "" ) ) { array0 = arrays; rightSide = array0; } else { // alle arrys müssen den gleichen Typ haben if ( !array0.equalsIgnoreCase( arrays ) ) { validTable = false; validDatabase = false; namesOfInvalidColumns.append( (namesOfInvalidColumns.length() > 0) ? ", " : "" ); namesOfInvalidColumns.append( columnName ); getMessageService().logError( getTextResourceService().getText( MESSAGE_XML_MODUL_E_SIARD ) + getTextResourceService().getText( MESSAGE_XML_E_ARRAY, (siardTable.getTableName() + ".xsd(" + columnName + ")") ) ); } } } } } } String delimiter = "("; // Trim the column types - eliminates the brackets and specific numeric parameters String trimmedExpectedType = trimLeftSideType( leftSide, delimiter ); // Designing expected column type in table.xsd, called "rightSide" String pathToWorkDir = configMap.get( "PathToWorkDir" ); pathToWorkDir = pathToWorkDir + File.separator + "SIARD"; File metadataXml = new File( new StringBuilder( pathToWorkDir ).append( File.separator ) .append( "header" ).append( File.separator ).append( "metadata.xml" ).toString() ); Boolean version1 = FileUtils.readFileToString( metadataXml, "ISO-8859-1" ).contains( "http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd" ); Boolean version2 = FileUtils.readFileToString( metadataXml, "ISO-8859-1" ).contains( "http://www.bar.admin.ch/xmlns/siard/2/metadata.xsd" ); /* Interval wird vereinfacht kontrolliert */ if ( trimmedExpectedType.startsWith( "INTERVAL" ) || trimmedExpectedType.startsWith( "interval" ) ) { trimmedExpectedType = "INTERVAL"; } if ( version1 ) { trimmedExpectedType = "1_" + trimmedExpectedType; } else if ( version2 ) { trimmedExpectedType = "2_" + trimmedExpectedType; } String expectedType = properties.getProperty( trimmedExpectedType ); // In case the expected type does not exist if ( expectedType == null ) { System.out.print( " Unknown Type " + trimmedExpectedType ); expectedType = "Unknown Type"; validTable = false; validDatabase = false; namesOfInvalidColumns.append( (namesOfInvalidColumns.length() > 0) ? ", " : "" ); namesOfInvalidColumns.append( columnName + "(" + trimmedExpectedType + "=?)" ); } else if ( !expectedType.equalsIgnoreCase( rightSide ) ) { /* grössere strings dürfen auch als clob separat abgespeichert werden. Das gleiche für * hexBinarx als blob * * xs:hexBinary ~ blobType && xs:string ~ clobType */ if ( expectedType.equalsIgnoreCase( "xs:hexBinary" ) && rightSide.equalsIgnoreCase( "blobType" ) ) { // valid: xs:hexBinary ~ blobType } else if ( expectedType.equalsIgnoreCase( "xs:string" ) && rightSide.equalsIgnoreCase( "clobType" ) ) { // valid: xs:string ~ clobType } else { validTable = false; validDatabase = false; String columnNameLsRs = columnName + " (" + expectedType + " - " + rightSide + ")"; namesOfInvalidColumns.append( (namesOfInvalidColumns.length() > 0) ? ", " : "" ); namesOfInvalidColumns.append( columnNameLsRs ); } } // Convey the column types for the all over sequence test [E.4] xmlElementSequence.add( expectedType ); xsdElementSequence.add( rightSide ); } } if ( !validTable ) { namesOfInvalidTables.append( (namesOfInvalidTables.length() > 0) ? ", " : "" ); namesOfInvalidTables.append( siardTable.getTableName() ); namesOfInvalidTables.append( ".xsd" ); namesOfInvalidTables.append( "(" ); namesOfInvalidTables.append( namesOfInvalidColumns ); namesOfInvalidTables.append( ")" ); namesOfInvalidColumns = null; namesOfInvalidColumns = new StringBuilder(); } if ( udtColumn ) { namesOfUdtTables.append( (namesOfUdtTables.length() > 0) ? ", " : "" ); namesOfUdtTables.append( siardTable.getTableName() ); namesOfUdtTables.append( ".xsd" ); namesOfUdtTables.append( "(" ); namesOfUdtTables.append( namesOfUdtColumns ); namesOfUdtTables.append( ")" ); namesOfUdtColumns = null; namesOfUdtColumns = new StringBuilder(); } if ( showOnWork ) { if ( onWork == 410 ) { onWork = 2; System.out.print( "E- " ); System.out.print( "\b\b\b\b\b" ); } else if ( onWork == 110 ) { onWork = onWork + 1; System.out.print( "E\\ " ); System.out.print( "\b\b\b\b\b" ); } else if ( onWork == 210 ) { onWork = onWork + 1; System.out.print( "E| " ); System.out.print( "\b\b\b\b\b" ); } else if ( onWork == 310 ) { onWork = onWork + 1; System.out.print( "E/ " ); System.out.print( "\b\b\b\b\b" ); } else { onWork = onWork + 1; } } } this.setIncongruentColumnType( namesOfInvalidTables ); this.setWarningColumnType( namesOfUdtTables ); // Save the allover column elements for [E.4] validationContext.setXmlElementsSequence( xmlElementSequence ); validationContext.setXsdElementsSequence( xsdElementSequence ); this.setValidationContext( validationContext ); // Return the current validation state return validDatabase; } /* Internal helper methods */ /* [E.0.1]Load the validation properties */ private boolean initializeProperties() throws IOException { ValidationContext validationContext = this.getValidationContext(); boolean successfullyCommitted = false; // Initializing the validation context properties String propertiesName = "/validation.properties"; // Get the properties file InputStream propertiesInputStream = getClass().getResourceAsStream( propertiesName ); Properties properties = new Properties(); properties.load( propertiesInputStream ); validationContext.setValidationProperties( properties ); // Log messages are created inside the if clause to catch missing properties errors if ( validationContext.getValidationProperties() != null ) { successfullyCommitted = true; } else { successfullyCommitted = false; throw new IOException(); } return successfullyCommitted; } /* [E.0.2]Initializes the SIARD path configuration */ private boolean initializePath( ValidationContext validationContext, Map<String, String> configMap ) throws Exception { boolean successfullyCommitted = false; StringBuilder headerPath = new StringBuilder(); StringBuilder contentPath = new StringBuilder(); // Initializing validation Logging String workDir = configMap.get( "PathToWorkDir" ); // Preparing the internal SIARD directory structure headerPath.append( workDir ); headerPath.append( File.separator ); headerPath.append( "header" ); contentPath.append( workDir ); contentPath.append( File.separator ); contentPath.append( "content" ); // Writing back the directory structure to the validation context validationContext.setHeaderPath( headerPath.toString() ); validationContext.setContentPath( contentPath.toString() ); if ( validationContext.getHeaderPath() != null && validationContext.getContentPath() != null ) { successfullyCommitted = true; this.setValidationContext( validationContext ); } else { successfullyCommitted = false; this.setValidationContext( null ); throw new Exception(); } return successfullyCommitted; } /* [E.0.5]Prepares the XML access */ private boolean prepareXMLAccess( ValidationContext validationContext ) throws JDOMException, IOException, Exception { boolean successfullyCommitted = false; File metadataXML = validationContext.getMetadataXML(); InputStream inputStream = new FileInputStream( metadataXML ); SAXBuilder builder = new SAXBuilder(); Document document = builder.build( inputStream ); // Assigning JDOM Document to the validation context validationContext.setMetadataXMLDocument( document ); String xmlPrefix = "pre"; String xsdPrefix = "xs"; // Setting the namespaces to access metadata.xml and the different table.xsd Element rootElement = document.getRootElement(); String namespaceURI = rootElement.getNamespaceURI(); Namespace xmlNamespace = Namespace.getNamespace( xmlPrefix, namespaceURI ); Namespace xsdNamespace = Namespace.getNamespace( xsdPrefix, namespaceURI ); // Assigning prefix to the validation context validationContext.setXmlPrefix( xmlPrefix ); validationContext.setXsdPrefix( xsdPrefix ); // Assigning namespace info to the validation context validationContext.setXmlNamespace( xmlNamespace ); validationContext.setXsdNamespace( xsdNamespace ); if ( validationContext.getXmlNamespace() != null && validationContext.getXsdNamespace() != null && validationContext.getXmlPrefix() != null && validationContext.getXsdPrefix() != null && validationContext.getMetadataXMLDocument() != null ) { this.setValidationContext( validationContext ); successfullyCommitted = true; } else { successfullyCommitted = false; this.setValidationContext( null ); throw new Exception(); } return successfullyCommitted; } /* Trimming the search terms for column type validation */ private String trimLeftSideType( String leftside, String delimiter ) throws Exception { return (leftside.indexOf( delimiter ) > -1) ? leftside.substring( 0, leftside.indexOf( delimiter ) ) : leftside; } /* [E.0.3]Extracting the SIARD packages */ private boolean extractSiardArchive( ValidationContext validationContext, Map<String, String> configMap ) throws FileNotFoundException, IOException, Exception { boolean showOnWork = true; int onWork = 410; // Informationen zur Darstellung "onWork" holen String onWorkConfig = configMap.get( "ShowProgressOnWork" ); if ( onWorkConfig.equals( "no" ) ) { // keine Ausgabe showOnWork = false; } else { // Ausgabe SIP-Modul Ersichtlich das KOST-Val arbeitet System.out.print( "E " ); System.out.print( "\b\b\b\b\b" ); } boolean sucessfullyCommitted = false; // Initializing the access to the SIARD archive Zip64File zipfile = new Zip64File( validationContext.getSiardArchive() ); List<FileEntry> fileEntryList = zipfile.getListFileEntries(); String pathToWorkDir = configMap.get( "PathToWorkDir" ); File tmpDir = new File( pathToWorkDir ); // Initializing the resulting Hashmap containing all files, indexed by its absolute path HashMap<String, File> extractedSiardFiles = new HashMap<String, File>(); // Iterating over the whole SIARD archive for ( FileEntry fileEntry : fileEntryList ) { if ( !fileEntry.isDirectory() ) { byte[] buffer = new byte[8192]; EntryInputStream eis = zipfile.openEntryInputStream( fileEntry.getName() ); File newFile = new File( tmpDir, fileEntry.getName() ); File parent = newFile.getParentFile(); if ( !parent.exists() ) { parent.mkdirs(); } FileOutputStream fos = new FileOutputStream( newFile ); for ( int iRead = eis.read( buffer ); iRead >= 0; iRead = eis.read( buffer ) ) { fos.write( buffer, 0, iRead ); } extractedSiardFiles.put( newFile.getPath(), newFile ); eis.close(); fos.close(); // set to null eis = null; fos = null; } if ( showOnWork ) { if ( onWork == 410 ) { onWork = 2; System.out.print( "E- " ); System.out.print( "\b\b\b\b\b" ); } else if ( onWork == 110 ) { onWork = onWork + 1; System.out.print( "E\\ " ); System.out.print( "\b\b\b\b\b" ); } else if ( onWork == 210 ) { onWork = onWork + 1; System.out.print( "E| " ); System.out.print( "\b\b\b\b\b" ); } else if ( onWork == 310 ) { onWork = onWork + 1; System.out.print( "E/ " ); System.out.print( "\b\b\b\b\b" ); } else { onWork = onWork + 1; } } } validationContext.setSiardFiles( extractedSiardFiles ); // Checks whether the siard extraction succeeded or not if ( validationContext.getSiardFiles() != null ) { this.setValidationContext( validationContext ); sucessfullyCommitted = true; } else { this.setValidationContext( null ); sucessfullyCommitted = false; throw new Exception(); } return sucessfullyCommitted; } /* [E.0.4]Pick up the metadata.xml from the SIARD package */ private boolean pickMetadataXML( ValidationContext validationContext, Map<String, String> configMap ) throws Exception { boolean successfullyCommitted = false; StringBuilder pathToMetadataXML = new StringBuilder(); pathToMetadataXML.append( configMap.get( "PathToWorkDir" ) ); pathToMetadataXML.append( File.separator ); pathToMetadataXML.append( "header" ); pathToMetadataXML.append( File.separator ); pathToMetadataXML.append( "metadata.xml" ); HashMap<String, File> siardFiles = validationContext.getSiardFiles(); File metadataXML = siardFiles.get( pathToMetadataXML.toString() ); // Retreave the metadata.xml from the SIARD archive and writes it back to the validation context validationContext.setMetadataXML( metadataXML ); // Checks whether the metadata.xml could be picked up if ( validationContext.getMetadataXML() != null ) { this.setValidationContext( validationContext ); successfullyCommitted = true; } else { this.setValidationContext( null ); successfullyCommitted = false; throw new Exception(); } return successfullyCommitted; } /* [E.0.6]Preparing the data to be validated */ private boolean prepareValidationData( ValidationContext validationContext, Map<String, String> configMap ) throws JDOMException, IOException, Exception { boolean showOnWork = true; int onWork = 410; // Informationen zur Darstellung "onWork" holen String onWorkConfig = configMap.get( "ShowProgressOnWork" ); if ( onWorkConfig.equals( "no" ) ) { // keine Ausgabe showOnWork = false; } else { // Ausgabe SIP-Modul Ersichtlich das KOST-Val arbeitet System.out.print( "E " ); System.out.print( "\b\b\b\b\b" ); } boolean successfullyCommitted = false; Namespace xmlNamespace = validationContext.getXmlNamespace(); // Gets the tables to be validated List<SiardTable> siardTables = new ArrayList<SiardTable>(); Document document = validationContext.getMetadataXMLDocument(); Element rootElement = document.getRootElement(); String workingDirectory = configMap.get( "PathToWorkDir" ); String siardSchemasElementsName = "schemas"; // Gets the list of <schemas> elements from metadata.xml List<Element> siardSchemasElements = rootElement.getChildren( siardSchemasElementsName, xmlNamespace ); for ( Element siardSchemasElement : siardSchemasElements ) { // Gets the list of <schema> elements from metadata.xml List<Element> siardSchemaElements = siardSchemasElement.getChildren( "schema", xmlNamespace ); // Iterating over all <schema> elements for ( Element siardSchemaElement : siardSchemaElements ) { String schemaFolderName = siardSchemaElement.getChild( "folder", xmlNamespace ).getValue(); if ( siardSchemaElement.getChild( "tables", xmlNamespace ) != null ) { Element siardTablesElement = siardSchemaElement.getChild( "tables", xmlNamespace ); List<Element> siardTableElements = siardTablesElement.getChildren( "table", xmlNamespace ); // Iterating over all containing table elements for ( Element siardTableElement : siardTableElements ) { Element siardColumnsElement = siardTableElement.getChild( "columns", xmlNamespace ); List<Element> siardColumnElements = siardColumnsElement.getChildren( "column", xmlNamespace ); String tableName = siardTableElement.getChild( "folder", xmlNamespace ).getValue(); SiardTable siardTable = new SiardTable(); siardTable.setMetadataXMLElements( siardColumnElements ); siardTable.setTableName( tableName ); String siardTableFolderName = siardTableElement.getChild( "folder", xmlNamespace ) .getValue(); StringBuilder pathToTableSchema = new StringBuilder(); // Preparing access to the according XML schema file pathToTableSchema.append( workingDirectory ); pathToTableSchema.append( File.separator ); pathToTableSchema.append( "content" ); pathToTableSchema.append( File.separator ); pathToTableSchema.append( schemaFolderName.replaceAll( " ", "" ) ); pathToTableSchema.append( File.separator ); pathToTableSchema.append( siardTableFolderName.replaceAll( " ", "" ) ); pathToTableSchema.append( File.separator ); pathToTableSchema.append( siardTableFolderName.replaceAll( " ", "" ) ); pathToTableSchema.append( ".xsd" ); // Retrieve the according XML schema File tableSchema = validationContext.getSiardFiles().get( pathToTableSchema.toString() ); SAXBuilder builder = new SAXBuilder(); Document tableSchemaDocument = builder.build( tableSchema ); Element tableSchemaRootElement = tableSchemaDocument.getRootElement(); Namespace namespace = tableSchemaRootElement.getNamespace(); // Getting the tags from XML schema to be validated Element tableSchemaComplexType = tableSchemaRootElement.getChild( "complexType", namespace ); Element tableSchemaComplexTypeSequence = tableSchemaComplexType.getChild( "sequence", namespace ); List<Element> tableSchemaComplexTypeElements = tableSchemaComplexTypeSequence .getChildren( "element", namespace ); siardTable.setTableXSDElements( tableSchemaComplexTypeElements ); siardTables.add( siardTable ); // Writing back the List off all SIARD tables to the validation context validationContext.setSiardTables( siardTables ); } } else { // Kein Fehler sondern leeres schema } } if ( showOnWork ) { if ( onWork == 410 ) { onWork = 2; System.out.print( "E- " ); System.out.print( "\b\b\b\b\b" ); } else if ( onWork == 110 ) { onWork = onWork + 1; System.out.print( "E\\ " ); System.out.print( "\b\b\b\b\b" ); } else if ( onWork == 210 ) { onWork = onWork + 1; System.out.print( "E| " ); System.out.print( "\b\b\b\b\b" ); } else if ( onWork == 310 ) { onWork = onWork + 1; System.out.print( "E/ " ); System.out.print( "\b\b\b\b\b" ); } else { onWork = onWork + 1; } } } if ( validationContext.getSiardTables().size() > 0 ) { this.setValidationContext( validationContext ); successfullyCommitted = true; } else { this.setValidationContext( null ); successfullyCommitted = false; throw new Exception(); } return successfullyCommitted; } // Setter and Getter methods /** @return the validationContext */ public ValidationContext getValidationContext() { return validationContext; } /** @param validationContext * the validationContext to set */ public void setValidationContext( ValidationContext validationContext ) { this.validationContext = validationContext; } /** @return the incongruentColumnCount */ public StringBuilder getIncongruentColumnCount() { return incongruentColumnCount; } /** @param incongruentColumnCount * the incongruentColumnCount to set */ public void setIncongruentColumnCount( StringBuilder incongruentColumnCount ) { this.incongruentColumnCount = incongruentColumnCount; } /** @return the incongruentColumnOccurrence */ public StringBuilder getIncongruentColumnOccurrence() { return incongruentColumnOccurrence; } /** @param incongruentColumnOccurrence * the incongruentColumnOccurrence to set */ public void setIncongruentColumnOccurrence( StringBuilder incongruentColumnOccurrence ) { this.incongruentColumnOccurrence = incongruentColumnOccurrence; } /** @return the incongruentColumnType */ public StringBuilder getIncongruentColumnType() { return incongruentColumnType; } /** @param incongruentColumnType * the incongruentColumnType to set */ public void setIncongruentColumnType( StringBuilder incongruentColumnType ) { this.incongruentColumnType = incongruentColumnType; } /** @return the warningColumnType */ public StringBuilder getWarningColumnType() { return warningColumnType; } /** @param warningColumnType * the warningColumnType to set */ public void setWarningColumnType( StringBuilder warningColumnType ) { this.warningColumnType = warningColumnType; } /** @return the incongruentColumnSequence */ public StringBuilder getIncongruentColumnSequence() { return incongruentColumnSequence; } /** @param incongruentColumnSequence * the incongruentColumnSequence to set */ public void setIncongruentColumnSequence( StringBuilder incongruentColumnSequence ) { this.incongruentColumnSequence = incongruentColumnSequence; } }
92303f4f4a8568d4b2f57017573907bb137313a5
1,120
java
Java
src/test/java/org/monarchinitiative/svart/UnknownContigTest.java
exomiser/svart
33322d5e73085ceff3a45cc8bd93d4a69a572ee8
[ "BSD-3-Clause" ]
6
2021-03-31T19:17:34.000Z
2022-01-24T12:38:55.000Z
src/test/java/org/monarchinitiative/svart/UnknownContigTest.java
exomiser/svart
33322d5e73085ceff3a45cc8bd93d4a69a572ee8
[ "BSD-3-Clause" ]
11
2021-06-17T20:08:22.000Z
2022-02-02T13:56:28.000Z
src/test/java/org/monarchinitiative/svart/UnknownContigTest.java
exomiser/svart
33322d5e73085ceff3a45cc8bd93d4a69a572ee8
[ "BSD-3-Clause" ]
null
null
null
21.538462
74
0.633929
995,410
package org.monarchinitiative.svart; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; public class UnknownContigTest { private Contig unknown = Contig.unknown(); @Test public void id() { assertThat(unknown.id(), equalTo(0)); } @Test public void name() { assertThat(unknown.name(), equalTo("na")); } @Test public void sequenceRole() { assertThat(unknown.sequenceRole(), equalTo(SequenceRole.UNKNOWN)); } @Test public void length() { assertThat(unknown.length(), equalTo(0)); } @Test public void genBankAccession() { assertThat(unknown.genBankAccession(), equalTo("")); } @Test public void refSeqAccession() { assertThat(unknown.refSeqAccession(), equalTo("")); } @Test public void ucscName() { assertThat(unknown.ucscName(), equalTo("na")); } @Test public void isUnknown() { assertThat(unknown.isUnknown(), is(true)); } }
92303fc81f45d78d850649e0eef9293de149d808
1,170
java
Java
yard/skills/66-java/spboot/src/main/java/com/imooc/service/SysUserService.java
akondasif/bbxyard
fba1745949cef01b738caf12fa32bd32e8a17e43
[ "Apache-2.0" ]
1
2016-03-29T02:01:58.000Z
2016-03-29T02:01:58.000Z
yard/skills/66-java/spboot/src/main/java/com/imooc/service/SysUserService.java
akondasif/bbxyard
fba1745949cef01b738caf12fa32bd32e8a17e43
[ "Apache-2.0" ]
18
2019-02-13T09:15:25.000Z
2021-12-09T21:32:13.000Z
yard/skills/66-java/spboot/src/main/java/com/imooc/service/SysUserService.java
akondasif/bbxyard
fba1745949cef01b738caf12fa32bd32e8a17e43
[ "Apache-2.0" ]
2
2020-07-05T01:01:30.000Z
2020-07-08T22:33:06.000Z
15.6
90
0.536752
995,411
package com.imooc.service; import com.imooc.pojo.SysUser; import java.util.List; /** * 系统用户表访问类 */ public interface SysUserService { /** * 保存用户 * * @param user * @throws Exception */ public void saveUser(SysUser user) throws Exception; /** * 更新用户 * * @param user */ public void updateUser(SysUser user); /** * 删除用户 * * @param userId */ public void deleteUser(String userId); /** * 根据id查询用户 * * @param userId * @return */ public SysUser queryUserById(String userId); /** * 查询用户列表 * * @param user * @return */ public List<SysUser> queryUserList(SysUser user); /** * 分页查询用户列表 * * @param user * @param page * @param pageSize * @return */ public List<SysUser> queryUserListPaged(SysUser user, Integer page, Integer pageSize); /** * 自定义查询by id * * @param id * @return */ public SysUser queryUserByIdCustom(String id); /** * 保存用户,基于事务 * * @param user */ public void saveUserTransactional(SysUser user); }
92304011a698443e1605e89f8169b74b62323a9f
17,894
java
Java
stroom-search/stroom-expression-matcher/src/main/java/stroom/expression/matcher/ExpressionMatcher.java
CharlyOscarGolf/stroom
bbdd0833e6ff8895eacf3f59708a25eb06c8ed5b
[ "Apache-2.0" ]
2
2020-03-23T21:22:34.000Z
2020-03-23T21:23:14.000Z
stroom-search/stroom-expression-matcher/src/main/java/stroom/expression/matcher/ExpressionMatcher.java
CharlyOscarGolf/stroom
bbdd0833e6ff8895eacf3f59708a25eb06c8ed5b
[ "Apache-2.0" ]
null
null
null
stroom-search/stroom-expression-matcher/src/main/java/stroom/expression/matcher/ExpressionMatcher.java
CharlyOscarGolf/stroom
bbdd0833e6ff8895eacf3f59708a25eb06c8ed5b
[ "Apache-2.0" ]
null
null
null
39.941964
119
0.531463
995,412
/* * Copyright 2017 Crown Copyright * * 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 stroom.expression.matcher; import stroom.collection.api.CollectionService; import stroom.datasource.api.v2.AbstractField; import stroom.datasource.api.v2.DocRefField; import stroom.datasource.api.v2.FieldTypes; import stroom.dictionary.api.WordListProvider; import stroom.docref.DocRef; import stroom.query.api.v2.ExpressionItem; import stroom.query.api.v2.ExpressionOperator; import stroom.query.api.v2.ExpressionTerm; import stroom.query.api.v2.ExpressionTerm.Condition; import stroom.util.date.DateUtil; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; public class ExpressionMatcher { private static final String DELIMITER = ","; private final Map<String, AbstractField> fieldMap; private final WordListProvider wordListProvider; private final CollectionService collectionService; private final Map<DocRef, String[]> wordMap = new HashMap<>(); private final Map<String, Pattern> patternMap = new HashMap<>(); public ExpressionMatcher(final Map<String, AbstractField> fieldMap) { this.fieldMap = fieldMap; this.wordListProvider = null; this.collectionService = null; } public ExpressionMatcher(final Map<String, AbstractField> fieldMap, final WordListProvider wordListProvider, final CollectionService collectionService) { this.fieldMap = fieldMap; this.wordListProvider = wordListProvider; this.collectionService = collectionService; } public boolean match(final Map<String, Object> attributeMap, final ExpressionItem item) { if (item == null || !item.enabled()) { return true; } if (item instanceof ExpressionOperator) { final ExpressionOperator operator = (ExpressionOperator) item; if (operator.getChildren() == null || operator.getChildren().size() == 0) { return true; } switch (operator.getOp()) { case AND: for (final ExpressionItem child : operator.getChildren()) { if (!match(attributeMap, child)) { return false; } } return true; case OR: for (final ExpressionItem child : operator.getChildren()) { if (match(attributeMap, child)) { return true; } } return false; case NOT: return operator.getChildren().size() == 1 && !match(attributeMap, operator.getChildren().get(0)); } } else if (item instanceof ExpressionTerm) { return matchTerm(attributeMap, (ExpressionTerm) item); } throw new MatchException("Unexpected item type"); } private boolean matchTerm(final Map<String, Object> attributeMap, final ExpressionTerm term) { String termField = term.getField(); final Condition condition = term.getCondition(); String termValue = term.getValue(); final DocRef docRef = term.getDocRef(); // Clean strings to remove unwanted whitespace that the user may have // added accidentally. if (termField != null) { termField = termField.trim(); } if (termValue != null) { termValue = termValue.trim(); } // Try and find the referenced field. if (termField == null || termField.length() == 0) { throw new MatchException("Field not set"); } final AbstractField field = fieldMap.get(termField); if (field == null) { throw new MatchException("Field not found in index: " + termField); } final String fieldName = field.getName(); // Ensure an appropriate termValue has been provided for the condition type. if (Condition.IN_DICTIONARY.equals(condition) || Condition.IN_FOLDER.equals(condition) || Condition.IS_DOC_REF.equals(condition)) { if (docRef == null || docRef.getUuid() == null) { throw new MatchException("DocRef not set for field: " + termField); } } else { if (termValue == null || termValue.length() == 0) { throw new MatchException("Value not set"); } } final Object attribute = attributeMap.get(term.getField()); // Perform null/not null equality if required. if (Condition.IS_NULL.equals(condition)) { return attribute == null; } else if (Condition.IS_NOT_NULL.equals(condition)) { return attribute != null; } if (attribute == null) { throw new MatchException("Attribute '" + term.getField() + "' not found"); } // Create a query based on the field type and condition. if (field.isNumeric()) { switch (condition) { case EQUALS: { final long num1 = getNumber(fieldName, attribute); final long num2 = getNumber(fieldName, termValue); return num1 == num2; } case CONTAINS: { final long num1 = getNumber(fieldName, attribute); final long num2 = getNumber(fieldName, termValue); return num1 == num2; } case GREATER_THAN: { final long num1 = getNumber(fieldName, attribute); final long num2 = getNumber(fieldName, termValue); return num1 > num2; } case GREATER_THAN_OR_EQUAL_TO: { final long num1 = getNumber(fieldName, attribute); final long num2 = getNumber(fieldName, termValue); return num1 >= num2; } case LESS_THAN: { final long num1 = getNumber(fieldName, attribute); final long num2 = getNumber(fieldName, termValue); return num1 < num2; } case LESS_THAN_OR_EQUAL_TO: { final long num1 = getNumber(fieldName, attribute); final long num2 = getNumber(fieldName, termValue); return num1 <= num2; } case BETWEEN: { final long[] between = getNumbers(fieldName, termValue); if (between.length != 2) { throw new MatchException("2 numbers needed for between query"); } if (between[0] >= between[1]) { throw new MatchException("From number must lower than to number"); } final long num = getNumber(fieldName, attribute); return num >= between[0] && num <= between[1]; } case IN: return isNumericIn(fieldName, termValue, attribute); case IN_DICTIONARY: return isInDictionary(fieldName, docRef, field, attribute); default: throw new MatchException("Unexpected condition '" + condition.getDisplayValue() + "' for " + field.getType() + " field type"); } } else if (FieldTypes.DATE.equals(field.getType())) { switch (condition) { case EQUALS: { final long date1 = getDate(fieldName, attribute); final long date2 = getDate(fieldName, termValue); return date1 == date2; } case CONTAINS: { final long date1 = getDate(fieldName, attribute); final long date2 = getDate(fieldName, termValue); return date1 == date2; } case GREATER_THAN: { final long date1 = getDate(fieldName, attribute); final long date2 = getDate(fieldName, termValue); return date1 > date2; } case GREATER_THAN_OR_EQUAL_TO: { final long date1 = getDate(fieldName, attribute); final long date2 = getDate(fieldName, termValue); return date1 >= date2; } case LESS_THAN: { final long date1 = getDate(fieldName, attribute); final long date2 = getDate(fieldName, termValue); return date1 < date2; } case LESS_THAN_OR_EQUAL_TO: { final long date1 = getDate(fieldName, attribute); final long date2 = getDate(fieldName, termValue); return date1 <= date2; } case BETWEEN: { final long[] between = getDates(fieldName, termValue); if (between.length != 2) { throw new MatchException("2 dates needed for between query"); } if (between[0] >= between[1]) { throw new MatchException("From date must occur before to date"); } final long num = getDate(fieldName, attribute); return num >= between[0] && num <= between[1]; } case IN: return isDateIn(fieldName, termValue, attribute); case IN_DICTIONARY: return isInDictionary(fieldName, docRef, field, attribute); default: throw new MatchException("Unexpected condition '" + condition.getDisplayValue() + "' for " + field.getType() + " field type"); } } else { switch (condition) { case EQUALS: return isStringMatch(termValue, attribute); case CONTAINS: return isStringMatch(termValue, attribute); case IN: return isIn(fieldName, termValue, attribute); case IN_DICTIONARY: return isInDictionary(fieldName, docRef, field, attribute); case IN_FOLDER: return isInFolder(fieldName, docRef, field, attribute); case IS_DOC_REF: return isDocRef(fieldName, docRef, field, attribute); default: throw new MatchException("Unexpected condition '" + condition.getDisplayValue() + "' for " + field.getType() + " field type"); } } } private boolean isNumericIn(final String fieldName, final Object termValue, final Object attribute) { final long num = getNumber(fieldName, attribute); final long[] in = getNumbers(fieldName, termValue); if (in != null) { for (final long n : in) { if (n == num) { return true; } } } return false; } private boolean isDateIn(final String fieldName, final Object termValue, final Object attribute) { final long num = getDate(fieldName, attribute); final long[] in = getDates(fieldName, termValue); if (in != null) { for (final long n : in) { if (n == num) { return true; } } } return false; } private boolean isIn(final String fieldName, final Object termValue, final Object attribute) { final String[] termValues = termValue.toString().split(" "); for (final String tv : termValues) { if (isStringMatch(tv, attribute)) { return true; } } return false; } private boolean isStringMatch(final String termValue, final Object attribute) { final Pattern pattern = patternMap.computeIfAbsent(termValue, t -> Pattern.compile(t.replaceAll("\\*", ".*"))); if (attribute instanceof DocRef) { final DocRef docRef = (DocRef) attribute; if (pattern.matcher(docRef.getUuid()).matches()) { return true; } return pattern.matcher(docRef.getName()).matches(); } return pattern.matcher(attribute.toString()).matches(); } private boolean isInDictionary(final String fieldName, final DocRef docRef, final AbstractField field, final Object attribute) { final String[] lines = loadWords(docRef); if (lines != null) { for (final String line : lines) { if (field.isNumeric()) { if (isNumericIn(fieldName, line, attribute)) { return true; } } else if (FieldTypes.DATE.equals(field.getType())) { if (isDateIn(fieldName, line, attribute)) { return true; } } else { if (isIn(fieldName, line, attribute)) { return true; } } } } return false; } private boolean isInFolder(final String fieldName, final DocRef docRef, final AbstractField field, final Object attribute) { if (field instanceof DocRefField) { final String type = ((DocRefField) field).getDocRefType(); if (type != null && collectionService != null) { final Set<DocRef> descendants = collectionService.getDescendants(docRef, type); if (descendants != null && descendants.size() > 0) { if (attribute instanceof DocRef) { final String uuid = ((DocRef) attribute).getUuid(); if (uuid != null) { for (final DocRef descendant : descendants) { if (uuid.equals(descendant.getUuid())) { return true; } } } } } } } return false; } private boolean isDocRef(final String fieldName, final DocRef docRef, final AbstractField field, final Object attribute) { if (attribute instanceof DocRef) { final String uuid = ((DocRef) attribute).getUuid(); return (null != uuid && uuid.equals(docRef.getUuid())); } return false; } private String[] loadWords(final DocRef docRef) { if (wordListProvider == null) { return null; } return wordMap.computeIfAbsent(docRef, k -> { final String[] words = wordListProvider.getWords(docRef); if (words != null) { return words; } return null; }); } private long getDate(final String fieldName, final Object value) { try { if (value instanceof Long) { return (Long) value; } return DateUtil.parseNormalDateTimeString(value.toString()); // return new DateExpressionParser().parse(value, timeZoneId, nowEpochMilli).toInstant().toEpochMilli(); } catch (final RuntimeException e) { throw new MatchException("Expected a standard date value for field \"" + fieldName + "\" but was given string \"" + value + "\""); } } private long[] getDates(final String fieldName, final Object value) { final String[] values = value.toString().split(DELIMITER); final long[] dates = new long[values.length]; for (int i = 0; i < values.length; i++) { dates[i] = getDate(fieldName, values[i].trim()); } return dates; } private long getNumber(final String fieldName, final Object value) { try { if (value instanceof Long) { return (Long) value; } return Long.valueOf(value.toString()); } catch (final NumberFormatException e) { throw new MatchException( "Expected a numeric value for field \"" + fieldName + "\" but was given string \"" + value + "\""); } } private long[] getNumbers(final String fieldName, final Object value) { final String[] values = value.toString().split(DELIMITER); final long[] numbers = new long[values.length]; for (int i = 0; i < values.length; i++) { numbers[i] = getNumber(fieldName, values[i].trim()); } return numbers; } private static class MatchException extends RuntimeException { MatchException(final String message) { super(message); } } }
92304016df9d860d568faea327541e58be28b974
9,953
java
Java
src/main/java/net/daw/factory/ServiceFactory.java
kailw/wildcart
7671969a92b3bcc4f948e187801e039adde4010b
[ "MIT" ]
null
null
null
src/main/java/net/daw/factory/ServiceFactory.java
kailw/wildcart
7671969a92b3bcc4f948e187801e039adde4010b
[ "MIT" ]
null
null
null
src/main/java/net/daw/factory/ServiceFactory.java
kailw/wildcart
7671969a92b3bcc4f948e187801e039adde4010b
[ "MIT" ]
null
null
null
40.790984
93
0.410228
995,413
package net.daw.factory; import javax.servlet.http.HttpServletRequest; import net.daw.bean.ReplyBean; import net.daw.service.CarritoService; import net.daw.service.FacturaService; import net.daw.service.LineaService; import net.daw.service.ProductoService; import net.daw.service.TipoproductoService; import net.daw.service.TipousuarioService; import net.daw.service.UsuarioService; public class ServiceFactory { public static ReplyBean executeService(HttpServletRequest oRequest) throws Exception { String ob = oRequest.getParameter("ob"); String op = oRequest.getParameter("op"); ReplyBean oReplyBean = null; switch (ob) { case "tipousuario": TipousuarioService oTipousuarioService = new TipousuarioService(oRequest); switch (op) { case "get": oReplyBean = oTipousuarioService.get(); break; case "create": oReplyBean = oTipousuarioService.create(); break; case "update": oReplyBean = oTipousuarioService.update(); break; case "remove": oReplyBean = oTipousuarioService.remove(); break; case "getcount": oReplyBean = oTipousuarioService.getcount(); break; case "getpage": oReplyBean = oTipousuarioService.getpage(); break; default: oReplyBean = new ReplyBean(500, "Operation doesn't exist"); break; } break; case "carrito": CarritoService oCarritoService = new CarritoService(oRequest); switch (op) { case "add": oReplyBean = oCarritoService.add(); break; case "empty": oReplyBean = oCarritoService.empty(); break; case "show": oReplyBean = oCarritoService.show(); break; case "buy": oReplyBean = oCarritoService.buy(); break; case "reduce": oReplyBean = oCarritoService.reduce(); break; case "allproduct": oReplyBean = oCarritoService.totalproduct(); break; default: oReplyBean = new ReplyBean(500, "Operatin doesn't exist"); break; } break; case "usuario": UsuarioService oUsuarioService = new UsuarioService(oRequest); switch (op) { case "get": oReplyBean = oUsuarioService.get(); break; case "create": oReplyBean = oUsuarioService.create(); break; case "update": oReplyBean = oUsuarioService.update(); break; case "remove": oReplyBean = oUsuarioService.remove(); break; case "getcount": oReplyBean = oUsuarioService.getcount(); break; case "getpage": oReplyBean = oUsuarioService.getpage(); break; case "fill": oReplyBean = oUsuarioService.cargarUsuarios(); break; case "login": oReplyBean = oUsuarioService.login(); break; case "logout": oReplyBean = oUsuarioService.logout(); break; case "check": oReplyBean = oUsuarioService.check(); break; default: oReplyBean = new ReplyBean(500, "Operation doesn't exist"); break; } break; case "factura": FacturaService oFacturaService = new FacturaService(oRequest); switch (op) { case "get": oReplyBean = oFacturaService.get(); break; case "create": oReplyBean = oFacturaService.create(); break; case "update": oReplyBean = oFacturaService.update(); break; case "remove": oReplyBean = oFacturaService.remove(); break; case "getcount": oReplyBean = oFacturaService.getcount(); break; case "getpage": oReplyBean = oFacturaService.getpage(); break; case "getpagexusuario": oReplyBean = oFacturaService.getpageXusuario(); break; case "getcountfacturauser": oReplyBean = oFacturaService.getcountFacturaUser(); break; default: oReplyBean = new ReplyBean(500, "Operation doesn't exist"); break; } break; case "linea": LineaService oLineaService = new LineaService(oRequest); switch (op) { case "get": oReplyBean = oLineaService.get(); break; case "create": oReplyBean = oLineaService.create(); break; case "update": oReplyBean = oLineaService.update(); break; case "remove": oReplyBean = oLineaService.remove(); break; case "getcount": oReplyBean = oLineaService.getcount(); break; case "getpage": oReplyBean = oLineaService.getpage(); break; case "getlineafactura": oReplyBean = oLineaService.getLineaFactura(); break; case "getcountxlinea": oReplyBean = oLineaService.getcountxlinea(); break; default: oReplyBean = new ReplyBean(500, "Operation doesn't exist"); break; } break; case "producto": ProductoService oProductoService = new ProductoService(oRequest); switch (op) { case "get": oReplyBean = oProductoService.get(); break; case "create": oReplyBean = oProductoService.create(); break; case "update": oReplyBean = oProductoService.update(); break; case "remove": oReplyBean = oProductoService.remove(); break; case "getcount": oReplyBean = oProductoService.getcount(); break; case "getpage": oReplyBean = oProductoService.getpage(); break; case "fill": oReplyBean = oProductoService.cargarProductos(); break; case "addimage": oReplyBean = oProductoService.addimage(); break; default: oReplyBean = new ReplyBean(500, "Operation doesn't exist"); break; } break; case "tipoproducto": TipoproductoService oTipoproductoService = new TipoproductoService(oRequest); switch (op) { case "get": oReplyBean = oTipoproductoService.get(); break; case "create": oReplyBean = oTipoproductoService.create(); break; case "update": oReplyBean = oTipoproductoService.update(); break; case "remove": oReplyBean = oTipoproductoService.remove(); break; case "getcount": oReplyBean = oTipoproductoService.getcount(); break; case "getpage": oReplyBean = oTipoproductoService.getpage(); break; default: oReplyBean = new ReplyBean(500, "Operation doesn't exist"); break; } break; default: oReplyBean = new ReplyBean(500, "Object doesn't exist"); break; } return oReplyBean; } }
923041749a43fd100b673000b03392f53aae3bd9
4,583
java
Java
app/src/main/java/com/example/usedmarket/activity/AddActivity.java
2573722674/UsedMarket
a644960a2d0aa48d50bacd714b46bd84c6afc0f3
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/usedmarket/activity/AddActivity.java
2573722674/UsedMarket
a644960a2d0aa48d50bacd714b46bd84c6afc0f3
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/usedmarket/activity/AddActivity.java
2573722674/UsedMarket
a644960a2d0aa48d50bacd714b46bd84c6afc0f3
[ "Apache-2.0" ]
null
null
null
43.647619
115
0.484617
995,414
package com.example.usedmarket.activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.usedmarket.Config; import com.example.usedmarket.FunctionActivity; import com.example.usedmarket.R; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class AddActivity extends AppCompatActivity { private EditText activityName,userName,startTime,endTime,activityDetail; private Button addBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add); activityName=findViewById(R.id.activityName); userName=findViewById(R.id.userName); startTime=findViewById(R.id.startTime); endTime=findViewById(R.id.endTime); activityDetail=findViewById(R.id.activityDetail); addBtn=findViewById(R.id.addBtn); addBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ProgressDialog progressDialog=new ProgressDialog(AddActivity.this); progressDialog.setTitle("正在发布中"); progressDialog.setMessage("Posting..."); progressDialog.setCancelable(true); progressDialog.show(); new Thread(new Runnable() { @Override public void run() { OkHttpClient client=new OkHttpClient(); RequestBody requestBody=new FormBody.Builder() .add("user_name",userName.getText().toString()) .add("activity_name",activityName.getText().toString()) .add("start_time",startTime.getText().toString()) .add("end_time",endTime.getText().toString()) .add("activity_detail",activityDetail.getText().toString()) .build(); Request request=new Request.Builder() .url(Config.host+"/activity/post") .post(requestBody) .build(); Call call=client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { final String error=e.getMessage(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(AddActivity.this,error,Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String responseText=response.body().string(); try { JSONObject jsonObject=new JSONObject(responseText); if(jsonObject.getInt("code")==0){ runOnUiThread(new Runnable() { @Override public void run() { Intent intent=new Intent(AddActivity.this, FunctionActivity.class); startActivity(intent); finish(); } }); } } catch (JSONException e) { e.printStackTrace(); } } }); } }).start(); } }); } }
9230448ae498a558710e22217b2550127e4358e8
712
java
Java
src/test/java/umm3601/todos/GetTodosByBodyStringFromDB.java
UMM-CSci-3601-S19/lab-2-laly-and-aaron-w
ee709d7afa36c4ffddae7aa5756a2be49124a706
[ "MIT" ]
null
null
null
src/test/java/umm3601/todos/GetTodosByBodyStringFromDB.java
UMM-CSci-3601-S19/lab-2-laly-and-aaron-w
ee709d7afa36c4ffddae7aa5756a2be49124a706
[ "MIT" ]
22
2019-02-14T19:27:46.000Z
2019-02-19T18:59:06.000Z
src/test/java/umm3601/todos/GetTodosByBodyStringFromDB.java
UMM-CSci-3601-S19/lab-2-laly-and-aaron-w
ee709d7afa36c4ffddae7aa5756a2be49124a706
[ "MIT" ]
null
null
null
27.384615
84
0.73736
995,415
package umm3601.todos; import org.junit.Test; import java.io.IOException; import java.util.HashMap; import static junit.framework.TestCase.assertTrue; import static junit.framework.TestCase.assertEquals; public class GetTodosByBodyStringFromDB { @Test public void searchFor_sit_() throws IOException { TodosDatabase db = new TodosDatabase("src/main/data/todos.json"); Todo[] todos = db.listTodos(new HashMap<>()); Todo[] _sit_todos = db.getTodosByBodyString(todos, "sit"); for(Todo todo:_sit_todos) { assertTrue(todo.body.contains("sit")); } System.out.println(_sit_todos.length); assertEquals("Incorrect number of todos containing sit", 69, _sit_todos.length); } }
9230449a98a7326b00414993c313af90969d12a1
857
java
Java
AndroidStudio/projects/fundamentals/4th/PendingIntentSample/app/src/main/java/jp/mixi/sample/intent/pending/MainActivity.java
harus2rock/AndroidTraining
b10a35143295d0e4b2248502f46d659631680c71
[ "Apache-2.0" ]
746
2015-01-03T01:36:11.000Z
2022-03-23T10:14:26.000Z
AndroidStudio/projects/fundamentals/4th/PendingIntentSample/app/src/main/java/jp/mixi/sample/intent/pending/MainActivity.java
harus2rock/AndroidTraining
b10a35143295d0e4b2248502f46d659631680c71
[ "Apache-2.0" ]
108
2015-01-01T12:28:45.000Z
2022-01-21T05:04:17.000Z
AndroidStudio/projects/fundamentals/4th/PendingIntentSample/app/src/main/java/jp/mixi/sample/intent/pending/MainActivity.java
harus2rock/AndroidTraining
b10a35143295d0e4b2248502f46d659631680c71
[ "Apache-2.0" ]
314
2015-01-02T08:12:22.000Z
2022-01-21T05:06:13.000Z
35.708333
117
0.75846
995,416
package jp.mixi.sample.intent.pending; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Intent の準備。明示的 Intent でも、暗黙的 Intent でもどちらでも構わない Intent intent = new Intent(this, SubActivity.class); // PendingIntent オブジェクトの生成。このオブジェクトを他のアプリに渡すことで、引数に渡した Intent の送信を委ねることができる // PendingIntent は、Intent の送信先のコンポーネントの種類によって使い分けること // 第二引数の requestCode は、API リファレンスの記載に間違いがあり、Currently not used とあるが実際には利用されていることに注意する PendingIntent activityIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } }
92304542c4581c31307edff71eb039372fb6c43d
3,380
java
Java
spring-cloud-sleuth-zipkin/src/test/java/org/springframework/cloud/sleuth/zipkin/ServerPropertiesEndpointLocatorTests.java
vaquarkhan/spring-cloud-sleuth-Zipkins
634fa90a0df46168fa64bf0a19251b93ecebf989
[ "Apache-2.0" ]
1
2017-04-18T05:33:32.000Z
2017-04-18T05:33:32.000Z
spring-cloud-sleuth-zipkin/src/test/java/org/springframework/cloud/sleuth/zipkin/ServerPropertiesEndpointLocatorTests.java
vaquarkhan/spring-cloud-sleuth-Zipkins
634fa90a0df46168fa64bf0a19251b93ecebf989
[ "Apache-2.0" ]
null
null
null
spring-cloud-sleuth-zipkin/src/test/java/org/springframework/cloud/sleuth/zipkin/ServerPropertiesEndpointLocatorTests.java
vaquarkhan/spring-cloud-sleuth-Zipkins
634fa90a0df46168fa64bf0a19251b93ecebf989
[ "Apache-2.0" ]
null
null
null
36.344086
90
0.773669
995,417
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.springframework.cloud.sleuth.zipkin; import java.net.InetAddress; import java.net.UnknownHostException; import org.junit.Test; import org.mockito.Mockito; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.cloud.commons.util.InetUtils; import org.springframework.cloud.commons.util.InetUtilsProperties; import static org.assertj.core.api.Assertions.assertThat; public class ServerPropertiesEndpointLocatorTests { public static final byte[] ADDRESS1234 = { 1, 2, 3, 4 }; @Test public void portDefaultsTo8080() throws UnknownHostException { ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator( new ServerProperties(), "unknown", new ZipkinProperties(), localAddress(ADDRESS1234)); assertThat(locator.local().port).isEqualTo((short) 8080); } @Test public void portFromServerProperties() throws UnknownHostException { ServerProperties properties = new ServerProperties(); properties.setPort(1234); ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator( properties, "unknown", new ZipkinProperties(),localAddress(ADDRESS1234)); assertThat(locator.local().port).isEqualTo((short) 1234); } @Test public void portDefaultsToLocalhost() throws UnknownHostException { ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator( new ServerProperties(), "unknown", new ZipkinProperties(), localAddress(ADDRESS1234)); assertThat(locator.local().ipv4).isEqualTo(1 << 24 | 2 << 16 | 3 << 8 | 4); } @Test public void hostFromServerPropertiesIp() throws UnknownHostException { ServerProperties properties = new ServerProperties(); properties.setAddress(InetAddress.getByAddress(ADDRESS1234)); ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator( properties, "unknown", new ZipkinProperties(), localAddress(new byte[] { 4, 4, 4, 4 })); assertThat(locator.local().ipv4).isEqualTo(1 << 24 | 2 << 16 | 3 << 8 | 4); } @Test public void appNameFromProperties() throws UnknownHostException { ServerProperties properties = new ServerProperties(); ZipkinProperties zipkinProperties = new ZipkinProperties(); zipkinProperties.getService().setName("foo"); ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator( properties, "unknown", zipkinProperties,localAddress(ADDRESS1234)); assertThat(locator.local().serviceName).isEqualTo("foo"); } private InetUtils localAddress(byte[] address) throws UnknownHostException { InetUtils mocked = Mockito.spy(new InetUtils(new InetUtilsProperties())); Mockito.when(mocked.findFirstNonLoopbackAddress()) .thenReturn(InetAddress.getByAddress(address)); return mocked; } }
9230486b21683ce8f67c00be5aa6e3ce944d6941
13,029
java
Java
src/java/info/jdavid/font/subset/Woff2Writer.java
programingjd/font_subset
390aa5d4bb6fa1c046250cf3b6d471cac10d9e66
[ "Apache-2.0" ]
1
2017-05-30T04:06:58.000Z
2017-05-30T04:06:58.000Z
src/java/info/jdavid/font/subset/Woff2Writer.java
programingjd/font_subset
390aa5d4bb6fa1c046250cf3b6d471cac10d9e66
[ "Apache-2.0" ]
null
null
null
src/java/info/jdavid/font/subset/Woff2Writer.java
programingjd/font_subset
390aa5d4bb6fa1c046250cf3b6d471cac10d9e66
[ "Apache-2.0" ]
null
null
null
38.096491
109
0.630747
995,418
package info.jdavid.font.subset; // Adapted from chromium's font-compression-reference code by Raph Levien // https://chromium.googlesource.com/external/font-compression-reference/+/ // 5ce8fad3ab9824f9f4d5fb4768c313b6309e94e3/src/com/google/typography/font/compression/Woff2Writer.java import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeSet; import com.google.typography.font.sfntly.Font; import com.google.typography.font.sfntly.Tag; import com.google.typography.font.sfntly.data.WritableFontData; import com.google.typography.font.sfntly.table.Table; import com.google.typography.font.sfntly.table.core.FontHeaderTable; import org.meteogroup.jbrotli.Brotli; import org.meteogroup.jbrotli.BrotliStreamCompressor; import org.meteogroup.jbrotli.libloader.BrotliLibraryLoader; public class Woff2Writer { private static final long SIGNATURE = 0x774f4632; private static final int WOFF2_HEADER_SIZE = 48; private static final int FLAG_CONTINUE_STREAM = 1 << 4; private static final int FLAG_APPLY_TRANSFORM = 1 << 5; private static final Map<Integer, Integer> TRANSFORM_MAP = createTransformMap(); private static Map<Integer, Integer> createTransformMap() { final Map<Integer, Integer> map = new HashMap<>(2); map.put(Tag.glyf, Tag.intValue(new byte[]{ 'g', 'l', 'z', '1' })); map.put(Tag.loca, Tag.intValue(new byte[]{ 'l', 'o', 'c', 'z' })); return map; } private static final Map<Integer, Integer> KNOWN_TABLES = createKnownTables(); private static Map<Integer, Integer> createKnownTables() { final Map<Integer, Integer> map = new HashMap<>(30); map.put(Tag.intValue(new byte[] {'c', 'm', 'a', 'p' }), 0); map.put(Tag.intValue(new byte[]{ 'h', 'e', 'a', 'd' }), 1); map.put(Tag.intValue(new byte[]{ 'h', 'h', 'e', 'a' }), 2); map.put(Tag.intValue(new byte[]{ 'h', 'm', 't', 'x' }), 3); map.put(Tag.intValue(new byte[]{ 'm', 'a', 'x', 'p' }), 4); map.put(Tag.intValue(new byte[]{ 'n', 'a', 'm', 'e' }), 5); map.put(Tag.intValue(new byte[]{ 'O', 'S', '/', '2' }), 6); map.put(Tag.intValue(new byte[]{ 'p', 'o', 's', 't' }), 7); map.put(Tag.intValue(new byte[]{ 'c', 'v', 't', ' ' }), 8); map.put(Tag.intValue(new byte[]{ 'f', 'p', 'g', 'm' }), 9); map.put(Tag.intValue(new byte[]{ 'g', 'l', 'y', 'f' }), 10); map.put(Tag.intValue(new byte[]{ 'l', 'o', 'c', 'a' }), 11); map.put(Tag.intValue(new byte[]{ 'p', 'r', 'e', 'p' }), 12); map.put(Tag.intValue(new byte[]{ 'C', 'F', 'F', ' ' }), 13); map.put(Tag.intValue(new byte[]{ 'V', 'O', 'R', 'G' }), 14); map.put(Tag.intValue(new byte[]{ 'E', 'B', 'D', 'T' }), 15); map.put(Tag.intValue(new byte[]{ 'E', 'B', 'L', 'C' }), 16); map.put(Tag.intValue(new byte[]{ 'g', 'a', 's', 'p' }), 17); map.put(Tag.intValue(new byte[]{ 'h', 'd', 'm', 'x' }), 18); map.put(Tag.intValue(new byte[]{ 'k', 'e', 'r', 'n' }), 19); map.put(Tag.intValue(new byte[]{ 'L', 'T', 'S', 'H' }), 20); map.put(Tag.intValue(new byte[]{ 'P', 'C', 'L', 'T' }), 21); map.put(Tag.intValue(new byte[]{ 'V', 'D', 'M', 'X' }), 22); map.put(Tag.intValue(new byte[]{ 'v', 'h', 'e', 'a' }), 23); map.put(Tag.intValue(new byte[]{ 'v', 'm', 't', 'x' }), 24); map.put(Tag.intValue(new byte[]{ 'B', 'A', 'S', 'E' }), 25); map.put(Tag.intValue(new byte[]{ 'G', 'D', 'E', 'F' }), 26); map.put(Tag.intValue(new byte[]{ 'G', 'P', 'O', 'S' }), 27); map.put(Tag.intValue(new byte[]{ 'G', 'S', 'U', 'B' }), 28); return map; } public Woff2Writer() {} public WritableFontData convert(final Font font) { final List<TableDirectoryEntry> entries = createTableDirectoryEntries(font); final int size = computeCompressedFontSize(entries); final WritableFontData writableFontData = WritableFontData.createWritableFontData(size); int index = 0; final FontHeaderTable head = font.getTable(Tag.head); index += writeWoff2Header(writableFontData, entries, font.sfntVersion(), size, head.fontRevision()); index += writeDirectory(writableFontData, index, entries); /*index +=*/ writeTables(writableFontData, index, entries); return writableFontData; } private List<TableDirectoryEntry> createTableDirectoryEntries(final Font font) { final List<TableDirectoryEntry> entries = new ArrayList<>(); final TreeSet<Integer> tags = new TreeSet<>(font.tableMap().keySet()); for (int tag: tags) { final Table table = font.getTable(tag); final byte[] uncompressedBytes = bytesFromTable(table); if (TRANSFORM_MAP.containsValue(tag)) { // Don't store the intermediate transformed tables under the nonstandard tags. continue; } final byte[] transformedBytes; if (TRANSFORM_MAP.containsKey(tag)) { int transformedTag = TRANSFORM_MAP.get(tag); Table transformedTable = font.getTable(transformedTag); if (transformedTable != null) { transformedBytes = bytesFromTable(transformedTable); } else { transformedBytes = null; } } else { transformedBytes = null; } if (transformedBytes == null) { entries.add(new TableDirectoryEntry(tag, uncompressedBytes)); } else { entries.add(new TableDirectoryEntry(tag, uncompressedBytes, transformedBytes, FLAG_APPLY_TRANSFORM)); } } return entries; } private byte[] bytesFromTable(final Table table) { final int length = table.dataLength(); final byte[] bytes = new byte[length]; table.readFontData().readBytes(0, bytes, 0, length); return bytes; } private int writeWoff2Header(final WritableFontData writableFontData, final List<TableDirectoryEntry> entries, final int flavor, final int length, final int version) { int index = 0; index += writableFontData.writeULong(index, SIGNATURE); index += writableFontData.writeULong(index, flavor); index += writableFontData.writeULong(index, length); index += writableFontData.writeUShort(index, entries.size()); // numTables index += writableFontData.writeUShort(index, 0); // reserved int uncompressedFontSize = computeUncompressedSize(entries); index += writableFontData.writeULong(index, uncompressedFontSize); int compressedFontSize = computeCompressedFontSize(entries); index += writableFontData.writeULong(index, compressedFontSize); index += writableFontData.writeFixed(index, version); index += writableFontData.writeULong(index, 0); // metaOffset index += writableFontData.writeULong(index, 0); // metaLength index += writableFontData.writeULong(index, 0); // metaOrigLength index += writableFontData.writeULong(index, 0); // privOffset index += writableFontData.writeULong(index, 0); // privLength return index; } private int writeDirectory(final WritableFontData writableFontData, final int offset, final List<TableDirectoryEntry> entries) { final int directorySize = computeDirectoryLength(entries); int index = offset; for (final TableDirectoryEntry entry: entries) { index += entry.writeEntry(writableFontData, index); } return directorySize; } private int writeTables(final WritableFontData writableFontData, final int offset, final List<TableDirectoryEntry> entries) { int index = offset; for (final TableDirectoryEntry entry: entries) { index += entry.writeData(writableFontData, index); index = align4(index); } return index - offset; } private int computeDirectoryLength(final List<TableDirectoryEntry> entries) { int index = 0; for (final TableDirectoryEntry entry: entries) { index += entry.writeEntry(null, index); } return index; } private int align4(final int value) { return (value + 3) & -4; } private int computeUncompressedSize(final List<TableDirectoryEntry> entries) { int index = 20 + 16 * entries.size(); // sfnt header length for (final TableDirectoryEntry entry: entries) { index += entry.origLength; index = align4(index); } return index; } private int computeCompressedFontSize(final List<TableDirectoryEntry> entries) { int index = WOFF2_HEADER_SIZE; index += computeDirectoryLength(entries); for (final TableDirectoryEntry entry: entries) { index += entry.bytes.length; index = align4(index); } return index; } // Note: if writableFontData is null, just return the size private static byte[] base128(final long value) { final ByteArrayOutputStream out = new ByteArrayOutputStream(64); int size = 1; long tmpValue = value; while (tmpValue >= 128) { size += 1; tmpValue = tmpValue >> 7; } for (int i=0; i<size; i++) { int b = (int)(value >> (7 * (size - i - 1))) & 0x7f; if (i < size - 1) { b |= 0x80; } out.write((byte)b); } return out.toByteArray(); } // Note: if writableFontData is null, just return the size private static int writeBase128(final WritableFontData writableFontData, final long value, final int offset) { int size = 1; long tmpValue = value; int index = offset; while (tmpValue >= 128) { size += 1; tmpValue = tmpValue >> 7; } for (int i=0; i<size; i++) { int b = (int)(value >> (7 * (size - i - 1))) & 0x7f; if (i < size - 1) { b |= 0x80; } if (writableFontData != null) { writableFontData.writeByte(index, (byte)b); } index += 1; } return size; } private class TableDirectoryEntry { private final long tag; private final long flags; public final long origLength; private final long transformLength; public final byte[] bytes; public TableDirectoryEntry(final long tag, final byte[] uncompressedBytes) { this(tag, uncompressedBytes, uncompressedBytes, 0); } public TableDirectoryEntry(final long tag, final byte[] uncompressedBytes, final byte[] transformedBytes, final long transformFlags) { final byte[] compressedBytes = compress(transformedBytes); this.tag = tag; this.flags = transformFlags | 2L; this.origLength = uncompressedBytes.length; this.transformLength = transformedBytes.length; this.bytes = compressedBytes; } public int writeEntry(final WritableFontData writableFontData, final int offset) { int index = offset; int flag_byte = 0x3f; if (KNOWN_TABLES.containsKey((int)tag)) { flag_byte = KNOWN_TABLES.get((int)tag); } if ((flags & FLAG_APPLY_TRANSFORM) != 0) { flag_byte |= 0x20; } if ((flags & FLAG_CONTINUE_STREAM) != 0) { flag_byte |= 0xc0; } // else { // flag_byte |= (flags & 3) << 6; // } if (writableFontData != null) { // System.out.printf("%d: tag = %08x, flag = %02x\n", offset, tag, flag_byte); writableFontData.writeByte(index, (byte)flag_byte); } index += 1; if ((flag_byte & 0x1f) == 0x1f) { if (writableFontData != null) { writableFontData.writeULong(index, tag); } index += 4; } index += writeBase128(writableFontData, origLength, index); if ((flag_byte & 0x20) != 0) { index += writeBase128(writableFontData, transformLength, index); } if ((flag_byte & 0xc0) == 0x40 || (flag_byte & 0xc0) == 0x80) { index += writeBase128(writableFontData, bytes.length, index); } return index - offset; } public int writeData(final WritableFontData writableFontData, final int offset) { writableFontData.writeBytes(offset, bytes); return bytes.length; } } // private static byte[] compress(final byte[] input) { // try { // final ByteArrayInputStream in = new ByteArrayInputStream(input); // final ByteArrayOutputStream out = new ByteArrayOutputStream(); // final Encoder encoder = new Encoder(); // encoder.SetAlgorithm(2); // encoder.SetDictionarySize(1 << 23); // encoder.SetNumFastBytes(128); // encoder.SetMatchFinder(1); // encoder.SetLcLpPb(3, 0, 2); // encoder.SetEndMarkerMode(true); // encoder.WriteCoderProperties(out); // for (int i=0; i<8; i++) { // out.write((int) ((long) -1 >>> (8 * i)) & 0xFF); // } // encoder.Code(in, out, -1, -1, null); // out.flush(); // out.close(); // return out.toByteArray(); // } // catch (final IOException e) { // throw new RuntimeException(e); // } // } private static byte[] compress(final byte[] input) { return new BrotliStreamCompressor(Brotli.DEFAULT_PARAMETER).compressArray(input, true); } static { BrotliLibraryLoader.loadBrotli(); } }
92304917d2758f3d1ef270c4b00b415789d8078f
1,329
java
Java
build/sources/main/java/net/jekruy/rotr/gui/GuiDTROTR.java
JEKRUY/rotrSYSTEM
07bf8610dd496a62b80089921fcec75a70c7334d
[ "MIT" ]
1
2021-04-18T14:39:37.000Z
2021-04-18T14:39:37.000Z
src/main/java/net/jekruy/rotr/gui/GuiDTROTR.java
JEKRUY/rotrSYSTEM
07bf8610dd496a62b80089921fcec75a70c7334d
[ "MIT" ]
null
null
null
src/main/java/net/jekruy/rotr/gui/GuiDTROTR.java
JEKRUY/rotrSYSTEM
07bf8610dd496a62b80089921fcec75a70c7334d
[ "MIT" ]
null
null
null
35.918919
146
0.726862
995,419
package net.jekruy.rotr.gui; import org.lwjgl.opengl.GL11; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraft.util.ResourceLocation; public class GuiDTROTR extends GuiScreen { public void initGui() { this.buttonList.clear(); } public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawBackground(0); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation("rotr:textures/backk.png")); Gui.drawModalRectWithCustomSizedTexture(0, 0, 0, 0, this.width, this.height, this.width, this.height); Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation("rotr:textures/controller255.png")); Gui.drawModalRectWithCustomSizedTexture(this.width / 2 - 96, this.height / 2 - 64, 0, 0, 193, 128, 193, 128); this.drawCenteredString(this.fontRenderer, I18n.format("multiplayer.downloadingTerrain"), this.width / 2, this.height / 2 + 90, 16777215); super.drawScreen(mouseX, mouseY, partialTicks); } public boolean doesGuiPauseGame() { return false; } }
9230491862340599ce132262b0f4e73c09a91fc7
1,334
java
Java
SpliteratorImplementaion/src/main/java/org/doInjava8/spliterators/custom/PersonSpliterator.java
DhirenKumar13/Java8
c485a219a2f1e46dfe6b4aa65a8d858481d8e420
[ "MIT" ]
null
null
null
SpliteratorImplementaion/src/main/java/org/doInjava8/spliterators/custom/PersonSpliterator.java
DhirenKumar13/Java8
c485a219a2f1e46dfe6b4aa65a8d858481d8e420
[ "MIT" ]
null
null
null
SpliteratorImplementaion/src/main/java/org/doInjava8/spliterators/custom/PersonSpliterator.java
DhirenKumar13/Java8
c485a219a2f1e46dfe6b4aa65a8d858481d8e420
[ "MIT" ]
null
null
null
25.169811
81
0.73988
995,420
package org.doInjava8.spliterators.custom; import java.util.Spliterator; import java.util.function.Consumer; import org.doInjava8.spliterators.model.Person; public class PersonSpliterator implements Spliterator<Person> { private final Spliterator<String> linespliterator; private String name; private Integer age; private String city; public PersonSpliterator(Spliterator<String> lines) { this.linespliterator = lines; } @Override public boolean tryAdvance(Consumer<? super Person> action) { if(this.linespliterator.tryAdvance(line -> this.name = line) && this.linespliterator.tryAdvance(line -> this.age = Integer.valueOf(line)) && this.linespliterator.tryAdvance(line -> this.city = line)) { Person person = new Person(name,age,city); action.accept(person); return true; }else { return false; } } @Override public int characteristics() { //Just returning the default characteristics .. return linespliterator.characteristics(); } @Override public long estimateSize() { //As in our file 3 lines contains informations about one person //So divide total size with 3 to get each person's info return linespliterator.estimateSize() / 3 ; } @Override public Spliterator<Person> trySplit() { //We don't need parallel stream hence returning null return null; } }
923049281a6841eac4e92212cc441ac1887a685e
560
java
Java
04_Polymorphism/src/shapes/Rectangle.java
itonov/Java-OOP-Basics
5743ee926d0bdf5249cb96173f7a2adb04b1068c
[ "MIT" ]
3
2017-12-04T15:43:13.000Z
2017-12-04T15:43:20.000Z
04_Polymorphism/src/shapes/Rectangle.java
itonov/Java-OOP-Basics
5743ee926d0bdf5249cb96173f7a2adb04b1068c
[ "MIT" ]
null
null
null
04_Polymorphism/src/shapes/Rectangle.java
itonov/Java-OOP-Basics
5743ee926d0bdf5249cb96173f7a2adb04b1068c
[ "MIT" ]
null
null
null
18.666667
46
0.603571
995,421
package shapes; public class Rectangle extends Shape { private double height; private double width; Rectangle(double height, double width) { this.height = height; this.width = width; } public double getHeight() { return this.height; } public double getWidth() { return this.width; } @Override public double calculatePerimeter() { return 2 + (this.height + this.width); } @Override public double calculateArea() { return this.height * this.width; } }
92304aee095f379232dc3d61eae7c7b1f98e0231
5,120
java
Java
plugins/org.jkiss.dbeaver.ext.vertica/src/org/jkiss/dbeaver/ext/vertica/edit/VerticaTableColumnManager.java
tomas303/dbeaver
f96af4733065668b9483132714b1fbb11bba02a9
[ "Apache-2.0" ]
3
2017-10-25T01:25:55.000Z
2020-12-23T06:05:00.000Z
plugins/org.jkiss.dbeaver.ext.vertica/src/org/jkiss/dbeaver/ext/vertica/edit/VerticaTableColumnManager.java
tomas303/dbeaver
f96af4733065668b9483132714b1fbb11bba02a9
[ "Apache-2.0" ]
1
2020-04-11T02:41:36.000Z
2020-04-11T02:41:36.000Z
plugins/org.jkiss.dbeaver.ext.vertica/src/org/jkiss/dbeaver/ext/vertica/edit/VerticaTableColumnManager.java
tomas303/dbeaver
f96af4733065668b9483132714b1fbb11bba02a9
[ "Apache-2.0" ]
1
2017-10-18T20:06:47.000Z
2017-10-18T20:06:47.000Z
46.527273
201
0.705158
995,422
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2019 Serge Rider (efpyi@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 org.jkiss.dbeaver.ext.vertica.edit; import org.jkiss.dbeaver.ext.generic.edit.GenericTableColumnManager; import org.jkiss.dbeaver.ext.generic.model.GenericTableBase; import org.jkiss.dbeaver.ext.generic.model.GenericTableColumn; import org.jkiss.dbeaver.model.DBConstants; import org.jkiss.dbeaver.model.DBPEvaluationContext; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.impl.edit.DBECommandAbstract; import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.utils.CommonUtils; import java.util.List; import java.util.Map; /** * Vertica table column manager */ public class VerticaTableColumnManager extends GenericTableColumnManager { protected final ColumnModifier<GenericTableColumn> VerticaDataTypeModifier = (monitor, column, sql, command) -> { sql.append(" SET DATA TYPE "); DataTypeModifier.appendModifier(monitor, column, sql, command); }; protected final ColumnModifier<GenericTableColumn> VerticaDefaultModifier = (monitor, column, sql, command) -> { if (CommonUtils.isEmpty(command.getObject().getDefaultValue())) { sql.append(" DROP DEFAULT"); } else { sql.append(" SET DEFAULT "); DefaultModifier.appendModifier(monitor, column, sql, command); } }; protected final ColumnModifier<GenericTableColumn> VerticaNotNullModifier = (monitor, column, sql, command) -> { if (command.getObject().isRequired()) { sql.append(" SET NOT NULL"); } else { sql.append(" DROP NOT NULL"); } }; @Override public StringBuilder getNestedDeclaration(DBRProgressMonitor monitor, GenericTableBase owner, DBECommandAbstract<GenericTableColumn> command, Map<String, Object> options) { StringBuilder decl = super.getNestedDeclaration(monitor, owner, command, options); final GenericTableColumn column = command.getObject(); if (column.isAutoIncrement()) { final String autoIncrementClause = column.getDataSource().getMetaModel().getAutoIncrementClause(column); if (autoIncrementClause != null && !autoIncrementClause.isEmpty()) { decl.append(" ").append(autoIncrementClause); //$NON-NLS-1$ } } return decl; } @Override protected ColumnModifier[] getSupportedModifiers(GenericTableColumn column, Map<String, Object> options) { // According to SQL92 DEFAULT comes before constraints return new ColumnModifier[] {VerticaDataTypeModifier, VerticaDefaultModifier, VerticaNotNullModifier}; } /** * Copy-pasted from PostgreSQL implementation. * TODO: Vertica is originally based on PG. Maybe we should refactor this stuff somehow. */ @Override protected void addObjectModifyActions(DBRProgressMonitor monitor, List<DBEPersistAction> actionList, ObjectChangeCommand command, Map<String, Object> options) { final GenericTableColumn column = command.getObject(); String prefix = "ALTER TABLE " + DBUtils.getObjectFullName(column.getTable(), DBPEvaluationContext.DDL) + " ALTER COLUMN " + DBUtils.getQuotedIdentifier(column) + " "; String typeClause = column.getFullTypeName(); if (command.getProperty(DBConstants.PROP_ID_TYPE_NAME) != null || command.getProperty("maxLength") != null || command.getProperty("precision") != null || command.getProperty("scale") != null) { actionList.add(new SQLDatabasePersistAction("Set column type", prefix + "SET DATA TYPE " + typeClause)); } if (command.getProperty(DBConstants.PROP_ID_REQUIRED) != null) { actionList.add(new SQLDatabasePersistAction("Set column nullability", prefix + (column.isRequired() ? "SET" : "DROP") + " NOT NULL")); } if (command.getProperty(DBConstants.PROP_ID_DEFAULT_VALUE) != null) { if (CommonUtils.isEmpty(column.getDefaultValue())) { actionList.add(new SQLDatabasePersistAction("Drop column default", prefix + "DROP DEFAULT")); } else { actionList.add(new SQLDatabasePersistAction("Set column default", prefix + "SET DEFAULT " + column.getDefaultValue())); } } super.addObjectModifyActions(monitor, actionList, command, options); } }
92304b32d07379b946ada3f40e11a737ed08941c
37,625
java
Java
src/test/java/io/personium/test/jersey/box/odatacol/UserDataDeepComplexTypeTest.java
yoh1496/personium-core
4f210419aeee7341b6731a13dd6ca16acbdb6bd0
[ "Apache-2.0" ]
90
2017-01-20T09:17:10.000Z
2022-01-28T13:42:30.000Z
src/test/java/io/personium/test/jersey/box/odatacol/UserDataDeepComplexTypeTest.java
yoh1496/personium-core
4f210419aeee7341b6731a13dd6ca16acbdb6bd0
[ "Apache-2.0" ]
348
2017-01-20T10:58:02.000Z
2022-03-31T03:52:23.000Z
src/test/java/io/personium/test/jersey/box/odatacol/UserDataDeepComplexTypeTest.java
yoh1496/personium-core
4f210419aeee7341b6731a13dd6ca16acbdb6bd0
[ "Apache-2.0" ]
27
2017-01-20T10:42:11.000Z
2021-05-05T03:22:29.000Z
45.276775
110
0.551787
995,423
/** * Personium * Copyright 2014-2021 Personium Project Authors * - FUJITSU LIMITED * * 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.personium.test.jersey.box.odatacol; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.apache.http.HttpStatus; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import io.personium.core.rs.PersoniumCoreApplication; import io.personium.test.CompareJSON; import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; import io.personium.test.categories.Unit; import io.personium.test.jersey.AbstractCase; import io.personium.test.jersey.PersoniumIntegTestRunner; import io.personium.test.jersey.PersoniumTest; import io.personium.test.setup.Setup; import io.personium.test.utils.AssociationEndUtils; import io.personium.test.utils.BoxUtils; import io.personium.test.utils.CellUtils; import io.personium.test.utils.DavResourceUtils; import io.personium.test.utils.EntityTypeUtils; import io.personium.test.utils.TResponse; import io.personium.test.utils.UserDataUtils; /** * UserDataComplexType複数階層のテスト. */ @RunWith(PersoniumIntegTestRunner.class) @Category({Unit.class, Integration.class, Regression.class }) public class UserDataDeepComplexTypeTest extends PersoniumTest { private static final String COMPLEX_TYPE_NAME_1 = "complexType1"; private static final String LIST_COMPLEX_TYPE_NAME_1 = "listComplexType1"; private static final String COMPLEX_TYPE_NAME_2 = "complexType2"; private static final String LIST_COMPLEX_TYPE_NAME_2 = "listComplexType2"; private static final String COMPLEX_TYPE_NAME_3 = "complexType3"; private static final String LIST_COMPLEX_TYPE_NAME_3 = "listComplexType3"; /** * コンストラクタ. */ public UserDataDeepComplexTypeTest() { super(new PersoniumCoreApplication()); } /** * 複数階層あるデータに対して1階層目のデータをMERGEして_正常に更新できること. */ @Test public final void 複数階層あるデータに対して1階層目のデータをMERGEして_正常に更新できること() { String token = AbstractCase.MASTER_TOKEN_NAME; String cellName = "userdatadeepcomplextypetestcell"; String boxName = "box"; String odataColName = "col"; String entityTypeName = "entity"; try { createODataCollection(token, cellName, boxName, odataColName); createSchema(token, cellName, boxName, odataColName, entityTypeName); // 1階層目の文字列Propertyを指定してMERGE createUserData(token, cellName, boxName, odataColName, entityTypeName, "id001"); String bodyString = "{" + " \"p1Property\": \"p1PropertyValueUpdated\"" + "}"; UserDataUtils.merge(token, HttpStatus.SC_NO_CONTENT, parseStringToJSONObject(bodyString), cellName, boxName, odataColName, entityTypeName, "id001", "*"); // 更新確認 TResponse response = UserDataUtils.get(cellName, token, boxName, odataColName, entityTypeName, "id001", HttpStatus.SC_OK); CompareJSON.Result res = CompareJSON.compareJSON( getDefaultUserDataRequestBody("id001"), response.getBody()); assertNotNull(res); assertEquals(1, res.size()); assertEquals("p1PropertyValueUpdated", res.getMismatchValue("p1Property")); // 1階層目の文字列Property配列を指定してMERGE createUserData(token, cellName, boxName, odataColName, entityTypeName, "id002"); String bodyStringArray = "{" + " \"p1ListProperty\": [" + " \"p1ListPropertyValueUpdated1\"," + " \"p1ListPropertyValueUpdated2\"" + " ]" + "}"; UserDataUtils.merge(token, HttpStatus.SC_NO_CONTENT, parseStringToJSONObject(bodyStringArray), cellName, boxName, odataColName, entityTypeName, "id002", "*"); // 更新確認 response = UserDataUtils.get(cellName, token, boxName, odataColName, entityTypeName, "id002", HttpStatus.SC_OK); res = CompareJSON.compareJSON( getDefaultUserDataRequestBody("id002"), response.getBody()); assertNotNull(res); assertEquals(1, res.size()); JSONArray resArray = (JSONArray) res.getMismatchValue("p1ListProperty"); assertEquals(2, resArray.size()); assertTrue(resArray.contains("p1ListPropertyValueUpdated1")); assertTrue(resArray.contains("p1ListPropertyValueUpdated2")); } catch (ParseException e) { fail(e.getMessage()); } finally { // Cell一括削除 Setup.cellBulkDeletion(cellName); } } /** * 複数階層あるデータに対して2階層目のデータをMERGEして_正常に更新できること. */ @Test public final void 複数階層あるデータに対して2階層目のデータをMERGEして_正常に更新できること() { String token = AbstractCase.MASTER_TOKEN_NAME; String cellName = "userdatadeepcomplextypetestcell"; String boxName = "box"; String odataColName = "col"; String entityTypeName = "entity"; try { createODataCollection(token, cellName, boxName, odataColName); createSchema(token, cellName, boxName, odataColName, entityTypeName); // 2階層目の文字列Propertyを指定してMERGE createUserData(token, cellName, boxName, odataColName, entityTypeName, "id001"); String bodyString = "{" + " \"p1ComplexProperty\": {" + " \"c1Property\": \"c1PropertyValueUpdated\"" + " }" + "}"; UserDataUtils.merge(token, HttpStatus.SC_NO_CONTENT, parseStringToJSONObject(bodyString), cellName, boxName, odataColName, entityTypeName, "id001", "*"); // 更新確認 TResponse response = UserDataUtils.get(cellName, token, boxName, odataColName, entityTypeName, "id001", HttpStatus.SC_OK); CompareJSON.Result res = CompareJSON.compareJSON( getDefaultUserDataRequestBody("id001"), response.getBody()); assertNotNull(res); assertEquals(1, res.size()); assertEquals("c1PropertyValueUpdated", res.getMismatchValue("p1ComplexProperty.c1Property")); // 2階層目の文字列Property配列を指定してMERGE createUserData(token, cellName, boxName, odataColName, entityTypeName, "id002"); String bodyStringArray = "{" + " \"p1ComplexProperty\": {" + " \"c1ListProperty\": [" + " \"c1ListPropertyValueUpdated1\"," + " \"c1ListPropertyValueUpdated2\"" + " ]" + " }" + "}"; UserDataUtils.merge(token, HttpStatus.SC_NO_CONTENT, parseStringToJSONObject(bodyStringArray), cellName, boxName, odataColName, entityTypeName, "id002", "*"); // 更新確認 response = UserDataUtils.get(cellName, token, boxName, odataColName, entityTypeName, "id002", HttpStatus.SC_OK); res = CompareJSON.compareJSON( getDefaultUserDataRequestBody("id002"), response.getBody()); assertNotNull(res); assertEquals(1, res.size()); JSONArray resArray = (JSONArray) res.getMismatchValue("p1ComplexProperty.c1ListProperty"); assertEquals(2, resArray.size()); assertTrue(resArray.contains("c1ListPropertyValueUpdated1")); assertTrue(resArray.contains("c1ListPropertyValueUpdated2")); // 配列型の2階層目の文字列Propertyを指定してMERGE createUserData(token, cellName, boxName, odataColName, entityTypeName, "id003"); String bodyArrayComplexString = "{" + " \"p1ComplexListProperty\": [" + " {" + " \"lc1Property\": \"lc1PropertyValueUpdated\"" + " }" + " ]" + "}"; UserDataUtils.merge(token, HttpStatus.SC_NO_CONTENT, parseStringToJSONObject(bodyArrayComplexString), cellName, boxName, odataColName, entityTypeName, "id003", "*"); // ComplexType型のListのMERGEは未サポートのため、MERGE後のチェックは省略 // 配列型の2階層目の文字列Propertyを指定してMERGE createUserData(token, cellName, boxName, odataColName, entityTypeName, "id004"); String bodyArrayComplexArrayString = "{" + " \"p1ComplexListProperty\": [" + " {" + " \"lc1ListProperty\": [" + " \"lc1ListPropertyValueUpdated1\"," + " \"lc1ListPropertyValueUpdated2\"" + " ]" + " }" + " ]" + "}"; UserDataUtils.merge(token, HttpStatus.SC_NO_CONTENT, parseStringToJSONObject(bodyArrayComplexArrayString), cellName, boxName, odataColName, entityTypeName, "id004", "*"); // ComplexType型のListのMERGEは未サポートのため、MERGE後のチェックは省略 } catch (ParseException e) { fail(e.getMessage()); } finally { // Cell一括削除 Setup.cellBulkDeletion(cellName); } } /** * 複数階層あるデータに対して4階層目のデータをMERGEして_正常に更新できること. */ @Test public final void 複数階層あるデータに対して4階層目のデータをMERGEして_正常に更新できること() { String token = AbstractCase.MASTER_TOKEN_NAME; String cellName = "userdatadeepcomplextypetestcell"; String boxName = "box"; String odataColName = "col"; String entityTypeName = "entity"; try { createODataCollection(token, cellName, boxName, odataColName); createSchema(token, cellName, boxName, odataColName, entityTypeName); // 4階層目の文字列Propertyを指定してMERGE createUserData(token, cellName, boxName, odataColName, entityTypeName, "id001"); String bodyString = "{" + " \"p1ComplexProperty\": {" + " \"c1ComplexProperty\": {" + " \"c2ComplexProperty\": {" + " \"c3Property\": \"c3PropertyValueUpdated\"" + " }" + " }" + " }" + "}"; UserDataUtils.merge(token, HttpStatus.SC_NO_CONTENT, parseStringToJSONObject(bodyString), cellName, boxName, odataColName, entityTypeName, "id001", "*"); // 更新確認 TResponse response = UserDataUtils.get(cellName, token, boxName, odataColName, entityTypeName, "id001", HttpStatus.SC_OK); CompareJSON.Result res = CompareJSON.compareJSON( getDefaultUserDataRequestBody("id001"), response.getBody()); assertNotNull(res); assertEquals(1, res.size()); assertEquals("c3PropertyValueUpdated", res.getMismatchValue("p1ComplexProperty.c1ComplexProperty.c2ComplexProperty.c3Property")); // 4階層目の文字列Property配列を指定してMERGE createUserData(token, cellName, boxName, odataColName, entityTypeName, "id002"); String bodyStringArray = "{" + " \"p1ComplexProperty\": {" + " \"c1ComplexProperty\": {" + " \"c2ComplexProperty\": {" + " \"c3ListProperty\": [" + " \"c3ListPropertyValueUpdated1\"," + " \"c3ListPropertyValueUpdated2\"" + " ]" + " }" + " }" + " }" + "}"; UserDataUtils.merge(token, HttpStatus.SC_NO_CONTENT, parseStringToJSONObject(bodyStringArray), cellName, boxName, odataColName, entityTypeName, "id002", "*"); // 更新確認 response = UserDataUtils.get(cellName, token, boxName, odataColName, entityTypeName, "id002", HttpStatus.SC_OK); res = CompareJSON.compareJSON( getDefaultUserDataRequestBody("id002"), response.getBody()); assertNotNull(res); assertEquals(1, res.size()); JSONArray resArray = (JSONArray) res .getMismatchValue("p1ComplexProperty.c1ComplexProperty.c2ComplexProperty.c3ListProperty"); assertEquals(2, resArray.size()); assertTrue(resArray.contains("c3ListPropertyValueUpdated1")); assertTrue(resArray.contains("c3ListPropertyValueUpdated2")); // 配列型の4階層目の文字列Propertyを指定してMERGE createUserData(token, cellName, boxName, odataColName, entityTypeName, "id003"); String bodyArrayComplexString = "{" + " \"p1ComplexListProperty\": [" + " {" + " \"lc1ListComplexProperty\": [" + " {" + " \"lc2ListComplexProperty\": [" + " {" + " \"lc3Property\": \"lc3PropertyValue\"" + " }" + " ]" + " }" + " ]" + " }" + " ]" + "}"; UserDataUtils.merge(token, HttpStatus.SC_NO_CONTENT, parseStringToJSONObject(bodyArrayComplexString), cellName, boxName, odataColName, entityTypeName, "id003", "*"); // ComplexType型のListのMERGEは未サポートのため、MERGE後のチェックは省略 // 配列型の4階層目の文字列Propertyを指定してMERGE createUserData(token, cellName, boxName, odataColName, entityTypeName, "id004"); String bodyArrayComplexArrayString = "{" + " \"p1ComplexListProperty\": [" + " {" + " \"lc1ListComplexProperty\": [" + " {" + " \"lc2ListComplexProperty\": [" + " {" + " \"lc3ListProperty\": [" + " \"lc3ListPropertyValueUpdated1\"," + " \"lc3ListPropertyValueUpdated2\"" + " ]" + " }" + " ]" + " }" + " ]" + " }" + " ]" + "}"; UserDataUtils.merge(token, HttpStatus.SC_NO_CONTENT, parseStringToJSONObject(bodyArrayComplexArrayString), cellName, boxName, odataColName, entityTypeName, "id004", "*"); // ComplexType型のListのMERGEは未サポートのため、MERGE後のチェックは省略 } catch (ParseException e) { fail(e.getMessage()); } finally { // Cell一括削除 Setup.cellBulkDeletion(cellName); } } /** * 複数階層あるデータに対してZeroToZeroのNP経由登録して_ソース側のデータに変更がないこと. */ @Test public final void 複数階層あるデータに対してZeroToZeroのNP経由登録して_ソース側のデータに変更がないこと() { String token = AbstractCase.MASTER_TOKEN_NAME; String cellName = "userdatadeepcomplextypetestcell"; String boxName = "box"; String odataColName = "col"; String entityTypeName = "entity"; try { createODataCollection(token, cellName, boxName, odataColName); createSchema(token, cellName, boxName, odataColName, entityTypeName); String entityTypeNameNP = "entityNP"; String sourceMultiplicity = "0..1"; String targetMultiplicity = "0..1"; createLinkedEntityType(token, cellName, boxName, odataColName, entityTypeName, entityTypeNameNP, sourceMultiplicity, targetMultiplicity); String srcId = "id001"; createUserData(token, cellName, boxName, odataColName, entityTypeName, srcId); TResponse response = UserDataUtils.get(cellName, token, boxName, odataColName, entityTypeName, srcId, HttpStatus.SC_OK); UserDataUtils.createViaNP(token, parseStringToJSONObject("{\"__id\":\"idNp\"}"), cellName, boxName, odataColName, entityTypeName, srcId, entityTypeNameNP, HttpStatus.SC_CREATED); // ソース側のデータに変更がないこと TResponse modResponse = UserDataUtils.get(cellName, token, boxName, odataColName, entityTypeName, srcId, HttpStatus.SC_OK); CompareJSON.Result res = CompareJSON.compareJSON( response.getBody(), modResponse.getBody()); assertNull(res); } catch (ParseException e) { fail(e.getMessage()); } finally { // Cell一括削除 Setup.cellBulkDeletion(cellName); } } /** * 複数階層あるデータに対してZeroToManyのNP経由登録して_ソース側のデータに変更がないこと. */ @Test public final void 複数階層あるデータに対してZeroToManyのNP経由登録して_ソース側のデータに変更がないこと() { String token = AbstractCase.MASTER_TOKEN_NAME; String cellName = "userdatadeepcomplextypetestcell"; String boxName = "box"; String odataColName = "col"; String entityTypeName = "entity"; try { createODataCollection(token, cellName, boxName, odataColName); createSchema(token, cellName, boxName, odataColName, entityTypeName); String entityTypeNameNP = "entityNP"; String sourceMultiplicity = "0..1"; String targetMultiplicity = "*"; createLinkedEntityType(token, cellName, boxName, odataColName, entityTypeName, entityTypeNameNP, sourceMultiplicity, targetMultiplicity); String srcId = "id001"; createUserData(token, cellName, boxName, odataColName, entityTypeName, srcId); TResponse response = UserDataUtils.get(cellName, token, boxName, odataColName, entityTypeName, srcId, HttpStatus.SC_OK); UserDataUtils.createViaNP(token, parseStringToJSONObject("{\"__id\":\"idNp\"}"), cellName, boxName, odataColName, entityTypeName, srcId, entityTypeNameNP, HttpStatus.SC_CREATED); // ソース側のデータに変更がないこと TResponse modResponse = UserDataUtils.get(cellName, token, boxName, odataColName, entityTypeName, srcId, HttpStatus.SC_OK); CompareJSON.Result res = CompareJSON.compareJSON( response.getBody(), modResponse.getBody()); assertNull(res); } catch (ParseException e) { fail(e.getMessage()); } finally { // Cell一括削除 Setup.cellBulkDeletion(cellName); } } /** * 複数階層あるデータに対してManyToZeroのNP経由登録して_ソース側のデータに変更がないこと. */ @Test public final void 複数階層あるデータに対してManyToZeroのNP経由登録して_ソース側のデータに変更がないこと() { String token = AbstractCase.MASTER_TOKEN_NAME; String cellName = "userdatadeepcomplextypetestcell"; String boxName = "box"; String odataColName = "col"; String entityTypeName = "entity"; try { createODataCollection(token, cellName, boxName, odataColName); createSchema(token, cellName, boxName, odataColName, entityTypeName); String entityTypeNameNP = "entityNP"; String sourceMultiplicity = "*"; String targetMultiplicity = "0..1"; createLinkedEntityType(token, cellName, boxName, odataColName, entityTypeName, entityTypeNameNP, sourceMultiplicity, targetMultiplicity); String srcId = "id001"; createUserData(token, cellName, boxName, odataColName, entityTypeName, srcId); TResponse response = UserDataUtils.get(cellName, token, boxName, odataColName, entityTypeName, srcId, HttpStatus.SC_OK); UserDataUtils.createViaNP(token, parseStringToJSONObject("{\"__id\":\"idNp\"}"), cellName, boxName, odataColName, entityTypeName, srcId, entityTypeNameNP, HttpStatus.SC_CREATED); // ソース側のデータに変更がないこと TResponse modResponse = UserDataUtils.get(cellName, token, boxName, odataColName, entityTypeName, srcId, HttpStatus.SC_OK); CompareJSON.Result res = CompareJSON.compareJSON( response.getBody(), modResponse.getBody()); assertNull(res); } catch (ParseException e) { fail(e.getMessage()); } finally { // Cell一括削除 Setup.cellBulkDeletion(cellName); } } /** * 複数階層あるデータに対してManyToManyのNP経由登録して_ソース側のデータに変更がないこと. */ @Test public final void 複数階層あるデータに対してManyToManyのNP経由登録して_ソース側のデータに変更がないこと() { String token = AbstractCase.MASTER_TOKEN_NAME; String cellName = "userdatadeepcomplextypetestcell"; String boxName = "box"; String odataColName = "col"; String entityTypeName = "entity"; try { createODataCollection(token, cellName, boxName, odataColName); createSchema(token, cellName, boxName, odataColName, entityTypeName); String entityTypeNameNP = "entityNP"; String sourceMultiplicity = "*"; String targetMultiplicity = "*"; createLinkedEntityType(token, cellName, boxName, odataColName, entityTypeName, entityTypeNameNP, sourceMultiplicity, targetMultiplicity); String srcId = "id001"; createUserData(token, cellName, boxName, odataColName, entityTypeName, srcId); TResponse response = UserDataUtils.get(cellName, token, boxName, odataColName, entityTypeName, srcId, HttpStatus.SC_OK); UserDataUtils.createViaNP(token, parseStringToJSONObject("{\"__id\":\"idNp\"}"), cellName, boxName, odataColName, entityTypeName, srcId, entityTypeNameNP, HttpStatus.SC_CREATED); // ソース側のデータに変更がないこと TResponse modResponse = UserDataUtils.get(cellName, token, boxName, odataColName, entityTypeName, srcId, HttpStatus.SC_OK); CompareJSON.Result res = CompareJSON.compareJSON( response.getBody(), modResponse.getBody()); assertNull(res); } catch (ParseException e) { fail(e.getMessage()); } finally { // Cell一括削除 Setup.cellBulkDeletion(cellName); } } private void createLinkedEntityType(String token, String cellName, String boxName, String odataColName, String sourceEntityTypeName, String targetEntityTypeName, String sourceMultiplicity, String targetMultiplicity) { // EntityType作成 EntityTypeUtils.create(cellName, token, boxName, odataColName, targetEntityTypeName, HttpStatus.SC_CREATED); // AssociationEnd作成 AssociationEndUtils.create(token, sourceMultiplicity, cellName, boxName, odataColName, HttpStatus.SC_CREATED, "assoc1", sourceEntityTypeName); AssociationEndUtils.create(token, targetMultiplicity, cellName, boxName, odataColName, HttpStatus.SC_CREATED, "assoc2", targetEntityTypeName); // AsoociationEnd $links作成 AssociationEndUtils.createLink(AbstractCase.MASTER_TOKEN_NAME, cellName, boxName, odataColName, sourceEntityTypeName, targetEntityTypeName, "assoc1", "assoc2", HttpStatus.SC_NO_CONTENT); } private JSONObject parseStringToJSONObject(String body) { JSONObject bodyJSON = null; try { bodyJSON = (JSONObject) new JSONParser().parse(body); } catch (ParseException e) { fail("parse failed. [" + e.getMessage() + "]"); } return bodyJSON; } private void createSchema( String token, String cellName, String boxName, String odataColName, String entityTypeName) { // EntityType作成 EntityTypeUtils.create(cellName, token, boxName, odataColName, entityTypeName, HttpStatus.SC_CREATED); // 3階層目のComplexType作成 UserDataUtils.createComplexType(cellName, boxName, odataColName, COMPLEX_TYPE_NAME_3); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "c3Property", COMPLEX_TYPE_NAME_3, "Edm.String", true, null, "None"); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "c3ListProperty", COMPLEX_TYPE_NAME_3, "Edm.String", true, null, "List"); // 3階層目のComplexType(List)作成 UserDataUtils.createComplexType(cellName, boxName, odataColName, LIST_COMPLEX_TYPE_NAME_3); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "lc3Property", LIST_COMPLEX_TYPE_NAME_3, "Edm.String", true, null, "None"); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "lc3ListProperty", LIST_COMPLEX_TYPE_NAME_3, "Edm.String", true, null, "List"); // 2階層目のComplexType作成 UserDataUtils.createComplexType(cellName, boxName, odataColName, COMPLEX_TYPE_NAME_2); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "c2Property", COMPLEX_TYPE_NAME_2, "Edm.String", true, null, "None"); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "c2ListProperty", COMPLEX_TYPE_NAME_2, "Edm.String", true, null, "List"); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "c2ComplexProperty", COMPLEX_TYPE_NAME_2, COMPLEX_TYPE_NAME_3, true, null, "None"); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "c2ListComplexProperty", COMPLEX_TYPE_NAME_2, LIST_COMPLEX_TYPE_NAME_3, true, null, "List"); // 2階層目のComplexType(List)作成 UserDataUtils.createComplexType(cellName, boxName, odataColName, LIST_COMPLEX_TYPE_NAME_2); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "lc2Property", LIST_COMPLEX_TYPE_NAME_2, "Edm.String", true, null, "None"); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "lc2ListProperty", LIST_COMPLEX_TYPE_NAME_2, "Edm.String", true, null, "List"); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "lc2ComplexProperty", LIST_COMPLEX_TYPE_NAME_2, COMPLEX_TYPE_NAME_3, true, null, "None"); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "lc2ListComplexProperty", LIST_COMPLEX_TYPE_NAME_2, LIST_COMPLEX_TYPE_NAME_3, true, null, "List"); // 1階層目のComplexType作成 UserDataUtils.createComplexType(cellName, boxName, odataColName, COMPLEX_TYPE_NAME_1); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "c1Property", COMPLEX_TYPE_NAME_1, "Edm.String", true, null, "None"); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "c1ListProperty", COMPLEX_TYPE_NAME_1, "Edm.String", true, null, "List"); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "c1ComplexProperty", COMPLEX_TYPE_NAME_1, COMPLEX_TYPE_NAME_2, true, null, "None"); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "c1ListComplexProperty", COMPLEX_TYPE_NAME_1, LIST_COMPLEX_TYPE_NAME_2, true, null, "List"); // 1階層目のComplexType(List)作成 UserDataUtils.createComplexType(cellName, boxName, odataColName, LIST_COMPLEX_TYPE_NAME_1); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "lc1Property", LIST_COMPLEX_TYPE_NAME_1, "Edm.String", true, null, "None"); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "lc1ListProperty", LIST_COMPLEX_TYPE_NAME_1, "Edm.String", true, null, "List"); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "lc1ComplexProperty", LIST_COMPLEX_TYPE_NAME_1, COMPLEX_TYPE_NAME_2, true, null, "None"); UserDataUtils.createComplexTypeProperty(cellName, boxName, odataColName, "lc1ListComplexProperty", LIST_COMPLEX_TYPE_NAME_1, LIST_COMPLEX_TYPE_NAME_2, true, null, "List"); // Property作成 UserDataUtils.createProperty(cellName, boxName, odataColName, "p1Property", entityTypeName, "Edm.String", true, null, "None", false, null); UserDataUtils.createProperty(cellName, boxName, odataColName, "p1ListProperty", entityTypeName, "Edm.String", true, null, "List", false, null); UserDataUtils.createProperty(cellName, boxName, odataColName, "p1ComplexProperty", entityTypeName, COMPLEX_TYPE_NAME_1, true, null, "None", false, null); UserDataUtils.createProperty(cellName, boxName, odataColName, "p1ComplexListProperty", entityTypeName, LIST_COMPLEX_TYPE_NAME_1, true, null, "List", false, null); } private TResponse createUserData(String token, String cellName, String boxName, String odataColName, String entityTypeName, String id) { // ユーザOData作成 return UserDataUtils.create(token, HttpStatus.SC_CREATED, getDefaultUserDataRequestBody(id), cellName, boxName, odataColName, entityTypeName); } private void createODataCollection(String token, String cellName, String boxName, String odataColName) { // Cell作成 CellUtils.create(cellName, token, HttpStatus.SC_CREATED); // Box作成 BoxUtils.create(cellName, boxName, token, HttpStatus.SC_CREATED); // Collection作成 DavResourceUtils.createODataCollection(token, HttpStatus.SC_CREATED, cellName, boxName, odataColName); } private String getDefaultUserDataRequestBody(String id) { return "{" + " \"__id\": \"" + id + "\"," + " \"p1Property\": \"p1PropertyValue\"," + " \"p1ListProperty\": [" + " \"p1ListPropertyValue1\"," + " \"p1ListPropertyValue2\"" + " ]," + " \"p1ComplexProperty\": {" + " \"c1Property\": \"c1PropertyValue\"," + " \"c1ListProperty\": [" + " \"c1ListPropertyValue1\"," + " \"c1ListPropertyValue2\"" + " ]," + " \"c1ComplexProperty\": {" + " \"c2Property\": \"c2PropertyValue\"," + " \"c2ListProperty\": [" + " \"c2ListPropertyValue1\"," + " \"c2ListPropertyValue2\"" + " ]," + " \"c2ComplexProperty\": {" + " \"c3Property\": \"c3PropertyValue\"," + " \"c3ListProperty\": [" + " \"c3ListPropertyValue1\"," + " \"c3ListPropertyValue2\"" + " ]" + " }," + " \"c2ListComplexProperty\": [" + " {" + " \"lc3Property\": \"lc3PropertyValue\"," + " \"lc3ListProperty\": [" + " \"lc3ListPropertyValue1\"," + " \"lc3ListPropertyValue2\"" + " ]" + " }" + " ]" + " }," + " \"c1ListComplexProperty\": [" + " {" + " \"lc2Property\": \"lc2PropertyValue\"," + " \"lc2ListProperty\": [" + " \"lc2ListPropertyValue1\"," + " \"lc2ListPropertyValue2\"" + " ]," + " \"lc2ComplexProperty\": {" + " \"c3Property\": \"c3PropertyValue\"," + " \"c3ListProperty\": [" + " \"c3ListPropertyValue1\"," + " \"c3ListPropertyValue2\"" + " ]" + " }," + " \"lc2ListComplexProperty\": [" + " {" + " \"lc3Property\": \"lc3PropertyValue\"," + " \"lc3ListProperty\": [" + " \"lc3ListPropertyValue1\"," + " \"lc3ListPropertyValue2\"" + " ]" + " }" + " ]" + " }" + " ]" + " }," + " \"p1ComplexListProperty\": [" + " {" + " \"lc1Property\": \"lc1PropertyValue\"," + " \"lc1ListProperty\": [" + " \"lc1ListPropertyValue1\"," + " \"lc1ListPropertyValue2\"" + " ]," + " \"lc1ComplexProperty\": {" + " \"c2Property\": \"c2PropertyValue\"," + " \"c2ListProperty\": [" + " \"c2ListPropertyValue1\"," + " \"c2ListPropertyValue2\"" + " ]," + " \"c2ComplexProperty\": {" + " \"c3Property\": \"c3PropertyValue\"," + " \"c3ListProperty\": [" + " \"c3ListPropertyValue1\"," + " \"c3ListPropertyValue2\"" + " ]" + " }," + " \"c2ListComplexProperty\": [" + " {" + " \"lc3Property\": \"lc3PropertyValue\"," + " \"lc3ListProperty\": [" + " \"lc3ListPropertyValue1\"," + " \"lc3ListPropertyValue2\"" + " ]" + " }" + " ]" + " }," + " \"lc1ListComplexProperty\": [" + " {" + " \"lc2Property\": \"lc2PropertyValue\"," + " \"lc2ListProperty\": [" + " \"lc2ListPropertyValue1\"," + " \"lc2ListPropertyValue2\"" + " ]," + " \"lc2ComplexProperty\": {" + " \"c3Property\": \"c3PropertyValue\"," + " \"c3ListProperty\": [" + " \"c3ListPropertyValue1\"," + " \"c3ListPropertyValue2\"" + " ]" + " }," + " \"lc2ListComplexProperty\": [" + " {" + " \"lc3Property\": \"lc3PropertyValue\"," + " \"lc3ListProperty\": [" + " \"lc3ListPropertyValue1\"," + " \"lc3ListPropertyValue2\"" + " ]" + " }" + " ]" + " }" + " ]" + " }" + " ]" + "}"; } }
92304bdd6317c81e7edfb32d3740a615d700aa89
2,346
java
Java
MMN15/final/question1/MainWindow.java
ronen25/20554_advanced_java
e59fb7f9c48cd6c3e4ae3b9ff81d845d7d696d91
[ "Unlicense" ]
1
2020-02-22T09:42:24.000Z
2020-02-22T09:42:24.000Z
MMN15/question1/src/MainWindow.java
ronen25/20554_advanced_java
e59fb7f9c48cd6c3e4ae3b9ff81d845d7d696d91
[ "Unlicense" ]
null
null
null
MMN15/question1/src/MainWindow.java
ronen25/20554_advanced_java
e59fb7f9c48cd6c3e4ae3b9ff81d845d7d696d91
[ "Unlicense" ]
null
null
null
28.609756
102
0.602302
995,424
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** Main application window */ public class MainWindow extends JFrame { // Constants private final int WINDOW_WIDTH = 700; private final int WINDOW_HEIGHT = 700; // Properties private int numThreads, numPasses; private ImageDisplay display; private ButtonPanel btnPanel; private ImageCrunchWorker crunchWorker; // Cnstr. public MainWindow(int dimension, int threads, int passes) { numThreads = threads; numPasses = passes; initFrame(); initUI(dimension); initActions(); } /** Initialize the frame itself. */ private void initFrame() { setTitle("Shrink"); setSize(WINDOW_WIDTH, WINDOW_HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } /** Initialize UI */ private void initUI(int dimension) { // Initialize layout this.setLayout(new BorderLayout()); // Initialize display display = new ImageDisplay(dimension); // Initialize button panel btnPanel = new ButtonPanel(); // Add everything to the window this.add(display, BorderLayout.CENTER); this.add(btnPanel, BorderLayout.SOUTH); } /** Initialize button actions. */ private void initActions() { // "Clear" button event btnPanel.getClearButton().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { clearButtonClicked(); } }); // "Go" button event btnPanel.getGoButton().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { goButtonClicked(); } }); } /** Event callback for the "clear" button. */ private void clearButtonClicked() { display.clearBoard(); } /** Event callback for the go/stop button. */ private void goButtonClicked() { crunchWorker = new ImageCrunchWorker(display, btnPanel.getGoButton(), numPasses, numThreads); crunchWorker.execute(); } }
92304d9979c41deb2b457a68889ea2059741eac8
2,057
java
Java
onebusaway-status-jetty-exporter/src/main/java/org/onebusaway/status_exporter/StatusJettyExporterModule.java
OneBusAway/onebusaway-status-exporter
98657202048fd6d8ac941dd4a50927677fa6437c
[ "Apache-2.0" ]
null
null
null
onebusaway-status-jetty-exporter/src/main/java/org/onebusaway/status_exporter/StatusJettyExporterModule.java
OneBusAway/onebusaway-status-exporter
98657202048fd6d8ac941dd4a50927677fa6437c
[ "Apache-2.0" ]
1
2020-02-11T15:12:16.000Z
2020-02-11T15:12:16.000Z
onebusaway-status-jetty-exporter/src/main/java/org/onebusaway/status_exporter/StatusJettyExporterModule.java
OneBusAway/onebusaway-status-exporter
98657202048fd6d8ac941dd4a50927677fa6437c
[ "Apache-2.0" ]
1
2020-02-11T14:46:00.000Z
2020-02-11T14:46:00.000Z
28.971831
90
0.725328
995,425
/** * Copyright (C) 2012 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 org.onebusaway.status_exporter; import java.net.MalformedURLException; import java.net.URL; import java.util.Set; import javax.servlet.Servlet; import org.onebusaway.guice.jetty_exporter.JettyExporterModule; import com.google.inject.AbstractModule; import com.google.inject.Module; import com.google.inject.name.Names; public class StatusJettyExporterModule extends AbstractModule { public static void addModuleAndDependencies(Set<Module> modules) { modules.add(new StatusJettyExporterModule()); JettyExporterModule.addModuleAndDependencies(modules); StatusServiceModule.addModuleAndDependencies(modules); } @Override protected void configure() { bind(StatusServletSource.class); try { bind(URL.class).annotatedWith(Names.named(StatusServletSource.URL_NAME)).toInstance( new URL("http://localhost/status")); } catch (MalformedURLException e) { throw new IllegalStateException(e); } bind(Servlet.class).annotatedWith( Names.named(StatusServletSource.SERVLET_NAME)).to(StatusServlet.class); } /** * Implement hashCode() and equals() such that two instances of the module * will be equal. */ @Override public int hashCode() { return this.getClass().hashCode(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; return this.getClass().equals(o.getClass()); } }
92304df588d14df0d8616d1a74c0c3bf47f8d850
1,980
java
Java
src/main/java/org/kasperrat/server/Server.java
KasperOmari/KaspeRRAT-server
d9b30679dbedde3806553e8542058279a77ca2af
[ "MIT" ]
null
null
null
src/main/java/org/kasperrat/server/Server.java
KasperOmari/KaspeRRAT-server
d9b30679dbedde3806553e8542058279a77ca2af
[ "MIT" ]
null
null
null
src/main/java/org/kasperrat/server/Server.java
KasperOmari/KaspeRRAT-server
d9b30679dbedde3806553e8542058279a77ca2af
[ "MIT" ]
1
2018-04-13T21:50:21.000Z
2018-04-13T21:50:21.000Z
25.714286
94
0.539899
995,426
package org.kasperrat.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class Server { static String clientname; public static void main(String[] args) { try(ServerSocket ss = new ServerSocket(5461)){ System.out.println("listening.. "); Socket s = ss.accept(); PrintWriter pw = new PrintWriter(s.getOutputStream()); BufferedReader bf = new BufferedReader(new InputStreamReader(s.getInputStream())); Scanner in = new Scanner(System.in); clientname = s.getInetAddress().getHostName(); //pw.println("Welcome the server"); //pw.flush(); System.out.println("Connected to: " + clientname); // while(!(str = bf.readLine()).equals("bye")){ // // System.out.println(clientname + ": " + str); // String response = in.nextLine(); // pw.println(response); // } //poc(); String str; do{ str = in.nextLine(); pw.println(str); pw.flush(); if(str.equals("bye")) break; System.out.println("Response: "); bf.lines().forEach(System.out::println); //System.out.println("Response: " + response); }while(true); s.close(); } catch (IOException e) { e.printStackTrace(); } } public static void poc(String cmd){ try { Process p = new ProcessBuilder("ls").start(); BufferedReader bf = new BufferedReader(new InputStreamReader(p.getInputStream())); bf.lines().forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } }
92304e92c49e1ebb0021a299b5d24bd3f2e5e008
472
java
Java
geo-analyzer/src/main/java/au/gov/amsa/util/rx/CompositeException.java
Matthimatiker/risky
d8bf1313b2584ea176c80c751cfa8bd312670340
[ "Apache-2.0" ]
9
2015-04-21T12:06:02.000Z
2022-03-06T08:36:47.000Z
geo-analyzer/src/main/java/au/gov/amsa/util/rx/CompositeException.java
Matthimatiker/risky
d8bf1313b2584ea176c80c751cfa8bd312670340
[ "Apache-2.0" ]
66
2018-03-28T06:06:37.000Z
2022-03-29T03:26:05.000Z
geo-analyzer/src/main/java/au/gov/amsa/util/rx/CompositeException.java
Matthimatiker/risky
d8bf1313b2584ea176c80c751cfa8bd312670340
[ "Apache-2.0" ]
7
2015-01-19T07:56:49.000Z
2021-11-17T20:34:12.000Z
23.6
68
0.78178
995,427
package au.gov.amsa.util.rx; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CompositeException extends Exception { private static final long serialVersionUID = -1150240783814840391L; private final List<Throwable> exceptions; public CompositeException(Throwable... exceptions) { this.exceptions = Arrays.asList(exceptions); } public List<Throwable> getExceptions() { return new ArrayList<Throwable>(exceptions); } }
92304ecd95d22a125c7b6dda893bec9715e2ed5f
666
java
Java
src/main/java/no/hvl/past/webui/backend/quickRuleEngine/AbstractEventTrigger.java
webminz/mdegraphlib-gui
2d82a919046059a600537c48b073c43d6bf5d9ce
[ "Unlicense" ]
null
null
null
src/main/java/no/hvl/past/webui/backend/quickRuleEngine/AbstractEventTrigger.java
webminz/mdegraphlib-gui
2d82a919046059a600537c48b073c43d6bf5d9ce
[ "Unlicense" ]
null
null
null
src/main/java/no/hvl/past/webui/backend/quickRuleEngine/AbstractEventTrigger.java
webminz/mdegraphlib-gui
2d82a919046059a600537c48b073c43d6bf5d9ce
[ "Unlicense" ]
null
null
null
24.666667
104
0.63964
995,428
package no.hvl.past.webui.backend.quickRuleEngine; import no.hvl.past.webui.transfer.quickRuleEngine.domain.Event; import java.util.function.Consumer; public abstract class AbstractEventTrigger<E extends Event> extends Trigger implements Consumer<Event> { public AbstractEventTrigger(RuleEngine engine) { super(engine); engine.registerForEvents(this); } @Override public void accept(Event e) { try { if (reactsOn((E) e)) { trigger(); } } catch (ClassCastException ex) { // Nothing to do here } } protected abstract boolean reactsOn(E event); }
92304f1f5d9bb0e581e9f0143688865124611fd0
585
java
Java
8BitBot/src/org/usfirst/frc/team6317/robot/commands/WaitTimer.java
DisruptiveInnovation6317/GearBot
f20f3e4de625b80af2473752ae2e75f4186ac23e
[ "MIT" ]
null
null
null
8BitBot/src/org/usfirst/frc/team6317/robot/commands/WaitTimer.java
DisruptiveInnovation6317/GearBot
f20f3e4de625b80af2473752ae2e75f4186ac23e
[ "MIT" ]
1
2017-04-21T02:38:35.000Z
2017-04-21T02:38:35.000Z
8BitBot/src/org/usfirst/frc/team6317/robot/commands/WaitTimer.java
DisruptiveInnovation6317/GearBot
f20f3e4de625b80af2473752ae2e75f4186ac23e
[ "MIT" ]
8
2017-04-14T15:00:56.000Z
2018-02-16T03:53:01.000Z
18.28125
62
0.726496
995,429
package org.usfirst.frc.team6317.robot.commands; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.command.Command; public class WaitTimer extends Command { double seconds; double startTime; Timer timing = new Timer(); public WaitTimer(double seconds) { this.seconds = seconds; } @Override protected void initialize() { startTime = timing.getFPGATimestamp(); // timing.delay(this.seconds); } @Override protected boolean isFinished() { return timing.getFPGATimestamp() - startTime > this.seconds; } @Override protected void end() { } }
92305030607c857dfbbe761c18ec782f69bb46a9
2,423
java
Java
finance/egov/egov-egi/src/main/java/org/egov/infra/microservice/models/BankAccountServiceMappingResponse.java
jagankumar-egov/DIGIT-OSS
271259e847c236a287401bbd4f95cbbbeab8522b
[ "MIT" ]
11
2021-04-22T13:18:00.000Z
2021-07-13T06:24:48.000Z
finance/egov/egov-egi/src/main/java/org/egov/infra/microservice/models/BankAccountServiceMappingResponse.java
jagankumar-egov/DIGIT-OSS
271259e847c236a287401bbd4f95cbbbeab8522b
[ "MIT" ]
56
2019-09-24T00:12:41.000Z
2022-02-01T00:58:00.000Z
finance/egov/egov-egi/src/main/java/org/egov/infra/microservice/models/BankAccountServiceMappingResponse.java
jagankumar-egov/DIGIT-OSS
271259e847c236a287401bbd4f95cbbbeab8522b
[ "MIT" ]
11
2021-04-14T08:24:35.000Z
2021-07-12T04:15:09.000Z
40.5
105
0.746502
995,430
/* * eGov suite of products aim to improve the internal efficiency,transparency, * accountability and the service delivery of the government organizations. * * Copyright (C) 2016 eGovernments Foundation * * The updated version of eGov suite of products as by eGovernments Foundation * is available at http://www.egovernments.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/ or * http://www.gnu.org/licenses/gpl.html . * * In addition to the terms of the GPL license to be adhered to in using this * program, the following additional terms are to be complied with: * * 1) All versions of this program, verbatim or modified must carry this * Legal Notice. * * 2) Any misrepresentation of the origin of the material is prohibited. It * is required that all modified versions of this material be marked in * reasonable ways as different from the original version. * * 3) This license does not grant any rights to any user of the program * with regards to rights under trademark law for use of the trade names * or trademarks of eGovernments Foundation. * * In case of any queries, you can reach eGovernments Foundation at lyhxr@example.com. */ package org.egov.infra.microservice.models; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; public class BankAccountServiceMappingResponse { @JsonProperty("BankAccountServiceMapping") private List<BankAccountServiceMapping> bankAccountServiceMapping; public List<BankAccountServiceMapping> getBankAccountServiceMapping() { return bankAccountServiceMapping; } public void setBankAccountServiceMapping(List<BankAccountServiceMapping> bankAccountServiceMapping) { this.bankAccountServiceMapping = bankAccountServiceMapping; } }
923050bfb5a671e221ea3b6cd0900126fc542f04
6,771
java
Java
emoji-ios/src/main/java/com/vanniktech/emoji/ios/category/TravelCategory.java
Kraskovskiy/Emoji
6ae147edca6b1bcb9978bb7662613c8989b9f801
[ "Apache-2.0" ]
1
2017-08-27T15:27:39.000Z
2017-08-27T15:27:39.000Z
emoji-ios/src/main/java/com/vanniktech/emoji/ios/category/TravelCategory.java
torindev/emoji
c5d81b463fe617f333222106cbf53ea71a93fd85
[ "Apache-2.0" ]
null
null
null
emoji-ios/src/main/java/com/vanniktech/emoji/ios/category/TravelCategory.java
torindev/emoji
c5d81b463fe617f333222106cbf53ea71a93fd85
[ "Apache-2.0" ]
1
2020-03-30T05:00:59.000Z
2020-03-30T05:00:59.000Z
48.364286
112
0.751735
995,431
package com.vanniktech.emoji.ios.category; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import com.vanniktech.emoji.emoji.Emoji; import com.vanniktech.emoji.emoji.EmojiCategory; import com.vanniktech.emoji.ios.R; @SuppressWarnings("PMD.MethodReturnsInternalArray") public final class TravelCategory implements EmojiCategory { private static final Emoji[] DATA = new Emoji[] { new Emoji(0x1f697, R.drawable.emoji_ios_1f697), new Emoji(0x1f695, R.drawable.emoji_ios_1f695), new Emoji(0x1f699, R.drawable.emoji_ios_1f699), new Emoji(0x1f68c, R.drawable.emoji_ios_1f68c), new Emoji(0x1f68e, R.drawable.emoji_ios_1f68e), new Emoji(0x1f3ce, R.drawable.emoji_ios_1f3ce), new Emoji(0x1f693, R.drawable.emoji_ios_1f693), new Emoji(0x1f691, R.drawable.emoji_ios_1f691), new Emoji(0x1f692, R.drawable.emoji_ios_1f692), new Emoji(0x1f690, R.drawable.emoji_ios_1f690), new Emoji(0x1f69a, R.drawable.emoji_ios_1f69a), new Emoji(0x1f69b, R.drawable.emoji_ios_1f69b), new Emoji(0x1f69c, R.drawable.emoji_ios_1f69c), new Emoji(0x1f6f4, R.drawable.emoji_ios_1f6f4), new Emoji(0x1f6b2, R.drawable.emoji_ios_1f6b2), new Emoji(0x1f6f5, R.drawable.emoji_ios_1f6f5), new Emoji(0x1f3cd, R.drawable.emoji_ios_1f3cd), new Emoji(0x1f6a8, R.drawable.emoji_ios_1f6a8), new Emoji(0x1f694, R.drawable.emoji_ios_1f694), new Emoji(0x1f68d, R.drawable.emoji_ios_1f68d), new Emoji(0x1f698, R.drawable.emoji_ios_1f698), new Emoji(0x1f696, R.drawable.emoji_ios_1f696), new Emoji(0x1f6a1, R.drawable.emoji_ios_1f6a1), new Emoji(0x1f6a0, R.drawable.emoji_ios_1f6a0), new Emoji(0x1f69f, R.drawable.emoji_ios_1f69f), new Emoji(0x1f683, R.drawable.emoji_ios_1f683), new Emoji(0x1f68b, R.drawable.emoji_ios_1f68b), new Emoji(0x1f69e, R.drawable.emoji_ios_1f69e), new Emoji(0x1f69d, R.drawable.emoji_ios_1f69d), new Emoji(0x1f684, R.drawable.emoji_ios_1f684), new Emoji(0x1f685, R.drawable.emoji_ios_1f685), new Emoji(0x1f688, R.drawable.emoji_ios_1f688), new Emoji(0x1f682, R.drawable.emoji_ios_1f682), new Emoji(0x1f686, R.drawable.emoji_ios_1f686), new Emoji(0x1f687, R.drawable.emoji_ios_1f687), new Emoji(0x1f68a, R.drawable.emoji_ios_1f68a), new Emoji(0x1f689, R.drawable.emoji_ios_1f689), new Emoji(0x1f681, R.drawable.emoji_ios_1f681), new Emoji(0x1f6e9, R.drawable.emoji_ios_1f6e9), new Emoji(0x2708, R.drawable.emoji_ios_2708), new Emoji(0x1f6eb, R.drawable.emoji_ios_1f6eb), new Emoji(0x1f6ec, R.drawable.emoji_ios_1f6ec), new Emoji(0x1f680, R.drawable.emoji_ios_1f680), new Emoji(0x1f6f0, R.drawable.emoji_ios_1f6f0), new Emoji(0x1f4ba, R.drawable.emoji_ios_1f4ba), new Emoji(0x1f6f6, R.drawable.emoji_ios_1f6f6), new Emoji(0x26f5, R.drawable.emoji_ios_26f5), new Emoji(0x1f6e5, R.drawable.emoji_ios_1f6e5), new Emoji(0x1f6a4, R.drawable.emoji_ios_1f6a4), new Emoji(0x1f6f3, R.drawable.emoji_ios_1f6f3), new Emoji(0x26f4, R.drawable.emoji_ios_26f4), new Emoji(0x1f6a2, R.drawable.emoji_ios_1f6a2), new Emoji(0x2693, R.drawable.emoji_ios_2693), new Emoji(0x1f6a7, R.drawable.emoji_ios_1f6a7), new Emoji(0x26fd, R.drawable.emoji_ios_26fd), new Emoji(0x1f68f, R.drawable.emoji_ios_1f68f), new Emoji(0x1f6a6, R.drawable.emoji_ios_1f6a6), new Emoji(0x1f6a5, R.drawable.emoji_ios_1f6a5), new Emoji(0x1f5fa, R.drawable.emoji_ios_1f5fa), new Emoji(0x1f5ff, R.drawable.emoji_ios_1f5ff), new Emoji(0x1f5fd, R.drawable.emoji_ios_1f5fd), new Emoji(0x26f2, R.drawable.emoji_ios_26f2), new Emoji(0x1f5fc, R.drawable.emoji_ios_1f5fc), new Emoji(0x1f3f0, R.drawable.emoji_ios_1f3f0), new Emoji(0x1f3ef, R.drawable.emoji_ios_1f3ef), new Emoji(0x1f3df, R.drawable.emoji_ios_1f3df), new Emoji(0x1f3a1, R.drawable.emoji_ios_1f3a1), new Emoji(0x1f3a2, R.drawable.emoji_ios_1f3a2), new Emoji(0x1f3a0, R.drawable.emoji_ios_1f3a0), new Emoji(0x26f1, R.drawable.emoji_ios_26f1), new Emoji(0x1f3d6, R.drawable.emoji_ios_1f3d6), new Emoji(0x1f3dd, R.drawable.emoji_ios_1f3dd), new Emoji(0x26f0, R.drawable.emoji_ios_26f0), new Emoji(0x1f3d4, R.drawable.emoji_ios_1f3d4), new Emoji(0x1f5fb, R.drawable.emoji_ios_1f5fb), new Emoji(0x1f30b, R.drawable.emoji_ios_1f30b), new Emoji(0x1f3dc, R.drawable.emoji_ios_1f3dc), new Emoji(0x1f3d5, R.drawable.emoji_ios_1f3d5), new Emoji(0x26fa, R.drawable.emoji_ios_26fa), new Emoji(0x1f6e4, R.drawable.emoji_ios_1f6e4), new Emoji(0x1f6e3, R.drawable.emoji_ios_1f6e3), new Emoji(0x1f3d7, R.drawable.emoji_ios_1f3d7), new Emoji(0x1f3ed, R.drawable.emoji_ios_1f3ed), new Emoji(0x1f3e0, R.drawable.emoji_ios_1f3e0), new Emoji(0x1f3e1, R.drawable.emoji_ios_1f3e1), new Emoji(0x1f3d8, R.drawable.emoji_ios_1f3d8), new Emoji(0x1f3da, R.drawable.emoji_ios_1f3da), new Emoji(0x1f3e2, R.drawable.emoji_ios_1f3e2), new Emoji(0x1f3ec, R.drawable.emoji_ios_1f3ec), new Emoji(0x1f3e3, R.drawable.emoji_ios_1f3e3), new Emoji(0x1f3e4, R.drawable.emoji_ios_1f3e4), new Emoji(0x1f3e5, R.drawable.emoji_ios_1f3e5), new Emoji(0x1f3e6, R.drawable.emoji_ios_1f3e6), new Emoji(0x1f3e8, R.drawable.emoji_ios_1f3e8), new Emoji(0x1f3ea, R.drawable.emoji_ios_1f3ea), new Emoji(0x1f3eb, R.drawable.emoji_ios_1f3eb), new Emoji(0x1f3e9, R.drawable.emoji_ios_1f3e9), new Emoji(0x1f492, R.drawable.emoji_ios_1f492), new Emoji(0x1f3db, R.drawable.emoji_ios_1f3db), new Emoji(0x26ea, R.drawable.emoji_ios_26ea), new Emoji(0x1f54c, R.drawable.emoji_ios_1f54c), new Emoji(0x1f54d, R.drawable.emoji_ios_1f54d), new Emoji(0x1f54b, R.drawable.emoji_ios_1f54b), new Emoji(0x26e9, R.drawable.emoji_ios_26e9), new Emoji(0x1f5fe, R.drawable.emoji_ios_1f5fe), new Emoji(0x1f391, R.drawable.emoji_ios_1f391), new Emoji(0x1f3de, R.drawable.emoji_ios_1f3de), new Emoji(0x1f305, R.drawable.emoji_ios_1f305), new Emoji(0x1f304, R.drawable.emoji_ios_1f304), new Emoji(0x1f320, R.drawable.emoji_ios_1f320), new Emoji(0x1f387, R.drawable.emoji_ios_1f387), new Emoji(0x1f386, R.drawable.emoji_ios_1f386), new Emoji(0x1f307, R.drawable.emoji_ios_1f307), new Emoji(0x1f306, R.drawable.emoji_ios_1f306), new Emoji(0x1f3d9, R.drawable.emoji_ios_1f3d9), new Emoji(0x1f303, R.drawable.emoji_ios_1f303), new Emoji(0x1f30c, R.drawable.emoji_ios_1f30c), new Emoji(0x1f309, R.drawable.emoji_ios_1f309), new Emoji(0x1f301, R.drawable.emoji_ios_1f301) }; @Override @NonNull public Emoji[] getEmojis() { return DATA; } @Override @DrawableRes public int getIcon() { return R.drawable.emoji_ios_category_travel; } }
9230512a03dc7f1de1ffa0969f700a1150e3a046
4,332
java
Java
Corpus/birt/7639.java
JamesCao2048/BlizzardData
a524bec4f0d297bb748234eeb1c2fcdee3dce7d7
[ "MIT" ]
1
2022-01-15T02:47:45.000Z
2022-01-15T02:47:45.000Z
Corpus/birt/7639.java
JamesCao2048/BlizzardData
a524bec4f0d297bb748234eeb1c2fcdee3dce7d7
[ "MIT" ]
null
null
null
Corpus/birt/7639.java
JamesCao2048/BlizzardData
a524bec4f0d297bb748234eeb1c2fcdee3dce7d7
[ "MIT" ]
null
null
null
26.740741
100
0.638504
995,432
/******************************************************************************* * Copyright (c) 2004, 2005 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.data.engine.olap.data.util; import java.io.IOException; import java.math.BigDecimal; import java.util.Date; import org.eclipse.birt.data.engine.olap.data.util.BufferedStructureArray; import junit.framework.TestCase; /** * */ public class BufferedStructureArrayTest extends TestCase { /* * (non-Javadoc) * * @see junit.framework.TestCase#setUp() */ protected void setUp( ) throws Exception { super.setUp( ); } /* * @see TestCase#tearDown() */ protected void tearDown( ) throws Exception { super.tearDown( ); } public void testMemberForTest( ) throws IOException { int objectNumber = 1001; BufferedStructureArray list = new BufferedStructureArray( MemberForTest.getMemberCreator( ),200 ); for ( int i = 0; i < objectNumber; i++ ) { list.add( createMember( i ) ); } assertEquals( list.size( ), objectNumber ); for ( int i = 0; i < objectNumber; i++ ) { assertEquals( list.get( i ), createMember( i ) ); } list.close( ); } public void testMemberForTest1( ) throws IOException { int objectNumber = 10001; BufferedStructureArray list = new BufferedStructureArray( MemberForTest.getMemberCreator( ),200 ); for ( int i = 0; i < objectNumber; i++ ) { list.add( createMember( i ) ); try { list.get( i+1 ); fail(); } catch(IndexOutOfBoundsException e) { } } assertEquals( list.size( ), objectNumber ); for ( int i = 0; i < objectNumber; i++ ) { assertEquals( list.get( i ), createMember( i ) ); } list.close( ); } public void testMemberForTest2( ) throws IOException { int objectNumber1 = 5401; int objectNumber2 = 2000; BufferedStructureArray list = new BufferedStructureArray( MemberForTest.getMemberCreator( ),200 ); for ( int i = 0; i < objectNumber1; i++ ) { list.add( createMember( i ) ); } assertEquals( list.size( ), objectNumber1 ); for ( int i = 0; i < objectNumber1; i++ ) { assertEquals( list.get( i ), createMember( i ) ); } for ( int i = 0; i < objectNumber2; i++ ) { list.add( createMember( i ) ); } assertEquals( list.size( ), objectNumber1 + objectNumber2 ); for ( int i = 0; i < objectNumber2; i++ ) { assertEquals( list.get( objectNumber1 + i ), createMember( i ) ); } list.close( ); } public void testMemberForTest3( ) throws IOException { int objectNumber = 10001; BufferedStructureArray list = new BufferedStructureArray( MemberForTest.getMemberCreator( ),200 ); for ( int i = 0; i < objectNumber; i++ ) { list.add( createMember( i ) ); assertEquals( list.size( ), i + 1 ); assertEquals( list.get( i ), createMember( i ) ); } list.close( ); } public void testStress( ) throws IOException { long startTime = System.currentTimeMillis( ); int objectNumber = 100000; BufferedStructureArray list = new BufferedStructureArray( MemberForTest.getMemberCreator( ),200 ); for ( int i = 0; i < objectNumber; i++ ) { list.add( createMember( i ) ); } System.out.println( "used add:" +(System.currentTimeMillis( )-startTime)/100); assertEquals( list.size( ), objectNumber ); for ( int i = 0; i < objectNumber; i++ ) { assertEquals( list.get( i ), createMember( i ) ); } System.out.println( "used get:" +(System.currentTimeMillis( )-startTime)/100); list.close( ); } static private MemberForTest createMember( int i ) { int iField = i; Date dateField = new Date( 190001000 + i * 1000 ); String stringField = "string" + i; double doubleField = i + 10.0; BigDecimal bigDecimalField = new BigDecimal( "1010101010100101010110" + i ); boolean booleanField = ( i % 2 == 0 ? true : false ); return new MemberForTest( iField, dateField, stringField, doubleField, bigDecimalField, booleanField ); } }
9230516c057b8c3b42ffde58fc49707e56126fca
8,227
java
Java
dxa-framework/dxa-tridion-provider/src/main/java/com/sdl/dxa/tridion/graphql/GraphQLProvider.java
NIkonDSL/dxa-web-application-java
cbc039ec259c45d4b749af5d9b0bb1e7faad6db2
[ "Apache-2.0" ]
32
2015-08-11T21:44:38.000Z
2021-05-06T13:48:59.000Z
dxa-framework/dxa-tridion-provider/src/main/java/com/sdl/dxa/tridion/graphql/GraphQLProvider.java
NIkonDSL/dxa-web-application-java
cbc039ec259c45d4b749af5d9b0bb1e7faad6db2
[ "Apache-2.0" ]
125
2015-09-09T09:07:35.000Z
2021-06-10T12:04:35.000Z
dxa-framework/dxa-tridion-provider/src/main/java/com/sdl/dxa/tridion/graphql/GraphQLProvider.java
NIkonDSL/dxa-web-application-java
cbc039ec259c45d4b749af5d9b0bb1e7faad6db2
[ "Apache-2.0" ]
36
2015-09-01T16:57:52.000Z
2021-05-21T19:10:56.000Z
48.394118
227
0.657834
995,433
package com.sdl.dxa.tridion.graphql; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.sdl.dxa.api.datamodel.model.EntityModelData; import com.sdl.dxa.common.dto.EntityRequestDto; import com.sdl.dxa.common.dto.PageRequestDto; import com.sdl.dxa.tridion.pcaclient.ApiClientProvider; import com.sdl.dxa.tridion.pcaclient.GraphQLUtils; import com.sdl.web.pca.client.ApiClient; import com.sdl.web.pca.client.contentmodel.ContextData; import com.sdl.web.pca.client.contentmodel.enums.ContentIncludeMode; import com.sdl.web.pca.client.contentmodel.enums.ContentType; import com.sdl.web.pca.client.contentmodel.enums.DataModelType; import com.sdl.web.pca.client.contentmodel.enums.DcpType; import com.sdl.web.pca.client.contentmodel.enums.ModelServiceLinkRendering; import com.sdl.web.pca.client.contentmodel.enums.PageInclusion; import com.sdl.web.pca.client.contentmodel.enums.TcdlLinkRendering; import com.sdl.webapp.common.api.content.ContentProviderException; import com.sdl.webapp.common.api.content.PageNotFoundException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import java.io.IOException; import static com.sdl.dxa.common.util.PathUtils.normalizePathToDefaults; import static com.sdl.web.pca.client.contentmodel.enums.ContentNamespace.Sites; /** * Common class for interaction with GraphQL backend. */ @Slf4j @Component @Profile("!cil.providers.active") public class GraphQLProvider { private ObjectMapper objectMapper; private ApiClientProvider pcaClientProvider; @Autowired public GraphQLProvider(ApiClientProvider pcaClientProvider, ObjectMapper objectMapper) { this.objectMapper = objectMapper; this.pcaClientProvider = pcaClientProvider; } private ApiClient getPcaClient() { ApiClient pcaClient = this.pcaClientProvider.getClient(); pcaClient.setDefaultModelType(DataModelType.R2); pcaClient.setDefaultContentType(ContentType.MODEL); pcaClient.setModelSericeLinkRenderingType(ModelServiceLinkRendering.RELATIVE); pcaClient.setTcdlLinkRenderingType(TcdlLinkRendering.RELATIVE); return pcaClient; } // DXA supports "extensionless URLs" and "index pages". // For example: the index Page at root level (aka the Home Page) has a CM URL path of /index.html // It can be addressed in the DXA web application in several ways: // 1. /index.html – exactly the same as the CM URL // 2. /index – the file extension doesn't have to be specified explicitly {"extensionless URLs") // 3. / - the file name of an index page doesn't have to be specified explicitly either. // Note that the third option is the most clean one and considered the "canonical URL" in DXA; links to an index Page will be generated like that. // The problem with these "URL compression" features is that if a URL does not end with a slash (nor an extension), you don't // know upfront if the URL addresses a regular Page or an index Page (within a nested SG). // To determine this, DXA first tries the regular Page and if it doesn't exist, it appends /index.html and tries again. // TODO: The above should be handled by GraphQL (See CRQ-11703) public <T> T loadPage(Class<T> type, PageRequestDto pageRequest, ContentType contentType) throws ContentProviderException { try { JsonNode pageNode = getPcaClient().getPageModelData( GraphQLUtils.convertUriToGraphQLContentNamespace(pageRequest.getUriType()), pageRequest.getPublicationId(), normalizePathToDefaults(pageRequest.getPath()), contentType, DataModelType.valueOf(pageRequest.getDataModelType().toString()), PageInclusion.valueOf(pageRequest.getIncludePages().toString()), ContentIncludeMode.INCLUDE_DATA_AND_RENDER, null ); T result = mapToType(type, pageNode); if (log.isTraceEnabled()) { log.trace("Loaded '{}' for pageRequest '{}'", result, pageRequest); } return result; } catch (IOException e) { String pathToDefaults = normalizePathToDefaults(pageRequest.getPath(), true); log.info("Page not found by " + pageRequest + ", trying to find it by path " + pathToDefaults); JsonNode node = null; try { node = getPcaClient().getPageModelData( GraphQLUtils.convertUriToGraphQLContentNamespace(pageRequest.getUriType()), pageRequest.getPublicationId(), pathToDefaults, contentType, DataModelType.valueOf(pageRequest.getDataModelType().toString()), PageInclusion.valueOf(pageRequest.getIncludePages().toString()), ContentIncludeMode.INCLUDE_DATA_AND_RENDER, null); T result = mapToType(type, node); if (log.isTraceEnabled()) { log.trace("Loaded '{}' for pageRequest '{}'", result, pageRequest); } return result; } catch (IOException ex) { if (log.isTraceEnabled()) { log.trace("Response for request " + pageRequest + " is " + node, e); } throw new PageNotFoundException("Unable to load page, by request " + pageRequest, ex); } } } public <T> T loadPage(Class<T> type, String namespace, int publicationId, int pageId, ContentType contentType, DataModelType modelType, PageInclusion pageInclusion, ContextData contextData) throws ContentProviderException { JsonNode pageNode = getPcaClient().getPageModelData( GraphQLUtils.convertUriToGraphQLContentNamespace(namespace), publicationId, pageId, contentType, modelType, pageInclusion, ContentIncludeMode.INCLUDE_DATA_AND_RENDER, contextData ); T result = null; try { result = mapToType(type, pageNode); } catch (IOException ex) { throw new PageNotFoundException(String.format("Item '%d' not found for Localization '%d'", pageId, publicationId), ex); } return result; } public EntityModelData getEntityModelData(EntityRequestDto entityRequest) throws ContentProviderException { JsonNode node = null; try { node = getPcaClient().getEntityModelData(Sites, entityRequest.getPublicationId(), entityRequest.getComponentId(), entityRequest.getTemplateId(), ContentType.valueOf(entityRequest.getContentType().toString()), DataModelType.valueOf(entityRequest.getDataModelType().toString()), DcpType.valueOf(entityRequest.getDcpType().toString()), ContentIncludeMode.INCLUDE_DATA_AND_RENDER, null); EntityModelData modelData = mapToType(EntityModelData.class, node); if (log.isTraceEnabled()) { log.trace("Loaded '{}' for entityId '{}'", modelData, entityRequest.getComponentId()); } return modelData; } catch (IOException e) { if (log.isTraceEnabled()) { log.trace("Response for request " + entityRequest + " is " + node, e); } throw new ContentProviderException("Entity not found ny request " + entityRequest, e); } } private <T> T mapToType(Class<T> type, JsonNode result) throws JsonProcessingException { if (type.equals(String.class)) { return (T) result.toString(); } return objectMapper.treeToValue(result, type); } }
9230526fe7fd4b903ad8683e1a1d73d387670e93
726
java
Java
kodluyoruz-java-1-Odev/src/question7/inheritance/Inheritance.java
kodluyoruz-java-101-31102020-odevler/hafta-1-java-temelleri-ve-oop-Rojda97
300d3d48b33cf6c70a0aa72cae05c4536d58ff37
[ "MIT" ]
null
null
null
kodluyoruz-java-1-Odev/src/question7/inheritance/Inheritance.java
kodluyoruz-java-101-31102020-odevler/hafta-1-java-temelleri-ve-oop-Rojda97
300d3d48b33cf6c70a0aa72cae05c4536d58ff37
[ "MIT" ]
null
null
null
kodluyoruz-java-1-Odev/src/question7/inheritance/Inheritance.java
kodluyoruz-java-101-31102020-odevler/hafta-1-java-temelleri-ve-oop-Rojda97
300d3d48b33cf6c70a0aa72cae05c4536d58ff37
[ "MIT" ]
null
null
null
21.352941
57
0.677686
995,434
package question7.inheritance; public class Inheritance { public static void main(String[] args) { PersonelReport personelReport= new PersonelReport(); personelReport.setName("Deniz"); System.out.println("Adı: "+ personelReport.getName()); String value = personelReport.hashMD5Result(); System.out.println(value); SalesReport salesReport = new SalesReport(); salesReport.setName("Ayşe"); System.out.println(salesReport.getName()); String information ="Bilgi Teknolojileri"; DatabaseOperations.open(); DatabaseOperations.runQuery(information); Report report = new Report(); report.setName("Rapor"); Printer.print(report); } }
9230527cc4066b70bacbc6a7233e1538eb6006d8
253
java
Java
base/src/main/java/me/lynnchurch/base/mvp/BaseView.java
lynnchurch/MVPDemo
b333bc8c28aecfb567251d86826c1db5873b99b1
[ "Apache-2.0" ]
null
null
null
base/src/main/java/me/lynnchurch/base/mvp/BaseView.java
lynnchurch/MVPDemo
b333bc8c28aecfb567251d86826c1db5873b99b1
[ "Apache-2.0" ]
null
null
null
base/src/main/java/me/lynnchurch/base/mvp/BaseView.java
lynnchurch/MVPDemo
b333bc8c28aecfb567251d86826c1db5873b99b1
[ "Apache-2.0" ]
null
null
null
14.882353
47
0.715415
995,435
package me.lynnchurch.base.mvp; import android.app.Activity; public interface BaseView { void requestPermissions(Activity activity); void showLoading(); void hideLoading(); void showMessage(String message); void toFinish(); }
92305303de337c60a022fff559802f5f2311dac8
16,980
java
Java
docs-core/src/main/java/com/sismics/util/totp/GoogleAuthenticator.java
euanmcgregor/teddy-cloudron
d0a69f6fae6165b70edad9d88ec776f5b53d0e88
[ "MIT" ]
null
null
null
docs-core/src/main/java/com/sismics/util/totp/GoogleAuthenticator.java
euanmcgregor/teddy-cloudron
d0a69f6fae6165b70edad9d88ec776f5b53d0e88
[ "MIT" ]
null
null
null
docs-core/src/main/java/com/sismics/util/totp/GoogleAuthenticator.java
euanmcgregor/teddy-cloudron
d0a69f6fae6165b70edad9d88ec776f5b53d0e88
[ "MIT" ]
null
null
null
38.243243
219
0.659776
995,436
/* * Copyright (c) 2014-2016 Enrico M. Crisostomo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the author nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.sismics.util.totp; import org.apache.commons.codec.binary.Base32; import org.apache.commons.codec.binary.Base64; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.*; /** * This class implements the functionality described in RFC 6238 (TOTP: Time * based one-time password algorithm) and has been tested again Google's * implementation of such algorithm in its Google Authenticator application. * <p/> * This class lets users create a new 16-bit base32-encoded secret key with the * validation code calculated at {@code time = 0} (the UNIX epoch) and the URL * of a Google-provided QR barcode to let an user load the generated information * into Google Authenticator. * <p/> * The random number generator used by this class uses the default algorithm and * provider. Users can override them by setting the following system properties * to the algorithm and provider name of their choice: * <ul> * <li>{@link #RNG_ALGORITHM}.</li> * <li>{@link #RNG_ALGORITHM_PROVIDER}.</li> * </ul> * <p/> * This class does not store in any way either the generated keys nor the keys * passed during the authorization process. * <p/> * Java Server side class for Google Authenticator's TOTP generator was inspired * by an author's blog post. * * @author Enrico M. Crisostomo * @author Warren Strange * @version 0.5.0 * @see <a href= * "http://thegreyblog.blogspot.com/2011/12/google-authenticator-using-it-in-your.html" * /> * @see <a href="http://code.google.com/p/google-authenticator" /> * @see <a href="http://tools.ietf.org/id/draft-mraihi-totp-timebased-06.txt" /> * @since 0.3.0 */ public final class GoogleAuthenticator { /** * The system property to specify the random number generator algorithm to * use. * * @since 0.5.0 */ public static final String RNG_ALGORITHM = "com.warrenstrange.googleauth.rng.algorithm"; /** * The system property to specify the random number generator provider to * use. * * @since 0.5.0 */ public static final String RNG_ALGORITHM_PROVIDER = "com.warrenstrange.googleauth.rng.algorithmProvider"; /** * The number of bits of a secret key in binary form. Since the Base32 * encoding with 8 bit characters introduces an 160% overhead, we just need * 80 bits (10 bytes) to generate a 16 bytes Base32-encoded secret key. */ private static final int SECRET_BITS = 80; /** * Number of scratch codes to generate during the key generation. We are * using Google's default of providing 5 scratch codes. */ private static final int SCRATCH_CODES = 5; /** * Number of digits of a scratch code represented as a decimal integer. */ private static final int SCRATCH_CODE_LENGTH = 8; /** * Modulus used to truncate the scratch code. */ private static final int SCRATCH_CODE_MODULUS = (int) Math.pow(10, SCRATCH_CODE_LENGTH); /** * Magic number representing an invalid scratch code. */ private static final int SCRATCH_CODE_INVALID = -1; /** * Length in bytes of each scratch code. We're using Google's default of * using 4 bytes per scratch code. */ private static final int BYTES_PER_SCRATCH_CODE = 4; /** * The default SecureRandom algorithm to use if none is specified. * * @see java.security.SecureRandom#getInstance(String) * @since 0.5.0 */ private static final String DEFAULT_RANDOM_NUMBER_ALGORITHM = "SHA1PRNG"; /** * The default random number algorithm provider to use if none is specified. * * @see java.security.SecureRandom#getInstance(String) * @since 0.5.0 */ private static final String DEFAULT_RANDOM_NUMBER_ALGORITHM_PROVIDER = "SUN"; /** * Cryptographic hash function used to calculate the HMAC (Hash-based * Message Authentication Code). This implementation uses the SHA1 hash * function. */ private static final String HMAC_HASH_FUNCTION = "HmacSHA1"; /** * The configuration used by the current instance. */ private final GoogleAuthenticatorConfig config; /** * The internal SecureRandom instance used by this class. Since Java 7 * {@link Random} instances are required to be thread-safe, no * synchronisation is required in the methods of this class using this * instance. Thread-safety of this class was a de-facto standard in previous * versions of Java so that it is expected to work correctly in previous * versions of the Java platform as well. */ private ReseedingSecureRandom secureRandom = new ReseedingSecureRandom(getRandomNumberAlgorithm(), getRandomNumberAlgorithmProvider()); public GoogleAuthenticator() { config = new GoogleAuthenticatorConfig(); } /** * @return the random number generator algorithm. * @since 0.5.0 */ private String getRandomNumberAlgorithm() { return System.getProperty(RNG_ALGORITHM, DEFAULT_RANDOM_NUMBER_ALGORITHM); } /** * @return the random number generator algorithm provider. * @since 0.5.0 */ private String getRandomNumberAlgorithmProvider() { return System.getProperty(RNG_ALGORITHM_PROVIDER, DEFAULT_RANDOM_NUMBER_ALGORITHM_PROVIDER); } public int calculateCode(String secret, long tm) { return calculateCode(decodeKey(secret), tm); } /** * Decode a secret key in raw bytes. * * @param secret Secret key * @return Raw bytes */ private byte[] decodeKey(String secret) { switch (config.getKeyRepresentation()) { case BASE32: Base32 codec32 = new Base32(); return codec32.decode(secret); case BASE64: Base64 codec64 = new Base64(); return codec64.decode(secret); default: throw new IllegalArgumentException("Unknown key representation type."); } } /** * Calculates the verification code of the provided key at the specified * instant of time using the algorithm specified in RFC 6238. * * @param key the secret key in binary format. * @param tm the instant of time. * @return the validation code for the provided key at the specified instant * of time. */ private int calculateCode(byte[] key, long tm) { // Allocating an array of bytes to represent the specified instant // of time. byte[] data = new byte[8]; long value = tm; // Converting the instant of time from the long representation to a // big-endian array of bytes (RFC4226, 5.2. Description). for (int i = 8; i-- > 0; value >>>= 8) { data[i] = (byte) value; } // Building the secret key specification for the HmacSHA1 algorithm. SecretKeySpec signKey = new SecretKeySpec(key, HMAC_HASH_FUNCTION); try { // Getting an HmacSHA1 algorithm implementation from the JCE. Mac mac = Mac.getInstance(HMAC_HASH_FUNCTION); // Initializing the MAC algorithm. mac.init(signKey); // Processing the instant of time and getting the encrypted data. byte[] hash = mac.doFinal(data); // Building the validation code performing dynamic truncation // (RFC4226, 5.3. Generating an HOTP value) int offset = hash[hash.length - 1] & 0xF; // We are using a long because Java hasn't got an unsigned integer // type // and we need 32 unsigned bits). long truncatedHash = 0; for (int i = 0; i < 4; ++i) { truncatedHash <<= 8; // Java bytes are signed but we need an unsigned integer: // cleaning off all but the LSB. truncatedHash |= (hash[offset + i] & 0xFF); } // Clean bits higher than the 32nd (inclusive) and calculate the // module with the maximum validation code value. truncatedHash &= 0x7FFFFFFF; truncatedHash %= config.getKeyModulus(); // Returning the validation code to the caller. return (int) truncatedHash; } catch (NoSuchAlgorithmException | InvalidKeyException ex) { // We're not disclosing internal error details to our clients. throw new GoogleAuthenticatorException("The operation cannot be performed now.", ex); } } /** * This method implements the algorithm specified in RFC 6238 to check if a * validation code is valid in a given instant of time for the given secret * key. * * @param secret the Base32 encoded secret key. * @param code the code to validate. * @param timestamp the instant of time to use during the validation process. * @param window the window size to use during the validation process. * @return <code>true</code> if the validation code is valid, * <code>false</code> otherwise. */ private boolean checkCode(String secret, long code, long timestamp, int window) { // Decoding the secret key to get its raw byte representation. byte[] decodedKey = decodeKey(secret); // convert unix time into a 30 second "window" as specified by the // TOTP specification. Using Google's default interval of 30 seconds. final long timeWindow = timestamp / this.config.getTimeStepSizeInMillis(); // Calculating the verification code of the given key in each of the // time intervals and returning true if the provided code is equal to // one of them. for (int i = -((window - 1) / 2); i <= window / 2; ++i) { // Calculating the verification code for the current time interval. long hash = calculateCode(decodedKey, timeWindow + i); // Checking if the provided code is equal to the calculated one. if (hash == code) { // The verification code is valid. return true; } } // The verification code is invalid. return false; } public GoogleAuthenticatorKey createCredentials() { // Allocating a buffer sufficiently large to hold the bytes required by // the secret key and the scratch codes. byte[] buffer = new byte[SECRET_BITS / 8 + SCRATCH_CODES * BYTES_PER_SCRATCH_CODE]; secureRandom.nextBytes(buffer); // Extracting the bytes making up the secret key. byte[] secretKey = Arrays.copyOf(buffer, SECRET_BITS / 8); String generatedKey = calculateSecretKey(secretKey); // Generating the verification code at time = 0. int validationCode = calculateValidationCode(secretKey); // Calculate scratch codes List<Integer> scratchCodes = calculateScratchCodes(buffer); return new GoogleAuthenticatorKey(generatedKey, validationCode, scratchCodes); } private List<Integer> calculateScratchCodes(byte[] buffer) { List<Integer> scratchCodes = new ArrayList<>(); while (scratchCodes.size() < SCRATCH_CODES) { byte[] scratchCodeBuffer = Arrays.copyOfRange(buffer, SECRET_BITS / 8 + BYTES_PER_SCRATCH_CODE * scratchCodes.size(), SECRET_BITS / 8 + BYTES_PER_SCRATCH_CODE * scratchCodes.size() + BYTES_PER_SCRATCH_CODE); int scratchCode = calculateScratchCode(scratchCodeBuffer); if (scratchCode != SCRATCH_CODE_INVALID) { scratchCodes.add(scratchCode); } else { scratchCodes.add(generateScratchCode()); } } return scratchCodes; } /** * This method calculates a scratch code from a random byte buffer of * suitable size <code>#BYTES_PER_SCRATCH_CODE</code>. * * @param scratchCodeBuffer a random byte buffer whose minimum size is <code>#BYTES_PER_SCRATCH_CODE</code>. * @return the scratch code. */ private int calculateScratchCode(byte[] scratchCodeBuffer) { if (scratchCodeBuffer.length < BYTES_PER_SCRATCH_CODE) { throw new IllegalArgumentException(String.format("The provided random byte buffer is too small: %d.", scratchCodeBuffer.length)); } int scratchCode = 0; for (int i = 0; i < BYTES_PER_SCRATCH_CODE; ++i) { scratchCode = (scratchCode << 8) + (scratchCodeBuffer[i] & 0xff); } scratchCode = (scratchCode & 0x7FFFFFFF) % SCRATCH_CODE_MODULUS; // Accept the scratch code only if it has exactly // SCRATCH_CODE_LENGTH digits. if (scratchCode >= SCRATCH_CODE_MODULUS / 10) { return scratchCode; } else { return SCRATCH_CODE_INVALID; } } /** * This method creates a new random byte buffer from which a new scratch * code is generated. This function is invoked if a scratch code generated * from the main buffer is invalid because it does not satisfy the scratch * code restrictions. * * @return A valid scratch code. */ private int generateScratchCode() { while (true) { byte[] scratchCodeBuffer = new byte[BYTES_PER_SCRATCH_CODE]; secureRandom.nextBytes(scratchCodeBuffer); int scratchCode = calculateScratchCode(scratchCodeBuffer); if (scratchCode != SCRATCH_CODE_INVALID) { return scratchCode; } } } /** * This method calculates the validation code at time 0. * * @param secretKey The secret key to use. * @return the validation code at time 0. */ private int calculateValidationCode(byte[] secretKey) { return calculateCode(secretKey, 0); } /** * This method calculates the secret key given a random byte buffer. * * @param secretKey a random byte buffer. * @return the secret key. */ private String calculateSecretKey(byte[] secretKey) { switch (config.getKeyRepresentation()) { case BASE32: return new Base32().encodeToString(secretKey); case BASE64: return new Base64().encodeToString(secretKey); default: throw new IllegalArgumentException("Unknown key representation type."); } } public boolean authorize(String secret, int verificationCode) throws GoogleAuthenticatorException { return authorize(secret, verificationCode, new Date().getTime()); } private boolean authorize(String secret, int verificationCode, long time) throws GoogleAuthenticatorException { // Checking user input and failing if the secret key was not provided. if (secret == null) { throw new IllegalArgumentException("Secret cannot be null."); } // Checking if the verification code is between the legal bounds. if (verificationCode <= 0 || verificationCode >= this.config.getKeyModulus()) { return false; } // Checking the validation code using the current UNIX time. return checkCode(secret, verificationCode, time, this.config.getWindowSize()); } }
9230532fb1ea997180cccf12a7078feaf7d9c263
1,879
java
Java
2.3.1/source/CN-Framework-Pay-1400/src/main/java/org/zmsoft/pay/api/WeixinNoticeController.java
qq744788292/cnsoft
b9b921d43ea9b06c881121ab5d98ce18e14df87d
[ "BSD-3-Clause-Clear" ]
null
null
null
2.3.1/source/CN-Framework-Pay-1400/src/main/java/org/zmsoft/pay/api/WeixinNoticeController.java
qq744788292/cnsoft
b9b921d43ea9b06c881121ab5d98ce18e14df87d
[ "BSD-3-Clause-Clear" ]
null
null
null
2.3.1/source/CN-Framework-Pay-1400/src/main/java/org/zmsoft/pay/api/WeixinNoticeController.java
qq744788292/cnsoft
b9b921d43ea9b06c881121ab5d98ce18e14df87d
[ "BSD-3-Clause-Clear" ]
1
2022-03-16T01:57:07.000Z
2022-03-16T01:57:07.000Z
37.58
182
0.80628
995,437
package org.zmsoft.pay.api; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.zmsoft.framework.pay.ISOrderCheck; import org.zmsoft.framework.support.MyTokenCommonSupport; import org.zmsoft.pay.bean.WxPayCallBackBean; /** * 活动赛选页面接口 * * @version 0.1.1 * @since 0.1.1 */ @Controller @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class WeixinNoticeController extends MyTokenCommonSupport { // MyTokenCommonSupport @Resource private UserNoticeService userNoticeService; // 到账通知 @RequestMapping(value = "/api/1.0/pay/txnotice/{ordertoken}", method = { RequestMethod.GET, RequestMethod.POST }) public ModelAndView doTxChannelNotice(HttpServletRequest request, HttpServletResponse response, @PathVariable String ordertoken, WxPayCallBackBean weiXinCallBack) throws Exception { ModelAndView modelAndView = new ModelAndView("/pay/pay-result-wx"); // 通知结果 String orderCode = weiXinCallBack.getSdcustomno(); // 支付成功 if (ONE.equals(weiXinCallBack.getState()) && myWeixinOrderCheckService.doUserOrderCheck(weiXinCallBack)) {// 合法订单验证 userNoticeService.channelNoticeProcess(TWO, orderCode, orderCode); } else { logger.warn("doAliChannelNotice=====签名验证失败>>>>>" + weiXinCallBack); } modelAndView.addObject("respCode", "1"); return modelAndView; } @Resource(name="WeixinOrderCheckService") private ISOrderCheck myWeixinOrderCheckService; }
92305370200f467785f3aa6107397d72e2097368
237
java
Java
src/main/java/com/aryedri/spring/config/SecurityWebApplicationInitializer.java
aryedri/spring-payment-tracker
495245e1321b5c4fe998707f08e81290bc0c02a5
[ "MIT" ]
1
2021-05-19T19:23:56.000Z
2021-05-19T19:23:56.000Z
src/main/java/com/aryedri/spring/config/SecurityWebApplicationInitializer.java
aryedri/spring-payment-tracker
495245e1321b5c4fe998707f08e81290bc0c02a5
[ "MIT" ]
null
null
null
src/main/java/com/aryedri/spring/config/SecurityWebApplicationInitializer.java
aryedri/spring-payment-tracker
495245e1321b5c4fe998707f08e81290bc0c02a5
[ "MIT" ]
null
null
null
26.333333
90
0.860759
995,438
package com.aryedri.spring.config; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { }
9230537d3f25fa45eedfbb814429d66cf8d79381
3,871
java
Java
src/main/java/org/trustedanalytics/hadoop/config/client/CloudFoundryAppConfiguration.java
Bhanuprakash-ch/hadoop-utils
8108da1c031e1e797441c8cbc300bc7f7f55093a
[ "Apache-2.0" ]
5
2017-03-30T04:01:40.000Z
2019-06-24T12:04:32.000Z
src/main/java/org/trustedanalytics/hadoop/config/client/CloudFoundryAppConfiguration.java
Bhanuprakash-ch/hadoop-utils
8108da1c031e1e797441c8cbc300bc7f7f55093a
[ "Apache-2.0" ]
1
2016-01-05T09:16:22.000Z
2016-01-05T09:16:22.000Z
src/main/java/org/trustedanalytics/hadoop/config/client/CloudFoundryAppConfiguration.java
Bhanuprakash-ch/hadoop-utils
8108da1c031e1e797441c8cbc300bc7f7f55093a
[ "Apache-2.0" ]
10
2015-10-31T01:10:29.000Z
2020-01-22T18:09:11.000Z
38.71
107
0.672436
995,439
/** * Copyright (c) 2015 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.trustedanalytics.hadoop.config.client; import com.google.common.collect.Lists; import org.trustedanalytics.hadoop.config.internal.ConfigConstants; import org.trustedanalytics.hadoop.config.internal.ConfigNode; import org.trustedanalytics.hadoop.config.internal.ConfigPath; import java.util.List; import java.util.Optional; public final class CloudFoundryAppConfiguration implements AppConfiguration { private ConfigNode rootConfigNode; private CloudFoundryAppConfiguration() { } CloudFoundryAppConfiguration(ConfigNode node) { this.rootConfigNode = node; } /** * {@inheritDoc} */ @Override public ServiceInstanceConfiguration getServiceConfig(String serviceInstanceName) { Optional<ServiceInstanceConfiguration> found = Optional.empty(); // search configuration of all predefined types for(ServiceType serviceType : ServiceType.values()) { ConfigPath configPath = ConfigPath .createPath().append(serviceType.getConfPath()).add( configNode -> Lists.newArrayList(configNode .selectOne(ConfigConstants.INSTANCE_NAME_PROP_NAME, serviceInstanceName))); found = CloudFoundryServiceInstanceConfiguration.getConfiguration(this.rootConfigNode, configPath); if (found.isPresent()) { break; } } return found.orElseThrow(() -> new IllegalStateException("Not found configuration for service instance named " + serviceInstanceName + "!")); } /** * {@inheritDoc} */ @Override public ServiceInstanceConfiguration getServiceConfig(ServiceType serviceTypeLocation) throws IllegalStateException { ConfigPath configPath = ConfigPath.createPath().append(serviceTypeLocation.getConfPath()) .add(ConfigNode::getChildren); Optional<ServiceInstanceConfiguration> found = CloudFoundryServiceInstanceConfiguration.getConfiguration(this.rootConfigNode, configPath); return found.orElseThrow(() -> new IllegalStateException("Not found " + serviceTypeLocation + " service configuration!")); } /** * {@inheritDoc} */ @Override public List<ServiceInstanceConfiguration> getServiceConfigList(ServiceType serviceTypeLocation) { ConfigPath typeSection = ConfigPath.createPath().append(serviceTypeLocation.getConfPath()) .add(ConfigNode::getChildren); return CloudFoundryServiceInstanceConfiguration.getListConfiguration(this.rootConfigNode, typeSection); } /** * {@inheritDoc} */ @Override public Optional<ServiceInstanceConfiguration> getServiceConfigIfExists(ServiceType serviceTypeLocation) { ConfigPath configPath = ConfigPath.createPath().append(serviceTypeLocation.getConfPath()) .add(ConfigNode::getChildren); return CloudFoundryServiceInstanceConfiguration.getConfiguration(this.rootConfigNode, configPath); } }
923053b914ef7d863f9eeaa624e176d170c6b000
442
java
Java
2.JavaCore/2.Basics of OOP,overloading, polymorphism, abstraction, interfaces/task1208/Solution.java
MarekGrucka/Tutorials-CodeGym-
bf99c108d0366cc38b2da9aff2813a1a231ab58d
[ "Apache-2.0" ]
null
null
null
2.JavaCore/2.Basics of OOP,overloading, polymorphism, abstraction, interfaces/task1208/Solution.java
MarekGrucka/Tutorials-CodeGym-
bf99c108d0366cc38b2da9aff2813a1a231ab58d
[ "Apache-2.0" ]
null
null
null
2.JavaCore/2.Basics of OOP,overloading, polymorphism, abstraction, interfaces/task1208/Solution.java
MarekGrucka/Tutorials-CodeGym-
bf99c108d0366cc38b2da9aff2813a1a231ab58d
[ "Apache-2.0" ]
null
null
null
20.090909
54
0.644796
995,440
package com.codegym.task.task12.task1208; /* Freedom of the press */ public class Solution { public static void main(String[] args) { print(1); } public static void print(int x){} public static void print(int x, String y){} public static void print(int a, int b, String c){} public static void print(String a, int b){} public static void print(int a, String b, int c){} //write your code here }
92305418a7dc219b3aa227dd3556adc026dae27a
256
java
Java
api/src/main/java/no/autopacker/api/domain/KeycloakAdminClientConfig.java
AutoPacker-OSS/AutoPacker
af3987cecafd88f976b6b5c46d7424550ca0e1a9
[ "MIT" ]
9
2020-10-01T15:37:50.000Z
2021-02-03T20:51:01.000Z
api/src/main/java/no/autopacker/api/domain/KeycloakAdminClientConfig.java
AutoPacker-OSS/AutoPacker
af3987cecafd88f976b6b5c46d7424550ca0e1a9
[ "MIT" ]
52
2020-10-01T15:41:49.000Z
2021-02-03T20:47:23.000Z
api/src/main/java/no/autopacker/api/domain/KeycloakAdminClientConfig.java
AutoPacker-OSS/AutoPacker
af3987cecafd88f976b6b5c46d7424550ca0e1a9
[ "MIT" ]
2
2020-10-01T19:36:49.000Z
2020-10-22T16:40:14.000Z
17.066667
40
0.765625
995,441
package no.autopacker.api.domain; import lombok.Builder; import lombok.Data; @Data @Builder public class KeycloakAdminClientConfig { private String serverUrl; private String realm; private String clientId; private String clientSecret; }
92305419cb0bfa394152e9e199f4fce1c3a4c6ce
894
java
Java
gulimall-coupon/src/main/java/com/lsh/gulimall/coupon/entity/SpuBoundsEntity.java
star574/gulli-mall
457ef99561d7998953055a5c7cf8ff7e1458fb57
[ "Apache-2.0" ]
null
null
null
gulimall-coupon/src/main/java/com/lsh/gulimall/coupon/entity/SpuBoundsEntity.java
star574/gulli-mall
457ef99561d7998953055a5c7cf8ff7e1458fb57
[ "Apache-2.0" ]
null
null
null
gulimall-coupon/src/main/java/com/lsh/gulimall/coupon/entity/SpuBoundsEntity.java
star574/gulli-mall
457ef99561d7998953055a5c7cf8ff7e1458fb57
[ "Apache-2.0" ]
null
null
null
19.042553
111
0.710615
995,442
package com.lsh.gulimall.coupon.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.math.BigDecimal; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * 商品spu积分设置 * * @author codestar * @email kenaa@example.com * @date 2021-06-01 00:30:32 */ @Data @TableName("sms_spu_bounds") public class SpuBoundsEntity implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @TableId(type = IdType.AUTO) private Long id; /** * */ private Long spuId; /** * 成长积分 */ private BigDecimal growBounds; /** * 购物积分 */ private BigDecimal buyBounds; /** * 优惠生效情况[1111(四个状态位,从右到左);0 - 无优惠,成长积分是否赠送;1 - 无优惠,购物积分是否赠送;2 - 有优惠,成长积分是否赠送;3 - 有优惠,购物积分是否赠送【状态位0:不赠送,1:赠送】] */ private Integer work; }
923054961282c4279ac9951aee9ab87cb2fe039c
6,653
java
Java
src/test/java/org/tests/model/elementcollection/TestElementCollectionEmbeddedList.java
mrmx/ebean
88429c6a7e4b5257787200693a2dd186233e6930
[ "Apache-2.0" ]
1
2017-02-28T17:32:39.000Z
2017-02-28T17:32:39.000Z
src/test/java/org/tests/model/elementcollection/TestElementCollectionEmbeddedList.java
mrmx/ebean
88429c6a7e4b5257787200693a2dd186233e6930
[ "Apache-2.0" ]
11
2017-11-07T18:32:56.000Z
2022-03-08T16:39:45.000Z
src/test/java/org/tests/model/elementcollection/TestElementCollectionEmbeddedList.java
mrmx/ebean
88429c6a7e4b5257787200693a2dd186233e6930
[ "Apache-2.0" ]
null
null
null
37.587571
169
0.69292
995,443
package org.tests.model.elementcollection; import io.ebean.BaseTestCase; import io.ebean.Ebean; import org.ebeantest.LoggedSqlCollector; import org.junit.Test; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class TestElementCollectionEmbeddedList extends BaseTestCase { @Test public void test() { LoggedSqlCollector.start(); EcblPerson person = new EcblPerson("Fiona64021"); person.getPhoneNumbers().add(new EcPhone("64", "021","1234")); person.getPhoneNumbers().add(new EcPhone("64","021","4321")); Ebean.save(person); List<String> sql = LoggedSqlCollector.current(); if (isPersistBatchOnCascade()) { assertThat(sql).hasSize(4); assertThat(sql.get(0)).contains("insert into ecbl_person"); assertThat(sql.get(1)).contains("insert into ecbl_person_phone_numbers"); assertSqlBind(sql, 2, 3); } else { assertThat(sql).hasSize(3); assertThat(sql.get(0)).contains("insert into ecbl_person"); assertThat(sql.get(1)).contains("insert into ecbl_person_phone_numbers"); assertThat(sql.get(2)).contains("insert into ecbl_person_phone_numbers"); } EcblPerson person1 = new EcblPerson("Fiona6409"); person1.getPhoneNumbers().add(new EcPhone("61","09","1234")); person1.getPhoneNumbers().add(new EcPhone("64","09","4321")); Ebean.save(person1); LoggedSqlCollector.current(); List<EcblPerson> found = Ebean.find(EcblPerson.class).where() .startsWith("name", "Fiona640") .order().asc("id") .findList(); List<EcPhone> phoneNumbers0 = found.get(0).getPhoneNumbers(); List<EcPhone> phoneNumbers1 = found.get(1).getPhoneNumbers(); phoneNumbers0.size(); assertThat(phoneNumbers0.toString()).contains("64-021-1234", "64-021-4321"); assertThat(phoneNumbers1.toString()).contains("61-09-1234", "64-09-4321"); sql = LoggedSqlCollector.current(); assertThat(sql).hasSize(2); assertThat(trimSql(sql.get(0))).contains("select t0.id, t0.name, t0.version from ecbl_person"); assertThat(trimSql(sql.get(1))).contains("select t0.person_id, t0.country_code, t0.area, t0.number from ecbl_person_phone_numbers"); List<EcblPerson> found2 = Ebean.find(EcblPerson.class) .fetch("phoneNumbers") .where() .startsWith("name", "Fiona640") .order().asc("id") .findList(); assertThat(found2).hasSize(2); sql = LoggedSqlCollector.current(); assertThat(sql).hasSize(1); String trimmedSql = trimSql(sql.get(0)); assertThat(trimmedSql).contains("select t0.id, t0.name, t0.version, t1.country_code, t1.area, t1.number from ecbl_person t0 left join ecbl_person_phone_numbers t1"); EcblPerson foundFirst = found2.get(0); jsonToFrom(foundFirst); updateBasic(foundFirst); LoggedSqlCollector.stop(); } private void updateBasic(EcblPerson bean) { bean.setName("Fiona64-mod-0"); Ebean.save(bean); List<String> sql = LoggedSqlCollector.current(); assertThat(sql).hasSize(1); assertThat(sql.get(0)).contains("update ecbl_person"); updateBoth(bean); } private void updateBoth(EcblPerson bean) { bean.setName("Fiona64-mod-both"); bean.getPhoneNumbers().add(new EcPhone("01", "234", "123")); Ebean.save(bean); List<String> sql = LoggedSqlCollector.current(); if (isPersistBatchOnCascade()) { assertThat(sql).hasSize(6); assertThat(sql.get(0)).contains("update ecbl_person set name=?, version=? where id=? and version=?"); assertThat(sql.get(1)).contains("delete from ecbl_person_phone_numbers where person_id=?"); assertThat(sql.get(2)).contains("insert into ecbl_person_phone_numbers (person_id,country_code,area,number) values (?,?,?,?)"); assertSqlBind(sql, 3, 5); } else { assertThat(sql).hasSize(5); assertThat(sql.get(0)).contains("update ecbl_person set name=?, version=? where id=? and version=?"); assertThat(sql.get(1)).contains("delete from ecbl_person_phone_numbers where person_id=?"); assertThat(sql.get(2)).contains("insert into ecbl_person_phone_numbers (person_id,country_code,area,number) values (?,?,?,?)"); assertThat(sql.get(3)).contains("insert into ecbl_person_phone_numbers (person_id,country_code,area,number) values (?,?,?,?)"); assertThat(sql.get(4)).contains("insert into ecbl_person_phone_numbers (person_id,country_code,area,number) values (?,?,?,?)"); } updateNothing(bean); } private void updateNothing(EcblPerson bean) { Ebean.save(bean); List<String> sql = LoggedSqlCollector.current(); assertThat(sql).hasSize(0); updateOnlyCollection(bean); } private void updateOnlyCollection(EcblPerson bean) { bean.getPhoneNumbers().add(new EcPhone("01", "12", "4321")); Ebean.save(bean); List<String> sql = LoggedSqlCollector.current(); if (isPersistBatchOnCascade()) { assertThat(sql).hasSize(6); assertThat(sql.get(0)).contains("delete from ecbl_person_phone_numbers where person_id=?"); assertThat(sql.get(1)).contains("insert into ecbl_person_phone_numbers (person_id,country_code,area,number) values (?,?,?,?)"); assertSqlBind(sql, 2, 5); } else { assertThat(sql).hasSize(5); assertThat(sql.get(0)).contains("delete from ecbl_person_phone_numbers where person_id=?"); assertThat(sql.get(1)).contains("insert into ecbl_person_phone_numbers (person_id,country_code,area,number) values (?,?,?,?)"); assertThat(sql.get(2)).contains("insert into ecbl_person_phone_numbers (person_id,country_code,area,number) values (?,?,?,?)"); assertThat(sql.get(3)).contains("insert into ecbl_person_phone_numbers (person_id,country_code,area,number) values (?,?,?,?)"); assertThat(sql.get(4)).contains("insert into ecbl_person_phone_numbers (person_id,country_code,area,number) values (?,?,?,?)"); } delete(bean); } private void delete(EcblPerson bean) { Ebean.delete(bean); List<String> sql = LoggedSqlCollector.current(); assertThat(sql).hasSize(2); assertThat(sql.get(0)).contains("delete from ecbl_person_phone_numbers where person_id = ?"); assertThat(sql.get(1)).contains("delete from ecbl_person where id=? and version=?"); } private void jsonToFrom(EcblPerson foundFirst) { String asJson = Ebean.json().toJson(foundFirst); EcblPerson fromJson = Ebean.json().toBean(EcblPerson.class, asJson); String phoneString = fromJson.getPhoneNumbers().toString(); assertThat(phoneString).contains("64-021-1234"); assertThat(phoneString).contains("64-021-4321"); } }
92305697e2afc16d196958b30ec7ff8dd06c8a52
335
java
Java
seekers/src/test/java/com/tasd/seekers/SeekersApplicationTests.java
CostantiniMatteo/progetto-tasd
061e89e96990512c9e02d1682a26bef615aed14b
[ "MIT" ]
1
2020-10-29T19:28:30.000Z
2020-10-29T19:28:30.000Z
seekers/src/test/java/com/tasd/seekers/SeekersApplicationTests.java
CostantiniMatteo/progetto-tasd
061e89e96990512c9e02d1682a26bef615aed14b
[ "MIT" ]
null
null
null
seekers/src/test/java/com/tasd/seekers/SeekersApplicationTests.java
CostantiniMatteo/progetto-tasd
061e89e96990512c9e02d1682a26bef615aed14b
[ "MIT" ]
null
null
null
18.611111
60
0.80597
995,444
package com.tasd.seekers; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SeekersApplicationTests { @Test public void contextLoads() { } }
9230570ef3702ef973c3c0e5a1b64fb14e43041c
6,995
java
Java
information_models/src/main/java/it/nextworks/tmf_offering_catalog/information_models/common/PlaceRef.java
5GZORRO/resource-and-service-offer-catalog
87eba131867099dae4c412f3aead8ff7d0e25f48
[ "Apache-2.0" ]
null
null
null
information_models/src/main/java/it/nextworks/tmf_offering_catalog/information_models/common/PlaceRef.java
5GZORRO/resource-and-service-offer-catalog
87eba131867099dae4c412f3aead8ff7d0e25f48
[ "Apache-2.0" ]
null
null
null
information_models/src/main/java/it/nextworks/tmf_offering_catalog/information_models/common/PlaceRef.java
5GZORRO/resource-and-service-offer-catalog
87eba131867099dae4c412f3aead8ff7d0e25f48
[ "Apache-2.0" ]
null
null
null
23.631757
116
0.665904
995,445
package it.nextworks.tmf_offering_catalog.information_models.common; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.hibernate.annotations.GenericGenerator; import org.springframework.validation.annotation.Validated; import javax.persistence.*; import javax.validation.constraints.*; /** * Place reference. PlaceRef defines the placeRefs where the products are sold or delivered. */ @ApiModel(description = "Place reference. PlaceRef defines the placeRefs where the products are sold or delivered.") @Validated @javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2021-02-09T15:56:41.618Z") @Entity @Table(name = "place_refs") public class PlaceRef { @JsonProperty("@baseType") @Column(name = "base_type") private String baseType = null; @JsonProperty("@referredType") @Column(name = "referred_type") private String referredType = null; @JsonProperty("@schemaLocation") @Column(name = "schema_location") private String schemaLocation = null; @JsonProperty("@type") private String type = null; @JsonProperty("href") private String href = null; @JsonProperty("id") private String id = null; @JsonProperty("name") private String name = null; @JsonProperty("role") private String role = null; @JsonIgnore @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") private String uuid = null; public PlaceRef baseType(String baseType) { this.baseType = baseType; return this; } /** * When sub-classing, this defines the super-class * @return baseType **/ @ApiModelProperty(value = "When sub-classing, this defines the super-class") public String getBaseType() { return baseType; } public void setBaseType(String baseType) { this.baseType = baseType; } public PlaceRef referredType(String referredType) { this.referredType = referredType; return this; } /** * The actual type of the target instance when needed for disambiguation. * @return referredType **/ @ApiModelProperty(value = "The actual type of the target instance when needed for disambiguation.") public String getReferredType() { return referredType; } public void setReferredType(String referredType) { this.referredType = referredType; } public PlaceRef schemaLocation(String schemaLocation) { this.schemaLocation = schemaLocation; return this; } /** * A URI to a JSON-Schema file that defines additional attributes and relationships * @return schemaLocation **/ @ApiModelProperty(value = "A URI to a JSON-Schema file that defines additional attributes and relationships") public String getSchemaLocation() { return schemaLocation; } public void setSchemaLocation(String schemaLocation) { this.schemaLocation = schemaLocation; } public PlaceRef type(String type) { this.type = type; return this; } /** * Get type * @return type **/ @ApiModelProperty(value = "") public String getType() { return type; } public void setType(String type) { this.type = type; } public PlaceRef href(String href) { this.href = href; return this; } /** * Unique reference of the entity * @return href **/ @ApiModelProperty(value = "Unique reference of the entity") public String getHref() { return href; } public void setHref(String href) { this.href = href; } public PlaceRef id(String id) { this.id = id; return this; } /** * Unique identifier of a related entity. * @return id **/ @ApiModelProperty(required = true, value = "Unique identifier of a related entity.") @NotNull public String getId() { return id; } public void setId(String id) { this.id = id; } public PlaceRef name(String name) { this.name = name; return this; } /** * Name of the entity * @return name **/ @ApiModelProperty(value = "Name of the entity") public String getName() { return name; } public void setName(String name) { this.name = name; } public PlaceRef role(String role) { this.role = role; return this; } /** * Role of the place (for instance: 'home delivery', 'shop retrieval') * @return role **/ @ApiModelProperty(value = "Role of the place (for instance: 'home delivery', 'shop retrieval')") public String getRole() { return role; } public void setRole(String role) { this.role = role; } public PlaceRef uuid(String uuid) { this.uuid = uuid; return this; } /** * Get uuid * @return uuid **/ @ApiModelProperty(value = "") public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PlaceRef placeRef = (PlaceRef) o; return Objects.equals(this.baseType, placeRef.baseType) && Objects.equals(this.referredType, placeRef.referredType) && Objects.equals(this.schemaLocation, placeRef.schemaLocation) && Objects.equals(this.type, placeRef.type) && Objects.equals(this.href, placeRef.href) && Objects.equals(this.id, placeRef.id) && Objects.equals(this.name, placeRef.name) && Objects.equals(this.role, placeRef.role) && Objects.equals(this.uuid, placeRef.uuid); } @Override public int hashCode() { return Objects.hash(baseType, referredType, schemaLocation, type, href, id, name, role, uuid); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PlaceRef {\n"); sb.append(" baseType: ").append(toIndentedString(baseType)).append("\n"); sb.append(" referredType: ").append(toIndentedString(referredType)).append("\n"); sb.append(" schemaLocation: ").append(toIndentedString(schemaLocation)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" href: ").append(toIndentedString(href)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" role: ").append(toIndentedString(role)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
92305724305a290ba3922065389e8462795064e0
1,163
java
Java
solr/core/src/test/org/apache/solr/cloud/RecoveryZkTest.java
girishjammu/solr
df84356a816442c6b2a7b578cb193f22b418cdae
[ "Apache-2.0" ]
1
2022-03-09T23:03:11.000Z
2022-03-09T23:03:11.000Z
solr/core/src/test/org/apache/solr/cloud/RecoveryZkTest.java
daeltonpinheiro/solr
f07b7b0c75ec818c787db07492c71e2064ccdc86
[ "Apache-2.0" ]
null
null
null
solr/core/src/test/org/apache/solr/cloud/RecoveryZkTest.java
daeltonpinheiro/solr
f07b7b0c75ec818c787db07492c71e2064ccdc86
[ "Apache-2.0" ]
null
null
null
34.205882
90
0.756664
995,446
/* * 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.solr.cloud; import org.apache.lucene.util.LuceneTestCase.Slow; import org.junit.Test; /* * Implementation moved to AbstractRecoveryZkTestBase as it is used by HDFS contrib tests. */ @Slow public class RecoveryZkTest extends AbstractRecoveryZkTestBase { @Test @Override public void test() throws Exception { super.test(); } }
92305736fcd8c315f56e342dc1ea42f18864a2cd
3,562
java
Java
client/src/main/java/engine/client/sound/ALSoundSource.java
UnknownStudio/KnownDomain
e5fa7dca74f1252ee1563db8e962502bdafbf068
[ "Apache-2.0" ]
59
2020-08-05T02:22:39.000Z
2022-03-13T12:45:42.000Z
client/src/main/java/engine/client/sound/ALSoundSource.java
UnknownStudio/KnownDomain
e5fa7dca74f1252ee1563db8e962502bdafbf068
[ "Apache-2.0" ]
37
2019-05-14T04:42:50.000Z
2020-01-07T12:48:56.000Z
client/src/main/java/engine/client/sound/ALSoundSource.java
UnknownStudio/KnownDomain
e5fa7dca74f1252ee1563db8e962502bdafbf068
[ "Apache-2.0" ]
16
2019-05-26T07:22:35.000Z
2019-12-16T05:00:23.000Z
23.746667
77
0.581976
995,447
package engine.client.sound; import org.joml.Vector3f; import org.joml.Vector3fc; import org.lwjgl.system.MemoryStack; import java.nio.FloatBuffer; import static org.lwjgl.openal.AL10.*; import static org.lwjgl.system.MemoryStack.stackPush; public final class ALSoundSource implements SoundSource { private int id = 0; private boolean loop; private boolean relative; public ALSoundSource(boolean loop, boolean relative) { this.loop = loop; this.relative = relative; } @Override public void createSource() { if (id == 0) { id = alGenSources(); alSourcei(id, AL_LOOPING, loop ? AL_TRUE : AL_FALSE); alSourcei(id, AL_SOURCE_RELATIVE, relative ? AL_TRUE : AL_FALSE); } } @Override public void assign(Sound sound) { stop(); alSourcei(id, AL_BUFFER, ((ALSound) sound).getId()); } @Override public void stop() { alSourceStop(id); } @Override public void pause() { alSourcePause(id); } @Override public void play() { alSourcePlay(id); } @Override public boolean isPlaying() { return alGetSourcei(id, AL_SOURCE_STATE) == AL_PLAYING; } @Override public boolean isPaused() { return alGetSourcei(id, AL_SOURCE_STATE) == AL_PAUSED; } @Override public boolean isStopped() { return alGetSourcei(id, AL_SOURCE_STATE) == AL_STOPPED; } public int getId() { return id; } @Override public SoundSource position(float x, float y, float z) { alSource3f(id, AL_POSITION, x, y, z); return this; } @Override public Vector3fc getPosition() { try (MemoryStack stack = stackPush()) { FloatBuffer x = stack.callocFloat(1); FloatBuffer y = stack.callocFloat(1); FloatBuffer z = stack.callocFloat(1); alGetSource3f(id, AL_POSITION, x, y, z); return new Vector3f(x.get(), y.get(), z.get()); } } @Override public SoundSource position(Vector3fc pos) { return position(pos.x(), pos.y(), pos.z()); } @Override public SoundSource speed(float x, float y, float z) { alSource3f(id, AL_VELOCITY, x, y, z); return this; } @Override public SoundSource speed(Vector3fc speed) { return speed(speed.x(), speed.y(), speed.z()); } @Override public Vector3fc getSpeed() { try (MemoryStack stack = stackPush()) { FloatBuffer x = stack.callocFloat(1); FloatBuffer y = stack.callocFloat(1); FloatBuffer z = stack.callocFloat(1); alGetSource3f(id, AL_VELOCITY, x, y, z); return new Vector3f(x.get(), y.get(), z.get()); } } @Override public SoundSource gain(float gain) { alSourcef(id, AL_GAIN, gain); return this; } @Override public SoundSource setLoop(boolean flag) { loop = flag; alSourcei(id, AL_LOOPING, loop ? AL_TRUE : AL_FALSE); return this; } @Override public SoundSource setRelative(boolean relative) { this.relative = relative; alSourcei(id, AL_SOURCE_RELATIVE, relative ? AL_TRUE : AL_FALSE); return this; } @Override public void dispose() { if (id != 0) { stop(); alDeleteSources(id); id = 0; } } @Override public boolean isDisposed() { return id == 0; } }
923059f4f105c761779b2c1baa8ce95546599b2a
126
java
Java
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/topLevel/extensionWithCustomFileName/JavaClass.java
06needhamt/intellij-community
63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b
[ "Apache-2.0" ]
null
null
null
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/topLevel/extensionWithCustomFileName/JavaClass.java
06needhamt/intellij-community
63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b
[ "Apache-2.0" ]
null
null
null
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/topLevel/extensionWithCustomFileName/JavaClass.java
06needhamt/intellij-community
63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b
[ "Apache-2.0" ]
null
null
null
21
47
0.674603
995,448
public class JavaClass { public static void main(String[] args) { CustomKotlinName.topLevelExtension(42); } }