hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
922e26e4d1fd18c31c731d36c74d25994731acf9
943
java
Java
etrace-consumer/src/main/java/io/etrace/consumer/exception/CallStackNotFoundException.java
PhenixStack/etrace
541210c748395e1682e5012da979bf5dfcdde86f
[ "Apache-2.0" ]
41
2019-12-05T03:01:17.000Z
2022-03-24T14:35:45.000Z
etrace-consumer/src/main/java/io/etrace/consumer/exception/CallStackNotFoundException.java
jacobke/etrace
bae5654e9a6412e444d4f519a86090af7d25d988
[ "Apache-2.0" ]
5
2020-01-12T12:21:55.000Z
2022-01-13T03:46:23.000Z
etrace-consumer/src/main/java/io/etrace/consumer/exception/CallStackNotFoundException.java
jacobke/etrace
bae5654e9a6412e444d4f519a86090af7d25d988
[ "Apache-2.0" ]
18
2019-11-27T07:22:31.000Z
2022-03-08T12:48:38.000Z
32.517241
75
0.760339
994,647
/* * Copyright 2019 etrace.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.etrace.consumer.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.NOT_FOUND) public class CallStackNotFoundException extends RuntimeException { public CallStackNotFoundException(String message) { super(message); } }
922e2714b0f8d4563992b65cc30b97ac83cf21df
5,750
java
Java
play2-provider-api/src/main/java/com/google/code/play2/provider/api/Play2RunnerConfiguration.java
play2-maven-plugin/play2-maven-plugin
ca6c59aef9444a814bdc51e105e41a6d124035b5
[ "Apache-2.0" ]
52
2015-12-18T07:52:21.000Z
2021-06-25T10:57:24.000Z
play2-provider-api/src/main/java/com/google/code/play2/provider/api/Play2RunnerConfiguration.java
kocher/play2-maven-plugin
e5649a939809392171f444f6bd0c6683be5b178d
[ "Apache-2.0" ]
125
2015-12-07T14:46:16.000Z
2022-01-19T22:40:22.000Z
play2-provider-api/src/main/java/com/google/code/play2/provider/api/Play2RunnerConfiguration.java
kocher/play2-maven-plugin
e5649a939809392171f444f6bd0c6683be5b178d
[ "Apache-2.0" ]
19
2016-02-22T14:19:50.000Z
2022-01-19T22:42:20.000Z
17.179104
75
0.509644
994,648
/* * Copyright 2013-2020 Grzegorz Slowikowski (gslowikowski at gmail dot com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.google.code.play2.provider.api; import java.io.File; import java.io.Serializable; import java.util.List; import java.util.Map; /** * Play! runner configuration. * * @author <a href="mailto:envkt@example.com">Grzegorz Slowikowski</a> */ public class Play2RunnerConfiguration implements Serializable { private static final long serialVersionUID = 1L; /** * ... */ private File baseDirectory; /** * ... */ private List<File> outputDirectories; /** * ... */ private List<File> dependencyClasspath; /** * ... */ private File docsFile; /** * ... */ private List<File> docsClasspath; /** * ... */ private Integer httpPort; /** * ... */ private Integer httpsPort; /** * ... */ private String httpAddress; /** * ... */ private String assetsPrefix; /** * ... */ private File assetsDirectory; /** * ... */ private Map<String, String> devSettings; /** * ... */ private transient Play2Builder buildLink; /** * Returns ... . * * @return ... */ public File getBaseDirectory() { return baseDirectory; } /** * Sets ... . * * @param baseDirectory ... */ public void setBaseDirectory( File baseDirectory ) { this.baseDirectory = baseDirectory; } /** * Returns ... . * * @return ... */ public List<File> getOutputDirectories() { return outputDirectories; } /** * Sets ... . * * @param outputDirectories ... */ public void setOutputDirectories( List<File> outputDirectories ) { this.outputDirectories = outputDirectories; } /** * Returns ... . * * @return ... */ public List<File> getDependencyClasspath() { return dependencyClasspath; } /** * Sets ... . * * @param dependencyClasspath ... */ public void setDependencyClasspath( List<File> dependencyClasspath ) { this.dependencyClasspath = dependencyClasspath; } /** * Returns ... . * * @return ... */ public File getDocsFile() { return docsFile; } /** * Sets ... . * * @param docsFile ... */ public void setDocsFile( File docsFile ) { this.docsFile = docsFile; } /** * Returns ... . * * @return ... */ public List<File> getDocsClasspath() { return docsClasspath; } /** * Sets ... . * * @param docsClasspath ... */ public void setDocsClasspath( List<File> docsClasspath ) { this.docsClasspath = docsClasspath; } /** * Returns ... . * * @return ... */ public Integer getHttpPort() { return httpPort; } /** * Sets ... . * * @param httpPort ... */ public void setHttpPort( Integer httpPort ) { this.httpPort = httpPort; } /** * Returns ... . * * @return ... */ public Integer getHttpsPort() { return httpsPort; } /** * Sets ... . * * @param httpsPort ... */ public void setHttpsPort( Integer httpsPort ) { this.httpsPort = httpsPort; } /** * Returns ... . * * @return ... */ public String getHttpAddress() { return httpAddress; } /** * Sets ... . * * @param httpAddress ... */ public void setHttpAddress( String httpAddress ) { this.httpAddress = httpAddress; } /** * Returns ... . * * @return ... */ public String getAssetsPrefix() { return assetsPrefix; } /** * Sets ... . * * @param assetsPrefix ... */ public void setAssetsPrefix( String assetsPrefix ) { this.assetsPrefix = assetsPrefix; } /** * Returns ... . * * @return ... */ public File getAssetsDirectory() { return assetsDirectory; } /** * Sets ... . * * @param assetsDirectory ... */ public void setAssetsDirectory( File assetsDirectory ) { this.assetsDirectory = assetsDirectory; } /** * Returns ... . * * @return ... */ public Map<String, String> getDevSettings() { return devSettings; } /** * Sets ... . * * @param devSettings ... */ public void setDevSettings( Map<String, String> devSettings ) { this.devSettings = devSettings; } /** * Returns ... . * * @return ... */ public Play2Builder getBuildLink() { return buildLink; } /** * Sets ... . * * @param buildLink ... */ public void setBuildLink( Play2Builder buildLink ) { this.buildLink = buildLink; } }
922e28da0600f265402a6b41abde8af5731d7b82
3,124
java
Java
Ghidra/Framework/Docking/src/test/java/docking/widgets/table/constrainteditor/IntegerValueConstraintEditorTest.java
bdcht/ghidra
9e732318148cd11edeb4862afd23d56418551812
[ "Apache-2.0" ]
17
2022-01-15T03:52:37.000Z
2022-03-30T18:12:17.000Z
Ghidra/Framework/Docking/src/test/java/docking/widgets/table/constrainteditor/IntegerValueConstraintEditorTest.java
BStudent/ghidra
0cdc722921cef61b7ca1b7236bdc21079fd4c03e
[ "Apache-2.0" ]
9
2022-01-15T03:58:02.000Z
2022-02-21T10:22:49.000Z
Ghidra/Framework/Docking/src/test/java/docking/widgets/table/constrainteditor/IntegerValueConstraintEditorTest.java
BStudent/ghidra
0cdc722921cef61b7ca1b7236bdc21079fd4c03e
[ "Apache-2.0" ]
3
2019-12-02T13:36:50.000Z
2019-12-04T05:40:12.000Z
29.196262
90
0.764725
994,649
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package docking.widgets.table.constrainteditor; import static org.junit.Assert.*; import java.awt.Component; import java.util.Collection; import org.junit.Before; import org.junit.Test; import docking.test.AbstractDockingTest; import docking.widgets.spinner.IntegerSpinner; import docking.widgets.table.constraint.ColumnConstraint; import docking.widgets.table.constraint.SingleValueColumnConstraint; import docking.widgets.table.constraint.provider.NumberColumnConstraintProvider; import docking.widgets.textfield.IntegerTextField; public class IntegerValueConstraintEditorTest extends AbstractDockingTest { private SingleValueColumnConstraint<Integer> constraint; private ColumnConstraintEditor<Integer> editor; private IntegerSpinner spinner; private IntegerTextField textField; @Before public void setup() { constraint = (SingleValueColumnConstraint<Integer>) findIntegerConstraint(); editor = constraint.getEditor(null); forceBuildOfGuiComponents(); spinner = (IntegerSpinner) getInstanceField("spinner", editor); textField = spinner.getTextField(); assertNotNull("Unable to locate JTextField editor component of spinner", textField); } private Component forceBuildOfGuiComponents() { return runSwing(() -> editor.getInlineComponent()); } @Test public void testSetValue() { setEditorValue("128"); assertEquals("128", textField.getText()); } @Test public void testGetValue() { setEditorValue("923"); assertEquals("923", getEditorValue().getConstraintValueString()); } @Test public void testReset() { setTextValue(23); editor.reset(); assertEquals("0", textField.getText()); } @Test public void testDetailComponent() { assertNull(editor.getDetailComponent()); } @SuppressWarnings("unchecked") private ColumnConstraint<Integer> findIntegerConstraint() { Collection<ColumnConstraint<?>> columnConstraints = new NumberColumnConstraintProvider().getColumnConstraints(); for (ColumnConstraint<?> columnConstraint : columnConstraints) { if (columnConstraint.getColumnType().equals(Integer.class)) { return (ColumnConstraint<Integer>) columnConstraint; } } return null; } private void setTextValue(int value) { runSwing(() -> textField.setValue(value)); waitForSwing(); } private void setEditorValue(String constraintValue) { runSwing(() -> editor.setValue(constraint.parseConstraintValue(constraintValue, null))); waitForSwing(); } private ColumnConstraint<Integer> getEditorValue() { return runSwing(() -> editor.getValue()); } }
922e29c0c4d1b059356a88add2ed5da98597b419
64
java
Java
app-itests/src/itest/java/com/rideaustin/applepay/ApplePay.java
coopersystem-fsd/server
24354717624c25b5d4faf0b7ea540e2742e8039f
[ "MIT" ]
13
2020-08-20T23:51:13.000Z
2021-08-23T17:47:14.000Z
app-itests/src/itest/java/com/rideaustin/applepay/ApplePay.java
coopersystem-fsd/server
24354717624c25b5d4faf0b7ea540e2742e8039f
[ "MIT" ]
3
2020-06-25T18:16:12.000Z
2021-11-25T21:36:19.000Z
app-itests/src/itest/java/com/rideaustin/applepay/ApplePay.java
coopersystem-fsd/server
24354717624c25b5d4faf0b7ea540e2742e8039f
[ "MIT" ]
12
2020-06-16T20:42:18.000Z
2022-03-10T21:45:39.000Z
12.8
32
0.796875
994,650
package com.rideaustin.applepay; public interface ApplePay { }
922e29cd6f2bad230ed8827e4b40bcb38d165a5f
4,822
java
Java
src/test/java/com/test/score/BasicScoreCalculatorTest.java
deshaion/decathlon-service
d45f5a286a683090e79b90a9b202e162a47a97e6
[ "Apache-2.0" ]
null
null
null
src/test/java/com/test/score/BasicScoreCalculatorTest.java
deshaion/decathlon-service
d45f5a286a683090e79b90a9b202e162a47a97e6
[ "Apache-2.0" ]
null
null
null
src/test/java/com/test/score/BasicScoreCalculatorTest.java
deshaion/decathlon-service
d45f5a286a683090e79b90a9b202e162a47a97e6
[ "Apache-2.0" ]
null
null
null
37.671875
124
0.659477
994,651
package com.test.score; import com.test.participant.Event; import com.test.participant.Participant; import com.test.participant.ScoredParticipant; import org.junit.Assert; import org.junit.Test; import java.util.Collections; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; public class BasicScoreCalculatorTest { private BasicScoreCalculator scoreCalculator = new BasicScoreCalculator(); @Test public void testSprint100m() { Participant participant = Participant.ParticipantBuilder.builder() .name("Test") .event(Event.Sprint100m, "10") .build(); List<ScoredParticipant> scoredParticipants = scoreCalculator.calculateScore(Collections.singletonList(participant)); Assert.assertThat(scoredParticipants.get(0).getTotalScore(), is(1096)); } @Test public void testLongJump() { Participant participant = Participant.ParticipantBuilder.builder() .name("Test") .event(Event.LongJump, "5.00") .build(); List<ScoredParticipant> scoredParticipants = scoreCalculator.calculateScore(Collections.singletonList(participant)); Assert.assertThat(scoredParticipants.get(0).getTotalScore(), is(382)); } @Test public void testShotPut() { Participant participant = Participant.ParticipantBuilder.builder() .name("Test") .event(Event.ShotPut, "9.22") .build(); List<ScoredParticipant> scoredParticipants = scoreCalculator.calculateScore(Collections.singletonList(participant)); Assert.assertThat(scoredParticipants.get(0).getTotalScore(), is(439)); } @Test public void testHighJump() { Participant participant = Participant.ParticipantBuilder.builder() .name("Test") .event(Event.HighJump, "2") .build(); List<ScoredParticipant> scoredParticipants = scoreCalculator.calculateScore(Collections.singletonList(participant)); Assert.assertThat(scoredParticipants.get(0).getTotalScore(), is(803)); } @Test public void testSprint400m() { Participant participant = Participant.ParticipantBuilder.builder() .name("Test") .event(Event.Sprint400m, "60.32") .build(); List<ScoredParticipant> scoredParticipants = scoreCalculator.calculateScore(Collections.singletonList(participant)); Assert.assertThat(scoredParticipants.get(0).getTotalScore(), is(402)); } @Test public void testSprint110mHurdles() { Participant participant = Participant.ParticipantBuilder.builder() .name("Test") .event(Event.Sprint110mHurdles, "16.43") .build(); List<ScoredParticipant> scoredParticipants = scoreCalculator.calculateScore(Collections.singletonList(participant)); Assert.assertThat(scoredParticipants.get(0).getTotalScore(), is(685)); } @Test public void testDiscusThrow() { Participant participant = Participant.ParticipantBuilder.builder() .name("Test") .event(Event.DiscusThrow, "21.6") .build(); List<ScoredParticipant> scoredParticipants = scoreCalculator.calculateScore(Collections.singletonList(participant)); Assert.assertThat(scoredParticipants.get(0).getTotalScore(), is(302)); } @Test public void testPoleVault() { Participant participant = Participant.ParticipantBuilder.builder() .name("Test") .event(Event.PoleVault, "2.6") .build(); List<ScoredParticipant> scoredParticipants = scoreCalculator.calculateScore(Collections.singletonList(participant)); Assert.assertThat(scoredParticipants.get(0).getTotalScore(), is(264)); } @Test public void testJavelinThrow() { Participant participant = Participant.ParticipantBuilder.builder() .name("Test") .event(Event.JavelinThrow, "35.81") .build(); List<ScoredParticipant> scoredParticipants = scoreCalculator.calculateScore(Collections.singletonList(participant)); Assert.assertThat(scoredParticipants.get(0).getTotalScore(), is(382)); } @Test public void testRun1500m() { Participant participant = Participant.ParticipantBuilder.builder() .name("Test") .event(Event.Run1500m, "5.25.72") .build(); List<ScoredParticipant> scoredParticipants = scoreCalculator.calculateScore(Collections.singletonList(participant)); Assert.assertThat(scoredParticipants.get(0).getTotalScore(), is(421)); } }
922e2b083b4d9d096ea32cfd486408e2a0d15847
1,948
java
Java
javasrc/com/phronemophobic/cljcef/CefTaskRunner.java
phronmophobic/clj-cef
ac8281a1b54e88f716e46fc2021f05ce34c7512f
[ "Apache-2.0" ]
36
2021-02-19T21:52:33.000Z
2022-03-14T12:44:53.000Z
javasrc/com/phronemophobic/cljcef/CefTaskRunner.java
phronmophobic/clj-cef
ac8281a1b54e88f716e46fc2021f05ce34c7512f
[ "Apache-2.0" ]
2
2021-02-11T05:44:06.000Z
2021-04-25T18:37:11.000Z
javasrc/com/phronemophobic/cljcef/CefTaskRunner.java
phronmophobic/clj-cef
ac8281a1b54e88f716e46fc2021f05ce34c7512f
[ "Apache-2.0" ]
1
2021-02-20T14:02:55.000Z
2021-02-20T14:02:55.000Z
20.723404
168
0.774641
994,652
// AUTO GENERATED BY gen2.clj! package com.phronemophobic.cljcef; import com.phronemophobic.cljcef.*; import com.sun.jna.Structure; import com.sun.jna.Callback; import com.sun.jna.Pointer; import java.util.List; import java.util.Arrays; public class CefTaskRunner extends Structure{ public CefTaskRunner(){ base.size.setValue(this.size()); ReferenceCountImpl.track(this.getPointer()); } public static interface IsSameFunc extends Callback { int is_same(CefTaskRunner x0, CefTaskRunner x1); } public static interface BelongsToCurrentThreadFunc extends Callback { int belongs_to_current_thread(CefTaskRunner x0); } public static interface BelongsToThreadFunc extends Callback { int belongs_to_thread(CefTaskRunner x0, int x1); } public static interface PostTaskFunc extends Callback { int post_task(CefTaskRunner x0, CefTask x1); } public static interface PostDelayedTaskFunc extends Callback { int post_delayed_task(CefTaskRunner x0, CefTask x1, long x2); } public CefBaseRefCounted base; public IsSameFunc is_same; public BelongsToCurrentThreadFunc belongs_to_current_thread; public BelongsToThreadFunc belongs_to_thread; public PostTaskFunc post_task; public PostDelayedTaskFunc post_delayed_task; protected List getFieldOrder() { return Arrays.asList("base", "is_same", "belongs_to_current_thread", "belongs_to_thread", "post_task", "post_delayed_task"); } public int isSame (CefTaskRunner x1) { return this.is_same.is_same(this, x1); } public int belongsToCurrentThread () { return this.belongs_to_current_thread.belongs_to_current_thread(this); } public int belongsToThread (int x1) { return this.belongs_to_thread.belongs_to_thread(this, x1); } public int postTask (CefTask x1) { return this.post_task.post_task(this, x1); } public int postDelayedTask (CefTask x1, long x2) { return this.post_delayed_task.post_delayed_task(this, x1, x2); }}
922e2b6661b8b5c298efc3683d8f6159c96d5991
982
java
Java
src/main/java/com/rb/springissues/sample/SampleMain.java
bironran/spring_issues_proxy_factory
016beaed3a196818814efb914bdddf77e9c8d3b6
[ "MIT" ]
1
2017-07-09T01:33:23.000Z
2017-07-09T01:33:23.000Z
src/main/java/com/rb/springissues/sample/SampleMain.java
bironran/spring_issues_proxy_factory
016beaed3a196818814efb914bdddf77e9c8d3b6
[ "MIT" ]
null
null
null
src/main/java/com/rb/springissues/sample/SampleMain.java
bironran/spring_issues_proxy_factory
016beaed3a196818814efb914bdddf77e9c8d3b6
[ "MIT" ]
null
null
null
35.071429
74
0.682281
994,653
package com.rb.springissues.sample; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.rb.springissues.LoggerBase; public class SampleMain { private static ClassPathXmlApplicationContext context; public static void main(String[] args) { context = new ClassPathXmlApplicationContext(); context.setAllowBeanDefinitionOverriding(false); context.setAllowCircularReferences(false); context.setConfigLocation("sample/applicationContext.xml"); context.refresh(); LoggerBase.logPlain("=== Init done"); String[] beanDefinitionNames = context.getBeanDefinitionNames(); for (String beanDefinitionName : beanDefinitionNames) { Object bean = context.getBean(beanDefinitionName); if(bean instanceof LoggerBase) { ((LoggerBase) bean).nop(); } } LoggerBase.logPlain("=== NOP done"); LoggerBase.print(); } }
922e2b7fbfd28d3b49efd40968cbd14274e0175b
3,184
java
Java
MultiMC/src/forkk/multimc/task/Task.java
Jorch72/JMultiMC
107db1cae3d0189df3e6916e33bc6af8599d030a
[ "Apache-2.0" ]
1
2019-01-14T08:08:17.000Z
2019-01-14T08:08:17.000Z
MultiMC/src/forkk/multimc/task/Task.java
Jorch72/JMultiMC
107db1cae3d0189df3e6916e33bc6af8599d030a
[ "Apache-2.0" ]
null
null
null
MultiMC/src/forkk/multimc/task/Task.java
Jorch72/JMultiMC
107db1cae3d0189df3e6916e33bc6af8599d030a
[ "Apache-2.0" ]
null
null
null
28.176991
81
0.701319
994,654
/** * Copyright 2012 Andrew Okin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package forkk.multimc.task; import java.util.ArrayList; public abstract class Task extends Thread { public void run() { OnProgressChange(0); OnStatusChange(""); TaskStart(); } /** * The task's entry-point */ public abstract void TaskStart(); /** * @return false if the progress bar should show progress. Default is true */ public boolean isProgressIndeterminate() { return true; } // Events public static interface TaskListener { public abstract void taskStart(Task t); public abstract void taskEnd(Task t); public abstract void taskProgressChange(Task t, int p); public abstract void taskStatusChange(Task t, String status); public abstract void taskErrorMessage(Task t, String status); } private ArrayList<TaskListener> taskListeners = new ArrayList<Task.TaskListener>(); public void AddTaskListener(TaskListener l) { taskListeners.add(l); } public void RemoveTaskListener(TaskListener l) { taskListeners.add(l); } protected void OnTaskStart() { running = true; for (TaskListener l : taskListeners) { l.taskStart(this); } } protected void OnTaskEnd() { running = false; for (TaskListener l : taskListeners.toArray(new TaskListener[0])) { l.taskEnd(this); } } public void AddProgressListener(TaskListener l) { taskListeners.add(l); } public void RemoveProgressListener(TaskListener l) { taskListeners.remove(l); } protected void OnProgressChange(int p) { for (TaskListener l : taskListeners) { l.taskProgressChange(this, p); } } public void AddStatusListener(TaskListener l) { taskListeners.add(l); } public void RemoveStatusListener(TaskListener l) { taskListeners.remove(l); } protected void OnStatusChange(String newStatus) { for (TaskListener l : taskListeners) { l.taskStatusChange(this, newStatus); } } public void AddErrorListener(TaskListener l) { taskListeners.add(l); } public void RemoveErrorListener(TaskListener l) { taskListeners.remove(l); } protected void OnErrorMessage(String errorMessage) { for (TaskListener l : taskListeners) { l.taskErrorMessage(this, errorMessage); } } // Properties String status; public String getStatus() { return status; } public void setStatus(String s) { status = s; OnStatusChange(s); } int progress; public int getProgress() { return progress; } public void setProgress(int p) { progress = p; OnProgressChange(p); } boolean running; public boolean isRunning() { return running; } }
922e2d779523a0e5d77baad5d0ffaa9cd916a9a1
12,451
java
Java
serenity-core/src/main/java/net/thucydides/core/webdriver/WebDriverFacade.java
schmurgon/serenity-core
7c4e0df97b5bb04652c1d7898b7859b3388ebfd6
[ "Apache-2.0" ]
null
null
null
serenity-core/src/main/java/net/thucydides/core/webdriver/WebDriverFacade.java
schmurgon/serenity-core
7c4e0df97b5bb04652c1d7898b7859b3388ebfd6
[ "Apache-2.0" ]
null
null
null
serenity-core/src/main/java/net/thucydides/core/webdriver/WebDriverFacade.java
schmurgon/serenity-core
7c4e0df97b5bb04652c1d7898b7859b3388ebfd6
[ "Apache-2.0" ]
null
null
null
32.594241
144
0.639145
994,655
package net.thucydides.core.webdriver; import com.gargoylesoftware.htmlunit.ScriptException; import net.serenitybdd.core.pages.DefaultTimeouts; import net.thucydides.core.ThucydidesSystemProperty; import net.thucydides.core.guice.Injectors; import net.thucydides.core.steps.StepEventBus; import net.thucydides.core.util.EnvironmentVariables; import net.thucydides.core.webdriver.stubs.*; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.*; import org.openqa.selenium.interactions.HasInputDevices; import org.openqa.selenium.interactions.Keyboard; import org.openqa.selenium.interactions.Mouse; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.ui.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import static java.util.concurrent.TimeUnit.MILLISECONDS; /** * A proxy class for webdriver instances, designed to prevent the browser being opened unnecessarily. */ public class WebDriverFacade implements WebDriver, TakesScreenshot, HasInputDevices, JavascriptExecutor, HasCapabilities, ConfigurableTimeouts { private final Class<? extends WebDriver> driverClass; private final WebDriverFactory webDriverFactory; protected WebDriver proxiedWebDriver; private static final Logger LOGGER = LoggerFactory.getLogger(WebDriverFacade.class); private EnvironmentVariables environmentVariables; /** * Implicit timeout values recorded to that they can be restored after calling findElements() */ protected Duration implicitTimeout; public WebDriverFacade(final Class<? extends WebDriver> driverClass, final WebDriverFactory webDriverFactory) { this(driverClass, webDriverFactory, Injectors.getInjector().getInstance(EnvironmentVariables.class)); } public WebDriverFacade(final Class<? extends WebDriver> driverClass, final WebDriverFactory webDriverFactory, final EnvironmentVariables environmentVariables ) { this.driverClass = driverClass; this.webDriverFactory = webDriverFactory; this.environmentVariables = environmentVariables; this.implicitTimeout = defaultImplicitWait(); } public WebDriverFacade(final WebDriver driver, final WebDriverFactory webDriverFactory, final EnvironmentVariables environmentVariables ) { this.driverClass = driver.getClass(); this.proxiedWebDriver = driver; this.webDriverFactory = webDriverFactory; this.environmentVariables = environmentVariables; this.implicitTimeout = defaultImplicitWait(); } private Duration defaultImplicitWait() { int configuredWaitForTimeoutInMilliseconds = ThucydidesSystemProperty.WEBDRIVER_TIMEOUTS_IMPLICITLYWAIT .integerFrom(environmentVariables, (int) DefaultTimeouts.DEFAULT_IMPLICIT_WAIT_TIMEOUT.in(MILLISECONDS)); return new Duration(configuredWaitForTimeoutInMilliseconds, TimeUnit.MILLISECONDS); } public WebDriverFacade(final Class<? extends WebDriver> driverClass, final WebDriverFactory webDriverFactory, WebDriver proxiedWebDriver, Duration implicitTimeout) { this.driverClass = driverClass; this.webDriverFactory = webDriverFactory; this.proxiedWebDriver = proxiedWebDriver; this.implicitTimeout = implicitTimeout; } public WebDriverFacade withTimeoutOf(Duration implicitTimeout) { return new WebDriverFacade(driverClass, webDriverFactory, proxiedWebDriver, implicitTimeout); } public Class<? extends WebDriver> getDriverClass() { if (driverClass.isAssignableFrom(SupportedWebDriver.PROVIDED.getWebdriverClass())) { return getProxiedDriver().getClass(); } return driverClass; } public WebDriver getProxiedDriver() { if (proxiedWebDriver == null) { proxiedWebDriver = newProxyDriver(); WebdriverProxyFactory.getFactory().notifyListenersOfWebdriverCreationIn(this); } return proxiedWebDriver; } public boolean isEnabled() { return !StepEventBus.getEventBus().webdriverCallsAreSuspended(); } public void reset() { if (proxiedWebDriver != null) { forcedQuit(); } proxiedWebDriver = null; } private void forcedQuit() { try { getDriverInstance().quit(); proxiedWebDriver = null; } catch (WebDriverException e) { LOGGER.warn("Closing a driver that was already closed: " + e.getMessage()); } } protected WebDriver newProxyDriver() { return newDriverInstance(); } private WebDriver newDriverInstance() { try { if (StepEventBus.getEventBus().isDryRun()) { return new WebDriverStub(); } else { webDriverFactory.setupFixtureServices(); return webDriverFactory.newWebdriverInstance(driverClass); } } catch (UnsupportedDriverException e) { LOGGER.error("FAILED TO CREATE NEW WEBDRIVER_DRIVER INSTANCE " + driverClass + ": " + e.getMessage(), e); throw new UnsupportedDriverException("Could not instantiate " + driverClass, e); } } public <X> X getScreenshotAs(final OutputType<X> target) { if (proxyInstanciated() && driverCanTakeScreenshots()) { try { return ((TakesScreenshot) getProxiedDriver()).getScreenshotAs(target); } catch (WebDriverException e) { LOGGER.warn("Failed to take screenshot - driver closed already? (" + e.getMessage() + ")"); } catch (OutOfMemoryError outOfMemoryError) { // Out of memory errors can happen with extremely big screens, and currently Selenium does // not handle them correctly/at all. LOGGER.error("Failed to take screenshot - out of memory", outOfMemoryError); } } return null; } private boolean driverCanTakeScreenshots() { return (TakesScreenshot.class.isAssignableFrom(getProxiedDriver().getClass())); } public void get(final String url) { if (!isEnabled()) { return; } openIgnoringHtmlUnitScriptErrors(url); } private void openIgnoringHtmlUnitScriptErrors(final String url) { try { getProxiedDriver().get(url); setTimeouts(); } catch (WebDriverException e) { if (!htmlunitScriptError(e)) { throw e; } } } private void setTimeouts() { webDriverFactory.setTimeouts(getProxiedDriver(), implicitTimeout); } private boolean htmlunitScriptError(WebDriverException e) { if ((e.getCause() != null) && (e.getCause() instanceof ScriptException)) { LOGGER.warn("Ignoring HTMLUnit script error: " + e.getMessage()); return true; } else { return false; } } public String getCurrentUrl() { if (!isEnabled()) { return StringUtils.EMPTY; } return getProxiedDriver().getCurrentUrl(); } public String getTitle() { if (!isEnabled()) { return StringUtils.EMPTY; } return getProxiedDriver().getTitle(); } public List<WebElement> findElements(final By by) { if (!isEnabled()) { return Collections.emptyList(); } List<WebElement> elements; try { webDriverFactory.setTimeouts(getProxiedDriver(), getCurrentImplicitTimeout()); elements = getProxiedDriver().findElements(by); } catch (Throwable e) { throw e; } finally { webDriverFactory.resetTimeouts(getProxiedDriver()); } return elements; } public WebElement findElement(final By by) { if (!isEnabled()) { return new WebElementFacadeStub(); } WebElement element; try { webDriverFactory.setTimeouts(getProxiedDriver(), getCurrentImplicitTimeout()); element = getProxiedDriver().findElement(by); } catch(Throwable e) { throw e; } finally { webDriverFactory.resetTimeouts(getProxiedDriver()); } return element; } public String getPageSource() { if (!isEnabled()) { return StringUtils.EMPTY; } return getProxiedDriver().getPageSource(); } public void setImplicitTimeout(Duration implicitTimeout) { webDriverFactory.setTimeouts(getProxiedDriver(), implicitTimeout); } public Duration getCurrentImplicitTimeout() { return webDriverFactory.currentTimeoutFor(getProxiedDriver()); } public void resetTimeouts() { webDriverFactory.resetTimeouts(getProxiedDriver()); } protected WebDriver getDriverInstance() { return proxiedWebDriver; } public void close() { if (proxyInstanciated()) { //if there is only one window closing it means quitting the web driver if (getDriverInstance().getWindowHandles() != null && getDriverInstance().getWindowHandles().size() == 1){ this.quit(); } else{ getDriverInstance().close(); } webDriverFactory.shutdownFixtureServices(); } } public void quit() { if (proxyInstanciated()) { try { getDriverInstance().quit(); } catch (WebDriverException e) { LOGGER.warn("Error while quitting the driver (" + e.getMessage() + ")"); } proxiedWebDriver = null; } } protected boolean proxyInstanciated() { return (getDriverInstance() != null); } public Set<String> getWindowHandles() { if (!isEnabled()) { return new HashSet<String>(); } return getProxiedDriver().getWindowHandles(); } public String getWindowHandle() { if (!isEnabled()) { return StringUtils.EMPTY; } return getProxiedDriver().getWindowHandle(); } public TargetLocator switchTo() { if (!isEnabled()) { return new TargetLocatorStub(this); } return getProxiedDriver().switchTo(); } public Navigation navigate() { if (!isEnabled()) { return new NavigationStub(); } return getProxiedDriver().navigate(); } public Options manage() { if (!isEnabled()) { return new OptionsStub(); } return new OptionsFacade(getProxiedDriver().manage(), this); } public boolean canTakeScreenshots() { if (driverClass != null) { if (driverClass == ProvidedDriver.class) { return TakesScreenshot.class.isAssignableFrom(getProxiedDriver().getClass()) || (getProxiedDriver().getClass() == RemoteWebDriver.class); } else { return TakesScreenshot.class.isAssignableFrom(driverClass) || (driverClass == RemoteWebDriver.class); } } else { return false; } } public boolean isInstantiated() { return (driverClass != null) && (proxiedWebDriver != null); } public Keyboard getKeyboard() { return ((HasInputDevices) getProxiedDriver()).getKeyboard(); } public Mouse getMouse() { return ((HasInputDevices) getProxiedDriver()).getMouse(); } public Object executeScript(String script, Object... parameters) { return ((JavascriptExecutor) getProxiedDriver()).executeScript(script, parameters); } public Object executeAsyncScript(String script, Object... parameters) { return ((JavascriptExecutor) getProxiedDriver()).executeAsyncScript(script, parameters); } @Override public Capabilities getCapabilities() { return ((HasCapabilities) getProxiedDriver()).getCapabilities(); } public String getDriverName() { return SupportedWebDriver.forClass(this.driverClass).name().toLowerCase(); } }
922e2dcb0dfb926ecea9eaaa1f5fb8f21a55e135
3,055
java
Java
src/main/java/com/alipay/api/request/AlipayFundTransAppPayRequest.java
10088/alipay-sdk-java-all
64dfba5e687e39aa7a735a711bd6f1392f63c69d
[ "Apache-2.0" ]
null
null
null
src/main/java/com/alipay/api/request/AlipayFundTransAppPayRequest.java
10088/alipay-sdk-java-all
64dfba5e687e39aa7a735a711bd6f1392f63c69d
[ "Apache-2.0" ]
1
2018-05-23T08:08:56.000Z
2018-08-26T07:16:29.000Z
src/main/java/com/alipay/api/request/AlipayFundTransAppPayRequest.java
antopen/alipay-sdk-java-all
790dea41169e764e3f2e08330800246b4aba1b29
[ "Apache-2.0" ]
null
null
null
22.137681
100
0.694599
994,656
package com.alipay.api.request; import com.alipay.api.domain.AlipayFundTransAppPayModel; import java.util.Map; import com.alipay.api.AlipayRequest; import com.alipay.api.internal.util.AlipayHashMap; import com.alipay.api.response.AlipayFundTransAppPayResponse; import com.alipay.api.AlipayObject; /** * ALIPAY API: alipay.fund.trans.app.pay request * * @author auto create * @since 1.0, 2022-01-17 18:00:21 */ public class AlipayFundTransAppPayRequest implements AlipayRequest<AlipayFundTransAppPayResponse> { private AlipayHashMap udfParams; // add user-defined text parameters private String apiVersion="1.0"; /** * 无线转账支付接口 */ private String bizContent; public void setBizContent(String bizContent) { this.bizContent = bizContent; } public String getBizContent() { return this.bizContent; } private String terminalType; private String terminalInfo; private String prodCode; private String notifyUrl; private String returnUrl; private boolean needEncrypt=false; private AlipayObject bizModel=null; public String getNotifyUrl() { return this.notifyUrl; } public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public String getReturnUrl() { return this.returnUrl; } public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } public String getApiVersion() { return this.apiVersion; } public void setApiVersion(String apiVersion) { this.apiVersion = apiVersion; } public void setTerminalType(String terminalType){ this.terminalType=terminalType; } public String getTerminalType(){ return this.terminalType; } public void setTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public String getTerminalInfo(){ return this.terminalInfo; } public void setProdCode(String prodCode) { this.prodCode=prodCode; } public String getProdCode() { return this.prodCode; } public String getApiMethodName() { return "alipay.fund.trans.app.pay"; } public Map<String, String> getTextParams() { AlipayHashMap txtParams = new AlipayHashMap(); txtParams.put("biz_content", this.bizContent); if(udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } public void putOtherTextParam(String key, String value) { if(this.udfParams == null) { this.udfParams = new AlipayHashMap(); } this.udfParams.put(key, value); } public Class<AlipayFundTransAppPayResponse> getResponseClass() { return AlipayFundTransAppPayResponse.class; } public boolean isNeedEncrypt() { return this.needEncrypt; } public void setNeedEncrypt(boolean needEncrypt) { this.needEncrypt=needEncrypt; } public AlipayObject getBizModel() { return this.bizModel; } public void setBizModel(AlipayObject bizModel) { this.bizModel=bizModel; } }
922e2e2212765eb2a2edb0d4b04f540096fe8005
2,255
java
Java
doc/CyberSecurity/Modern_Cryptography/Steganography/Java_Program/StegApp.java
tanducmai/.dotfiles
13cad9bc7fcecff6108eb5df34635d4748712532
[ "Unlicense" ]
null
null
null
doc/CyberSecurity/Modern_Cryptography/Steganography/Java_Program/StegApp.java
tanducmai/.dotfiles
13cad9bc7fcecff6108eb5df34635d4748712532
[ "Unlicense" ]
null
null
null
doc/CyberSecurity/Modern_Cryptography/Steganography/Java_Program/StegApp.java
tanducmai/.dotfiles
13cad9bc7fcecff6108eb5df34635d4748712532
[ "Unlicense" ]
null
null
null
23.489583
56
0.639468
994,657
import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.util.*; import java.awt.event.*; public class StegApp implements ActionListener { private JFrame jf; private Container cp; private JButton openBtn, saveBtn; private JButton encodeBtn, decodeBtn; private JTextArea textField; private PictureEdit pic; public void setupGUI() { jf = new JFrame("Steg App"); cp = jf.getContentPane(); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setSize(600, 400); jf.setLayout(new GridLayout(2, 1)); Container buttonsCtr = new Container(); buttonsCtr.setLayout(new GridLayout(2,2, 5, 5)); JPanel msgCtr = new JPanel(); msgCtr.setLayout(new GridLayout(1,1)); TitledBorder title; title = BorderFactory.createTitledBorder("Message"); msgCtr.setBorder(title); textField = new JTextArea(); msgCtr.add(textField); openBtn = new JButton("Open Image"); saveBtn = new JButton("Save Image"); encodeBtn = new JButton("Encode Message"); decodeBtn = new JButton("Decode Message"); openBtn.addActionListener(this); saveBtn.addActionListener(this); encodeBtn.addActionListener(this); decodeBtn.addActionListener(this); buttonsCtr.add(openBtn); buttonsCtr.add(saveBtn); buttonsCtr.add(encodeBtn); buttonsCtr.add(decodeBtn); cp.add(buttonsCtr); cp.add(msgCtr); jf.setLocation(100, 100); jf.setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Open Image")) { pic = new PictureEdit(); pic.displayImage(); } if (pic == null) { return; } if(e.getActionCommand().equals("Save Image")) { pic.saveAs(); } if(e.getActionCommand().equals("Encode Message")) { String msg = textField.getText(); pic = Steganography.encode(pic, msg); textField.setText(msg); } if(e.getActionCommand().equals("Decode Message")) { String msg = Steganography.decode(pic); textField.setText(msg); } } public static void main(String[] args) { StegApp myApp = new StegApp(); myApp.setupGUI(); } }
922e2ef783a940531aa21c6aa889d5ccdcb09eaa
962
java
Java
mockserver/src/test/java/com/github/mock/MockClient.java
lys091112/util-compose-practice
2ceec1c1e4a930c8dc65e282fdc564f16753be55
[ "Apache-2.0" ]
null
null
null
mockserver/src/test/java/com/github/mock/MockClient.java
lys091112/util-compose-practice
2ceec1c1e4a930c8dc65e282fdc564f16753be55
[ "Apache-2.0" ]
1
2017-07-17T05:47:53.000Z
2017-07-31T05:30:53.000Z
mockserver/src/test/java/com/github/mock/MockClient.java
lys091112/util-compose-practice
2ceec1c1e4a930c8dc65e282fdc564f16753be55
[ "Apache-2.0" ]
null
null
null
31.032258
96
0.615385
994,658
package com.github.mock; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; import java.util.concurrent.TimeUnit; class MockClient { public static void main(String[] args) throws IOException, InterruptedException { OkHttpClient client = new OkHttpClient.Builder().readTimeout(100, TimeUnit.SECONDS). connectTimeout(5, TimeUnit.SECONDS).writeTimeout(100, TimeUnit.SECONDS).build(); String url = "http://localhost:18002/crescent/login.do"; int count = 0; for (int i = 0; i < 1000000; i++) { Request request = new Request.Builder().url(url).get().build(); try (Response response = client.newCall(request).execute()) { if (response.isSuccessful()) { count++; } } } System.out.println("success Count: " + count); Thread.sleep(10000); } }
922e2f317f69885b8d5f98497131a637b24e8f00
1,026
java
Java
dtm-query-execution-core/src/main/java/ru/datamart/prostore/query/execution/core/eddl/dto/DropUploadExternalTableQuery.java
datamarts/prostore
9bdcd0d63f4dbd2c88b3cd3091a80df506227a5c
[ "Apache-2.0" ]
31
2022-01-21T09:44:01.000Z
2022-02-16T10:59:15.000Z
dtm-query-execution-core/src/main/java/ru/datamart/prostore/query/execution/core/eddl/dto/DropUploadExternalTableQuery.java
datamarts/prostore
9bdcd0d63f4dbd2c88b3cd3091a80df506227a5c
[ "Apache-2.0" ]
null
null
null
dtm-query-execution-core/src/main/java/ru/datamart/prostore/query/execution/core/eddl/dto/DropUploadExternalTableQuery.java
datamarts/prostore
9bdcd0d63f4dbd2c88b3cd3091a80df506227a5c
[ "Apache-2.0" ]
null
null
null
32.0625
78
0.758285
994,659
/* * Copyright © 2022 DATAMART LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.datamart.prostore.query.execution.core.eddl.dto; import lombok.Data; import lombok.EqualsAndHashCode; /** * Запрос удаления внешней загрузки */ @EqualsAndHashCode(callSuper = true) @Data public class DropUploadExternalTableQuery extends EddlQuery { public DropUploadExternalTableQuery(String schemaName, String tableName) { super(EddlAction.DROP_UPLOAD_EXTERNAL_TABLE, schemaName, tableName); } }
922e3077da9271b24ae505472c0e918423ba6606
1,655
java
Java
application/Application.java
steveharwell1/LoginSystem
be4b7c3104f231bdbd64bb3ee85265860a4c40c6
[ "MIT" ]
null
null
null
application/Application.java
steveharwell1/LoginSystem
be4b7c3104f231bdbd64bb3ee85265860a4c40c6
[ "MIT" ]
null
null
null
application/Application.java
steveharwell1/LoginSystem
be4b7c3104f231bdbd64bb3ee85265860a4c40c6
[ "MIT" ]
null
null
null
20.6375
65
0.712296
994,660
/** * */ package application; import java.util.HashMap; import java.util.Map; import models.User; import models.UserFactory; import views.CustomerMainView; import views.EmployeeMainView; import views.LoginView; import views.View; /** * @author steve * */ public class Application implements RedirectListener { private Map<String, View> views = new HashMap<String, View>(); private View currentView; /** * */ public Application() { // TODO Auto-generated constructor stub } /** * @param args */ public static void main(String[] args) { Application app = new Application(); UserFactory userFactory = new UserFactory(); userFactory.createUser("Steve", "upchh@example.com", "customer"); userFactory.createUser("admin", "envkt@example.com", "manager"); LoginView loginView = new LoginView(app); User.addListener(loginView); app.addView("loginView", loginView); app.currentView = loginView; EmployeeMainView employeeMainView = new EmployeeMainView(app); User.addListener(employeeMainView); app.addView("employeeMainView", employeeMainView); CustomerMainView customerMainView = new CustomerMainView(app); User.addListener(customerMainView); app.addView("customerMainView", customerMainView); while (true) { app.currentView.displayView(); System.out.println(); } } @Override public void redirect(String target) { currentView = views.getOrDefault(target, currentView); } /** * @return the views */ public Map<String, View> getViews() { return views; } /** * @param views the views to set */ public void addView(String name, View view) { views.put(name, view); } }
922e3139e4b6dec1cba045bb02498c9f5e6958bd
556
java
Java
spring-boot/spring-boot-rest/Spring-boot-Rest/src/main/java/org/harman/SpringBootRestApplication.java
3surajpatil/java
dcae9356c2eb87eb4dd531bf6fb40521eb454394
[ "Unlicense" ]
null
null
null
spring-boot/spring-boot-rest/Spring-boot-Rest/src/main/java/org/harman/SpringBootRestApplication.java
3surajpatil/java
dcae9356c2eb87eb4dd531bf6fb40521eb454394
[ "Unlicense" ]
null
null
null
spring-boot/spring-boot-rest/Spring-boot-Rest/src/main/java/org/harman/SpringBootRestApplication.java
3surajpatil/java
dcae9356c2eb87eb4dd531bf6fb40521eb454394
[ "Unlicense" ]
null
null
null
25.478261
76
0.825939
994,661
package org.harman; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication(scanBasePackages= {"org.harman"}) //@EnableAutoConfiguration efpyi@example.com") public class SpringBootRestApplication { public static void main(String[] args) { SpringApplication.run(SpringBootRestApplication.class, args); } }
922e316a2e0a8ac32ea8cf8abf482b73ccbcc8c5
1,420
java
Java
core/src/test/java/com/severell/core/middleware/SecureHeadersMiddlewareTest.java
severell/severell
9bc9b5d746997a757d8551369f6dc2b5806d3e01
[ "MIT" ]
33
2020-10-13T23:52:57.000Z
2022-02-26T14:40:59.000Z
core/src/test/java/com/severell/core/middleware/SecureHeadersMiddlewareTest.java
mitchdennett/severell-core
9bc9b5d746997a757d8551369f6dc2b5806d3e01
[ "MIT" ]
12
2020-09-28T22:31:29.000Z
2021-02-26T20:27:58.000Z
core/src/test/java/com/severell/core/middleware/SecureHeadersMiddlewareTest.java
mitchdennett/severell-core
9bc9b5d746997a757d8551369f6dc2b5806d3e01
[ "MIT" ]
5
2020-09-28T23:32:31.000Z
2021-02-12T04:04:31.000Z
35.5
93
0.697887
994,662
package com.severell.core.middleware; import com.severell.core.http.*; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import java.util.HashMap; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class SecureHeadersMiddlewareTest { @Test public void headersShouldBeSet() throws Exception { Response resp = mock(Response.class); Request req = mock(Request.class); MiddlewareChain chain = mock(MiddlewareChain.class); ArgumentCaptor<HashMap<String, String>> key = ArgumentCaptor.forClass(HashMap.class); SecureHeadersMiddleware middleware = new SecureHeadersMiddleware(); middleware.handle(req, resp, chain); verify(resp).headers(key.capture()); HashMap<String, String> headers = new HashMap<>(); headers.put("Strict-Transport-Security", "max-age=63072000; includeSubdomains"); headers.put("X-Frame-Options", "SAMEORIGIN"); headers.put("X-XSS-Protection", "1; mode=block"); headers.put("X-Content-Type-Options", "nosniff"); headers.put("Referrer-Policy", "no-referrer, strict-origin-when-cross-origin"); headers.put("Cache-control", "no-cache, no-store, must-revalidate"); headers.put("Pragma", "no-cache"); assertEquals(headers, key.getValue()); } }
922e3206e3d59c992b48d7b3d7794cb230c136bc
14,077
java
Java
Drinks/src/main/java/fr/masciulli/drinks/fragment/LiquorDetailFragment.java
tbarthel-fr/Drinks
dddb4013b004ee027d45d461802ff05cc83f7f3e
[ "Apache-2.0" ]
1
2016-07-13T17:56:59.000Z
2016-07-13T17:56:59.000Z
Drinks/src/main/java/fr/masciulli/drinks/fragment/LiquorDetailFragment.java
tbarthel-fr/Drinks
dddb4013b004ee027d45d461802ff05cc83f7f3e
[ "Apache-2.0" ]
null
null
null
Drinks/src/main/java/fr/masciulli/drinks/fragment/LiquorDetailFragment.java
tbarthel-fr/Drinks
dddb4013b004ee027d45d461802ff05cc83f7f3e
[ "Apache-2.0" ]
null
null
null
34.844059
128
0.641543
994,663
package fr.masciulli.drinks.fragment; import android.animation.TimeInterpolator; import android.app.Fragment; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ViewPropertyAnimator; import android.view.ViewTreeObserver; import android.view.animation.DecelerateInterpolator; import android.widget.AbsListView; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.squareup.picasso.Picasso; import com.squareup.picasso.Target; import com.squareup.picasso.Transformation; import java.util.ArrayList; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; import butterknife.OnItemClick; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; import fr.masciulli.android_quantizer.lib.ColorQuantizer; import fr.masciulli.drinks.R; import fr.masciulli.drinks.activity.DrinkDetailActivity; import fr.masciulli.drinks.adapter.LiquorDetailAdapter; import fr.masciulli.drinks.data.DrinksProvider; import fr.masciulli.drinks.model.Drink; import fr.masciulli.drinks.model.Liquor; import fr.masciulli.drinks.util.AnimUtils; import fr.masciulli.drinks.view.BlurTransformation; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; public class LiquorDetailFragment extends Fragment implements AbsListView.OnScrollListener { private static final int HEADERVIEWS_COUNT = 1; private static final long ANIM_IMAGE_ENTER_DURATION = 500; private static final long ANIM_TEXT_ENTER_DURATION = 500; private static final long ANIM_IMAGE_ENTER_STARTDELAY = 300; private static final long ANIM_COLORBOX_ENTER_DURATION = 200; private static final TimeInterpolator sDecelerator = new DecelerateInterpolator(); @InjectView(R.id.image) ImageView mImageView; @InjectView(R.id.image_blurred) ImageView mBlurredImageView; @InjectView(R.id.history) TextView mHistoryView; @InjectView(R.id.progressbar) ProgressBar mProgressBar; @InjectView(R.id.wikipedia) Button mWikipediaButton; @InjectView(R.id.drinks_title) TextView mDrinksTitleView; @InjectView(R.id.colorbox) View mColorBox; @InjectView(R.id.color1) View mColorView1; @InjectView(R.id.color2) View mColorView2; @InjectView(R.id.color3) View mColorView3; @InjectView(R.id.color4) View mColorView4; private ListView mListView; private View mHeaderView; private Target mTarget = new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { mImageView.setImageBitmap(bitmap); new QuantizeBitmapTask().execute(bitmap); } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } }; private LiquorDetailAdapter mDrinkAdapter; private DrinksOnScrollListener mAnimationOnScrollListener; private Liquor mLiquor; private int mImageViewHeight; private Callback<List<Drink>> mDrinksCallback = new Callback<List<Drink>>() { /** * Retrofit callback when drinks loaded * @param drinks * @param response */ @Override public void success(List<Drink> drinks, Response response) { Log.d(getTag(), "Liquor detail related drinks loading/retrieving has succeeded"); if (getActivity() == null) return; List<Drink> filteredDrinks = new ArrayList<Drink>(); for (Drink drink : drinks) { for (String ingredient : drink.ingredients) { if (ingredient.toLowerCase().contains(mLiquor.name.toLowerCase())) { filteredDrinks.add(drink); break; } //At this point, we know main name does not match for (String otherName : mLiquor.otherNames) { if (ingredient.toLowerCase().contains(otherName.toLowerCase())) { filteredDrinks.add(drink); break; } } } } if (filteredDrinks.size() > 0) { mDrinksTitleView.setVisibility(View.VISIBLE); } else { mDrinksTitleView.setVisibility(View.GONE); } mDrinkAdapter.update(filteredDrinks); } @Override public void failure(RetrofitError error) { Response resp = error.getResponse(); String message; if (resp != null) { message = "response status : " + resp.getStatus(); } else { message = "no response"; } Log.e(getTag(), "Liquor detail related drinks loading has failed : " + message); if (getActivity() == null) return; if (error.isNetworkError()) { Crouton.makeText(getActivity(), getString(R.string.network_error), Style.ALERT).show(); } else { String croutonText = String.format(getString(R.string.liquor_detail_drinks_loading_failed), mLiquor.name); Crouton.makeText(getActivity(), croutonText, Style.ALERT).show(); } } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_liquor_detail, container, false); setHasOptionsMenu(true); mHeaderView = inflater.inflate(R.layout.header_liquor_detail, null); mListView = ButterKnife.findById(root, R.id.list); mListView.addHeaderView(mHeaderView); //View injection only done here because header has to be added before ButterKnife.inject(this, root); mDrinkAdapter = new LiquorDetailAdapter(getActivity()); mListView.setAdapter(mDrinkAdapter); Intent intent = getActivity().getIntent(); mLiquor = intent.getParcelableExtra("liquor"); getActivity().setTitle(mLiquor.name); Picasso.with(getActivity()).load(mLiquor.imageUrl).into(mTarget); Transformation transformation = new BlurTransformation(getActivity(), getResources().getInteger(R.integer.blur_radius)); Picasso.with(getActivity()).load(mLiquor.imageUrl).transform(transformation).into(mBlurredImageView); mImageViewHeight = (int) getResources().getDimension(R.dimen.liquor_detail_recipe_margin); mListView.setOnScrollListener(this); mAnimationOnScrollListener = new DrinksOnScrollListener(mListView); if (savedInstanceState != null) { mColorBox.setAlpha(1); Liquor liquor = savedInstanceState.getParcelable("liquor"); List<Drink> drinks = savedInstanceState.getParcelableArrayList("drinks"); if (liquor != null && drinks != null) { onLiquorFound(mLiquor); mDrinksCallback.success(drinks, null); } else { refresh(mLiquor); } } else { ViewTreeObserver observer = mImageView.getViewTreeObserver(); if (observer != null) { observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { mImageView.getViewTreeObserver().removeOnPreDrawListener(this); runEnterAnimation(); return true; } }); } else { refresh(mLiquor); } } return root; } @OnClick(R.id.wikipedia) void goToWikipedia() { if (mLiquor == null) return; startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mLiquor.wikipedia))); } @OnItemClick(R.id.list) void openRelatedDrinkDetail(int position, View view) { Drink drink = mDrinkAdapter.getItem(position - HEADERVIEWS_COUNT); Intent intent = new Intent(getActivity(), DrinkDetailActivity.class); intent.putExtra("drink", drink); startActivity(intent); } private void runEnterAnimation() { Runnable refreshRunnable = new Runnable() { @Override public void run() { refresh(mLiquor); } }; mImageView.setTranslationY(-mImageView.getHeight()); ViewPropertyAnimator animator = mImageView.animate().setDuration(ANIM_IMAGE_ENTER_DURATION). setStartDelay(ANIM_IMAGE_ENTER_STARTDELAY). translationY(0). setInterpolator(sDecelerator); Runnable animateColorBoxRunnable = new Runnable() { @Override public void run() { mColorBox.animate() .alpha(1) .setDuration(ANIM_COLORBOX_ENTER_DURATION) .setInterpolator(sDecelerator); } }; AnimUtils.scheduleStartAction(animator, refreshRunnable, ANIM_IMAGE_ENTER_STARTDELAY); AnimUtils.scheduleEndAction(animator, animateColorBoxRunnable, ANIM_IMAGE_ENTER_DURATION, ANIM_IMAGE_ENTER_STARTDELAY); } public void onLiquorFound(Liquor liquor) { mLiquor = liquor; if (getActivity() == null) return; mProgressBar.setVisibility(View.GONE); mHistoryView.setText(liquor.history); mWikipediaButton.setText(String.format(getString(R.string.liquor_detail_wikipedia), liquor.name)); mDrinksTitleView.setText(String.format(getString(R.string.liquor_detail_drinks), liquor.name)); ViewTreeObserver observer = mListView.getViewTreeObserver(); if (observer != null) { observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { mListView.getViewTreeObserver().removeOnPreDrawListener(this); mListView.setAlpha(0); mListView.animate().setDuration(ANIM_TEXT_ENTER_DURATION). alpha(1). setInterpolator(sDecelerator); return true; } }); } mListView.setVisibility(View.VISIBLE); } public void refresh(Liquor liquor) { if (getActivity() == null) return; DrinksProvider.getAllDrinks(mDrinksCallback); onLiquorFound(liquor); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.liquor_detail, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: getActivity().finish(); return true; case R.id.retry: refresh(mLiquor); return true; } return super.onOptionsItemSelected(item); } @Override public void onScrollStateChanged(AbsListView listView, int state) { if (mAnimationOnScrollListener != null) { mAnimationOnScrollListener.onScrollStateChanged(listView, state); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (mAnimationOnScrollListener != null) { mAnimationOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); } float alpha = 2 * (float) -mHeaderView.getTop() / (float) mImageViewHeight; if (alpha > 1) { alpha = 1; } mBlurredImageView.setAlpha(alpha); mImageView.setTop(mHeaderView.getTop() / 2); mImageView.setBottom(mImageViewHeight + mHeaderView.getTop()); mBlurredImageView.setTop(mHeaderView.getTop() / 2); mBlurredImageView.setBottom(mImageViewHeight + mHeaderView.getTop()); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // TODO do not use getCount if (mLiquor != null && mDrinkAdapter.getCount() > 0) { outState.putParcelable("liquor", mLiquor); outState.putParcelableArrayList("drinks", mDrinkAdapter.getDrinks()); } } private class QuantizeBitmapTask extends AsyncTask<Bitmap, Void, ArrayList<Integer>> { @Override protected ArrayList<Integer> doInBackground(Bitmap... bitmaps) { Bitmap originalBitmap = bitmaps[0]; int originalWidth = originalBitmap.getWidth(); int originalHeight = originalBitmap.getHeight(); Bitmap bitmap = Bitmap.createScaledBitmap(originalBitmap, originalWidth / 16, originalHeight / 16, true); ArrayList<Integer> quantizedColors = new ColorQuantizer().load(bitmap).quantize().getQuantizedColors(); //TODO figure out why only two colors for some images return quantizedColors; } @Override protected void onPostExecute(ArrayList<Integer> colors) { View[] colorViews = new View[]{mColorView1, mColorView2, mColorView3, mColorView4}; for (int i = 0; i < colors.size() && i < 4; i++) { colorViews[i].setBackgroundColor(colors.get(i)); } } } }
922e32187d6764648ff829139edb8e6e17b60d73
631
java
Java
java/typeMigration/testData/inspections/guava/fluentIterableChainWithoutVariable.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
java/typeMigration/testData/inspections/guava/fluentIterableChainWithoutVariable.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
173
2018-07-05T13:59:39.000Z
2018-08-09T01:12:03.000Z
java/typeMigration/testData/inspections/guava/fluentIterableChainWithoutVariable.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
2
2020-03-15T08:57:37.000Z
2020-04-07T04:48:14.000Z
25.24
102
0.660856
994,664
import com.google.common.collect.FluentIterable; import java.util.ArrayList; import java.util.Iterator; class Main { void mmm() { Iterator<String> iterator = m().iterator(); int i = m1() + 10; FluentIterable<String> strings = m2(); } Iterable<String> m() { return FluentIterable.from(new ArrayList<String>()).transform(s -> s + s).filter(String::isEmpty); } int m1() { return FluentIterable.from(new ArrayList<String>()).transform(s -> s + s).size(); } FluentIterable<String> m2() { return FluentIterable.from(new ArrayList<String>()).transform(s -> s + s).filter(String::isEmpty); } }
922e32c1b2a5ebf572dfc98ccb654bd1e30e1a61
5,155
java
Java
src/nl/leocms/util/ListUtil.java
mmbase/natmm
e87fc70ddb29519478edc0829d29758582827629
[ "DOC", "Unlicense" ]
null
null
null
src/nl/leocms/util/ListUtil.java
mmbase/natmm
e87fc70ddb29519478edc0829d29758582827629
[ "DOC", "Unlicense" ]
null
null
null
src/nl/leocms/util/ListUtil.java
mmbase/natmm
e87fc70ddb29519478edc0829d29758582827629
[ "DOC", "Unlicense" ]
null
null
null
38.470149
172
0.603686
994,665
/* * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is LeoCMS. * * The Initial Developer of the Original Code is * 'De Gemeente Leeuwarden' (The dutch municipality Leeuwarden). * * See license.txt in the root of the LeoCMS directory for the full license. */ package nl.leocms.util; import org.mmbase.bridge.*; import org.mmbase.util.logging.Logging; import org.mmbase.util.logging.Logger; /** * Utility methods to create searchforms. * * @author Henk Hangyi Date : Aug 11, 2006 */ public class ListUtil { Cloud cloud; private static final Logger log = Logging.getLoggerInstance(ListUtil.class); public ListUtil(Cloud cloud) { this.cloud = cloud; } public String getObjects(String objects, String source, String role, String destination, String nodeId) { StringBuffer sbObjects = new StringBuffer(); String constraint = "(" + destination + ".number = '" + nodeId + "')"; log.debug("getObjects objects=" + objects + ", path=" + source + "," + role + "," + destination + ", fields=" + source + ".number" + ", constraints=" + constraint); if(!nodeId.equals("")) { NodeList nlObjects = cloud.getList(objects, source + "," + role + "," + destination, source + ".number", constraint, null,null,null,true); for(int n=0; n<nlObjects.size(); n++) { if(n>0) { sbObjects.append(','); } sbObjects.append(nlObjects.getNode(n).getStringValue(source + ".number")); } objects = sbObjects.toString(); log.debug(destination + ": " + objects); } return objects; } public String getObjectsConstraint(String objects, String source, String path, String constraint) { StringBuffer sbObjects = new StringBuffer(); log.debug("objects=" + objects + ", path=" + path + ", fields=" + source + ".number" + ", constraints=" + constraint); NodeList nlObjects = cloud.getList(objects, path,source + ".number","(" + constraint + ")",null,null,null,true); for(int n=0; n<nlObjects.size(); n++) { if(n>0) { sbObjects.append(','); } sbObjects.append(nlObjects.getNode(n).getStringValue(source + ".number")); } objects = sbObjects.toString(); log.debug("getObjectsConstraint: " + objects); return objects; } public NodeList getRelated(String objects, String source, String role, String destination, String field, String field2, String language) { String fields = destination + ".number," + destination + "." + LocaleUtil.getLangFieldName(field,language); if (!field2.equals("")) { fields += "," + destination + "." + LocaleUtil.getLangFieldName(field2,language); } log.debug("getRelated objects=" + objects + ", path=" + source + "," + role + "," + destination + ", fields=" + fields + ", destination=" + destination + "." + field); NodeList nlRelated = cloud.getList(objects, source + "," + role + "," + destination, fields, null,destination + "." + field,"UP",null,true); int n=0; String lastFields = ""; while(n<nlRelated.size()) { // make list unique String thisFields = nlRelated.getNode(n).getStringValue(destination + "." + field); if (!field2.equals("")) { fields += "," + nlRelated.getNode(n).getStringValue(destination + "." + field2); } if(thisFields.equals(lastFields)) { nlRelated.remove(n); } else { n++; } lastFields = thisFields; } return nlRelated; } public NodeList getRelated(String objects, String source, String role, String destination, String field) { return getRelated(objects,source,role,destination,field,"","nl"); } public String setSelected(String object, NodeList objectList, String field) { if("".equals(object)&&objectList.size()==1) { object = objectList.getNode(0).getStringValue(field); } return object; } public int count(String base, String searchFor) { int len = searchFor.length(); int result = 0; if (len > 0) { // search only if there is something int start = base.indexOf(searchFor); while (start != -1) { result++; start = base.indexOf(searchFor, start+len); } } return result; } } /** * $Log: not supported by cvs2svn $ * Revision 1.1 2006/08/11 09:24:16 henk * Moved searchform related functions to class * * */
922e3434bb4219213832631d9db72b5979241695
5,148
java
Java
Team France/SorterThread.java
nomelif/ControlCodesRepo
0b4f6e5ed969919244e7f6a68549564558261299
[ "MIT" ]
1
2017-08-12T08:24:18.000Z
2017-08-12T08:24:18.000Z
Team France/SorterThread.java
nomelif/ControlCodesRepo
0b4f6e5ed969919244e7f6a68549564558261299
[ "MIT" ]
3
2017-07-04T09:07:31.000Z
2017-08-15T17:51:03.000Z
Team France/SorterThread.java
nomelif/ControlCodesRepo
0b4f6e5ed969919244e7f6a68549564558261299
[ "MIT" ]
5
2017-07-03T20:15:59.000Z
2018-06-29T16:48:37.000Z
36.771429
131
0.514957
994,666
package org.firstinspires.ftc.teamcode; import com.qualcomm.hardware.lynx.LynxI2cColorRangeSensor; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorImplEx; import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit; class SorterThread implements Runnable{ private DcMotorImplEx shuffleMotor; private LynxI2cColorRangeSensor centerColor; boolean running = false; public boolean blocked = false; private boolean killed = false; private boolean tour = true; public LynxI2cColorRangeSensor getCenterColor() { return centerColor; } public DcMotor getShuffleMotor() { return shuffleMotor; } SorterThread(DcMotorImplEx tri, LynxI2cColorRangeSensor distcol){ Thread thread = new Thread(this); shuffleMotor = tri; centerColor = distcol; thread.start(); } public void run(){ this.shuffleMotor.setPower(1); running = true; killed=false; while (!killed) { while (running) { switch (OPMode.modeTri) { case DROITE: if (centerColor.getDistance(DistanceUnit.MM) < 60) {this.triDC(1);} break; case GAUCHE: if (centerColor.getDistance(DistanceUnit.MM) < 60) {this.triDC(-1);} break; case UNI: if (centerColor.getDistance(DistanceUnit.MM) < 60){ if (tour){ OPMode.rtPosCible -= 96; } else { OPMode.rtPosCible += 96; } tour = !tour; this.shuffleMotor.setTargetPosition(OPMode.rtPosCible); while (this.shuffleMotor.isBusy()) { OPMode.telemetryProxy.addLine("Stucked in isBusy UNI"); OPMode.telemetryProxy.addData("thread bloqué ?",blocked); OPMode.telemetryProxy.addData("Position roue tri :", this.shuffleMotor.getCurrentPosition()); OPMode.telemetryProxy.addData("vraie Position cible rt :", this.shuffleMotor.getTargetPosition()); OPMode.telemetryProxy.addData("roueTrie enabled ?",this.shuffleMotor.isMotorEnabled()); OPMode.telemetryProxy.addData("roueTrie busy ?",this.shuffleMotor.isBusy()); OPMode.telemetryProxy.update(); if (!OPMode.opModActif) { break; } } } break; case MANUEL: { sleep(10); break; } } } sleep(10); } stopMotors(); sleep(10); } void kill(){ running = false; killed = true; stopMotors(); OPMode.telemetryProxy.addLine("Sorter thread has been killed!"); /*FirstOpMode.telemetryProxy.update();*/ } void relaunch(){running = true;} void stop(){running = false;} private void triDC(int sens) { /*if (this.centerColor.blue() < this.centerColor.red()){this.rtPosCible -= 96;} else {this.rtPosCible += 96;}*/ if (this.centerColor.blue()<this.centerColor.red()) { OPMode.rtPosCible -= 96*sens; } else { OPMode.rtPosCible += 96*sens; } this.shuffleMotor.setTargetPosition(OPMode.rtPosCible); while (this.shuffleMotor.isBusy()) { blocked=true; /*OPMode.telemetryProxy.addLine("Stucked in isBusy"); OPMode.telemetryProxy.addData("thread bloqué ?",blocked); OPMode.telemetryProxy.addData("Position roue tri :", this.shuffleMotor.getCurrentPosition()); OPMode.telemetryProxy.addData("vraie Position cible rt :", this.shuffleMotor.getTargetPosition()); OPMode.telemetryProxy.addData("roueTrie enabled ?",this.shuffleMotor.isMotorEnabled()); OPMode.telemetryProxy.addData("roueTrie busy ?",this.shuffleMotor.isBusy()); OPMode.telemetryProxy.update();*/ if (!OPMode.opModActif) break; } blocked = false; } private void sleep(int t){ try { Thread.sleep(t); } catch (InterruptedException e) { OPMode.telemetryProxy.addData("Interrupted Exception occured", "Line %d", e.getStackTrace()[0].getLineNumber()); OPMode.telemetryProxy.update(); } } private void stopMotors(){ //shuffleMotor.setPower(0); } }
922e3455b53b99e925158ca84d9d30fe5f8455bc
130
java
Java
ProjectSourceCode/Apache Commons Math v3.5/src/test/java/org/apache/commons/math3/fitting/leastsquares/LevenbergMarquardtOptimizerTest.java
yashgolwala/Software_Measurement_Team_M
3d2aef4c0711b7a02155a42ca6b08bb6c2693d4c
[ "Unlicense" ]
null
null
null
ProjectSourceCode/Apache Commons Math v3.5/src/test/java/org/apache/commons/math3/fitting/leastsquares/LevenbergMarquardtOptimizerTest.java
yashgolwala/Software_Measurement_Team_M
3d2aef4c0711b7a02155a42ca6b08bb6c2693d4c
[ "Unlicense" ]
null
null
null
ProjectSourceCode/Apache Commons Math v3.5/src/test/java/org/apache/commons/math3/fitting/leastsquares/LevenbergMarquardtOptimizerTest.java
yashgolwala/Software_Measurement_Team_M
3d2aef4c0711b7a02155a42ca6b08bb6c2693d4c
[ "Unlicense" ]
2
2019-06-24T22:57:32.000Z
2019-06-26T16:58:52.000Z
32.5
75
0.884615
994,667
version https://git-lfs.github.com/spec/v1 oid sha256:048446744437e3a96868263a96446052f24348bb26ae24622b7923fda7c7891e size 15629
922e346b83d14b2e328078514c6df2488adf7914
803
java
Java
utm_web/src/main/java/com/utm/basic/entity/AbstractEntity.java
ahzhangfeifei/utm_core
8aa2d716242181a62801e61d453f62aa2791a472
[ "Apache-2.0" ]
3
2017-07-31T14:55:18.000Z
2018-03-20T09:58:31.000Z
utm_web/src/main/java/com/utm/basic/entity/AbstractEntity.java
ahzhangfeifei/utm
8aa2d716242181a62801e61d453f62aa2791a472
[ "Apache-2.0" ]
null
null
null
utm_web/src/main/java/com/utm/basic/entity/AbstractEntity.java
ahzhangfeifei/utm
8aa2d716242181a62801e61d453f62aa2791a472
[ "Apache-2.0" ]
null
null
null
25.09375
84
0.692403
994,668
package com.utm.basic.entity; import org.apache.commons.lang3.builder.ToStringBuilder; public abstract class AbstractEntity implements java.io.Serializable { //private static final long serialVersionUID =1L; @Override public String toString() { return ToStringBuilder.reflectionToString(this); } public void save() { // ICommonService commonService = SpringContextUtil.getBean("CommonService"); // commonService.save(this); } public void delete() { // ICommonService commonService = SpringContextUtil.getBean("CommonService"); // commonService.deleteObject(this); } public void update() { // ICommonService commonService = SpringContextUtil.getBean("CommonService"); // commonService.update(this); } }
922e3492f100bd672843d736740b15fa6abb9a38
919
java
Java
src/test/java/org/springframework/samples/petclinic/sfg/junit5/HearingInterpreterLaurelTest.java
tosumaso/junit5Spring
fea12b1f7db0fa3b7ee115516951430f1a5d080b
[ "Apache-2.0" ]
null
null
null
src/test/java/org/springframework/samples/petclinic/sfg/junit5/HearingInterpreterLaurelTest.java
tosumaso/junit5Spring
fea12b1f7db0fa3b7ee115516951430f1a5d080b
[ "Apache-2.0" ]
null
null
null
src/test/java/org/springframework/samples/petclinic/sfg/junit5/HearingInterpreterLaurelTest.java
tosumaso/junit5Spring
fea12b1f7db0fa3b7ee115516951430f1a5d080b
[ "Apache-2.0" ]
null
null
null
32.821429
84
0.825898
994,669
package org.springframework.samples.petclinic.sfg.junit5; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.samples.petclinic.sfg.BaseConfig; import org.springframework.samples.petclinic.sfg.HearingInterpreter; import org.springframework.samples.petclinic.sfg.LaurelConfig; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @ActiveProfiles("base-test") //@SpringJUnitConfig : @ExtendWith(SpringExtension.class),@ContextConfiguration()を含む @SpringJUnitConfig(classes= {BaseConfig.class, LaurelConfig.class}) class HearingInterpreterLaurelTest { @Autowired HearingInterpreter hearingInterpreter; @Test void whatIheard() { String word = hearingInterpreter.whatIheard(); assertEquals("Laurel",word); } }
922e34c12dbc7913db5537d99c8727d07f7834ee
1,499
java
Java
src/main/java/net/theawesomegem/blockdropstweaker/proxy/ClientProxy.java
TheAwesomeGem/BlockDropsTweaker
c3eabc201c587b7e5e69eadde3d3f71d9a1661fc
[ "Apache-2.0" ]
1
2018-01-10T17:41:10.000Z
2018-01-10T17:41:10.000Z
src/main/java/net/theawesomegem/blockdropstweaker/proxy/ClientProxy.java
TheAwesomeGem/BlockDropsTweaker
c3eabc201c587b7e5e69eadde3d3f71d9a1661fc
[ "Apache-2.0" ]
11
2018-02-15T02:41:23.000Z
2021-01-21T13:32:55.000Z
src/main/java/net/theawesomegem/blockdropstweaker/proxy/ClientProxy.java
TheAwesomeGem/BlockDropsTweaker
c3eabc201c587b7e5e69eadde3d3f71d9a1661fc
[ "Apache-2.0" ]
null
null
null
28.283019
96
0.745163
994,670
package net.theawesomegem.blockdropstweaker.proxy; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.IThreadListener; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; import net.theawesomegem.blockdropstweaker.client.event.KeyBindingHandler; import net.theawesomegem.blockdropstweaker.client.keybind.KeybindManager; /** * Created by TheAwesomeGem on 6/18/2017. */ public class ClientProxy extends CommonProxy { @Override public void onPreInit(FMLPreInitializationEvent e) { super.onPreInit(e); } @Override public void onInit(FMLInitializationEvent e) { super.onInit(e); KeybindManager.load(); } @Override protected void registerEvents() { super.registerEvents(); MinecraftForge.EVENT_BUS.register(new KeyBindingHandler()); } @Override public IThreadListener getListener(MessageContext ctx) { return ctx.side == Side.CLIENT ? Minecraft.getMinecraft() : super.getListener(ctx); } @Override public EntityPlayer getPlayer(MessageContext ctx) { return ctx.side == Side.CLIENT ? Minecraft.getMinecraft().player : super.getPlayer(ctx); } }
922e3635493ec92531905682a5907427fad80f6a
23,087
java
Java
pulsar-functions/utils/src/test/java/org/apache/pulsar/functions/utils/SinkConfigUtilsTest.java
shink/pulsar
e6b12c64b043903eb5ff2dc5186fe8030f157cfc
[ "Apache-2.0" ]
778
2017-06-23T07:34:43.000Z
2018-09-20T10:56:16.000Z
pulsar-functions/utils/src/test/java/org/apache/pulsar/functions/utils/SinkConfigUtilsTest.java
shink/pulsar
e6b12c64b043903eb5ff2dc5186fe8030f157cfc
[ "Apache-2.0" ]
1,575
2017-06-21T21:34:42.000Z
2018-09-22T00:16:35.000Z
pulsar-functions/utils/src/test/java/org/apache/pulsar/functions/utils/SinkConfigUtilsTest.java
shink/pulsar
e6b12c64b043903eb5ff2dc5186fe8030f157cfc
[ "Apache-2.0" ]
188
2017-06-22T20:47:59.000Z
2018-09-19T00:59:01.000Z
46.081836
159
0.702387
994,671
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.functions.utils; import com.google.common.collect.Lists; import com.google.gson.Gson; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import org.apache.pulsar.common.functions.ConsumerConfig; import org.apache.pulsar.common.functions.FunctionConfig; import org.apache.pulsar.common.functions.Resources; import org.apache.pulsar.common.io.ConnectorDefinition; import org.apache.pulsar.common.io.SinkConfig; import org.apache.pulsar.config.validation.ConfigValidationAnnotations; import org.apache.pulsar.functions.api.utils.IdentityFunction; import org.apache.pulsar.functions.proto.Function; import org.testng.annotations.Test; import java.io.IOException; import java.lang.reflect.Field; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.apache.pulsar.common.functions.FunctionConfig.ProcessingGuarantees.ATLEAST_ONCE; import static org.apache.pulsar.common.functions.FunctionConfig.ProcessingGuarantees.ATMOST_ONCE; import static org.apache.pulsar.common.functions.FunctionConfig.ProcessingGuarantees.EFFECTIVELY_ONCE; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static org.testng.Assert.expectThrows; /** * Unit test of {@link SinkConfigUtilsTest}. */ public class SinkConfigUtilsTest { private ConnectorDefinition defn; @Data @Accessors(chain = true) @NoArgsConstructor public static class TestSinkConfig { @ConfigValidationAnnotations.NotNull private String configParameter; } @Test public void testConvertBackFidelity() throws IOException { SinkConfig sinkConfig = new SinkConfig(); sinkConfig.setTenant("test-tenant"); sinkConfig.setNamespace("test-namespace"); sinkConfig.setName("test-source"); sinkConfig.setParallelism(1); sinkConfig.setArchive("builtin://jdbc"); sinkConfig.setSourceSubscriptionName("test-subscription"); Map<String, ConsumerConfig> inputSpecs = new HashMap<>(); inputSpecs.put("test-input", ConsumerConfig.builder() .isRegexPattern(true) .receiverQueueSize(532) .serdeClassName("test-serde") .poolMessages(true).build()); sinkConfig.setInputs(Collections.singleton("test-input")); sinkConfig.setInputSpecs(inputSpecs); sinkConfig.setProcessingGuarantees(FunctionConfig.ProcessingGuarantees.ATLEAST_ONCE); Map<String, String> producerConfigs = new HashMap<>(); producerConfigs.put("security.protocal", "SASL_PLAINTEXT"); Map<String, Object> configs = new HashMap<>(); configs.put("topic", "kafka"); configs.put("bootstrapServers", "server-1,server-2"); configs.put("producerConfigProperties", producerConfigs); sinkConfig.setConfigs(configs); sinkConfig.setRetainOrdering(false); sinkConfig.setRetainKeyOrdering(false); sinkConfig.setAutoAck(true); sinkConfig.setCleanupSubscription(false); sinkConfig.setTimeoutMs(2000l); sinkConfig.setRuntimeFlags("-DKerberos"); sinkConfig.setCleanupSubscription(true); sinkConfig.setResources(Resources.getDefaultResources()); Function.FunctionDetails functionDetails = SinkConfigUtils.convert(sinkConfig, new SinkConfigUtils.ExtractedSinkDetails(null, null)); assertEquals(Function.SubscriptionType.SHARED, functionDetails.getSource().getSubscriptionType()); SinkConfig convertedConfig = SinkConfigUtils.convertFromDetails(functionDetails); assertEquals( new Gson().toJson(convertedConfig), new Gson().toJson(sinkConfig) ); sinkConfig.setRetainOrdering(true); sinkConfig.setRetainKeyOrdering(false); functionDetails = SinkConfigUtils.convert(sinkConfig, new SinkConfigUtils.ExtractedSinkDetails(null, null)); assertEquals(Function.SubscriptionType.FAILOVER, functionDetails.getSource().getSubscriptionType()); convertedConfig = SinkConfigUtils.convertFromDetails(functionDetails); assertEquals( new Gson().toJson(convertedConfig), new Gson().toJson(sinkConfig)); sinkConfig.setRetainOrdering(false); sinkConfig.setRetainKeyOrdering(true); functionDetails = SinkConfigUtils.convert(sinkConfig, new SinkConfigUtils.ExtractedSinkDetails(null, null)); assertEquals(Function.SubscriptionType.KEY_SHARED, functionDetails.getSource().getSubscriptionType()); convertedConfig = SinkConfigUtils.convertFromDetails(functionDetails); assertEquals( new Gson().toJson(convertedConfig), new Gson().toJson(sinkConfig)); } @Test public void testParseRetainOrderingField() throws IOException { List<Boolean> testcases = Lists.newArrayList(true, false, null); for (Boolean testcase : testcases) { SinkConfig sinkConfig = createSinkConfig(); sinkConfig.setRetainOrdering(testcase); Function.FunctionDetails functionDetails = SinkConfigUtils.convert(sinkConfig, new SinkConfigUtils.ExtractedSinkDetails(null, null)); SinkConfig result = SinkConfigUtils.convertFromDetails(functionDetails); assertEquals(result.getRetainOrdering(), testcase != null ? testcase : Boolean.valueOf(false)); } } @Test public void testParseKeyRetainOrderingField() throws IOException { List<Boolean> testcases = Lists.newArrayList(true, false, null); for (Boolean testcase : testcases) { SinkConfig sinkConfig = createSinkConfig(); sinkConfig.setRetainKeyOrdering(testcase); Function.FunctionDetails functionDetails = SinkConfigUtils.convert(sinkConfig, new SinkConfigUtils.ExtractedSinkDetails(null, null)); SinkConfig result = SinkConfigUtils.convertFromDetails(functionDetails); assertEquals(result.getRetainKeyOrdering(), testcase != null ? testcase : Boolean.valueOf(false)); } } @Test public void testParseProcessingGuaranteesField() throws IOException { List<FunctionConfig.ProcessingGuarantees> testcases = Lists.newArrayList( EFFECTIVELY_ONCE, ATMOST_ONCE, ATLEAST_ONCE, null ); for (FunctionConfig.ProcessingGuarantees testcase : testcases) { SinkConfig sinkConfig = createSinkConfig(); sinkConfig.setProcessingGuarantees(testcase); Function.FunctionDetails functionDetails = SinkConfigUtils.convert(sinkConfig, new SinkConfigUtils.ExtractedSinkDetails(null, null)); SinkConfig result = SinkConfigUtils.convertFromDetails(functionDetails); assertEquals(result.getProcessingGuarantees(), testcase == null ? ATLEAST_ONCE : testcase); } } @Test public void testCleanSubscriptionField() throws IOException { List<Boolean> testcases = Lists.newArrayList(true, false, null); for (Boolean testcase : testcases) { SinkConfig sinkConfig = createSinkConfig(); sinkConfig.setCleanupSubscription(testcase); Function.FunctionDetails functionDetails = SinkConfigUtils.convert(sinkConfig, new SinkConfigUtils.ExtractedSinkDetails(null, null)); SinkConfig result = SinkConfigUtils.convertFromDetails(functionDetails); assertEquals(result.getCleanupSubscription(), testcase == null ? Boolean.valueOf(true) : testcase); } } @Test public void testMergeEqual() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createSinkConfig(); SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); assertEquals( new Gson().toJson(sinkConfig), new Gson().toJson(mergedConfig) ); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Sink Names differ") public void testMergeDifferentName() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("name", "Different"); SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Tenants differ") public void testMergeDifferentTenant() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("tenant", "Different"); SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Namespaces differ") public void testMergeDifferentNamespace() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("namespace", "Different"); SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); } @Test public void testMergeDifferentClassName() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("className", "Different"); SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); assertEquals( mergedConfig.getClassName(), "Different" ); mergedConfig.setClassName(sinkConfig.getClassName()); assertEquals( new Gson().toJson(sinkConfig), new Gson().toJson(mergedConfig) ); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Input Topics cannot be altered") public void testMergeDifferentInputs() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("topicsPattern", "Different"); SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "isRegexPattern for input topic test-input cannot be altered") public void testMergeDifferentInputSpecWithRegexChange() { SinkConfig sinkConfig = createSinkConfig(); Map<String, ConsumerConfig> inputSpecs = new HashMap<>(); inputSpecs.put("test-input", ConsumerConfig.builder().isRegexPattern(false).serdeClassName("my-serde").build()); SinkConfig newSinkConfig = createUpdatedSinkConfig("inputSpecs", inputSpecs); SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); } @Test public void testMergeDifferentInputSpec() { SinkConfig sinkConfig = createSinkConfig(); sinkConfig.getInputSpecs().put("test-input", ConsumerConfig.builder().isRegexPattern(true).receiverQueueSize(1000).build()); Map<String, ConsumerConfig> inputSpecs = new HashMap<>(); inputSpecs.put("test-input", ConsumerConfig.builder().isRegexPattern(true).serdeClassName("test-serde").receiverQueueSize(58).build()); SinkConfig newSinkConfig = createUpdatedSinkConfig("inputSpecs", inputSpecs); SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); assertEquals(mergedConfig.getInputSpecs().get("test-input"), newSinkConfig.getInputSpecs().get("test-input")); // make sure original sinkConfig was not modified assertEquals(sinkConfig.getInputSpecs().get("test-input").getReceiverQueueSize().intValue(), 1000); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Processing Guarantees cannot be altered") public void testMergeDifferentProcessingGuarantees() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("processingGuarantees", EFFECTIVELY_ONCE); SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Retain Ordering cannot be altered") public void testMergeDifferentRetainOrdering() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("retainOrdering", true); SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Retain Key Ordering cannot be altered") public void testMergeDifferentRetainKeyOrdering() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("retainKeyOrdering", true); SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); } @Test public void testMergeDifferentUserConfig() { SinkConfig sinkConfig = createSinkConfig(); Map<String, String> myConfig = new HashMap<>(); myConfig.put("MyKey", "MyValue"); SinkConfig newSinkConfig = createUpdatedSinkConfig("configs", myConfig); SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); assertEquals( mergedConfig.getConfigs(), myConfig ); mergedConfig.setConfigs(sinkConfig.getConfigs()); assertEquals( new Gson().toJson(sinkConfig), new Gson().toJson(mergedConfig) ); } @Test public void testMergeDifferentSecrets() { SinkConfig sinkConfig = createSinkConfig(); Map<String, String> mySecrets = new HashMap<>(); mySecrets.put("MyKey", "MyValue"); SinkConfig newSinkConfig = createUpdatedSinkConfig("secrets", mySecrets); SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); assertEquals( mergedConfig.getSecrets(), mySecrets ); mergedConfig.setSecrets(sinkConfig.getSecrets()); assertEquals( new Gson().toJson(sinkConfig), new Gson().toJson(mergedConfig) ); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "AutoAck cannot be altered") public void testMergeDifferentAutoAck() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("autoAck", false); SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Subscription Name cannot be altered") public void testMergeDifferentSubname() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("sourceSubscriptionName", "Different"); SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); } @Test public void testMergeDifferentParallelism() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("parallelism", 101); SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); assertEquals( mergedConfig.getParallelism(), new Integer(101) ); mergedConfig.setParallelism(sinkConfig.getParallelism()); assertEquals( new Gson().toJson(sinkConfig), new Gson().toJson(mergedConfig) ); } @Test public void testMergeDifferentResources() { SinkConfig sinkConfig = createSinkConfig(); Resources resources = new Resources(); resources.setCpu(0.3); resources.setRam(1232l); resources.setDisk(123456l); SinkConfig newSinkConfig = createUpdatedSinkConfig("resources", resources); SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); assertEquals( mergedConfig.getResources(), resources ); mergedConfig.setResources(sinkConfig.getResources()); assertEquals( new Gson().toJson(sinkConfig), new Gson().toJson(mergedConfig) ); } @Test public void testMergeDifferentTimeout() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("timeoutMs", 102l); SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); assertEquals( mergedConfig.getTimeoutMs(), new Long(102l) ); mergedConfig.setTimeoutMs(sinkConfig.getTimeoutMs()); assertEquals( new Gson().toJson(sinkConfig), new Gson().toJson(mergedConfig) ); } @Test public void testMergeDifferentCleanupSubscription() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("cleanupSubscription", false); SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); assertFalse(mergedConfig.getCleanupSubscription()); mergedConfig.setCleanupSubscription(sinkConfig.getCleanupSubscription()); assertEquals( new Gson().toJson(sinkConfig), new Gson().toJson(mergedConfig) ); } @Test public void testMergeRuntimeFlags() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newFunctionConfig = createUpdatedSinkConfig("runtimeFlags", "-Dfoo=bar2"); SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newFunctionConfig); assertEquals( mergedConfig.getRuntimeFlags(), "-Dfoo=bar2" ); mergedConfig.setRuntimeFlags(sinkConfig.getRuntimeFlags()); assertEquals( new Gson().toJson(sinkConfig), new Gson().toJson(mergedConfig) ); } @Test public void testValidateConfig() throws IOException { SinkConfig sinkConfig = createSinkConfig(); // Good config sinkConfig.getConfigs().put("configParameter", "Test"); SinkConfigUtils.validateSinkConfig(sinkConfig, TestSinkConfig.class); // Bad config sinkConfig.getConfigs().put("configParameter", null); Exception e = expectThrows(IllegalArgumentException.class, () -> SinkConfigUtils.validateSinkConfig(sinkConfig, TestSinkConfig.class)); assertTrue(e.getMessage().contains("Could not validate sink config: Field 'configParameter' cannot be null!")); } private SinkConfig createSinkConfig() { SinkConfig sinkConfig = new SinkConfig(); sinkConfig.setTenant("test-tenant"); sinkConfig.setNamespace("test-namespace"); sinkConfig.setName("test-sink"); sinkConfig.setParallelism(1); sinkConfig.setClassName(IdentityFunction.class.getName()); Map<String, ConsumerConfig> inputSpecs = new HashMap<>(); inputSpecs.put("test-input", ConsumerConfig.builder().isRegexPattern(true).serdeClassName("test-serde").build()); sinkConfig.setInputSpecs(inputSpecs); sinkConfig.setProcessingGuarantees(FunctionConfig.ProcessingGuarantees.ATLEAST_ONCE); sinkConfig.setRetainOrdering(false); sinkConfig.setRetainKeyOrdering(false); sinkConfig.setConfigs(new HashMap<>()); sinkConfig.setAutoAck(true); sinkConfig.setTimeoutMs(2000l); sinkConfig.setCleanupSubscription(true); sinkConfig.setArchive("DummyArchive.nar"); sinkConfig.setCleanupSubscription(true); return sinkConfig; } private SinkConfig createUpdatedSinkConfig(String fieldName, Object fieldValue) { SinkConfig sinkConfig = createSinkConfig(); Class<?> fClass = SinkConfig.class; try { Field chap = fClass.getDeclaredField(fieldName); chap.setAccessible(true); chap.set(sinkConfig, fieldValue); } catch (Exception e) { throw new RuntimeException("Something wrong with the test", e); } return sinkConfig; } @Test public void testPoolMessages() throws IOException { SinkConfig sinkConfig = createSinkConfig(); Function.FunctionDetails functionDetails = SinkConfigUtils.convert(sinkConfig, new SinkConfigUtils.ExtractedSinkDetails(null, null)); assertFalse(functionDetails.getSource().getInputSpecsMap().get("test-input").getPoolMessages()); SinkConfig convertedConfig = SinkConfigUtils.convertFromDetails(functionDetails); assertFalse(convertedConfig.getInputSpecs().get("test-input").isPoolMessages()); Map<String, ConsumerConfig> inputSpecs = new HashMap<>(); inputSpecs.put("test-input", ConsumerConfig.builder() .poolMessages(true).build()); sinkConfig.setInputSpecs(inputSpecs); functionDetails = SinkConfigUtils.convert(sinkConfig, new SinkConfigUtils.ExtractedSinkDetails(null, null)); assertTrue(functionDetails.getSource().getInputSpecsMap().get("test-input").getPoolMessages()); convertedConfig = SinkConfigUtils.convertFromDetails(functionDetails); assertTrue(convertedConfig.getInputSpecs().get("test-input").isPoolMessages()); } @Test public void testAllowDisableSinkTimeout() { SinkConfig sinkConfig = createSinkConfig(); sinkConfig.setInputSpecs(null); sinkConfig.setTopicsPattern("my-topic-*"); SinkConfigUtils.validateAndExtractDetails(sinkConfig, this.getClass().getClassLoader(), true); sinkConfig.setTimeoutMs(null); SinkConfigUtils.validateAndExtractDetails(sinkConfig, this.getClass().getClassLoader(), true); sinkConfig.setTimeoutMs(0L); SinkConfigUtils.validateAndExtractDetails(sinkConfig, this.getClass().getClassLoader(), true); } }
922e365f2ce70379e0f35709d3dacda86f2b5184
2,108
java
Java
hoot/src/main/java/org/hoot/IlvesDbDiff.java
bubblecloud/hoot-bundle-translation-site
0ff21663776aacfce5b2358593ba22e40eb4e5c5
[ "Apache-2.0" ]
null
null
null
hoot/src/main/java/org/hoot/IlvesDbDiff.java
bubblecloud/hoot-bundle-translation-site
0ff21663776aacfce5b2358593ba22e40eb4e5c5
[ "Apache-2.0" ]
null
null
null
hoot/src/main/java/org/hoot/IlvesDbDiff.java
bubblecloud/hoot-bundle-translation-site
0ff21663776aacfce5b2358593ba22e40eb4e5c5
[ "Apache-2.0" ]
null
null
null
39.773585
109
0.743359
994,672
/** * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/> */ package org.hoot; import org.apache.log4j.xml.DOMConfigurator; import org.bubblecloud.ilves.util.PersistenceUtil; import org.bubblecloud.ilves.util.PropertiesUtil; /** * Helper class for easily generating templates for liquibase change files from JPA model. * * You will need to edit the generated change sets to modify things like schema and data types. */ public class IlvesDbDiff { /** * * @param args */ public static void main(final String[] args) throws Exception { // Configure logging. DOMConfigurator.configure("log4j.xml"); PropertiesUtil.setCategoryRedirection("site", HootMain.PROPERTIES_FILE_PREFIX); final String diff = PersistenceUtil.diff(HootMain.PERSISTENCE_UNIT, HootMain.PROPERTIES_FILE_PREFIX); System.out.println(diff); } }
922e388647bcad6dc443160932ff0345f8711781
6,817
java
Java
zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ConnectionPoolHandler.java
arabelle/zuul
ed55476a7cab8317b73e3c1d0347f7db4ae67358
[ "Apache-2.0" ]
12,101
2015-01-02T01:13:33.000Z
2022-03-31T14:37:11.000Z
zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ConnectionPoolHandler.java
arabelle/zuul
ed55476a7cab8317b73e3c1d0347f7db4ae67358
[ "Apache-2.0" ]
722
2015-01-12T23:38:15.000Z
2022-03-29T16:01:59.000Z
zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ConnectionPoolHandler.java
arabelle/zuul
ed55476a7cab8317b73e3c1d0347f7db4ae67358
[ "Apache-2.0" ]
2,454
2015-01-08T11:40:59.000Z
2022-03-31T22:07:12.000Z
42.625
159
0.655572
994,673
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.connectionpool; import com.netflix.spectator.api.Counter; import com.netflix.zuul.netty.ChannelUtils; import com.netflix.zuul.netty.SpectatorUtils; import com.netflix.zuul.origins.OriginName; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.timeout.IdleStateEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent; import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason; import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason.SESSION_COMPLETE; /** * User: envkt@example.com * Date: 6/23/16 * Time: 1:57 PM */ @ChannelHandler.Sharable public class ConnectionPoolHandler extends ChannelDuplexHandler { private static final Logger LOG = LoggerFactory.getLogger(ConnectionPoolHandler.class); public static final String METRIC_PREFIX = "connectionpool"; private final OriginName originName; private final Counter idleCounter; private final Counter inactiveCounter; private final Counter errorCounter; public ConnectionPoolHandler(OriginName originName) { if (originName == null) { throw new IllegalArgumentException("Null originName passed to constructor!"); } this.originName = originName; this.idleCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_idle", originName.getMetricId()); this.inactiveCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_inactive", originName.getMetricId()); this.errorCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_error", originName.getMetricId()); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { // First let other handlers do their thing ... // super.userEventTriggered(ctx, evt); if (evt instanceof IdleStateEvent) { // Log some info about this. idleCounter.increment(); final String msg = "Origin channel for origin - " + originName + " - idle timeout has fired. " + ChannelUtils.channelInfoForLogging(ctx.channel()); closeConnection(ctx, msg); } else if (evt instanceof CompleteEvent) { // The HttpLifecycleChannelHandler instance will fire this event when either a response has finished being written, or // the channel is no longer active or disconnected. // Return the connection to pool. CompleteEvent completeEvt = (CompleteEvent) evt; final CompleteReason reason = completeEvt.getReason(); if (reason == SESSION_COMPLETE) { final PooledConnection conn = PooledConnection.getFromChannel(ctx.channel()); if (conn != null) { if ("close".equalsIgnoreCase(getConnectionHeader(completeEvt))) { final String msg = "Origin channel for origin - " + originName + " - completed because of expired keep-alive. " + ChannelUtils.channelInfoForLogging(ctx.channel()); closeConnection(ctx, msg); } else { conn.setConnectionState(PooledConnection.ConnectionState.WRITE_READY); conn.release(); } } } else { final String msg = "Origin channel for origin - " + originName + " - completed with reason " + reason.name() + ", " + ChannelUtils.channelInfoForLogging(ctx.channel()); closeConnection(ctx, msg); } } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { //super.exceptionCaught(ctx, cause); errorCounter.increment(); final String mesg = "Exception on Origin channel for origin - " + originName + ". " + ChannelUtils.channelInfoForLogging(ctx.channel()) + " - " + cause.getClass().getCanonicalName() + ": " + cause.getMessage(); closeConnection(ctx, mesg); if (LOG.isDebugEnabled()) { LOG.debug(mesg, cause); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { //super.channelInactive(ctx); inactiveCounter.increment(); final String msg = "Client channel for origin - " + originName + " - inactive event has fired. " + ChannelUtils.channelInfoForLogging(ctx.channel()); closeConnection(ctx, msg); } private void closeConnection(ChannelHandlerContext ctx, String msg) { PooledConnection conn = PooledConnection.getFromChannel(ctx.channel()); if (conn != null) { if (LOG.isDebugEnabled()) { msg = msg + " Closing the PooledConnection and releasing. conn={}"; LOG.debug(msg, conn); } flagCloseAndReleaseConnection(conn); } else { // If somehow we don't have a PooledConnection instance attached to this channel, then // close the channel directly. LOG.warn(msg + " But no PooledConnection attribute. So just closing Channel."); ctx.close(); } } private void flagCloseAndReleaseConnection(PooledConnection pooledConnection) { if (pooledConnection.isInPool()) { pooledConnection.closeAndRemoveFromPool(); } else { pooledConnection.flagShouldClose(); pooledConnection.release(); } } private static String getConnectionHeader(CompleteEvent completeEvt) { HttpResponse response = completeEvt.getResponse(); if (response != null) { return response.headers().get(HttpHeaderNames.CONNECTION); } return null; } }
922e39a60f72d492c2190547ea69133ba349cfd4
486
java
Java
lab-10/eregistrarwebapi/src/main/java/edu/miu/cs/cs425/lab10/eregistrarwebapi/config/AppConf.java
mikiyasbelhu/cs425-swe-202006
d33ecf0596942ffcb8c9039012b2c1d9491fdccd
[ "CC0-1.0" ]
1
2020-05-29T22:54:56.000Z
2020-05-29T22:54:56.000Z
lab-10/eregistrarwebapi/src/main/java/edu/miu/cs/cs425/lab10/eregistrarwebapi/config/AppConf.java
mikiyasbelhu/cs425-swe-202006
d33ecf0596942ffcb8c9039012b2c1d9491fdccd
[ "CC0-1.0" ]
null
null
null
lab-10/eregistrarwebapi/src/main/java/edu/miu/cs/cs425/lab10/eregistrarwebapi/config/AppConf.java
mikiyasbelhu/cs425-swe-202006
d33ecf0596942ffcb8c9039012b2c1d9491fdccd
[ "CC0-1.0" ]
null
null
null
34.714286
75
0.792181
994,674
package edu.miu.cs.cs425.lab10.eregistrarwebapi.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class AppConf implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("*").allowedMethods("*"); } }
922e39bb7fa9b3ec352a0d0910d8e95eb465484e
96,021
java
Java
core/src/test/java/org/elasticsearch/index/translog/TranslogTests.java
psiitoy/elasticsearch-2.1
86cbcb22bf6b88e3da8fd1b48ca593f2132e2829
[ "Apache-2.0" ]
1
2017-07-31T03:48:22.000Z
2017-07-31T03:48:22.000Z
core/src/test/java/org/elasticsearch/index/translog/TranslogTests.java
psiitoy/elasticsearch-2.1
86cbcb22bf6b88e3da8fd1b48ca593f2132e2829
[ "Apache-2.0" ]
null
null
null
core/src/test/java/org/elasticsearch/index/translog/TranslogTests.java
psiitoy/elasticsearch-2.1
86cbcb22bf6b88e3da8fd1b48ca593f2132e2829
[ "Apache-2.0" ]
null
null
null
46.885254
256
0.586257
994,675
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.translog; import com.carrotsearch.randomizedtesting.generators.RandomPicks; import org.apache.lucene.codecs.CodecUtil; import org.apache.lucene.index.Term; import org.apache.lucene.mockfile.FilterFileChannel; import org.apache.lucene.store.AlreadyClosedException; import org.apache.lucene.store.ByteArrayDataOutput; import org.apache.lucene.store.MockDirectoryWrapper; import org.apache.lucene.util.IOUtils; import org.apache.lucene.util.LineFileDocs; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util.TestUtil; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.Version; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.FileSystemUtils; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.common.util.concurrent.AbstractRunnable; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; import org.elasticsearch.index.Index; import org.elasticsearch.index.VersionType; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.test.ESTestCase; import org.hamcrest.Matchers; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.file.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.hamcrest.Matchers.*; /** * */ public class TranslogTests extends ESTestCase { private static final Pattern PARSE_LEGACY_ID_PATTERN = Pattern.compile("^" + Translog.TRANSLOG_FILE_PREFIX + "(\\d+)((\\.recovering))?$"); protected final ShardId shardId = new ShardId(new Index("index"), 1); protected Translog translog; protected Path translogDir; @Override protected void afterIfSuccessful() throws Exception { super.afterIfSuccessful(); if (translog.isOpen()) { if (translog.currentFileGeneration() > 1) { translog.commit(); assertFileDeleted(translog, translog.currentFileGeneration() - 1); } translog.close(); } assertFileIsPresent(translog, translog.currentFileGeneration()); IOUtils.rm(translog.location()); // delete all the locations } @Override @Before public void setUp() throws Exception { super.setUp(); // if a previous test failed we clean up things here translogDir = createTempDir(); translog = create(translogDir); } @Override @After public void tearDown() throws Exception { try { assertEquals("there are still open views", 0, translog.getNumOpenViews()); translog.close(); } finally { super.tearDown(); } } private Translog create(Path path) throws IOException { return new Translog(getTranslogConfig(path)); } protected TranslogConfig getTranslogConfig(Path path) { Settings build = Settings.settingsBuilder() .put(TranslogConfig.INDEX_TRANSLOG_FS_TYPE, TranslogWriter.Type.SIMPLE.name()) .build(); return new TranslogConfig(shardId, path, build, Translog.Durabilty.REQUEST, BigArrays.NON_RECYCLING_INSTANCE, null); } protected void addToTranslogAndList(Translog translog, ArrayList<Translog.Operation> list, Translog.Operation op) throws IOException { list.add(op); translog.add(op); } public void testIdParsingFromFile() { long id = randomIntBetween(0, Integer.MAX_VALUE); Path file = translogDir.resolve(Translog.TRANSLOG_FILE_PREFIX + id + ".tlog"); assertThat(Translog.parseIdFromFileName(file), equalTo(id)); id = randomIntBetween(0, Integer.MAX_VALUE); file = translogDir.resolve(Translog.TRANSLOG_FILE_PREFIX + id); try { Translog.parseIdFromFileName(file); fail("invalid pattern"); } catch (IllegalArgumentException ex) { // all good } file = translogDir.resolve(Translog.TRANSLOG_FILE_PREFIX + id + ".recovering"); try { Translog.parseIdFromFileName(file); fail("invalid pattern"); } catch (IllegalArgumentException ex) { // all good } file = translogDir.resolve(Translog.TRANSLOG_FILE_PREFIX + randomNonTranslogPatternString(1, 10) + id); try { Translog.parseIdFromFileName(file); fail("invalid pattern"); } catch (IllegalArgumentException ex) { // all good } file = translogDir.resolve(randomNonTranslogPatternString(1, Translog.TRANSLOG_FILE_PREFIX.length() - 1)); try { Translog.parseIdFromFileName(file); fail("invalid pattern"); } catch (IllegalArgumentException ex) { // all good } } private String randomNonTranslogPatternString(int min, int max) { String string; boolean validPathString; do { validPathString = false; string = randomRealisticUnicodeOfCodepointLength(randomIntBetween(min, max)); try { final Path resolved = translogDir.resolve(string); // some strings (like '/' , '..') do not refer to a file, which we this method should return validPathString = resolved.getFileName() != null; } catch (InvalidPathException ex) { // some FS don't like our random file names -- let's just skip these random choices } } while (Translog.PARSE_STRICT_ID_PATTERN.matcher(string).matches() || validPathString == false); return string; } @Test public void testRead() throws IOException { Translog.Location loc1 = translog.add(new Translog.Create("test", "1", new byte[]{1})); Translog.Location loc2 = translog.add(new Translog.Create("test", "2", new byte[]{2})); assertThat(translog.read(loc1).getSource().source.toBytesArray(), equalTo(new BytesArray(new byte[]{1}))); assertThat(translog.read(loc2).getSource().source.toBytesArray(), equalTo(new BytesArray(new byte[]{2}))); translog.sync(); assertThat(translog.read(loc1).getSource().source.toBytesArray(), equalTo(new BytesArray(new byte[]{1}))); assertThat(translog.read(loc2).getSource().source.toBytesArray(), equalTo(new BytesArray(new byte[]{2}))); Translog.Location loc3 = translog.add(new Translog.Create("test", "2", new byte[]{3})); assertThat(translog.read(loc3).getSource().source.toBytesArray(), equalTo(new BytesArray(new byte[]{3}))); translog.sync(); assertThat(translog.read(loc3).getSource().source.toBytesArray(), equalTo(new BytesArray(new byte[]{3}))); translog.prepareCommit(); assertThat(translog.read(loc3).getSource().source.toBytesArray(), equalTo(new BytesArray(new byte[]{3}))); translog.commit(); assertNull(translog.read(loc1)); assertNull(translog.read(loc2)); assertNull(translog.read(loc3)); try { translog.read(new Translog.Location(translog.currentFileGeneration() + 1, 17, 35)); fail("generation is greater than the current"); } catch (IllegalStateException ex) { // expected } } @Test public void testSimpleOperations() throws IOException { ArrayList<Translog.Operation> ops = new ArrayList<>(); Translog.Snapshot snapshot = translog.newSnapshot(); assertThat(snapshot, SnapshotMatchers.size(0)); snapshot.close(); addToTranslogAndList(translog, ops, new Translog.Create("test", "1", new byte[]{1})); snapshot = translog.newSnapshot(); assertThat(snapshot, SnapshotMatchers.equalsTo(ops)); assertThat(snapshot.estimatedTotalOperations(), equalTo(1)); snapshot.close(); addToTranslogAndList(translog, ops, new Translog.Index("test", "2", new byte[]{2})); snapshot = translog.newSnapshot(); assertThat(snapshot, SnapshotMatchers.equalsTo(ops)); assertThat(snapshot.estimatedTotalOperations(), equalTo(ops.size())); snapshot.close(); addToTranslogAndList(translog, ops, new Translog.Delete(newUid("3"))); snapshot = translog.newSnapshot(); assertThat(snapshot, SnapshotMatchers.equalsTo(ops)); assertThat(snapshot.estimatedTotalOperations(), equalTo(ops.size())); snapshot.close(); snapshot = translog.newSnapshot(); Translog.Create create = (Translog.Create) snapshot.next(); assertThat(create != null, equalTo(true)); assertThat(create.source().toBytes(), equalTo(new byte[]{1})); Translog.Index index = (Translog.Index) snapshot.next(); assertThat(index != null, equalTo(true)); assertThat(index.source().toBytes(), equalTo(new byte[]{2})); Translog.Delete delete = (Translog.Delete) snapshot.next(); assertThat(delete != null, equalTo(true)); assertThat(delete.uid(), equalTo(newUid("3"))); assertThat(snapshot.next(), equalTo(null)); snapshot.close(); long firstId = translog.currentFileGeneration(); translog.prepareCommit(); assertThat(translog.currentFileGeneration(), Matchers.not(equalTo(firstId))); snapshot = translog.newSnapshot(); assertThat(snapshot, SnapshotMatchers.equalsTo(ops)); assertThat(snapshot.estimatedTotalOperations(), equalTo(ops.size())); snapshot.close(); translog.commit(); snapshot = translog.newSnapshot(); assertThat(snapshot, SnapshotMatchers.size(0)); assertThat(snapshot.estimatedTotalOperations(), equalTo(0)); snapshot.close(); } protected TranslogStats stats() throws IOException { // force flushing and updating of stats translog.sync(); TranslogStats stats = translog.stats(); if (randomBoolean()) { BytesStreamOutput out = new BytesStreamOutput(); stats.writeTo(out); StreamInput in = StreamInput.wrap(out.bytes()); stats = new TranslogStats(); stats.readFrom(in); } return stats; } @Test public void testStats() throws IOException { final long firstOperationPosition = translog.getFirstOperationPosition(); TranslogStats stats = stats(); assertThat(stats.estimatedNumberOfOperations(), equalTo(0l)); long lastSize = stats.getTranslogSizeInBytes(); assertThat((int) firstOperationPosition, greaterThan(CodecUtil.headerLength(TranslogWriter.TRANSLOG_CODEC))); assertThat(lastSize, equalTo(firstOperationPosition)); TranslogStats total = new TranslogStats(); translog.add(new Translog.Create("test", "1", new byte[]{1})); stats = stats(); total.add(stats); assertThat(stats.estimatedNumberOfOperations(), equalTo(1l)); assertThat(stats.getTranslogSizeInBytes(), greaterThan(lastSize)); lastSize = stats.getTranslogSizeInBytes(); translog.add(new Translog.Index("test", "2", new byte[]{2})); stats = stats(); total.add(stats); assertThat(stats.estimatedNumberOfOperations(), equalTo(2l)); assertThat(stats.getTranslogSizeInBytes(), greaterThan(lastSize)); lastSize = stats.getTranslogSizeInBytes(); translog.add(new Translog.Delete(newUid("3"))); stats = stats(); total.add(stats); assertThat(stats.estimatedNumberOfOperations(), equalTo(3l)); assertThat(stats.getTranslogSizeInBytes(), greaterThan(lastSize)); translog.commit(); stats = stats(); total.add(stats); assertThat(stats.estimatedNumberOfOperations(), equalTo(0l)); assertThat(stats.getTranslogSizeInBytes(), equalTo(firstOperationPosition)); assertEquals(6, total.estimatedNumberOfOperations()); assertEquals(428, total.getTranslogSizeInBytes()); BytesStreamOutput out = new BytesStreamOutput(); total.writeTo(out); TranslogStats copy = new TranslogStats(); copy.readFrom(StreamInput.wrap(out.bytes())); assertEquals(6, copy.estimatedNumberOfOperations()); assertEquals(428, copy.getTranslogSizeInBytes()); assertEquals("\"translog\"{\n" + " \"operations\" : 6,\n" + " \"size_in_bytes\" : 428\n" + "}", copy.toString().trim()); try { new TranslogStats(1, -1); fail("must be positive"); } catch (IllegalArgumentException ex) { //all well } try { new TranslogStats(-1, 1); fail("must be positive"); } catch (IllegalArgumentException ex) { //all well } } public void testSnapshot() throws IOException { ArrayList<Translog.Operation> ops = new ArrayList<>(); Translog.Snapshot snapshot = translog.newSnapshot(); assertThat(snapshot, SnapshotMatchers.size(0)); snapshot.close(); addToTranslogAndList(translog, ops, new Translog.Create("test", "1", new byte[]{1})); snapshot = translog.newSnapshot(); assertThat(snapshot, SnapshotMatchers.equalsTo(ops)); assertThat(snapshot.estimatedTotalOperations(), equalTo(1)); snapshot.close(); snapshot = translog.newSnapshot(); assertThat(snapshot, SnapshotMatchers.equalsTo(ops)); assertThat(snapshot.estimatedTotalOperations(), equalTo(1)); // snapshot while another is open Translog.Snapshot snapshot1 = translog.newSnapshot(); assertThat(snapshot1, SnapshotMatchers.size(1)); assertThat(snapshot1.estimatedTotalOperations(), equalTo(1)); snapshot.close(); snapshot1.close(); } @Test public void testSnapshotWithNewTranslog() throws IOException { ArrayList<Translog.Operation> ops = new ArrayList<>(); Translog.Snapshot snapshot = translog.newSnapshot(); assertThat(snapshot, SnapshotMatchers.size(0)); snapshot.close(); addToTranslogAndList(translog, ops, new Translog.Create("test", "1", new byte[]{1})); Translog.Snapshot snapshot1 = translog.newSnapshot(); addToTranslogAndList(translog, ops, new Translog.Index("test", "2", new byte[]{2})); translog.prepareCommit(); addToTranslogAndList(translog, ops, new Translog.Index("test", "3", new byte[]{3})); Translog.Snapshot snapshot2 = translog.newSnapshot(); translog.commit(); assertThat(snapshot2, SnapshotMatchers.equalsTo(ops)); assertThat(snapshot2.estimatedTotalOperations(), equalTo(ops.size())); assertThat(snapshot1, SnapshotMatchers.equalsTo(ops.get(0))); snapshot1.close(); snapshot2.close(); } public void testSnapshotOnClosedTranslog() throws IOException { assertTrue(Files.exists(translogDir.resolve(translog.getFilename(1)))); translog.add(new Translog.Create("test", "1", new byte[]{1})); translog.close(); try { Translog.Snapshot snapshot = translog.newSnapshot(); fail("translog is closed"); } catch (AlreadyClosedException ex) { assertEquals(ex.getMessage(), "translog is already closed"); } } @Test public void deleteOnSnapshotRelease() throws Exception { ArrayList<Translog.Operation> firstOps = new ArrayList<>(); addToTranslogAndList(translog, firstOps, new Translog.Create("test", "1", new byte[]{1})); Translog.Snapshot firstSnapshot = translog.newSnapshot(); assertThat(firstSnapshot.estimatedTotalOperations(), equalTo(1)); translog.commit(); assertFileIsPresent(translog, 1); ArrayList<Translog.Operation> secOps = new ArrayList<>(); addToTranslogAndList(translog, secOps, new Translog.Index("test", "2", new byte[]{2})); assertThat(firstSnapshot.estimatedTotalOperations(), equalTo(1)); Translog.Snapshot secondSnapshot = translog.newSnapshot(); translog.add(new Translog.Index("test", "3", new byte[]{3})); assertThat(secondSnapshot, SnapshotMatchers.equalsTo(secOps)); assertThat(secondSnapshot.estimatedTotalOperations(), equalTo(1)); assertFileIsPresent(translog, 1); assertFileIsPresent(translog, 2); firstSnapshot.close(); assertFileDeleted(translog, 1); assertFileIsPresent(translog, 2); secondSnapshot.close(); assertFileIsPresent(translog, 2); // it's the current nothing should be deleted translog.commit(); assertFileIsPresent(translog, 3); // it's the current nothing should be deleted assertFileDeleted(translog, 2); } public void assertFileIsPresent(Translog translog, long id) { if (Files.exists(translogDir.resolve(translog.getFilename(id)))) { return; } fail(translog.getFilename(id) + " is not present in any location: " + translog.location()); } public void assertFileDeleted(Translog translog, long id) { assertFalse("translog [" + id + "] still exists", Files.exists(translog.location().resolve(translog.getFilename(id)))); } static class LocationOperation { final Translog.Operation operation; final Translog.Location location; public LocationOperation(Translog.Operation operation, Translog.Location location) { this.operation = operation; this.location = location; } } @Test public void testConcurrentWritesWithVaryingSize() throws Throwable { final int opsPerThread = randomIntBetween(10, 200); int threadCount = 2 + randomInt(5); logger.info("testing with [{}] threads, each doing [{}] ops", threadCount, opsPerThread); final BlockingQueue<LocationOperation> writtenOperations = new ArrayBlockingQueue<>(threadCount * opsPerThread); Thread[] threads = new Thread[threadCount]; final Throwable[] threadExceptions = new Throwable[threadCount]; final CountDownLatch downLatch = new CountDownLatch(1); for (int i = 0; i < threadCount; i++) { final int threadId = i; threads[i] = new TranslogThread(translog, downLatch, opsPerThread, threadId, writtenOperations, threadExceptions); threads[i].setDaemon(true); threads[i].start(); } downLatch.countDown(); for (int i = 0; i < threadCount; i++) { if (threadExceptions[i] != null) { throw threadExceptions[i]; } threads[i].join(60 * 1000); } for (LocationOperation locationOperation : writtenOperations) { Translog.Operation op = translog.read(locationOperation.location); Translog.Operation expectedOp = locationOperation.operation; assertEquals(expectedOp.opType(), op.opType()); switch (op.opType()) { case SAVE: Translog.Index indexOp = (Translog.Index) op; Translog.Index expIndexOp = (Translog.Index) expectedOp; assertEquals(expIndexOp.id(), indexOp.id()); assertEquals(expIndexOp.routing(), indexOp.routing()); assertEquals(expIndexOp.type(), indexOp.type()); assertEquals(expIndexOp.source(), indexOp.source()); assertEquals(expIndexOp.version(), indexOp.version()); assertEquals(expIndexOp.versionType(), indexOp.versionType()); break; case CREATE: Translog.Create createOp = (Translog.Create) op; Translog.Create expCreateOp = (Translog.Create) expectedOp; assertEquals(expCreateOp.id(), createOp.id()); assertEquals(expCreateOp.routing(), createOp.routing()); assertEquals(expCreateOp.type(), createOp.type()); assertEquals(expCreateOp.source(), createOp.source()); assertEquals(expCreateOp.version(), createOp.version()); assertEquals(expCreateOp.versionType(), createOp.versionType()); break; case DELETE: Translog.Delete delOp = (Translog.Delete) op; Translog.Delete expDelOp = (Translog.Delete) expectedOp; assertEquals(expDelOp.uid(), delOp.uid()); assertEquals(expDelOp.version(), delOp.version()); assertEquals(expDelOp.versionType(), delOp.versionType()); break; default: throw new ElasticsearchException("unsupported opType"); } } } @Test public void testTranslogChecksums() throws Exception { List<Translog.Location> locations = new ArrayList<>(); int translogOperations = randomIntBetween(10, 100); for (int op = 0; op < translogOperations; op++) { String ascii = randomAsciiOfLengthBetween(1, 50); locations.add(translog.add(new Translog.Create("test", "" + op, ascii.getBytes("UTF-8")))); } translog.sync(); corruptTranslogs(translogDir); AtomicInteger corruptionsCaught = new AtomicInteger(0); for (Translog.Location location : locations) { try { translog.read(location); } catch (TranslogCorruptedException e) { corruptionsCaught.incrementAndGet(); } } assertThat("at least one corruption was caused and caught", corruptionsCaught.get(), greaterThanOrEqualTo(1)); } @Test public void testTruncatedTranslogs() throws Exception { List<Translog.Location> locations = new ArrayList<>(); int translogOperations = randomIntBetween(10, 100); for (int op = 0; op < translogOperations; op++) { String ascii = randomAsciiOfLengthBetween(1, 50); locations.add(translog.add(new Translog.Create("test", "" + op, ascii.getBytes("UTF-8")))); } translog.sync(); truncateTranslogs(translogDir); AtomicInteger truncations = new AtomicInteger(0); for (Translog.Location location : locations) { try { translog.read(location); } catch (ElasticsearchException e) { if (e.getCause() instanceof EOFException) { truncations.incrementAndGet(); } else { throw e; } } } assertThat("at least one truncation was caused and caught", truncations.get(), greaterThanOrEqualTo(1)); } /** * Randomly truncate some bytes in the translog files */ private void truncateTranslogs(Path directory) throws Exception { Path[] files = FileSystemUtils.files(directory, "translog-*"); for (Path file : files) { try (FileChannel f = FileChannel.open(file, StandardOpenOption.READ, StandardOpenOption.WRITE)) { long prevSize = f.size(); long newSize = prevSize - randomIntBetween(1, (int) prevSize / 2); logger.info("--> truncating {}, prev: {}, now: {}", file, prevSize, newSize); f.truncate(newSize); } } } /** * Randomly overwrite some bytes in the translog files */ private void corruptTranslogs(Path directory) throws Exception { Path[] files = FileSystemUtils.files(directory, "translog-*"); for (Path file : files) { logger.info("--> corrupting {}...", file); FileChannel f = FileChannel.open(file, StandardOpenOption.READ, StandardOpenOption.WRITE); int corruptions = scaledRandomIntBetween(10, 50); for (int i = 0; i < corruptions; i++) { // note: with the current logic, this will sometimes be a no-op long pos = randomIntBetween(0, (int) f.size()); ByteBuffer junk = ByteBuffer.wrap(new byte[]{randomByte()}); f.write(junk, pos); } f.close(); } } private Term newUid(String id) { return new Term("_uid", id); } @Test public void testVerifyTranslogIsNotDeleted() throws IOException { assertFileIsPresent(translog, 1); translog.add(new Translog.Create("test", "1", new byte[]{1})); Translog.Snapshot snapshot = translog.newSnapshot(); assertThat(snapshot, SnapshotMatchers.size(1)); assertFileIsPresent(translog, 1); assertThat(snapshot.estimatedTotalOperations(), equalTo(1)); if (randomBoolean()) { translog.close(); snapshot.close(); } else { snapshot.close(); translog.close(); } assertFileIsPresent(translog, 1); } /** Tests that concurrent readers and writes maintain view and snapshot semantics */ @Test public void testConcurrentWriteViewsAndSnapshot() throws Throwable { final Thread[] writers = new Thread[randomIntBetween(1, 10)]; final Thread[] readers = new Thread[randomIntBetween(1, 10)]; final int flushEveryOps = randomIntBetween(5, 100); // used to notify main thread that so many operations have been written so it can simulate a flush final AtomicReference<CountDownLatch> writtenOpsLatch = new AtomicReference<>(new CountDownLatch(0)); final AtomicLong idGenerator = new AtomicLong(); final CyclicBarrier barrier = new CyclicBarrier(writers.length + readers.length + 1); // a map of all written ops and their returned location. final Map<Translog.Operation, Translog.Location> writtenOps = ConcurrentCollections.newConcurrentMap(); // a signal for all threads to stop final AtomicBoolean run = new AtomicBoolean(true); // any errors on threads final List<Throwable> errors = new CopyOnWriteArrayList<>(); logger.debug("using [{}] readers. [{}] writers. flushing every ~[{}] ops.", readers.length, writers.length, flushEveryOps); for (int i = 0; i < writers.length; i++) { final String threadId = "writer_" + i; writers[i] = new Thread(new AbstractRunnable() { @Override public void doRun() throws BrokenBarrierException, InterruptedException, IOException { barrier.await(); int counter = 0; while (run.get()) { long id = idGenerator.incrementAndGet(); final Translog.Operation op; switch (Translog.Operation.Type.values()[((int) (id % Translog.Operation.Type.values().length))]) { case CREATE: op = new Translog.Create("type", "" + id, new byte[]{(byte) id}); break; case SAVE: op = new Translog.Index("type", "" + id, new byte[]{(byte) id}); break; case DELETE: op = new Translog.Delete(newUid("" + id)); break; case DELETE_BY_QUERY: // deprecated continue; default: throw new ElasticsearchException("unknown type"); } Translog.Location location = translog.add(op); Translog.Location existing = writtenOps.put(op, location); if (existing != null) { fail("duplicate op [" + op + "], old entry at " + location); } writtenOpsLatch.get().countDown(); counter++; } logger.debug("--> [{}] done. wrote [{}] ops.", threadId, counter); } @Override public void onFailure(Throwable t) { logger.error("--> writer [{}] had an error", t, threadId); errors.add(t); } }, threadId); writers[i].start(); } for (int i = 0; i < readers.length; i++) { final String threadId = "reader_" + i; readers[i] = new Thread(new AbstractRunnable() { Translog.View view = null; Set<Translog.Operation> writtenOpsAtView; @Override public void onFailure(Throwable t) { logger.error("--> reader [{}] had an error", t, threadId); errors.add(t); closeView(); } void closeView() { if (view != null) { view.close(); } } void newView() { closeView(); view = translog.newView(); // captures the currently written ops so we know what to expect from the view writtenOpsAtView = new HashSet<>(writtenOps.keySet()); logger.debug("--> [{}] opened view from [{}]", threadId, view.minTranslogGeneration()); } @Override protected void doRun() throws Exception { barrier.await(); int iter = 0; while (run.get()) { if (iter++ % 10 == 0) { newView(); } // captures al views that are written since the view was created (with a small caveat see bellow) // these are what we expect the snapshot to return (and potentially some more). Set<Translog.Operation> expectedOps = new HashSet<>(writtenOps.keySet()); expectedOps.removeAll(writtenOpsAtView); try (Translog.Snapshot snapshot = view.snapshot()) { Translog.Operation op; while ((op = snapshot.next()) != null) { expectedOps.remove(op); } } if (expectedOps.isEmpty() == false) { StringBuilder missed = new StringBuilder("missed ").append(expectedOps.size()).append(" operations"); boolean failed = false; for (Translog.Operation op : expectedOps) { final Translog.Location loc = writtenOps.get(op); if (loc.generation < view.minTranslogGeneration()) { // writtenOps is only updated after the op was written to the translog. This mean // that ops written to the translog before the view was taken (and will be missing from the view) // may yet be available in writtenOpsAtView, meaning we will erroneously expect them continue; } failed = true; missed.append("\n --> [").append(op).append("] written at ").append(loc); } if (failed) { fail(missed.toString()); } } // slow down things a bit and spread out testing.. writtenOpsLatch.get().await(200, TimeUnit.MILLISECONDS); } closeView(); logger.debug("--> [{}] done. tested [{}] snapshots", threadId, iter); } }, threadId); readers[i].start(); } barrier.await(); try { for (int iterations = scaledRandomIntBetween(10, 200); iterations > 0 && errors.isEmpty(); iterations--) { writtenOpsLatch.set(new CountDownLatch(flushEveryOps)); while (writtenOpsLatch.get().await(200, TimeUnit.MILLISECONDS) == false) { if (errors.size() > 0) { break; } } translog.commit(); } } finally { run.set(false); logger.debug("--> waiting for threads to stop"); for (Thread thread : writers) { thread.join(); } for (Thread thread : readers) { thread.join(); } if (errors.size() > 0) { Throwable e = errors.get(0); for (Throwable suppress : errors.subList(1, errors.size())) { e.addSuppressed(suppress); } throw e; } logger.info("--> test done. total ops written [{}]", writtenOps.size()); } } public void testSyncUpTo() throws IOException { int translogOperations = randomIntBetween(10, 100); int count = 0; for (int op = 0; op < translogOperations; op++) { final Translog.Location location = translog.add(new Translog.Create("test", "" + op, Integer.toString(++count).getBytes(Charset.forName("UTF-8")))); if (randomBoolean()) { assertTrue("at least one operation pending", translog.syncNeeded()); assertTrue("this operation has not been synced", translog.ensureSynced(location)); assertFalse("the last call to ensureSycned synced all previous ops", translog.syncNeeded()); // we are the last location so everything should be synced translog.add(new Translog.Create("test", "" + op, Integer.toString(++count).getBytes(Charset.forName("UTF-8")))); assertTrue("one pending operation", translog.syncNeeded()); assertFalse("this op has been synced before", translog.ensureSynced(location)); // not syncing now assertTrue("we only synced a previous operation yet", translog.syncNeeded()); } if (rarely()) { translog.commit(); assertFalse("location is from a previous translog - already synced", translog.ensureSynced(location)); // not syncing now assertFalse("no sync needed since no operations in current translog", translog.syncNeeded()); } if (randomBoolean()) { translog.sync(); assertFalse("translog has been synced already", translog.ensureSynced(location)); } } } public void testLocationComparison() throws IOException { List<Translog.Location> locations = new ArrayList<>(); int translogOperations = randomIntBetween(10, 100); int count = 0; for (int op = 0; op < translogOperations; op++) { locations.add(translog.add(new Translog.Create("test", "" + op, Integer.toString(++count).getBytes(Charset.forName("UTF-8"))))); if (rarely() && translogOperations > op+1) { translog.commit(); } } Collections.shuffle(locations, random()); Translog.Location max = locations.get(0); for (Translog.Location location : locations) { max = max(max, location); } assertEquals(max.generation, translog.currentFileGeneration()); final Translog.Operation read = translog.read(max); assertEquals(read.getSource().source.toUtf8(), Integer.toString(count)); } public static Translog.Location max(Translog.Location a, Translog.Location b) { if (a.compareTo(b) > 0) { return a; } return b; } public void testBasicCheckpoint() throws IOException { List<Translog.Location> locations = new ArrayList<>(); int translogOperations = randomIntBetween(10, 100); int lastSynced = -1; for (int op = 0; op < translogOperations; op++) { locations.add(translog.add(new Translog.Create("test", "" + op, Integer.toString(op).getBytes(Charset.forName("UTF-8"))))); if (frequently()) { translog.sync(); lastSynced = op; } } assertEquals(translogOperations, translog.totalOperations()); final Translog.Location lastLocation = translog.add(new Translog.Create("test", "" + translogOperations, Integer.toString(translogOperations).getBytes(Charset.forName("UTF-8")))); final Checkpoint checkpoint = Checkpoint.read(translog.location().resolve(Translog.CHECKPOINT_FILE_NAME)); try (final ImmutableTranslogReader reader = translog.openReader(translog.location().resolve(translog.getFilename(translog.currentFileGeneration())), checkpoint)) { assertEquals(lastSynced + 1, reader.totalOperations()); for (int op = 0; op < translogOperations; op++) { Translog.Location location = locations.get(op); if (op <= lastSynced) { final Translog.Operation read = reader.read(location); assertEquals(Integer.toString(op), read.getSource().source.toUtf8()); } else { try { reader.read(location); fail("read past checkpoint"); } catch (EOFException ex) { } } } try { reader.read(lastLocation); fail("read past checkpoint"); } catch (EOFException ex) { } } assertEquals(translogOperations + 1, translog.totalOperations()); translog.close(); } public void testTranslogWriter() throws IOException { final TranslogWriter writer = translog.createWriter(0); final int numOps = randomIntBetween(10, 100); byte[] bytes = new byte[4]; ByteArrayDataOutput out = new ByteArrayDataOutput(bytes); for (int i = 0; i < numOps; i++) { out.reset(bytes); out.writeInt(i); writer.add(new BytesArray(bytes)); } writer.sync(); final TranslogReader reader = randomBoolean() ? writer : translog.openReader(writer.path(), Checkpoint.read(translog.location().resolve(Translog.CHECKPOINT_FILE_NAME))); for (int i = 0; i < numOps; i++) { ByteBuffer buffer = ByteBuffer.allocate(4); reader.readBytes(buffer, reader.getFirstOperationOffset() + 4*i); buffer.flip(); final int value = buffer.getInt(); assertEquals(i, value); } out.reset(bytes); out.writeInt(2048); writer.add(new BytesArray(bytes)); if (reader instanceof ImmutableTranslogReader) { ByteBuffer buffer = ByteBuffer.allocate(4); try { reader.readBytes(buffer, reader.getFirstOperationOffset() + 4 * numOps); fail("read past EOF?"); } catch (EOFException ex) { // expected } } else { // live reader! ByteBuffer buffer = ByteBuffer.allocate(4); final long pos = reader.getFirstOperationOffset() + 4 * numOps; reader.readBytes(buffer, pos); buffer.flip(); final int value = buffer.getInt(); assertEquals(2048, value); } IOUtils.close(writer, reader); } public void testBasicRecovery() throws IOException { List<Translog.Location> locations = new ArrayList<>(); int translogOperations = randomIntBetween(10, 100); Translog.TranslogGeneration translogGeneration = null; int minUncommittedOp = -1; final boolean commitOften = randomBoolean(); for (int op = 0; op < translogOperations; op++) { locations.add(translog.add(new Translog.Create("test", "" + op, Integer.toString(op).getBytes(Charset.forName("UTF-8"))))); final boolean commit = commitOften ? frequently() : rarely(); if (commit && op < translogOperations-1) { translog.commit(); minUncommittedOp = op+1; translogGeneration = translog.getGeneration(); } } translog.sync(); TranslogConfig config = translog.getConfig(); translog.close(); config.setTranslogGeneration(translogGeneration); translog = new Translog(config); if (translogGeneration == null) { assertEquals(0, translog.stats().estimatedNumberOfOperations()); assertEquals(1, translog.currentFileGeneration()); assertFalse(translog.syncNeeded()); try (Translog.Snapshot snapshot = translog.newSnapshot()) { assertNull(snapshot.next()); } } else { assertEquals("lastCommitted must be 1 less than current", translogGeneration.translogFileGeneration + 1, translog.currentFileGeneration()); assertFalse(translog.syncNeeded()); try (Translog.Snapshot snapshot = translog.newSnapshot()) { for (int i = minUncommittedOp; i < translogOperations; i++) { assertEquals("expected operation" + i + " to be in the previous translog but wasn't", translog.currentFileGeneration() - 1, locations.get(i).generation); Translog.Operation next = snapshot.next(); assertNotNull("operation " + i + " must be non-null", next); assertEquals(i, Integer.parseInt(next.getSource().source.toUtf8())); } } } } public void testRecoveryUncommitted() throws IOException { List<Translog.Location> locations = new ArrayList<>(); int translogOperations = randomIntBetween(10, 100); final int prepareOp = randomIntBetween(0, translogOperations-1); Translog.TranslogGeneration translogGeneration = null; final boolean sync = randomBoolean(); for (int op = 0; op < translogOperations; op++) { locations.add(translog.add(new Translog.Create("test", "" + op, Integer.toString(op).getBytes(Charset.forName("UTF-8"))))); if (op == prepareOp) { translogGeneration = translog.getGeneration(); translog.prepareCommit(); assertEquals("expected this to be the first commit", 1l, translogGeneration.translogFileGeneration); assertNotNull(translogGeneration.translogUUID); } } if (sync) { translog.sync(); } // we intentionally don't close the tlog that is in the prepareCommit stage since we try to recovery the uncommitted // translog here as well. TranslogConfig config = translog.getConfig(); config.setTranslogGeneration(translogGeneration); try (Translog translog = new Translog(config)) { assertNotNull(translogGeneration); assertEquals("lastCommitted must be 2 less than current - we never finished the commit", translogGeneration.translogFileGeneration + 2, translog.currentFileGeneration()); assertFalse(translog.syncNeeded()); try (Translog.Snapshot snapshot = translog.newSnapshot()) { int upTo = sync ? translogOperations : prepareOp; for (int i = 0; i < upTo; i++) { Translog.Operation next = snapshot.next(); assertNotNull("operation " + i + " must be non-null synced: " + sync, next); assertEquals("payload missmatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.toUtf8())); } } } if (randomBoolean()) { // recover twice try (Translog translog = new Translog(config)) { assertNotNull(translogGeneration); assertEquals("lastCommitted must be 3 less than current - we never finished the commit and run recovery twice", translogGeneration.translogFileGeneration + 3, translog.currentFileGeneration()); assertFalse(translog.syncNeeded()); try (Translog.Snapshot snapshot = translog.newSnapshot()) { int upTo = sync ? translogOperations : prepareOp; for (int i = 0; i < upTo; i++) { Translog.Operation next = snapshot.next(); assertNotNull("operation " + i + " must be non-null synced: " + sync, next); assertEquals("payload missmatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.toUtf8())); } } } } } public void testRecoveryUncommittedFileExists() throws IOException { List<Translog.Location> locations = new ArrayList<>(); int translogOperations = randomIntBetween(10, 100); final int prepareOp = randomIntBetween(0, translogOperations-1); Translog.TranslogGeneration translogGeneration = null; final boolean sync = randomBoolean(); for (int op = 0; op < translogOperations; op++) { locations.add(translog.add(new Translog.Index("test", "" + op, Integer.toString(op).getBytes(Charset.forName("UTF-8"))))); if (op == prepareOp) { translogGeneration = translog.getGeneration(); translog.prepareCommit(); assertEquals("expected this to be the first commit", 1l, translogGeneration.translogFileGeneration); assertNotNull(translogGeneration.translogUUID); } } if (sync) { translog.sync(); } // we intentionally don't close the tlog that is in the prepareCommit stage since we try to recovery the uncommitted // translog here as well. TranslogConfig config = translog.getConfig(); config.setTranslogGeneration(translogGeneration); Path ckp = config.getTranslogPath().resolve(Translog.CHECKPOINT_FILE_NAME); Checkpoint read = Checkpoint.read(ckp); Files.copy(ckp, config.getTranslogPath().resolve(Translog.getCommitCheckpointFileName(read.generation))); try (Translog translog = new Translog(config)) { assertNotNull(translogGeneration); assertEquals("lastCommitted must be 2 less than current - we never finished the commit", translogGeneration.translogFileGeneration + 2, translog.currentFileGeneration()); assertFalse(translog.syncNeeded()); try (Translog.Snapshot snapshot = translog.newSnapshot()) { int upTo = sync ? translogOperations : prepareOp; for (int i = 0; i < upTo; i++) { Translog.Operation next = snapshot.next(); assertNotNull("operation " + i + " must be non-null synced: " + sync, next); assertEquals("payload missmatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.toUtf8())); } } } if (randomBoolean()) { // recover twice try (Translog translog = new Translog(config)) { assertNotNull(translogGeneration); assertEquals("lastCommitted must be 3 less than current - we never finished the commit and run recovery twice", translogGeneration.translogFileGeneration + 3, translog.currentFileGeneration()); assertFalse(translog.syncNeeded()); try (Translog.Snapshot snapshot = translog.newSnapshot()) { int upTo = sync ? translogOperations : prepareOp; for (int i = 0; i < upTo; i++) { Translog.Operation next = snapshot.next(); assertNotNull("operation " + i + " must be non-null synced: " + sync, next); assertEquals("payload missmatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.toUtf8())); } } } } } public void testRecoveryUncommittedCorryptedCheckpoint() throws IOException { List<Translog.Location> locations = new ArrayList<>(); int translogOperations = 100; final int prepareOp = 44; Translog.TranslogGeneration translogGeneration = null; final boolean sync = randomBoolean(); for (int op = 0; op < translogOperations; op++) { locations.add(translog.add(new Translog.Index("test", "" + op, Integer.toString(op).getBytes(Charset.forName("UTF-8"))))); if (op == prepareOp) { translogGeneration = translog.getGeneration(); translog.prepareCommit(); assertEquals("expected this to be the first commit", 1l, translogGeneration.translogFileGeneration); assertNotNull(translogGeneration.translogUUID); } } translog.sync(); // we intentionally don't close the tlog that is in the prepareCommit stage since we try to recovery the uncommitted // translog here as well. TranslogConfig config = translog.getConfig(); config.setTranslogGeneration(translogGeneration); Path ckp = config.getTranslogPath().resolve(Translog.CHECKPOINT_FILE_NAME); Checkpoint read = Checkpoint.read(ckp); Checkpoint corrupted = new Checkpoint(0,0,0); Checkpoint.write(config.getTranslogPath().resolve(Translog.getCommitCheckpointFileName(read.generation)), corrupted, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW); try (Translog translog = new Translog(config)) { fail("corrupted"); } catch (IllegalStateException ex) { assertEquals(ex.getMessage(), "Checkpoint file translog-2.ckp already exists but has corrupted content expected: Checkpoint{offset=2683, numOps=55, translogFileGeneration= 2} but got: Checkpoint{offset=0, numOps=0, translogFileGeneration= 0}"); } Checkpoint.write(config.getTranslogPath().resolve(Translog.getCommitCheckpointFileName(read.generation)), read, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); try (Translog translog = new Translog(config)) { assertNotNull(translogGeneration); assertEquals("lastCommitted must be 2 less than current - we never finished the commit", translogGeneration.translogFileGeneration + 2, translog.currentFileGeneration()); assertFalse(translog.syncNeeded()); try (Translog.Snapshot snapshot = translog.newSnapshot()) { int upTo = sync ? translogOperations : prepareOp; for (int i = 0; i < upTo; i++) { Translog.Operation next = snapshot.next(); assertNotNull("operation " + i + " must be non-null synced: " + sync, next); assertEquals("payload missmatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.toUtf8())); } } } } public void testSnapshotFromStreamInput() throws IOException { BytesStreamOutput out = new BytesStreamOutput(); List<Translog.Operation> ops = new ArrayList<>(); int translogOperations = randomIntBetween(10, 100); for (int op = 0; op < translogOperations; op++) { Translog.Create test = new Translog.Create("test", "" + op, Integer.toString(op).getBytes(Charset.forName("UTF-8"))); ops.add(test); } Translog.writeOperations(out, ops); final List<Translog.Operation> readOperations = Translog.readOperations(StreamInput.wrap(out.bytes())); assertEquals(ops.size(), readOperations.size()); assertEquals(ops, readOperations); } public void testLocationHashCodeEquals() throws IOException { List<Translog.Location> locations = new ArrayList<>(); List<Translog.Location> locations2 = new ArrayList<>(); int translogOperations = randomIntBetween(10, 100); try(Translog translog2 = create(createTempDir())) { for (int op = 0; op < translogOperations; op++) { locations.add(translog.add(new Translog.Create("test", "" + op, Integer.toString(op).getBytes(Charset.forName("UTF-8"))))); locations2.add(translog2.add(new Translog.Create("test", "" + op, Integer.toString(op).getBytes(Charset.forName("UTF-8"))))); } int iters = randomIntBetween(10, 100); for (int i = 0; i < iters; i++) { Translog.Location location = RandomPicks.randomFrom(random(), locations); for (Translog.Location loc : locations) { if (loc == location) { assertTrue(loc.equals(location)); assertEquals(loc.hashCode(), location.hashCode()); } else { assertFalse(loc.equals(location)); } } for (int j = 0; j < translogOperations; j++) { assertTrue(locations.get(j).equals(locations2.get(j))); assertEquals(locations.get(j).hashCode(), locations2.get(j).hashCode()); } } } } public void testOpenForeignTranslog() throws IOException { List<Translog.Location> locations = new ArrayList<>(); int translogOperations = randomIntBetween(1, 10); int firstUncommitted = 0; for (int op = 0; op < translogOperations; op++) { locations.add(translog.add(new Translog.Create("test", "" + op, Integer.toString(op).getBytes(Charset.forName("UTF-8"))))); if (randomBoolean()) { translog.commit(); firstUncommitted = op + 1; } } TranslogConfig config = translog.getConfig(); Translog.TranslogGeneration translogGeneration = translog.getGeneration(); translog.close(); config.setTranslogGeneration(new Translog.TranslogGeneration(randomRealisticUnicodeOfCodepointLengthBetween(1, translogGeneration.translogUUID.length()),translogGeneration.translogFileGeneration)); try { new Translog(config); fail("translog doesn't belong to this UUID"); } catch (TranslogCorruptedException ex) { } config.setTranslogGeneration(translogGeneration); this.translog = new Translog(config); try (Translog.Snapshot snapshot = this.translog.newSnapshot()) { for (int i = firstUncommitted; i < translogOperations; i++) { Translog.Operation next = snapshot.next(); assertNotNull("" + i, next); assertEquals(Integer.parseInt(next.getSource().source.toUtf8()), i); } assertNull(snapshot.next()); } } public void testUpgradeOldTranslogFiles() throws IOException { List<Path> indexes = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(getBwcIndicesPath(), "index-*.zip")) { for (Path path : stream) { indexes.add(path); } } TranslogConfig config = this.translog.getConfig(); Translog.TranslogGeneration gen = translog.getGeneration(); this.translog.close(); try { Translog.upgradeLegacyTranslog(logger, translog.getConfig()); fail("no generation set"); } catch (IllegalArgumentException ex) { } translog.getConfig().setTranslogGeneration(gen); try { Translog.upgradeLegacyTranslog(logger, translog.getConfig()); fail("already upgraded generation set"); } catch (IllegalArgumentException ex) { } for (Path indexFile : indexes) { final String indexName = indexFile.getFileName().toString().replace(".zip", "").toLowerCase(Locale.ROOT); Version version = Version.fromString(indexName.replace("index-", "")); if (version.onOrAfter(Version.V_2_0_0_beta1)) { continue; } Path unzipDir = createTempDir(); Path unzipDataDir = unzipDir.resolve("data"); // decompress the index try (InputStream stream = Files.newInputStream(indexFile)) { TestUtil.unzip(stream, unzipDir); } // check it is unique assertTrue(Files.exists(unzipDataDir)); Path[] list = FileSystemUtils.files(unzipDataDir); if (list.length != 1) { throw new IllegalStateException("Backwards index must contain exactly one cluster but was " + list.length); } // the bwc scripts packs the indices under this path Path src = list[0].resolve("nodes/0/indices/" + indexName); Path translog = list[0].resolve("nodes/0/indices/" + indexName).resolve("0").resolve("translog"); assertTrue("[" + indexFile + "] missing index dir: " + src.toString(), Files.exists(src)); assertTrue("[" + indexFile + "] missing translog dir: " + translog.toString(), Files.exists(translog)); Path[] tlogFiles = FileSystemUtils.files(translog); assertEquals(tlogFiles.length, 1); final long size = Files.size(tlogFiles[0]); final long generation = parseLegacyTranslogFile(tlogFiles[0]); assertTrue(generation >= 1); logger.info("upgrading index {} file: {} size: {}", indexName, tlogFiles[0].getFileName(), size); TranslogConfig upgradeConfig = new TranslogConfig(config.getShardId(), translog, config.getIndexSettings(), config.getDurabilty(), config.getBigArrays(), config.getThreadPool()); upgradeConfig.setTranslogGeneration(new Translog.TranslogGeneration(null, generation)); Translog.upgradeLegacyTranslog(logger, upgradeConfig); try (Translog upgraded = new Translog(upgradeConfig)) { assertEquals(generation + 1, upgraded.getGeneration().translogFileGeneration); assertEquals(upgraded.getRecoveredReaders().size(), 1); final long headerSize; if (version.before(Version.V_1_4_0_Beta1)) { assertTrue(upgraded.getRecoveredReaders().get(0).getClass().toString(), upgraded.getRecoveredReaders().get(0).getClass() == LegacyTranslogReader.class); headerSize = 0; } else { assertTrue(upgraded.getRecoveredReaders().get(0).getClass().toString(), upgraded.getRecoveredReaders().get(0).getClass() == LegacyTranslogReaderBase.class); headerSize = CodecUtil.headerLength(TranslogWriter.TRANSLOG_CODEC); } List<Translog.Operation> operations = new ArrayList<>(); try (Translog.Snapshot snapshot = upgraded.newSnapshot()) { Translog.Operation op = null; while ((op = snapshot.next()) != null) { operations.add(op); } } if (size > headerSize) { assertFalse(operations.toString(), operations.isEmpty()); } else { assertTrue(operations.toString(), operations.isEmpty()); } } } } /** * this tests a set of files that has some of the operations flushed with a buffered translog such that tlogs are truncated. * 3 of the 6 files are created with ES 1.3 and the rest is created wiht ES 1.4 such that both the checksummed as well as the * super old version of the translog without a header is tested. */ public void testOpenAndReadTruncatedLegacyTranslogs() throws IOException { Path zip = getDataPath("/org/elasticsearch/index/translog/legacy_translogs.zip"); Path unzipDir = createTempDir(); try (InputStream stream = Files.newInputStream(zip)) { TestUtil.unzip(stream, unzipDir); } TranslogConfig config = this.translog.getConfig(); int count = 0; try (DirectoryStream<Path> stream = Files.newDirectoryStream(unzipDir)) { for (Path legacyTranslog : stream) { logger.debug("upgrading {} ", legacyTranslog.getFileName()); Path directory = legacyTranslog.resolveSibling("translog_" + count++); Files.createDirectories(directory); Files.copy(legacyTranslog, directory.resolve(legacyTranslog.getFileName())); TranslogConfig upgradeConfig = new TranslogConfig(config.getShardId(), directory, config.getIndexSettings(), config.getDurabilty(), config.getBigArrays(), config.getThreadPool()); try { Translog.upgradeLegacyTranslog(logger, upgradeConfig); fail("no generation set"); } catch (IllegalArgumentException ex) { // expected } long generation = parseLegacyTranslogFile(legacyTranslog); upgradeConfig.setTranslogGeneration(new Translog.TranslogGeneration(null, generation)); Translog.upgradeLegacyTranslog(logger, upgradeConfig); try (Translog tlog = new Translog(upgradeConfig)) { List<Translog.Operation> operations = new ArrayList<>(); try (Translog.Snapshot snapshot = tlog.newSnapshot()) { Translog.Operation op = null; while ((op = snapshot.next()) != null) { operations.add(op); } } logger.debug("num ops recovered: {} for file {} ", operations.size(), legacyTranslog.getFileName()); assertFalse(operations.isEmpty()); } } } } public static long parseLegacyTranslogFile(Path translogFile) { final String fileName = translogFile.getFileName().toString(); final Matcher matcher = PARSE_LEGACY_ID_PATTERN.matcher(fileName); if (matcher.matches()) { try { return Long.parseLong(matcher.group(1)); } catch (NumberFormatException e) { throw new IllegalStateException("number formatting issue in a file that passed PARSE_STRICT_ID_PATTERN: " + fileName + "]", e); } } throw new IllegalArgumentException("can't parse id from file: " + fileName); } public void testFailOnClosedWrite() throws IOException { translog.add(new Translog.Index("test", "1", Integer.toString(1).getBytes(Charset.forName("UTF-8")))); translog.close(); try { translog.add(new Translog.Index("test", "1", Integer.toString(1).getBytes(Charset.forName("UTF-8")))); fail("closed"); } catch (AlreadyClosedException ex) { // all is welll } } public void testCloseConcurrently() throws Throwable { final int opsPerThread = randomIntBetween(10, 200); int threadCount = 2 + randomInt(5); logger.info("testing with [{}] threads, each doing [{}] ops", threadCount, opsPerThread); final BlockingQueue<LocationOperation> writtenOperations = new ArrayBlockingQueue<>(threadCount * opsPerThread); Thread[] threads = new Thread[threadCount]; final Throwable[] threadExceptions = new Throwable[threadCount]; final CountDownLatch downLatch = new CountDownLatch(1); for (int i = 0; i < threadCount; i++) { final int threadId = i; threads[i] = new TranslogThread(translog, downLatch, opsPerThread, threadId, writtenOperations, threadExceptions); threads[i].setDaemon(true); threads[i].start(); } downLatch.countDown(); translog.close(); for (int i = 0; i < threadCount; i++) { if (threadExceptions[i] != null) { if ((threadExceptions[i] instanceof AlreadyClosedException) == false) { throw threadExceptions[i]; } } threads[i].join(60 * 1000); } } private static class TranslogThread extends Thread { private final CountDownLatch downLatch; private final int opsPerThread; private final int threadId; private final Collection<LocationOperation> writtenOperations; private final Throwable[] threadExceptions; private final Translog translog; public TranslogThread(Translog translog, CountDownLatch downLatch, int opsPerThread, int threadId, Collection<LocationOperation> writtenOperations, Throwable[] threadExceptions) { this.translog = translog; this.downLatch = downLatch; this.opsPerThread = opsPerThread; this.threadId = threadId; this.writtenOperations = writtenOperations; this.threadExceptions = threadExceptions; } @Override public void run() { try { downLatch.await(); for (int opCount = 0; opCount < opsPerThread; opCount++) { Translog.Operation op; switch (randomFrom(Translog.Operation.Type.values())) { case CREATE: op = new Translog.Create("test", threadId + "_" + opCount, randomUnicodeOfLengthBetween(1, 20 * 1024).getBytes("UTF-8")); break; case SAVE: op = new Translog.Index("test", threadId + "_" + opCount, randomUnicodeOfLengthBetween(1, 20 * 1024).getBytes("UTF-8")); break; case DELETE: op = new Translog.Delete(new Term("_uid", threadId + "_" + opCount), 1 + randomInt(100000), randomFrom(VersionType.values())); break; case DELETE_BY_QUERY: // deprecated continue; default: throw new ElasticsearchException("not supported op type"); } Translog.Location loc = add(op); writtenOperations.add(new LocationOperation(op, loc)); afterAdd(); } } catch (Throwable t) { threadExceptions[threadId] = t; } } protected Translog.Location add(Translog.Operation op) throws IOException { return translog.add(op); } protected void afterAdd() throws IOException {} } public void testFailFlush() throws IOException { Path tempDir = createTempDir(); final FailSwitch fail = new FailSwitch(); TranslogConfig config = getTranslogConfig(tempDir); Translog translog = getFailableTranslog(fail, config); List<Translog.Location> locations = new ArrayList<>(); int opsSynced = 0; boolean failed = false; while(failed == false) { try { locations.add(translog.add(new Translog.Index("test", "" + opsSynced, Integer.toString(opsSynced).getBytes(Charset.forName("UTF-8"))))); translog.sync(); opsSynced++; } catch (MockDirectoryWrapper.FakeIOException ex) { failed = true; assertFalse(translog.isOpen()); } catch (IOException ex) { failed = true; assertFalse(translog.isOpen()); assertEquals("__FAKE__ no space left on device", ex.getMessage()); } if (randomBoolean()) { fail.failAlways(); } else { fail.failNever(); } } fail.failNever(); if (randomBoolean()) { try { locations.add(translog.add(new Translog.Index("test", "" + opsSynced, Integer.toString(opsSynced).getBytes(Charset.forName("UTF-8"))))); fail("we are already closed"); } catch (AlreadyClosedException ex) { assertNotNull(ex.getCause()); if (ex.getCause() instanceof MockDirectoryWrapper.FakeIOException) { assertNull(ex.getCause().getMessage()); } else { assertEquals(ex.getCause().getMessage(), "__FAKE__ no space left on device"); } } } Translog.TranslogGeneration translogGeneration = translog.getGeneration(); try { translog.newSnapshot(); fail("already closed"); } catch (AlreadyClosedException ex) { // all is well assertNotNull(ex.getCause()); assertSame(translog.getTragicException(), ex.getCause()); } try { translog.commit(); fail("already closed"); } catch (AlreadyClosedException ex) { assertNotNull(ex.getCause()); assertSame(translog.getTragicException(), ex.getCause()); } assertFalse(translog.isOpen()); translog.close(); // we are closed config.setTranslogGeneration(translogGeneration); try (Translog tlog = new Translog(config)){ assertEquals("lastCommitted must be 1 less than current", translogGeneration.translogFileGeneration + 1, tlog.currentFileGeneration()); assertFalse(tlog.syncNeeded()); try (Translog.Snapshot snapshot = tlog.newSnapshot()) { assertEquals(opsSynced, snapshot.estimatedTotalOperations()); for (int i = 0; i < opsSynced; i++) { assertEquals("expected operation" + i + " to be in the previous translog but wasn't", tlog.currentFileGeneration() - 1, locations.get(i).generation); Translog.Operation next = snapshot.next(); assertNotNull("operation " + i + " must be non-null", next); assertEquals(i, Integer.parseInt(next.getSource().source.toUtf8())); } } } } public void testTranslogOpsCountIsCorrect() throws IOException { List<Translog.Location> locations = new ArrayList<>(); int numOps = randomIntBetween(100, 200); LineFileDocs lineFileDocs = new LineFileDocs(random()); // writes pretty big docs so we cross buffer boarders regularly for (int opsAdded = 0; opsAdded < numOps; opsAdded++) { locations.add(translog.add(new Translog.Index("test", "" + opsAdded, lineFileDocs.nextDoc().toString().getBytes(Charset.forName("UTF-8"))))); try (Translog.Snapshot snapshot = translog.newSnapshot()) { assertEquals(opsAdded+1, snapshot.estimatedTotalOperations()); for (int i = 0; i < opsAdded; i++) { assertEquals("expected operation" + i + " to be in the current translog but wasn't", translog.currentFileGeneration(), locations.get(i).generation); Translog.Operation next = snapshot.next(); assertNotNull("operation " + i + " must be non-null", next); } } } } public void testTragicEventCanBeAnyException() throws IOException { Path tempDir = createTempDir(); final FailSwitch fail = new FailSwitch(); TranslogConfig config = getTranslogConfig(tempDir); assumeFalse("this won't work if we sync on any op",config.isSyncOnEachOperation()); Translog translog = getFailableTranslog(fail, config, false, true); LineFileDocs lineFileDocs = new LineFileDocs(random()); // writes pretty big docs so we cross buffer boarders regularly translog.add(new Translog.Index("test", "1", lineFileDocs.nextDoc().toString().getBytes(Charset.forName("UTF-8")))); fail.failAlways(); try { Translog.Location location = translog.add(new Translog.Index("test", "2", lineFileDocs.nextDoc().toString().getBytes(Charset.forName("UTF-8")))); if (config.getType() == TranslogWriter.Type.BUFFERED) { // the buffered case will fail on the add if we exceed the buffer or will fail on the flush once we sync if (randomBoolean()) { translog.ensureSynced(location); } else { translog.sync(); } } //TODO once we have a mock FS that can simulate we can also fail on plain sync fail("WTF"); } catch (UnknownException ex) { // w00t } catch (TranslogException ex) { assertTrue(ex.getCause() instanceof UnknownException); } assertFalse(translog.isOpen()); assertTrue(translog.getTragicException() instanceof UnknownException); } public void testFatalIOExceptionsWhileWritingConcurrently() throws IOException, InterruptedException { Path tempDir = createTempDir(); final FailSwitch fail = new FailSwitch(); TranslogConfig config = getTranslogConfig(tempDir); final Translog translog = getFailableTranslog(fail, config); final int threadCount = randomIntBetween(1, 5); Thread[] threads = new Thread[threadCount]; final Throwable[] threadExceptions = new Throwable[threadCount]; final CountDownLatch downLatch = new CountDownLatch(1); final CountDownLatch added = new CountDownLatch(randomIntBetween(10, 100)); List<LocationOperation> writtenOperations = Collections.synchronizedList(new ArrayList<LocationOperation>()); for (int i = 0; i < threadCount; i++) { final int threadId = i; threads[i] = new TranslogThread(translog, downLatch, 200, threadId, writtenOperations, threadExceptions) { @Override protected Translog.Location add(Translog.Operation op) throws IOException { Translog.Location add = super.add(op); added.countDown(); return add; } @Override protected void afterAdd() throws IOException { if (randomBoolean()) { translog.sync(); } } }; threads[i].setDaemon(true); threads[i].start(); } downLatch.countDown(); added.await(); try (Translog.View view = translog.newView()) { // this holds a reference to the current tlog channel such that it's not closed // if we hit a tragic event. this is important to ensure that asserts inside the Translog#add doesn't trip // otherwise our assertions here are off by one sometimes. fail.failAlways(); for (int i = 0; i < threadCount; i++) { threads[i].join(); } boolean atLeastOneFailed = false; for (Throwable ex : threadExceptions) { assertTrue(ex.toString(), ex instanceof IOException || ex instanceof AlreadyClosedException); if (ex != null) { atLeastOneFailed = true; } } if (atLeastOneFailed == false) { try { boolean syncNeeded = translog.syncNeeded(); translog.close(); assertFalse("should have failed if sync was needed", syncNeeded); } catch (IOException ex) { // boom now we failed } } Collections.sort(writtenOperations, new Comparator<LocationOperation>() { @Override public int compare(LocationOperation a, LocationOperation b) { return a.location.compareTo(b.location); } }); assertFalse(translog.isOpen()); final Checkpoint checkpoint = Checkpoint.read(config.getTranslogPath().resolve(Translog.CHECKPOINT_FILE_NAME)); Iterator<LocationOperation> iterator = writtenOperations.iterator(); while (iterator.hasNext()) { LocationOperation next = iterator.next(); if (checkpoint.offset < (next.location.translogLocation + next.location.size)) { // drop all that haven't been synced iterator.remove(); } } config.setTranslogGeneration(translog.getGeneration()); try (Translog tlog = new Translog(config)) { try (Translog.Snapshot snapshot = tlog.newSnapshot()) { if (writtenOperations.size() != snapshot.estimatedTotalOperations()) { for (int i = 0; i < threadCount; i++) { if (threadExceptions[i] != null) threadExceptions[i].printStackTrace(); } } assertEquals(writtenOperations.size(), snapshot.estimatedTotalOperations()); for (int i = 0; i < writtenOperations.size(); i++) { assertEquals("expected operation" + i + " to be in the previous translog but wasn't", tlog.currentFileGeneration() - 1, writtenOperations.get(i).location.generation); Translog.Operation next = snapshot.next(); assertNotNull("operation " + i + " must be non-null", next); assertEquals(next, writtenOperations.get(i).operation); } } } } } private Translog getFailableTranslog(FailSwitch fail, final TranslogConfig config) throws IOException { return getFailableTranslog(fail, config, randomBoolean(), false); } private static class FailSwitch { private volatile int failRate; private volatile boolean onceFailedFailAlways = false; public boolean fail() { boolean fail = randomIntBetween(1, 100) <= failRate; if (fail && onceFailedFailAlways) { failAlways(); } return fail; } public void failNever() { failRate = 0; } public void failAlways() { failRate = 100; } public void failRandomly() { failRate = randomIntBetween(1, 100); } public void onceFailedFailAlways() { onceFailedFailAlways = true; } } private Translog getFailableTranslog(final FailSwitch fail, final TranslogConfig config, final boolean paritalWrites, final boolean throwUnknownException) throws IOException { return new Translog(config) { @Override TranslogWriter.ChannelFactory getChannelFactory() { final TranslogWriter.ChannelFactory factory = super.getChannelFactory(); return new TranslogWriter.ChannelFactory() { @Override public FileChannel open(Path file) throws IOException { FileChannel channel = factory.open(file); boolean success = false; try { ThrowingFileChannel throwingFileChannel = new ThrowingFileChannel(fail, paritalWrites, throwUnknownException, channel); success = true; return throwingFileChannel; } finally { if (success == false) { IOUtils.closeWhileHandlingException(channel); } } } }; } @Override protected boolean assertBytesAtLocation(Location location, BytesReference expectedBytes) throws IOException { return true; // we don't wanna fail in the assert } }; } public static class ThrowingFileChannel extends FilterFileChannel { private final FailSwitch fail; private final boolean partialWrite; private final boolean throwUnknownException; public ThrowingFileChannel(FailSwitch fail, boolean partialWrite, boolean throwUnknownException, FileChannel delegate) throws MockDirectoryWrapper.FakeIOException { super(delegate); this.fail = fail; this.partialWrite = partialWrite; this.throwUnknownException = throwUnknownException; if (fail.fail()) { throw new MockDirectoryWrapper.FakeIOException(); } } @Override public int read(ByteBuffer dst) throws IOException { if (fail.fail()) { throw new MockDirectoryWrapper.FakeIOException(); } return super.read(dst); } @Override public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { if (fail.fail()) { throw new MockDirectoryWrapper.FakeIOException(); } return super.read(dsts, offset, length); } @Override public long write(ByteBuffer[] srcs, int offset, int length) throws IOException { throw new UnsupportedOperationException(); } @Override public int write(ByteBuffer src, long position) throws IOException { throw new UnsupportedOperationException(); } public int write(ByteBuffer src) throws IOException { if (fail.fail()) { if (partialWrite) { if (src.hasRemaining()) { final int pos = src.position(); final int limit = src.limit(); src.limit(randomIntBetween(pos, limit)); super.write(src); src.limit(limit); src.position(pos); throw new IOException("__FAKE__ no space left on device"); } } if (throwUnknownException) { throw new UnknownException(); } else { throw new MockDirectoryWrapper.FakeIOException(); } } return super.write(src); } @Override public void force(boolean metaData) throws IOException { if (fail.fail()) { throw new MockDirectoryWrapper.FakeIOException(); } super.force(metaData); } @Override public long position() throws IOException { if (fail.fail()) { throw new MockDirectoryWrapper.FakeIOException(); } return super.position(); } } private static final class UnknownException extends RuntimeException { } // see https://github.com/elastic/elasticsearch/issues/15754 public void testFailWhileCreateWriteWithRecoveredTLogs() throws IOException { Path tempDir = createTempDir(); TranslogConfig config = getTranslogConfig(tempDir); Translog translog = new Translog(config); translog.add(new Translog.Index("test", "boom", "boom".getBytes(Charset.forName("UTF-8")))); Translog.TranslogGeneration generation = translog.getGeneration(); translog.close(); config.setTranslogGeneration(generation); try { new Translog(config) { @Override protected TranslogWriter createWriter(long fileGeneration) throws IOException { throw new MockDirectoryWrapper.FakeIOException(); } }; // if we have a LeakFS here we fail if not all resources are closed fail("should have been failed"); } catch (MockDirectoryWrapper.FakeIOException ex) { // all is well } } public void testRecoverWithUnbackedNextGen() throws IOException { translog.add(new Translog.Index("test", "" + 0, Integer.toString(0).getBytes(Charset.forName("UTF-8")))); Translog.TranslogGeneration translogGeneration = translog.getGeneration(); translog.close(); TranslogConfig config = translog.getConfig(); Path ckp = config.getTranslogPath().resolve(Translog.CHECKPOINT_FILE_NAME); Checkpoint read = Checkpoint.read(ckp); Files.copy(ckp, config.getTranslogPath().resolve(Translog.getCommitCheckpointFileName(read.generation))); Files.createFile(config.getTranslogPath().resolve("translog-" + (read.generation + 1) + ".tlog")); config.setTranslogGeneration(translogGeneration); try (Translog tlog = new Translog(config)) { assertNotNull(translogGeneration); assertFalse(tlog.syncNeeded()); try (Translog.Snapshot snapshot = tlog.newSnapshot()) { for (int i = 0; i < 1; i++) { Translog.Operation next = snapshot.next(); assertNotNull("operation " + i + " must be non-null", next); assertEquals("payload missmatch", i, Integer.parseInt(next.getSource().source.toUtf8())); } } tlog.add(new Translog.Index("test", "" + 1, Integer.toString(1).getBytes(Charset.forName("UTF-8")))); } try (Translog tlog = new Translog(config)) { assertNotNull(translogGeneration); assertFalse(tlog.syncNeeded()); try (Translog.Snapshot snapshot = tlog.newSnapshot()) { for (int i = 0; i < 2; i++) { Translog.Operation next = snapshot.next(); assertNotNull("operation " + i + " must be non-null", next); assertEquals("payload missmatch", i, Integer.parseInt(next.getSource().source.toUtf8())); } } } } public void testRecoverWithUnbackedNextGenInIllegalState() throws IOException { translog.add(new Translog.Index("test", "" + 0, Integer.toString(0).getBytes(Charset.forName("UTF-8")))); Translog.TranslogGeneration translogGeneration = translog.getGeneration(); translog.close(); TranslogConfig config = translog.getConfig(); Path ckp = config.getTranslogPath().resolve(Translog.CHECKPOINT_FILE_NAME); Checkpoint read = Checkpoint.read(ckp); // don't copy the new file Files.createFile(config.getTranslogPath().resolve("translog-" + (read.generation + 1) + ".tlog")); config.setTranslogGeneration(translogGeneration); try { Translog tlog = new Translog(config); fail("file already exists?"); } catch (TranslogException ex) { // all is well assertEquals(ex.getMessage(), "failed to create new translog file"); assertEquals(ex.getCause().getClass(), FileAlreadyExistsException.class); } } public void testRecoverWithUnbackedNextGenAndFutureFile() throws IOException { translog.add(new Translog.Index("test", "" + 0, Integer.toString(0).getBytes(Charset.forName("UTF-8")))); Translog.TranslogGeneration translogGeneration = translog.getGeneration(); translog.close(); TranslogConfig config = translog.getConfig(); Path ckp = config.getTranslogPath().resolve(Translog.CHECKPOINT_FILE_NAME); Checkpoint read = Checkpoint.read(ckp); Files.copy(ckp, config.getTranslogPath().resolve(Translog.getCommitCheckpointFileName(read.generation))); Files.createFile(config.getTranslogPath().resolve("translog-" + (read.generation + 1) + ".tlog")); // we add N+1 and N+2 to ensure we only delete the N+1 file and never jump ahead and wipe without the right condition Files.createFile(config.getTranslogPath().resolve("translog-" + (read.generation + 2) + ".tlog")); config.setTranslogGeneration(translogGeneration); try (Translog tlog = new Translog(config)) { assertNotNull(translogGeneration); assertFalse(tlog.syncNeeded()); try (Translog.Snapshot snapshot = tlog.newSnapshot()) { for (int i = 0; i < 1; i++) { Translog.Operation next = snapshot.next(); assertNotNull("operation " + i + " must be non-null", next); assertEquals("payload missmatch", i, Integer.parseInt(next.getSource().source.toUtf8())); } } tlog.add(new Translog.Index("test", "" + 1, Integer.toString(1).getBytes(Charset.forName("UTF-8")))); } try { Translog tlog = new Translog(config); fail("file already exists?"); } catch (TranslogException ex) { // all is well assertEquals(ex.getMessage(), "failed to create new translog file"); assertEquals(ex.getCause().getClass(), FileAlreadyExistsException.class); } } /** * This test adds operations to the translog which might randomly throw an IOException. The only thing this test verifies is * that we can, after we hit an exception, open and recover the translog successfully and retrieve all successfully synced operations * from the transaction log. */ public void testWithRandomException() throws IOException { final int runs = randomIntBetween(5, 10); for (int run = 0; run < runs; run++) { Path tempDir = createTempDir(); final FailSwitch fail = new FailSwitch(); fail.failRandomly(); TranslogConfig config = getTranslogConfig(tempDir); final int numOps = randomIntBetween(100, 200); List<String> syncedDocs = new ArrayList<>(); List<String> unsynced = new ArrayList<>(); if (randomBoolean()) { fail.onceFailedFailAlways(); } try { final Translog failableTLog = getFailableTranslog(fail, config, randomBoolean(), false); try { LineFileDocs lineFileDocs = new LineFileDocs(random()); //writes pretty big docs so we cross buffer boarders regularly for (int opsAdded = 0; opsAdded < numOps; opsAdded++) { String doc = lineFileDocs.nextDoc().toString(); failableTLog.add(new Translog.Index("test", "" + opsAdded, doc.getBytes(Charset.forName("UTF-8")))); unsynced.add(doc); if (randomBoolean()) { failableTLog.sync(); syncedDocs.addAll(unsynced); unsynced.clear(); } if (randomFloat() < 0.1) { failableTLog.sync(); // we have to sync here first otherwise we don't know if the sync succeeded if the commit fails syncedDocs.addAll(unsynced); unsynced.clear(); if (randomBoolean()) { failableTLog.prepareCommit(); } failableTLog.commit(); syncedDocs.clear(); } } // we survived all the randomness!!! // lets close the translog and if it succeeds we are all synced again. If we don't do this we will close // it in the finally block but miss to copy over unsynced docs to syncedDocs and fail the assertion down the road... failableTLog.close(); syncedDocs.addAll(unsynced); unsynced.clear(); } catch (TranslogException | MockDirectoryWrapper.FakeIOException ex) { // fair enough } catch (IOException ex) { assertEquals(ex.getMessage(), "__FAKE__ no space left on device"); } finally { config.setTranslogGeneration(failableTLog.getGeneration()); IOUtils.closeWhileHandlingException(failableTLog); } } catch (TranslogException | MockDirectoryWrapper.FakeIOException ex) { // failed - that's ok, we didn't even create it } // now randomly open this failing tlog again just to make sure we can also recover from failing during recovery if (randomBoolean()) { try { IOUtils.close(getFailableTranslog(fail, config, randomBoolean(), false)); } catch (TranslogException | MockDirectoryWrapper.FakeIOException ex) { // failed - that's ok, we didn't even create it } } try (Translog translog = new Translog(config)) { try (Translog.Snapshot snapshot = translog.newSnapshot()) { assertEquals(syncedDocs.size(), snapshot.estimatedTotalOperations()); for (int i = 0; i < syncedDocs.size(); i++) { Translog.Operation next = snapshot.next(); assertEquals(syncedDocs.get(i), next.getSource().source.toUtf8()); assertNotNull("operation " + i + " must be non-null", next); } } } } } }
922e3a6cd7ea00cd4052bdc2eb6ec51afc5fc6d3
24,386
java
Java
src/main/java/strlet/transferLearning/inductive/taskLearning/trees/Strut.java
Novemser/DSSM
6d55514a1f2ec1b4a30ece412d9679e8da021d5c
[ "MIT" ]
5
2019-01-21T12:56:09.000Z
2021-03-22T06:39:50.000Z
src/main/java/strlet/transferLearning/inductive/taskLearning/trees/Strut.java
Novemser/DSSM
6d55514a1f2ec1b4a30ece412d9679e8da021d5c
[ "MIT" ]
null
null
null
src/main/java/strlet/transferLearning/inductive/taskLearning/trees/Strut.java
Novemser/DSSM
6d55514a1f2ec1b4a30ece412d9679e8da021d5c
[ "MIT" ]
1
2019-03-05T13:24:29.000Z
2019-03-05T13:24:29.000Z
26.945856
98
0.639711
994,676
package strlet.transferLearning.inductive.taskLearning.trees; import java.io.Serializable; import java.util.Enumeration; import java.util.LinkedList; import java.util.Queue; import java.util.Random; import strlet.transferLearning.inductive.SingleSourceTransfer; import strlet.transferLearning.inductive.taskLearning.SingleSourceModelTransfer; import weka.classifiers.trees.j48.Distribution; import weka.core.Attribute; import weka.core.ContingencyTables; import weka.core.Instance; import weka.core.Instances; import weka.core.Randomizable; import weka.core.Utils; import weka.core.WeightedInstancesHandler; public class Strut extends SingleSourceModelTransfer implements WeightedInstancesHandler, Randomizable { private Node m_root = null; private int mSeed = 1; @Override public void setSeed(int seed) { mSeed = seed; } @Override public int getSeed() { return mSeed; } @Override protected void buildModel(Instances source) throws Exception { if (source == null) throw new Exception("no source to work on"); source = new Instances(source); source.deleteWithMissingClass(); m_root = Node.buildTree(source, mSeed); } @Override protected void transferModel(Instances target) throws Exception { if (target == null) throw new Exception("no target to work on"); target = new Instances(target); target.deleteWithMissingClass(); if (Utils.eq(target.sumOfWeights(), 0)) { return; } Queue<Node> splitNodes = new LinkedList<Node>(); splitNodes.add(m_root); Queue<Instances> splitInstances = new LinkedList<Instances>(); splitInstances.add(target); while (!splitNodes.isEmpty()) { Node treeNode = splitNodes.poll(); Instances data = splitInstances.poll(); if (changeToLeaf(data)) { treeNode.changeToLeaf(data); continue; } if (treeNode.m_IsLeaf) { // Remember class distribution rememberClassDistribution(treeNode, data); continue; } if (data.attribute(treeNode.m_Attribute).isNumeric()) { updateThresholds(treeNode, data); } else { // Remember class distribution for none-numeric feature rememberClassDistribution(treeNode, data); } if (treeNode.m_IsLeaf) continue; Instances[] subsets = treeNode.splitData(data); Node[] origSons = treeNode.m_Sons; for (int i = 0; i < subsets.length; ++i) { splitNodes.add(origSons[i]); splitInstances.add(subsets[i]); } } } private static void rememberClassDistribution(Node treeNode, Instances data) throws Exception { Distribution d = new Distribution(data); treeNode.m_ClassDistribution = new double[data.numClasses()]; for (int i = 0; i < treeNode.m_ClassDistribution.length; ++i) treeNode.m_ClassDistribution[i] = d.prob(i); } private int addTillMiss(Distribution newDist, Instances data, int attIndex) throws Exception { @SuppressWarnings("unchecked") Enumeration<Instance> enu = data.enumerateInstances(); int i = 0; while (enu.hasMoreElements()) { Instance instance = enu.nextElement(); if (instance.isMissing(attIndex)) break; newDist.add(1, instance); ++i; } return i; } @SuppressWarnings("unchecked") private static boolean changeToLeaf(Instances data) { if ((data == null) || (data.numInstances() < 2) || Utils.eq(data.sumOfWeights(), 0)) { return true; } double classValue = data.firstInstance().classValue(); Enumeration<Instance> enu = data.enumerateInstances(); while (enu.hasMoreElements()) { double nextValue = enu.nextElement().classValue(); if (!Utils.eq(classValue, nextValue)) return false; } return true; } private void updateThresholds(Node treeNode, Instances data) throws Exception { int attIndex = treeNode.m_Attribute; data.sort(attIndex); double[][] dist = new double[2][]; dist[0] = treeNode.m_Sons[0].m_ClassDistribution.clone(); dist[1] = treeNode.m_Sons[1].m_ClassDistribution.clone(); Distribution existingDist = new Distribution(dist); Distribution newDist = new Distribution(2, data.numClasses()); // Only Instances with known values are relevant. int firstMiss = addTillMiss(newDist, data, attIndex); // Enough Instances with known values? if (Utils.sm((double) firstMiss, 2)) { treeNode.changeToLeaf(data); return; } Distribution invertedDist = new Distribution(2, data.numClasses()); addTillMiss(invertedDist, data, attIndex); invertedDist.shiftRange(1, 0, data, 0, firstMiss); // Compute values of criteria for all possible split indices. double[] informationGains = new double[1 + firstMiss]; double[] jsds = new double[1 + firstMiss]; double[] inverted_jsds = new double[1 + firstMiss]; int tot = 0; int last = 0; for (int next = 1; next < firstMiss; ++next) { if (data.instance(next - 1).value(attIndex) + 1e-5 < data.instance(next).value(attIndex)) { // Move class values for all Instances up to next // possible split point. newDist.shiftRange(1, 0, data, last, next); invertedDist.shiftRange(0, 1, data, last, next); informationGains[next] = treeNode.gain(newDist.matrix()); jsds[next] = 1 - calcJSD(newDist, existingDist); inverted_jsds[next] = 1 - calcJSD(invertedDist, existingDist); // System.out.println("jsds[next]" + jsds[next] + "inverted_jsds[next]" + inverted_jsds[next]); ++tot; last = next; } } // Was there any useful split? if (tot == 0) { treeNode.changeToLeaf(data); return; } int splitIndex = 0; double best = Math.max(jsds[splitIndex], inverted_jsds[splitIndex]); for (int i = 1; i < jsds.length - 1; ++i) { if ((informationGains[i - 1] <= informationGains[i]) && (informationGains[i + 1] <= informationGains[i])) { if (jsds[i] > best) { best = jsds[i]; splitIndex = i; } if (inverted_jsds[i] > best) { best = inverted_jsds[i]; splitIndex = i; } } } // System.out.println("inverted_jsds[splitIndex]=" + inverted_jsds[splitIndex] + // ", jsds[splitIndex]" + jsds[splitIndex]); if (Utils.gr(inverted_jsds[splitIndex], jsds[splitIndex])) { Node tmp = treeNode.m_Sons[0]; treeNode.m_Sons[0] = treeNode.m_Sons[1]; treeNode.m_Sons[1] = tmp; } // Was there any useful split? if (splitIndex == 0) { treeNode.changeToLeaf(data); return; } double splitPoint = (data.instance(splitIndex - 1).value(attIndex) + data .instance(splitIndex).value(attIndex)) / 2; // In case we have a numerical precision problem we need to choose // the smaller value if (splitPoint == data.instance(splitIndex).value(attIndex)) { splitPoint = data.instance(splitIndex - 1).value(attIndex); } treeNode.m_SplitPoint = splitPoint; // Split and calculate weights // Instances[] subsets = treeNode.splitData(data); treeNode.m_Weights = new double[2]; for (int index = 0; index < firstMiss; ++index) { Instance instance = data.instance(index); if (instance.value(attIndex) < splitPoint) { treeNode.m_Weights[0] += instance.weight(); } else { treeNode.m_Weights[1] += instance.weight(); } } if (Utils.eq(0, Utils.sum(treeNode.m_Weights))) { for (int i = 0; i < treeNode.m_Weights.length; ++i) { treeNode.m_Weights[i] = 1.0 / treeNode.m_Weights.length; } } else { Utils.normalize(treeNode.m_Weights); } // Update distribution Distribution d = new Distribution(data); for (int i = 0; i < treeNode.m_ClassDistribution.length; ++i) treeNode.m_ClassDistribution[i] = d.prob(i); } private double calcJSD(Distribution distUnderTest, Distribution origDisitribution) { int numBags = distUnderTest.numBags(); double[] weights = new double[numBags]; for (int i = 0; i < numBags; ++i) { weights[i] = distUnderTest.perBag(i) / distUnderTest.total(); } int numClasses = distUnderTest.numClasses(); double[] jsds = new double[numBags]; for (int i = 0; i < numBags; ++i) { double jsp = 0; for (int cls = 0; cls < numClasses; ++cls) { double o = distUnderTest.prob(cls, i); double e = origDisitribution.prob(cls, i); double m = (o + e) / 2; if (Utils.eq(m, 0)) continue; double logO = Utils.log2(o / m) * o; if (Double.isNaN(logO)) logO = 0; double logE = Utils.log2(e / m) * e; if (Double.isNaN(logE)) logE = 0; jsp += (logO + logE); } jsds[i] = jsp / 2; } // Weight the JSPs for (int i = 0; i < numBags; ++i) { jsds[i] *= weights[i]; } double sum = Utils.sum(jsds); return sum; } @Override public double[] distributionForInstance(Instance instance) throws Exception { return m_root.distributionForInstance(instance); } /** * Returns a description of the classifier. * * @return a description of the classifier */ @Override public String toString() { if (m_root == null) { return "No classifier built"; } return "Local Transformation J48\n------------------\n" + m_root.toString(); } @Override public SingleSourceTransfer makeDuplicate() throws Exception { Strut dup = new Strut(); dup.setSeed(getSeed()); if (m_root != null) { throw new Exception( "Tree cannot be duplicated - method not implemented"); } return dup; } private static class Node implements Serializable { private static final long serialVersionUID = -2752818564382895182L; private final Instances m_header; private final Random m_rand; /** Is the current node a leaf */ protected boolean m_IsLeaf; /** Is there any useful information in the leaf */ protected boolean m_IsEmpty; /** The subtrees appended to this tree. */ protected Node[] m_Sons; /** The attribute to split on. */ protected int m_Attribute; /** The split point. */ protected double m_SplitPoint; /** Class probabilities from the training data. */ protected double[] m_ClassDistribution; /** Training data distribution between sons. */ protected double[] m_Weights; public Node(Instances data, Random rand) { m_header = new Instances(data, 0); m_rand = rand; } public static Node buildTree(Instances trainData, int seed) throws Exception { Node root = new Node(trainData, new Random(seed)); root.buildTree(trainData); return root; } private void buildTree(Instances data) throws Exception { // Compute initial class counts double[] classProbs = new double[data.numClasses()]; for (int i = 0; i < data.numInstances(); ++i) { Instance inst = data.instance(i); classProbs[(int) inst.classValue()] += inst.weight(); } // Create the attribute indices window int[] attIndicesWindow = new int[data.numAttributes() - 1]; int j = 0; for (int i = 0; i < attIndicesWindow.length; ++i) { if (j == data.classIndex()) { ++j; // do not include the class } attIndicesWindow[i] = j++; } buildTree(data, classProbs, attIndicesWindow); } private void buildTree(Instances data, double[] classProbs, int[] attIndicesWindow) throws Exception { m_IsLeaf = false; m_IsEmpty = false; m_Attribute = -1; m_ClassDistribution = null; m_Weights = null; m_SplitPoint = Double.NaN; m_Sons = null; // Make leaf if there are no training instances if (data.numInstances() == 0) { m_IsLeaf = true; m_IsEmpty = true; return; } // Check if node doesn't contain enough instances or is pure or // maximum depth reached m_ClassDistribution = (double[]) classProbs.clone(); if ((Utils.sum(m_ClassDistribution) < 2) || isPure(classProbs)) { // Make leaf m_Attribute = -1; m_IsLeaf = true; m_Weights = null; return; } // Compute class distributions and value of splitting criterion for // each attribute double[] vals = new double[data.numAttributes()]; double[][][] dists = new double[data.numAttributes()][0][0]; double[][] props = new double[data.numAttributes()][0]; double[] splits = new double[data.numAttributes()]; // Investigate K random attributes int attIndex = 0; int windowSize = attIndicesWindow.length; int k = (int) Utils.log2(data.numAttributes()) + 1; boolean gainFound = false; while ((windowSize > 0) && (k-- > 0 || !gainFound)) { int chosenIndex = m_rand.nextInt(windowSize); attIndex = attIndicesWindow[chosenIndex]; // shift chosen attIndex out of window attIndicesWindow[chosenIndex] = attIndicesWindow[windowSize - 1]; attIndicesWindow[windowSize - 1] = attIndex; windowSize--; splits[attIndex] = distribution(props, dists, attIndex, data); vals[attIndex] = gain(dists[attIndex]); if (Utils.gr(vals[attIndex], 0)) gainFound = true; } // Find best attribute m_Attribute = Utils.maxIndex(vals); double[][] distribution = dists[m_Attribute]; // Any useful split found? if (Utils.gr(vals[m_Attribute], 0)) { // Build subtrees m_SplitPoint = splits[m_Attribute]; m_Weights = props[m_Attribute]; Instances[] subsets = splitData(data); m_Sons = new Node[distribution.length]; for (int i = 0; i < distribution.length; ++i) { m_Sons[i] = new Node(m_header, m_rand); m_Sons[i].buildTree(subsets[i], distribution[i], attIndicesWindow); } } else { // Make leaf m_Attribute = -1; m_IsLeaf = true; } } private boolean isPure(double[] classProbs) { double maxProb = classProbs[Utils.maxIndex(classProbs)]; double sumProbs = Utils.sum(classProbs); return Utils.eq(maxProb, sumProbs); } /** * Computes class distribution for an attribute. * * @param props * @param dists * @param att * the attribute index * @param data * the data to work with * @throws Exception * if something goes wrong */ private double distribution(double[][] props, double[][][] dists, int att, Instances data) throws Exception { double splitPoint = Double.NaN; Attribute attribute = data.attribute(att); double[][] dist = null; int indexOfFirstMissingValue = -1; if (attribute.isNominal()) { // For nominal attributes dist = new double[attribute.numValues()][data.numClasses()]; for (int i = 0; i < data.numInstances(); i++) { Instance inst = data.instance(i); if (inst.isMissing(att)) { // Skip missing values at this stage if (indexOfFirstMissingValue < 0) { indexOfFirstMissingValue = i; } continue; } dist[(int) inst.value(att)][(int) inst.classValue()] += inst .weight(); } } else { // For numeric attributes double[][] currDist = new double[2][data.numClasses()]; dist = new double[2][data.numClasses()]; // Sort data data.sort(att); // Move all instances into second subset for (int j = 0; j < data.numInstances(); j++) { Instance inst = data.instance(j); if (inst.isMissing(att)) { // Can stop as soon as we hit a missing value indexOfFirstMissingValue = j; break; } currDist[1][(int) inst.classValue()] += inst.weight(); } // Value before splitting double priorVal = ContingencyTables .entropyOverColumns(currDist); // Save initial distribution for (int j = 0; j < currDist.length; j++) { System.arraycopy(currDist[j], 0, dist[j], 0, dist[j].length); } // Try all possible split points double currSplit = data.instance(0).value(att); double currVal, bestVal = -Double.MAX_VALUE; for (int i = 0; i < data.numInstances(); i++) { Instance inst = data.instance(i); if (inst.isMissing(att)) { // Can stop as soon as we hit a missing value break; } // Can we place a sensible split point here? if (inst.value(att) > currSplit) { // Compute gain for split point currVal = gain(currDist, priorVal); // Is the current split point the best point so far? if (currVal > bestVal) { // Store value of current point bestVal = currVal; // Save split point splitPoint = (inst.value(att) + currSplit) / 2.0; // Save distribution for (int j = 0; j < currDist.length; j++) { System.arraycopy(currDist[j], 0, dist[j], 0, dist[j].length); } } } currSplit = inst.value(att); // Shift over the weight currDist[0][(int) inst.classValue()] += inst.weight(); currDist[1][(int) inst.classValue()] -= inst.weight(); } } // Compute weights for subsets props[att] = new double[dist.length]; for (int k = 0; k < props[att].length; k++) { props[att][k] = Utils.sum(dist[k]); } if (Utils.eq(Utils.sum(props[att]), 0)) { for (int k = 0; k < props[att].length; k++) { props[att][k] = 1.0 / (double) props[att].length; } } else { Utils.normalize(props[att]); } // Any instances with missing values ? if (indexOfFirstMissingValue > -1) { // Distribute weights for instances with missing values for (int i = indexOfFirstMissingValue; i < data.numInstances(); i++) { Instance inst = data.instance(i); if (attribute.isNominal()) { // Need to check if attribute value is missing if (inst.isMissing(att)) { for (int j = 0; j < dist.length; j++) { dist[j][(int) inst.classValue()] += props[att][j] * inst.weight(); } } } else { // Can be sure that value is missing, so no test // required for (int j = 0; j < dist.length; j++) { dist[j][(int) inst.classValue()] += props[att][j] * inst.weight(); } } } } // Return distribution and split point dists[att] = dist; return splitPoint; } /** * Computes value of splitting criterion after split. * * @param dist * the distributions * @param priorVal * the splitting criterion * @return the gain after the split */ private double gain(double[][] dist, double priorVal) { return priorVal - ContingencyTables.entropyConditionedOnRows(dist); } /** * Splits instances into subsets based on the given split. * * @param data * the data to work with * @return the subsets of instances * @throws Exception * if something goes wrong */ private Instances[] splitData(Instances data) throws Exception { // Allocate array of Instances objects Instances[] subsets = new Instances[m_Weights.length]; for (int i = 0; i < m_Weights.length; i++) { subsets[i] = new Instances(data, data.numInstances()); } // Go through the data for (int i = 0; i < data.numInstances(); i++) { // Get instance Instance inst = data.instance(i); // Does the instance have a missing value? if (inst.isMissing(m_Attribute)) { // Split instance up for (int k = 0; k < m_Weights.length; k++) { if (m_Weights[k] > 0) { Instance copy = (Instance) inst.copy(); copy.setWeight(m_Weights[k] * inst.weight()); subsets[k].add(copy); } } // Proceed to next instance continue; } // Do we have a nominal attribute? if (data.attribute(m_Attribute).isNominal()) { subsets[(int) inst.value(m_Attribute)].add(inst); // Proceed to next instance continue; } // Do we have a numeric attribute? if (data.attribute(m_Attribute).isNumeric()) { // subsets[(inst.value(m_Attribute) < m_SplitPoint) ? 0 : 1].add(inst); // Proceed to next instance continue; } // Else throw an exception throw new IllegalArgumentException("Unknown attribute type"); } // Save memory for (int i = 0; i < m_Weights.length; i++) { subsets[i].compactify(); } // Return the subsets return subsets; } private double gain(double[][] data) { return gain(data, ContingencyTables.entropyOverColumns(data)); } /** * Computes class distribution of an instance using the decision tree. * * @param instance * the instance to compute the distribution for * @return the computed class distribution * @throws Exception * if computation fails */ public double[] distributionForInstance(Instance instance) { if (m_IsLeaf) { if (m_IsEmpty) { return null; } double[] normalizedDistribution = (double[]) m_ClassDistribution .clone(); Utils.normalize(normalizedDistribution); return normalizedDistribution; } // double[] returnedDist = null; if (instance.isMissing(m_Attribute)) { // Value is missing double[] returnedDist = new double[m_header.numClasses()]; // Split instance up for (int i = 0; i < m_Sons.length; i++) { double[] help = m_Sons[i].distributionForInstance(instance); if (help != null) { for (int j = 0; j < help.length; j++) { returnedDist[j] += m_Weights[i] * help[j]; } } } return returnedDist; } else if (m_header.attribute(m_Attribute).isNominal()) { // For nominal attributes double[] returnedDist = m_Sons[(int) instance .value(m_Attribute)].distributionForInstance(instance); if (returnedDist != null) { return returnedDist; } } else { // For numeric attributes double[] returnedDist = null; if (instance.value(m_Attribute) < m_SplitPoint) { returnedDist = m_Sons[0].distributionForInstance(instance); } else { returnedDist = m_Sons[1].distributionForInstance(instance); } if (returnedDist != null) { return returnedDist; } } // Is node empty? if (m_ClassDistribution == null) { return null; } // Else return normalized distribution double[] normalizedDistribution = (double[]) m_ClassDistribution .clone(); Utils.normalize(normalizedDistribution); return normalizedDistribution; } public void changeToLeaf(Instances data) throws Exception { m_IsEmpty = Utils.eq(data.sumOfWeights(), 0); m_IsLeaf = true; m_Sons = null; m_Attribute = -1; m_Weights = null; if (m_IsEmpty) { m_ClassDistribution = null; } else { rememberClassDistribution(Node.this, data); } } /** * Prints tree structure. * * @return the tree structure */ @Override public String toString() { try { StringBuffer text = new StringBuffer(); if (m_IsLeaf) { text.append(": "); text.append(m_header.classAttribute().value( Utils.maxIndex(m_ClassDistribution))); } else dumpTree(0, text); text.append("\n\nNumber of Leaves : \t" + numLeaves() + "\n"); text.append("\nSize of the tree : \t" + numNodes() + "\n"); return text.toString(); } catch (Exception e) { return "Can't print classification tree."; } } /** * Help method for printing tree structure. * * @param depth * the current depth * @param text * for outputting the structure * @throws Exception * if something goes wrong */ private void dumpTree(int depth, StringBuffer text) throws Exception { for (int i = 0; i < m_Sons.length; ++i) { text.append("\n"); for (int j = 0; j < depth; ++j) text.append("| "); text.append(m_header.attribute(m_Attribute).name()); if (m_header.attribute(i).isNominal()) text.append(" = " + m_header.attribute(m_Attribute).value(i)); else if (i == 0) text.append(" <= " + Utils.doubleToString(m_SplitPoint, 6)); else text.append(" > " + Utils.doubleToString(m_SplitPoint, 6)); if (m_Sons[i].m_IsLeaf) { text.append(": "); if (m_Sons[i].m_IsEmpty) { text.append(m_header.classAttribute().value( Utils.maxIndex(m_ClassDistribution))); } else { text.append(m_header.classAttribute().value( Utils.maxIndex(m_Sons[i].m_ClassDistribution))); } } else m_Sons[i].dumpTree(depth + 1, text); } } /** * Returns number of leaves in tree structure. * * @return the number of leaves */ public int numLeaves() { if (m_IsLeaf) return 1; int num = 0; for (int i = 0; i < m_Sons.length; ++i) num += m_Sons[i].numLeaves(); return num; } /** * Returns number of nodes in tree structure. * * @return the number of nodes */ public int numNodes() { int no = 1; if (!m_IsLeaf) for (int i = 0; i < m_Sons.length; ++i) no += m_Sons[i].numNodes(); return no; } } }
922e3a9166688b7d000f512848c7e6202b760000
1,282
java
Java
http/objectos-http-server-nio/src/main/java/br/com/objectos/http/server/nio/ImmutableHttpServerImpl.java
objectos/incubator
881fa1c0eb364be98a627d5072b473d334279027
[ "Apache-2.0" ]
null
null
null
http/objectos-http-server-nio/src/main/java/br/com/objectos/http/server/nio/ImmutableHttpServerImpl.java
objectos/incubator
881fa1c0eb364be98a627d5072b473d334279027
[ "Apache-2.0" ]
null
null
null
http/objectos-http-server-nio/src/main/java/br/com/objectos/http/server/nio/ImmutableHttpServerImpl.java
objectos/incubator
881fa1c0eb364be98a627d5072b473d334279027
[ "Apache-2.0" ]
null
null
null
32.05
89
0.75585
994,677
/* * Copyright (C) 2016-2021 Objectos Software LTDA. * * This file is part of the ObjectosHttp project. * * ObjectosHttp is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * ObjectosHttp is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with ObjectosHttp. If not, see <https://www.gnu.org/licenses/>. */ package br.com.objectos.http.server.nio; import br.com.objectos.http.path.Router; import br.com.objectos.http.server.HttpModule; import br.com.objectos.http.server.ImmutableHttpServer; class ImmutableHttpServerImpl extends AbstractHttpServer implements ImmutableHttpServer { private final Router router; ImmutableHttpServerImpl(Channel channel, HttpModule module) { super(channel); this.router = Router.of(module); } @Override final Router router() { return router; } }
922e3c51065aba43bc5e178cc0b28f9eab9ba230
6,097
java
Java
src/test/java/org/elasticsearch/benchmark/scripts/score/ScriptsScoreBenchmark.java
Laymo007/elasticsearch
f042b8f2e1f7c21eec5b6f2b79d9efcd9b1c6896
[ "Apache-2.0" ]
35
2015-02-26T22:56:48.000Z
2019-04-17T23:37:56.000Z
src/test/java/org/elasticsearch/benchmark/scripts/score/ScriptsScoreBenchmark.java
Laymo007/elasticsearch
f042b8f2e1f7c21eec5b6f2b79d9efcd9b1c6896
[ "Apache-2.0" ]
19
2019-07-25T21:25:23.000Z
2021-07-30T21:24:52.000Z
src/test/java/org/elasticsearch/benchmark/scripts/score/ScriptsScoreBenchmark.java
Laymo007/elasticsearch
f042b8f2e1f7c21eec5b6f2b79d9efcd9b1c6896
[ "Apache-2.0" ]
11
2015-03-07T15:22:44.000Z
2018-10-15T22:06:14.000Z
44.50365
194
0.658193
994,678
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.benchmark.scripts.score; import org.elasticsearch.benchmark.scripts.score.plugin.NativeScriptExamplesPlugin; import org.elasticsearch.benchmark.scripts.score.script.NativeNaiveTFIDFScoreScript; import org.elasticsearch.client.Client; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.node.Node; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.elasticsearch.node.NodeBuilder.nodeBuilder; /** * */ public class ScriptsScoreBenchmark extends BasicScriptBenchmark { public static void main(String[] args) throws Exception { int minTerms = 1; int maxTerms = 50; int maxIter = 100; int warmerIter = 10; boolean runMVEL = false; init(maxTerms); List<Results> allResults = new ArrayList<>(); Settings settings = settingsBuilder().put("plugin.types", NativeScriptExamplesPlugin.class.getName()).build(); String clusterName = ScriptsScoreBenchmark.class.getSimpleName(); Node node1 = nodeBuilder().clusterName(clusterName).settings(settingsBuilder().put(settings).put("name", "node1")).node(); Client client = node1.client(); client.admin().cluster().prepareHealth("test").setWaitForGreenStatus().setTimeout("10s").execute().actionGet(); indexData(10000, client, false); client.admin().cluster().prepareHealth("test").setWaitForGreenStatus().setTimeout("10s").execute().actionGet(); Results results = new Results(); results.init(maxTerms - minTerms, "native tfidf script score dense posting list", "Results for native script score with dense posting list:", "black", "--"); // init native script searches List<Entry<String, RequestInfo>> searchRequests = initNativeSearchRequests(minTerms, maxTerms, NativeNaiveTFIDFScoreScript.NATIVE_NAIVE_TFIDF_SCRIPT_SCORE, true); // run actual benchmark runBenchmark(client, maxIter, results, searchRequests, minTerms, warmerIter); allResults.add(results); results = new Results(); results.init(maxTerms - minTerms, "term query dense posting list", "Results for term query with dense posting lists:", "green", "--"); // init term queries searchRequests = initTermQueries(minTerms, maxTerms); // run actual benchmark runBenchmark(client, maxIter, results, searchRequests, minTerms, warmerIter); allResults.add(results); if (runMVEL) { results = new Results(); results.init(maxTerms - minTerms, "mvel tfidf dense posting list", "Results for mvel score with dense posting list:", "red", "--"); // init native script searches searchRequests = initNativeSearchRequests( minTerms, maxTerms, "score = 0.0; fi= _terminfo[\"text\"]; for(i=0; i<text.size(); i++){terminfo = fi[text.get(i)]; score = score + terminfo.tf()*fi.getDocCount()/terminfo.df();} return score;", false); // run actual benchmark runBenchmark(client, maxIter, results, searchRequests, minTerms, warmerIter); allResults.add(results); } indexData(10000, client, true); results = new Results(); results.init(maxTerms - minTerms, "native tfidf script score sparse posting list", "Results for native script scorewith sparse posting list:", "black", "-."); // init native script searches searchRequests = initNativeSearchRequests(minTerms, maxTerms, NativeNaiveTFIDFScoreScript.NATIVE_NAIVE_TFIDF_SCRIPT_SCORE, true); // run actual benchmark runBenchmark(client, maxIter, results, searchRequests, minTerms, warmerIter); allResults.add(results); results = new Results(); results.init(maxTerms - minTerms, "term query sparse posting list", "Results for term query with sparse posting lists:", "green", "-."); // init term queries searchRequests = initTermQueries(minTerms, maxTerms); // run actual benchmark runBenchmark(client, maxIter, results, searchRequests, minTerms, warmerIter); allResults.add(results); if (runMVEL) { results = new Results(); results.init(maxTerms - minTerms, "mvel tfidf sparse posting list", "Results for mvel score with sparse posting list:", "red", "-."); // init native script searches searchRequests = initNativeSearchRequests( minTerms, maxTerms, "score = 0.0; fi= _terminfo[\"text\"]; for(i=0; i<text.size(); i++){terminfo = fi[text.get(i)]; score = score + terminfo.tf()*fi.getDocCount()/terminfo.df();} return score;", false); // run actual benchmark runBenchmark(client, maxIter, results, searchRequests, minTerms, warmerIter); allResults.add(results); } printOctaveScript(allResults, args); client.close(); node1.close(); } }
922e3ccaca36dd1a91946c1c51c571d45ee1fba1
647
java
Java
carp-ums/carp-ums-query/src/main/java/com/github/rxyor/carp/query/dto/permission/PermissionDTO.java
rxyor/carp-ddd
b69dc60b679a76d27fc5d2ea3fea9d1adee44d69
[ "Apache-2.0" ]
3
2020-04-03T07:38:46.000Z
2020-04-03T16:34:08.000Z
carp-ums/carp-ums-query/src/main/java/com/github/rxyor/carp/query/dto/permission/PermissionDTO.java
rxyor/carp-ddd
b69dc60b679a76d27fc5d2ea3fea9d1adee44d69
[ "Apache-2.0" ]
1
2021-08-09T20:59:09.000Z
2021-08-09T20:59:09.000Z
carp-ums/carp-ums-query/src/main/java/com/github/rxyor/carp/query/dto/permission/PermissionDTO.java
rxyor/carp-ddd
b69dc60b679a76d27fc5d2ea3fea9d1adee44d69
[ "Apache-2.0" ]
null
null
null
12.207547
51
0.510046
994,679
package com.github.rxyor.carp.query.dto.permission; import java.util.Date; import lombok.Data; /** *<p> * *</p> * * @author liuyang * @date 2020/2/18 周二 14:39:00 * @since 1.0.0 */ @Data public class PermissionDTO { /** * 权限id */ private Long id; /** * 权限编码 */ private String permissionCode; /** * 权限名称 */ private String permissionName; /** * 权限描述 */ private String remark; /** * 禁用标识, 0:启用, 1:禁用 */ private Integer disable; /** * 创建时间 */ private Date createTime; /** * 更新时间 */ private Date updateTime; }
922e3d9db599d96559bcab7681daeffe76e096f9
1,804
java
Java
src/test/java/com/corevalue/constant/menu/YMenuBillConst.java
NickRbk/selenium
f47c5c6d4bb77f39b95f1e0dc57f9f36000c1cf7
[ "MIT" ]
null
null
null
src/test/java/com/corevalue/constant/menu/YMenuBillConst.java
NickRbk/selenium
f47c5c6d4bb77f39b95f1e0dc57f9f36000c1cf7
[ "MIT" ]
null
null
null
src/test/java/com/corevalue/constant/menu/YMenuBillConst.java
NickRbk/selenium
f47c5c6d4bb77f39b95f1e0dc57f9f36000c1cf7
[ "MIT" ]
null
null
null
36.816327
96
0.711197
994,680
package com.corevalue.constant.menu; public interface YMenuBillConst { String FEE_TYPE = "Cost"; String BILL_DEPT_TYPE = "Eviction"; String BILL_EVIDENCE = "Pending"; String BILL_TYPE = "General Sessions"; String BILL_NOTES = "draft notes"; String BILL_COMMENTS = "asap"; String BILL_BORROWER_RCVB = "Recoverable"; String BILL_INVESTOR_RCVB = "Reimbursable"; String BILL_AMOUNT = "2000.00"; String BILL_QUANTITY = "150"; String BILL_FIELD_FEE_TYPE_SELECTOR = "[id$=LIT_TYPE_ID]"; String BILL_FIELD_DEPT_TYPE_SELECTOR = "[id$=DEPT_ID]"; String BILL_FIELD_TYPE_SELECTOR = "[id$=PAYEE_TYPE_ID]"; String BILL_FIELD_AMOUNT_SELECTOR = "[id$=LI_AMOUNT]"; String BILL_FIELD_QUANTITY_SELECTOR = "[id$=LI_QUANTITY]"; String BILL_FIELD_NOTES_SELECTOR = "[id$=LI_NOTE]"; String BILL_FIELD_COMMENTS_SELECTOR = "[id$=LI_INV_COMMENTS]"; String BILL_FIELD_BORROWER_RCVB_SELECTOR = "[id$=LI_RECOVERABLE]"; String BILL_FIELD_INVESTOR_RCVB_SELECTOR = "[id$=LI_INVESTOR_RECOVERABLE]"; String BILL_FIELD_EVIDENCE_SELECTOR = "[id$=ALL_EVIDENCE_COLLECTED]"; String BILL_FIELD_SELECTOR = ".cellBorderBR"; String BILLS_ID = "#MainTable > tbody > tr"; String EVIDENCE_TYPE_ID = "evidenceType"; String EVIDENCE_TYPE = "Receipt"; String DM_SELECTOR = "#select > img"; String DM_DOCUMENT_SELECTOR = "#browser > li:nth-child(4) > ul > li > ul > li:nth-child(4)"; String DM_DOCUMENT_ATTACH_LINK = "Attach to Bill Line Item"; String EVIDENCE_ADD_SELECTOR = ".tbFrameToolBar#Bar tr td:nth-child(2)"; String BILL_ADD_ID = "AddP"; String BILL_REMOVE_ID = "DeleteP"; String BUTTON_SUBMIT_ID = "Finish"; String ADD_BILL_OPTION = "add"; String REMOVE_BILL_OPTION = "delete"; int DELAY = 3000; }
922e3ebcfcd4eb01886ef2ca2d84e06299dd319b
1,120
java
Java
ec_pdm/src/main/java/com/gyf/ec/service/EcFileUrlService.java
gto5516172/test
cb9883a42363945d7aa0fd4ef7aca87b0e6faf4d
[ "Apache-2.0" ]
null
null
null
ec_pdm/src/main/java/com/gyf/ec/service/EcFileUrlService.java
gto5516172/test
cb9883a42363945d7aa0fd4ef7aca87b0e6faf4d
[ "Apache-2.0" ]
null
null
null
ec_pdm/src/main/java/com/gyf/ec/service/EcFileUrlService.java
gto5516172/test
cb9883a42363945d7aa0fd4ef7aca87b0e6faf4d
[ "Apache-2.0" ]
null
null
null
23.333333
72
0.771429
994,681
package com.gyf.ec.service; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.gohuinuo.common.base.ServiceMybatis; import com.gyf.ec.mapper.EcFileUrlMapper; import com.gyf.ec.model.EcFile; import com.gyf.ec.model.EcFileUrl; @Service("ecFileUrlService") public class EcFileUrlService extends ServiceMybatis<EcFileUrl> { @Resource private EcFileUrlMapper ecFileUrlMapper; public int saveEcFileUrl(EcFileUrl ecFileUrl) { return this.insertSelective(ecFileUrl); } public List<EcFileUrl> findFileUrlList(Map<String, Object> params) { return ecFileUrlMapper.findFileUrlList(params); } public List<EcFileUrl> findFileUrlListTwo(Map<String, Object> params) { return ecFileUrlMapper.findFileUrlListTwo(params); } /** * 根据id删除自身 * @param id * @return */ public int deleteEcFileUrlByRootId(Long id){ int num = -1; num = ecFileUrlMapper.deleteEcFileUrlByRootId(id); return num; } public List<EcFileUrl> findFileUrlMain() { return ecFileUrlMapper.findFileUrlMain(); } }
922e3ee208de4c6d908305c744b8ab4edfa5ade6
1,733
java
Java
src/test/java/models/EncodingTest.java
melissakobia/cipher
278853fc03ad1019b99e74db542fe2347aaaa355
[ "MIT" ]
null
null
null
src/test/java/models/EncodingTest.java
melissakobia/cipher
278853fc03ad1019b99e74db542fe2347aaaa355
[ "MIT" ]
null
null
null
src/test/java/models/EncodingTest.java
melissakobia/cipher
278853fc03ad1019b99e74db542fe2347aaaa355
[ "MIT" ]
null
null
null
28.409836
96
0.671091
994,682
package models; import org.junit.Test; import static org.junit.Assert.assertEquals; public class EncodingTest { @Test public void newEncoder_instantiatesCorrectly() { Encoding newEncoder = new Encoding("word",3); assertEquals(true, newEncoder instanceof Encoding); } @Test public void newEncoder_getsInput() { Encoding newEncoder = new Encoding("word",3); assertEquals("word", newEncoder.getInput()); } @Test public void newEncoder_getsKey() { Encoding newEncoder = new Encoding("word",3); assertEquals(3, newEncoder.getKey()); } @Test public void encoder_EncryptsUppercaseCharacterA_D() { Encoding newEncoder = new Encoding("A",3); assertEquals("D", newEncoder.encoder(newEncoder.getInput(),newEncoder.getKey())); } @Test public void encoder_EncryptsLowercaseCharacterm_p() { Encoding newEncoder = new Encoding("m",3); assertEquals("p", newEncoder.encoder(newEncoder.getInput(),newEncoder.getKey())); } @Test public void encoder_EncryptsAWordInLowecase_qfed() { Encoding newEncoder = new Encoding("lazy",5); assertEquals("qfed", newEncoder.encoder(newEncoder.getInput(),newEncoder.getKey())); } @Test public void encoder_EncryptsAWordInUppercase_QFED() { Encoding newEncoder = new Encoding("LAZY",5); assertEquals("QFED", newEncoder.encoder(newEncoder.getInput(),newEncoder.getKey())); } @Test public void encoder_EncryptsASentence_Ymj_Qfed() { Encoding newEncoder = new Encoding("The Lazy", 5); assertEquals("Ymj Qfed", newEncoder.encoder(newEncoder.getInput(),newEncoder.getKey())); } }
922e3f04129f2f91309300313e7bf2b858e95a42
620
java
Java
src/com/domain/contacts/service/IContactsService.java
jagadeeshtechgeek/java-web-level2
03e0a01e6a91ce2d5f9b2aadf53beb45b1ea472b
[ "MIT" ]
null
null
null
src/com/domain/contacts/service/IContactsService.java
jagadeeshtechgeek/java-web-level2
03e0a01e6a91ce2d5f9b2aadf53beb45b1ea472b
[ "MIT" ]
null
null
null
src/com/domain/contacts/service/IContactsService.java
jagadeeshtechgeek/java-web-level2
03e0a01e6a91ce2d5f9b2aadf53beb45b1ea472b
[ "MIT" ]
null
null
null
32.631579
93
0.824194
994,683
package com.domain.contacts.service; import java.util.List; import com.domain.contacts.exception.ContactsServiceException; import com.domain.contacts.vo.ContactVO; import com.domain.contacts.vo.GenericMessageVO; public interface IContactsService { public List<ContactVO> getAllContacts() throws ContactsServiceException; public GenericMessageVO saveContact(ContactVO contactVO) throws ContactsServiceException; public ContactVO getContact(ContactVO contactVO) throws ContactsServiceException; public GenericMessageVO deleteContact(ContactVO contactVO) throws ContactsServiceException; }
922e3f23f77585b9c5559973933ec505efdec40e
434
java
Java
value-fixture/src/org/immutables/fixture/couse/NotYetGeneratedGenericsInDefaultInitializer.java
nastra/immutables
0a3175a1eb4c38c509f0e0f4f6c7925abeac9cd9
[ "Apache-2.0" ]
3,263
2015-01-06T09:54:18.000Z
2022-03-31T19:53:54.000Z
value-fixture/src/org/immutables/fixture/couse/NotYetGeneratedGenericsInDefaultInitializer.java
stardv/immutables
7538110812936b4750a251de0413e75ca034fb70
[ "Apache-2.0" ]
1,194
2015-01-01T20:05:20.000Z
2022-03-30T16:21:47.000Z
value-fixture/src/org/immutables/fixture/couse/NotYetGeneratedGenericsInDefaultInitializer.java
stardv/immutables
7538110812936b4750a251de0413e75ca034fb70
[ "Apache-2.0" ]
308
2015-04-07T22:13:03.000Z
2022-03-17T03:52:49.000Z
22.842105
72
0.758065
994,684
package org.immutables.fixture.couse; import java.util.function.Supplier; import java.util.stream.Stream; import org.immutables.value.Value; @Value.Style // reset @Value.Immutable interface NotYetGeneratedGenericsInDefaultInitializer { @Value.Style // reset @Value.Immutable interface ToBeGenX<X, Y> {} @Value.Default default Supplier<Stream<ImmutableToBeGenX<?, ?>>> getEventSupplier() { return Stream::empty; } }
922e3fabbba7724438fbaddcae68d5a32a9cd614
1,851
java
Java
app/src/main/java/com/rolandopalermo/facturacion/ec/app/config/SwaggerConfig.java
rolandopalermo/facturacion-electronica-ec
9d706e84b1fa2993b3f0755240fc4ff2d7115ce2
[ "MIT" ]
21
2018-10-30T19:17:45.000Z
2019-12-20T14:56:17.000Z
app/src/main/java/com/rolandopalermo/facturacion/ec/app/config/SwaggerConfig.java
DARIO5023/veronica-open-api
226e3aa2b44bfcd41cc357df0931160a98818def
[ "MIT" ]
18
2018-10-30T16:23:14.000Z
2019-12-05T17:26:46.000Z
app/src/main/java/com/rolandopalermo/facturacion/ec/app/config/SwaggerConfig.java
DARIO5023/veronica-open-api
226e3aa2b44bfcd41cc357df0931160a98818def
[ "MIT" ]
25
2018-11-01T22:02:13.000Z
2019-12-27T01:21:35.000Z
44.071429
155
0.645597
994,685
package com.rolandopalermo.facturacion.ec.app.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @EnableSwagger2 @Configuration public class SwaggerConfig { @Bean public Docket v1APIConfiguration() { return new Docket( DocumentationType.SWAGGER_2).groupName("api_v1.0").select() .apis(RequestHandlerSelectors.basePackage("com.rolandopalermo.facturacion.ec.app.api.v1")) .paths(PathSelectors.regex("/api/v1.*")) .build() .apiInfo(new ApiInfoBuilder().version("1.0") .title("Veronica Open API") .description("\uD83C\uDDEA\uD83C\uDDE8 Implementanción del proceso de facturación electrónica según la normativa vigente del SRI") .build()); } @Bean public Docket v1OperationConfiguration() { return new Docket( DocumentationType.SWAGGER_2).groupName("operaciones").select() .apis(RequestHandlerSelectors.basePackage("com.rolandopalermo.facturacion.ec.app.api")) .paths(PathSelectors.regex("/operaciones.*")) .build() .apiInfo(new ApiInfoBuilder().version("1.0") .title("Operaciones") .description("Documentation Veronica API") .build()); } }
922e4370bdfe494d045169ab56f320327336c456
901
java
Java
scrimage-examples/src/main/java/com/sksamuel/scrimage/examples/Scale.java
gipeshka/scrimage
de467304de8c9ac7b1b790c3e05a2b40f2227837
[ "Apache-2.0" ]
772
2015-01-02T14:28:59.000Z
2022-03-29T05:33:06.000Z
scrimage-examples/src/main/java/com/sksamuel/scrimage/examples/Scale.java
gipeshka/scrimage
de467304de8c9ac7b1b790c3e05a2b40f2227837
[ "Apache-2.0" ]
189
2015-01-02T16:41:27.000Z
2022-03-29T02:14:43.000Z
scrimage-examples/src/main/java/com/sksamuel/scrimage/examples/Scale.java
gipeshka/scrimage
de467304de8c9ac7b1b790c3e05a2b40f2227837
[ "Apache-2.0" ]
130
2015-01-23T21:21:56.000Z
2022-01-13T22:00:57.000Z
30.033333
98
0.715871
994,686
package com.sksamuel.scrimage.examples; import com.sksamuel.scrimage.ImmutableImage; import com.sksamuel.scrimage.ScaleMethod; import com.sksamuel.scrimage.nio.JpegWriter; import java.io.IOException; public class Scale { public static void main(String[] args) throws IOException { ImmutableImage image = ImmutableImage.loader().fromResource("/input.jpg").scaleToWidth(640); image.scaleToWidth(400) .forWriter(JpegWriter.Default).write("scale_w400.jpg"); image.scaleToHeight(200) .forWriter(JpegWriter.Default).write("scale_h200.jpg"); image.scaleTo(400, 400) .forWriter(JpegWriter.Default).write("scale_400_400.jpg"); image.scaleTo(400, 400, ScaleMethod.FastScale) .forWriter(JpegWriter.Default).write("scale_400_400_fast.jpg"); image.scale(0.5) .forWriter(JpegWriter.Default).write("scale_0.5.jpg"); } }
922e44061b577c1953c6684f34a6eb19aebc84eb
2,119
java
Java
uranus-auth-server/src/main/java/me/wgy/config/OAuth2AuthorizationJwtConfig.java
DayoWang/uranus
e59a948a44d6f3900bfdc2fb44b9c9bd070481ff
[ "Apache-2.0" ]
5
2018-11-24T12:45:34.000Z
2020-04-08T14:44:20.000Z
uranus-auth-server/src/main/java/me/wgy/config/OAuth2AuthorizationJwtConfig.java
DayoWang/uranus
e59a948a44d6f3900bfdc2fb44b9c9bd070481ff
[ "Apache-2.0" ]
null
null
null
uranus-auth-server/src/main/java/me/wgy/config/OAuth2AuthorizationJwtConfig.java
DayoWang/uranus
e59a948a44d6f3900bfdc2fb44b9c9bd070481ff
[ "Apache-2.0" ]
null
null
null
34.737705
116
0.791411
994,687
package me.wgy.config; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; /** * OAuth2 JWT 配置 * * @author wgy * @date 2019/10/2 */ @Slf4j @Configuration @EnableAuthorizationServer public class OAuth2AuthorizationJwtConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Bean public JwtAccessTokenConverter accessTokenConverter() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setSigningKey("test-secret"); return converter; } @Bean public JwtTokenStore jwtTokenStore() { return new JwtTokenStore(accessTokenConverter()); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .authenticationManager(authenticationManager) .tokenStore(jwtTokenStore()) .accessTokenConverter(accessTokenConverter()); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("clientapp") .secret("{noop}112233") .scopes("read_userinfo") .authorizedGrantTypes( "password", "authorization_code", "refresh_token"); } }
922e44c64c8797739a78063e022f7d5acfd54f8f
676
java
Java
codegen/src/main/java/org/robobinding/codegen/viewbinding/SimpleOneWayPropertySetterFilter.java
icse18-refactorings/RoboBinding
d5e213d012b2a845fe809c1c6c58ec83ef94b82e
[ "Apache-2.0" ]
1,020
2015-01-03T16:39:05.000Z
2021-11-25T10:21:46.000Z
codegen/src/main/java/org/robobinding/codegen/viewbinding/SimpleOneWayPropertySetterFilter.java
icse18-refactorings/RoboBinding
d5e213d012b2a845fe809c1c6c58ec83ef94b82e
[ "Apache-2.0" ]
81
2015-01-08T01:09:16.000Z
2019-08-20T06:22:12.000Z
codegen/src/main/java/org/robobinding/codegen/viewbinding/SimpleOneWayPropertySetterFilter.java
icse18-refactorings/RoboBinding
d5e213d012b2a845fe809c1c6c58ec83ef94b82e
[ "Apache-2.0" ]
232
2015-01-06T09:46:13.000Z
2021-07-07T02:11:27.000Z
27.04
86
0.786982
994,688
package org.robobinding.codegen.viewbinding; import java.util.Collection; import org.robobinding.codegen.apt.SetterElementFilter; import org.robobinding.codegen.apt.element.SetterElement; /** * @since 1.0 * @author Cheng Wei * */ public class SimpleOneWayPropertySetterFilter implements SetterElementFilter { private final Collection<String> simpleOneWayProperties; public SimpleOneWayPropertySetterFilter(Collection<String> simpleOneWayProperties) { this.simpleOneWayProperties = simpleOneWayProperties; } @Override public boolean include(SetterElement element) { return simpleOneWayProperties.contains(element.propertyName()); } }
922e4544a6c524f8db3174dc0b412465048356d9
4,120
java
Java
Core/soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangObjectNative.java
bugvm/robovm
430cbeb4a9f49f48b982821b40741fad110efe57
[ "MIT" ]
29
2018-06-04T21:34:00.000Z
2022-02-21T16:34:44.000Z
Core/soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangObjectNative.java
bugvm/robovm
430cbeb4a9f49f48b982821b40741fad110efe57
[ "MIT" ]
15
2018-03-02T03:38:56.000Z
2021-03-22T02:06:14.000Z
Core/soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangObjectNative.java
bugvm/robovm
430cbeb4a9f49f48b982821b40741fad110efe57
[ "MIT" ]
6
2018-10-17T02:28:28.000Z
2020-11-27T04:47:50.000Z
33.225806
73
0.681553
994,689
/* Soot - a J*va Optimization Framework * Copyright (C) 2003 Feng Qian * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /** * Simulates the native method side effects in class java.lang.Object. * * @author Feng Qian */ package soot.jimple.toolkits.pointer.nativemethods; import soot.*; import soot.jimple.toolkits.pointer.representations.*; import soot.jimple.toolkits.pointer.util.*; public class JavaLangObjectNative extends NativeMethodClass { public JavaLangObjectNative( NativeHelper helper ) { super(helper); } /** * Implements the abstract method simulateMethod. * It distributes the request to the corresponding methods * by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]){ String subSignature = method.getSubSignature(); /* Driver */ if (subSignature.equals("java.lang.Class getClass()")) { java_lang_Object_getClass(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Object clone()")) { java_lang_Object_clone(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /*********************** java.lang.Object *********************/ /** * The return variable is assigned an abstract object represneting * all classes (UnknowClassObject) from environment. * * public final native java.lang.Class getClass(); */ public void java_lang_Object_getClass(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassObject()); } /** * Creates and returns a copy of this object. The precise meaning of * "copy" may depend on the class of the object. The general intent * is that, for any object x, the expression: * * x.clone() != x * * will be true, and that the expression: * * x.clone().getClass() == x.getClass() * * will be true, but these are not absolute requirements. While it is * typically the case that: * * x.clone().equals(x) * * will be true, this is not an absolute requirement. Copying an * object will typically entail creating a new instance of its * class, but it also may require copying of internal data * structures as well. No constructors are called. * * NOTE: it may raise an exception, the decision of cloning made by * analysis by implementing the ReferneceVariable.cloneObject() * method. * * protected native java.lang.Object clone() * throws java.lang.CloneNotSupported */ public void java_lang_Object_clone(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable newVar = helper.cloneObject(thisVar); helper.assign(returnVar, newVar); } /** * Following methods have NO side effect * * private static native void registerNatives(); * public native int hashCode(); * public final native void notify(); * public final native void notifyAll(); * public final native void wait(long) * throws java.lang.InterruptedException; */ }
922e4603df04cc7c4f91f1ff8f1432683c7848c3
408
java
Java
src/tool-template/templates/type/t.userdefinedtype.java
rmulvey/ciera
756d5c2cd951236b92216cb7d5d9732c9f08986a
[ "Apache-2.0" ]
2
2020-02-01T19:09:14.000Z
2020-11-05T11:08:00.000Z
src/tool-template/templates/type/t.userdefinedtype.java
rmulvey/ciera
756d5c2cd951236b92216cb7d5d9732c9f08986a
[ "Apache-2.0" ]
3
2020-10-07T21:18:38.000Z
2021-09-25T03:39:26.000Z
src/tool-template/templates/type/t.userdefinedtype.java
rmulvey/ciera
756d5c2cd951236b92216cb7d5d9732c9f08986a
[ "Apache-2.0" ]
10
2019-12-29T18:41:53.000Z
2021-07-15T18:40:03.000Z
19.428571
73
0.617647
994,690
package ${self.package}; ${imports} public class ${self.name} extends ${extends_type} implements IXtumlType { public ${self.name}() { super(); } public ${self.name}(Object value) throws XtumlException { super(value); } @SuppressWarnings("unchecked") public ${self.name} promote(Object o) throws XtumlException { return new ${self.name}(cast(o)); } }
922e4603e6582f24df26aaa671ba608845a4626f
2,060
java
Java
server/src/main/java/org/apache/iotdb/db/query/dataset/ShowContinuousQueriesResult.java
SzyWilliam/iotdb
13c732b43a307fe2ecbf6cd990cc537f8c73eceb
[ "Apache-2.0" ]
945
2018-12-13T00:39:04.000Z
2020-10-01T04:17:02.000Z
server/src/main/java/org/apache/iotdb/db/query/dataset/ShowContinuousQueriesResult.java
SzyWilliam/iotdb
13c732b43a307fe2ecbf6cd990cc537f8c73eceb
[ "Apache-2.0" ]
923
2019-01-18T01:12:04.000Z
2020-10-01T02:17:11.000Z
server/src/main/java/org/apache/iotdb/db/query/dataset/ShowContinuousQueriesResult.java
leety1228/iotdb
ffdcc0a5381596a74bb807a8f89fe6de3749125a
[ "Apache-2.0" ]
375
2018-12-23T06:40:33.000Z
2020-10-01T02:49:20.000Z
27.105263
63
0.735437
994,691
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iotdb.db.query.dataset; import org.apache.iotdb.commons.path.PartialPath; public class ShowContinuousQueriesResult extends ShowResult { private String querySql; private String continuousQueryName; private PartialPath targetPath; private long everyInterval; private long forInterval; private long boundary; public ShowContinuousQueriesResult( String querySql, String continuousQueryName, PartialPath targetPath, long everyInterval, long forInterval, long boundary) { this.querySql = querySql; this.continuousQueryName = continuousQueryName; this.targetPath = targetPath; this.everyInterval = everyInterval; this.forInterval = forInterval; this.boundary = boundary; } public String getQuerySql() { return querySql; } public String getContinuousQueryName() { return continuousQueryName; } public PartialPath getTargetPath() { return targetPath; } public void setTargetPath(PartialPath targetPath) { this.targetPath = targetPath; } public long getEveryInterval() { return everyInterval; } public long getForInterval() { return forInterval; } public long getBoundary() { return boundary; } }
922e460928cb8ec487779a7813878dc44a46d758
2,945
java
Java
sesame/sesame-engine/src/test/java/com/opengamma/sesame/marketdata/scenarios/CurrencyPairFilterTest.java
UbuntuEvangelist/OG-Platform
0aac9675ff92fd702d2e53a991de085388bfdc83
[ "Apache-2.0" ]
12
2017-03-10T13:56:52.000Z
2021-10-03T01:21:20.000Z
sesame/sesame-engine/src/test/java/com/opengamma/sesame/marketdata/scenarios/CurrencyPairFilterTest.java
UbuntuEvangelist/OG-Platform
0aac9675ff92fd702d2e53a991de085388bfdc83
[ "Apache-2.0" ]
1
2021-08-02T17:20:43.000Z
2021-08-02T17:20:43.000Z
sesame/sesame-engine/src/test/java/com/opengamma/sesame/marketdata/scenarios/CurrencyPairFilterTest.java
UbuntuEvangelist/OG-Platform
0aac9675ff92fd702d2e53a991de085388bfdc83
[ "Apache-2.0" ]
16
2017-01-12T10:31:58.000Z
2019-04-19T08:17:33.000Z
38.246753
109
0.75416
994,692
/** * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.sesame.marketdata.scenarios; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.util.Set; import org.testng.annotations.Test; import com.opengamma.financial.currency.CurrencyPair; import com.opengamma.sesame.marketdata.FxRateId; import com.opengamma.util.test.TestGroup; @Test(groups = TestGroup.UNIT) public class CurrencyPairFilterTest { public void match() { CurrencyPair pair = CurrencyPair.parse("EUR/USD"); CurrencyPairFilter filter = new CurrencyPairFilter(pair); Set<? extends MatchDetails> matchDetails = filter.apply(FxRateId.of(pair)); assertEquals(1, matchDetails.size()); CurrencyPairMatchDetails currencyPairDetails = (CurrencyPairMatchDetails) matchDetails.iterator().next(); assertFalse(currencyPairDetails.isInverse()); } public void matchInverse() { CurrencyPair pair = CurrencyPair.parse("EUR/USD"); CurrencyPair inverse = pair.inverse(); CurrencyPairFilter filter = new CurrencyPairFilter(pair); Set<? extends MatchDetails> matchDetails = filter.apply(FxRateId.of(inverse)); assertEquals(1, matchDetails.size()); CurrencyPairMatchDetails currencyPairDetails = (CurrencyPairMatchDetails) matchDetails.iterator().next(); assertTrue(currencyPairDetails.isInverse()); } public void noMatch() { CurrencyPair pair = CurrencyPair.parse("EUR/USD"); CurrencyPairFilter filter = new CurrencyPairFilter(CurrencyPair.parse("EUR/CHF")); assertEquals(0, filter.apply(FxRateId.of(pair)).size()); } public void matchWithData() { CurrencyPair pair = CurrencyPair.parse("EUR/USD"); CurrencyPairFilter filter = new CurrencyPairFilter(pair); Set<? extends MatchDetails> matchDetails = filter.apply(FxRateId.of(pair), 1.1); assertEquals(1, matchDetails.size()); CurrencyPairMatchDetails currencyPairDetails = (CurrencyPairMatchDetails) matchDetails.iterator().next(); assertFalse(currencyPairDetails.isInverse()); } public void matchInverseWithData() { CurrencyPair pair = CurrencyPair.parse("EUR/USD"); CurrencyPair inverse = pair.inverse(); CurrencyPairFilter filter = new CurrencyPairFilter(pair); Set<? extends MatchDetails> matchDetails = filter.apply(FxRateId.of(inverse), 1.1); assertEquals(1, matchDetails.size()); CurrencyPairMatchDetails currencyPairDetails = (CurrencyPairMatchDetails) matchDetails.iterator().next(); assertTrue(currencyPairDetails.isInverse()); } public void noMatchWithData() { CurrencyPair pair = CurrencyPair.parse("EUR/USD"); CurrencyPairFilter filter = new CurrencyPairFilter(CurrencyPair.parse("EUR/CHF")); assertEquals(0, filter.apply(FxRateId.of(pair), 1.1).size()); } }
922e465da518e758ea3933848bf2092e12b1f6d1
3,629
java
Java
analysis/reverse-engineering/decompile-fitts-20191031-2200/sources/androidx/appcompat/widget/AppCompatCheckBox.java
skkuse-adv/2019Fall_team2
3ea84c6be39855f54634a7f9b1093e80893886eb
[ "Apache-2.0" ]
4
2019-10-07T05:17:21.000Z
2020-11-02T08:29:13.000Z
analysis/reverse-engineering/decompile-fitts-with-gradle-20191031-2200/src/main/java/androidx/appcompat/widget/AppCompatCheckBox.java
skkuse-adv/2019Fall_team2
3ea84c6be39855f54634a7f9b1093e80893886eb
[ "Apache-2.0" ]
38
2019-10-07T02:40:35.000Z
2019-12-12T09:15:24.000Z
analysis/reverse-engineering/decompile-fitts-with-gradle-20191031-2200/src/main/java/androidx/appcompat/widget/AppCompatCheckBox.java
skkuse-adv/2019Fall_team2
3ea84c6be39855f54634a7f9b1093e80893886eb
[ "Apache-2.0" ]
5
2019-10-07T02:41:15.000Z
2020-10-30T01:36:08.000Z
41.238636
152
0.741802
994,693
package androidx.appcompat.widget; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.PorterDuff.Mode; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.CheckBox; import androidx.annotation.DrawableRes; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.annotation.RestrictTo.Scope; import androidx.appcompat.R; import androidx.appcompat.content.res.AppCompatResources; import androidx.core.widget.TintableCompoundButton; public class AppCompatCheckBox extends CheckBox implements TintableCompoundButton { private final AppCompatCompoundButtonHelper mCompoundButtonHelper; public AppCompatCheckBox(Context context) { this(context, null); } public AppCompatCheckBox(Context context, AttributeSet attributeSet) { this(context, attributeSet, R.attr.checkboxStyle); } public AppCompatCheckBox(Context context, AttributeSet attributeSet, int i) { super(TintContextWrapper.wrap(context), attributeSet, i); this.mCompoundButtonHelper = new AppCompatCompoundButtonHelper(this); this.mCompoundButtonHelper.loadFromAttributes(attributeSet, i); } public void setButtonDrawable(Drawable drawable) { super.setButtonDrawable(drawable); AppCompatCompoundButtonHelper appCompatCompoundButtonHelper = this.mCompoundButtonHelper; if (appCompatCompoundButtonHelper != null) { appCompatCompoundButtonHelper.onSetButtonDrawable(); } } public void setButtonDrawable(@DrawableRes int i) { setButtonDrawable(AppCompatResources.getDrawable(getContext(), i)); } public int getCompoundPaddingLeft() { int compoundPaddingLeft = super.getCompoundPaddingLeft(); AppCompatCompoundButtonHelper appCompatCompoundButtonHelper = this.mCompoundButtonHelper; return appCompatCompoundButtonHelper != null ? appCompatCompoundButtonHelper.getCompoundPaddingLeft(compoundPaddingLeft) : compoundPaddingLeft; } @RestrictTo({Scope.LIBRARY_GROUP}) public void setSupportButtonTintList(@Nullable ColorStateList colorStateList) { AppCompatCompoundButtonHelper appCompatCompoundButtonHelper = this.mCompoundButtonHelper; if (appCompatCompoundButtonHelper != null) { appCompatCompoundButtonHelper.setSupportButtonTintList(colorStateList); } } @Nullable @RestrictTo({Scope.LIBRARY_GROUP}) public ColorStateList getSupportButtonTintList() { AppCompatCompoundButtonHelper appCompatCompoundButtonHelper = this.mCompoundButtonHelper; if (appCompatCompoundButtonHelper != null) { return appCompatCompoundButtonHelper.getSupportButtonTintList(); } return null; } @RestrictTo({Scope.LIBRARY_GROUP}) public void setSupportButtonTintMode(@Nullable Mode mode) { AppCompatCompoundButtonHelper appCompatCompoundButtonHelper = this.mCompoundButtonHelper; if (appCompatCompoundButtonHelper != null) { appCompatCompoundButtonHelper.setSupportButtonTintMode(mode); } } @Nullable @RestrictTo({Scope.LIBRARY_GROUP}) public Mode getSupportButtonTintMode() { AppCompatCompoundButtonHelper appCompatCompoundButtonHelper = this.mCompoundButtonHelper; if (appCompatCompoundButtonHelper != null) { return appCompatCompoundButtonHelper.getSupportButtonTintMode(); } return null; } }
922e479e3804af160b36ff6f7cc266a811e7ceb0
2,055
java
Java
src/test/java/seedu/address/logic/commands/calendar/CalViewCommandTest.java
dinhnhobao/main
04d1c7885673d1386fcbc394652fad3fc5a18a98
[ "MIT" ]
2
2020-02-26T04:09:08.000Z
2021-06-25T06:57:53.000Z
src/test/java/seedu/address/logic/commands/calendar/CalViewCommandTest.java
dinhnhobao/main
04d1c7885673d1386fcbc394652fad3fc5a18a98
[ "MIT" ]
108
2020-02-20T16:35:35.000Z
2020-04-17T04:06:21.000Z
src/test/java/seedu/address/logic/commands/calendar/CalViewCommandTest.java
dinhnhobao/main
04d1c7885673d1386fcbc394652fad3fc5a18a98
[ "MIT" ]
7
2020-02-16T01:02:24.000Z
2022-03-01T08:48:26.000Z
35.431034
108
0.737713
994,694
package seedu.address.logic.commands.calendar; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess; import static seedu.address.testutil.Assert.assertThrows; import java.time.LocalDate; import org.junit.jupiter.api.Test; import seedu.address.logic.commands.CommandResult; import seedu.address.logic.commands.CommandType; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.calendar.Calendar; public class CalViewCommandTest { private Model model = new ModelManager(); private Model expectedModel = new ModelManager(); @Test public void constructor_nullWeek_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> new CalViewCommand(null)); } @Test public void execute_calView_success() { CommandResult expectedCommandResult = new CommandResult( CalViewCommand.MESSAGE_SUCCESS, CommandType.CALENDAR); assertCommandSuccess(new CalViewCommand( Calendar.getNowCalendar()), model, expectedCommandResult, expectedModel); } @Test public void equals() { CalViewCommand calViewCommand = new CalViewCommand(new Calendar(LocalDate.parse("2020-02-02"))); CalViewCommand calViewCommandCopy = new CalViewCommand(new Calendar(LocalDate.parse("2020-02-02"))); CalViewCommand otherCalViewCommand = new CalViewCommand(Calendar.getNextWeekCalendar()); //same object -> return true assertEquals(calViewCommand, calViewCommand); //same date -> return true assertEquals(calViewCommand, calViewCommandCopy); //null -> return false assertFalse(calViewCommand.equals(null)); //different type -> return false assertFalse(calViewCommand.equals(1)); //different date -> return false assertFalse(calViewCommand.equals(otherCalViewCommand)); } }
922e482571883c8f1a8388d54122225cd538d456
3,710
java
Java
gen/de/fhkl/mahe0034/spotdatsportsdata/R.java
brezelman/SpotDatSportsData
965e27d0d5958eb10b91ec03633776804c49c7e8
[ "MIT" ]
null
null
null
gen/de/fhkl/mahe0034/spotdatsportsdata/R.java
brezelman/SpotDatSportsData
965e27d0d5958eb10b91ec03633776804c49c7e8
[ "MIT" ]
null
null
null
gen/de/fhkl/mahe0034/spotdatsportsdata/R.java
brezelman/SpotDatSportsData
965e27d0d5958eb10b91ec03633776804c49c7e8
[ "MIT" ]
null
null
null
40.769231
82
0.701887
994,695
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package de.fhkl.mahe0034.spotdatsportsdata; public final class R { public static final class attr { } public static final class dimen { /** Default screen margins, per the Android Design guidelines. Customize dimensions originally defined in res/values/dimens.xml (such as screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here. */ public static final int activity_horizontal_margin=0x7f040000; public static final int activity_vertical_margin=0x7f040001; } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class id { public static final int action_goto=0x7f08000e; public static final int competitionsListView=0x7f080000; public static final int kickoff_at=0x7f080001; public static final int list_former_clashes=0x7f080004; public static final int list_match_events=0x7f080003; public static final int menu_item_calendar_export=0x7f08000f; public static final int pager=0x7f080005; public static final int pager_title_strip=0x7f080006; public static final int team1emblem=0x7f080008; public static final int team1goals=0x7f080009; public static final int team1name=0x7f080007; public static final int team2emblem=0x7f08000c; public static final int team2goals=0x7f08000b; public static final int team2name=0x7f08000d; public static final int teamsSeparator=0x7f08000a; public static final int venue=0x7f080002; } public static final class layout { public static final int activity_main=0x7f030000; public static final int activity_match=0x7f030001; public static final int activity_matchday=0x7f030002; public static final int listitem_match=0x7f030003; } public static final class menu { public static final int matchday=0x7f070000; public static final int matches_context_menu=0x7f070001; } public static final class string { public static final int action_goto=0x7f050001; public static final int app_name=0x7f050000; public static final int by=0x7f050005; public static final int own_goal=0x7f050003; public static final int penalty=0x7f050004; public static final int title_activity_match=0x7f050002; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f060000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f060001; } }
922e483b9272f5e3de63528b925e3e794ff89924
1,951
java
Java
src/main/java/dev/lambdaurora/spruceui/hud/component/TextHudComponent.java
Stealthii/SpruceUI
a84dd3befe9f928e43b1fab76ddf224fea894ae2
[ "MIT" ]
47
2020-08-19T09:49:45.000Z
2022-03-17T09:51:01.000Z
src/main/java/dev/lambdaurora/spruceui/hud/component/TextHudComponent.java
PseudoDistant/SpruceUI
82c86a6a7609f4c9b101067c1182d6837ee67e01
[ "MIT" ]
12
2020-08-15T15:53:55.000Z
2021-11-27T10:36:48.000Z
src/main/java/dev/lambdaurora/spruceui/hud/component/TextHudComponent.java
PseudoDistant/SpruceUI
82c86a6a7609f4c9b101067c1182d6837ee67e01
[ "MIT" ]
27
2020-06-28T18:35:56.000Z
2022-03-05T00:51:41.000Z
23.590361
112
0.643514
994,696
/* * Copyright © 2020 LambdAurora <nnheo@example.com> * * This file is part of SpruceUI. * * Licensed under the MIT license. For more information, * see the LICENSE file. */ package dev.lambdaurora.spruceui.hud.component; import dev.lambdaurora.spruceui.hud.HudComponent; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.DrawableHelper; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.text.Text; import net.minecraft.util.Identifier; /** * Represents a text HUD component. * * @author LambdAurora * @version 3.2.1 * @since 1.3.5 */ public class TextHudComponent extends HudComponent { protected MinecraftClient client; protected Text text; protected int color; public TextHudComponent(Identifier identifier, int x, int y, Text text) { this(identifier, x, y, text, 0xffffffff); } public TextHudComponent(Identifier identifier, int x, int y, Text text, int color) { super(identifier, x, y); this.client = MinecraftClient.getInstance(); this.text = text; this.color = color; } /** * Gets this component's text. * * @return the component's text */ public Text getText() { return this.text; } /** * Sets this component's text. * * @param text the text */ public void setText(Text text) { this.text = text; } /** * Gets this component's text color. * * @return the text color */ public int getColor() { return this.color; } /** * Sets this component's text color. * * @param color the text color */ public void setColor(int color) { this.color = color; } @Override public void render(MatrixStack matrices, float tickDelta) { DrawableHelper.drawTextWithShadow(matrices, client.textRenderer, this.text, this.x, this.y, this.color); } }
922e493aacdd939e8f0650109cf5dcb3346ba071
4,137
java
Java
src/main/java/net/jitse/apollo/bungeecord/socket/SocketHandler.java
JitseB/Apollo
42dfb0ea8bc29d30b7b9e19eb8c77db8570e4764
[ "Apache-2.0" ]
6
2017-11-08T09:57:21.000Z
2021-03-27T09:29:12.000Z
src/main/java/net/jitse/apollo/bungeecord/socket/SocketHandler.java
JitseB/Apollo
42dfb0ea8bc29d30b7b9e19eb8c77db8570e4764
[ "Apache-2.0" ]
null
null
null
src/main/java/net/jitse/apollo/bungeecord/socket/SocketHandler.java
JitseB/Apollo
42dfb0ea8bc29d30b7b9e19eb8c77db8570e4764
[ "Apache-2.0" ]
2
2017-11-05T14:51:08.000Z
2017-12-01T20:29:23.000Z
39.4
126
0.576988
994,697
package net.jitse.apollo.bungeecord.socket; /* * A server overview system for Minecraft networks. * Copyright (C) 2017 Jitse Boonstra * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law sor agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.s */ import com.corundumstudio.socketio.Configuration; import com.corundumstudio.socketio.SocketIOServer; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import net.jitse.apollo.bungeecord.ApolloBungeeCord; import net.jitse.apollo.datatype.DataType; import java.sql.SQLException; /** * @auhor Jitse B. * @since 11.23.2017 */ public class SocketHandler { private SocketIOServer server; public SocketHandler(ApolloBungeeCord plugin) { Configuration config = new Configuration(); config.setHostname("localhost"); config.setPingInterval(5000); config.setPingTimeout(10000); config.setPort(plugin.getConfig().getConfig().getInt("SocketPort")); server = new SocketIOServer(config); server.addEventListener("server_list", null, (client, data, ackRequest) -> { int limit = plugin.getConfig().getConfig().getInt("ServerListSize"); plugin.getMySql().select("SELECT * FROM ApolloServers WHERE Name IS NOT NULL LIMIT " + limit + ";", resultSet -> { try { JsonArray servers = new JsonArray(); while (resultSet.next()) { JsonObject serverData = new JsonObject(); for (DataType type : DataType.values()) { Object value = resultSet.getObject(type.getSQLName()); if (value instanceof String) { serverData.addProperty(type.getSQLName(), (String) value); } else if (value instanceof Boolean) { serverData.addProperty(type.getSQLName(), (Boolean) value); } else if (value instanceof Number) { serverData.addProperty(type.getSQLName(), (Number) value); } else { throw new IllegalStateException("Invalid primitive type for " + type.toString() + "!"); } } servers.add(serverData); } client.sendEvent("server_list", "", servers.toString()); } catch (SQLException | IllegalStateException exception) { client.sendEvent("server_list", exception.getMessage()); } }); }); // Todo in future: Change these to sql based values for RedisBungee support. server.addEventListener("total_players", null, (client, data, ackRequest) -> { int total = plugin.getProxy().getOnlineCount(); client.sendEvent("total_players", total); }); server.addEventListener("player_record", null, (client, data, ackRequest) -> { plugin.getMySql().select("SELECT Record FROM ApolloStats;", resultSet -> { try { int record = 0; if (resultSet.next()) { record = resultSet.getInt("record"); } client.sendEvent("player_record", "", record); } catch (SQLException | IllegalStateException exception) { client.sendEvent("player_record", exception.getMessage()); } }); }); server.start(); } public void stop() { server.stop(); } }
922e49cf5136b735c0c2c63b73310442b5821415
2,872
java
Java
hekate-core/src/main/java/io/hekate/election/Candidate.java
Inkon/hekate
abe6ec59edeaa83f0016da9ed16aae4ded7e5cab
[ "Apache-2.0" ]
null
null
null
hekate-core/src/main/java/io/hekate/election/Candidate.java
Inkon/hekate
abe6ec59edeaa83f0016da9ed16aae4ded7e5cab
[ "Apache-2.0" ]
null
null
null
hekate-core/src/main/java/io/hekate/election/Candidate.java
Inkon/hekate
abe6ec59edeaa83f0016da9ed16aae4ded7e5cab
[ "Apache-2.0" ]
null
null
null
39.888889
138
0.711699
994,698
/* * Copyright 2019 The Hekate Project * * The Hekate Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.hekate.election; /** * Leader election candidate. * * <p> * Implementations of this interface can be registered within the {@link ElectionService} in order to participate in the leader * election process. If this candidate wins then its {@link #becomeLeader(LeaderContext)} method will be called. If some other candidate * wins then this candidate will be notified via {@link #becomeFollower(FollowerContext)} method. If later on the existing leader leaves * the cluster or {@link LeaderContext#yieldLeadership() yeilds leadship} then this candidate will try again to become a new leader. If * it finally succeeds then {@link #becomeLeader(LeaderContext)} method will be called. * </p> * * <p> * For more details about the leader election process please see the documentation of {@link ElectionService} interface. * </p> * * @see ElectionServiceFactory#withCandidate(CandidateConfig) */ public interface Candidate { /** * Gets called when this candidate becomes a group leader. * * <p> * <b>IMPORTANT:</b> Implementations of this method should not block the calling thread for a long time and should execute all long * running computations asynchronously. * </p> * * @param ctx Leader context. */ void becomeLeader(LeaderContext ctx); /** * Gets called when this candidate couldn't win elections and switched to the follower state. Information about the current leader can * be obtained via {@link FollowerContext#leader()}. * * <p> * <b>IMPORTANT:</b> Implementations of this method should not block the calling thread for a long time and should execute all long * running computations asynchronously. * </p> * * @param ctx Follower context. */ void becomeFollower(FollowerContext ctx); /** * Gets called when candidate must be terminated because of the {@link ElectionService} being stopped. * * <p> * Note that this method will NOT be called if this candidate never reached any of the Leader/Follower state (i.e. if {@link * #becomeLeader(LeaderContext)} or {@link #becomeFollower(FollowerContext)} were never called). * </p> */ void terminate(); }
922e4b8bf530d4eb0e1744696358cbd28109b3dc
270
java
Java
bomberman_app/app/src/main/java/main/nongameobject/Background.java
slawyn/app-bomberman-canvas-legacy
fdc290972c6406203dd23a20f149d24c6c3b352c
[ "Apache-2.0" ]
null
null
null
bomberman_app/app/src/main/java/main/nongameobject/Background.java
slawyn/app-bomberman-canvas-legacy
fdc290972c6406203dd23a20f149d24c6c3b352c
[ "Apache-2.0" ]
null
null
null
bomberman_app/app/src/main/java/main/nongameobject/Background.java
slawyn/app-bomberman-canvas-legacy
fdc290972c6406203dd23a20f149d24c6c3b352c
[ "Apache-2.0" ]
null
null
null
24.545455
65
0.762963
994,699
package main.nongameobject; import main.buildingblocks.AnimationSet; import main.nongameobject.NonGameObject; public class Background extends NonGameObject { public Background(int posx, int posy, AnimationSet animset) { super(posx, posy, animset); } }
922e4c501f3c9c0ef1b2229325259fd020f3b958
1,049
java
Java
src/viewmodels/ViewModelFactory.java
sebsmgzz/OakTwister
7fefa933ad17bdf850baad7602282f1f190c9687
[ "Apache-2.0" ]
null
null
null
src/viewmodels/ViewModelFactory.java
sebsmgzz/OakTwister
7fefa933ad17bdf850baad7602282f1f190c9687
[ "Apache-2.0" ]
null
null
null
src/viewmodels/ViewModelFactory.java
sebsmgzz/OakTwister
7fefa933ad17bdf850baad7602282f1f190c9687
[ "Apache-2.0" ]
null
null
null
24.395349
62
0.672069
994,700
package viewmodels; import management.Manager; public class ViewModelFactory { private final Manager manager; private HomeViewModel homeViewModel; private LateralPaneViewModel lateralPaneViewModel; private PlatformsViewModel platformsViewModel; public HomeViewModel getHomeViewModel() { if(homeViewModel == null) { homeViewModel = new HomeViewModel(); } return homeViewModel; } public LateralPaneViewModel getLateralPaneViewModel() { if(lateralPaneViewModel == null) { lateralPaneViewModel = new LateralPaneViewModel(); } return lateralPaneViewModel; } public PlatformsViewModel getPlatformsViewModel() { if(platformsViewModel == null) { platformsViewModel = new PlatformsViewModel(); } return platformsViewModel; } public PaneViewModel getPaneViewModel() { return new PaneViewModel(); } public ViewModelFactory(Manager manager) { this.manager = manager; } }
922e4d7326517b5a58d38eb4864fe95b03c8bce0
1,541
java
Java
legacy-core/src/main/java/archimedes/legacy/gui/indices/IndexMetaDataListModel.java
greifentor/archimedes-legacy
32eac85cba6e82b2c2001b339cb6af20b11799b9
[ "Apache-2.0" ]
null
null
null
legacy-core/src/main/java/archimedes/legacy/gui/indices/IndexMetaDataListModel.java
greifentor/archimedes-legacy
32eac85cba6e82b2c2001b339cb6af20b11799b9
[ "Apache-2.0" ]
27
2021-03-11T13:09:39.000Z
2021-11-19T07:14:13.000Z
legacy-core/src/main/java/archimedes/legacy/gui/indices/IndexMetaDataListModel.java
greifentor/archimedes-legacy
32eac85cba6e82b2c2001b339cb6af20b11799b9
[ "Apache-2.0" ]
null
null
null
20.546667
77
0.646334
994,701
/* * IndexMetaDataListModel.java * * 15.12.2011 * * (c) by ollie * */ package archimedes.legacy.gui.indices; import javax.swing.ListModel; import javax.swing.event.ListDataListener; import archimedes.model.IndexMetaData; /** * Eine <CODE>ListModel</CODE>-Implementierung zur Darstellung von * <CODE>IndexMetaData</CODE> Implementierungen in der GUI. * * @author ollie * * @changed OLI 15.12.2011 - Hinzugef&uuml;gt. */ public class IndexMetaDataListModel implements ListModel { private IndexMetaData[] list = null; /** * Erzeugt ein neues ListModel auf Basis der angegebenen Liste von * IndexMetaData-Objekten. * * @param indices * Die Liste der <CODE>IndexMetaData</CODE>, die durch das Model * repr&auml;sentiert werden soll. * * @changed OLI 15.12.2011 - Hinzugef&uuml;gt. */ public IndexMetaDataListModel(IndexMetaData[] indices) { super(); this.list = indices; } /** * @changed OLI 15.12.2011 - Hinzugef&uuml;gt. */ @Override public void addListDataListener(ListDataListener l) { } /** * @changed OLI 15.12.2011 - Hinzugef&uuml;gt. */ @Override public Object getElementAt(int index) { return this.list[index]; } /** * @changed OLI 15.12.2011 - Hinzugef&uuml;gt. */ @Override public int getSize() { return this.list.length; } /** * @changed OLI 15.12.2011 - Hinzugef&uuml;gt. */ @Override public void removeListDataListener(ListDataListener l) { } }
922e4e94b67801c24898b67a17b30fee12b997f2
4,215
java
Java
core/src/hoffinc/gdxtrials1/Trial106_MeshRectangle.java
robert-hoff/libgdxtrials-lsystem-plants
0d2dde26358b2029311025a8f4d6b24ee7e3dd5f
[ "MIT" ]
null
null
null
core/src/hoffinc/gdxtrials1/Trial106_MeshRectangle.java
robert-hoff/libgdxtrials-lsystem-plants
0d2dde26358b2029311025a8f4d6b24ee7e3dd5f
[ "MIT" ]
null
null
null
core/src/hoffinc/gdxtrials1/Trial106_MeshRectangle.java
robert-hoff/libgdxtrials-lsystem-plants
0d2dde26358b2029311025a8f4d6b24ee7e3dd5f
[ "MIT" ]
null
null
null
28.869863
91
0.698932
994,702
package hoffinc.gdxtrials1; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Graphics; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.utils.ScreenUtils; import hoffinc.utils.ApplicationProp; /* * Draws a line outline of a rectangle using Model (com.badlogic.gdx.graphics.g3d.Model) * */ public class Trial106_MeshRectangle extends ApplicationAdapter { private Environment environment; private PerspectiveCamera cam; private CameraInputController camController; private ModelBatch modelBatch; private Model rectangleModel; private ModelInstance modelInstance; @Override public void create () { setTitle("Rectangle outline as Model"); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(4f, 4f, 10f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); modelBatch = new ModelBatch(); Material mat = new Material(ColorAttribute.createDiffuse(Color.BLACK)); // float x00, y00, z00 // float x10, y10, z10 // float x11, y11, z11 // float x01, y01, z01 // float normalX, normalY, normalZ, // int primitiveType, Material material, long attributes ModelBuilder modelBuilder = new ModelBuilder(); rectangleModel = modelBuilder.createRect( 0,0,0, 5,0,0, 5,5,0, 0,5,0, 0,0,1, GL20.GL_LINES, mat, Usage.Position); modelInstance = new ModelInstance(rectangleModel); // ModelInstance } @Override public void render () { Gdx.gl20.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); ScreenUtils.clear(1, 1, 1, 1); modelBatch.begin(cam); modelBatch.render(modelInstance, environment); modelBatch.end(); if(Gdx.input.isKeyPressed(Keys.ESCAPE)) { Gdx.app.exit(); } } @Override public void dispose () { modelBatch.dispose(); rectangleModel.dispose(); // save window x,y and window width,height // NOTE - The initial size of the window is set from the Desktop-launcher Lwjgl3Graphics lwjgl3 = (Lwjgl3Graphics) Gdx.graphics; int win_width = lwjgl3.getWidth(); int win_height = lwjgl3.getHeight(); int win_x = lwjgl3.getWindow().getPositionX(); int win_y = lwjgl3.getWindow().getPositionY(); String FILENAME = "app.auto.properties"; ApplicationProp prop = new ApplicationProp(FILENAME); prop.addProperty("WIN_WIDTH", ""+win_width); prop.addProperty("WIN_HEIGHT", ""+win_height); prop.addProperty("WIN_X", ""+win_x); prop.addProperty("WIN_Y", ""+win_y); prop.saveToFile(); } public static void showFloatArray(float[] a) { if (a.length == 0) { System.err.println("[]"); } else { System.err.printf("["); for (int i = 0; i < a.length; i++) { System.err.printf("%7.3f", a[i]); } System.err.println("]"); } } static private void setTitle(String title) { try { ((Lwjgl3Graphics) Gdx.graphics).getWindow().setTitle(title); } catch (Exception e) {} } }
922e4f54489dde23296e7163e611fe267ee5a3a0
991
java
Java
chapter-2-classes-and-objects-a-trip-to-objectville/compiler2.java
destinymalone/head-first-java-cliffsnotes-example
37ac5fa36be290df8ce0973611f12acc13ca32f4
[ "MIT" ]
null
null
null
chapter-2-classes-and-objects-a-trip-to-objectville/compiler2.java
destinymalone/head-first-java-cliffsnotes-example
37ac5fa36be290df8ce0973611f12acc13ca32f4
[ "MIT" ]
2
2020-01-23T21:27:10.000Z
2020-01-29T16:45:07.000Z
chapter-2-classes-and-objects-a-trip-to-objectville/compiler2.java
destinymalone/head-first-java-cliffsnotes-example
37ac5fa36be290df8ce0973611f12acc13ca32f4
[ "MIT" ]
null
null
null
19.057692
89
0.573158
994,703
// Note: all of your .java source files should be named whatever your superclass name is. // DVDPlayer.java class DVDPlayer { boolean canRecord = false; void recordDVD() { System.out.println("DVD recording"); } } class DVDPlayerTestDrive { public static void main(String[] args) { DVDPlayer d = new DVDPlayer; d.canRecord = true; d.playDVD(); if (d.canRecord == true) { d.recordDVD(); } } } // Solution class DVDPlayer { boolean canRecord = false; void recordDVD() { System.out.println("DVD recording"); } void playDVD() { System.out.println("DVD playing"); } } class DVDPlayerTestDrive { public static void main(String[] args) { DVDPlayer d = new DVDPlayer(); d.canRecord = true; d.playDVD(); if (d.canRecord == true) { d.recordDVD(); } } } // The line: d.playDVD(); wouldn't compile without a method.
922e500fa8b07d9f277f10d92c62e04d9a2c4890
1,039
java
Java
gwt-chrome-api/src/com/google/gwt/chrome/history/HistoryQueryDetails.java
spoole/ARC
c5134fd39c7d9584c066757066cf192b3e9789e7
[ "Apache-2.0" ]
null
null
null
gwt-chrome-api/src/com/google/gwt/chrome/history/HistoryQueryDetails.java
spoole/ARC
c5134fd39c7d9584c066757066cf192b3e9789e7
[ "Apache-2.0" ]
null
null
null
gwt-chrome-api/src/com/google/gwt/chrome/history/HistoryQueryDetails.java
spoole/ARC
c5134fd39c7d9584c066757066cf192b3e9789e7
[ "Apache-2.0" ]
null
null
null
28.081081
90
0.66795
994,704
package com.google.gwt.chrome.history; import com.google.gwt.core.client.JavaScriptObject; /** * Create an object to be used with {@link History#getVisits()), * {@link History#addUrl()) or {@link History#deleteUrl()) * * To create an instance of this object use {@link HistoryQueryDetails#create()} function. * @author Pawel Psztyc * */ public class HistoryQueryDetails extends JavaScriptObject { protected HistoryQueryDetails() { } /** * Create an instance of an overlay JS object. * This is only method to create an instance of this object. * @return Instance of this object */ public static final native HistoryQueryDetails create() /*-{ return {}; }-*/; /** * * @param url * The URL for which to retrieve visit information or add or to * remove. It must be in the format as returned from a call to * history.search. */ public final native void setUrl(String url) /*-{ this.url = url; }-*/; public final native String getUrl() /*-{ return this.url; }-*/; }
922e502e801f300d39fea32f411a6cb6d12a8dd4
234
java
Java
src/main/java/test/TestManejoPersonas.java
igorariza/JavaMedicCenterJDBC
adcb91b99ade2457cc78fd5cb068aa1d1189b625
[ "MIT" ]
null
null
null
src/main/java/test/TestManejoPersonas.java
igorariza/JavaMedicCenterJDBC
adcb91b99ade2457cc78fd5cb068aa1d1189b625
[ "MIT" ]
null
null
null
src/main/java/test/TestManejoPersonas.java
igorariza/JavaMedicCenterJDBC
adcb91b99ade2457cc78fd5cb068aa1d1189b625
[ "MIT" ]
null
null
null
15.6
53
0.683761
994,705
package test; import data.PersonaDAO; import domain.Persona; import java.util.List; public class TestManejoPersonas { public static void main(String[] args) { PersonaDAO personaDAO = new PersonaDAO(); } }
922e50dddec11548695098a5d417517bdfdc3191
1,004
java
Java
jutrack-core/src/main/java/com/github/ibiber/jutrack/domain/data/jira/HistoryItem.java
iBiber/uTrack
ea0ba47e93e5ba8498424c00d97756e2101de63c
[ "Apache-2.0" ]
1
2019-05-23T07:42:34.000Z
2019-05-23T07:42:34.000Z
jutrack-core/src/main/java/com/github/ibiber/jutrack/domain/data/jira/HistoryItem.java
iBiber/uTrack
ea0ba47e93e5ba8498424c00d97756e2101de63c
[ "Apache-2.0" ]
13
2017-10-04T11:20:15.000Z
2018-03-28T10:15:41.000Z
jutrack-core/src/main/java/com/github/ibiber/jutrack/domain/data/jira/HistoryItem.java
iBiber/uTrack
ea0ba47e93e5ba8498424c00d97756e2101de63c
[ "Apache-2.0" ]
1
2017-09-07T21:54:51.000Z
2017-09-07T21:54:51.000Z
30.424242
120
0.595618
994,706
package com.github.ibiber.jutrack.domain.data.jira; public class HistoryItem { public final String field; public final String fieldtype; public final String from; public final String fromString; public final String to; public final String toString; /** Constructor needed by framework */ HistoryItem() { this(null, null, null, null, null, null); } public HistoryItem(String field, String fieldtype, String from, String fromString, String to, String toString) { super(); this.field = field; this.fieldtype = fieldtype; this.from = from; this.fromString = fromString; this.to = to; this.toString = toString; } @Override public String toString() { return "ChangelogHistoryItem [field=" + field + ", fieldtype=" + fieldtype + ", from=" + from + ", fromString=" + fromString + ", to=" + to + ", toString=" + toString + "]"; } }
922e521b0fd8e690cb803f9fa42e861d2ef58918
25,240
java
Java
src/test/java/ch/uzh/ifi/hase/soprafs21/service/GameServiceTest.java
sopra-fs21-group-24/server
f94dc0b95ea14d4a20e11fe3758f659f306d6b14
[ "MIT" ]
1
2021-03-22T10:17:17.000Z
2021-03-22T10:17:17.000Z
src/test/java/ch/uzh/ifi/hase/soprafs21/service/GameServiceTest.java
sopra-fs21-group-24/server
f94dc0b95ea14d4a20e11fe3758f659f306d6b14
[ "MIT" ]
92
2021-03-24T19:52:41.000Z
2021-05-29T16:18:50.000Z
src/test/java/ch/uzh/ifi/hase/soprafs21/service/GameServiceTest.java
sopra-fs21-group-24/server
f94dc0b95ea14d4a20e11fe3758f659f306d6b14
[ "MIT" ]
null
null
null
32.993464
108
0.664897
994,707
package ch.uzh.ifi.hase.soprafs21.service; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import ch.uzh.ifi.hase.soprafs21.entity.*; import ch.uzh.ifi.hase.soprafs21.entity.gamemodes.Clouds; import ch.uzh.ifi.hase.soprafs21.entity.gamemodes.Pixelation; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import ch.uzh.ifi.hase.soprafs21.entity.gamemodes.Time; import ch.uzh.ifi.hase.soprafs21.entity.usermodes.MultiPlayer; import ch.uzh.ifi.hase.soprafs21.entity.usermodes.SinglePlayer; import ch.uzh.ifi.hase.soprafs21.exceptions.NotCreatorException; import ch.uzh.ifi.hase.soprafs21.exceptions.NotFoundException; import ch.uzh.ifi.hase.soprafs21.exceptions.PreconditionFailedException; import ch.uzh.ifi.hase.soprafs21.exceptions.UnauthorizedException; import ch.uzh.ifi.hase.soprafs21.repository.GameRepository; import ch.uzh.ifi.hase.soprafs21.repository.UserRepository; public class GameServiceTest { @Mock private ScoreService scoreService; @Mock private QuestionService questionService; @Mock private LobbyService lobbyService; @Mock private UserService userService; @Mock private GameRepository gameRepository; @Mock private UserRepository userRepository; @InjectMocks private GameService gameService; private GameEntity testGame; private User user; private Answer answer; private Question question; private Score score; private Lobby lobby; @BeforeEach public void setup() { MockitoAnnotations.openMocks(this); // sample User user = new User(); user.setId(2L); user.setUsername("Max"); user.setToken("maximilian"); user.setPassword("sicher"); // sampe Anwser answer = new Answer(); answer.setGameId(1L); answer.setUserId(1L); answer.setCoordGuess(new Coordinate(1.0, 1.2)); answer.setQuestionId(0L); question = new Question(); question.setCoordinate(new Coordinate(-44.247274, 168.828488)); question.setZoomLevel(15); question.setQuestionId(10L); score = new Score(); score.setTempScore(100L); score.setTotalScore(50L); score.setLastCoordinate(new Coordinate(15.15,15.15)); // given testGame = new GameEntity(); testGame.setCreatorUserId(1L); testGame.setGameId(1L); testGame.setGameMode(new Time()); testGame.setLobbyId(null); testGame.setBreakDuration(40); testGame.setUserMode(new SinglePlayer()); List<Long> userAnsweredList = new ArrayList<>(); userAnsweredList.add(user.getId()); testGame.setUsersAnswered(userAnsweredList); testGame.setCurrentTime(); testGame.setRoundStart(System.currentTimeMillis()-10); lobby = new Lobby(); lobby.setCreator(9L); lobby.setId(14L); lobby.setGameId(testGame.getGameId()); lobby.setPublicStatus(true); // user list initial List<Long> usersInitial = new ArrayList<>(); usersInitial.add(testGame.getCreatorUserId()); testGame.setUserIds(usersInitial); // when -> any object is being save in the userRepository -> return the dummy testUser Mockito.when(gameRepository.save(Mockito.any())).thenReturn(testGame); } @AfterEach void tearDown() { } // Some Checks and Helper functions @Test void checkAuthSuccess() { // sample header, not null for token Map<String, String> header = new HashMap<>(); header.put("token", "maximilian"); // precondition: invalid input in header gets catched in userService tests when(userService.getUserByToken(Mockito.any())).thenReturn(user); assertDoesNotThrow(() -> gameService.checkAuth(header)); } @Test void checkAuthFail() { // sample header, not null for token Map<String, String> header = new HashMap<>(); header.put("token", ""); // precondition: invalid input in header gets catched in userService tests when(userService.getUserByToken(Mockito.any())).thenThrow(new NotFoundException("Failed")); // logic and token not in header assertAll( () -> assertThrows(UnauthorizedException.class, () -> gameService.checkAuth(header)), () -> assertThrows(UnauthorizedException.class, () -> gameService.checkAuth(new HashMap<>())) ); } @Test void checkPartofGameSuccess() { // add user to game (global) List<Long> userIds = new ArrayList<>(); userIds.add(user.getId()); testGame.setUserIds(userIds); assertDoesNotThrow(() -> gameService.checkPartofGame(testGame, user)); } void checkPartofGameFailure() { // user wich is not in game assertThrows(UnauthorizedException.class, () -> gameService.checkPartofGame(testGame, user)); } @Test void checkGameCreatorSuccess() { // user (global) is gamecreator testGame.setCreatorUserId(user.getId()); assertDoesNotThrow(() -> gameService.checkGameCreator(testGame, user)); } @Test void checkGameCreatorFailure() { // user wich is not the game creator assertThrows(NotCreatorException.class, () -> gameService.checkGameCreator(testGame, user)); } @Test void gameByIdSuccess() { // precondition on database when(gameRepository.findById(Mockito.any())).thenReturn(Optional.ofNullable(testGame)); assertDoesNotThrow(() -> gameService.gameById(testGame.getGameId())); // there is no need to check correctness of return } @Test void gameByIdFailure() { when(gameRepository.findById(Mockito.any())).thenReturn(Optional.empty()); assertThrows(NotFoundException.class, () -> gameService.gameById(111L)); } // ExistsGameByCreatorModded @Test void existsGameByCreatorModded() { } // Create Game Functionality @Test void createGameGeneralSuccess() { // setting missing components testGame.setCreatorUserId(user.getId()); // visual, but userService doesn't return // sanity check GameEntity game = assertDoesNotThrow(() -> gameService.createGame(testGame, true)); // userlist of one user (host) List<Long> expectedList = new ArrayList<>(); expectedList.add(testGame.getCreatorUserId()); assertEquals(expectedList, game.getUserIds()); // basic stuff assertEquals(testGame.getGameId(), game.getGameId()); assertEquals(testGame.getGameMode(), game.getGameMode()); assertEquals(testGame.getLobbyId(), game.getLobbyId()); assertEquals(testGame.getBreakDuration(), game.getBreakDuration()); assertEquals(testGame.getUserMode(), game.getUserMode()); } @Test void createGameMultiplayerSuccess() { // setting missing components testGame.setCreatorUserId(user.getId()); // visual, but userService doesn't return testGame.setUserMode(new MultiPlayer()); // dummy lobby Lobby lobby = new Lobby(); lobby.setId(1337L); lobby.setCreator(testGame.getCreatorUserId()); lobby.setPublicStatus(true); lobby.setGameId(testGame.getGameId()); when(lobbyService.createLobby(Mockito.any())).thenReturn(lobby); // sanity check GameEntity game = assertDoesNotThrow(() -> gameService.createGame(testGame, true)); // checks on returned object assertNotNull(game.getLobbyId()); // check general again createGameGeneralSuccess(); } @Test void createGameSingleplayerSuccess() { // setting missing components testGame.setCreatorUserId(user.getId()); // visual, but userService doesn't return // sanity check GameEntity game = assertDoesNotThrow(() -> gameService.createGame(testGame, true)); // checks on returned object assertNull(game.getLobbyId()); // check general again createGameGeneralSuccess(); } @Test void createGameFailureOnUser() { // setting missing components testGame.setCreatorUserId(user.getId()); // creatorid is not in the database when(userService.getUserByUserId(Mockito.any())).thenThrow(NotFoundException.class); // user is not in db assertThrows(NotFoundException.class, () -> gameService.createGame(testGame, true)); } @Test void createGameAlreadyExists() { // setting missing components testGame.setCreatorUserId(user.getId()); // simulate: return existing game in db when(gameRepository.findByCreatorUserId(Mockito.any())).thenReturn(Optional.of(testGame)); // fail on existsGameCreatorModded // newGame with same creatorUserId in db GameEntity newGame = new GameEntity(); newGame.setCreatorUserId(user.getId()); newGame.setGameId(11L); newGame.setGameMode(new Time()); newGame.setLobbyId(null); newGame.setBreakDuration(40); newGame.setUserMode(new SinglePlayer()); assertThrows(PreconditionFailedException.class, () -> gameService.createGame(newGame, true)); } @Test void createQuestionList() { // test not necessary when(questionService.count()).thenReturn(1L); List<Long> expected = new ArrayList<>(); expected.add(0L); expected.add(0L); expected.add(0L); assertEquals(gameService.createQuestionList(), expected); } // StartGame Functionality // TODO @Test void startGameGeneralSucess() { // given: game is in system when(questionService.count()).thenReturn(3L); when(gameRepository.findById(Mockito.any())).thenReturn(Optional.ofNullable(testGame)); gameService.startGame(testGame.getGameId()); assertAll( () -> assertEquals(testGame.getRound(), 1), () -> assertNotNull(testGame.getRoundStart()), () -> assertNotNull(testGame.getGameStartTime()), () -> assertNotNull(testGame.getQuestions()) ); } @Test void startGameSinglePlayerSuccess() { // Singleplayer settings List<Long> expected = new ArrayList<>(); expected.add(testGame.getCreatorUserId()); // general check startGameGeneralSucess(); // singleplayer specific tests assertEquals(expected, testGame.getUserIds()); } @Test void startGameSinglePlayerFailure() { // singleplayer failure testGame.getUserIds().add(3L); // given game in system when(questionService.count()).thenReturn(3L); when(gameRepository.findById(Mockito.any())).thenReturn(Optional.ofNullable(testGame)); assertThrows(PreconditionFailedException.class, () -> gameService.startGame(testGame.getGameId())); } @Test void startGameMultiPlayerSuccess() { // multiplayer settings testGame.setUserMode(new MultiPlayer()); List<Long> expected = new ArrayList<>(); expected.add(testGame.getCreatorUserId()); expected.add(3L); Lobby lobby = new Lobby(); lobby.setCreator(testGame.getCreatorUserId()); lobby.setGameId(testGame.getGameId()); lobby.setPublicStatus(true); lobby.setUsers(expected); // given when(lobbyService.getLobbyById(Mockito.any())).thenReturn(lobby); // general check startGameGeneralSucess(); // multiplayer specifc tests assertAll( () -> assertEquals(expected, testGame.getUserIds()), () -> assertNull(testGame.getLobbyId()) ); } @Test void startGameInvalidGameIdFailure() { // given when(questionService.count()).thenReturn(3L); // invalid gameId Long gameId = 1337L; // throws exception assertThrows(NotFoundException.class, () -> gameService.startGame(gameId));; } @Test void startGameAlreadyStartedFailure() { // given when(questionService.count()).thenReturn(3L); when(gameRepository.findById(Mockito.any())).thenReturn(Optional.ofNullable(testGame)); // start game gameService.startGame(testGame.getGameId()); // should throw error assertThrows(PreconditionFailedException.class, () -> gameService.startGame(testGame.getGameId()));; } // MakeGuess Functionality @Test void makeGuessGeneralSucess() { //set some things for passing of checks, check for success List<Long> questionsList = new ArrayList<Long>(); questionsList.add(question.getQuestionId()); questionsList.add(11L); testGame.setQuestions(questionsList); answer.setQuestionId(1L); testGame.setRound(1); answer.setQuestionId(question.getQuestionId()); when(questionService.count()).thenReturn(3L); when(questionService.questionById(Mockito.any())).thenReturn(question); when(gameRepository.findById(Mockito.any())).thenReturn(Optional.ofNullable(testGame)); when(scoreService.findById(Mockito.any())).thenReturn(score); Score returnedScore = gameService.makeGuess(answer); assertTrue(returnedScore instanceof Score); assertEquals(returnedScore.getTotalScore(), score.getTotalScore()); assertEquals(returnedScore.getLastCoordinate(), score.getLastCoordinate()); } @Test void makeGuessTimeSuccess() { //longer time to answer - 50 score testGame.setRoundStart(System.currentTimeMillis()-20000); //set some things for passing of checks, check for success List<Long> questionsList = new ArrayList<Long>(); questionsList.add(question.getQuestionId()); questionsList.add(11L); testGame.setQuestions(questionsList); answer.setQuestionId(1L); testGame.setRound(1); testGame.setGameMode(new Time()); answer.setQuestionId(question.getQuestionId()); when(questionService.count()).thenReturn(3L); when(questionService.questionById(Mockito.any())).thenReturn(question); when(gameRepository.findById(Mockito.any())).thenReturn(Optional.ofNullable(testGame)); when(scoreService.findById(Mockito.any())).thenReturn(score); long scorePreChange = score.getTotalScore(); Score returnedScore = gameService.makeGuess(answer); assertTrue(returnedScore instanceof Score); assertEquals(returnedScore.getTotalScore(), score.getTotalScore()); System.out.println((returnedScore.getTotalScore())); assertEquals(returnedScore.getUserId(), score.getUserId()); assertEquals(answer.getDifficultyFactor(),1); assertEquals(returnedScore.getLastCoordinate(), score.getLastCoordinate()); } @Test void makeGuessCloudsSuccess() { //set some things for passing of checks, check for success List<Long> questionsList = new ArrayList<Long>(); questionsList.add(question.getQuestionId()); questionsList.add(11L); testGame.setQuestions(questionsList); answer.setQuestionId(1L); testGame.setRound(1); testGame.setGameMode(new Clouds()); answer.setQuestionId(question.getQuestionId()); when(questionService.count()).thenReturn(3L); when(questionService.questionById(Mockito.any())).thenReturn(question); when(gameRepository.findById(Mockito.any())).thenReturn(Optional.ofNullable(testGame)); when(scoreService.findById(Mockito.any())).thenReturn(score); Score returnedScore = gameService.makeGuess(answer); assertTrue(returnedScore instanceof Score); assertEquals(returnedScore.getTotalScore(), score.getTotalScore()); assertEquals(returnedScore.getLastCoordinate(), score.getLastCoordinate()); } @Test void makeGuessPixelationSuccess() { //set some things for passing of checks, check for success answer.setQuestionId(1L); testGame.setRound(1); testGame.setGameMode(new Pixelation()); answer.setQuestionId(question.getQuestionId()); List<Long> questionsList = new ArrayList<Long>(); questionsList.add(question.getQuestionId()); questionsList.add(11L); testGame.setQuestions(questionsList); when(questionService.count()).thenReturn(3L); when(questionService.questionById(Mockito.any())).thenReturn(question); when(gameRepository.findById(Mockito.any())).thenReturn(Optional.ofNullable(testGame)); when(scoreService.findById(Mockito.any())).thenReturn(score); Score returnedScore = gameService.makeGuess(answer); assertTrue(returnedScore instanceof Score); assertEquals(returnedScore.getTotalScore(), score.getTotalScore()); assertEquals(returnedScore.getLastCoordinate(), score.getLastCoordinate()); } @Test void makeGuessTimeFailure_TakeToLongToAnswer() { //set round start to far in the past testGame.setRoundStart(System.currentTimeMillis()-200000); //set some things for passing of checks, check for success List<Long> questionsList = new ArrayList<Long>(); questionsList.add(question.getQuestionId()); questionsList.add(11L); testGame.setQuestions(questionsList); answer.setQuestionId(1L); testGame.setRound(1); testGame.setGameMode(new Time()); answer.setQuestionId(question.getQuestionId()); when(questionService.count()).thenReturn(3L); when(questionService.questionById(Mockito.any())).thenReturn(question); when(gameRepository.findById(Mockito.any())).thenReturn(Optional.ofNullable(testGame)); when(scoreService.findById(Mockito.any())).thenReturn(score); assertThrows(PreconditionFailedException.class, () -> gameService.makeGuess(answer)); } @Test void makeGuessCloudsFailure() { //empty question list given will throw error List<Long> questionsList = new ArrayList<Long>(); testGame.setQuestions(questionsList); answer.setQuestionId(1L); testGame.setRound(1); testGame.setGameMode(new Clouds()); answer.setQuestionId(question.getQuestionId()); when(questionService.count()).thenReturn(3L); when(questionService.questionById(Mockito.any())).thenReturn(question); when(gameRepository.findById(Mockito.any())).thenReturn(Optional.ofNullable(testGame)); when(scoreService.findById(Mockito.any())).thenReturn(score); assertThrows(PreconditionFailedException.class, () -> gameService.makeGuess(answer)); } @Test void makeGuessPixelationFailure() { //Wrong question id, rest stays the same List<Long> questionsList = new ArrayList<Long>(); questionsList.add(88L); questionsList.add(99L); testGame.setQuestions(questionsList); answer.setQuestionId(1L); testGame.setRound(3); testGame.setGameMode(new Pixelation()); answer.setQuestionId(question.getQuestionId()); when(questionService.count()).thenReturn(3L); when(questionService.questionById(Mockito.any())).thenReturn(question); when(gameRepository.findById(Mockito.any())).thenReturn(Optional.ofNullable(testGame)); when(scoreService.findById(Mockito.any())).thenReturn(score); assertThrows(PreconditionFailedException.class, () -> gameService.makeGuess(answer)); } @Test void makeZeroScoreGuessSuccess() { when(questionService.count()).thenReturn(3L); when(questionService.questionById(Mockito.any())).thenReturn(question); when(gameRepository.findById(Mockito.any())).thenReturn(Optional.ofNullable(testGame)); when(scoreService.findById(Mockito.any())).thenReturn(score); Score returnedScore = gameService.makeZeroScoreGuess(answer); assertTrue(returnedScore instanceof Score); assertEquals(score.getTotalScore(), returnedScore.getTotalScore()); //check if score 0 was given assertEquals(0, returnedScore.getTempScore()); } @Test void checkGuessPreconditionsSucess() { } @Test void checkGuessPreconditionsFailure() { } @Test void apresGuess() { } //-------- // exitGame Functionality @Test void exitGame() { } // exitGame Functionality @Test void exitGameUser() { testGame.setUserMode(new MultiPlayer()); when(questionService.count()).thenReturn(3L); when(questionService.questionById(Mockito.any())).thenReturn(question); when(gameRepository.findById(Mockito.any())).thenReturn(Optional.ofNullable(testGame)); when(scoreService.findById(Mockito.any())).thenReturn(score); gameService.exitGameUser(testGame, user); List<Long> preExit = testGame.getUserIds(); preExit.remove(user.getId()); //check if user was removed from userlist assertEquals(testGame.getUserIds(), preExit); } @Test void closeLooseEnds() { } @Test void update() { //create new game which is the "template" for the one that has to be updated. GameEntity testGame2 = new GameEntity(); testGame2.setCreatorUserId(13L); testGame2.setGameId(testGame.getGameId()); testGame2.setGameMode(new Clouds()); testGame2.setLobbyId(null); testGame2.setBreakDuration(40); testGame2.setUserMode(new SinglePlayer()); testGame2.setRound(0); testGame.setRound(0); when(questionService.count()).thenReturn(3L); when(questionService.questionById(Mockito.any())).thenReturn(question); when(gameRepository.findById(testGame.getGameId())).thenReturn(Optional.ofNullable(testGame)); when(gameRepository.findById(testGame2.getGameId())).thenReturn(Optional.ofNullable(testGame2)); when(scoreService.findById(Mockito.any())).thenReturn(score); when(lobbyService.getLobbyById(Mockito.any())).thenReturn(lobby); GameEntity gameReturned = gameService.update(testGame2, false); //check if gameRepo was called en game was updated in the database. Mockito.verify(gameRepository, Mockito.times(1)).saveAndFlush(Mockito.any()); //check if GameMode was updated to Clouds assertEquals(gameReturned.getGameMode().getName(),"Clouds"); //check if lobby was set to private assertEquals(lobby.getPublicStatus(),false); } @Test void update_fail() { //create new game which is the "template" for the one that has to be updated. GameEntity testGame2 = new GameEntity(); testGame2.setCreatorUserId(13L); testGame2.setGameId(testGame.getGameId()); testGame2.setGameMode(new Clouds()); testGame2.setLobbyId(null); testGame2.setBreakDuration(40); testGame2.setUserMode(new SinglePlayer()); //Game has already started testGame.setRound(1); testGame2.setRound(1); when(questionService.count()).thenReturn(3L); when(questionService.questionById(Mockito.any())).thenReturn(question); when(gameRepository.findById(testGame.getGameId())).thenReturn(Optional.ofNullable(testGame)); when(gameRepository.findById(testGame2.getGameId())).thenReturn(Optional.ofNullable(testGame2)); when(scoreService.findById(Mockito.any())).thenReturn(score); when(lobbyService.getLobbyById(Mockito.any())).thenReturn(lobby); //check if error is thrown, when i try to update an already started game assertThrows(PreconditionFailedException.class, () -> gameService.update(testGame2, false)); } @Test void handleGame() { } @Test void handleScores() { } @Test void removeRequestFromGameMap() { // wrapper around util.Map method, no need for tests } @Test void addRequestToQueueGameMap() { // wrapper around util.Map method, no need for tests } @Test void removeRequestFromAllScoreMap() { // wrapper around util.Map method, no need for tests } @Test void addRequestAllScoreMap() { // wrapper around util.Map method, no need for tests } @Test void getQuestionsOfGame() { // wrapper around getter, no need for tests } @Test void gameByCreatorUserIdOptional() { // wrapper around getter, no need for tests } @Test void getAllGames() { // wrapper around getter, no need for tests } }
922e52a9c3027902c9dac56a8d7ce1fb79d0b1f7
2,010
java
Java
camel-core/src/test/java/org/apache/camel/management/ManagedShutdownStrategyTest.java
dhirajsb/camel
fe8ebaa932ef34f76bb3b26a3e570664e26e724f
[ "Apache-2.0" ]
null
null
null
camel-core/src/test/java/org/apache/camel/management/ManagedShutdownStrategyTest.java
dhirajsb/camel
fe8ebaa932ef34f76bb3b26a3e570664e26e724f
[ "Apache-2.0" ]
null
null
null
camel-core/src/test/java/org/apache/camel/management/ManagedShutdownStrategyTest.java
dhirajsb/camel
fe8ebaa932ef34f76bb3b26a3e570664e26e724f
[ "Apache-2.0" ]
null
null
null
36.545455
123
0.711443
994,708
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.management; import java.util.Locale; import java.util.concurrent.TimeUnit; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.camel.builder.RouteBuilder; /** * @version */ public class ManagedShutdownStrategyTest extends ManagementTestSupport { public void testManagedShutdownStrategy() throws Exception { // set timeout to 300 context.getShutdownStrategy().setTimeout(300); MBeanServer mbeanServer = getMBeanServer(); ObjectName on = ObjectName.getInstance("org.apache.camel:context=localhost/camel-1,type=context,name=\"camel-1\""); Long timeout = (Long) mbeanServer.getAttribute(on, "Timeout"); assertEquals(300, timeout.longValue()); TimeUnit unit = (TimeUnit) mbeanServer.getAttribute(on, "TimeUnit"); assertEquals("seconds", unit.toString().toLowerCase(Locale.ENGLISH)); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:foo").to("mock:foo"); } }; } }
922e535ff2df9b8a4a94de5179319ff0fadf77ac
7,214
java
Java
src/main/java/com/github/lukasgail/simplegates/GlowingSelection.java
LukasGail/SimpleGates
d561ccd995075cc6733013c32fe9e47324e8ecbb
[ "MIT" ]
null
null
null
src/main/java/com/github/lukasgail/simplegates/GlowingSelection.java
LukasGail/SimpleGates
d561ccd995075cc6733013c32fe9e47324e8ecbb
[ "MIT" ]
null
null
null
src/main/java/com/github/lukasgail/simplegates/GlowingSelection.java
LukasGail/SimpleGates
d561ccd995075cc6733013c32fe9e47324e8ecbb
[ "MIT" ]
null
null
null
37.968421
148
0.565844
994,709
package com.github.lukasgail.simplegates; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Particle; import org.bukkit.block.Block; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.FallingBlock; import org.bukkit.entity.Player; import org.bukkit.entity.Shulker; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitRunnable; import java.util.List; import static com.github.lukasgail.simplegates.SimpleGates.select; public class GlowingSelection { private Plugin pluginSimpleGate; private final static String META_STRING = ChatColor.GOLD + "" + ChatColor.BOLD + "Gate selector stick"; private final String pluginPrefix = ChatColor.GREEN + "[SimpleGate]"; private Player player; private String playerName; private Location selectedLocation1; private Location selectedLocation2; private List<Block> blocks; private FallingBlock[] fallingBlocks; private Shulker[] shulkers; public GlowingSelection(Player player, Plugin plugin) { this.pluginSimpleGate = plugin; this.player = player; this.playerName = player.getDisplayName(); } public void glowEffect() { if (selectedLocation1 != null && selectedLocation2 != null) { blocks = select(player.getWorld(), selectedLocation1, selectedLocation2); if (blocks.size() > 201){ removeSelectionEffect(); return; } removeSelectionEffect(); fallingBlocks = new FallingBlock[blocks.size()]; shulkers = new Shulker[blocks.size()]; for (int i = 0; i < fallingBlocks.length; i++) { Location loc = blocks.get(i).getLocation().add(0.5, 0, 0.5); this.fallingBlocks[i] = blocks.get(i).getWorld().spawnFallingBlock(loc, Material.SHULKER_BOX, (byte) 0); this.fallingBlocks[i].addScoreboardTag("selection"); this.fallingBlocks[i].setGravity(false); this.fallingBlocks[i].setInvulnerable(true); this.fallingBlocks[i].setDropItem(false); this.fallingBlocks[i].setFallDistance(0); this.fallingBlocks[i].setGlowing(true); this.fallingBlocks[i].setTicksLived(1); FallingBlock fallingBlock = this.fallingBlocks[i]; new BukkitRunnable() { public void run() { if (fallingBlock.isDead()) { this.cancel(); } else { player.spawnParticle(Particle.FLAME, fallingBlock.getLocation().add(0, 0.5, 0), 1, 0, 0, 0, 0); player.spawnParticle(Particle.DRAGON_BREATH, fallingBlock.getLocation().add(0.4, 0.1, 0.4), 1, 0, 0, 0, 0); player.spawnParticle(Particle.DRAGON_BREATH, fallingBlock.getLocation().add(0.4, 0.1, -0.4), 1, 0, 0, 0, 0); player.spawnParticle(Particle.DRAGON_BREATH, fallingBlock.getLocation().add(0.4, 0.9, 0.4), 1, 0, 0, 0, 0); player.spawnParticle(Particle.DRAGON_BREATH, fallingBlock.getLocation().add(0.4, 0.9, -0.4), 1, 0, 0, 0, 0); player.spawnParticle(Particle.DRAGON_BREATH, fallingBlock.getLocation().add(-0.4, 0.1, 0.4), 1, 0, 0, 0, 0); player.spawnParticle(Particle.DRAGON_BREATH, fallingBlock.getLocation().add(-0.4, 0.1, -0.4), 1, 0, 0, 0, 0); player.spawnParticle(Particle.DRAGON_BREATH, fallingBlock.getLocation().add(-0.4, 0.9, 0.4), 1, 0, 0, 0, 0); player.spawnParticle(Particle.DRAGON_BREATH, fallingBlock.getLocation().add(-0.4, 0.9, -0.4), 1, 0, 0, 0, 0); } } }.runTaskTimer(pluginSimpleGate, 0, 20L); if (loc.getBlock().getType().isSolid()) { this.shulkers[i] = loc.getWorld().spawn(loc, Shulker.class, shulker -> { shulker.addScoreboardTag("slidingDoor"); shulker.addScoreboardTag("selection"); shulker.setGravity(false); shulker.setSilent(true); shulker.setInvulnerable(true); shulker.setAI(false); shulker.setCanPickupItems(false); shulker.setHealth(30); shulker.setAbsorptionAmount(30); shulker.setCollidable(true); shulker.setGlowing(true); shulker.addPotionEffect((new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 10, false, false, false))); shulker.addPotionEffect((new PotionEffect(PotionEffectType.ABSORPTION, Integer.MAX_VALUE, 10, false, false, false))); shulker.addPotionEffect((new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, Integer.MAX_VALUE, 10, false, false, false))); shulker.addPotionEffect((new PotionEffect(PotionEffectType.REGENERATION, Integer.MAX_VALUE, 10, false, false, false))); new BukkitRunnable() { @Override public void run() { if(shulker.isDead()){ this.cancel(); }else{ shulker.remove(); } } }.runTaskLaterAsynchronously(pluginSimpleGate, 600); }); } } } } public void removeSelectionEffect() { if (fallingBlocks != null) { for (int i = 0; i < fallingBlocks.length; i++) { if (fallingBlocks[i] != null) { fallingBlocks[i].remove(); } if (shulkers[i] != null) { shulkers[i].remove(); } } } } public Player getPlayer() { return player; } public void setPlayer(Player player) { this.player = player; } public String getPlayerName() { return playerName; } public void setPlayerName(String playerName) { this.playerName = playerName; } public List<Block> getBlocks(){ return this.blocks; } public Location getSelectedLocation1() { return selectedLocation1; } public void setSelectedLocation1(Location selectedLocation1) { this.selectedLocation1 = selectedLocation1; glowEffect(); } public Location getSelectedLocation2() { return selectedLocation2; } public void setSelectedLocation2(Location selectedLocation2) { this.selectedLocation2 = selectedLocation2; glowEffect(); } }
922e55c9d8014701f964eed6b911e195c383d795
962
java
Java
uaa/src/main/java/com/chumbok/uaa/domain/repository/TenantRepository.java
mmahmoodictbd/production-ready-microservices-starter
a8cf1e71870b673192241d5eef06e7cc58de7c27
[ "MIT" ]
42
2018-07-31T04:14:58.000Z
2022-01-26T13:42:47.000Z
uaa/src/main/java/com/chumbok/uaa/domain/repository/TenantRepository.java
mmahmoodictbd/microservice-hello-world
a8cf1e71870b673192241d5eef06e7cc58de7c27
[ "MIT" ]
32
2019-04-28T00:58:54.000Z
2019-11-03T12:15:05.000Z
uaa/src/main/java/com/chumbok/uaa/domain/repository/TenantRepository.java
mmahmoodictbd/microservice-hello-world
a8cf1e71870b673192241d5eef06e7cc58de7c27
[ "MIT" ]
20
2018-10-17T15:04:54.000Z
2022-03-20T02:42:16.000Z
30.0625
85
0.767152
994,710
package com.chumbok.uaa.domain.repository; import com.chumbok.uaa.domain.model.Tenant; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; /** * Tenant repository. */ @Repository public interface TenantRepository extends JpaRepository<Tenant, String> { Page<Tenant> findAllByOrgId(String orgId, Pageable pageable); @Query("SELECT t.id FROM Tenant t WHERE t.org.id = ?1") List<String> findTenantIdsByOrgId(String orgId); @Query("SELECT count(t) > 0 FROM Tenant t WHERE t.org.id = ?1 AND t.tenant = ?2") boolean isTenantExist(String orgId, String tenant); boolean existsByOrgOrgAndTenant(String org, String tenant); void deleteAllByOrgId(String orgId); Tenant getByTenant(String tenant); }
922e5695c0770c66beb0096826479ce4ae0e8437
1,696
java
Java
cup/src/main/java/com/lvcoding/security/CommonAccessDeniedHandler.java
wuyanshen/cup
1e1bca84ea7f91d4bcd0c7a80301b0c1cf46ac60
[ "MIT" ]
1
2022-02-14T09:23:53.000Z
2022-02-14T09:23:53.000Z
cup/src/main/java/com/lvcoding/security/CommonAccessDeniedHandler.java
wuyanshen/cup
1e1bca84ea7f91d4bcd0c7a80301b0c1cf46ac60
[ "MIT" ]
null
null
null
cup/src/main/java/com/lvcoding/security/CommonAccessDeniedHandler.java
wuyanshen/cup
1e1bca84ea7f91d4bcd0c7a80301b0c1cf46ac60
[ "MIT" ]
null
null
null
36.869565
164
0.787736
994,711
/* * * Copyright (c) 2021-2015, wuyanshen All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of the lvcoding.com developer nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * Author: wuyanshen * */ package com.lvcoding.security; import com.lvcoding.util.Res; import com.lvcoding.util.ResUtil; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author wuyanshen * @date 2020-03-24 4:59 下午 * @description 当登录后访问的接口没有权限时,自定义返回结果 */ @Component public class CommonAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { ResUtil.jsonResult(response, Res.success(403, "您无权访问该资源,请联系管理员")); } }
922e56997a3dfd129b3cbdf73a9745ee6cc9b945
784
java
Java
src/main/java/com/notfound/crm/common/exception/SystemException.java
Zhuyaning/crm
8bdfc30bd64962a2065b54966241df599cd3acfe
[ "MulanPSL-1.0" ]
1
2021-08-06T07:40:27.000Z
2021-08-06T07:40:27.000Z
src/main/java/com/notfound/crm/common/exception/SystemException.java
Zhuyaning/crm
8bdfc30bd64962a2065b54966241df599cd3acfe
[ "MulanPSL-1.0" ]
null
null
null
src/main/java/com/notfound/crm/common/exception/SystemException.java
Zhuyaning/crm
8bdfc30bd64962a2065b54966241df599cd3acfe
[ "MulanPSL-1.0" ]
null
null
null
16.333333
55
0.584184
994,712
package com.notfound.crm.common.exception; /** * @author Wan_JiaLin * @Create 2021-04-30 11:09 * @Description: 这里是员工类的controller,端口访问 */ /** * 业务异常类 * 当程序出现异常时,抛出异常信息 * 1.数据校验不通过时 * 2.当数据操作出现异常时,抛出异常信息,数据回滚 */ public class SystemException extends RuntimeException { /** * 异常编码 */ private Integer code; /** * 异常信息 */ private String msg; public SystemException(){} public SystemException(Integer code, String msg){ this.code = code; this.msg = msg; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
922e56edf02f515d25525e78138f58f5834de750
1,391
java
Java
src/main/java/com/google/codeu/servlets/PuzzleServlet.java
miaboloix/virtual-escape
41b83c6a0b4274302fa588cd7bb6015c1dde9bf1
[ "Apache-2.0" ]
2
2019-06-23T20:46:06.000Z
2019-07-25T05:26:07.000Z
src/main/java/com/google/codeu/servlets/PuzzleServlet.java
miaboloix/virtual-escape
41b83c6a0b4274302fa588cd7bb6015c1dde9bf1
[ "Apache-2.0" ]
7
2019-06-06T20:33:55.000Z
2019-07-13T23:48:37.000Z
src/main/java/com/google/codeu/servlets/PuzzleServlet.java
miaboloix/virtual-escape
41b83c6a0b4274302fa588cd7bb6015c1dde9bf1
[ "Apache-2.0" ]
3
2019-07-27T17:19:11.000Z
2019-09-16T19:45:35.000Z
30.911111
79
0.712437
994,713
package com.google.codeu.servlets; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import com.google.codeu.data.Datastore; import com.google.codeu.data.Puzzle; import com.google.codeu.data.User; import com.google.gson.Gson; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/puzzle") public class PuzzleServlet extends HttpServlet { private Datastore datastore; public void init() { datastore = new Datastore(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("application/json"); datastore.savePuzzles(); UserService userService = UserServiceFactory.getUserService(); String user_email = userService.getCurrentUser().getEmail(); if (userService.getCurrentUser() == null) { response.sendRedirect("/"); } User user = datastore.getUser(user_email); int level = user.getLevel(); String puzzle = datastore.getPuzzle(level).getAnswer(); Gson gson = new Gson(); String json = gson.toJson(puzzle); response.getWriter().println(json); } }
922e5732b3628f342c7c3fac61a53a5b588aaa35
80
java
Java
FHIR-IntelligentDataRouter/fhir-panache-persist-mongo/src/main/java/com/ibm/domain/Encounter.java
Project-Herophilus/iDaaS-Route
bc6d6f724251304850b3d6cf1b60a7bf77a7ed05
[ "Apache-2.0" ]
null
null
null
FHIR-IntelligentDataRouter/fhir-panache-persist-mongo/src/main/java/com/ibm/domain/Encounter.java
Project-Herophilus/iDaaS-Route
bc6d6f724251304850b3d6cf1b60a7bf77a7ed05
[ "Apache-2.0" ]
null
null
null
FHIR-IntelligentDataRouter/fhir-panache-persist-mongo/src/main/java/com/ibm/domain/Encounter.java
Project-Herophilus/iDaaS-Route
bc6d6f724251304850b3d6cf1b60a7bf77a7ed05
[ "Apache-2.0" ]
1
2021-10-05T07:29:49.000Z
2021-10-05T07:29:49.000Z
16
28
0.75
994,714
package com.ibm.domain; public class Encounter{ public String reference; }
922e5756de100ac821049a7ef5c37091b29162e0
1,207
java
Java
src/main/java/com/opencore/ExactMessageHandler.java
moremagic/mirrormaker_topic_rename
eec23b611cb1645df07b8958a167c8cb6f4edecd
[ "Apache-2.0" ]
33
2017-08-30T09:47:30.000Z
2022-03-23T06:33:20.000Z
src/main/java/com/opencore/ExactMessageHandler.java
moremagic/mirrormaker_topic_rename
eec23b611cb1645df07b8958a167c8cb6f4edecd
[ "Apache-2.0" ]
9
2017-03-08T18:30:16.000Z
2020-02-11T08:59:41.000Z
src/main/java/com/opencore/ExactMessageHandler.java
moremagic/mirrormaker_topic_rename
eec23b611cb1645df07b8958a167c8cb6f4edecd
[ "Apache-2.0" ]
29
2017-03-08T18:16:57.000Z
2022-03-31T00:58:51.000Z
48.28
168
0.781276
994,715
package com.opencore; import java.util.Collections; import java.util.List; import kafka.consumer.BaseConsumerRecord; import kafka.tools.MirrorMaker; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.record.RecordBatch; /** * An implementation of MirrorMakerMessageHandler that can be used when a topic should be recreated as close * to identical as possible. * This will preserve topic, partition, timestamp, headers, key and value. * * Note: by preserving the exact partition this handler bypasses the partitioning algorithm, which means that the * target topic has to be set up with at least as many partitions as the source topic, as otherwise messages will * be written to non-existent partitions which will fail. */ public class ExactMessageHandler implements MirrorMaker.MirrorMakerMessageHandler { public List<ProducerRecord<byte[], byte[]>> handle(BaseConsumerRecord record) { Long timestamp = record.timestamp() == RecordBatch.NO_TIMESTAMP ? null : record.timestamp(); return Collections.singletonList(new ProducerRecord<byte[], byte[]>(record.topic(), record.partition(), timestamp, record.key(), record.value(), record.headers())); } }
922e582d26f9b8126ec5017b24e6682c08a3ad34
7,471
java
Java
dao-gen-core/src/main/java/com/ctrip/platform/dal/daogen/entity/GenTaskByFreeSql.java
wwjiang007/dal
b1ed4717f571a601ead66847f0027d398c7caa93
[ "Apache-2.0" ]
1,346
2016-08-18T09:31:56.000Z
2022-03-19T14:30:27.000Z
dao-gen-core/src/main/java/com/ctrip/platform/dal/daogen/entity/GenTaskByFreeSql.java
wwjiang007/dal
b1ed4717f571a601ead66847f0027d398c7caa93
[ "Apache-2.0" ]
60
2016-09-20T01:27:33.000Z
2021-06-06T07:05:16.000Z
dao-gen-core/src/main/java/com/ctrip/platform/dal/daogen/entity/GenTaskByFreeSql.java
wwjiang007/dal
b1ed4717f571a601ead66847f0027d398c7caa93
[ "Apache-2.0" ]
527
2016-09-01T09:07:16.000Z
2022-03-25T06:00:47.000Z
22.169139
80
0.63887
994,716
package com.ctrip.platform.dal.daogen.entity; import com.ctrip.platform.dal.dao.DalPojo; import com.ctrip.platform.dal.dao.annotation.Database; import com.ctrip.platform.dal.dao.annotation.Type; import javax.persistence.*; import java.sql.Timestamp; import java.sql.Types; @Entity @Database(name = "dao") @Table(name = "task_sql") public class GenTaskByFreeSql implements Comparable<GenTaskByFreeSql>, DalPojo { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.AUTO) @Type(value = Types.INTEGER) private Integer id; @Column(name = "db_name") @Type(value = Types.VARCHAR) private String databaseSetName; @Column(name = "class_name") @Type(value = Types.VARCHAR) private String class_name; @Column(name = "pojo_name") @Type(value = Types.VARCHAR) private String pojo_name; @Column(name = "method_name") @Type(value = Types.VARCHAR) private String method_name; @Column(name = "crud_type") @Type(value = Types.VARCHAR) private String crud_type; @Column(name = "sql_content") @Type(value = Types.LONGVARCHAR) private String sql_content; @Column(name = "project_id") @Type(value = Types.INTEGER) private Integer project_id; @Column(name = "parameters") @Type(value = Types.LONGVARCHAR) private String parameters; @Column(name = "generated") @Type(value = Types.BIT) private Boolean generated; @Column(name = "version") @Type(value = Types.INTEGER) private Integer version; @Column(name = "update_user_no") @Type(value = Types.VARCHAR) private String update_user_no; @Column(name = "update_time") @Type(value = Types.TIMESTAMP) private Timestamp update_time; @Column(name = "comment") @Type(value = Types.LONGVARCHAR) private String comment; @Column(name = "scalarType") @Type(value = Types.VARCHAR) private String scalarType; @Column(name = "pojoType") @Type(value = Types.VARCHAR) private String pojoType; @Column(name = "pagination") @Type(value = Types.BIT) private Boolean pagination; // @Column(name = "length") // @Type(value = Types.TINYINT) // private Boolean length; @Column(name = "sql_style") @Type(value = Types.VARCHAR) private String sql_style; @Column(name = "approved") @Type(value = Types.INTEGER) private Integer approved; @Column(name = "approveMsg") @Type(value = Types.LONGVARCHAR) private String approveMsg; @Column(name = "hints") @Type(value = Types.VARCHAR) private String hints; @Column(name = "mode_type") @Type(value = Types.VARCHAR) private String mode_type; private String allInOneName; private String str_approved; private String str_update_time; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDatabaseSetName() { return databaseSetName; } public void setDatabaseSetName(String databaseSetName) { this.databaseSetName = databaseSetName; } public String getClass_name() { return class_name; } public void setClass_name(String class_name) { this.class_name = class_name; } public String getPojo_name() { return pojo_name; } public void setPojo_name(String pojo_name) { this.pojo_name = pojo_name; } public String getMethod_name() { return method_name; } public void setMethod_name(String method_name) { this.method_name = method_name; } public String getCrud_type() { return crud_type; } public void setCrud_type(String crud_type) { this.crud_type = crud_type; } public String getSql_content() { return sql_content; } public void setSql_content(String sql_content) { this.sql_content = sql_content; } public Integer getProject_id() { return project_id; } public void setProject_id(Integer project_id) { this.project_id = project_id; } public String getParameters() { return parameters; } public void setParameters(String parameters) { this.parameters = parameters; } public Boolean getGenerated() { return generated; } public void setGenerated(Boolean generated) { this.generated = generated; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getUpdate_user_no() { return update_user_no; } public void setUpdate_user_no(String update_user_no) { this.update_user_no = update_user_no; } public Timestamp getUpdate_time() { return update_time; } public void setUpdate_time(Timestamp update_time) { this.update_time = update_time; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getScalarType() { return scalarType; } public void setScalarType(String scalarType) { this.scalarType = scalarType; } public String getPojoType() { return pojoType; } public void setPojoType(String pojoType) { this.pojoType = pojoType; } public Boolean getPagination() { return pagination; } public void setPagination(Boolean pagination) { this.pagination = pagination; } // public Boolean getLength() { // return length; // } // // public void setLength(Boolean length) { // this.length = length; // } public String getSql_style() { return sql_style; } public void setSql_style(String sql_style) { this.sql_style = sql_style; } public Integer getApproved() { return approved; } public void setApproved(Integer approved) { this.approved = approved; } public String getApproveMsg() { return approveMsg; } public void setApproveMsg(String approveMsg) { this.approveMsg = approveMsg; } public String getHints() { return hints; } public void setHints(String hints) { this.hints = hints; } public String getAllInOneName() { return allInOneName; } public void setAllInOneName(String allInOneName) { this.allInOneName = allInOneName; } public void setStr_update_time(String str_update_time) { this.str_update_time = str_update_time; } public String getStr_update_time() { return str_update_time; } public void setStr_approved(String str_approved) { this.str_approved = str_approved; } public String getStr_approved() { return str_approved; } public String getMode_type() { return mode_type; } public void setMode_type(String mode_type) { this.mode_type = mode_type; } @Override public int compareTo(GenTaskByFreeSql o) { int result = getAllInOneName().compareTo(o.getAllInOneName()); if (result != 0) return result; result = getClass_name().compareTo(o.getClass_name()); if (result != 0) return result; return getMethod_name().compareTo(o.getMethod_name()); } }
922e58b7a5d3a5e07277f5248b615adc5278d8f8
2,979
java
Java
chapter_001/src/main/java/ru/job4j/tree/binarytree/BinaryTree.java
vguryanov/job4j
1aedca2f1fc1817e1b69e65cf4b69fb12cc245c0
[ "Apache-2.0" ]
2
2018-04-08T17:55:28.000Z
2018-04-08T17:58:16.000Z
chapter_001/src/main/java/ru/job4j/tree/binarytree/BinaryTree.java
vguryanov/job4j
1aedca2f1fc1817e1b69e65cf4b69fb12cc245c0
[ "Apache-2.0" ]
null
null
null
chapter_001/src/main/java/ru/job4j/tree/binarytree/BinaryTree.java
vguryanov/job4j
1aedca2f1fc1817e1b69e65cf4b69fb12cc245c0
[ "Apache-2.0" ]
null
null
null
24.418033
76
0.472642
994,717
package ru.job4j.tree.binarytree; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; /** * Created by User2 on 19.05.2018. */ public class BinaryTree<E extends Comparable<E>> implements Iterable<E> { private Node<E> root; private int size; public boolean add(E e) { if (root == null) { root = new Node<>(e); size++; return true; } return addLeaf(e); } private boolean addLeaf(E e) { boolean result = root.addLeaf(e); if (result) { size++; } return result; } public int getSize() { return size; } @Override public Iterator<E> iterator() { return new Iterator<E>() { private Queue<Node<E>> nodeQueue = new LinkedList<>(); { nodeQueue.offer(BinaryTree.this.root); } @Override public boolean hasNext() { return !nodeQueue.isEmpty(); } @Override public E next() { Node<E> next = nodeQueue.poll(); Node<E> nextLeft = next.getLeft(); Node<E> nextRight = next.getRight(); if (nextLeft != null) { nodeQueue.offer(nextLeft); } if (nextRight != null) { nodeQueue.offer(nextRight); } return next.getValue(); } }; } public static class Node<E extends Comparable<E>> { private final E value; private BranchContainer left = new BranchContainer(); private BranchContainer right = new BranchContainer(); public Node(final E value) { this.value = value; } public E getValue() { return value; } Node<E> getLeft() { return left.getBranch(); } Node<E> getRight() { return right.getBranch(); } private boolean addLeaf(E e) { int comparisonIndex = e.compareTo(value); if (comparisonIndex == 0) { return false; } BranchContainer nextBranch = comparisonIndex < 0 ? left : right; return nextBranch.addLeaf(e); } @Override public String toString() { return value.toString(); } private class BranchContainer { private Node<E> branch; private Node<E> getBranch() { return branch; } private boolean addLeaf(E e) { if (branch == null) { branch = new Node<>(e); return true; } return branch.addLeaf(e); } @Override public String toString() { return branch.toString(); } } } }
922e596bf6380ed369ed272498a0e25a9fb39f29
4,674
java
Java
app/services/TwitterApi.java
whyshu/AkkaImplementation
dc711f56764c4bca96a440065edc0eebdf5e500b
[ "CC0-1.0" ]
1
2018-05-20T03:17:35.000Z
2018-05-20T03:17:35.000Z
app/services/TwitterApi.java
whyshu/AkkaImplementation
dc711f56764c4bca96a440065edc0eebdf5e500b
[ "CC0-1.0" ]
null
null
null
app/services/TwitterApi.java
whyshu/AkkaImplementation
dc711f56764c4bca96a440065edc0eebdf5e500b
[ "CC0-1.0" ]
null
null
null
29.961538
114
0.685708
994,718
package services; import Models.Profile; import Models.Tweet; import twitter4j.*; import twitter4j.conf.ConfigurationBuilder; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * Represents TwitterApi. * @author Prasanth, Vaishnavi, Anil, Simarpreet * * @version 1.0 * @since 1.0 */ public class TwitterApi { private Twitter twitterInstance; /** * Instantiates the twitter4js Configuration builder with the available twitter * account information Creates the twitter instance to issue the Rest API */ public TwitterApi() { ConfBuilder confBuilder = new ConfBuilder(); ConfigurationBuilder cb = confBuilder.getConf(); TwitterFactory tf = new TwitterFactory(cb.build()); twitterInstance = tf.getInstance(); } /** * Sets the initialised instance of the twitter instance * * @param twitter An instance * of the Twitter class */ public void SetTwitterInstance(Twitter twitter) { this.twitterInstance = twitter; } /** * Gets the initialised instance of the twitter instance * * @return An instance of the Twitter class */ public Twitter getTwitterInstance() { return this.twitterInstance; } /** * Gets the list of ten latest tweets queried based on the given search key * * @param searchKey Key based on which tweets should be fetched * * * @return ArrayList<Tweet>, array list containing instances of the Tweet class * @link Tweet * * @throws whenever * the twitter instance is not instantiated with the given Twitter * account information */ public String getTweets(String searchKey) { try { Query query = new Query(searchKey); QueryResult result = getTwitterInstance().search(query); List<Status> tweets = result.getTweets(); tweets = tweets.parallelStream().limit(10).collect(Collectors.toList()); return convertToTweets(tweets); }catch(Exception e) { return ""; } } /** * Converts the list of tweets of Status class type to Tweet class * * @param tweets list containing instances of twitter4j Status class * * @return ArrayList<Tweet>, array list containing instances of Tweet class * @link Tweet * @throws whenever * the twitter instance is not instantiated with the given Twitter * account information */ public String convertToTweets(List<Status> tweets)throws Exception { ArrayList<Tweet> tweetStatus = new ArrayList<>(); for (Status tweet : tweets) { Status status = getTwitterInstance().showStatus(tweet.getId()); int favorites = (status.isRetweet()) ? status.getRetweetedStatus().getFavoriteCount() : status.getFavoriteCount(); String text = (status.isRetweet()) ? status.getRetweetedStatus().getText() : tweet.getText(); Tweet t = new Tweet(tweet.getUser().getName(), tweet.getUser().getScreenName(), text, tweet.getRetweetCount(), favorites, tweet.getCreatedAt().toString(), tweet.getUser().getBiggerProfileImageURL()); tweetStatus.add(t); } String output = " "; for(Tweet tweet : tweetStatus){ output = output + "|||||||||||||" + tweet.toString(); } return output; } /** * Gets the instance of profile based on the provided username * * @param userName name of the user * * @return Profile an instance of the Profile class * @link Profile * @throws whenever * the twitter instance is not instantiated with the given Twitter * account information */ public Profile getProfile(String userName){ try { User userDetail = null; userDetail = getTwitterInstance().showUser(userName); Profile profile = new Profile(userDetail.getName(), userDetail.getScreenName(), userDetail.getFollowersCount(), userDetail.getFriendsCount(), userDetail.getLocation(), userDetail.getStatusesCount(), userDetail.getOriginalProfileImageURL()); return profile; }catch(Exception e) { return new Profile(); } } /** * Gets the latest ten tweets of a twitter user with the provided username * * @param userName name of the user * * @return ArrayList<Tweet>, list containing instances of the Tweet class * @link Tweet * @throws whenever * the twitter instance is not instantiated with the given Twitter * account information */ public String getUserTweets(String userName) { try { List<Status> tweets = getTwitterInstance().getUserTimeline(userName); tweets = tweets.stream().limit(10).collect(Collectors.toList()); return convertToTweets(tweets); }catch(Exception e) { return ""; } } }
922e5aa4f14781ae264264f1e38e71e2cc7699aa
933
java
Java
name.martingeisse.common/src/main/java/name/martingeisse/common/util/SemaphoreWithPublicReducePermits.java
MartinGeisse/public
57b905485322222447187ae78a5a56bf3ce67900
[ "MIT" ]
1
2015-06-16T13:18:45.000Z
2015-06-16T13:18:45.000Z
name.martingeisse.common/src/main/java/name/martingeisse/common/util/SemaphoreWithPublicReducePermits.java
MartinGeisse/public
57b905485322222447187ae78a5a56bf3ce67900
[ "MIT" ]
3
2022-03-08T21:11:04.000Z
2022-03-08T21:11:15.000Z
name.martingeisse.common/src/main/java/name/martingeisse/common/util/SemaphoreWithPublicReducePermits.java
MartinGeisse/public
57b905485322222447187ae78a5a56bf3ce67900
[ "MIT" ]
null
null
null
20.733333
81
0.721329
994,719
/** * Copyright (c) 2010 Martin Geisse * * This file is distributed under the terms of the MIT license. */ package name.martingeisse.common.util; import java.util.concurrent.Semaphore; /** * A {@link Semaphore} subclass whose {@link #reducePermits(int)} method * is public. */ public class SemaphoreWithPublicReducePermits extends Semaphore { /** * Constructor. * @param permits the initial number of permits * @param fair whether this semaphore is fair */ public SemaphoreWithPublicReducePermits(final int permits, final boolean fair) { super(permits, fair); } /** * Constructor. * @param permits the initial number of permits */ public SemaphoreWithPublicReducePermits(final int permits) { super(permits); } /* (non-Javadoc) * @see java.util.concurrent.Semaphore#reducePermits(int) */ @Override public void reducePermits(final int reduction) { super.reducePermits(reduction); }; }
922e5bae81e45cdfc859f4ee2f32ae95d602ab00
1,016
java
Java
odcleanstore/webfrontend/src/main/java/cz/cuni/mff/odcleanstore/webfrontend/core/components/DeleteConfirmationMessage.java
ODCleanStore/ODCleanStore
3a68c345c5b67349447add8d61d97ae59edd8d7d
[ "Apache-2.0" ]
4
2015-11-16T10:30:21.000Z
2021-04-16T16:16:36.000Z
odcleanstore/webfrontend/src/main/java/cz/cuni/mff/odcleanstore/webfrontend/core/components/DeleteConfirmationMessage.java
ODCleanStore/ODCleanStore
3a68c345c5b67349447add8d61d97ae59edd8d7d
[ "Apache-2.0" ]
null
null
null
odcleanstore/webfrontend/src/main/java/cz/cuni/mff/odcleanstore/webfrontend/core/components/DeleteConfirmationMessage.java
ODCleanStore/ODCleanStore
3a68c345c5b67349447add8d61d97ae59edd8d7d
[ "Apache-2.0" ]
null
null
null
23.295455
81
0.705366
994,720
package cz.cuni.mff.odcleanstore.webfrontend.core.components; /** * Represents the message to be displayed inside a confirmation * box applied to a delete button. * * @author Dušan Rychnovský (dycjh@example.com) * */ public class DeleteConfirmationMessage { /** the message to be displayed */ String message; /** * * @param primaryObjName the name of the entity to be deleted */ public DeleteConfirmationMessage(String primaryObjName) { this.message = "Are you sure you want to delete the " + primaryObjName + "?"; } /** * * @param primaryObjName the name of the primary entity to be deleted * @param secondaryObjName the name of the secondary (dependent) entities * to be deleted */ public DeleteConfirmationMessage(String primaryObjName, String secondaryObjName) { this.message = "Are you sure you want to delete the " + primaryObjName + " and all associated " + secondaryObjName + "s?"; } @Override public String toString() { return message; } }
922e5cade342476cb5fffe9dc3534f1ed7663b11
2,919
java
Java
commons/bundle/src/main/java/com/composum/pages/commons/util/AttributeSet.java
ist-rw/composum-pages
886774490674470bc24b0c8050f3e1055eaa1d07
[ "MIT" ]
7
2017-09-27T07:49:29.000Z
2022-02-09T05:03:57.000Z
commons/bundle/src/main/java/com/composum/pages/commons/util/AttributeSet.java
ist-rw/composum-pages
886774490674470bc24b0c8050f3e1055eaa1d07
[ "MIT" ]
5
2017-10-17T08:50:31.000Z
2020-12-23T09:49:59.000Z
commons/bundle/src/main/java/com/composum/pages/commons/util/AttributeSet.java
ist-rw/composum-pages
886774490674470bc24b0c8050f3e1055eaa1d07
[ "MIT" ]
2
2017-10-06T18:23:49.000Z
2018-09-01T19:50:12.000Z
31.053191
74
0.582391
994,721
package com.composum.pages.commons.util; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; @SuppressWarnings("unchecked") public class AttributeSet implements Iterable<Map.Entry<String, Object>> { protected Map<String, Object> attributes = new HashMap<>(); public String toString() { StringBuilder builder = new StringBuilder(); for (Map.Entry<String, Object> entry : attributes.entrySet()) { Object value = entry.getValue(); if (value != null) { if (builder.length() > 0) { builder.append(" "); } builder.append(entry.getKey()).append("=\""); builder.append(value instanceof Collection ? StringUtils.join((Collection) value, ",") : value.toString()).append("\""); } } return builder.toString(); } public <T> T consumeAttribute(String key, Class<T> type) { T value = getAttribute(key, type); attributes.remove(key); return value; } public <T> T consumeAttribute(String key, T defaultValue) { T value = getAttribute(key, defaultValue); attributes.remove(key); return value; } public <T> T getAttribute(String key, Class<T> type) { return (T) attributes.get(key); } public <T> T getAttribute(String key, T defaultValue) { T value = (T) getAttribute(key, defaultValue.getClass()); return value != null ? value : defaultValue; } public void setAttribute(String key, Object value) { if (value != null) { attributes.put(key, value); } else { attributes.remove(key); } } public boolean isOption(String optionsKey, String key) { List<String> options = getAttribute(optionsKey, List.class); return options != null && options.contains(key); } public void setOption(String optionsKey, String key, Object value) { List<String> options = getAttribute(optionsKey, List.class); if (options == null) { options = new ArrayList<>(); } boolean ruleValue = value == null ? Boolean.TRUE : (value instanceof Boolean ? (Boolean) value : Boolean.valueOf(value.toString())); if (ruleValue) { if (!options.contains(key)) { options.add(key); } } else { options.remove(key); } setAttribute(optionsKey, options.size() > 0 ? options : null); } @Nonnull @Override public Iterator<Map.Entry<String, Object>> iterator() { return attributes.entrySet().iterator(); } }
922e5d7c5e3351f8a4700023ab03719c3182035f
1,762
java
Java
imagepicker/src/main/java/com/zhangteng/imagepicker/cameralibrary/state/BorrowVideoState.java
duoluo9/ImagePicker
f23c6b05e8d8821a38ecfae76a57c6e7facb9506
[ "Unlicense" ]
6
2020-08-19T09:32:53.000Z
2021-04-17T01:44:06.000Z
imagepicker/src/main/java/com/zhangteng/imagepicker/cameralibrary/state/BorrowVideoState.java
duoluo9/ImagePicker
f23c6b05e8d8821a38ecfae76a57c6e7facb9506
[ "Unlicense" ]
1
2021-05-07T03:25:17.000Z
2021-05-07T03:25:17.000Z
imagepicker/src/main/java/com/zhangteng/imagepicker/cameralibrary/state/BorrowVideoState.java
duoluo9/ImagePicker
f23c6b05e8d8821a38ecfae76a57c6e7facb9506
[ "Unlicense" ]
null
null
null
21.487805
81
0.68672
994,722
package com.zhangteng.imagepicker.cameralibrary.state; import android.view.Surface; import android.view.SurfaceHolder; import com.zhangteng.imagepicker.widget.CameraInterface; import com.zhangteng.imagepicker.widget.JCameraView; import com.zhangteng.imagepicker.utils.LogUtil; public class BorrowVideoState implements State { private final String TAG = "BorrowVideoState"; private CameraMachine machine; public BorrowVideoState(CameraMachine machine) { this.machine = machine; } @Override public void start(SurfaceHolder holder, float screenProp) { CameraInterface.getInstance().doStartPreview(holder, screenProp); machine.setState(machine.getPreviewState()); } @Override public void stop() { } @Override public void focus(float x, float y, CameraInterface.FocusCallback callback) { } @Override public void switich(SurfaceHolder holder, float screenProp) { } @Override public void restart() { } @Override public void capture(boolean isMirror) { } @Override public void record(Surface surface, float screenProp) { } @Override public void stopRecord(boolean isShort, long time) { } @Override public void cancel(SurfaceHolder holder, float screenProp) { machine.getView().resetState(JCameraView.TYPE_VIDEO); machine.setState(machine.getPreviewState()); } @Override public void confirm() { machine.getView().confirmState(JCameraView.TYPE_VIDEO); machine.setState(machine.getPreviewState()); } @Override public void zoom(float zoom, int type) { LogUtil.i(TAG, "zoom"); } @Override public void flash(String mode) { } }
922e5dafc4e64ca76df8300f02ebeeb9d38c5960
4,052
java
Java
sources/com/google/android/gms/internal/ads/zzbmn.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
1
2019-10-01T11:34:10.000Z
2019-10-01T11:34:10.000Z
sources/com/google/android/gms/internal/ads/zzbmn.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
null
null
null
sources/com/google/android/gms/internal/ads/zzbmn.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
1
2020-05-26T05:10:33.000Z
2020-05-26T05:10:33.000Z
27.564626
95
0.601185
994,723
package com.google.android.gms.internal.ads; import android.content.Context; import com.google.android.gms.ads.internal.overlay.zzo; import com.google.android.gms.common.util.Clock; import java.lang.ref.WeakReference; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; import org.json.JSONObject; public final class zzbmn implements zzo, zzbrw, zzbrx, zzue { /* renamed from: a */ private final zzbmg f25548a; /* renamed from: b */ private final zzbml f25549b; /* renamed from: c */ private final Set<zzbgz> f25550c = new HashSet(); /* renamed from: d */ private final zzamd<JSONObject, JSONObject> f25551d; /* renamed from: e */ private final Executor f25552e; /* renamed from: f */ private final Clock f25553f; /* renamed from: g */ private final AtomicBoolean f25554g = new AtomicBoolean(false); /* renamed from: h */ private final zzbmp f25555h = new zzbmp(); /* renamed from: i */ private boolean f25556i = false; /* renamed from: j */ private WeakReference<Object> f25557j = new WeakReference<>(this); public zzbmn(zzaly zzaly, zzbml zzbml, Executor executor, zzbmg zzbmg, Clock clock) { this.f25548a = zzbmg; zzaln<JSONObject> zzaln = zzalo.f24411b; this.f25551d = zzaly.mo29810a("google.afma.activeView.handleUpdate", zzaln, zzaln); this.f25549b = zzbml; this.f25552e = executor; this.f25553f = clock; } /* renamed from: C */ public final synchronized void mo30740C() { if (!(this.f25557j.get() != null)) { mo30741D(); } else if (!this.f25556i && this.f25554g.get()) { try { this.f25555h.f25561d = this.f25553f.mo27934a(); JSONObject a = this.f25549b.mo28177a(this.f25555h); for (zzbgz rf : this.f25550c) { this.f25552e.execute(new C9101Rf(rf, a)); } zzbao.m26374b(this.f25551d.mo26658a(a), "ActiveViewListener.callActiveViewJs"); } catch (Exception e) { zzawz.m26002e("Failed to call ActiveViewJS", e); } } } /* renamed from: E */ private final void m27256E() { for (zzbgz b : this.f25550c) { this.f25548a.mo30738b(b); } this.f25548a.mo30735a(); } /* renamed from: D */ public final synchronized void mo30741D() { m27256E(); this.f25556i = true; } /* renamed from: a */ public final synchronized void mo30742a(zzbgz zzbgz) { this.f25550c.add(zzbgz); this.f25548a.mo30736a(zzbgz); } /* renamed from: a */ public final void mo30743a(Object obj) { this.f25557j = new WeakReference<>(obj); } /* renamed from: a */ public final synchronized void mo28694a(zzud zzud) { this.f25555h.f25558a = zzud.f29465m; this.f25555h.f25563f = zzud; mo30740C(); } /* renamed from: b */ public final synchronized void mo29183b(Context context) { this.f25555h.f25559b = true; mo30740C(); } /* renamed from: d */ public final synchronized void mo29185d(Context context) { this.f25555h.f25559b = false; mo30740C(); } /* renamed from: c */ public final synchronized void mo29184c(Context context) { this.f25555h.f25562e = "u"; mo30740C(); m27256E(); this.f25556i = true; } public final void zzsz() { } public final synchronized void onPause() { this.f25555h.f25559b = true; mo30740C(); } public final synchronized void onResume() { this.f25555h.f25559b = false; mo30740C(); } public final void zzta() { } public final synchronized void onAdImpression() { if (this.f25554g.compareAndSet(false, true)) { this.f25548a.mo30737a(this); mo30740C(); } } }
922e5df6cb5a9454974286355c9df839bbad0cea
2,893
java
Java
src/main/java/net/zuz/cwm/item/trinkets/items/TntFrog.java
ZuzAser80/CWM
5f88560d6a6a80dd15ba47ac7e026c461507c607
[ "MIT" ]
null
null
null
src/main/java/net/zuz/cwm/item/trinkets/items/TntFrog.java
ZuzAser80/CWM
5f88560d6a6a80dd15ba47ac7e026c461507c607
[ "MIT" ]
2
2022-02-07T19:21:11.000Z
2022-02-15T07:55:09.000Z
src/main/java/net/zuz/cwm/item/trinkets/items/TntFrog.java
ZuzAser80/CWM
5f88560d6a6a80dd15ba47ac7e026c461507c607
[ "MIT" ]
null
null
null
46.66129
325
0.733149
994,724
package net.zuz.cwm.item.trinkets.items; import dev.emi.trinkets.api.SlotReference; import dev.emi.trinkets.api.TrinketItem; import dev.emi.trinkets.api.client.TrinketRenderer; import net.minecraft.client.render.OverlayTexture; import net.minecraft.client.render.VertexConsumer; import net.minecraft.client.render.VertexConsumerProvider; import net.minecraft.client.render.entity.model.BipedEntityModel; import net.minecraft.client.render.entity.model.EntityModel; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.Identifier; import net.minecraft.world.World; import net.minecraft.world.explosion.Explosion; import net.zuz.cwm.entity.trinkets.TntFrogEntity; public class TntFrog extends TrinketItem implements TrinketRenderer { public TntFrog(Settings settings) { super(settings); } private int counter = 0; @Override public void tick(ItemStack stack, SlotReference slot, LivingEntity entity) { World world = entity.world; counter++; if(!(entity.getAttacker() == null) && counter > 100) { counter = 0; world.createExplosion(entity, entity.getAttacker().getX(), entity.getAttacker().getY(), entity.getAttacker().getZ(), 2, Explosion.DestructionType.DESTROY); } if(!(entity.getAttacking() == null) && counter > 100) { counter = 0; world.createExplosion(entity, entity.getAttacking().getX(), entity.getAttacking().getY(), entity.getAttacking().getZ(), 3, Explosion.DestructionType.BREAK); } } private static final Identifier TEXTURE = new Identifier("cwm", "textures/item/trinkets/tnt_frog_model.png"); private BipedEntityModel<LivingEntity> model; @Override public void render(ItemStack stack, SlotReference slotReference, EntityModel<? extends LivingEntity> contextModel, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, LivingEntity entity, float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, float headPitch) { BipedEntityModel<LivingEntity> model = this.getModel(); model.setAngles(entity, limbAngle, limbDistance, animationProgress, animationProgress, headPitch); TrinketRenderer.followBodyRotations(entity, model); VertexConsumer vertexConsumer = vertexConsumers.getBuffer(model.getLayer(TEXTURE)); model.render(matrices, vertexConsumer, light, OverlayTexture.DEFAULT_UV, 1, 1, 1, 1); } private BipedEntityModel<LivingEntity> getModel() { if (this.model == null) { // Vanilla 1.17 uses EntityModels, EntityModelLoader and EntityModelLayers this.model = new TntFrogEntity(TntFrogEntity.getTexturedModelData().createModel()); } return this.model; } }
922e5eb7ea35190026231a8cce4495e496d725ac
1,538
java
Java
sparrow-server-spring-boot-common/src/main/java/com/github/thierrysquirrel/sparrow/server/common/netty/consumer/init/client/core/builder/container/ConsumerThreadPoolExecutorContainer.java
ThierrySquirrel/sparrow-server-spring-boot-starter
524059e2a9326bd1298992bafdd0a36eac950bb0
[ "Apache-2.0" ]
3
2020-06-11T04:58:30.000Z
2020-06-11T05:31:04.000Z
sparrow-server-spring-boot-common/src/main/java/com/github/thierrysquirrel/sparrow/server/common/netty/consumer/init/client/core/builder/container/ConsumerThreadPoolExecutorContainer.java
ThierrySquirrel/sparrow-server-spring-boot-starter
524059e2a9326bd1298992bafdd0a36eac950bb0
[ "Apache-2.0" ]
null
null
null
sparrow-server-spring-boot-common/src/main/java/com/github/thierrysquirrel/sparrow/server/common/netty/consumer/init/client/core/builder/container/ConsumerThreadPoolExecutorContainer.java
ThierrySquirrel/sparrow-server-spring-boot-starter
524059e2a9326bd1298992bafdd0a36eac950bb0
[ "Apache-2.0" ]
1
2020-06-11T05:12:33.000Z
2020-06-11T05:12:33.000Z
36.619048
131
0.789337
994,725
/** * Copyright 2020 the original author or authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.thierrysquirrel.sparrow.server.common.netty.consumer.init.client.core.builder.container; import com.github.thierrysquirrel.sparrow.server.common.netty.consumer.init.client.core.builder.ThreadPoolExecutorBuilder; import com.google.common.collect.Maps; import java.util.Map; import java.util.concurrent.ThreadPoolExecutor; /** * ClassName: ConsumerThreadPoolExecutorContainer * Description: * date: 2020/12/8 4:17 * * @author ThierrySquirrel * @since JDK 1.8 */ public class ConsumerThreadPoolExecutorContainer { private static final Map<String, ThreadPoolExecutor> CONSUMER_THREAD_POOL_EXECUTOR = Maps.newConcurrentMap(); private ConsumerThreadPoolExecutorContainer() { } public static ThreadPoolExecutor getThreadPoolExecutor(String topic) { return CONSUMER_THREAD_POOL_EXECUTOR.computeIfAbsent(topic, ThreadPoolExecutorBuilder::builderSparrowConsumerThreadPoolExecutor); } }
922e5ee8f594f754405bc1abac168ae9c0bd0fcc
966
java
Java
api/src/main/java/com/bjs/bjsapi/database/repository/UserPrivilegeRepository.java
bjs-org/bjs-api
d4bf258506122d0c71100644e1ffe770deff7cbb
[ "Apache-2.0" ]
null
null
null
api/src/main/java/com/bjs/bjsapi/database/repository/UserPrivilegeRepository.java
bjs-org/bjs-api
d4bf258506122d0c71100644e1ffe770deff7cbb
[ "Apache-2.0" ]
25
2019-11-24T15:21:18.000Z
2020-03-22T14:05:14.000Z
api/src/main/java/com/bjs/bjsapi/database/repository/UserPrivilegeRepository.java
bjs-org/bjs-api
d4bf258506122d0c71100644e1ffe770deff7cbb
[ "Apache-2.0" ]
1
2021-11-04T17:42:03.000Z
2021-11-04T17:42:03.000Z
29.272727
92
0.81677
994,726
package com.bjs.bjsapi.database.repository; import java.util.List; import java.util.Optional; import org.springframework.data.repository.CrudRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.security.access.prepost.PreAuthorize; import com.bjs.bjsapi.database.model.Class; import com.bjs.bjsapi.database.model.User; import com.bjs.bjsapi.database.model.UserPrivilege; @PreAuthorize("hasRole('ROLE_ADMIN')") @RepositoryRestResource(path = "user_privileges", collectionResourceRel = "user_privileges") public interface UserPrivilegeRepository extends CrudRepository<UserPrivilege, Long> { @Override List<UserPrivilege> findAll(); Optional<UserPrivilege> findById(Long id); List<UserPrivilege> findByUser(User user); List<UserPrivilege> findByAccessibleClass(Class accessibleClass); @Override <S extends UserPrivilege> S save(S entity); @Override void delete(UserPrivilege entity); }
922e5f0361632116ccfbf0b2bf5911bc0fbd8ae4
4,824
java
Java
oauthsecure-web/src/main/java/za/co/sindi/oauth/web/servlet/context/http/HttpServletResponseContext.java
TheEliteGentleman/oauthsecure
69dfc5a8c440a2ccabdb481264a0be1477325b1a
[ "Apache-2.0" ]
null
null
null
oauthsecure-web/src/main/java/za/co/sindi/oauth/web/servlet/context/http/HttpServletResponseContext.java
TheEliteGentleman/oauthsecure
69dfc5a8c440a2ccabdb481264a0be1477325b1a
[ "Apache-2.0" ]
null
null
null
oauthsecure-web/src/main/java/za/co/sindi/oauth/web/servlet/context/http/HttpServletResponseContext.java
TheEliteGentleman/oauthsecure
69dfc5a8c440a2ccabdb481264a0be1477325b1a
[ "Apache-2.0" ]
null
null
null
28.886228
112
0.744818
994,727
/** * */ package za.co.sindi.oauth.web.servlet.context.http; import java.io.IOException; import java.util.Collection; import javax.servlet.http.HttpServletResponse; import za.co.sindi.oauth.core.http.Cookie; import za.co.sindi.oauth.server.context.http.HttpResponseContext; import za.co.sindi.oauth.web.servlet.context.ServletResponseContext; /** * @author Buhake Sindi * @since 13 April 2012 * */ public class HttpServletResponseContext extends ServletResponseContext implements HttpResponseContext { /** * @param servletResponse */ public HttpServletResponseContext(HttpServletResponse servletResponse) { super(servletResponse); // TODO Auto-generated constructor stub } /* (non-Javadoc) * @see com.neurologic.oauth.core.context.web.servlet.ServletResponseContext#getServletResponse() */ @Override public HttpServletResponse getServletResponse() { // TODO Auto-generated method stub return (HttpServletResponse) super.getServletResponse(); } /* (non-Javadoc) * @see com.neurologic.oauth.core.context.HeaderContext#containsHeader(java.lang.String) */ @Override public boolean containsHeader(String name) { // TODO Auto-generated method stub return getServletResponse().containsHeader(name); } /* (non-Javadoc) * @see com.neurologic.oauth.core.context.HttpResponseContext#encodeRedirectURL(java.lang.String) */ @Override public String encodeRedirectURL(String url) { // TODO Auto-generated method stub return getServletResponse().encodeRedirectURL(url); } /* (non-Javadoc) * @see com.neurologic.oauth.core.context.HttpResponseContext#encodeURL(java.lang.String) */ @Override public String encodeURL(String url) { // TODO Auto-generated method stub return getServletResponse().encodeURL(url); } /* (non-Javadoc) * @see com.neurologic.oauth.core.context.HeaderContext#getHeader(java.lang.String) */ @Override public String getHeader(String name) { // TODO Auto-generated method stub return getServletResponse().getHeader(name); } /* (non-Javadoc) * @see com.neurologic.oauth.core.context.HeaderContext#getHeaderNames() */ @Override public String[] getHeaderNames() { // TODO Auto-generated method stub Collection<String> headers = getServletResponse().getHeaderNames(); if (headers == null) { return null; } return headers.toArray(new String[headers.size()]); } /* (non-Javadoc) * @see com.neurologic.oauth.core.context.HeaderContext#getHeaders(java.lang.String) */ @Override public String[] getHeaders(String name) { // TODO Auto-generated method stub Collection<String> headers = getServletResponse().getHeaders(name); if (headers == null) { return null; } return headers.toArray(new String[headers.size()]); } /* (non-Javadoc) * @see com.neurologic.oauth.core.context.HttpResponseContext#addCookie(net.oauth.transport.http.Cookie) */ @Override public void addCookie(Cookie cookie) { // TODO Auto-generated method stub if (cookie != null) { javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue()); servletCookie.setComment(cookie.getComment()); servletCookie.setDomain(cookie.getDomain()); servletCookie.setMaxAge(cookie.getMaxAge()); servletCookie.setPath(cookie.getPath()); servletCookie.setSecure(cookie.isSecure()); servletCookie.setVersion(cookie.getVersion()); getServletResponse().addCookie(servletCookie); } } /* (non-Javadoc) * @see com.neurologic.oauth.core.context.HttpResponseContext#addHeader(java.lang.String, java.lang.String) */ @Override public void addHeader(String name, String value) { // TODO Auto-generated method stub getServletResponse().addHeader(name, value); } /* (non-Javadoc) * @see za.co.sindi.oauth.server.context.http.HttpResponseContext#sendError(int, java.lang.String) */ @Override public void sendError(int statusCode, String message) throws IOException { // TODO Auto-generated method stub getServletResponse().sendError(statusCode, message); } /* (non-Javadoc) * @see za.co.sindi.oauth.server.context.http.HttpResponseContext#sendError(int) */ @Override public void sendError(int statusCode) throws IOException { // TODO Auto-generated method stub getServletResponse().sendError(statusCode); } /* (non-Javadoc) * @see com.neurologic.oauth.core.context.HttpResponseContext#sendRedirect(java.lang.String) */ @Override public void sendRedirect(String url) throws IOException { // TODO Auto-generated method stub getServletResponse().sendRedirect(url); } /* (non-Javadoc) * @see com.neurologic.oauth.core.context.HttpResponseContext#setStatusCode(int) */ @Override public void setStatusCode(int statusCode) { // TODO Auto-generated method stub getServletResponse().setStatus(statusCode); } }
922e617ba508cb555d4829b140d77664e8575500
4,545
java
Java
src/Map/BalloonItemizedOverlay.java
JH1025/MyStore
4bc9e794eb641cc492cdce764d0e4b347c038c0d
[ "Apache-2.0" ]
null
null
null
src/Map/BalloonItemizedOverlay.java
JH1025/MyStore
4bc9e794eb641cc492cdce764d0e4b347c038c0d
[ "Apache-2.0" ]
null
null
null
src/Map/BalloonItemizedOverlay.java
JH1025/MyStore
4bc9e794eb641cc492cdce764d0e4b347c038c0d
[ "Apache-2.0" ]
null
null
null
25.391061
92
0.678108
994,728
package Map; import java.lang.reflect.Method; import java.util.List; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup.LayoutParams; import com.MyStore.R; import com.google.android.maps.GeoPoint; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; /** * An abstract extension of ItemizedOverlay for displaying an information balloon * upon screen-tap of each marker overlay. * * @author Jeff Gilfelt */ public abstract class BalloonItemizedOverlay<ITEM> extends ItemizedOverlay<MyOverlayItem> { private MapView mapView; private BalloonOverlayView balloonView; private View clickRegion; private int viewOffset; final MapController mc; public BalloonItemizedOverlay(Drawable defaultMarker, MapView mapView) { super(defaultMarker); this.mapView = mapView; viewOffset = 0; mc = mapView.getController(); } public void setBalloonBottomOffset(int pixels) { viewOffset = pixels; } protected boolean onBalloonTap(int index) { return false; } @Override protected final boolean onTap(int index) { boolean isRecycled; final int thisIndex; GeoPoint point; thisIndex = index; point = createItem(index).getPoint(); if (balloonView == null) { balloonView = new BalloonOverlayView(mapView.getContext(), viewOffset); clickRegion = balloonView.findViewById(R.id.balloon_inner_layout); isRecycled = false; } else { isRecycled = true; } balloonView.setVisibility(View.GONE); List<Overlay> mapOverlays = mapView.getOverlays(); if (mapOverlays.size() > 1) { hideOtherBalloons(mapOverlays); } balloonView.setData(createItem(index)); MapView.LayoutParams params = new MapView.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, point, MapView.LayoutParams.BOTTOM_CENTER); params.mode = MapView.LayoutParams.MODE_MAP; setBalloonTouchListener(thisIndex); balloonView.setVisibility(View.VISIBLE); if (isRecycled) { balloonView.setLayoutParams(params); } else { mapView.addView(balloonView, params); } mc.animateTo(point); return true; } /** * Sets the visibility of this overlay's balloon view to GONE. */ private void hideBalloon() { if (balloonView != null) { balloonView.setVisibility(View.GONE); } } /** * Hides the balloon view for any other BalloonItemizedOverlay instances * that might be present on the MapView. * * @param overlays - list of overlays (including this) on the MapView. */ private void hideOtherBalloons(List<Overlay> overlays) { for (Overlay overlay : overlays) { if (overlay instanceof BalloonItemizedOverlay && overlay != this) { ((BalloonItemizedOverlay) overlay).hideBalloon(); } } } /** * Sets the onTouchListener for the balloon being displayed, calling the * overridden onBalloonTap if implemented. * * @param thisIndex - The index of the item whose balloon is tapped. */ private void setBalloonTouchListener(final int thisIndex) { try { @SuppressWarnings("unused") Method m = this.getClass().getDeclaredMethod("onBalloonTap", int.class); clickRegion.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { View l = ((View) v.getParent()).findViewById(R.id.balloon_main_layout); Drawable d = l.getBackground(); if (event.getAction() == MotionEvent.ACTION_DOWN) { int[] states = {android.R.attr.state_pressed}; if (d.setState(states)) { d.invalidateSelf(); } return true; } else if (event.getAction() == MotionEvent.ACTION_UP) { int newStates[] = {}; if (d.setState(newStates)) { d.invalidateSelf(); } // call overridden method onBalloonTap(thisIndex); return true; } else { return false; } } }); } catch (SecurityException e) { Log.e("BalloonItemizedOverlay", "setBalloonTouchListener reflection SecurityException"); return; } catch (NoSuchMethodException e) { // method not overridden - do nothing return; } } }
922e629d1a6bf3dd5adff82794472305520a6be6
6,039
java
Java
tests/robotests/src/com/android/settings/panel/PanelSlicesAdapterTest.java
protodevnan0/android_packages_apps_settings
b2c2db0467becfb578c81c24a84065f1264a7b83
[ "Apache-2.0" ]
null
null
null
tests/robotests/src/com/android/settings/panel/PanelSlicesAdapterTest.java
protodevnan0/android_packages_apps_settings
b2c2db0467becfb578c81c24a84065f1264a7b83
[ "Apache-2.0" ]
null
null
null
tests/robotests/src/com/android/settings/panel/PanelSlicesAdapterTest.java
protodevnan0/android_packages_apps_settings
b2c2db0467becfb578c81c24a84065f1264a7b83
[ "Apache-2.0" ]
null
null
null
37.74375
95
0.714026
994,729
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings.panel; import static com.android.settings.panel.PanelSlicesAdapter.MAX_NUM_OF_SLICES; import static com.android.settings.slices.CustomSliceRegistry.MEDIA_OUTPUT_INDICATOR_SLICE_URI; import static com.google.common.truth.Truth.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import android.content.Context; import android.net.Uri; import android.view.ViewGroup; import android.widget.FrameLayout; import androidx.lifecycle.LiveData; import androidx.slice.Slice; import com.android.settings.R; import com.android.settings.slices.CustomSliceRegistry; import com.android.settings.testutils.FakeFeatureFactory; import org.junit.Before; import org.junit.runner.RunWith; import org.junit.Test; import org.mockito.MockitoAnnotations; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.android.controller.ActivityController; import java.util.ArrayList; import java.util.List; @RunWith(RobolectricTestRunner.class) public class PanelSlicesAdapterTest { private static final Uri DATA_URI = CustomSliceRegistry.DATA_USAGE_SLICE_URI; private Context mContext; private PanelFragment mPanelFragment; private PanelFeatureProvider mPanelFeatureProvider; private FakeFeatureFactory mFakeFeatureFactory; private FakePanelContent mFakePanelContent; private List<LiveData<Slice>> mData = new ArrayList<>(); @Before public void setUp() { MockitoAnnotations.initMocks(this); mContext = RuntimeEnvironment.application; mPanelFeatureProvider = spy(new PanelFeatureProviderImpl()); mFakeFeatureFactory = FakeFeatureFactory.setupForTest(); mFakeFeatureFactory.panelFeatureProvider = mPanelFeatureProvider; mFakePanelContent = new FakePanelContent(); doReturn(mFakePanelContent).when(mPanelFeatureProvider).getPanel(any(), any(), any()); ActivityController<FakeSettingsPanelActivity> activityController = Robolectric.buildActivity(FakeSettingsPanelActivity.class); activityController.setup(); mPanelFragment = spy((PanelFragment) activityController .get() .getSupportFragmentManager() .findFragmentById(R.id.main_content)); } private void addTestLiveData(Uri uri) { // Create a slice to return for the LiveData final Slice slice = spy(new Slice()); doReturn(uri).when(slice).getUri(); final LiveData<Slice> liveData = mock(LiveData.class); when(liveData.getValue()).thenReturn(slice); mData.add(liveData); } @Test public void onCreateViewHolder_returnsSliceRowViewHolder() { addTestLiveData(DATA_URI); final PanelSlicesAdapter adapter = new PanelSlicesAdapter(mPanelFragment, mData, 0 /* metrics category */); final ViewGroup view = new FrameLayout(mContext); final PanelSlicesAdapter.SliceRowViewHolder viewHolder = adapter.onCreateViewHolder(view, 0); assertThat(viewHolder.sliceView).isNotNull(); } @Test public void sizeOfAdapter_shouldNotExceedMaxNum() { for (int i = 0; i < MAX_NUM_OF_SLICES + 2; i++) { addTestLiveData(DATA_URI); } assertThat(mData.size()).isEqualTo(MAX_NUM_OF_SLICES + 2); final PanelSlicesAdapter adapter = new PanelSlicesAdapter(mPanelFragment, mData, 0 /* metrics category */); final ViewGroup view = new FrameLayout(mContext); final PanelSlicesAdapter.SliceRowViewHolder viewHolder = adapter.onCreateViewHolder(view, 0); assertThat(adapter.getItemCount()).isEqualTo(MAX_NUM_OF_SLICES); assertThat(adapter.getData().size()).isEqualTo(MAX_NUM_OF_SLICES); } @Test public void nonMediaOutputIndicatorSlice_shouldAllowDividerAboveAndBelow() { addTestLiveData(DATA_URI); final PanelSlicesAdapter adapter = new PanelSlicesAdapter(mPanelFragment, mData, 0 /* metrics category */); final int position = 0; final ViewGroup view = new FrameLayout(mContext); final PanelSlicesAdapter.SliceRowViewHolder viewHolder = adapter.onCreateViewHolder(view, 0 /* view type*/); adapter.onBindViewHolder(viewHolder, position); assertThat(viewHolder.isDividerAllowedAbove()).isTrue(); assertThat(viewHolder.isDividerAllowedBelow()).isTrue(); } @Test public void mediaOutputIndicatorSlice_shouldNotAllowDividerAbove() { addTestLiveData(MEDIA_OUTPUT_INDICATOR_SLICE_URI); final PanelSlicesAdapter adapter = new PanelSlicesAdapter(mPanelFragment, mData, 0 /* metrics category */); final int position = 0; final ViewGroup view = new FrameLayout(mContext); final PanelSlicesAdapter.SliceRowViewHolder viewHolder = adapter.onCreateViewHolder(view, 0 /* view type*/); adapter.onBindViewHolder(viewHolder, position); assertThat(viewHolder.isDividerAllowedAbove()).isFalse(); } }
922e62c2ef63110120cdedbefa1cdc603c4a4254
700
java
Java
src/infsci2560/week8/Employee.java
drk-web-dev/infsci2560_java
2fd75e680f1a565cfc579015ef18370557c43096
[ "MIT" ]
null
null
null
src/infsci2560/week8/Employee.java
drk-web-dev/infsci2560_java
2fd75e680f1a565cfc579015ef18370557c43096
[ "MIT" ]
null
null
null
src/infsci2560/week8/Employee.java
drk-web-dev/infsci2560_java
2fd75e680f1a565cfc579015ef18370557c43096
[ "MIT" ]
null
null
null
17.948718
79
0.562857
994,730
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package infsci2560.week8; /** * * @author bk */ public class Employee { String name; int salary; public Employee() { this(null, 0); } public Employee(String n) { name = n; } public Employee(String n, int sal) { name = n; salary = sal; } public void raiseSalary(int amount) { salary = salary + amount; } public static void main(String [] args) { Employee e; e = new Employee(); } }
922e634ad7175dfb5610c4c716ec8560c3d3cc4d
2,228
java
Java
rhinohcf/src/main/java/com/sergivb01/hcf/commands/HCFCommand.java
Waifyui/Rhino-HCF-and-framework
a22e080d0c5704858cd00a5631a0eb2e18d95e72
[ "Apache-2.0" ]
1
2019-08-12T15:26:19.000Z
2019-08-12T15:26:19.000Z
rhinohcf/src/main/java/com/sergivb01/hcf/commands/HCFCommand.java
Waifyui/Rhino-HCF-and-framework
a22e080d0c5704858cd00a5631a0eb2e18d95e72
[ "Apache-2.0" ]
null
null
null
rhinohcf/src/main/java/com/sergivb01/hcf/commands/HCFCommand.java
Waifyui/Rhino-HCF-and-framework
a22e080d0c5704858cd00a5631a0eb2e18d95e72
[ "Apache-2.0" ]
2
2019-05-05T15:08:52.000Z
2020-01-28T04:14:12.000Z
26.52381
146
0.743268
994,731
package com.sergivb01.hcf.commands; import com.sergivb01.base.BaseConstants; import com.sergivb01.util.BukkitUtils; import com.sergivb01.util.command.ArgumentExecutor; import org.apache.commons.lang3.ArrayUtils; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.Arrays; import java.util.regex.Pattern; public class HCFCommand extends ArgumentExecutor{ private static final Pattern USAGE_REPLACER_PATTERN = Pattern.compile("(command)", 16); private final String name; private final String description; private String[] aliases; private String usage; public HCFCommand(String name, String description){ super(name); this.name = name; this.description = description; } public static boolean checkNull(CommandSender sender, String player){ Player target = BukkitUtils.playerWithNameOrUUID(player); if(target == null || !HCFCommand.canSee(sender, target)){ sender.sendMessage(String.format(BaseConstants.PLAYER_WITH_NAME_OR_UUID_NOT_FOUND, player)); return true; } return false; } public static boolean canSee(CommandSender sender, Player target){ return target != null && (!(sender instanceof Player) || ((Player) sender).canSee(target)); } public final String getPermission(){ return "commands." + this.name; } public boolean isPlayerOnlyCommand(){ return false; } public String getName(){ return this.name; } public String getDescription(){ return this.description; } public String getUsage(){ if(this.usage == null){ this.usage = ""; } return ChatColor.RED + "Usage: " + USAGE_REPLACER_PATTERN.matcher(this.usage).replaceAll(this.name) + ChatColor.GRAY + " - " + this.description; } public void setUsage(String usage){ this.usage = usage; } public String getUsage(String label){ return ChatColor.RED + "Usage: " + USAGE_REPLACER_PATTERN.matcher(this.usage).replaceAll(label) + ChatColor.GRAY + " - " + this.description; } public String[] getAliases(){ if(this.aliases == null){ this.aliases = ArrayUtils.EMPTY_STRING_ARRAY; } return Arrays.copyOf(this.aliases, this.aliases.length); } protected void setAliases(String[] aliases){ this.aliases = aliases; } }
922e652f3b15dc459866693b95a5a9934842f862
1,059
java
Java
engine/table/src/main/java/io/deephaven/engine/util/scripts/ClasspathScriptPathLoader.java
mattrunyon/deephaven-core
80e3567e4647ab76a81e483d0a8ab542f9aadace
[ "MIT" ]
55
2021-05-11T16:01:59.000Z
2022-03-30T14:30:33.000Z
engine/table/src/main/java/io/deephaven/engine/util/scripts/ClasspathScriptPathLoader.java
mattrunyon/deephaven-core
80e3567e4647ab76a81e483d0a8ab542f9aadace
[ "MIT" ]
943
2021-05-10T14:00:02.000Z
2022-03-31T21:28:15.000Z
engine/table/src/main/java/io/deephaven/engine/util/scripts/ClasspathScriptPathLoader.java
mattrunyon/deephaven-core
80e3567e4647ab76a81e483d0a8ab542f9aadace
[ "MIT" ]
29
2021-05-10T11:33:16.000Z
2022-03-30T21:01:54.000Z
24.068182
93
0.712937
994,732
/* * Copyright (c) 2016-2021 Deephaven Data Labs and Patent Pending */ package io.deephaven.engine.util.scripts; import io.deephaven.base.FileUtils; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.Set; public class ClasspathScriptPathLoader implements ScriptPathLoader { @Override public void lock() {} @Override public void unlock() {} @Override public Set<String> getAvailableScriptDisplayPaths() { return Collections.emptySet(); } @Override public String getScriptBodyByDisplayPath(final String displayPath) throws IOException { throw new UnsupportedOperationException(); } @Override public String getScriptBodyByRelativePath(final String relativePath) throws IOException { final InputStream stream = getClass().getResourceAsStream('/' + relativePath); return stream == null ? null : FileUtils.readTextFile(stream); } @Override public void refresh() {} @Override public void close() {} }
922e653a930eec1fc6266f7029bf5111cdd19604
1,844
java
Java
redux/src/androidTest/java/io/github/roisagiv/android/redux/todo/TodoReducer.java
roisagiv/Android-Redux
35b254b6cd4a8da3fa3829108a87a58f52b8d0a3
[ "Apache-2.0" ]
null
null
null
redux/src/androidTest/java/io/github/roisagiv/android/redux/todo/TodoReducer.java
roisagiv/Android-Redux
35b254b6cd4a8da3fa3829108a87a58f52b8d0a3
[ "Apache-2.0" ]
null
null
null
redux/src/androidTest/java/io/github/roisagiv/android/redux/todo/TodoReducer.java
roisagiv/Android-Redux
35b254b6cd4a8da3fa3829108a87a58f52b8d0a3
[ "Apache-2.0" ]
null
null
null
25.260274
87
0.637744
994,733
package io.github.roisagiv.android.redux.todo; import io.github.roisagiv.android.redux.Action; import io.github.roisagiv.android.redux.Reducer; import java.util.List; public class TodoReducer implements Reducer<TodoState, TodoAction> { @Override public TodoState handleAction(Action<TodoAction> action, TodoState state) { TodoState newState = new TodoState(); newState.getTodos().addAll(state.getTodos()); Todo todo; switch (action.getType()) { case AddTodo: TodoAction.AddTodoAction addTodoAction = (TodoAction.AddTodoAction) action; int id = maxId(newState.getTodos()); newState.getTodos().add(new Todo(id, addTodoAction.getText(), false)); break; case DeleteTodo: break; case EditTodo: break; case CompletingTodo: TodoAction.CompletingTodoAction completeTodoAction = (TodoAction.CompletingTodoAction) action; todo = findById(completeTodoAction.getId(), newState.getTodos()); todo.setCompleting(true); break; case CompletedTodo: TodoAction.CompletedTodoAction completedTodoAction = (TodoAction.CompletedTodoAction) action; todo = findById(completedTodoAction.getId(), newState.getTodos()); todo.setCompleted(true); break; case CompleteAll: break; case ClearCompleted: break; } return newState; } private int maxId(List<Todo> todos) { int result = 0; if (todos.size() == 0) { return result; } for (Todo todo : todos) { result = Math.max(result, todo.getId()); } return result + 1; } private Todo findById(int id, List<Todo> todos) { for (Todo todo : todos) { if (todo.getId() == id) { return todo; } } // else return null; } }
922e68333bb9b2e9ec4c23c7182c1993d4254126
1,944
java
Java
src/com/interview/algortihmictoolboxpractice/week4/Karatsuba.java
prdp89/interview
04424ec1f13b0d1555382090d35c394b99a3a24b
[ "Apache-2.0" ]
1
2018-03-29T07:45:26.000Z
2018-03-29T07:45:26.000Z
src/com/interview/algortihmictoolboxpractice/week4/Karatsuba.java
prdp89/interview
04424ec1f13b0d1555382090d35c394b99a3a24b
[ "Apache-2.0" ]
null
null
null
src/com/interview/algortihmictoolboxpractice/week4/Karatsuba.java
prdp89/interview
04424ec1f13b0d1555382090d35c394b99a3a24b
[ "Apache-2.0" ]
1
2019-03-26T04:57:19.000Z
2019-03-26T04:57:19.000Z
27
79
0.515432
994,734
package com.interview.algortihmictoolboxpractice.week4; import java.util.Scanner; //Watch this video first : https://www.youtube.com/watch?v=JCbZayFr9RE public class Karatsuba { /** * Function to multiply two numbers **/ public long multiply( long x, long y ) { int size1 = getSize(x); int size2 = getSize(y); /** Maximum of lengths of number **/ int N = Math.max(size1, size2); /** for small values directly multiply **/ if (N < 10) return x * y; /** max length divided, rounded up **/ N = (N / 2) + (N % 2); /** multiplier **/ long m = (long) Math.pow(10, N); /** compute sub expressions **/ long b = x / m; long a = x - (b * m); long d = y / m; long c = y - (d * N); /** compute sub expressions **/ long z0 = multiply(a, c); long z1 = multiply(a + b, c + d); long z2 = multiply(b, d); return z0 + ((z1 - z0 - z2) * m) + (z2 * (long) (Math.pow(10, 2 * N))); } /** * Function to calculate length or number of digits in a number **/ private int getSize( long num ) { int ctr = 0; while (num != 0) { ctr++; num /= 10; } return ctr; } /** * Main function **/ public static void main( String[] args ) { Scanner scan = new Scanner(System.in); System.out.println("Karatsuba Multiplication Algorithm Test\n"); /** Make an object of Karatsuba class **/ Karatsuba kts = new Karatsuba(); /** Accept two integers **/ System.out.println("Enter two integer numbers\n"); long n1 = scan.nextLong(); long n2 = scan.nextLong(); /** Call function multiply of class Karatsuba **/ long product = kts.multiply(n1, n2); System.out.println("\nProduct : " + product); } }
922e68904ea8d6fc5293e9ee4e10a0de0981961a
2,162
java
Java
hello-jmh/src/main/java/org/sample/ListOperations.java
backpaper0/sandbox
6b6dc836bc1183998b9ebf233946f7fd8ef097ba
[ "MIT" ]
15
2015-06-06T00:00:51.000Z
2020-06-26T00:21:52.000Z
hello-jmh/src/main/java/org/sample/ListOperations.java
backpaper0/sandbox
6b6dc836bc1183998b9ebf233946f7fd8ef097ba
[ "MIT" ]
5
2016-01-02T06:28:58.000Z
2022-02-19T23:04:15.000Z
hello-jmh/src/main/java/org/sample/ListOperations.java
backpaper0/sandbox
6b6dc836bc1183998b9ebf233946f7fd8ef097ba
[ "MIT" ]
12
2015-07-14T18:18:06.000Z
2021-11-17T02:27:14.000Z
24.850575
95
0.655412
994,735
package org.sample; import static java.util.stream.Collectors.*; import java.util.Collections; import java.util.List; import java.util.function.Supplier; import java.util.stream.IntStream; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; @State(Scope.Benchmark) public class ListOperations { @Param private ListImplementation listImplementation; private static List<Integer> addMe1 = IntStream.rangeClosed(1, 100) .mapToObj(Integer::valueOf) .collect(toList()); private static Integer addMe2 = 0; private static int size = addMe1.size() / 2; private static Integer findMe = addMe1.get(size); private List<Integer> list1; private List<Integer> list2; @Setup(Level.Invocation) public void setUp() { list1 = listImplementation.get(); list2 = listImplementation.get(); list2.addAll(addMe1); } @Benchmark public void get() { list2.get(size); } @Benchmark public void iteration() { for (final Integer unused : list2) { } } @Benchmark public void contains() { list2.contains(findMe); } @Benchmark public void indexOf() { list2.indexOf(findMe); } @Benchmark public void add() { list1.add(addMe2); } @Benchmark public void addAll() { list1.addAll(addMe1); } public enum ListImplementation { ArrayList(java.util.ArrayList::new), LinkedList(java.util.LinkedList::new), CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList::new), SynchronizedArrayList(() -> Collections.synchronizedList(new java.util.ArrayList<>())); private final Supplier<List<Integer>> factory; private ListImplementation(final Supplier<List<Integer>> factory) { this.factory = factory; } public List<Integer> get() { return factory.get(); } } }
922e68a46d63e1070b28670450fb8a7f29789b4f
4,600
java
Java
go/quickstep/src/com/android/quickstep/ThumbnailDrawable.java
Surendrajat/Omega
5ae5aec819fc933db852d3527f2fffc20db18d66
[ "Apache-2.0" ]
183
2018-05-03T03:08:09.000Z
2021-12-26T18:22:57.000Z
go/quickstep/src/com/android/quickstep/ThumbnailDrawable.java
Surendrajat/Omega
5ae5aec819fc933db852d3527f2fffc20db18d66
[ "Apache-2.0" ]
75
2018-06-04T15:11:53.000Z
2020-07-30T18:08:20.000Z
go/quickstep/src/com/android/quickstep/ThumbnailDrawable.java
Surendrajat/Omega
5ae5aec819fc933db852d3527f2fffc20db18d66
[ "Apache-2.0" ]
28
2018-06-07T03:42:17.000Z
2021-04-12T04:38:43.000Z
31.506849
91
0.675
994,736
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.quickstep; import static android.graphics.Shader.TileMode.CLAMP; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import androidx.annotation.NonNull; import com.android.launcher3.R; import com.android.systemui.shared.recents.model.ThumbnailData; /** * Bitmap backed drawable that supports rotating the thumbnail bitmap depending on if the * orientation the thumbnail was taken in matches the desired orientation. In addition, the * thumbnail always fills into the containing bounds. */ public final class ThumbnailDrawable extends Drawable { private final Paint mPaint = new Paint(); private final Matrix mMatrix = new Matrix(); private final ThumbnailData mThumbnailData; private final BitmapShader mShader; private final RectF mDestRect = new RectF(); private final int mCornerRadius; private int mRequestedOrientation; public ThumbnailDrawable(Resources res, @NonNull ThumbnailData thumbnailData, int requestedOrientation) { mThumbnailData = thumbnailData; mRequestedOrientation = requestedOrientation; mCornerRadius = (int) res.getDimension(R.dimen.task_thumbnail_corner_radius); mShader = new BitmapShader(mThumbnailData.thumbnail, CLAMP, CLAMP); mPaint.setShader(mShader); mPaint.setAntiAlias(true); updateMatrix(); } /** * Set the requested orientation. * * @param orientation the orientation we want the thumbnail to be in */ public void setRequestedOrientation(int orientation) { if (mRequestedOrientation != orientation) { mRequestedOrientation = orientation; updateMatrix(); } } @Override public void draw(Canvas canvas) { if (mThumbnailData.thumbnail == null) { return; } canvas.drawRoundRect(mDestRect, mCornerRadius, mCornerRadius, mPaint); } @Override protected void onBoundsChange(Rect bounds) { super.onBoundsChange(bounds); mDestRect.set(bounds); updateMatrix(); } @Override public void setAlpha(int alpha) { final int oldAlpha = mPaint.getAlpha(); if (alpha != oldAlpha) { mPaint.setAlpha(alpha); invalidateSelf(); } } @Override public int getAlpha() { return mPaint.getAlpha(); } @Override public void setColorFilter(ColorFilter colorFilter) { mPaint.setColorFilter(colorFilter); invalidateSelf(); } @Override public ColorFilter getColorFilter() { return mPaint.getColorFilter(); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } private void updateMatrix() { if (mThumbnailData.thumbnail == null) { return; } mMatrix.reset(); float scaleX; float scaleY; Rect bounds = getBounds(); Bitmap thumbnail = mThumbnailData.thumbnail; if (mRequestedOrientation != mThumbnailData.orientation) { // Rotate and translate so that top left is the same. mMatrix.postRotate(90, 0, 0); mMatrix.postTranslate(thumbnail.getHeight(), 0); scaleX = (float) bounds.width() / thumbnail.getHeight(); scaleY = (float) bounds.height() / thumbnail.getWidth(); } else { scaleX = (float) bounds.width() / thumbnail.getWidth(); scaleY = (float) bounds.height() / thumbnail.getHeight(); } // Scale to fill. mMatrix.postScale(scaleX, scaleY); mShader.setLocalMatrix(mMatrix); } }
922e6a3e7ea9fc51f432f657feee64e591570e16
2,231
java
Java
tests/unit/gov/noaa/nws/ncep/edex/plugin/aww/common/AwwFipsTest.java
drjoeycadieux/awips2
3b467b15915cba23d9216eefd97a21758e66c748
[ "Apache-2.0" ]
null
null
null
tests/unit/gov/noaa/nws/ncep/edex/plugin/aww/common/AwwFipsTest.java
drjoeycadieux/awips2
3b467b15915cba23d9216eefd97a21758e66c748
[ "Apache-2.0" ]
null
null
null
tests/unit/gov/noaa/nws/ncep/edex/plugin/aww/common/AwwFipsTest.java
drjoeycadieux/awips2
3b467b15915cba23d9216eefd97a21758e66c748
[ "Apache-2.0" ]
1
2021-10-30T00:03:05.000Z
2021-10-30T00:03:05.000Z
25.94186
84
0.649933
994,737
/** * This Java class is the JUnit test for the AwwFips. * * <pre> * SOFTWARE HISTORY * * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * 10/2008 38 L. Lin Creation * 04/2009 128 T. Lee Append ^r^n to testMndLine * </pre> * * @author L. Lin * @version 1.0 */ package gov.noaa.nws.ncep.edex.plugin.aww.common; import static org.junit.Assert.*; import java.util.Calendar; import gov.noaa.nws.ncep.edex.tools.decoder.MndTime; import gov.noaa.nws.ncep.edex.plugin.aww.util.AwwParser; import gov.noaa.nws.ncep.common.dataplugin.aww.AwwFips; import gov.noaa.nws.ncep.common.dataplugin.aww.AwwUgc; import java.util.Iterator; import java.util.ArrayList; import java.util.TimeZone; import org.junit.Test; public class AwwFipsTest { private final String testMndLine = "1005 AM EDT TUE SEP 16 2008\r\r\n"; private final String testUgcLine = "NDZ031-076-MIC094-162205-"; MndTime mt = new MndTime(testMndLine.getBytes()); Calendar mndTime = mt.getMndTime(); AwwUgc testUgc = new AwwUgc(); AwwFips af = new AwwFips(); public void setUp() throws Exception { } @Test public void testProcessFips() { ArrayList<String> cfipsList = new ArrayList<String>(); System.out.println("mndtime -->"+ mndTime); cfipsList.add("NDZ031"); cfipsList.add("NDZ076"); cfipsList.add("MIC094"); AwwParser.processFips(testUgcLine, testUgc, mndTime); /* * test the product purge date */ Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.set(Calendar.YEAR, 2008); cal.set(Calendar.MONTH, 8); cal.set(Calendar.DATE, 16); cal.set(Calendar.HOUR_OF_DAY, 22); cal.set(Calendar.MINUTE, 5); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cc = testUgc.getProdPurgeTime(); assertEquals(cal,cc); // test the county fips if (testUgc.getAwwFIPS() !=null && testUgc.getAwwFIPS().size() >0) { for (Iterator<AwwFips> iter = testUgc.getAwwFIPS().iterator(); iter.hasNext();) { AwwFips cond = iter.next(); String fips = cond.getFips(); assertTrue(cfipsList.contains(fips)); } } } }
922e6ac6a3cb6cb671969e34962816aaaeb55bf4
284
java
Java
lemeng/uikit/src/com/netease/nim/uikit/team/cjj/MaterialRefreshListener.java
519430378qqcom/2017-7-5
59bab2542e6691f4ac13860d560ee0e4ba8f20d3
[ "Apache-2.0" ]
null
null
null
lemeng/uikit/src/com/netease/nim/uikit/team/cjj/MaterialRefreshListener.java
519430378qqcom/2017-7-5
59bab2542e6691f4ac13860d560ee0e4ba8f20d3
[ "Apache-2.0" ]
null
null
null
lemeng/uikit/src/com/netease/nim/uikit/team/cjj/MaterialRefreshListener.java
519430378qqcom/2017-7-5
59bab2542e6691f4ac13860d560ee0e4ba8f20d3
[ "Apache-2.0" ]
null
null
null
35.5
81
0.809859
994,738
package com.netease.nim.uikit.team.cjj; public abstract class MaterialRefreshListener { public void onfinish(){}; public abstract void onRefresh(MaterialRefreshLayout materialRefreshLayout); public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout){}; }
922e6ac7f69564cd7064083bc426c92cab8af35c
830
java
Java
book-cloud-account/src/main/java/com/jerry/bookcloud/account/service/UserLikeSeeService.java
luoyefeiwu/learn_read_cloud
bfcd04b5e01bc8bac0d69ad2d34281aaab0ded2f
[ "Apache-2.0" ]
null
null
null
book-cloud-account/src/main/java/com/jerry/bookcloud/account/service/UserLikeSeeService.java
luoyefeiwu/learn_read_cloud
bfcd04b5e01bc8bac0d69ad2d34281aaab0ded2f
[ "Apache-2.0" ]
null
null
null
book-cloud-account/src/main/java/com/jerry/bookcloud/account/service/UserLikeSeeService.java
luoyefeiwu/learn_read_cloud
bfcd04b5e01bc8bac0d69ad2d34281aaab0ded2f
[ "Apache-2.0" ]
null
null
null
18.043478
76
0.577108
994,739
package com.jerry.bookcloud.account.service; import com.jerry.bookcloud.common.result.Result; /** * 喜欢看服务 */ public interface UserLikeSeeService { /** * 喜欢点击处理 * * @param userId * @param bookId * @param value 0.取消喜欢,1.喜欢 * @return */ Result likeSeeClick(Integer userId, String bookId, Integer value); /** * 获取图书喜欢数量 * * @param bookId * @return */ Result<Integer> getBookLikesCount(String bookId); /** * 获取用户喜欢列表 * * @param userId * @param page * @param limit * @return */ Result getUserLikeBookList(Integer userId, Integer page, Integer limit); /** * 用户是否喜欢此书 * * @param userId * @param bookId * @return */ Result userLikeThisBook(Integer userId, String bookId); }
922e6b991c9068e172e2d43b3b11dd5162a88848
2,428
java
Java
src/main/java/com/tterrag/k9/mcp/VersionJson.java
pie-flavor/K9
8820aa8073ed4e1c266e71bb3ac39a7149ca836e
[ "MIT" ]
null
null
null
src/main/java/com/tterrag/k9/mcp/VersionJson.java
pie-flavor/K9
8820aa8073ed4e1c266e71bb3ac39a7149ca836e
[ "MIT" ]
null
null
null
src/main/java/com/tterrag/k9/mcp/VersionJson.java
pie-flavor/K9
8820aa8073ed4e1c266e71bb3ac39a7149ca836e
[ "MIT" ]
null
null
null
29.253012
97
0.60832
994,740
package com.tterrag.k9.mcp; import java.util.Arrays; import java.util.Map; import java.util.Set; import java.util.TreeMap; import com.google.common.collect.Maps; import com.tterrag.k9.util.NonNull; import com.tterrag.k9.util.NullHelper; import com.tterrag.k9.util.Nullable; import gnu.trove.list.array.TIntArrayList; public class VersionJson { public static class MappingsJson { private TIntArrayList snapshot; private TIntArrayList stable; public boolean hasSnapshot(String version) { return hasSnapshot(Integer.valueOf(version)); } public boolean hasSnapshot(int version) { return snapshot.contains(version); } public int latestSnapshot() { return snapshot.get(0); } public boolean hasStable(String version) { return hasStable(Integer.valueOf(version)); } public boolean hasStable(int version) { return stable.contains(version); } public int latestStable() { return stable.size() > 0 ? stable.get(0) : -1; } } private final TreeMap<@NonNull String, MappingsJson> versionToList; public VersionJson(Map<String, MappingsJson> data) { this.versionToList = Maps.newTreeMap(VersionJson::compareVersions); this.versionToList.putAll(data); } private static int compareVersions(String version1, String version2) { int[] v1 = toVersionNumbers(version1); int[] v2 = toVersionNumbers(version2); for (int i = 0; i < v1.length && i < v2.length; i++) { if (v2[i] > v1[i]) { return -1; } else if (v2[i] < v1[i]) { return 1; } } return v1.length - v2.length; } private static int @NonNull[] toVersionNumbers(String version) { return Arrays.stream(version.split("\\.")).mapToInt(Integer::parseInt).toArray(); } public @Nullable MappingsJson getMappings(String mcversion) { return versionToList.get(mcversion); } public @NonNull Set<@NonNull String> getVersions() { return NullHelper.notnullJ(versionToList.descendingKeySet(), "TreeMap#descendingKeySet"); } public @NonNull String getLatestVersion() { return getVersions().iterator().next(); } }
922e6bf8e9f8dd248f9bbcd839792c77d4c9657e
4,004
java
Java
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/SelectFilteringAction.java
erdi/intellij-community
dda25a8a4e6375c6d964cb0197e5c387d585ea9e
[ "Apache-2.0" ]
2
2018-12-29T09:53:39.000Z
2018-12-29T09:53:42.000Z
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/SelectFilteringAction.java
tnorbye/intellij-community
f01cf262fc196bf4dbb99e20cd937dee3705a7b6
[ "Apache-2.0" ]
null
null
null
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/SelectFilteringAction.java
tnorbye/intellij-community
f01cf262fc196bf4dbb99e20cd937dee3705a7b6
[ "Apache-2.0" ]
1
2019-07-18T16:50:52.000Z
2019-07-18T16:50:52.000Z
34.817391
155
0.746004
994,741
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vcs.changes.committed; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.openapi.vcs.*; import com.intellij.util.NotNullFunction; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.List; /** * @author yole */ public class SelectFilteringAction extends LabeledComboBoxAction { @NotNull private final Project myProject; @NotNull private final CommittedChangesTreeBrowser myBrowser; @NotNull private ChangeListFilteringStrategy myPreviousSelection; public SelectFilteringAction(@NotNull Project project, @NotNull CommittedChangesTreeBrowser browser) { super(VcsBundle.message("committed.changes.filter.title")); myProject = project; myBrowser = browser; myPreviousSelection = ChangeListFilteringStrategy.NONE; } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setText(myPreviousSelection.toString()); } @NotNull @Override protected DefaultActionGroup createPopupActionGroup(JComponent button) { return new DefaultActionGroup(ContainerUtil.map(collectStrategies(), (NotNullFunction<ChangeListFilteringStrategy, AnAction>)strategy -> new SetFilteringAction(strategy))); } @NotNull @Override protected Condition<AnAction> getPreselectCondition() { return action -> ((SetFilteringAction)action).myStrategy.getKey().equals(myPreviousSelection.getKey()); } @NotNull private List<ChangeListFilteringStrategy> collectStrategies() { List<ChangeListFilteringStrategy> result = ContainerUtil.newArrayList(); result.add(ChangeListFilteringStrategy.NONE); result.add(new StructureFilteringStrategy(myProject)); boolean addNameFilter = false; for (AbstractVcs vcs : ProjectLevelVcsManager.getInstance(myProject).getAllActiveVcss()) { CommittedChangesProvider provider = vcs.getCommittedChangesProvider(); if (provider != null) { addNameFilter = true; for (ChangeListColumn column : provider.getColumns()) { if (ChangeListColumn.isCustom(column)) { result.add(new ColumnFilteringStrategy(column, provider.getClass())); } } } } if (addNameFilter) { result.add(new ColumnFilteringStrategy(ChangeListColumn.NAME, CommittedChangesProvider.class)); } return result; } private class SetFilteringAction extends DumbAwareAction { @NotNull private final ChangeListFilteringStrategy myStrategy; private SetFilteringAction(@NotNull ChangeListFilteringStrategy strategy) { super(strategy.toString()); myStrategy = strategy; } @Override public void actionPerformed(@NotNull AnActionEvent e) { if (!ChangeListFilteringStrategy.NONE.equals(myPreviousSelection)) { myBrowser.removeFilteringStrategy(myPreviousSelection.getKey()); } if (!ChangeListFilteringStrategy.NONE.equals(myStrategy)) { myBrowser.setFilteringStrategy(myStrategy); } myPreviousSelection = myStrategy; } } }
922e6dacb83e27d0956db39de7fa6c737e8748e9
689
java
Java
org.shaneking.roc.persistence/src/main/java/org/shaneking/roc/persistence/entity/ChannelizedEntity.java
ShaneKingOrg/org.shaneking.roc
8dbd0a4c245b7479a0929669a82ba50afc22792e
[ "Apache-2.0" ]
2
2021-08-18T13:51:39.000Z
2021-08-18T13:53:07.000Z
org.shaneking.roc.persistence/src/main/java/org/shaneking/roc/persistence/entity/ChannelizedEntity.java
ShaneKingOrg/org.shaneking.roc
8dbd0a4c245b7479a0929669a82ba50afc22792e
[ "Apache-2.0" ]
null
null
null
org.shaneking.roc.persistence/src/main/java/org/shaneking/roc/persistence/entity/ChannelizedEntity.java
ShaneKingOrg/org.shaneking.roc
8dbd0a4c245b7479a0929669a82ba50afc22792e
[ "Apache-2.0" ]
null
null
null
31.318182
96
0.802612
994,742
package org.shaneking.roc.persistence.entity; import com.github.liaochong.myexcel.core.annotation.ExcelColumn; import lombok.Getter; import lombok.Setter; import lombok.ToString; import lombok.experimental.Accessors; import org.shaneking.ling.persistence.entity.sql.Channelized; import org.shaneking.roc.persistence.AbstractCacheableEntity; import javax.persistence.Column; @Accessors(chain = true) @ToString(callSuper = true) public abstract class ChannelizedEntity extends AbstractCacheableEntity implements Channelized { @Column(length = 40, columnDefinition = "default '' COMMENT ''") @ExcelColumn(style = {"title->color:red"}) @Getter @Setter private String channelId; }
922e6eb8f6c6a93d2c1ff44080253c8bc2ddbb90
628
java
Java
operator/src/test/java/oracle/kubernetes/operator/logging/MockLoggingFilter.java
v-2vikc/weblogic-kubernetes-operator
8af46a3a9c7eba1214110805d7ceac387a743306
[ "UPL-1.0", "MIT" ]
1
2020-06-29T19:43:01.000Z
2020-06-29T19:43:01.000Z
operator/src/test/java/oracle/kubernetes/operator/logging/MockLoggingFilter.java
v-2vikc/weblogic-kubernetes-operator
8af46a3a9c7eba1214110805d7ceac387a743306
[ "UPL-1.0", "MIT" ]
null
null
null
operator/src/test/java/oracle/kubernetes/operator/logging/MockLoggingFilter.java
v-2vikc/weblogic-kubernetes-operator
8af46a3a9c7eba1214110805d7ceac387a743306
[ "UPL-1.0", "MIT" ]
null
null
null
26.166667
82
0.769108
994,743
// Copyright 2019, Oracle Corporation and/or its affiliates. All rights reserved. // Licensed under the Universal Permissive License v 1.0 as shown at // http://oss.oracle.com/licenses/upl. package oracle.kubernetes.operator.logging; public class MockLoggingFilter implements LoggingFilter { final boolean returnValue; public MockLoggingFilter(boolean returnValue) { this.returnValue = returnValue; } public static MockLoggingFilter createWithReturnValue(boolean returnValue) { return new MockLoggingFilter(returnValue); } @Override public boolean canLog(String msg) { return returnValue; } }
922e6ebaebd80730f48c2dc0537b9bc90c8d8491
4,569
java
Java
src/main/java/gui/LimitLinesDocumentListener.java
cwngg/email-to-pdf-converter
4c91fc586b3456330757d36acb0c5eb339507803
[ "Apache-2.0" ]
70
2020-10-04T06:37:12.000Z
2022-03-30T13:59:20.000Z
src/main/java/gui/LimitLinesDocumentListener.java
cwngg/email-to-pdf-converter
4c91fc586b3456330757d36acb0c5eb339507803
[ "Apache-2.0" ]
22
2020-10-05T17:23:14.000Z
2022-03-27T11:23:08.000Z
src/main/java/gui/LimitLinesDocumentListener.java
cwngg/email-to-pdf-converter
4c91fc586b3456330757d36acb0c5eb339507803
[ "Apache-2.0" ]
25
2020-10-07T07:08:05.000Z
2022-03-07T00:51:46.000Z
30.258278
84
0.648063
994,744
/* * Copyright 2016 Nick Russler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gui; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.Element; /** * A class to control the maximum number of lines to be stored in a Document * * Excess lines can be removed from the start or end of the Document depending * on your requirement. * * a) if you append text to the Document, then you would want to remove lines * from the start. b) if you insert text at the beginning of the Document, then * you would want to remove lines from the end. */ public class LimitLinesDocumentListener implements DocumentListener { private int maximumLines; private boolean isRemoveFromStart; /* * Specify the number of lines to be stored in the Document. Extra lines * will be removed from the start of the Document. */ public LimitLinesDocumentListener(int maximumLines) { this(maximumLines, true); } /* * Specify the number of lines to be stored in the Document. Extra lines * will be removed from the start or end of the Document, depending on the * boolean value specified. */ public LimitLinesDocumentListener(int maximumLines, boolean isRemoveFromStart) { setLimitLines(maximumLines); this.isRemoveFromStart = isRemoveFromStart; } /* * Return the maximum number of lines to be stored in the Document */ public int getLimitLines() { return maximumLines; } /* * Set the maximum number of lines to be stored in the Document */ public void setLimitLines(int maximumLines) { if (maximumLines < 1) { String message = "Maximum lines must be greater than 0"; throw new IllegalArgumentException(message); } this.maximumLines = maximumLines; } // Handle insertion of new text into the Document @Override public void insertUpdate(final DocumentEvent e) { // Changes to the Document can not be done within the listener // so we need to add the processing to the end of the EDT SwingUtilities.invokeLater(new Runnable() { @Override public void run() { removeLines(e); } }); } @Override public void removeUpdate(DocumentEvent e) { } @Override public void changedUpdate(DocumentEvent e) { } /* * Remove lines from the Document when necessary */ private void removeLines(DocumentEvent e) { // The root Element of the Document will tell us the total number // of line in the Document. Document document = e.getDocument(); Element root = document.getDefaultRootElement(); while (root.getElementCount() > maximumLines) { if (isRemoveFromStart) { removeFromStart(document, root); } else { removeFromEnd(document, root); } } } /* * Remove lines from the start of the Document */ private void removeFromStart(Document document, Element root) { Element line = root.getElement(0); int end = line.getEndOffset(); try { document.remove(0, end); } catch (BadLocationException ble) { ble.printStackTrace(); } } /* * Remove lines from the end of the Document */ private void removeFromEnd(Document document, Element root) { // We use start minus 1 to make sure we remove the newline // character of the previous line Element line = root.getElement(root.getElementCount() - 1); int start = line.getStartOffset(); int end = line.getEndOffset(); try { document.remove(start - 1, end - start); } catch (BadLocationException ble) { ble.printStackTrace(); } } }
922e70600eafec4bdef7970c13d937f893eeb354
1,128
java
Java
Mage.Sets/src/mage/cards/k/KitchenImp.java
zeffirojoe/mage
71260c382a4e3afef5cdf79adaa00855b963c166
[ "MIT" ]
1,444
2015-01-02T00:25:38.000Z
2022-03-31T13:57:18.000Z
Mage.Sets/src/mage/cards/k/KitchenImp.java
zeffirojoe/mage
71260c382a4e3afef5cdf79adaa00855b963c166
[ "MIT" ]
6,180
2015-01-02T19:10:09.000Z
2022-03-31T21:10:44.000Z
Mage.Sets/src/mage/cards/k/KitchenImp.java
zeffirojoe/mage
71260c382a4e3afef5cdf79adaa00855b963c166
[ "MIT" ]
1,001
2015-01-01T01:15:20.000Z
2022-03-30T20:23:04.000Z
24.521739
78
0.683511
994,745
package mage.cards.k; import mage.MageInt; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.keyword.FlyingAbility; import mage.abilities.keyword.HasteAbility; import mage.abilities.keyword.MadnessAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import java.util.UUID; /** * @author TheElk801 */ public final class KitchenImp extends CardImpl { public KitchenImp(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{B}"); this.subtype.add(SubType.IMP); this.power = new MageInt(2); this.toughness = new MageInt(2); // Flying this.addAbility(FlyingAbility.getInstance()); // Haste this.addAbility(HasteAbility.getInstance()); // Madness {B} this.addAbility(new MadnessAbility(this, new ManaCostsImpl<>("{B}"))); } private KitchenImp(final KitchenImp card) { super(card); } @Override public KitchenImp copy() { return new KitchenImp(this); } }
922e712d88aaca38de938e8acbe50d347f739b06
1,789
java
Java
business/src/main/java/study/business/infrastructure/jpa/dao/PersonDaoJpa.java
rafaeltorquato/javaee7-template
0f6d1f764cf0513c9134d7435bacc782d477a2b6
[ "MIT" ]
null
null
null
business/src/main/java/study/business/infrastructure/jpa/dao/PersonDaoJpa.java
rafaeltorquato/javaee7-template
0f6d1f764cf0513c9134d7435bacc782d477a2b6
[ "MIT" ]
null
null
null
business/src/main/java/study/business/infrastructure/jpa/dao/PersonDaoJpa.java
rafaeltorquato/javaee7-template
0f6d1f764cf0513c9134d7435bacc782d477a2b6
[ "MIT" ]
null
null
null
29.327869
87
0.667412
994,746
package study.business.infrastructure.jpa.dao; import study.business.domain.model.person.Person; import study.business.domain.model.person.PersonDao; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityGraph; import javax.persistence.EntityManager; import javax.persistence.LockModeType; import javax.persistence.PersistenceContext; import java.util.HashMap; import java.util.List; import java.util.Map; @TransactionAttribute(TransactionAttributeType.MANDATORY) @Stateless public class PersonDaoJpa implements PersonDao { @PersistenceContext private EntityManager em; @Override public void save(Person person) { if (em.contains(person)) { em.persist(person); } else { em.merge(person); } } @Override public void delete(Person person) { em.remove(person); } @Override @SuppressWarnings("unchecked") public List<Person> list() { EntityGraph entityGraph = em.getEntityGraph("fetch-all-limited-relationship"); return em.createNamedQuery(Person.LIST_ALL) .setHint("javax.persistence.fetchgraph", entityGraph) .getResultList(); } @Override public Person findById(Long id) { EntityGraph entityGraph = em.getEntityGraph("fetch-all-limited-relationship"); Map<String, Object> properties = new HashMap<>(); properties.put("javax.persistence.fetchgraph", entityGraph); Person person = em.find(Person.class, id, properties); if (person != null) { em.lock(person, LockModeType.OPTIMISTIC); } return person; } }