blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
d48c33e3d368d89fb44b3f88219a95aa72e5296a
Java
LINGLUOJUN/node-manager
/src/main/java/com/six/node_manager/Lock.java
UTF-8
210
1.773438
2
[]
no_license
package com.six.node_manager; /** * @author sixliu E-mail:359852326@qq.com * @version 创建时间:2018年1月17日 下午8:05:43 类说明 */ public interface Lock { void lock(); void unlock(); }
true
9c735c5e9473284717c40d2ebbb16acdeb086d4b
Java
2014283119/test
/src/main/java/com/demo/ading/demo/service/DingUserService.java
UTF-8
296
1.75
2
[]
no_license
package com.demo.ading.demo.service; import com.demo.ading.demo.dto.DingUserDTO; import com.demo.ading.demo.dto.DingUserIdDTO; public interface DingUserService { DingUserIdDTO getUserId(String access_token, String code); DingUserDTO getUserInfo(String access_token, String userid); }
true
064aa1572caffaafc7eb75056890d65d92166fbc
Java
lzb4616/BuyThingsByLBS
/BuyThingsByLBS/src/com/bishe/ui/base/BaseHomeFragment.java
UTF-8
1,026
2.0625
2
[]
no_license
package com.bishe.ui.base; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * @author robin * @date 2015-4-21 * Copyright 2015 The robin . All rights reserved */ public abstract class BaseHomeFragment extends BaseFragment{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View contentView = inflater.inflate(getLayoutId(),container,false); initData(); findViews(contentView); setupViews(savedInstanceState); initListeners(); return contentView; } protected abstract int getLayoutId(); protected abstract void findViews(View view); protected abstract void setupViews(Bundle bundle); protected abstract void initListeners(); protected abstract void initData(); }
true
736137590dc34f1674f2dce602c82b1fd58536b5
Java
crazyandcoder/awesome-practise
/android/TopUniversity-Android/app/src/main/java/com/crazyandcoder/top/university/di/component/setting/AboutComponent.java
UTF-8
1,055
1.859375
2
[]
no_license
package com.crazyandcoder.top.university.di.component.setting; import dagger.BindsInstance; import dagger.Component; import com.crazyandcoder.android.lib.base.di.component.AppComponent; import com.crazyandcoder.top.university.di.module.setting.AboutModule; import com.crazyandcoder.top.university.mvp.contract.setting.AboutContract; import com.crazyandcoder.android.lib.base.di.scope.ActivityScope; import com.crazyandcoder.top.university.mvp.ui.activity.setting.AboutActivity; /** * ================================================ * * @Author: crazyandcoder * @Version: 1.0 * ================================================ */ @ActivityScope @Component(modules = AboutModule.class, dependencies = AppComponent.class) public interface AboutComponent { void inject(AboutActivity activity); @Component.Builder interface Builder { @BindsInstance AboutComponent.Builder view(AboutContract.View view); AboutComponent.Builder appComponent(AppComponent appComponent); AboutComponent build(); } }
true
13a94e5288f1e6fb544294a396a97a9f8cfee403
Java
umitmert/sample_springboot_project
/src/test/java/com/iyzico/service/TodoServiceTest.java
UTF-8
1,380
2.078125
2
[]
no_license
package com.iyzico.service; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; import com.ibss.domain.Todo; import com.ibss.domain.TodoState; import com.ibss.repository.TodoRepository; @RunWith(SpringRunner.class) @DataJpaTest @AutoConfigureTestDatabase(replace=Replace.NONE) public class TodoServiceTest { @Autowired TodoRepository todoRepository; @Autowired TestEntityManager testEntityManager; @Test public void create() { String desc = "Todo 1"; Todo todoInfo = new Todo(); todoInfo.setDesc(desc); todoInfo.setState(TodoState.WAITING); testEntityManager.persist(todoInfo); Todo todo = this.todoRepository.findByDesc(desc); assertThat(todo.getState().name(), equalTo(TodoState.WAITING.name())); } }
true
7ea1172dfba9af73f9bb640dfeb6701aa7cba4fd
Java
swJava/Guns-1
/guns-rest/src/main/java/com/stylefeng/guns/rest/modular/examine/responser/ExamineAnswerPaperListResponse.java
UTF-8
1,185
2.171875
2
[ "Apache-2.0" ]
permissive
package com.stylefeng.guns.rest.modular.examine.responser; import com.stylefeng.guns.rest.core.SimpleResponser; import java.util.ArrayList; import java.util.Collection; import java.util.Set; /** * @Description //TODO * @Author 罗华 * @Date 2019/2/20 00:01 * @Version 1.0 */ public class ExamineAnswerPaperListResponse extends SimpleResponser { private Collection<ExamineAnswerPaperResponse> datas = new ArrayList<ExamineAnswerPaperResponse>(); public static ExamineAnswerPaperListResponse me(Set<ExamineAnswerPaperResponse> paperResponseList) { ExamineAnswerPaperListResponse responser = new ExamineAnswerPaperListResponse(); responser.setCode(SUCCEED); responser.setMessage("查询成功"); if (null != paperResponseList) responser.setDatas(paperResponseList); return responser; } public Collection<ExamineAnswerPaperResponse> getDatas() { return datas; } public void setDatas(Collection<ExamineAnswerPaperResponse> datas) { this.datas = datas; } public void add(ExamineAnswerPaperResponse answerPaperResponse) { this.datas.add(answerPaperResponse); } }
true
eb9913450ba13325438bfb5b280a817a8d8c3b33
Java
yachmenev/MyProject
/src/reversList/Type.java
UTF-8
561
3.265625
3
[]
no_license
package reversList; /** * Created by Admin on 30.11.14. */ public class Type { String str; Integer i; public Type(Object obj){ if (obj instanceof String){ str = (String) obj; } else if (obj instanceof Integer){ i = (Integer) obj; } else { new IllegalStateException("illegal"); } } @Override public String toString() { if (str != null){ return str; } else { return i.toString(); } } }
true
326d91d4e88a187f3e380608bd562bf68272ac16
Java
rituvesh/data-catalog-backend
/data-catalog-backend-test/data-catalog-backend-test-integration/src/test/java/no/nav/data/catalog/backend/test/integration/informationtype/InformationTypeControllerIT.java
UTF-8
26,896
1.625
2
[ "MIT" ]
permissive
package no.nav.data.catalog.backend.test.integration.informationtype; import no.nav.data.catalog.backend.app.AppStarter; import no.nav.data.catalog.backend.app.codelist.CodelistService; import no.nav.data.catalog.backend.app.codelist.ListName; import no.nav.data.catalog.backend.app.informationtype.InformationType; import no.nav.data.catalog.backend.app.informationtype.InformationTypeRepository; import no.nav.data.catalog.backend.app.informationtype.InformationTypeRequest; import no.nav.data.catalog.backend.app.informationtype.InformationTypeResponse; import no.nav.data.catalog.backend.app.informationtype.RestResponsePage; import no.nav.data.catalog.backend.test.component.PostgresTestContainer; import no.nav.data.catalog.backend.test.component.elasticsearch.FixedElasticsearchContainer; import no.nav.data.catalog.backend.test.integration.IntegrationTestConfig; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; import static no.nav.data.catalog.backend.app.elasticsearch.ElasticsearchStatus.TO_BE_DELETED; import static no.nav.data.catalog.backend.app.elasticsearch.ElasticsearchStatus.TO_BE_UPDATED; import static no.nav.data.catalog.backend.test.integration.informationtype.TestdataInformationTypes.CATEGORY_CODE; import static no.nav.data.catalog.backend.test.integration.informationtype.TestdataInformationTypes.DESCRIPTION; import static no.nav.data.catalog.backend.test.integration.informationtype.TestdataInformationTypes.NAME; import static no.nav.data.catalog.backend.test.integration.informationtype.TestdataInformationTypes.PRODUCER_CODE_STRING; import static no.nav.data.catalog.backend.test.integration.informationtype.TestdataInformationTypes.SYSTEM_CODE; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {IntegrationTestConfig.class, AppStarter.class}) @ActiveProfiles("test") @ContextConfiguration(initializers = {PostgresTestContainer.Initializer.class}) public class InformationTypeControllerIT { @Autowired protected TestRestTemplate restTemplate; @Autowired protected InformationTypeRepository repository; @Autowired protected CodelistService codelistService; private static Map<ListName, Map<String, String>> codelists; @ClassRule public static PostgresTestContainer postgreSQLContainer = PostgresTestContainer.getInstance(); @ClassRule public static FixedElasticsearchContainer container = new FixedElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch-oss:6.4.1"); @Before public void setUp() { repository.deleteAll(); initializeCodelists(); } @After public void cleanUp() { repository.deleteAll(); } private void initializeCodelists() { codelists = CodelistService.codelists; codelists.get(ListName.CATEGORY).put("PERSONALIA", "Personalia"); codelists.get(ListName.CATEGORY).put("ARBEIDSFORHOLD", "Arbeidsforhold"); codelists.get(ListName.PRODUCER).put("SKATTEETATEN", "Skatteetaten"); codelists.get(ListName.PRODUCER).put("BRUKER", "Bruker"); codelists.get(ListName.PRODUCER).put("FOLKEREGISTERET", "Folkeregisteret"); codelists.get(ListName.PRODUCER).put("ARBEIDSGIVER", "Arbeidsgiver"); codelists.get(ListName.SYSTEM).put("AA-REG", "Arbeidsgiver / Arbeidstaker register"); codelists.get(ListName.SYSTEM).put("TPS", "Tjenestebasert PersondataSystem"); } @Test public void getInformationTypeById() { InformationType informationType = saveAnInformationType(createRequest()); ResponseEntity<InformationTypeResponse> responseEntity = restTemplate.exchange( "/informationtype/" + informationType.getId(), HttpMethod.GET, HttpEntity.EMPTY, InformationTypeResponse.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertInformationTypeResponse(responseEntity.getBody()); } @Test public void getInformationTypeByName() { InformationType informationType = saveAnInformationType(createRequest()); ResponseEntity<InformationTypeResponse> responseEntity = restTemplate.exchange( "/informationtype/name/" + informationType.getName(), HttpMethod.GET, HttpEntity.EMPTY, InformationTypeResponse.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertInformationTypeResponse(responseEntity.getBody()); responseEntity = restTemplate.exchange( "/informationtype/name/" + informationType.getName().toUpperCase(), HttpMethod.GET, HttpEntity.EMPTY, InformationTypeResponse.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertInformationTypeResponse(responseEntity.getBody()); responseEntity = restTemplate.exchange( "/informationtype/name/" + informationType.getName() .toLowerCase(), HttpMethod.GET, HttpEntity.EMPTY, InformationTypeResponse.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertInformationTypeResponse(responseEntity.getBody()); responseEntity = restTemplate.exchange( "/informationtype/name/" + informationType.getName() + " ", HttpMethod.GET, HttpEntity.EMPTY, InformationTypeResponse.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertInformationTypeResponse(responseEntity.getBody()); } private InformationType saveAnInformationType(InformationTypeRequest request) { return repository.save(new InformationType().convertFromRequest(request, false)); } @Test public void get20FirstInformationTypes() { createInformationTypeTestData(30); ResponseEntity<RestResponsePage<InformationTypeResponse>> responseEntity = restTemplate.exchange("/informationtype", HttpMethod.GET, HttpEntity.EMPTY, new ParameterizedTypeReference<RestResponsePage<InformationTypeResponse>>() { }); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(repository.findAll().size(), is(30)); assertThat(responseEntity.getBody().getContent().size(), is(20)); assertThat(responseEntity.getBody().getNumber(), is(0)); assertThat(responseEntity.getBody().getSize(), is(20)); assertThat(responseEntity.getBody().getTotalElements(), is(30L)); } @Test public void get100InformationTypes() { createInformationTypeTestData(100); ResponseEntity<RestResponsePage<InformationTypeResponse>> responseEntity = restTemplate.exchange( "/informationtype?page=0&pageSize=100", HttpMethod.GET, null, new ParameterizedTypeReference<RestResponsePage<InformationTypeResponse>>() { }); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(repository.findAll().size(), is(100)); assertThat(responseEntity.getBody().getContent().size(), is(100)); assertThat(responseEntity.getBody().getNumber(), is(0)); assertThat(responseEntity.getBody().getSize(), is(100)); assertThat(responseEntity.getBody().getTotalElements(), is(100L)); } @Test public void getLastPageWithInformationTypes() { createInformationTypeTestData(98); ResponseEntity<RestResponsePage<InformationTypeResponse>> responseEntity = restTemplate.exchange( "/informationtype?page=4&pageSize=20", HttpMethod.GET, null, new ParameterizedTypeReference<RestResponsePage<InformationTypeResponse>>() { }); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(repository.findAll().size(), is(98)); assertThat(responseEntity.getBody().getContent().size(), is(18)); assertThat(responseEntity.getBody().getNumber(), is(4)); assertThat(responseEntity.getBody().getSize(), is(20)); assertThat(responseEntity.getBody().getTotalElements(), is(98L)); } @Test public void getInformationTypesSortedByIdInDescendingOrder() { createInformationTypeTestData(100); ResponseEntity<RestResponsePage<InformationTypeResponse>> responseEntity = restTemplate.exchange( "/informationtype?sort=id,desc", HttpMethod.GET, null, new ParameterizedTypeReference<RestResponsePage<InformationTypeResponse>>() { }); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(repository.findAll().size(), is(100)); assertThat(responseEntity.getBody().getContent().get(0).getName(), equalTo("InformationTypeName_nr_100")); assertThat(responseEntity.getBody().getContent().get(1).getName(), equalTo("InformationTypeName_nr_99")); assertThat(responseEntity.getBody().getNumber(), is(0)); assertThat(responseEntity.getBody().getSize(), is(20)); assertThat(responseEntity.getBody().getTotalElements(), is(100L)); } @Test public void getAllInformationTypesThatHasTheNumberOneInTheName() { createInformationTypeTestData(100); ResponseEntity<RestResponsePage<InformationTypeResponse>> responseEntity = restTemplate.exchange( "/informationtype?name=1&pageSize=30", HttpMethod.GET, null, new ParameterizedTypeReference<RestResponsePage<InformationTypeResponse>>() { }); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(repository.findAll().size(), is(100)); assertThat(responseEntity.getBody().getContent().size(), is(20)); assertThat(responseEntity.getBody().getNumber(), is(0)); assertThat(responseEntity.getBody().getSize(), is(30)); assertThat(responseEntity.getBody().getTotalElements(), is(20L)); } @Test public void getInformationTypeByFilterQuerys() { initializeDBForFilterQuery(); ResponseEntity<RestResponsePage<InformationTypeResponse>> responseEntity = restTemplate.exchange("/informationtype?name=Sivilstand", HttpMethod.GET, null, new ParameterizedTypeReference<RestResponsePage<InformationTypeResponse>>() { }); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(repository.findAll().size(), is(3)); assertThat(responseEntity.getBody().getContent().size(), is(1)); assertThat(responseEntity.getBody().getNumber(), is(0)); assertThat(responseEntity.getBody().getSize(), is(20)); assertThat(responseEntity.getBody().getTotalElements(), is(1L)); assertThat(responseEntity.getBody().getContent().get(0).getName(), equalTo("Sivilstand")); responseEntity = restTemplate.exchange("/informationtype?description=begrepskatalog", HttpMethod.GET, null, new ParameterizedTypeReference<RestResponsePage<InformationTypeResponse>>() { }); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(responseEntity.getBody().getContent().size(), is(2)); assertThat(responseEntity.getBody().getTotalElements(), is(2L)); assertThat(responseEntity.getBody().getContent().get(0).getName(), equalTo("Sivilstand")); assertThat(responseEntity.getBody().getContent().get(1).getName(), equalTo("Kjønn")); responseEntity = restTemplate.exchange("/informationtype?personalData=false", HttpMethod.GET, null, new ParameterizedTypeReference<RestResponsePage<InformationTypeResponse>>() { }); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(responseEntity.getBody().getContent().size(), is(1)); assertThat(responseEntity.getBody().getTotalElements(), is(1L)); assertThat(responseEntity.getBody().getContent().get(0).getName(), equalTo("Kjønn")); responseEntity = restTemplate.exchange("/informationtype?category=PERSONALIA", HttpMethod.GET, null, new ParameterizedTypeReference<RestResponsePage<InformationTypeResponse>>() { }); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(responseEntity.getBody().getContent().size(), is(2)); assertThat(responseEntity.getBody().getTotalElements(), is(2L)); assertThat(responseEntity.getBody().getContent().get(0).getName(), equalTo("Sivilstand")); assertThat(responseEntity.getBody().getContent().get(1).getName(), equalTo("Kjønn")); responseEntity = restTemplate.exchange("/informationtype?system=aa-reg", HttpMethod.GET, null, new ParameterizedTypeReference<RestResponsePage<InformationTypeResponse>>() { }); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(responseEntity.getBody().getContent().size(), is(2)); assertThat(responseEntity.getBody().getTotalElements(), is(2L)); assertThat(responseEntity.getBody().getContent().get(0).getName(), equalTo("Sivilstand")); assertThat(responseEntity.getBody().getContent().get(1).getName(), equalTo("Arbeidsforhold")); responseEntity = restTemplate.exchange("/informationtype?producer=Folkeregisteret", HttpMethod.GET, null, new ParameterizedTypeReference<RestResponsePage<InformationTypeResponse>>() { }); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(responseEntity.getBody().getContent().size(), is(2)); assertThat(responseEntity.getBody().getTotalElements(), is(2L)); assertThat(responseEntity.getBody().getContent().get(0).getName(), equalTo("Sivilstand")); assertThat(responseEntity.getBody().getContent().get(0).getProducer().size(), is(1)); assertThat(responseEntity.getBody().getContent().get(1).getName(), equalTo("Kjønn")); assertThat(responseEntity.getBody().getContent().get(1).getProducer().size(), is(2)); responseEntity = restTemplate.exchange("/informationtype?producer=Folkeregisteret&sort=id,desc", HttpMethod.GET, null, new ParameterizedTypeReference<RestResponsePage<InformationTypeResponse>>() { }); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(responseEntity.getBody().getContent().size(), is(2)); assertThat(responseEntity.getBody().getTotalElements(), is(2L)); assertThat(responseEntity.getBody().getContent().get(1).getName(), equalTo("Sivilstand")); assertThat(responseEntity.getBody().getContent().get(1).getProducer().size(), is(1)); assertThat(responseEntity.getBody().getContent().get(0).getName(), equalTo("Kjønn")); assertThat(responseEntity.getBody().getContent().get(0).getProducer().size(), is(2)); } @Test public void countInformationTypes() { createInformationTypeTestData(100); ResponseEntity<Long> responseEntity = restTemplate.exchange( "/informationtype/count", HttpMethod.GET, null, Long.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(repository.findAll().size(), is(100)); assertThat(responseEntity.getBody(), is(100L)); } @Test public void countNoInformationTypes() { ResponseEntity<Long> responseEntity = restTemplate.exchange( "/informationtype/count", HttpMethod.GET, null, Long.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(repository.findAll().size(), is(0)); assertThat(responseEntity.getBody(), is(0L)); } @Test public void createInformationType() { List<InformationTypeRequest> requests = List.of(createRequest()); ResponseEntity<String> responseEntity = restTemplate.exchange( "/informationtype", HttpMethod.POST, new HttpEntity<>(requests), String.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.ACCEPTED)); assertThat(repository.findAll().size(), is(1)); assertInformationType(repository.findByName("InformationName").get()); } @Test public void createInformationType_shouldThrowValidationException_withEmptyListOfRequests() { List requests = Collections.emptyList(); ResponseEntity<String> responseEntity = restTemplate.exchange( "/informationtype", HttpMethod.POST, new HttpEntity<>(requests), String.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.BAD_REQUEST)); assertThat(responseEntity.getBody(), containsString("The request was not accepted because it is empty")); } @Test public void createInformationTypes_shouldThrowValidationErrors_withInvalidRequests() { List<InformationTypeRequest> requestsListWithEmtpyAndDuplicate = List.of( createRequest("Request_1"), createRequest("Request_2"), InformationTypeRequest.builder().build(), createRequest("Request_2")); ResponseEntity<String> responseEntity = restTemplate.exchange( "/informationtype", HttpMethod.POST, new HttpEntity<>(requestsListWithEmtpyAndDuplicate), String.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.BAD_REQUEST)); assertThat(repository.findAll().size(), is(0)); } @Test public void updateInformationTypes() { List<InformationTypeRequest> requests = List.of(createRequest("UPDATE_1"), createRequest("UPDATE_2")); ResponseEntity<String> responseEntity = restTemplate.exchange( "/informationtype", HttpMethod.POST, new HttpEntity<>(requests), String.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.ACCEPTED)); assertThat(repository.findAll().size(), is(2)); requests.forEach(request -> request.setDescription("Updated description")); ResponseEntity<List<InformationTypeResponse>> updatedResponseEntity = restTemplate.exchange( "/informationtype", HttpMethod.PUT, new HttpEntity<>(requests), new ParameterizedTypeReference<List<InformationTypeResponse>>() { }); assertThat(updatedResponseEntity.getStatusCode(), is(HttpStatus.ACCEPTED)); assertThat(repository.findAll().size(), is(2)); assertThat(repository.findAll().get(0).getDescription(), is("Updated description")); assertThat(repository.findAll().get(1).getDescription(), is("Updated description")); } @Test public void updateInformationTypes_shouldReturnNotFound_withNonExistingInformationType() { createInformationTypeTestData(2); List<InformationTypeRequest> requests = List.of( createRequest("InformationTypeName_nr_1"), createRequest("InformationTypeName_nr_3")); ResponseEntity<String> responseEntity = restTemplate.exchange( "/informationtype", HttpMethod.PUT, new HttpEntity<>(requests), String.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.BAD_REQUEST)); assertThat(responseEntity.getBody(), containsString( "Request:2={nameNotFound=There is not an InformationType with the name InformationTypeName_nr_3 and therefore it cannot be updated}")); } @Test public void updateInformationTypes_shouldReturnBadRequest_withInvalidRequests() { createInformationTypeTestData(2); assertThat(repository.findAll().size(), is(2)); List<InformationTypeRequest> updateRequestsWithEmptyRequest = List.of( createRequest("InformationTypeName_nr_2"), InformationTypeRequest.builder().build(), createRequest("InformationTypeName_nr_1")); ResponseEntity<String> responseEntity = restTemplate.exchange( "/informationtype", HttpMethod.PUT, new HttpEntity<>(updateRequestsWithEmptyRequest), String.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.BAD_REQUEST)); assertThat(repository.findAll().size(), is(2)); } //TODO: Is this method ever used? @Test public void updateOneInformationTypeById() { InformationTypeRequest request = createRequest(); repository.save(new InformationType().convertFromRequest(request, false)); assertThat(repository.findAll().size(), is(1)); InformationType storedInformationType = repository.findByName("InformationName").get(); request.setDescription("InformationDescription" + "UPDATED"); ResponseEntity responseEntity = restTemplate.exchange( "/informationtype/" + storedInformationType.getId(), HttpMethod.PUT, new HttpEntity<>(request), String.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.ACCEPTED)); assertThat(repository.findAll().size(), is(1)); storedInformationType = repository.findByName("InformationName").get(); assertThat(storedInformationType.getDescription(), is("InformationDescription" + "UPDATED")); assertThat(storedInformationType.getElasticsearchStatus(), is(TO_BE_UPDATED)); } @Test public void deleteInformationTypeById() { List<InformationTypeRequest> requests = List.of(createRequest()); ResponseEntity<String> responseEntity = restTemplate.exchange( "/informationtype", HttpMethod.POST, new HttpEntity<>(requests), String.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.ACCEPTED)); assertThat(repository.findAll().size(), is(1)); InformationType storedInformationType = repository.findByName("InformationName").get(); responseEntity = restTemplate.exchange( "/informationtype/" + storedInformationType.getId(), HttpMethod.DELETE, HttpEntity.EMPTY, String.class); assertThat(repository.findAll().size(), is(1)); assertThat(responseEntity.getStatusCode(), is(HttpStatus.ACCEPTED)); storedInformationType = repository.findByName("InformationName").get(); assertThat(storedInformationType.getElasticsearchStatus(), is(TO_BE_DELETED)); } @Test public void deleteInformationTypeById_returnNotFound_whenNonExistingId() { long nonExistingId = 42L; ResponseEntity responseEntity = restTemplate.exchange( "/informationtype/" + nonExistingId, HttpMethod.DELETE, HttpEntity.EMPTY, String.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.NOT_FOUND)); assertNull(responseEntity.getBody()); } @Test public void createInformationType_shouldChangeFieldsInTheRequestToTheCorrectFormat() { InformationTypeRequest request = InformationTypeRequest.builder() .name(" Trimmed Name ") .description(" Trimmed description ") .categoryCode(" perSonAlia ") .systemCode(" aa-Reg ") .producerCode(List.of("skatteetaten", " BruKer ")) .personalData(true) .build(); ResponseEntity<String> responseEntity = restTemplate.exchange( "/informationtype", HttpMethod.POST, new HttpEntity<>(List.of(request)), String.class); assertThat(responseEntity.getStatusCode(), is(HttpStatus.ACCEPTED)); assertTrue(repository.findByName("Trimmed Name").isPresent()); InformationType validatedInformationType = repository.findByName("Trimmed Name").get(); assertThat(validatedInformationType.getName(), is("Trimmed Name")); assertThat(validatedInformationType.getDescription(), is("Trimmed description")); assertThat(validatedInformationType.getCategoryCode(), is("PERSONALIA")); assertThat(validatedInformationType.getSystemCode(), is("AA-REG")); assertThat(validatedInformationType.getProducerCode(), is("SKATTEETATEN, BRUKER")); assertTrue(validatedInformationType.isPersonalData()); } private void assertInformationType(InformationType informationType) { assertThat(informationType.getProducerCode(), is(PRODUCER_CODE_STRING)); assertThat(informationType.getSystemCode(), is(SYSTEM_CODE)); assertThat(informationType.isPersonalData(), is(true)); assertThat(informationType.getName(), is(NAME)); assertThat(informationType.getDescription(), is(DESCRIPTION)); assertThat(informationType.getCategoryCode(), is(CATEGORY_CODE)); } private void assertInformationTypeResponse(InformationTypeResponse response) { assertThat(response.getName(), equalTo("InformationName")); assertThat(response.getDescription(), equalTo("InformationDescription")); assertThat(response.getCategory().get("code"), equalTo("PERSONALIA")); assertThat(response.getCategory().get("description"), equalTo("Personalia")); assertThat(response.getProducer(), equalTo(List.of( Map.of("code", "SKATTEETATEN", "description", "Skatteetaten"), Map.of("code", "BRUKER", "description", "Bruker")))); assertThat(response.getSystem().get("code"), equalTo("AA-REG")); assertThat(response.getSystem().get("description"), equalTo("Arbeidsgiver / Arbeidstaker register")); } private void createInformationTypeTestData(int nrOfRows) { repository.saveAll(IntStream.rangeClosed(1, nrOfRows) .mapToObj(i -> new InformationType() .convertFromRequest(createRequest("InformationTypeName_nr_" + i), false)) .collect(Collectors.toList())); } private InformationTypeRequest createRequest(String name) { return InformationTypeRequest.builder() .name(name) .description("InformationDescription") .categoryCode("PERSONALIA") .producerCode(List.of("SKATTEETATEN", "BRUKER")) .systemCode("AA-REG") .personalData(true) .build(); } private InformationTypeRequest createRequest() { return createRequest("InformationName"); } private void initializeDBForFilterQuery() { InformationTypeRequest sivilstandRequest = InformationTypeRequest.builder() .name("Sivilstand") .description("En overordnet kategori som beskriver en persons forhold til en annen person. Ref. til Begrepskatalog: https://jira.adeo.no/browse/BEGREP-176") .categoryCode("PERSONALIA") .producerCode(List.of("Folkeregisteret")) .systemCode("AA-REG") .personalData(true) .build(); InformationTypeRequest arbeidsforholdRequest = InformationTypeRequest.builder() .name("Arbeidsforhold") .description("Avtaleforhold hvor den ene part, arbeidstakeren, forplikter seg til å utføre arbeid mot lønn eller annen godtgjørelse for den annen part, arbeidsgiveren, i henhold til dennes ledelse.") .categoryCode("Arbeidsforhold") .producerCode(List.of("Arbeidsgiver")) .systemCode("AA-REG") .personalData(true) .build(); InformationTypeRequest kjonnRequest = InformationTypeRequest.builder() .name("Kjønn") .description("TODO - mangler i begrepskatalogen og i MFNs begrepsoversikt") .categoryCode("PERSONALIA") .producerCode(List.of("FOLKEREGISTERET", "BRUKER")) .systemCode("TPS") .personalData(false) .build(); sivilstandRequest.toUpperCaseAndTrim(); arbeidsforholdRequest.toUpperCaseAndTrim(); kjonnRequest.toUpperCaseAndTrim(); repository.save(new InformationType().convertFromRequest(sivilstandRequest, false)); repository.save(new InformationType().convertFromRequest(arbeidsforholdRequest, false)); repository.save(new InformationType().convertFromRequest(kjonnRequest, false)); } }
true
a9082bece7723c0bba4d5c3496e7384e203f1c1e
Java
aimbin/bean-autocoder
/autocoder/org.aimbin.autocoder.bean/src/main/java/org/aimbin/autocoder/service/DaoCreateService.java
UTF-8
541
1.914063
2
[ "MIT" ]
permissive
/** fun_endless@163.com 2018年11月28日 */ package org.aimbin.autocoder.service; import java.util.Map; import org.aimbin.autocoder.component.ClassContent; /**Create a data access object. * @author aimbin * @verison 1.0.0 2018年11月28日 */ public interface DaoCreateService { /** * Create a DAO like MyBatis-Mapper from bean class info. * @author aimbin * @version 1.0.0 2018年12月13日 * @param beanClaz * @param configs */ public ClassContent createDao(Object beanClaz, Map<String,String> configs ); }
true
bede421e9db53d96ec6ecc43f92b14f9b579fb7d
Java
tdscott10/sportsCompare2
/src/model/Sport.java
UTF-8
1,221
2.5
2
[]
no_license
package model; public class Sport { private int sportId; private int userId; private String name; private String position; private String favoriteTeam; public Sport(int sportId, int userId, String name, String position, String favoriteTeam) { this.sportId = sportId; this.userId = userId; this.name = name; this.position = position; this.favoriteTeam = favoriteTeam; } public Sport(int userId, String name, String position, String favoriteTeam) { this.userId = userId; this.name = name; this.position = position; this.favoriteTeam = favoriteTeam; } public int getSportId() { return sportId; } public void setSportId(int sportId) { this.sportId = sportId; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getFavoriteTeam() { return favoriteTeam; } public void setFavoriteTeam(String favoriteTeam) { this.favoriteTeam = favoriteTeam; } }
true
614f3d1f78ebbc489737102b393e545be715d3e7
Java
zhongxingyu/Seer
/Diff-Raw-Data/32/32_8850cb53dee2524a82712cfbadc739e78ce1aaa2/GUIMessage/32_8850cb53dee2524a82712cfbadc739e78ce1aaa2_GUIMessage_s.java
UTF-8
1,577
2.8125
3
[]
no_license
package net.sf.freecol.client.gui; import java.awt.Color; import java.util.Date; import java.util.logging.Logger; /** * Represents a message that can be displayed in the GUI. It has message data * and a Color. */ public final class GUIMessage { public static final String COPYRIGHT = "Copyright (C) 2003-2005 The FreeCol Team"; public static final String LICENSE = "http://www.gnu.org/licenses/gpl.html"; public static final String REVISION = "$Revision$"; private static final Logger logger = Logger.getLogger(GUIMessage.class.getName()); private final String message; private final Color color; private final Date creationTime; /** * The constructor to use. * @param message The actual message. * @param color The color in which to display this message. */ public GUIMessage(String message, Color color) { this.message = message; this.color = color; this.creationTime = new Date(); } /** * Returns the actual message data. * @return The actual message data. */ public String getMessage() { return message; } /** * Returns the message's Color. * @return The message's Color. */ public Color getColor() { return color; } /** * Returns the time at which this message was created. * @return The time at which this message was created. */ public Date getCreationTime() { return creationTime; } }
true
3e15e2e273167fa81008a71024dfeaeab782b9fb
Java
wojeong/MusicGame
/app/src/main/java/com/example/musicgame/Correct.java
UTF-8
1,331
2.375
2
[]
no_license
package com.example.musicgame; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.View; import android.widget.Button; import android.widget.ImageView; import androidx.annotation.Nullable; public class Correct extends Activity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { // change image Intent image = getIntent(); String imageID = image.getExtras().getString("title");//name of the song int id = getResources().getIdentifier(imageID, "drawable", getPackageName());//matches the song name with actual song file. Drawable drawable = getResources().getDrawable(id);//making R.Drawable.songName // pop up super.onCreate(savedInstanceState); setContentView(R.layout.correct); //image ImageView myImageView = (ImageView) findViewById(R.id.imageView); myImageView.setImageDrawable(drawable); // end Button endbutton = (Button) findViewById(R.id.btnContinue); endbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
true
e7c7b11fb0e7c061cc942b86e1b48c1431c2e586
Java
zhengby8491/printmanager
/src/main/java/com/huayin/printmanager/job/SystemJobService.java
UTF-8
1,769
2.34375
2
[]
no_license
/** * <pre> * Author: think * Create: 2018年1月11日 上午11:17:46 * Copyright: Copyright (c) 2017 * Company: Shenzhen HuaYin * @since: 1.0 * <pre> */ package com.huayin.printmanager.job; import com.huayin.common.exception.ServiceResult; import com.huayin.printmanager.persist.entity.sys.SystemJob; /** * <pre> * 框架 - 系统任务 * </pre> * @author think * @since 1.0, 2018年1月11日 */ public interface SystemJobService { /** * <pre> * 检查任务 如果不存在,则创建 * </pre> * @param className * @param taskName * @param taskDescription * @return */ public SystemJob checkJob(String className, String taskName, String taskDescription); public void execOverSystemJob(String className, boolean isSuccess, int runCount); public ServiceResult<SystemJob> execSystemJob(String className, long timeout); /** * <pre> * 通过类名查找对应的JOB * </pre> * @param className 类名 * @return */ SystemJob findByClassName(String className); /** * <pre> * 根据系统作业ID查询系统作业 * </pre> * @param id 系统作业ID * @return */ ServiceResult<SystemJob> get(String className); /** * <pre> * 根据系统作业ID查询系统作业 * </pre> * @param id 系统作业ID * @return */ SystemJob lock(String className); /** * <pre> * 还原所有系统任务状态 * </pre> * @return 被还原状态的任务数 */ public int resetAllSystemJob(); /** * <pre> * 新增系统作业 * </pre> * @param sysJob */ ServiceResult<SystemJob> save(SystemJob sysJob); /** * <pre> * 修改系统作业 * </pre> * @param sysJob 系统作业 * @return */ ServiceResult<SystemJob> update(SystemJob sysJob); }
true
6171056d74cae1addc6558ab28433ea65dd1434d
Java
wjdwn1988/kaist.tap.kaf
/kaist.tap.kaf/src/kaist/tap/kaf/views/ShapeCanvas.java
UTF-8
9,845
2.109375
2
[]
no_license
package kaist.tap.kaf.views; import java.util.Vector; import kaist.tap.kaf.component.Arrow; import kaist.tap.kaf.component.Component; import kaist.tap.kaf.component.Line; import kaist.tap.kaf.component.Parallelogram; import kaist.tap.kaf.component.Rectangle; import kaist.tap.kaf.component.Group; import kaist.tap.kaf.component.Component.Selection; import kaist.tap.kaf.manager.*; import kaist.tap.kaf.manager.View.viewType; import org.eclipse.jface.util.ListenerList; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.*; public class ShapeCanvas extends Canvas implements ISelectionProvider { protected ComponentRepository repo; protected ViewManager vm; ListenerList listeners = new ListenerList(); private Component selected = null; private Vector<Component> psel, copy; private Component tmpComp = null; private Point sp = null; public ShapeCanvas(Composite parent, int style) { super(parent, style); vm = new ViewManager(); vm.addView(new LogicalView()); vm.addRepo(new ComponentRepository()); vm.addView(new RunTimeView()); vm.addRepo(new ComponentRepository()); repo = vm.getRepo(viewType.LOGICAL_VIEW); psel = new Vector<Component>(); copy = new Vector<Component>(); this.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(final SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); if (selection.isEmpty() == false) { Object select = selection.getFirstElement(); if (select instanceof Component) { selected = (Component) select; } else if (select instanceof View) { View v = (View) select; repo = vm.getRepo(v.getViewType()); psel.clear(); copy.clear(); redraw(); } } } }); addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { if (repo.getNumberOfComponents() > 0) { repo.draw(e.gc); } if (tmpComp != null) { tmpComp.draw(e.gc); } e.gc.dispose(); } }); this.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.DEL) { // delete selected component if (psel.size() == 0) return; repo.remove(psel); psel.clear(); } else if ((e.stateMask & SWT.CTRL) != 0) { if (e.keyCode == 'c' || e.keyCode == 'C') { // copy component if (psel.size() == 0) return; if (psel.get(0).isSelected() == true) { for (int i = 0; i < psel.size(); ++i) { copy.add(psel.get(i).clone()); } } else { copy.clear(); } } else if (e.keyCode == 'x' || e.keyCode == 'X') { if (psel.size() == 0) return; if (psel.get(0).isSelected() == true) { for (int i = 0; i < psel.size(); ++i) { copy.add(psel.get(i).clone()); } } repo.remove(psel); psel.clear(); } else if (e.keyCode == 'v' || e.keyCode == 'V') { // paste component if (copy.size() == 0) return; for (int i = 0; i < copy.size(); ++i) { Component comp = copy.get(i); comp.move(10, 10); repo.register(comp); } copy.clear(); } else if (e.keyCode == 'G' || e.keyCode == 'g') { if (psel.size() <= 1) return; System.out.println("G is pressed"); Group group = new Group(); for (int i = 0; i < psel.size(); ++i) { Component c = psel.get(i); group.addComponent(c); c.unselect(); c.setGrouped(); } group.setDrawn(true); repo.register(group); psel.clear(); } else if (e.keyCode == 'U' || e.keyCode == 'u') { for (int i = 0; i < psel.size(); ++i) { Component c = psel.get(i); if (c instanceof Group) { ((Group) c).clear(); psel.remove(c); repo.remove(c); } } } else if (e.keyCode == '+' || e.keyCode == '=') { if (psel.size() != 1) return; Component c = psel.get(0); repo.raise(c); } else if (e.keyCode == '-' || e.keyCode == '_') { if (psel.size() != 1) return; Component c = psel.get(0); repo.lower(c); } } redraw(); } }); addMouseListener(new MouseAdapter() { public void mouseDown(MouseEvent e) { Component current = null; boolean shift = false; if ((e.stateMask & SWT.SHIFT) != 0) { shift = true; } // pick test for (int i = repo.getNumberOfComponents()-1; i >=0; --i) { current = repo.get(i); if (current.contains(e.x, e.y)) { setSelection(new StructuredSelection(current)); if (psel.size() > 0 && shift == false) { for (int j = 0; j < psel.size(); ++j) { Component comp = psel.get(j); if (comp != current) { comp.unselect(); } } psel.clear(); } current.select(); psel.add(current); break; } else current = null; } // if no one selected, but previous selection is existed if (current == null && psel.size() > 0) { for (int i = 0; i < psel.size(); ++i) { psel.get(i).unselect(); psel.clear(); } } sp = new Point(e.x, e.y); redraw(); } public void mouseUp(MouseEvent e) { int x, y, w, h; tmpComp = null; if (selected == null) { sp = null; return; } if (selected.getDrawn() == false) { if (selected instanceof Group) { selected = null; sp = null; return; } else if (selected instanceof Parallelogram) { x = sp.x < e.x ? sp.x : e.x; y = sp.y < e.y ? sp.y : e.y; w = Math.abs(e.x-sp.x); h = Math.abs(e.y-sp.y); w = (w < 5) ? 20 : w; h = (h < 5) ? 20 : h; Parallelogram src = (Parallelogram) selected; Parallelogram para = src.clone(); para.setControlPoint(w/4); para.setDrawn(true); repo.register(para); } else if (selected instanceof Rectangle) { x = sp.x < e.x ? sp.x : e.x; y = sp.y < e.y ? sp.y : e.y; w = Math.abs(e.x-sp.x); h = Math.abs(e.y-sp.y); w = (w < 5) ? 20 : w; h = (h < 5) ? 20 : h; Rectangle src = (Rectangle) selected; Rectangle rect = src.clone(); rect.setDrawn(true); repo.register(rect); } else if (selected instanceof Arrow) { Arrow src = (Arrow) selected; Arrow arrow = src.clone(); arrow.setDrawn(true); repo.register(arrow); } else if (selected instanceof Line) { Line src = (Line) selected; Line line = src.clone(); line.setDrawn(true); repo.register(line); } } else { if (selected.getSelection() == Selection.FALSE) selected.move(e.x-sp.x, e.y-sp.y); else selected.resize(e.x, e.y); } redraw(); sp = null; selected = null; } }); addMouseMoveListener(new MouseMoveListener() { public void mouseMove(MouseEvent e) { if (sp == null) return; if (selected != null) { if (selected.getDrawn()==true) { for (int i = 0; i < psel.size(); ++i) { Component sel = psel.get(i); if (sel.getSelection() == Selection.FALSE) sel.move(e.x-sp.x, e.y-sp.y); else sel.resize(e.x, e.y); } sp.x = e.x; sp.y = e.y; } else { int x, y, w, h; if (selected instanceof Rectangle) { Rectangle rect = (Rectangle) selected; x = sp.x < e.x ? sp.x : e.x; y = sp.y < e.y ? sp.y : e.y; w = Math.abs(e.x-sp.x); h = Math.abs(e.y-sp.y); rect.setPosition(new Point(x, y)); rect.setWidth(w); rect.setHeight(h); } else if (selected instanceof Line) { selected.setPosition(sp); selected.setEndPosition(new Point(e.x, e.y)); } tmpComp = selected; } redraw(); } } }); } public void deleteSelections() { while (psel.size() > 0) { // psel. } } public void addSelectionListener(SelectionListener listener) { this.addListener(SWT.Selection, new TypedListener(listener)); } public void removeSelectionListener(SelectionListener listener) { this.removeListener(SWT.Selection, listener); } @Override public void addSelectionChangedListener(ISelectionChangedListener listener) { listeners.add(listener); } public ISelection getSelection() { if (selected != null) { return new StructuredSelection(selected); } return new StructuredSelection(); } public void removeSelectionChangedListener(ISelectionChangedListener listener) { listeners.remove(listener); } public void setSelection(ISelection select) { Object[] list = listeners.getListeners(); for (int i = 0; i < listeners.size(); ++i) { ((ISelectionChangedListener) list[i]).selectionChanged(new SelectionChangedEvent(this, select)); } } }
true
8d02faaeea94824371c3b62072b54e621d45a84d
Java
octaviomunoz/sistema-requerimiento
/backend/src/main/java/com/sistema/requerimiento/repository/RequisitoRepository.java
UTF-8
304
1.570313
2
[]
no_license
package com.sistema.requerimiento.repository; import com.sistema.requerimiento.model.Requisito; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Component; @Component public interface RequisitoRepository extends JpaRepository<Requisito, Long> { }
true
c1431e08d2c0bd525367e4e82bbb727a3672f323
Java
cuixingzheng/my-study-modules
/gof/src/main/java/com/gof/code/visit/Computer.java
UTF-8
534
3.03125
3
[]
no_license
package com.gof.code.visit; /** * @author: cxz * @create: 2020/8/13 15:02 * @description: **/ public class Computer implements Part { private Part[] parts; @Override public void describe() { System.out.println("computer contain : {"); for (Part part : parts){ part.describe(); } System.out.println("}"); } public Computer(Part[] parts) { this.parts = parts; } @Override public void accept(Visitor visitor) { visitor.visit(this); } }
true
1636fe10fe6f06e1be4003615befc92d4fd640dc
Java
grodskvi/coding-tasks
/TaxCalculator/src/main/java/taxcalculator/domain/finance/Rate.java
UTF-8
1,195
3.21875
3
[]
no_license
package taxcalculator.domain.finance; import static taxcalculator.utils.ParametersValidator.NON_NEGATIVE_NUMBER; import static taxcalculator.utils.ParametersValidator.validateParameter; import java.math.BigDecimal; import java.util.Objects; public class Rate { private BigDecimal rate; public Rate(BigDecimal rate) { validateParameter(rate, NON_NEGATIVE_NUMBER, "Can not create Rate with negative rate"); this.rate = rate; } BigDecimal getRate() { return rate; } public Rate sum(Rate anotherRate) { BigDecimal totalRate = rate.add(anotherRate.rate); return new Rate(totalRate); } public static Rate aRateOf(String rate) { return new Rate(new BigDecimal(rate)); } @Override public int hashCode() { return Objects.hash(rate); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Rate other = (Rate) obj; if (rate == null) { if (other.rate != null) return false; } else if (rate.compareTo(other.rate) != 0) return false; return true; } @Override public String toString() { return "Rate [rate=" + rate + "]"; } }
true
e8fb96d5d794e894e73c326c03022634fcc61162
Java
software-engineering-amsterdam/many-ql
/JeffSebastian/playground/src/main/java/nl/uva/se/ql/ast/expression/literal/IntegerLiteral.java
UTF-8
373
2.34375
2
[]
no_license
package nl.uva.se.ql.ast.expression.literal; import nl.uva.se.ql.ast.expression.ExpressionVisitor; public class IntegerLiteral extends AbstractLiteral<Integer> { public IntegerLiteral(int lineNumber, int offset, Integer value) { super(lineNumber, offset, value); } @Override public <T> T accept(ExpressionVisitor<T> visitor) { return visitor.visit(this); } }
true
c0289023a64917e05d3007918b2d21310537d2c2
Java
ratulalahy/SurveyWebProgramming
/src/java/com/survey/models/BeanSurveyModule.java
UTF-8
2,912
2.125
2
[]
no_license
/* * 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 com.survey.models; import java.beans.*; import java.io.Serializable; import java.sql.Timestamp; import java.util.List; /** * * @author Ratul */ public class BeanSurveyModule implements Serializable { private PropertyChangeSupport propertySupport; private long surveyID; private String surveyTitle; private String surveyDesc; private String logoLocation; private Timestamp lastModifiedTime; private Timestamp publishedTime; private java.sql.Timestamp closingTime; private long userID; private List<BeanQuestionModule> questionModules; public BeanSurveyModule() { propertySupport = new PropertyChangeSupport(this); } public void addPropertyChangeListener(PropertyChangeListener listener) { propertySupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { propertySupport.removePropertyChangeListener(listener); } public String getSurveyTitle() { return surveyTitle; } public void setSurveyTitle(String surveyTitle) { this.surveyTitle = surveyTitle; } public String getSurveyDesc() { return surveyDesc; } public void setSurveyDesc(String surveyDesc) { this.surveyDesc = surveyDesc; } public List<BeanQuestionModule> getQuestionModules() { return questionModules; } public void setQuestionModules(List<BeanQuestionModule> questionModules) { this.questionModules = questionModules; } public long getSurveyID() { return surveyID; } public void setSurveyID(long surveyID) { this.surveyID = surveyID; } public String getLogoLocation() { return logoLocation; } public void setLogoLocation(String logoLocation) { this.logoLocation = logoLocation; } public long getUserID() { return userID; } public void setUserID(long userID) { this.userID = userID; } public Timestamp getLastModifiedTime() { return lastModifiedTime; } public void setLastModifiedTime(Timestamp lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } public Timestamp getPublishedTime() { return publishedTime; } public void setPublishedTime(Timestamp publishedTime) { this.publishedTime = publishedTime; } public java.sql.Timestamp getClosingTime() { return closingTime; } public void setClosingTime(java.sql.Timestamp closingTime) { this.closingTime = closingTime; } }
true
182a26ee561d03d2a0b809bb67112afb11646608
Java
sebasanger/sprintel
/src/main/java/com/sanger/sprintel/services/PaymentMethodService.java
UTF-8
369
1.546875
2
[]
no_license
package com.sanger.sprintel.services; import com.sanger.sprintel.model.PaymentMethod; import com.sanger.sprintel.repository.PaymentMethodsRepository; import com.sanger.sprintel.services.base.BaseService; import org.springframework.stereotype.Service; @Service public class PaymentMethodService extends BaseService<PaymentMethod, Long, PaymentMethodsRepository> { }
true
f4afd7b4e518c985375c1acdb11251438a4ebc8b
Java
RicardoLaMadrid/prograiii
/HITO 2/proyect/src/Calculadora/Suma.java
UTF-8
85
1.851563
2
[ "MIT" ]
permissive
package Calculadora; public interface Suma { public int suma (int a , int b); }
true
fa0ccbbec608e79e40cabfa21f6fc700ed2909ef
Java
mykevinjung/alicesfavs
/AlicesFavsWebApp/src/main/java/com/alicesfavs/webapp/comparator/SaleDateComparator.java
UTF-8
596
2.6875
3
[]
no_license
package com.alicesfavs.webapp.comparator; import com.alicesfavs.webapp.uimodel.UiProduct; import java.util.Comparator; /** * Compare products by sale date in descending order, i.e. new sale first */ public class SaleDateComparator extends DecoratedComparator { public SaleDateComparator() { super(); } public SaleDateComparator(Comparator<UiProduct> baseComparator) { super(baseComparator); } @Override protected int compare0(UiProduct p1, UiProduct p2) { return p2.getSaleStartDate().compareTo(p1.getSaleStartDate()); } }
true
520b8c90645c19a1aa0b6391a60f9591be6c20a1
Java
stounio/Fun-Game
/src/com/stounio/fungame/gui/action/FunGameGuiExitAction.java
UTF-8
481
2.171875
2
[]
no_license
package com.stounio.fungame.gui.action; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import com.stounio.fungame.factory.GamePlayServiceFactory; import com.stounio.fungame.game.service.GamePlayService; public class FunGameGuiExitAction implements ActionListener { @Override public void actionPerformed(ActionEvent actionEvent) { GamePlayService gamePlayService = GamePlayServiceFactory.getFactory().getInstance(); gamePlayService.exit(); } }
true
f2cd0f40c456fb54e41cb1f1fcff392a9ce93596
Java
Hung051098/RnDforSunlife
/SpringAdapter/src/main/java/com/hung/springadapter/ehcacheentities/EhCacheEntities.java
UTF-8
307
1.5625
2
[]
no_license
package com.hung.springadapter.ehcacheentities; import com.ibm.json.java.JSONObject; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class EhCacheEntities { private Object tokenAuth; private Object tokenMfp; }
true
1c4d33a2403ee28dec197bf8d1c6dddc8dfabd7c
Java
Ronak14999/ELEC_20_Problem_Hackers
/Testing1/app/src/main/java/com/example/testing_1/MainActivity.java
UTF-8
3,842
1.984375
2
[]
no_license
package com.example.testing_1; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { RecyclerView mRecyclerView; List<RoomData> myRoomList; private DatabaseReference databaseReference; private ValueEventListener valueEventListener; MyAdapter myAdapter; ProgressDialog progressDialog; EditText etSearch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().hide(); mRecyclerView=(RecyclerView)findViewById(R.id.recyclerView); GridLayoutManager gridLayoutManager=new GridLayoutManager(MainActivity.this,1); mRecyclerView.setLayoutManager(gridLayoutManager); etSearch=(EditText)findViewById(R.id.etsearch) ; progressDialog=new ProgressDialog(this); progressDialog.setMessage("Loading"); myRoomList=new ArrayList<>(); myAdapter=new MyAdapter(MainActivity.this,myRoomList); mRecyclerView.setAdapter(myAdapter); databaseReference= FirebaseDatabase.getInstance().getReference("Room_Details"); progressDialog.show(); valueEventListener=databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { myRoomList.clear(); for(DataSnapshot itemSnapshot:dataSnapshot.getChildren()){ RoomData roomData=itemSnapshot.getValue(RoomData.class); roomData.setKey(itemSnapshot.getKey()); myRoomList.add(roomData); } myAdapter.notifyDataSetChanged(); progressDialog.dismiss(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { progressDialog.dismiss(); } }); etSearch.addTextChangedListener((new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { filter(s.toString()); } })); } private void filter(String text) { ArrayList<RoomData> filterList =new ArrayList<>(); for(RoomData item:myRoomList){ if(item.getArea().toLowerCase().contains(text.toLowerCase())){ filterList.add(item); } } myAdapter.filteredList(filterList); } public void uploadbtn(View view) { startActivity(new Intent(this,Upload_Details.class)); } public void advanceSearchbtn(View view) { startActivity(new Intent(this,SearchFilter.class)); } }
true
3576c629de182fafea40c2354be614c5ebc92ea8
Java
magolla/Prueba
/src/test/java/com/tdil/d2d/controller/NoteControllerTest.java
UTF-8
4,236
2.171875
2
[]
no_license
package com.tdil.d2d.controller; import com.tdil.d2d.controller.api.request.CreateNoteRequest; import com.tdil.d2d.controller.api.request.IdRequest; import com.tdil.d2d.controller.api.request.RegistrationRequestA; import com.tdil.d2d.persistence.NoteCategory; import io.restassured.RestAssured; import io.restassured.config.SSLConfig; import io.restassured.http.Header; import org.junit.Assert; import org.junit.Test; import org.springframework.http.MediaType; import java.util.Date; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; public class NoteControllerTest extends AbstractDTDTest { @Test public void test() { RegistrationRequestA registrationA = createRegistrationRequestA(suffix, mobilePhone, deviceId); given().config(RestAssured.config().sslConfig( new SSLConfig().allowAllHostnames().relaxedHTTPSValidation())).contentType("application/json") .body(toJson(registrationA)) .post(API_URL + "/api/user/registerA") .then().log().body().statusCode(201).body("status", equalTo(201))/*. and().time(lessThan(100L))*/; given().config(RestAssured.config().sslConfig( new SSLConfig().allowAllHostnames().relaxedHTTPSValidation())).contentType("application/json") .body("{\"mobilePhone\":\"" + mobilePhone + "\",\"deviceId\":\"" + deviceId + "\",\"smsCode\":\"" + smsCode + "\"}") .post(API_URL + "/api/user/validate") .then().log().body().statusCode(200); String jwttokenOfferent = given().config(RestAssured.config().sslConfig( new SSLConfig().allowAllHostnames().relaxedHTTPSValidation())).contentType("application/json").body("{\"username\":\"" + mobilePhone + "\",\"password\":\"" + deviceId + "\"}") .post(API_URL + "/api/auth") .then().log().body().statusCode(200).extract().path("token"); Assert.assertNotNull(jwttokenOfferent); CreateNoteRequest note = new CreateNoteRequest(); note.setTitle("title"); note.setSubtitle("subtitle"); note.setContent("This is article content"); note.setCategory(NoteCategory.CAT_1.toString()); note.setExpirationDate(new Date()); int id = given().config(RestAssured.config().sslConfig( new SSLConfig().allowAllHostnames().relaxedHTTPSValidation())) .contentType(MediaType.APPLICATION_JSON.toString()) .body(toJson(note)) .header(new Header("Authorization", jwttokenOfferent)) .body(toJson(note)) .post(API_URL + "/api/notes") .then().log().body().statusCode(200).body("status", equalTo(200)).extract().path("data.id"); int occupationId = given().config(RestAssured.config().sslConfig( new SSLConfig().allowAllHostnames().relaxedHTTPSValidation())) .contentType(MediaType.APPLICATION_JSON.toString()) .body(toJson(note)) .header(new Header("Authorization", jwttokenOfferent)) .body(toJson(note)) .post(API_URL + "/api/specialties/occupations") .then().log().body().statusCode(200).body("status", equalTo(200)).extract().path("data[0].id"); IdRequest request = new IdRequest(); request.setId(Long.valueOf(occupationId)); given().config(RestAssured.config().sslConfig( new SSLConfig().allowAllHostnames().relaxedHTTPSValidation())) .contentType(MediaType.APPLICATION_JSON.toString()) .body(toJson(note)) .header(new Header("Authorization", jwttokenOfferent)) .body(toJson(request)) .post(API_URL + "/api/notes/" + id + "/occupations") .then().log().body().statusCode(200).body("status", equalTo(200)); given().config(RestAssured.config().sslConfig( new SSLConfig().allowAllHostnames().relaxedHTTPSValidation())) .contentType(MediaType.APPLICATION_JSON.toString()) .body(toJson(note)) .header(new Header("Authorization", jwttokenOfferent)) .body(toJson(request)) .post(API_URL + "/api/notes/" + id + "/specialities") .then().log().body().statusCode(200).body("status", equalTo(200)); given().config(RestAssured.config().sslConfig( new SSLConfig().allowAllHostnames().relaxedHTTPSValidation())) .contentType(MediaType.APPLICATION_JSON.toString()) .header(new Header("Authorization", jwttokenOfferent)) .get(API_URL + "/api/notes?category=CAT_1") .then().log().body().statusCode(200).body("status", equalTo(200)); } }
true
ac98ff170f15e3d823a3caa78bbba448f2a419f4
Java
smikhalev/sql-server-utils
/data-pump/src/test/java/com/smikhalev/sqlserverutils/test/BaseImporterTest.java
UTF-8
4,427
2.25
2
[]
no_license
package com.smikhalev.sqlserverutils.test; import com.smikhalev.sqlserverutils.core.executor.DataRow; import com.smikhalev.sqlserverutils.core.executor.DataTable; import com.smikhalev.sqlserverutils.core.executor.StatementExecutor; import com.smikhalev.sqlserverutils.exportdata.exporter.SequentialExporter; import com.smikhalev.sqlserverutils.generator.DataGenerator; import com.smikhalev.sqlserverutils.importdata.Importer; import com.smikhalev.sqlserverutils.schema.Database; import com.smikhalev.sqlserverutils.schema.DatabaseContext; import com.smikhalev.sqlserverutils.schema.dbobjects.DbObject; import com.smikhalev.sqlserverutils.schema.dbobjects.ForeignKey; import com.smikhalev.sqlserverutils.schema.dbobjects.Table; import com.smikhalev.sqlserverutils.schema.dbobjects.Trigger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.Assert; import java.util.ArrayList; import java.util.List; @ContextConfiguration(locations = {"classpath:test-spring-config.xml"}) public class BaseImporterTest extends AbstractTestNGSpringContextTests { @Autowired private StatementExecutor executor; @Autowired private SequentialExporter exporter; @Autowired private DataGenerator generator; @Autowired private TableComparator comparator; protected void importDatabase(Database database, Importer importer, int size) throws Exception { try (DatabaseContext dbContext = new DatabaseContext(database, executor)) { dbContext.create(); generator.generateData(database, size); TableWriterProviderStub tableWriterProvider = new TableWriterProviderStub(); exporter.exportData(database, tableWriterProvider); renameDatabaseTables(database); dbContext.create(); addRenamedTablesToDatabase(database); TableReaderProviderStub readerProvider = new TableReaderProviderStub(tableWriterProvider.getWriters()); importer.importData(database, readerProvider); compareImportTables(database); } } private void renameDatabaseTables(Database database) { for(Table table : database.getTables()) { String newTableName = buildRenamedTableName(table); for(ForeignKey fk : table.getForeignKeys()) { executor.executeScript(fk.generateDropScript()); } for(Trigger trigger : table.getTriggers()) { executor.executeScript(trigger.generateDropScript()); } String renameScript = String.format("sp_rename %s, %s", table.getName(), newTableName); executor.executeScript(renameScript); } } private void addRenamedTablesToDatabase(Database database) { List<String> newTables = new ArrayList<>(); for(Table table : database.getTables()) { String newTableName = buildRenamedTableName(table); newTables.add(newTableName); } for(String newTableName : newTables) { Table table = new Table(newTableName, null); database.getTables().add(table); } } private String buildRenamedTableName(Table table) { return "renamed_" + table.getName(); } private void compareImportTables(Database database) { for(Table table : database.getTables()) { if (!table.getName().startsWith("renamed")) { String fullName = DbObject.buildFullName(table.getSchema(), buildRenamedTableName(table)); Table targetTable = database.getTableByFullName(fullName); Assert.assertNotNull(targetTable); DataTable compareResult = comparator.compare(table, targetTable); if (!compareResult.getRows().isEmpty()) { printDataTable(compareResult); } Assert.assertTrue(compareResult.getRows().isEmpty()); } } } private void printDataTable(DataTable compareResult) { for (DataRow row : compareResult.getRows()) { for(Object value : row.values()) { System.out.print(value); System.out.print(","); } System.out.println(); } } }
true
60d53512a75af5e77f641238af2dc73436a6d1ee
Java
yxtumingzhi/cloud-demo
/demoa/src/main/java/com/example/demoa/mq/ReceiverServiceImpl2.java
UTF-8
563
2.015625
2
[]
no_license
package com.example.demoa.mq; import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.annotation.StreamListener; import org.springframework.stereotype.Service; /** * @Author tumingzhi * @Date 2020/9/18 16:05 **/ @Service @Slf4j @EnableBinding(IReceiverService.class) public class ReceiverServiceImpl2 { @StreamListener(IReceiverService.DPB_EXCHANGE_INPUT_2) public void receiverAction(String msg){ log.info("2号接收到了一条消息:" + msg); } }
true
4522d4354986aee37d22b32e5e4f883c61d139d7
Java
liu67224657/besl-platform
/webcommon/src/main/java/com/enjoyf/platform/webapps/common/html/ValidateImageGenerator.java
UTF-8
8,821
2.578125
3
[]
no_license
package com.enjoyf.platform.webapps.common.html; import com.enjoyf.platform.util.log.GAlerter; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class ValidateImageGenerator { private static ValidateImageGenerator instance = null; private ValidateImageGenerator() { } public static ValidateImageGenerator get() { if (instance == null) { synchronized (ValidateImageGenerator.class) { if (instance == null) { instance = new ValidateImageGenerator(); } } } return instance; } public static final String RANDOMCODEKEY = "JOYMEROMDANKEY";// 放到session中的key private Random random = new Random(); private String[] randStr = new String[]{"刀山火海", "百发百中", "日久天长", "里应外合", "虎头蛇尾", "空前绝后", "顶天立地", "一心一意", "三心二意", "闭月羞花", "沉鱼落雁", "国色天香", "如花似玉", "七上八下", "九死一生", "三长两短", "百发百中", "人山人海", "无中生有", "小题大做", "日久天长", "自由自在", "斤斤计较", "井井有条", "自言自语", "无边无际 ", "风雨同舟", "同甘共苦", "五颜六色", "三三两两", "无穷无尽", "车水马龙", "守株待兔", "画蛇添足", "亡羊补牢", "形形色色", "对牛弹琴", "画龙点睛", "千山万水"}; private char[] randString = new char[]{'a', 'b', 'c', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; private int width = 100;// 图片宽 private int height = 26;// 图片高 private int lineSize = 30;// 干扰线数量 /* * 获得字体 */ // private Font getFont() { // return new Font("Fixedsys", Font.CENTER_BASELINE, 18); // } /* * 获得颜色 */ private Color getRandColor(int fc, int bc) { if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc - 16); int g = fc + random.nextInt(bc - fc - 14); int b = fc + random.nextInt(bc - fc - 18); return new Color(r, g, b); } /** * 生成随机图片 */ public void getRandcode(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics();// 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作 g.fillRect(0, 0, width, height); g.setFont(new Font("黑体", Font.ROMAN_BASELINE, 18)); g.setColor(getRandColor(15, 100)); // 绘制干扰线 for (int i = 0; i <= lineSize; i++) { drowLine(g); } // 绘制随机字符 String[] ramdonString = this.getRandomString(); Graphics2D g2d = (Graphics2D) g; String displayString = ramdonString[1]; // 正数还是负数 int a = random.nextInt(2); // 偏的角度 int b = random.nextInt(10); // 最后偏的角度 int c = a == 0 ? b : 360 - b; g2d.rotate(c * Math.PI / 180); g2d.setColor(Color.RED); g2d.drawString(displayString, 10, 20); session.setAttribute(RANDOMCODEKEY, ramdonString[0]); g.dispose(); try { ImageIO.write(image, "JPEG", response.getOutputStream()); } catch (Exception e) { } } /** * 生成数字图片 */ public void getSimplebercode(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics();// 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作 g.fillRect(0, 0, width, height); g.setFont(new Font("黑体", Font.ROMAN_BASELINE, 18)); g.setColor(Color.LIGHT_GRAY); // 绘制干扰线 for (int i = 0; i <= lineSize; i++) { drowLine(g); } // 绘制随机字符 String[] chars = this.getSimpleRandomString(4); Graphics2D g2d = (Graphics2D) g; // 正数还是负数 int a = random.nextInt(2); // 偏的角度 int b = random.nextInt(10); // 最后偏的角度 int i = 0; String s = ""; for (String charct : chars) { g2d.setColor(Color.RED); g2d.drawString(charct, 10 + i, 20); s += charct; i = i + 20; } session.setAttribute(RANDOMCODEKEY, s); g.dispose(); try { ImageIO.write(image, "JPEG", response.getOutputStream()); } catch (Exception e) { } } /* * 绘制字符串 */ // private String drowString(Graphics g, String randomString, int i) { // g.setFont(getFont()); // g.setColor(new Color(random.nextInt(101), random.nextInt(111), // random.nextInt(121))); // String rand = // String.valueOf(getRandomString(random.nextInt(randString.length()))); // randomString += rand; // g.translate(random.nextInt(3), random.nextInt(3)); // g.drawString(rand, 13 * i, 16); // return randomString; // } /* * 绘制干扰线 */ private void drowLine(Graphics g) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(13); int yl = random.nextInt(15); g.drawLine(x, y, x + xl, y + yl); } /* * 获取随机的字符 */ // public String getRandomString(int num) { // return String.valueOf(randString.charAt(num)); // } public String[] getRandomString() { String str = randStr[random.nextInt(randStr.length)]; int length = str.length(); int num = random.nextInt(length); String replaceStr = new String(new char[]{str.charAt(num)}); String remainStr = str.replaceFirst(String.valueOf(str.charAt(num)), "?"); return new String[]{replaceStr, remainStr}; } public String[] getSimpleRandomString(int length) { String[] str = new String[length]; for (int i = 0; i < length; i++) { str[i] = String.valueOf(randString[random.nextInt(randString.length)]); } return str; } public void getSimplebercode(FileOutputStream file) { // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics();// 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作 g.fillRect(0, 0, width, height); g.setFont(new Font("黑体", Font.ROMAN_BASELINE, 18)); g.setColor(Color.LIGHT_GRAY); // 绘制干扰线 for (int i = 0; i <= lineSize; i++) { drowLine(g); } // 绘制随机字符 String[] chars = this.getSimpleRandomString(4); Graphics2D g2d = (Graphics2D) g; // 正数还是负数 int a = random.nextInt(2); // 偏的角度 int b = random.nextInt(10); // 最后偏的角度 int i = 0; String s = ""; for (String charct : chars) { // int c = a == 0 ? b : 360 - b; // g2d.rotate(c * Math.PI / 180); g2d.setColor(Color.RED); g2d.drawString(charct, 10 + i, 20); s += charct; i = i + 20; } g.dispose(); try { ImageIO.write(image, "JPEG",file ); } catch (Exception e) { } } public static void main(String[] args) throws FileNotFoundException { ValidateImageGenerator.get().getSimplebercode(new FileOutputStream("e:/1.jpg")); } }
true
8c395b53981ed9a49dff3f059af9948ef303db31
Java
mrBELLAZIA/ENTPERendu
/ENTPE/app/src/main/java/com/example/entpe/activity/Parametres.java
UTF-8
7,396
2.171875
2
[]
no_license
package com.example.entpe.activity; import android.location.Criteria; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.example.entpe.R; import com.example.entpe.application.MyApplication; import com.example.entpe.dialog.ChoixSettings; import com.example.entpe.dialog.Updatable; import com.example.entpe.model.Settings; import com.example.entpe.storage.DataBaseManager; public class Parametres extends AppCompatActivity implements Updatable { Settings settings; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settings); settings = null; final Button choixSettings = findViewById(R.id.button); choixSettings.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { (new ChoixSettings(Parametres.this)).show(getSupportFragmentManager(), ""); } }); final Button modif = findViewById(R.id.button2); modif.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { DataBaseManager dbm = new DataBaseManager(getApplicationContext()); String nom = ((EditText)findViewById(R.id.nomSettings)).getText().toString(); int periode = 2; int precision = Criteria.ACCURACY_HIGH; int conso = Criteria.POWER_HIGH; if(((EditText)findViewById(R.id.periode)).getText().toString()!=""){ periode = Integer.parseInt(((EditText)findViewById(R.id.periode)).getText().toString()); } RadioGroup rb = findViewById(R.id.groupePrecision); RadioButton choixPrecision = rb.findViewById(rb.getCheckedRadioButtonId()); if(choixPrecision == null) { precision = Criteria.ACCURACY_HIGH; } else { String precisionTexte = choixPrecision.getText().toString(); switch(precisionTexte) { case "Faible": // code block precision = Criteria.ACCURACY_LOW; break; case "Moyenne": // code block precision = Criteria.ACCURACY_MEDIUM; break; case "Haute": // code block precision = Criteria.ACCURACY_HIGH; break; } } RadioGroup rc = findViewById(R.id.groupeConso); RadioButton choixConso = rc.findViewById(rc.getCheckedRadioButtonId()); if(choixConso == null) { conso = Criteria.POWER_HIGH; } else { String consoTexte = choixConso.getText().toString(); switch(consoTexte) { case "Faible": // code block conso = Criteria.POWER_LOW; break; case "Moyenne": // code block conso = Criteria.POWER_MEDIUM; break; case "Haute": // code block conso = Criteria.POWER_HIGH; break; } } if(settings == null){ dbm.insert(new Settings(-1,nom,conso,precision,periode)); Toast.makeText(getApplicationContext(),"Paramètres ajoutés à la liste", Toast.LENGTH_LONG).show(); } if(settings!=null){ settings.setPeriode(periode); settings.setPrecision(precision); settings.setNomSettings(nom); settings.setConsommation(conso); dbm.update(settings.getId(),settings); Toast.makeText(getApplicationContext(),"Paramètres modifiés", Toast.LENGTH_LONG).show(); } update(); } }); final Button confirmeSettings = findViewById(R.id.editConfirme); confirmeSettings.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if(settings==null){ Toast.makeText(getApplicationContext(),"Aucun paramètres selectionnés", Toast.LENGTH_LONG).show(); }else{ MyApplication.setSettings(settings); Toast.makeText(getApplicationContext(),"Paramètres mis à jour pour les prochaines tournées", Toast.LENGTH_LONG).show(); } } }); } @Override public void update() { if(settings == null){ ((Button)findViewById(R.id.button2)).setText("Ajouter"); ((EditText)findViewById(R.id.nomSettings)).setText(""); ((EditText)findViewById(R.id.periode)).setText(""); ((RadioButton)findViewById(R.id.setLow)).setChecked(false); ((RadioButton)findViewById(R.id.setMedium)).setChecked(false); ((RadioButton)findViewById(R.id.setHigh)).setChecked(false); ((RadioButton)findViewById(R.id.powLow)).setChecked(false); ((RadioButton)findViewById(R.id.powMedium)).setChecked(false); ((RadioButton)findViewById(R.id.powHigh)).setChecked(false); }else{ ((Button)findViewById(R.id.button2)).setText("Modifier"); ((EditText)findViewById(R.id.nomSettings)).setText(settings.getNomSettings()); ((EditText)findViewById(R.id.periode)).setText(Integer.toString(settings.getPeriode())); switch (settings.getPrecision()){ case 1: ((RadioButton)findViewById(R.id.setLow)).setChecked(true); break; case 2: ((RadioButton)findViewById(R.id.setMedium)).setChecked(true); break; case 3: ((RadioButton)findViewById(R.id.setHigh)).setChecked(true); break; } switch (settings.getConsommation()){ case 1: ((RadioButton)findViewById(R.id.powLow)).setChecked(true); break; case 2: ((RadioButton)findViewById(R.id.powMedium)).setChecked(true); break; case 3: ((RadioButton)findViewById(R.id.powHigh)).setChecked(true); break; } } } public Settings getSettings() { return settings; } public void setSettings(Settings settings) { this.settings = settings; } }
true
2b46080c7cc7f97499bcf478f1e9c82b37c23a8a
Java
guterresrafael/tracker
/src/main/java/org/traccar/repository/UserRepository.java
UTF-8
310
1.726563
2
[ "Apache-2.0" ]
permissive
package org.traccar.repository; import arch.repository.Repository; import org.traccar.entity.User; /** * * @author Rafael Guterres */ public class UserRepository extends BaseTraccarRepository<User, Long> implements Repository<User, Long> { private static final long serialVersionUID = 7882604236163190244L; }
true
8d5be6bc468ab40ed8e2d2db80d4eade0955749d
Java
JJFly-JOJO/jojo-rpc-framework
/rpc-framework-simple/src/main/java/github/jojo/registry/ServiceRegistry.java
UTF-8
490
2
2
[]
no_license
package github.jojo.registry; import github.jojo.extension.SPI; import java.net.InetSocketAddress; /** * @author zzj * @version 1.0 * @date 2021/1/31 21:24 * @description -----------服务注册---------- */ @SPI public interface ServiceRegistry { /** * register service * * @param rpcServiceName rpc service name * @param inetSocketAddress service address */ void registerService(String rpcServiceName, InetSocketAddress inetSocketAddress); }
true
ee21a54101eb01ab2567cac721766d53ca84d789
Java
BrinedFish/springboot-mybatisplus-security-jwt-restful
/src/main/java/com/github/missthee/config/socketio/model/AckModel.java
UTF-8
617
2.171875
2
[]
no_license
package com.github.missthee.config.socketio.model; import lombok.Data; @Data public class AckModel { boolean result; String msg; private AckModel(boolean result, String msg) { this.msg = msg; this.result = result; } public static AckModel success() { return new AckModel(true, ""); } public static AckModel success(String msg) { return new AckModel(true, msg); } public static AckModel failure() { return new AckModel(false, ""); } public static AckModel failure(String msg) { return new AckModel(false, msg); } }
true
adde793cf1d1c4645861ce6be1e5f488cf4476b2
Java
sajit/hacks
/src/main/java/hackerrank/algo/nondivisiablesubset/Solution.java
UTF-8
4,649
2.9375
3
[]
no_license
package hackerrank.algo.nondivisiablesubset; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.*; import java.util.function.Predicate; public class Solution { public static Set<Integer> maxSet(int k,Set<Integer> sSet) { List<Set<Integer>> outList = new ArrayList<>(); Integer oustedNum = breakSet(k, sSet); while(oustedNum != null){ boolean mergeable = false; for(int i=0;i<outList.size();i++){ if(canMerge(oustedNum,outList.get(i),k)) { outList.get(i).add(oustedNum); Collections.sort(outList, (o1, o2) -> o2.size()-o1.size()); mergeable = true; break; } } if(!mergeable){ outList.add(new HashSet<>(Arrays.asList(oustedNum))); } oustedNum = breakSet(k,sSet); } return (outList.isEmpty()||sSet.size()>outList.get(0).size())?sSet:outList.get(0); } private static boolean canMerge(Integer oustedNum, Set<Integer> integers,int k) { Iterator<Integer> setItr = integers.iterator(); while(setItr.hasNext()){ Integer x = setItr.next(); if((oustedNum+x)%k==0) return false; } return true; } public static Integer breakSet(int k,Set<Integer> set) { Set<Integer> remainders = new HashSet<>(); if(set.size()<2) return null; Iterator<Integer> setItr = set.iterator(); Integer duplicate = null; while(setItr.hasNext()){ Integer element = setItr.next(); int remainder = element%k; if(remainders.contains(k-remainder)) { duplicate = element; break; } remainders.add(element); } if(duplicate!=null){ set.remove(duplicate); } return duplicate; } // public static boolean isDivisible(int k,int[] elements) { // Set<Integer> remainders = new HashSet<>(); // for(int i=0;i<elements.length;i++){ // int remainder = elements[i]%k; // if(remainders.contains(k-remainder)){ // return true; // } // remainders.add(remainder); // } // return false; // } // // Complete the nonDivisibleSubset function below. // public static int dononDivisibleSubset(int k, int[] S, int maxSize) { // if(maxSize>S.length){ // return maxSize; // } // if(S.length<2) return 0; // if(!isDivisible(k,S)){ // return S.length; // } // else { // for(int i=0;i<S.length;i++){ // int[] subArray = getArrayWithout(S,i); // int size = dononDivisibleSubset(k,subArray,maxSize); // if(size>maxSize){ // maxSize = size; // } // // // } // return maxSize; // } // } // public static int[] getArrayWithout(int[] s, int elIdx) { // int[] subArray = new int[s.length-1]; // for(int i=0;i<subArray.length;i++){ // if(i>=elIdx){ // subArray[i]=s[i+1]; // } // else { // subArray[i] = s[i]; // } // // } // return subArray; // } public static int nonDivisibleSubset(int k, int[] S) { Integer[] sInt = Arrays.stream(S).boxed().toArray(Integer[]::new); Set<Integer> sSet = new HashSet<Integer>(Arrays.asList(sInt)); Set<Integer> maxSubSet = maxSet(k,sSet); return maxSubSet.size(); } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")))) { String[] nk = scanner.nextLine().split(" "); int n = Integer.parseInt(nk[0]); int k = Integer.parseInt(nk[1]); int[] S = new int[n]; String[] SItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < n; i++) { int SItem = Integer.parseInt(SItems[i]); S[i] = SItem; } int result = nonDivisibleSubset(k, S); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); bufferedWriter.close(); } scanner.close(); } }
true
e72445c86478d4a31f03845237f0a810c0abd0d7
Java
qingchengfit/QcWidgets
/widgets/src/main/java/cn/qingchengfit/utils/Hash.java
UTF-8
4,737
2.84375
3
[ "Apache-2.0" ]
permissive
package cn.qingchengfit.utils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * power by * <p> * d8888b. .d8b. d8888b. d88888b d8888b. * 88 `8D d8' `8b 88 `8D 88' 88 `8D * 88oodD' 88ooo88 88oodD' 88ooooo 88oobY' * 88~~~ 88~~~88 88~~~ 88~~~~~ 88`8b * 88 88 88 88 88. 88 `88. * 88 YP YP 88 Y88888P 88 YD * <p> * <p> * Created by Paper on 15/7/31 2015. */ public class Hash { private static final String NULL = ""; /** * cacultate string to hash string */ private static String strHash(HashType type, String origin) { try { MessageDigest md = MessageDigest.getInstance(type.getValue()); md.update(origin.getBytes("UTF-8")); BigInteger bi = new BigInteger(1, md.digest()); return bi.toString(16); } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { return NULL; } } /** * caculate file to hash string */ private static String fileHash(HashType type, String filePath) { File file = new File(filePath); if (file == null || !file.exists()) { return NULL; } String result = NULL; FileInputStream fis = null; try { fis = new FileInputStream(file); MappedByteBuffer mbf = fis.getChannel().map( FileChannel.MapMode.READ_ONLY, 0, file.length()); MessageDigest md = MessageDigest.getInstance(type.getValue()); md.update(mbf); BigInteger bi = new BigInteger(1, md.digest()); result = bi.toString(16); } catch (Exception e) { return NULL; } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { /* ignore */ } } } return result; } /** * hash type */ private enum HashType { MD5("MD5"), SHA1("SHA1"); String type; HashType(String type) { this.type = type; } public String getValue() { return type; } } /** * Caculate MD5 hash string. */ public static class MD5 { /** * Used to encrypt string to md5 hash. * * @param origin the string to be encrpted * @return hash string */ public static String str(String origin) { return strHash(HashType.MD5, origin); } /** * Caculate md5 hash of specifed file. This may spend some time, * use new Thread if necessary. * * @param filePath the path of file * @return md5 hash string */ public static String file(String filePath) { return fileHash(HashType.MD5, filePath); } public final static String getMessageDigest(byte[] buffer) { char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; try { MessageDigest mdTemp = MessageDigest.getInstance("MD5"); mdTemp.update(buffer); byte[] md = mdTemp.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { return null; } } } /** * Caculate SHA1 hash string. */ public static class SHA1 { /** * Used to encrypt string to sha1 hash. * * @param origin the string to be encrpted * @return sha1 hash string */ public static String str(String origin) { return strHash(HashType.SHA1, origin); } /** * Caculate sha1 hash of specifed file. This may spend some time, * use new Thread if necessary. * * @param filePath the path of file * @return sha1 hash string */ public static String file(String filePath) { return fileHash(HashType.SHA1, filePath); } } }
true
674a52d97cbe72ab199a8d55095a93ea564b3016
Java
lletter12/javaworkspace
/p200917/src/p200917/p9.java
UTF-8
374
3.125
3
[]
no_license
package p200917; public class p9 { public static void main(String[] args) { // TODO Auto-generated method stub int a = 20; boolean r = a < 20; r = !true; // !는 not System.out.println(r); if(a <= 20) { System.out.println("a는 20보다 큽니다."); }else { System.out.println("a는 20보다 작거나 같습니다."); } } }
true
e4fe2779aee8c2b546423123871dbbe5bbc62e95
Java
Fonzeca/QueMepongo
/src/main/java/com/quemepongo/springapp/business/repositories/MiUsuarioRepository.java
UTF-8
265
1.617188
2
[]
no_license
package com.quemepongo.springapp.business.repositories; import org.springframework.data.repository.CrudRepository; import com.quemepongo.springapp.business.entities.MiUsuario; public interface MiUsuarioRepository extends CrudRepository<MiUsuario, Integer> { }
true
99b93f3702e0f5228ed5da5f90ed07294fcdb4ec
Java
oguzcansenel/vektorel
/VektorelJava23/src/com/vektorel/kalıtım2/Islem.java
WINDOWS-1250
256
1.84375
2
[]
no_license
package com.vektorel.kaltm2; public class Islem { public static void main(String[] args) { Otobus otobus = new Otobus(); Minibus minibus = new Minibus(); minibus.yolcuAldi("5 yolcu bindi"); otobus.duragaGeldi("30987"); } }
true
f8b39b8c19f6754b9be5e022f5d11546ed176e98
Java
kh-c4u/Semi
/src/com/kh/semi/member/service/MemberService.java
UTF-8
1,594
2.140625
2
[]
no_license
package com.kh.semi.member.service; import static com.kh.semi.common.JDBCTemplate.close; import static com.kh.semi.common.JDBCTemplate.commit; import static com.kh.semi.common.JDBCTemplate.getConnection; import static com.kh.semi.common.JDBCTemplate.rollback; import java.sql.Connection; import com.kh.semi.member.dao.MemberDao; import com.kh.semi.member.vo.Member; public class MemberService { private Connection conn; private MemberDao mDao = new MemberDao(); public int MemberSignUp(Member m){ conn = getConnection(); int result = 0; result = mDao.MemberSignUp(conn,m); if(result>0) { commit(conn); }else { rollback(conn); } close(conn); return result; } public int chkId(String id) { int result = 0; conn = getConnection(); result = mDao.chkId(conn,id); close(conn); return result; } public Member memberLogin(Member m) { Member result = null; conn = getConnection(); result = mDao.memberLogin(conn,m); close(conn); return result; } public int deleteMember(String userId) { conn = getConnection(); int result = mDao.deleteMember(conn,userId); if(result > 0) commit(conn); else rollback(conn); close(conn); return result; } public String findId(String name, String email) { String id = null; conn = getConnection(); id= mDao.findId(conn,name,email); close(conn); return id; } public String findPwd(String id, String email) { String pwd = null; conn = getConnection(); pwd=mDao.findPwd(conn,id,email); close(conn); return pwd; } }
true
13d0ac0e982bae8a1bf54ebce50f4634fefd7c76
Java
heroyuy/systar
/history/SoyoMaker2/src/com/soyostar/listener/DataChangedEvent.java
UTF-8
648
1.929688
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.soyostar.listener; //import com.soyostar.data.Data; import com.soyostar.data.DataManager; import com.soyostar.data.dao.ModelStore; import com.soyostar.data.model.Skill; import java.util.EventObject; /** * * @author Administrator */ public class DataChangedEvent extends EventObject { /** * * @param layer */ public DataChangedEvent(DataManager layer) { super(layer); } /** * * @return */ public DataManager getData() { return (DataManager) getSource(); } }
true
a1c0515ede04b867e3131d7536a05b29b3309a6a
Java
jc01rho/RealmMemoWithAAC
/app/src/main/java/com/massivcode/realmwithandroidarchitecturecomponents/lifecycle/LifecycleListener.java
UTF-8
1,407
2.34375
2
[]
no_license
package com.massivcode.realmwithandroidarchitecturecomponents.lifecycle; import android.arch.lifecycle.Lifecycle.Event; import android.arch.lifecycle.LifecycleObserver; import android.arch.lifecycle.OnLifecycleEvent; import android.content.Context; import android.widget.Toast; /** * Created by massivcode@gmail.com on 2017. 11. 23. 14:15 */ public class LifecycleListener implements LifecycleObserver { private Context mContext; public LifecycleListener(Context mContext) { this.mContext = mContext; } @OnLifecycleEvent(Event.ON_CREATE) void onCreate() { Toast.makeText(mContext, "LifecycleListener.onCreate()", Toast.LENGTH_SHORT).show(); } @OnLifecycleEvent(Event.ON_RESUME) void onResume() { Toast.makeText(mContext, "LifecycleListener.onResume()", Toast.LENGTH_SHORT).show(); } @OnLifecycleEvent(Event.ON_STOP) void onPause() { Toast.makeText(mContext, "LifecycleListener.onPause()", Toast.LENGTH_SHORT).show(); } @OnLifecycleEvent(Event.ON_START) void onStart() { Toast.makeText(mContext, "LifecycleListener.onStart()", Toast.LENGTH_SHORT).show(); } @OnLifecycleEvent(Event.ON_STOP) void onStop() { Toast.makeText(mContext, "LifecycleListener.onStop()", Toast.LENGTH_SHORT).show(); } @OnLifecycleEvent(Event.ON_DESTROY) void onDestroy() { Toast.makeText(mContext, "LifecycleListener.onDestory()", Toast.LENGTH_SHORT).show(); } }
true
6051e0d7c6cd44b02bbb74db15d4dd1c713263ea
Java
YousefSadaqa/htu-java-upskilling-0202
/generics-sample/src/main/java/jo/edu/htu/util/Packager.java
UTF-8
234
2.71875
3
[]
no_license
package jo.edu.htu.util; public class Packager { public <I> void fill(I item, Box<? super I> box) { if (!box.isEmpty()) throw new IllegalStateException("The box is not empty"); box.put(item); } }
true
d36818ffc5a86a40140a8ed60749e9e01763389d
Java
josefloso/FunsoftHMIS
/biz/systempartners/claims/FolderTreeNode.java
UTF-8
4,025
2.1875
2
[]
no_license
/* * @(#)FolderTreeNode.java 1.8 01/05/23 * * Copyright 1997-2000 Sun Microsystems, Inc. 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. * * - Redistribution 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 Sun Microsystems, Inc. or the names of contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES * SUFFERED BY LICENSEE AS A RESULT OF OR RELATING TO USE, MODIFICATION * OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL * SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that Software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */ package biz.systempartners.claims; import javax.swing.tree.DefaultMutableTreeNode; import javax.mail.Store; import javax.mail.Folder; import javax.mail.MessagingException; /** * Node which represents a Folder in the javax.mail apis. * * @version 1.8, 01/05/23 * @author Christopher Cotton */ public class FolderTreeNode extends DefaultMutableTreeNode { protected Folder folder = null; protected boolean hasLoaded = false; /** * creates a tree node that points to the particular Store. * * @param what the store for this node */ public FolderTreeNode(Folder what) { super(what); folder = what; } /** * a Folder is a leaf if it cannot contain sub folders */ public boolean isLeaf() { try { if ((folder.getType() & Folder.HOLDS_FOLDERS) == 0) return true; } catch (MessagingException me) { } // otherwise it does hold folders, and therefore not // a leaf return false; } /** * returns the folder for this node */ public Folder getFolder() { return folder; } /** * return the number of children for this folder node. The first * time this method is called we load up all of the folders * under the store's defaultFolder */ public int getChildCount() { if (!hasLoaded) { loadChildren(); } return super.getChildCount(); } protected void loadChildren() { // if it is a leaf, just say we have loaded them if (isLeaf()) { hasLoaded = true; return; } try { // Folder[] sub = folder.listSubscribed(); Folder[] sub = folder.list(); // add a FolderTreeNode for each Folder int num = sub.length; for(int i = 0; i < num; i++) { FolderTreeNode node = new FolderTreeNode(sub[i]); // we used insert here, since add() would make // another recursive call to getChildCount(); insert(node, i); } } catch (MessagingException me) { me.printStackTrace(); } } /** * override toString() since we only want to display a folder's * name, and not the full path of the folder */ public String toString() { return folder.getName(); } }
true
922cf4021d6bebb8007deafda84e31e2cfc1890d
Java
balaganivenkatasubbaiah/MyApplication
/app/src/main/java/com/lyrebirdstudio/svg/SvgFaceMiddle.java
UTF-8
4,822
2.265625
2
[]
no_license
package com.lyrebirdstudio.svg; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.Path; import com.lyrebirdstudio.lyrebirdlibrary.BlurBuilderNormal; public class SvgFaceMiddle extends Svg { private static final Matrix f1525m = new Matrix(); private static float od; private static final Paint f1526p = new Paint(); private static final Paint ps = new Paint(); private static final Path f1527t = new Path(); public void draw(Canvas c, int w, int h) { draw(c, (float) w, (float) h, 0.0f, 0.0f, false); } public void draw(Canvas c, float w, float h, float dx, float dy, boolean clearMode) { od = w / 415.0f < h / 512.0f ? w / 415.0f : h / 512.0f; m1546r(new Integer[0]); c.save(); c.translate(((w - (od * 415.0f)) / 2.0f) + dx, ((h - (od * 512.0f)) / 2.0f) + dy); f1525m.reset(); f1525m.setScale(od, od); c.save(); if (clearMode) { f1526p.setXfermode(this.xferModeClear); ps.setXfermode(this.xferModeClear); } ps.setColor(Color.argb(0, 0, 0, 0)); ps.setStrokeCap(Cap.BUTT); ps.setStrokeJoin(Join.MITER); ps.setStrokeMiter(4.0f * od); c.translate(0.2f * od, 0.0f); c.scale(1.0f, 1.0f); c.save(); c.save(); f1527t.reset(); f1527t.moveTo(7.73f, 512.72f); f1527t.cubicTo(7.73f, 512.72f, 52.28f, 505.55f, 59.96f, 453.06f); f1527t.cubicTo(60.47f, 431.56f, 55.35f, 407.75f, 69.44f, 385.98f); f1527t.cubicTo(111.17f, 383.42f, 107.07f, 355.0f, 99.65f, 344.51f); f1527t.cubicTo(88.89f, 328.38f, 84.54f, 325.05f, 84.54f, 325.05f); f1527t.cubicTo(84.54f, 325.05f, 136.26f, 339.9f, 129.35f, 277.17f); f1527t.cubicTo(118.85f, 248.49f, 159.81f, 246.7f, 177.23f, 247.21f); f1527t.cubicTo(227.15f, 243.12f, 213.33f, 191.4f, 212.56f, 188.07f); f1527t.cubicTo(217.17f, 177.06f, 172.36f, 75.93f, 164.94f, 57.24f); f1527t.cubicTo(157.0f, 43.41f, 159.3f, 5.52f, 167.24f, BlurBuilderNormal.BITMAP_SCALE); f1527t.cubicTo(175.18f, BlurBuilderNormal.BITMAP_SCALE, 415.59f, BlurBuilderNormal.BITMAP_SCALE, 415.59f, BlurBuilderNormal.BITMAP_SCALE); f1527t.cubicTo(415.59f, BlurBuilderNormal.BITMAP_SCALE, 394.86f, 7.4f, 378.98f, 111.52f); f1527t.cubicTo(384.61f, 136.44f, 386.41f, 130.72f, 383.08f, 150.43f); f1527t.cubicTo(382.82f, 171.94f, 357.9f, 192.87f, 349.79f, 201.13f); f1527t.cubicTo(340.58f, 210.51f, 281.94f, 250.54f, 273.5f, 263.86f); f1527t.cubicTo(261.46f, 285.87f, 268.12f, 303.8f, 292.19f, 324.02f); f1527t.cubicTo(299.35f, 330.42f, 305.5f, 335.03f, 305.5f, 335.03f); f1527t.cubicTo(305.5f, 335.03f, 311.64f, 346.04f, 304.22f, 357.56f); f1527t.cubicTo(296.79f, 369.09f, 289.37f, 378.05f, 287.83f, 385.73f); f1527t.cubicTo(289.88f, 392.64f, 306.52f, 403.91f, 303.96f, 410.05f); f1527t.cubicTo(279.13f, 426.18f, 278.87f, 440.52f, 288.86f, 456.39f); f1527t.cubicTo(302.68f, 477.13f, 294.75f, 504.53f, 284.25f, 512.72f); f1527t.cubicTo(268.25f, 512.72f, 7.73f, 512.72f, 7.73f, 512.72f); f1527t.transform(f1525m); c.drawPath(f1527t, f1526p); c.drawPath(f1527t, ps); c.restore(); m1546r(Integer.valueOf(3), Integer.valueOf(2), Integer.valueOf(0), Integer.valueOf(1)); c.restore(); m1546r(Integer.valueOf(3), Integer.valueOf(2), Integer.valueOf(0), Integer.valueOf(1)); c.save(); c.restore(); m1546r(Integer.valueOf(3), Integer.valueOf(2), Integer.valueOf(0), Integer.valueOf(1)); c.restore(); m1546r(new Integer[0]); c.restore(); } private static void m1546r(Integer... o) { f1526p.reset(); ps.reset(); if (cf != null) { f1526p.setColorFilter(cf); ps.setColorFilter(cf); } f1526p.setAntiAlias(true); ps.setAntiAlias(true); f1526p.setStyle(Style.FILL); ps.setStyle(Style.STROKE); for (Integer i : o) { switch (i.intValue()) { case 0: ps.setStrokeJoin(Join.MITER); break; case 1: ps.setStrokeMiter(4.0f * od); break; case 2: ps.setStrokeCap(Cap.BUTT); break; case 3: ps.setColor(Color.argb(0, 0, 0, 0)); break; default: break; } } } }
true
f201c725cffa9bf5e7a92b9e69740330cf99c3e5
Java
anikurhade/employeee-Management
/src/front_end_developer.java
UTF-8
1,147
2.671875
3
[]
no_license
class FrontEnd_developer extends employee{ private String proj; private String lang_special; public FrontEnd_developer(int empId, String empName, long empPhone, address a1, String userName, String password, String proj, String lang_special) { super(empId, empName, empPhone, a1); this.proj = proj; this.lang_special = lang_special; } public String getProj() { return proj; } public String getLang_special() { return lang_special; } public String toString(){ System.out.println("\n\t\t\t\t\t--------------------Front End Developer"+getEmpName()+"Information ----------------------"); System.out.println("\n\n\t\t\t\t\t\t Hello !!!!! "+getEmpName()+" Your Detail Are -> "); return "\n\t\t\t\t\t\t Id :- \t"+getEmpId()+"\n\t\t\t\t\t\t Name :-\t "+getEmpName()+"\n\t\t\t\t\t\t Contact :-\t"+getEmpPhone()+"\n\t\t\t\t\t\t Specialitation Language :- \t"+getLang_special()+"\n\t\t\t\t\t\t Project Done :- \t"+getProj()+"\n\t\t\t\t\t\t Address :- \t"+getA1()+"\n\t\t\t\t\t\t UserId :-\t"+getUserName()+"\n\t\t\t\t\t\t PassWord :- \t******"; } }
true
a94fc2097ce9108940b8c44fa09a1c8384a9bc29
Java
asifazamali/programming_practice
/src/com/practice/programming/CheckPythagoreanTriplet.java
UTF-8
1,708
3.609375
4
[]
no_license
package com.practice.programming; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class CheckPythagoreanTriplet { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(reader.readLine()); while(T-- > 0) { int n = Integer.parseInt(reader.readLine()); ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(reader.readLine().split(" "))); ArrayList<Integer> numbers = new ArrayList<>(); arrayList.forEach(x -> numbers.add(Integer.parseInt(x))); System.out.println(checkPythagoreanTriplet(numbers)); } } private static boolean checkPythagoreanTriplet(ArrayList<Integer> arrayList) { ArrayList<Integer> arrayListSquared = new ArrayList<>(); arrayList.forEach( x-> arrayListSquared.add(x*x)); Collections.sort(arrayListSquared); for(int i = arrayListSquared.size() -1 ; i >= 1; i--) { if(checkSumPresent(arrayListSquared, 0, i-1, arrayListSquared.get(i))) return true; } return false; } private static boolean checkSumPresent(ArrayList<Integer> arrayListSquared, int i, int n, int summ) { int rangeSum = 0; while(i < n) { rangeSum = arrayListSquared.get(i) + arrayListSquared.get(n); if (rangeSum == summ) return true; if (rangeSum < summ) i++; else n--; } return true; } }
true
b42b27f4b0dbf331d8580454f87787572433ff29
Java
Ezzideen/UpSklling-Java-Ezzo
/Hotel_HTU_Project/src/main/java/entity/EHotel.java
UTF-8
2,011
2.234375
2
[]
no_license
package entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "hot_hotel") public class EHotel { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "name") private String name; @Column(name = "description") private String description; @ManyToOne @JoinColumn(name = "company_id") private ECompany company; @ManyToOne @JoinColumn(name = "city_id") private ECity city; @ManyToOne @JoinColumn(name = "category_id") private ECategory category; @Column(name = "is_active") private boolean is_active; @Column(name = "rate") private int rate; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public ECompany getCompany() { if (company == null) { company = new ECompany(); } return company; } public void setCompany(ECompany company) { this.company = company; } public ECity getCity() { if (city == null) { city = new ECity(); } return city; } public void setCity(ECity city) { this.city = city; } public ECategory getCategory() { if (category == null) { category = new ECategory(); } return category; } public void setCategory(ECategory category) { this.category = category; } public boolean isIs_active() { return is_active; } public void setIs_active(boolean is_active) { this.is_active = is_active; } public int getRate() { return rate; } public void setRate(int rate) { this.rate = rate; } }
true
214341fd55236bb9e4d0062bde542fecf12d732b
Java
chrisabbod/unit-testing-in-android-course
/unit_testing_fundamentals/src/test/java/com/techyourchance/unittestingfundamentals/exercise3/IntervalsAdjacencyDetectorTest.java
UTF-8
3,338
3.046875
3
[]
no_license
package com.techyourchance.unittestingfundamentals.exercise3; import com.techyourchance.unittestingfundamentals.example3.Interval; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; public class IntervalsAdjacencyDetectorTest { IntervalsAdjacencyDetector SUT; @Before public void setup(){ SUT = new IntervalsAdjacencyDetector(); } @Test public void isAdjacent_intervalOneBeforeIntervalTwo_falseReturned(){ Interval intervalOne = new Interval(-1, 4); Interval intervalTwo = new Interval(5, 8); Boolean result = SUT.isAdjacent(intervalOne, intervalTwo); assertThat(result, is(false)); } @Test public void isAdjacent_intervalOneBeforeAndAdjacentIntervalTwo_trueReturned(){ Interval intervalOne = new Interval(-1, 5); Interval intervalTwo = new Interval(5, 8); Boolean result = SUT.isAdjacent(intervalOne, intervalTwo); assertThat(result, is(true)); } @Test public void isAdjacent_intervalOneOverlapsIntervalTwoAtStart_falseReturned(){ Interval intervalOne = new Interval(-1, 5); Interval intervalTwo = new Interval(3, 8); Boolean result = SUT.isAdjacent(intervalOne, intervalTwo); assertThat(result, is(false)); } @Test public void isAdjacent_intervalOneContainedWithinIntervalTwo_falseReturned(){ Interval intervalOne = new Interval(3, 5); Interval intervalTwo = new Interval(2, 8); Boolean result = SUT.isAdjacent(intervalOne, intervalTwo); assertThat(result, is(false)); } @Test public void isAdjacent_intervalOneContainsIntervalTwo_falseReturned(){ Interval intervalOne = new Interval(-1, 8); Interval intervalTwo = new Interval(2, 6); Boolean result = SUT.isAdjacent(intervalOne, intervalTwo); assertThat(result, is(false)); } @Test public void isAdjacent_intervalOneEqualsIntervalTwo_trueReturned(){ Interval intervalOne = new Interval(-1, 8); Interval intervalTwo = new Interval(-1, 8); Boolean result = SUT.isAdjacent(intervalOne, intervalTwo); assertThat(result, is(true)); } @Test public void isAdjacent_intervalOneOverlapsIntervalTwoAtEnd_falseReturned(){ Interval intervalOne = new Interval(-1, 5); Interval intervalTwo = new Interval(2, 8); Boolean result = SUT.isAdjacent(intervalOne, intervalTwo); assertThat(result, is(false)); } @Test public void isAdjacent_intervalOneAfterAndAdjacentIntervalTwo_trueReturned(){ Interval intervalOne = new Interval(5, 8); Interval intervalTwo = new Interval(2, 5); Boolean result = SUT.isAdjacent(intervalOne, intervalTwo); assertThat(result, is(true)); } @Test public void isAdjacent_intervalOneAfterIntervalTwo_falseReturned(){ Interval intervalOne = new Interval(5, 8); Interval intervalTwo = new Interval(2, 4); Boolean result = SUT.isAdjacent(intervalOne, intervalTwo); assertThat(result, is(false)); } //Interval1 after and adjacent Interval2 //Interval1 after interval2 }
true
8ff605daf09775bfbbbcda478c33a64b4e1ec37d
Java
BigEgg/WeChat-Platform
/WeChat-Core/src/main/java/com/thoughtworks/wechat_core/messages/outbound/OutboundMessage.java
UTF-8
330
1.898438
2
[]
no_license
package com.thoughtworks.wechat_core.messages.outbound; import com.thoughtworks.wechat_core.wechat.outbound.WeChatOutbound; import org.joda.time.DateTime; public interface OutboundMessage { OutboundMessageType getMessageType(); DateTime getCreatedTime(); WeChatOutbound toWeChat(OutboundMessageEnvelop envelop); }
true
f3e84ef745881c1aa8a4c8f8623a79384e4a3347
Java
nekochord/bank-demo
/account/src/main/java/com/demo/account/function/AccountQueryFunction.java
UTF-8
1,068
2.09375
2
[]
no_license
package com.demo.account.function; import com.demo.account.converter.DataConverter; import com.demo.account.entity.Account; import com.demo.account.repository.AccountRepository; import com.demo.cqrs.query.QueryFunction; import com.demo.cqrs.query.account.AccountQuery; import com.demo.cqrs.query.account.AccountRes; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @Component public class AccountQueryFunction implements QueryFunction<AccountQuery, AccountRes> { @Autowired private AccountRepository accountRepository; @Override @Transactional(readOnly = true) public AccountRes query(AccountQuery request) throws Exception { Account account = accountRepository.findById(request.getAccountId()) .orElseThrow(AccountRes.Code.ACCOUNT_NOT_FOUND::exception); AccountRes res = new AccountRes(); res.setAccountData(DataConverter.toAccountData(account)); return res; } }
true
f764292dccc16363ebf2ade89eef3abb4a804104
Java
Harjacober/ObounceChat
/app/src/main/java/com/example/harjacober/obouncechat/fragments/ChatsFragment.java
UTF-8
3,454
2.0625
2
[]
no_license
package com.example.harjacober.obouncechat.fragments; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.example.harjacober.obouncechat.R; import com.example.harjacober.obouncechat.adapters.ChatsListAdapter; import com.example.harjacober.obouncechat.data.Chats; import com.example.harjacober.obouncechat.viewmodel.ChatsListViewModel; import java.util.ArrayList; import java.util.List; import static com.example.harjacober.obouncechat.fragments.CallsFragments.displayImageInDialog; public class ChatsFragment extends Fragment implements ChatsListAdapter.ListItmeClickedListener{ private List<Chats> chatList; private RecyclerView mrecyclerView; private ChatsListAdapter adapter; private LinearLayout emptyView; public ChatsFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_chats, container, false); emptyView = view.findViewById(R.id.empty_view); chatList = new ArrayList<>(); mrecyclerView = view.findViewById(R.id.chats_recycler_view); mrecyclerView.setHasFixedSize(true); mrecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); adapter = new ChatsListAdapter(chatList, getContext(), this); mrecyclerView.setAdapter(adapter); fetchDataFromFirebase(); return view; } @Override public void onProfilePicClickedListener(String thumbnail, String profileUrl, String fullName) { displayImageInDialog(thumbnail, profileUrl, fullName, getContext(), getActivity()); } public void fetchDataFromFirebase(){ ChatsListViewModel userViewModel = ViewModelProviders.of(this) .get(ChatsListViewModel.class); LiveData<List<Chats>> allGroupLivedata = userViewModel.getAllChatsLivedata(); allGroupLivedata.observe(this, new Observer<List<Chats>>() { @Override public void onChanged(@Nullable List<Chats> list) { chatList.clear(); if (list != null){ emptyView.setVisibility(View.INVISIBLE); mrecyclerView.setVisibility(View.VISIBLE); chatList = list; adapter.update(chatList); }else { emptyView.setVisibility(View.VISIBLE); mrecyclerView.setVisibility(View.INVISIBLE); } } }); } }
true
59eea30dabc6781df07033d69e7faae4c937ebd7
Java
Frong-nt/vehicle-shop
/src/main/java/com/example/vehicleshop/VehicleShopApplication.java
UTF-8
3,710
3.046875
3
[]
no_license
package com.example.vehicleshop; import desgin.pattern.vehicle.Car; import desgin.pattern.vehicle.Vehicle; import desgin.pattern.vehicle.VehicleFactory; import desgin.pattern.vehicle.VehicleSingleton; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @SpringBootApplication @RestController public class VehicleShopApplication { private VehicleSingleton singleton = VehicleSingleton.getInstance(); private VehicleFactory vehicleFactory = new VehicleFactory(); public static void main(String[] args) { SpringApplication.run(VehicleShopApplication.class, args); } @RequestMapping("/") public String home(){ String s = "/create/{vehicle}\t=> create 'Car' or 'Plane'\n\n"; s+= "/get/{index}\t\t=> get specific vehicle\n\n"; s+= "/all\t\t\t\t=> return all vehicle\n\n"; s+= "/delete/{index}\t\t=> delete specific vehicle\n\n"; s+= "/update/{index}\t\t=> update specific vehicle\n\n"; s+= "/all-car\t\t\t=> get all of Cars\n\n"; s+= "/all-plane\t\t\t=> get all of Planes"; return s; } @RequestMapping("/all") public List<Vehicle> allVehicle(){ return singleton.getAllVehicles(); } @RequestMapping(value = "/create/{vehicle}", method = RequestMethod.POST) public ResponseEntity<List<Vehicle>> create(@RequestBody Vehicle v,@PathVariable("vehicle") String vehicleType) { //to create specific type fo vehicle like car of plane Vehicle vehicle = vehicleFactory.getVehicle(vehicleType); vehicle.setFuel(v.getFuel()); vehicle.setAvailable(v.isAvailable()); vehicle.setSpeed(v.getSpeed()); vehicle.setColor(v.getColor()); vehicle.setType(v.getType()); // if we just pass v as argument in the first place then we cant know that what is the exactly type of v, // because we pass v as parameter in type Of Vehicle not Car or Plane so the above line of code to make sure // that we already check and create the exactly type. this.singleton.createVehicle(vehicle); return new ResponseEntity<List<Vehicle>>(this.singleton.getAllVehicles(), HttpStatus.OK); } @RequestMapping(value = "/get/{index}") public ResponseEntity<Vehicle> get(@PathVariable("index") int index) { return new ResponseEntity<Vehicle>( singleton.getVehicle(index), HttpStatus.OK); } @RequestMapping(value = "/update/{index}", method = RequestMethod.POST) public ResponseEntity<List<Vehicle>> update(@PathVariable("index")int index, @RequestBody Vehicle vehicle) { this.singleton.update(index, vehicle); return new ResponseEntity<List<Vehicle>>(this.singleton.getAllVehicles(), HttpStatus.OK); } @RequestMapping(value = "/delete/{index}") public ResponseEntity<List<Vehicle>> delete(@PathVariable("index") int index) { this.singleton.delete(index); return new ResponseEntity<List<Vehicle>>(this.singleton.getAllVehicles(), HttpStatus.OK); } @RequestMapping(value = "/all-car") public ResponseEntity<List<Vehicle>> getAllCar() { return new ResponseEntity<List<Vehicle>>(this.singleton.getAllCar(), HttpStatus.OK); } @RequestMapping(value = "/all-plane") public ResponseEntity<List<Vehicle>> getAllPlane() { return new ResponseEntity<List<Vehicle>>(this.singleton.getAllPlane(), HttpStatus.OK); } }
true
a82a07dd8f54504a55eb71daed9286d040aa344a
Java
ossaw/jdk
/src/com/sun/security/auth/login/ConfigFile.java
UTF-8
4,302
2.265625
2
[]
no_license
/* * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.sun.security.auth.login; import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.Configuration; import java.net.URI; // NOTE: As of JDK 8, this class instantiates // sun.security.provider.ConfigFile.Spi and forwards all methods to that // implementation. All implementation fixes and enhancements should be made to // sun.security.provider.ConfigFile.Spi and not this class. // See JDK-8005117 for more information. /** * This class represents a default implementation for * {@code javax.security.auth.login.Configuration}. * <p> * This object stores the runtime login configuration representation, and is the * amalgamation of multiple static login configurations that resides in files. * The algorithm for locating the login configuration file(s) and reading their * information into this {@code Configuration} object is: * <ol> * <li>Loop through the security properties, <i>login.config.url.1</i>, * <i>login.config.url.2</i>, ..., <i>login.config.url.X</i>. Each property * value specifies a {@code URL} pointing to a login configuration file to be * loaded. Read in and load each configuration. * <li>The {@code java.lang.System} property * <i>java.security.auth.login.config</i> may also be set to a {@code URL} * pointing to another login configuration file (which is the case when a user * uses the -D switch at runtime). If this property is defined, and its use is * allowed by the security property file (the Security property, * <i>policy.allowSystemProperty</i> is set to <i>true</i>), also load that * login configuration. * <li>If the <i>java.security.auth.login.config</i> property is defined using * "==" (rather than "="), then ignore all other specified login configurations * and only load this configuration. * <li>If no system or security properties were set, try to read from the file, * ${user.home}/.java.login.config, where ${user.home} is the value represented * by the "user.home" System property. * </ol> * <p> * The configuration syntax supported by this implementation is exactly that * syntax specified in the {@code javax.security.auth.login.Configuration} * class. * * @see javax.security.auth.login.LoginContext * @see java.security.Security security properties */ @jdk.Exported public class ConfigFile extends Configuration { private final sun.security.provider.ConfigFile.Spi spi; /** * Create a new {@code Configuration} object. * * @throws SecurityException * if the {@code Configuration} can not be * initialized */ public ConfigFile() { spi = new sun.security.provider.ConfigFile.Spi(); } /** * Create a new {@code Configuration} object from the specified {@code URI}. * * @param uri * the {@code URI} * @throws SecurityException * if the {@code Configuration} can not be * initialized * @throws NullPointerException * if {@code uri} is null */ public ConfigFile(URI uri) { spi = new sun.security.provider.ConfigFile.Spi(uri); } /** * Retrieve an entry from the {@code Configuration} using an application * name as an index. * * @param applicationName * the name used to index the {@code Configuration} * @return an array of {@code AppConfigurationEntry} which correspond to the * stacked configuration of {@code LoginModule}s for this * application, or null if this application has no configured * {@code LoginModule}s. */ @Override public AppConfigurationEntry[] getAppConfigurationEntry(String applicationName) { return spi.engineGetAppConfigurationEntry(applicationName); } /** * Refresh and reload the {@code Configuration} by re-reading all of the * login configurations. * * @throws SecurityException * if the caller does not have permission to * refresh the * {@code Configuration} */ @Override public void refresh() { spi.engineRefresh(); } }
true
7773b764f7e8f46cee94d5bade4ed8c283b91575
Java
apache/ctakes
/ctakes-relation-extractor/src/main/java/org/apache/ctakes/relationextractor/pipelines/RelationExtractorPipeline.java
UTF-8
3,508
2.109375
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * 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.ctakes.relationextractor.pipelines; import org.apache.ctakes.core.config.ConfigParameterConstants; import org.apache.ctakes.core.cr.FileTreeReader; import org.apache.ctakes.core.util.doc.DocIdUtil; import org.apache.uima.UIMAException; import org.apache.uima.analysis_engine.AnalysisEngineDescription; import org.apache.uima.cas.SerialFormat; import org.apache.uima.collection.CollectionReaderDescription; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.fit.factory.CollectionReaderFactory; import org.apache.uima.fit.pipeline.SimplePipeline; import org.apache.uima.jcas.JCas; import org.apache.uima.util.CasIOUtils; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * A simple pipeline that runs relation extraction on all files in a directory and saves * the resulting annotations as XMI files. The core part of this pipeline is the aggregate * relation extractor AE which runs all the preprocessing that is necessary for relation * extraction as well as the AEs that extract relations. * * @author dmitriy dligach * */ public class RelationExtractorPipeline { public static class Options { @Option( name = "--input-dir", usage = "specify the path to the directory containing the clinical notes to be processed", required = true) public String inputDirectory; @Option( name = "--output-dir", usage = "specify the path to the directory where the output xmi files are to be saved", required = true) public String outputDirectory; } public static void main(String[] args) throws UIMAException, IOException, CmdLineException { Options options = new Options(); CmdLineParser parser = new CmdLineParser(options); parser.parseArgument(args); CollectionReaderDescription collectionReader = CollectionReaderFactory.createReaderDescription( FileTreeReader.class, ConfigParameterConstants.PARAM_INPUTDIR, options.inputDirectory); // make sure the model parameters match those used for training AnalysisEngineDescription relationExtractor = AnalysisEngineFactory.createEngineDescriptionFromPath( "desc/analysis_engine/RelationExtractorAggregate.xml"); for(JCas jcas : SimplePipeline.iteratePipeline(collectionReader, relationExtractor)){ String docId = DocIdUtil.getDocumentID(jcas); try(FileOutputStream fos = new FileOutputStream(new File(options.outputDirectory, String.format("%s.xmi", docId)))) { CasIOUtils.save(jcas.getCas(), fos, SerialFormat.XMI); } } } }
true
939c2638529c69cadf058fb74ae0eb41c040cf6a
Java
pawellasota/find-the-way
/src/main/java/com/codecool/findtheway/ui/Ui.java
UTF-8
449
2.984375
3
[]
no_license
package com.codecool.findtheway.ui; import com.codecool.findtheway.model.Vertex; import java.util.List; public class Ui { public static void displayTrip(List<Vertex> path, Integer costs) { System.out.println("Shortest trip:"); for (Vertex vertex : path) { System.out.println(Integer.toString(path.indexOf(vertex)+1)+". "+vertex.getName()); } System.out.println("Overall costs: " + costs); } }
true
dd714c3dc41932ac0d77e664aecf83e278893cc3
Java
ashoknanabala/Q2
/src/main/java/com/vm/Q2/dto/UserProjection.java
UTF-8
426
1.796875
2
[]
no_license
/* * 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 com.vm.Q2.dto; import com.vm.Q2.models.Technology; import java.util.List; /** * * @author Ashok */ public interface UserProjection { Long getId(); String getFirstName(); List<Technology> getTechnology(); }
true
a4ed14ddb9f556c9f45e3521d998cd9e64114242
Java
ghaohao/netty-rpc
/rpc-common/src/main/java/com/rpc/common/model/RpcResponse.java
UTF-8
344
1.875
2
[]
no_license
package com.rpc.common.model; import lombok.Data; /** * 封装请求结果 * @Author gu * @Version V1.0 * @Date 17/12/29 下午4:25 */ @Data public class RpcResponse { private String requestId; private Exception exception; private Object result; public boolean hasException() { return exception != null; } }
true
1bd8a5e49ef53cd12dcd1a18e49be3050b361aec
Java
gozdegungor/SE311Project
/src/SessionFactory/TerminalSession.java
UTF-8
290
2.0625
2
[]
no_license
// Yiğit Ege Miman - 20160602022 // Gözde Güngör - 20160601023 // Cem Özcan - 20170601024 // A Pluggable Authentication Mechanism package SessionFactory; //Concrete product class public class TerminalSession extends Session { public String getSessionType() { return "Terminal Session"; } }
true
37e24b337c5a67a89a03cb4524884bc3ecb74cab
Java
EDUMATT3/orange-talents-06-template-proposta
/src/main/java/com/desafio/zup/proposta/proposta/solicitacaoanalise/SolicitacaoAnaliseRequest.java
UTF-8
514
1.953125
2
[ "Apache-2.0" ]
permissive
package com.desafio.zup.proposta.proposta.solicitacaoanalise; import com.desafio.zup.proposta.proposta.Proposta; import com.fasterxml.jackson.annotation.JsonProperty; public class SolicitacaoAnaliseRequest { @JsonProperty private String documento, nome; @JsonProperty private Long idProposta; public SolicitacaoAnaliseRequest(Proposta proposta) { this.documento = proposta.getDocumento(); this.nome = proposta.getNome(); this.idProposta = proposta.getId(); } }
true
4e5616aebb098c8becc3cfaa594e6d76c93a26ee
Java
blastgwen/dsl-browser-automatisation
/com.selenium.gram.xtext/src-gen/com/selenium/gram/xtext/slnDsl/Loop.java
UTF-8
1,129
1.804688
2
[]
no_license
/** */ package com.selenium.gram.xtext.slnDsl; import org.eclipse.emf.common.util.EList; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Loop</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link com.selenium.gram.xtext.slnDsl.Loop#getIns <em>Ins</em>}</li> * </ul> * </p> * * @see com.selenium.gram.xtext.slnDsl.SlnDslPackage#getLoop() * @model * @generated */ public interface Loop extends Instruction { /** * Returns the value of the '<em><b>Ins</b></em>' containment reference list. * The list contents are of type {@link com.selenium.gram.xtext.slnDsl.Instruction}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Ins</em>' containment reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Ins</em>' containment reference list. * @see com.selenium.gram.xtext.slnDsl.SlnDslPackage#getLoop_Ins() * @model containment="true" * @generated */ EList<Instruction> getIns(); } // Loop
true
9183f8df46c194c570a0ab79698e896df522853e
Java
tibijejczyk/TheMinecraft
/minecraft/dex3r/API/chunkprotection/ProtectEventHookContainer.java
UTF-8
1,259
2.28125
2
[]
no_license
package dex3r.API.chunkprotection; import java.util.Date; import net.minecraftforge.event.ForgeSubscribe; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import dex3r.API.Colors; import dex3r.API.shared.PowerTools; public class ProtectEventHookContainer { @ForgeSubscribe public void playerInteractEvent(PlayerInteractEvent event) { int dimension = event.entityPlayer.worldObj.provider.dimensionId; int x = PowerTools.toChunkCoordinate(event.x); int z = PowerTools.toChunkCoordinate(event.z); String name = event.entityPlayer.getCommandSenderName(); byte compare = ChunkProtection.chunkCompare(dimension, x, z, name); // DEBUG REDPOWER !name.equals("") if (!name.equals("") && compare==1 && event.isCancelable() ) { event.setCanceled(true); PowerTools.date = new Date(); // Display message again after 2 seconds long time2 = PowerTools.date.getTime(); if (time2 - PowerTools.plGetTimer1(name) > 2000) { event.entityPlayer.sendChatToPlayer(Colors.Yellow + "This land is owned by '" + ChunkProtection.chunkOwner(dimension, x, z) + "'."); event.entityPlayer.sendChatToPlayer(Colors.Yellow + "You aren't allowed to build or break here."); PowerTools.plSetTimer1(name, time2); } } } }
true
cc042dee6dec5820344caf34ca968d8d9f554c53
Java
ProkazaEvgeniy/WebNutritionist
/src/main/java/net/www/webnutritionist/form/VegetableNutritionistForm.java
UTF-8
770
2.390625
2
[]
no_license
package net.www.webnutritionist.form; import java.util.ArrayList; import java.util.List; import javax.validation.Valid; import net.www.webnutritionist.entity.VegetableNutritionist; public class VegetableNutritionistForm { @Valid private List<VegetableNutritionist> items = new ArrayList<>(); public VegetableNutritionistForm() { super(); } public VegetableNutritionistForm(List<VegetableNutritionist> items) { super(); this.items = items; } public List<VegetableNutritionist> getItems() { return items; } public void setItems(List<VegetableNutritionist> items) { this.items = items; } @Override public String toString() { return String.format("VegetableNutritionistForm [items=%s]", items); } }
true
b1ac1c13cca962ad6131043d56cd154a5e350bdb
Java
kibris-order/kibrisOrderapp
/app/src/main/java/com/example/campus_comuputer/listviewapplication/verticalRecycleView_activity/RecyclerViewAdapter.java
UTF-8
3,084
2.296875
2
[]
no_license
package com.example.campus_comuputer.listviewapplication.verticalRecycleView_activity; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.example.campus_comuputer.listviewapplication.R; import com.example.campus_comuputer.listviewapplication.shared_classes.RowComponentData; import java.util.ArrayList; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by Campus-Comuputer on 4/23/2018. */ public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> { private static final String TAG = "RecyclerViewAdapter"; private ArrayList<RowComponentData> rowComponentData = new ArrayList<>(); private Context mContext; public RecyclerViewAdapter(Context mContext,ArrayList<RowComponentData> rowComponentData) { this.rowComponentData = rowComponentData; this.mContext = mContext; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listitem, parent, false); ViewHolder holder = new ViewHolder(view); return holder; } @Override public void onBindViewHolder(ViewHolder holder, final int position) { Log.d(TAG, " onBindViewHolder: called"); Glide.with(mContext) .asBitmap() .load(rowComponentData.get(position).getUrl()) .into(holder.image); holder.imageName.setText(rowComponentData.get(position).getName()); holder.imageDescription.setText(rowComponentData.get(position).getDescription()); holder.parentLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "onClick: clicked on: " + rowComponentData.get(position).getName()); Toast.makeText(mContext, rowComponentData.get(position).getName(), Toast.LENGTH_SHORT).show(); } }); } @Override public int getItemCount() { return rowComponentData.size(); } public class ViewHolder extends RecyclerView.ViewHolder { CircleImageView image; TextView imageName; TextView imageDescription; RelativeLayout parentLayout; // ImageButton imageButton; //this holdes each individual view in memory public ViewHolder(View itemView) { super(itemView); image = itemView.findViewById(R.id.image); imageName = itemView.findViewById(R.id.image_name); imageDescription = itemView.findViewById(R.id.image_description); // imageButton = itemView.findViewById(R.id.imageButton); parentLayout = itemView.findViewById(R.id.parent_layout); } } }
true
b2d72cffcba9fdeb466ed215eeb4c01392f3692e
Java
aj470/AI_PathFinding
/AI_Pathfinding-master/src/Model/AstarComparator.java
UTF-8
501
3.078125
3
[]
no_license
package Model; import java.util.Comparator; public class AstarComparator implements Comparator<Node> { public int compare(Node m, Node n) { if(m.getfCost() > n.getfCost()) { return 1; } else if (m.getfCost() < n.getfCost()) { return -1; } else { if(m.gethCost() > n.gethCost()) return 1; else return -1; } } }
true
23e3c6ce837153055bb118213b7881ee01972425
Java
shwetha337/DailyHealthCheckCode
/TestScreenShotDemo/src/test/java/com/hcc/qa/util/CommonMethodsOfDHC.java
UTF-8
1,180
2.234375
2
[]
no_license
package com.hcc.qa.util; import java.io.File; import java.io.IOException; import java.util.Base64; import java.util.IllegalFormatException; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import com.relevantcodes.extentreports.ExtentTest; import com.relevantcodes.extentreports.LogStatus; public class CommonMethodsOfDHC{ WebDriver driver; ExtentTest logger; public void LOGWithScreenshot(ExtentTest logger, String status, String TestDescription) throws IOException, IllegalFormatException { String Base64StringofScreenshot = ""; File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); byte[] fileContent = FileUtils.readFileToByteArray(src); Base64StringofScreenshot = "data:image/png;base64," + Base64.getEncoder().encodeToString(fileContent); if (status.equalsIgnoreCase("fail")) { // logger.log(LogStatus.PASS, // TestDescription+"\n"+logger.addBase64ScreenShot(Base64StringofScreenshot)); // else logger.log(LogStatus.FAIL, TestDescription + "\n" + logger.addBase64ScreenShot(Base64StringofScreenshot)); } } }
true
cadd8b035e702358eca2f4e702a5051d4e5184ee
Java
hogeschool/INFDEV02-4
/Assignment/JAVA + GDX incomplete assignments/GUIapp - iteration 4 - TODO (maven)/src/main/java/edu/hr/infdev024/GUIMenuCreator.java
UTF-8
167
1.585938
2
[ "Apache-2.0", "MIT" ]
permissive
package edu.hr.infdev024; // Describes a class with a factory method for creating menu screens public abstract class GUIMenuCreator { //TODO: ADD MISSING CODE HERE }
true
57efd499f45a2808f006b5edc8a4e84a63205154
Java
luninez/Palomas
/PalomasApp/app/src/main/java/com/example/palomasapp/List/fragment_list/PastelesFragment.java
UTF-8
6,483
2.140625
2
[]
no_license
package com.example.palomasapp.List.fragment_list; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.palomasapp.Interfaz.OnListLineaPedidoInteractionListener; import com.example.palomasapp.List.Adapter.MypastelesRecyclerViewAdapter; import com.example.palomasapp.Funcionalidades.ServiceGenerator; import com.example.palomasapp.Funcionalidades.Services.ProductoService; import com.example.palomasapp.Interfaz.OnListProductoInteractionListener; import com.example.palomasapp.Models.Producto; import com.example.palomasapp.Models.ResponseContainer; import com.example.palomasapp.R; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class PastelesFragment extends Fragment { private static final String ARG_COLUMN_COUNT = "column-count"; private int mColumnCount = 1; private OnListLineaPedidoInteractionListener mListener; private MypastelesRecyclerViewAdapter adapter; private Context ctx; private RecyclerView recyclerView; private SwipeRefreshLayout swipe; public String categoriaId; public boolean filtrarPorCategoria; public PastelesFragment() { filtrarPorCategoria = false; } public static PastelesFragment newInstance(int columnCount) { PastelesFragment fragment = new PastelesFragment(); Bundle args = new Bundle(); args.putInt(ARG_COLUMN_COUNT, columnCount); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_pasteles_list, container, false); swipe = view.findViewById(R.id.swipePasteles); if (view instanceof SwipeRefreshLayout) { Context context = view.getContext(); recyclerView = view.findViewById(R.id.listPasteles); recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL)); if (mColumnCount <= 1) { recyclerView.setLayoutManager(new LinearLayoutManager(context)); } else { recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount)); } //LLAMADA A LA API if(!filtrarPorCategoria) { cargarDatos(recyclerView); }else{ cargarDatosPorCategoria(recyclerView, categoriaId); } } swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { actualizarDatos(); swipe.setRefreshing(false); } }, 3000); } }); return view; } public void cargarDatos(final RecyclerView recyclerView) { ProductoService productoService = ServiceGenerator.createService(ProductoService.class); Call<ResponseContainer<Producto>> call = productoService.getProductos(); call.enqueue(new Callback<ResponseContainer<Producto>>() { @Override public void onResponse(Call<ResponseContainer<Producto>> call, Response<ResponseContainer<Producto>> response) { if (response.isSuccessful()) { adapter = new MypastelesRecyclerViewAdapter(ctx, R.layout.fragment_pasteles, response.body().getRows(), mListener); recyclerView.setAdapter(adapter); } else { Toast.makeText(getContext(), "Error al obtener datos", Toast.LENGTH_LONG).show(); } } @Override public void onFailure(Call<ResponseContainer<Producto>> call, Throwable t) { Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show(); } }); } public void cargarDatosPorCategoria(final RecyclerView recyclerView, String categoriaId) { ProductoService productoService = ServiceGenerator.createService(ProductoService.class); Call<ResponseContainer<Producto>> call = productoService.getFiltrarCategoria(categoriaId); call.enqueue(new Callback<ResponseContainer<Producto>>() { @Override public void onResponse(Call<ResponseContainer<Producto>> call, Response<ResponseContainer<Producto>> response) { if (response.isSuccessful()) { adapter = new MypastelesRecyclerViewAdapter(ctx, R.layout.fragment_pasteles, response.body().getRows(), mListener); recyclerView.setAdapter(adapter); } else { Toast.makeText(getContext(), "Error al obtener datos", Toast.LENGTH_LONG).show(); } } @Override public void onFailure(Call<ResponseContainer<Producto>> call, Throwable t) { Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show(); } }); } public void actualizarDatos(){ cargarDatos(recyclerView); } @Override public void onAttach(Context context) { super.onAttach(context); ctx = context; if (context instanceof OnListLineaPedidoInteractionListener) { mListener = (OnListLineaPedidoInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } }
true
a95171fd29ced4e7f0d01adc3a983aec335e1c61
Java
weijiqian/StudyNotes
/java工具类/shawn-common-utils-master/src/main/java/com/shawntime/common/web/annotation/AutoValidate.java
UTF-8
552
2.15625
2
[]
no_license
package com.shawntime.common.web.annotation; import java.lang.annotation.*; /** * 表单入参验证注解 * * @author YinZhaohua */ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface AutoValidate { /** * 必填验证 */ boolean required() default false; /** * 最大值验证 */ int maxLength() default -1; /** * 手机号验证 */ boolean phone() default false; /** * 提示前缀 */ String prefixMsg() default "字段"; }
true
c4a474dd5ddb6762046aba94aa21975ae715f4fb
Java
de-tu-berlin-tfs/Henshin-Editor
/de.tub.tfs.henshin.tgg.editor/src/de/tub/tfs/henshin/tggeditor/tools/MarkerCreationTool.java
UTF-8
1,673
1.96875
2
[]
no_license
/******************************************************************************* * Copyright (c) 2010-2015 Henshin developers. All rights reserved. * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * TU Berlin, University of Luxembourg, SES S.A. *******************************************************************************/ package de.tub.tfs.henshin.tggeditor.tools; import org.eclipse.gef.commands.Command; import org.eclipse.gef.requests.CreationFactory; import org.eclipse.gef.tools.CreationTool; import de.tub.tfs.henshin.tggeditor.commands.create.rule.MarkCommand; import de.tub.tfs.henshin.tggeditor.commands.create.rule.MarkEdgeCommand; /** * The MarkerCreationTool can mark or demark nodes in a rule with <++>. * @see MarkCommand */ public class MarkerCreationTool extends CreationTool { /** * the constructor */ public MarkerCreationTool() { super(); } /** * the constructor * @param aFactory */ public MarkerCreationTool(CreationFactory aFactory) { super(aFactory); } /* (non-Javadoc) * @see org.eclipse.gef.tools.AbstractTool#handleFinished() */ @Override protected void handleFinished() { reactivate(); // super.handleFinished(); } @Override protected void executeCommand(Command command) { // if (command instanceof CreateMarkCommand || // command instanceof DeleteMarkCommand) { if (command instanceof MarkCommand || command instanceof MarkEdgeCommand) { super.executeCommand(command); } } }
true
15caeb1e39edaa02c8de76140d853d4d3b6e1d81
Java
sachinjha1/Algorithm
/Queue/src/com/q/Node.java
UTF-8
555
3.25
3
[ "MIT" ]
permissive
/** * */ package com.q; /** * @author Sachin Jha * Node * */ public class Node { public int value; public Node next; public Node(int value, Node next) { super(); this.value = value; this.next = next; } public Node(int value) { super(); this.value = value; } public Node(Node next) { super(); this.next = next; } public static void main(String[] args){ Node first = new Node(3); Node middle = new Node(5); Node last = new Node(7); // (3,*)->(5,*)->(7,null) first.next=middle; middle.next=last; } }
true
5720f428d4d754f1048c141983bb83d5fc5b1ae5
Java
psun2/Korea-IT-Academy
/FullStack_B/WebWork/STS20_JUnitTest08/src/main/java/com/lec/junit/App.java
UTF-8
485
3.078125
3
[]
no_license
package com.lec.junit; public class App { // 실습 1 public int add(int a, int b) { return a + b; } // 실습 2 public boolean comp(String a, String b) { if (a.equals(b)) { return true; } return false; } // 실습3 public int toNumber(String num) { return Integer.parseInt(num); } // 실습4 public String toDigit(String str) { StringBuffer result = new StringBuffer(); result.append(str.replaceAll("[^0-9]", "")); return result.toString(); } }
true
04f1f74d4a387d84c7e0a75382b1d10c3ad79377
Java
ly774508966/UnityDemo
/平时积累的文档/cocos时期/踩坑实录/ftp上传文件,注意不是SFTP!!/FtpUtil.java
UTF-8
6,729
2.46875
2
[]
no_license
package com.zgame.Activity; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; //import com.jcraft.jsch.Channel; //import com.jcraft.jsch.ChannelSftp; //import com.jcraft.jsch.ChannelSftp.LsEntry; //import com.jcraft.jsch.JSch; //import com.jcraft.jsch.Session; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import org.apache.log4j.Logger; import common.VariavlesPropertiesTool; public class FtpUtil { private static Logger logger=Logger.getLogger(FtpUtil.class); private static FTPClient ftp; private String fileName; public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } /** * 获取ftp连接 * @param f * @return * @throws Exception */ public boolean connectFtp(Ftp f) throws Exception{ ftp=new FTPClient(); boolean flag=false; int reply; ftp.connect(f.getIpAddr(),f.getPort()); ftp.login(f.getUserName(), f.getPwd()); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return flag; } ftp.changeWorkingDirectory("/home"); flag = true; return flag; } /** * 关闭ftp连接 */ public static void closeFtp(){ if (ftp!=null && ftp.isConnected()) { try { ftp.logout(); ftp.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } /** * ftp上传文件 * @param f * @throws Exception */ public void upload(File f) throws Exception{ //如果是目录 if (f.isDirectory()) { ftp.makeDirectory(f.getName()); FileInputStream input=new FileInputStream(f); ftp.storeFile("override.txt",input); input.close(); } } /** * 下载链接配置 * @param f * @param localBaseDir 本地目录 * @param remoteBaseDir 远程目录 * @throws Exception */ public void startDown(Ftp f,String localBaseDir,String remoteBaseDir ) throws Exception{ if (connectFtp(f)) { try { FTPFile[] files = null; boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir); if (changedir) { ftp.setControlEncoding("GBK"); files = ftp.listFiles(); for (int i = 0; i < files.length; i++) { try{ downloadFile(files[i], localBaseDir, remoteBaseDir); }catch(Exception e){ logger.error(e); logger.error("<"+files[i].getName()+">下载失败"); } } } } catch (Exception e) { logger.error(e); logger.error("下载过程中出现异常"); } }else{ logger.error("链接失败!"); } } /** * * 下载FTP文件 * 当你需要下载FTP文件的时候,调用此方法 * 根据<b>获取的文件名,本地地址,远程地址</b>进行下载 * * @param ftpFile * @param relativeLocalPath * @param relativeRemotePath */ private static void downloadFile(FTPFile ftpFile, String relativeLocalPath,String relativeRemotePath) { if (ftpFile.isFile()) { if (ftpFile.getName().indexOf("?") == -1) { OutputStream outputStream = null; try { File locaFile= new File(relativeLocalPath+ ftpFile.getName()); //判断文件是否存在,存在则返回 if(locaFile.exists()){ return; }else{ outputStream = new FileOutputStream(relativeLocalPath+ ftpFile.getName()); ftp.retrieveFile(ftpFile.getName(), outputStream); outputStream.flush(); outputStream.close(); } } catch (Exception e) { logger.error(e); } finally { try { if (outputStream != null){ outputStream.close(); } } catch (IOException e) { logger.error("输出文件流异常"); } } } } else { String newlocalRelatePath = relativeLocalPath + ftpFile.getName(); String newRemote = new String(relativeRemotePath+ ftpFile.getName().toString()); File fl = new File(newlocalRelatePath); if (!fl.exists()) { fl.mkdirs(); } try { newlocalRelatePath = newlocalRelatePath + '/'; newRemote = newRemote + "/"; String currentWorkDir = ftpFile.getName().toString(); boolean changedir = ftp.changeWorkingDirectory(currentWorkDir); if (changedir) { FTPFile[] files = null; files = ftp.listFiles(); for (int i = 0; i < files.length; i++) { downloadFile(files[i], newlocalRelatePath, newRemote); } } if (changedir){ ftp.changeToParentDirectory(); } } catch (Exception e) { logger.error(e); } } } public String UpLoadFile(){ VariavlesPropertiesTool.InitPropertiesTool(); for(int i=0; i<VariavlesPropertiesTool.serverSize; i++){ try { connectFtp(VariavlesPropertiesTool.serverList.get(i)); File file = new File(fileName); upload(file);//把文件上传在ftp上 //startDown(f, "e:/", "/xxtest");//下载ftp文件测试 System.out.println("ok"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return "success"; } }
true
0e64289286f34ed50669235204cb3f461228067a
Java
shinnoki/android-camera-spike
/src/com/konashi/fashionstamp/view/CommentView.java
UTF-8
649
1.851563
2
[]
no_license
package com.konashi.fashionstamp.view; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import com.example.camerastamp.R; public class CommentView extends FrameLayout { public CommentView(Context context) { super(context); LayoutInflater inflator = LayoutInflater.from(context); View layout = inflator.inflate(R.layout.comment_edit, null); this.addView(layout); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // TODO 自動生成されたメソッド・スタブ } }
true
8677e0f767748c695bd6572f4eee8132e664daae
Java
raffaeleflorio/surily
/src/main/java/io/github/raffaeleflorio/surily/Uri.java
UTF-8
9,850
1.875
2
[ "Apache-2.0" ]
permissive
/* Copyright 2021 Raffaele Florio Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package io.github.raffaeleflorio.surily; import io.github.raffaeleflorio.surily.authority.AuthorityComponent; import io.github.raffaeleflorio.surily.authority.UndefinedAuthority; import io.github.raffaeleflorio.surily.fragment.FragmentComponent; import io.github.raffaeleflorio.surily.fragment.UndefinedFragment; import io.github.raffaeleflorio.surily.path.EmptyPath; import io.github.raffaeleflorio.surily.path.NormalizedSegments; import io.github.raffaeleflorio.surily.path.PathComponent; import io.github.raffaeleflorio.surily.path.PathSegmentSubcomponent; import io.github.raffaeleflorio.surily.query.QueryComponent; import io.github.raffaeleflorio.surily.query.UndefinedQuery; import io.github.raffaeleflorio.surily.scheme.SchemeComponent; import java.nio.charset.Charset; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; /** * RFC3986 compliant URI * * @author Raffaele Florio (raffaeleflorio@protonmail.com) * @see <a href="https://datatracker.ietf.org/doc/html/rfc3986#section-3">RFC3986 definition</a> * @since 1.0.0 */ public final class Uri implements UriReference { /** * Builds an URI * * @param scheme The scheme * @since 1.0.0 */ public Uri(final SchemeComponent scheme) { this(scheme, new UndefinedAuthority()); } /** * Builds an URI * * @param scheme The scheme * @param authority The authority * @since 1.0.0 */ public Uri(final SchemeComponent scheme, final AuthorityComponent authority) { this(scheme, authority, new EmptyPath()); } /** * Builds an URI * * @param scheme The scheme * @param authority The authority * @param path The path * @since 1.0.0 */ public Uri(final SchemeComponent scheme, final AuthorityComponent authority, final PathComponent path) { this(scheme, authority, path, new UndefinedQuery()); } /** * Builds an URI * * @param scheme The scheme * @param authority The authority * @param path The path * @param query The query * @since 1.0.0 */ public Uri( final SchemeComponent scheme, final AuthorityComponent authority, final PathComponent path, final QueryComponent query ) { this(scheme, authority, path, query, new UndefinedFragment()); } /** * Builds an URI * * @param scheme The scheme * @param authority The authority * @param path The path * @param query The query * @param fragment The fragment * @since 1.0.0 */ public Uri( final SchemeComponent scheme, final AuthorityComponent authority, final PathComponent path, final QueryComponent query, final FragmentComponent fragment ) { this( scheme, authority, path, query, fragment, FormattedComponents::new, JoinedComponents::new, NormalizedSegments::new ); } /** * Builds an URI * * @param scheme The scheme * @param path The path * @since 1.0.0 */ public Uri(final SchemeComponent scheme, final PathComponent path) { this(scheme, new UndefinedAuthority(), path); } /** * Builds an URI * * @param scheme The scheme * @param path The path * @param fragment The fragment * @since 1.0.0 */ public Uri(final SchemeComponent scheme, final PathComponent path, final FragmentComponent fragment) { this(scheme, new UndefinedAuthority(), path, new UndefinedQuery(), fragment); } /** * Builds an URI * * @param scheme The scheme * @param path The path * @param query The query * @since 1.0.0 */ public Uri(final SchemeComponent scheme, final PathComponent path, final QueryComponent query) { this(scheme, new UndefinedAuthority(), path, query); } /** * Builds an URI * * @param scheme The scheme * @param query The query * @since 1.0.0 */ public Uri(final SchemeComponent scheme, final QueryComponent query) { this(scheme, new UndefinedAuthority(), new EmptyPath(), query); } /** * Builds an URI * * @param scheme The scheme * @param authority The authority * @param query The query * @since 1.0.0 */ public Uri(final SchemeComponent scheme, final AuthorityComponent authority, final QueryComponent query) { this(scheme, authority, new EmptyPath(), query); } /** * Builds an URI * * @param scheme The scheme * @param fragment The fragment * @since 1.0.0 */ public Uri(final SchemeComponent scheme, final FragmentComponent fragment) { this(scheme, new UndefinedAuthority(), new EmptyPath(), new UndefinedQuery(), fragment); } /** * Builds an URI * * @param scheme The scheme * @param authority The authority * @param fragment The fragment * @since 1.0.0 */ public Uri(final SchemeComponent scheme, final AuthorityComponent authority, final FragmentComponent fragment) { this(scheme, authority, new EmptyPath(), new UndefinedQuery(), fragment); } /** * Builds an URI * * @param scheme The scheme * @param authority The authority * @param path The path * @param fragment The fragment * @since 1.0.0 */ public Uri( final SchemeComponent scheme, final AuthorityComponent authority, final PathComponent path, final FragmentComponent fragment ) { this(scheme, authority, path, new UndefinedQuery(), fragment); } /** * Builds an URI * * @param scheme The scheme * @param query The query * @param fragment The fragment * @since 1.0.0 */ public Uri(final SchemeComponent scheme, final QueryComponent query, final FragmentComponent fragment) { this(scheme, new UndefinedAuthority(), new EmptyPath(), query, fragment); } /** * Builds an URI * * @param scheme The scheme * @param authority The authority * @param query The query * @param fragment The fragment * @since 1.0.0 */ public Uri( final SchemeComponent scheme, final AuthorityComponent authority, final QueryComponent query, final FragmentComponent fragment ) { this(scheme, authority, new EmptyPath(), query, fragment); } /** * Builds an URI * * @param scheme The scheme * @param authority The authority * @param path The path * @param query The query * @param fragment The fragment * @param formattedFn The function to format components * @param joinedFn The function to join components * @since 1.0.0 */ Uri( final SchemeComponent scheme, final AuthorityComponent authority, final PathComponent path, final QueryComponent query, final FragmentComponent fragment, final BiFunction<String, List<UriComponent>, UriComponent> formattedFn, final BiFunction<List<UriComponent>, String, UriComponent> joinedFn, final Function<PathComponent, List<PathSegmentSubcomponent>> normalizedSegmentsFn ) { this.scheme = scheme; this.authority = authority; this.path = path; this.query = query; this.fragment = fragment; this.formattedFn = formattedFn; this.joinedFn = joinedFn; this.normalizedSegmentsFn = normalizedSegmentsFn; } @Override public CharSequence encoded(final Charset charset) { return joinedComponents().encoded(charset); } private UriComponent joinedComponents() { return joinedFn.apply(formattedComponents(), ""); } private List<UriComponent> formattedComponents() { return Stream.of(formattedScheme(), hierPart(), formattedQuery(), formattedFragment()) .flatMap(Function.identity()) .collect(Collectors.toUnmodifiableList()); } private Stream<UriComponent> formattedScheme() { return Stream.of(formattedFn.apply("%s:", List.of(scheme))); } private Stream<UriComponent> hierPart() { return Stream.of( authority.<UriComponent>ifDefinedElse(path::hierPart, path::hierPart) ); } private Stream<UriComponent> formattedQuery() { return query.ifDefinedElse( x -> Stream.of(formattedFn.apply("?%s", List.of(x))), Stream::empty ); } private Stream<UriComponent> formattedFragment() { return fragment.ifDefinedElse( x -> Stream.of(formattedFn.apply("#%s", List.of(x))), Stream::empty ); } @Override public String asString() { return joinedComponents().asString(); } @Override public SchemeComponent scheme() { return scheme; } @Override public AuthorityComponent authority() { return authority; } @Override public PathComponent path() { return path; } @Override public QueryComponent query() { return query; } @Override public FragmentComponent fragment() { return fragment; } private final SchemeComponent scheme; private final AuthorityComponent authority; private final PathComponent path; private final QueryComponent query; private final FragmentComponent fragment; private final BiFunction<String, List<UriComponent>, UriComponent> formattedFn; private final BiFunction<List<UriComponent>, String, UriComponent> joinedFn; private final Function<PathComponent, List<PathSegmentSubcomponent>> normalizedSegmentsFn; }
true
c200235bed41e6af5a475b5bccf21463f266e59e
Java
AyushyaChitransh/oneops
/antenna/src/test/java/com/oneops/antenna/senders/generic/XMPPMsgServiceTest.java
UTF-8
5,060
2.0625
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2015 Walmart, Inc. * <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.oneops.antenna.senders.generic; import com.codahale.metrics.MetricRegistry; import com.oneops.antenna.domain.EmailSubscriber; import com.oneops.notification.NotificationMessage; import com.oneops.notification.NotificationType; import com.oneops.antenna.domain.XMPPSubscriber; import com.oneops.util.URLUtil; import org.mockito.InjectMocks; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.testng.Assert.*; /** * Test case class */ public class XMPPMsgServiceTest { @Spy private MetricRegistry metric = new MetricRegistry(); @InjectMocks private XMPPMsgService svc = new XMPPMsgService(metric); private static final int timeout = Integer.MAX_VALUE; @BeforeClass public void init() { System.setProperty("oneops.url", "https://oneops.com"); MockitoAnnotations.initMocks(this); svc.init(); } @Test public void mutabilityTest() { svc.setBotName("RobotX"); svc.setTimeout(timeout); assertEquals("RobotX", svc.getBotName()); assertEquals(timeout, svc.getTimeout()); } @Test(expectedExceptions = ClassCastException.class) public void negativeCastTest() throws Exception { this.svc.postMessage(new NotificationMessage(), new EmailSubscriber()); } @Test public void postMessageExerciseTest() { svc.setBotName("postMessageExerciseTest"); svc.setTimeout(1); boolean b1 = false; boolean b2 = false; XMPPSubscriber sub1 = new XMPPSubscriber(); sub1.setChatServer("notarealaddressOK"); sub1.setChatPort(9); XMPPSubscriber sub2 = new XMPPSubscriber(); sub2.setChatServer("notarealaddressOK"); sub2.setChatPort(7); try { b1 = svc.postMessage(null, sub1); //illegal argument exception b2 = svc.postMessage(null, sub2); } catch (IllegalArgumentException e) { } assertFalse(b1); assertFalse(b2); } @Test(expectedExceptions = IllegalArgumentException.class) public void postNullMessageTest() { svc.setBotName("postMessageExerciseTest"); svc.setTimeout(1); XMPPSubscriber sub = new XMPPSubscriber(); sub.setChatServer("notarealaddressOK"); sub.setChatPort(9); svc.postMessage(null, sub); } @Test public void linkFormatTest() { String deploymentNsp = "/oneops/forge/cd1/bom"; // https://oneops.com/org/assemblies/forge/transition/environments/paas#summary String deploymentUrlEnd = "https*://\\S+/oneops/assemblies/forge/transition/environments/\\w+#summary"; String repairNsp = "/platform/LMS/prod/bom/LMS/1"; // https://oneops.com/org/assemblies/LMS/operations/environments/prod/platforms/LMS#summary String repairUrlEnd = "https*://\\S+/r/ci/\\w+"; NotificationMessage nMessage = new NotificationMessage(); nMessage.setNsPath(deploymentNsp); nMessage.setType(NotificationType.deployment); URL url = URLUtil.getNotificationUrl(nMessage); assertNotNull(url, "DEPLOYMNENT URL unexpected null in place of a good url for nspath: " + deploymentNsp); assertTrue(url.toString().startsWith("http"), "DEPLOYMNENT URL h-t-t-p " + "are not first letters of this bad URL: " + url); Pattern pattern = Pattern.compile(deploymentUrlEnd); Matcher matcher = pattern.matcher(url.toString()); assertTrue(matcher.matches(), "NSPATH-" + deploymentNsp + " DEPLOYMNENT URL: " + url + " does not match: " + deploymentUrlEnd); //Continue to next type.... nMessage.setNsPath(repairNsp); nMessage.setType(NotificationType.procedure); url =URLUtil.getNotificationUrl(nMessage); assertNotNull(url, "OPERATION URL unexpected null in place of a good url for nspath: " + deploymentNsp); assertTrue(url.toString().startsWith("http"), "OPERATION URL h-t-t-p are not first letters of this bad URL: " + url); pattern = Pattern.compile(repairUrlEnd); matcher = pattern.matcher(url.toString()); assertTrue(matcher.matches(), "NSPATH-" + repairNsp + " OPERATION URL: " + url + " does not match: " + repairUrlEnd); } }
true
9f833f74c2753a88b9a823935929790fc1476d12
Java
Matsv/voxelwind
/api/src/main/java/com/voxelwind/api/game/entities/passive/SnowGolem.java
UTF-8
144
1.640625
2
[ "MIT" ]
permissive
package com.voxelwind.api.game.entities.passive; import com.voxelwind.api.game.entities.Animal; public interface SnowGolem extends Animal { }
true
e2e68ccdb31e132799f04c4e233b2de497030687
Java
DatanewsOrg/datanews-java
/src/main/java/io/datanews/exceptions/DatanewsIOException.java
UTF-8
286
2.265625
2
[ "MIT" ]
permissive
package io.datanews.exceptions; import java.io.IOException; public class DatanewsIOException extends IOException { public DatanewsIOException(String message, Throwable cause) { super(message, cause); } public DatanewsIOException(String message) { super(message); } }
true
24dedcd987dc509a2aed8c7d2bd31f28d57aded4
Java
mjw99/cytospade
/src/main/java/name/mjw/facs/ScaleDefaults.java
UTF-8
7,411
2.59375
3
[]
no_license
/** * ScaleDefaults.java * * * Cytobank (TM) is server and client software for web-based management, analysis, * and sharing of flow cytometry data. * * Copyright (C) 2009 Cytobank, Inc. All rights reserved. * * This program 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Cytobank, Inc. * 659 Oak Grove Avenue #205 * Menlo Park, CA 94025 * * http://www.cytobank.org */ package name.mjw.facs; // Import the scale package import name.mjw.facs.scale.*; /** * <p> * A class containing the default values for the scale parameters of the * different file types. This class is designed to be the bottleneck for the * scale defaults so that any changes to the defaults can be localized to this * class. * </p> * * <p> * This is the embodiment of what Jonathan wishes the scale cofactors and ranges * to be. So if you have problems with them, you should take it up with him. * </p> * * <p> * The default settings for each scale type are as follows: * </p> * * <p> * Linear: * </p> * <ul> * <li>Min: 1</li> * <li>Max: Scale Max Range</li> * <li>Cofactor: 1</li> * </ul> * * <p> * Log: * </p> * <ul> * <li>Min: 1</li> * <li>Max: Scale Max Range</li> * <li>Cofactor: 1</li> * </ul> * * <p> * Arcsinh: * </p> * <ul> * <li>Min: -200</li> * <li>Max: Scale Max Range</li> * <li>Cofactor: 150</li> * </ul> * * <p> * The default scales are determined by whether the channel is stored in log * format and whether the channel should be displayed in log format. If the * channel is stored in log format, as is the case for pre-logged Calibur data, * then the log scale is used. Otherwise, if the channel is not stored in log * format, then whether the channel should be displayed in log format is used to * determine the scale to use. If the channel should be displayed in log format, * then the arcsinh scale is used. Otherwise, the linear scale is used. * </p> */ public final class ScaleDefaults { /** * The constants for the scale defaults */ /** * The default channel minimum to use for the linear scale */ private static final double LINEAR_SCALE_MINIMUM = 1.0d; /** * The default scale argument string to use for the linear scale */ private static final String LINEAR_SCALE_ARGUMENT = "1"; /** * The default channel minimum to use for the log scale */ private static final double LOG_SCALE_MINIMUM = 1.0d; /** * The default scale argument string to use for the log scale */ private static final String LOG_SCALE_ARGUMENT = "1"; /** * The default channel minimum to use for the arcsinh scale */ public static final double ARCSINH_SCALE_MINIMUM_FLUOR = -200.0d; public static final double ARCSINH_SCALE_MINIMUM_CYTOF = -20.0d; /** * The default scale argument string to use for the arcsinh scale */ private static final String ARCSINH_SCALE_ARGUMENT = "150"; /** * <p> * A private constructor to suppress the default constructor so the class * cannot be instantiated. * </p> */ private ScaleDefaults() { } /** * <p> * Returns the default scale for the channel based on whether the channel is * stored in log format in the boolean flag isLog and whether the channel * should be displayed in log format in the boolean flag isLogDisplay. * </p> * * @param isLog * boolean flag indicating whether the channel is stored in log * format. * @param isLogDisplay * boolean flag indicating whether the channel should be * displayed in log format. * @return <code>Scale</code> object to the default scale for the channel. */ public static Scale getDefaultScale(boolean isLog, boolean isLogDisplay) { return Scaling.getScale(ScaleDefaults.getDefaultScaleFlag(isLog, isLogDisplay)); } /** * <p> * Returns the scale type flag of the default scale for the channel based on * whether the channel is stored in log format in the boolean flag isLog and * whether the channel should be displayed in log format in the boolean flag * isLogDisplay. * </p> * * @param isLog * boolean flag indicating whether the channel is stored in log * format. * @param isLogDisplay * boolean flag indicating whether the channel should be * displayed in log format. * @return int scale type flag of the default scale for the channel. */ public static int getDefaultScaleFlag(boolean isLog, boolean isLogDisplay) { if (isLog) { // If the channel is stored in log format, then return the log // scale. return Scaling.LOG; } else { // Otherwise, the channel is not stored in log format, so check // whether the channel should be displayed in log format. if (isLogDisplay) { // If the channel should be displayed in log format, then return // the arcsinh scale. return Scaling.ARCSINH; } else { // Otherwise, return the linear scale. return Scaling.LINEAR; } } } /** * <p> * Returns the default scale argument for the scale with scale type flag * type. * </p> * * @param type * int scale type flag of the scale. * @return <code>ScaleArgument</code> object to the default scale argument * for the scale with scale type flag type. */ public static ScaleArgument getDefaultScaleArgument(int type) { return Scaling.getScaleArgument(type, ScaleDefaults.getDefaultScaleArgumentString(type)); } /** * <p> * Returns the default scale argument string for the scale with scale type * flag type. * </p> * * @param type * int scale type flag of the scale. * @return <code>String</code> default scale argument string for the scale * with scale type flag type. */ public static String getDefaultScaleArgumentString(int type) { // Return the default scale argument string based on the type flag switch (type) { case Scaling.LINEAR: return LINEAR_SCALE_ARGUMENT; case Scaling.LOG: return LOG_SCALE_ARGUMENT; case Scaling.ARCSINH: return ARCSINH_SCALE_ARGUMENT; // Otherwise, return null. default: return null; } } /** * <p> * Returns the default channel minimum for the scale with scale type flag * type. * </p> * * @param type * int scale type flag of the scale. * @return double default channel minimum for the scale with scale type flag * type. */ public static double getDefaultChannelMinimum(int type) { // Return the default channel minimum based on the type flag switch (type) { case Scaling.LINEAR: return LINEAR_SCALE_MINIMUM; case Scaling.LOG: return LOG_SCALE_MINIMUM; case Scaling.ARCSINH: return ARCSINH_SCALE_MINIMUM_FLUOR; // Otherwise, return 1.0d. default: return 1.0d; } } }
true
714721b623215cfadc7987b77fcc6221045cdde5
Java
tomeszmh/Dispatcher
/dispatcher-web/src/main/java/com/carussel/dispatcher/server/Log4jServer.java
UTF-8
2,272
2.46875
2
[]
no_license
package com.carussel.dispatcher.server; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.carussel.dispatcher.repository.ApacheAccessLogRepository; import com.carussel.dispatcher.repository.ApacheErrorLogRepository; @Service public class Log4jServer implements Runnable { private static final Logger logger = LoggerFactory.getLogger(Log4jServer.class); private final int port = 4715; private ServerSocket serverSocket = null; private boolean isAcceptConnections = true; private Log4jServerClient log4jServerClient; @Autowired ApacheAccessLogRepository apacheAccessLogRepository; @Autowired ApacheErrorLogRepository apacheErrorLogRepository; private static int clients = 0; void init() { try { serverSocket = new ServerSocket(port); } catch (IOException e) { logger.error(e.getMessage()); } } @Override public void run() { init(); while (isAcceptConnections) { try { Socket socket = serverSocket.accept(); logger.info("ServerSocket accept."); log4jServerClient = new Log4jServerClient(); log4jServerClient.setApacheLogRepository(apacheAccessLogRepository); log4jServerClient.setApacheErrorLogRepository(apacheErrorLogRepository); log4jServerClient.setSocket(socket); new Thread(log4jServerClient).start(); } catch (IOException e) { logger.error(e.getMessage()); } } while (clients == 0) { try { Thread.sleep(200); } catch (InterruptedException e) { logger.error(e.getMessage()); } } deInit(); }; void deInit() { if (serverSocket != null) { try { serverSocket.close(); logger.info("ServerSocket closed."); } catch (IOException e) { logger.error(e.getMessage()); } } } public synchronized boolean isAcceptConnections() { return isAcceptConnections; } public synchronized void setAcceptConnections(boolean isAcceptConnections) { this.isAcceptConnections = isAcceptConnections; } }
true
a9375f3013f74bff52797ad552b727b2aefa78ee
Java
haoyangt/Projects
/yaoshixi/yaoshixi/src/com/szfore/service/LoginService.java
UTF-8
1,222
2.28125
2
[]
no_license
package com.szfore.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.szfore.mapper.LoginMapper; import com.szfore.mapper.UserBasicInfoMapper; import com.szfore.model.Login; import com.szfore.model.UserBasicInfo; @Repository public class LoginService { @Autowired private LoginMapper loginMapper; @Autowired private UserBasicInfoMapper userBasicInfoMapper; public List<Map<String, Object>> findUserIdsByUsername( List<String> emailList) { if(emailList== null || emailList.isEmpty()){ return new ArrayList<Map<String,Object>>(); } return loginMapper.findUserIdsByUsername(emailList); } public Integer insertLogin(Login login) { if(login == null){ return -1; } loginMapper.insertUser(login); if(login.getId() == 0){ return -1; } UserBasicInfo userBasicInfo = new UserBasicInfo(); userBasicInfo.setUserId(login.getId()); userBasicInfoMapper.insertUserBasicInfo(userBasicInfo); /*Resume resume = new Resume(); resume.setUserId(login.getId()); resumeMapper.insertResume(resume);*/ return login.getId(); } }
true
3d9ee3ed4bc5d65aa236bc9b2bb695479aa9a408
Java
trungquangphan/JavaPF
/src/algorithm/ChuoiLienTiep.java
UTF-8
208
1.960938
2
[]
no_license
package algorithm; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class ChuoiLienTiep { public static void main(String[] args) { int[] arr = {1,2,3}; } }
true
5112480a28755c09208009e7b146b6681c6fae3a
Java
u17207411/Inventario
/src/main/java/pe/com/sistema/servicio/ProveedorService.java
UTF-8
359
1.867188
2
[]
no_license
package pe.com.sistema.servicio; import java.util.List; import pe.com.sistema.domain.Proveedor; public interface ProveedorService { public List<Proveedor> listarProveedores(); public void guardar(Proveedor proveedor); public void eliminar(Proveedor proveedor); public Proveedor encontrarProveedor(Proveedor proveedor); }
true
da761f0120c11b9f70a323be4de53532f8365b1f
Java
eogra7/StyleShare
/app/src/main/java/com/evanogra/styleshare/AuthActivity.java
UTF-8
1,852
1.929688
2
[]
no_license
package com.evanogra.styleshare; import android.support.v4.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.Button; import android.widget.RelativeLayout; import com.firebase.client.Firebase; public class AuthActivity extends AppCompatActivity { private Firebase mFirebase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_auth); LoginFragment loginFragment = new LoginFragment(); FragmentTransaction mFragmentTransaction = getSupportFragmentManager().beginTransaction(); mFragmentTransaction.add(R.id.fragment_container, loginFragment).commit(); getSupportFragmentManager().executePendingTransactions(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_auth, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
true
aabdb66118cec8c937598446055abbff868a3922
Java
antowang/TCamera
/app/src/main/java/com/abcew/camera/gles/GlSurfaceTexture.java
UTF-8
3,099
1.984375
2
[]
no_license
package com.abcew.camera.gles; import android.graphics.SurfaceTexture; import android.opengl.GLES11Ext; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.abcew.camera.ui.acs.Cam; import static android.opengl.GLES20.GL_CLAMP_TO_EDGE; import static android.opengl.GLES20.GL_LINEAR; import static android.opengl.GLES20.GL_NEAREST; import static android.opengl.GLES20.GL_TEXTURE_2D; import static android.opengl.GLES20.GL_TEXTURE_MAG_FILTER; import static android.opengl.GLES20.GL_TEXTURE_MIN_FILTER; import static android.opengl.GLES20.GL_TEXTURE_WRAP_S; import static android.opengl.GLES20.GL_TEXTURE_WRAP_T; import static android.opengl.GLES20.glBindTexture; import static android.opengl.GLES20.glDeleteTextures; import static android.opengl.GLES20.glGenTextures; import static android.opengl.GLES20.glTexParameterf; import static android.opengl.GLES20.glTexParameteri; /** * Created by laputan on 16/11/1. */ public final class GlSurfaceTexture implements PreviewTextureInterface, SurfaceTexture.OnFrameAvailableListener{ @Nullable private SurfaceTexture surfaceTexture; private OnFrameAvailableListener onFrameAvailableListener; private int texName; final int[] textures = new int[1]; public GlSurfaceTexture() { } @Override public void setOnFrameAvailableListener(final OnFrameAvailableListener l) { onFrameAvailableListener = l; } @Override public int getTextureId() { return texName; } public void init() { glGenTextures(textures.length, textures, 0); this.texName = textures[0]; surfaceTexture = new SurfaceTexture(texName); surfaceTexture.setOnFrameAvailableListener(this); } @Override public void release() { if (surfaceTexture != null) { surfaceTexture.release(); surfaceTexture = null; glDeleteTextures(textures.length, textures, 0); } } @Override public int getTextureTarget() { return GLES11Ext.GL_TEXTURE_EXTERNAL_OES; } @Override public void setup(@NonNull final Cam camera) { release(); init(); glBindTexture(getTextureTarget(), texName); glTexParameterf(getTextureTarget(), GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(getTextureTarget(), GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(getTextureTarget(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(getTextureTarget(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); camera.setSurface(surfaceTexture); } @Override public void updateTexImage() { surfaceTexture.updateTexImage(); } @Override public void getTransformMatrix(final float[] mtx) { surfaceTexture.getTransformMatrix(mtx); } @Override public void onFrameAvailable(final SurfaceTexture surfaceTexture) { if (onFrameAvailableListener != null) { onFrameAvailableListener.onFrameAvailable(this); } } }
true
9d47f7c02c4e9ac608ccbf60a8258a24fd3723cc
Java
VelozMarkus/inflection
/src/main/java/ch/liquidmind/inflection/loader/SystemTaxonomyLoader.java
UTF-8
1,166
2.34375
2
[ "Apache-2.0" ]
permissive
package ch.liquidmind.inflection.loader; import ch.liquidmind.inflection.model.AccessType; import ch.liquidmind.inflection.model.compiled.TaxonomyCompiled; import ch.liquidmind.inflection.model.external.Taxonomy; public class SystemTaxonomyLoader extends TaxonomyLoader { public static final String JAVA_LANG = "java.lang"; public static final String CH_LIQUIDMIND_INFLECTION = "ch.liquidmind.inflection"; public static final String TAXONOMY = CH_LIQUIDMIND_INFLECTION + ".Taxonomy"; private static TaxonomyCompiled taxonomy; static { taxonomy = new TaxonomyCompiled( TAXONOMY ); taxonomy.setDefaultAccessType( AccessType.PROPERTY ); } public SystemTaxonomyLoader() { super( null, Thread.currentThread().getContextClassLoader() ); } public SystemTaxonomyLoader( TaxonomyLoader parentTaxonomyLoader, ClassLoader classLoader ) { super( parentTaxonomyLoader, classLoader ); } @Override public Taxonomy findTaxonomy( String name ) { Taxonomy foundTaxonomy = null; if ( name.equals( TAXONOMY ) ) foundTaxonomy = defineTaxonomy( taxonomy ); else foundTaxonomy = super.findTaxonomy( name ); return foundTaxonomy; } }
true
46a773b17e344be88b9a0a02d5aaab34b05483f7
Java
zsigui/SGFrameUtils
/app/src/main/java/com/jackiezhuang/sgframework/utils/http/bean/NetworkResponse.java
UTF-8
1,797
2.265625
2
[]
no_license
package com.jackiezhuang.sgframework.utils.http.bean; import java.io.InputStream; import java.util.Map; /** * 执行网络请求后响应类 * <p></p> * Created by zsigui on 15-9-2. */ public class NetworkResponse { private InputStream mContent; private int mResponseCode; private String mContentType; private String mContentEncoding; private int mContentLength; private long mLastModified; private long mDate; private long mIfModifiedSince; private Map<String, String> mHeaders; public InputStream getContent() { return mContent; } public void setContent(InputStream content) { mContent = content; } public int getResponseCode() { return mResponseCode; } public void setResponseCode(int responseCode) { mResponseCode = responseCode; } public String getContentType() { return mContentType; } public void setContentType(String contentType) { mContentType = contentType; } public String getContentEncoding() { return mContentEncoding; } public void setContentEncoding(String contentEncoding) { mContentEncoding = contentEncoding; } public int getContentLength() { return mContentLength; } public void setContentLength(int contentLength) { mContentLength = contentLength; } public long getLastModified() { return mLastModified; } public void setLastModified(long lastModified) { mLastModified = lastModified; } public long getDate() { return mDate; } public void setDate(long date) { mDate = date; } public long getIfModifiedSince() { return mIfModifiedSince; } public void setIfModifiedSince(long ifModifiedSince) { mIfModifiedSince = ifModifiedSince; } public Map<String, String> getHeaders() { return mHeaders; } public void setHeaders(Map<String, String> headers) { mHeaders = headers; } }
true
8da163448da09d1df3d79a8024882e893a56163e
Java
445759814/converter-file
/converter-file/src/main/java/com/cm/retrofit2/converter/file/FileUtils.java
UTF-8
1,663
2.875
3
[ "Apache-2.0" ]
permissive
package com.cm.retrofit2.converter.file; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import okhttp3.ResponseBody; /** * Created by Cmad on 2016/5/3. */ public class FileUtils { /** * 将文件写入本地 * @param body http响应体 * @param path 保存路径 * @return 保存file */ public static File writeResponseBodyToDisk(ResponseBody body, String path) { File futureStudioIconFile = null; try { futureStudioIconFile = new File(path); InputStream inputStream = null; OutputStream outputStream = null; try { byte[] fileReader = new byte[4096]; inputStream = body.byteStream(); outputStream = new FileOutputStream(futureStudioIconFile); while (true) { int read = inputStream.read(fileReader); if (read == -1) { break; } outputStream.write(fileReader, 0, read); } outputStream.flush(); return futureStudioIconFile; } catch (IOException e) { return futureStudioIconFile; } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } catch (IOException e) { return futureStudioIconFile; } } }
true
04ef4a91a3b13ec39165492b64bd2d03749f49ed
Java
yang00yang/spring-boot-demo
/spring-boot-mvc-demo/src/main/java/com/dragon/study/spring/boot/mvc/service/IHelloWorldService.java
UTF-8
154
1.625
2
[]
no_license
package com.dragon.study.spring.boot.mvc.service; /** * Created by dragon on 16/7/10. */ public interface IHelloWorldService { void helloWorld(); }
true
c486ca131db54c8f1064419bf5ef7e5da1c29ecd
Java
galuszkamarta/selenium-training
/src/test/java/Litecart/model/Item.java
UTF-8
767
2.5625
3
[ "Apache-2.0" ]
permissive
package Litecart.model; /** * Created by m on 2020-02-06. */ public class Item { private String size; private String quantity; public static Litecart.model.Item.Builder newEntity() { return new Litecart.model.Item().new Builder(); } public String getSize() { return size; } public String getQuantity() { return quantity; } public class Builder { private Builder() {} public Litecart.model.Item.Builder withSize(String size) { Litecart.model.Item.this.size = size; return this; } public Litecart.model.Item.Builder withQuantity(String quantity) { Litecart.model.Item.this.quantity = quantity; return this; } public Litecart.model.Item build() {return Litecart.model.Item.this; } } }
true
97e7154c023df3a2ae398217de86a9c8558caf47
Java
ebarnett/anathema
/Lib/src/net/sf/anathema/lib/control/change/IChangeListener.java
UTF-8
175
1.695313
2
[]
no_license
package net.sf.anathema.lib.control.change; import java.util.EventListener; public interface IChangeListener extends EventListener { public void changeOccured(); }
true
1bddc40e629489c2dd886f0f6e8f6007bff213e8
Java
MougLee/runtimeconfig
/src/main/java/si/mougli/runtimeconfig/business/Configurator.java
UTF-8
582
1.914063
2
[]
no_license
/* * 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 si.mougli.runtimeconfig.business; import javax.enterprise.inject.Produces; /** * * @author mougli */ public class Configurator { @Produces public Service getConfiguredService() { // TODO: get values from Database; return RuntimeConfigServlet.CONFIG == 1 ? new ServiceMock(System.currentTimeMillis()) : new ServiceTest(System.currentTimeMillis()); } }
true
13e6058fc05bb3b3eb459f260aed4677a0a69a3a
Java
VirgilSecurity/virgil-sdk-java-android
/sdk/src/main/java/com/virgilsecurity/sdk/cards/Card.java
UTF-8
14,029
1.945313
2
[ "BSD-3-Clause" ]
permissive
/* * Copyright (c) 2015-2020, Virgil Security, Inc. * * Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * (3) Neither the name of virgil nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.virgilsecurity.sdk.cards; import com.virgilsecurity.common.exception.NullArgumentException; import com.virgilsecurity.common.util.Validator; import com.virgilsecurity.sdk.cards.model.RawCardContent; import com.virgilsecurity.sdk.cards.model.RawSignature; import com.virgilsecurity.sdk.cards.model.RawSignedModel; import com.virgilsecurity.sdk.client.exceptions.VirgilCardVerificationException; import com.virgilsecurity.sdk.crypto.VirgilCardCrypto; import com.virgilsecurity.sdk.crypto.VirgilPublicKey; import com.virgilsecurity.sdk.crypto.exceptions.CryptoException; import com.virgilsecurity.sdk.utils.CardUtils; import com.virgilsecurity.sdk.utils.ConvertionUtils; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.logging.Logger; /** * The {@link Card} class is the main entity of Virgil Services. Every user/device is represented * with a Virgil Card which contains a public key and information about identity. */ public class Card { private static final Logger LOGGER = Logger.getLogger(Card.class.getName()); private String identifier; private String identity; private VirgilPublicKey publicKey; private String version; private Date createdAt; private String previousCardId; private Card previousCard; private List<CardSignature> signatures; private boolean isOutdated; private byte[] contentSnapshot; /** * Parse card from provided raw signed model. * * @param cardCrypto The card crypto. * @param cardModel The card model to be parsed. * * @return The card that is parsed from provided {@link RawSignedModel}. * * @throws CryptoException If any crypto operation fails. */ public static Card parse(VirgilCardCrypto cardCrypto, RawSignedModel cardModel) throws CryptoException { if (cardCrypto == null) { throw new NullArgumentException("Card -> 'crypto' should not be null"); } if (cardModel == null) { throw new NullArgumentException("Card -> 'cardModel' should not be null"); } RawCardContent rawCardContent = ConvertionUtils .deserializeFromJson(new String(cardModel.getContentSnapshot()), RawCardContent.class); String cardId = CardUtils.generateCardId(cardCrypto, cardModel.getContentSnapshot()); VirgilPublicKey publicKey = cardCrypto.importPublicKey(ConvertionUtils.base64ToBytes(rawCardContent.getPublicKey())); // Converting RawSignatures to CardSignatures List<CardSignature> cardSignatures = new ArrayList<>(); if (cardModel.getSignatures() != null) { for (RawSignature rawSignature : cardModel.getSignatures()) { CardSignature.CardSignatureBuilder cardSignature = new CardSignature.CardSignatureBuilder( rawSignature.getSigner(), ConvertionUtils.base64ToBytes(rawSignature.getSignature())); if (rawSignature.getSnapshot() != null) { String snapshot = rawSignature.getSnapshot(); Map<String, String> additionalDataSignature = ConvertionUtils .deserializeMapFromJson(ConvertionUtils.base64ToString(snapshot)); cardSignature.snapshot(ConvertionUtils.base64ToBytes(snapshot)); cardSignature.extraFields(additionalDataSignature); } else { LOGGER.info( String.format("Signature '%s' has no additional data", rawSignature.getSigner())); } cardSignatures.add(cardSignature.build()); } } else { throw new VirgilCardVerificationException("Card should have at least self signature"); } return new Card(cardId, rawCardContent.getIdentity(), publicKey, rawCardContent.getVersion(), rawCardContent.getCreatedAtDate(), rawCardContent.getPreviousCardId(), cardSignatures, cardModel.getContentSnapshot()); } /** * Instantiates a new Card. * * @param identifier Uniquely identifies the Card in Virgil Services. * @param identity Unique identity value. * @param publicKey The public key. * @param version The version of Card (ex. "5.0"). * @param createdAt When the Card was created at. * @param signatures The list of signatures. * @param contentSnapshot The card content snapshot. */ public Card(String identifier, String identity, VirgilPublicKey publicKey, String version, Date createdAt, List<CardSignature> signatures, byte[] contentSnapshot) { this.identifier = identifier; this.identity = identity; this.publicKey = publicKey; this.version = version; this.createdAt = createdAt; this.signatures = signatures; this.contentSnapshot = contentSnapshot; } /** * Instantiates a new Card. * * @param identifier Uniquely identifies the Card in Virgil Services. * @param identity Unique identity value. * @param publicKey The public key. * @param version The version of Card (ex. "5.0"). * @param createdAt When the Card was created at. * @param previousCardId The previous Card identifier that current card is used to override. * @param previousCard The previous Card that current card is used to override. * @param signatures The list of signatures. * @param isOutdated Whether the card is overridden by another card. * @param contentSnapshot The card content snapshot. */ public Card(String identifier, String identity, VirgilPublicKey publicKey, String version, Date createdAt, String previousCardId, Card previousCard, List<CardSignature> signatures, boolean isOutdated, byte[] contentSnapshot) { this.identifier = identifier; this.identity = identity; this.publicKey = publicKey; this.version = version; this.createdAt = createdAt; this.previousCardId = previousCardId; this.previousCard = previousCard; this.signatures = signatures; this.isOutdated = isOutdated; this.contentSnapshot = contentSnapshot; } /** * Instantiates a new Card. * * @param identifier Uniquely identifies the Card in Virgil Services. * @param identity Unique identity value. * @param publicKey The public key. * @param version The version of Card (ex. "5.0"). * @param createdAt When the Card was created at. * @param previousCardId The previous Card identifier that current card is used to override. * @param previousCard The previous Card that current card is used to override. * @param signatures The list of signatures. * @param contentSnapshot The card content snapshot. */ public Card(String identifier, String identity, VirgilPublicKey publicKey, String version, Date createdAt, String previousCardId, Card previousCard, List<CardSignature> signatures, byte[] contentSnapshot) { this.identifier = identifier; this.identity = identity; this.publicKey = publicKey; this.version = version; this.createdAt = createdAt; this.previousCardId = previousCardId; this.previousCard = previousCard; this.signatures = signatures; this.contentSnapshot = contentSnapshot; } /** * Instantiates a new Card. * * @param identifier Uniquely identifies the Card in Virgil Services. * @param identity Unique identity value. * @param publicKey The public key. * @param version The version of Card (ex. "5.0"). * @param createdAt When the Card was created at. * @param previousCardId The previous Card identifier that current card is used to override. * @param signatures The list of signatures. * @param contentSnapshot The card content snapshot. */ public Card(String identifier, String identity, VirgilPublicKey publicKey, String version, Date createdAt, String previousCardId, List<CardSignature> signatures, byte[] contentSnapshot) { this.identifier = identifier; this.identity = identity; this.publicKey = publicKey; this.version = version; this.createdAt = createdAt; this.previousCardId = previousCardId; this.signatures = signatures; this.contentSnapshot = contentSnapshot; } // TODO move to builder? /** * Get Card's content snapshot which is representation of {@link RawCardContent}. * * @return The content snapshot as byte [ ]. */ public byte[] getContentSnapshot() { return contentSnapshot; } /** * Gets the date and time fo card creation in UTC. * * @return The created at. */ public Date getCreatedAt() { return createdAt; } /** * Gets the Card identifier that uniquely identifies the Card in Virgil Services. * * @return The Card identifier. */ public String getIdentifier() { return identifier; } /** * Gets the identity value that can be anything which identifies the user in your application. * * @return The identity. */ public String getIdentity() { return identity; } /** * Get previous Card that current card is used to override to. * * @return The previous card. */ public Card getPreviousCard() { return previousCard; } /** * Get previous Card identifier that current card is used to override to. * * @return The previous card id. */ public String getPreviousCardId() { return previousCardId; } /** * Gets the public key. * * @return The public key. */ public VirgilPublicKey getPublicKey() { return publicKey; } /** * Gets raw signed model from current Card. * * @return The {@link RawSignedModel} exported from this Card. */ public RawSignedModel getRawCard() { RawSignedModel cardModel = new RawSignedModel(contentSnapshot); for (CardSignature signature : signatures) { if (signature.getSnapshot() != null) { cardModel .addSignature(new RawSignature(ConvertionUtils.toBase64String(signature.getSnapshot()), signature.getSigner(), ConvertionUtils.toBase64String(signature.getSignature()))); } else { cardModel.addSignature(new RawSignature(signature.getSigner(), ConvertionUtils.toBase64String(signature.getSignature()))); } } return cardModel; } /** * Gets self signature. * * @return The self {@link CardSignature}. * * @throws VirgilCardVerificationException If self signature was not found in signatures list. */ public CardSignature getSelfSignature() throws VirgilCardVerificationException { for (CardSignature cardSignature : signatures) { if (cardSignature.getSigner().equals(SignerType.SELF.getRawValue())) { return cardSignature; } } LOGGER.warning("Card must have self signature"); throw new VirgilCardVerificationException("Card -> card must have 'self' signature"); } /** * Gets a list of signatures. * * @return the signatures */ public List<CardSignature> getSignatures() { return signatures; } /** * Gets the version of the card. * * @return The version. */ public String getVersion() { return version; } @Override public int hashCode() { return Objects.hash(identifier, identity, publicKey, version, createdAt, previousCardId, previousCard, signatures, isOutdated); } /** * Whether the card is overridden by another card. * * @return If the Card is outdated - {@code true}, otherwise {@code false}. */ public boolean isOutdated() { return isOutdated; } /** * Sets Card's content snapshot which is representation of {@link RawCardContent}. * * @param contentSnapshot The content snapshot as byte [ ]. */ public void setContentSnapshot(byte[] contentSnapshot) { this.contentSnapshot = contentSnapshot; } /** * Sets whether the card is overridden by another card. * * @param outdated If the Card is outdated - {@code true}, otherwise {@code false}. */ public void setOutdated(boolean outdated) { isOutdated = outdated; } /** * Set previous Card that current card is used to override to. * * @param previousCard The previous card. */ public void setPreviousCard(Card previousCard) { Validator.checkNullAgrument(previousCard, "Card -> 'previousCard' should not be null"); this.previousCard = previousCard; } }
true
4426f401ad6690ff154aee08bd42889ff54bbb44
Java
diksha16017/assignment4
/app/src/main/java/com/example/ajay/myevent/DisplayMyViewPagerActivity.java
UTF-8
2,240
2.5
2
[]
no_license
package com.example.ajay.myevent; import android.content.Intent; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.Toast; /** * Created by AJAY on 04-Nov-16. */ public class DisplayMyViewPagerActivity extends AppCompatActivity{ // public List<ToDo> todoList = new ArrayList<>(); int position=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_view_pager); // function created to get stored data if (savedInstanceState == null) { Bundle extras = getIntent().getExtras(); if (extras == null) { position = 0; } else { position = extras.getInt("position"); } } else { position = Integer.parseInt((String)savedInstanceState.getSerializable("position")); } //setting adapter to view pager ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); viewPager.setAdapter(new CustomPagerAdapter(this)); viewPager.setCurrentItem(position); } // function created to go to main page on toolbar button public void goToMyHome(View v) { Intent home_screen = new Intent(this,MainActivity.class); startActivity(home_screen); } //function created to delete event from the database public void deleteMyEvent(View view) { String taskTitle = ((TextView) findViewById(R.id.title)).getText().toString(); MyDatabaseHandler dh = new MyDatabaseHandler(this); int res = dh.deleteEvent(taskTitle); if(res>0) { Toast.makeText(this, "Event has been deleted successfully!!!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "No such event is present!!!", Toast.LENGTH_SHORT).show(); } ((TextView) findViewById(R.id.title)).setText(""); ((TextView) findViewById(R.id.details)).setText(""); startActivity(new Intent(this, MainActivity.class)); } }
true
842963ce21e871fc1b0b893aa6d91b746d07e033
Java
rlawpdud301/jdbc_coffee
/src/main/java/jdbc_coffee/jdbc/dao/Coffeedao.java
UTF-8
484
1.945313
2
[]
no_license
package jdbc_coffee.jdbc.dao; import java.sql.SQLException; import java.util.List; import javax.swing.JTextField; import jdbc_coffee.jdbc.dto.Coffee; public interface Coffeedao { List<Coffee> selectCoffeedaoByAll(); int insertCoffeedao(Coffee coffee) throws SQLException; int deleteCoffeedao(Coffee coffee) throws SQLException; int updateCoffeedao(Coffee coffee) throws SQLException; Coffee selectCoffeedaoByCode(Coffee coffee) throws SQLException; }
true
a14b0163a3cd051ff34b7d1ef3bb25d05035bc55
Java
rajneeshgautam75/Z_Project
/src/main/java/com/zephyr_batch_4/stepdefinition/Release_Creation.java
UTF-8
4,587
2.15625
2
[]
no_license
package com.zephyr_batch_4.stepdefinition; import com.zephyr.common.LaunchBrowser; import com.zephyr.generic.Excel_Lib; import com.zephyr.generic.Property_Lib; import com.zephyr.reusablemethods.BasePage; import com.zephyr.reusablemethods.LoginPage; import com.zephyr.reusablemethods.ProjectPage; import com.zephyr.reusablemethods.ReleasePage; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class Release_Creation extends LaunchBrowser{ LaunchBrowser lb; ProjectPage pp; ReleasePage rp; BasePage bp; LoginPage lp; String fileName="Release_Creation"; @Given("^User select the project(\\d+)$") public void user_select_the_project(int arg1) throws Throwable { try { bp=new BasePage(); if(arg1==1) { String projectName=Property_Lib.getPropertyValue(CONFIG_PATH+CONFIG_FILE_DASH,"Normal_Project_1"); pp=new ProjectPage(driver); pp.clickOnLogout(); lp=new LoginPage(driver); String userName=Property_Lib.getPropertyValue(CONFIG_PATH+CONFIG_FILE_DASH,"Lead_Username_1"); String passWord=Property_Lib.getPropertyValue(CONFIG_PATH+CONFIG_FILE_DASH,"Lead_Password_1"); lp.enterUnameAndPassword(userName, passWord); pp.selectProject(projectName); } else if(arg1==2) { String projectName=Property_Lib.getPropertyValue(CONFIG_PATH+CONFIG_FILE_DASH,"Normal_Project_2"); pp=new ProjectPage(driver); pp.selectProject(projectName); } else if(arg1==3) { String projectName=Property_Lib.getPropertyValue(CONFIG_PATH+CONFIG_FILE_DASH,"Restricted_Project_1"); pp=new ProjectPage(driver); pp.selectProject(projectName); } else if(arg1==4) { String projectName=Property_Lib.getPropertyValue(CONFIG_PATH+CONFIG_FILE_DASH,"Restricted_Project_2"); pp=new ProjectPage(driver); pp.selectProject(projectName); } else if(arg1==5) { String projectName=Property_Lib.getPropertyValue(CONFIG_PATH+CONFIG_FILE_DASH,"Isolated_Project_1"); pp=new ProjectPage(driver); pp.selectProject(projectName); } } catch(Exception e) { lb=new LaunchBrowser(); lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User create a release for all the projects$") public void user_create_a_release_for_all_the_projects() throws Throwable { try { rp=new ReleasePage(driver); //tp=new TestPlanningPage(driver); bp.waitForElement(); rp.clickOnManageRelease(); bp.waitForElement(); String releaseName=Property_Lib.getPropertyValue(CONFIG_PATH+CONFIG_FILE_DASH,"Release_2"); boolean res=rp.checkAvailableRelease(releaseName); if(res==false) { //String releaseName=Excel_Lib.getData(INPUT_PATH, "Releases", 2,0); String Hide=Excel_Lib.getData(INPUT_PATH, "Requirements", 100,100); String Desc=Excel_Lib.getData(INPUT_PATH, "Requirements", 100,100); String MapexternalDefect=Excel_Lib.getData(INPUT_PATH, "Requirements", 100,100); rp.addNewRelease(releaseName, Desc, Hide, MapexternalDefect); String syear=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH, "Projects", 0, 2)); String smonth=Excel_Lib.getData(INPUT_PATH, "Projects", 0, 3); String sday=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH, "Projects", 0, 4)); String eyear=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH, "Projects", 0, 5)); String emonth=Excel_Lib.getData(INPUT_PATH, "Projects", 0, 6); String eday=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH, "Projects", 0, 7)); rp.enterStartDatAndEndDateForRelease(syear, smonth, sday, eyear, emonth, eday); //rp.enterStartDatAndEndDate(syear, smonth, sday, eyear, emonth, eday); rp.clickOnAdd(); } } catch(Exception e) { lb=new LaunchBrowser(); lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @Then("^release is created for all projects$") public void release_is_created_for_all_projects() throws Throwable { try { log.info("release is created for all projects"); } catch(Exception e) { lb=new LaunchBrowser(); lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } }
true
f049bb123f48435df5f9313e18c79cbc47acccbc
Java
gurramleelabhavani/DesignPatterns
/src/main/java/com/vvit/bike/App.java
UTF-8
1,520
3.5625
4
[]
no_license
package com.vvit.bike; import java.util.logging.Logger; import java.util.logging.Level; interface Bike { public void assemble(); } class BasicBike implements Bike { public void assemble() { System.out.print("Basic Bike."); } } class BikeDecorator implements Bike { protected Bike bike; public BikeDecorator(Bike c){ this.bike=c; } public void assemble() { this.bike.assemble(); } } class SportsBike extends BikeDecorator { public SportsBike(Bike c) { super(c); } public void assemble(){ super.assemble(); System.out.print(" Adding features of Sports Bike."); } } class LuxuryBike extends BikeDecorator { public LuxuryBike(Bike c) { super(c); } public void assemble(){ super.assemble(); System.out.print(" Adding features of Luxury Bike."); } } public class App { private static final Logger l=Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); public static void main( String[] args ) { l.log(Level.INFO,"use of memento behaviour pattern and decorate structural pattern"); Bike sportsBike = new SportsBike(new BasicBike()); Bike lC=new LuxuryBike(new BasicBike()); sportsBike.assemble(); lC.assemble(); System.out.println("\n*****"); Bike sportsLuxuryBike = new SportsBike(new LuxuryBike(new BasicBike())); sportsLuxuryBike.assemble(); l.log(Level.INFO,"program terminated"); } }
true
91ae1bec991b986d5ce16a3c57d658eae727e987
Java
kamaludin21/Perumahan
/app/src/main/java/inc/mtwo/perumahan/Model/Order.java
UTF-8
444
2.046875
2
[]
no_license
package inc.mtwo.perumahan.Model; import com.google.gson.annotations.SerializedName; public class Order { @SerializedName("iduser") private String Iduser; @SerializedName("blok") private String Blok; @SerializedName("harga") private String Harga; public String getIduser() { return Iduser; } public String getBlok() { return Blok; } public String getHarga() { return Harga; } }
true
358a0742710e9ffaafcdfa61dc4749487c2c550d
Java
radjel/battleshipgame
/src/Battleship/SetShips.java
UTF-8
3,434
2.875
3
[]
no_license
package Battleship; import java.util.Random; import Battleship.*; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class SetShips extends Application { private Stage stage; public final int board_size =16; Cell[][] cell = new Cell [16][16]; final static ships[] ships; static { ships = new ships[] { new ships("Carrier", shipSize.Carrier),//makes the kind of ships we want to place new ships("Battleship", shipSize.Battleship), new ships("Cruiser", shipSize.Cruiser), new ships("Submarine", shipSize.Submarine), new ships("Destroyer", shipSize.Destroyer) };} public class Cell extends Pane{ public Cell() { setStyle("-fx-border-color:black");//makes the border of the boxes black this.setPrefSize(2000, 2000);} } @Override public void start(Stage primaryStage) { stage = primaryStage; Scene scene = StartGame1(); primaryStage.setResizable(false); primaryStage.setTitle("battleship"); primaryStage.setScene(scene); primaryStage.show(); } public Scene StartGame1() { Pane root = new Pane(); Button start = new Button("Start Player 1"); start.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent t) { stage.setScene(placeShipsOnBoard()); }}); root.getChildren().add(start); return new Scene(root); } public Scene placeShipsOnBoard(){ Random rnd = new Random(); GridPane pane = new GridPane(), temp = new GridPane(); Label instruction = new Label("Place ships:"); Button b1 = new Button("Click for randomized ships"); Button b2 = new Button("Done"); HBox t = new HBox(instruction, b1, b2); for(int i =0; i<16; i++) { for (int j=0; j<16; j++) { pane.add(cell[i][j]=new Cell(), j, i); }} temp = pane; EventHandler<ActionEvent> again2 = new EventHandler<ActionEvent>(){ public void handle(ActionEvent z) { stage.setScene(placeShipsOnBoard());}}; BorderPane edge = new BorderPane(); edge.setCenter(pane); edge.setTop(t); Scene scene = new Scene(edge,640,640); b1.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent a) { int randRow, randCol, length; for(int i =0; i<5; i++) { length=ships[i].getSize(); int randDirection = rnd.nextInt(2); if(randDirection == 1) { randRow = rnd.nextInt(16); randCol = rnd.nextInt(16-length); for(int j=randCol; j<randCol+length;j++) { pane.getChildren().remove(cell[randRow][j]);} pane.add(ships[i].rectangle(length*40, 40), randCol, randRow, length, 1);} else { randRow = rnd.nextInt(16-length); randCol = rnd.nextInt(16); for(int j=randRow; j<randRow+length;j++) { pane.getChildren().remove(cell[j][randCol]);} pane.add(ships[i].rectangle(40, length*40), randCol, randRow, 1, length);}} Button again = new Button("tryagain?"); again.setOnAction(again2); t.getChildren().remove(b1); t.getChildren().add(1, again); } }); b2.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent t) { stage.setScene(scene); stage.hide();}}); return scene; } public static void main(String[] args) { Application.launch(args);} }
true
af4ca4025f06f00555b4f352b1c492b4d5dea041
Java
laurita/SimilaritySearch-project
/src/algorithms/RNN.java
UTF-8
1,184
3.5625
4
[]
no_license
package algorithms; import java.util.ArrayList; public class RNN { // reference: // http://cgi.cse.unsw.edu.au/~macheema/thesis/node22.html // find the matches public static ArrayList<int[]> match(double[][] matrix) { ArrayList<int[]> result = new ArrayList<int[]>(); for (int i = 0; i < matrix.length; i++) { // find the minimum value in the current row // and the corresponding column double min = 1; double min2 = 1; // the second smallest entry int pos = 0; for (int j = 0; j < matrix[0].length; j++) { if (min >= matrix[i][j]) { min2 = min; min = matrix[i][j]; pos = j; } } // check that the minimum value is unique if (min < min2) { // loop through the column and find the minimum value boolean isRNN = true; for (int x = 0; x < matrix.length; x++) { // if value is smaller or equal, the minimum is not // the unique minimum value in this column if ((min >= matrix[x][pos]) && (x != i)) { isRNN = false; break; } } // check if we need to add to result if (isRNN) { result.add(new int[]{i,pos}); } } } return result; } }
true
d0bc28de9052a48c473c0d479b615bcead17a7f0
Java
rjjrrjjr/demo-sc
/sc-api/src/main/java/com/rj/model/Dept.java
UTF-8
542
1.921875
2
[]
no_license
package com.rj.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; /** * @author ruanjin * @since 2019/5/9 20:54 */ @Data @NoArgsConstructor @AllArgsConstructor @Accessors(chain = true) public class Dept { private Long deptNo; //主键 private String deptName; //部门名称 private String dbSource;//来自那个数据库,因为微服务架构可以一个服务对应一个数据库,同一个信息被存储到不同数据库 }
true