id
int64
22
34.9k
original_code
stringlengths
31
107k
code_wo_comment
stringlengths
29
77.3k
cleancode
stringlengths
25
62.1k
repo
stringlengths
6
65
label
sequencelengths
4
4
25,273
@Override public IASTTranslationUnit getTranslationUnit(IFile fileToParse) throws UnsupportedDialectException { //TODO - At this time, we purely delegate blindly //In the future, we may need to delegate based upon context provided return defaultService.getTranslationUnit(fileToParse); }
@Override public IASTTranslationUnit getTranslationUnit(IFile fileToParse) throws UnsupportedDialectException { return defaultService.getTranslationUnit(fileToParse); }
@override public iasttranslationunit gettranslationunit(ifile filetoparse) throws unsupporteddialectexception { return defaultservice.gettranslationunit(filetoparse); }
seemoo-lab/polypyus_pdom
[ 0, 1, 0, 0 ]
25,274
@Override public IASTTranslationUnit getTranslationUnit(IFile fileToParse, ICodeReaderFactory fileCreator) throws UnsupportedDialectException { //TODO - At this time, we purely delegate blindly //In the future, we may need to delegate based upon context provided return defaultService.getTranslationUnit(fileToParse, fileCreator ); }
@Override public IASTTranslationUnit getTranslationUnit(IFile fileToParse, ICodeReaderFactory fileCreator) throws UnsupportedDialectException { return defaultService.getTranslationUnit(fileToParse, fileCreator ); }
@override public iasttranslationunit gettranslationunit(ifile filetoparse, icodereaderfactory filecreator) throws unsupporteddialectexception { return defaultservice.gettranslationunit(filetoparse, filecreator ); }
seemoo-lab/polypyus_pdom
[ 0, 1, 0, 0 ]
25,275
@Override public IASTTranslationUnit getTranslationUnit(IFile fileToParse, ICodeReaderFactory fileCreator, IParserConfiguration configuration) throws UnsupportedDialectException { //TODO - At this time, we purely delegate blindly //In the future, we may need to delegate based upon context provided return defaultService.getTranslationUnit(fileToParse, fileCreator, configuration ); }
@Override public IASTTranslationUnit getTranslationUnit(IFile fileToParse, ICodeReaderFactory fileCreator, IParserConfiguration configuration) throws UnsupportedDialectException { return defaultService.getTranslationUnit(fileToParse, fileCreator, configuration ); }
@override public iasttranslationunit gettranslationunit(ifile filetoparse, icodereaderfactory filecreator, iparserconfiguration configuration) throws unsupporteddialectexception { return defaultservice.gettranslationunit(filetoparse, filecreator, configuration ); }
seemoo-lab/polypyus_pdom
[ 0, 1, 0, 0 ]
25,276
@Override public IASTCompletionNode getCompletionNode(IFile fileToParse, int offset, ICodeReaderFactory fileCreator) throws UnsupportedDialectException { //TODO - At this time, we purely delegate blindly //In the future, we may need to delegate based upon context provided return defaultService.getCompletionNode(fileToParse, offset, fileCreator); }
@Override public IASTCompletionNode getCompletionNode(IFile fileToParse, int offset, ICodeReaderFactory fileCreator) throws UnsupportedDialectException { return defaultService.getCompletionNode(fileToParse, offset, fileCreator); }
@override public iastcompletionnode getcompletionnode(ifile filetoparse, int offset, icodereaderfactory filecreator) throws unsupporteddialectexception { return defaultservice.getcompletionnode(filetoparse, offset, filecreator); }
seemoo-lab/polypyus_pdom
[ 0, 1, 0, 0 ]
25,277
@Override public IASTCompletionNode getCompletionNode(IStorage fileToParse, IProject project, int offset, ICodeReaderFactory fileCreator) throws UnsupportedDialectException { //TODO - At this time, we purely delegate blindly //In the future, we may need to delegate based upon context provided return defaultService.getCompletionNode(fileToParse, project, offset, fileCreator); }
@Override public IASTCompletionNode getCompletionNode(IStorage fileToParse, IProject project, int offset, ICodeReaderFactory fileCreator) throws UnsupportedDialectException { return defaultService.getCompletionNode(fileToParse, project, offset, fileCreator); }
@override public iastcompletionnode getcompletionnode(istorage filetoparse, iproject project, int offset, icodereaderfactory filecreator) throws unsupporteddialectexception { return defaultservice.getcompletionnode(filetoparse, project, offset, filecreator); }
seemoo-lab/polypyus_pdom
[ 0, 1, 0, 0 ]
17,091
@Override public List<SpawnResult> writeOutputToFile( AbstractAction action, ActionExecutionContext actionExecutionContext, DeterministicWriter deterministicWriter, boolean makeExecutable, boolean isRemotable) throws ExecException { Path outputPath = actionExecutionContext.getInputPath(Iterables.getOnlyElement(action.getOutputs())); // TODO(ulfjack): Consider acquiring local resources here before trying to write the file. try (AutoProfiler p = AutoProfiler.logged( "running write for action " + action.prettyPrint(), logger, /*minTimeForLoggingInMilliseconds=*/ 100)) { try { try (OutputStream out = new BufferedOutputStream(outputPath.getOutputStream())) { deterministicWriter.writeOutputFile(out); } if (makeExecutable) { outputPath.setExecutable(true); } } catch (IOException e) { throw new EnvironmentalExecException("IOException during file write", e); } } return ImmutableList.of(); }
@Override public List<SpawnResult> writeOutputToFile( AbstractAction action, ActionExecutionContext actionExecutionContext, DeterministicWriter deterministicWriter, boolean makeExecutable, boolean isRemotable) throws ExecException { Path outputPath = actionExecutionContext.getInputPath(Iterables.getOnlyElement(action.getOutputs())); try (AutoProfiler p = AutoProfiler.logged( "running write for action " + action.prettyPrint(), logger, 100)) { try { try (OutputStream out = new BufferedOutputStream(outputPath.getOutputStream())) { deterministicWriter.writeOutputFile(out); } if (makeExecutable) { outputPath.setExecutable(true); } } catch (IOException e) { throw new EnvironmentalExecException("IOException during file write", e); } } return ImmutableList.of(); }
@override public list<spawnresult> writeoutputtofile( abstractaction action, actionexecutioncontext actionexecutioncontext, deterministicwriter deterministicwriter, boolean makeexecutable, boolean isremotable) throws execexception { path outputpath = actionexecutioncontext.getinputpath(iterables.getonlyelement(action.getoutputs())); try (autoprofiler p = autoprofiler.logged( "running write for action " + action.prettyprint(), logger, 100)) { try { try (outputstream out = new bufferedoutputstream(outputpath.getoutputstream())) { deterministicwriter.writeoutputfile(out); } if (makeexecutable) { outputpath.setexecutable(true); } } catch (ioexception e) { throw new environmentalexecexception("ioexception during file write", e); } } return immutablelist.of(); }
sevki/bazel
[ 0, 1, 0, 0 ]
733
public static void stopTimerQueue() { singleton.stop(); singleton.queue = new PriorityQueue(); }
public static void stopTimerQueue() { singleton.stop(); singleton.queue = new PriorityQueue(); }
public static void stoptimerqueue() { singleton.stop(); singleton.queue = new priorityqueue(); }
rondinelisaad/lockss-daemon
[ 0, 0, 1, 0 ]
25,316
@Deprecated // caused issues https://github.com/holgerbrandl/r4intellij/issues/79 private static ArrayList<String> getInstallationFromPaths(@NotNull final String scriptName, @NotNull final String[] paths) { final ArrayList<String> result = new ArrayList<String>(); for (String path : paths) { // does not work in tests final VirtualFile rootVDir = LocalFileSystem.getInstance().findFileByPath(path); if (rootVDir != null) { // final VirtualFile rScript = rootVDir.findFileByRelativePath("bin/" + scriptName); final File rScript = findScript(scriptName, path); if (rScript != null) { result.add(FileUtil.toSystemDependentName(rScript.getPath())); } } } return result; }
@Deprecated private static ArrayList<String> getInstallationFromPaths(@NotNull final String scriptName, @NotNull final String[] paths) { final ArrayList<String> result = new ArrayList<String>(); for (String path : paths) { final VirtualFile rootVDir = LocalFileSystem.getInstance().findFileByPath(path); if (rootVDir != null) { final File rScript = findScript(scriptName, path); if (rScript != null) { result.add(FileUtil.toSystemDependentName(rScript.getPath())); } } } return result; }
@deprecated private static arraylist<string> getinstallationfrompaths(@notnull final string scriptname, @notnull final string[] paths) { final arraylist<string> result = new arraylist<string>(); for (string path : paths) { final virtualfile rootvdir = localfilesystem.getinstance().findfilebypath(path); if (rootvdir != null) { final file rscript = findscript(scriptname, path); if (rscript != null) { result.add(fileutil.tosystemdependentname(rscript.getpath())); } } } return result; }
rillig/r4intellij
[ 0, 0, 1, 0 ]
784
@Test @Ignore //Fix or deprecate fromExecutor, this test might randomly hang on CI public void rejectedExecutionExceptionOnErrorSignalExecutor() throws InterruptedException { Exception exception = new IllegalStateException(); final AtomicReference<Throwable> throwableInOnOperatorError = new AtomicReference<>(); final AtomicReference<Object> dataInOnOperatorError = new AtomicReference<>(); try { CountDownLatch hookLatch = new CountDownLatch(2); Hooks.onOperatorError((t, d) -> { throwableInOnOperatorError.set(t); dataInOnOperatorError.set(d); hookLatch.countDown(); return t; }); ExecutorService executor = newCachedThreadPool(); CountDownLatch latch = new CountDownLatch(1); AssertSubscriber<Integer> assertSubscriber = new AssertSubscriber<>(); Flux.range(0, 5) .publishOn(fromExecutorService(executor)) .doOnNext(s -> { try { latch.await(); } catch (InterruptedException e) { throw Exceptions.propagate(exception); } }) .publishOn(fromExecutor(executor)) .subscribe(assertSubscriber); executor.shutdownNow(); assertSubscriber.assertNoValues() .assertNoError() .assertNotComplete(); hookLatch.await(); assertThat(throwableInOnOperatorError.get()).isInstanceOf(RejectedExecutionException.class); assertThat(throwableInOnOperatorError.get().getSuppressed()[0]).isSameAs(exception); } finally { Hooks.resetOnOperatorError(); } }
@Test @Ignore public void rejectedExecutionExceptionOnErrorSignalExecutor() throws InterruptedException { Exception exception = new IllegalStateException(); final AtomicReference<Throwable> throwableInOnOperatorError = new AtomicReference<>(); final AtomicReference<Object> dataInOnOperatorError = new AtomicReference<>(); try { CountDownLatch hookLatch = new CountDownLatch(2); Hooks.onOperatorError((t, d) -> { throwableInOnOperatorError.set(t); dataInOnOperatorError.set(d); hookLatch.countDown(); return t; }); ExecutorService executor = newCachedThreadPool(); CountDownLatch latch = new CountDownLatch(1); AssertSubscriber<Integer> assertSubscriber = new AssertSubscriber<>(); Flux.range(0, 5) .publishOn(fromExecutorService(executor)) .doOnNext(s -> { try { latch.await(); } catch (InterruptedException e) { throw Exceptions.propagate(exception); } }) .publishOn(fromExecutor(executor)) .subscribe(assertSubscriber); executor.shutdownNow(); assertSubscriber.assertNoValues() .assertNoError() .assertNotComplete(); hookLatch.await(); assertThat(throwableInOnOperatorError.get()).isInstanceOf(RejectedExecutionException.class); assertThat(throwableInOnOperatorError.get().getSuppressed()[0]).isSameAs(exception); } finally { Hooks.resetOnOperatorError(); } }
@test @ignore public void rejectedexecutionexceptiononerrorsignalexecutor() throws interruptedexception { exception exception = new illegalstateexception(); final atomicreference<throwable> throwableinonoperatorerror = new atomicreference<>(); final atomicreference<object> datainonoperatorerror = new atomicreference<>(); try { countdownlatch hooklatch = new countdownlatch(2); hooks.onoperatorerror((t, d) -> { throwableinonoperatorerror.set(t); datainonoperatorerror.set(d); hooklatch.countdown(); return t; }); executorservice executor = newcachedthreadpool(); countdownlatch latch = new countdownlatch(1); assertsubscriber<integer> assertsubscriber = new assertsubscriber<>(); flux.range(0, 5) .publishon(fromexecutorservice(executor)) .doonnext(s -> { try { latch.await(); } catch (interruptedexception e) { throw exceptions.propagate(exception); } }) .publishon(fromexecutor(executor)) .subscribe(assertsubscriber); executor.shutdownnow(); assertsubscriber.assertnovalues() .assertnoerror() .assertnotcomplete(); hooklatch.await(); assertthat(throwableinonoperatorerror.get()).isinstanceof(rejectedexecutionexception.class); assertthat(throwableinonoperatorerror.get().getsuppressed()[0]).issameas(exception); } finally { hooks.resetonoperatorerror(); } }
steppedreckoner/reactor-core
[ 0, 0, 0, 1 ]
25,367
void stopSolver() { if (solverFuture != null) { // TODO what happens if solver hasn't started yet (solve() is called asynchronously) solver.terminateEarly(); // make sure solver has terminated and propagate exceptions try { solverFuture.get(); solverFuture = null; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("Failed to stop solver", e); } catch (ExecutionException e) { throw new RuntimeException("Failed to stop solver", e); } } }
void stopSolver() { if (solverFuture != null) { solver.terminateEarly(); try { solverFuture.get(); solverFuture = null; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("Failed to stop solver", e); } catch (ExecutionException e) { throw new RuntimeException("Failed to stop solver", e); } } }
void stopsolver() { if (solverfuture != null) { solver.terminateearly(); try { solverfuture.get(); solverfuture = null; } catch (interruptedexception e) { thread.currentthread().interrupt(); throw new runtimeexception("failed to stop solver", e); } catch (executionexception e) { throw new runtimeexception("failed to stop solver", e); } } }
rsynek-bot-account/optaweb-vehicle-routing
[ 1, 0, 0, 0 ]
813
@Override public boolean asyncCheckpoint(long fileId) throws AlluxioTException { return false; }
@Override public boolean asyncCheckpoint(long fileId) throws AlluxioTException { return false; }
@override public boolean asynccheckpoint(long fileid) throws alluxiotexception { return false; }
shaneknapp/tachyon
[ 1, 0, 0, 0 ]
825
private Instance marshall(ServiceInstance serviceInstance) { String hostname = serviceInstance.getHost(); String cluster = getClusterName(serviceInstance); Boolean status = Boolean.TRUE; //TODO: where to get? if (hostname != null && cluster != null && status != null) { Instance instance = new Instance(hostname, cluster, status); // TODO: reimplement when metadata is in commons // add metadata /*Map<String, String> metadata = instanceInfo.getMetadata(); if (metadata != null) { instance.getAttributes().putAll(metadata); }*/ // add ports instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort())); boolean securePortEnabled = serviceInstance.isSecure(); if (securePortEnabled) { instance.getAttributes().put("securePort", String.valueOf(serviceInstance.getPort())); } return instance; } else { return null; } }
private Instance marshall(ServiceInstance serviceInstance) { String hostname = serviceInstance.getHost(); String cluster = getClusterName(serviceInstance); Boolean status = Boolean.TRUE; if (hostname != null && cluster != null && status != null) { Instance instance = new Instance(hostname, cluster, status); instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort())); boolean securePortEnabled = serviceInstance.isSecure(); if (securePortEnabled) { instance.getAttributes().put("securePort", String.valueOf(serviceInstance.getPort())); } return instance; } else { return null; } }
private instance marshall(serviceinstance serviceinstance) { string hostname = serviceinstance.gethost(); string cluster = getclustername(serviceinstance); boolean status = boolean.true; if (hostname != null && cluster != null && status != null) { instance instance = new instance(hostname, cluster, status); instance.getattributes().put("port", string.valueof(serviceinstance.getport())); boolean secureportenabled = serviceinstance.issecure(); if (secureportenabled) { instance.getattributes().put("secureport", string.valueof(serviceinstance.getport())); } return instance; } else { return null; } }
royclarkson/spring-cloud-netflix
[ 1, 1, 0, 0 ]
17,289
@PostConstruct public void setup(){ //Do not use getClass() here... a typical weld issue... endpointUrl=appConfiguration.getBaseEndpoint() + ServiceProviderConfigWS.class.getAnnotation(Path.class).value(); }
@PostConstruct public void setup(){ endpointUrl=appConfiguration.getBaseEndpoint() + ServiceProviderConfigWS.class.getAnnotation(Path.class).value(); }
@postconstruct public void setup(){ endpointurl=appconfiguration.getbaseendpoint() + serviceproviderconfigws.class.getannotation(path.class).value(); }
shoebkhan09/oxTrust
[ 0, 0, 1, 0 ]
25,484
@Test public void testUserDefinedAggregateFunctionImplementsInterface() { final String empDept = JdbcTest.EmpDeptTableFactory.class.getName(); final String mySum3 = Smalls.MySum3.class.getName(); final String model = "{\n" + " version: '1.0',\n" + " schemas: [\n" + " {\n" + " name: 'adhoc',\n" + " tables: [\n" + " {\n" + " name: 'EMPLOYEES',\n" + " type: 'custom',\n" + " factory: '" + empDept + "',\n" + " operand: {'foo': true, 'bar': 345}\n" + " }\n" + " ],\n" + " functions: [\n" + " {\n" + " name: 'MY_SUM3',\n" + " className: '" + mySum3 + "'\n" + " }\n" + " ]\n" + " }\n" + " ]\n" + "}"; final CalciteAssert.AssertThat with = CalciteAssert.model(model) .withDefaultSchema("adhoc"); with.query("select my_sum3(\"deptno\") as p from EMPLOYEES\n") .returns("P=50\n"); with.withDefaultSchema(null) .query("select \"adhoc\".my_sum3(\"deptno\") as p\n" + "from \"adhoc\".EMPLOYEES\n") .returns("P=50\n"); with.query("select my_sum3(\"empid\"), \"deptno\" as p from EMPLOYEES\n") .throws_("Expression 'deptno' is not being grouped"); with.query("select my_sum3(\"deptno\") as p from EMPLOYEES\n") .returns("P=50\n"); with.query("select my_sum3(\"name\") as p from EMPLOYEES\n") .throws_("No match found for function signature MY_SUM3(<CHARACTER>)"); with.query("select my_sum3(\"deptno\", 1) as p from EMPLOYEES\n") .throws_("No match found for function signature " + "MY_SUM3(<NUMERIC>, <NUMERIC>)"); with.query("select my_sum3() as p from EMPLOYEES\n") .throws_("No match found for function signature MY_SUM3()"); with.query("select \"deptno\", my_sum3(\"deptno\") as p from EMPLOYEES\n" + "group by \"deptno\"") .returnsUnordered("deptno=20; P=20", "deptno=10; P=30"); }
@Test public void testUserDefinedAggregateFunctionImplementsInterface() { final String empDept = JdbcTest.EmpDeptTableFactory.class.getName(); final String mySum3 = Smalls.MySum3.class.getName(); final String model = "{\n" + " version: '1.0',\n" + " schemas: [\n" + " {\n" + " name: 'adhoc',\n" + " tables: [\n" + " {\n" + " name: 'EMPLOYEES',\n" + " type: 'custom',\n" + " factory: '" + empDept + "',\n" + " operand: {'foo': true, 'bar': 345}\n" + " }\n" + " ],\n" + " functions: [\n" + " {\n" + " name: 'MY_SUM3',\n" + " className: '" + mySum3 + "'\n" + " }\n" + " ]\n" + " }\n" + " ]\n" + "}"; final CalciteAssert.AssertThat with = CalciteAssert.model(model) .withDefaultSchema("adhoc"); with.query("select my_sum3(\"deptno\") as p from EMPLOYEES\n") .returns("P=50\n"); with.withDefaultSchema(null) .query("select \"adhoc\".my_sum3(\"deptno\") as p\n" + "from \"adhoc\".EMPLOYEES\n") .returns("P=50\n"); with.query("select my_sum3(\"empid\"), \"deptno\" as p from EMPLOYEES\n") .throws_("Expression 'deptno' is not being grouped"); with.query("select my_sum3(\"deptno\") as p from EMPLOYEES\n") .returns("P=50\n"); with.query("select my_sum3(\"name\") as p from EMPLOYEES\n") .throws_("No match found for function signature MY_SUM3(<CHARACTER>)"); with.query("select my_sum3(\"deptno\", 1) as p from EMPLOYEES\n") .throws_("No match found for function signature " + "MY_SUM3(<NUMERIC>, <NUMERIC>)"); with.query("select my_sum3() as p from EMPLOYEES\n") .throws_("No match found for function signature MY_SUM3()"); with.query("select \"deptno\", my_sum3(\"deptno\") as p from EMPLOYEES\n" + "group by \"deptno\"") .returnsUnordered("deptno=20; P=20", "deptno=10; P=30"); }
@test public void testuserdefinedaggregatefunctionimplementsinterface() { final string empdept = jdbctest.empdepttablefactory.class.getname(); final string mysum3 = smalls.mysum3.class.getname(); final string model = "{\n" + " version: '1.0',\n" + " schemas: [\n" + " {\n" + " name: 'adhoc',\n" + " tables: [\n" + " {\n" + " name: 'employees',\n" + " type: 'custom',\n" + " factory: '" + empdept + "',\n" + " operand: {'foo': true, 'bar': 345}\n" + " }\n" + " ],\n" + " functions: [\n" + " {\n" + " name: 'my_sum3',\n" + " classname: '" + mysum3 + "'\n" + " }\n" + " ]\n" + " }\n" + " ]\n" + "}"; final calciteassert.assertthat with = calciteassert.model(model) .withdefaultschema("adhoc"); with.query("select my_sum3(\"deptno\") as p from employees\n") .returns("p=50\n"); with.withdefaultschema(null) .query("select \"adhoc\".my_sum3(\"deptno\") as p\n" + "from \"adhoc\".employees\n") .returns("p=50\n"); with.query("select my_sum3(\"empid\"), \"deptno\" as p from employees\n") .throws_("expression 'deptno' is not being grouped"); with.query("select my_sum3(\"deptno\") as p from employees\n") .returns("p=50\n"); with.query("select my_sum3(\"name\") as p from employees\n") .throws_("no match found for function signature my_sum3(<character>)"); with.query("select my_sum3(\"deptno\", 1) as p from employees\n") .throws_("no match found for function signature " + "my_sum3(<numeric>, <numeric>)"); with.query("select my_sum3() as p from employees\n") .throws_("no match found for function signature my_sum3()"); with.query("select \"deptno\", my_sum3(\"deptno\") as p from employees\n" + "group by \"deptno\"") .returnsunordered("deptno=20; p=20", "deptno=10; p=30"); }
sarasara100/Quicksql
[ 0, 0, 0, 1 ]
25,500
@Override public void generateNormalAppearance() { PDAnnotationInk ink = (PDAnnotationInk) getAnnotation(); PDColor color = ink.getColor(); if (color == null || color.getComponents().length == 0) { return; } // PDF spec does not mention /Border for ink annotations, but it is used if /BS is not available AnnotationBorder ab = AnnotationBorder.getAnnotationBorder(ink, ink.getBorderStyle()); if (Float.compare(ab.width, 0) == 0) { return; } // Adjust rectangle even if not empty // file from PDF.js issue 13447 //TODO in a class structure this should be overridable float minX = Float.MAX_VALUE; float minY = Float.MAX_VALUE; float maxX = Float.MIN_VALUE; float maxY = Float.MIN_VALUE; for (float[] pathArray : ink.getInkList()) { int nPoints = pathArray.length / 2; for (int i = 0; i < nPoints; ++i) { float x = pathArray[i * 2]; float y = pathArray[i * 2 + 1]; minX = Math.min(minX, x); minY = Math.min(minY, y); maxX = Math.max(maxX, x); maxY = Math.max(maxY, y); } } PDRectangle rect = ink.getRectangle(); rect.setLowerLeftX(Math.min(minX - ab.width * 2, rect.getLowerLeftX())); rect.setLowerLeftY(Math.min(minY - ab.width * 2, rect.getLowerLeftY())); rect.setUpperRightX(Math.max(maxX + ab.width * 2, rect.getUpperRightX())); rect.setUpperRightY(Math.max(maxY + ab.width * 2, rect.getUpperRightY())); ink.setRectangle(rect); try (PDAppearanceContentStream cs = getNormalAppearanceAsContentStream()) { setOpacity(cs, ink.getConstantOpacity()); cs.setStrokingColor(color); if (ab.dashArray != null) { cs.setLineDashPattern(ab.dashArray, 0); } cs.setLineWidth(ab.width); for (float[] pathArray : ink.getInkList()) { int nPoints = pathArray.length / 2; // "When drawn, the points shall be connected by straight lines or curves // in an implementation-dependent way" - we do lines. for (int i = 0; i < nPoints; ++i) { float x = pathArray[i * 2]; float y = pathArray[i * 2 + 1]; if (i == 0) { cs.moveTo(x, y); } else { cs.lineTo(x, y); } } cs.stroke(); } } catch (IOException ex) { LOG.error(ex); } }
@Override public void generateNormalAppearance() { PDAnnotationInk ink = (PDAnnotationInk) getAnnotation(); PDColor color = ink.getColor(); if (color == null || color.getComponents().length == 0) { return; } AnnotationBorder ab = AnnotationBorder.getAnnotationBorder(ink, ink.getBorderStyle()); if (Float.compare(ab.width, 0) == 0) { return; } float minX = Float.MAX_VALUE; float minY = Float.MAX_VALUE; float maxX = Float.MIN_VALUE; float maxY = Float.MIN_VALUE; for (float[] pathArray : ink.getInkList()) { int nPoints = pathArray.length / 2; for (int i = 0; i < nPoints; ++i) { float x = pathArray[i * 2]; float y = pathArray[i * 2 + 1]; minX = Math.min(minX, x); minY = Math.min(minY, y); maxX = Math.max(maxX, x); maxY = Math.max(maxY, y); } } PDRectangle rect = ink.getRectangle(); rect.setLowerLeftX(Math.min(minX - ab.width * 2, rect.getLowerLeftX())); rect.setLowerLeftY(Math.min(minY - ab.width * 2, rect.getLowerLeftY())); rect.setUpperRightX(Math.max(maxX + ab.width * 2, rect.getUpperRightX())); rect.setUpperRightY(Math.max(maxY + ab.width * 2, rect.getUpperRightY())); ink.setRectangle(rect); try (PDAppearanceContentStream cs = getNormalAppearanceAsContentStream()) { setOpacity(cs, ink.getConstantOpacity()); cs.setStrokingColor(color); if (ab.dashArray != null) { cs.setLineDashPattern(ab.dashArray, 0); } cs.setLineWidth(ab.width); for (float[] pathArray : ink.getInkList()) { int nPoints = pathArray.length / 2; for (int i = 0; i < nPoints; ++i) { float x = pathArray[i * 2]; float y = pathArray[i * 2 + 1]; if (i == 0) { cs.moveTo(x, y); } else { cs.lineTo(x, y); } } cs.stroke(); } } catch (IOException ex) { LOG.error(ex); } }
@override public void generatenormalappearance() { pdannotationink ink = (pdannotationink) getannotation(); pdcolor color = ink.getcolor(); if (color == null || color.getcomponents().length == 0) { return; } annotationborder ab = annotationborder.getannotationborder(ink, ink.getborderstyle()); if (float.compare(ab.width, 0) == 0) { return; } float minx = float.max_value; float miny = float.max_value; float maxx = float.min_value; float maxy = float.min_value; for (float[] patharray : ink.getinklist()) { int npoints = patharray.length / 2; for (int i = 0; i < npoints; ++i) { float x = patharray[i * 2]; float y = patharray[i * 2 + 1]; minx = math.min(minx, x); miny = math.min(miny, y); maxx = math.max(maxx, x); maxy = math.max(maxy, y); } } pdrectangle rect = ink.getrectangle(); rect.setlowerleftx(math.min(minx - ab.width * 2, rect.getlowerleftx())); rect.setlowerlefty(math.min(miny - ab.width * 2, rect.getlowerlefty())); rect.setupperrightx(math.max(maxx + ab.width * 2, rect.getupperrightx())); rect.setupperrighty(math.max(maxy + ab.width * 2, rect.getupperrighty())); ink.setrectangle(rect); try (pdappearancecontentstream cs = getnormalappearanceascontentstream()) { setopacity(cs, ink.getconstantopacity()); cs.setstrokingcolor(color); if (ab.dasharray != null) { cs.setlinedashpattern(ab.dasharray, 0); } cs.setlinewidth(ab.width); for (float[] patharray : ink.getinklist()) { int npoints = patharray.length / 2; for (int i = 0; i < npoints; ++i) { float x = patharray[i * 2]; float y = patharray[i * 2 + 1]; if (i == 0) { cs.moveto(x, y); } else { cs.lineto(x, y); } } cs.stroke(); } } catch (ioexception ex) { log.error(ex); } }
steven-g/pdfbox
[ 1, 0, 0, 0 ]
987
private OuterJoinPushDownResult processLimitedOuterJoin(RowExpression inheritedPredicate, RowExpression outerEffectivePredicate, RowExpression innerEffectivePredicate, RowExpression joinPredicate, Collection<VariableReferenceExpression> outerVariables) { checkArgument(Iterables.all(VariablesExtractor.extractUnique(outerEffectivePredicate), in(outerVariables)), "outerEffectivePredicate must only contain variables from outerVariables"); checkArgument(Iterables.all(VariablesExtractor.extractUnique(innerEffectivePredicate), not(in(outerVariables))), "innerEffectivePredicate must not contain variables from outerVariables"); ImmutableList.Builder<RowExpression> outerPushdownConjuncts = ImmutableList.builder(); ImmutableList.Builder<RowExpression> innerPushdownConjuncts = ImmutableList.builder(); ImmutableList.Builder<RowExpression> postJoinConjuncts = ImmutableList.builder(); ImmutableList.Builder<RowExpression> joinConjuncts = ImmutableList.builder(); // Strip out non-deterministic conjuncts postJoinConjuncts.addAll(filter(extractConjuncts(inheritedPredicate), not(determinismEvaluator::isDeterministic))); inheritedPredicate = logicalRowExpressions.filterDeterministicConjuncts(inheritedPredicate); outerEffectivePredicate = logicalRowExpressions.filterDeterministicConjuncts(outerEffectivePredicate); innerEffectivePredicate = logicalRowExpressions.filterDeterministicConjuncts(innerEffectivePredicate); joinConjuncts.addAll(filter(extractConjuncts(joinPredicate), not(determinismEvaluator::isDeterministic))); joinPredicate = logicalRowExpressions.filterDeterministicConjuncts(joinPredicate); // Generate equality inferences EqualityInference inheritedInference = createEqualityInference(inheritedPredicate); EqualityInference outerInference = createEqualityInference(inheritedPredicate, outerEffectivePredicate); EqualityInference.EqualityPartition equalityPartition = inheritedInference.generateEqualitiesPartitionedBy(in(outerVariables)); RowExpression outerOnlyInheritedEqualities = logicalRowExpressions.combineConjuncts(equalityPartition.getScopeEqualities()); EqualityInference potentialNullSymbolInference = createEqualityInference(outerOnlyInheritedEqualities, outerEffectivePredicate, innerEffectivePredicate, joinPredicate); // See if we can push inherited predicates down for (RowExpression conjunct : nonInferableConjuncts(inheritedPredicate)) { RowExpression outerRewritten = outerInference.rewriteExpression(conjunct, in(outerVariables)); if (outerRewritten != null) { outerPushdownConjuncts.add(outerRewritten); // A conjunct can only be pushed down into an inner side if it can be rewritten in terms of the outer side RowExpression innerRewritten = potentialNullSymbolInference.rewriteExpression(outerRewritten, not(in(outerVariables))); if (innerRewritten != null) { innerPushdownConjuncts.add(innerRewritten); } } else { postJoinConjuncts.add(conjunct); } } // Add the equalities from the inferences back in outerPushdownConjuncts.addAll(equalityPartition.getScopeEqualities()); postJoinConjuncts.addAll(equalityPartition.getScopeComplementEqualities()); postJoinConjuncts.addAll(equalityPartition.getScopeStraddlingEqualities()); // See if we can push down any outer effective predicates to the inner side for (RowExpression conjunct : nonInferableConjuncts(outerEffectivePredicate)) { RowExpression rewritten = potentialNullSymbolInference.rewriteExpression(conjunct, not(in(outerVariables))); if (rewritten != null) { innerPushdownConjuncts.add(rewritten); } } // See if we can push down join predicates to the inner side for (RowExpression conjunct : nonInferableConjuncts(joinPredicate)) { RowExpression innerRewritten = potentialNullSymbolInference.rewriteExpression(conjunct, not(in(outerVariables))); if (innerRewritten != null) { innerPushdownConjuncts.add(innerRewritten); } else { joinConjuncts.add(conjunct); } } // Push outer and join equalities into the inner side. For example: // SELECT * FROM nation LEFT OUTER JOIN region ON nation.regionkey = region.regionkey and nation.name = region.name WHERE nation.name = 'blah' EqualityInference potentialNullSymbolInferenceWithoutInnerInferred = createEqualityInference(outerOnlyInheritedEqualities, outerEffectivePredicate, joinPredicate); innerPushdownConjuncts.addAll(potentialNullSymbolInferenceWithoutInnerInferred.generateEqualitiesPartitionedBy(not(in(outerVariables))).getScopeEqualities()); // TODO: we can further improve simplifying the equalities by considering other relationships from the outer side EqualityInference.EqualityPartition joinEqualityPartition = createEqualityInference(joinPredicate).generateEqualitiesPartitionedBy(not(in(outerVariables))); innerPushdownConjuncts.addAll(joinEqualityPartition.getScopeEqualities()); joinConjuncts.addAll(joinEqualityPartition.getScopeComplementEqualities()) .addAll(joinEqualityPartition.getScopeStraddlingEqualities()); return new OuterJoinPushDownResult(logicalRowExpressions.combineConjuncts(outerPushdownConjuncts.build()), logicalRowExpressions.combineConjuncts(innerPushdownConjuncts.build()), logicalRowExpressions.combineConjuncts(joinConjuncts.build()), logicalRowExpressions.combineConjuncts(postJoinConjuncts.build())); }
private OuterJoinPushDownResult processLimitedOuterJoin(RowExpression inheritedPredicate, RowExpression outerEffectivePredicate, RowExpression innerEffectivePredicate, RowExpression joinPredicate, Collection<VariableReferenceExpression> outerVariables) { checkArgument(Iterables.all(VariablesExtractor.extractUnique(outerEffectivePredicate), in(outerVariables)), "outerEffectivePredicate must only contain variables from outerVariables"); checkArgument(Iterables.all(VariablesExtractor.extractUnique(innerEffectivePredicate), not(in(outerVariables))), "innerEffectivePredicate must not contain variables from outerVariables"); ImmutableList.Builder<RowExpression> outerPushdownConjuncts = ImmutableList.builder(); ImmutableList.Builder<RowExpression> innerPushdownConjuncts = ImmutableList.builder(); ImmutableList.Builder<RowExpression> postJoinConjuncts = ImmutableList.builder(); ImmutableList.Builder<RowExpression> joinConjuncts = ImmutableList.builder(); postJoinConjuncts.addAll(filter(extractConjuncts(inheritedPredicate), not(determinismEvaluator::isDeterministic))); inheritedPredicate = logicalRowExpressions.filterDeterministicConjuncts(inheritedPredicate); outerEffectivePredicate = logicalRowExpressions.filterDeterministicConjuncts(outerEffectivePredicate); innerEffectivePredicate = logicalRowExpressions.filterDeterministicConjuncts(innerEffectivePredicate); joinConjuncts.addAll(filter(extractConjuncts(joinPredicate), not(determinismEvaluator::isDeterministic))); joinPredicate = logicalRowExpressions.filterDeterministicConjuncts(joinPredicate); EqualityInference inheritedInference = createEqualityInference(inheritedPredicate); EqualityInference outerInference = createEqualityInference(inheritedPredicate, outerEffectivePredicate); EqualityInference.EqualityPartition equalityPartition = inheritedInference.generateEqualitiesPartitionedBy(in(outerVariables)); RowExpression outerOnlyInheritedEqualities = logicalRowExpressions.combineConjuncts(equalityPartition.getScopeEqualities()); EqualityInference potentialNullSymbolInference = createEqualityInference(outerOnlyInheritedEqualities, outerEffectivePredicate, innerEffectivePredicate, joinPredicate); for (RowExpression conjunct : nonInferableConjuncts(inheritedPredicate)) { RowExpression outerRewritten = outerInference.rewriteExpression(conjunct, in(outerVariables)); if (outerRewritten != null) { outerPushdownConjuncts.add(outerRewritten); RowExpression innerRewritten = potentialNullSymbolInference.rewriteExpression(outerRewritten, not(in(outerVariables))); if (innerRewritten != null) { innerPushdownConjuncts.add(innerRewritten); } } else { postJoinConjuncts.add(conjunct); } } outerPushdownConjuncts.addAll(equalityPartition.getScopeEqualities()); postJoinConjuncts.addAll(equalityPartition.getScopeComplementEqualities()); postJoinConjuncts.addAll(equalityPartition.getScopeStraddlingEqualities()); for (RowExpression conjunct : nonInferableConjuncts(outerEffectivePredicate)) { RowExpression rewritten = potentialNullSymbolInference.rewriteExpression(conjunct, not(in(outerVariables))); if (rewritten != null) { innerPushdownConjuncts.add(rewritten); } } for (RowExpression conjunct : nonInferableConjuncts(joinPredicate)) { RowExpression innerRewritten = potentialNullSymbolInference.rewriteExpression(conjunct, not(in(outerVariables))); if (innerRewritten != null) { innerPushdownConjuncts.add(innerRewritten); } else { joinConjuncts.add(conjunct); } } EqualityInference potentialNullSymbolInferenceWithoutInnerInferred = createEqualityInference(outerOnlyInheritedEqualities, outerEffectivePredicate, joinPredicate); innerPushdownConjuncts.addAll(potentialNullSymbolInferenceWithoutInnerInferred.generateEqualitiesPartitionedBy(not(in(outerVariables))).getScopeEqualities()); EqualityInference.EqualityPartition joinEqualityPartition = createEqualityInference(joinPredicate).generateEqualitiesPartitionedBy(not(in(outerVariables))); innerPushdownConjuncts.addAll(joinEqualityPartition.getScopeEqualities()); joinConjuncts.addAll(joinEqualityPartition.getScopeComplementEqualities()) .addAll(joinEqualityPartition.getScopeStraddlingEqualities()); return new OuterJoinPushDownResult(logicalRowExpressions.combineConjuncts(outerPushdownConjuncts.build()), logicalRowExpressions.combineConjuncts(innerPushdownConjuncts.build()), logicalRowExpressions.combineConjuncts(joinConjuncts.build()), logicalRowExpressions.combineConjuncts(postJoinConjuncts.build())); }
private outerjoinpushdownresult processlimitedouterjoin(rowexpression inheritedpredicate, rowexpression outereffectivepredicate, rowexpression innereffectivepredicate, rowexpression joinpredicate, collection<variablereferenceexpression> outervariables) { checkargument(iterables.all(variablesextractor.extractunique(outereffectivepredicate), in(outervariables)), "outereffectivepredicate must only contain variables from outervariables"); checkargument(iterables.all(variablesextractor.extractunique(innereffectivepredicate), not(in(outervariables))), "innereffectivepredicate must not contain variables from outervariables"); immutablelist.builder<rowexpression> outerpushdownconjuncts = immutablelist.builder(); immutablelist.builder<rowexpression> innerpushdownconjuncts = immutablelist.builder(); immutablelist.builder<rowexpression> postjoinconjuncts = immutablelist.builder(); immutablelist.builder<rowexpression> joinconjuncts = immutablelist.builder(); postjoinconjuncts.addall(filter(extractconjuncts(inheritedpredicate), not(determinismevaluator::isdeterministic))); inheritedpredicate = logicalrowexpressions.filterdeterministicconjuncts(inheritedpredicate); outereffectivepredicate = logicalrowexpressions.filterdeterministicconjuncts(outereffectivepredicate); innereffectivepredicate = logicalrowexpressions.filterdeterministicconjuncts(innereffectivepredicate); joinconjuncts.addall(filter(extractconjuncts(joinpredicate), not(determinismevaluator::isdeterministic))); joinpredicate = logicalrowexpressions.filterdeterministicconjuncts(joinpredicate); equalityinference inheritedinference = createequalityinference(inheritedpredicate); equalityinference outerinference = createequalityinference(inheritedpredicate, outereffectivepredicate); equalityinference.equalitypartition equalitypartition = inheritedinference.generateequalitiespartitionedby(in(outervariables)); rowexpression outeronlyinheritedequalities = logicalrowexpressions.combineconjuncts(equalitypartition.getscopeequalities()); equalityinference potentialnullsymbolinference = createequalityinference(outeronlyinheritedequalities, outereffectivepredicate, innereffectivepredicate, joinpredicate); for (rowexpression conjunct : noninferableconjuncts(inheritedpredicate)) { rowexpression outerrewritten = outerinference.rewriteexpression(conjunct, in(outervariables)); if (outerrewritten != null) { outerpushdownconjuncts.add(outerrewritten); rowexpression innerrewritten = potentialnullsymbolinference.rewriteexpression(outerrewritten, not(in(outervariables))); if (innerrewritten != null) { innerpushdownconjuncts.add(innerrewritten); } } else { postjoinconjuncts.add(conjunct); } } outerpushdownconjuncts.addall(equalitypartition.getscopeequalities()); postjoinconjuncts.addall(equalitypartition.getscopecomplementequalities()); postjoinconjuncts.addall(equalitypartition.getscopestraddlingequalities()); for (rowexpression conjunct : noninferableconjuncts(outereffectivepredicate)) { rowexpression rewritten = potentialnullsymbolinference.rewriteexpression(conjunct, not(in(outervariables))); if (rewritten != null) { innerpushdownconjuncts.add(rewritten); } } for (rowexpression conjunct : noninferableconjuncts(joinpredicate)) { rowexpression innerrewritten = potentialnullsymbolinference.rewriteexpression(conjunct, not(in(outervariables))); if (innerrewritten != null) { innerpushdownconjuncts.add(innerrewritten); } else { joinconjuncts.add(conjunct); } } equalityinference potentialnullsymbolinferencewithoutinnerinferred = createequalityinference(outeronlyinheritedequalities, outereffectivepredicate, joinpredicate); innerpushdownconjuncts.addall(potentialnullsymbolinferencewithoutinnerinferred.generateequalitiespartitionedby(not(in(outervariables))).getscopeequalities()); equalityinference.equalitypartition joinequalitypartition = createequalityinference(joinpredicate).generateequalitiespartitionedby(not(in(outervariables))); innerpushdownconjuncts.addall(joinequalitypartition.getscopeequalities()); joinconjuncts.addall(joinequalitypartition.getscopecomplementequalities()) .addall(joinequalitypartition.getscopestraddlingequalities()); return new outerjoinpushdownresult(logicalrowexpressions.combineconjuncts(outerpushdownconjuncts.build()), logicalrowexpressions.combineconjuncts(innerpushdownconjuncts.build()), logicalrowexpressions.combineconjuncts(joinconjuncts.build()), logicalrowexpressions.combineconjuncts(postjoinconjuncts.build())); }
shrinidhijoshi/presto
[ 1, 0, 0, 0 ]
17,401
public static SqlTypeName zetaSqlTypeToCalciteType(TypeKind zetaSqlType) { switch (zetaSqlType) { case TYPE_INT64: return SqlTypeName.BIGINT; case TYPE_NUMERIC: return SqlTypeName.DECIMAL; case TYPE_DOUBLE: return SqlTypeName.DOUBLE; case TYPE_STRING: return SqlTypeName.VARCHAR; case TYPE_TIMESTAMP: return SqlTypeName.TIMESTAMP; case TYPE_BOOL: return SqlTypeName.BOOLEAN; case TYPE_BYTES: return SqlTypeName.VARBINARY; // TODO[BEAM-9179] Add conversion code for ARRAY and ROW types default: throw new IllegalArgumentException("Unsupported ZetaSQL type: " + zetaSqlType.name()); } }
public static SqlTypeName zetaSqlTypeToCalciteType(TypeKind zetaSqlType) { switch (zetaSqlType) { case TYPE_INT64: return SqlTypeName.BIGINT; case TYPE_NUMERIC: return SqlTypeName.DECIMAL; case TYPE_DOUBLE: return SqlTypeName.DOUBLE; case TYPE_STRING: return SqlTypeName.VARCHAR; case TYPE_TIMESTAMP: return SqlTypeName.TIMESTAMP; case TYPE_BOOL: return SqlTypeName.BOOLEAN; case TYPE_BYTES: return SqlTypeName.VARBINARY; default: throw new IllegalArgumentException("Unsupported ZetaSQL type: " + zetaSqlType.name()); } }
public static sqltypename zetasqltypetocalcitetype(typekind zetasqltype) { switch (zetasqltype) { case type_int64: return sqltypename.bigint; case type_numeric: return sqltypename.decimal; case type_double: return sqltypename.double; case type_string: return sqltypename.varchar; case type_timestamp: return sqltypename.timestamp; case type_bool: return sqltypename.boolean; case type_bytes: return sqltypename.varbinary; default: throw new illegalargumentexception("unsupported zetasql type: " + zetasqltype.name()); } }
stephenoken/beam
[ 0, 1, 0, 0 ]
33,808
private boolean checkPermission(Cluster cluster, boolean readOnly) { for (GrantedAuthority grantedAuthority : securityHelper.getCurrentAuthorities()) { if (grantedAuthority instanceof AmbariGrantedAuthority) { AmbariGrantedAuthority authority = (AmbariGrantedAuthority) grantedAuthority; PrivilegeEntity privilegeEntity = authority.getPrivilegeEntity(); Integer permissionId = privilegeEntity.getPermission().getId(); // admin has full access if (permissionId.equals(PermissionEntity.AMBARI_ADMINISTRATOR_PERMISSION)) { return true; } if (cluster != null) { if (cluster.checkPermission(privilegeEntity, readOnly)) { return true; } } } } // TODO : should we log this? return false; }
private boolean checkPermission(Cluster cluster, boolean readOnly) { for (GrantedAuthority grantedAuthority : securityHelper.getCurrentAuthorities()) { if (grantedAuthority instanceof AmbariGrantedAuthority) { AmbariGrantedAuthority authority = (AmbariGrantedAuthority) grantedAuthority; PrivilegeEntity privilegeEntity = authority.getPrivilegeEntity(); Integer permissionId = privilegeEntity.getPermission().getId(); if (permissionId.equals(PermissionEntity.AMBARI_ADMINISTRATOR_PERMISSION)) { return true; } if (cluster != null) { if (cluster.checkPermission(privilegeEntity, readOnly)) { return true; } } } } return false; }
private boolean checkpermission(cluster cluster, boolean readonly) { for (grantedauthority grantedauthority : securityhelper.getcurrentauthorities()) { if (grantedauthority instanceof ambarigrantedauthority) { ambarigrantedauthority authority = (ambarigrantedauthority) grantedauthority; privilegeentity privilegeentity = authority.getprivilegeentity(); integer permissionid = privilegeentity.getpermission().getid(); if (permissionid.equals(permissionentity.ambari_administrator_permission)) { return true; } if (cluster != null) { if (cluster.checkpermission(privilegeentity, readonly)) { return true; } } } } return false; }
runningt/ambari
[ 1, 0, 0, 0 ]
1,051
@Override public ShuffleDataModel.KValueTypeId getKValueTypeId() { int val = ngetKValueTypeId(this.pointerToStore); if (val==ShuffleDataModel.KValueTypeId.Int.state){ return ShuffleDataModel.KValueTypeId.Int; } else if (val == ShuffleDataModel.KValueTypeId.Long.state){ return ShuffleDataModel.KValueTypeId.Long; } else if (val == ShuffleDataModel.KValueTypeId.Float.state){ return ShuffleDataModel.KValueTypeId.Float; } else if (val == ShuffleDataModel.KValueTypeId.Double.state){ return ShuffleDataModel.KValueTypeId.Double; } else if (val == ShuffleDataModel.KValueTypeId.String.state){ return ShuffleDataModel.KValueTypeId.String; } else if (val == ShuffleDataModel.KValueTypeId.ByteArray.state){ return ShuffleDataModel.KValueTypeId.ByteArray; } else if (val == ShuffleDataModel.KValueTypeId.Object.state){ return ShuffleDataModel.KValueTypeId.Object; } else if (val == ShuffleDataModel.KValueTypeId.Unknown.state) { throw new RuntimeException("Unknown key value type encountered"); } else { throw new RuntimeException("unsupported key value type encountered"); } }
@Override public ShuffleDataModel.KValueTypeId getKValueTypeId() { int val = ngetKValueTypeId(this.pointerToStore); if (val==ShuffleDataModel.KValueTypeId.Int.state){ return ShuffleDataModel.KValueTypeId.Int; } else if (val == ShuffleDataModel.KValueTypeId.Long.state){ return ShuffleDataModel.KValueTypeId.Long; } else if (val == ShuffleDataModel.KValueTypeId.Float.state){ return ShuffleDataModel.KValueTypeId.Float; } else if (val == ShuffleDataModel.KValueTypeId.Double.state){ return ShuffleDataModel.KValueTypeId.Double; } else if (val == ShuffleDataModel.KValueTypeId.String.state){ return ShuffleDataModel.KValueTypeId.String; } else if (val == ShuffleDataModel.KValueTypeId.ByteArray.state){ return ShuffleDataModel.KValueTypeId.ByteArray; } else if (val == ShuffleDataModel.KValueTypeId.Object.state){ return ShuffleDataModel.KValueTypeId.Object; } else if (val == ShuffleDataModel.KValueTypeId.Unknown.state) { throw new RuntimeException("Unknown key value type encountered"); } else { throw new RuntimeException("unsupported key value type encountered"); } }
@override public shuffledatamodel.kvaluetypeid getkvaluetypeid() { int val = ngetkvaluetypeid(this.pointertostore); if (val==shuffledatamodel.kvaluetypeid.int.state){ return shuffledatamodel.kvaluetypeid.int; } else if (val == shuffledatamodel.kvaluetypeid.long.state){ return shuffledatamodel.kvaluetypeid.long; } else if (val == shuffledatamodel.kvaluetypeid.float.state){ return shuffledatamodel.kvaluetypeid.float; } else if (val == shuffledatamodel.kvaluetypeid.double.state){ return shuffledatamodel.kvaluetypeid.double; } else if (val == shuffledatamodel.kvaluetypeid.string.state){ return shuffledatamodel.kvaluetypeid.string; } else if (val == shuffledatamodel.kvaluetypeid.bytearray.state){ return shuffledatamodel.kvaluetypeid.bytearray; } else if (val == shuffledatamodel.kvaluetypeid.object.state){ return shuffledatamodel.kvaluetypeid.object; } else if (val == shuffledatamodel.kvaluetypeid.unknown.state) { throw new runtimeexception("unknown key value type encountered"); } else { throw new runtimeexception("unsupported key value type encountered"); } }
sparkle-plugin/sparkle
[ 1, 0, 0, 0 ]
9,251
public Optional<ClassName> copierClassFor(MemberModel memberModel) { if (canCopyReference(memberModel)) { return Optional.empty(); } if (canUseStandardCopier(memberModel)) { return Optional.of(ClassName.get(StandardMemberCopier.class)); } // FIXME: Ugly hack, but some services (Health) have shapes with names // that differ only in the casing of the first letter, and generating // classes for them breaks on case insensitive filesystems... String shapeName = memberModel.getC2jShape(); if (shapeName.substring(0, 1).toLowerCase(Locale.ENGLISH).equals(shapeName.substring(0, 1))) { shapeName = "_" + shapeName; } return Optional.of(poetExtensions.getModelClass(shapeName + "Copier")); }
public Optional<ClassName> copierClassFor(MemberModel memberModel) { if (canCopyReference(memberModel)) { return Optional.empty(); } if (canUseStandardCopier(memberModel)) { return Optional.of(ClassName.get(StandardMemberCopier.class)); } String shapeName = memberModel.getC2jShape(); if (shapeName.substring(0, 1).toLowerCase(Locale.ENGLISH).equals(shapeName.substring(0, 1))) { shapeName = "_" + shapeName; } return Optional.of(poetExtensions.getModelClass(shapeName + "Copier")); }
public optional<classname> copierclassfor(membermodel membermodel) { if (cancopyreference(membermodel)) { return optional.empty(); } if (canusestandardcopier(membermodel)) { return optional.of(classname.get(standardmembercopier.class)); } string shapename = membermodel.getc2jshape(); if (shapename.substring(0, 1).tolowercase(locale.english).equals(shapename.substring(0, 1))) { shapename = "_" + shapename; } return optional.of(poetextensions.getmodelclass(shapename + "copier")); }
slachiewicz/aws-sdk-java-v2
[ 1, 0, 0, 0 ]
1,396
private synchronized void fillCostMapWithGeometries() { if (mGeometryList.isEmpty()) { Log.wtf(TAG, "Empty geometries list"); setValid(false); return; } // Get the grid boundaries to determine the size of the cost map. double[][] positions = findGeometriesBoundaries(); if (positions == null) { Log.wtf(TAG, "Could not find grid boundaries"); setValid(false); return; } // Create the grid. makeGrid(positions, MIN_COST); for (Geometry g : mGeometryList) { int size = g.mPolygon.getSize(); List<Transform> points = g.mPolygon.getPoints(); // DiscretizedVertices contain only X and Y. int[][] discretizedVertices = new int[size][2]; for (int i = 0; i < size; i++) { double[] pointPosition = points.get(i).getPosition(); discretizedVertices[i][0] = (int) Math.floor(pointPosition[0] / getResolution()); discretizedVertices[i][1] = (int) Math.floor(pointPosition[1] / getResolution()); } // TODO mCost is not used, function below sets polygon regions to OBSTACLE_COST. drawPolygonOnGrid(discretizedVertices); } }
private synchronized void fillCostMapWithGeometries() { if (mGeometryList.isEmpty()) { Log.wtf(TAG, "Empty geometries list"); setValid(false); return; } double[][] positions = findGeometriesBoundaries(); if (positions == null) { Log.wtf(TAG, "Could not find grid boundaries"); setValid(false); return; } makeGrid(positions, MIN_COST); for (Geometry g : mGeometryList) { int size = g.mPolygon.getSize(); List<Transform> points = g.mPolygon.getPoints(); int[][] discretizedVertices = new int[size][2]; for (int i = 0; i < size; i++) { double[] pointPosition = points.get(i).getPosition(); discretizedVertices[i][0] = (int) Math.floor(pointPosition[0] / getResolution()); discretizedVertices[i][1] = (int) Math.floor(pointPosition[1] / getResolution()); } drawPolygonOnGrid(discretizedVertices); } }
private synchronized void fillcostmapwithgeometries() { if (mgeometrylist.isempty()) { log.wtf(tag, "empty geometries list"); setvalid(false); return; } double[][] positions = findgeometriesboundaries(); if (positions == null) { log.wtf(tag, "could not find grid boundaries"); setvalid(false); return; } makegrid(positions, min_cost); for (geometry g : mgeometrylist) { int size = g.mpolygon.getsize(); list<transform> points = g.mpolygon.getpoints(); int[][] discretizedvertices = new int[size][2]; for (int i = 0; i < size; i++) { double[] pointposition = points.get(i).getposition(); discretizedvertices[i][0] = (int) math.floor(pointposition[0] / getresolution()); discretizedvertices[i][1] = (int) math.floor(pointposition[1] / getresolution()); } drawpolygonongrid(discretizedvertices); } }
rhickman/cellbots3
[ 1, 0, 0, 0 ]
1,397
private synchronized double[][] findGeometriesBoundaries() { if (mGeometryList.isEmpty()) { Log.wtf(TAG, "Empty geometries list"); return null; } double minX = Double.MAX_VALUE; double maxX = -Double.MAX_VALUE; double minY = Double.MAX_VALUE; double maxY = -Double.MAX_VALUE; for (Geometry g : mGeometryList) { int size = g.mPolygon.getSize(); List<Transform> points = g.mPolygon.getPoints(); for (int i = 0; i < size; i++) { double[] pointPosition = points.get(i).getPosition(); minX = Math.min(minX, pointPosition[0]); maxX = Math.max(maxX, pointPosition[0]); minY = Math.min(minY, pointPosition[1]); maxY = Math.max(maxY, pointPosition[1]); } } return new double[][]{{minX - mRobotRadius, minY - mRobotRadius}, {maxX + mRobotRadius, maxY + mRobotRadius}}; }
private synchronized double[][] findGeometriesBoundaries() { if (mGeometryList.isEmpty()) { Log.wtf(TAG, "Empty geometries list"); return null; } double minX = Double.MAX_VALUE; double maxX = -Double.MAX_VALUE; double minY = Double.MAX_VALUE; double maxY = -Double.MAX_VALUE; for (Geometry g : mGeometryList) { int size = g.mPolygon.getSize(); List<Transform> points = g.mPolygon.getPoints(); for (int i = 0; i < size; i++) { double[] pointPosition = points.get(i).getPosition(); minX = Math.min(minX, pointPosition[0]); maxX = Math.max(maxX, pointPosition[0]); minY = Math.min(minY, pointPosition[1]); maxY = Math.max(maxY, pointPosition[1]); } } return new double[][]{{minX - mRobotRadius, minY - mRobotRadius}, {maxX + mRobotRadius, maxY + mRobotRadius}}; }
private synchronized double[][] findgeometriesboundaries() { if (mgeometrylist.isempty()) { log.wtf(tag, "empty geometries list"); return null; } double minx = double.max_value; double maxx = -double.max_value; double miny = double.max_value; double maxy = -double.max_value; for (geometry g : mgeometrylist) { int size = g.mpolygon.getsize(); list<transform> points = g.mpolygon.getpoints(); for (int i = 0; i < size; i++) { double[] pointposition = points.get(i).getposition(); minx = math.min(minx, pointposition[0]); maxx = math.max(maxx, pointposition[0]); miny = math.min(miny, pointposition[1]); maxy = math.max(maxy, pointposition[1]); } } return new double[][]{{minx - mrobotradius, miny - mrobotradius}, {maxx + mrobotradius, maxy + mrobotradius}}; }
rhickman/cellbots3
[ 1, 0, 0, 0 ]
34,326
public String exportAll(String filename) throws IOException { // currently only support python - maybe in future we'll support js too String python = LangUtils.toPython(); Files.write(Paths.get(filename), python.toString().getBytes()); info("saved %s to %s", getName(), filename); return python; }
public String exportAll(String filename) throws IOException { String python = LangUtils.toPython(); Files.write(Paths.get(filename), python.toString().getBytes()); info("saved %s to %s", getName(), filename); return python; }
public string exportall(string filename) throws ioexception { string python = langutils.topython(); files.write(paths.get(filename), python.tostring().getbytes()); info("saved %s to %s", getname(), filename); return python; }
srayner/myrobotlab
[ 1, 0, 0, 0 ]
26,189
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); filePath = selectedFile.getAbsolutePath(); } try{ File f=new File(filePath); Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); PreparedStatement ps = con.prepareStatement ("insert into song values(?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, null); ps.setString(2, name.getText()); ps.setString(3, albumID.get(albums.getSelectedItem().toString())); ps.setString(4, genre.getText()); ps.setInt(5, 0); ps.setInt(6, Integer.parseInt(song_num.getText())); System.out.println(""+f.length()); ps.setBytes(7, readFile(filePath)); ps.executeUpdate(); ps.close(); PreparedStatement ps1 = con.prepareStatement ("select id from song where name=? and album_id=?"); ps1.setString(1, name.getText()); ps1.setString(2, albumID.get(albums.getSelectedItem().toString())); //step4 execute query ResultSet rs1=ps1.executeQuery(); String id = ""; while(rs1.next()) { id = rs1.getString(1); } ps1.close(); for(Object a:artists.getSelectedValuesList()) { ps = con.prepareCall ("{call addsongartist(?, ?)}"); ps.setString(1, id); ps.setString(2, artistID.get(a.toString())); ps.executeUpdate(); ps.close(); } con.close(); } catch (Exception e) {e.printStackTrace();} this.updateTable(); JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) { try { try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } con.close(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); filePath = selectedFile.getAbsolutePath(); } try{ File f=new File(filePath); Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); PreparedStatement ps = con.prepareStatement ("insert into song values(?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, null); ps.setString(2, name.getText()); ps.setString(3, albumID.get(albums.getSelectedItem().toString())); ps.setString(4, genre.getText()); ps.setInt(5, 0); ps.setInt(6, Integer.parseInt(song_num.getText())); System.out.println(""+f.length()); ps.setBytes(7, readFile(filePath)); ps.executeUpdate(); ps.close(); PreparedStatement ps1 = con.prepareStatement ("select id from song where name=? and album_id=?"); ps1.setString(1, name.getText()); ps1.setString(2, albumID.get(albums.getSelectedItem().toString())); ResultSet rs1=ps1.executeQuery(); String id = ""; while(rs1.next()) { id = rs1.getString(1); } ps1.close(); for(Object a:artists.getSelectedValuesList()) { ps = con.prepareCall ("{call addsongartist(?, ?)}"); ps.setString(1, id); ps.setString(2, artistID.get(a.toString())); ps.executeUpdate(); ps.close(); } con.close(); } catch (Exception e) {e.printStackTrace();} this.updateTable(); JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
private void addbuttonactionperformed(java.awt.event.actionevent evt) { try { try { clip.stop(); } catch(exception e) { } try { class.forname("oracle.jdbc.driver.oracledriver"); } catch (classnotfoundexception ex) { logger.getlogger(adminview.class.getname()).log(level.severe, null, ex); } connection con=drivermanager.getconnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); statement stmt=con.createstatement(); resultset rs=stmt.executequery("select * from album"); arraylist<string> albumlist = new arraylist<string>(); hashmap<string, string> albumid = new hashmap<>(); while(rs.next()) { albumlist.add((rs.getstring(2))); albumid.put(rs.getstring(2), rs.getstring(1)); } rs=stmt.executequery("select * from artist"); arraylist<string> artistlist = new arraylist<string>(); hashmap<string, string> artistid = new hashmap<>(); while(rs.next()) { artistlist.add((rs.getstring(2))); artistid.put(rs.getstring(2), rs.getstring(1)); } con.close(); jtextfield name = new jtextfield(); jtextfield genre = new jtextfield(); jtextfield song_num = new jtextfield(); jcombobox<string> albums = new jcombobox<string>(albumlist.toarray(new string[0])); jlist artists = new jlist(artistlist.toarray(new string[0])); artists.setselectionmode( listselectionmodel.multiple_interval_selection); int[] select = {19, 20, 22}; object[] input = { "name : ", name, "genre :", genre, "artist :", artists, "song number in album :", song_num, "album :", albums, }; int option = joptionpane.showconfirmdialog(this, input, "enter song details", joptionpane.ok_cancel_option); if(option == joptionpane.ok_option) { jfilechooser jfc = new jfilechooser(); int returnvalue = jfc.showopendialog(null); string filepath = null; if (returnvalue == jfilechooser.approve_option) { file selectedfile = jfc.getselectedfile(); system.out.println(selectedfile.getabsolutepath()); filepath = selectedfile.getabsolutepath(); } try{ file f=new file(filepath); class.forname("oracle.jdbc.driver.oracledriver"); con = drivermanager.getconnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); preparedstatement ps = con.preparestatement ("insert into song values(?, ?, ?, ?, ?, ?, ?)"); ps.setstring(1, null); ps.setstring(2, name.gettext()); ps.setstring(3, albumid.get(albums.getselecteditem().tostring())); ps.setstring(4, genre.gettext()); ps.setint(5, 0); ps.setint(6, integer.parseint(song_num.gettext())); system.out.println(""+f.length()); ps.setbytes(7, readfile(filepath)); ps.executeupdate(); ps.close(); preparedstatement ps1 = con.preparestatement ("select id from song where name=? and album_id=?"); ps1.setstring(1, name.gettext()); ps1.setstring(2, albumid.get(albums.getselecteditem().tostring())); resultset rs1=ps1.executequery(); string id = ""; while(rs1.next()) { id = rs1.getstring(1); } ps1.close(); for(object a:artists.getselectedvalueslist()) { ps = con.preparecall ("{call addsongartist(?, ?)}"); ps.setstring(1, id); ps.setstring(2, artistid.get(a.tostring())); ps.executeupdate(); ps.close(); } con.close(); } catch (exception e) {e.printstacktrace();} this.updatetable(); joptionpane.showmessagedialog(this, "success!\n"); } } catch (exception e) { joptionpane.showmessagedialog(this, "error!\n"+e.getmessage()); } }
shivamkumar78/Music_Application
[ 0, 1, 0, 0 ]
26,190
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try { // TODO add your handling code here: searchText.setText(""); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField about = new JTextField(); Object[] input = { // "Id : ", id, "Name : ", name, "About : ", about, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Artist details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); CallableStatement ps = con.prepareCall ("{call addartist(?, ?, ?)}"); ps.setString(1,null); ps.setString(2, name.getText()); ps.setString(3, about.getText()); ps.executeUpdate(); ps.close(); con.close(); } catch (Exception e) {e.printStackTrace();} JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) { try { searchText.setText(""); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } JTextField name = new JTextField(); JTextField about = new JTextField(); Object[] input = { "Name : ", name, "About : ", about, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Artist details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); CallableStatement ps = con.prepareCall ("{call addartist(?, ?, ?)}"); ps.setString(1,null); ps.setString(2, name.getText()); ps.setString(3, about.getText()); ps.executeUpdate(); ps.close(); con.close(); } catch (Exception e) {e.printStackTrace();} JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
private void addartistactionperformed(java.awt.event.actionevent evt) { try { searchtext.settext(""); try { class.forname("oracle.jdbc.driver.oracledriver"); } catch (classnotfoundexception ex) { logger.getlogger(adminview.class.getname()).log(level.severe, null, ex); } jtextfield name = new jtextfield(); jtextfield about = new jtextfield(); object[] input = { "name : ", name, "about : ", about, }; int option = joptionpane.showconfirmdialog(this, input, "enter artist details", joptionpane.ok_cancel_option); if(option == joptionpane.ok_option) { try{ class.forname("oracle.jdbc.driver.oracledriver"); connection con = drivermanager.getconnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); callablestatement ps = con.preparecall ("{call addartist(?, ?, ?)}"); ps.setstring(1,null); ps.setstring(2, name.gettext()); ps.setstring(3, about.gettext()); ps.executeupdate(); ps.close(); con.close(); } catch (exception e) {e.printstacktrace();} joptionpane.showmessagedialog(this, "success!\n"); } } catch (exception e) { joptionpane.showmessagedialog(this, "error!\n"+e.getmessage()); } }
shivamkumar78/Music_Application
[ 0, 1, 0, 0 ]
26,191
private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed // TODO add your handling code here: try { // TODO add your handling code here: try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); Object[] input = { // "Id : ", id, "Name : ", name, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Album details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); CallableStatement ps = con.prepareCall ("{call addalbum(?, ?)}"); ps.setString(1, null); ps.setString(2, name.getText()); ps.executeUpdate(); ps.close(); con.close(); } catch (Exception e) {e.printStackTrace();} JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) { try { try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } JTextField name = new JTextField(); Object[] input = { "Name : ", name, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Album details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); CallableStatement ps = con.prepareCall ("{call addalbum(?, ?)}"); ps.setString(1, null); ps.setString(2, name.getText()); ps.executeUpdate(); ps.close(); con.close(); } catch (Exception e) {e.printStackTrace();} JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
private void addalbumactionperformed(java.awt.event.actionevent evt) { try { try { class.forname("oracle.jdbc.driver.oracledriver"); } catch (classnotfoundexception ex) { logger.getlogger(adminview.class.getname()).log(level.severe, null, ex); } jtextfield name = new jtextfield(); object[] input = { "name : ", name, }; int option = joptionpane.showconfirmdialog(this, input, "enter album details", joptionpane.ok_cancel_option); if(option == joptionpane.ok_option) { try{ class.forname("oracle.jdbc.driver.oracledriver"); connection con = drivermanager.getconnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); callablestatement ps = con.preparecall ("{call addalbum(?, ?)}"); ps.setstring(1, null); ps.setstring(2, name.gettext()); ps.executeupdate(); ps.close(); con.close(); } catch (exception e) {e.printstacktrace();} joptionpane.showmessagedialog(this, "success!\n"); } } catch (exception e) { joptionpane.showmessagedialog(this, "error!\n"+e.getmessage()); } }
shivamkumar78/Music_Application
[ 0, 1, 0, 0 ]
26,243
public RunResult run(RunDecision runDecision) throws DetectUserFriendlyException, InterruptedException, IntegrationException { //TODO: Better way for run manager to get dependencies so he can be tested. (And better ways of creating his objects) final DetectConfiguration detectConfiguration = detectContext.getBean(DetectConfiguration.class); final DetectConfigurationFactory detectConfigurationFactory = detectContext.getBean(DetectConfigurationFactory.class); final DirectoryManager directoryManager = detectContext.getBean(DirectoryManager.class); final EventSystem eventSystem = detectContext.getBean(EventSystem.class); final CodeLocationNameManager codeLocationNameManager = detectContext.getBean(CodeLocationNameManager.class); final BdioCodeLocationCreator bdioCodeLocationCreator = detectContext.getBean(BdioCodeLocationCreator.class); final ConnectionManager connectionManager = detectContext.getBean(ConnectionManager.class); final DetectInfo detectInfo = detectContext.getBean(DetectInfo.class); final RunResult runResult = new RunResult(); final RunOptions runOptions = detectConfigurationFactory.createRunOptions(); final DetectToolFilter detectToolFilter = runOptions.getDetectToolFilter(); if (runDecision.willRunBlackduck()) { logger.info("Black Duck tools will run."); final ConnectivityManager connectivityManager = detectContext.getBean(ConnectivityManager.class); if (connectivityManager.getPhoneHomeManager().isPresent()) { connectivityManager.getPhoneHomeManager().get().startPhoneHome(); } DetectorEnvironment detectorEnvironment = new DetectorEnvironment(directoryManager.getSourceDirectory(), Collections.emptySet(), 0, null, false); DetectorFactory detectorFactory = detectContext.getBean(DetectorFactory.class); logger.info(ReportConstants.RUN_SEPARATOR); if (detectToolFilter.shouldInclude(DetectTool.DOCKER)) { logger.info("Will include the docker tool."); ToolRunner toolRunner = new ToolRunner(eventSystem, detectorFactory.createDockerDetector(detectorEnvironment)); toolRunner.run(runResult); logger.info("Docker actions finished."); } else { logger.info("Docker tool will not be run."); } logger.info(ReportConstants.RUN_SEPARATOR); if (detectToolFilter.shouldInclude(DetectTool.BAZEL)) { logger.info("Will include the bazel tool."); ToolRunner toolRunner = new ToolRunner(eventSystem, detectorFactory.createBazelDetector(detectorEnvironment)); toolRunner.run(runResult); logger.info("Bazel actions finished."); } else { logger.info("Bazel tool will not be run."); } logger.info(ReportConstants.RUN_SEPARATOR); if (detectToolFilter.shouldInclude(DetectTool.DETECTOR)) { logger.info("Will include the detector tool."); final String projectBomTool = detectConfiguration.getProperty(DetectProperty.DETECT_PROJECT_DETECTOR, PropertyAuthority.None); final SearchOptions searchOptions = detectConfigurationFactory.createSearchOptions(directoryManager.getSourceDirectory()); final DetectorTool detectorTool = new DetectorTool(detectContext); final DetectorToolResult detectorToolResult = detectorTool.performDetectors(searchOptions, projectBomTool); runResult.addToolNameVersionIfPresent(DetectTool.DETECTOR, detectorToolResult.bomToolProjectNameVersion); runResult.addDetectCodeLocations(detectorToolResult.bomToolCodeLocations); runResult.addApplicableDetectors(detectorToolResult.applicableDetectorTypes); if (detectorToolResult.failedDetectorTypes.size() > 0) { eventSystem.publishEvent(Event.ExitCode, new ExitCodeRequest(ExitCodeType.FAILURE_DETECTOR, "A detector failed.")); } logger.info("Detector actions finished."); } else { logger.info("Detector tool will not be run."); } logger.info(ReportConstants.RUN_SEPARATOR); logger.info("Completed code location tools."); logger.info("Determining project info."); final ProjectNameVersionOptions projectNameVersionOptions = detectConfigurationFactory.createProjectNameVersionOptions(directoryManager.getSourceDirectory().getName()); final ProjectNameVersionDecider projectNameVersionDecider = new ProjectNameVersionDecider(projectNameVersionOptions); final NameVersion projectNameVersion = projectNameVersionDecider.decideProjectNameVersion(runOptions.getPreferredTools(), runResult.getDetectToolProjectInfo()); logger.info("Project name: " + projectNameVersion.getName()); logger.info("Project version: " + projectNameVersion.getVersion()); Optional<ProjectVersionWrapper> projectVersionWrapper = Optional.empty(); if (connectivityManager.isDetectOnline() && connectivityManager.getBlackDuckServicesFactory().isPresent()) { final BlackDuckServicesFactory blackDuckServicesFactory = connectivityManager.getBlackDuckServicesFactory().get(); logger.info("Getting or creating project."); final DetectProjectServiceOptions options = detectConfigurationFactory.createDetectProjectServiceOptions(); final DetectProjectMappingService detectProjectMappingService = new DetectProjectMappingService(blackDuckServicesFactory.createBlackDuckService()); final DetectProjectService detectProjectService = new DetectProjectService(blackDuckServicesFactory, options, detectProjectMappingService); projectVersionWrapper = Optional.of(detectProjectService.createOrUpdateHubProject(projectNameVersion, options.getApplicationId())); if (projectVersionWrapper.isPresent() && runOptions.shouldUnmapCodeLocations()) { logger.info("Unmapping code locations."); final DetectCodeLocationUnmapService detectCodeLocationUnmapService = new DetectCodeLocationUnmapService(blackDuckServicesFactory.createBlackDuckService(), blackDuckServicesFactory.createCodeLocationService()); detectCodeLocationUnmapService.unmapCodeLocations(projectVersionWrapper.get().getProjectVersionView()); } else { logger.debug("Will not unmap code locations: Project view was not present, or should not unmap code locations."); } } else { logger.debug("Detect is not online, and will not create the project."); } logger.info("Completed project and version actions."); logger.info("Processing Detect Code Locations."); final CodeLocationWaitData codeLocationWaitData = new CodeLocationWaitData(); final BdioManager bdioManager = new BdioManager(detectInfo, new SimpleBdioFactory(), new IntegrationEscapeUtil(), codeLocationNameManager, detectConfiguration, bdioCodeLocationCreator, directoryManager, eventSystem); final BdioResult bdioResult = bdioManager.createBdioFiles(runOptions.getAggregateName(), projectNameVersion, runResult.getDetectCodeLocations()); if (bdioResult.getUploadTargets().size() > 0) { logger.info("Created " + bdioResult.getUploadTargets().size() + " BDIO files."); bdioResult.getUploadTargets().forEach(it -> eventSystem.publishEvent(Event.OutputFileOfInterest, it.getUploadFile())); if (connectivityManager.isDetectOnline() && connectivityManager.getBlackDuckServicesFactory().isPresent()) { logger.info("Uploading BDIO files."); final BlackDuckServicesFactory blackDuckServicesFactory = connectivityManager.getBlackDuckServicesFactory().get(); final DetectBdioUploadService detectBdioUploadService = new DetectBdioUploadService(detectConfiguration, blackDuckServicesFactory.createBdioUploadService(), eventSystem); final CodeLocationCreationData<UploadBatchOutput> uploadBatchOutputCodeLocationCreationData = detectBdioUploadService.uploadBdioFiles(bdioResult.getUploadTargets()); codeLocationWaitData.setFromBdioCodeLocationCreationData(uploadBatchOutputCodeLocationCreationData); } } else { logger.debug("Did not create any BDIO files."); } logger.info("Completed Detect Code Location processing."); logger.info(ReportConstants.RUN_SEPARATOR); if (detectToolFilter.shouldInclude(DetectTool.SIGNATURE_SCAN)) { logger.info("Will include the signature scanner tool."); final BlackDuckSignatureScannerOptions blackDuckSignatureScannerOptions = detectConfigurationFactory.createBlackDuckSignatureScannerOptions(); final BlackDuckSignatureScannerTool blackDuckSignatureScannerTool = new BlackDuckSignatureScannerTool(blackDuckSignatureScannerOptions, detectContext); final SignatureScannerToolResult signatureScannerToolResult = blackDuckSignatureScannerTool.runScanTool(projectNameVersion, runResult.getDockerTar()); if (signatureScannerToolResult.getResult() == Result.SUCCESS && signatureScannerToolResult.getCreationData().isPresent()) { codeLocationWaitData.setFromSignatureScannerCodeLocationCreationData(signatureScannerToolResult.getCreationData().get()); } logger.info("Signature scanner actions finished."); } else { logger.info("Signature scan tool will not be run."); } logger.info(ReportConstants.RUN_SEPARATOR); if (detectToolFilter.shouldInclude(DetectTool.BINARY_SCAN)) { logger.info("Will include the binary scanner tool."); if (connectivityManager.isDetectOnline() && connectivityManager.getBlackDuckServicesFactory().isPresent()) { final BlackDuckServicesFactory blackDuckServicesFactory = connectivityManager.getBlackDuckServicesFactory().get(); final BlackDuckBinaryScannerTool blackDuckBinaryScanner = new BlackDuckBinaryScannerTool(eventSystem, codeLocationNameManager, detectConfiguration, blackDuckServicesFactory); BinaryScanToolResult result = blackDuckBinaryScanner.performBinaryScanActions(projectNameVersion); if (result.isSuccessful()) { codeLocationWaitData.setFromBinaryScan(result.getNotificationTaskRange(), result.getCodeLocationNames()); } } logger.info("Binary scanner actions finished."); } else { logger.info("Binary scan tool will not be run."); } logger.info(ReportConstants.RUN_SEPARATOR); if (projectVersionWrapper.isPresent() && connectivityManager.isDetectOnline() && connectivityManager.getBlackDuckServicesFactory().isPresent()) { final BlackDuckServicesFactory blackDuckServicesFactory = connectivityManager.getBlackDuckServicesFactory().get(); logger.info("Will perform Black Duck post actions."); final BlackduckReportOptions blackduckReportOptions = detectConfigurationFactory.createReportOptions(); final PolicyCheckOptions policyCheckOptions = detectConfigurationFactory.createPolicyCheckOptions(); final long timeoutInSeconds = detectConfigurationFactory.getTimeoutInSeconds(); final BlackduckPostActions blackduckPostActions = new BlackduckPostActions(blackDuckServicesFactory, eventSystem); blackduckPostActions.perform(blackduckReportOptions, policyCheckOptions, codeLocationWaitData, projectVersionWrapper.get(), timeoutInSeconds); final boolean hasAtLeastOneBdio = !bdioResult.getUploadTargets().isEmpty(); final boolean shouldHaveScanned = detectToolFilter.shouldInclude(DetectTool.SIGNATURE_SCAN); if (hasAtLeastOneBdio || shouldHaveScanned) { final Optional<String> componentsLink = projectVersionWrapper.get().getProjectVersionView().getFirstLink(ProjectVersionView.COMPONENTS_LINK); if (componentsLink.isPresent()) { logger.info(String.format("To see your results, follow the URL: %s", componentsLink.get())); } } logger.info("Black Duck actions have finished."); } else { logger.debug("Will not perform post actions: Detect is not online."); } } else { logger.info("Black Duck tools will NOT be run."); } if (runDecision.willRunPolaris()) { logger.info(ReportConstants.RUN_SEPARATOR); if (detectToolFilter.shouldInclude(DetectTool.POLARIS)) { logger.info("Will include the Polaris tool."); final PolarisTool polarisTool = new PolarisTool(eventSystem, directoryManager, new ExecutableRunner(), connectionManager, detectConfiguration); polarisTool.runPolaris(new Slf4jIntLogger(logger), directoryManager.getSourceDirectory()); logger.info("Polaris actions finished."); } else { logger.info("Polaris CLI tool will not be run."); } } else { logger.info("Polaris tools will NOT be run."); } logger.info("All tools have finished."); logger.info(ReportConstants.RUN_SEPARATOR); return runResult; }
public RunResult run(RunDecision runDecision) throws DetectUserFriendlyException, InterruptedException, IntegrationException { final DetectConfiguration detectConfiguration = detectContext.getBean(DetectConfiguration.class); final DetectConfigurationFactory detectConfigurationFactory = detectContext.getBean(DetectConfigurationFactory.class); final DirectoryManager directoryManager = detectContext.getBean(DirectoryManager.class); final EventSystem eventSystem = detectContext.getBean(EventSystem.class); final CodeLocationNameManager codeLocationNameManager = detectContext.getBean(CodeLocationNameManager.class); final BdioCodeLocationCreator bdioCodeLocationCreator = detectContext.getBean(BdioCodeLocationCreator.class); final ConnectionManager connectionManager = detectContext.getBean(ConnectionManager.class); final DetectInfo detectInfo = detectContext.getBean(DetectInfo.class); final RunResult runResult = new RunResult(); final RunOptions runOptions = detectConfigurationFactory.createRunOptions(); final DetectToolFilter detectToolFilter = runOptions.getDetectToolFilter(); if (runDecision.willRunBlackduck()) { logger.info("Black Duck tools will run."); final ConnectivityManager connectivityManager = detectContext.getBean(ConnectivityManager.class); if (connectivityManager.getPhoneHomeManager().isPresent()) { connectivityManager.getPhoneHomeManager().get().startPhoneHome(); } DetectorEnvironment detectorEnvironment = new DetectorEnvironment(directoryManager.getSourceDirectory(), Collections.emptySet(), 0, null, false); DetectorFactory detectorFactory = detectContext.getBean(DetectorFactory.class); logger.info(ReportConstants.RUN_SEPARATOR); if (detectToolFilter.shouldInclude(DetectTool.DOCKER)) { logger.info("Will include the docker tool."); ToolRunner toolRunner = new ToolRunner(eventSystem, detectorFactory.createDockerDetector(detectorEnvironment)); toolRunner.run(runResult); logger.info("Docker actions finished."); } else { logger.info("Docker tool will not be run."); } logger.info(ReportConstants.RUN_SEPARATOR); if (detectToolFilter.shouldInclude(DetectTool.BAZEL)) { logger.info("Will include the bazel tool."); ToolRunner toolRunner = new ToolRunner(eventSystem, detectorFactory.createBazelDetector(detectorEnvironment)); toolRunner.run(runResult); logger.info("Bazel actions finished."); } else { logger.info("Bazel tool will not be run."); } logger.info(ReportConstants.RUN_SEPARATOR); if (detectToolFilter.shouldInclude(DetectTool.DETECTOR)) { logger.info("Will include the detector tool."); final String projectBomTool = detectConfiguration.getProperty(DetectProperty.DETECT_PROJECT_DETECTOR, PropertyAuthority.None); final SearchOptions searchOptions = detectConfigurationFactory.createSearchOptions(directoryManager.getSourceDirectory()); final DetectorTool detectorTool = new DetectorTool(detectContext); final DetectorToolResult detectorToolResult = detectorTool.performDetectors(searchOptions, projectBomTool); runResult.addToolNameVersionIfPresent(DetectTool.DETECTOR, detectorToolResult.bomToolProjectNameVersion); runResult.addDetectCodeLocations(detectorToolResult.bomToolCodeLocations); runResult.addApplicableDetectors(detectorToolResult.applicableDetectorTypes); if (detectorToolResult.failedDetectorTypes.size() > 0) { eventSystem.publishEvent(Event.ExitCode, new ExitCodeRequest(ExitCodeType.FAILURE_DETECTOR, "A detector failed.")); } logger.info("Detector actions finished."); } else { logger.info("Detector tool will not be run."); } logger.info(ReportConstants.RUN_SEPARATOR); logger.info("Completed code location tools."); logger.info("Determining project info."); final ProjectNameVersionOptions projectNameVersionOptions = detectConfigurationFactory.createProjectNameVersionOptions(directoryManager.getSourceDirectory().getName()); final ProjectNameVersionDecider projectNameVersionDecider = new ProjectNameVersionDecider(projectNameVersionOptions); final NameVersion projectNameVersion = projectNameVersionDecider.decideProjectNameVersion(runOptions.getPreferredTools(), runResult.getDetectToolProjectInfo()); logger.info("Project name: " + projectNameVersion.getName()); logger.info("Project version: " + projectNameVersion.getVersion()); Optional<ProjectVersionWrapper> projectVersionWrapper = Optional.empty(); if (connectivityManager.isDetectOnline() && connectivityManager.getBlackDuckServicesFactory().isPresent()) { final BlackDuckServicesFactory blackDuckServicesFactory = connectivityManager.getBlackDuckServicesFactory().get(); logger.info("Getting or creating project."); final DetectProjectServiceOptions options = detectConfigurationFactory.createDetectProjectServiceOptions(); final DetectProjectMappingService detectProjectMappingService = new DetectProjectMappingService(blackDuckServicesFactory.createBlackDuckService()); final DetectProjectService detectProjectService = new DetectProjectService(blackDuckServicesFactory, options, detectProjectMappingService); projectVersionWrapper = Optional.of(detectProjectService.createOrUpdateHubProject(projectNameVersion, options.getApplicationId())); if (projectVersionWrapper.isPresent() && runOptions.shouldUnmapCodeLocations()) { logger.info("Unmapping code locations."); final DetectCodeLocationUnmapService detectCodeLocationUnmapService = new DetectCodeLocationUnmapService(blackDuckServicesFactory.createBlackDuckService(), blackDuckServicesFactory.createCodeLocationService()); detectCodeLocationUnmapService.unmapCodeLocations(projectVersionWrapper.get().getProjectVersionView()); } else { logger.debug("Will not unmap code locations: Project view was not present, or should not unmap code locations."); } } else { logger.debug("Detect is not online, and will not create the project."); } logger.info("Completed project and version actions."); logger.info("Processing Detect Code Locations."); final CodeLocationWaitData codeLocationWaitData = new CodeLocationWaitData(); final BdioManager bdioManager = new BdioManager(detectInfo, new SimpleBdioFactory(), new IntegrationEscapeUtil(), codeLocationNameManager, detectConfiguration, bdioCodeLocationCreator, directoryManager, eventSystem); final BdioResult bdioResult = bdioManager.createBdioFiles(runOptions.getAggregateName(), projectNameVersion, runResult.getDetectCodeLocations()); if (bdioResult.getUploadTargets().size() > 0) { logger.info("Created " + bdioResult.getUploadTargets().size() + " BDIO files."); bdioResult.getUploadTargets().forEach(it -> eventSystem.publishEvent(Event.OutputFileOfInterest, it.getUploadFile())); if (connectivityManager.isDetectOnline() && connectivityManager.getBlackDuckServicesFactory().isPresent()) { logger.info("Uploading BDIO files."); final BlackDuckServicesFactory blackDuckServicesFactory = connectivityManager.getBlackDuckServicesFactory().get(); final DetectBdioUploadService detectBdioUploadService = new DetectBdioUploadService(detectConfiguration, blackDuckServicesFactory.createBdioUploadService(), eventSystem); final CodeLocationCreationData<UploadBatchOutput> uploadBatchOutputCodeLocationCreationData = detectBdioUploadService.uploadBdioFiles(bdioResult.getUploadTargets()); codeLocationWaitData.setFromBdioCodeLocationCreationData(uploadBatchOutputCodeLocationCreationData); } } else { logger.debug("Did not create any BDIO files."); } logger.info("Completed Detect Code Location processing."); logger.info(ReportConstants.RUN_SEPARATOR); if (detectToolFilter.shouldInclude(DetectTool.SIGNATURE_SCAN)) { logger.info("Will include the signature scanner tool."); final BlackDuckSignatureScannerOptions blackDuckSignatureScannerOptions = detectConfigurationFactory.createBlackDuckSignatureScannerOptions(); final BlackDuckSignatureScannerTool blackDuckSignatureScannerTool = new BlackDuckSignatureScannerTool(blackDuckSignatureScannerOptions, detectContext); final SignatureScannerToolResult signatureScannerToolResult = blackDuckSignatureScannerTool.runScanTool(projectNameVersion, runResult.getDockerTar()); if (signatureScannerToolResult.getResult() == Result.SUCCESS && signatureScannerToolResult.getCreationData().isPresent()) { codeLocationWaitData.setFromSignatureScannerCodeLocationCreationData(signatureScannerToolResult.getCreationData().get()); } logger.info("Signature scanner actions finished."); } else { logger.info("Signature scan tool will not be run."); } logger.info(ReportConstants.RUN_SEPARATOR); if (detectToolFilter.shouldInclude(DetectTool.BINARY_SCAN)) { logger.info("Will include the binary scanner tool."); if (connectivityManager.isDetectOnline() && connectivityManager.getBlackDuckServicesFactory().isPresent()) { final BlackDuckServicesFactory blackDuckServicesFactory = connectivityManager.getBlackDuckServicesFactory().get(); final BlackDuckBinaryScannerTool blackDuckBinaryScanner = new BlackDuckBinaryScannerTool(eventSystem, codeLocationNameManager, detectConfiguration, blackDuckServicesFactory); BinaryScanToolResult result = blackDuckBinaryScanner.performBinaryScanActions(projectNameVersion); if (result.isSuccessful()) { codeLocationWaitData.setFromBinaryScan(result.getNotificationTaskRange(), result.getCodeLocationNames()); } } logger.info("Binary scanner actions finished."); } else { logger.info("Binary scan tool will not be run."); } logger.info(ReportConstants.RUN_SEPARATOR); if (projectVersionWrapper.isPresent() && connectivityManager.isDetectOnline() && connectivityManager.getBlackDuckServicesFactory().isPresent()) { final BlackDuckServicesFactory blackDuckServicesFactory = connectivityManager.getBlackDuckServicesFactory().get(); logger.info("Will perform Black Duck post actions."); final BlackduckReportOptions blackduckReportOptions = detectConfigurationFactory.createReportOptions(); final PolicyCheckOptions policyCheckOptions = detectConfigurationFactory.createPolicyCheckOptions(); final long timeoutInSeconds = detectConfigurationFactory.getTimeoutInSeconds(); final BlackduckPostActions blackduckPostActions = new BlackduckPostActions(blackDuckServicesFactory, eventSystem); blackduckPostActions.perform(blackduckReportOptions, policyCheckOptions, codeLocationWaitData, projectVersionWrapper.get(), timeoutInSeconds); final boolean hasAtLeastOneBdio = !bdioResult.getUploadTargets().isEmpty(); final boolean shouldHaveScanned = detectToolFilter.shouldInclude(DetectTool.SIGNATURE_SCAN); if (hasAtLeastOneBdio || shouldHaveScanned) { final Optional<String> componentsLink = projectVersionWrapper.get().getProjectVersionView().getFirstLink(ProjectVersionView.COMPONENTS_LINK); if (componentsLink.isPresent()) { logger.info(String.format("To see your results, follow the URL: %s", componentsLink.get())); } } logger.info("Black Duck actions have finished."); } else { logger.debug("Will not perform post actions: Detect is not online."); } } else { logger.info("Black Duck tools will NOT be run."); } if (runDecision.willRunPolaris()) { logger.info(ReportConstants.RUN_SEPARATOR); if (detectToolFilter.shouldInclude(DetectTool.POLARIS)) { logger.info("Will include the Polaris tool."); final PolarisTool polarisTool = new PolarisTool(eventSystem, directoryManager, new ExecutableRunner(), connectionManager, detectConfiguration); polarisTool.runPolaris(new Slf4jIntLogger(logger), directoryManager.getSourceDirectory()); logger.info("Polaris actions finished."); } else { logger.info("Polaris CLI tool will not be run."); } } else { logger.info("Polaris tools will NOT be run."); } logger.info("All tools have finished."); logger.info(ReportConstants.RUN_SEPARATOR); return runResult; }
public runresult run(rundecision rundecision) throws detectuserfriendlyexception, interruptedexception, integrationexception { final detectconfiguration detectconfiguration = detectcontext.getbean(detectconfiguration.class); final detectconfigurationfactory detectconfigurationfactory = detectcontext.getbean(detectconfigurationfactory.class); final directorymanager directorymanager = detectcontext.getbean(directorymanager.class); final eventsystem eventsystem = detectcontext.getbean(eventsystem.class); final codelocationnamemanager codelocationnamemanager = detectcontext.getbean(codelocationnamemanager.class); final bdiocodelocationcreator bdiocodelocationcreator = detectcontext.getbean(bdiocodelocationcreator.class); final connectionmanager connectionmanager = detectcontext.getbean(connectionmanager.class); final detectinfo detectinfo = detectcontext.getbean(detectinfo.class); final runresult runresult = new runresult(); final runoptions runoptions = detectconfigurationfactory.createrunoptions(); final detecttoolfilter detecttoolfilter = runoptions.getdetecttoolfilter(); if (rundecision.willrunblackduck()) { logger.info("black duck tools will run."); final connectivitymanager connectivitymanager = detectcontext.getbean(connectivitymanager.class); if (connectivitymanager.getphonehomemanager().ispresent()) { connectivitymanager.getphonehomemanager().get().startphonehome(); } detectorenvironment detectorenvironment = new detectorenvironment(directorymanager.getsourcedirectory(), collections.emptyset(), 0, null, false); detectorfactory detectorfactory = detectcontext.getbean(detectorfactory.class); logger.info(reportconstants.run_separator); if (detecttoolfilter.shouldinclude(detecttool.docker)) { logger.info("will include the docker tool."); toolrunner toolrunner = new toolrunner(eventsystem, detectorfactory.createdockerdetector(detectorenvironment)); toolrunner.run(runresult); logger.info("docker actions finished."); } else { logger.info("docker tool will not be run."); } logger.info(reportconstants.run_separator); if (detecttoolfilter.shouldinclude(detecttool.bazel)) { logger.info("will include the bazel tool."); toolrunner toolrunner = new toolrunner(eventsystem, detectorfactory.createbazeldetector(detectorenvironment)); toolrunner.run(runresult); logger.info("bazel actions finished."); } else { logger.info("bazel tool will not be run."); } logger.info(reportconstants.run_separator); if (detecttoolfilter.shouldinclude(detecttool.detector)) { logger.info("will include the detector tool."); final string projectbomtool = detectconfiguration.getproperty(detectproperty.detect_project_detector, propertyauthority.none); final searchoptions searchoptions = detectconfigurationfactory.createsearchoptions(directorymanager.getsourcedirectory()); final detectortool detectortool = new detectortool(detectcontext); final detectortoolresult detectortoolresult = detectortool.performdetectors(searchoptions, projectbomtool); runresult.addtoolnameversionifpresent(detecttool.detector, detectortoolresult.bomtoolprojectnameversion); runresult.adddetectcodelocations(detectortoolresult.bomtoolcodelocations); runresult.addapplicabledetectors(detectortoolresult.applicabledetectortypes); if (detectortoolresult.faileddetectortypes.size() > 0) { eventsystem.publishevent(event.exitcode, new exitcoderequest(exitcodetype.failure_detector, "a detector failed.")); } logger.info("detector actions finished."); } else { logger.info("detector tool will not be run."); } logger.info(reportconstants.run_separator); logger.info("completed code location tools."); logger.info("determining project info."); final projectnameversionoptions projectnameversionoptions = detectconfigurationfactory.createprojectnameversionoptions(directorymanager.getsourcedirectory().getname()); final projectnameversiondecider projectnameversiondecider = new projectnameversiondecider(projectnameversionoptions); final nameversion projectnameversion = projectnameversiondecider.decideprojectnameversion(runoptions.getpreferredtools(), runresult.getdetecttoolprojectinfo()); logger.info("project name: " + projectnameversion.getname()); logger.info("project version: " + projectnameversion.getversion()); optional<projectversionwrapper> projectversionwrapper = optional.empty(); if (connectivitymanager.isdetectonline() && connectivitymanager.getblackduckservicesfactory().ispresent()) { final blackduckservicesfactory blackduckservicesfactory = connectivitymanager.getblackduckservicesfactory().get(); logger.info("getting or creating project."); final detectprojectserviceoptions options = detectconfigurationfactory.createdetectprojectserviceoptions(); final detectprojectmappingservice detectprojectmappingservice = new detectprojectmappingservice(blackduckservicesfactory.createblackduckservice()); final detectprojectservice detectprojectservice = new detectprojectservice(blackduckservicesfactory, options, detectprojectmappingservice); projectversionwrapper = optional.of(detectprojectservice.createorupdatehubproject(projectnameversion, options.getapplicationid())); if (projectversionwrapper.ispresent() && runoptions.shouldunmapcodelocations()) { logger.info("unmapping code locations."); final detectcodelocationunmapservice detectcodelocationunmapservice = new detectcodelocationunmapservice(blackduckservicesfactory.createblackduckservice(), blackduckservicesfactory.createcodelocationservice()); detectcodelocationunmapservice.unmapcodelocations(projectversionwrapper.get().getprojectversionview()); } else { logger.debug("will not unmap code locations: project view was not present, or should not unmap code locations."); } } else { logger.debug("detect is not online, and will not create the project."); } logger.info("completed project and version actions."); logger.info("processing detect code locations."); final codelocationwaitdata codelocationwaitdata = new codelocationwaitdata(); final bdiomanager bdiomanager = new bdiomanager(detectinfo, new simplebdiofactory(), new integrationescapeutil(), codelocationnamemanager, detectconfiguration, bdiocodelocationcreator, directorymanager, eventsystem); final bdioresult bdioresult = bdiomanager.createbdiofiles(runoptions.getaggregatename(), projectnameversion, runresult.getdetectcodelocations()); if (bdioresult.getuploadtargets().size() > 0) { logger.info("created " + bdioresult.getuploadtargets().size() + " bdio files."); bdioresult.getuploadtargets().foreach(it -> eventsystem.publishevent(event.outputfileofinterest, it.getuploadfile())); if (connectivitymanager.isdetectonline() && connectivitymanager.getblackduckservicesfactory().ispresent()) { logger.info("uploading bdio files."); final blackduckservicesfactory blackduckservicesfactory = connectivitymanager.getblackduckservicesfactory().get(); final detectbdiouploadservice detectbdiouploadservice = new detectbdiouploadservice(detectconfiguration, blackduckservicesfactory.createbdiouploadservice(), eventsystem); final codelocationcreationdata<uploadbatchoutput> uploadbatchoutputcodelocationcreationdata = detectbdiouploadservice.uploadbdiofiles(bdioresult.getuploadtargets()); codelocationwaitdata.setfrombdiocodelocationcreationdata(uploadbatchoutputcodelocationcreationdata); } } else { logger.debug("did not create any bdio files."); } logger.info("completed detect code location processing."); logger.info(reportconstants.run_separator); if (detecttoolfilter.shouldinclude(detecttool.signature_scan)) { logger.info("will include the signature scanner tool."); final blackducksignaturescanneroptions blackducksignaturescanneroptions = detectconfigurationfactory.createblackducksignaturescanneroptions(); final blackducksignaturescannertool blackducksignaturescannertool = new blackducksignaturescannertool(blackducksignaturescanneroptions, detectcontext); final signaturescannertoolresult signaturescannertoolresult = blackducksignaturescannertool.runscantool(projectnameversion, runresult.getdockertar()); if (signaturescannertoolresult.getresult() == result.success && signaturescannertoolresult.getcreationdata().ispresent()) { codelocationwaitdata.setfromsignaturescannercodelocationcreationdata(signaturescannertoolresult.getcreationdata().get()); } logger.info("signature scanner actions finished."); } else { logger.info("signature scan tool will not be run."); } logger.info(reportconstants.run_separator); if (detecttoolfilter.shouldinclude(detecttool.binary_scan)) { logger.info("will include the binary scanner tool."); if (connectivitymanager.isdetectonline() && connectivitymanager.getblackduckservicesfactory().ispresent()) { final blackduckservicesfactory blackduckservicesfactory = connectivitymanager.getblackduckservicesfactory().get(); final blackduckbinaryscannertool blackduckbinaryscanner = new blackduckbinaryscannertool(eventsystem, codelocationnamemanager, detectconfiguration, blackduckservicesfactory); binaryscantoolresult result = blackduckbinaryscanner.performbinaryscanactions(projectnameversion); if (result.issuccessful()) { codelocationwaitdata.setfrombinaryscan(result.getnotificationtaskrange(), result.getcodelocationnames()); } } logger.info("binary scanner actions finished."); } else { logger.info("binary scan tool will not be run."); } logger.info(reportconstants.run_separator); if (projectversionwrapper.ispresent() && connectivitymanager.isdetectonline() && connectivitymanager.getblackduckservicesfactory().ispresent()) { final blackduckservicesfactory blackduckservicesfactory = connectivitymanager.getblackduckservicesfactory().get(); logger.info("will perform black duck post actions."); final blackduckreportoptions blackduckreportoptions = detectconfigurationfactory.createreportoptions(); final policycheckoptions policycheckoptions = detectconfigurationfactory.createpolicycheckoptions(); final long timeoutinseconds = detectconfigurationfactory.gettimeoutinseconds(); final blackduckpostactions blackduckpostactions = new blackduckpostactions(blackduckservicesfactory, eventsystem); blackduckpostactions.perform(blackduckreportoptions, policycheckoptions, codelocationwaitdata, projectversionwrapper.get(), timeoutinseconds); final boolean hasatleastonebdio = !bdioresult.getuploadtargets().isempty(); final boolean shouldhavescanned = detecttoolfilter.shouldinclude(detecttool.signature_scan); if (hasatleastonebdio || shouldhavescanned) { final optional<string> componentslink = projectversionwrapper.get().getprojectversionview().getfirstlink(projectversionview.components_link); if (componentslink.ispresent()) { logger.info(string.format("to see your results, follow the url: %s", componentslink.get())); } } logger.info("black duck actions have finished."); } else { logger.debug("will not perform post actions: detect is not online."); } } else { logger.info("black duck tools will not be run."); } if (rundecision.willrunpolaris()) { logger.info(reportconstants.run_separator); if (detecttoolfilter.shouldinclude(detecttool.polaris)) { logger.info("will include the polaris tool."); final polaristool polaristool = new polaristool(eventsystem, directorymanager, new executablerunner(), connectionmanager, detectconfiguration); polaristool.runpolaris(new slf4jintlogger(logger), directorymanager.getsourcedirectory()); logger.info("polaris actions finished."); } else { logger.info("polaris cli tool will not be run."); } } else { logger.info("polaris tools will not be run."); } logger.info("all tools have finished."); logger.info(reportconstants.run_separator); return runresult; }
selaliadobor-wt/synopsys-detect
[ 1, 0, 0, 0 ]
18,139
public float getBending_damping() throws IOException { if ((__io__pointersize == 8)) { return __io__block.readFloat(__io__address + 160); } else { return __io__block.readFloat(__io__address + 156); } }
public float getBending_damping() throws IOException { if ((__io__pointersize == 8)) { return __io__block.readFloat(__io__address + 160); } else { return __io__block.readFloat(__io__address + 156); } }
public float getbending_damping() throws ioexception { if ((__io__pointersize == 8)) { return __io__block.readfloat(__io__address + 160); } else { return __io__block.readfloat(__io__address + 156); } }
sirivus/studioonline
[ 1, 0, 0, 0 ]
18,140
public void setBending_damping(float bending_damping) throws IOException { if ((__io__pointersize == 8)) { __io__block.writeFloat(__io__address + 160, bending_damping); } else { __io__block.writeFloat(__io__address + 156, bending_damping); } }
public void setBending_damping(float bending_damping) throws IOException { if ((__io__pointersize == 8)) { __io__block.writeFloat(__io__address + 160, bending_damping); } else { __io__block.writeFloat(__io__address + 156, bending_damping); } }
public void setbending_damping(float bending_damping) throws ioexception { if ((__io__pointersize == 8)) { __io__block.writefloat(__io__address + 160, bending_damping); } else { __io__block.writefloat(__io__address + 156, bending_damping); } }
sirivus/studioonline
[ 1, 0, 0, 0 ]
18,263
public static <T> VectorModel minimize(LossDefinition<T> lossDefinition, Collection<Observation<T>> observations, int dimensionality, double learningRate, int numRepetitions, double minStepSize) { final Random random = new Random(); // Repeat the optimization multiple times and keep the best model. VectorModel bestModel = null; double bestLoss = Double.NaN; for (int repetition = 0; repetition < numRepetitions; repetition++) { logger.info("Performing repetition {}/{}.", repetition + 1, numRepetitions); // Generate an initial model. final double[] parameters = new double[dimensionality]; for (int dimension = 0; dimension < parameters.length; dimension++) { parameters[dimension] = random.nextGaussian() * 10; // TODO: It might be important to allow a meaningful customization of the initial weights. } final VectorModel model = new VectorModel(parameters); // Repeatedly go against the gradient until convergence. double stepSize; double lastLoss = Double.NaN; long nextLogMillis = System.currentTimeMillis() + 30_000L; long round = 1L; do { // Calculate the gradient of the current model. final double[] gradient = lossDefinition.calculateGradient(model, observations); // Update the model and calculate the width of the update step. for (int i = 0; i < gradient.length; i++) { gradient[i] *= -learningRate; } model.add(gradient); stepSize = calculateEuclidianDistance(gradient); // Adapt the learning rate (Bold Driver): // If we we are getting better, increase the learning rate by 5%. Otherwise, decrease it by 50%. double loss = lossDefinition.calculateLoss(model, observations); if (!Double.isNaN(lastLoss)) { if (lastLoss >= loss) learningRate *= 1.05; else learningRate *= .5; } lastLoss = loss; if (System.currentTimeMillis() >= nextLogMillis) { logger.info("Current loss after {} rounds: {}", round, loss); nextLogMillis += 30_000L; } round++; } while (stepSize > minStepSize); // Update the best model. double loss = lossDefinition.calculateLoss(model, observations); logger.info("Final loss after {} rounds: {}", round, loss); if (bestModel == null || bestLoss < loss) { bestModel = model; bestLoss = loss; } } return bestModel; }
public static <T> VectorModel minimize(LossDefinition<T> lossDefinition, Collection<Observation<T>> observations, int dimensionality, double learningRate, int numRepetitions, double minStepSize) { final Random random = new Random(); VectorModel bestModel = null; double bestLoss = Double.NaN; for (int repetition = 0; repetition < numRepetitions; repetition++) { logger.info("Performing repetition {}/{}.", repetition + 1, numRepetitions); final double[] parameters = new double[dimensionality]; for (int dimension = 0; dimension < parameters.length; dimension++) { parameters[dimension] = random.nextGaussian() * 10; } final VectorModel model = new VectorModel(parameters); double stepSize; double lastLoss = Double.NaN; long nextLogMillis = System.currentTimeMillis() + 30_000L; long round = 1L; do { final double[] gradient = lossDefinition.calculateGradient(model, observations); for (int i = 0; i < gradient.length; i++) { gradient[i] *= -learningRate; } model.add(gradient); stepSize = calculateEuclidianDistance(gradient); double loss = lossDefinition.calculateLoss(model, observations); if (!Double.isNaN(lastLoss)) { if (lastLoss >= loss) learningRate *= 1.05; else learningRate *= .5; } lastLoss = loss; if (System.currentTimeMillis() >= nextLogMillis) { logger.info("Current loss after {} rounds: {}", round, loss); nextLogMillis += 30_000L; } round++; } while (stepSize > minStepSize); double loss = lossDefinition.calculateLoss(model, observations); logger.info("Final loss after {} rounds: {}", round, loss); if (bestModel == null || bestLoss < loss) { bestModel = model; bestLoss = loss; } } return bestModel; }
public static <t> vectormodel minimize(lossdefinition<t> lossdefinition, collection<observation<t>> observations, int dimensionality, double learningrate, int numrepetitions, double minstepsize) { final random random = new random(); vectormodel bestmodel = null; double bestloss = double.nan; for (int repetition = 0; repetition < numrepetitions; repetition++) { logger.info("performing repetition {}/{}.", repetition + 1, numrepetitions); final double[] parameters = new double[dimensionality]; for (int dimension = 0; dimension < parameters.length; dimension++) { parameters[dimension] = random.nextgaussian() * 10; } final vectormodel model = new vectormodel(parameters); double stepsize; double lastloss = double.nan; long nextlogmillis = system.currenttimemillis() + 30_000l; long round = 1l; do { final double[] gradient = lossdefinition.calculategradient(model, observations); for (int i = 0; i < gradient.length; i++) { gradient[i] *= -learningrate; } model.add(gradient); stepsize = calculateeuclidiandistance(gradient); double loss = lossdefinition.calculateloss(model, observations); if (!double.isnan(lastloss)) { if (lastloss >= loss) learningrate *= 1.05; else learningrate *= .5; } lastloss = loss; if (system.currenttimemillis() >= nextlogmillis) { logger.info("current loss after {} rounds: {}", round, loss); nextlogmillis += 30_000l; } round++; } while (stepsize > minstepsize); double loss = lossdefinition.calculateloss(model, observations); logger.info("final loss after {} rounds: {}", round, loss); if (bestmodel == null || bestloss < loss) { bestmodel = model; bestloss = loss; } } return bestmodel; }
stratosphere/metadata-store
[ 1, 0, 0, 0 ]
18,305
public Session getSession(String sessionId) { // TODO lock sessions to prevent fetching an expired session? Session session = sessions.get(sessionId); if (session == null) { String msg = String.format("Session: %s does not exist.", sessionId); LOG.error(msg); throw new SqlGatewayException(msg); } session.touch(); return session; }
public Session getSession(String sessionId) { Session session = sessions.get(sessionId); if (session == null) { String msg = String.format("Session: %s does not exist.", sessionId); LOG.error(msg); throw new SqlGatewayException(msg); } session.touch(); return session; }
public session getsession(string sessionid) { session session = sessions.get(sessionid); if (session == null) { string msg = string.format("session: %s does not exist.", sessionid); log.error(msg); throw new sqlgatewayexception(msg); } session.touch(); return session; }
romainr/flink-sql-gateway
[ 0, 1, 0, 0 ]
34,775
public void sendHandshakeRecord(TlsHandshakeMessage handshakeMessage) { TlsPlaintextRecord record = new TlsPlaintextRecord(TlsConstants.HANDSHAKE, version); TlsHandshakeFragment fragment = new HandshakeFragment(handshakeMessage); record.setFragment(fragment); byte[] encoded = record.encode(); ByteBuffer buffer = ByteBuffer.wrap(encoded); connectionManager.write(buffer, new CompletionHandler<Integer, ConnectionManager>() { @Override public void completed(Integer result, ConnectionManager attachment) { // Nothing to do here } @Override public void failed(Throwable exc, ConnectionManager attachment) { // TODO handle sending errors back to handshake engine. Callback? connectionManager.close(); } }); }
public void sendHandshakeRecord(TlsHandshakeMessage handshakeMessage) { TlsPlaintextRecord record = new TlsPlaintextRecord(TlsConstants.HANDSHAKE, version); TlsHandshakeFragment fragment = new HandshakeFragment(handshakeMessage); record.setFragment(fragment); byte[] encoded = record.encode(); ByteBuffer buffer = ByteBuffer.wrap(encoded); connectionManager.write(buffer, new CompletionHandler<Integer, ConnectionManager>() { @Override public void completed(Integer result, ConnectionManager attachment) { } @Override public void failed(Throwable exc, ConnectionManager attachment) { connectionManager.close(); } }); }
public void sendhandshakerecord(tlshandshakemessage handshakemessage) { tlsplaintextrecord record = new tlsplaintextrecord(tlsconstants.handshake, version); tlshandshakefragment fragment = new handshakefragment(handshakemessage); record.setfragment(fragment); byte[] encoded = record.encode(); bytebuffer buffer = bytebuffer.wrap(encoded); connectionmanager.write(buffer, new completionhandler<integer, connectionmanager>() { @override public void completed(integer result, connectionmanager attachment) { } @override public void failed(throwable exc, connectionmanager attachment) { connectionmanager.close(); } }); }
swbrenneis/secomm-tls-java
[ 0, 1, 0, 0 ]
34,776
public void sendAlertRecord(AlertFragment alertFragment) { TlsPlaintextRecord record = new TlsPlaintextRecord(TlsConstants.ALERT, version); record.setFragment(alertFragment); byte[] encoded = record.encode(); ByteBuffer buffer = ByteBuffer.wrap(encoded); connectionManager.write(buffer, new CompletionHandler<Integer, ConnectionManager>() { @Override public void completed(Integer result, ConnectionManager attachment) { } @Override public void failed(Throwable exc, ConnectionManager attachment) { // TODO handle sending errors back to handshake engine. Callback? connectionManager.close(); } }); }
public void sendAlertRecord(AlertFragment alertFragment) { TlsPlaintextRecord record = new TlsPlaintextRecord(TlsConstants.ALERT, version); record.setFragment(alertFragment); byte[] encoded = record.encode(); ByteBuffer buffer = ByteBuffer.wrap(encoded); connectionManager.write(buffer, new CompletionHandler<Integer, ConnectionManager>() { @Override public void completed(Integer result, ConnectionManager attachment) { } @Override public void failed(Throwable exc, ConnectionManager attachment) { connectionManager.close(); } }); }
public void sendalertrecord(alertfragment alertfragment) { tlsplaintextrecord record = new tlsplaintextrecord(tlsconstants.alert, version); record.setfragment(alertfragment); byte[] encoded = record.encode(); bytebuffer buffer = bytebuffer.wrap(encoded); connectionmanager.write(buffer, new completionhandler<integer, connectionmanager>() { @override public void completed(integer result, connectionmanager attachment) { } @override public void failed(throwable exc, connectionmanager attachment) { connectionmanager.close(); } }); }
swbrenneis/secomm-tls-java
[ 0, 1, 0, 0 ]
2,041
public String getPrimaryKeyColumn(String tableName) { // FIXME: Currently working for PostgreSQL only if (this.dbSystem.equals("POSTGRESQL")) { String sqlPrimaryKey = "SELECT a.attname FROM pg_index i JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey) WHERE i.indrelid = '" + tableName + "'::regclass AND i.indisprimary;"; return (String) findSingletonValue(sqlPrimaryKey); } else // TODO: Handle other JDBC sources return null; }
public String getPrimaryKeyColumn(String tableName) { if (this.dbSystem.equals("POSTGRESQL")) { String sqlPrimaryKey = "SELECT a.attname FROM pg_index i JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey) WHERE i.indrelid = '" + tableName + "'::regclass AND i.indisprimary;"; return (String) findSingletonValue(sqlPrimaryKey); } else return null; }
public string getprimarykeycolumn(string tablename) { if (this.dbsystem.equals("postgresql")) { string sqlprimarykey = "select a.attname from pg_index i join pg_attribute a on a.attrelid = i.indrelid and a.attnum = any(i.indkey) where i.indrelid = '" + tablename + "'::regclass and i.indisprimary;"; return (string) findsingletonvalue(sqlprimarykey); } else return null; }
smartdatalake/simsearch
[ 1, 1, 0, 0 ]
18,449
public static BufferedImage getPDFPageImage(File pdfFile, int pageNumber) throws Exception { PDDocument document = null; BufferedImage pageImage = null; try { document = PDDocument.load(pdfFile); if (document.isEncrypted()) { throw new Exception("Cannot read an encrypted PDF file."); } // TODO: what is this code for? /* PDPageTree pages = document.getPages(); PDPage page = pages.get(pageNumber - 1); if (page.getContents() != null) { PDResources resources = page.getResources(); Iterable<COSName> names = resources.getXObjectNames(); for (COSName name : names) { PDXObject xobj = resources.getXObject(name); if (xobj instanceof PDImageXObject) { PDImageXObject ximage = (PDImageXObject) xobj; BufferedImage bi = ximage.getImage(); if (bi.getType() <= 0) { BufferedImage bi2 = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_RGB); bi2.getGraphics().drawImage(bi, 0, 0, null); return bi2; } return bi; } } } */ PDFRenderer pdfRenderer = new PDFRenderer(document); pageImage = pdfRenderer.renderImageWithDPI(pageNumber - 1, 400); } catch (Exception e) { if (document != null) { document.close(); } throw e; } if (document != null) { document.close(); } return pageImage; }
public static BufferedImage getPDFPageImage(File pdfFile, int pageNumber) throws Exception { PDDocument document = null; BufferedImage pageImage = null; try { document = PDDocument.load(pdfFile); if (document.isEncrypted()) { throw new Exception("Cannot read an encrypted PDF file."); } PDFRenderer pdfRenderer = new PDFRenderer(document); pageImage = pdfRenderer.renderImageWithDPI(pageNumber - 1, 400); } catch (Exception e) { if (document != null) { document.close(); } throw e; } if (document != null) { document.close(); } return pageImage; }
public static bufferedimage getpdfpageimage(file pdffile, int pagenumber) throws exception { pddocument document = null; bufferedimage pageimage = null; try { document = pddocument.load(pdffile); if (document.isencrypted()) { throw new exception("cannot read an encrypted pdf file."); } pdfrenderer pdfrenderer = new pdfrenderer(document); pageimage = pdfrenderer.renderimagewithdpi(pagenumber - 1, 400); } catch (exception e) { if (document != null) { document.close(); } throw e; } if (document != null) { document.close(); } return pageimage; }
rquast/formreturn
[ 0, 0, 0, 0 ]
10,298
@Override public void close() { // Stop the thread. interrupt(); // After the interrupt, the run() method will stop Tun2Socks, and then complete. // We need to wait until that is finished before closing the TUN device. try { join(); } catch (InterruptedException e) { // This is weird: the calling thread has _also_ been interrupted. LogWrapper.report(e); } try { tunFd.close(); } catch (IOException e) { LogWrapper.report(e); } }
@Override public void close() { interrupt(); try { join(); } catch (InterruptedException e) { LogWrapper.report(e); } try { tunFd.close(); } catch (IOException e) { LogWrapper.report(e); } }
@override public void close() { interrupt(); try { join(); } catch (interruptedexception e) { logwrapper.report(e); } try { tunfd.close(); } catch (ioexception e) { logwrapper.report(e); } }
superhero75/Intra
[ 0, 0, 1, 0 ]
10,520
@Override public Builder setPath(Path absolutePath, Path ideallyRelative) throws IOException { // TODO(plamenko): this check should not be necessary, but otherwise some tests fail due to // FileHashLoader throwing NoSuchFileException which doesn't get correctly propagated. if (inputSizeLimit != Long.MAX_VALUE) { sizeLimiter.add(fileHashLoader.getSize(absolutePath)); } super.setPath(absolutePath, ideallyRelative); return this; }
@Override public Builder setPath(Path absolutePath, Path ideallyRelative) throws IOException { if (inputSizeLimit != Long.MAX_VALUE) { sizeLimiter.add(fileHashLoader.getSize(absolutePath)); } super.setPath(absolutePath, ideallyRelative); return this; }
@override public builder setpath(path absolutepath, path ideallyrelative) throws ioexception { if (inputsizelimit != long.max_value) { sizelimiter.add(filehashloader.getsize(absolutepath)); } super.setpath(absolutepath, ideallyrelative); return this; }
stefb965/buck
[ 0, 0, 1, 0 ]
18,792
@Test public void testallocateContainerDistributesAllocation() throws Exception { /* This is a lame test, we should really be testing something like z-score or make sure that we don't have 3sigma kind of events. Too lazy to write all that code. This test very lamely tests if we have more than 5 separate nodes from the list of 10 datanodes that got allocated a container. */ Set<UUID> pipelineList = new TreeSet<>(); for (int x = 0; x < 30; x++) { ContainerInfo containerInfo = containerManager.allocateContainer( replicationType, replicationFactor, OzoneConsts.OZONE); Assert.assertNotNull(containerInfo); Assert.assertNotNull(containerInfo.getPipelineID()); pipelineList.add(pipelineManager.getPipeline( containerInfo.getPipelineID()).getFirstNode() .getUuid()); } Assert.assertTrue(pipelineList.size() >= 1); }
@Test public void testallocateContainerDistributesAllocation() throws Exception { Set<UUID> pipelineList = new TreeSet<>(); for (int x = 0; x < 30; x++) { ContainerInfo containerInfo = containerManager.allocateContainer( replicationType, replicationFactor, OzoneConsts.OZONE); Assert.assertNotNull(containerInfo); Assert.assertNotNull(containerInfo.getPipelineID()); pipelineList.add(pipelineManager.getPipeline( containerInfo.getPipelineID()).getFirstNode() .getUuid()); } Assert.assertTrue(pipelineList.size() >= 1); }
@test public void testallocatecontainerdistributesallocation() throws exception { set<uuid> pipelinelist = new treeset<>(); for (int x = 0; x < 30; x++) { containerinfo containerinfo = containermanager.allocatecontainer( replicationtype, replicationfactor, ozoneconsts.ozone); assert.assertnotnull(containerinfo); assert.assertnotnull(containerinfo.getpipelineid()); pipelinelist.add(pipelinemanager.getpipeline( containerinfo.getpipelineid()).getfirstnode() .getuuid()); } assert.asserttrue(pipelinelist.size() >= 1); }
smengcl/hadoop-ozone
[ 1, 0, 0, 0 ]
10,608
@BeforeClass public static void createInput() throws IOException { // TODO: set up your sample input object here. input = null; }
@BeforeClass public static void createInput() throws IOException { input = null; }
@beforeclass public static void createinput() throws ioexception { input = null; }
rt-di/usageserver
[ 0, 1, 0, 0 ]
18,984
private void newNoMatchStopsRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newNoMatchStopsRadioButtonActionPerformed // TODO change text on button to add updateStopCategory(gtfsUploadNoConflict, 0); dontuploadAllBtn.setEnabled(true); }
private void newNoMatchStopsRadioButtonActionPerformed(java.awt.event.ActionEvent evt) { updateStopCategory(gtfsUploadNoConflict, 0); dontuploadAllBtn.setEnabled(true); }
private void newnomatchstopsradiobuttonactionperformed(java.awt.event.actionevent evt) { updatestopcategory(gtfsuploadnoconflict, 0); dontuploadallbtn.setenabled(true); }
reubot/gtfs-osm-sync
[ 0, 1, 0, 0 ]
19,409
private static int offsetToLine(String text, int offset) { return offsetToLine(text, 0, offset); }
private static int offsetToLine(String text, int offset) { return offsetToLine(text, 0, offset); }
private static int offsettoline(string text, int offset) { return offsettoline(text, 0, offset); }
sylviawan/oop_assignment1
[ 1, 0, 0, 0 ]
19,410
private static int offsetToLine(String text, int start, int offset) { int line = 0; while (offset >= start) { offset = text.lastIndexOf('\n', offset-1); line++; } return line - 1; }
private static int offsetToLine(String text, int start, int offset) { int line = 0; while (offset >= start) { offset = text.lastIndexOf('\n', offset-1); line++; } return line - 1; }
private static int offsettoline(string text, int start, int offset) { int line = 0; while (offset >= start) { offset = text.lastindexof('\n', offset-1); line++; } return line - 1; }
sylviawan/oop_assignment1
[ 1, 0, 0, 0 ]
19,420
@Test(dataProvider = "collectionsAndVersion") public void testIteration(CollectionOp op, ProtocolVersion version) throws IOException { Map<String, String> dataIn = new HashMap<>(); dataIn.put("aKey", "aValue"); dataIn.put("bKey", "bValue"); RemoteCache<Object, Object> cacheToUse; RemoteCacheManager temporaryManager; if (version != ProtocolVersion.DEFAULT_PROTOCOL_VERSION) { String servers = HotRodClientTestingUtil.getServersString(hotrodServers); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); // Set the version on the manager to connect with clientBuilder.version(version); clientBuilder.addServers(servers); temporaryManager = new RemoteCacheManager(clientBuilder.build()); cacheToUse = temporaryManager.getCache(); } else { temporaryManager = null; cacheToUse = remoteCache; } try { // putAll doesn't work in older versions (so we use new client) - that is a different issue completely remoteCache.putAll(dataIn); CloseableIteratorCollection<?> collection = op.function.apply(cacheToUse); // If we don't support it we should get an exception if (version.compareTo(op.minimumVersionForIteration()) < 0) { Exceptions.expectException(UnsupportedOperationException.class, () -> { try (CloseableIterator<?> iter = collection.iterator()) { } }); } else { try (CloseableIterator<?> iter = collection.iterator()) { assertTrue(iter.hasNext()); assertNotNull(iter.next()); assertTrue(iter.hasNext()); } } } finally { if (temporaryManager != null) { temporaryManager.close(); } } }
@Test(dataProvider = "collectionsAndVersion") public void testIteration(CollectionOp op, ProtocolVersion version) throws IOException { Map<String, String> dataIn = new HashMap<>(); dataIn.put("aKey", "aValue"); dataIn.put("bKey", "bValue"); RemoteCache<Object, Object> cacheToUse; RemoteCacheManager temporaryManager; if (version != ProtocolVersion.DEFAULT_PROTOCOL_VERSION) { String servers = HotRodClientTestingUtil.getServersString(hotrodServers); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.version(version); clientBuilder.addServers(servers); temporaryManager = new RemoteCacheManager(clientBuilder.build()); cacheToUse = temporaryManager.getCache(); } else { temporaryManager = null; cacheToUse = remoteCache; } try { remoteCache.putAll(dataIn); CloseableIteratorCollection<?> collection = op.function.apply(cacheToUse); if (version.compareTo(op.minimumVersionForIteration()) < 0) { Exceptions.expectException(UnsupportedOperationException.class, () -> { try (CloseableIterator<?> iter = collection.iterator()) { } }); } else { try (CloseableIterator<?> iter = collection.iterator()) { assertTrue(iter.hasNext()); assertNotNull(iter.next()); assertTrue(iter.hasNext()); } } } finally { if (temporaryManager != null) { temporaryManager.close(); } } }
@test(dataprovider = "collectionsandversion") public void testiteration(collectionop op, protocolversion version) throws ioexception { map<string, string> datain = new hashmap<>(); datain.put("akey", "avalue"); datain.put("bkey", "bvalue"); remotecache<object, object> cachetouse; remotecachemanager temporarymanager; if (version != protocolversion.default_protocol_version) { string servers = hotrodclienttestingutil.getserversstring(hotrodservers); org.infinispan.client.hotrod.configuration.configurationbuilder clientbuilder = new org.infinispan.client.hotrod.configuration.configurationbuilder(); clientbuilder.version(version); clientbuilder.addservers(servers); temporarymanager = new remotecachemanager(clientbuilder.build()); cachetouse = temporarymanager.getcache(); } else { temporarymanager = null; cachetouse = remotecache; } try { remotecache.putall(datain); closeableiteratorcollection<?> collection = op.function.apply(cachetouse); if (version.compareto(op.minimumversionforiteration()) < 0) { exceptions.expectexception(unsupportedoperationexception.class, () -> { try (closeableiterator<?> iter = collection.iterator()) { } }); } else { try (closeableiterator<?> iter = collection.iterator()) { asserttrue(iter.hasnext()); assertnotnull(iter.next()); asserttrue(iter.hasnext()); } } } finally { if (temporarymanager != null) { temporarymanager.close(); } } }
shawkins/infinispan-1
[ 0, 0, 1, 0 ]
11,310
public static int insertWMFromFile(String species, String wmname, String wmversion, String wmtype, String wmfile) throws SQLException, NotFoundException, UnknownRoleException, FileNotFoundException, ParseException, IOException { WeightMatrix matrix; System.err.println("name " + wmname + " version " + wmversion + " type " + wmtype); if (wmtype.matches(".*TAMO.*")) { matrix = PWMParser.readTamoMatrix(wmfile); } else if (wmtype.matches(".*MEME.*")) { matrix = PWMParser.readMemeMatrix(wmfile); } else if (wmtype.matches(".*SEQ.*")) { matrix = PWMParser.readAlignedSequenceMatrix(wmfile); } else if (wmtype.matches(".*TRANSFAC.*")) { //TODO add a method to read a single transfac matrix matrix = PWMParser.readTRANSFACFreqMatrices(wmfile, wmversion).get(0); } else if (wmtype.matches(".*PRIORITY.*")) { matrix = PWMParser.parsePriorityBestOutput(wmfile); } else if (wmtype.matches(".*UniProbe.*")) { matrix = PWMParser.readUniProbeFile(wmfile); } else if (wmtype.toUpperCase().matches(".*GIMME.*")) { matrix = PWMParser.readGimmeMotifsMatrices(wmfile,wmversion,wmtype).get(0); } else { System.err.println("Didn't see a program I recognize in the type. defaulting to reading TAMO format"); matrix = PWMParser.readTamoMatrix(wmfile); } matrix.name = wmname; matrix.version = wmversion; matrix.type = wmtype; matrix.speciesid = (new Species(species)).getDBID(); return insertMatrixIntoDB(matrix); }
public static int insertWMFromFile(String species, String wmname, String wmversion, String wmtype, String wmfile) throws SQLException, NotFoundException, UnknownRoleException, FileNotFoundException, ParseException, IOException { WeightMatrix matrix; System.err.println("name " + wmname + " version " + wmversion + " type " + wmtype); if (wmtype.matches(".*TAMO.*")) { matrix = PWMParser.readTamoMatrix(wmfile); } else if (wmtype.matches(".*MEME.*")) { matrix = PWMParser.readMemeMatrix(wmfile); } else if (wmtype.matches(".*SEQ.*")) { matrix = PWMParser.readAlignedSequenceMatrix(wmfile); } else if (wmtype.matches(".*TRANSFAC.*")) { matrix = PWMParser.readTRANSFACFreqMatrices(wmfile, wmversion).get(0); } else if (wmtype.matches(".*PRIORITY.*")) { matrix = PWMParser.parsePriorityBestOutput(wmfile); } else if (wmtype.matches(".*UniProbe.*")) { matrix = PWMParser.readUniProbeFile(wmfile); } else if (wmtype.toUpperCase().matches(".*GIMME.*")) { matrix = PWMParser.readGimmeMotifsMatrices(wmfile,wmversion,wmtype).get(0); } else { System.err.println("Didn't see a program I recognize in the type. defaulting to reading TAMO format"); matrix = PWMParser.readTamoMatrix(wmfile); } matrix.name = wmname; matrix.version = wmversion; matrix.type = wmtype; matrix.speciesid = (new Species(species)).getDBID(); return insertMatrixIntoDB(matrix); }
public static int insertwmfromfile(string species, string wmname, string wmversion, string wmtype, string wmfile) throws sqlexception, notfoundexception, unknownroleexception, filenotfoundexception, parseexception, ioexception { weightmatrix matrix; system.err.println("name " + wmname + " version " + wmversion + " type " + wmtype); if (wmtype.matches(".*tamo.*")) { matrix = pwmparser.readtamomatrix(wmfile); } else if (wmtype.matches(".*meme.*")) { matrix = pwmparser.readmemematrix(wmfile); } else if (wmtype.matches(".*seq.*")) { matrix = pwmparser.readalignedsequencematrix(wmfile); } else if (wmtype.matches(".*transfac.*")) { matrix = pwmparser.readtransfacfreqmatrices(wmfile, wmversion).get(0); } else if (wmtype.matches(".*priority.*")) { matrix = pwmparser.parseprioritybestoutput(wmfile); } else if (wmtype.matches(".*uniprobe.*")) { matrix = pwmparser.readuniprobefile(wmfile); } else if (wmtype.touppercase().matches(".*gimme.*")) { matrix = pwmparser.readgimmemotifsmatrices(wmfile,wmversion,wmtype).get(0); } else { system.err.println("didn't see a program i recognize in the type. defaulting to reading tamo format"); matrix = pwmparser.readtamomatrix(wmfile); } matrix.name = wmname; matrix.version = wmversion; matrix.type = wmtype; matrix.speciesid = (new species(species)).getdbid(); return insertmatrixintodb(matrix); }
seqcode/seqcode-core
[ 0, 1, 0, 0 ]
11,311
public static int insertWMFromFile(String species, String wmname, String wmversion, String wmtype, String wmfile, String bgFreq) throws SQLException, NotFoundException, UnknownRoleException, FileNotFoundException, ParseException, IOException { WeightMatrix matrix; if (wmtype.matches(".*TAMO.*")) { matrix = PWMParser.readTamoMatrix(wmfile); } else if (wmtype.matches(".*MEME.*")) { matrix = PWMParser.readMemeMatrix(wmfile); } else if (wmtype.matches(".*SEQ.*")) { matrix = PWMParser.readAlignedSequenceMatrix(wmfile); } else if (wmtype.matches(".*TRANSFAC.*")) { //TODO add a method to read a single transfac matrix matrix = PWMParser.readTRANSFACFreqMatrices(wmfile, wmversion).get(0); } else if (wmtype.matches(".*PRIORITY.*")) { matrix = PWMParser.parsePriorityBestOutput(wmfile); } else if (wmtype.toUpperCase().matches(".*GIMME.*")) { matrix = PWMParser.readGimmeMotifsMatrices(wmfile,wmversion,wmtype).get(0); } else { System.err.println("Didn't see a program I recognize in the type. defaulting to reading TAMO format"); matrix = PWMParser.readTamoMatrix(wmfile); } matrix.name = wmname; matrix.version = wmversion; matrix.type = wmtype; matrix.speciesid = (new Species(species)).getDBID(); return insertMatrixIntoDB(matrix); }
public static int insertWMFromFile(String species, String wmname, String wmversion, String wmtype, String wmfile, String bgFreq) throws SQLException, NotFoundException, UnknownRoleException, FileNotFoundException, ParseException, IOException { WeightMatrix matrix; if (wmtype.matches(".*TAMO.*")) { matrix = PWMParser.readTamoMatrix(wmfile); } else if (wmtype.matches(".*MEME.*")) { matrix = PWMParser.readMemeMatrix(wmfile); } else if (wmtype.matches(".*SEQ.*")) { matrix = PWMParser.readAlignedSequenceMatrix(wmfile); } else if (wmtype.matches(".*TRANSFAC.*")) { matrix = PWMParser.readTRANSFACFreqMatrices(wmfile, wmversion).get(0); } else if (wmtype.matches(".*PRIORITY.*")) { matrix = PWMParser.parsePriorityBestOutput(wmfile); } else if (wmtype.toUpperCase().matches(".*GIMME.*")) { matrix = PWMParser.readGimmeMotifsMatrices(wmfile,wmversion,wmtype).get(0); } else { System.err.println("Didn't see a program I recognize in the type. defaulting to reading TAMO format"); matrix = PWMParser.readTamoMatrix(wmfile); } matrix.name = wmname; matrix.version = wmversion; matrix.type = wmtype; matrix.speciesid = (new Species(species)).getDBID(); return insertMatrixIntoDB(matrix); }
public static int insertwmfromfile(string species, string wmname, string wmversion, string wmtype, string wmfile, string bgfreq) throws sqlexception, notfoundexception, unknownroleexception, filenotfoundexception, parseexception, ioexception { weightmatrix matrix; if (wmtype.matches(".*tamo.*")) { matrix = pwmparser.readtamomatrix(wmfile); } else if (wmtype.matches(".*meme.*")) { matrix = pwmparser.readmemematrix(wmfile); } else if (wmtype.matches(".*seq.*")) { matrix = pwmparser.readalignedsequencematrix(wmfile); } else if (wmtype.matches(".*transfac.*")) { matrix = pwmparser.readtransfacfreqmatrices(wmfile, wmversion).get(0); } else if (wmtype.matches(".*priority.*")) { matrix = pwmparser.parseprioritybestoutput(wmfile); } else if (wmtype.touppercase().matches(".*gimme.*")) { matrix = pwmparser.readgimmemotifsmatrices(wmfile,wmversion,wmtype).get(0); } else { system.err.println("didn't see a program i recognize in the type. defaulting to reading tamo format"); matrix = pwmparser.readtamomatrix(wmfile); } matrix.name = wmname; matrix.version = wmversion; matrix.type = wmtype; matrix.speciesid = (new species(species)).getdbid(); return insertmatrixintodb(matrix); }
seqcode/seqcode-core
[ 0, 1, 0, 0 ]
19,634
@Override public MergerToken createSetNotNullToDb(DbEntity entity, DbAttribute column) { return new SetNotNullToDb(entity, column) { @Override public List<String> createSql(DbAdapter adapter) { /* * TODO: we generate this query as in ingres db documentation, * but unfortunately ingres don't support it */ StringBuilder sqlBuffer = new StringBuilder(); QuotingStrategy context = adapter.getQuotingStrategy(); sqlBuffer.append("ALTER TABLE "); sqlBuffer.append(getEntity().getFullyQualifiedName()); sqlBuffer.append(" ALTER COLUMN "); sqlBuffer.append(context.quotedName(getColumn())); sqlBuffer.append(" "); sqlBuffer.append(adapter.externalTypesForJdbcType(getColumn().getType())[0]); if (adapter.typeSupportsLength(getColumn().getType()) && getColumn().getMaxLength() > 0) { sqlBuffer.append("("); sqlBuffer.append(getColumn().getMaxLength()); sqlBuffer.append(")"); } sqlBuffer.append(" NOT NULL"); return Collections.singletonList(sqlBuffer.toString()); } }; }
@Override public MergerToken createSetNotNullToDb(DbEntity entity, DbAttribute column) { return new SetNotNullToDb(entity, column) { @Override public List<String> createSql(DbAdapter adapter) { StringBuilder sqlBuffer = new StringBuilder(); QuotingStrategy context = adapter.getQuotingStrategy(); sqlBuffer.append("ALTER TABLE "); sqlBuffer.append(getEntity().getFullyQualifiedName()); sqlBuffer.append(" ALTER COLUMN "); sqlBuffer.append(context.quotedName(getColumn())); sqlBuffer.append(" "); sqlBuffer.append(adapter.externalTypesForJdbcType(getColumn().getType())[0]); if (adapter.typeSupportsLength(getColumn().getType()) && getColumn().getMaxLength() > 0) { sqlBuffer.append("("); sqlBuffer.append(getColumn().getMaxLength()); sqlBuffer.append(")"); } sqlBuffer.append(" NOT NULL"); return Collections.singletonList(sqlBuffer.toString()); } }; }
@override public mergertoken createsetnotnulltodb(dbentity entity, dbattribute column) { return new setnotnulltodb(entity, column) { @override public list<string> createsql(dbadapter adapter) { stringbuilder sqlbuffer = new stringbuilder(); quotingstrategy context = adapter.getquotingstrategy(); sqlbuffer.append("alter table "); sqlbuffer.append(getentity().getfullyqualifiedname()); sqlbuffer.append(" alter column "); sqlbuffer.append(context.quotedname(getcolumn())); sqlbuffer.append(" "); sqlbuffer.append(adapter.externaltypesforjdbctype(getcolumn().gettype())[0]); if (adapter.typesupportslength(getcolumn().gettype()) && getcolumn().getmaxlength() > 0) { sqlbuffer.append("("); sqlbuffer.append(getcolumn().getmaxlength()); sqlbuffer.append(")"); } sqlbuffer.append(" not null"); return collections.singletonlist(sqlbuffer.tostring()); } }; }
rohankumardubey/cayenne
[ 0, 0, 1, 0 ]
19,696
public static CDI<Object> current() { if (INSTANCE == null) { INSTANCE = ServiceLoader.load(CDIProvider.class).iterator().next().getCDI(); } return INSTANCE; //X TODO implement! }
public static CDI<Object> current() { if (INSTANCE == null) { INSTANCE = ServiceLoader.load(CDIProvider.class).iterator().next().getCDI(); } return INSTANCE; }
public static cdi<object> current() { if (instance == null) { instance = serviceloader.load(cdiprovider.class).iterator().next().getcdi(); } return instance; }
salyh/geronimo-specs
[ 0, 1, 0, 0 ]
19,697
public static void setCDIProvider(CDIProvider provider) { //X TODO implement! if (provider == null) { INSTANCE = null; } else { INSTANCE = provider.getCDI(); } }
public static void setCDIProvider(CDIProvider provider) { if (provider == null) { INSTANCE = null; } else { INSTANCE = provider.getCDI(); } }
public static void setcdiprovider(cdiprovider provider) { if (provider == null) { instance = null; } else { instance = provider.getcdi(); } }
salyh/geronimo-specs
[ 1, 1, 0, 0 ]
19,886
@Override @Committing @PureWithSideEffects @SuppressWarnings("UseSpecificCatch") public void run() { try { final @Nonnull String address = getSocket().getInetAddress().getHostAddress(); Log.debugging("Received a request from $.", address); final @Nonnull Time start = TimeBuilder.build(); @Nullable Encryption<Signature<Compression<Pack>>> encryptedMethod = null; @Nullable Signature<Compression<Pack>> signedMethod = null; @Nullable Method<?> method = null; @Nullable Reply<?> reply = null; try { try { final @Nonnull Pack pack = Pack.loadFrom(getSocket()); final @Nonnull Request request = pack.unpack(RequestConverter.INSTANCE, null); encryptedMethod = request.getEncryption(); final @Nullable HostIdentifier recipient = encryptedMethod.getRecipient(); if (recipient == null) { throw RequestExceptionBuilder.withCode(RequestErrorCode.RECIPIENT).withMessage("The recipient may not be null.").build(); } final @Nonnull Host host = Host.of(recipient); signedMethod = encryptedMethod.getObject(); final @Nonnull SemanticType type = signedMethod.getObject().getObject().getType(); Log.debugging("Executing the method $ on host $.", type.getAddress(), recipient); final @Nonnull InternalIdentifier subject; if (type.equals(OpenAccount.TYPE)) { subject = recipient; } else { subject = signedMethod.getSubject(); } final @Nonnull Account account = Account.with(host, subject.resolve()); method = MethodIndex.get(signedMethod, account); reply = method.executeOnHost(); Database.commit(); } catch (@Nonnull InternalException exception) { throw RequestExceptionBuilder.withCode(RequestErrorCode.INTERNAL).withMessage("An internal problem occurred.").withCause(exception).build(); } catch (@Nonnull ExternalException exception) { throw RequestExceptionBuilder.withCode(RequestErrorCode.EXTERNAL).withMessage("An external problem occurred.").withCause(exception).build(); } } catch (@Nonnull RequestException exception) { Database.rollback(); Log.warning("A request error occurred:", exception); reply = RequestExceptionReplyBuilder.withRequestException(exception.isDecoded() ? RequestExceptionBuilder.withCode(RequestErrorCode.REQUEST).withMessage("Another server responded with a request error.").withCause(exception).build() : exception).build(); } if (reply == null) { reply = EmptyReplyBuilder.build(); } final @Nonnull Compression<Pack> compressedReply = CompressionBuilder.withObject(reply.pack()).build(); // The reply.pack() statement maps the semantic type of the reply converter, which results in a concurrent update if the client unpacks the response with the same database. The following commit prevents this. However, it is a suboptimal fix for this problem. try { Database.commit(); } catch (@Nonnull DatabaseException exception) { Database.rollback(); } final @Nonnull Signature<Compression<Pack>> signedReply; if (encryptedMethod != null && signedMethod != null) { signedReply = HostSignatureCreator.sign(compressedReply, CompressionConverterBuilder.withObjectConverter(PackConverter.INSTANCE).build()).about(signedMethod.getSubject()).as(encryptedMethod.getRecipient()); } else { signedReply = SignatureBuilder.withObjectConverter(CompressionConverterBuilder.withObjectConverter(PackConverter.INSTANCE).build()).withObject(compressedReply).withSubject(HostIdentifier.DIGITALID).build(); } final @Nonnull Encryption<Signature<Compression<Pack>>> encryptedReply; if (encryptedMethod instanceof RequestEncryption) { encryptedReply = ResponseEncryptionBuilder.withObject(signedReply).withSymmetricKey(((RequestEncryption) encryptedMethod).getSymmetricKey()).build(); } else { encryptedReply = EncryptionBuilder.withObject(signedReply).build(); } final @Nonnull Response response = ResponseBuilder.withEncryption(encryptedReply).build(); response.pack().storeTo(getSocket()); Log.information(method + " from " + address + " handled in " + start.ago().getValue() + " ms."); } catch (@Nonnull NetworkException exception) { Log.warning("Could not send a response.", exception); } catch (@Nonnull Throwable throwable) { Log.warning("Something went wrong.", throwable); } finally { try { if (!getSocket().isClosed()) { getSocket().close(); } } catch (@Nonnull IOException exception) { Log.warning("Could not close the socket.", exception); } } }
@Override @Committing @PureWithSideEffects @SuppressWarnings("UseSpecificCatch") public void run() { try { final @Nonnull String address = getSocket().getInetAddress().getHostAddress(); Log.debugging("Received a request from $.", address); final @Nonnull Time start = TimeBuilder.build(); @Nullable Encryption<Signature<Compression<Pack>>> encryptedMethod = null; @Nullable Signature<Compression<Pack>> signedMethod = null; @Nullable Method<?> method = null; @Nullable Reply<?> reply = null; try { try { final @Nonnull Pack pack = Pack.loadFrom(getSocket()); final @Nonnull Request request = pack.unpack(RequestConverter.INSTANCE, null); encryptedMethod = request.getEncryption(); final @Nullable HostIdentifier recipient = encryptedMethod.getRecipient(); if (recipient == null) { throw RequestExceptionBuilder.withCode(RequestErrorCode.RECIPIENT).withMessage("The recipient may not be null.").build(); } final @Nonnull Host host = Host.of(recipient); signedMethod = encryptedMethod.getObject(); final @Nonnull SemanticType type = signedMethod.getObject().getObject().getType(); Log.debugging("Executing the method $ on host $.", type.getAddress(), recipient); final @Nonnull InternalIdentifier subject; if (type.equals(OpenAccount.TYPE)) { subject = recipient; } else { subject = signedMethod.getSubject(); } final @Nonnull Account account = Account.with(host, subject.resolve()); method = MethodIndex.get(signedMethod, account); reply = method.executeOnHost(); Database.commit(); } catch (@Nonnull InternalException exception) { throw RequestExceptionBuilder.withCode(RequestErrorCode.INTERNAL).withMessage("An internal problem occurred.").withCause(exception).build(); } catch (@Nonnull ExternalException exception) { throw RequestExceptionBuilder.withCode(RequestErrorCode.EXTERNAL).withMessage("An external problem occurred.").withCause(exception).build(); } } catch (@Nonnull RequestException exception) { Database.rollback(); Log.warning("A request error occurred:", exception); reply = RequestExceptionReplyBuilder.withRequestException(exception.isDecoded() ? RequestExceptionBuilder.withCode(RequestErrorCode.REQUEST).withMessage("Another server responded with a request error.").withCause(exception).build() : exception).build(); } if (reply == null) { reply = EmptyReplyBuilder.build(); } final @Nonnull Compression<Pack> compressedReply = CompressionBuilder.withObject(reply.pack()).build(); try { Database.commit(); } catch (@Nonnull DatabaseException exception) { Database.rollback(); } final @Nonnull Signature<Compression<Pack>> signedReply; if (encryptedMethod != null && signedMethod != null) { signedReply = HostSignatureCreator.sign(compressedReply, CompressionConverterBuilder.withObjectConverter(PackConverter.INSTANCE).build()).about(signedMethod.getSubject()).as(encryptedMethod.getRecipient()); } else { signedReply = SignatureBuilder.withObjectConverter(CompressionConverterBuilder.withObjectConverter(PackConverter.INSTANCE).build()).withObject(compressedReply).withSubject(HostIdentifier.DIGITALID).build(); } final @Nonnull Encryption<Signature<Compression<Pack>>> encryptedReply; if (encryptedMethod instanceof RequestEncryption) { encryptedReply = ResponseEncryptionBuilder.withObject(signedReply).withSymmetricKey(((RequestEncryption) encryptedMethod).getSymmetricKey()).build(); } else { encryptedReply = EncryptionBuilder.withObject(signedReply).build(); } final @Nonnull Response response = ResponseBuilder.withEncryption(encryptedReply).build(); response.pack().storeTo(getSocket()); Log.information(method + " from " + address + " handled in " + start.ago().getValue() + " ms."); } catch (@Nonnull NetworkException exception) { Log.warning("Could not send a response.", exception); } catch (@Nonnull Throwable throwable) { Log.warning("Something went wrong.", throwable); } finally { try { if (!getSocket().isClosed()) { getSocket().close(); } } catch (@Nonnull IOException exception) { Log.warning("Could not close the socket.", exception); } } }
@override @committing @purewithsideeffects @suppresswarnings("usespecificcatch") public void run() { try { final @nonnull string address = getsocket().getinetaddress().gethostaddress(); log.debugging("received a request from $.", address); final @nonnull time start = timebuilder.build(); @nullable encryption<signature<compression<pack>>> encryptedmethod = null; @nullable signature<compression<pack>> signedmethod = null; @nullable method<?> method = null; @nullable reply<?> reply = null; try { try { final @nonnull pack pack = pack.loadfrom(getsocket()); final @nonnull request request = pack.unpack(requestconverter.instance, null); encryptedmethod = request.getencryption(); final @nullable hostidentifier recipient = encryptedmethod.getrecipient(); if (recipient == null) { throw requestexceptionbuilder.withcode(requesterrorcode.recipient).withmessage("the recipient may not be null.").build(); } final @nonnull host host = host.of(recipient); signedmethod = encryptedmethod.getobject(); final @nonnull semantictype type = signedmethod.getobject().getobject().gettype(); log.debugging("executing the method $ on host $.", type.getaddress(), recipient); final @nonnull internalidentifier subject; if (type.equals(openaccount.type)) { subject = recipient; } else { subject = signedmethod.getsubject(); } final @nonnull account account = account.with(host, subject.resolve()); method = methodindex.get(signedmethod, account); reply = method.executeonhost(); database.commit(); } catch (@nonnull internalexception exception) { throw requestexceptionbuilder.withcode(requesterrorcode.internal).withmessage("an internal problem occurred.").withcause(exception).build(); } catch (@nonnull externalexception exception) { throw requestexceptionbuilder.withcode(requesterrorcode.external).withmessage("an external problem occurred.").withcause(exception).build(); } } catch (@nonnull requestexception exception) { database.rollback(); log.warning("a request error occurred:", exception); reply = requestexceptionreplybuilder.withrequestexception(exception.isdecoded() ? requestexceptionbuilder.withcode(requesterrorcode.request).withmessage("another server responded with a request error.").withcause(exception).build() : exception).build(); } if (reply == null) { reply = emptyreplybuilder.build(); } final @nonnull compression<pack> compressedreply = compressionbuilder.withobject(reply.pack()).build(); try { database.commit(); } catch (@nonnull databaseexception exception) { database.rollback(); } final @nonnull signature<compression<pack>> signedreply; if (encryptedmethod != null && signedmethod != null) { signedreply = hostsignaturecreator.sign(compressedreply, compressionconverterbuilder.withobjectconverter(packconverter.instance).build()).about(signedmethod.getsubject()).as(encryptedmethod.getrecipient()); } else { signedreply = signaturebuilder.withobjectconverter(compressionconverterbuilder.withobjectconverter(packconverter.instance).build()).withobject(compressedreply).withsubject(hostidentifier.digitalid).build(); } final @nonnull encryption<signature<compression<pack>>> encryptedreply; if (encryptedmethod instanceof requestencryption) { encryptedreply = responseencryptionbuilder.withobject(signedreply).withsymmetrickey(((requestencryption) encryptedmethod).getsymmetrickey()).build(); } else { encryptedreply = encryptionbuilder.withobject(signedreply).build(); } final @nonnull response response = responsebuilder.withencryption(encryptedreply).build(); response.pack().storeto(getsocket()); log.information(method + " from " + address + " handled in " + start.ago().getvalue() + " ms."); } catch (@nonnull networkexception exception) { log.warning("could not send a response.", exception); } catch (@nonnull throwable throwable) { log.warning("something went wrong.", throwable); } finally { try { if (!getsocket().isclosed()) { getsocket().close(); } } catch (@nonnull ioexception exception) { log.warning("could not close the socket.", exception); } } }
stephaniestroka/digitalid-core
[ 1, 0, 0, 0 ]
3,591
public static void popupManager(final View view, final SoundObject soundObject){ // Declare PopupMenu and assign it to the design created in longclick.xml PopupMenu popup = new PopupMenu(view.getContext(), view); popup.getMenuInflater().inflate(R.menu.longclick, popup.getMenu()); // Handle user clicks on the popupmenu popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { // Check if the user wants to share a sound or set a sound as system audio if (item.getItemId() == R.id.action_send || item.getItemId() == R.id.action_ringtone){ // Define a filename on the given information from the SoundObject AND add the .mp3 tag to it final String fileName = soundObject.getItemName() + ".mp3"; // Get the path to the users external storage File storage = Environment.getExternalStorageDirectory(); // Define the directory path to the soundboard apps folder // Change my_soundboard to whatever you want as your folder but keep the slash // TODO: When changing the path be sure to also modify the path in filepaths.xml (res/xml/filepaths.xml) File directory = new File(storage.getAbsolutePath() + "/my_soundboard/"); // Creates the directory if it doesn't exist // mkdirs() gives back a boolean. You can use it to do some processes as well but we don't really need it. directory.mkdirs(); // Finally define the file by giving over the directory and the filename final File file = new File(directory, fileName); // Define an InputStream that will read the data from your sound-raw.mp3 file into a buffer InputStream in = view.getContext().getResources().openRawResource(soundObject.getItemID()); try{ // Log the name of the sound that is being saved Log.i(LOG_TAG, "Saving sound " + soundObject.getItemName()); // Define an OutputStream/FileOutputStream that will write the buffer data into the sound.mp3 on the external storage OutputStream out = new FileOutputStream(file); // Define a buffer of 1kb (you can make it a little bit bigger but 1kb will be adequate) byte[] buffer = new byte[1024]; int len; // Write the data to the sound.mp3 file while reading it from the sound-raw.mp3 // if (int) InputStream.read() returns -1 stream is at the end of file while ((len = in.read(buffer, 0, buffer.length)) != -1){ out.write(buffer, 0 , len); } // Close both streams in.close(); out.close(); } catch (IOException e){ // Log error if process failed Log.e(LOG_TAG, "Failed to save file: " + e.getMessage()); } // Send a sound via WhatsApp or the like if (item.getItemId() == R.id.action_send){ try{ // Check if the users device Android version is 5.1 or higher // If it is you'll have to use FileProvider to get the sharing function to work properly if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1){ final String AUTHORITY = view.getContext().getPackageName() + ".fileprovider"; Uri contentUri = FileProvider.getUriForFile(view.getContext(), AUTHORITY, file); final Intent shareIntent = new Intent(Intent.ACTION_SEND); final Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_STREAM, contentUri); // Define the intent to be of type audio/mp3 intent.setType("audio/mp3"); // Start a new chooser dialog where the user can choose an app to share the sound view.getContext().startActivity(Intent.createChooser(intent, "Share sound via...")); } else { final Intent intent = new Intent(Intent.ACTION_SEND); // Uri refers to a name or location // .parse() analyzes a given uri string and creates a Uri from it // Define a "link" (Uri) to the saved file Uri fileUri = Uri.parse(file.getAbsolutePath()); intent.putExtra(Intent.EXTRA_STREAM, fileUri); // Define the intent to be of type audio/mp3 intent.setType("audio/mp3"); // Start a new chooser dialog where the user can choose an app to share the sound view.getContext().startActivity(Intent.createChooser(intent, "Share sound via...")); } } catch (Exception e){ // Log error if process failed Log.e(LOG_TAG, "Failed to share sound: " + e.getMessage()); } } // Save as ringtone, alarm or notification // if (item.getItemId() == R.id.action_ringtone) { // // // Create a little popup like dialog that gives the user the choice between the 3 types // // THEME_HOLO_LIGHT was deprecated in API 23 but to support older APIs you should use it // AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext(), AlertDialog.THEME_HOLO_LIGHT); // builder.setTitle("Save as..."); // builder.setItems(new CharSequence[]{"Ringtone", "Notification", "Alarm"}, new DialogInterface.OnClickListener(){ // // @Override // public void onClick(DialogInterface dialog, int which){ // // // Decide on the users choice which information will be send to a method that handles the settings for all kinds of system audio //// switch (which) { //// //// // Ringtone //// case 0: //// changeSystemAudio(context, RingtoneManager.TYPE_RINGTONE, file); //// break; //// // Notification //// case 1: //// changeSystemAudio(context, RingtoneManager.TYPE_NOTIFICATION, file); //// break; //// // Alarmton //// case 2: //// changeSystemAudio(context, RingtoneManager.TYPE_ALARM, file); //// break; //// default: //// } // } // }); // builder.create(); // builder.show(); // } } // Add sound to favorites / Remove sound from favorites // if (item.getItemId() == R.id.action_favorite) { // // DatabaseHandler databaseHandler = DatabaseHandler // .getInstance(context.getApplicationContext()); // // // Identify the current activity // if (context instanceof FavoriteActivity) { // databaseHandler.removeFavorite(context, soundObject); // } else { // databaseHandler.addFavorite(soundObject); // } // } return true; } }); popup.show(); }
public static void popupManager(final View view, final SoundObject soundObject){ PopupMenu popup = new PopupMenu(view.getContext(), view); popup.getMenuInflater().inflate(R.menu.longclick, popup.getMenu()); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.action_send || item.getItemId() == R.id.action_ringtone){ final String fileName = soundObject.getItemName() + ".mp3"; File storage = Environment.getExternalStorageDirectory(); File directory = new File(storage.getAbsolutePath() + "/my_soundboard/"); directory.mkdirs(); final File file = new File(directory, fileName); InputStream in = view.getContext().getResources().openRawResource(soundObject.getItemID()); try{ Log.i(LOG_TAG, "Saving sound " + soundObject.getItemName()); OutputStream out = new FileOutputStream(file); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer, 0, buffer.length)) != -1){ out.write(buffer, 0 , len); } in.close(); out.close(); } catch (IOException e){ Log.e(LOG_TAG, "Failed to save file: " + e.getMessage()); } if (item.getItemId() == R.id.action_send){ try{ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1){ final String AUTHORITY = view.getContext().getPackageName() + ".fileprovider"; Uri contentUri = FileProvider.getUriForFile(view.getContext(), AUTHORITY, file); final Intent shareIntent = new Intent(Intent.ACTION_SEND); final Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_STREAM, contentUri); intent.setType("audio/mp3"); view.getContext().startActivity(Intent.createChooser(intent, "Share sound via...")); } else { final Intent intent = new Intent(Intent.ACTION_SEND); Uri fileUri = Uri.parse(file.getAbsolutePath()); intent.putExtra(Intent.EXTRA_STREAM, fileUri); intent.setType("audio/mp3"); view.getContext().startActivity(Intent.createChooser(intent, "Share sound via...")); } } catch (Exception e){ Log.e(LOG_TAG, "Failed to share sound: " + e.getMessage()); } } } return true; } }); popup.show(); }
public static void popupmanager(final view view, final soundobject soundobject){ popupmenu popup = new popupmenu(view.getcontext(), view); popup.getmenuinflater().inflate(r.menu.longclick, popup.getmenu()); popup.setonmenuitemclicklistener(new popupmenu.onmenuitemclicklistener() { @override public boolean onmenuitemclick(menuitem item) { if (item.getitemid() == r.id.action_send || item.getitemid() == r.id.action_ringtone){ final string filename = soundobject.getitemname() + ".mp3"; file storage = environment.getexternalstoragedirectory(); file directory = new file(storage.getabsolutepath() + "/my_soundboard/"); directory.mkdirs(); final file file = new file(directory, filename); inputstream in = view.getcontext().getresources().openrawresource(soundobject.getitemid()); try{ log.i(log_tag, "saving sound " + soundobject.getitemname()); outputstream out = new fileoutputstream(file); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer, 0, buffer.length)) != -1){ out.write(buffer, 0 , len); } in.close(); out.close(); } catch (ioexception e){ log.e(log_tag, "failed to save file: " + e.getmessage()); } if (item.getitemid() == r.id.action_send){ try{ if (build.version.sdk_int >= build.version_codes.lollipop_mr1){ final string authority = view.getcontext().getpackagename() + ".fileprovider"; uri contenturi = fileprovider.geturiforfile(view.getcontext(), authority, file); final intent shareintent = new intent(intent.action_send); final intent intent = new intent(intent.action_send); intent.putextra(intent.extra_stream, contenturi); intent.settype("audio/mp3"); view.getcontext().startactivity(intent.createchooser(intent, "share sound via...")); } else { final intent intent = new intent(intent.action_send); uri fileuri = uri.parse(file.getabsolutepath()); intent.putextra(intent.extra_stream, fileuri); intent.settype("audio/mp3"); view.getcontext().startactivity(intent.createchooser(intent, "share sound via...")); } } catch (exception e){ log.e(log_tag, "failed to share sound: " + e.getmessage()); } } } return true; } }); popup.show(); }
scubedcombd/Sacred_Games_Soundboard
[ 1, 0, 0, 0 ]
3,789
private void addNoteAsFingerMarker(byte[] dat) { final int command = dat[0] & 0xf0; final int channel = dat[0] & 0x0f; int note = dat[1]; final int velocity = dat[2]; // if (type == NOTE_ON || type == NOTE_OFF) if ((command & 0x80) == 0x80) { // only show if channel switch is on if (GuitarChannel.isChannelEnabled(chanTog, channel)) { GuitarChannel guitarchannel = GuitarChannel.get(gchannels, channel); if (command == NOTEON && velocity != 0) { printMessage(dat); guitarchannel.noteOn(note); } else /* if (command == NOTEOFF || velocity == 0) */{ guitarchannel.noteOff(note); } } // update progress slider periodically if (noteCount % 30 == 0) { // need to figure out why this doesn't work // float percent = sequencer.getTickPosition() / // sequence.getTickLength() * 100; GuitarView.getProgSlide().setValue(sequencer.getTickPosition()); // GuitarView.getProgSlide().setValueLabel(String.format("%d", // percent)); // GuitarView.myTextarea.append(String.format("%d", percent) + // "\n"); } noteCount++; } }
private void addNoteAsFingerMarker(byte[] dat) { final int command = dat[0] & 0xf0; final int channel = dat[0] & 0x0f; int note = dat[1]; final int velocity = dat[2]; if ((command & 0x80) == 0x80) { if (GuitarChannel.isChannelEnabled(chanTog, channel)) { GuitarChannel guitarchannel = GuitarChannel.get(gchannels, channel); if (command == NOTEON && velocity != 0) { printMessage(dat); guitarchannel.noteOn(note); } else{ guitarchannel.noteOff(note); } } if (noteCount % 30 == 0) { GuitarView.getProgSlide().setValue(sequencer.getTickPosition()); } noteCount++; } }
private void addnoteasfingermarker(byte[] dat) { final int command = dat[0] & 0xf0; final int channel = dat[0] & 0x0f; int note = dat[1]; final int velocity = dat[2]; if ((command & 0x80) == 0x80) { if (guitarchannel.ischannelenabled(chantog, channel)) { guitarchannel guitarchannel = guitarchannel.get(gchannels, channel); if (command == noteon && velocity != 0) { printmessage(dat); guitarchannel.noteon(note); } else{ guitarchannel.noteoff(note); } } if (notecount % 30 == 0) { guitarview.getprogslide().setvalue(sequencer.gettickposition()); } notecount++; } }
rsampson/GuitarView
[ 0, 0, 1, 0 ]
3,880
@Test public void shouldReturnExpectedResponseWhenGetRequestMadeOverSslWithTlsVersion_1_3() throws Exception { // The following is a bad practice: conditionally running this test only if 'TLSv1.3' is supported by the JDK if (new HashSet<>(asList(SslUtils.enabledProtocols())).contains(TLS_v1_3)) { makeRequestAndAssert(buildHttpClient(TLS_v1_3)); } else { assertThat(true).isTrue(); } }
@Test public void shouldReturnExpectedResponseWhenGetRequestMadeOverSslWithTlsVersion_1_3() throws Exception { if (new HashSet<>(asList(SslUtils.enabledProtocols())).contains(TLS_v1_3)) { makeRequestAndAssert(buildHttpClient(TLS_v1_3)); } else { assertThat(true).isTrue(); } }
@test public void shouldreturnexpectedresponsewhengetrequestmadeoversslwithtlsversion_1_3() throws exception { if (new hashset<>(aslist(sslutils.enabledprotocols())).contains(tls_v1_3)) { makerequestandassert(buildhttpclient(tls_v1_3)); } else { assertthat(true).istrue(); } }
rohankumardubey/stubby4j
[ 0, 0, 0, 1 ]
12,261
public void register() { if (!isRegistered) { VirtualFileManager.getInstance().addAsyncFileListener((@NotNull List<? extends VFileEvent> events) -> { for (VFileEvent event : events) { if (event instanceof VFileDeleteEvent) { // TODO run configuration icon change System.out.println("deleted : " + event.getFile()); } } return null; }, () -> {}); isRegistered = true; } }
public void register() { if (!isRegistered) { VirtualFileManager.getInstance().addAsyncFileListener((@NotNull List<? extends VFileEvent> events) -> { for (VFileEvent event : events) { if (event instanceof VFileDeleteEvent) { System.out.println("deleted : " + event.getFile()); } } return null; }, () -> {}); isRegistered = true; } }
public void register() { if (!isregistered) { virtualfilemanager.getinstance().addasyncfilelistener((@notnull list<? extends vfileevent> events) -> { for (vfileevent event : events) { if (event instanceof vfiledeleteevent) { system.out.println("deleted : " + event.getfile()); } } return null; }, () -> {}); isregistered = true; } }
soungminjoo/httpflow-intellij-plugin
[ 0, 1, 0, 0 ]
20,616
private void setBandInfo(DataChoice dataChoice, AddeImageInfo aii) { BandInfo bi = (BandInfo) dataChoice.getId(); List<BandInfo> bandInfos = (List<BandInfo>) getProperty(PROP_BANDINFO, (Object) null); boolean hasBand = true; //If this data source has been changed after we have create a display //then the possibility exists that the bandinfo contained by the incoming //data choice might not be valid. If it isn't then default to the first //one in the list if (bandInfos != null) { hasBand = bandInfos.contains(bi); if ( !hasBand) { // System.err.println("has band = " + bandInfos.contains(bi)); } if ( !hasBand && (bandInfos.size() > 0)) { bi = bandInfos.get(0); } else { //Not sure what to do here. } } aii.setBand("" + bi.getBandNumber()); aii.setUnit(bi.getPreferredUnit()); }
private void setBandInfo(DataChoice dataChoice, AddeImageInfo aii) { BandInfo bi = (BandInfo) dataChoice.getId(); List<BandInfo> bandInfos = (List<BandInfo>) getProperty(PROP_BANDINFO, (Object) null); boolean hasBand = true; if (bandInfos != null) { hasBand = bandInfos.contains(bi); if ( !hasBand) { } if ( !hasBand && (bandInfos.size() > 0)) { bi = bandInfos.get(0); } else { } } aii.setBand("" + bi.getBandNumber()); aii.setUnit(bi.getPreferredUnit()); }
private void setbandinfo(datachoice datachoice, addeimageinfo aii) { bandinfo bi = (bandinfo) datachoice.getid(); list<bandinfo> bandinfos = (list<bandinfo>) getproperty(prop_bandinfo, (object) null); boolean hasband = true; if (bandinfos != null) { hasband = bandinfos.contains(bi); if ( !hasband) { } if ( !hasband && (bandinfos.size() > 0)) { bi = bandinfos.get(0); } else { } } aii.setband("" + bi.getbandnumber()); aii.setunit(bi.getpreferredunit()); }
slclark/IDV
[ 0, 1, 0, 0 ]
20,666
public List<DijkstraNode> getNeighbors() { // TODO // Check if on edge of map - breaks if we're on the pixel right next // to the edge. List<DijkstraNode> neighborNodeList = new ArrayList<DijkstraNode>(); Coordinate currentCoordinate = this.getPosition(); int currentX = currentCoordinate.getX(); int currentY = currentCoordinate.getY(); // since we're on a grid, treat our graph as such and determine neighbors like that Coordinate coordinateLeft = new Coordinate(currentX - 1, currentY); Coordinate coordinateUpLeft = new Coordinate(currentX - 1, currentY + 1); Coordinate coordinateUp = new Coordinate(currentX, currentY + 1); Coordinate coordinateUpRight = new Coordinate(currentX + 1, currentY + 1); Coordinate coordinateRight = new Coordinate(currentX + 1, currentY); Coordinate coordinateDownRight = new Coordinate(currentX + 1, currentY - 1); Coordinate coordinateDown = new Coordinate(currentX, currentY - 1); Coordinate coordinateDownLeft = new Coordinate(currentX - 1, currentY - 1); DijkstraNode nodeLeft = new DijkstraNode(coordinateLeft); DijkstraNode nodeUpLeft = new DijkstraNode(coordinateUpLeft); DijkstraNode nodeUp = new DijkstraNode(coordinateUp); DijkstraNode nodeUpRight = new DijkstraNode(coordinateUpRight); DijkstraNode nodeRight = new DijkstraNode(coordinateRight); DijkstraNode nodeDownRight = new DijkstraNode(coordinateDownRight); DijkstraNode nodeDown = new DijkstraNode(coordinateDown); DijkstraNode nodeDownLeft = new DijkstraNode(coordinateDownLeft); neighborNodeList.add(nodeLeft); neighborNodeList.add(nodeUpLeft); neighborNodeList.add(nodeUp); neighborNodeList.add(nodeUpRight); neighborNodeList.add(nodeRight); neighborNodeList.add(nodeDownRight); neighborNodeList.add(nodeDown); neighborNodeList.add(nodeDownLeft); return neighborNodeList; }
public List<DijkstraNode> getNeighbors() { List<DijkstraNode> neighborNodeList = new ArrayList<DijkstraNode>(); Coordinate currentCoordinate = this.getPosition(); int currentX = currentCoordinate.getX(); int currentY = currentCoordinate.getY(); Coordinate coordinateLeft = new Coordinate(currentX - 1, currentY); Coordinate coordinateUpLeft = new Coordinate(currentX - 1, currentY + 1); Coordinate coordinateUp = new Coordinate(currentX, currentY + 1); Coordinate coordinateUpRight = new Coordinate(currentX + 1, currentY + 1); Coordinate coordinateRight = new Coordinate(currentX + 1, currentY); Coordinate coordinateDownRight = new Coordinate(currentX + 1, currentY - 1); Coordinate coordinateDown = new Coordinate(currentX, currentY - 1); Coordinate coordinateDownLeft = new Coordinate(currentX - 1, currentY - 1); DijkstraNode nodeLeft = new DijkstraNode(coordinateLeft); DijkstraNode nodeUpLeft = new DijkstraNode(coordinateUpLeft); DijkstraNode nodeUp = new DijkstraNode(coordinateUp); DijkstraNode nodeUpRight = new DijkstraNode(coordinateUpRight); DijkstraNode nodeRight = new DijkstraNode(coordinateRight); DijkstraNode nodeDownRight = new DijkstraNode(coordinateDownRight); DijkstraNode nodeDown = new DijkstraNode(coordinateDown); DijkstraNode nodeDownLeft = new DijkstraNode(coordinateDownLeft); neighborNodeList.add(nodeLeft); neighborNodeList.add(nodeUpLeft); neighborNodeList.add(nodeUp); neighborNodeList.add(nodeUpRight); neighborNodeList.add(nodeRight); neighborNodeList.add(nodeDownRight); neighborNodeList.add(nodeDown); neighborNodeList.add(nodeDownLeft); return neighborNodeList; }
public list<dijkstranode> getneighbors() { list<dijkstranode> neighbornodelist = new arraylist<dijkstranode>(); coordinate currentcoordinate = this.getposition(); int currentx = currentcoordinate.getx(); int currenty = currentcoordinate.gety(); coordinate coordinateleft = new coordinate(currentx - 1, currenty); coordinate coordinateupleft = new coordinate(currentx - 1, currenty + 1); coordinate coordinateup = new coordinate(currentx, currenty + 1); coordinate coordinateupright = new coordinate(currentx + 1, currenty + 1); coordinate coordinateright = new coordinate(currentx + 1, currenty); coordinate coordinatedownright = new coordinate(currentx + 1, currenty - 1); coordinate coordinatedown = new coordinate(currentx, currenty - 1); coordinate coordinatedownleft = new coordinate(currentx - 1, currenty - 1); dijkstranode nodeleft = new dijkstranode(coordinateleft); dijkstranode nodeupleft = new dijkstranode(coordinateupleft); dijkstranode nodeup = new dijkstranode(coordinateup); dijkstranode nodeupright = new dijkstranode(coordinateupright); dijkstranode noderight = new dijkstranode(coordinateright); dijkstranode nodedownright = new dijkstranode(coordinatedownright); dijkstranode nodedown = new dijkstranode(coordinatedown); dijkstranode nodedownleft = new dijkstranode(coordinatedownleft); neighbornodelist.add(nodeleft); neighbornodelist.add(nodeupleft); neighbornodelist.add(nodeup); neighbornodelist.add(nodeupright); neighbornodelist.add(noderight); neighbornodelist.add(nodedownright); neighbornodelist.add(nodedown); neighbornodelist.add(nodedownleft); return neighbornodelist; }
sapols/JPL-CUSeniorProjects
[ 0, 1, 0, 0 ]
12,757
protected Entry getSpreadEntry(Request request, ServiceInput dpi, Entry sample, String climstartYear, String climendYear) throws Exception { Entry sprdEntry = null; //System.err.println("Creating spread"); //String statName = "mean"; String statName = "ens01"; // per Marty hoerling - just use the spread of one member // Find the mean List<Entry> mean = findStatisticEntry(request, sample, statName); if ((mean == null) || mean.isEmpty()) { //System.err.println("Couldn't find " + statName); // TODO: Should we just exit if no mean? sprdEntry = sample; } else if (mean.size() > 1) { System.err.println("found too many"); } else { sprdEntry = mean.get(0); //System.err.println("found mean: " + sprdEntry); } //sprdEntry = sample; // Now make the spread from the mean String stail = getOutputHandler().getStorageManager().getFileTail(sprdEntry); sprdEntry = makeStatistic(request, sprdEntry, dpi, stail, "smegma", climstartYear, climendYear); return sprdEntry; }
protected Entry getSpreadEntry(Request request, ServiceInput dpi, Entry sample, String climstartYear, String climendYear) throws Exception { Entry sprdEntry = null; String statName = "ens01"; List<Entry> mean = findStatisticEntry(request, sample, statName); if ((mean == null) || mean.isEmpty()) { sprdEntry = sample; } else if (mean.size() > 1) { System.err.println("found too many"); } else { sprdEntry = mean.get(0); } String stail = getOutputHandler().getStorageManager().getFileTail(sprdEntry); sprdEntry = makeStatistic(request, sprdEntry, dpi, stail, "smegma", climstartYear, climendYear); return sprdEntry; }
protected entry getspreadentry(request request, serviceinput dpi, entry sample, string climstartyear, string climendyear) throws exception { entry sprdentry = null; string statname = "ens01"; list<entry> mean = findstatisticentry(request, sample, statname); if ((mean == null) || mean.isempty()) { sprdentry = sample; } else if (mean.size() > 1) { system.err.println("found too many"); } else { sprdentry = mean.get(0); } string stail = getoutputhandler().getstoragemanager().getfiletail(sprdentry); sprdentry = makestatistic(request, sprdentry, dpi, stail, "smegma", climstartyear, climendyear); return sprdentry; }
suvarchal/ramadda
[ 1, 0, 0, 0 ]
13,239
private static void displayExceptionPrivate(JFrame aFrame, Throwable aE) { StringWriter tempStringWriter = new StringWriter(); PrintWriter tempPrintWriter = new PrintWriter(tempStringWriter); aE.printStackTrace(tempPrintWriter); tempPrintWriter.close(); final JDialog tempDialog = new JDialog(aFrame, "Error: " + aE.getMessage()); tempDialog.setModal(true); Dimension tempScreen = Toolkit.getDefaultToolkit().getScreenSize(); tempDialog.setSize(tempScreen.width / 2, tempScreen.height / 2); tempDialog.setLocation(tempScreen.width / 4, tempScreen.height / 4); tempDialog.getContentPane().setLayout(new BorderLayout()); ScrollPane tempScrollPane = new ScrollPane(); JEditorPane tempEditorPane = new JEditorPane(); // TODO Replace by Font.MONOSPACED with JDK 6 tempEditorPane.setFont(new Font("Monospaced", 0, aFrame.getFont().getSize())); tempEditorPane.setText(tempStringWriter.toString()); tempScrollPane.add(tempEditorPane); tempDialog.getContentPane().add(tempScrollPane, BorderLayout.CENTER); Action tempActionListener = new AbstractAction("OK") { @Override public void actionPerformed(ActionEvent aE) { tempDialog.dispose(); } }; tempDialog.getContentPane().add(createButtons(new Action[] { tempActionListener }), BorderLayout.SOUTH); tempDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); tempDialog.setVisible(true); }
private static void displayExceptionPrivate(JFrame aFrame, Throwable aE) { StringWriter tempStringWriter = new StringWriter(); PrintWriter tempPrintWriter = new PrintWriter(tempStringWriter); aE.printStackTrace(tempPrintWriter); tempPrintWriter.close(); final JDialog tempDialog = new JDialog(aFrame, "Error: " + aE.getMessage()); tempDialog.setModal(true); Dimension tempScreen = Toolkit.getDefaultToolkit().getScreenSize(); tempDialog.setSize(tempScreen.width / 2, tempScreen.height / 2); tempDialog.setLocation(tempScreen.width / 4, tempScreen.height / 4); tempDialog.getContentPane().setLayout(new BorderLayout()); ScrollPane tempScrollPane = new ScrollPane(); JEditorPane tempEditorPane = new JEditorPane(); tempEditorPane.setFont(new Font("Monospaced", 0, aFrame.getFont().getSize())); tempEditorPane.setText(tempStringWriter.toString()); tempScrollPane.add(tempEditorPane); tempDialog.getContentPane().add(tempScrollPane, BorderLayout.CENTER); Action tempActionListener = new AbstractAction("OK") { @Override public void actionPerformed(ActionEvent aE) { tempDialog.dispose(); } }; tempDialog.getContentPane().add(createButtons(new Action[] { tempActionListener }), BorderLayout.SOUTH); tempDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); tempDialog.setVisible(true); }
private static void displayexceptionprivate(jframe aframe, throwable ae) { stringwriter tempstringwriter = new stringwriter(); printwriter tempprintwriter = new printwriter(tempstringwriter); ae.printstacktrace(tempprintwriter); tempprintwriter.close(); final jdialog tempdialog = new jdialog(aframe, "error: " + ae.getmessage()); tempdialog.setmodal(true); dimension tempscreen = toolkit.getdefaulttoolkit().getscreensize(); tempdialog.setsize(tempscreen.width / 2, tempscreen.height / 2); tempdialog.setlocation(tempscreen.width / 4, tempscreen.height / 4); tempdialog.getcontentpane().setlayout(new borderlayout()); scrollpane tempscrollpane = new scrollpane(); jeditorpane tempeditorpane = new jeditorpane(); tempeditorpane.setfont(new font("monospaced", 0, aframe.getfont().getsize())); tempeditorpane.settext(tempstringwriter.tostring()); tempscrollpane.add(tempeditorpane); tempdialog.getcontentpane().add(tempscrollpane, borderlayout.center); action tempactionlistener = new abstractaction("ok") { @override public void actionperformed(actionevent ae) { tempdialog.dispose(); } }; tempdialog.getcontentpane().add(createbuttons(new action[] { tempactionlistener }), borderlayout.south); tempdialog.setdefaultcloseoperation(jdialog.dispose_on_close); tempdialog.setvisible(true); }
rscadrde/projekt-task-capturing
[ 1, 0, 0, 0 ]
13,240
private static void displayTextPrivate(JFrame aFrame, String aTitle, String aText, boolean aModalFlag, List<Action> anActions) { final JDialog tempDialog = new JDialog(aFrame, aTitle); tempDialog.setModal(aModalFlag); Dimension tempScreen = Toolkit.getDefaultToolkit().getScreenSize(); tempDialog.setSize(tempScreen.width * 4 / 10, tempScreen.height * 4 / 5); tempDialog.setLocation(tempScreen.width / 4, tempScreen.height / 10); tempDialog.getContentPane().setLayout(new BorderLayout()); ScrollPane tempScrollPane = new ScrollPane(); JEditorPane tempEditorPane = new JEditorPane(); // TODO Replace by Font.MONOSPACED with JDK 6 tempEditorPane.setFont(new Font("Monospaced", 0, aFrame.getFont().getSize())); tempEditorPane.setText(aText); tempScrollPane.add(tempEditorPane); tempDialog.getContentPane().add(tempScrollPane, BorderLayout.CENTER); Action tempActionListener = new AbstractAction("OK") { @Override public void actionPerformed(ActionEvent aE) { tempDialog.dispose(); } }; List<Action> tempActions = new ArrayList<Action>(); tempActions.add(tempActionListener); if (anActions != null) { tempActions.addAll(anActions); } tempDialog.getContentPane().add(createButtons(tempActions.toArray(new Action[tempActions.size()])), BorderLayout.SOUTH); tempDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); tempDialog.setAlwaysOnTop(false); tempDialog.setVisible(true); }
private static void displayTextPrivate(JFrame aFrame, String aTitle, String aText, boolean aModalFlag, List<Action> anActions) { final JDialog tempDialog = new JDialog(aFrame, aTitle); tempDialog.setModal(aModalFlag); Dimension tempScreen = Toolkit.getDefaultToolkit().getScreenSize(); tempDialog.setSize(tempScreen.width * 4 / 10, tempScreen.height * 4 / 5); tempDialog.setLocation(tempScreen.width / 4, tempScreen.height / 10); tempDialog.getContentPane().setLayout(new BorderLayout()); ScrollPane tempScrollPane = new ScrollPane(); JEditorPane tempEditorPane = new JEditorPane(); tempEditorPane.setFont(new Font("Monospaced", 0, aFrame.getFont().getSize())); tempEditorPane.setText(aText); tempScrollPane.add(tempEditorPane); tempDialog.getContentPane().add(tempScrollPane, BorderLayout.CENTER); Action tempActionListener = new AbstractAction("OK") { @Override public void actionPerformed(ActionEvent aE) { tempDialog.dispose(); } }; List<Action> tempActions = new ArrayList<Action>(); tempActions.add(tempActionListener); if (anActions != null) { tempActions.addAll(anActions); } tempDialog.getContentPane().add(createButtons(tempActions.toArray(new Action[tempActions.size()])), BorderLayout.SOUTH); tempDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); tempDialog.setAlwaysOnTop(false); tempDialog.setVisible(true); }
private static void displaytextprivate(jframe aframe, string atitle, string atext, boolean amodalflag, list<action> anactions) { final jdialog tempdialog = new jdialog(aframe, atitle); tempdialog.setmodal(amodalflag); dimension tempscreen = toolkit.getdefaulttoolkit().getscreensize(); tempdialog.setsize(tempscreen.width * 4 / 10, tempscreen.height * 4 / 5); tempdialog.setlocation(tempscreen.width / 4, tempscreen.height / 10); tempdialog.getcontentpane().setlayout(new borderlayout()); scrollpane tempscrollpane = new scrollpane(); jeditorpane tempeditorpane = new jeditorpane(); tempeditorpane.setfont(new font("monospaced", 0, aframe.getfont().getsize())); tempeditorpane.settext(atext); tempscrollpane.add(tempeditorpane); tempdialog.getcontentpane().add(tempscrollpane, borderlayout.center); action tempactionlistener = new abstractaction("ok") { @override public void actionperformed(actionevent ae) { tempdialog.dispose(); } }; list<action> tempactions = new arraylist<action>(); tempactions.add(tempactionlistener); if (anactions != null) { tempactions.addall(anactions); } tempdialog.getcontentpane().add(createbuttons(tempactions.toarray(new action[tempactions.size()])), borderlayout.south); tempdialog.setdefaultcloseoperation(jdialog.dispose_on_close); tempdialog.setalwaysontop(false); tempdialog.setvisible(true); }
rscadrde/projekt-task-capturing
[ 1, 0, 0, 0 ]
21,707
private synchronized Bitmap getBitmapFromEntryIfNeeded(String entryName, boolean recycle) { Bitmap bitmap = null; ImageState status = imageState.get(entryName); if (status == null || status.equals(ImageState.UNKNOWN)) { ZipEntry entry = mZip.getEntry(entryName); try { File file = extract(entry, entry.getName()); BitmapFactory.decodeFile(file.getPath(), bounds); if (bounds.outWidth == -1) { // TODO: Error } int width = bounds.outWidth; int height = bounds.outHeight; boolean landscape = height > width; int maxHeight = getMaxHeight(landscape); int maxWidth = getMaxWidth(landscape); boolean withinBounds = width <= maxWidth && height <= maxHeight; if (withinBounds) { imageState.put(entryName, ImageState.ORIGINAL); } else { bitmap = resampleAndSave(entryName, width, height); } } catch (Exception e) { e.printStackTrace(); } } if (bitmap != null && recycle) { bitmap.recycle(); return null; } else { return bitmap; } }
private synchronized Bitmap getBitmapFromEntryIfNeeded(String entryName, boolean recycle) { Bitmap bitmap = null; ImageState status = imageState.get(entryName); if (status == null || status.equals(ImageState.UNKNOWN)) { ZipEntry entry = mZip.getEntry(entryName); try { File file = extract(entry, entry.getName()); BitmapFactory.decodeFile(file.getPath(), bounds); if (bounds.outWidth == -1) { } int width = bounds.outWidth; int height = bounds.outHeight; boolean landscape = height > width; int maxHeight = getMaxHeight(landscape); int maxWidth = getMaxWidth(landscape); boolean withinBounds = width <= maxWidth && height <= maxHeight; if (withinBounds) { imageState.put(entryName, ImageState.ORIGINAL); } else { bitmap = resampleAndSave(entryName, width, height); } } catch (Exception e) { e.printStackTrace(); } } if (bitmap != null && recycle) { bitmap.recycle(); return null; } else { return bitmap; } }
private synchronized bitmap getbitmapfromentryifneeded(string entryname, boolean recycle) { bitmap bitmap = null; imagestate status = imagestate.get(entryname); if (status == null || status.equals(imagestate.unknown)) { zipentry entry = mzip.getentry(entryname); try { file file = extract(entry, entry.getname()); bitmapfactory.decodefile(file.getpath(), bounds); if (bounds.outwidth == -1) { } int width = bounds.outwidth; int height = bounds.outheight; boolean landscape = height > width; int maxheight = getmaxheight(landscape); int maxwidth = getmaxwidth(landscape); boolean withinbounds = width <= maxwidth && height <= maxheight; if (withinbounds) { imagestate.put(entryname, imagestate.original); } else { bitmap = resampleandsave(entryname, width, height); } } catch (exception e) { e.printstacktrace(); } } if (bitmap != null && recycle) { bitmap.recycle(); return null; } else { return bitmap; } }
remco138/ocrmangareaderforandroid
[ 0, 0, 1, 0 ]
13,922
public void setSimpleTag() { /* TODO: clear previously-set field and avoid memory leak */ t = Tag.SIMPLE_TAG; }
public void setSimpleTag() { t = Tag.SIMPLE_TAG; }
public void setsimpletag() { t = tag.simple_tag; }
syntakker/atd
[ 0, 1, 0, 0 ]
22,202
public EasySource getInnerText(char open, char close) { StringBuffer code = new StringBuffer(); int brace_counter = 0; while (true) { if (pos >= src.length) { return null; } char c = src[pos]; if (c == open) { // TODO: what about open and close inside strings ? brace_counter++; // code.appendInPlace(parse(rs, hook).src); // code.appendInPlace(close); } if (c == close) //|| src[pos] == close) { if (brace_counter > 0) brace_counter--; else { pos++; break; } } code.append(c); // TODO: optimize pos++; } return new EasySource(code.toString().toCharArray()); }
public EasySource getInnerText(char open, char close) { StringBuffer code = new StringBuffer(); int brace_counter = 0; while (true) { if (pos >= src.length) { return null; } char c = src[pos]; if (c == open) { brace_counter++; } if (c == close) { if (brace_counter > 0) brace_counter--; else { pos++; break; } } code.append(c); pos++; } return new EasySource(code.toString().toCharArray()); }
public easysource getinnertext(char open, char close) { stringbuffer code = new stringbuffer(); int brace_counter = 0; while (true) { if (pos >= src.length) { return null; } char c = src[pos]; if (c == open) { brace_counter++; } if (c == close) { if (brace_counter > 0) brace_counter--; else { pos++; break; } } code.append(c); pos++; } return new easysource(code.tostring().tochararray()); }
rhulha/EasyLang
[ 1, 0, 0, 0 ]
14,027
public void finalizeReports(String currentSessionId) { // TODO: Need to implement procedure to skip finalizing the current session when this is // called on app start, but keep the current session when called at crash time. Currently // this only works when called at app start. List<File> sessionDirectories = capAndGetOpenSessions(currentSessionId); for (File sessionDirectory : sessionDirectories) { final List<File> eventFiles = getFilesInDirectory( sessionDirectory, (f, name) -> name.startsWith(EVENT_FILE_NAME_PREFIX)); Collections.sort(eventFiles); // TODO: Fix nulls // Only process the session if it has associated events if (!eventFiles.isEmpty()) { final List<Event> events = new ArrayList<>(); boolean isHighPriorityReport = false; for (File eventFile : eventFiles) { final Event event = TRANSFORM.eventFromJson(readTextFile(eventFile)); isHighPriorityReport = isHighPriorityReport || isHighPriorityEventFile(eventFile.getName()); events.add(event); } // FIXME: If we fail to parse the events, we'll need to bail. String userId = null; final File userFile = new File(sessionDirectory, USER_FILE_NAME); if (userFile.exists()) { userId = readTextFile(userFile); } CrashlyticsReport report = TRANSFORM.reportFromJson(readTextFile(new File(sessionDirectory, REPORT_FILE_NAME))); final String sessionId = report.getSession().getIdentifier(); if (userId != null) { report = report.withUserId(userId); } final File outputDirectory = prepareDirectory(isHighPriorityReport ? priorityReportsDirectory : reportsDirectory); writeTextFile( new File(outputDirectory, sessionId), TRANSFORM.reportToJson(report.withEvents(ImmutableList.from(events)))); } recursiveDelete(sessionDirectory); } capFinalizedReports(); }
public void finalizeReports(String currentSessionId) { List<File> sessionDirectories = capAndGetOpenSessions(currentSessionId); for (File sessionDirectory : sessionDirectories) { final List<File> eventFiles = getFilesInDirectory( sessionDirectory, (f, name) -> name.startsWith(EVENT_FILE_NAME_PREFIX)); Collections.sort(eventFiles); if (!eventFiles.isEmpty()) { final List<Event> events = new ArrayList<>(); boolean isHighPriorityReport = false; for (File eventFile : eventFiles) { final Event event = TRANSFORM.eventFromJson(readTextFile(eventFile)); isHighPriorityReport = isHighPriorityReport || isHighPriorityEventFile(eventFile.getName()); events.add(event); } String userId = null; final File userFile = new File(sessionDirectory, USER_FILE_NAME); if (userFile.exists()) { userId = readTextFile(userFile); } CrashlyticsReport report = TRANSFORM.reportFromJson(readTextFile(new File(sessionDirectory, REPORT_FILE_NAME))); final String sessionId = report.getSession().getIdentifier(); if (userId != null) { report = report.withUserId(userId); } final File outputDirectory = prepareDirectory(isHighPriorityReport ? priorityReportsDirectory : reportsDirectory); writeTextFile( new File(outputDirectory, sessionId), TRANSFORM.reportToJson(report.withEvents(ImmutableList.from(events)))); } recursiveDelete(sessionDirectory); } capFinalizedReports(); }
public void finalizereports(string currentsessionid) { list<file> sessiondirectories = capandgetopensessions(currentsessionid); for (file sessiondirectory : sessiondirectories) { final list<file> eventfiles = getfilesindirectory( sessiondirectory, (f, name) -> name.startswith(event_file_name_prefix)); collections.sort(eventfiles); if (!eventfiles.isempty()) { final list<event> events = new arraylist<>(); boolean ishighpriorityreport = false; for (file eventfile : eventfiles) { final event event = transform.eventfromjson(readtextfile(eventfile)); ishighpriorityreport = ishighpriorityreport || ishighpriorityeventfile(eventfile.getname()); events.add(event); } string userid = null; final file userfile = new file(sessiondirectory, user_file_name); if (userfile.exists()) { userid = readtextfile(userfile); } crashlyticsreport report = transform.reportfromjson(readtextfile(new file(sessiondirectory, report_file_name))); final string sessionid = report.getsession().getidentifier(); if (userid != null) { report = report.withuserid(userid); } final file outputdirectory = preparedirectory(ishighpriorityreport ? priorityreportsdirectory : reportsdirectory); writetextfile( new file(outputdirectory, sessionid), transform.reporttojson(report.withevents(immutablelist.from(events)))); } recursivedelete(sessiondirectory); } capfinalizedreports(); }
sevax88/firebase-android-sdk
[ 0, 1, 1, 0 ]
30,415
private Optional<List<Relation>> processDefaultRelation(final Relation relation, final List<Long> parents) { final List<Relation> createdRelations = new ArrayList<>(); final List<RelationMember> members = new ArrayList<>(); boolean isModified = false; for (final RelationMember member : relation.getMembers()) { switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else { return ISOCountryTag.COUNTRY_MISSING; } } })); final List<RelationMember> memberWithoutCountry; if (countryEntityMap.containsKey(ISOCountryTag.COUNTRY_MISSING)) { memberWithoutCountry = countryEntityMap.remove(ISOCountryTag.COUNTRY_MISSING); } else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
private Optional<List<Relation>> processDefaultRelation(final Relation relation, final List<Long> parents) { final List<Relation> createdRelations = new ArrayList<>(); final List<RelationMember> members = new ArrayList<>(); boolean isModified = false; for (final RelationMember member : relation.getMembers()) { switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); if (subRelation == null) { members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: members.add(member); break; } } if (isModified) { this.changeSet.addModifiedRelation(relation); } final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else { return ISOCountryTag.COUNTRY_MISSING; } } })); final List<RelationMember> memberWithoutCountry; if (countryEntityMap.containsKey(ISOCountryTag.COUNTRY_MISSING)) { memberWithoutCountry = countryEntityMap.remove(ISOCountryTag.COUNTRY_MISSING); } else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
private optional<list<relation>> processdefaultrelation(final relation relation, final list<long> parents) { final list<relation> createdrelations = new arraylist<>(); final list<relationmember> members = new arraylist<>(); boolean ismodified = false; for (final relationmember member : relation.getmembers()) { switch (member.getmembertype()) { case way: final list<way> slicedways = this.changeset .getcreatedways(member.getmemberid()); if (slicedways != null && !slicedways.isempty()) { ismodified = true; slicedways.foreach(way -> members .add(this.store.createrelationmember(member, way.getid()))); } else { members.add(member); } break; case relation: parents.add(relation.getid()); final relation subrelation = this.store.getrelation(member.getmemberid()); if (subrelation == null) { members.add(member); break; } final optional<list<relation>> slicedmembers; if (!parents.contains(subrelation.getid())) { slicedmembers = slicerelation(subrelation, parents); } else { logger.error("relation {} has a loop! parent tree: {}", subrelation.getid(), parents); slicedmembers = optional.empty(); } if (slicedmembers.ispresent()) { ismodified = true; slicedmembers.get().foreach(slicedrelation -> { members.add(this.store.createrelationmember(member, slicedrelation.getid())); }); } else { members.add(member); } break; default: members.add(member); break; } } if (ismodified) { this.changeset.addmodifiedrelation(relation); } final map<string, list<relationmember>> countryentitymap = members.stream() .collect(collectors.groupingby(member -> { final entity entity = this.store.getentity(member); if (objects.isnull(entity)) { return isocountrytag.country_missing; } else { final optional<tag> countrycodetag = entity.gettags().stream() .filter(tag -> tag.getkey().equals(isocountrytag.key)).findfirst(); if (countrycodetag.ispresent()) { return countrycodetag.get().getvalue(); } else { return isocountrytag.country_missing; } } })); final list<relationmember> memberwithoutcountry; if (countryentitymap.containskey(isocountrytag.country_missing)) { memberwithoutcountry = countryentitymap.remove(isocountrytag.country_missing); } else { memberwithoutcountry = collections.emptylist(); } final int countrycount = countryentitymap.size(); if (countrycount == 0) { relation.gettags().add(new tag(isocountrytag.key, isocountrytag.country_missing)); return optional.empty(); } else if (countrycount == 1) { relation.gettags() .add(new tag(isocountrytag.key, countryentitymap.keyset().iterator().next())); return optional.empty(); } else { runtimecounter.relationsliced(); this.changeset.adddeletedrelation(relation); final countryslicingidentifierfactory relationidfactory = new countryslicingidentifierfactory( relation.getid()); countryentitymap.entryset().foreach(entry -> { final list<relationmember> candidatemembers = new arraylist<>(); candidatemembers.addall(entry.getvalue()); candidatemembers.addall(memberwithoutcountry); if (!candidatemembers.isempty()) { final relation relationtoadd = this.store.createrelation(relation, relationidfactory.nextidentifier(), candidatemembers); relationtoadd.gettags().add(new tag(isocountrytag.key, entry.getkey())); createdrelations.add(relationtoadd); this.changeset.addcreatedrelation(relationtoadd); } }); } return optional.of(createdrelations); }
savannahostrowski/atlas
[ 1, 0, 0, 0 ]
14,066
@JsonGetter("accessToken") public String getAccessToken ( ) { return this.accessToken; }
@JsonGetter("accessToken") public String getAccessToken ( ) { return this.accessToken; }
@jsongetter("accesstoken") public string getaccesstoken ( ) { return this.accesstoken; }
serkaneren78/konkod-android-sdk
[ 0, 0, 0, 0 ]
14,067
@JsonSetter("accessToken") public void setAccessToken (String value) { this.accessToken = value; notifyObservers(this.accessToken); }
@JsonSetter("accessToken") public void setAccessToken (String value) { this.accessToken = value; notifyObservers(this.accessToken); }
@jsonsetter("accesstoken") public void setaccesstoken (string value) { this.accesstoken = value; notifyobservers(this.accesstoken); }
serkaneren78/konkod-android-sdk
[ 0, 0, 0, 0 ]
14,068
@JsonGetter("tokeType") public String getTokeType ( ) { return this.tokeType; }
@JsonGetter("tokeType") public String getTokeType ( ) { return this.tokeType; }
@jsongetter("toketype") public string gettoketype ( ) { return this.toketype; }
serkaneren78/konkod-android-sdk
[ 0, 0, 0, 0 ]
14,069
@JsonSetter("tokeType") public void setTokeType (String value) { this.tokeType = value; notifyObservers(this.tokeType); }
@JsonSetter("tokeType") public void setTokeType (String value) { this.tokeType = value; notifyObservers(this.tokeType); }
@jsonsetter("toketype") public void settoketype (string value) { this.toketype = value; notifyobservers(this.toketype); }
serkaneren78/konkod-android-sdk
[ 0, 0, 0, 0 ]
14,070
@JsonGetter("expiresIn") public Long getExpiresIn ( ) { return this.expiresIn; }
@JsonGetter("expiresIn") public Long getExpiresIn ( ) { return this.expiresIn; }
@jsongetter("expiresin") public long getexpiresin ( ) { return this.expiresin; }
serkaneren78/konkod-android-sdk
[ 0, 0, 0, 0 ]
14,071
@JsonSetter("expiresIn") public void setExpiresIn (Long value) { this.expiresIn = value; notifyObservers(this.expiresIn); }
@JsonSetter("expiresIn") public void setExpiresIn (Long value) { this.expiresIn = value; notifyObservers(this.expiresIn); }
@jsonsetter("expiresin") public void setexpiresin (long value) { this.expiresin = value; notifyobservers(this.expiresin); }
serkaneren78/konkod-android-sdk
[ 0, 0, 0, 0 ]
30,633
public static SourceFileModule resolve(File rootDir, File dir, String target) throws IOException, JSONException { // NOTE(Zhen): Ignore CoreModule for now to enable a more flexible semantic modeling // if (NodejsRequiredCoreModule.isCoreModule(target)) return NodejsRequiredCoreModule.make(target); if (target.startsWith("./") || target.startsWith("/") || target.startsWith("../")) { SourceFileModule module = loadAsFile(rootDir, new File(dir, target)); if (module != null) return module; module = loadAsDirectory(rootDir, new File(dir, target)); if (module != null) return module; } // NOTE(Zhen): it is not very useful to throw exception... return loadNodeModules(rootDir, dir, target); }
public static SourceFileModule resolve(File rootDir, File dir, String target) throws IOException, JSONException { if (target.startsWith("./") || target.startsWith("/") || target.startsWith("../")) { SourceFileModule module = loadAsFile(rootDir, new File(dir, target)); if (module != null) return module; module = loadAsDirectory(rootDir, new File(dir, target)); if (module != null) return module; } return loadNodeModules(rootDir, dir, target); }
public static sourcefilemodule resolve(file rootdir, file dir, string target) throws ioexception, jsonexception { if (target.startswith("./") || target.startswith("/") || target.startswith("../")) { sourcefilemodule module = loadasfile(rootdir, new file(dir, target)); if (module != null) return module; module = loadasdirectory(rootdir, new file(dir, target)); if (module != null) return module; } return loadnodemodules(rootdir, dir, target); }
semantic-graph/js2graph
[ 1, 0, 0, 0 ]
22,463
private String prepareHeadersAndBodyForService(HttpServletRequest request, String method, String url, List<String> clientRequestHeaders, Interactor.Interaction interaction, String clientRequestContentType, InteractionManipulations interactionManipulations) throws IOException { Enumeration<String> hdrs = request.getHeaderNames(); ServletInputStream is = request.getInputStream(); Object clientRequestBody = null; //if (is.available() > 0) { if (isText(clientRequestContentType)) { clientRequestBody = null; String characterEncoding = request.getCharacterEncoding(); if (characterEncoding == null) { characterEncoding = "utf-8"; } try (Scanner scanner = new Scanner(is, characterEncoding)) { if(scanner.hasNext()) { clientRequestBody = scanner.useDelimiter("\\A").next(); } } if (shouldHavePrettyPrintedTextBodies() && clientRequestBody != null) { clientRequestBody = prettifyDocOrNot((String) clientRequestBody); } } else if(is.available() > 0){ byte[] targetArray = new byte[is.available()]; is.read(targetArray); clientRequestBody = targetArray; } //} while (hdrs.hasMoreElements()) { // TODO - make this cater for multiple lines with the same name String hdrName = hdrs.nextElement(); String hdrVal = request.getHeader(hdrName); hdrVal = interactionManipulations.headerReplacement(hdrName, hdrVal); final String fullHeader = (getLowerCaseHeaders() ? hdrName.toLowerCase() : hdrName) + ": " + hdrVal; clientRequestHeaders.add(fullHeader); interactionManipulations.changeSingleHeaderForRequestToService(method, fullHeader, clientRequestHeaders); } interactionManipulations.changeAnyHeadersForRequestToService(clientRequestHeaders); if (clientRequestBody instanceof String) { clientRequestBody = interactionManipulations.changeBodyForRequestToService((String) clientRequestBody); } if (clientRequestBody == null) { clientRequestBody = ""; } interaction.noteClientRequestHeadersAndBody(clientRequestHeaders, clientRequestBody, clientRequestContentType); return interactionManipulations.changeUrlForRequestToService(url); }
private String prepareHeadersAndBodyForService(HttpServletRequest request, String method, String url, List<String> clientRequestHeaders, Interactor.Interaction interaction, String clientRequestContentType, InteractionManipulations interactionManipulations) throws IOException { Enumeration<String> hdrs = request.getHeaderNames(); ServletInputStream is = request.getInputStream(); Object clientRequestBody = null; if (isText(clientRequestContentType)) { clientRequestBody = null; String characterEncoding = request.getCharacterEncoding(); if (characterEncoding == null) { characterEncoding = "utf-8"; } try (Scanner scanner = new Scanner(is, characterEncoding)) { if(scanner.hasNext()) { clientRequestBody = scanner.useDelimiter("\\A").next(); } } if (shouldHavePrettyPrintedTextBodies() && clientRequestBody != null) { clientRequestBody = prettifyDocOrNot((String) clientRequestBody); } } else if(is.available() > 0){ byte[] targetArray = new byte[is.available()]; is.read(targetArray); clientRequestBody = targetArray; } while (hdrs.hasMoreElements()) { String hdrName = hdrs.nextElement(); String hdrVal = request.getHeader(hdrName); hdrVal = interactionManipulations.headerReplacement(hdrName, hdrVal); final String fullHeader = (getLowerCaseHeaders() ? hdrName.toLowerCase() : hdrName) + ": " + hdrVal; clientRequestHeaders.add(fullHeader); interactionManipulations.changeSingleHeaderForRequestToService(method, fullHeader, clientRequestHeaders); } interactionManipulations.changeAnyHeadersForRequestToService(clientRequestHeaders); if (clientRequestBody instanceof String) { clientRequestBody = interactionManipulations.changeBodyForRequestToService((String) clientRequestBody); } if (clientRequestBody == null) { clientRequestBody = ""; } interaction.noteClientRequestHeadersAndBody(clientRequestHeaders, clientRequestBody, clientRequestContentType); return interactionManipulations.changeUrlForRequestToService(url); }
private string prepareheadersandbodyforservice(httpservletrequest request, string method, string url, list<string> clientrequestheaders, interactor.interaction interaction, string clientrequestcontenttype, interactionmanipulations interactionmanipulations) throws ioexception { enumeration<string> hdrs = request.getheadernames(); servletinputstream is = request.getinputstream(); object clientrequestbody = null; if (istext(clientrequestcontenttype)) { clientrequestbody = null; string characterencoding = request.getcharacterencoding(); if (characterencoding == null) { characterencoding = "utf-8"; } try (scanner scanner = new scanner(is, characterencoding)) { if(scanner.hasnext()) { clientrequestbody = scanner.usedelimiter("\\a").next(); } } if (shouldhaveprettyprintedtextbodies() && clientrequestbody != null) { clientrequestbody = prettifydocornot((string) clientrequestbody); } } else if(is.available() > 0){ byte[] targetarray = new byte[is.available()]; is.read(targetarray); clientrequestbody = targetarray; } while (hdrs.hasmoreelements()) { string hdrname = hdrs.nextelement(); string hdrval = request.getheader(hdrname); hdrval = interactionmanipulations.headerreplacement(hdrname, hdrval); final string fullheader = (getlowercaseheaders() ? hdrname.tolowercase() : hdrname) + ": " + hdrval; clientrequestheaders.add(fullheader); interactionmanipulations.changesingleheaderforrequesttoservice(method, fullheader, clientrequestheaders); } interactionmanipulations.changeanyheadersforrequesttoservice(clientrequestheaders); if (clientrequestbody instanceof string) { clientrequestbody = interactionmanipulations.changebodyforrequesttoservice((string) clientrequestbody); } if (clientrequestbody == null) { clientrequestbody = ""; } interaction.noteclientrequestheadersandbody(clientrequestheaders, clientrequestbody, clientrequestcontenttype); return interactionmanipulations.changeurlforrequesttoservice(url); }
rogerfsg/servirtium
[ 1, 0, 0, 0 ]
14,278
private void doWelcome(Session session) { if (! session.isInteractive()) { return; } File confDir = getConfigDirectory(); File welcomeFile = new File(confDir, ".welcome"); if (welcomeFile.exists()) { return; } /* * Create the welcome file since we are going to welcome them! */ try { welcomeFile.createNewFile(); } catch (IOException e) { System.err.println("WARNING: Failed to create " + welcomeFile + ": " + e.getMessage()); return; } /* * Here's a hack. The ".welcome" file is a recent change to jsqsh, and * we don't want to do the whole welcome thing if an existing jsqsh user * already has a ~/.jsqsh but doesn't have a .welcome file in it. To avoid * this, check to see if drivers.xml is older than the date at which this * comment was written and don't do the setup activities. */ File driversFile = new File(confDir, "drivers.xml"); if (driversFile.exists()) { long lastModified = driversFile.lastModified(); /* * Directory was created prior to "now" (when I am typing this comment), * so pretend the welcome was done */ if (lastModified < 1392411017075L) { return; } } HelpTopic welcome = helpManager.getTopic("welcome"); System.out.println(welcome.getHelp()); session.out.println(); session.out.println("You will now enter the jsqsh setup wizard."); try { getConsole().readline("Hit enter to continue: ", false); Command command = session.getCommandManager().getCommand("\\setup"); command.execute(session, new String [] { }); } catch (Exception e) { /* NOT SURE WHAT TO DO HERE */ e.printStackTrace(); } }
private void doWelcome(Session session) { if (! session.isInteractive()) { return; } File confDir = getConfigDirectory(); File welcomeFile = new File(confDir, ".welcome"); if (welcomeFile.exists()) { return; } try { welcomeFile.createNewFile(); } catch (IOException e) { System.err.println("WARNING: Failed to create " + welcomeFile + ": " + e.getMessage()); return; } File driversFile = new File(confDir, "drivers.xml"); if (driversFile.exists()) { long lastModified = driversFile.lastModified(); if (lastModified < 1392411017075L) { return; } } HelpTopic welcome = helpManager.getTopic("welcome"); System.out.println(welcome.getHelp()); session.out.println(); session.out.println("You will now enter the jsqsh setup wizard."); try { getConsole().readline("Hit enter to continue: ", false); Command command = session.getCommandManager().getCommand("\\setup"); command.execute(session, new String [] { }); } catch (Exception e) { e.printStackTrace(); } }
private void dowelcome(session session) { if (! session.isinteractive()) { return; } file confdir = getconfigdirectory(); file welcomefile = new file(confdir, ".welcome"); if (welcomefile.exists()) { return; } try { welcomefile.createnewfile(); } catch (ioexception e) { system.err.println("warning: failed to create " + welcomefile + ": " + e.getmessage()); return; } file driversfile = new file(confdir, "drivers.xml"); if (driversfile.exists()) { long lastmodified = driversfile.lastmodified(); if (lastmodified < 1392411017075l) { return; } } helptopic welcome = helpmanager.gettopic("welcome"); system.out.println(welcome.gethelp()); session.out.println(); session.out.println("you will now enter the jsqsh setup wizard."); try { getconsole().readline("hit enter to continue: ", false); command command = session.getcommandmanager().getcommand("\\setup"); command.execute(session, new string [] { }); } catch (exception e) { e.printstacktrace(); } }
scottwakeling/jsqsh
[ 1, 0, 0, 0 ]
14,375
private void networkNameMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_networkNameMouseClicked // TODO add your handling code here: // jTextField1.setText(""); }
private void networkNameMouseClicked(java.awt.event.MouseEvent evt) { }
private void networknamemouseclicked(java.awt.event.mouseevent evt) { }
rohit-khokle/Medicare
[ 0, 1, 0, 0 ]
22,631
public static ExchangeUnitAuxiliaryInputStatistics getAuxiliaryStatisticsWithVPra(KepProblemData<ExchangeUnit,DonorEdge> kepProblemData){ AuxiliaryInputStatistics<ExchangeUnit,DonorEdge> regular = getAuxiliaryStatistics(kepProblemData); List<Donor> donors = new ArrayList<Donor>(); List<Receiver> receivers = new ArrayList<Receiver>(); for(ExchangeUnit unit: kepProblemData.getGraph().getVertices()){ for(Donor donor: unit.getDonor()){ donors.add(donor); } if(!kepProblemData.getRootNodes().contains(unit)){ receivers.add(unit.getReceiver()); } } ImmutableMap.Builder<Receiver,Double> builder = ImmutableMap.<Receiver,Double>builder(); for(Receiver receiver: receivers){ int count = 0; for(Donor donor: donors){ if(!receiver.getTissueTypeSensitivity().isCompatible(donor.getTissueType())){ count++; } } builder.put(receiver, 100*count/(double)donors.size()); } return new ExchangeUnitAuxiliaryInputStatistics( regular.getDonorPowerPostPreference(), regular.getReceiverPowerPostPreference(), builder.build()) ; }
public static ExchangeUnitAuxiliaryInputStatistics getAuxiliaryStatisticsWithVPra(KepProblemData<ExchangeUnit,DonorEdge> kepProblemData){ AuxiliaryInputStatistics<ExchangeUnit,DonorEdge> regular = getAuxiliaryStatistics(kepProblemData); List<Donor> donors = new ArrayList<Donor>(); List<Receiver> receivers = new ArrayList<Receiver>(); for(ExchangeUnit unit: kepProblemData.getGraph().getVertices()){ for(Donor donor: unit.getDonor()){ donors.add(donor); } if(!kepProblemData.getRootNodes().contains(unit)){ receivers.add(unit.getReceiver()); } } ImmutableMap.Builder<Receiver,Double> builder = ImmutableMap.<Receiver,Double>builder(); for(Receiver receiver: receivers){ int count = 0; for(Donor donor: donors){ if(!receiver.getTissueTypeSensitivity().isCompatible(donor.getTissueType())){ count++; } } builder.put(receiver, 100*count/(double)donors.size()); } return new ExchangeUnitAuxiliaryInputStatistics( regular.getDonorPowerPostPreference(), regular.getReceiverPowerPostPreference(), builder.build()) ; }
public static exchangeunitauxiliaryinputstatistics getauxiliarystatisticswithvpra(kepproblemdata<exchangeunit,donoredge> kepproblemdata){ auxiliaryinputstatistics<exchangeunit,donoredge> regular = getauxiliarystatistics(kepproblemdata); list<donor> donors = new arraylist<donor>(); list<receiver> receivers = new arraylist<receiver>(); for(exchangeunit unit: kepproblemdata.getgraph().getvertices()){ for(donor donor: unit.getdonor()){ donors.add(donor); } if(!kepproblemdata.getrootnodes().contains(unit)){ receivers.add(unit.getreceiver()); } } immutablemap.builder<receiver,double> builder = immutablemap.<receiver,double>builder(); for(receiver receiver: receivers){ int count = 0; for(donor donor: donors){ if(!receiver.gettissuetypesensitivity().iscompatible(donor.gettissuetype())){ count++; } } builder.put(receiver, 100*count/(double)donors.size()); } return new exchangeunitauxiliaryinputstatistics( regular.getdonorpowerpostpreference(), regular.getreceiverpowerpostpreference(), builder.build()) ; }
rma350/kidneyExchange
[ 1, 0, 0, 0 ]
14,588
public void testSolve() { RealMatrixImpl m = new RealMatrixImpl(testData); RealMatrix mInv = new RealMatrixImpl(testDataInv); // being a bit slothful here -- actually testing that X = A^-1 * B assertClose("inverse-operate",mInv.operate(testVector), m.solve(testVector),normTolerance); try { m.solve(testVector2); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { ; } RealMatrix bs = new RealMatrixImpl(bigSingular); try { bs.solve(bs); fail("Expecting InvalidMatrixException"); } catch (InvalidMatrixException ex) { ; } try { m.solve(bs); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { ; } try { new RealMatrixImpl(testData2).solve(bs); fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { ; } try { (new RealMatrixImpl(testData2)).luDecompose(); fail("Expecting InvalidMatrixException"); } catch (InvalidMatrixException ex) { ; } }
public void testSolve() { RealMatrixImpl m = new RealMatrixImpl(testData); RealMatrix mInv = new RealMatrixImpl(testDataInv); assertClose("inverse-operate",mInv.operate(testVector), m.solve(testVector),normTolerance); try { m.solve(testVector2); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { ; } RealMatrix bs = new RealMatrixImpl(bigSingular); try { bs.solve(bs); fail("Expecting InvalidMatrixException"); } catch (InvalidMatrixException ex) { ; } try { m.solve(bs); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { ; } try { new RealMatrixImpl(testData2).solve(bs); fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { ; } try { (new RealMatrixImpl(testData2)).luDecompose(); fail("Expecting InvalidMatrixException"); } catch (InvalidMatrixException ex) { ; } }
public void testsolve() { realmatriximpl m = new realmatriximpl(testdata); realmatrix minv = new realmatriximpl(testdatainv); assertclose("inverse-operate",minv.operate(testvector), m.solve(testvector),normtolerance); try { m.solve(testvector2); fail("expecting illegalargumentexception"); } catch (illegalargumentexception ex) { ; } realmatrix bs = new realmatriximpl(bigsingular); try { bs.solve(bs); fail("expecting invalidmatrixexception"); } catch (invalidmatrixexception ex) { ; } try { m.solve(bs); fail("expecting illegalargumentexception"); } catch (illegalargumentexception ex) { ; } try { new realmatriximpl(testdata2).solve(bs); fail("expecting illegalargumentexception"); } catch (illegalargumentexception ex) { ; } try { (new realmatriximpl(testdata2)).ludecompose(); fail("expecting invalidmatrixexception"); } catch (invalidmatrixexception ex) { ; } }
svenpopping/acfl-replication-package
[ 1, 0, 0, 0 ]
31,003
public static CompositeValue create(ICPPClassType classType, IASTNode point, int nestingLevel) { Set<ICPPClassType> recursionProtectionSet = fCreateInProgress.get(); if (!recursionProtectionSet.add(classType)) { return new CompositeValue(null, ICPPEvaluation.EMPTY_ARRAY); } try { if (sDEBUG && nestingLevel > 0) { System.out.println("CompositeValue.create(" + ASTTypeUtil.getType(classType) + ", " + nestingLevel + ")"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ System.out.flush(); } ActivationRecord record = new ActivationRecord(); ICPPEvaluation[] values = new ICPPEvaluation[ClassTypeHelper.getFields(classType, point).length]; // Recursively create all the base class member variables. ICPPBase[] bases = ClassTypeHelper.getBases(classType, point); for (ICPPBase base : bases) { IBinding baseClass = base.getBaseClass(); if (baseClass instanceof ICPPClassType) { ICPPClassType baseClassType = (ICPPClassType) baseClass; ICPPField[] baseFields = ClassTypeHelper.getDeclaredFields(baseClassType, point); IValue compValue = CompositeValue.create(baseClassType, point, nestingLevel + 1); for (ICPPField baseField : baseFields) { int fieldPos = CPPASTFieldReference.getFieldPosition(baseField); if (fieldPos == -1) { continue; } record.update(baseField, compValue.getSubValue(fieldPos)); // TODO(nathanridge): This won't work with multiple inheritance, since 'fieldPos' // is a field position in the base class' hierarchy, while values[] expects // as index a field position in classType's hierarchy. values[fieldPos] = compValue.getSubValue(fieldPos); } } } ICPPField[] fields = ClassTypeHelper.getDeclaredFields(classType, point); for (ICPPField field : fields) { if (field.isStatic()) continue; final ICPPEvaluation value = EvalUtil.getVariableValue(field, record, point); int fieldPos = CPPASTFieldReference.getFieldPosition(field); if (fieldPos == -1) { continue; } record.update(field, value); values[fieldPos] = value; } return new CompositeValue(null, values); } finally { recursionProtectionSet.remove(classType); } }
public static CompositeValue create(ICPPClassType classType, IASTNode point, int nestingLevel) { Set<ICPPClassType> recursionProtectionSet = fCreateInProgress.get(); if (!recursionProtectionSet.add(classType)) { return new CompositeValue(null, ICPPEvaluation.EMPTY_ARRAY); } try { if (sDEBUG && nestingLevel > 0) { System.out.println("CompositeValue.create(" + ASTTypeUtil.getType(classType) + ", " + nestingLevel + ")"); System.out.flush(); } ActivationRecord record = new ActivationRecord(); ICPPEvaluation[] values = new ICPPEvaluation[ClassTypeHelper.getFields(classType, point).length]; ICPPBase[] bases = ClassTypeHelper.getBases(classType, point); for (ICPPBase base : bases) { IBinding baseClass = base.getBaseClass(); if (baseClass instanceof ICPPClassType) { ICPPClassType baseClassType = (ICPPClassType) baseClass; ICPPField[] baseFields = ClassTypeHelper.getDeclaredFields(baseClassType, point); IValue compValue = CompositeValue.create(baseClassType, point, nestingLevel + 1); for (ICPPField baseField : baseFields) { int fieldPos = CPPASTFieldReference.getFieldPosition(baseField); if (fieldPos == -1) { continue; } record.update(baseField, compValue.getSubValue(fieldPos)); values[fieldPos] = compValue.getSubValue(fieldPos); } } } ICPPField[] fields = ClassTypeHelper.getDeclaredFields(classType, point); for (ICPPField field : fields) { if (field.isStatic()) continue; final ICPPEvaluation value = EvalUtil.getVariableValue(field, record, point); int fieldPos = CPPASTFieldReference.getFieldPosition(field); if (fieldPos == -1) { continue; } record.update(field, value); values[fieldPos] = value; } return new CompositeValue(null, values); } finally { recursionProtectionSet.remove(classType); } }
public static compositevalue create(icppclasstype classtype, iastnode point, int nestinglevel) { set<icppclasstype> recursionprotectionset = fcreateinprogress.get(); if (!recursionprotectionset.add(classtype)) { return new compositevalue(null, icppevaluation.empty_array); } try { if (sdebug && nestinglevel > 0) { system.out.println("compositevalue.create(" + asttypeutil.gettype(classtype) + ", " + nestinglevel + ")"); system.out.flush(); } activationrecord record = new activationrecord(); icppevaluation[] values = new icppevaluation[classtypehelper.getfields(classtype, point).length]; icppbase[] bases = classtypehelper.getbases(classtype, point); for (icppbase base : bases) { ibinding baseclass = base.getbaseclass(); if (baseclass instanceof icppclasstype) { icppclasstype baseclasstype = (icppclasstype) baseclass; icppfield[] basefields = classtypehelper.getdeclaredfields(baseclasstype, point); ivalue compvalue = compositevalue.create(baseclasstype, point, nestinglevel + 1); for (icppfield basefield : basefields) { int fieldpos = cppastfieldreference.getfieldposition(basefield); if (fieldpos == -1) { continue; } record.update(basefield, compvalue.getsubvalue(fieldpos)); values[fieldpos] = compvalue.getsubvalue(fieldpos); } } } icppfield[] fields = classtypehelper.getdeclaredfields(classtype, point); for (icppfield field : fields) { if (field.isstatic()) continue; final icppevaluation value = evalutil.getvariablevalue(field, record, point); int fieldpos = cppastfieldreference.getfieldposition(field); if (fieldpos == -1) { continue; } record.update(field, value); values[fieldpos] = value; } return new compositevalue(null, values); } finally { recursionprotectionset.remove(classtype); } }
seemoo-lab/polypyus_pdom
[ 0, 0, 1, 0 ]
22,978
private void checkPins(List<X509Certificate> chain) throws CertificateException { PinSet pinSet = mNetworkSecurityConfig.getPins(); if (pinSet.pins.isEmpty() || System.currentTimeMillis() > pinSet.expirationTime || !isPinningEnforced(chain)) { return; } Set<String> pinAlgorithms = pinSet.getPinAlgorithms(); Map<String, MessageDigest> digestMap = new ArrayMap<String, MessageDigest>( pinAlgorithms.size()); for (int i = chain.size() - 1; i >= 0 ; i--) { X509Certificate cert = chain.get(i); byte[] encodedSPKI = cert.getPublicKey().getEncoded(); for (String algorithm : pinAlgorithms) { MessageDigest md = digestMap.get(algorithm); if (md == null) { try { md = MessageDigest.getInstance(algorithm); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } digestMap.put(algorithm, md); } if (pinSet.pins.contains(new Pin(algorithm, md.digest(encodedSPKI)))) { return; } } } // TODO: Throw a subclass of CertificateException which indicates a pinning failure. throw new CertificateException("Pin verification failed"); }
private void checkPins(List<X509Certificate> chain) throws CertificateException { PinSet pinSet = mNetworkSecurityConfig.getPins(); if (pinSet.pins.isEmpty() || System.currentTimeMillis() > pinSet.expirationTime || !isPinningEnforced(chain)) { return; } Set<String> pinAlgorithms = pinSet.getPinAlgorithms(); Map<String, MessageDigest> digestMap = new ArrayMap<String, MessageDigest>( pinAlgorithms.size()); for (int i = chain.size() - 1; i >= 0 ; i--) { X509Certificate cert = chain.get(i); byte[] encodedSPKI = cert.getPublicKey().getEncoded(); for (String algorithm : pinAlgorithms) { MessageDigest md = digestMap.get(algorithm); if (md == null) { try { md = MessageDigest.getInstance(algorithm); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } digestMap.put(algorithm, md); } if (pinSet.pins.contains(new Pin(algorithm, md.digest(encodedSPKI)))) { return; } } } throw new CertificateException("Pin verification failed"); }
private void checkpins(list<x509certificate> chain) throws certificateexception { pinset pinset = mnetworksecurityconfig.getpins(); if (pinset.pins.isempty() || system.currenttimemillis() > pinset.expirationtime || !ispinningenforced(chain)) { return; } set<string> pinalgorithms = pinset.getpinalgorithms(); map<string, messagedigest> digestmap = new arraymap<string, messagedigest>( pinalgorithms.size()); for (int i = chain.size() - 1; i >= 0 ; i--) { x509certificate cert = chain.get(i); byte[] encodedspki = cert.getpublickey().getencoded(); for (string algorithm : pinalgorithms) { messagedigest md = digestmap.get(algorithm); if (md == null) { try { md = messagedigest.getinstance(algorithm); } catch (generalsecurityexception e) { throw new runtimeexception(e); } digestmap.put(algorithm, md); } if (pinset.pins.contains(new pin(algorithm, md.digest(encodedspki)))) { return; } } } throw new certificateexception("pin verification failed"); }
rio-31/android_frameworks_base-1
[ 0, 1, 0, 0 ]
23,034
private static boolean isOnline(){ try{ new URL("http://74.125.230.174").openConnection().connect(); //Confused? Copy the URL and paste it in your browser. return true; }catch (IOException e) { return false; } }
private static boolean isOnline(){ try{ new URL("http://74.125.230.174").openConnection().connect(); return true; }catch (IOException e) { return false; } }
private static boolean isonline(){ try{ new url("http://74.125.230.174").openconnection().connect(); return true; }catch (ioexception e) { return false; } }
scottkillen-vault/Bunyan
[ 1, 0, 0, 0 ]
31,253
private void verifyAllComponents() { // check root component has no generics if (!this.components.get(this.topname).getGenerics().isEmpty()) genericError(String.format("top component %s cannot contain generics", this.topname)); // verify all components for (Component component : this.components.values()) { this.currentComponent = component.name; this.verifyPortArch(component.ast); this.verifyIdentifiers(component.ast); this.verifyConstantExpressions(component.ast); this.verifyTypes(component.ast); } }
private void verifyAllComponents() { if (!this.components.get(this.topname).getGenerics().isEmpty()) genericError(String.format("top component %s cannot contain generics", this.topname)); for (Component component : this.components.values()) { this.currentComponent = component.name; this.verifyPortArch(component.ast); this.verifyIdentifiers(component.ast); this.verifyConstantExpressions(component.ast); this.verifyTypes(component.ast); } }
private void verifyallcomponents() { if (!this.components.get(this.topname).getgenerics().isempty()) genericerror(string.format("top component %s cannot contain generics", this.topname)); for (component component : this.components.values()) { this.currentcomponent = component.name; this.verifyportarch(component.ast); this.verifyidentifiers(component.ast); this.verifyconstantexpressions(component.ast); this.verifytypes(component.ast); } }
reed-foster/cdl
[ 0, 1, 0, 0 ]
23,074
public void testJ5_32_speculative() throws Exception { CppCompositeType J5_struct = createJ5_struct32(vbtManager32); J5_struct.createLayout(classLayoutChoice, vbtManager32, TaskMonitor.DUMMY); Composite composite = J5_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ5_32(), composite, true); }
public void testJ5_32_speculative() throws Exception { CppCompositeType J5_struct = createJ5_struct32(vbtManager32); J5_struct.createLayout(classLayoutChoice, vbtManager32, TaskMonitor.DUMMY); Composite composite = J5_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ5_32(), composite, true); }
public void testj5_32_speculative() throws exception { cppcompositetype j5_struct = createj5_struct32(vbtmanager32); j5_struct.createlayout(classlayoutchoice, vbtmanager32, taskmonitor.dummy); composite composite = j5_struct.getcomposite(); compositetestutils.assertexpectedcomposite(this, getspeculatedj5_32(), composite, true); }
sigurasg/ghidra
[ 1, 0, 0, 0 ]
23,075
public void testJ5_64_speculative() throws Exception { CppCompositeType J5_struct = createJ5_struct64(vbtManager64); J5_struct.createLayout(classLayoutChoice, vbtManager64, TaskMonitor.DUMMY); Composite composite = J5_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ5_64(), composite, true); }
public void testJ5_64_speculative() throws Exception { CppCompositeType J5_struct = createJ5_struct64(vbtManager64); J5_struct.createLayout(classLayoutChoice, vbtManager64, TaskMonitor.DUMMY); Composite composite = J5_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ5_64(), composite, true); }
public void testj5_64_speculative() throws exception { cppcompositetype j5_struct = createj5_struct64(vbtmanager64); j5_struct.createlayout(classlayoutchoice, vbtmanager64, taskmonitor.dummy); composite composite = j5_struct.getcomposite(); compositetestutils.assertexpectedcomposite(this, getspeculatedj5_64(), composite, true); }
sigurasg/ghidra
[ 1, 0, 0, 0 ]
23,076
public void testJ6_32_speculative() throws Exception { CppCompositeType J6_struct = createJ6_struct32(vbtManager32); J6_struct.createLayout(classLayoutChoice, vbtManager32, TaskMonitor.DUMMY); Composite composite = J6_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ6_32(), composite, true); }
public void testJ6_32_speculative() throws Exception { CppCompositeType J6_struct = createJ6_struct32(vbtManager32); J6_struct.createLayout(classLayoutChoice, vbtManager32, TaskMonitor.DUMMY); Composite composite = J6_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ6_32(), composite, true); }
public void testj6_32_speculative() throws exception { cppcompositetype j6_struct = createj6_struct32(vbtmanager32); j6_struct.createlayout(classlayoutchoice, vbtmanager32, taskmonitor.dummy); composite composite = j6_struct.getcomposite(); compositetestutils.assertexpectedcomposite(this, getspeculatedj6_32(), composite, true); }
sigurasg/ghidra
[ 1, 0, 0, 0 ]
23,077
public void testJ6_64_speculative() throws Exception { CppCompositeType J6_struct = createJ6_struct64(vbtManager64); J6_struct.createLayout(classLayoutChoice, vbtManager64, TaskMonitor.DUMMY); Composite composite = J6_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ6_64(), composite, true); }
public void testJ6_64_speculative() throws Exception { CppCompositeType J6_struct = createJ6_struct64(vbtManager64); J6_struct.createLayout(classLayoutChoice, vbtManager64, TaskMonitor.DUMMY); Composite composite = J6_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ6_64(), composite, true); }
public void testj6_64_speculative() throws exception { cppcompositetype j6_struct = createj6_struct64(vbtmanager64); j6_struct.createlayout(classlayoutchoice, vbtmanager64, taskmonitor.dummy); composite composite = j6_struct.getcomposite(); compositetestutils.assertexpectedcomposite(this, getspeculatedj6_64(), composite, true); }
sigurasg/ghidra
[ 1, 0, 0, 0 ]
31,319
public List<HeatConsumption> findHeatConsumptions() throws IOException { // TODO convert into model that contains electricity info also return heatRepository.findAll(); }
public List<HeatConsumption> findHeatConsumptions() throws IOException { return heatRepository.findAll(); }
public list<heatconsumption> findheatconsumptions() throws ioexception { return heatrepository.findall(); }
renanpelicari/java-kata
[ 0, 1, 0, 0 ]
31,329
public static Document parse(String text, int windowSize, JSONArray spacyEntities, JSONArray dbpediaEntities) { Document result = new Document(); result._originaltext = text; result._sentences = new java.util.ArrayList<Sentence>(); List<String> splitSentences = StanfordNLP.splitSentences(text); int lastFoundPosition = -1; int lastSentenceLength = 1; int sentenceCount = 0; int runningSentinmentScore = 0; // perform the window parsing - used to do coreref, plus get initial named entities, sentiment, and tokens for (int sentenceIndex = 0; sentenceIndex < splitSentences.size(); sentenceIndex++) { SplitResult sr = getTextWindow(splitSentences, sentenceIndex,windowSize); Annotation sentenceDoc = StanfordNLP.annotateText(sr.text); List<CoreMap> sentences = sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class); CoreMap sentence = sentences.get(sr.sentencePositionToUse); sentenceCount++; String sentenceText = sentence.get(CoreAnnotations.TextAnnotation.class); int documentPosition = text.indexOf(sentenceText,lastFoundPosition); if (documentPosition == -1) { documentPosition = lastFoundPosition + lastSentenceLength; } java.util.List<Token> sentenceTokens = Token.extractTokens(sentence, sentenceCount); Sentence s = new Sentence(sentenceText, documentPosition, sentenceCount, sentenceTokens); Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class); int sentiment = RNNCoreAnnotations.getPredictedClass(tree); s.setSentiment(sentiment); runningSentinmentScore += sentiment; List<String> resolvedSentences = Coreference.resolveCoreferences(sentenceDoc); s.setCorefText(resolvedSentences.get(sr.sentencePositionToUse)); result._sentences.add(s); lastFoundPosition = documentPosition; lastSentenceLength = sentenceText.length(); } result._sentimentScore = ((double) runningSentinmentScore) / sentenceCount; // reparse to get openIE / relations items int baseSentenceIndex = -1; for (Sentence s: result._sentences) { Annotation sentenceDoc = StanfordNLP.annotateText(s.getCorefText()); baseSentenceIndex++; java.util.List<Token> sentenceTokens = Token.extractTokens(sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class).get(0), baseSentenceIndex); java.util.List<TripleRelation> triples = TripleRelation.extractTriples(sentenceDoc, baseSentenceIndex); triples = TripleRelation.valiadateTriples(triples, sentenceTokens); List<AnnotatedProposition> minieTriplesAP = StanfordNLP.extractMinIETriples(s.getCorefText()); java.util.List<TripleRelation> minetriples = TripleRelation.extractTriples(minieTriplesAP, baseSentenceIndex); minetriples = TripleRelation.valiadateTriples(minetriples, sentenceTokens); java.util.List<TripleRelation> combinedTriples = TripleRelation.combine(triples, minetriples); combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MAXIMIZE_SUBJ_OBJ_MINIMIZE_RELATION); //combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MINIMIZE_TERMS); TripleRelation.augmentSubjectObjectWithStanfordNER(combinedTriples,s.getNamedEntities()); TripleRelation.augmentSubjectObjectWithSpacyNER(combinedTriples, spacyEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); TripleRelation.augmentSubjectObjectWithDBPedia(combinedTriples, dbpediaEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); s.setTripleRelations(combinedTriples); } return result; }
public static Document parse(String text, int windowSize, JSONArray spacyEntities, JSONArray dbpediaEntities) { Document result = new Document(); result._originaltext = text; result._sentences = new java.util.ArrayList<Sentence>(); List<String> splitSentences = StanfordNLP.splitSentences(text); int lastFoundPosition = -1; int lastSentenceLength = 1; int sentenceCount = 0; int runningSentinmentScore = 0; for (int sentenceIndex = 0; sentenceIndex < splitSentences.size(); sentenceIndex++) { SplitResult sr = getTextWindow(splitSentences, sentenceIndex,windowSize); Annotation sentenceDoc = StanfordNLP.annotateText(sr.text); List<CoreMap> sentences = sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class); CoreMap sentence = sentences.get(sr.sentencePositionToUse); sentenceCount++; String sentenceText = sentence.get(CoreAnnotations.TextAnnotation.class); int documentPosition = text.indexOf(sentenceText,lastFoundPosition); if (documentPosition == -1) { documentPosition = lastFoundPosition + lastSentenceLength; } java.util.List<Token> sentenceTokens = Token.extractTokens(sentence, sentenceCount); Sentence s = new Sentence(sentenceText, documentPosition, sentenceCount, sentenceTokens); Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class); int sentiment = RNNCoreAnnotations.getPredictedClass(tree); s.setSentiment(sentiment); runningSentinmentScore += sentiment; List<String> resolvedSentences = Coreference.resolveCoreferences(sentenceDoc); s.setCorefText(resolvedSentences.get(sr.sentencePositionToUse)); result._sentences.add(s); lastFoundPosition = documentPosition; lastSentenceLength = sentenceText.length(); } result._sentimentScore = ((double) runningSentinmentScore) / sentenceCount; int baseSentenceIndex = -1; for (Sentence s: result._sentences) { Annotation sentenceDoc = StanfordNLP.annotateText(s.getCorefText()); baseSentenceIndex++; java.util.List<Token> sentenceTokens = Token.extractTokens(sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class).get(0), baseSentenceIndex); java.util.List<TripleRelation> triples = TripleRelation.extractTriples(sentenceDoc, baseSentenceIndex); triples = TripleRelation.valiadateTriples(triples, sentenceTokens); List<AnnotatedProposition> minieTriplesAP = StanfordNLP.extractMinIETriples(s.getCorefText()); java.util.List<TripleRelation> minetriples = TripleRelation.extractTriples(minieTriplesAP, baseSentenceIndex); minetriples = TripleRelation.valiadateTriples(minetriples, sentenceTokens); java.util.List<TripleRelation> combinedTriples = TripleRelation.combine(triples, minetriples); combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MAXIMIZE_SUBJ_OBJ_MINIMIZE_RELATION); TripleRelation.augmentSubjectObjectWithStanfordNER(combinedTriples,s.getNamedEntities()); TripleRelation.augmentSubjectObjectWithSpacyNER(combinedTriples, spacyEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); TripleRelation.augmentSubjectObjectWithDBPedia(combinedTriples, dbpediaEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); s.setTripleRelations(combinedTriples); } return result; }
public static document parse(string text, int windowsize, jsonarray spacyentities, jsonarray dbpediaentities) { document result = new document(); result._originaltext = text; result._sentences = new java.util.arraylist<sentence>(); list<string> splitsentences = stanfordnlp.splitsentences(text); int lastfoundposition = -1; int lastsentencelength = 1; int sentencecount = 0; int runningsentinmentscore = 0; for (int sentenceindex = 0; sentenceindex < splitsentences.size(); sentenceindex++) { splitresult sr = gettextwindow(splitsentences, sentenceindex,windowsize); annotation sentencedoc = stanfordnlp.annotatetext(sr.text); list<coremap> sentences = sentencedoc.get(coreannotations.sentencesannotation.class); coremap sentence = sentences.get(sr.sentencepositiontouse); sentencecount++; string sentencetext = sentence.get(coreannotations.textannotation.class); int documentposition = text.indexof(sentencetext,lastfoundposition); if (documentposition == -1) { documentposition = lastfoundposition + lastsentencelength; } java.util.list<token> sentencetokens = token.extracttokens(sentence, sentencecount); sentence s = new sentence(sentencetext, documentposition, sentencecount, sentencetokens); tree tree = sentence.get(sentimentcoreannotations.sentimentannotatedtree.class); int sentiment = rnncoreannotations.getpredictedclass(tree); s.setsentiment(sentiment); runningsentinmentscore += sentiment; list<string> resolvedsentences = coreference.resolvecoreferences(sentencedoc); s.setcoreftext(resolvedsentences.get(sr.sentencepositiontouse)); result._sentences.add(s); lastfoundposition = documentposition; lastsentencelength = sentencetext.length(); } result._sentimentscore = ((double) runningsentinmentscore) / sentencecount; int basesentenceindex = -1; for (sentence s: result._sentences) { annotation sentencedoc = stanfordnlp.annotatetext(s.getcoreftext()); basesentenceindex++; java.util.list<token> sentencetokens = token.extracttokens(sentencedoc.get(coreannotations.sentencesannotation.class).get(0), basesentenceindex); java.util.list<triplerelation> triples = triplerelation.extracttriples(sentencedoc, basesentenceindex); triples = triplerelation.valiadatetriples(triples, sentencetokens); list<annotatedproposition> minietriplesap = stanfordnlp.extractminietriples(s.getcoreftext()); java.util.list<triplerelation> minetriples = triplerelation.extracttriples(minietriplesap, basesentenceindex); minetriples = triplerelation.valiadatetriples(minetriples, sentencetokens); java.util.list<triplerelation> combinedtriples = triplerelation.combine(triples, minetriples); combinedtriples = triplerelation.reducetriples(combinedtriples, filterstyle.filter_to_maximize_subj_obj_minimize_relation); triplerelation.augmentsubjectobjectwithstanfordner(combinedtriples,s.getnamedentities()); triplerelation.augmentsubjectobjectwithspacyner(combinedtriples, spacyentities, s.getstartposition(), s.getstartposition() + s.getoriginaltext().length()); triplerelation.augmentsubjectobjectwithdbpedia(combinedtriples, dbpediaentities, s.getstartposition(), s.getstartposition() + s.getoriginaltext().length()); s.settriplerelations(combinedtriples); } return result; }
slankas/OSKE
[ 0, 0, 0, 0 ]
31,468
public static boolean isProvidedUserChoicesForNodeInstance(Map<String, List<Parameter<?>>> userChoices, String nodeInstanceName) { if (userChoices == null || userChoices.isEmpty()) return false; List<Parameter<?>> paramsForNodeInstance = userChoices.get(nodeInstanceName); if (paramsForNodeInstance == null || paramsForNodeInstance.isEmpty()) return false; return true; }
public static boolean isProvidedUserChoicesForNodeInstance(Map<String, List<Parameter<?>>> userChoices, String nodeInstanceName) { if (userChoices == null || userChoices.isEmpty()) return false; List<Parameter<?>> paramsForNodeInstance = userChoices.get(nodeInstanceName); if (paramsForNodeInstance == null || paramsForNodeInstance.isEmpty()) return false; return true; }
public static boolean isprovideduserchoicesfornodeinstance(map<string, list<parameter<?>>> userchoices, string nodeinstancename) { if (userchoices == null || userchoices.isempty()) return false; list<parameter<?>> paramsfornodeinstance = userchoices.get(nodeinstancename); if (paramsfornodeinstance == null || paramsfornodeinstance.isempty()) return false; return true; }
slipstream/cimi-mf2c
[ 1, 0, 0, 0 ]
15,468
private void handleUpload(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException, WsException { checkPermission(WebswingAction.file_upload); try { String uuid = request.getParameter("uuid"); if (uuid != null) { SwingInstance instance = manager.findInstanceBySessionId(uuid); if (instance != null) { double maxMB = instance.getAppConfig().getUploadMaxSize(); long maxsize = (long) (maxMB * 1024 * 1024); Part filePart = request.getPart("files[]"); // Retrieves <input type="file" name="file"> String filename = getFilename(filePart); if (maxsize > 0 && filePart.getSize() > maxsize) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.getWriter().write(String.format("File '%s' is too large. (Max. file size is %.1fMB)", filename, maxMB)); } else { String tempDir = System.getProperty(Constants.TEMP_DIR_PATH); String tempName = UUID.randomUUID().toString(); InputStream filecontent = filePart.getInputStream(); File f = new File(URI.create(tempDir + "/" + tempName)); FileOutputStream output = new FileOutputStream(f); IOUtils.copy(filecontent, output); output.close(); filecontent.close(); log.info("File " + filename + " uploaded (size:" + filePart.getSize() + ") to " + f.getAbsolutePath()); UploadEventMsgIn msg = new UploadEventMsgIn(); msg.setFileName(filename); msg.setTempFileLocation(f.getAbsolutePath()); boolean sent = instance.sendToSwing(null, msg); if (!sent) { log.error("Failed to send upload notification to app session. File:" + filename + "+ClientID:" + instance.getClientId()); f.delete(); } else { resp.getWriter().write("{\"files\":[{\"name\":\"" + filename + "\"}]}"); // TODO size } } } else { throw new Exception("Related App instance not found.(" + uuid + ")"); } } else { throw new Exception("UUID not specified in request"); } } catch (Exception e) { if (e.getCause() instanceof EOFException) { log.warn("File upload canceled by user: " + e.getMessage()); } else { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.getWriter().write("Upload finished with error..."); log.error("Error while uploading file: " + e.getMessage(), e); } } }
private void handleUpload(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException, WsException { checkPermission(WebswingAction.file_upload); try { String uuid = request.getParameter("uuid"); if (uuid != null) { SwingInstance instance = manager.findInstanceBySessionId(uuid); if (instance != null) { double maxMB = instance.getAppConfig().getUploadMaxSize(); long maxsize = (long) (maxMB * 1024 * 1024); Part filePart = request.getPart("files[]"); String filename = getFilename(filePart); if (maxsize > 0 && filePart.getSize() > maxsize) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.getWriter().write(String.format("File '%s' is too large. (Max. file size is %.1fMB)", filename, maxMB)); } else { String tempDir = System.getProperty(Constants.TEMP_DIR_PATH); String tempName = UUID.randomUUID().toString(); InputStream filecontent = filePart.getInputStream(); File f = new File(URI.create(tempDir + "/" + tempName)); FileOutputStream output = new FileOutputStream(f); IOUtils.copy(filecontent, output); output.close(); filecontent.close(); log.info("File " + filename + " uploaded (size:" + filePart.getSize() + ") to " + f.getAbsolutePath()); UploadEventMsgIn msg = new UploadEventMsgIn(); msg.setFileName(filename); msg.setTempFileLocation(f.getAbsolutePath()); boolean sent = instance.sendToSwing(null, msg); if (!sent) { log.error("Failed to send upload notification to app session. File:" + filename + "+ClientID:" + instance.getClientId()); f.delete(); } else { resp.getWriter().write("{\"files\":[{\"name\":\"" + filename + "\"}]}"); } } } else { throw new Exception("Related App instance not found.(" + uuid + ")"); } } else { throw new Exception("UUID not specified in request"); } } catch (Exception e) { if (e.getCause() instanceof EOFException) { log.warn("File upload canceled by user: " + e.getMessage()); } else { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.getWriter().write("Upload finished with error..."); log.error("Error while uploading file: " + e.getMessage(), e); } } }
private void handleupload(httpservletrequest request, httpservletresponse resp) throws servletexception, ioexception, wsexception { checkpermission(webswingaction.file_upload); try { string uuid = request.getparameter("uuid"); if (uuid != null) { swinginstance instance = manager.findinstancebysessionid(uuid); if (instance != null) { double maxmb = instance.getappconfig().getuploadmaxsize(); long maxsize = (long) (maxmb * 1024 * 1024); part filepart = request.getpart("files[]"); string filename = getfilename(filepart); if (maxsize > 0 && filepart.getsize() > maxsize) { resp.setstatus(httpservletresponse.sc_bad_request); resp.getwriter().write(string.format("file '%s' is too large. (max. file size is %.1fmb)", filename, maxmb)); } else { string tempdir = system.getproperty(constants.temp_dir_path); string tempname = uuid.randomuuid().tostring(); inputstream filecontent = filepart.getinputstream(); file f = new file(uri.create(tempdir + "/" + tempname)); fileoutputstream output = new fileoutputstream(f); ioutils.copy(filecontent, output); output.close(); filecontent.close(); log.info("file " + filename + " uploaded (size:" + filepart.getsize() + ") to " + f.getabsolutepath()); uploadeventmsgin msg = new uploadeventmsgin(); msg.setfilename(filename); msg.settempfilelocation(f.getabsolutepath()); boolean sent = instance.sendtoswing(null, msg); if (!sent) { log.error("failed to send upload notification to app session. file:" + filename + "+clientid:" + instance.getclientid()); f.delete(); } else { resp.getwriter().write("{\"files\":[{\"name\":\"" + filename + "\"}]}"); } } } else { throw new exception("related app instance not found.(" + uuid + ")"); } } else { throw new exception("uuid not specified in request"); } } catch (exception e) { if (e.getcause() instanceof eofexception) { log.warn("file upload canceled by user: " + e.getmessage()); } else { resp.setstatus(httpservletresponse.sc_internal_server_error); resp.getwriter().write("upload finished with error..."); log.error("error while uploading file: " + e.getmessage(), e); } } }
swing-fly/webswing
[ 0, 0, 0, 0 ]
15,624
@Override public void enableSupportForSerializationIfApplicable(CancelIndicator cancelIndicator) { if (!IterableExtensions.isNullOrEmpty(targetConfig.protoFiles)) { // Enable support for proto serialization enabledSerializers.add(SupportedSerializers.PROTO); } for (SupportedSerializers serialization : enabledSerializers) { switch (serialization) { case NATIVE: { FedNativePythonSerialization pickler = new FedNativePythonSerialization(); code.pr(pickler.generatePreambleForSupport().toString()); } case PROTO: { // Handle .proto files. for (String name : targetConfig.protoFiles) { this.processProtoFile(name, cancelIndicator); int dotIndex = name.lastIndexOf("."); String rootFilename = dotIndex > 0 ? name.substring(0, dotIndex) : name; pythonPreamble.pr("import "+rootFilename+"_pb2 as "+rootFilename); protoNames.add(rootFilename); } } case ROS2: { // FIXME: Not supported yet } } } }
@Override public void enableSupportForSerializationIfApplicable(CancelIndicator cancelIndicator) { if (!IterableExtensions.isNullOrEmpty(targetConfig.protoFiles)) { enabledSerializers.add(SupportedSerializers.PROTO); } for (SupportedSerializers serialization : enabledSerializers) { switch (serialization) { case NATIVE: { FedNativePythonSerialization pickler = new FedNativePythonSerialization(); code.pr(pickler.generatePreambleForSupport().toString()); } case PROTO: { for (String name : targetConfig.protoFiles) { this.processProtoFile(name, cancelIndicator); int dotIndex = name.lastIndexOf("."); String rootFilename = dotIndex > 0 ? name.substring(0, dotIndex) : name; pythonPreamble.pr("import "+rootFilename+"_pb2 as "+rootFilename); protoNames.add(rootFilename); } } case ROS2: { } } } }
@override public void enablesupportforserializationifapplicable(cancelindicator cancelindicator) { if (!iterableextensions.isnullorempty(targetconfig.protofiles)) { enabledserializers.add(supportedserializers.proto); } for (supportedserializers serialization : enabledserializers) { switch (serialization) { case native: { fednativepythonserialization pickler = new fednativepythonserialization(); code.pr(pickler.generatepreambleforsupport().tostring()); } case proto: { for (string name : targetconfig.protofiles) { this.processprotofile(name, cancelindicator); int dotindex = name.lastindexof("."); string rootfilename = dotindex > 0 ? name.substring(0, dotindex) : name; pythonpreamble.pr("import "+rootfilename+"_pb2 as "+rootfilename); protonames.add(rootfilename); } } case ros2: { } } } }
soerendomroes/lingua-franca
[ 0, 1, 0, 0 ]
15,626
@Override public void writeDockerFile(File dockerComposeDir, String dockerFileName, String federateName) { if (mainDef == null) { return; } Path srcGenPath = fileConfig.getSrcGenPath(); String dockerFile = srcGenPath + File.separator + dockerFileName; CodeBuilder contents = new CodeBuilder(); contents.pr(PythonDockerGenerator.generateDockerFileContent(topLevelName, srcGenPath)); try { // If a dockerfile exists, remove it. Files.deleteIfExists(srcGenPath.resolve(dockerFileName)); contents.writeToFile(dockerFile); } catch (IOException e) { Exceptions.sneakyThrow(e); } System.out.println(getDockerBuildCommand(dockerFile, dockerComposeDir, federateName)); }
@Override public void writeDockerFile(File dockerComposeDir, String dockerFileName, String federateName) { if (mainDef == null) { return; } Path srcGenPath = fileConfig.getSrcGenPath(); String dockerFile = srcGenPath + File.separator + dockerFileName; CodeBuilder contents = new CodeBuilder(); contents.pr(PythonDockerGenerator.generateDockerFileContent(topLevelName, srcGenPath)); try { Files.deleteIfExists(srcGenPath.resolve(dockerFileName)); contents.writeToFile(dockerFile); } catch (IOException e) { Exceptions.sneakyThrow(e); } System.out.println(getDockerBuildCommand(dockerFile, dockerComposeDir, federateName)); }
@override public void writedockerfile(file dockercomposedir, string dockerfilename, string federatename) { if (maindef == null) { return; } path srcgenpath = fileconfig.getsrcgenpath(); string dockerfile = srcgenpath + file.separator + dockerfilename; codebuilder contents = new codebuilder(); contents.pr(pythondockergenerator.generatedockerfilecontent(toplevelname, srcgenpath)); try { files.deleteifexists(srcgenpath.resolve(dockerfilename)); contents.writetofile(dockerfile); } catch (ioexception e) { exceptions.sneakythrow(e); } system.out.println(getdockerbuildcommand(dockerfile, dockercomposedir, federatename)); }
soerendomroes/lingua-franca
[ 0, 0, 0, 0 ]
32,106
@Test public void testMakePaymentForSavingsAccountOnDeposit() throws Exception { savingsBO = createClientSavingsAccount(); String deposit = "400"; CustomerDto clientDto = new CustomerDto(); clientDto.setCustomerId(client.getCustomerId()); //FIXME why one day in future payment is allowed LocalDate paymentDate = new LocalDate().plusDays(1); LocalDate receiptDate = new LocalDate().minusDays(3); String receiptNumber = "AA/03/UX-9Q"; Assert.assertEquals(0, savingsBO.getAccountPayments().size()); AccountPaymentParametersDto depositPayment = new AccountPaymentParametersDto(new UserReferenceDto(savingsBO .getPersonnel().getPersonnelId()), new AccountReferenceDto(savingsBO.getAccountId()), new BigDecimal( deposit), paymentDate, defaultPaymentType, "comment", receiptDate, receiptNumber, clientDto); standardAccountService.makePayment(depositPayment); TestObjectFactory.updateObject(savingsBO); Assert.assertEquals("The amount returned for the payment should have been " + deposit, Double .parseDouble(deposit), savingsBO.getLastPmntAmnt()); Assert.assertEquals(1, savingsBO.getAccountPayments().size()); for (AccountPaymentEntity payment : savingsBO.getAccountPayments()) { Assert.assertEquals(TestUtils.createMoney(deposit), payment.getAmount()); Assert.assertEquals(1, payment.getAccountTrxns().size()); Assert.assertEquals(paymentDate.toDateMidnight().toDate(), payment.getPaymentDate()); Assert.assertEquals(defaultPaymentType.getName(), payment.getPaymentType().getName()); Assert.assertEquals("comment", payment.getComment()); Assert.assertEquals(savingsBO, payment.getAccount()); Assert.assertEquals(savingsBO.getPersonnel(), payment.getCreatedByUser()); Assert.assertEquals(receiptDate.toDateMidnight().toDate(), payment.getReceiptDate()); Assert.assertEquals(receiptNumber, payment.getReceiptNumber()); Assert.assertNull(payment.getCheckNumber()); Assert.assertNull(payment.getBankName()); Assert.assertNull(payment.getVoucherNumber()); Assert.assertTrue(payment.isSavingsDeposit()); Assert.assertFalse(payment.isSavingsWithdrawal()); Assert.assertTrue(payment.isSavingsDepositOrWithdrawal()); for (AccountTrxnEntity accountTrxn : payment.getAccountTrxns()) { Assert.assertEquals(client.getCustomerId(), accountTrxn.getCustomer().getCustomerId()); } } }
@Test public void testMakePaymentForSavingsAccountOnDeposit() throws Exception { savingsBO = createClientSavingsAccount(); String deposit = "400"; CustomerDto clientDto = new CustomerDto(); clientDto.setCustomerId(client.getCustomerId()); LocalDate paymentDate = new LocalDate().plusDays(1); LocalDate receiptDate = new LocalDate().minusDays(3); String receiptNumber = "AA/03/UX-9Q"; Assert.assertEquals(0, savingsBO.getAccountPayments().size()); AccountPaymentParametersDto depositPayment = new AccountPaymentParametersDto(new UserReferenceDto(savingsBO .getPersonnel().getPersonnelId()), new AccountReferenceDto(savingsBO.getAccountId()), new BigDecimal( deposit), paymentDate, defaultPaymentType, "comment", receiptDate, receiptNumber, clientDto); standardAccountService.makePayment(depositPayment); TestObjectFactory.updateObject(savingsBO); Assert.assertEquals("The amount returned for the payment should have been " + deposit, Double .parseDouble(deposit), savingsBO.getLastPmntAmnt()); Assert.assertEquals(1, savingsBO.getAccountPayments().size()); for (AccountPaymentEntity payment : savingsBO.getAccountPayments()) { Assert.assertEquals(TestUtils.createMoney(deposit), payment.getAmount()); Assert.assertEquals(1, payment.getAccountTrxns().size()); Assert.assertEquals(paymentDate.toDateMidnight().toDate(), payment.getPaymentDate()); Assert.assertEquals(defaultPaymentType.getName(), payment.getPaymentType().getName()); Assert.assertEquals("comment", payment.getComment()); Assert.assertEquals(savingsBO, payment.getAccount()); Assert.assertEquals(savingsBO.getPersonnel(), payment.getCreatedByUser()); Assert.assertEquals(receiptDate.toDateMidnight().toDate(), payment.getReceiptDate()); Assert.assertEquals(receiptNumber, payment.getReceiptNumber()); Assert.assertNull(payment.getCheckNumber()); Assert.assertNull(payment.getBankName()); Assert.assertNull(payment.getVoucherNumber()); Assert.assertTrue(payment.isSavingsDeposit()); Assert.assertFalse(payment.isSavingsWithdrawal()); Assert.assertTrue(payment.isSavingsDepositOrWithdrawal()); for (AccountTrxnEntity accountTrxn : payment.getAccountTrxns()) { Assert.assertEquals(client.getCustomerId(), accountTrxn.getCustomer().getCustomerId()); } } }
@test public void testmakepaymentforsavingsaccountondeposit() throws exception { savingsbo = createclientsavingsaccount(); string deposit = "400"; customerdto clientdto = new customerdto(); clientdto.setcustomerid(client.getcustomerid()); localdate paymentdate = new localdate().plusdays(1); localdate receiptdate = new localdate().minusdays(3); string receiptnumber = "aa/03/ux-9q"; assert.assertequals(0, savingsbo.getaccountpayments().size()); accountpaymentparametersdto depositpayment = new accountpaymentparametersdto(new userreferencedto(savingsbo .getpersonnel().getpersonnelid()), new accountreferencedto(savingsbo.getaccountid()), new bigdecimal( deposit), paymentdate, defaultpaymenttype, "comment", receiptdate, receiptnumber, clientdto); standardaccountservice.makepayment(depositpayment); testobjectfactory.updateobject(savingsbo); assert.assertequals("the amount returned for the payment should have been " + deposit, double .parsedouble(deposit), savingsbo.getlastpmntamnt()); assert.assertequals(1, savingsbo.getaccountpayments().size()); for (accountpaymententity payment : savingsbo.getaccountpayments()) { assert.assertequals(testutils.createmoney(deposit), payment.getamount()); assert.assertequals(1, payment.getaccounttrxns().size()); assert.assertequals(paymentdate.todatemidnight().todate(), payment.getpaymentdate()); assert.assertequals(defaultpaymenttype.getname(), payment.getpaymenttype().getname()); assert.assertequals("comment", payment.getcomment()); assert.assertequals(savingsbo, payment.getaccount()); assert.assertequals(savingsbo.getpersonnel(), payment.getcreatedbyuser()); assert.assertequals(receiptdate.todatemidnight().todate(), payment.getreceiptdate()); assert.assertequals(receiptnumber, payment.getreceiptnumber()); assert.assertnull(payment.getchecknumber()); assert.assertnull(payment.getbankname()); assert.assertnull(payment.getvouchernumber()); assert.asserttrue(payment.issavingsdeposit()); assert.assertfalse(payment.issavingswithdrawal()); assert.asserttrue(payment.issavingsdepositorwithdrawal()); for (accounttrxnentity accounttrxn : payment.getaccounttrxns()) { assert.assertequals(client.getcustomerid(), accounttrxn.getcustomer().getcustomerid()); } } }
sureshkrishnamoorthy/suresh-mifos
[ 1, 0, 0, 0 ]
32,149
public static int raiseTo(int n, int p) { if (n == 0) { return 0; } if (p == 0) { return 1; } if (n == 1) { return n; } long result = n; int counter = 1; while (counter < p) { if (result * n >= Integer.MAX_VALUE) { return Integer.MAX_VALUE; } result *= n; counter++; } return (int) result; }
public static int raiseTo(int n, int p) { if (n == 0) { return 0; } if (p == 0) { return 1; } if (n == 1) { return n; } long result = n; int counter = 1; while (counter < p) { if (result * n >= Integer.MAX_VALUE) { return Integer.MAX_VALUE; } result *= n; counter++; } return (int) result; }
public static int raiseto(int n, int p) { if (n == 0) { return 0; } if (p == 0) { return 1; } if (n == 1) { return n; } long result = n; int counter = 1; while (counter < p) { if (result * n >= integer.max_value) { return integer.max_value; } result *= n; counter++; } return (int) result; }
sachinlala/JavaPerfTests
[ 1, 0, 0, 0 ]
24,068
public static String assignShard(DocCollection collection, Integer numShards) { if (numShards == null) { numShards = 1; } String returnShardId = null; Map<String, Slice> sliceMap = collection != null ? collection.getActiveSlicesMap() : null; // TODO: now that we create shards ahead of time, is this code needed? Esp since hash ranges aren't assigned when creating via this method? if (sliceMap == null) { return "shard1"; } List<String> shardIdNames = new ArrayList<>(sliceMap.keySet()); if (shardIdNames.size() < numShards) { return "shard" + (shardIdNames.size() + 1); } // TODO: don't need to sort to find shard with fewest replicas! // else figure out which shard needs more replicas final Map<String, Integer> map = new HashMap<>(); for (String shardId : shardIdNames) { int cnt = sliceMap.get(shardId).getReplicasMap().size(); map.put(shardId, cnt); } Collections.sort(shardIdNames, (String o1, String o2) -> { Integer one = map.get(o1); Integer two = map.get(o2); return one.compareTo(two); }); returnShardId = shardIdNames.get(0); return returnShardId; }
public static String assignShard(DocCollection collection, Integer numShards) { if (numShards == null) { numShards = 1; } String returnShardId = null; Map<String, Slice> sliceMap = collection != null ? collection.getActiveSlicesMap() : null; if (sliceMap == null) { return "shard1"; } List<String> shardIdNames = new ArrayList<>(sliceMap.keySet()); if (shardIdNames.size() < numShards) { return "shard" + (shardIdNames.size() + 1); } final Map<String, Integer> map = new HashMap<>(); for (String shardId : shardIdNames) { int cnt = sliceMap.get(shardId).getReplicasMap().size(); map.put(shardId, cnt); } Collections.sort(shardIdNames, (String o1, String o2) -> { Integer one = map.get(o1); Integer two = map.get(o2); return one.compareTo(two); }); returnShardId = shardIdNames.get(0); return returnShardId; }
public static string assignshard(doccollection collection, integer numshards) { if (numshards == null) { numshards = 1; } string returnshardid = null; map<string, slice> slicemap = collection != null ? collection.getactiveslicesmap() : null; if (slicemap == null) { return "shard1"; } list<string> shardidnames = new arraylist<>(slicemap.keyset()); if (shardidnames.size() < numshards) { return "shard" + (shardidnames.size() + 1); } final map<string, integer> map = new hashmap<>(); for (string shardid : shardidnames) { int cnt = slicemap.get(shardid).getreplicasmap().size(); map.put(shardid, cnt); } collections.sort(shardidnames, (string o1, string o2) -> { integer one = map.get(o1); integer two = map.get(o2); return one.compareto(two); }); returnshardid = shardidnames.get(0); return returnshardid; }
robin850/solr
[ 1, 0, 0, 0 ]
24,102
@Test @MediumTest public void testAppButtonExitsVoiceInput() throws InterruptedException { Runnable exitAction = () -> { NativeUiUtils.clickAppButton(UserFriendlyElementName.CURRENT_POSITION, new PointF()); }; testExitVoiceInputImpl(exitAction); }
@Test @MediumTest public void testAppButtonExitsVoiceInput() throws InterruptedException { Runnable exitAction = () -> { NativeUiUtils.clickAppButton(UserFriendlyElementName.CURRENT_POSITION, new PointF()); }; testExitVoiceInputImpl(exitAction); }
@test @mediumtest public void testappbuttonexitsvoiceinput() throws interruptedexception { runnable exitaction = () -> { nativeuiutils.clickappbutton(userfriendlyelementname.current_position, new pointf()); }; testexitvoiceinputimpl(exitaction); }
sarang-apps/darshan_browser
[ 0, 0, 0, 1 ]
15,921
public static Map<String, List<Object>> parseAttributes(String samlResponse, Set<String> attributes) throws ServletException { Map<String, List<Object>> parsedResult = new HashMap<>(); // TODO - Using a library for managing collections if (attributes == null || attributes.isEmpty()) { return parsedResult; } byte[] samlAssertionDecoded = new byte[0]; try { samlAssertionDecoded = Base64.decodeBase64(samlResponse.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unsupported encoding to decode Saml Response"); } ByteArrayInputStream is = new ByteArrayInputStream(samlAssertionDecoded); Assertion assertion; try { DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(is); Element element = document.getDocumentElement(); Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element); if (unmarshaller == null) { throw new RuntimeException("Could not find an unmarshaller for XML parsing"); } XMLObject responseXmlObj = unmarshaller.unmarshall(element); Response response = (Response) responseXmlObj; if (response.getAssertions() == null || response.getAssertions().isEmpty()) { throw new ServletException("No assertions found in SAML response"); } assertion = response.getAssertions().get(0); } catch (UnmarshallingException | ParserConfigurationException | SAXException | IOException e) { throw new ServletException("Could not parse the SAML assertion", e); } for (AttributeStatement attributeStatement : assertion.getAttributeStatements()) { for (Attribute attribute : attributeStatement.getAttributes()) { if (attributes.contains(attribute.getName())) { List<Object> values = new ArrayList<>(attribute.getAttributeValues()); parsedResult.put(attribute.getName(), values); } } } return parsedResult; }
public static Map<String, List<Object>> parseAttributes(String samlResponse, Set<String> attributes) throws ServletException { Map<String, List<Object>> parsedResult = new HashMap<>(); if (attributes == null || attributes.isEmpty()) { return parsedResult; } byte[] samlAssertionDecoded = new byte[0]; try { samlAssertionDecoded = Base64.decodeBase64(samlResponse.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unsupported encoding to decode Saml Response"); } ByteArrayInputStream is = new ByteArrayInputStream(samlAssertionDecoded); Assertion assertion; try { DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(is); Element element = document.getDocumentElement(); Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element); if (unmarshaller == null) { throw new RuntimeException("Could not find an unmarshaller for XML parsing"); } XMLObject responseXmlObj = unmarshaller.unmarshall(element); Response response = (Response) responseXmlObj; if (response.getAssertions() == null || response.getAssertions().isEmpty()) { throw new ServletException("No assertions found in SAML response"); } assertion = response.getAssertions().get(0); } catch (UnmarshallingException | ParserConfigurationException | SAXException | IOException e) { throw new ServletException("Could not parse the SAML assertion", e); } for (AttributeStatement attributeStatement : assertion.getAttributeStatements()) { for (Attribute attribute : attributeStatement.getAttributes()) { if (attributes.contains(attribute.getName())) { List<Object> values = new ArrayList<>(attribute.getAttributeValues()); parsedResult.put(attribute.getName(), values); } } } return parsedResult; }
public static map<string, list<object>> parseattributes(string samlresponse, set<string> attributes) throws servletexception { map<string, list<object>> parsedresult = new hashmap<>(); if (attributes == null || attributes.isempty()) { return parsedresult; } byte[] samlassertiondecoded = new byte[0]; try { samlassertiondecoded = base64.decodebase64(samlresponse.getbytes("utf-8")); } catch (unsupportedencodingexception e) { throw new runtimeexception("unsupported encoding to decode saml response"); } bytearrayinputstream is = new bytearrayinputstream(samlassertiondecoded); assertion assertion; try { documentbuilder builder = factory.newdocumentbuilder(); document document = builder.parse(is); element element = document.getdocumentelement(); unmarshaller unmarshaller = unmarshallerfactory.getunmarshaller(element); if (unmarshaller == null) { throw new runtimeexception("could not find an unmarshaller for xml parsing"); } xmlobject responsexmlobj = unmarshaller.unmarshall(element); response response = (response) responsexmlobj; if (response.getassertions() == null || response.getassertions().isempty()) { throw new servletexception("no assertions found in saml response"); } assertion = response.getassertions().get(0); } catch (unmarshallingexception | parserconfigurationexception | saxexception | ioexception e) { throw new servletexception("could not parse the saml assertion", e); } for (attributestatement attributestatement : assertion.getattributestatements()) { for (attribute attribute : attributestatement.getattributes()) { if (attributes.contains(attribute.getname())) { list<object> values = new arraylist<>(attribute.getattributevalues()); parsedresult.put(attribute.getname(), values); } } } return parsedresult; }
sharad-oss/knox
[ 0, 1, 0, 0 ]
16,008
@Override public void makeMove() { // TODO Not just randomly select a tile to mark while (true) { try { List<Tile> tiles = getGameLogic().getTerritory().getTiles(); Tile tile = tiles.get(GameLogic.RANDOM.nextInt(tiles.size())); tile.setMarkedPlayer(this); getGameLogic().endMove(); return; } catch (TileAreadyMarkedException e) { } } }
@Override public void makeMove() { while (true) { try { List<Tile> tiles = getGameLogic().getTerritory().getTiles(); Tile tile = tiles.get(GameLogic.RANDOM.nextInt(tiles.size())); tile.setMarkedPlayer(this); getGameLogic().endMove(); return; } catch (TileAreadyMarkedException e) { } } }
@override public void makemove() { while (true) { try { list<tile> tiles = getgamelogic().getterritory().gettiles(); tile tile = tiles.get(gamelogic.random.nextint(tiles.size())); tile.setmarkedplayer(this); getgamelogic().endmove(); return; } catch (tileareadymarkedexception e) { } } }
sengerts/tic-tac-toe
[ 1, 0, 0, 0 ]
16,106
public static String getData() { Future<String> f = getInstance().startupFuture.get(); if (f == null) { // FIXME haven't even started yet... need to busy-wait, perhaps } try { String data = f.get(30, TimeUnit.SECONDS); return data; } catch (InterruptedException | ExecutionException e) { // FIXME failed to startup or was interrupted during startup; maybe throw to the caller? throw new IllegalStateException(e); } catch (TimeoutException e) { // FIXME got tired of waiting, maybe do something special here? throw new IllegalStateException(e); } }
public static String getData() { Future<String> f = getInstance().startupFuture.get(); if (f == null) { } try { String data = f.get(30, TimeUnit.SECONDS); return data; } catch (InterruptedException | ExecutionException e) { throw new IllegalStateException(e); } catch (TimeoutException e) { throw new IllegalStateException(e); } }
public static string getdata() { future<string> f = getinstance().startupfuture.get(); if (f == null) { } try { string data = f.get(30, timeunit.seconds); return data; } catch (interruptedexception | executionexception e) { throw new illegalstateexception(e); } catch (timeoutexception e) { throw new illegalstateexception(e); } }
seemikehack/synchronized-startup
[ 0, 0, 1, 0 ]
8,111
public synchronized void start() throws IOException, InterruptedException { final AtomicBoolean bound = new AtomicBoolean(); running.set(true); Thread t = new Thread(new Runnable() { @Override public void run() { try { ServerSocket ss = new ServerSocket(port); synchronized (bound) { bound.set(true); bound.notifyAll(); } Socket[] conn = new Socket[nDataGens]; try { for (int i = 0; i < nDataGens; i++) { conn[i] = ss.accept(); } for (int n = 0; n < nIntervals; ++n) { //TODO refactor operations according to the protocol message if (flagStopResume) { for (int i = 0; i < nDataGens; i++) { receiveStopped(conn[i]); } protocolActions[n].perform(); if (n != nIntervals - 1) { for (int i = 0; i < nDataGens; i++) { sendResume(conn[i]); } } } else { for (int i = 0; i < nDataGens; i++) { receiveReached(conn[i]); } protocolActions[n].perform(); } } } finally { for (int i = 0; i < conn.length; ++i) { if (conn[i] != null) { conn[i].close(); } } ss.close(); } running.set(false); synchronized (OrchestratorServer.this) { OrchestratorServer.this.notifyAll(); } } catch (Throwable t) { t.printStackTrace(); } } }); t.start(); synchronized (bound) { while (!bound.get()) { bound.wait(); } } }
public synchronized void start() throws IOException, InterruptedException { final AtomicBoolean bound = new AtomicBoolean(); running.set(true); Thread t = new Thread(new Runnable() { @Override public void run() { try { ServerSocket ss = new ServerSocket(port); synchronized (bound) { bound.set(true); bound.notifyAll(); } Socket[] conn = new Socket[nDataGens]; try { for (int i = 0; i < nDataGens; i++) { conn[i] = ss.accept(); } for (int n = 0; n < nIntervals; ++n) { if (flagStopResume) { for (int i = 0; i < nDataGens; i++) { receiveStopped(conn[i]); } protocolActions[n].perform(); if (n != nIntervals - 1) { for (int i = 0; i < nDataGens; i++) { sendResume(conn[i]); } } } else { for (int i = 0; i < nDataGens; i++) { receiveReached(conn[i]); } protocolActions[n].perform(); } } } finally { for (int i = 0; i < conn.length; ++i) { if (conn[i] != null) { conn[i].close(); } } ss.close(); } running.set(false); synchronized (OrchestratorServer.this) { OrchestratorServer.this.notifyAll(); } } catch (Throwable t) { t.printStackTrace(); } } }); t.start(); synchronized (bound) { while (!bound.get()) { bound.wait(); } } }
public synchronized void start() throws ioexception, interruptedexception { final atomicboolean bound = new atomicboolean(); running.set(true); thread t = new thread(new runnable() { @override public void run() { try { serversocket ss = new serversocket(port); synchronized (bound) { bound.set(true); bound.notifyall(); } socket[] conn = new socket[ndatagens]; try { for (int i = 0; i < ndatagens; i++) { conn[i] = ss.accept(); } for (int n = 0; n < nintervals; ++n) { if (flagstopresume) { for (int i = 0; i < ndatagens; i++) { receivestopped(conn[i]); } protocolactions[n].perform(); if (n != nintervals - 1) { for (int i = 0; i < ndatagens; i++) { sendresume(conn[i]); } } } else { for (int i = 0; i < ndatagens; i++) { receivereached(conn[i]); } protocolactions[n].perform(); } } } finally { for (int i = 0; i < conn.length; ++i) { if (conn[i] != null) { conn[i].close(); } } ss.close(); } running.set(false); synchronized (orchestratorserver.this) { orchestratorserver.this.notifyall(); } } catch (throwable t) { t.printstacktrace(); } } }); t.start(); synchronized (bound) { while (!bound.get()) { bound.wait(); } } }
srinivas491/AsterixDB
[ 1, 0, 0, 0 ]
16,343
@Override public void registerDefaults() { // @formatter:off /////////////////// /// Air /// /////////////////// register(0, builder() .properties(PropertyProviderCollections.DEFAULT_GAS) .translation("tile.air.name") .build("minecraft", "air")); /////////////////// /// Stone /// /////////////////// register(1, simpleBuilder() .trait(LanternEnumTraits.STONE_TYPE) .defaultState(state -> state.withTrait(LanternEnumTraits.STONE_TYPE, LanternStoneType.STONE).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.STONE_TYPE, LanternStoneType.STONE) ) ) .properties(builder -> builder .add(hardness(1.5)) .add(blastResistance(30.0))) .translation(TranslationProvider.of(LanternEnumTraits.STONE_TYPE)) .build("minecraft", "stone"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.STONE_TYPE).get().getInternalId()); /////////////////// /// Grass /// /////////////////// register(2, simpleBuilder() .trait(LanternBooleanTraits.SNOWY) .extendedStateProvider(new SnowyExtendedBlockStateProvider()) .defaultState(state -> state.withTrait(LanternBooleanTraits.SNOWY, false).get()) .itemType() .properties(builder -> builder .add(hardness(0.6)) .add(blastResistance(3.0))) .translation("tile.grass.name") .build("minecraft", "grass")); /////////////////// /// Dirt /// /////////////////// register(3, simpleBuilder() .traits(LanternEnumTraits.DIRT_TYPE, LanternBooleanTraits.SNOWY) .defaultState(state -> state .withTrait(LanternEnumTraits.DIRT_TYPE, LanternDirtType.DIRT).get() .withTrait(LanternBooleanTraits.SNOWY, false).get()) .extendedStateProvider(new SnowyExtendedBlockStateProvider()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.DIRT_TYPE, LanternDirtType.DIRT) ) ) .properties(builder -> builder .add(hardness(0.5)) .add(blastResistance(2.5))) .translation(TranslationProvider.of(LanternEnumTraits.DIRT_TYPE)) .build("minecraft", "dirt"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.DIRT_TYPE).get().getInternalId()); /////////////////// /// Cobblestone /// /////////////////// register(4, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(2.0)) .add(blastResistance(3.0))) .translation("tile.stonebrick.name") .build("minecraft", "cobblestone")); /////////////////// /// Planks /// /////////////////// register(5, simpleBuilder() .trait(LanternEnumTraits.TREE_TYPE) .defaultState(state -> state.withTrait(LanternEnumTraits.TREE_TYPE, LanternTreeType.OAK).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.TREE_TYPE, LanternTreeType.OAK) ) ) .properties(builder -> builder .add(hardness(2.0)) .add(blastResistance(5.0)) .add(flammableInfo(5, 20))) .translation(TranslationProvider.of(LanternEnumTraits.TREE_TYPE, type -> tr("tile.planks." + type.getTranslationKeyBase() + ".name"))) .build("minecraft", "planks"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.TREE_TYPE).get().getInternalId()); //////////////////// /// Sapling /// //////////////////// register(6, simpleBuilder() .traits(LanternEnumTraits.TREE_TYPE, LanternIntegerTraits.SAPLING_GROWTH_STAGE) .defaultState(state -> state .withTrait(LanternEnumTraits.TREE_TYPE, LanternTreeType.OAK).get() .withTrait(LanternIntegerTraits.SAPLING_GROWTH_STAGE, 0).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.TREE_TYPE, LanternTreeType.OAK) ) ) .properties(builder -> builder .add(PASSABLE) .add(INSTANT_BROKEN)) .translation(TranslationProvider.of(LanternEnumTraits.TREE_TYPE, type -> tr("tile.sapling." + type.getTranslationKeyBase() + ".name"))) .build("minecraft", "sapling"), blockState -> { final int type = blockState.getTraitValue(LanternEnumTraits.TREE_TYPE).get().getInternalId(); final int stage = blockState.getTraitValue(LanternIntegerTraits.SAPLING_GROWTH_STAGE).get(); return (byte) (stage << 3 | type); }); //////////////////// /// Bedrock /// //////////////////// register(7, simpleBuilder() .itemType() .properties(builder -> builder .add(PropertyProviderCollections.UNBREAKABLE)) .translation("tile.bedrock.name") .build("minecraft", "bedrock")); //////////////////// /// Sand /// //////////////////// register(12, simpleBuilder() .trait(LanternEnumTraits.SAND_TYPE) .defaultState(state -> state.withTrait(LanternEnumTraits.SAND_TYPE, LanternSandType.NORMAL).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.SAND_TYPE, LanternSandType.NORMAL) ) ) .properties(builder -> builder .add(hardness(0.5)) .add(blastResistance(2.5))) .translation(TranslationProvider.of(LanternEnumTraits.SAND_TYPE)) .build("minecraft", "sand"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.SAND_TYPE).get().getInternalId()); // TODO: Sand physics behavior //////////////////// /// Gravel /// //////////////////// register(13, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(0.6)) .add(blastResistance(3.0))) .translation("tile.gravel.name") .build("minecraft", "gravel")); // TODO: Gravel physics behavior //////////////////// /// Gold Ore /// //////////////////// register(14, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(15.0))) .translation("tile.oreGold.name") .build("minecraft", "gold_ore")); //////////////////// /// Iron Ore /// //////////////////// register(15, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(15.0))) .translation("tile.oreIron.name") .build("minecraft", "iron_ore")); //////////////////// /// Coal Ore /// //////////////////// register(16, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(15.0))) .translation("tile.oreCoal.name") .build("minecraft", "coal_ore")); //////////////////// /// Log 1 /// //////////////////// register(17, logBuilder(LanternEnumTraits.LOG1_TYPE, LanternTreeType.OAK) .build("minecraft", "log"), blockState -> logData(blockState, blockState.getTraitValue(LanternEnumTraits.LOG1_TYPE).get().getInternalId())); //////////////////// /// Leaves 1 /// //////////////////// register(18, leavesBuilder(LanternEnumTraits.LEAVES1_TYPE, LanternTreeType.OAK) .build("minecraft", "leaves"), blockState -> leavesData(blockState, blockState.getTraitValue(LanternEnumTraits.LEAVES1_TYPE).get().getInternalId())); //////////////////// /// Sponge /// //////////////////// register(19, simpleBuilder() .trait(LanternBooleanTraits.IS_WET) .defaultState(state -> state.withTrait(LanternBooleanTraits.IS_WET, false).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.IS_WET, false) ) ) .properties(builder -> builder .add(hardness(0.6)) .add(blastResistance(3.0))) .translation(new SpongeTranslationProvider()) .build("minecraft", "sponge"), blockState -> (byte) (blockState.getTraitValue(LanternBooleanTraits.IS_WET).get() ? 1 : 0)); //////////////////// /// Glass /// //////////////////// register(20, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(0.3)) .add(blastResistance(1.5))) .translation("tile.glass.name") .build("minecraft", "glass")); //////////////////// /// Lapis Ore /// //////////////////// register(21, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(15.0))) .translation("tile.oreLapis.name") .build("minecraft", "lapis_ore")); //////////////////// /// Lapis Block /// //////////////////// register(22, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(15.0))) .translation("tile.blockLapis.name") .build("minecraft", "lapis_block")); //////////////////// /// Dispenser /// //////////////////// register(23, simpleBuilder() .traits(LanternEnumTraits.FACING, LanternBooleanTraits.TRIGGERED) .defaultState(state -> state .withTrait(LanternEnumTraits.FACING, Direction.NORTH).get() .withTrait(LanternBooleanTraits.TRIGGERED, false).get()) .itemType() .properties(builder -> builder .add(hardness(3.5)) .add(blastResistance(17.5))) // .tileEntityType(() -> TileEntityTypes.DISPENSER) .translation("tile.dispenser.name") .behaviors(pipeline -> pipeline .add(new RotationPlacementBehavior())) .build("minecraft", "dispenser"), blockState -> { int data = directionData(blockState.getTraitValue(LanternEnumTraits.FACING).get()); if (blockState.getTraitValue(LanternBooleanTraits.TRIGGERED).get()) { data |= 0x8; } return (byte) data; }); //////////////////// /// Sandstone /// //////////////////// register(24, simpleBuilder() .trait(LanternEnumTraits.SANDSTONE_TYPE) .defaultState(state -> state.withTrait(LanternEnumTraits.SANDSTONE_TYPE, LanternSandstoneType.DEFAULT).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.SANDSTONE_TYPE, LanternSandstoneType.DEFAULT) ) ) .properties(builder -> builder .add(hardness(0.8)) .add(blastResistance(4.0))) .translation(TranslationProvider.of(LanternEnumTraits.SANDSTONE_TYPE)) .build("minecraft", "sandstone"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.SANDSTONE_TYPE).get().getInternalId()); //////////////////// /// Noteblock /// //////////////////// register(25, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(0.8)) .add(blastResistance(4.0))) .translation("tile.musicBlock.name") .tileEntityType(() -> TileEntityTypes.NOTE) .behaviors(pipeline -> pipeline .add(new NoteBlockInteractionBehavior())) .build("minecraft", "noteblock")); //////////////////// /// Bed /// //////////////////// register(26, simpleBuilder() .traits(LanternEnumTraits.HORIZONTAL_FACING, LanternEnumTraits.BED_PART, LanternBooleanTraits.OCCUPIED) .defaultState(state -> state .withTrait(LanternEnumTraits.HORIZONTAL_FACING, Direction.NORTH).get() .withTrait(LanternEnumTraits.BED_PART, LanternBedPart.FOOT).get() .withTrait(LanternBooleanTraits.OCCUPIED, false).get()) .properties(builder -> builder .add(hardness(0.2)) .add(blastResistance(1.0))) .translation("tile.bed.name") .build("minecraft", "bed"), blockState -> { final Direction facing = blockState.getTraitValue(LanternEnumTraits.HORIZONTAL_FACING).get(); int type = facing == Direction.SOUTH ? 0 : facing == Direction.WEST ? 1 : facing == Direction.NORTH ? 2 : facing == Direction.EAST ? 3 : -1; checkArgument(type != -1); if (blockState.getTraitValue(LanternBooleanTraits.OCCUPIED).get()) { type |= 0x4; } if (blockState.getTraitValue(LanternEnumTraits.BED_PART).get() == LanternBedPart.HEAD) { type |= 0x8; } return (byte) type; }); ////////////////////// /// Golden Rail /// ////////////////////// register(27, simpleBuilder() .traits(LanternEnumTraits.STRAIGHT_RAIL_DIRECTION, LanternBooleanTraits.POWERED) .defaultState(state -> state .withTrait(LanternEnumTraits.STRAIGHT_RAIL_DIRECTION, LanternRailDirection.NORTH_SOUTH).get() .withTrait(LanternBooleanTraits.POWERED, false).get()) .itemType() .selectionBox(BoundingBoxes::rail) .properties(builder -> builder .add(PASSABLE) .add(hardness(0.7)) .add(blastResistance(3.5))) .translation("tile.goldenRail.name") .build("minecraft", "golden_rail"), blockState -> { int type = blockState.getTraitValue(LanternEnumTraits.STRAIGHT_RAIL_DIRECTION).get().getInternalId(); if (blockState.getTraitValue(LanternBooleanTraits.POWERED).get()) { type |= 0x8; } return (byte) type; }); //////////////////////// /// Detector Rail /// //////////////////////// register(28, simpleBuilder() .traits(LanternEnumTraits.STRAIGHT_RAIL_DIRECTION, LanternBooleanTraits.POWERED) .defaultState(state -> state .withTrait(LanternEnumTraits.STRAIGHT_RAIL_DIRECTION, LanternRailDirection.NORTH_SOUTH).get() .withTrait(LanternBooleanTraits.POWERED, false).get()) .itemType() .selectionBox(BoundingBoxes::rail) .properties(builder -> builder .add(PASSABLE) .add(hardness(0.7)) .add(blastResistance(3.5))) .translation("tile.detectorRail.name") .build("minecraft", "detector_rail"), blockState -> { int type = blockState.getTraitValue(LanternEnumTraits.STRAIGHT_RAIL_DIRECTION).get().getInternalId(); if (blockState.getTraitValue(LanternBooleanTraits.POWERED).get()) { type |= 0x8; } return (byte) type; }); // TODO: 29 /////////////// /// Web /// /////////////// register(30, simpleBuilder() .itemType() .properties(builder -> builder .add(PASSABLE) .add(hardness(4.0)) .add(blastResistance(20.0))) .translation("tile.web.name") .build("minecraft", "web")); ////////////////////// /// Tall Grass /// ////////////////////// register(31, simpleBuilder() .traits(LanternEnumTraits.SHRUB_TYPE) .defaultState(state -> state .withTrait(LanternEnumTraits.SHRUB_TYPE, LanternShrubType.DEAD_BUSH).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.SHRUB_TYPE, LanternShrubType.DEAD_BUSH))) .selectionBox(BoundingBoxes.bush()) .properties(builder -> builder .add(INSTANT_BROKEN) .add(PASSABLE) .add(replaceable(true))) .translation("tile.tallgrass.name") .build("minecraft", "tallgrass"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.SHRUB_TYPE).get().getInternalId()); ///////////////////// /// Dead Bush /// ///////////////////// register(32, simpleBuilder() .properties(builder -> builder .add(INSTANT_BROKEN) .add(PASSABLE) .add(replaceable(true))) .selectionBox(BoundingBoxes.bush()) .itemType() .translation("tile.deadbush.name") .build("minecraft", "deadbush")); // TODO: 33 // TODO: 34 /////////////////// /// Wool /// /////////////////// register(35, dyedBuilder("tile.wool.%s.name") .properties(builder -> builder .add(hardness(0.8)) .add(blastResistance(4.0))) .build("minecraft", "wool"), this::dyedData); // TODO: 36 ///////////////////////// /// Yellow Flower /// ///////////////////////// register(37, simpleBuilder() .traits(LanternEnumTraits.YELLOW_FLOWER_TYPE) .defaultState(state -> state .withTrait(LanternEnumTraits.YELLOW_FLOWER_TYPE, LanternPlantType.DANDELION).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.PLANT_TYPE, LanternPlantType.DANDELION))) .selectionBox(BoundingBoxes.bush()) .properties(builder -> builder .add(INSTANT_BROKEN) .add(PASSABLE)) .translation(TranslationProvider.of(LanternEnumTraits.YELLOW_FLOWER_TYPE)) .build("minecraft", "yellow_flower"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.YELLOW_FLOWER_TYPE).get().getInternalId()); ////////////////////// /// Red Flower /// ////////////////////// register(38, simpleBuilder() .traits(LanternEnumTraits.RED_FLOWER_TYPE) .defaultState(state -> state .withTrait(LanternEnumTraits.RED_FLOWER_TYPE, LanternPlantType.POPPY).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.PLANT_TYPE, LanternPlantType.POPPY))) .selectionBox(BoundingBoxes.bush()) .properties(builder -> builder .add(INSTANT_BROKEN) .add(PASSABLE)) .translation(TranslationProvider.of(LanternEnumTraits.RED_FLOWER_TYPE)) .build("minecraft", "red_flower"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.RED_FLOWER_TYPE).get().getInternalId()); ////////////////////////// /// Brown Mushroom /// ////////////////////////// register(39, simpleBuilder() .selectionBox(BoundingBoxes.bush()) .properties(builder -> builder .add(INSTANT_BROKEN) .add(PASSABLE) .add(lightEmission(1))) .translation("tile.mushroom.name") .build("minecraft", "brown_mushroom")); //////////////////////// /// Red Mushroom /// //////////////////////// register(40, simpleBuilder() .selectionBox(BoundingBoxes.bush()) .properties(builder -> builder .add(INSTANT_BROKEN) .add(PASSABLE)) .translation("tile.mushroom.name") .build("minecraft", "red_mushroom")); ////////////////////// /// Gold Block /// ////////////////////// register(41, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(10.0))) .translation("tile.blockGold.name") .build("minecraft", "gold_block")); ////////////////////// /// Iron Block /// ////////////////////// register(42, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(5.0)) .add(blastResistance(10.0))) .translation("tile.blockIron.name") .build("minecraft", "iron_block")); /////////////////////////// /// Double Stone Slab 1 /// /////////////////////////// register(43, doubleStoneSlab(LanternEnumTraits.STONE_SLAB1_TYPE, LanternSlabType.STONE) .translation("tile.stoneSlab.name") .build("minecraft", "double_stone_slab"), blockState -> doubleStoneSlabData(blockState, blockState.getTraitValue(LanternEnumTraits.STONE_SLAB1_TYPE).get().getInternalId())); //////////////////////// /// Stone Slab 1 /// //////////////////////// register(44, stoneSlab(LanternEnumTraits.STONE_SLAB1_TYPE, LanternSlabType.STONE, () -> BlockTypes.STONE_SLAB, () -> BlockTypes.DOUBLE_STONE_SLAB) .translation("tile.stoneSlab.name") .collisionBox(BoundingBoxes::slab) .build("minecraft", "stone_slab"), blockState -> stoneSlabData(blockState, blockState.getTraitValue(LanternEnumTraits.STONE_SLAB1_TYPE).get().getInternalId())); /////////////////////// /// Brick Block /// /////////////////////// register(45, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(2.0)) .add(blastResistance(10.0))) .translation("tile.brick.name") .build("minecraft", "brick_block")); /////////////// /// TNT /// /////////////// register(46, simpleBuilder() .trait(LanternBooleanTraits.EXPLODE) .defaultState(state -> state .withTrait(LanternBooleanTraits.EXPLODE, false).get()) .itemType() .properties(builder -> builder .add(INSTANT_BROKEN)) .translation("tile.tnt.name") .build("minecraft", "tnt"), blockState -> (byte) (blockState.getTraitValue(LanternBooleanTraits.EXPLODE).get() ? 1 : 0)); ///////////////////// /// Bookshelf /// ///////////////////// register(47, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(1.5)) .add(blastResistance(7.5))) .translation("tile.bookshelf.name") .build("minecraft", "bookshelf")); ///////////////////////////// /// Mossy Cobblestone /// ///////////////////////////// register(48, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(2.0)) .add(blastResistance(10.0))) .translation("tile.stoneMoss.name") .build("minecraft", "mossy_cobblestone")); //////////////////// /// Obsidian /// //////////////////// register(49, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(50.0)) .add(blastResistance(2000.0))) .translation("tile.obsidian.name") .build("minecraft", "obsidian")); ///////////////// /// Torch /// ///////////////// register(50, builder() .trait(LanternEnumTraits.TORCH_FACING) .defaultState(state -> state .withTrait(LanternEnumTraits.TORCH_FACING, Direction.UP).get()) .itemType() .properties(builder -> builder .add(PASSABLE) .add(INSTANT_BROKEN)) .translation("tile.torch.name") .selectionBox(BoundingBoxes::torch) .behaviors(pipeline -> pipeline .add(new BlockSnapshotProviderPlaceBehavior()) .add(new TorchPlacementBehavior()) .add(new SimpleBreakBehavior())) .build("minecraft", "torch"), blockState -> { final Direction direction = blockState.getTraitValue(LanternEnumTraits.TORCH_FACING).get(); switch (direction) { case EAST: return (byte) 1; case WEST: return (byte) 2; case SOUTH: return (byte) 3; case NORTH: return (byte) 4; case UP: return (byte) 5; default: throw new IllegalArgumentException(); } }); ////////////// /// Fire /// ////////////// register(51, simpleBuilder() .properties(builder -> builder .add(PASSABLE) .add(INSTANT_BROKEN) .add(lightEmission(15))) .collisionBox(BoundingBoxes.NULL) .translation("tile.fire.name") .build("minecraft", "fire")); ///////////////////// /// Mob Spawner /// ///////////////////// register(52, simpleBuilder() .properties(builder -> builder .add(hardness(5.0)) .add(blastResistance(25.0))) .translation("tile.mobSpawner.name") .build("minecraft", "mob_spawner")); // TODO: Oak Stairs //////////////////// /// Chest /// //////////////////// register(54, chestBuilder() .translation("tile.chest.name") .build("minecraft", "chest"), this::horizontalFacingData); /////////////////////////// /// Redstone Wire /// /////////////////////////// register(55, simpleBuilder() .traits(LanternIntegerTraits.POWER) .selectionBox(new AABB(0, 0, 0, 1.0, 0.0625, 1.0)) // TODO: Based on connections .properties(builder -> builder .add(PASSABLE) .add(INSTANT_BROKEN)) .defaultState(state -> state .withTrait(LanternIntegerTraits.POWER, 0).get()) .translation("tile.redstoneDust.name") .build("minecraft", "redstone_wire"), state -> state.get(Keys.POWER).get().byteValue()); /////////////////////// /// Diamond Ore /// /////////////////////// register(56, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(5.0))) .translation("tile.oreDiamond.name") .build("minecraft", "diamond_ore")); ///////////////////////// /// Diamond Block /// ///////////////////////// register(57, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(5.0)) .add(blastResistance(10.0))) .translation("tile.blockDiamond.name") .build("minecraft", "diamond_block")); ////////////////////////// /// Crafting Table /// ////////////////////////// register(58, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(2.5)) .add(blastResistance(12.5))) .translation("tile.workbench.name") .behaviors(pipeline -> pipeline .add(new CraftingTableInteractionBehavior())) .build("minecraft", "crafting_table")); // TODO: Wheat //////////////////// /// Farmland /// //////////////////// register(60, simpleBuilder() .collisionBox(BoundingBoxes.farmland()) .trait(LanternIntegerTraits.MOISTURE) .properties(builder -> builder .add(hardness(0.6)) .add(blastResistance(3.0))) .defaultState(state -> state.withTrait(LanternIntegerTraits.MOISTURE, 0).get()) .translation("tile.farmland.name") .build("minecraft", "farmland"), state -> state.getTraitValue(LanternIntegerTraits.MOISTURE).get().byteValue()); //////////////////// /// Furnace /// //////////////////// register(61, furnaceBuilder() .itemType() .translation("tile.furnace.name") .build("minecraft", "furnace"), this::directionData); //////////////////// /// Lit Furnace /// //////////////////// register(62, furnaceBuilder() .properties(builder -> builder .add(lightEmission(13))) .translation("tile.furnace.name") .build("minecraft", "lit_furnace"), this::directionData); //////////////////////////// /// Stone Pressure Plate /// //////////////////////////// register(70, pressurePlateBuilder() .translation("tile.pressurePlateStone.name") .build("minecraft", "stone_pressure_plate"), this::pressurePlateData); ///////////////////////////// /// Wooden Pressure Plate /// ///////////////////////////// register(72, pressurePlateBuilder() .translation("tile.pressurePlateWood.name") .build("minecraft", "wooden_pressure_plate"), this::pressurePlateData); //////////////////// /// Jukebox /// //////////////////// register(84, simpleBuilder() .itemType() .traits(LanternBooleanTraits.HAS_RECORD) .defaultState(state -> state .withTrait(LanternBooleanTraits.HAS_RECORD, false).get()) .properties(builder -> builder .add(hardness(2.0)) .add(blastResistance(10.0))) .tileEntityType(() -> TileEntityTypes.JUKEBOX) .translation("tile.jukebox.name") .behaviors(pipeline -> pipeline .add(new JukeboxInteractionBehavior())) .build("minecraft", "jukebox"), state -> (byte) (state.getTraitValue(LanternBooleanTraits.HAS_RECORD).get() ? 1 : 0)); //////////////////// /// Pumpkin /// //////////////////// register(86, pumpkinBuilder() .itemType(builder -> builder .properties(properties -> properties .add(equipmentType(EquipmentTypes.HEADWEAR)))) .translation("tile.pumpkin.name") .build("minecraft", "pumpkin"), this::horizontalDirectionData); ////////////////////// /// Netherrack /// ////////////////////// register(87, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(0.4)) .add(blastResistance(2.0))) .translation("tile.hellrock.name") .build("minecraft", "netherrack")); //////////////////// /// Lit Pumpkin /// //////////////////// register(91, pumpkinBuilder() .properties(builder -> builder .add(lightEmission(15))) .translation("tile.litpumpkin.name") .build("minecraft", "lit_pumpkin"), this::horizontalDirectionData); ///////////////////// /// Stained Glass /// ///////////////////// register(95, dyedBuilder("tile.stainedGlass.%s.name") .properties(builder -> builder .add(hardness(0.3)) .add(blastResistance(1.5))) .build("minecraft", "stained_glass"), this::dyedData); /////////////////// /// Iron Bars /// /////////////////// register(101, simpleBuilder() // TODO .itemType() .properties(builder -> builder .add(hardness(5.0)) .add(blastResistance(10.0))) .translation("tile.fenceIron.name") .build("minecraft", "iron_bars")); ///////////////////// /// End Stone /// ///////////////////// register(121, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(15.0))) .translation("tile.whiteStone.name") .build("minecraft", "end_stone")); ////////////////////////// /// Double Wooden Slab /// ////////////////////////// register(125, simpleBuilder() .traits(LanternEnumTraits.TREE_TYPE) .defaultState(state -> state .withTrait(LanternEnumTraits.TREE_TYPE, LanternTreeType.OAK).get()) .translation(TranslationProvider.of(LanternEnumTraits.TREE_TYPE, type -> tr("tile.woodSlab." + type.getTranslationKeyBase() + ".name"))) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.TREE_TYPE, LanternTreeType.OAK) ) ) .properties(builder -> builder .add(hardness(2.0)) .add(blastResistance(5.0))) .build("minecraft", "double_wooden_slab"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.TREE_TYPE).get().getInternalId()); ////////////////////////// /// Wooden Slab /// ////////////////////////// register(126, simpleBuilder() .traits(LanternEnumTraits.PORTION_TYPE, LanternEnumTraits.TREE_TYPE) .defaultState(state -> state .withTrait(LanternEnumTraits.PORTION_TYPE, LanternPortionType.BOTTOM).get() .withTrait(LanternEnumTraits.TREE_TYPE, LanternTreeType.OAK).get()) .translation(TranslationProvider.of(LanternEnumTraits.TREE_TYPE, type -> tr("tile.woodSlab." + type.getTranslationKeyBase() + ".name"))) .itemType(builder -> builder .behaviors(pipeline -> pipeline .add(new SlabItemInteractionBehavior<>(LanternEnumTraits.TREE_TYPE, () -> BlockTypes.WOODEN_SLAB, () -> BlockTypes.DOUBLE_WOODEN_SLAB)) .add(new PlacementCollisionDetectionBehavior())) .keysProvider(collection -> collection .register(Keys.TREE_TYPE, LanternTreeType.OAK) ) ) .collisionBox(BoundingBoxes::slab) .properties(builder -> builder .add(hardness(2.0)) .add(blastResistance(5.0))) .build("minecraft", "wooden_slab"), blockState -> { final int type = blockState.getTraitValue(LanternEnumTraits.TREE_TYPE).get().getInternalId(); final int portion = (byte) blockState.getTraitValue(LanternEnumTraits.PORTION_TYPE).get().getInternalId(); return (byte) (portion << 3 | type); }); ///////////////////// /// Ender Chest /// ///////////////////// register(130, simpleBuilder() .trait(LanternEnumTraits.HORIZONTAL_FACING) .defaultState(state -> state.withTrait(LanternEnumTraits.HORIZONTAL_FACING, Direction.NORTH).get()) .itemType() .tileEntityType(() -> TileEntityTypes.ENDER_CHEST) .properties(builder -> builder .add(hardness(22.5)) .add(blastResistance(3000.0)) .add(lightEmission(7))) .translation("tile.enderChest.name") .collisionBox(BoundingBoxes.chest()) .behaviors(pipeline -> pipeline .add(new HorizontalRotationPlacementBehavior()) .add(new EnderChestInteractionBehavior())) .build("minecraft", "ender_chest"), this::horizontalFacingData); ///////////////////// /// Trapped Chest /// ///////////////////// register(146, chestBuilder() .translation("tile.chestTrap.name") .build("minecraft", "trapped_chest"), this::horizontalFacingData); /////////////////////////////////////// /// Weighted Pressure Plate (Light) /// /////////////////////////////////////// register(147, weightedPressurePlateBuilder() .translation("tile.weightedPlate_light.name") .build("minecraft", "light_weighted_pressure_plate"), this::weightedPressurePlateData); /////////////////////////////////////// /// Weighted Pressure Plate (Heavy) /// /////////////////////////////////////// register(148, weightedPressurePlateBuilder() .translation("tile.weightedPlate_heavy.name") .build("minecraft", "heavy_weighted_pressure_plate"), this::weightedPressurePlateData); /////////////////////// /// Redstone Block /// /////////////////////// register(152, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(5.0)) .add(blastResistance(30.0))) .translation("tile.blockRedstone.name") .build("minecraft", "redstone_block")); //////////////////// /// Quartz Ore /// //////////////////// register(153, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(15.0))) .translation("tile.netherquartz.name") .build("minecraft", "quartz_ore")); //////////////////// /// Hopper /// //////////////////// register(154, simpleBuilder() .traits(LanternEnumTraits.HOPPER_FACING, LanternBooleanTraits.ENABLED) .defaultState(state -> state .withTrait(LanternEnumTraits.HOPPER_FACING, Direction.DOWN).get() .withTrait(LanternBooleanTraits.ENABLED, false).get()) .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(8.0))) .translation("tile.hopper.name") .behaviors(pipeline -> pipeline .add(new HopperPlacementBehavior())) .build("minecraft", "hopper"), blockState -> { int data = directionData(blockState.getTraitValue(LanternEnumTraits.HOPPER_FACING).get()); if (!blockState.getTraitValue(LanternBooleanTraits.ENABLED).get()) { data |= 0x8; } return (byte) data; }); ////////////////////// /// Quartz Block /// ////////////////////// register(155, simpleBuilder() .trait(LanternEnumTraits.QUARTZ_TYPE) .defaultState(state -> state .withTrait(LanternEnumTraits.QUARTZ_TYPE, LanternQuartzType.DEFAULT).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.QUARTZ_TYPE, LanternQuartzType.DEFAULT) ) ) .properties(builder -> builder .add(hardness(0.8)) .add(blastResistance(2.4))) .translation(TranslationProvider.of(LanternEnumTraits.QUARTZ_TYPE)) .behaviors(pipeline -> pipeline .add(new QuartzLinesRotationPlacementBehavior())) .build("minecraft", "quartz_block"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.QUARTZ_TYPE).get().getInternalId()); //////////////////// /// Dropper /// //////////////////// register(158, simpleBuilder() .traits(LanternEnumTraits.FACING, LanternBooleanTraits.TRIGGERED) .defaultState(state -> state .withTrait(LanternEnumTraits.FACING, Direction.NORTH).get() .withTrait(LanternBooleanTraits.TRIGGERED, false).get()) .itemType() .properties(builder -> builder .add(hardness(3.5)) .add(blastResistance(17.5))) // .tileEntityType(() -> TileEntityTypes.DROPPER) .translation("tile.dropper.name") .behaviors(pipeline -> pipeline .add(new RotationPlacementBehavior())) .build("minecraft", "dropper"), blockState -> { int data = directionData(blockState.getTraitValue(LanternEnumTraits.FACING).get()); if (blockState.getTraitValue(LanternBooleanTraits.TRIGGERED).get()) { data |= 0x8; } return (byte) data; }); ////////////////////////////// /// Stained Hardended Clay /// ////////////////////////////// register(159, dyedBuilder("tile.clayHardenedStained.%s.name") .properties(builder -> builder .add(hardness(1.25)) .add(blastResistance(7.0))) .build("minecraft", "stained_hardened_clay"), this::dyedData); ////////////////////////// /// Stained Glass Pane /// ////////////////////////// register(160, dyedBuilder("tile.thinStainedGlass.%s.name") .properties(builder -> builder .add(hardness(0.3)) .add(blastResistance(1.5))) .build("minecraft", "stained_glass_pane"), this::dyedData); //////////////////// /// Leaves 2 /// //////////////////// register(161, leavesBuilder(LanternEnumTraits.LEAVES2_TYPE, LanternTreeType.ACACIA) .build("minecraft", "leaves2"), blockState -> leavesData(blockState, blockState.getTraitValue(LanternEnumTraits.LEAVES2_TYPE).get().getInternalId() - 4)); //////////////////// /// Log 2 /// //////////////////// register(162, logBuilder(LanternEnumTraits.LOG2_TYPE, LanternTreeType.ACACIA) .build("minecraft", "log2"), blockState -> logData(blockState, blockState.getTraitValue(LanternEnumTraits.LOG2_TYPE).get().getInternalId() - 4)); //////////////////// /// Barrier /// //////////////////// register(166, simpleBuilder() .itemType() .properties(builder -> builder .add(PropertyProviderCollections.UNBREAKABLE)) .translation("tile.barrier.name") .build("minecraft", "barrier")); ///////////////////// /// Carpet /// ///////////////////// register(171, dyedBuilder("tile.carpet.%s.name") .properties(builder -> builder .add(hardness(0.1)) .add(blastResistance(0.5)) .add(solidMaterial(false))) .collisionBox(BoundingBoxes.carpet()) .build("minecraft", "carpet"), this::dyedData); ///////////////////// /// Red Sandstone /// ///////////////////// register(179, simpleBuilder() .trait(LanternEnumTraits.SANDSTONE_TYPE) .defaultState(state -> state.withTrait(LanternEnumTraits.SANDSTONE_TYPE, LanternSandstoneType.DEFAULT).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.SANDSTONE_TYPE, LanternSandstoneType.DEFAULT) ) ) .properties(builder -> builder .add(hardness(0.8)) .add(blastResistance(4.0))) .translation(TranslationProvider.of(LanternEnumTraits.SANDSTONE_TYPE)) .build("minecraft", "red_sandstone"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.SANDSTONE_TYPE).get().getInternalId()); /////////////////////////// /// Double Stone Slab 2 /// /////////////////////////// register(181, doubleStoneSlab(LanternEnumTraits.STONE_SLAB2_TYPE, LanternSlabType.RED_SAND) .translation("tile.stoneSlab2.name") .build("minecraft", "double_stone_slab2"), blockState -> doubleStoneSlabData(blockState, blockState.getTraitValue(LanternEnumTraits.STONE_SLAB2_TYPE).get().getInternalId() - 8)); //////////////////////// /// Stone Slab 2 /// //////////////////////// register(182, stoneSlab(LanternEnumTraits.STONE_SLAB2_TYPE, LanternSlabType.RED_SAND, () -> BlockTypes.STONE_SLAB2, () -> BlockTypes.DOUBLE_STONE_SLAB2) .translation("tile.stoneSlab2.name") .collisionBox(BoundingBoxes::slab) .build("minecraft", "stone_slab2"), blockState -> stoneSlabData(blockState, blockState.getTraitValue(LanternEnumTraits.STONE_SLAB2_TYPE).get().getInternalId() - 8)); /////////////////// /// End Rod /// /////////////////// register(198, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(0.0)) .add(blastResistance(0.0)) .add(lightEmission(14))) .translation("tile.endRod.name") .build("minecraft", "end_rod")); /////////////////////////// /// White Shulker Box /// /////////////////////////// register(219, shulkerBox() .translation("tile.shulkerBoxWhite.name") .build("minecraft", "white_shulker_box"), this::shulkerBoxData); /////////////////////////// /// Orange Shulker Box /// /////////////////////////// register(220, shulkerBox() .translation("tile.shulkerBoxOrange.name") .build("minecraft", "orange_shulker_box"), this::shulkerBoxData); //////////////////////////// /// Magenta Shulker Box /// //////////////////////////// register(221, shulkerBox() .translation("tile.shulkerBoxMagenta.name") .build("minecraft", "magenta_shulker_box"), this::shulkerBoxData); /////////////////////////////// /// Light Blue Shulker Box /// /////////////////////////////// register(222, shulkerBox() .translation("tile.shulkerBoxLightBlue.name") .build("minecraft", "light_blue_shulker_box"), this::shulkerBoxData); /////////////////////////// /// Yellow Shulker Box /// /////////////////////////// register(223, shulkerBox() .translation("tile.shulkerBoxYellow.name") .build("minecraft", "yellow_shulker_box"), this::shulkerBoxData); ///////////////////////// /// Lime Shulker Box /// ///////////////////////// register(224, shulkerBox() .translation("tile.shulkerBoxLime.name") .build("minecraft", "lime_shulker_box"), this::shulkerBoxData); ///////////////////////// /// Pink Shulker Box /// ///////////////////////// register(225, shulkerBox() .translation("tile.shulkerBoxPink.name") .build("minecraft", "pink_shulker_box"), this::shulkerBoxData); ///////////////////////// /// Gray Shulker Box /// ///////////////////////// register(226, shulkerBox() .translation("tile.shulkerBoxGray.name") .build("minecraft", "gray_shulker_box"), this::shulkerBoxData); ///////////////////////// /// Gray Shulker Box /// ///////////////////////// register(227, shulkerBox() .translation("tile.shulkerBoxSilver.name") .build("minecraft", "silver_shulker_box"), this::shulkerBoxData); ///////////////////////// /// Cyan Shulker Box /// ///////////////////////// register(228, shulkerBox() .translation("tile.shulkerBoxCyan.name") .build("minecraft", "cyan_shulker_box"), this::shulkerBoxData); /////////////////////////// /// Purple Shulker Box /// /////////////////////////// register(229, shulkerBox() .translation("tile.shulkerBoxPurple.name") .build("minecraft", "purple_shulker_box"), this::shulkerBoxData); ///////////////////////// /// Blue Shulker Box /// ///////////////////////// register(230, shulkerBox() .translation("tile.shulkerBoxBlue.name") .build("minecraft", "blue_shulker_box"), this::shulkerBoxData); ////////////////////////// /// Brown Shulker Box /// ////////////////////////// register(231, shulkerBox() .translation("tile.shulkerBoxBrown.name") .build("minecraft", "brown_shulker_box"), this::shulkerBoxData); ////////////////////////// /// Green Shulker Box /// ////////////////////////// register(232, shulkerBox() .translation("tile.shulkerBoxGreen.name") .build("minecraft", "green_shulker_box"), this::shulkerBoxData); //////////////////////// /// Red Shulker Box /// //////////////////////// register(233, shulkerBox() .translation("tile.shulkerBoxRed.name") .build("minecraft", "red_shulker_box"), this::shulkerBoxData); ////////////////////////// /// Black Shulker Box /// ////////////////////////// register(234, shulkerBox() .translation("tile.shulkerBoxBlack.name") .build("minecraft", "black_shulker_box"), this::shulkerBoxData); ////////////// /// Sign /// ////////////// register(63, simpleBuilder() .trait(LanternIntegerTraits.ROTATION) .defaultState(state -> state .withTrait(LanternIntegerTraits.ROTATION, 0).get()) .properties(builder -> builder .add(hardness(1.0)) .add(blastResistance(5.0))) .behaviors(pipeline -> pipeline .add(new SignInteractionBehavior())) .tileEntityType(() -> TileEntityTypes.SIGN) .build("minecraft", "standing_sign"), blockState -> blockState.getTraitValue(LanternIntegerTraits.ROTATION).get().byteValue()); register(68, simpleBuilder() .trait(LanternEnumTraits.HORIZONTAL_FACING) .defaultState(state -> state .withTrait(LanternEnumTraits.HORIZONTAL_FACING, Direction.NORTH).get()) .properties(builder -> builder .add(hardness(1.0)) .add(blastResistance(5.0))) .behaviors(pipeline -> pipeline .add(new SignInteractionBehavior())) .tileEntityType(() -> TileEntityTypes.SIGN) .build("minecraft", "wall_sign"), this::horizontalFacingData); //////////////// /// Banner /// //////////////// register(176, simpleBuilder() .trait(LanternIntegerTraits.ROTATION) .defaultState(state -> state .withTrait(LanternIntegerTraits.ROTATION, 0).get()) .properties(builder -> builder .add(hardness(1.0)) .add(blastResistance(5.0))) .behaviors(pipeline -> pipeline .add(new SignInteractionBehavior())) .tileEntityType(() -> TileEntityTypes.BANNER) .build("minecraft", "standing_banner"), blockState -> blockState.getTraitValue(LanternIntegerTraits.ROTATION).get().byteValue()); register(177, simpleBuilder() .trait(LanternEnumTraits.HORIZONTAL_FACING) .defaultState(state -> state .withTrait(LanternEnumTraits.HORIZONTAL_FACING, Direction.NORTH).get()) .properties(builder -> builder .add(hardness(1.0)) .add(blastResistance(5.0))) .behaviors(pipeline -> pipeline .add(new SignInteractionBehavior())) .tileEntityType(() -> TileEntityTypes.BANNER) .build("minecraft", "wall_banner"), this::horizontalFacingData); // @formatter:on }
@Override public void registerDefaults() { register(0, builder() .properties(PropertyProviderCollections.DEFAULT_GAS) .translation("tile.air.name") .build("minecraft", "air")); register(1, simpleBuilder() .trait(LanternEnumTraits.STONE_TYPE) .defaultState(state -> state.withTrait(LanternEnumTraits.STONE_TYPE, LanternStoneType.STONE).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.STONE_TYPE, LanternStoneType.STONE) ) ) .properties(builder -> builder .add(hardness(1.5)) .add(blastResistance(30.0))) .translation(TranslationProvider.of(LanternEnumTraits.STONE_TYPE)) .build("minecraft", "stone"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.STONE_TYPE).get().getInternalId()); register(2, simpleBuilder() .trait(LanternBooleanTraits.SNOWY) .extendedStateProvider(new SnowyExtendedBlockStateProvider()) .defaultState(state -> state.withTrait(LanternBooleanTraits.SNOWY, false).get()) .itemType() .properties(builder -> builder .add(hardness(0.6)) .add(blastResistance(3.0))) .translation("tile.grass.name") .build("minecraft", "grass")); register(3, simpleBuilder() .traits(LanternEnumTraits.DIRT_TYPE, LanternBooleanTraits.SNOWY) .defaultState(state -> state .withTrait(LanternEnumTraits.DIRT_TYPE, LanternDirtType.DIRT).get() .withTrait(LanternBooleanTraits.SNOWY, false).get()) .extendedStateProvider(new SnowyExtendedBlockStateProvider()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.DIRT_TYPE, LanternDirtType.DIRT) ) ) .properties(builder -> builder .add(hardness(0.5)) .add(blastResistance(2.5))) .translation(TranslationProvider.of(LanternEnumTraits.DIRT_TYPE)) .build("minecraft", "dirt"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.DIRT_TYPE).get().getInternalId()); register(4, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(2.0)) .add(blastResistance(3.0))) .translation("tile.stonebrick.name") .build("minecraft", "cobblestone")); register(5, simpleBuilder() .trait(LanternEnumTraits.TREE_TYPE) .defaultState(state -> state.withTrait(LanternEnumTraits.TREE_TYPE, LanternTreeType.OAK).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.TREE_TYPE, LanternTreeType.OAK) ) ) .properties(builder -> builder .add(hardness(2.0)) .add(blastResistance(5.0)) .add(flammableInfo(5, 20))) .translation(TranslationProvider.of(LanternEnumTraits.TREE_TYPE, type -> tr("tile.planks." + type.getTranslationKeyBase() + ".name"))) .build("minecraft", "planks"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.TREE_TYPE).get().getInternalId()); register(6, simpleBuilder() .traits(LanternEnumTraits.TREE_TYPE, LanternIntegerTraits.SAPLING_GROWTH_STAGE) .defaultState(state -> state .withTrait(LanternEnumTraits.TREE_TYPE, LanternTreeType.OAK).get() .withTrait(LanternIntegerTraits.SAPLING_GROWTH_STAGE, 0).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.TREE_TYPE, LanternTreeType.OAK) ) ) .properties(builder -> builder .add(PASSABLE) .add(INSTANT_BROKEN)) .translation(TranslationProvider.of(LanternEnumTraits.TREE_TYPE, type -> tr("tile.sapling." + type.getTranslationKeyBase() + ".name"))) .build("minecraft", "sapling"), blockState -> { final int type = blockState.getTraitValue(LanternEnumTraits.TREE_TYPE).get().getInternalId(); final int stage = blockState.getTraitValue(LanternIntegerTraits.SAPLING_GROWTH_STAGE).get(); return (byte) (stage << 3 | type); }); register(7, simpleBuilder() .itemType() .properties(builder -> builder .add(PropertyProviderCollections.UNBREAKABLE)) .translation("tile.bedrock.name") .build("minecraft", "bedrock")); register(12, simpleBuilder() .trait(LanternEnumTraits.SAND_TYPE) .defaultState(state -> state.withTrait(LanternEnumTraits.SAND_TYPE, LanternSandType.NORMAL).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.SAND_TYPE, LanternSandType.NORMAL) ) ) .properties(builder -> builder .add(hardness(0.5)) .add(blastResistance(2.5))) .translation(TranslationProvider.of(LanternEnumTraits.SAND_TYPE)) .build("minecraft", "sand"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.SAND_TYPE).get().getInternalId()); register(13, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(0.6)) .add(blastResistance(3.0))) .translation("tile.gravel.name") .build("minecraft", "gravel")); register(14, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(15.0))) .translation("tile.oreGold.name") .build("minecraft", "gold_ore")); register(15, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(15.0))) .translation("tile.oreIron.name") .build("minecraft", "iron_ore")); register(16, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(15.0))) .translation("tile.oreCoal.name") .build("minecraft", "coal_ore")); register(17, logBuilder(LanternEnumTraits.LOG1_TYPE, LanternTreeType.OAK) .build("minecraft", "log"), blockState -> logData(blockState, blockState.getTraitValue(LanternEnumTraits.LOG1_TYPE).get().getInternalId())); register(18, leavesBuilder(LanternEnumTraits.LEAVES1_TYPE, LanternTreeType.OAK) .build("minecraft", "leaves"), blockState -> leavesData(blockState, blockState.getTraitValue(LanternEnumTraits.LEAVES1_TYPE).get().getInternalId())); register(19, simpleBuilder() .trait(LanternBooleanTraits.IS_WET) .defaultState(state -> state.withTrait(LanternBooleanTraits.IS_WET, false).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.IS_WET, false) ) ) .properties(builder -> builder .add(hardness(0.6)) .add(blastResistance(3.0))) .translation(new SpongeTranslationProvider()) .build("minecraft", "sponge"), blockState -> (byte) (blockState.getTraitValue(LanternBooleanTraits.IS_WET).get() ? 1 : 0)); register(20, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(0.3)) .add(blastResistance(1.5))) .translation("tile.glass.name") .build("minecraft", "glass")); register(21, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(15.0))) .translation("tile.oreLapis.name") .build("minecraft", "lapis_ore")); register(22, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(15.0))) .translation("tile.blockLapis.name") .build("minecraft", "lapis_block")); register(23, simpleBuilder() .traits(LanternEnumTraits.FACING, LanternBooleanTraits.TRIGGERED) .defaultState(state -> state .withTrait(LanternEnumTraits.FACING, Direction.NORTH).get() .withTrait(LanternBooleanTraits.TRIGGERED, false).get()) .itemType() .properties(builder -> builder .add(hardness(3.5)) .add(blastResistance(17.5))) .translation("tile.dispenser.name") .behaviors(pipeline -> pipeline .add(new RotationPlacementBehavior())) .build("minecraft", "dispenser"), blockState -> { int data = directionData(blockState.getTraitValue(LanternEnumTraits.FACING).get()); if (blockState.getTraitValue(LanternBooleanTraits.TRIGGERED).get()) { data |= 0x8; } return (byte) data; }); register(24, simpleBuilder() .trait(LanternEnumTraits.SANDSTONE_TYPE) .defaultState(state -> state.withTrait(LanternEnumTraits.SANDSTONE_TYPE, LanternSandstoneType.DEFAULT).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.SANDSTONE_TYPE, LanternSandstoneType.DEFAULT) ) ) .properties(builder -> builder .add(hardness(0.8)) .add(blastResistance(4.0))) .translation(TranslationProvider.of(LanternEnumTraits.SANDSTONE_TYPE)) .build("minecraft", "sandstone"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.SANDSTONE_TYPE).get().getInternalId()); register(25, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(0.8)) .add(blastResistance(4.0))) .translation("tile.musicBlock.name") .tileEntityType(() -> TileEntityTypes.NOTE) .behaviors(pipeline -> pipeline .add(new NoteBlockInteractionBehavior())) .build("minecraft", "noteblock")); register(26, simpleBuilder() .traits(LanternEnumTraits.HORIZONTAL_FACING, LanternEnumTraits.BED_PART, LanternBooleanTraits.OCCUPIED) .defaultState(state -> state .withTrait(LanternEnumTraits.HORIZONTAL_FACING, Direction.NORTH).get() .withTrait(LanternEnumTraits.BED_PART, LanternBedPart.FOOT).get() .withTrait(LanternBooleanTraits.OCCUPIED, false).get()) .properties(builder -> builder .add(hardness(0.2)) .add(blastResistance(1.0))) .translation("tile.bed.name") .build("minecraft", "bed"), blockState -> { final Direction facing = blockState.getTraitValue(LanternEnumTraits.HORIZONTAL_FACING).get(); int type = facing == Direction.SOUTH ? 0 : facing == Direction.WEST ? 1 : facing == Direction.NORTH ? 2 : facing == Direction.EAST ? 3 : -1; checkArgument(type != -1); if (blockState.getTraitValue(LanternBooleanTraits.OCCUPIED).get()) { type |= 0x4; } if (blockState.getTraitValue(LanternEnumTraits.BED_PART).get() == LanternBedPart.HEAD) { type |= 0x8; } return (byte) type; }); register(27, simpleBuilder() .traits(LanternEnumTraits.STRAIGHT_RAIL_DIRECTION, LanternBooleanTraits.POWERED) .defaultState(state -> state .withTrait(LanternEnumTraits.STRAIGHT_RAIL_DIRECTION, LanternRailDirection.NORTH_SOUTH).get() .withTrait(LanternBooleanTraits.POWERED, false).get()) .itemType() .selectionBox(BoundingBoxes::rail) .properties(builder -> builder .add(PASSABLE) .add(hardness(0.7)) .add(blastResistance(3.5))) .translation("tile.goldenRail.name") .build("minecraft", "golden_rail"), blockState -> { int type = blockState.getTraitValue(LanternEnumTraits.STRAIGHT_RAIL_DIRECTION).get().getInternalId(); if (blockState.getTraitValue(LanternBooleanTraits.POWERED).get()) { type |= 0x8; } return (byte) type; }); register(28, simpleBuilder() .traits(LanternEnumTraits.STRAIGHT_RAIL_DIRECTION, LanternBooleanTraits.POWERED) .defaultState(state -> state .withTrait(LanternEnumTraits.STRAIGHT_RAIL_DIRECTION, LanternRailDirection.NORTH_SOUTH).get() .withTrait(LanternBooleanTraits.POWERED, false).get()) .itemType() .selectionBox(BoundingBoxes::rail) .properties(builder -> builder .add(PASSABLE) .add(hardness(0.7)) .add(blastResistance(3.5))) .translation("tile.detectorRail.name") .build("minecraft", "detector_rail"), blockState -> { int type = blockState.getTraitValue(LanternEnumTraits.STRAIGHT_RAIL_DIRECTION).get().getInternalId(); if (blockState.getTraitValue(LanternBooleanTraits.POWERED).get()) { type |= 0x8; } return (byte) type; }); register(30, simpleBuilder() .itemType() .properties(builder -> builder .add(PASSABLE) .add(hardness(4.0)) .add(blastResistance(20.0))) .translation("tile.web.name") .build("minecraft", "web")); register(31, simpleBuilder() .traits(LanternEnumTraits.SHRUB_TYPE) .defaultState(state -> state .withTrait(LanternEnumTraits.SHRUB_TYPE, LanternShrubType.DEAD_BUSH).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.SHRUB_TYPE, LanternShrubType.DEAD_BUSH))) .selectionBox(BoundingBoxes.bush()) .properties(builder -> builder .add(INSTANT_BROKEN) .add(PASSABLE) .add(replaceable(true))) .translation("tile.tallgrass.name") .build("minecraft", "tallgrass"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.SHRUB_TYPE).get().getInternalId()); register(32, simpleBuilder() .properties(builder -> builder .add(INSTANT_BROKEN) .add(PASSABLE) .add(replaceable(true))) .selectionBox(BoundingBoxes.bush()) .itemType() .translation("tile.deadbush.name") .build("minecraft", "deadbush")); register(35, dyedBuilder("tile.wool.%s.name") .properties(builder -> builder .add(hardness(0.8)) .add(blastResistance(4.0))) .build("minecraft", "wool"), this::dyedData); register(37, simpleBuilder() .traits(LanternEnumTraits.YELLOW_FLOWER_TYPE) .defaultState(state -> state .withTrait(LanternEnumTraits.YELLOW_FLOWER_TYPE, LanternPlantType.DANDELION).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.PLANT_TYPE, LanternPlantType.DANDELION))) .selectionBox(BoundingBoxes.bush()) .properties(builder -> builder .add(INSTANT_BROKEN) .add(PASSABLE)) .translation(TranslationProvider.of(LanternEnumTraits.YELLOW_FLOWER_TYPE)) .build("minecraft", "yellow_flower"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.YELLOW_FLOWER_TYPE).get().getInternalId()); register(38, simpleBuilder() .traits(LanternEnumTraits.RED_FLOWER_TYPE) .defaultState(state -> state .withTrait(LanternEnumTraits.RED_FLOWER_TYPE, LanternPlantType.POPPY).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.PLANT_TYPE, LanternPlantType.POPPY))) .selectionBox(BoundingBoxes.bush()) .properties(builder -> builder .add(INSTANT_BROKEN) .add(PASSABLE)) .translation(TranslationProvider.of(LanternEnumTraits.RED_FLOWER_TYPE)) .build("minecraft", "red_flower"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.RED_FLOWER_TYPE).get().getInternalId()); register(39, simpleBuilder() .selectionBox(BoundingBoxes.bush()) .properties(builder -> builder .add(INSTANT_BROKEN) .add(PASSABLE) .add(lightEmission(1))) .translation("tile.mushroom.name") .build("minecraft", "brown_mushroom")); register(40, simpleBuilder() .selectionBox(BoundingBoxes.bush()) .properties(builder -> builder .add(INSTANT_BROKEN) .add(PASSABLE)) .translation("tile.mushroom.name") .build("minecraft", "red_mushroom")); register(41, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(10.0))) .translation("tile.blockGold.name") .build("minecraft", "gold_block")); register(42, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(5.0)) .add(blastResistance(10.0))) .translation("tile.blockIron.name") .build("minecraft", "iron_block")); register(43, doubleStoneSlab(LanternEnumTraits.STONE_SLAB1_TYPE, LanternSlabType.STONE) .translation("tile.stoneSlab.name") .build("minecraft", "double_stone_slab"), blockState -> doubleStoneSlabData(blockState, blockState.getTraitValue(LanternEnumTraits.STONE_SLAB1_TYPE).get().getInternalId())); register(44, stoneSlab(LanternEnumTraits.STONE_SLAB1_TYPE, LanternSlabType.STONE, () -> BlockTypes.STONE_SLAB, () -> BlockTypes.DOUBLE_STONE_SLAB) .translation("tile.stoneSlab.name") .collisionBox(BoundingBoxes::slab) .build("minecraft", "stone_slab"), blockState -> stoneSlabData(blockState, blockState.getTraitValue(LanternEnumTraits.STONE_SLAB1_TYPE).get().getInternalId())); register(45, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(2.0)) .add(blastResistance(10.0))) .translation("tile.brick.name") .build("minecraft", "brick_block")); register(46, simpleBuilder() .trait(LanternBooleanTraits.EXPLODE) .defaultState(state -> state .withTrait(LanternBooleanTraits.EXPLODE, false).get()) .itemType() .properties(builder -> builder .add(INSTANT_BROKEN)) .translation("tile.tnt.name") .build("minecraft", "tnt"), blockState -> (byte) (blockState.getTraitValue(LanternBooleanTraits.EXPLODE).get() ? 1 : 0)); register(47, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(1.5)) .add(blastResistance(7.5))) .translation("tile.bookshelf.name") .build("minecraft", "bookshelf")); register(48, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(2.0)) .add(blastResistance(10.0))) .translation("tile.stoneMoss.name") .build("minecraft", "mossy_cobblestone")); register(49, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(50.0)) .add(blastResistance(2000.0))) .translation("tile.obsidian.name") .build("minecraft", "obsidian")); register(50, builder() .trait(LanternEnumTraits.TORCH_FACING) .defaultState(state -> state .withTrait(LanternEnumTraits.TORCH_FACING, Direction.UP).get()) .itemType() .properties(builder -> builder .add(PASSABLE) .add(INSTANT_BROKEN)) .translation("tile.torch.name") .selectionBox(BoundingBoxes::torch) .behaviors(pipeline -> pipeline .add(new BlockSnapshotProviderPlaceBehavior()) .add(new TorchPlacementBehavior()) .add(new SimpleBreakBehavior())) .build("minecraft", "torch"), blockState -> { final Direction direction = blockState.getTraitValue(LanternEnumTraits.TORCH_FACING).get(); switch (direction) { case EAST: return (byte) 1; case WEST: return (byte) 2; case SOUTH: return (byte) 3; case NORTH: return (byte) 4; case UP: return (byte) 5; default: throw new IllegalArgumentException(); } }); register(51, simpleBuilder() .properties(builder -> builder .add(PASSABLE) .add(INSTANT_BROKEN) .add(lightEmission(15))) .collisionBox(BoundingBoxes.NULL) .translation("tile.fire.name") .build("minecraft", "fire")); register(52, simpleBuilder() .properties(builder -> builder .add(hardness(5.0)) .add(blastResistance(25.0))) .translation("tile.mobSpawner.name") .build("minecraft", "mob_spawner")); register(54, chestBuilder() .translation("tile.chest.name") .build("minecraft", "chest"), this::horizontalFacingData); register(55, simpleBuilder() .traits(LanternIntegerTraits.POWER) .selectionBox(new AABB(0, 0, 0, 1.0, 0.0625, 1.0)) .properties(builder -> builder .add(PASSABLE) .add(INSTANT_BROKEN)) .defaultState(state -> state .withTrait(LanternIntegerTraits.POWER, 0).get()) .translation("tile.redstoneDust.name") .build("minecraft", "redstone_wire"), state -> state.get(Keys.POWER).get().byteValue()); register(56, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(5.0))) .translation("tile.oreDiamond.name") .build("minecraft", "diamond_ore")); register(57, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(5.0)) .add(blastResistance(10.0))) .translation("tile.blockDiamond.name") .build("minecraft", "diamond_block")); register(58, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(2.5)) .add(blastResistance(12.5))) .translation("tile.workbench.name") .behaviors(pipeline -> pipeline .add(new CraftingTableInteractionBehavior())) .build("minecraft", "crafting_table")); register(60, simpleBuilder() .collisionBox(BoundingBoxes.farmland()) .trait(LanternIntegerTraits.MOISTURE) .properties(builder -> builder .add(hardness(0.6)) .add(blastResistance(3.0))) .defaultState(state -> state.withTrait(LanternIntegerTraits.MOISTURE, 0).get()) .translation("tile.farmland.name") .build("minecraft", "farmland"), state -> state.getTraitValue(LanternIntegerTraits.MOISTURE).get().byteValue()); register(61, furnaceBuilder() .itemType() .translation("tile.furnace.name") .build("minecraft", "furnace"), this::directionData); register(62, furnaceBuilder() .properties(builder -> builder .add(lightEmission(13))) .translation("tile.furnace.name") .build("minecraft", "lit_furnace"), this::directionData); register(70, pressurePlateBuilder() .translation("tile.pressurePlateStone.name") .build("minecraft", "stone_pressure_plate"), this::pressurePlateData); register(72, pressurePlateBuilder() .translation("tile.pressurePlateWood.name") .build("minecraft", "wooden_pressure_plate"), this::pressurePlateData); register(84, simpleBuilder() .itemType() .traits(LanternBooleanTraits.HAS_RECORD) .defaultState(state -> state .withTrait(LanternBooleanTraits.HAS_RECORD, false).get()) .properties(builder -> builder .add(hardness(2.0)) .add(blastResistance(10.0))) .tileEntityType(() -> TileEntityTypes.JUKEBOX) .translation("tile.jukebox.name") .behaviors(pipeline -> pipeline .add(new JukeboxInteractionBehavior())) .build("minecraft", "jukebox"), state -> (byte) (state.getTraitValue(LanternBooleanTraits.HAS_RECORD).get() ? 1 : 0)); register(86, pumpkinBuilder() .itemType(builder -> builder .properties(properties -> properties .add(equipmentType(EquipmentTypes.HEADWEAR)))) .translation("tile.pumpkin.name") .build("minecraft", "pumpkin"), this::horizontalDirectionData); register(87, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(0.4)) .add(blastResistance(2.0))) .translation("tile.hellrock.name") .build("minecraft", "netherrack")); register(91, pumpkinBuilder() .properties(builder -> builder .add(lightEmission(15))) .translation("tile.litpumpkin.name") .build("minecraft", "lit_pumpkin"), this::horizontalDirectionData); register(95, dyedBuilder("tile.stainedGlass.%s.name") .properties(builder -> builder .add(hardness(0.3)) .add(blastResistance(1.5))) .build("minecraft", "stained_glass"), this::dyedData); register(101, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(5.0)) .add(blastResistance(10.0))) .translation("tile.fenceIron.name") .build("minecraft", "iron_bars")); register(121, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(15.0))) .translation("tile.whiteStone.name") .build("minecraft", "end_stone")); register(125, simpleBuilder() .traits(LanternEnumTraits.TREE_TYPE) .defaultState(state -> state .withTrait(LanternEnumTraits.TREE_TYPE, LanternTreeType.OAK).get()) .translation(TranslationProvider.of(LanternEnumTraits.TREE_TYPE, type -> tr("tile.woodSlab." + type.getTranslationKeyBase() + ".name"))) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.TREE_TYPE, LanternTreeType.OAK) ) ) .properties(builder -> builder .add(hardness(2.0)) .add(blastResistance(5.0))) .build("minecraft", "double_wooden_slab"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.TREE_TYPE).get().getInternalId()); register(126, simpleBuilder() .traits(LanternEnumTraits.PORTION_TYPE, LanternEnumTraits.TREE_TYPE) .defaultState(state -> state .withTrait(LanternEnumTraits.PORTION_TYPE, LanternPortionType.BOTTOM).get() .withTrait(LanternEnumTraits.TREE_TYPE, LanternTreeType.OAK).get()) .translation(TranslationProvider.of(LanternEnumTraits.TREE_TYPE, type -> tr("tile.woodSlab." + type.getTranslationKeyBase() + ".name"))) .itemType(builder -> builder .behaviors(pipeline -> pipeline .add(new SlabItemInteractionBehavior<>(LanternEnumTraits.TREE_TYPE, () -> BlockTypes.WOODEN_SLAB, () -> BlockTypes.DOUBLE_WOODEN_SLAB)) .add(new PlacementCollisionDetectionBehavior())) .keysProvider(collection -> collection .register(Keys.TREE_TYPE, LanternTreeType.OAK) ) ) .collisionBox(BoundingBoxes::slab) .properties(builder -> builder .add(hardness(2.0)) .add(blastResistance(5.0))) .build("minecraft", "wooden_slab"), blockState -> { final int type = blockState.getTraitValue(LanternEnumTraits.TREE_TYPE).get().getInternalId(); final int portion = (byte) blockState.getTraitValue(LanternEnumTraits.PORTION_TYPE).get().getInternalId(); return (byte) (portion << 3 | type); }); register(130, simpleBuilder() .trait(LanternEnumTraits.HORIZONTAL_FACING) .defaultState(state -> state.withTrait(LanternEnumTraits.HORIZONTAL_FACING, Direction.NORTH).get()) .itemType() .tileEntityType(() -> TileEntityTypes.ENDER_CHEST) .properties(builder -> builder .add(hardness(22.5)) .add(blastResistance(3000.0)) .add(lightEmission(7))) .translation("tile.enderChest.name") .collisionBox(BoundingBoxes.chest()) .behaviors(pipeline -> pipeline .add(new HorizontalRotationPlacementBehavior()) .add(new EnderChestInteractionBehavior())) .build("minecraft", "ender_chest"), this::horizontalFacingData); register(146, chestBuilder() .translation("tile.chestTrap.name") .build("minecraft", "trapped_chest"), this::horizontalFacingData); register(147, weightedPressurePlateBuilder() .translation("tile.weightedPlate_light.name") .build("minecraft", "light_weighted_pressure_plate"), this::weightedPressurePlateData); register(148, weightedPressurePlateBuilder() .translation("tile.weightedPlate_heavy.name") .build("minecraft", "heavy_weighted_pressure_plate"), this::weightedPressurePlateData); register(152, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(5.0)) .add(blastResistance(30.0))) .translation("tile.blockRedstone.name") .build("minecraft", "redstone_block")); register(153, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(15.0))) .translation("tile.netherquartz.name") .build("minecraft", "quartz_ore")); register(154, simpleBuilder() .traits(LanternEnumTraits.HOPPER_FACING, LanternBooleanTraits.ENABLED) .defaultState(state -> state .withTrait(LanternEnumTraits.HOPPER_FACING, Direction.DOWN).get() .withTrait(LanternBooleanTraits.ENABLED, false).get()) .itemType() .properties(builder -> builder .add(hardness(3.0)) .add(blastResistance(8.0))) .translation("tile.hopper.name") .behaviors(pipeline -> pipeline .add(new HopperPlacementBehavior())) .build("minecraft", "hopper"), blockState -> { int data = directionData(blockState.getTraitValue(LanternEnumTraits.HOPPER_FACING).get()); if (!blockState.getTraitValue(LanternBooleanTraits.ENABLED).get()) { data |= 0x8; } return (byte) data; }); register(155, simpleBuilder() .trait(LanternEnumTraits.QUARTZ_TYPE) .defaultState(state -> state .withTrait(LanternEnumTraits.QUARTZ_TYPE, LanternQuartzType.DEFAULT).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.QUARTZ_TYPE, LanternQuartzType.DEFAULT) ) ) .properties(builder -> builder .add(hardness(0.8)) .add(blastResistance(2.4))) .translation(TranslationProvider.of(LanternEnumTraits.QUARTZ_TYPE)) .behaviors(pipeline -> pipeline .add(new QuartzLinesRotationPlacementBehavior())) .build("minecraft", "quartz_block"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.QUARTZ_TYPE).get().getInternalId()); register(158, simpleBuilder() .traits(LanternEnumTraits.FACING, LanternBooleanTraits.TRIGGERED) .defaultState(state -> state .withTrait(LanternEnumTraits.FACING, Direction.NORTH).get() .withTrait(LanternBooleanTraits.TRIGGERED, false).get()) .itemType() .properties(builder -> builder .add(hardness(3.5)) .add(blastResistance(17.5))) .translation("tile.dropper.name") .behaviors(pipeline -> pipeline .add(new RotationPlacementBehavior())) .build("minecraft", "dropper"), blockState -> { int data = directionData(blockState.getTraitValue(LanternEnumTraits.FACING).get()); if (blockState.getTraitValue(LanternBooleanTraits.TRIGGERED).get()) { data |= 0x8; } return (byte) data; }); register(159, dyedBuilder("tile.clayHardenedStained.%s.name") .properties(builder -> builder .add(hardness(1.25)) .add(blastResistance(7.0))) .build("minecraft", "stained_hardened_clay"), this::dyedData); register(160, dyedBuilder("tile.thinStainedGlass.%s.name") .properties(builder -> builder .add(hardness(0.3)) .add(blastResistance(1.5))) .build("minecraft", "stained_glass_pane"), this::dyedData); register(161, leavesBuilder(LanternEnumTraits.LEAVES2_TYPE, LanternTreeType.ACACIA) .build("minecraft", "leaves2"), blockState -> leavesData(blockState, blockState.getTraitValue(LanternEnumTraits.LEAVES2_TYPE).get().getInternalId() - 4)); register(162, logBuilder(LanternEnumTraits.LOG2_TYPE, LanternTreeType.ACACIA) .build("minecraft", "log2"), blockState -> logData(blockState, blockState.getTraitValue(LanternEnumTraits.LOG2_TYPE).get().getInternalId() - 4)); register(166, simpleBuilder() .itemType() .properties(builder -> builder .add(PropertyProviderCollections.UNBREAKABLE)) .translation("tile.barrier.name") .build("minecraft", "barrier")); register(171, dyedBuilder("tile.carpet.%s.name") .properties(builder -> builder .add(hardness(0.1)) .add(blastResistance(0.5)) .add(solidMaterial(false))) .collisionBox(BoundingBoxes.carpet()) .build("minecraft", "carpet"), this::dyedData); register(179, simpleBuilder() .trait(LanternEnumTraits.SANDSTONE_TYPE) .defaultState(state -> state.withTrait(LanternEnumTraits.SANDSTONE_TYPE, LanternSandstoneType.DEFAULT).get()) .itemType(builder -> builder .keysProvider(collection -> collection .register(Keys.SANDSTONE_TYPE, LanternSandstoneType.DEFAULT) ) ) .properties(builder -> builder .add(hardness(0.8)) .add(blastResistance(4.0))) .translation(TranslationProvider.of(LanternEnumTraits.SANDSTONE_TYPE)) .build("minecraft", "red_sandstone"), blockState -> (byte) blockState.getTraitValue(LanternEnumTraits.SANDSTONE_TYPE).get().getInternalId()); register(181, doubleStoneSlab(LanternEnumTraits.STONE_SLAB2_TYPE, LanternSlabType.RED_SAND) .translation("tile.stoneSlab2.name") .build("minecraft", "double_stone_slab2"), blockState -> doubleStoneSlabData(blockState, blockState.getTraitValue(LanternEnumTraits.STONE_SLAB2_TYPE).get().getInternalId() - 8)); register(182, stoneSlab(LanternEnumTraits.STONE_SLAB2_TYPE, LanternSlabType.RED_SAND, () -> BlockTypes.STONE_SLAB2, () -> BlockTypes.DOUBLE_STONE_SLAB2) .translation("tile.stoneSlab2.name") .collisionBox(BoundingBoxes::slab) .build("minecraft", "stone_slab2"), blockState -> stoneSlabData(blockState, blockState.getTraitValue(LanternEnumTraits.STONE_SLAB2_TYPE).get().getInternalId() - 8)); register(198, simpleBuilder() .itemType() .properties(builder -> builder .add(hardness(0.0)) .add(blastResistance(0.0)) .add(lightEmission(14))) .translation("tile.endRod.name") .build("minecraft", "end_rod")); register(219, shulkerBox() .translation("tile.shulkerBoxWhite.name") .build("minecraft", "white_shulker_box"), this::shulkerBoxData); register(220, shulkerBox() .translation("tile.shulkerBoxOrange.name") .build("minecraft", "orange_shulker_box"), this::shulkerBoxData); register(221, shulkerBox() .translation("tile.shulkerBoxMagenta.name") .build("minecraft", "magenta_shulker_box"), this::shulkerBoxData); register(222, shulkerBox() .translation("tile.shulkerBoxLightBlue.name") .build("minecraft", "light_blue_shulker_box"), this::shulkerBoxData); register(223, shulkerBox() .translation("tile.shulkerBoxYellow.name") .build("minecraft", "yellow_shulker_box"), this::shulkerBoxData); register(224, shulkerBox() .translation("tile.shulkerBoxLime.name") .build("minecraft", "lime_shulker_box"), this::shulkerBoxData); register(225, shulkerBox() .translation("tile.shulkerBoxPink.name") .build("minecraft", "pink_shulker_box"), this::shulkerBoxData); register(226, shulkerBox() .translation("tile.shulkerBoxGray.name") .build("minecraft", "gray_shulker_box"), this::shulkerBoxData); register(227, shulkerBox() .translation("tile.shulkerBoxSilver.name") .build("minecraft", "silver_shulker_box"), this::shulkerBoxData); register(228, shulkerBox() .translation("tile.shulkerBoxCyan.name") .build("minecraft", "cyan_shulker_box"), this::shulkerBoxData); register(229, shulkerBox() .translation("tile.shulkerBoxPurple.name") .build("minecraft", "purple_shulker_box"), this::shulkerBoxData); register(230, shulkerBox() .translation("tile.shulkerBoxBlue.name") .build("minecraft", "blue_shulker_box"), this::shulkerBoxData); register(231, shulkerBox() .translation("tile.shulkerBoxBrown.name") .build("minecraft", "brown_shulker_box"), this::shulkerBoxData); register(232, shulkerBox() .translation("tile.shulkerBoxGreen.name") .build("minecraft", "green_shulker_box"), this::shulkerBoxData); register(233, shulkerBox() .translation("tile.shulkerBoxRed.name") .build("minecraft", "red_shulker_box"), this::shulkerBoxData); register(234, shulkerBox() .translation("tile.shulkerBoxBlack.name") .build("minecraft", "black_shulker_box"), this::shulkerBoxData); register(63, simpleBuilder() .trait(LanternIntegerTraits.ROTATION) .defaultState(state -> state .withTrait(LanternIntegerTraits.ROTATION, 0).get()) .properties(builder -> builder .add(hardness(1.0)) .add(blastResistance(5.0))) .behaviors(pipeline -> pipeline .add(new SignInteractionBehavior())) .tileEntityType(() -> TileEntityTypes.SIGN) .build("minecraft", "standing_sign"), blockState -> blockState.getTraitValue(LanternIntegerTraits.ROTATION).get().byteValue()); register(68, simpleBuilder() .trait(LanternEnumTraits.HORIZONTAL_FACING) .defaultState(state -> state .withTrait(LanternEnumTraits.HORIZONTAL_FACING, Direction.NORTH).get()) .properties(builder -> builder .add(hardness(1.0)) .add(blastResistance(5.0))) .behaviors(pipeline -> pipeline .add(new SignInteractionBehavior())) .tileEntityType(() -> TileEntityTypes.SIGN) .build("minecraft", "wall_sign"), this::horizontalFacingData); register(176, simpleBuilder() .trait(LanternIntegerTraits.ROTATION) .defaultState(state -> state .withTrait(LanternIntegerTraits.ROTATION, 0).get()) .properties(builder -> builder .add(hardness(1.0)) .add(blastResistance(5.0))) .behaviors(pipeline -> pipeline .add(new SignInteractionBehavior())) .tileEntityType(() -> TileEntityTypes.BANNER) .build("minecraft", "standing_banner"), blockState -> blockState.getTraitValue(LanternIntegerTraits.ROTATION).get().byteValue()); register(177, simpleBuilder() .trait(LanternEnumTraits.HORIZONTAL_FACING) .defaultState(state -> state .withTrait(LanternEnumTraits.HORIZONTAL_FACING, Direction.NORTH).get()) .properties(builder -> builder .add(hardness(1.0)) .add(blastResistance(5.0))) .behaviors(pipeline -> pipeline .add(new SignInteractionBehavior())) .tileEntityType(() -> TileEntityTypes.BANNER) .build("minecraft", "wall_banner"), this::horizontalFacingData); }
@override public void registerdefaults() { register(0, builder() .properties(propertyprovidercollections.default_gas) .translation("tile.air.name") .build("minecraft", "air")); register(1, simplebuilder() .trait(lanternenumtraits.stone_type) .defaultstate(state -> state.withtrait(lanternenumtraits.stone_type, lanternstonetype.stone).get()) .itemtype(builder -> builder .keysprovider(collection -> collection .register(keys.stone_type, lanternstonetype.stone) ) ) .properties(builder -> builder .add(hardness(1.5)) .add(blastresistance(30.0))) .translation(translationprovider.of(lanternenumtraits.stone_type)) .build("minecraft", "stone"), blockstate -> (byte) blockstate.gettraitvalue(lanternenumtraits.stone_type).get().getinternalid()); register(2, simplebuilder() .trait(lanternbooleantraits.snowy) .extendedstateprovider(new snowyextendedblockstateprovider()) .defaultstate(state -> state.withtrait(lanternbooleantraits.snowy, false).get()) .itemtype() .properties(builder -> builder .add(hardness(0.6)) .add(blastresistance(3.0))) .translation("tile.grass.name") .build("minecraft", "grass")); register(3, simplebuilder() .traits(lanternenumtraits.dirt_type, lanternbooleantraits.snowy) .defaultstate(state -> state .withtrait(lanternenumtraits.dirt_type, lanterndirttype.dirt).get() .withtrait(lanternbooleantraits.snowy, false).get()) .extendedstateprovider(new snowyextendedblockstateprovider()) .itemtype(builder -> builder .keysprovider(collection -> collection .register(keys.dirt_type, lanterndirttype.dirt) ) ) .properties(builder -> builder .add(hardness(0.5)) .add(blastresistance(2.5))) .translation(translationprovider.of(lanternenumtraits.dirt_type)) .build("minecraft", "dirt"), blockstate -> (byte) blockstate.gettraitvalue(lanternenumtraits.dirt_type).get().getinternalid()); register(4, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(2.0)) .add(blastresistance(3.0))) .translation("tile.stonebrick.name") .build("minecraft", "cobblestone")); register(5, simplebuilder() .trait(lanternenumtraits.tree_type) .defaultstate(state -> state.withtrait(lanternenumtraits.tree_type, lanterntreetype.oak).get()) .itemtype(builder -> builder .keysprovider(collection -> collection .register(keys.tree_type, lanterntreetype.oak) ) ) .properties(builder -> builder .add(hardness(2.0)) .add(blastresistance(5.0)) .add(flammableinfo(5, 20))) .translation(translationprovider.of(lanternenumtraits.tree_type, type -> tr("tile.planks." + type.gettranslationkeybase() + ".name"))) .build("minecraft", "planks"), blockstate -> (byte) blockstate.gettraitvalue(lanternenumtraits.tree_type).get().getinternalid()); register(6, simplebuilder() .traits(lanternenumtraits.tree_type, lanternintegertraits.sapling_growth_stage) .defaultstate(state -> state .withtrait(lanternenumtraits.tree_type, lanterntreetype.oak).get() .withtrait(lanternintegertraits.sapling_growth_stage, 0).get()) .itemtype(builder -> builder .keysprovider(collection -> collection .register(keys.tree_type, lanterntreetype.oak) ) ) .properties(builder -> builder .add(passable) .add(instant_broken)) .translation(translationprovider.of(lanternenumtraits.tree_type, type -> tr("tile.sapling." + type.gettranslationkeybase() + ".name"))) .build("minecraft", "sapling"), blockstate -> { final int type = blockstate.gettraitvalue(lanternenumtraits.tree_type).get().getinternalid(); final int stage = blockstate.gettraitvalue(lanternintegertraits.sapling_growth_stage).get(); return (byte) (stage << 3 | type); }); register(7, simplebuilder() .itemtype() .properties(builder -> builder .add(propertyprovidercollections.unbreakable)) .translation("tile.bedrock.name") .build("minecraft", "bedrock")); register(12, simplebuilder() .trait(lanternenumtraits.sand_type) .defaultstate(state -> state.withtrait(lanternenumtraits.sand_type, lanternsandtype.normal).get()) .itemtype(builder -> builder .keysprovider(collection -> collection .register(keys.sand_type, lanternsandtype.normal) ) ) .properties(builder -> builder .add(hardness(0.5)) .add(blastresistance(2.5))) .translation(translationprovider.of(lanternenumtraits.sand_type)) .build("minecraft", "sand"), blockstate -> (byte) blockstate.gettraitvalue(lanternenumtraits.sand_type).get().getinternalid()); register(13, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(0.6)) .add(blastresistance(3.0))) .translation("tile.gravel.name") .build("minecraft", "gravel")); register(14, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(3.0)) .add(blastresistance(15.0))) .translation("tile.oregold.name") .build("minecraft", "gold_ore")); register(15, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(3.0)) .add(blastresistance(15.0))) .translation("tile.oreiron.name") .build("minecraft", "iron_ore")); register(16, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(3.0)) .add(blastresistance(15.0))) .translation("tile.orecoal.name") .build("minecraft", "coal_ore")); register(17, logbuilder(lanternenumtraits.log1_type, lanterntreetype.oak) .build("minecraft", "log"), blockstate -> logdata(blockstate, blockstate.gettraitvalue(lanternenumtraits.log1_type).get().getinternalid())); register(18, leavesbuilder(lanternenumtraits.leaves1_type, lanterntreetype.oak) .build("minecraft", "leaves"), blockstate -> leavesdata(blockstate, blockstate.gettraitvalue(lanternenumtraits.leaves1_type).get().getinternalid())); register(19, simplebuilder() .trait(lanternbooleantraits.is_wet) .defaultstate(state -> state.withtrait(lanternbooleantraits.is_wet, false).get()) .itemtype(builder -> builder .keysprovider(collection -> collection .register(keys.is_wet, false) ) ) .properties(builder -> builder .add(hardness(0.6)) .add(blastresistance(3.0))) .translation(new spongetranslationprovider()) .build("minecraft", "sponge"), blockstate -> (byte) (blockstate.gettraitvalue(lanternbooleantraits.is_wet).get() ? 1 : 0)); register(20, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(0.3)) .add(blastresistance(1.5))) .translation("tile.glass.name") .build("minecraft", "glass")); register(21, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(3.0)) .add(blastresistance(15.0))) .translation("tile.orelapis.name") .build("minecraft", "lapis_ore")); register(22, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(3.0)) .add(blastresistance(15.0))) .translation("tile.blocklapis.name") .build("minecraft", "lapis_block")); register(23, simplebuilder() .traits(lanternenumtraits.facing, lanternbooleantraits.triggered) .defaultstate(state -> state .withtrait(lanternenumtraits.facing, direction.north).get() .withtrait(lanternbooleantraits.triggered, false).get()) .itemtype() .properties(builder -> builder .add(hardness(3.5)) .add(blastresistance(17.5))) .translation("tile.dispenser.name") .behaviors(pipeline -> pipeline .add(new rotationplacementbehavior())) .build("minecraft", "dispenser"), blockstate -> { int data = directiondata(blockstate.gettraitvalue(lanternenumtraits.facing).get()); if (blockstate.gettraitvalue(lanternbooleantraits.triggered).get()) { data |= 0x8; } return (byte) data; }); register(24, simplebuilder() .trait(lanternenumtraits.sandstone_type) .defaultstate(state -> state.withtrait(lanternenumtraits.sandstone_type, lanternsandstonetype.default).get()) .itemtype(builder -> builder .keysprovider(collection -> collection .register(keys.sandstone_type, lanternsandstonetype.default) ) ) .properties(builder -> builder .add(hardness(0.8)) .add(blastresistance(4.0))) .translation(translationprovider.of(lanternenumtraits.sandstone_type)) .build("minecraft", "sandstone"), blockstate -> (byte) blockstate.gettraitvalue(lanternenumtraits.sandstone_type).get().getinternalid()); register(25, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(0.8)) .add(blastresistance(4.0))) .translation("tile.musicblock.name") .tileentitytype(() -> tileentitytypes.note) .behaviors(pipeline -> pipeline .add(new noteblockinteractionbehavior())) .build("minecraft", "noteblock")); register(26, simplebuilder() .traits(lanternenumtraits.horizontal_facing, lanternenumtraits.bed_part, lanternbooleantraits.occupied) .defaultstate(state -> state .withtrait(lanternenumtraits.horizontal_facing, direction.north).get() .withtrait(lanternenumtraits.bed_part, lanternbedpart.foot).get() .withtrait(lanternbooleantraits.occupied, false).get()) .properties(builder -> builder .add(hardness(0.2)) .add(blastresistance(1.0))) .translation("tile.bed.name") .build("minecraft", "bed"), blockstate -> { final direction facing = blockstate.gettraitvalue(lanternenumtraits.horizontal_facing).get(); int type = facing == direction.south ? 0 : facing == direction.west ? 1 : facing == direction.north ? 2 : facing == direction.east ? 3 : -1; checkargument(type != -1); if (blockstate.gettraitvalue(lanternbooleantraits.occupied).get()) { type |= 0x4; } if (blockstate.gettraitvalue(lanternenumtraits.bed_part).get() == lanternbedpart.head) { type |= 0x8; } return (byte) type; }); register(27, simplebuilder() .traits(lanternenumtraits.straight_rail_direction, lanternbooleantraits.powered) .defaultstate(state -> state .withtrait(lanternenumtraits.straight_rail_direction, lanternraildirection.north_south).get() .withtrait(lanternbooleantraits.powered, false).get()) .itemtype() .selectionbox(boundingboxes::rail) .properties(builder -> builder .add(passable) .add(hardness(0.7)) .add(blastresistance(3.5))) .translation("tile.goldenrail.name") .build("minecraft", "golden_rail"), blockstate -> { int type = blockstate.gettraitvalue(lanternenumtraits.straight_rail_direction).get().getinternalid(); if (blockstate.gettraitvalue(lanternbooleantraits.powered).get()) { type |= 0x8; } return (byte) type; }); register(28, simplebuilder() .traits(lanternenumtraits.straight_rail_direction, lanternbooleantraits.powered) .defaultstate(state -> state .withtrait(lanternenumtraits.straight_rail_direction, lanternraildirection.north_south).get() .withtrait(lanternbooleantraits.powered, false).get()) .itemtype() .selectionbox(boundingboxes::rail) .properties(builder -> builder .add(passable) .add(hardness(0.7)) .add(blastresistance(3.5))) .translation("tile.detectorrail.name") .build("minecraft", "detector_rail"), blockstate -> { int type = blockstate.gettraitvalue(lanternenumtraits.straight_rail_direction).get().getinternalid(); if (blockstate.gettraitvalue(lanternbooleantraits.powered).get()) { type |= 0x8; } return (byte) type; }); register(30, simplebuilder() .itemtype() .properties(builder -> builder .add(passable) .add(hardness(4.0)) .add(blastresistance(20.0))) .translation("tile.web.name") .build("minecraft", "web")); register(31, simplebuilder() .traits(lanternenumtraits.shrub_type) .defaultstate(state -> state .withtrait(lanternenumtraits.shrub_type, lanternshrubtype.dead_bush).get()) .itemtype(builder -> builder .keysprovider(collection -> collection .register(keys.shrub_type, lanternshrubtype.dead_bush))) .selectionbox(boundingboxes.bush()) .properties(builder -> builder .add(instant_broken) .add(passable) .add(replaceable(true))) .translation("tile.tallgrass.name") .build("minecraft", "tallgrass"), blockstate -> (byte) blockstate.gettraitvalue(lanternenumtraits.shrub_type).get().getinternalid()); register(32, simplebuilder() .properties(builder -> builder .add(instant_broken) .add(passable) .add(replaceable(true))) .selectionbox(boundingboxes.bush()) .itemtype() .translation("tile.deadbush.name") .build("minecraft", "deadbush")); register(35, dyedbuilder("tile.wool.%s.name") .properties(builder -> builder .add(hardness(0.8)) .add(blastresistance(4.0))) .build("minecraft", "wool"), this::dyeddata); register(37, simplebuilder() .traits(lanternenumtraits.yellow_flower_type) .defaultstate(state -> state .withtrait(lanternenumtraits.yellow_flower_type, lanternplanttype.dandelion).get()) .itemtype(builder -> builder .keysprovider(collection -> collection .register(keys.plant_type, lanternplanttype.dandelion))) .selectionbox(boundingboxes.bush()) .properties(builder -> builder .add(instant_broken) .add(passable)) .translation(translationprovider.of(lanternenumtraits.yellow_flower_type)) .build("minecraft", "yellow_flower"), blockstate -> (byte) blockstate.gettraitvalue(lanternenumtraits.yellow_flower_type).get().getinternalid()); register(38, simplebuilder() .traits(lanternenumtraits.red_flower_type) .defaultstate(state -> state .withtrait(lanternenumtraits.red_flower_type, lanternplanttype.poppy).get()) .itemtype(builder -> builder .keysprovider(collection -> collection .register(keys.plant_type, lanternplanttype.poppy))) .selectionbox(boundingboxes.bush()) .properties(builder -> builder .add(instant_broken) .add(passable)) .translation(translationprovider.of(lanternenumtraits.red_flower_type)) .build("minecraft", "red_flower"), blockstate -> (byte) blockstate.gettraitvalue(lanternenumtraits.red_flower_type).get().getinternalid()); register(39, simplebuilder() .selectionbox(boundingboxes.bush()) .properties(builder -> builder .add(instant_broken) .add(passable) .add(lightemission(1))) .translation("tile.mushroom.name") .build("minecraft", "brown_mushroom")); register(40, simplebuilder() .selectionbox(boundingboxes.bush()) .properties(builder -> builder .add(instant_broken) .add(passable)) .translation("tile.mushroom.name") .build("minecraft", "red_mushroom")); register(41, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(3.0)) .add(blastresistance(10.0))) .translation("tile.blockgold.name") .build("minecraft", "gold_block")); register(42, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(5.0)) .add(blastresistance(10.0))) .translation("tile.blockiron.name") .build("minecraft", "iron_block")); register(43, doublestoneslab(lanternenumtraits.stone_slab1_type, lanternslabtype.stone) .translation("tile.stoneslab.name") .build("minecraft", "double_stone_slab"), blockstate -> doublestoneslabdata(blockstate, blockstate.gettraitvalue(lanternenumtraits.stone_slab1_type).get().getinternalid())); register(44, stoneslab(lanternenumtraits.stone_slab1_type, lanternslabtype.stone, () -> blocktypes.stone_slab, () -> blocktypes.double_stone_slab) .translation("tile.stoneslab.name") .collisionbox(boundingboxes::slab) .build("minecraft", "stone_slab"), blockstate -> stoneslabdata(blockstate, blockstate.gettraitvalue(lanternenumtraits.stone_slab1_type).get().getinternalid())); register(45, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(2.0)) .add(blastresistance(10.0))) .translation("tile.brick.name") .build("minecraft", "brick_block")); register(46, simplebuilder() .trait(lanternbooleantraits.explode) .defaultstate(state -> state .withtrait(lanternbooleantraits.explode, false).get()) .itemtype() .properties(builder -> builder .add(instant_broken)) .translation("tile.tnt.name") .build("minecraft", "tnt"), blockstate -> (byte) (blockstate.gettraitvalue(lanternbooleantraits.explode).get() ? 1 : 0)); register(47, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(1.5)) .add(blastresistance(7.5))) .translation("tile.bookshelf.name") .build("minecraft", "bookshelf")); register(48, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(2.0)) .add(blastresistance(10.0))) .translation("tile.stonemoss.name") .build("minecraft", "mossy_cobblestone")); register(49, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(50.0)) .add(blastresistance(2000.0))) .translation("tile.obsidian.name") .build("minecraft", "obsidian")); register(50, builder() .trait(lanternenumtraits.torch_facing) .defaultstate(state -> state .withtrait(lanternenumtraits.torch_facing, direction.up).get()) .itemtype() .properties(builder -> builder .add(passable) .add(instant_broken)) .translation("tile.torch.name") .selectionbox(boundingboxes::torch) .behaviors(pipeline -> pipeline .add(new blocksnapshotproviderplacebehavior()) .add(new torchplacementbehavior()) .add(new simplebreakbehavior())) .build("minecraft", "torch"), blockstate -> { final direction direction = blockstate.gettraitvalue(lanternenumtraits.torch_facing).get(); switch (direction) { case east: return (byte) 1; case west: return (byte) 2; case south: return (byte) 3; case north: return (byte) 4; case up: return (byte) 5; default: throw new illegalargumentexception(); } }); register(51, simplebuilder() .properties(builder -> builder .add(passable) .add(instant_broken) .add(lightemission(15))) .collisionbox(boundingboxes.null) .translation("tile.fire.name") .build("minecraft", "fire")); register(52, simplebuilder() .properties(builder -> builder .add(hardness(5.0)) .add(blastresistance(25.0))) .translation("tile.mobspawner.name") .build("minecraft", "mob_spawner")); register(54, chestbuilder() .translation("tile.chest.name") .build("minecraft", "chest"), this::horizontalfacingdata); register(55, simplebuilder() .traits(lanternintegertraits.power) .selectionbox(new aabb(0, 0, 0, 1.0, 0.0625, 1.0)) .properties(builder -> builder .add(passable) .add(instant_broken)) .defaultstate(state -> state .withtrait(lanternintegertraits.power, 0).get()) .translation("tile.redstonedust.name") .build("minecraft", "redstone_wire"), state -> state.get(keys.power).get().bytevalue()); register(56, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(3.0)) .add(blastresistance(5.0))) .translation("tile.orediamond.name") .build("minecraft", "diamond_ore")); register(57, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(5.0)) .add(blastresistance(10.0))) .translation("tile.blockdiamond.name") .build("minecraft", "diamond_block")); register(58, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(2.5)) .add(blastresistance(12.5))) .translation("tile.workbench.name") .behaviors(pipeline -> pipeline .add(new craftingtableinteractionbehavior())) .build("minecraft", "crafting_table")); register(60, simplebuilder() .collisionbox(boundingboxes.farmland()) .trait(lanternintegertraits.moisture) .properties(builder -> builder .add(hardness(0.6)) .add(blastresistance(3.0))) .defaultstate(state -> state.withtrait(lanternintegertraits.moisture, 0).get()) .translation("tile.farmland.name") .build("minecraft", "farmland"), state -> state.gettraitvalue(lanternintegertraits.moisture).get().bytevalue()); register(61, furnacebuilder() .itemtype() .translation("tile.furnace.name") .build("minecraft", "furnace"), this::directiondata); register(62, furnacebuilder() .properties(builder -> builder .add(lightemission(13))) .translation("tile.furnace.name") .build("minecraft", "lit_furnace"), this::directiondata); register(70, pressureplatebuilder() .translation("tile.pressureplatestone.name") .build("minecraft", "stone_pressure_plate"), this::pressureplatedata); register(72, pressureplatebuilder() .translation("tile.pressureplatewood.name") .build("minecraft", "wooden_pressure_plate"), this::pressureplatedata); register(84, simplebuilder() .itemtype() .traits(lanternbooleantraits.has_record) .defaultstate(state -> state .withtrait(lanternbooleantraits.has_record, false).get()) .properties(builder -> builder .add(hardness(2.0)) .add(blastresistance(10.0))) .tileentitytype(() -> tileentitytypes.jukebox) .translation("tile.jukebox.name") .behaviors(pipeline -> pipeline .add(new jukeboxinteractionbehavior())) .build("minecraft", "jukebox"), state -> (byte) (state.gettraitvalue(lanternbooleantraits.has_record).get() ? 1 : 0)); register(86, pumpkinbuilder() .itemtype(builder -> builder .properties(properties -> properties .add(equipmenttype(equipmenttypes.headwear)))) .translation("tile.pumpkin.name") .build("minecraft", "pumpkin"), this::horizontaldirectiondata); register(87, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(0.4)) .add(blastresistance(2.0))) .translation("tile.hellrock.name") .build("minecraft", "netherrack")); register(91, pumpkinbuilder() .properties(builder -> builder .add(lightemission(15))) .translation("tile.litpumpkin.name") .build("minecraft", "lit_pumpkin"), this::horizontaldirectiondata); register(95, dyedbuilder("tile.stainedglass.%s.name") .properties(builder -> builder .add(hardness(0.3)) .add(blastresistance(1.5))) .build("minecraft", "stained_glass"), this::dyeddata); register(101, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(5.0)) .add(blastresistance(10.0))) .translation("tile.fenceiron.name") .build("minecraft", "iron_bars")); register(121, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(3.0)) .add(blastresistance(15.0))) .translation("tile.whitestone.name") .build("minecraft", "end_stone")); register(125, simplebuilder() .traits(lanternenumtraits.tree_type) .defaultstate(state -> state .withtrait(lanternenumtraits.tree_type, lanterntreetype.oak).get()) .translation(translationprovider.of(lanternenumtraits.tree_type, type -> tr("tile.woodslab." + type.gettranslationkeybase() + ".name"))) .itemtype(builder -> builder .keysprovider(collection -> collection .register(keys.tree_type, lanterntreetype.oak) ) ) .properties(builder -> builder .add(hardness(2.0)) .add(blastresistance(5.0))) .build("minecraft", "double_wooden_slab"), blockstate -> (byte) blockstate.gettraitvalue(lanternenumtraits.tree_type).get().getinternalid()); register(126, simplebuilder() .traits(lanternenumtraits.portion_type, lanternenumtraits.tree_type) .defaultstate(state -> state .withtrait(lanternenumtraits.portion_type, lanternportiontype.bottom).get() .withtrait(lanternenumtraits.tree_type, lanterntreetype.oak).get()) .translation(translationprovider.of(lanternenumtraits.tree_type, type -> tr("tile.woodslab." + type.gettranslationkeybase() + ".name"))) .itemtype(builder -> builder .behaviors(pipeline -> pipeline .add(new slabiteminteractionbehavior<>(lanternenumtraits.tree_type, () -> blocktypes.wooden_slab, () -> blocktypes.double_wooden_slab)) .add(new placementcollisiondetectionbehavior())) .keysprovider(collection -> collection .register(keys.tree_type, lanterntreetype.oak) ) ) .collisionbox(boundingboxes::slab) .properties(builder -> builder .add(hardness(2.0)) .add(blastresistance(5.0))) .build("minecraft", "wooden_slab"), blockstate -> { final int type = blockstate.gettraitvalue(lanternenumtraits.tree_type).get().getinternalid(); final int portion = (byte) blockstate.gettraitvalue(lanternenumtraits.portion_type).get().getinternalid(); return (byte) (portion << 3 | type); }); register(130, simplebuilder() .trait(lanternenumtraits.horizontal_facing) .defaultstate(state -> state.withtrait(lanternenumtraits.horizontal_facing, direction.north).get()) .itemtype() .tileentitytype(() -> tileentitytypes.ender_chest) .properties(builder -> builder .add(hardness(22.5)) .add(blastresistance(3000.0)) .add(lightemission(7))) .translation("tile.enderchest.name") .collisionbox(boundingboxes.chest()) .behaviors(pipeline -> pipeline .add(new horizontalrotationplacementbehavior()) .add(new enderchestinteractionbehavior())) .build("minecraft", "ender_chest"), this::horizontalfacingdata); register(146, chestbuilder() .translation("tile.chesttrap.name") .build("minecraft", "trapped_chest"), this::horizontalfacingdata); register(147, weightedpressureplatebuilder() .translation("tile.weightedplate_light.name") .build("minecraft", "light_weighted_pressure_plate"), this::weightedpressureplatedata); register(148, weightedpressureplatebuilder() .translation("tile.weightedplate_heavy.name") .build("minecraft", "heavy_weighted_pressure_plate"), this::weightedpressureplatedata); register(152, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(5.0)) .add(blastresistance(30.0))) .translation("tile.blockredstone.name") .build("minecraft", "redstone_block")); register(153, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(3.0)) .add(blastresistance(15.0))) .translation("tile.netherquartz.name") .build("minecraft", "quartz_ore")); register(154, simplebuilder() .traits(lanternenumtraits.hopper_facing, lanternbooleantraits.enabled) .defaultstate(state -> state .withtrait(lanternenumtraits.hopper_facing, direction.down).get() .withtrait(lanternbooleantraits.enabled, false).get()) .itemtype() .properties(builder -> builder .add(hardness(3.0)) .add(blastresistance(8.0))) .translation("tile.hopper.name") .behaviors(pipeline -> pipeline .add(new hopperplacementbehavior())) .build("minecraft", "hopper"), blockstate -> { int data = directiondata(blockstate.gettraitvalue(lanternenumtraits.hopper_facing).get()); if (!blockstate.gettraitvalue(lanternbooleantraits.enabled).get()) { data |= 0x8; } return (byte) data; }); register(155, simplebuilder() .trait(lanternenumtraits.quartz_type) .defaultstate(state -> state .withtrait(lanternenumtraits.quartz_type, lanternquartztype.default).get()) .itemtype(builder -> builder .keysprovider(collection -> collection .register(keys.quartz_type, lanternquartztype.default) ) ) .properties(builder -> builder .add(hardness(0.8)) .add(blastresistance(2.4))) .translation(translationprovider.of(lanternenumtraits.quartz_type)) .behaviors(pipeline -> pipeline .add(new quartzlinesrotationplacementbehavior())) .build("minecraft", "quartz_block"), blockstate -> (byte) blockstate.gettraitvalue(lanternenumtraits.quartz_type).get().getinternalid()); register(158, simplebuilder() .traits(lanternenumtraits.facing, lanternbooleantraits.triggered) .defaultstate(state -> state .withtrait(lanternenumtraits.facing, direction.north).get() .withtrait(lanternbooleantraits.triggered, false).get()) .itemtype() .properties(builder -> builder .add(hardness(3.5)) .add(blastresistance(17.5))) .translation("tile.dropper.name") .behaviors(pipeline -> pipeline .add(new rotationplacementbehavior())) .build("minecraft", "dropper"), blockstate -> { int data = directiondata(blockstate.gettraitvalue(lanternenumtraits.facing).get()); if (blockstate.gettraitvalue(lanternbooleantraits.triggered).get()) { data |= 0x8; } return (byte) data; }); register(159, dyedbuilder("tile.clayhardenedstained.%s.name") .properties(builder -> builder .add(hardness(1.25)) .add(blastresistance(7.0))) .build("minecraft", "stained_hardened_clay"), this::dyeddata); register(160, dyedbuilder("tile.thinstainedglass.%s.name") .properties(builder -> builder .add(hardness(0.3)) .add(blastresistance(1.5))) .build("minecraft", "stained_glass_pane"), this::dyeddata); register(161, leavesbuilder(lanternenumtraits.leaves2_type, lanterntreetype.acacia) .build("minecraft", "leaves2"), blockstate -> leavesdata(blockstate, blockstate.gettraitvalue(lanternenumtraits.leaves2_type).get().getinternalid() - 4)); register(162, logbuilder(lanternenumtraits.log2_type, lanterntreetype.acacia) .build("minecraft", "log2"), blockstate -> logdata(blockstate, blockstate.gettraitvalue(lanternenumtraits.log2_type).get().getinternalid() - 4)); register(166, simplebuilder() .itemtype() .properties(builder -> builder .add(propertyprovidercollections.unbreakable)) .translation("tile.barrier.name") .build("minecraft", "barrier")); register(171, dyedbuilder("tile.carpet.%s.name") .properties(builder -> builder .add(hardness(0.1)) .add(blastresistance(0.5)) .add(solidmaterial(false))) .collisionbox(boundingboxes.carpet()) .build("minecraft", "carpet"), this::dyeddata); register(179, simplebuilder() .trait(lanternenumtraits.sandstone_type) .defaultstate(state -> state.withtrait(lanternenumtraits.sandstone_type, lanternsandstonetype.default).get()) .itemtype(builder -> builder .keysprovider(collection -> collection .register(keys.sandstone_type, lanternsandstonetype.default) ) ) .properties(builder -> builder .add(hardness(0.8)) .add(blastresistance(4.0))) .translation(translationprovider.of(lanternenumtraits.sandstone_type)) .build("minecraft", "red_sandstone"), blockstate -> (byte) blockstate.gettraitvalue(lanternenumtraits.sandstone_type).get().getinternalid()); register(181, doublestoneslab(lanternenumtraits.stone_slab2_type, lanternslabtype.red_sand) .translation("tile.stoneslab2.name") .build("minecraft", "double_stone_slab2"), blockstate -> doublestoneslabdata(blockstate, blockstate.gettraitvalue(lanternenumtraits.stone_slab2_type).get().getinternalid() - 8)); register(182, stoneslab(lanternenumtraits.stone_slab2_type, lanternslabtype.red_sand, () -> blocktypes.stone_slab2, () -> blocktypes.double_stone_slab2) .translation("tile.stoneslab2.name") .collisionbox(boundingboxes::slab) .build("minecraft", "stone_slab2"), blockstate -> stoneslabdata(blockstate, blockstate.gettraitvalue(lanternenumtraits.stone_slab2_type).get().getinternalid() - 8)); register(198, simplebuilder() .itemtype() .properties(builder -> builder .add(hardness(0.0)) .add(blastresistance(0.0)) .add(lightemission(14))) .translation("tile.endrod.name") .build("minecraft", "end_rod")); register(219, shulkerbox() .translation("tile.shulkerboxwhite.name") .build("minecraft", "white_shulker_box"), this::shulkerboxdata); register(220, shulkerbox() .translation("tile.shulkerboxorange.name") .build("minecraft", "orange_shulker_box"), this::shulkerboxdata); register(221, shulkerbox() .translation("tile.shulkerboxmagenta.name") .build("minecraft", "magenta_shulker_box"), this::shulkerboxdata); register(222, shulkerbox() .translation("tile.shulkerboxlightblue.name") .build("minecraft", "light_blue_shulker_box"), this::shulkerboxdata); register(223, shulkerbox() .translation("tile.shulkerboxyellow.name") .build("minecraft", "yellow_shulker_box"), this::shulkerboxdata); register(224, shulkerbox() .translation("tile.shulkerboxlime.name") .build("minecraft", "lime_shulker_box"), this::shulkerboxdata); register(225, shulkerbox() .translation("tile.shulkerboxpink.name") .build("minecraft", "pink_shulker_box"), this::shulkerboxdata); register(226, shulkerbox() .translation("tile.shulkerboxgray.name") .build("minecraft", "gray_shulker_box"), this::shulkerboxdata); register(227, shulkerbox() .translation("tile.shulkerboxsilver.name") .build("minecraft", "silver_shulker_box"), this::shulkerboxdata); register(228, shulkerbox() .translation("tile.shulkerboxcyan.name") .build("minecraft", "cyan_shulker_box"), this::shulkerboxdata); register(229, shulkerbox() .translation("tile.shulkerboxpurple.name") .build("minecraft", "purple_shulker_box"), this::shulkerboxdata); register(230, shulkerbox() .translation("tile.shulkerboxblue.name") .build("minecraft", "blue_shulker_box"), this::shulkerboxdata); register(231, shulkerbox() .translation("tile.shulkerboxbrown.name") .build("minecraft", "brown_shulker_box"), this::shulkerboxdata); register(232, shulkerbox() .translation("tile.shulkerboxgreen.name") .build("minecraft", "green_shulker_box"), this::shulkerboxdata); register(233, shulkerbox() .translation("tile.shulkerboxred.name") .build("minecraft", "red_shulker_box"), this::shulkerboxdata); register(234, shulkerbox() .translation("tile.shulkerboxblack.name") .build("minecraft", "black_shulker_box"), this::shulkerboxdata); register(63, simplebuilder() .trait(lanternintegertraits.rotation) .defaultstate(state -> state .withtrait(lanternintegertraits.rotation, 0).get()) .properties(builder -> builder .add(hardness(1.0)) .add(blastresistance(5.0))) .behaviors(pipeline -> pipeline .add(new signinteractionbehavior())) .tileentitytype(() -> tileentitytypes.sign) .build("minecraft", "standing_sign"), blockstate -> blockstate.gettraitvalue(lanternintegertraits.rotation).get().bytevalue()); register(68, simplebuilder() .trait(lanternenumtraits.horizontal_facing) .defaultstate(state -> state .withtrait(lanternenumtraits.horizontal_facing, direction.north).get()) .properties(builder -> builder .add(hardness(1.0)) .add(blastresistance(5.0))) .behaviors(pipeline -> pipeline .add(new signinteractionbehavior())) .tileentitytype(() -> tileentitytypes.sign) .build("minecraft", "wall_sign"), this::horizontalfacingdata); register(176, simplebuilder() .trait(lanternintegertraits.rotation) .defaultstate(state -> state .withtrait(lanternintegertraits.rotation, 0).get()) .properties(builder -> builder .add(hardness(1.0)) .add(blastresistance(5.0))) .behaviors(pipeline -> pipeline .add(new signinteractionbehavior())) .tileentitytype(() -> tileentitytypes.banner) .build("minecraft", "standing_banner"), blockstate -> blockstate.gettraitvalue(lanternintegertraits.rotation).get().bytevalue()); register(177, simplebuilder() .trait(lanternenumtraits.horizontal_facing) .defaultstate(state -> state .withtrait(lanternenumtraits.horizontal_facing, direction.north).get()) .properties(builder -> builder .add(hardness(1.0)) .add(blastresistance(5.0))) .behaviors(pipeline -> pipeline .add(new signinteractionbehavior())) .tileentitytype(() -> tileentitytypes.banner) .build("minecraft", "wall_banner"), this::horizontalfacingdata); }
shisheng-1/Lantern
[ 1, 1, 0, 0 ]
24,672
public String getJavaName() { return service.getName(); //TODO Capitalize first char?? }
public String getJavaName() { return service.getName(); }
public string getjavaname() { return service.getname(); }
timfel/netbeans
[ 0, 1, 0, 0 ]
32,867
@Override public boolean defineLock(String name, ClusteredLockConfiguration configuration) { // TODO: Configuration is not used because we don't support any other mode for now. For that : ISPN-8413 CacheHolder cacheHolder = extractCacheHolder(cacheHolderFuture); cache = cacheHolder.getClusteredLockCache(); ClusteredLockKey key = new ClusteredLockKey(ByteString.fromString(name)); ClusteredLockValue clusteredLockValue = cache.putIfAbsent(key, ClusteredLockValue.INITIAL_STATE); locks.putIfAbsent(name, new ClusteredLockImpl(name, key, cache, this)); return clusteredLockValue == null; }
@Override public boolean defineLock(String name, ClusteredLockConfiguration configuration) { CacheHolder cacheHolder = extractCacheHolder(cacheHolderFuture); cache = cacheHolder.getClusteredLockCache(); ClusteredLockKey key = new ClusteredLockKey(ByteString.fromString(name)); ClusteredLockValue clusteredLockValue = cache.putIfAbsent(key, ClusteredLockValue.INITIAL_STATE); locks.putIfAbsent(name, new ClusteredLockImpl(name, key, cache, this)); return clusteredLockValue == null; }
@override public boolean definelock(string name, clusteredlockconfiguration configuration) { cacheholder cacheholder = extractcacheholder(cacheholderfuture); cache = cacheholder.getclusteredlockcache(); clusteredlockkey key = new clusteredlockkey(bytestring.fromstring(name)); clusteredlockvalue clusteredlockvalue = cache.putifabsent(key, clusteredlockvalue.initial_state); locks.putifabsent(name, new clusteredlockimpl(name, key, cache, this)); return clusteredlockvalue == null; }
tqrg-bot/infinispan
[ 1, 0, 0, 0 ]