blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
332
content_id
stringlengths
40
40
detected_licenses
listlengths
0
50
license_type
stringclasses
2 values
repo_name
stringlengths
7
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
557 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
77.7k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
82 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
5.41M
extension
stringclasses
11 values
content
stringlengths
7
5.41M
authors
listlengths
1
1
author
stringlengths
0
161
6c6ee1e60b5a54356242b57d393952f14cfea227
e11ff8482d5c8c32cfb1934b81ebda936bed25f5
/ethereum/statetransition/src/test/java/tech/pegasys/teku/statetransition/attestation/AggregatingAttestationPoolTest.java
6cbf840116eefd6af65755dc52c23db70a5f685c
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
mark-terry/artemis
dc191a5888a549c9411a3e50da462d7ca3b55590
22e68acfdc419d1e5546c8b7ef32cc251e522b07
refs/heads/master
2021-01-03T04:13:27.754846
2020-06-10T01:04:13
2020-06-10T01:04:13
239,917,632
0
0
Apache-2.0
2020-04-15T01:16:56
2020-02-12T03:20:51
Java
UTF-8
Java
false
false
9,238
java
/* * Copyright 2020 ConsenSys AG. * * 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 tech.pegasys.teku.statetransition.attestation; import static com.google.common.primitives.UnsignedLong.ONE; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static tech.pegasys.teku.statetransition.attestation.AggregatorUtil.aggregateAttestations; import static tech.pegasys.teku.util.config.Constants.ATTESTATION_RETENTION_EPOCHS; import static tech.pegasys.teku.util.config.Constants.SLOTS_PER_EPOCH; import com.google.common.primitives.UnsignedLong; import java.util.Optional; import java.util.stream.IntStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import tech.pegasys.teku.core.BlockAttestationDataValidator; import tech.pegasys.teku.core.BlockAttestationDataValidator.AttestationInvalidReason; import tech.pegasys.teku.datastructures.attestation.ValidateableAttestation; import tech.pegasys.teku.datastructures.operations.Attestation; import tech.pegasys.teku.datastructures.operations.AttestationData; import tech.pegasys.teku.datastructures.state.BeaconState; import tech.pegasys.teku.datastructures.util.DataStructureUtil; import tech.pegasys.teku.ssz.SSZTypes.Bitlist; import tech.pegasys.teku.util.config.Constants; class AggregatingAttestationPoolTest { public static final UnsignedLong SLOT = UnsignedLong.valueOf(1234); private final DataStructureUtil dataStructureUtil = new DataStructureUtil(); private final BlockAttestationDataValidator attestationDataValidator = mock(BlockAttestationDataValidator.class); private final AggregatingAttestationPool aggregatingPool = new AggregatingAttestationPool(attestationDataValidator); @AfterEach public void tearDown() { Constants.setConstants("minimal"); } @Test public void createAggregateFor_shouldReturnEmptyWhenNoAttestationsMatchGivenData() { final Optional<ValidateableAttestation> result = aggregatingPool.createAggregateFor(dataStructureUtil.randomAttestationData()); assertThat(result).isEmpty(); } @Test public void createAggregateFor_shouldAggregateAttestationsWithMatchingData() { final AttestationData attestationData = dataStructureUtil.randomAttestationData(); final Attestation attestation1 = addAttestationFromValidators(attestationData, 1, 3, 5); final Attestation attestation2 = addAttestationFromValidators(attestationData, 2, 4, 6); final Optional<ValidateableAttestation> result = aggregatingPool.createAggregateFor(attestationData); assertThat(result.map(ValidateableAttestation::getAttestation)) .contains(aggregateAttestations(attestation1, attestation2)); } @Test public void createAggregateFor_shouldReturnBestAggregateForMatchingDataWhenSomeOverlap() { final AttestationData attestationData = dataStructureUtil.randomAttestationData(); final Attestation attestation1 = addAttestationFromValidators(attestationData, 1, 3, 5, 7); final Attestation attestation2 = addAttestationFromValidators(attestationData, 2, 4, 6, 8); addAttestationFromValidators(attestationData, 2, 3, 9); final Optional<ValidateableAttestation> result = aggregatingPool.createAggregateFor(attestationData); assertThat(result.map(ValidateableAttestation::getAttestation)) .contains(aggregateAttestations(attestation1, attestation2)); } @Test public void getAttestationsForBlock_shouldReturnEmptyListWhenNoAttestationsAvailable() { when(attestationDataValidator.validateAttestation(any(), any())).thenReturn(Optional.empty()); assertThat(aggregatingPool.getAttestationsForBlock(dataStructureUtil.randomBeaconState())) .isEmpty(); } @Test public void getAttestationsForBlock_shouldNotIncludeAttestationsWhereDataDoesNotValidate() { addAttestationFromValidators(dataStructureUtil.randomAttestationData(), 1); addAttestationFromValidators(dataStructureUtil.randomAttestationData(), 2); addAttestationFromValidators(dataStructureUtil.randomAttestationData(), 3); when(attestationDataValidator.validateAttestation(any(), any())) .thenReturn(Optional.of(AttestationInvalidReason.SLOT_NOT_IN_EPOCH)); assertThat(aggregatingPool.getAttestationsForBlock(dataStructureUtil.randomBeaconState())) .isEmpty(); } @Test public void getAttestationsForBlock_shouldIncludeAttestationsThatPassValidation() { final Attestation attestation1 = addAttestationFromValidators(dataStructureUtil.randomAttestationData(), 1); final Attestation attestation2 = addAttestationFromValidators(dataStructureUtil.randomAttestationData(), 2); final Attestation attestation3 = addAttestationFromValidators(dataStructureUtil.randomAttestationData(), 3); final BeaconState state = dataStructureUtil.randomBeaconState(); when(attestationDataValidator.validateAttestation(state, attestation1.getData())) .thenReturn(Optional.of(AttestationInvalidReason.SLOT_NOT_IN_EPOCH)); when(attestationDataValidator.validateAttestation(state, attestation2.getData())) .thenReturn(Optional.empty()); when(attestationDataValidator.validateAttestation(state, attestation3.getData())) .thenReturn(Optional.empty()); assertThat(aggregatingPool.getAttestationsForBlock(state)) .containsExactlyInAnyOrder(attestation2, attestation3); } @Test public void getAttestationsForBlock_shouldAggregateAttestationsWhenPossible() { final AttestationData attestationData = dataStructureUtil.randomAttestationData(); final Attestation attestation1 = addAttestationFromValidators(attestationData, 1, 2); final Attestation attestation2 = addAttestationFromValidators(attestationData, 3, 4); assertThat(aggregatingPool.getAttestationsForBlock(dataStructureUtil.randomBeaconState())) .containsExactly(aggregateAttestations(attestation1, attestation2)); } @Test public void getAttestationsForBlock_shouldIncludeAttestationsWithDifferentData() { final AttestationData attestationData = dataStructureUtil.randomAttestationData(); final Attestation attestation1 = addAttestationFromValidators(attestationData, 1, 2); final Attestation attestation2 = addAttestationFromValidators(attestationData, 3, 4); final Attestation attestation3 = addAttestationFromValidators(dataStructureUtil.randomAttestationData(), 3, 4); assertThat(aggregatingPool.getAttestationsForBlock(dataStructureUtil.randomBeaconState())) .containsExactlyInAnyOrder(aggregateAttestations(attestation1, attestation2), attestation3); } @Test public void getAttestationsForBlock_shouldNotAddMoreAttestationsThanAllowedInBlock() { final BeaconState state = dataStructureUtil.randomBeaconState(); Constants.MAX_ATTESTATIONS = 2; final AttestationData attestationData = dataStructureUtil.randomAttestationData(); final Attestation attestation1 = addAttestationFromValidators(attestationData, 1, 2, 3, 4); final Attestation attestation2 = addAttestationFromValidators(attestationData, 2, 5); // Won't be included because of the 2 attestation limit. addAttestationFromValidators(attestationData, 2); assertThat(aggregatingPool.getAttestationsForBlock(state)) .containsExactly(attestation1, attestation2); } @Test public void onSlot_shouldPruneAttestationsMoreThanTwoEpochsBehindCurrentSlot() { final AttestationData pruneAttestationData = dataStructureUtil.randomAttestationData(SLOT); final AttestationData preserveAttestationData = dataStructureUtil.randomAttestationData(SLOT.plus(ONE)); addAttestationFromValidators(pruneAttestationData, 1); final Attestation preserveAttestation = addAttestationFromValidators(preserveAttestationData, 2); aggregatingPool.onSlot( pruneAttestationData .getSlot() .plus(UnsignedLong.valueOf(SLOTS_PER_EPOCH * ATTESTATION_RETENTION_EPOCHS)) .plus(ONE)); assertThat(aggregatingPool.getAttestationsForBlock(dataStructureUtil.randomBeaconState())) .containsOnly(preserveAttestation); } private Attestation addAttestationFromValidators( final AttestationData data, final int... validators) { final Bitlist bitlist = new Bitlist(20, Constants.MAX_VALIDATORS_PER_COMMITTEE); IntStream.of(validators).forEach(bitlist::setBit); final Attestation attestation = new Attestation(bitlist, data, dataStructureUtil.randomSignature()); aggregatingPool.add(ValidateableAttestation.fromSingle(attestation)); return attestation; } }
7308664aaeb5170920605b15a76186fca59e6386
5f422f2e9b370ebe301b8f79deb4dfc34452b592
/Kattis/src/kattis_trollhunt.java
67817a5179ad7bfa6c15213586b8d2c7a02fc570
[]
no_license
trafalgarandre/Kattis
1a702e4ef01faf017141a35097a3107bfb517ca2
01dda4ffbf30ae1be9613d20130165d72f9f8d1d
refs/heads/master
2020-04-09T08:40:21.845450
2019-02-20T16:17:23
2019-02-20T16:17:23
160,203,644
0
0
null
null
null
null
UTF-8
Java
false
false
643
java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class kattis_trollhunt { public static void main(String args[]) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); int b = Integer.parseInt(tokenizer.nextToken()); int k = Integer.parseInt(tokenizer.nextToken()); int g = Integer.parseInt(tokenizer.nextToken()); int group = k / g; int days = 0; while (b > 1) { days++; b -= group; } System.out.println(days); } }
b236b6434bf45d676f618653e04a0372ce26cb3c
4d4cc1d1ddadcf1b416a9c3d9b69046e9d4b2f20
/src/com/sys/service/school/IndexImageService.java
ed1ecff90ba8cef32ae6536dcf4df9a02272e98c
[]
no_license
zfaster/schoolFriend
9ba36780f708e6ed11012ef226504b37e5a0d953
cf64a7f467178cd1eddb64adcb3300fa238db931
refs/heads/master
2021-01-18T22:20:55.814645
2017-04-03T07:09:19
2017-04-03T07:09:19
87,046,727
0
0
null
null
null
null
UTF-8
Java
false
false
205
java
package com.sys.service.school; import com.sys.bean.school.IndexImage; import com.sys.bean.school.Student; import com.sys.service.base.DAO; public interface IndexImageService extends DAO<IndexImage> { }
e3006fe07e617ae16e5ed64a7cc449f3461a205a
b546dcdf6addb142a90a68fbba472e8e291d34df
/app/src/main/java/net/named_data/jndn/encrypt/ProducerDb.java
9b50c1326d2e9215cf6d17ac228695a874849d3b
[]
no_license
gujianxiao/SN-android
1915886af8a8637842f753ad653420a7bb63e2ce
854035db93e00ea58492f08f5fab649f1ee87f72
refs/heads/master
2021-01-19T12:03:39.046429
2017-06-15T07:25:07
2017-06-15T07:25:07
68,998,756
0
0
null
null
null
null
UTF-8
Java
false
false
3,558
java
/** * Copyright (C) 2015-2016 Regents of the University of California. * @author: Jeff Thompson <[email protected]> * @author: From ndn-group-encrypt src/producer-db https://github.com/named-data/ndn-group-encrypt * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * A copy of the GNU Lesser General Public License is in the file COPYING. */ package net.named_data.jndn.encrypt; import net.named_data.jndn.util.Blob; /** * ProducerDb is an abstract base class for the storage of keys for the producer. It * contains one table that maps time slots (to the nearest hour) to the content * key created for that time slot. A subclass must implement the methods. For * example, see Sqlite3ProducerDb. * @note This class is an experimental feature. The API may change. */ public abstract class ProducerDb { /** * ProducerDb.Error extends Exception for errors using ProducerDb methods. * Note that even though this is called "Error" to be consistent with the * other libraries, it extends the Java Exception class, not Error. */ public static class Error extends Exception { public Error(String message) { super(message); } } /** * Check if a content key exists for the hour covering timeSlot. * @param timeSlot The time slot as milliseconds since Jan 1, 1970 UTC. * @return True if there is a content key for timeSlot. * @throws ProducerDb.Error for a database error. */ public abstract boolean hasContentKey(double timeSlot) throws ProducerDb.Error; /** * Get the content key for the hour covering timeSlot. * @param timeSlot The time slot as milliseconds since Jan 1, 1970 UTC. * @return A Blob with the encoded key. * @throws ProducerDb.Error if there is no key covering timeSlot or other * database error. */ public abstract Blob getContentKey(double timeSlot) throws ProducerDb.Error; /** * Add key as the content key for the hour covering timeSlot. * @param timeSlot The time slot as milliseconds since Jan 1, 1970 UTC. * @param key The encoded key. * @throws ProducerDb.Error if a key for the same hour already exists in the * database, or other database error. */ public abstract void addContentKey(double timeSlot, Blob key) throws ProducerDb.Error; /** * Delete the content key for the hour covering timeSlot. If there is no key * for the time slot, do nothing. * @param timeSlot The time slot as milliseconds since Jan 1, 1970 UTC. * @throws ProducerDb.Error for a database error. */ public abstract void deleteContentKey(double timeSlot) throws ProducerDb.Error; /** * Get the hour-based time slot. * @param timeSlot The time slot as milliseconds since Jan 1, 1970 UTC. * @return The hour-based time slot as hours since Jan 1, 1970 UTC. */ protected static int getFixedTimeSlot(double timeSlot) { return (int)Math.floor(Math.round(timeSlot) / 3600000.0); } }
1a61888c24624829b081c9729f333f994a63094b
1b1f3d51a3465bddbb88ce046a757c17095038d7
/Unit 6/Unit 6 Assessment/Deletion/TestCandidate8.java
b05fda6bd2ab0556903caf604fd1ce19d01e39db
[]
no_license
Deblob12/AP-CS
5441692eedf852bcaad4f3f52374a9013d97cb05
e1c6170d3492977c20e316e79baf11ee0a8b9d37
refs/heads/master
2020-04-10T15:47:48.979263
2018-12-10T06:04:26
2018-12-10T06:04:26
161,123,245
0
0
null
null
null
null
UTF-8
Java
false
false
4,435
java
import java.util.*; /** * Write a description of class TestCandidate here. * Candidate tester class using ArrayLists and replacing elements and inserting elements and deleting elements * @author (Jeffrey Chiu) * @version (06/04/18) */ public class TestCandidate8 { public static void printVotes(List<Candidate> c){ System.out.println("Results per candidate: "); System.out.println("-----------------------"); for(int i = 0; i < c.size(); i++){ System.out.println(c.get(i)); } } public static void replaceName(List<Candidate> c, String find, String replace){ for(int i = 0; i < c.size(); i++){ if(c.get(i).getName().equals(find)){ c.get(i).setName(replace); } } } public static void replaceVotes(List<Candidate> c, String find, int replace){ for(int i = 0; i < c.size(); i++){ if(c.get(i).getName().equals(find)){ c.get(i).setVotes(replace); } } } public static void replaceCandidate(List<Candidate> c, String find, String replace, int newVote){ for(int i = 0; i < c.size(); i++){ if(c.get(i).getName().equals(find)){ c.get(i).setName(replace); c.get(i).setVotes(newVote); } } } public static int getTotal(List<Candidate> c){ int sum = 0; for(int i = 0; i < c.size(); i++){ sum = sum + c.get(i).getVotes(); } return sum; } public static void printResults(List<Candidate> c){ String can = "Candidate"; String vr = "Votes Received"; String tv = "% of Total Votes"; int sum = getTotal(c); System.out.format("%-15s", can); System.out.format("%-15s", vr); System.out.format("%-15s", tv); System.out.println(); for(int i = 0; i < c.size(); i++){ System.out.format("%-15s", c.get(i).getName()); System.out.format("%-15d", c.get(i).getVotes()); System.out.format("%-15d", Math.round((c.get(i).getVotes()*100)/(double)sum)); System.out.println(); } System.out.println(); System.out.println("Total number of votes in election: " + sum); } public static List<Candidate> insertPosition(List<Candidate> c1, String name, int votes, int index){ c1.add(index, new Candidate(name, votes)); return c1; } public static List<Candidate> insertCandidate(List<Candidate> c1, String name, String name2, int votes){ int index = -1; for(Candidate c : c1){ if(c.getName().equals(name)){ index = c1.indexOf(c); } } if(index >= 0){ c1.add(index, new Candidate(name2, votes)); } return c1; } public static List<Candidate> deleteByLoc(List<Candidate> c1, int loc){ c1.remove(loc); return c1; } public static List<Candidate> deleteByName(List<Candidate> c1, String name){ int loc = -1; for(Candidate c : c1){ if(c.getName().equals(name)){ loc = c1.indexOf(c); } } if(loc >= 0){ c1.remove(loc); } return c1; } public static void main(String[] args){ List<Candidate> election = new ArrayList<Candidate>(); election.add(new Candidate("John Smith",5000 )); election.add(new Candidate("Mary Miller",4000 )); election.add(new Candidate("Micheal Duffy", 6000 )); election.add(new Candidate("Tom Robinson", 2500 )); election.add(new Candidate("Joe Ashtony", 1800 )); election.add(new Candidate("Mickey Jones", 3000)); election.add(new Candidate("Rebecca Morgan", 2000)); election.add(new Candidate("Kathleen Turner", 8000)); election.add(new Candidate("Tory Parker", 500)); election.add(new Candidate("Ashton Davis", 10000)); System.out.println("Original results: "); printResults(election); System.out.println("Delete location 6: "); election = deleteByLoc(election, 6); printResults(election); System.out.println(); System.out.println("Delete Kathleen Turner: "); election = deleteByName(election, "Kathleen Turner"); printResults(election); System.out.println(); } }
061d9a7e50265f336b2750777101a459c63e77ce
16cee9537c176c4b463d1a6b587c7417cb8e0622
/src/main/java/ioreadbytes/ByteChecker.java
aaca4ffc815e21861af3455953957588aaa7a519
[]
no_license
ipp203/training-solutions
23c1b615965326e6409fee2e3b9616d6bc3818bb
8f36a831d25f1d12097ec4dfb089128aa6a02998
refs/heads/master
2023-03-17T10:01:32.154321
2021-03-04T22:54:12
2021-03-04T22:54:12
308,043,249
0
0
null
null
null
null
UTF-8
Java
false
false
699
java
package ioreadbytes; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; public class ByteChecker { public int readBytesAndFindAs(String fileName) { int sum = 0; try (InputStream inputStream = new BufferedInputStream(ByteChecker.class.getResourceAsStream("/ioreadbytes/" + fileName))) { int size; byte[] bytes = new byte[50]; while ((size = inputStream.read(bytes)) > 0) { sum += size; } } catch (IOException ioe) { throw new IllegalStateException("", ioe); } return sum; } }
b0286e8f4015c489effb1aa36d71645d28bd8768
df12d5b8adf2172b4ab02dd2e9ef7a7232599f31
/app/src/main/java/com/peter/demo/model/xml/Person.java
1617328f023cae73d51b2be8a565a3e3550faffc
[]
no_license
peter-song/Sample
02dc76da754e39e4296abda4b0062d568d092203
6a1ecec11102625cb9b5798a06920223310a20ec
refs/heads/master
2021-06-23T00:18:12.709834
2017-02-16T03:54:34
2017-02-16T03:54:34
56,287,148
0
0
null
null
null
null
UTF-8
Java
false
false
1,027
java
package com.peter.demo.model.xml; /** * Created by songzhongkun on 16/2/25 15:00. */ public class Person { private Integer id; private String name; private Short age; public Person() { } public Person(String name, Short age) { this.name = name; this.age = age; } public Person(Integer id, String name, Short age) { this.id = id; this.name = name; this.age = age; } 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 Short getAge() { return age; } public void setAge(Short age) { this.age = age; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
65096d7597f17865c495d5ddf9147afdb5724fa1
cd49e08440c105a315a5a7b532d12252a8df3151
/aiTest/src/basic/TextToSpeechTest.java
942abf9fbce596ae54aa7715d053d98b57e2c618
[]
no_license
jegyeong/highJava
169f124c2fafa3de190b78670c07814c26fb6844
8d42fa7639d0e2a26fbea5e40773ca1632264544
refs/heads/master
2022-12-08T07:54:11.398771
2020-08-20T05:03:58
2020-08-20T05:03:58
288,878,496
1
0
null
null
null
null
UTF-8
Java
false
false
2,752
java
package basic; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import com.ibm.cloud.sdk.core.security.IamAuthenticator; import com.ibm.watson.text_to_speech.v1.TextToSpeech; import com.ibm.watson.text_to_speech.v1.model.SynthesizeOptions; import com.ibm.watson.text_to_speech.v1.model.Voices; import com.ibm.watson.text_to_speech.v1.util.WaveUtils; /* IBM Text To Speech 서비스는 IBM의 음성합성기능을 사용하여 다양한 언어, 방언 및 음성으로 텍스트를 자연스러운 발음으로 함성하는 API를 제공한다. 이 서비스는 각 언어에 대한 남성 또는 여성, 때로는 둘 다 지원한다. */ public class TextToSpeechTest { String API_KEY = "iHAn8JS55_iiZoqEbuC9ewL_P_JZf99S5LUloNe2bhuU"; String URL = "https://api.us-south.text-to-speech.watson.cloud.ibm.com/instances/63d48ede-9876-4e37-9d14-f4b5c45b8fc9"; String dir = "d:/d_other/"; // 저장될 폴더 String filename = "voiceResult.wav"; // 저장될 파일이름 // TextToSpeech서비스 객체 변수 선언 TextToSpeech service; // 서비스 설정 public void setService() { IamAuthenticator auth = new IamAuthenticator(API_KEY); service = new TextToSpeech(auth); service.setServiceUrl(URL); } // 왓슨에서 제공하는 음성 목록 public void getVoiceList(){ Voices voices = service.listVoices().execute().getResult(); System.out.println(voices); } // 서비스 실행 public void executeSevice() { try { // 옵션 설정 SynthesizeOptions synOptions = new SynthesizeOptions.Builder() // 실행할 Text 문장 //.text("Hello my name is Lisa. Nice to meet you!") .text("안녕하세요 제 이름은 영미입니다. 만나서 반가워요!!") .accept("audio/wav") // 저장할 Audio파일 종류 설정 //.voice("en-US_LisaV2Voice") // Voice 설정(영문) .voice("ko-KR_YoungmiVoice") // Voice 설정(한글) .build(); // 실행한 결과를 Audio파일로 저장하기 InputStream is = service.synthesize(synOptions).execute().getResult(); InputStream in = WaveUtils.reWriteWaveHeader(is); String fullFilename = dir + filename; OutputStream out = new FileOutputStream(fullFilename); byte[] buffer = new byte[1024]; int length; while((length=in.read(buffer))>0) { out.write(buffer, 0, length); } out.flush(); out.close(); in.close(); is.close(); System.out.println("작업 끝..."); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { TextToSpeechTest test = new TextToSpeechTest(); test.setService(); test.getVoiceList(); //test.executeSevice(); } }
7e6bfc584fb83b2a49cd7eb9587bbb589c963fe3
8d00583bf20dbe9bfd1af1ee46ddc92b3e58bc07
/guiao4/Barreira.java
835bb21016906dd3797c0c8c526d0563f9d05352
[]
no_license
dontworkagain/Concurrency-computer-science-
ccfe12a029d3041be413da1bafb7f75339d15018
9ddc611f45bf069dc6dd1f7829c3fccfa033a6bf
refs/heads/master
2021-04-04T10:26:47.012027
2018-04-11T17:52:46
2018-04-11T17:52:46
125,045,761
0
0
null
null
null
null
UTF-8
Java
false
false
299
java
package BarreiraGuiao4; public class Barreira { private int n; private int c = 0; public Barreira (int n) { this.n = n; } public synchronized void await() throws InterruptedException { c++; if(c<n) { while(c<n) { wait(); } } else { notifyAll(); } } }
2284fe8812402c374c6f98d6eef6bf6a56341fb7
31e1a2ac2b16cb3d7fcc440e806fbc009b278be0
/app/app/src/main/java/com/cleber/ramos/desafiofilmesandroid/model/FilmeDetalhe.java
9776ccd4aaef0d2093c3ed66068bcbc0eb501725
[]
no_license
clebernramos/desafiofilmesandroid
3886618be6f5f0f27b81a0ecaafc3d1d41bb571b
e246c0be86cd988153e441d1c6d705c03f1de2e3
refs/heads/master
2022-10-06T22:40:33.856682
2020-06-03T23:05:41
2020-06-03T23:05:41
265,007,301
0
0
null
2020-05-18T17:09:04
2020-05-18T17:09:03
null
UTF-8
Java
false
false
937
java
package com.cleber.ramos.desafiofilmesandroid.model; import com.google.gson.annotations.SerializedName; import java.util.List; public class FilmeDetalhe { @SerializedName("genres") public List<Genre> genres = null; @SerializedName("overview") public String overview; @SerializedName("poster_path") public String posterPath; @SerializedName("release_date") public String releaseDate; @SerializedName("tagline") public String tagline; @SerializedName("title") public String title; public List<Genre> getGenres() { return genres; } public String getOverview() { return overview; } public String getPosterPath() { return posterPath; } public String getReleaseDate() { return releaseDate; } public String getTagline() { return tagline; } public String getTitle() { return title; } }
e358db14821e94a4ba8643718765983a304d855a
75664b3a14f2a582c46cbd72daa7cd9b6b8128de
/src/main/java/com/guild/model/User.java
ba5ba9ef25b3403172aa7916b3dd179e1a671fd8
[]
no_license
liaojihan/AsterismController
f97d91f4073c4811ba043ca48bd71539a6627bc0
602d006593bcc9480df3a79d1d4d4eda4214e543
refs/heads/master
2021-05-03T06:12:17.523566
2018-07-28T11:59:53
2018-07-28T11:59:53
120,589,544
0
0
null
null
null
null
UTF-8
Java
false
false
561
java
package com.guild.model; /** * Created by knife on 2017/10/16. */ public class User { private int id; private String name; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
42147541ee5baced0752bcb5c2a658b498a6152f
4fa75fb107e40679f5bffbc96f310d00bd755423
/GitTest/src/foo/StudentConsumer.java
92ebaa0797f7c869ed901aef84eb684f49de2c6b
[]
no_license
valentinb23/GeneratorNumereInmatriculare
8b342c7a59f431d18bd5fa803eb45d5aaa595a9f
3913b4d1d3c4578e021d410cdaaa5460ae40cd0e
refs/heads/master
2021-01-01T19:40:09.793491
2017-08-03T10:33:45
2017-08-03T10:33:45
98,640,301
0
0
null
null
null
null
UTF-8
Java
false
false
261
java
package foo; public class StudentConsumer { public static void main(String[] args) { // TODO Auto-generated method stub Student s1 = new Student(); s1.setName("Ion"); s1.setAge(24); System.out.println("Hello " + s1.getName()); } }
a18a6e773b284200262cee5985b60d548643f26f
6252c165657baa6aa605337ebc38dd44b3f694e2
/org.eclipse.epsilon.egl.sync/Scalability-Tests/boiler-To-Generate-900-Files/boiler-To-Generate-900-Files/syncregions-900Files/TemperatureController4312.java
4b66c65433739148aa37c967681f479505ca2664
[]
no_license
soha500/EglSync
00fc49bcc73f7f7f7fb7641d0561ca2b9a8ea638
55101bc781349bb14fefc178bf3486e2b778aed6
refs/heads/master
2021-06-23T02:55:13.464889
2020-12-11T19:10:01
2020-12-11T19:10:01
139,832,721
0
1
null
2019-05-31T11:34:02
2018-07-05T10:20:00
Java
UTF-8
Java
false
false
367
java
package syncregions; public class TemperatureController4312 { public execute(int temperature4312, int targetTemperature4312) { //sync _bfpnFUbFEeqXnfGWlV4312, behaviour 1-if(temperatureDifference > 0 && boilerStatus == true) { return 1; } else if (temperatureDifference < 0 && boilerStatus == false) { return 2; } else return 0; //endSync } }
bbd707a786d847fe34f61076e86675781bb389fd
05e454259b44882a1bfff0ba82475374b36b74f0
/client/src/taco/agent/agentruntime/scenarios/OvertakeScenario.java
4e3e98ced5c7a86f00326d6664ab4088b7c1d2a0
[ "BSD-3-Clause" ]
permissive
TeamAutonomousCarOffenburg/TACO_2017
ec49f539528388f28114cca9787c1ab7db880e64
724c37188209818c22046d2229f67d882c36e2f4
refs/heads/master
2021-08-14T18:33:24.203830
2017-11-16T13:48:57
2017-11-16T13:48:57
110,350,009
4
1
null
null
null
null
UTF-8
Java
false
false
711
java
package taco.agent.agentruntime.scenarios; import taco.agent.model.worldmodel.DriveInstruction; import taco.agent.model.worldmodel.driveinstruction.DriveInstructionManager; import taco.agent.model.worldmodel.street.StreetMap; import taco.agent.model.worldmodel.street.maps.AADC2017QualiMap; import static taco.agent.model.worldmodel.DriveInstruction.*; public class OvertakeScenario extends ScenarioBase { public StreetMap createStreetMap() { return AADC2017QualiMap.create(); } @Override public int getStartSector() { return 3; } @Override public DriveInstructionManager createDriveInstructionManager() { return new DriveInstructionManager.Builder().add(STRAIGHT_FOREVER, 3).build(); } }
e274904dcccc3bc57b6ce177544465fa3baaa763
0ab0fc53bf702be69838b8e361df87755ec9034c
/src/com/cwl/test/GrapTest.java
e8754ea15f8745254d12004c89a7ac1c71309c69
[]
no_license
dave264/cwl
cb4c223d829a8c9024ed7617b9597b44ff8beeb9
88734319310735a2bb9557dc111c916a48e8b6ec
refs/heads/master
2021-01-21T18:50:31.950953
2016-09-21T02:45:14
2016-09-21T02:45:14
68,772,723
0
0
null
null
null
null
GB18030
Java
false
false
4,512
java
package com.cwl.test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.sql.ResultSet; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JEditorPane; import org.apache.http.Header; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import com.cwl.factory.DAOFactory; import com.cwl.imgIdent.ImgIdent; import com.cwl.parents.Home; import com.cwl.parse.tools.Parse; import com.cwl.tool.Tools; public class GrapTest extends Home{ public GrapTest(String url) { super(url); } public static void xingzhengCode() { List<String> list = DAOFactory.getIFileDAOInstance("file/城市编码.txt").BufferedReader(); List<Map> info = null; Map<String,Object> map = null; for (int i=0; i< list.size(); i++) { info = new ArrayList<Map>(); String Name = ""; Integer Code = 0; String idRegex = "\\d+"; String nameRegex = "\'\\W+"; String city = list.get(i).split(":")[0]; String cityName = city.split(",")[1]; String cityCode = city.split(",")[0]; Matcher mCityName = Pattern.compile(nameRegex).matcher(cityName); Matcher mCityCode = Pattern.compile(idRegex).matcher(cityCode); if(mCityName.find()) { Name = mCityName.group().replace("':", "").replace("'", ""); } if(mCityCode.find()) { Code = Integer.parseInt(mCityCode.group()); } map = new HashMap<String,Object>(); map.put(Name, Code); try { String s = list.get(i).split(":\\s+")[1]; String[] str = s.split(","); for (int j=0; j<str.length; j+=2) { String cityId = str[j]; String cName = str[j+1].replace("':", ""); Matcher mId = Pattern.compile(idRegex).matcher(cityId); Matcher mName = Pattern.compile(nameRegex).matcher(cName); Integer id = 0; String name = ""; if(mId.find()) { id = Integer.parseInt(mId.group()); if(id==0) { continue; } } if(mName.find()) { name = mName.group().replace("'", "").replaceAll("\\s+", ""); } map.put(name, id); info.add(map); } } catch(Exception e) { continue; } System.out.println(Tools.toJson(map)); DAOFactory.getIFileDAOInstance("d://行政编码.txt").FileOutputStream(Tools.toJson(map)+"\r\n", true); } } public static void main(String[] args) { GrapTest g = new GrapTest("http://www.baidu.com"); try { Document doc = DAOFactory.getIHttpDAOInstance(g.http).getDocument(); System.out.println(doc.html()); } catch (Exception e) { e.printStackTrace(); } } public static void URLConnection_(){ try { URL url = new URL("http://www.zy585.com/company/list.php?catid=3"); URLConnection conn = url.openConnection(); System.out.println("正文类型:"+conn.getContentType()); InputStream is = conn.getInputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int len = -1; while ((len = is.read(b))!=-1) { buffer.write(b,0,len); } String s = new String(buffer.toByteArray()); s = new String(s.getBytes("gbk"),"UTF-8"); System.out.println(s); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void URLOpenStream(){ try { URL url = new URL("http://www.zy585.com/company/list.php?catid=3"); InputStream in = url.openStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int len = -1; while((len = in.read(b))!=-1) { buffer.write(b,0,len); } String s = new String(buffer.toByteArray()); s = new String(s.getBytes("gbk"),"UTF-8"); Document doc = Jsoup.parse(s); System.out.println(doc.html()); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void grap(){ ImgIdent img = new ImgIdent("d://"); String s = img.postMultipart(); System.out.println(s); } }
611ebc2216ee825e1333ad0e74ba04d209bd30bd
7ba17a7f3edb0199876b81ef0a2a09fedc161b6a
/gmall-parent/gmall-manage-service/src/main/java/com/aryun/gmall/manage/mapper/PmsProductSaleAttrMapper.java
c373b332829650f047769581c20b27dbe7a72386
[]
no_license
wr18602424335/gmall
73c7e3cd799f9ccfc734e01126da0977e51b4f06
a8f88331fd6a76c822c5b0b27883c27786ca3969
refs/heads/master
2022-09-14T12:49:42.943422
2020-09-16T03:55:59
2020-09-16T03:55:59
219,521,768
0
0
null
2022-09-01T23:16:46
2019-11-04T14:32:53
CSS
UTF-8
Java
false
false
535
java
package com.aryun.gmall.manage.mapper; import com.aryun.gmall.bean.PmsProductInfo; import com.aryun.gmall.bean.PmsProductSaleAttr; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface PmsProductSaleAttrMapper extends BaseMapper<PmsProductSaleAttr> { List<PmsProductSaleAttr> selectSpuSaleAttrListCheckBySku(@Param("productId") String productId, @Param("skuId") String skuId); }
29bf0e0b8fb0313d4b3af15c4dccc0323526c333
ff0c33ccd3bbb8a080041fbdbb79e29989691747
/jdk.localedata/sun/text/resources/cldr/ext/FormatData_chr.java
25a246bcf22ae9481c41260c96c3065742eee164
[]
no_license
jiecai58/jdk15
7d0f2e518e3f6669eb9ebb804f3c89bbfb2b51f0
b04691a72e51947df1b25c31175071f011cb9bbe
refs/heads/main
2023-02-25T00:30:30.407901
2021-01-29T04:48:33
2021-01-29T04:48:33
330,704,930
0
1
null
null
null
null
UTF-8
Java
false
false
18,957
java
/* * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * COPYRIGHT AND PERMISSION NOTICE * * Copyright (C) 1991-2016 Unicode, Inc. All rights reserved. * Distributed under the Terms of Use in * http://www.unicode.org/copyright.html. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of the Unicode data files and any associated documentation * (the "Data Files") or Unicode software and any associated documentation * (the "Software") to deal in the Data Files or Software * without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, and/or sell copies of * the Data Files or Software, and to permit persons to whom the Data Files * or Software are furnished to do so, provided that * (a) this copyright and permission notice appear with all copies * of the Data Files or Software, * (b) this copyright and permission notice appear in associated * documentation, and * (c) there is clear notice in each modified Data File or in the Software * as well as in the documentation associated with the Data File(s) or * Software that the data or software has been modified. * * THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF * ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT OF THIRD PARTY RIGHTS. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS * NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL * DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THE DATA FILES OR SOFTWARE. * * Except as contained in this notice, the name of a copyright holder * shall not be used in advertising or otherwise to promote the sale, * use or other dealings in these Data Files or Software without prior * written authorization of the copyright holder. */ package sun.text.resources.cldr.ext; import java.util.ListResourceBundle; public class FormatData_chr extends ListResourceBundle { @Override protected final Object[][] getContents() { final String[] metaValue_MonthNames = new String[] { "\u13a4\u13c3\u13b8\u13d4\u13c5", "\u13a7\u13a6\u13b5", "\u13a0\u13c5\u13f1", "\u13a7\u13ec\u13c2", "\u13a0\u13c2\u13cd\u13ac\u13d8", "\u13d5\u13ad\u13b7\u13f1", "\u13ab\u13f0\u13c9\u13c2", "\u13a6\u13b6\u13c2", "\u13da\u13b5\u13cd\u13d7", "\u13da\u13c2\u13c5\u13d7", "\u13c5\u13d3\u13d5\u13c6", "\u13a5\u13cd\u13a9\u13f1", "", }; final String[] metaValue_MonthAbbreviations = new String[] { "\u13a4\u13c3", "\u13a7\u13a6", "\u13a0\u13c5", "\u13a7\u13ec", "\u13a0\u13c2", "\u13d5\u13ad", "\u13ab\u13f0", "\u13a6\u13b6", "\u13da\u13b5", "\u13da\u13c2", "\u13c5\u13d3", "\u13a5\u13cd", "", }; final String[] metaValue_MonthNarrows = new String[] { "\u13a4", "\u13a7", "\u13a0", "\u13a7", "\u13a0", "\u13d5", "\u13ab", "\u13a6", "\u13da", "\u13da", "\u13c5", "\u13a5", "", }; final String[] metaValue_DayNames = new String[] { "\u13a4\u13be\u13d9\u13d3\u13c6\u13cd\u13ac", "\u13a4\u13be\u13d9\u13d3\u13c9\u13c5\u13af", "\u13d4\u13b5\u13c1\u13a2\u13a6", "\u13e6\u13a2\u13c1\u13a2\u13a6", "\u13c5\u13a9\u13c1\u13a2\u13a6", "\u13e7\u13be\u13a9\u13b6\u13cd\u13d7", "\u13a4\u13be\u13d9\u13d3\u13c8\u13d5\u13be", }; final String[] metaValue_DayAbbreviations = new String[] { "\u13c6\u13cd\u13ac", "\u13c9\u13c5\u13af", "\u13d4\u13b5\u13c1", "\u13e6\u13a2\u13c1", "\u13c5\u13a9\u13c1", "\u13e7\u13be\u13a9", "\u13c8\u13d5\u13be", }; final String[] metaValue_DayNarrows = new String[] { "\u13c6", "\u13c9", "\u13d4", "\u13e6", "\u13c5", "\u13e7", "\u13a4", }; final String[] metaValue_QuarterNames = new String[] { "1st \u13a9\u13c4\u13d9\u13d7", "2nd \u13a9\u13c4\u13d9\u13d7", "3rd \u13a9\u13c4\u13d9\u13d7", "4th \u13a9\u13c4\u13d9\u13d7", }; final String[] metaValue_standalone_QuarterAbbreviations = new String[] { "Q1", "Q2", "Q3", "Q4", }; final String[] metaValue_AmPmMarkers = new String[] { "\u13cc\u13be\u13b4", "\u13d2\u13af\u13f1\u13a2\u13d7\u13e2", }; final String[] metaValue_narrow_AmPmMarkers = new String[] { "\u13cc", "\u13d2", }; final String[] metaValue_abbreviated_AmPmMarkers = new String[] { "\u13cc\u13be\u13b4", "\u13d2\u13af\u13f1\u13a2", }; final String[] metaValue_Eras = new String[] { "BC", "AD", }; final String[] metaValue_TimePatterns = new String[] { "h:mm:ss a zzzz", "h:mm:ss a z", "h:mm:ss a", "h:mm a", }; final String[] metaValue_buddhist_QuarterNarrows = new String[] { "1", "2", "3", "4", }; final String[] metaValue_java_time_buddhist_DatePatterns = new String[] { "EEEE, MMMM d, y G", "MMMM d, y G", "MMM d, y G", "M/d/y GGGGG", }; final String[] metaValue_buddhist_DatePatterns = new String[] { "EEEE, MMMM d, y GGGG", "MMMM d, y GGGG", "MMM d, y GGGG", "M/d/y G", }; final String metaValue_calendarname_gregorian = "\u13a9\u13b4\u13aa\u13b5\u13a0\u13c2 \u13c5\u13d9 \u13d7\u13ce\u13cd\u13d7"; final Object[][] data = new Object[][] { { "MonthNames", metaValue_MonthNames }, { "field.year", "\u13a4\u13d5\u13d8\u13f4\u13cc\u13d7\u13d2\u13a2" }, { "japanese.AmPmMarkers", metaValue_AmPmMarkers }, { "AmPmMarkers", metaValue_AmPmMarkers }, { "java.time.japanese.DatePatterns", metaValue_java_time_buddhist_DatePatterns }, { "standalone.QuarterAbbreviations", metaValue_standalone_QuarterAbbreviations }, { "roc.QuarterNames", metaValue_QuarterNames }, { "roc.MonthNarrows", metaValue_MonthNarrows }, { "islamic.narrow.AmPmMarkers", metaValue_narrow_AmPmMarkers }, { "japanese.TimePatterns", metaValue_TimePatterns }, { "narrow.Eras", metaValue_Eras }, { "abbreviated.AmPmMarkers", metaValue_abbreviated_AmPmMarkers }, { "timezone.regionFormat.standard", "{0} \u13a0\u13df\u13b6\u13cd\u13d7 \u13a0\u13df\u13a2\u13b5\u13d2" }, { "japanese.abbreviated.AmPmMarkers", metaValue_abbreviated_AmPmMarkers }, { "calendarname.japanese", "\u13e3\u13c6\u13c2\u13cf \u13c5\u13d9 \u13d7\u13ce\u13cd\u13d7" }, { "japanese.MonthNames", metaValue_MonthNames }, { "standalone.DayAbbreviations", metaValue_DayAbbreviations }, { "roc.MonthAbbreviations", metaValue_MonthAbbreviations }, { "long.Eras", new String[] { "\u13e7\u13d3\u13b7\u13b8 \u13a4\u13b7\u13af\u13cd\u13d7 \u13a6\u13b6\u13c1\u13db", "\u13a0\u13c3 \u13d9\u13bb\u13c2", } }, { "roc.QuarterNarrows", metaValue_buddhist_QuarterNarrows }, { "islamic.DayNames", metaValue_DayNames }, { "buddhist.MonthAbbreviations", metaValue_MonthAbbreviations }, { "buddhist.MonthNames", metaValue_MonthNames }, { "DateTimePatterns", new String[] { "{1} \u13a4\u13be\u13a2 {0}", "{1} \u13a4\u13be\u13a2 {0}", "{1}, {0}", "{1}, {0}", } }, { "narrow.AmPmMarkers", metaValue_narrow_AmPmMarkers }, { "latn.NumberElements", new String[] { ".", ",", ";", "%", "0", "#", "-", "E", "\u2030", "\u221e", "NaN", "", "", } }, { "MonthNarrows", metaValue_MonthNarrows }, { "japanese.DatePatterns", metaValue_buddhist_DatePatterns }, { "buddhist.DayNames", metaValue_DayNames }, { "field.minute", "\u13a2\u13ef\u13d4\u13ec\u13cd\u13d4\u13c5" }, { "field.era", "\u13d7\u13d3\u13b4\u13c2\u13cd\u13ac" }, { "buddhist.AmPmMarkers", metaValue_AmPmMarkers }, { "field.dayperiod", "\u13cc\u13be\u13b4/\u13d2\u13af\u13f1" }, { "standalone.MonthNarrows", metaValue_MonthNarrows }, { "japanese.QuarterNarrows", metaValue_buddhist_QuarterNarrows }, { "calendarname.roc", "\u13cd\u13a6\u13da\u13a9 \u13be\u13bf \u13d3\u13b6\u13c2\u13a8\u13cd\u13db \u13c5\u13d9 \u13d7\u13ce\u13cd\u13d7" }, { "islamic.DatePatterns", metaValue_buddhist_DatePatterns }, { "roc.QuarterAbbreviations", metaValue_standalone_QuarterAbbreviations }, { "field.month", "\u13a7\u13b8\u13a2" }, { "field.second", "\u13a0\u13ce\u13e2" }, { "DayAbbreviations", metaValue_DayAbbreviations }, { "DayNarrows", metaValue_DayNarrows }, { "roc.DatePatterns", metaValue_buddhist_DatePatterns }, { "calendarname.islamic", "\u13a2\u13cd\u13b3\u13bb\u13a9 \u13c5\u13d9 \u13d7\u13ce\u13cd\u13d7" }, { "japanese.narrow.AmPmMarkers", metaValue_narrow_AmPmMarkers }, { "buddhist.TimePatterns", metaValue_TimePatterns }, { "standalone.MonthAbbreviations", metaValue_MonthAbbreviations }, { "timezone.regionFormat", "{0} \u13a0\u13df\u13a2\u13b5\u13d2" }, { "long.CompactNumberPatterns", new String[] { "", "", "", "{one:0' '\u13a2\u13ef\u13a6\u13f4\u13b5 other:0' '\u13a2\u13ef\u13a6\u13f4\u13b5}", "{one:00' '\u13a2\u13ef\u13a6\u13f4\u13b5 other:00' '\u13a2\u13ef\u13a6\u13f4\u13b5}", "{one:000' '\u13a2\u13ef\u13a6\u13f4\u13b5 other:000' '\u13a2\u13ef\u13a6\u13f4\u13b5}", "{one:0' '\u13a2\u13f3\u13c6\u13d7\u13c5\u13db other:0' '\u13a2\u13f3\u13c6\u13d7\u13c5\u13db}", "{one:00' '\u13a2\u13f3\u13c6\u13d7\u13c5\u13db other:00' '\u13a2\u13f3\u13c6\u13d7\u13c5\u13db}", "{one:000' '\u13a2\u13f3\u13c6\u13d7\u13c5\u13db other:000' '\u13a2\u13f3\u13c6\u13d7\u13c5\u13db}", "{one:0' '\u13a2\u13ef\u13d4\u13b3\u13d7\u13c5\u13db other:0' '\u13a2\u13ef\u13d4\u13b3\u13d7\u13c5\u13db}", "{one:00' '\u13a2\u13ef\u13d4\u13b3\u13d7\u13c5\u13db other:00' '\u13a2\u13ef\u13d4\u13b3\u13d7\u13c5\u13db}", "{one:000' '\u13a2\u13ef\u13d4\u13b3\u13d7\u13c5\u13db other:000' '\u13a2\u13ef\u13d4\u13b3\u13d7\u13c5\u13db}", "{one:0' '\u13a2\u13ef\u13e6\u13a0\u13d7\u13c5\u13db other:0' '\u13a2\u13ef\u13e6\u13a0\u13d7\u13c5\u13db}", "{one:00' '\u13a2\u13ef\u13e6\u13a0\u13d7\u13c5\u13db other:00' '\u13a2\u13ef\u13e6\u13a0\u13d7\u13c5\u13db}", "{one:000' '\u13a2\u13ef\u13e6\u13a0\u13d7\u13c5\u13db other:000' '\u13a2\u13ef\u13e6\u13a0\u13d7\u13c5\u13db}", } }, { "roc.narrow.AmPmMarkers", metaValue_narrow_AmPmMarkers }, { "buddhist.QuarterNarrows", metaValue_buddhist_QuarterNarrows }, { "standalone.QuarterNames", metaValue_QuarterNames }, { "japanese.MonthNarrows", metaValue_MonthNarrows }, { "islamic.QuarterAbbreviations", metaValue_standalone_QuarterAbbreviations }, { "roc.DayAbbreviations", metaValue_DayAbbreviations }, { "standalone.DayNarrows", metaValue_DayNarrows }, { "islamic.AmPmMarkers", metaValue_AmPmMarkers }, { "TimePatterns", metaValue_TimePatterns }, { "islamic.DayNarrows", metaValue_DayNarrows }, { "field.zone", "\u13c2\u13ac\u13be\u13db \u13e7\u13d3\u13b4\u13c5\u13d3 \u13d3\u13df\u13a2\u13b5\u13cd\u13d2\u13a2" }, { "japanese.QuarterAbbreviations", metaValue_standalone_QuarterAbbreviations }, { "buddhist.narrow.AmPmMarkers", metaValue_narrow_AmPmMarkers }, { "buddhist.abbreviated.AmPmMarkers", metaValue_abbreviated_AmPmMarkers }, { "Eras", metaValue_Eras }, { "roc.DayNames", metaValue_DayNames }, { "islamic.QuarterNames", metaValue_QuarterNames }, { "islamic.abbreviated.AmPmMarkers", metaValue_abbreviated_AmPmMarkers }, { "java.time.islamic.DatePatterns", metaValue_java_time_buddhist_DatePatterns }, { "field.weekday", "\u13a2\u13a6 \u13d5\u13a8\u13cc\u13d7\u13d2" }, { "japanese.MonthAbbreviations", metaValue_MonthAbbreviations }, { "islamic.DayAbbreviations", metaValue_DayAbbreviations }, { "japanese.QuarterNames", metaValue_QuarterNames }, { "buddhist.QuarterAbbreviations", metaValue_standalone_QuarterAbbreviations }, { "japanese.DayNames", metaValue_DayNames }, { "japanese.DayAbbreviations", metaValue_DayAbbreviations }, { "DayNames", metaValue_DayNames }, { "buddhist.DatePatterns", metaValue_buddhist_DatePatterns }, { "roc.MonthNames", metaValue_MonthNames }, { "field.week", "\u13d2\u13be\u13d9\u13d3\u13c6\u13cd\u13d7" }, { "buddhist.MonthNarrows", metaValue_MonthNarrows }, { "buddhist.QuarterNames", metaValue_QuarterNames }, { "islamic.QuarterNarrows", metaValue_buddhist_QuarterNarrows }, { "roc.DayNarrows", metaValue_DayNarrows }, { "roc.AmPmMarkers", metaValue_AmPmMarkers }, { "java.time.roc.DatePatterns", metaValue_java_time_buddhist_DatePatterns }, { "java.time.buddhist.DatePatterns", metaValue_java_time_buddhist_DatePatterns }, { "short.CompactNumberPatterns", new String[] { "", "", "", "{one:0K other:0K}", "{one:00K other:00K}", "{one:000K other:000K}", "{one:0M other:0M}", "{one:00M other:00M}", "{one:000M other:000M}", "{one:0B other:0B}", "{one:00B other:00B}", "{one:000B other:000B}", "{one:0T other:0T}", "{one:00T other:00T}", "{one:000T other:000T}", } }, { "calendarname.gregorian", metaValue_calendarname_gregorian }, { "timezone.regionFormat.daylight", "{0} \u13aa\u13af \u13a2\u13a6 \u13a0\u13df\u13a2\u13b5\u13d2" }, { "DatePatterns", new String[] { "EEEE, MMMM d, y", "MMMM d, y", "MMM d, y", "M/d/yy", } }, { "buddhist.DayAbbreviations", metaValue_DayAbbreviations }, { "islamic.TimePatterns", metaValue_TimePatterns }, { "MonthAbbreviations", metaValue_MonthAbbreviations }, { "standalone.DayNames", metaValue_DayNames }, { "field.hour", "\u13d1\u13df\u13b6\u13d3" }, { "calendarname.buddhist", "\u13ca\u13d7\u13cd\u13d8 \u13c5\u13d9 \u13d7\u13ce\u13cd\u13d7" }, { "standalone.MonthNames", metaValue_MonthNames }, { "latn.NumberPatterns", new String[] { "#,##0.###", "\u00a4#,##0.00", "#,##0%", "\u00a4#,##0.00;(\u00a4#,##0.00)", } }, { "buddhist.DayNarrows", metaValue_DayNarrows }, { "japanese.DayNarrows", metaValue_DayNarrows }, { "QuarterNames", metaValue_QuarterNames }, { "roc.TimePatterns", metaValue_TimePatterns }, { "roc.abbreviated.AmPmMarkers", metaValue_abbreviated_AmPmMarkers }, { "calendarname.gregory", metaValue_calendarname_gregorian }, }; return data; } }
d95753228d5553d6afe940d49bd527cade8e0120
5ab083e5799b58ac962bab7d72294fbd3ca23b15
/src/main/java/com/person/yvan/test/RedisJunit.java
9f1c7c3876c6e7a64a0a765af966d8e2d3ecaea6
[]
no_license
gaoyuhub/TransactionDemo
68babf34be65e6a9db58a121e62b1238b079d898
cd7653b7d81351dcffd244775b66d656ea1114d8
refs/heads/master
2020-03-29T06:37:06.733410
2019-02-24T07:51:28
2019-02-24T07:51:28
149,633,287
0
0
null
2019-02-24T07:56:50
2018-09-20T15:46:34
Java
UTF-8
Java
false
false
2,183
java
package com.person.yvan.test; import org.junit.jupiter.api.Test; import org.springframework.data.redis.core.RedisTemplate; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import javax.annotation.Resource; //@RunWith(SpringJUnit4ClassRunner.class) //@ContextConfiguration(locations = {"classpath:spring-redis.xml"}) class RedisJunit { @Resource(name = "redisTemplate") private RedisTemplate redisTemplate; JedisPool jedisPool; Jedis jedis; /* @Before("testGet") public void setUp(){ JedisPoolConfig config = new JedisPoolConfig(); jedisPool = new JedisPool(config,"localhost"); jedis = jedisPool.getResource(); }*/ @Test public void testGet(){ redisTemplate.opsForValue().set("name","tom"); System.out.print(redisTemplate.opsForValue().get("name")); } @Test public void testBasicString(){ //-----添加数据---------- jedis.set("name","minxr");//向key-->name中放入了value-->minxr System.out.println(jedis.get("name"));//执行结果:minxr //-----修改数据----------- //1、在原来基础上修改 jedis.append("name","jarorwar"); //很直观,类似map 将jarorwar append到已经有的value之后 System.out.println(jedis.get("name"));//执行结果:minxrjarorwar //2、直接覆盖原来的数据 jedis.set("name","闵晓荣"); System.out.println(jedis.get("name"));//执行结果:闵晓荣 //删除key对应的记录 jedis.del("name"); System.out.println(jedis.get("name"));//执行结果:null /** * mset相当于 * jedis.set("name","minxr"); * jedis.set("jarorwar","闵晓荣"); */ jedis.mset("name","minxr","jarorwar","闵晓荣"); System.out.println(jedis.mget("name","jarorwar")); } }
23a3430aad137386ad11a860e0944089f298f0be
92e373f7afbee8b3b9c7c25d5351a12f7768d64b
/src/test/java/org/anantacreative/updater/tests/PackUnpackTest.java
c93e27dbb89808d95737587fb101a3621414dd91
[]
no_license
eignatik/updater
3272f6a7587c9124c6bb522e218f6cb2f8855c18
979cb47de7862f68bce455d30cc1e7bc080355e1
refs/heads/master
2020-12-02T20:59:38.759911
2017-07-01T18:58:25
2017-07-01T18:58:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,530
java
package org.anantacreative.updater.tests; import org.anantacreative.updater.Pack.Packer; import org.anantacreative.updater.Pack.UnPacker; import org.anantacreative.updater.ResourceUtil; import org.testng.annotations.Test; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import static org.testng.AssertJUnit.assertTrue; public class PackUnpackTest { @Test(dependsOnMethods = {"unPack"},groups = {"common"}) public void packDir() throws Exception { File testDir = TestUtil.initTestDir("./tmp"); File dir = new File(testDir, "dst"); List<File> files = TestUtil.initDirWithFiles(dir, 10, "file", "txt"); File dir2 = new File(dir, "dst2"); List<File> files2 = TestUtil.initDirWithFiles(dir2, 5, "fff", "txt"); File arch = new File(testDir, "pack_dir.zip"); Packer.packDir(dir, arch); assertTrue(arch.exists()); assertTrue(arch.length() > 0); File unpackFilesDir = new File(testDir,"unpacked_files"); UnPacker.unPack(arch, unpackFilesDir); TestUtil.hasFilesInDirExectly(unpackFilesDir,files.stream().map(File::getName).collect(Collectors.toList()),true); File dst2 = TestUtil.hasDirsInDirExectly(unpackFilesDir, Arrays.asList(dir2.getName()))[0]; TestUtil.hasFilesInDirExectly(dst2,files2.stream().map(File::getName).collect(Collectors.toList()),true); } @Test(dependsOnMethods = {"unPack"},groups = {"common"}) public void packFiles() throws Exception { File testDir = TestUtil.initTestDir("./tmp"); File toPackDir =new File(testDir,"to_pack"); TestUtil.initDirectory(toPackDir, Collections.EMPTY_LIST); File dir1 = new File(toPackDir, "dst1"); File dir2 = new File(toPackDir, "dst2"); List<File> files1 = TestUtil.initDirWithFiles(dir1, 10, "file", "txt"); List<File> files2 = TestUtil.initDirWithFiles(dir2, 5, "f", "txt"); File dir3 = new File(dir2, "dst3"); List<File> files3 = TestUtil.initDirWithFiles(dir3, 20, "fff", "txt"); File file1 = new File(toPackDir, "file1.txt"); TestUtil.createFile(file1); File file2 = new File(toPackDir, "file2.txt"); TestUtil.createFile(file2); List<File> toPackFiles = new ArrayList<>(); toPackFiles.add(dir1); toPackFiles.add(dir2); toPackFiles.add(file1); toPackFiles.add(file2); File arch = new File(testDir, "pack_files.zip"); Packer.packFiles(toPackFiles, arch); assertTrue(arch.exists()); assertTrue(arch.length() > 0); File archToUnpack = new File(testDir, "pack_files.zip"); File unpackFilesDir = new File(testDir,"unpacked_files"); UnPacker.unPack(archToUnpack, unpackFilesDir); File[] files = TestUtil.hasDirsInDirExectly(unpackFilesDir, Arrays.asList("dst1", "dst2")); File dst1 = files[0].getName().equals("dst1")? files[0] : files[1]; File dst2 = files[0].getName().equals("dst2")? files[0] : files[1]; File dst3 = TestUtil.hasDirsInDirExectly(dst2, Arrays.asList("dst3"))[0]; TestUtil.hasFilesInDirExectly(unpackFilesDir,Arrays.asList(file1.getName(),file2.getName()),true); TestUtil.hasFilesInDirExectly(dst1,files1.stream().map(File::getName).collect(Collectors.toList()), true); TestUtil.hasFilesInDirExectly(dst2,files2.stream().map(File::getName).collect(Collectors.toList()),true); TestUtil.hasFilesInDirExectly(dst3,files3.stream().map(File::getName).collect(Collectors.toList()),true); } /** * Проверяется распаковка заранее приготовленного архива. Архив берется из ресурсов тестов. * После прохождения этого теста можно использовать распаковку в тесте с упаковкой файлов для проверки результата */ @Test(groups = {"common"}) public void unPack() throws Exception { File testDir = TestUtil.initTestDir("./tmp"); File zipArch = ResourceUtil.saveResource(testDir, "test.zip", "/test.zip", true); File toUnPackDir=new File(testDir,"unpack_dir"); TestUtil.initDirectory(toUnPackDir, Collections.emptyList()); UnPacker.unPack(zipArch,toUnPackDir); checkUnPackTestArch(toUnPackDir); } /** * Проверяет файлы из распакованного архива test.zip из ресурсов тестов. * Архив содержит несколько вложенных директорий с файлами по 5 шт. в директоии, все файлы не нулевой длины и с одинаковым содержимым. * @param toUnpackDir папка распаковки */ public static void checkUnPackTestArch(File toUnpackDir){ List<String> nameFiles = Arrays.asList("file1.txt", "file2.txt", "file3.txt", "file4.txt", "file5.txt"); File dir = TestUtil.hasDirsInDirExectly(toUnpackDir, Arrays.asList("dir"))[0]; File dir2 = TestUtil.hasDirsInDirExectly(dir, Arrays.asList("dir2"))[0]; TestUtil.hasFilesInDirExectly(toUnpackDir, nameFiles,true); TestUtil.hasFilesInDirExectly(dir, nameFiles,true); TestUtil.hasFilesInDirExectly(dir2, nameFiles,true); } }
42bce031815c3057c5d56421e3d92ae22188a2dd
0c583d6d773684a436c12e3492b95476dfbf51f0
/app/src/main/java/com/vedas/weightloss/Controllers/DayFoodController.java
099ddfbd0fcc67933b9dfc81655d74ddbcfa2bd2
[]
no_license
peddareddyvedas/WeightLossfor
da118f2654652355c618f626d7ac66d6452074bf
ccc609dfc52aa340fe3aca842dabe80a2d8974c8
refs/heads/master
2020-03-23T14:55:05.834403
2018-07-20T12:14:15
2018-07-20T12:14:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
19,130
java
package com.vedas.weightloss.Controllers; import android.content.Context; import android.util.Log; import android.view.View; import com.vedas.weightloss.DataBase.BreakfastDataController; import com.vedas.weightloss.DataBase.DayFoodDataController; import com.vedas.weightloss.DataBase.DinnerDataController; import com.vedas.weightloss.DataBase.ExerciseDataController; import com.vedas.weightloss.DataBase.LunchDataController; import com.vedas.weightloss.DataBase.PersonalInfoDataController; import com.vedas.weightloss.DataBase.SnacksDataController; import com.vedas.weightloss.DataBase.WaterDataController; import com.vedas.weightloss.FoodModule.DayOneActivity; import com.vedas.weightloss.Models.BreakfastObject; import com.vedas.weightloss.Models.DayFoodObject; import com.vedas.weightloss.Models.DinnerObject; import com.vedas.weightloss.Models.ExerciseObject; import com.vedas.weightloss.Models.LunchObject; import com.vedas.weightloss.Models.SnacksObject; import com.vedas.weightloss.Models.WaterObject; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; /** * Created by VEDAS on 6/13/2018. */ public class DayFoodController { public static DayFoodController myObj; Context context; // public DayFoodObject selectedFoodObject; SimpleDateFormat timeformatter = new SimpleDateFormat("hh:mm a"); public ArrayList<String> footerArray; public ArrayList<String> headerArray; public static DayFoodController getInstance() { if (myObj == null) { myObj = new DayFoodController(); } return myObj; } public void fillContext(Context context1) { context = context1; } public void loadHeaderFooterArray() { footerArray = new ArrayList<>(); headerArray = new ArrayList<>(); Log.e("headerView", "call"); headerArray.add("Breakfast"); headerArray.add("Lunch"); headerArray.add("Dinner"); headerArray.add("Snacks"); headerArray.add("Exercises"); headerArray.add("Water"); //// footerArray.add("Add Breakfast"); footerArray.add("Add Lunch"); footerArray.add("Add Dinner"); footerArray.add("Add Snacks"); footerArray.add("Add Exercise"); footerArray.add("Add Water"); } public int calculatingTotalCaloriesForFood() { DayFoodObject dayFoodObject = DayFoodDataController.getInstance().currentFoodObject; int selectedCalories = 0; if (BreakfastDataController.getInstance().fetchBreakfastData(dayFoodObject).size() > 0) { for (BreakfastObject breakfastObject : BreakfastDataController.getInstance().fetchBreakfastData(dayFoodObject)) { String breakfastCalories = breakfastObject.getEsimatedCalories(); selectedCalories = selectedCalories + Integer.parseInt(breakfastCalories); } } if (LunchDataController.getInstance().fetchLunchData(dayFoodObject).size() > 0) { for (LunchObject breakfastObject : LunchDataController.getInstance().fetchLunchData(dayFoodObject)) { String breakfastCalories = breakfastObject.getEsimatedCalories(); selectedCalories = selectedCalories + Integer.parseInt(breakfastCalories); } } if (DinnerDataController.getInstance().fetchdinnerData(dayFoodObject).size() > 0) { for (DinnerObject breakfastObject : DinnerDataController.getInstance().fetchdinnerData(dayFoodObject)) { String breakfastCalories = breakfastObject.getEsimatedCalories(); selectedCalories = selectedCalories + Integer.parseInt(breakfastCalories); } } if (SnacksDataController.getInstance().fetchSnacksData(dayFoodObject).size() > 0) { for (SnacksObject breakfastObject : SnacksDataController.getInstance().fetchSnacksData(dayFoodObject)) { String breakfastCalories = breakfastObject.getEsimatedCalories(); selectedCalories = selectedCalories + Integer.parseInt(breakfastCalories); } } return selectedCalories; } public void calculatingTotalCaloriesForFoodForHeader() { DayFoodObject dayFoodObject = DayFoodDataController.getInstance().currentFoodObject; int breakfast = 0; int luncch = 0; int dinner = 0; int snacks = 0; int burnedCalories = 0; if (BreakfastDataController.getInstance().fetchBreakfastData(dayFoodObject).size() > 0) { for (BreakfastObject breakfastObject : BreakfastDataController.getInstance().fetchBreakfastData(dayFoodObject)) { String breakfastCalories = breakfastObject.getEsimatedCalories(); breakfast = breakfast + Integer.parseInt(breakfastCalories); } } if (LunchDataController.getInstance().fetchLunchData(dayFoodObject).size() > 0) { for (LunchObject breakfastObject : LunchDataController.getInstance().fetchLunchData(dayFoodObject)) { String breakfastCalories = breakfastObject.getEsimatedCalories(); luncch = luncch + Integer.parseInt(breakfastCalories); } } if (DinnerDataController.getInstance().fetchdinnerData(dayFoodObject).size() > 0) { for (DinnerObject breakfastObject : DinnerDataController.getInstance().fetchdinnerData(dayFoodObject)) { String breakfastCalories = breakfastObject.getEsimatedCalories(); dinner = dinner + Integer.parseInt(breakfastCalories); } } if (SnacksDataController.getInstance().fetchSnacksData(dayFoodObject).size() > 0) { for (SnacksObject breakfastObject : SnacksDataController.getInstance().fetchSnacksData(dayFoodObject)) { String breakfastCalories = breakfastObject.getEsimatedCalories(); snacks = snacks + Integer.parseInt(breakfastCalories); } } if (ExerciseDataController.getInstance().fetchExerciseData(dayFoodObject).size() > 0) { for (ExerciseObject exerciseObject : ExerciseDataController.getInstance().fetchExerciseData(dayFoodObject)) { String breakfastCalories = exerciseObject.getEstimatedCaloriesBurned(); burnedCalories = burnedCalories + Integer.parseInt(breakfastCalories); } } DayFoodDataController.getInstance().currentFoodObject.breakFastCalories = String.valueOf(breakfast); DayFoodDataController.getInstance().currentFoodObject.lunchCalories = String.valueOf(luncch); DayFoodDataController.getInstance().currentFoodObject.dinnerCalories = String.valueOf(dinner); DayFoodDataController.getInstance().currentFoodObject.snacksCalories = String.valueOf(snacks); DayFoodDataController.getInstance().currentFoodObject.burnedCalories = String.valueOf(burnedCalories); DayFoodDataController.getInstance().updateDayFoodData(DayFoodDataController.getInstance().currentFoodObject); } public double calculatelitersFromWaterobject() { double totalWater = 0.0; for (int i = 0; i <=WaterDataController.getInstance().fetchWaterData(DayFoodDataController.getInstance().currentFoodObject).size(); i++) { ArrayList<WaterObject> water = WaterDataController.getInstance().fetchWaterData(DayFoodDataController.getInstance().currentFoodObject); if (water.size()>0){ for (WaterObject breakfastObject : water) { String breakfastCalories = breakfastObject.getWaterUnits(); Log.e("breakfastCalories", "call" + breakfastCalories); if (breakfastObject.getWaterUnits().equals("Milliliter")) { double value = Double.parseDouble(breakfastObject.getWaterContent()); Log.e("value", "call" + value); double doubleValue = value /1000.0; Log.e("doubleValue", "call" + doubleValue); totalWater = totalWater + doubleValue; Log.e("Milliliters", "call" + totalWater); } else { Log.e("liters", "call" + totalWater); double value = Double.parseDouble(breakfastObject.getWaterContent()); totalWater = totalWater + value; } } Log.e("totalvalue", "call" + totalWater); return totalWater; } } return 0.0; } public int calculatingTotalCaloriesForExercise() { int burnedCalories = 0; if (ExerciseDataController.getInstance().fetchExerciseData(DayFoodDataController.getInstance().currentFoodObject).size() > 0) { for (ExerciseObject exerciseObject : ExerciseDataController.getInstance().fetchExerciseData(DayFoodDataController.getInstance().currentFoodObject)) { String breakfastCalories = exerciseObject.getEstimatedCaloriesBurned(); burnedCalories = burnedCalories + Integer.parseInt(breakfastCalories); } } return burnedCalories; } public int calculateTotlaRemainingCalories() { int remaineCalories = 0; int targetCalories = Integer.parseInt(PersonalInfoDataController.getInstance().currentMember.getTargetCalories()); int foodCalories = calculatingTotalCaloriesForFood(); int execciseCalories = calculatingTotalCaloriesForExercise(); remaineCalories = targetCalories - foodCalories; remaineCalories = remaineCalories + execciseCalories; return remaineCalories; } public String gettingCurrentDate() { String currentTIme = ""; // String currentDate = ""; Date currentTime = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(currentTime); // convert your date to Calendar object calendar.add(Calendar.DATE, -1); currentTime = calendar.getTime(); // again get back your date object currentTIme = timeformatter.format(currentTime); // currentTIme = formatter.format(currentTime); return currentTIme; } public void loadTextviewdata(DayOneActivity.DashBoardAdapter.MainVH holder, int section, int relativePosition, int absolutePosition) { DayFoodObject dayFoodObject = DayFoodDataController.getInstance().currentFoodObject; if (section == 0) { if (BreakfastDataController.getInstance().fetchBreakfastData(dayFoodObject).size() > 0) { holder.view.setVisibility(View.VISIBLE); holder.name.setText( String.format(BreakfastDataController.getInstance().fetchBreakfastData(dayFoodObject).get(relativePosition).getFoodName(), section, relativePosition, absolutePosition)); holder.calories.setText( String.format(BreakfastDataController.getInstance().fetchBreakfastData(dayFoodObject).get(relativePosition).getEsimatedCalories(), section, relativePosition, absolutePosition)); holder.added_time.setText( String.format(BreakfastDataController.getInstance().fetchBreakfastData(dayFoodObject).get(relativePosition).getAddedTime(), section, relativePosition, absolutePosition)); } else { holder.view.setVisibility(View.GONE); holder.name.setText( String.format("", section, relativePosition, absolutePosition)); holder.calories.setText( String.format("", section, relativePosition, absolutePosition)); holder.added_time.setText( String.format("", section, relativePosition, absolutePosition)); } } if (section == 1) { if (LunchDataController.getInstance().fetchLunchData(dayFoodObject).size() > 0) { holder.view.setVisibility(View.VISIBLE); holder.name.setText( String.format(LunchDataController.getInstance().fetchLunchData(dayFoodObject).get(relativePosition).getFoodName(), section, relativePosition, absolutePosition)); holder.calories.setText( String.format(LunchDataController.getInstance().fetchLunchData(dayFoodObject).get(relativePosition).getEsimatedCalories(), section, relativePosition, absolutePosition)); holder.added_time.setText( String.format(LunchDataController.getInstance().fetchLunchData(dayFoodObject).get(relativePosition).getAddedTime(), section, relativePosition, absolutePosition)); } else { holder.view.setVisibility(View.GONE); holder.name.setText( String.format("", section, relativePosition, absolutePosition)); holder.calories.setText( String.format("", section, relativePosition, absolutePosition)); holder.added_time.setText( String.format("", section, relativePosition, absolutePosition)); } } if (section == 2) { if (DinnerDataController.getInstance().fetchdinnerData(dayFoodObject).size() > 0) { holder.view.setVisibility(View.VISIBLE); holder.name.setText( String.format(DinnerDataController.getInstance().fetchdinnerData(dayFoodObject).get(relativePosition).getFoodName(), section, relativePosition, absolutePosition)); holder.calories.setText( String.format(DinnerDataController.getInstance().fetchdinnerData(dayFoodObject).get(relativePosition).getEsimatedCalories(), section, relativePosition, absolutePosition)); holder.added_time.setText( String.format(DinnerDataController.getInstance().fetchdinnerData(dayFoodObject).get(relativePosition).getAddedTime(), section, relativePosition, absolutePosition)); } else { holder.view.setVisibility(View.GONE); holder.name.setText( String.format("", section, relativePosition, absolutePosition)); holder.calories.setText( String.format("", section, relativePosition, absolutePosition)); holder.added_time.setText( String.format("", section, relativePosition, absolutePosition)); } } if (section == 3) { if (SnacksDataController.getInstance().fetchSnacksData(dayFoodObject).size() > 0) { holder.view.setVisibility(View.VISIBLE); holder.name.setText( String.format(SnacksDataController.getInstance().fetchSnacksData(dayFoodObject).get(relativePosition).getFoodName(), section, relativePosition, absolutePosition)); holder.calories.setText( String.format(SnacksDataController.getInstance().fetchSnacksData(dayFoodObject).get(relativePosition).getEsimatedCalories(), section, relativePosition, absolutePosition)); holder.added_time.setText( String.format(SnacksDataController.getInstance().fetchSnacksData(dayFoodObject).get(relativePosition).getAddedTime(), section, relativePosition, absolutePosition)); } else { holder.view.setVisibility(View.GONE); holder.name.setText( String.format("", section, relativePosition, absolutePosition)); holder.calories.setText( String.format("", section, relativePosition, absolutePosition)); holder.added_time.setText( String.format("", section, relativePosition, absolutePosition)); } } //exercise if (section == 4) { if (ExerciseDataController.getInstance().fetchExerciseData(dayFoodObject).size() > 0) { holder.view.setVisibility(View.VISIBLE); holder.name.setText( String.format(ExerciseDataController.getInstance().fetchExerciseData(dayFoodObject).get(relativePosition).getExerciseName(), section, relativePosition, absolutePosition)); holder.calories.setText( String.format(ExerciseDataController.getInstance().fetchExerciseData(dayFoodObject).get(relativePosition).getEstimatedCaloriesBurned(), section, relativePosition, absolutePosition)); holder.added_time.setText( String.format(ExerciseDataController.getInstance().fetchExerciseData(dayFoodObject).get(relativePosition).getAddedDate(), section, relativePosition, absolutePosition)); } else { holder.view.setVisibility(View.GONE); holder.name.setText( String.format("", section, relativePosition, absolutePosition)); holder.calories.setText( String.format("", section, relativePosition, absolutePosition)); holder.added_time.setText( String.format("", section, relativePosition, absolutePosition)); } } //water if (section == 5) { if (WaterDataController.getInstance().fetchWaterData(dayFoodObject).size() > 0) { holder.view.setVisibility(View.VISIBLE); /*holder.name.setText( String.format(DayFoodController.getInstance().selectedFoodObject.waterArrayList.get(relativePosition).getWaterContent(), section, relativePosition, absolutePosition)); */ holder.name.setText( String.format("Water", section, relativePosition, absolutePosition)); String water = WaterDataController.getInstance().fetchWaterData(dayFoodObject).get(relativePosition).getWaterContent() + " " + WaterDataController.getInstance().fetchWaterData(dayFoodObject).get(relativePosition).getWaterUnits(); holder.calories.setText( String.format(water, section, relativePosition, absolutePosition)); holder.added_time.setText( String.format(WaterDataController.getInstance().fetchWaterData(dayFoodObject).get(relativePosition).getAddedTime(), section, relativePosition, absolutePosition)); } else { holder.view.setVisibility(View.GONE); holder.name.setText( String.format("", section, relativePosition, absolutePosition)); holder.calories.setText( String.format("", section, relativePosition, absolutePosition)); holder.added_time.setText( String.format("", section, relativePosition, absolutePosition)); } } } }
393480c72821856fd78fdd11ccad26dd31b9bb30
354f50cb9bfe8fbdc626d09971e1508766562408
/PilotSop/basic/src/vn/com/hkt/tree/ui/enterprise/thuchi/tongquan/EnterpriseParentTongQuan.java
b47bc9f6a41d0609540fc5200db763b5e99f2012
[]
no_license
duongnguyenhoang103/FileJava
3d94ed3141eae568206973043cce4ddfc9609516
0d38d7761d63f67f2e21a88606fb3a7843ae0a7f
refs/heads/master
2021-01-17T15:06:04.157148
2012-04-11T09:52:45
2012-04-11T09:52:45
3,205,744
0
0
null
null
null
null
UTF-8
Java
false
false
17,521
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package vn.com.hkt.tree.ui.enterprise.thuchi.tongquan; import java.beans.PropertyEditor; import java.beans.PropertyEditorSupport; import vn.com.hkt.pilot.entities.Enterprise; import vn.com.hkt.basic.api.IEnterpriseBN; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.Vector; import org.openide.nodes.AbstractNode; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.nodes.Node.Property; import org.openide.nodes.PropertySupport; import org.openide.nodes.Sheet; import org.openide.util.Lookup; import org.openide.util.lookup.Lookups; import vn.com.hkt.erm.enterprise.dao.EnterpriseBN; import vn.com.hkt.finance.spi.CalculateSPI; import vn.com.hkt.pilot.datetime.utils.DateTimeUtils; /** * * @author longnt */ public class EnterpriseParentTongQuan extends Children.Keys { private List<Enterprise> list = new ArrayList<Enterprise>(); private IEnterpriseBN enterpriseBN = Lookup.getDefault().lookup(IEnterpriseBN.class); public static String ThuMonth1_PROPERTY = "ThuM1"; public static String ChiMonth1_PROPERTY = "ChiM1"; public static String Lai1_PROPERTY = "LaiM1"; public static String ThuMonth2_PROPERTY = "ThuM2"; public static String ChiMonth2_PROPERTY = "ChiM2"; public static String Lai2_PROPERTY = "LaiM2"; public static String ThuMonth3_PROPERTY = "ThuM3"; public static String ChiMonth3_PROPERTY = "ChiM3"; public static String Lai3_PROPERTY = "LaiM3"; public static String ThuYear1_PROPERTY = "ThuY1"; public static String ChiYear1_PROPERTY = "ChiY1"; public static String LaiYear1_PROPERTY = "LaiY1"; public static String ThuYear2_PROPERTY = "ThuY2"; public static String ChiYear2_PROPERTY = "ChiY2"; public static String LaiYear2_PROPERTY = "LaiY2"; public static String ThuAll_PROPERTY = "ThuAll"; public static String ChiAll_PROPERTY = "ChiAll"; public static String LaiAll_PROPERTY = "LaiAll"; private Enterprise enterprise; private CalculateSPI calculateSPI; private DateTimeUtils dateTimeUtils; private String month1, month2, month3, year1, year2; public EnterpriseParentTongQuan(boolean lazy) { super(lazy); } public EnterpriseParentTongQuan(Enterprise enterprise) { this.enterprise = enterprise; list = enterpriseBN.getAllEnterprise(); calculateSPI = new CalculateSPI(); dateTimeUtils = new DateTimeUtils(); month1 = dateTimeUtils.getCurrentMonth() + "/" + dateTimeUtils.getCurrentYear(); month2 = String.valueOf(dateTimeUtils.addMonth(-1)) + "/" + dateTimeUtils.addYearWithMonth(-1); month3 = String.valueOf(dateTimeUtils.addMonth(-2)) + "/" + dateTimeUtils.addYearWithMonth(-2); year1 = String.valueOf(dateTimeUtils.getCurrentYear()); year2 = String.valueOf(dateTimeUtils.getCurrentYear() - 1); } @Override protected Node[] createNodes(Object key) { final Enterprise enterprise1 = (Enterprise) key; Node result = new AbstractNode(new EnterpriseChildrenTongQuan(enterprise1), Lookups.singleton(enterprise1)) { @Override protected Sheet createSheet() { Sheet sheet = Sheet.createDefault(); Sheet.Set set = Sheet.createPropertiesSet(); Property thuMonth1Property = new PropertySupport.ReadOnly<String>(ThuMonth1_PROPERTY, String.class, "ThuM1", "aaa") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateImportByMonth(enterprise1, month1)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(thuMonth1Property); Property chiMonth1Property = new PropertySupport.ReadOnly<String>(ChiMonth1_PROPERTY, String.class, "ChiM1", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateExportByMonth(enterprise1, month1)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(chiMonth1Property); Property thuMonth2Property = new PropertySupport.ReadOnly<String>(ThuMonth2_PROPERTY, String.class, "ThuM2", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateImportByMonth(enterprise1, month2)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(thuMonth2Property); Property chiMonth2Property = new PropertySupport.ReadOnly<String>(ChiMonth2_PROPERTY, String.class, "ChiM2", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateExportByMonth(enterprise1, month2)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(chiMonth2Property); Property thuMonth3Property = new PropertySupport.ReadOnly<String>(ThuMonth3_PROPERTY, String.class, "ThuM3", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateImportByMonth(enterprise1, month3)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(thuMonth3Property); Property chiMonth3Property = new PropertySupport.ReadOnly<String>(ChiMonth3_PROPERTY, String.class, "ChiM3", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateExportByMonth(enterprise1, month3)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(chiMonth3Property); Property laiMonth1Property = new PropertySupport.ReadOnly<String>(Lai1_PROPERTY, String.class, "LaiM1", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateImportByMonth(enterprise1, month1) - calculateSPI.calculateExportByMonth(enterprise1, month1)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(laiMonth1Property); Property laiMonth2Property = new PropertySupport.ReadOnly<String>(Lai2_PROPERTY, String.class, "LaiM2", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateImportByMonth(enterprise1, month2) - calculateSPI.calculateExportByMonth(enterprise1, month2)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(laiMonth2Property); Property lMaionth3Property = new PropertySupport.ReadOnly<String>(Lai3_PROPERTY, String.class, "LaiM3", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateImportByMonth(enterprise1, month3) - calculateSPI.calculateExportByMonth(enterprise1, month3)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(lMaionth3Property); Property thuYear1Property = new PropertySupport.ReadOnly<String>(ThuYear1_PROPERTY, String.class, "ThuY1", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateImportByYear(enterprise1, year1)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(thuYear1Property); Property chiYear1Property = new PropertySupport.ReadOnly<String>(ChiYear1_PROPERTY, String.class, "ChiY1", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateExportByYear(enterprise1, year1)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(chiYear1Property); Property laiYear1Property = new PropertySupport.ReadOnly<String>(LaiYear1_PROPERTY, String.class, "LaiY1", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateImportByYear(enterprise1, year1) - calculateSPI.calculateExportByYear(enterprise1, year1)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(laiYear1Property); Property thuYear2Property = new PropertySupport.ReadOnly<String>(ThuYear2_PROPERTY, String.class, "ThuY2", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateImportByYear(enterprise1, year2)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(thuYear2Property); Property chiYear2Property = new PropertySupport.ReadOnly<String>(ChiYear2_PROPERTY, String.class, "ChiY2", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateExportByYear(enterprise1, year2)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(chiYear2Property); Property laiYear2Property = new PropertySupport.ReadOnly<String>(LaiYear2_PROPERTY, String.class, "LaiY2", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateImportByYear(enterprise1, year2) - calculateSPI.calculateExportByYear(enterprise1, year2)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(laiYear2Property); Property thuAllProperty = new PropertySupport.ReadOnly<String>(ThuAll_PROPERTY, String.class, "ThuAll", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateSumImportByEnterprise(enterprise1)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(thuAllProperty); Property chiAllProperty = new PropertySupport.ReadOnly<String>(ChiAll_PROPERTY, String.class, "ChiAll", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateSumExportByEnterprise(enterprise1)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(chiAllProperty); Property laiAllProperty = new PropertySupport.ReadOnly<String>(LaiAll_PROPERTY, String.class, "LaiAll", "bbb") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return String.valueOf(calculateSPI.calculateSumImportByEnterprise(enterprise1) - calculateSPI.calculateSumExportByEnterprise(enterprise1)); } @Override public PropertyEditor getPropertyEditor() { return new PropertyEditorSupport(); } }; set.put(laiAllProperty); sheet.put(set); return sheet; } }; result.setDisplayName(enterprise1.getEnterpriseName()); return new Node[]{result}; } @Override protected void addNotify() { super.addNotify(); Vector instr = new Vector(); for (Enterprise bean : list) { if (bean.getEnterpriseParent().toString().trim().length() == 0) { instr.addElement(bean); } } Enterprise[] enterprises = new Enterprise[instr.size()]; for (int i = 0; i < instr.size(); i++) { enterprises[i] = (Enterprise) instr.elementAt(i); } setKeys(enterprises); } }
51a3b60edbedbd4de4c479867067c1238166d2dd
bc02a3e570569b8d68c72c4f33d441df4bf12eaa
/DynamicProgramming/MaxElement.java
5ce33d9374791b1e6776ef2562e6d68748b8c2e0
[]
no_license
bmekewar/Java-Practice
55f3881250f346cf3697392e3246201b03e0cc63
f3844c2e7dd6abc287713b38726749f0cd004d91
refs/heads/master
2021-06-21T16:26:07.720457
2021-03-20T05:24:10
2021-03-20T05:24:10
199,047,206
0
0
null
null
null
null
UTF-8
Java
false
false
752
java
import java.util.Scanner; import java.util.Stack; public class MaxElement { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int N = sc.nextInt(); Stack<Integer> mainStack = new Stack<>(); Stack<Integer> maxStack = new Stack<>(); maxStack.push(Integer.MIN_VALUE); for(int i=0;i < N;i++){ int op=sc.nextInt(); switch(op){ case 1: int item = sc.nextInt(); mainStack.push(item); int maxSoFar = maxStack.peek(); if(item > maxSoFar){ maxStack.push(item); } else { maxStack.push(maxSoFar); } break; case 2: mainStack.pop(); maxStack.pop(); break; case 3: System.out.println(maxStack.peek()); break; } } } }
dd04f5348f72587fcf773267f4bee648b9a80bbc
e62ebb781b3c0999a5e6050273d53e65e1df6a7e
/test/ichikawa/assist/MedicalInstituteEMIS.java
129bbb5f932221ca5e5466f688f393f67849f011
[ "Apache-2.0" ]
permissive
h-crisis/assistant
60f3c9af95f91b2936cc3b5c99f6bca3bbd4c425
5b28d697d183f02c2e392f9418e27395a9a54c24
refs/heads/master
2021-01-23T21:48:32.650745
2017-07-25T01:16:12
2017-07-25T01:16:12
59,541,422
0
0
null
null
null
null
UTF-8
Java
false
false
9,224
java
package ichikawa.assist; import ichikawa.common.Shape2GeoJson; import org.geotools.data.DataUtilities; import org.geotools.feature.SchemaException; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.geometry.jts.JTSFactoryFinder; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Point; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; /** * Created by manabu on 2016/06/24. */ public class MedicalInstituteEMIS { private File medicalInstituteMasterFile; private File medicalInstituteStatusFile; private File combinedFile; private File shapeFile; private File jsonFile; private SimpleFeatureType simpleFeatureType; private List<SimpleFeature> features; MedicalInstituteEMIS(String masterFilePath, String statusFilePath, String outFilePath) throws IOException, SchemaException { medicalInstituteMasterFile = new File(masterFilePath); medicalInstituteStatusFile = new File(statusFilePath); combinedFile = new File(outFilePath); shapeFile = new File("files/medical_status.shp"); jsonFile = new File("files/medical_status.geojson"); simpleFeatureType = createFeatureType(); features = new ArrayList<SimpleFeature>(); checkFiles(medicalInstituteMasterFile, medicalInstituteStatusFile, combinedFile); } // ShapeファイルのFeatureタイプと測地系及び属性値の設定を行う private SimpleFeatureType createFeatureType() throws SchemaException { SimpleFeatureType type = DataUtilities.createType("Medical Institute", "the_geom:Point:srid=4612," + "code:String," + "name:String," + "prefecture:String," + "address:String," + // 5 "assist:String,mds:String,team:String,rd:String,atd:String," + // 5 "e001:String,e002:String,e003:String,e004:String,e005:String,e006:String,e007:String,e008:String,e009:String,e010:String,e011:String,e012:String," + "d_f001:String,d_f002:String,d_f003:String,d_f004:String,d_f005:String," + "d_l001:String,d_l002:String,d_l003:String,d_l004:String,d_l005:String,d_l006:String,d_l007:String," + "d_c001:String,d_c002:String," + "d_p001:String,d_p002:String,d_p003:String,d_p004:String,d_p005:String," + "d_k001:String,d_k002:String,d_k003:String,d_k004:String,d_k005:String,d_k006:String,d_k007:String,d_k008:String,d_k009:String,d_k010:String,d_k011:String,d_k012:String,d_k013:String," + "d_g001:String,d_g002:String,d_g003:String,d_g004:String,d_g005:String,d_g006:String,d_g007:String," + "d_s001:String,d_s002:String,d_s003:String,d_s004:String,d_s005:String,d_s006:String," + "d_o:String,d_i:String,d_date:String,aid:String,head:String,end:String" ); System.out.println("CreateFeatureType: " + type); return type; } private static void checkFiles(File masterFile, File statusFile, File outFile) throws IOException { if(!masterFile.exists()) throw new RuntimeException("医療機関マスターファイルがありません。"); else if(!statusFile.exists()) throw new RuntimeException("医療機関状況ファイルがありません。"); else if(!outFile.exists()) outFile.createNewFile(); BufferedReader masterFileBR = new BufferedReader(new InputStreamReader(new FileInputStream(masterFile),"Shift_JIS")); BufferedReader statusFileBR = new BufferedReader(new InputStreamReader(new FileInputStream(statusFile),"Shift_JIS")); String str1 = masterFileBR.readLine(); String str2 = statusFileBR.readLine(); int col1 = str1.split(",").length; int col2 = str2.split(",").length; int line1 = 1; int line2 = 1; while(str1!=null) { if(col1 != str1.split(",").length) throw new RuntimeException("医療機関マスターファイルの列数が揃っていません: " + line1); str1 = masterFileBR.readLine(); line1++; } while(str2!=null) { if(col2 != str2.split(",").length) { System.out.println(str2.split(",").length + " " + col2); throw new RuntimeException("医療機関状況ファイルの列数が揃っていません: " + line2); } str2 = statusFileBR.readLine(); line2++; } } public void comineMedicalInstituteFiles() throws IOException { System.out.println("医療機関マスターファイルと状況ファイルを結合します"); HashMap<String, String> masterMap = new HashMap<String, String>(); HashMap<String, String> statusMap = new HashMap<String, String>(); LinkedList<String> codeList = new LinkedList<String>(); BufferedReader masterFileBR = new BufferedReader(new InputStreamReader(new FileInputStream(medicalInstituteMasterFile),"Shift_JIS")); BufferedReader statusFileBR = new BufferedReader(new InputStreamReader(new FileInputStream(medicalInstituteStatusFile),"Shift_JIS")); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(combinedFile),"UTF-8"))); String masterStr; while((masterStr = masterFileBR.readLine()) != null) { String pair[] = masterStr.split(","); for(int i =0; i<pair.length; i++) pair[i].trim(); codeList.addLast(pair[0]); masterMap.put(pair[0], masterStr); } masterFileBR.close(); String statusStr; while((statusStr = statusFileBR.readLine()) != null) { String pair[] = statusStr.split(","); for(int i =0; i<pair.length; i++) pair[i].trim(); String str = "," + pair[3] + "," + pair[4]; for(int i = 6; i<pair.length; i++) { str = str + "," + pair[i]; } statusMap.put(pair[0], str); } statusFileBR.close(); for(int i=0; i<codeList.size(); i++) { String code = codeList.get(i); String str = masterMap.get(code); if(statusMap.containsKey(code)) { String pair[] = statusMap.get(code).split(","); for(int j=1; j<pair.length; j++) str = str + "," + pair[j]; } else str = str + ",未,未入力,0,,0,,,,,,,,,,,,,,,,,,,,,,,,,,,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,,,,,,,,0,0,0,0,0,0,,,,0,,1"; pw.println(str); } pw.close(); System.out.println("医療機関マスターファイルと状況ファイルを結合が完了しました"); } public void createFeatures() throws Exception { System.out.println("Featureの作成を開始します"); GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(simpleFeatureType); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(combinedFile),"UTF-8")); try { String line = br.readLine(); while((line=br.readLine())!=null) { String pair[] = line.split(","); double lat = Double.parseDouble(pair[6]); double lon = Double.parseDouble(pair[7]); String code = pair[0]; String name = pair[1]; String prefecture = pair[4]; String address = pair[5]; Point point = geometryFactory.createPoint(new Coordinate(lon, lat)); featureBuilder.add(point); featureBuilder.add(code); featureBuilder.add(name); featureBuilder.add(prefecture); featureBuilder.add(address); for(int i=12; i < pair.length; i++) { if(pair[i].length()>50) { System.out.println(pair[i] + ">>" + pair[i].substring(0, 50)); featureBuilder.add(pair[i].substring(0, 50) + "..."); } else featureBuilder.add(pair[i]); } SimpleFeature feature = featureBuilder.buildFeature(null); features.add(feature); } } finally { br.close(); } System.out.println(features.size() + "のFeatureの作成が完了しました"); } public void createShapeFile() throws Exception { CreateShape.createShapeFile(shapeFile, "utf-8", simpleFeatureType, features); } public void createGeoJsonFile() throws Exception { Shape2GeoJson.createGeoJson(shapeFile, "utf-8", jsonFile, "utf-8"); } }
1640d9c9fdadfab1d4c5fc4edfb9a3fe1661859f
1fc7ed938f13469b3a6dbc9c3b5a825265ffa0b0
/gmall-sms/src/main/java/com/atguigu/gmall/sms/controller/CouponSpuController.java
45f066487a680cb36e6662d8d4795e5c598fcd2b
[ "Apache-2.0" ]
permissive
shenpengfei-git/gmall-0822
d86c694bd48a9e413e850469491f55e1c4ea2e73
5ef213ff055f9d8f6841a83f8484de5d632d01b4
refs/heads/main
2023-06-11T23:21:29.405883
2021-07-06T02:27:55
2021-07-06T02:27:55
380,265,094
0
0
null
null
null
null
UTF-8
Java
false
false
2,475
java
package com.atguigu.gmall.sms.controller; import java.util.List; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.atguigu.gmall.sms.entity.CouponSpuEntity; import com.atguigu.gmall.sms.service.CouponSpuService; import com.atguigu.gmall.common.bean.PageResultVo; import com.atguigu.gmall.common.bean.ResponseVo; import com.atguigu.gmall.common.bean.PageParamVo; /** * 优惠券与产品关联 * * @author shenpengfei * @email [email protected] * @date 2021-06-26 21:02:24 */ @Api(tags = "优惠券与产品关联 管理") @RestController @RequestMapping("sms/couponspu") public class CouponSpuController { @Autowired private CouponSpuService couponSpuService; /** * 列表 */ @GetMapping @ApiOperation("分页查询") public ResponseVo<PageResultVo> queryCouponSpuByPage(PageParamVo paramVo){ PageResultVo pageResultVo = couponSpuService.queryPage(paramVo); return ResponseVo.ok(pageResultVo); } /** * 信息 */ @GetMapping("{id}") @ApiOperation("详情查询") public ResponseVo<CouponSpuEntity> queryCouponSpuById(@PathVariable("id") Long id){ CouponSpuEntity couponSpu = couponSpuService.getById(id); return ResponseVo.ok(couponSpu); } /** * 保存 */ @PostMapping @ApiOperation("保存") public ResponseVo<Object> save(@RequestBody CouponSpuEntity couponSpu){ couponSpuService.save(couponSpu); return ResponseVo.ok(); } /** * 修改 */ @PostMapping("/update") @ApiOperation("修改") public ResponseVo update(@RequestBody CouponSpuEntity couponSpu){ couponSpuService.updateById(couponSpu); return ResponseVo.ok(); } /** * 删除 */ @PostMapping("/delete") @ApiOperation("删除") public ResponseVo delete(@RequestBody List<Long> ids){ couponSpuService.removeByIds(ids); return ResponseVo.ok(); } }
bc8f3013f95fc608fb47681f4547fb0d18989d24
480071b4d4334592538633f30020ebbf483e1278
/android/titanium/src/org/appcelerator/titanium/util/TiBackgroundExecutor.java
d55e56c8465513f8719af6a862af5a56124a79ae
[ "Apache-2.0" ]
permissive
mwaylabs/titanium_mobile
86cd1135ed42020eb564912ad35337d132167872
b46790cf7094de17d9c34aa5d46c7f739967cafd
refs/heads/master
2021-01-21T01:20:06.160191
2011-02-15T16:43:41
2011-02-15T16:43:41
918,019
4
1
null
null
null
null
UTF-8
Java
false
false
521
java
package org.appcelerator.titanium.util; import java.util.concurrent.Executor; import java.util.concurrent.Executors; /** * This class is used to provide a global threadpool for background * execution throughout Titanium. */ public class TiBackgroundExecutor { private static final int MAX_THREADS = 10; private static Executor executor = null; public static void execute(Runnable command) { if (executor == null) { executor = Executors.newFixedThreadPool(MAX_THREADS); } executor.execute(command); } }
b54fb5c8914c57e941e344b39f0089eb98e84741
ed5159d056e98d6715357d0d14a9b3f20b764f89
/src/irvine/oeis/a305/A305065.java
c55072da36c8c7f330650d15f4ff6fee1622cc64
[]
no_license
flywind2/joeis
c5753169cf562939b04dd246f8a2958e97f74558
e5efd6971a0062ac99f4fae21a7c78c9f9e74fea
refs/heads/master
2020-09-13T18:34:35.080552
2019-11-19T05:40:55
2019-11-19T05:40:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
382
java
package irvine.oeis.a305; // Generated by gen_pattern.pl - DO NOT EDIT here! import irvine.oeis.GeneratingFunctionSequence; /** * A305065 <code>a(n) = 48*2^n - 24</code>. * @author Georg Fischer */ public class A305065 extends GeneratingFunctionSequence { /** Construct the sequence. */ public A305065() { super(0, new long[] {24}, new long[] {1, -3, 2}); } }
8cde8845768a9582cd0e8c1e41cacafecff677f7
33845250079521867f9c12f1e07d80e2a38fffa6
/src/main/java/cn/slkj/sloa/Entity/stock/Sim.java
738300cffae40ffed67301bf98285624ccf29ca2
[]
no_license
hhkj/sloa
f02d7d442cceaecad273f991311976ec1833a807
960894e7724e9534c17029af42574f17a8eac145
refs/heads/master
2020-03-27T09:54:07.739723
2018-09-11T09:02:39
2018-09-11T09:02:39
146,381,452
0
0
null
null
null
null
UTF-8
Java
false
false
6,097
java
package cn.slkj.sloa.Entity.stock; /** * * @ClassName: Sim * @Description: SIM卡信息 * @author maxuhui * */ public class Sim { private String id; /** * 运营商 */ private String cardType;// /** * 序列号 */ private String listnum;// /** * SIM卡号 */ private String telnum;// /** * 状态 1= 已用 else 未用 */ private int state;// 状态 value = 1 表示已用 else 未用 private int ustate;// 状态 value = 1 表示 出库 else 未出库 private String intime;// 入库时间 private String outtime;// 出库时间 private String kktime;// 开卡日期 private String fhtime;// 返回时间 private String renewtime;// 交费时间 private String business;// 金额 private String beizhu;// 备注 private String gys;// 供应商 private String lyr;// 领用人 private String department;// 领用部门 private String departmentName;// 领用部门 private String lrr;// 操作人 private String installers;// 安装人 private String installtime;// 安装时间 private String carNumber;// 车牌号 private String companyId;// 所属公司 private String companyName;// 所属公司 private String remark;// private int addType; // 添加类型 private String listNo; // 批量添加相同数字 private String listnum_begin; // 添加始数字 private String listnum_end; // 添加末数字 public int getAddType() { return addType; } public void setAddType(int addType) { this.addType = addType; } public String getListNo() { return listNo; } public void setListNo(String listNo) { this.listNo = listNo; } public String getListnum_begin() { return listnum_begin; } public void setListnum_begin(String listnum_begin) { this.listnum_begin = listnum_begin; } public String getListnum_end() { return listnum_end; } public void setListnum_end(String listnum_end) { this.listnum_end = listnum_end; } public int getUstate() { return ustate; } public void setUstate(int ustate) { this.ustate = ustate; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getInstallers() { return installers; } public void setInstallers(String installers) { this.installers = installers; } public String getInstalltime() { return installtime; } public void setInstalltime(String installtime) { this.installtime = installtime; } public String getCarNumber() { return carNumber; } public void setCarNumber(String carNumber) { this.carNumber = carNumber; } public String getCompanyId() { return companyId; } public void setCompanyId(String companyId) { this.companyId = companyId; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCardType() { return cardType; } public void setCardType(String cardType) { this.cardType = cardType; } public String getListnum() { return listnum; } public void setListnum(String listnum) { this.listnum = listnum; } public String getTelnum() { return telnum; } public void setTelnum(String telnum) { this.telnum = telnum; } public int getState() { return state; } public void setState(int state) { this.state = state; } public String getIntime() { return intime; } public void setIntime(String intime) { this.intime = intime; } public String getOuttime() { return outtime; } public void setOuttime(String outtime) { this.outtime = outtime; } public String getKktime() { return kktime; } public void setKktime(String kktime) { this.kktime = kktime; } public String getFhtime() { return fhtime; } public void setFhtime(String fhtime) { this.fhtime = fhtime; } public String getBeizhu() { return beizhu; } public void setBeizhu(String beizhu) { this.beizhu = beizhu; } public String getLyr() { return lyr; } public void setLyr(String lyr) { this.lyr = lyr; } public String getGys() { return gys; } public void setGys(String gys) { this.gys = gys; } public String getLrr() { return lrr; } public void setLrr(String lrr) { this.lrr = lrr; } public String getRenewtime() { return renewtime; } public void setRenewtime(String renewtime) { this.renewtime = renewtime; } public String getBusiness() { return business; } public void setBusiness(String business) { this.business = business; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } @Override public String toString() { return "Sim [id=" + id + ", cardType=" + cardType + "" + ", listnum=" + listnum + ", telnum=" + telnum + "" + ", state=" + state + ", ustate=" + ustate + "" + ", intime=" + intime + ", outtime=" + outtime + "" + ", kktime=" + kktime + ", fhtime=" + fhtime + "" + ", renewtime=" + renewtime + ", business=" + business + "" + ", beizhu=" + beizhu + ", gys=" + gys + "" + ", lyr=" + lyr + ", department=" + department + "" + ", departmentName=" + departmentName + ", lrr=" + lrr + "" + ", installers=" + installers + ", installtime=" + installtime + "" + ", carNumber=" + carNumber + ", companyId=" + companyId + "" + ", companyName=" + companyName + ", remark=" + remark + "" + ", addType=" + addType + ", listNo=" + listNo + "" + ", listnum_begin=" + listnum_begin + ", listnum_end=" + listnum_end + "]"; } }
40bc65593d96286d597773d644ece6c67ba21960
68296d704f28ab7f99d06a432b6a9900b246f290
/Task_6/src/main/java/manafov/bass/EdmBass.java
1029449cb98dd7b3ff555c0686b3e762bd8058ff
[]
no_license
SuperArt3000/JavaSchool2021
b47a6c59278dd960ddbb78e4fcc66f0b3326ca53
a1c1246043512d1bcb915f570773613b49b098fa
refs/heads/main
2023-05-14T15:12:53.657897
2021-06-08T04:50:54
2021-06-08T04:50:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
172
java
package manafov.bass; public class EdmBass implements Bass { public EdmBass() { System.out.println("Глубокий электронный бас!"); } }
05d85fba603821c648dab407323bb082010aeaac
6fb45478d0e492dd0588f44c86ac497fc8c93025
/Ficha Familiar 2/build/generated/source/buildConfig/test/debug/ucr/ff/test/BuildConfig.java
3b652aae9be7176bbc7af5f54f545d9d172d7c26
[]
no_license
luysk/Ficha
180e72d564bf68077caa6c9fc6c2debe38d6c70d
cd6b1d56fb2acba6b34189572d70d18230cb1866
refs/heads/master
2021-01-10T19:22:28.589931
2014-12-03T05:18:39
2014-12-03T05:19:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
425
java
/** * Automatically generated file. DO NOT MODIFY */ package ucr.ff.test; public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String PACKAGE_NAME = "ucr.ff.test"; public static final String BUILD_TYPE = "debug"; public static final String FLAVOR = ""; public static final int VERSION_CODE = -1; public static final String VERSION_NAME = ""; }
009fa25ccbc14cfa430d1bae958a14c62a391899
ecec3c418dbe378dab5203ef5e2d8695c589a351
/DesignPattern/src/edu/auburn/szw0069/VisitorPattern/Visitable.java
a4a07df99226155f1eabe01460107999950d5727
[]
no_license
Wilkhu90/Practice
29b1331076bb64ab49895d34b7759735aec62d57
e6bb6a1117be996e9d482ab50a86f58c424f0887
refs/heads/master
2020-04-25T16:58:43.234101
2015-08-21T17:37:48
2015-08-21T17:37:48
39,739,561
0
0
null
null
null
null
UTF-8
Java
false
false
116
java
package edu.auburn.szw0069.VisitorPattern; public interface Visitable { public double accept(Visitor visitor); }
80dae6f3d9a44efd4e662d86ba3e6805e11d3a01
dd797aabc5ecb6768938429cec7fd6c8c8da543f
/yjc-server/src/main/java/com/dk/config/ShiroConfiguration.java
6873585603ad68a61cbf46f024d41c4286feb674
[]
no_license
XEgithub/yjc-server
e63d18f8e21bd5c53f1b911c5d0360f160452885
05e145b6c1c1de59c86c59878d17a08643627258
refs/heads/master
2020-06-17T13:55:57.723523
2019-05-28T06:08:18
2019-05-28T06:08:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,715
java
package com.dk.config; import com.dk.shiro.MyShiroRealm; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.cache.ehcache.EhCacheManager; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition; import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * shiro-demo * * @author 张浩伟 * @version 1.01 2017年12月04日 */ @Configuration public class ShiroConfiguration { private static Logger log = LoggerFactory.getLogger(ShiroConfiguration.class); @Bean public EhCacheManager getEhCacheManager(){ EhCacheManager em = new EhCacheManager(); em.setCacheManagerConfigFile("classpath:ehcache-shiro.xml"); return em; } /** * 凭证匹配器 * (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了 * 所以我们需要修改下doGetAuthenticationInfo中的代码; * ) * @return */ @Bean public HashedCredentialsMatcher hashedCredentialsMatcher(){ HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); hashedCredentialsMatcher.setHashAlgorithmName("md5"); hashedCredentialsMatcher.setHashIterations(2); return hashedCredentialsMatcher; } @Bean(name = "myShiroRealm") public MyShiroRealm myShiroRealm(EhCacheManager cacheManager){ MyShiroRealm realm = new MyShiroRealm(); realm.setCacheManager(cacheManager); realm.setCredentialsMatcher(hashedCredentialsMatcher()); return realm; } @Bean(name = "lifecycleBeanPostProcessor") public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } @Bean public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator daap = new DefaultAdvisorAutoProxyCreator(); daap.setProxyTargetClass(true); return daap; } @Bean(name = "securityManager") public DefaultWebSecurityManager getDefaultWebSecurityManager(MyShiroRealm myShiroRealm) { DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager(); dwsm.setRealm(myShiroRealm); // <!-- 用户授权/认证信息Cache, 采用EhCache 缓存 --> dwsm.setCacheManager(getEhCacheManager()); return dwsm; } @Bean public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) { AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor(); aasa.setSecurityManager(securityManager); return aasa; } /** * 加载shiroFilter权限控制规则(从数据库读取然后配置) * * @author SHANHY * @create 2016年1月14日 */ // private void loadShiroFilterChain(ShiroFilterFactoryBean shiroFilterFactoryBean){ // /////////////////////// 下面这些规则配置最好配置到配置文件中 /////////////////////// // Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); // // authc:该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter //// filterChainDefinitionMap.put("/admin/**", "authc,roles[superadmin]");// 这里为了测试,只限制/user,实际开发中请修改为具体拦截的请求规则 // // anon:它对应的过滤器里面是空的,什么都没做 // log.info("##################从数据库读取权限规则,加载到shiroFilter中##################"); //// filterChainDefinitionMap.put("/admin/role/**", "authc,roles[admin]");// 这里为了测试,固定写死的值,也可以从数据库或其他配置中读取 // filterChainDefinitionMap.put("/admin/**", "authc");// 这里为了测试,固定写死的值,也可以从数据库或其他配置中读取 // // //// filterChainDefinitionMap.put("/admin/sss", "authc,perms[user:edit]");// 这里为了测试,固定写死的值,也可以从数据库或其他配置中读取 // // filterChainDefinitionMap.put("/login", "anon"); // filterChainDefinitionMap.put("/wx/**", "anon"); // filterChainDefinitionMap.put("/**", "anon");//anon 可以理解为不拦截 // // shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); // } /** * ShiroFilter<br/> * 注意这里参数中的 StudentService 和 IScoreDao 只是一个例子,因为我们在这里可以用这样的方式获取到相关访问数据库的对象, * 然后读取数据库相关配置,配置到 shiroFilterFactoryBean 的访问规则中。实际项目中,请使用自己的Service来处理业务逻辑。 * * @param securityManager * @return * @author SHANHY * @create 2016年1月14日 */ // @Bean(name = "shiroFilter") // public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager) { // // ShiroFilterFactoryBean shiroFilterFactoryBean = new MShiroFilterFactoryBean(); // // 必须设置 SecurityManager // shiroFilterFactoryBean.setSecurityManager(securityManager); // // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面 // shiroFilterFactoryBean.setLoginUrl("/login"); // // 登录成功后要跳转的连接 // shiroFilterFactoryBean.setSuccessUrl("/admin/user/list"); // shiroFilterFactoryBean.setUnauthorizedUrl("/403"); // // loadShiroFilterChain(shiroFilterFactoryBean); // return shiroFilterFactoryBean; // } @Bean public ShiroFilterChainDefinition shiroFilterChainDefinition() { DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition(); // chainDefinition.addPathDefinition("/admin/**", "authc"); chainDefinition.addPathDefinition("/login", "anon"); chainDefinition.addPathDefinition("/wx/**", "anon"); chainDefinition.addPathDefinition("/**", "anon");//anon 可以理解为不拦截 return chainDefinition; } }
ae412a0e2fff9ae1b101d5d7178754a4dc64eb59
7ffb6b3fa7946f9934d34f43e646b7ef38ee67a4
/src/com/dicoding/javafundamental/belajar/primitivetypes/Cba.java
b722c88c1e844952b76f07ee3e7de939946f3fcd
[]
no_license
milanadila/learning-algirthm
eae3bcb7fad82741a88251a380a7b22286fa8217
b7b9654f941a492238c37dca987183654c54afe6
refs/heads/master
2020-07-30T17:53:28.467281
2020-01-14T04:05:28
2020-01-14T04:05:28
210,309,018
0
0
null
null
null
null
UTF-8
Java
false
false
285
java
package com.dicoding.javafundamental.belajar.primitivetypes; public class Cba { public static void main(String[] args) { double a = 2; double b = 8; double hasil= Math.pow(a, b); System.out.println(hasil); int[] arr = new int[5]; } }
0fef1653a23abf135095c1cffb5dd62ad23a52ea
25378f49d8b555789ddd36e180f0469de72a3b03
/src/main/java/com/controller/CounterController.java
e2877c29c4dcf89b2be20f316680f76557bf8b99
[]
no_license
luctr/Session-TH1
ee5d4e0633b55b8c65a7c458105deb248b5a1a45
364ca989ccdbb44124616e48c60b6531390b9666
refs/heads/master
2023-06-25T06:37:27.917865
2021-07-27T02:49:41
2021-07-27T02:49:41
389,828,838
0
0
null
null
null
null
UTF-8
Java
false
false
619
java
package com.controller; import com.model.Counter; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.SessionAttributes; @Controller @SessionAttributes("counter") public class CounterController { @ModelAttribute("counter") public Counter setUpCounter(){ return new Counter(); } @GetMapping("/") public String get(@ModelAttribute("counter")Counter counter){ counter.increment(); return "/index"; } }
d99ac4f6e7f660f51736b590804a9e7c05ff1329
7706f51c5ed0356bbcccb1f6ea7c466ff35c81cf
/PracticeSessions/src/OOP3/Animal.java
88a08793e51014a93a9952006b46ce7604ac377e
[]
no_license
JSabrin/TestingRepository
9d2ffa1fe19263d863275c9cffc68bcf06be0537
d1fa3e8206303f36a5257718e1b564efecc97b15
refs/heads/master
2020-04-23T14:25:25.651028
2019-02-18T07:06:39
2019-02-18T07:06:39
171,231,314
0
0
null
null
null
null
UTF-8
Java
false
false
119
java
package OOP3; public abstract class Animal { public final void eat (){ System.out.println("Animal --- eat"); } }
94d9d35c0a365f0f117a0647ecc386739296063b
6354c618a1e9213f0605c6b3e5da2449a4873d2c
/src/main/java/stevekung/mods/moreplanets/utils/debug/GuiListEntityFilter.java
3d6dd4ad56b55fdd191e3cd4c57cc18111d0bcff
[ "MIT" ]
permissive
SteveKunG/MorePlanets
a13d04244b7dec2eae2784ee8de835aaabe433e8
ff343a7e087e18eeeb2783dc7e984a7dcc7eec06
refs/heads/1.12.2
2023-03-16T19:18:12.993448
2023-03-09T11:30:32
2023-03-09T11:30:32
94,581,238
32
37
MIT
2023-08-30T22:48:34
2017-06-16T21:07:26
Java
UTF-8
Java
false
false
8,927
java
package stevekung.mods.moreplanets.utils.debug; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.annotation.Nullable; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiListExtended; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.EntityList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.MathHelper; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import stevekung.mods.moreplanets.utils.LoggerMP; import stevekung.mods.stevekunglib.utils.client.GLConstants; @SideOnly(Side.CLIENT) public class GuiListEntityFilter extends GuiListExtended { private final GuiShieldGeneratorEntityFilter parent; private final List<GuiListEntityFilterEntry> entries = new ArrayList<>(); private int selectedIdx = -1; public GuiListEntityFilter(GuiShieldGeneratorEntityFilter parent, Minecraft mc, int width, int height, int top, int bottom, int slotHeight) { super(mc, width, height, top, bottom, slotHeight); this.parent = parent; this.initEntityList(); } public void initEntityList() { Set<ResourceLocation> list = null; try { list = EntityList.getEntityNameList(); } catch (Exception e) { LoggerMP.error("Unable to collect entities name list!"); } for (ResourceLocation name : list) { this.entries.add(new GuiListEntityFilterEntry(this, name.toString())); } } @Override public GuiListEntityFilterEntry getListEntry(int index) { return this.entries.get(index); } @Override protected int getSize() { return this.entries.size(); } @Override protected int getScrollBarX() { return super.getScrollBarX() + 20; } @Override public int getListWidth() { return super.getListWidth() + 50; } @Override protected boolean isSelected(int index) { return index == this.selectedIdx; } @Override protected void drawContainerBackground(Tessellator tessellator) {} @Override protected void overlayBackground(int startY, int endY, int startAlpha, int endAlpha) {} @Override protected void drawSelectionBox(int insideLeft, int insideTop, int mouseXIn, int mouseYIn, float partialTicks) { int i = this.getSize(); Tessellator tessellator = Tessellator.getInstance(); BufferBuilder vertexbuffer = tessellator.getBuffer(); for (int j = 0; j < i; ++j) { int k = insideTop + j * this.slotHeight + this.headerPadding; int l = this.slotHeight - 4; if (k > this.bottom || k + l < this.top) { this.updateItemPos(j, insideLeft, k, partialTicks); } if (this.showSelectionBox && this.isSelected(j)) { int i1 = this.left + this.width / 2 - this.getListWidth() / 2; int j1 = this.left + this.width / 2 + this.getListWidth() / 2; GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); GlStateManager.disableTexture2D(); vertexbuffer.begin(GLConstants.QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); vertexbuffer.pos(i1, k + l + 2, 0.0D).tex(0.0D, 1.0D).color(128, 128, 128, 255).endVertex(); vertexbuffer.pos(j1, k + l + 2, 0.0D).tex(1.0D, 1.0D).color(128, 128, 128, 255).endVertex(); vertexbuffer.pos(j1, k - 2, 0.0D).tex(1.0D, 0.0D).color(128, 128, 128, 255).endVertex(); vertexbuffer.pos(i1, k - 2, 0.0D).tex(0.0D, 0.0D).color(128, 128, 128, 255).endVertex(); vertexbuffer.pos(i1 + 1, k + l + 1, 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 255).endVertex(); vertexbuffer.pos(j1 - 1, k + l + 1, 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); vertexbuffer.pos(j1 - 1, k - 1, 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 255).endVertex(); vertexbuffer.pos(i1 + 1, k - 1, 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 255).endVertex(); tessellator.draw(); GlStateManager.enableTexture2D(); } this.drawSlot(j, insideLeft, k, l, mouseXIn, mouseYIn, partialTicks); } } @Override public void drawScreen(int mouseXIn, int mouseYIn, float partialTicks) { if (this.visible) { this.mouseX = mouseXIn; this.mouseY = mouseYIn; this.drawBackground(); int i = this.getScrollBarX(); int j = i + 6; this.bindAmountScrolled(); GlStateManager.disableLighting(); GlStateManager.disableFog(); Tessellator tessellator = Tessellator.getInstance(); BufferBuilder vertexbuffer = tessellator.getBuffer(); this.drawContainerBackground(tessellator); int k = this.left + this.width / 2 - this.getListWidth() / 2 + 2; int l = this.top + 4 - (int)this.amountScrolled; if (this.hasListHeader) { this.drawListHeader(k, l, tessellator); } this.drawSelectionBox(k, l, mouseXIn, mouseYIn, partialTicks); GlStateManager.disableDepth(); this.overlayBackground(0, this.top, 255, 255); this.overlayBackground(this.bottom, this.height, 255, 255); GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ZERO, GlStateManager.DestFactor.ONE); GlStateManager.disableAlpha(); GlStateManager.shadeModel(7425); GlStateManager.disableTexture2D(); int j1 = this.getMaxScroll(); if (j1 > 0) { int k1 = (this.bottom - this.top) * (this.bottom - this.top) / this.getContentHeight(); k1 = MathHelper.clamp(k1, 32, this.bottom - this.top - 8); int l1 = (int)this.amountScrolled * (this.bottom - this.top - k1) / j1 + this.top; if (l1 < this.top) { l1 = this.top; } vertexbuffer.begin(GLConstants.QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); vertexbuffer.pos(i, this.bottom, 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 255).endVertex(); vertexbuffer.pos(j, this.bottom, 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); vertexbuffer.pos(j, this.top, 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 255).endVertex(); vertexbuffer.pos(i, this.top, 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 255).endVertex(); tessellator.draw(); vertexbuffer.begin(GLConstants.QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); vertexbuffer.pos(i, l1 + k1, 0.0D).tex(0.0D, 1.0D).color(128, 128, 128, 255).endVertex(); vertexbuffer.pos(j, l1 + k1, 0.0D).tex(1.0D, 1.0D).color(128, 128, 128, 255).endVertex(); vertexbuffer.pos(j, l1, 0.0D).tex(1.0D, 0.0D).color(128, 128, 128, 255).endVertex(); vertexbuffer.pos(i, l1, 0.0D).tex(0.0D, 0.0D).color(128, 128, 128, 255).endVertex(); tessellator.draw(); vertexbuffer.begin(GLConstants.QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); vertexbuffer.pos(i, l1 + k1 - 1, 0.0D).tex(0.0D, 1.0D).color(192, 192, 192, 255).endVertex(); vertexbuffer.pos(j - 1, l1 + k1 - 1, 0.0D).tex(1.0D, 1.0D).color(192, 192, 192, 255).endVertex(); vertexbuffer.pos(j - 1, l1, 0.0D).tex(1.0D, 0.0D).color(192, 192, 192, 255).endVertex(); vertexbuffer.pos(i, l1, 0.0D).tex(0.0D, 0.0D).color(192, 192, 192, 255).endVertex(); tessellator.draw(); } this.renderDecorations(mouseXIn, mouseYIn); GlStateManager.enableTexture2D(); GlStateManager.shadeModel(7424); GlStateManager.enableAlpha(); GlStateManager.disableBlend(); } } public void selectEntity(int index) { this.selectedIdx = index; this.parent.selectEntity(this.getSelectedEntity()); } @Nullable public GuiListEntityFilterEntry getSelectedEntity() { return this.selectedIdx >= 0 && this.selectedIdx < this.getSize() ? this.getListEntry(this.selectedIdx) : null; } public GuiShieldGeneratorEntityFilter getGuiSelection() { return this.parent; } }
7e4e74ea22c8e7fdf3553c2e4521014b806e79c6
78431b1baab70e838142efcc910c1ac577cebbb0
/IfElse.java
04146f071fa78909dca7cd2e68d96520b8e71f8c
[]
no_license
msanzar87/JavaPractice2
4b694c774ba4633835c8d22b8347760fcddd37b5
ccdb23506a57ff739e16298ad327dbfff8135791
refs/heads/main
2023-08-21T13:44:03.192246
2021-10-07T07:22:30
2021-10-07T07:22:30
409,795,258
0
0
null
null
null
null
UTF-8
Java
false
false
492
java
public class IfElse { public static void main(String[] args) { int grade = 45; if (grade >= 80){ System.out.println("you got an A!"); }else if(grade>=70){ System.out.println("you got a B!"); }else if(grade>=60){ System.out.println("you got a C!"); }else if(grade>=50){ System.out.println("you got a D!"); }else { System.out.println("Study harder next time!"); } } }
8497da34779eaae52ad63e3ade9420d002609b89
0ed5ac941aee7aea4a64094370c44659c7f3a780
/src/tempo/addinterestrate.java
13ce03621c97aa7817500a4bee30884823263d31
[]
no_license
vsvnimish/Interest-calculation-system
a1ba4702e0e4a44695a1fcbd2e8c276bb554a67d
05247a98e624990bd7cd9ce65c4f1658bdda40a2
refs/heads/main
2023-01-31T05:16:44.605352
2020-12-14T17:03:09
2020-12-14T17:03:09
321,415,146
0
0
null
null
null
null
UTF-8
Java
false
false
13,611
java
/* * 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 tempo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /** * * @author vsvnimish */ public class addinterestrate extends javax.swing.JFrame { /** * Creates new form addinterestrate */ public addinterestrate() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); fieldforenteringaccounttype = new javax.swing.JTextField(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jLabel2 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); addingbutton = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel1.setText("account type"); fieldforenteringaccounttype.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fieldforenteringaccounttypeActionPerformed(evt); } }); jRadioButton1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jRadioButton1.setText("is account type related to deposits"); jRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton1ActionPerformed(evt); } }); jRadioButton2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jRadioButton2.setText("is account type related to loans"); jRadioButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton2ActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel2.setText("interset rate(per month)"); addingbutton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N addingbutton.setText("add"); addingbutton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addingbuttonActionPerformed(evt); } }); jButton1.setText("back"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(81, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jRadioButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(71, 71, 71))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(8, 8, 8) .addComponent(fieldforenteringaccounttype, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jRadioButton1)) .addGap(73, 73, 73)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(93, 93, 93) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(55, 55, 55) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(220, 220, 220) .addComponent(addingbutton, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(33, 33, 33) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(fieldforenteringaccounttype, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton2) .addComponent(jRadioButton1)) .addGap(49, 49, 49) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(83, 83, 83) .addComponent(addingbutton, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(102, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed // TODO add your handling code here: jRadioButton2.setSelected(false); }//GEN-LAST:event_jRadioButton1ActionPerformed private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed // TODO add your handling code here: jRadioButton1.setSelected(false); }//GEN-LAST:event_jRadioButton2ActionPerformed private void fieldforenteringaccounttypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fieldforenteringaccounttypeActionPerformed // TODO add your handling code here: }//GEN-LAST:event_fieldforenteringaccounttypeActionPerformed private void addingbuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addingbuttonActionPerformed // TODO add your handling code here: String[] list = new String[4]; list[0] = fieldforenteringaccounttype.getText(); if (jRadioButton1.isSelected()) { list[1] = "yes"; list[2] = "no"; } else { list[2] = "yes"; list[1] = "no"; } list[3] = jTextField1.getText(); System.out.println("please1"); relatedtodatabase base = new relatedtodatabase(); System.out.println("please"); int m = 0; System.out.println("vsitthere"); // m=base.search(list[0]); System.out.println("isitthere"); Connection con = null; try { try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException ex) { Logger.getLogger(relatedtodatabase.class.getName()).log(Level.SEVERE, null, ex); } con=DriverManager.getConnection("jdbc:mysql://localhost:3306/datatable","root","nimishraja"); } catch (SQLException ex) { Logger.getLogger(relatedtodatabase.class.getName()).log(Level.SEVERE, null, ex); } PreparedStatement statement; statement=con.prepareStatement("select * from accounttypes"); // statement.setString(1,userid); //con=v.prepareStatement("select * from salary"); ResultSet rs=statement.executeQuery(); boolean b=rs.next();; String string; while(b==true){ string=rs.getString("accounttype"); b=rs.next(); if(string.equals(list[0])){ m=1; } } //System.out.println(m); if(m==0){ try { // base.add("accounttypes",list); base.add("accounttypes", list); JOptionPane.showMessageDialog(this,"added sucessfully","message",JOptionPane.PLAIN_MESSAGE); } catch (ClassNotFoundException ex) { Logger.getLogger(addinterestrate.class.getName()).log(Level.SEVERE, null, ex); } } else{ System.out.println("accounttype already exists"); JOptionPane.showMessageDialog(this,"accounttype already exists","Invalid",JOptionPane.PLAIN_MESSAGE); } }//GEN-LAST:event_addingbuttonActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: setVisible(false); new admininterestrates().setVisible(true); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(addinterestrate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(addinterestrate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(addinterestrate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(addinterestrate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new addinterestrate().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addingbutton; private javax.swing.JTextField fieldforenteringaccounttype; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
892905cb06cd902fe4a1a012a4fd71f5dc3cc820
859d6557bb1935c1d5610ef78af5442f88ccf442
/Examples/src/java/com/basilv/examples/mutableproperties/Order.java
961ee23329708a8a392a7196d211aae637137482
[]
no_license
basilv/Java-Examples
78f3632e51a4a5feff7f3c8ab7d8c8abf4a23ea7
57dee96b149de72f9d892d99e3eb3253805c882f
refs/heads/master
2021-01-23T08:57:08.802731
2012-03-06T05:19:12
2012-03-06T05:19:12
3,627,255
0
0
null
null
null
null
UTF-8
Java
false
false
356
java
// Copyright 2008 by Basil Vandegriend. All rights reserved. package com.basilv.examples.mutableproperties; import java.util.Calendar; public class Order { private Calendar date = Calendar.getInstance(); public Calendar getDate() { return date; } public void setDate(Calendar calendar) { this.date = calendar; } }
da20fe370f652ba63d0414fb30d74c025d8e3a32
fbd56eed89772e86f3137ebe8ef4ad72b9b75c33
/src/main/java/section5/DiagonalStar.java
1d50641e8c3b64468f910a5c98943be9dc64468a
[]
no_license
CatalinaSapca/MasterclassJava
d2cc63ca3e1235c489b856dc6f544a0e3e411b70
84593651fc32acd4628e1995b80ff96a30834f87
refs/heads/main
2023-06-19T10:10:43.292654
2021-07-15T18:03:47
2021-07-15T18:07:51
386,372,894
0
0
null
null
null
null
UTF-8
Java
false
false
773
java
package section5; public class DiagonalStar { public static void printSquareStar(int number){ if(number < 5){ System.out.println("Invalid Value"); return; } for(int i = 1; i<=number; i++){ for(int j = 1; j<=number; j++){ //daca ne aflam pe una din laturi || daca ne aflam pe diagonala principala || daca ne aflam pe diagonala secundara if(i == 1 || j == 1 || i == number || j == number || (i+j == number + 1) || i==j) System.out.print("*"); else System.out.print(" "); } System.out.print("\n"); } } public static void main(String[] args){ printSquareStar(25); } }
c20206c51e0fefd19354002e22d4ed59b27e298c
201238ee82be88f09478e6e39bfd0cd746ffbda2
/src/main/java/cc/zpfang/es/model/User.java
6bc8fee1944becf3779c4b59d64d8c3bf2ff396b
[]
no_license
zpfang/CodeChip
1a62ffbe98c2b25add9ee4003474c206b64647db
485b9e0d739529bd7283339d2eefff7b0601d488
refs/heads/master
2020-09-07T14:43:19.623485
2018-01-09T01:01:32
2018-01-09T01:01:32
94,430,832
0
0
null
null
null
null
UTF-8
Java
false
false
300
java
package cc.zpfang.es.model; import lombok.Getter; import lombok.Setter; /** * Description: * Created by zpfang on 2017/7/9. */ @Getter @Setter public class User { private Long id; private String name; private Integer age; private String address; private String groupCode; }
c61518cecb1c61ea7ac8fc2eadaa780e8d8ec58e
bc720aeaea099aa38782dcb7d9749554b7d182e4
/HW2/src/certi/MyRecordReader.java
ebff129aa79d241fc3045e22db53c32bce734563
[]
no_license
kiriti811/MapReduce
3665d527f774ba709af7fd4edd17b706d049b17c
bfa69fb79b012a3e77fcb3a033ccf45e63eaad99
refs/heads/master
2021-01-01T03:33:27.264247
2016-04-30T05:45:24
2016-04-30T05:45:24
57,428,931
0
0
null
null
null
null
UTF-8
Java
false
false
1,567
java
package certi; import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.LineRecordReader; public class MyRecordReader extends RecordReader<Text, Text> { LineRecordReader line = null; Text first = new Text(); Text second = new Text(); @Override public void close() throws IOException { // TODO Auto-generated method stub line.close(); } @Override public Text getCurrentKey() throws IOException, InterruptedException { // TODO Auto-generated method stub return first; } @Override public Text getCurrentValue() throws IOException, InterruptedException { // TODO Auto-generated method stub return second; } @Override public float getProgress() throws IOException, InterruptedException { // TODO Auto-generated method stub return line.getProgress(); } @Override public void initialize(InputSplit arg0, TaskAttemptContext arg1) throws IOException, InterruptedException { // TODO Auto-generated method stub line = new LineRecordReader(); initialize(arg0, arg1); } @Override public boolean nextKeyValue() throws IOException, InterruptedException { // TODO Auto-generated method stub if(!line.nextKeyValue()){ Text lineValue = line.getCurrentValue(); first = new Text("XYZ"); second = new Text("ABC"); return true; } else{ return false; } } }
29809f7a623b966201e885e98099ceeaa2925f51
910305c84c16e806148fef4218adeafd311271c8
/app/src/test/java/com/example/lijiang/login/ExampleUnitTest.java
438a4b1c3388cb89c6cc3c6f292087bd2e1863e8
[]
no_license
LJLuke/Login
7159c4842f6b1334ff662309be117e00b7b91273
80110a50e2864a57b9dfd14e7460100b45cc393c
refs/heads/master
2020-06-18T19:30:29.283557
2016-11-25T10:02:05
2016-11-25T10:02:05
74,746,269
0
0
null
null
null
null
UTF-8
Java
false
false
318
java
package com.example.lijiang.login; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
364a0d75107f74ca94f74db2131f1f637d673c51
53fab0d8e9ab09577cdb57c68f8937086de669e5
/OpenClosed/test/MyListTest.java
bb76d6f876edb6a9ad5ca61aa0d6d664f9acab07
[ "MIT" ]
permissive
ycswaves/SG-ObjectBootcamp
f42ab9144e0ecf2440f9d038cfdbf907ff3e3370
8d1a4f6be3b72db4b0c012ef2222ff7468a5e299
refs/heads/master
2021-01-14T08:31:04.789793
2016-09-15T14:55:43
2016-09-15T14:55:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,561
java
import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; public class MyListTest { @Test public void shouldStartEmpty(){ MyList list = new MyList(); assertThat(list.isEmpty(), is(true)); } @Test public void shouldAddToFront(){ MyList list = new MyList(); list.AddToFront(98); list.AddToFront(99); list.AddToFront(100); assertThat(list.PeekAt(0), is(equalTo(100))); } @Test public void shouldAddToBack(){ MyList list = new MyList(); list.AddToFront(98); list.AddToFront(99); list.AddToBack(100); assertThat(list.PeekAt(2), is(equalTo(100))); } @Test public void shouldAddInPosition(){ MyList list = new MyList(); list.AddToFront(98); list.AddToFront(99); list.AddAt(1, 100); assertThat(list.PeekAt(1), is(equalTo(100))); } @Test public void shouldCountItems(){ MyList list = new MyList(); list.AddToFront(98); list.AddToFront(99); list.AddToFront(100); assertThat(list.size(), is(equalTo(3))); } @Test public void shouldTakeFromFront(){ MyList list = new MyList(); list.AddToFront(98); list.AddToFront(99); list.AddToFront(100); assertThat(list.takeItemFromFront(), is(equalTo(100))); assertThat(list.size(), is(equalTo(2))); } }
8648af4bd962f478ec68adb030c957b85fc73265
48e835e6f176a8ac9ae3ca718e8922891f1e5a18
/benchmark/training/org/jboss/as/test/integration/ejb/security/SingleMethodsAnnSLSBTestCase.java
4f2fc4ac7a4f27a86ed0c7830eee399c006acba5
[]
no_license
STAMP-project/dspot-experiments
f2c7a639d6616ae0adfc491b4cb4eefcb83d04e5
121487e65cdce6988081b67f21bbc6731354a47f
refs/heads/master
2023-02-07T14:40:12.919811
2019-11-06T07:17:09
2019-11-06T07:17:09
75,710,758
14
19
null
2023-01-26T23:57:41
2016-12-06T08:27:42
null
UTF-8
Java
false
false
2,602
java
/** * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ejb.security; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.categories.CommonCriteria; import org.jboss.logging.Logger; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; /** * Checks whether basic EJB authorization works from EJB client to remote stateful EJB. * * @author <a href="mailto:[email protected]">Peter Skopek</a> */ @RunWith(Arquillian.class) @RunAsClient @Category(CommonCriteria.class) public class SingleMethodsAnnSLSBTestCase extends AnnSBTest { private static final Logger log = Logger.getLogger(SingleMethodsAnnSLSBTestCase.testClass()); private static final String MODULE = "singleMethodsAnnOnlySLSB"; @Test public void testSingleMethodAnnotationsNoUser() throws Exception { testSingleMethodAnnotationsNoUserTemplate(SingleMethodsAnnSLSBTestCase.MODULE, SingleMethodsAnnSLSBTestCase.log, SingleMethodsAnnSLSBTestCase.beanClass()); } @Test public void testSingleMethodAnnotationsUser1() throws Exception { testSingleMethodAnnotationsUser1Template(SingleMethodsAnnSLSBTestCase.MODULE, SingleMethodsAnnSLSBTestCase.log, SingleMethodsAnnSLSBTestCase.beanClass()); } @Test public void testSingleMethodAnnotationsUser2() throws Exception { testSingleMethodAnnotationsUser2Template(SingleMethodsAnnSLSBTestCase.MODULE, SingleMethodsAnnSLSBTestCase.log, SingleMethodsAnnSLSBTestCase.beanClass()); } }
f5582b17bf2c2f7ac6461eff9afd886695f37e02
4d0f2d62d1c156d936d028482561585207fb1e49
/Ma nguon/zcs-8.0.2_GA_5570-src/ZimbraCommon/src/java/com/zimbra/common/stats/RealtimeStatsCallback.java
2e0a679e9e6530d1694905da286c93ee64773d30
[]
no_license
vuhung/06-email-captinh
e3f0ff2e84f1c2bc6bdd6e4167cd7107ec42c0bd
af828ac73fc8096a3cc096806c8080e54d41251f
refs/heads/master
2020-07-08T09:09:19.146159
2013-05-18T12:57:24
2013-05-18T12:57:24
32,319,083
0
2
null
null
null
null
UTF-8
Java
false
false
699
java
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2006, 2007, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.common.stats; import java.util.Map; public interface RealtimeStatsCallback { public Map<String, Object> getStatData(); }
[ "[email protected]@ec614674-f94a-24a8-de76-55dc00f2b931" ]
[email protected]@ec614674-f94a-24a8-de76-55dc00f2b931
d11163ae87061090857f118479ac5f49207cd5a7
af97c0b0607989f4db87f9e8e485b8d5d6aa1f44
/src/main/java/com/sauloborges/ysura/service/ParkingSpaceServiceImpl.java
bbecf6d7480ab970d70869aa1406c32fa803be5d
[]
no_license
saudborg/garage
3be3277e9179b92b25f3e2ef43b188192765a56d
c7694f6a755c228ef38951ff918edcf05b8b7ffe
refs/heads/master
2020-05-29T17:09:55.735346
2016-01-24T16:50:54
2016-01-24T16:50:54
50,198,361
0
0
null
null
null
null
UTF-8
Java
false
false
3,248
java
package com.sauloborges.ysura.service; import java.util.Calendar; import java.util.List; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.sauloborges.ysura.domain.ParkingSpace; import com.sauloborges.ysura.domain.Vehicle; import com.sauloborges.ysura.exception.NoMoreSpacesException; import com.sauloborges.ysura.repository.ParkingSpaceRepository; @Service public class ParkingSpaceServiceImpl implements ParkingSpaceService { private final Logger logger = LoggerFactory.getLogger(ParkingSpaceServiceImpl.class); private static final Random RANDOM = new Random(); @Autowired private ParkingSpaceRepository parkingSpaceRepository; /** * Save a parking space */ @Override public ParkingSpace save(ParkingSpace parkingSpace) { logger.debug("call parkingSpace.save [" + parkingSpace + "]"); parkingSpace = parkingSpaceRepository.save(parkingSpace); logger.debug("call parkingSpace.save saved[id=" + parkingSpace.getId() + "]"); return parkingSpace; } @Override public List<ParkingSpace> getList() { logger.debug("call parkingSpace.findAll"); return parkingSpaceRepository.findAll(); } public ParkingSpace updateToOccupied(ParkingSpace parkingSpace, Vehicle vehicle) { logger.debug("call parkingSpace.updateToOcupped params[" + parkingSpace + ", " + vehicle + "]"); parkingSpace.setVehicle(vehicle); parkingSpace.setTimeEnter(Calendar.getInstance()); return this.save(parkingSpace); } public ParkingSpace updateToFree(ParkingSpace parkingSpace) { logger.debug("call parkingSpace.updateToFree params[" + parkingSpace + "]"); // set null means the space is free parkingSpace.setVehicle(null); parkingSpace.setTimeEnter(null); return this.save(parkingSpace); } /** * Return a list of spaces that are free */ @Override public List<ParkingSpace> getFreeSpaces() { logger.debug("call parkingSpace.findAllFreeSpaces"); List<ParkingSpace> allFreeSpaces = parkingSpaceRepository.getAllFreeSpaces(); logger.debug("call parkingSpace.findAllFreeSpaces - ok"); return allFreeSpaces; } /** * Get a free space in a garage. If is full throw a excpetion telling this */ @Override public ParkingSpace getAFreeSpace() throws NoMoreSpacesException { logger.debug("call parkingSpace.getAFreeSpace"); List<ParkingSpace> allFreeSpaces = this.getFreeSpaces(); if (allFreeSpaces.size() == 0) { throw new NoMoreSpacesException(); } ParkingSpace space = allFreeSpaces.get(RANDOM.nextInt(allFreeSpaces.size())); logger.debug("call parkingSpace.getAFreeSpace space=[" + space.getParkingLevel().getNumber() + "," + space.getNumber()); return space; } @Override public ParkingSpace findVehicleInAParkingSpaceByLicencePlate(String licencePlate) { logger.debug("call parkingSpace.findVehicleInAParkingSpaceByLicencePlate param=[" + licencePlate + "]"); return parkingSpaceRepository.findVehicleInAParkingSpaceByLicencePlate(licencePlate); } @Override public ParkingSpace findById(Integer id) { logger.debug("call parkingSpace.findById param=[" + id + "]"); return parkingSpaceRepository.findOne(id); } }
497d4e9598ce4b49fc0437e146054dc77af15cbf
8591542dc25cde84f1465f1dfad3308575af587d
/e5-core/src/com/founder/e5/rel/service/RelTableDocLibFieldsManager.java
23be53b53a3c522df912e4fe4824fc640129e491
[]
no_license
chis123/MyFounder
abe8362dce080cd91a745be6b5d46ccc2868e638
601346c156b321def81f944f72895f201f20267d
refs/heads/master
2021-01-07T04:38:31.418431
2012-12-15T15:03:44
2012-12-15T15:03:44
null
0
0
null
null
null
null
GB18030
Java
false
false
1,203
java
/********************************************************************** * Copyright (c) 2002,北大方正电子有限公司电子出版事业部集成系统开发部 * All rights reserved. * * 摘要: * * 当前版本:1.0 * 作者: 张凯峰 [email protected] * 完成日期:2006-3-24 18:42:08 * *********************************************************************/ package com.founder.e5.rel.service; import com.founder.e5.rel.dao.RelTableDocLibFieldsDAO; import com.founder.e5.rel.model.RelTableDocLibFields; public interface RelTableDocLibFieldsManager { public void setDao(RelTableDocLibFieldsDAO dao); public RelTableDocLibFields[] getRelTableDocLibFields(int docLibId,int catTypeId); /** * 保存指定的对象 * 2006-3-27 9:15:17 * @author zhang_kaifeng * @param relTableDocLib */ public void save(RelTableDocLibFields fields); /** * 删除指定的对象 * 2006-3-27 9:16:15 * @author zhang_kaifeng * @param docLibId * @param catTypeId */ public void remove(int docLibId,int catTypeId); public void removeFields(RelTableDocLibFields fields); }
1a34675dd0b3ba6110e2062ce07aa560040712e3
9a4780c1a7cc5f7396ff5f69a1d8a9422b5255bc
/configuration/geometry/WorldTileDimensions.java
5c1b1cf3744e8afb1abea27ce55efa23995f6969
[]
no_license
lmydayuldd/sharedspacesimulator
3bff6cf144abc1d2c868869b2fe7dfb86882f2c4
1b2648996cf33950a8da1d0ae9e165b374d6eaf6
refs/heads/master
2021-06-08T21:53:03.941948
2016-10-27T10:28:03
2016-10-27T10:28:03
null
0
0
null
null
null
null
WINDOWS-1252
Java
false
false
5,428
java
package uk.org.catapult.ts.cav.microsimulator.pedestrian.catpedsim.configuration.geometry; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import proguard.annotation.KeepClassMemberNames; import proguard.annotation.KeepName; import uk.org.catapult.ts.cav.microsimulator.pedestrian.catpedsim.utils.LengthUnits; /** * Reads word dimensions from the XML file. * * Example: * <worldDimensions width="50" depth="50" unitOfLength="m" acceptedUnitsOfLength * ="km m cm"> * * @author Ecaterina McCormick, [email protected] * * Copyright © <2016> TRANSPORT SYSTEMS CATAPULT * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. Users * of the Software shall acknowledge Transport Systems Catapult as the * source of the Software in any publication that refers to it. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ @XmlAccessorType(XmlAccessType.PROPERTY) @XmlType(name = "WorldTileDimensions", propOrder = { "width", "depth", "height", "unit", "acceptedUnitsOfLength" }) @KeepName @KeepClassMemberNames public class WorldTileDimensions implements Serializable { /** * For serialisation purposes. */ private static final long serialVersionUID = 6212330435073215806L; /** * World dimension unit as read from the XML. */ private LengthUnits unit = LengthUnits.METERS; /** * World width (x axis). */ private float width = 0.0f; /** * World depth (y axis). */ private float depth = 0.0f; /** * World height (z axis). */ private float height = 0.0f; /** * A description of accepted length units. */ private String acceptedUnitsOfLength = null; /** * Constructor. */ public WorldTileDimensions() { StringBuilder buildAcceptedUnitsOfLength = new StringBuilder(); for (LengthUnits myLengthUnit : LengthUnits.values()) { buildAcceptedUnitsOfLength.append(myLengthUnit.name() + " "); } acceptedUnitsOfLength = buildAcceptedUnitsOfLength.toString().trim(); } /** * Constructor. * * @param newWorldTileWidth * world tile width * @param newWorldTileDepth * world tile depth */ public WorldTileDimensions(final float newWorldTileWidth, final float newWorldTileDepth) { this(); width = newWorldTileWidth; depth = newWorldTileDepth; } /** * Gets the world width. * * @return world width */ @XmlAttribute(name = "width") public final float getWidth() { return width; } /** * Sets the world width. * * @param newWidth * to width to be set */ public final void setWidth(final float newWidth) { this.width = newWidth; } /** * gets world depth. * * @return world depth */ @XmlAttribute(name = "depth") public final float getDepth() { return depth; } /** * Sets the world depth. * * @param newDepth * world depth */ public final void setDepth(final float newDepth) { this.depth = newDepth; } /** * Get world height. * * @return world height (z axis) */ @XmlAttribute(name = "height") public final float getHeight() { return height; } /** * Set world height. * * @param newHeight * world height (z axis) */ public final void setHeight(final float newHeight) { this.height = newHeight; } /** * Gets world length unit. * * @return world length unit */ @XmlAttribute(name = "unitOfLength") public final LengthUnits getUnit() { return unit; } /** * Sets world length unit. * * @param newUnit * length unit */ public final void setUnit(final LengthUnits newUnit) { this.unit = newUnit; } /** * Gets accepted length units. A short guide for the user. * * @return accepted unit lengths */ @XmlAttribute(name = "acceptedUnitsOfLength") public final String getAcceptedUnitsOfLength() { return acceptedUnitsOfLength; } /** * Sets accepted length units. A short guide for the user. * * @param newAcceptedUnitsOfLength * accepted unit lengths */ public final void setAcceptedUnitsOfLength(final String newAcceptedUnitsOfLength) { this.acceptedUnitsOfLength = newAcceptedUnitsOfLength; } }
8768efa0cf1284cca1cbb59bf602667be913e613
ed5159d056e98d6715357d0d14a9b3f20b764f89
/test/irvine/oeis/a013/A013370Test.java
e362f447606b8ee31eeb663d5dc01e90e458fd18
[]
no_license
flywind2/joeis
c5753169cf562939b04dd246f8a2958e97f74558
e5efd6971a0062ac99f4fae21a7c78c9f9e74fea
refs/heads/master
2020-09-13T18:34:35.080552
2019-11-19T05:40:55
2019-11-19T05:40:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
195
java
package irvine.oeis.a013; import irvine.oeis.AbstractSequenceTest; /** * Tests the corresponding class. * @author Sean A. Irvine */ public class A013370Test extends AbstractSequenceTest { }
f0c365ea50c134d008e4a3866d35be00da673203
57d7801f31d911cde6570e3e513e43fb33f2baa3
/src/main/java/nl/strohalm/cyclos/setup/Version.java
1dde76649444fe1257e4041929c7c8fed8cb1e38
[]
no_license
kryzoo/cyclos
61f7f772db45b697fe010f11c5e6b2b2e34a8042
ead4176b832707d4568840e38d9795d7588943c8
refs/heads/master
2020-04-29T14:50:20.470400
2011-12-09T11:51:05
2011-12-09T11:51:05
54,712,705
0
1
null
2016-03-25T10:41:41
2016-03-25T10:41:41
null
UTF-8
Java
false
false
11,399
java
/* This file is part of Cyclos. Cyclos is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Cyclos is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Cyclos; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package nl.strohalm.cyclos.setup; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; /** * Represents a version on the upgrade descriptor. * @author luis */ public class Version implements Serializable { private static final long serialVersionUID = -823920658138712571L; private final String label; private String description; private Map<String, List<String>> statementsByDataBase; private Map<String, List<Class<Migration>>> migrationsByDataBase; private List<String> newHelps; private List<String> removedHelps; private List<String> newStaticFiles; private List<String> removedStaticFiles; private List<String> newTranslationKeys; private List<String> removedTranslationKeys; private List<String> newSetupKeys; private List<String> removedSetupKeys; private List<String> newLibraries; private List<String> removedLibraries; private List<String> newCssClasses; private List<String> removedCssClasses; private List<String> bugFixes; private List<String> enhancements; public Version(final String label) { if (StringUtils.isEmpty(label)) { throw new IllegalArgumentException("Empty label"); } this.label = label; } public void addMigration(String database, final Class<Migration> clazz) { if (clazz == null) { return; } if (!Migration.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException("Invalid migration class: " + clazz.getName()); } database = database.toLowerCase(); if (migrationsByDataBase == null) { migrationsByDataBase = new HashMap<String, List<Class<Migration>>>(); } List<Class<Migration>> migrations = migrationsByDataBase.get(database); if (migrations == null) { migrations = new ArrayList<Class<Migration>>(); migrationsByDataBase.put(database, migrations); } migrations.add(clazz); } public void addStatements(String database, final List<String> statements) { if (statements == null || statements.isEmpty()) { return; } database = database.toLowerCase(); if (statementsByDataBase == null) { statementsByDataBase = new HashMap<String, List<String>>(); } List<String> currentStatements = statementsByDataBase.get(database); if (currentStatements == null) { currentStatements = new ArrayList<String>(); statementsByDataBase.put(database, currentStatements); } currentStatements.addAll(statements); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof Version)) { return false; } final Version v = (Version) obj; return label.equals(v.label); } public List<String> getBugFixes() { return bugFixes; } public String getDescription() { return description; } public List<String> getEnhancements() { return enhancements; } public String getLabel() { return label; } public List<Class<Migration>> getMigrations(String database) { database = StringUtils.trimToNull(database); if (migrationsByDataBase == null && database != null) { return null; } for (final Map.Entry<String, List<Class<Migration>>> entry : migrationsByDataBase.entrySet()) { if (database.equalsIgnoreCase(entry.getKey())) { return entry.getValue(); } } return null; } public Map<String, List<Class<Migration>>> getMigrationsByDataBase() { return migrationsByDataBase; } public List<String> getNewCssClasses() { return newCssClasses; } public List<String> getNewHelps() { return newHelps; } public List<String> getNewLibraries() { return newLibraries; } public List<String> getNewSetupKeys() { return newSetupKeys; } public List<String> getNewStaticFiles() { return newStaticFiles; } public List<String> getNewTranslationKeys() { return newTranslationKeys; } public List<String> getRemovedCssClasses() { return removedCssClasses; } public List<String> getRemovedHelps() { return removedHelps; } public List<String> getRemovedLibraries() { return removedLibraries; } public List<String> getRemovedSetupKeys() { return removedSetupKeys; } public List<String> getRemovedStaticFiles() { return removedStaticFiles; } public List<String> getRemovedTranslationKeys() { return removedTranslationKeys; } public List<String> getStatements(String database) { database = StringUtils.trimToNull(database); if (statementsByDataBase == null && database != null) { return null; } for (final Map.Entry<String, List<String>> entry : statementsByDataBase.entrySet()) { if (database.equalsIgnoreCase(entry.getKey())) { return entry.getValue(); } } return null; } public Map<String, List<String>> getStatementsByDataBase() { return statementsByDataBase; } @Override public int hashCode() { return label.hashCode(); } public boolean sameAs(String label) { label = StringUtils.trimToNull(label); if (label == null) { return false; } return this.label.equalsIgnoreCase(label); } public void setBugFixes(final List<String> bugFixes) { this.bugFixes = bugFixes; } public void setDescription(final String description) { this.description = description; } public void setEnhancements(final List<String> enhancements) { this.enhancements = enhancements; } public void setMigrationsByDataBase(final Map<String, List<Class<Migration>>> migrationsByDataBase) { this.migrationsByDataBase = migrationsByDataBase; } public void setNewCssClasses(final List<String> newCssClasses) { this.newCssClasses = newCssClasses; } public void setNewHelps(final List<String> newHelps) { this.newHelps = newHelps; } public void setNewLibraries(final List<String> newLibraries) { this.newLibraries = newLibraries; } public void setNewSetupKeys(final List<String> newSetupKeys) { this.newSetupKeys = newSetupKeys; } public void setNewStaticFiles(final List<String> newStaticFiles) { this.newStaticFiles = newStaticFiles; } public void setNewTranslationKeys(final List<String> newTranslationKeys) { this.newTranslationKeys = newTranslationKeys; } public void setRemovedCssClasses(final List<String> removedCssClasses) { this.removedCssClasses = removedCssClasses; } public void setRemovedHelps(final List<String> removedHelps) { this.removedHelps = removedHelps; } public void setRemovedLibraries(final List<String> removedLibraries) { this.removedLibraries = removedLibraries; } public void setRemovedSetupKeys(final List<String> removedSetupKeys) { this.removedSetupKeys = removedSetupKeys; } public void setRemovedStaticFiles(final List<String> removedStaticFiles) { this.removedStaticFiles = removedStaticFiles; } public void setRemovedTranslationKeys(final List<String> removedTranslationKeys) { this.removedTranslationKeys = removedTranslationKeys; } public void setStatementsByDataBase(final Map<String, List<String>> statementsByDataBase) { this.statementsByDataBase = statementsByDataBase; } @Override public String toString() { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); final String header = String.format("Version %s", label); pw.println(header); pw.println(StringUtils.repeat("-", header.length())); if (StringUtils.isNotEmpty(description)) { pw.println(description); } pw.println(); appendList(pw, enhancements, "New / modified functions", " * ", null); appendList(pw, bugFixes, "Bug fixes", " * ", null); appendList(pw, newLibraries, "New library dependencies", " * ", null); appendList(pw, removedLibraries, "Removed library dependencies", " * ", null); appendList(pw, newHelps, "New help files", " * ", null); appendList(pw, removedHelps, "Removed help files", " * ", null); appendList(pw, newStaticFiles, "New static files", " * ", null); appendList(pw, removedStaticFiles, "Removed static files", " * ", null); appendList(pw, newCssClasses, "New CSS classes", " * ", null); appendList(pw, removedCssClasses, "Removed CSS classes", " * ", null); appendList(pw, newTranslationKeys, "New application translation keys", " * ", null); appendList(pw, removedTranslationKeys, "Removed application translation keys", " * ", null); appendList(pw, newSetupKeys, "New setup translation keys", " * ", null); appendList(pw, removedSetupKeys, "Removed setup translation keys", " * ", null); pw.close(); return sw.toString(); } private void appendList(final PrintWriter out, final List<String> list, final String header, final String prefix, final String suffix) { if (list == null || list.isEmpty()) { return; } out.println(header); for (final String item : list) { final StringBuilder sb = new StringBuilder(); if (StringUtils.isNotEmpty(prefix)) { sb.append(prefix); } sb.append(item); if (StringUtils.isNotEmpty(suffix)) { sb.append(suffix); } out.println(sb); } out.println(); } }
60cbfda42826762d819e12aa05848b17a0b09d89
719bdc303c59be44785360d4df23d5de75fd28f1
/src/main/java/com/pavlenko/util/HttpCode.java
ef86b7030732e77f7eb3fa855c1ce431a1ae0594
[]
no_license
smpavlenko/docker-file-server
b1fab5562b498d84545edd593138e07bd38be41c
f8e14a66e9e68b8bc8cb0bb172778cbae139647a
refs/heads/master
2022-12-11T21:58:54.696558
2020-08-30T16:07:48
2020-08-30T16:07:48
291,286,025
0
0
null
null
null
null
UTF-8
Java
false
false
296
java
package com.pavlenko.util; public class HttpCode { public static final int OK = 200; public static final int NOT_MODIFIED = 304; public static final int NOT_FOUND = 404; public static final int METHOD_NOT_ALLOWED = 405; public static final int INTERNAL_SERVER_ERROR = 500; }
675d26bafcd9b6ebea9901b035dec544098c710a
684cfd0da43c9e7068c5c8521ed32d89422b5e37
/src/main/java/pt/example/entity/GER_CONF_CONSUMOS_SILVER.java
8b2a6433d3404922e53672b4535051fead0894dd
[]
no_license
it-desenvolvimento-doureca/sgiid
be83362f5a1502d140e41c8fa8c2c0d56eae1a63
eb04902ab7e42f45f8e68c8d5dcf9e552eabdf21
refs/heads/master
2023-08-17T19:15:18.615231
2023-08-11T11:31:01
2023-08-11T11:31:01
107,684,993
1
0
null
null
null
null
UTF-8
Java
false
false
1,417
java
package pt.example.entity; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "GER_CONF_CONSUMOS_SILVER") public class GER_CONF_CONSUMOS_SILVER { private Integer ID_CONF; private String SECCAO_MANUTENCAO; private String SUBSECCAO_MANUTENCAO; private String REF_COMPOSTO_MANUTENCAO; @Id @Column(name = "ID_CONF") @GeneratedValue(strategy = GenerationType.IDENTITY) public Integer getID_CONF() { return ID_CONF; } @Column(name = "SECCAO_MANUTENCAO") public String getSECCAO_MANUTENCAO() { return SECCAO_MANUTENCAO; } @Column(name = "SUBSECCAO_MANUTENCAO") public String getSUBSECCAO_MANUTENCAO() { return SUBSECCAO_MANUTENCAO; } @Column(name = "REF_COMPOSTO_MANUTENCAO") public String getREF_COMPOSTO_MANUTENCAO() { return REF_COMPOSTO_MANUTENCAO; } public void setID_CONF(Integer iD_CONF) { ID_CONF = iD_CONF; } public void setSECCAO_MANUTENCAO(String sECCAO_MANUTENCAO) { SECCAO_MANUTENCAO = sECCAO_MANUTENCAO; } public void setSUBSECCAO_MANUTENCAO(String sUBSECCAO_MANUTENCAO) { SUBSECCAO_MANUTENCAO = sUBSECCAO_MANUTENCAO; } public void setREF_COMPOSTO_MANUTENCAO(String rEF_COMPOSTO_MANUTENCAO) { REF_COMPOSTO_MANUTENCAO = rEF_COMPOSTO_MANUTENCAO; } }
497195a4249548187c2d5b881103e1e3bd7b931d
6eed6e85453a517374fe05fa30a236a84899dff3
/ld26/src/de/swagner/triangulum/controls/PlayerOneControlMappings.java
c54aab04e1009ca0938caa35fa14cb3ed9e3eaf5
[]
no_license
bompo/Triangulum
4fa6dc930800d652bcb195fcf20bc32bedcd663e
534aaa5c84b6092a0940328c01d6282ae97df848
refs/heads/master
2021-01-10T19:09:05.995532
2013-05-24T14:24:03
2013-05-24T14:24:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
293
java
package de.swagner.triangulum.controls; import com.badlogic.gdx.Input; public class PlayerOneControlMappings extends ControlMappings { public PlayerOneControlMappings() { this.up = Input.Keys.W; this.down = Input.Keys.S; this.left = Input.Keys.A; this.right = Input.Keys.D; } }
d4f35cb8aa044e12b18e325b7000d7d8a12546e6
5bb943fc7dafbfd3cd831775dd32c28453baf2ec
/manifold-deps-parent/manifold-templates-test/src/test/java/manifold/templates/misc/FileFragmentTest.java
38780eba2844f9b8ce182423e9edf1f60df5a19e
[ "Apache-2.0" ]
permissive
escanda/manifold
98cf93bb2288d597fe81aec088a7851e2c9284e0
b558fadc9b3064dcefc9c884c80f18e398457f54
refs/heads/master
2022-08-28T14:46:18.222669
2022-07-22T02:52:16
2022-07-22T02:52:16
261,657,072
0
0
Apache-2.0
2020-05-06T05:06:13
2020-05-06T05:06:12
null
UTF-8
Java
false
false
1,270
java
/* * Copyright (c) 2019 - Manifold Systems LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package manifold.templates.misc; import org.junit.Test; import static java.lang.System.out; public class FileFragmentTest { @Test public void testFileFragment() { /*[>MyFragmentTest.html.mtl<] <%@ params(String name) %> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Use Template Manifold (ManTL)</title> </head> <body> The letters in <i>${name}</i>: <% for(int i = 0; i < name.length(); i++) { %> Letter: <b>${name.charAt(i)}</b> <% } %> </body> </html> */ out.println(!MyFragmentTest.render("hi").isEmpty()); } }
7ce6db76a9c34a9c6a40aa688889311ebfef8594
fabca0e7f6af977281b48f53d677808dc3c2fcf3
/mytest/itcaststore/src/cn/itcast/itcaststore/web/servlet/manager/ListNoticeServlet.java
f6d3cf86dfdc843116c90217763e074e3401b444
[]
no_license
340122/bookstore
cd12605e7db0116ce2cbedc39fcf82b47e2f336e
138298a4dae7f1b6355201aeb3a05a9bcc5443ad
refs/heads/master
2020-06-07T06:58:26.429892
2019-06-20T17:14:13
2019-06-20T17:14:13
192,955,853
1
0
null
null
null
null
UTF-8
Java
false
false
1,061
java
package cn.itcast.itcaststore.web.servlet.manager; import cn.itcast.itcaststore.domain.Notice; import cn.itcast.itcaststore.service.NoticeService; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; public class ListNoticeServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //后台查询所有公告的servlet NoticeService nService = new NoticeService(); List<Notice> notices = nService.getAllNotices(); request.setAttribute("notices", notices); request.getRequestDispatcher("/admin/notices/list.jsp").forward(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
0d20091f4c874ca649ac6896f89c558cc8937cf8
68bfd3ac3682619bef8d09652a4ea88e40669726
/src/main/java/com/mhdq/service/server/product/SProductService.java
0f1603012fc1b5c28261b9f4de3d652cfd85b5bb
[]
no_license
ellenkaijia/shopping-if
2beb06b41a1aeefbf28d9b68ab83b98bb6582fd0
a9e0f0c973b9e7c223af1b9426d8bf99af7229ed
refs/heads/master
2020-05-21T10:23:00.571035
2017-04-24T07:10:33
2017-04-24T07:10:33
84,615,505
0
0
null
null
null
null
UTF-8
Java
false
false
833
java
package com.mhdq.service.server.product; import java.util.List; import com.server.dto.SCurentPageDTO; import com.server.dto.SProductLevelDTO; import com.server.dto.STalkShowDTO; /** * 类说明 * * @author zkj * @date 2017年4月6日 新建 */ public interface SProductService { SProductLevelDTO getProductDetail(String prodId); List<SProductLevelDTO> getProductHot(SCurentPageDTO sCurentPageDTO); List<SProductLevelDTO> getProductNew(SCurentPageDTO sCurentPageDTO); List<SProductLevelDTO> getBandList(String bandId, SCurentPageDTO sCurentPageDTO); List<SProductLevelDTO> getSortList(String sortId, SCurentPageDTO sCurentPageDTO); List<SProductLevelDTO> getMoreList(Integer more, SCurentPageDTO sCurentPageDTO); List<STalkShowDTO> getProductTalkList(String prodId); }
d1fec7176011c630418a92c4608d7e39d23c3401
8d602ca2a14268fe53fd89d4fafc2742bab4f34c
/src/main/java/io/jenkins/plugins/analysis/warnings/groovy/GroovyParser.java
6cd64e3e9c8d31c84b10c6386cf2ad648fac2c4d
[ "MIT" ]
permissive
JeremyMarshall/warnings-ng-plugin
5925f9bb611928feb64876df54aebb2613a352cb
5b3002b4a3ebc9da5d446da92b3ee841c26389c3
refs/heads/master
2020-04-03T23:13:51.231523
2018-12-29T14:32:02
2018-12-29T14:32:02
155,623,511
0
0
MIT
2018-10-31T21:07:46
2018-10-31T21:07:46
null
UTF-8
Java
false
false
14,917
java
package io.jenkins.plugins.analysis.warnings.groovy; import javax.annotation.Nonnull; import java.io.Serializable; import java.util.Arrays; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.codehaus.groovy.control.CompilationFailedException; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import edu.hm.hafner.analysis.Issue; import edu.hm.hafner.analysis.IssueBuilder; import edu.hm.hafner.analysis.IssueParser; import edu.hm.hafner.util.Ensure; import edu.hm.hafner.util.VisibleForTesting; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import groovy.lang.Script; import io.jenkins.plugins.analysis.core.util.JenkinsFacade; import io.jenkins.plugins.analysis.core.model.ReportScanningTool; import jenkins.model.Jenkins; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; import hudson.util.FormValidation; import hudson.util.FormValidation.Kind; /** * Defines the properties of a warnings parser that uses a Groovy script to parse the warnings log. * * @author Ullrich Hafner */ public class GroovyParser extends AbstractDescribableImpl<GroovyParser> implements Serializable { private static final long serialVersionUID = 2447124045452896581L; private static final int MAX_EXAMPLE_SIZE = 4096; private final String id; private final String name; private final String regexp; private final String script; private final String example; @SuppressFBWarnings("SE") private transient JenkinsFacade jenkinsFacade = new JenkinsFacade(); /** * Creates a new instance of {@link GroovyParser}. * * @param id * the ID of the parser * @param name * the name of the parser * @param regexp * the regular expression * @param script * the script to map the expression to a warning * @param example * the example to verify the parser */ @DataBoundConstructor public GroovyParser(final String id, final String name, final String regexp, final String script, final String example) { super(); this.id = id; this.name = name; this.regexp = regexp; this.script = script; this.example = example.length() > MAX_EXAMPLE_SIZE ? example.substring(0, MAX_EXAMPLE_SIZE) : example; } private static boolean containsNewline(final String expression) { return StringUtils.contains(expression, "\\n") || StringUtils.contains(expression, "\\r"); } /** * Validates this instance. * * @return {@code true} if this instance is valid, {@code false} otherwise */ public boolean isValid() { DescriptorImpl d = new DescriptorImpl(getJenkinsFacade()); return d.doCheckScript(script).kind == Kind.OK && d.doCheckRegexp(regexp).kind == Kind.OK && d.validate(name, Messages.GroovyParser_Error_Name_isEmpty()).kind == Kind.OK; } public String getId() { return id; } /** * Returns the name. * * @return the name */ public String getName() { return name; } /** * Returns the regular expression. * * @return the regular expression */ public String getRegexp() { return regexp; } /** * Returns the Groovy script. * * @return the Groovy script */ public String getScript() { return script; } /** * Returns the example to verify the parser. * * @return the example */ public String getExample() { return StringUtils.defaultString(example); } /** * Returns whether the parser can scan messages spanning multiple lines. * * @return {@code true} if the parser can scan messages spanning multiple lines */ public final boolean hasMultiLineSupport() { return containsNewline(regexp); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GroovyParser that = (GroovyParser) o; if (!regexp.equals(that.regexp)) { return false; } return script.equals(that.script); } @Override public int hashCode() { int result = regexp.hashCode(); result = 31 * result + script.hashCode(); return result; } /** * Returns a new parser instance. * * @return a new parser instance * @throws AssertionError * if this parsers configuration is not valid */ public IssueParser createParser() { Ensure.that(isValid()).isTrue(); if (hasMultiLineSupport()) { return new DynamicDocumentParser(regexp, script); } else { return new DynamicLineParser(regexp, script); } } ReportScanningTool toStaticAnalysisTool() { return new GroovyParserToolAdapter(this); } @VisibleForTesting void setJenkinsFacade(final JenkinsFacade jenkinsFacade) { this.jenkinsFacade = jenkinsFacade; } private JenkinsFacade getJenkinsFacade() { return ObjectUtils.defaultIfNull(jenkinsFacade, new JenkinsFacade()); } /** * Descriptor to validate {@link GroovyParser}. * * @author Ullrich Hafner */ @Extension public static class DescriptorImpl extends Descriptor<GroovyParser> { private static final String NEWLINE = "\n"; private static final int MAX_MESSAGE_LENGTH = 60; private static final FormValidation NO_RUN_SCRIPT_PERMISSION_WARNING = FormValidation.warning(Messages.GroovyParser_Warning_NoRunScriptPermission()); private final JenkinsFacade jenkinsFacade; /** * Creates a new descriptor. */ @SuppressWarnings("unused") // Called by Jenkins public DescriptorImpl() { this(new JenkinsFacade()); } DescriptorImpl(final JenkinsFacade jenkinsFacade) { super(); this.jenkinsFacade = jenkinsFacade; } private FormValidation validate(final String name, final String message) { if (StringUtils.isBlank(name)) { return FormValidation.error(message); } return FormValidation.ok(); } /** * Performs on-the-fly validation of the parser ID. The ID needs to be unique. * * @param id * the ID of the parser * * @return the validation result */ public FormValidation doCheckId(@QueryParameter(required = true) final String id) { if (StringUtils.isBlank(id)) { return FormValidation.error(Messages.GroovyParser_Error_Id_isEmpty()); } return FormValidation.ok(); } /** * Performs on-the-fly validation on the name of the parser that needs to be unique. * * @param name * the name of the parser * * @return the validation result */ public FormValidation doCheckName(@QueryParameter(required = true) final String name) { if (StringUtils.isBlank(name)) { return FormValidation.error(Messages.GroovyParser_Error_Name_isEmpty()); } return FormValidation.ok(); } /** * Performs on-the-fly validation on the regular expression. * * @param regexp * the regular expression * * @return the validation result */ public FormValidation doCheckRegexp(@QueryParameter(required = true) final String regexp) { try { if (StringUtils.isBlank(regexp)) { return FormValidation.error(Messages.GroovyParser_Error_Regexp_isEmpty()); } Pattern pattern = Pattern.compile(regexp); Ensure.that(pattern).isNotNull(); return FormValidation.ok(); } catch (PatternSyntaxException exception) { return FormValidation.error( Messages.GroovyParser_Error_Regexp_invalid(exception.getLocalizedMessage())); } } /** * Performs on-the-fly validation on the Groovy script. * * @param script * the script * * @return the validation result */ public FormValidation doCheckScript(@QueryParameter(required = true) final String script) { if (isNotAllowedToRunScripts()) { return NO_RUN_SCRIPT_PERMISSION_WARNING; } try { if (StringUtils.isBlank(script)) { return FormValidation.error(Messages.GroovyParser_Error_Script_isEmpty()); } GroovyExpressionMatcher matcher = new GroovyExpressionMatcher(script); Script compiled = matcher.compile(); Ensure.that(compiled).isNotNull(); return FormValidation.ok(); } catch (CompilationFailedException exception) { return FormValidation.error( Messages.GroovyParser_Error_Script_invalid(exception.getLocalizedMessage())); } } private boolean isNotAllowedToRunScripts() { return !jenkinsFacade.hasPermission(Jenkins.RUN_SCRIPTS); } /** * Parses the example message with the specified regular expression and script. * * @param example * example that should be resolve to a warning * @param regexp * the regular expression * @param script * the script * * @return the validation result */ public FormValidation doCheckExample(@QueryParameter final String example, @QueryParameter final String regexp, @QueryParameter final String script) { if (isNotAllowedToRunScripts()) { return NO_RUN_SCRIPT_PERMISSION_WARNING; } if (StringUtils.isNotBlank(example) && StringUtils.isNotBlank(regexp) && StringUtils.isNotBlank(script)) { FormValidation response = parseExample(script, example, regexp, containsNewline(regexp)); if (example.length() <= MAX_EXAMPLE_SIZE) { return response; } return FormValidation.aggregate(Arrays.asList( FormValidation.warning(Messages.GroovyParser_long_examples_will_be_truncated()), response)); } else { return FormValidation.ok(); } } /** * Parses the example and returns a validation result of type {@link Kind#OK} if a warning has been found. * * @param script * the script that parses the expression * @param example * example text that will be matched by the regular expression * @param regexp * the regular expression * @param hasMultiLineSupport * determines whether multi-lines support is activated * * @return a result of {@link Kind#OK} if a warning has been found */ @SuppressWarnings("illegalcatch") private FormValidation parseExample(final String script, final String example, final String regexp, final boolean hasMultiLineSupport) { Pattern pattern; if (hasMultiLineSupport) { pattern = Pattern.compile(regexp, Pattern.MULTILINE); } else { pattern = Pattern.compile(regexp); } Matcher matcher = pattern.matcher(example); try { if (matcher.find()) { GroovyExpressionMatcher checker = new GroovyExpressionMatcher(script); Object result = checker.run(matcher, new IssueBuilder(), 0, "UI Example"); Optional<?> optional = (Optional) result; if (optional.isPresent()) { Object wrappedIssue = optional.get(); if (wrappedIssue instanceof Issue) { return createOkMessage((Issue) wrappedIssue); } } return FormValidation.error(Messages.GroovyParser_Error_Example_wrongReturnType(result)); } else { return FormValidation.error(Messages.GroovyParser_Error_Example_regexpDoesNotMatch()); } } catch (Exception exception) { // catch all exceptions of the Groovy script return FormValidation.error( Messages.GroovyParser_Error_Example_exception(exception.getMessage())); } } private FormValidation createOkMessage(final Issue issue) { StringBuilder okMessage = new StringBuilder(Messages.GroovyParser_Error_Example_ok_title()); message(okMessage, Messages.GroovyParser_Error_Example_ok_file(issue.getFileName())); message(okMessage, Messages.GroovyParser_Error_Example_ok_line(issue.getLineStart())); message(okMessage, Messages.GroovyParser_Error_Example_ok_priority(issue.getSeverity())); message(okMessage, Messages.GroovyParser_Error_Example_ok_category(issue.getCategory())); message(okMessage, Messages.GroovyParser_Error_Example_ok_type(issue.getType())); message(okMessage, Messages.GroovyParser_Error_Example_ok_message(issue.getMessage())); return FormValidation.ok(okMessage.toString()); } private void message(final StringBuilder okMessage, final String message) { okMessage.append(NEWLINE); int max = MAX_MESSAGE_LENGTH; if (message.length() > max) { int size = max / 2 - 1; okMessage.append(message, 0, size); okMessage.append("[...]"); okMessage.append(message, message.length() - size, message.length()); } else { okMessage.append(message); } } @Nonnull @Override public String getDisplayName() { return StringUtils.EMPTY; } } }
b6ac53eb81e5a1a0fc7f0969208f08a39eb45ae1
8369f003a18d00783cd0fcb0e99268f58dba4195
/src/TrabalhandoComNumeros.java
4ff9f03f66699e0af9474c79db98c21329c5bbd7
[]
no_license
CristianoCarvalhoCintra/Aula1
48bfb3975df13bf7657450342f3a03f8db1325d8
326ddfb7ba2623a6b9a3acfab9058b10731df9b3
refs/heads/master
2023-06-26T12:08:12.091737
2021-07-28T22:49:33
2021-07-28T22:49:33
390,531,179
0
0
null
null
null
null
ISO-8859-1
Java
false
false
875
java
import java.util.Scanner; public class TrabalhandoComNumeros { public static void main(String[] args) { Scanner leitor = new Scanner(System.in); int valor1; int valor2; int soma; int subtrai; int multiplic; double divide; System.out.println("Programa Calculadora!"); System.out.println("Por favor, informe o primeiro valor: "); valor1 = leitor.nextInt(); System.out.println("Por favor, informe o segundo valor: "); valor2 = leitor.nextInt(); soma = valor1 + valor2; subtrai = valor1 - valor2; multiplic = valor1 * valor2; divide = valor1 / (double) valor2; System.out.println("A soma dos valores é: " + soma); System.out.println("A subtração dos valores é: " + subtrai); System.out.println("A multiplicação valores é: " + multiplic); System.out.println("A divisão dos valores é: " + divide); leitor.close(); } }
1e06c93e58b21fe4cb24515d476e1077bccad6e0
e9b0d0af87e187785ee6ce5cd7dcea6ecbfa398c
/src/test/java/com.github.leofalco/CategoriaResourceTest.java
626e4971d1dccb8859b5db583bef0acd1976d391
[]
no_license
LeoFalco/udemy-spring-back
3576a26b7f5f475b41b4b6125860c595c82a767d
0fb6c40f744bb5708fbbe3b9fbdeee095d9fb9ec
refs/heads/master
2023-07-23T09:10:22.394622
2020-09-18T08:14:42
2020-09-27T21:38:45
143,989,075
0
0
null
2023-03-18T10:03:09
2018-08-08T09:09:03
Java
UTF-8
Java
false
false
1,826
java
package com.github.leofalco; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class CategoriaResourceTest { @Autowired private MockMvc mvc; @Test public void getCategoria1ResurnStatusOk() throws Exception { this.mvc.perform(get("/categorias/1")).andExpect(status().isOk()); } @Test public void getCategoria0ResurnNotFound() throws Exception { this.mvc.perform(get("/categorias/0")).andExpect(status().isNotFound()); } @Test public void getCategoriasReturnOk() throws Exception { MvcResult mvcResult = this.mvc.perform(get("/categorias")) .andExpect(status().isOk()).andReturn(); Assert.assertEquals("application/json;charset=UTF-8", mvcResult.getResponse().getContentType()); } @Test public void postCategorias() throws Exception { MvcResult mvcResult = this.mvc.perform(post("/categorias")) .andExpect(status().isOk()).andReturn(); Assert.assertEquals("application/json;charset=UTF-8", mvcResult.getResponse().getContentType()); } }
40aea0371d37cfecdcc4003bdbdf7fa65d1b9713
808c78b46356720a25af84692199e6efcd067fba
/de.hub.citygml.emf.ecore.editor/src/net/opengis/citygml/cityfurniture/presentation/CityfurnitureModelWizard.java
a04461122ca616cf4ed60f90b1d464569ef56b08
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
markus1978/citygml4emf
d4cc45107e588a435b1f9ddfdeb17ae77f46e9e7
06fe29a850646043ea0ffb7b1353d28115e16a53
refs/heads/master
2016-09-05T10:14:46.360922
2013-02-11T11:19:06
2013-02-11T11:19:06
8,071,822
1
1
null
null
null
null
UTF-8
Java
false
false
18,611
java
/** * <copyright> * </copyright> * * $Id$ */ package net.opengis.citygml.cityfurniture.presentation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.MissingResourceException; import java.util.StringTokenizer; import org.eclipse.emf.common.CommonPlugin; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.xmi.XMLResource; import org.eclipse.emf.edit.ui.provider.ExtendedImageRegistry; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.INewWizard; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.ui.dialogs.WizardNewFileCreationPage; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.part.ISetSelectionTarget; import net.opengis.citygml.cityfurniture.CityfurnitureFactory; import net.opengis.citygml.cityfurniture.CityfurniturePackage; import net.opengis.citygml.building.provider.CityGMLEditPlugin; import net.opengis.citygml.building.presentation.CityGMLEditorPlugin; import org.eclipse.core.runtime.Path; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.ecore.util.ExtendedMetaData; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; /** * This is a simple wizard for creating a new model file. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class CityfurnitureModelWizard extends Wizard implements INewWizard { /** * The supported extensions for created files. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<String> FILE_EXTENSIONS = Collections.unmodifiableList(Arrays.asList(CityGMLEditorPlugin.INSTANCE.getString("_UI_CityfurnitureEditorFilenameExtensions").split("\\s*,\\s*"))); /** * A formatted list of supported file extensions, suitable for display. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final String FORMATTED_FILE_EXTENSIONS = CityGMLEditorPlugin.INSTANCE.getString("_UI_CityfurnitureEditorFilenameExtensions").replaceAll("\\s*,\\s*", ", "); /** * This caches an instance of the model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CityfurniturePackage cityfurniturePackage = CityfurniturePackage.eINSTANCE; /** * This caches an instance of the model factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CityfurnitureFactory cityfurnitureFactory = cityfurniturePackage.getCityfurnitureFactory(); /** * This is the file creation page. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CityfurnitureModelWizardNewFileCreationPage newFileCreationPage; /** * This is the initial object creation page. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CityfurnitureModelWizardInitialObjectCreationPage initialObjectCreationPage; /** * Remember the selection during initialization for populating the default container. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IStructuredSelection selection; /** * Remember the workbench during initialization. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IWorkbench workbench; /** * Caches the names of the features representing global elements. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected List<String> initialObjectNames; /** * This just records the information. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void init(IWorkbench workbench, IStructuredSelection selection) { this.workbench = workbench; this.selection = selection; setWindowTitle(CityGMLEditorPlugin.INSTANCE.getString("_UI_Wizard_label")); setDefaultPageImageDescriptor(ExtendedImageRegistry.INSTANCE.getImageDescriptor(CityGMLEditorPlugin.INSTANCE.getImage("full/wizban/NewCityfurniture"))); } /** * Returns the names of the features representing global elements. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Collection<String> getInitialObjectNames() { if (initialObjectNames == null) { initialObjectNames = new ArrayList<String>(); for (EStructuralFeature eStructuralFeature : ExtendedMetaData.INSTANCE.getAllElements(ExtendedMetaData.INSTANCE.getDocumentRoot(cityfurniturePackage))) { if (eStructuralFeature.isChangeable()) { EClassifier eClassifier = eStructuralFeature.getEType(); if (eClassifier instanceof EClass) { EClass eClass = (EClass)eClassifier; if (!eClass.isAbstract()) { initialObjectNames.add(eStructuralFeature.getName()); } } } } Collections.sort(initialObjectNames, CommonPlugin.INSTANCE.getComparator()); } return initialObjectNames; } /** * Create a new model. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EObject createInitialModel() { EClass eClass = ExtendedMetaData.INSTANCE.getDocumentRoot(cityfurniturePackage); EStructuralFeature eStructuralFeature = eClass.getEStructuralFeature(initialObjectCreationPage.getInitialObjectName()); EObject rootObject = cityfurnitureFactory.create(eClass); rootObject.eSet(eStructuralFeature, EcoreUtil.create((EClass)eStructuralFeature.getEType())); return rootObject; } /** * Do the work after everything is specified. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean performFinish() { try { // Remember the file. // final IFile modelFile = getModelFile(); // Do the work within an operation. // WorkspaceModifyOperation operation = new WorkspaceModifyOperation() { @Override protected void execute(IProgressMonitor progressMonitor) { try { // Create a resource set // ResourceSet resourceSet = new ResourceSetImpl(); // Get the URI of the model file. // URI fileURI = URI.createPlatformResourceURI(modelFile.getFullPath().toString(), true); // Create a resource for this file. // Resource resource = resourceSet.createResource(fileURI); // Add the initial model object to the contents. // EObject rootObject = createInitialModel(); if (rootObject != null) { resource.getContents().add(rootObject); } // Save the contents of the resource to the file system. // Map<Object, Object> options = new HashMap<Object, Object>(); options.put(XMLResource.OPTION_ENCODING, initialObjectCreationPage.getEncoding()); resource.save(options); } catch (Exception exception) { CityGMLEditorPlugin.INSTANCE.log(exception); } finally { progressMonitor.done(); } } }; getContainer().run(false, false, operation); // Select the new file resource in the current view. // IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow(); IWorkbenchPage page = workbenchWindow.getActivePage(); final IWorkbenchPart activePart = page.getActivePart(); if (activePart instanceof ISetSelectionTarget) { final ISelection targetSelection = new StructuredSelection(modelFile); getShell().getDisplay().asyncExec (new Runnable() { public void run() { ((ISetSelectionTarget)activePart).selectReveal(targetSelection); } }); } // Open an editor on the new file. // try { page.openEditor (new FileEditorInput(modelFile), workbench.getEditorRegistry().getDefaultEditor(modelFile.getFullPath().toString()).getId()); } catch (PartInitException exception) { MessageDialog.openError(workbenchWindow.getShell(), CityGMLEditorPlugin.INSTANCE.getString("_UI_OpenEditorError_label"), exception.getMessage()); return false; } return true; } catch (Exception exception) { CityGMLEditorPlugin.INSTANCE.log(exception); return false; } } /** * This is the one page of the wizard. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class CityfurnitureModelWizardNewFileCreationPage extends WizardNewFileCreationPage { /** * Pass in the selection. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CityfurnitureModelWizardNewFileCreationPage(String pageId, IStructuredSelection selection) { super(pageId, selection); } /** * The framework calls this to see if the file is correct. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected boolean validatePage() { if (super.validatePage()) { String extension = new Path(getFileName()).getFileExtension(); if (extension == null || !FILE_EXTENSIONS.contains(extension)) { String key = FILE_EXTENSIONS.size() > 1 ? "_WARN_FilenameExtensions" : "_WARN_FilenameExtension"; setErrorMessage(CityGMLEditorPlugin.INSTANCE.getString(key, new Object [] { FORMATTED_FILE_EXTENSIONS })); return false; } return true; } return false; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IFile getModelFile() { return ResourcesPlugin.getWorkspace().getRoot().getFile(getContainerFullPath().append(getFileName())); } } /** * This is the page where the type of object to create is selected. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class CityfurnitureModelWizardInitialObjectCreationPage extends WizardPage { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Combo initialObjectField; /** * @generated * <!-- begin-user-doc --> * <!-- end-user-doc --> */ protected List<String> encodings; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Combo encodingField; /** * Pass in the selection. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CityfurnitureModelWizardInitialObjectCreationPage(String pageId) { super(pageId); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); { GridLayout layout = new GridLayout(); layout.numColumns = 1; layout.verticalSpacing = 12; composite.setLayout(layout); GridData data = new GridData(); data.verticalAlignment = GridData.FILL; data.grabExcessVerticalSpace = true; data.horizontalAlignment = GridData.FILL; composite.setLayoutData(data); } Label containerLabel = new Label(composite, SWT.LEFT); { containerLabel.setText(CityGMLEditorPlugin.INSTANCE.getString("_UI_ModelObject")); GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; containerLabel.setLayoutData(data); } initialObjectField = new Combo(composite, SWT.BORDER); { GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; initialObjectField.setLayoutData(data); } for (String objectName : getInitialObjectNames()) { initialObjectField.add(getLabel(objectName)); } if (initialObjectField.getItemCount() == 1) { initialObjectField.select(0); } initialObjectField.addModifyListener(validator); Label encodingLabel = new Label(composite, SWT.LEFT); { encodingLabel.setText(CityGMLEditorPlugin.INSTANCE.getString("_UI_XMLEncoding")); GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; encodingLabel.setLayoutData(data); } encodingField = new Combo(composite, SWT.BORDER); { GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; encodingField.setLayoutData(data); } for (String encoding : getEncodings()) { encodingField.add(encoding); } encodingField.select(0); encodingField.addModifyListener(validator); setPageComplete(validatePage()); setControl(composite); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ModifyListener validator = new ModifyListener() { public void modifyText(ModifyEvent e) { setPageComplete(validatePage()); } }; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected boolean validatePage() { return getInitialObjectName() != null && getEncodings().contains(encodingField.getText()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { if (initialObjectField.getItemCount() == 1) { initialObjectField.clearSelection(); encodingField.setFocus(); } else { encodingField.clearSelection(); initialObjectField.setFocus(); } } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getInitialObjectName() { String label = initialObjectField.getText(); for (String name : getInitialObjectNames()) { if (getLabel(name).equals(label)) { return name; } } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getEncoding() { return encodingField.getText(); } /** * Returns the label for the specified feature name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected String getLabel(String featureName) { try { return CityGMLEditPlugin.INSTANCE.getString("_UI_DocumentRoot_" + featureName + "_feature"); } catch(MissingResourceException mre) { CityGMLEditorPlugin.INSTANCE.log(mre); } return featureName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Collection<String> getEncodings() { if (encodings == null) { encodings = new ArrayList<String>(); for (StringTokenizer stringTokenizer = new StringTokenizer(CityGMLEditorPlugin.INSTANCE.getString("_UI_XMLEncodingChoices")); stringTokenizer.hasMoreTokens(); ) { encodings.add(stringTokenizer.nextToken()); } } return encodings; } } /** * The framework calls this to create the contents of the wizard. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void addPages() { // Create a page, set the title, and the initial model file name. // newFileCreationPage = new CityfurnitureModelWizardNewFileCreationPage("Whatever", selection); newFileCreationPage.setTitle(CityGMLEditorPlugin.INSTANCE.getString("_UI_CityfurnitureModelWizard_label")); newFileCreationPage.setDescription(CityGMLEditorPlugin.INSTANCE.getString("_UI_CityfurnitureModelWizard_description")); newFileCreationPage.setFileName(CityGMLEditorPlugin.INSTANCE.getString("_UI_CityfurnitureEditorFilenameDefaultBase") + "." + FILE_EXTENSIONS.get(0)); addPage(newFileCreationPage); // Try and get the resource selection to determine a current directory for the file dialog. // if (selection != null && !selection.isEmpty()) { // Get the resource... // Object selectedElement = selection.iterator().next(); if (selectedElement instanceof IResource) { // Get the resource parent, if its a file. // IResource selectedResource = (IResource)selectedElement; if (selectedResource.getType() == IResource.FILE) { selectedResource = selectedResource.getParent(); } // This gives us a directory... // if (selectedResource instanceof IFolder || selectedResource instanceof IProject) { // Set this for the container. // newFileCreationPage.setContainerFullPath(selectedResource.getFullPath()); // Make up a unique new name here. // String defaultModelBaseFilename = CityGMLEditorPlugin.INSTANCE.getString("_UI_CityfurnitureEditorFilenameDefaultBase"); String defaultModelFilenameExtension = FILE_EXTENSIONS.get(0); String modelFilename = defaultModelBaseFilename + "." + defaultModelFilenameExtension; for (int i = 1; ((IContainer)selectedResource).findMember(modelFilename) != null; ++i) { modelFilename = defaultModelBaseFilename + i + "." + defaultModelFilenameExtension; } newFileCreationPage.setFileName(modelFilename); } } } initialObjectCreationPage = new CityfurnitureModelWizardInitialObjectCreationPage("Whatever2"); initialObjectCreationPage.setTitle(CityGMLEditorPlugin.INSTANCE.getString("_UI_CityfurnitureModelWizard_label")); initialObjectCreationPage.setDescription(CityGMLEditorPlugin.INSTANCE.getString("_UI_Wizard_initial_object_description")); addPage(initialObjectCreationPage); } /** * Get the file from the page. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IFile getModelFile() { return newFileCreationPage.getModelFile(); } }
c6d1533c2c150f1edc1923be292a258127dab379
85eebaf1fb7934b1083275df3617f2f8101aca33
/src/com/xy/lr/tics/dezhouserver/DeZhouSocketServerJava.java
1c02df2e76f4f156f2e197ed02f81c63ea7bf220
[]
no_license
fanzw123/newTICS
099dcf88ce729898ead9052c96178875470453b6
7e88a205ca739d75b82e0bdfc3be6fc6329e8693
refs/heads/master
2020-12-24T12:20:42.861416
2015-04-26T12:24:47
2015-04-26T12:24:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,285
java
package com.xy.lr.tics.dezhouserver; import java.io.*; import java.net.*; import java.text.SimpleDateFormat; import java.util.Date; public class DeZhouSocketServerJava { ServerSocket sever; public DeZhouSocketServerJava(int port){ try{ sever = new ServerSocket(port); }catch(IOException e){ e.printStackTrace(); } } public String getCurrentTime(){ Date date = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); return df.format(date); } public void beginListen(String carNUmber){ while(true){ Thread t = null; try{ final Socket socket = sever.accept(); System.out.println("Got client connect from : " + socket.getInetAddress()); System.out.println("Start Send Meg"); final String CarNumber = carNUmber; t = new Thread(){ public void run(){ try{ int i = 0; PrintWriter out = new PrintWriter(socket.getOutputStream()); while(true){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } String time = getCurrentTime(); out.println("start" + "\t" + CarNumber + "\t" + time); // System.out.println("Hello!World@" + "\t" + i); i++; out.flush(); if(socket.isClosed()){ break; } } socket.close(); }catch(IOException e) { e.printStackTrace(); } } }; t.start(); }catch(IOException e){ e.printStackTrace(); t.stop(); } } } }
5d17effa639ed62bd980dacc105c213ecf74e919
3e50357e25251aa142528a37d79dfe64d92c9ff9
/javamud/area/RoomImporter.java
702f0068b39bfea3c689d1b1f66fa31039da8868
[]
no_license
wmerfalen/javamud
434618d55cdddaede5d261d8efcbcdf8590f5931
911a9bed9f9faeb45e6d0fc6013f1f8a8d5c5ef7
refs/heads/master
2021-01-19T04:24:44.573519
2017-04-13T04:53:25
2017-04-13T04:53:25
87,368,904
1
0
null
null
null
null
UTF-8
Java
false
false
9,597
java
/* * 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 javamud.area; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import javamud.mysql.Mysql; /** * * @author wmerfalen */ public class RoomImporter { private String m_file_name; public RoomImporter(String fName){ m_file_name = fName; } public ArrayList<Room> importFromDB(Integer areaId) throws SQLException, Exception{ Mysql db; db = new Mysql("localhost","javamud","javamud_user","sudorm-rf/"); PreparedStatement stmt = db.prepare("SELECT * FROM rooms where area_id = ?"); stmt.setInt(0, areaId.intValue()); ResultSet res = stmt.executeQuery(); ArrayList<Room> rooms = new ArrayList<Room>(); ArrayList<Integer> ids = new ArrayList<Integer>(); while(res.next()){ int id = res.getInt("id"); Room r = new Room(id, res.getString("name"), res.getString("description"), res.getInt("x"), res.getInt("y"), res.getInt("z") ); if(res.getInt("dir_north") != 0){ r.attachRoomId(res.getInt("dir_north"),Room.NORTH); } if(res.getInt("dir_northeast") != 0){ r.attachRoomId(res.getInt("dir_northeast"),Room.NORTHEAST); } if(res.getInt("dir_northwest") != 0){ r.attachRoomId(res.getInt("dir_northwest"),Room.NORTHWEST); } if(res.getInt("dir_east") != 0){ r.attachRoomId(res.getInt("dir_east"),Room.EAST); } if(res.getInt("dir_west") != 0){ r.attachRoomId(res.getInt("dir_west"),Room.WEST); } if(res.getInt("dir_south") != 0){ r.attachRoomId(res.getInt("dir_south"),Room.SOUTH); } if(res.getInt("dir_southeast") != 0){ r.attachRoomId(res.getInt("dir_southeast"),Room.SOUTHEAST); } if(res.getInt("dir_southwest") != 0){ r.attachRoomId(res.getInt("dir_south"),Room.SOUTHWEST); } rooms.add(r); } return rooms; } public ArrayList<Room> importFromFile() throws IOException { //Open the file ArrayList<Room> rooms = null; try { FileReader fReader = new FileReader(m_file_name); BufferedReader bReader = new BufferedReader(fReader); String line; /* * Read the header. The header should look like this: * NxM * where N is the number of rows, and M is the number of columns * * this file will generate an NxM grid of rooms */ line = bReader.readLine(); String[] parts = line.split("x"); int rows = Integer.decode(parts[0]); int cols = Integer.decode(parts[1]); while((line = bReader.readLine()) != null){ Integer iField = 0; String roomName = null,roomDesc = null; int x = 0,y = 0,z = 0; for(String part : line.split(",")){ switch(iField){ case 0: roomName = part; break; case 1: roomDesc = part; break; case 2: x = Integer.decode(part); break; case 3: y = Integer.decode(part); break; case 4: z = Integer.decode(part); break; default: System.out.println("Unknown column in csv file"); } iField++; } if(roomName != null && roomDesc != null){ rooms.add(new Room(roomName,roomDesc,x,y,z)); } } } catch (FileNotFoundException ex) { System.err.println("Cannot open file!" + m_file_name); Logger.getLogger(RoomImporter.class.getName()).log(Level.SEVERE, null, ex); } return rooms; } public Room[][][] generateFromFile() throws IOException { try { FileReader fReader = new FileReader(m_file_name); BufferedReader bReader = new BufferedReader(fReader); String line; /* * Read the header. The header should look like this: * NxMxZ * where N is the number of rows, and M is the number of columns * and Z is the up and down * * This file will generate an NxMxZ grid of rooms * */ line = bReader.readLine(); String[] parts = line.split("x"); int rows = Integer.decode(parts[0]); int cols = Integer.decode(parts[1]); int zzz = Integer.decode(parts[2]); Room[][][] roomList = new Room[rows][cols][zzz]; for(int x=0; x < rows;x++){ for(int y=0;y < cols;y++){ for(int z=0;z < zzz;z++){ String r = "Room:["; r += "["+x+"]"; r += "["+y+"]"; r += "["+z+"]"; String d = "An ordinary room"; roomList[x][y][z] = new Room(r,d,x,y,z); } } } for(int x=0; x < rows;x++){ for(int y=0;y < cols;y++){ for(int z=0;z < zzz;z++){ if((x-1) > -1){ roomList[x][y][z].attachRoom(roomList[x-1][y][z],Room.WEST); }else{ roomList[x][y][z].clearDirection(Room.WEST); } if((y-1) > -1){ roomList[x][y][z].attachRoom(roomList[x][y-1][z],Room.SOUTH); }else{ roomList[x][y][z].clearDirection(Room.SOUTH); } if((z-1) > -1){ roomList[x][y][z].attachRoom(roomList[x][y][z-1],Room.DOWN); }else{ roomList[x][y][z].clearDirection(Room.DOWN); } if((x+1) < rows){ roomList[x][y][z].attachRoom(roomList[x+1][y][z],Room.EAST); }else{ roomList[x][y][z].clearDirection(Room.EAST); } if((y+1) < cols){ roomList[x][y][z].attachRoom(roomList[x][y+1][z],Room.NORTH); }else{ roomList[x][y][z].clearDirection(Room.NORTH); } if((z+1) < zzz){ roomList[x][y][z].attachRoom(roomList[x][y][z+1],Room.UP); }else{ roomList[x][y][z].clearDirection(Room.UP); } /* North west */ if((x-1) > -1 && (y+1) < cols){ roomList[x][y][z].attachRoom(roomList[x-1][y+1][z],Room.NORTHWEST); }else{ roomList[x][y][z].clearDirection(Room.NORTHWEST); } /* North east */ if((x+1) < rows && (y+1) < cols){ roomList[x][y][z].attachRoom(roomList[x+1][y+1][z],Room.NORTHEAST); }else{ roomList[x][y][z].clearDirection(Room.NORTHEAST); } /* South west */ if((x-1) > -1 && (y-1) > -1){ roomList[x][y][z].attachRoom(roomList[x-1][y-1][z],Room.SOUTHWEST); }else{ roomList[x][y][z].clearDirection(Room.SOUTHWEST); } /* South east */ if((x+1) < rows && (y-1) > -1){ roomList[x][y][z].attachRoom(roomList[x+1][y-1][z],Room.SOUTHEAST); }else{ roomList[x][y][z].clearDirection(Room.SOUTHEAST); } } } } return roomList; } catch (FileNotFoundException ex) { System.err.println("Cannot open file!" + m_file_name); Logger.getLogger(RoomImporter.class.getName()).log(Level.SEVERE, null, ex); } return new Room[0][0][0]; } }
fcec817ed0dab4254501284350ab4f15c77e90c6
ce08afe3f0fcdf3c168c310012099321c9b5dbad
/TableLayout/app/src/test/java/com/zainur/tablelayout/ExampleUnitTest.java
4337a48ce17552f5f8e67ff2d0f746a3b13579ba
[]
no_license
zainur77/Project_Minggu_Ke-3
51af0201eef1172638896bb729a53cdf925c77b0
070a6fa6ad085619c391c3f1c318dba165eff0e7
refs/heads/main
2023-08-27T19:09:12.777931
2021-09-29T09:11:55
2021-09-29T09:11:55
411,603,073
0
0
null
null
null
null
UTF-8
Java
false
false
383
java
package com.zainur.tablelayout; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
e1f2f72f8f41ea431d54a07844a39d7430a81354
5ab3f025fe62046ced661803e4faa19bb66b7f05
/RMIserver/src/InvalidLogin.java
371009048375f9e59bda005ea9cb79cbf79b1467
[]
no_license
creaghstc/RMI-Banking-Application
ab26c4832eb8335647efe494574f3be9b588fd18
c016f4bbc41d777a1fe81716788a4a0b7e3b1918
refs/heads/master
2021-01-19T19:25:25.479934
2017-08-23T14:45:57
2017-08-23T14:45:57
101,191,212
0
0
null
null
null
null
UTF-8
Java
false
false
74
java
//Conor Creagh 13454222 public class InvalidLogin extends Exception { }
51355f77c1e98a6cb444acde29483d17ef1ef9a9
62be74613d6237d88d71a442506abc91056ffe60
/framework/src/main/java/com/sss/framework/Library/PullToRefresh/internal/ViewCompat.java
86dccfa9f54383010665131b1ad18d59d9c5e350
[]
no_license
michael007js/-DEMO
6589ed3ad445e60480bbe9d1c896bb1dc0392b6b
336a6a3406e4b23492c5cf6a91250b4e01dfc555
refs/heads/master
2020-03-11T12:22:50.337034
2018-04-18T10:08:14
2018-04-18T10:08:14
129,995,751
2
0
null
null
null
null
UTF-8
Java
false
false
2,066
java
/******************************************************************************* * Copyright 2011, 2012 Chris Banes. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.sss.framework.Library.PullToRefresh.internal; import android.annotation.TargetApi; import android.graphics.drawable.Drawable; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.view.View; @SuppressWarnings("deprecation") public class ViewCompat { public static void postOnAnimation(View view, Runnable runnable) { if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) { SDK16.postOnAnimation(view, runnable); } else { view.postDelayed(runnable, 16); } } public static void setBackground(View view, Drawable background) { if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) { SDK16.setBackground(view, background); } else { view.setBackgroundDrawable(background); } } public static void setLayerType(View view, int layerType) { if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { SDK11.setLayerType(view, layerType); } } @TargetApi(11) static class SDK11 { public static void setLayerType(View view, int layerType) { view.setLayerType(layerType, null); } } @TargetApi(16) static class SDK16 { public static void postOnAnimation(View view, Runnable runnable) { view.postOnAnimation(runnable); } public static void setBackground(View view, Drawable background) { view.setBackground(background); } } }
c7dc320d17b0c44aac0528fcde75df565932d414
dd2a091975b0fc0d1d062ae0c8ff392d6d280a9d
/app/src/main/java/com/shiyunzhang/wetrade/Activity/AuctionActivity.java
3fd47bfd8c87ba321aa39177b87e12e70e18d6fe
[]
no_license
szhang5/weTradeApp
1149dd50b8b97c9ba1b664f1c6290e06a59c6bb2
68bd7e4f894d786aa17a22ac7509d40bc05085bf
refs/heads/master
2020-05-03T11:46:40.422821
2019-05-18T00:45:10
2019-05-18T00:45:10
178,608,974
0
0
null
null
null
null
UTF-8
Java
false
false
15,803
java
package com.shiyunzhang.wetrade.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import com.google.firebase.firestore.SetOptions; import com.google.gson.Gson; import com.shiyunzhang.wetrade.Adapter.BidPriceAdapter; import com.shiyunzhang.wetrade.DataClass.Auction; import com.shiyunzhang.wetrade.DataClass.ConditionAndQuantity; import com.shiyunzhang.wetrade.DataClass.Inventory; import com.shiyunzhang.wetrade.DataClass.UserBidPrice; import com.shiyunzhang.wetrade.DataClass.UserFCMToken; import com.shiyunzhang.wetrade.DataClass.UserInfo; import com.shiyunzhang.wetrade.R; import java.util.ArrayList; import de.hdodenhof.circleimageview.CircleImageView; public class AuctionActivity extends AppCompatActivity { private final static String TAG = "AuctionActivity"; private FirebaseFirestore db = FirebaseFirestore.getInstance(); private DocumentReference auctionRef; private CollectionReference inventoryCollection; private Inventory inventory; private Auction auction; private CircleImageView hostImageView; private ImageView auctionItemImageView; private TextView auctionItemName, auctionItemDesc, auctionItemCondition, auctionItemPrice, hostName, yourBidPrice, auctionStatus, auctionUpdatedPrice; private EditText bidPrice; private double auctionStartPrice; private UserInfo userPreference; private BidPriceAdapter adapter; private ArrayList<UserBidPrice> userBidPriceArrayList; private String selectedWinnerId; private int selectedPosition = -1; private Button endAuctionBtn, submitPriceBtn; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_auction); setUpActionBar(); init(); } private void init() { getUserInfoFromPreference(); Intent intent = getIntent(); String auctionId = intent.getStringExtra("AUCTIONID"); String userType = intent.getStringExtra("USERTYPE"); if (userType.equals("Host")) { LinearLayout hostView = findViewById(R.id.auction_host_view); hostView.setVisibility(View.VISIBLE); } else { LinearLayout bidView = findViewById(R.id.bid_view); bidView.setVisibility(View.VISIBLE); } auctionRef = db.collection("Auction").document(auctionId); inventoryCollection = db.collection("Inventory"); auctionStatus = findViewById(R.id.auction_status); auctionItemImageView = findViewById(R.id.auction_image); auctionItemName = findViewById(R.id.auction_name); auctionItemDesc = findViewById(R.id.auction_desc); auctionItemCondition = findViewById(R.id.auction_condition); auctionItemPrice = findViewById(R.id.auction_price); auctionUpdatedPrice = findViewById(R.id.auction_updated_price); hostImageView = findViewById(R.id.host_profile_image); hostName = findViewById(R.id.host_name); bidPrice = findViewById(R.id.bid_price); endAuctionBtn = findViewById(R.id.end_auction_btn); submitPriceBtn = findViewById(R.id.submit_price_btn); yourBidPrice = findViewById(R.id.your_bid_price); userBidPriceArrayList = new ArrayList<>(); RecyclerView mRecyclerView = findViewById(R.id.auction_price_recyclerView); mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); adapter = new BidPriceAdapter(this, userBidPriceArrayList, v -> { int position = (int) v.getTag(); adapter.setSelectedPosition(position); selectedPosition = position == selectedPosition ? -1 : position; selectedWinnerId = selectedPosition == -1 ? null : userBidPriceArrayList.get(position).getUserId(); }); mRecyclerView.setAdapter(adapter); getAuctionFromDatabase(); } private void getUserInfoFromPreference() { SharedPreferences sharedpreferences = getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE); String userStr = sharedpreferences.getString("USER", ""); Gson gson = new Gson(); userPreference = gson.fromJson(userStr, UserInfo.class); } @Override protected void onStart() { super.onStart(); auctionRef.collection("BidPrice").addSnapshotListener((queryDocumentSnapshots, e) -> { if (e != null) return; userBidPriceArrayList.clear(); if (!queryDocumentSnapshots.isEmpty()) { double maxPrice = Integer.MIN_VALUE; for (QueryDocumentSnapshot queryDocumentSnapshot : queryDocumentSnapshots) { UserBidPrice userBidPrice = queryDocumentSnapshot.toObject(UserBidPrice.class); maxPrice = Math.max(maxPrice, userBidPrice.getPrice()); userBidPriceArrayList.add(userBidPrice); } auctionUpdatedPrice.setText("$ " + maxPrice); adapter.notifyDataSetChanged(); } }); auctionRef.addSnapshotListener((documentSnapshot, e) -> { if (e != null) return; Auction auctionChange = documentSnapshot.toObject(Auction.class); if (auctionChange.getWinnerId() != null && auctionChange.getWinnerId().equals(userPreference.getId())) { submitPriceBtn.setEnabled(false); bidPrice.setEnabled(false); setUpWinnerAlertDialog(); } else if (auctionChange.getWinnerId() != null && auctionChange.getInventory().getUserID().equals(userPreference.getId())) { endAuctionBtn.setEnabled(false); } else if (auctionChange.getWinnerId() != null && !auctionChange.getWinnerId().equals(userPreference.getId())) { submitPriceBtn.setEnabled(false); bidPrice.setEnabled(false); setUpLoserAlertDialog(); } }); } private void setUpActionBar() { ActionBar actionBar = getSupportActionBar(); actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.black))); } private void getAuctionFromDatabase() { auctionRef.get() .addOnSuccessListener(documentSnapshot -> { auction = documentSnapshot.toObject(Auction.class); inventory = auction.getInventory(); setTitle("Auction - " + inventory.getName()); Glide.with(AuctionActivity.this).load(inventory.getImageUrl()).into(auctionItemImageView); auctionItemName.setText(inventory.getName()); auctionItemDesc.setText(inventory.getDescription()); auctionItemCondition.setText("Condition: " + inventory.getConditionAndQuantities().get(0).getCondition()); auctionStartPrice = auction.getPrice(); auctionItemPrice.setText("$ " + auctionStartPrice); if (auction.getAuctionStatus().equals("End")) { auctionStatus.setText(auction.getAuctionStatus()); auctionStatus.setTextColor(getResources().getColor(R.color.red)); } else { auctionStatus.setText(auction.getAuctionStatus()); auctionStatus.setTextColor(getResources().getColor(R.color.green)); } getHostInfo(inventory.getUserID()); }) .addOnFailureListener(e -> { }); } private void getHostInfo(String uid) { db.collection("User").document(uid) .get() .addOnSuccessListener(documentSnapshot -> { UserInfo userInfo = documentSnapshot.toObject(UserInfo.class); if (userInfo.getImageUrl() != null) { Glide.with(AuctionActivity.this).load(userInfo.getImageUrl()).into(hostImageView); } if (userInfo.getFirstName() != null && userInfo.getLastName() != null) { hostName.setText(userInfo.getFirstName() + " " + userInfo.getLastName()); } }) .addOnFailureListener(e -> { }); } public void endAuction(View view) { if (selectedWinnerId == null) { Toast.makeText(this, "Please select a winner", Toast.LENGTH_SHORT).show(); return; } else { deductInventoryFromAuctionHost(); addUserTokenToAuctionDatabase(); } } public void deductInventoryFromAuctionHost() { inventoryCollection.document(inventory.getItemID()) .get() .addOnSuccessListener(documentSnapshot -> { Inventory item = documentSnapshot.toObject(Inventory.class); ArrayList<ConditionAndQuantity> conditionAndQuantities = item.getConditionAndQuantities(); for (ConditionAndQuantity conditionAndQuantity : conditionAndQuantities) { if (conditionAndQuantity.getCondition().equals(inventory.getConditionAndQuantities().get(0).getCondition())) { conditionAndQuantity.setQuantity(conditionAndQuantity.getQuantity() - inventory.getConditionAndQuantities().get(0).getQuantity()); break; } } item.setConditionAndQuantities(conditionAndQuantities); inventoryCollection.document(inventory.getItemID()).set(item).addOnSuccessListener(documentSnapshot1 -> { addInventoryToWinner(); }); }); } public void addInventoryToWinner(){ inventoryCollection.whereEqualTo("userID", selectedWinnerId) .whereEqualTo("productID", inventory.getProductID()) .get() .addOnSuccessListener(queryDocumentSnapshots -> { if(!queryDocumentSnapshots.isEmpty()){ for(QueryDocumentSnapshot queryDocumentSnapshot : queryDocumentSnapshots){ Inventory item = queryDocumentSnapshot.toObject(Inventory.class); ArrayList<ConditionAndQuantity> conditionAndQuantities = item.getConditionAndQuantities(); for (ConditionAndQuantity conditionAndQuantity : conditionAndQuantities) { if (conditionAndQuantity.getCondition().equals(inventory.getConditionAndQuantities().get(0).getCondition())) { conditionAndQuantity.setQuantity(conditionAndQuantity.getQuantity() + 1); break; } } item.setConditionAndQuantities(conditionAndQuantities); inventoryCollection.document(item.getItemID()).set(item).addOnSuccessListener(documentSnapshot1 -> {}); } } else { ArrayList<ConditionAndQuantity> conditionAndQuantities = new ArrayList<>(); conditionAndQuantities.add(new ConditionAndQuantity(inventory.getConditionAndQuantities().get(0).getCondition(), 1)); Inventory item = new Inventory(inventoryCollection.document().getId(), inventory.getImageUrl(), inventory.getCategory(), inventory.getName(), inventory.getDescription(), conditionAndQuantities, selectedWinnerId, inventory.getProductID()); inventoryCollection.document(item.getItemID()).set(item).addOnSuccessListener(aVoid -> {}); } }); } public void SubmitPrice(View view) { if (bidPrice.getText().toString().isEmpty()) { Toast.makeText(this, "Please Enter Price", Toast.LENGTH_SHORT).show(); } else { double price = Double.parseDouble(bidPrice.getText().toString()); if (price < auctionStartPrice) { Toast.makeText(this, "Please enter price greater than the start price", Toast.LENGTH_SHORT).show(); } else { yourBidPrice.setText("Your Bid Price : $ " + price); String name = userPreference.getFirstName() + " " + userPreference.getLastName(); UserBidPrice userBidPrice = new UserBidPrice(userPreference.getId(), name, price, userPreference.getImageUrl()); auctionRef.collection("BidPrice").document(userPreference.getId()) .set(userBidPrice) .addOnSuccessListener(aVoid -> bidPrice.setText("")) .addOnFailureListener(e -> { }); } } } private void setUpWinnerAlertDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(AuctionActivity.this); builder.setTitle("Congratulation!"); builder.setMessage("Item added to your inventory!"); builder.setPositiveButton("Confirm", (dialog, which) -> { dialog.dismiss(); }); builder.create().show(); } private void setUpLoserAlertDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(AuctionActivity.this); builder.setTitle("Sorry, Auction End"); builder.setMessage("Good luck next time!"); builder.setPositiveButton("Ok", (dialog, which) -> { dialog.dismiss(); }); builder.create().show(); } public void addUserTokenToAuctionDatabase() { DocumentReference userTokenRef = db.collection("UserToken").document(selectedWinnerId); userTokenRef.get() .addOnSuccessListener(documentSnapshot -> { UserFCMToken userFCMToken = documentSnapshot.toObject(UserFCMToken.class); auction.setWinner(userFCMToken.getToken()); auction.setWinnerId(selectedWinnerId); auction.setAuctionStatus("End"); auctionRef.set(auction, SetOptions.merge()).addOnSuccessListener(aVoid -> { }); }) .addOnFailureListener(e -> Log.d(TAG, e.toString())); } }
719312142251838a454bf8848a23b6df827a8661
353718643d2b56877edc170cdd90e437a086f36e
/app/src/test/java/com/example/dell/project1/ExampleUnitTest.java
6ef3fce6dcd4410f9b1a18242c69daf4067625d6
[]
no_license
dprk90/Project12
a287fb6e13c80537a49b35028ac72ba539663f66
6d400d43c67065b50a399ac624a5c1a506e38d37
refs/heads/master
2020-12-31T00:12:24.352973
2017-03-28T19:43:34
2017-03-28T19:43:34
86,499,525
0
0
null
null
null
null
UTF-8
Java
false
false
403
java
package com.example.dell.project1; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
[ "Prakash Dwivedi" ]
Prakash Dwivedi
64eb1b8209aadf13cbe1fba774c26c4a8743e22b
cb769b8875a0d5d54ec11c085f14bace328c934b
/app/src/main/java/com/example/madee/sga/API/EventApi.java
7d4b2d772210b8ea6684703500eae4122e371c60
[]
no_license
imrbpro/SmartGuideApplication-Mobile
c34313e3e9a4c579a22f0986a5b232311f9fbcf9
fc7c49124aa6a865be02db42705f06ba6b2a615d
refs/heads/master
2022-11-15T09:48:16.285853
2020-07-14T18:50:13
2020-07-14T18:50:13
254,666,753
1
0
null
null
null
null
UTF-8
Java
false
false
852
java
package com.example.madee.sga.API; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Path; public interface EventApi { @GET("Event/GetAll/{page}") Call<ResponseBody> GetAllEvents(@Path("page") int page); @GET("Event/GetById/{id}") Call<ResponseBody> GetEventById(@Path("id") int id); @Headers({"Content-Type: application/json"}) @POST("Event/Add") Call<ResponseBody> AddEvent(@Body String _event); @Headers({"Content-Type: application/json"}) @PUT("Event/Update") Call<ResponseBody> UpdateEvent(@Body String _event); @DELETE("Event/Delete/{id}") Call<ResponseBody> DeleteEvent(@Path("id") int id); }
529017ccb60243f9d535b451a093fd96bac61da2
593d39980296501e8a7d7d9b470ef46ec8b01e21
/spring-auto-restdocs-core/src/test/java/capital/scalable/restdocs/constraints/DynamicResourceBundleConstraintDescriptionResolverTest.java
035b68e67f597864059dfd57cb32c22b98b1a82a
[ "Apache-2.0" ]
permissive
ScaCap/spring-auto-restdocs
edfef3ced7963618ecf881037dbabc5059329b21
3028d679ef711c9074e56d6d02e9bbb106eca434
refs/heads/master
2023-08-13T03:56:05.652414
2022-11-07T10:07:42
2022-11-07T10:07:42
48,500,629
323
131
Apache-2.0
2023-09-14T10:16:40
2015-12-23T16:38:34
Java
UTF-8
Java
false
false
2,408
java
/*- * #%L * Spring Auto REST Docs Core * %% * Copyright (C) 2015 - 2021 Scalable Capital GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package capital.scalable.restdocs.constraints; import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.springframework.restdocs.constraints.Constraint; import org.springframework.restdocs.constraints.ConstraintDescriptionResolver; public class DynamicResourceBundleConstraintDescriptionResolverTest { private final ConstraintDescriptionResolver resolver = new DynamicResourceBundleConstraintDescriptionResolver(); @Test public void descriptionIsResolvedFromAnnotationMessage() { // given Map<String, Object> configuration = new HashMap<>(); configuration.put("message", "Must be it"); Constraint constraint = new Constraint("test.Constraint1", configuration); // when String description = resolver.resolveDescription(constraint); // then assertThat(description).isEqualTo("Must be it"); } @Test public void descriptionIsResolvedFromResource() { // given Map<String, Object> configuration = new HashMap<>(); Constraint constraint = new Constraint("test.Constraint2", configuration); // when String description = resolver.resolveDescription(constraint); // then assertThat(description).isEqualTo("Must be limited"); } @Test public void descriptionIsNotResolved() { // given Map<String, Object> configuration = new HashMap<>(); Constraint constraint = new Constraint("test.Constraint3", configuration); // when String description = resolver.resolveDescription(constraint); // then assertThat(description).isEmpty(); } }
6992c8ba96cd772d60f3710236d5e7ce776f6fc4
3ea7643cd711f65bcd6e610445e2fbc3a2a61ded
/Cemtrelised Attendance Automation/src/DAL/ConnectionManager.java
20a161f438a95ad23a5e9b89cf8376ad7664770c
[]
no_license
CrystalOfLife/centrelised-system-compolsery-1
6f4946a290898d031d4cc7a18bbc1a7d3ae2f77d
548ff276661d3b205fcddb637ce998205a33c653
refs/heads/master
2021-01-19T07:16:43.132542
2017-04-06T11:30:39
2017-04-06T11:30:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,485
java
/* * 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 DAL; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; import com.microsoft.sqlserver.jdbc.SQLServerException; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; /** * * @author Emil */ public class ConnectionManager { private SQLServerDataSource data; private static final String configFile = "DatabaseConfig.cfg"; public ConnectionManager() throws IOException { Properties properties = new Properties(); properties.load(new FileReader(configFile)); data = new SQLServerDataSource(); data.setServerName(properties.getProperty("SERVER")); data.setDatabaseName(properties.getProperty("DATABASE")); data.setUser(properties.getProperty("USER")); data.setPassword(properties.getProperty("PASSWORD")); } public Connection getConnection() throws SQLServerException { return data.getConnection(); } // public static void main(String[] args) throws SQLServerException, SQLException, IOException { // ConnectionManager cm = new ConnectionManager(); // Connection con = cm.getConnection(); // con.close(); // } }
04989886e50da8863d1ab15fb21ce72df7d60bd7
66a99ee3dbbbf378580d87f15084bf9c5d419c35
/app/src/main/java/chuang/sdklibrary/util/banner/BannerAdapter.java
4da7d8779882de74c143dec08d3fd46ec6d2f7ff
[]
no_license
chuangWu/SDKLibrary
aab36a7984e4f3875e970f0f8a9fee6823cd4757
d27bf75609bb6702f33cee2cae96bd96b92208ae
refs/heads/master
2020-04-09T09:52:29.440682
2015-03-17T07:01:50
2015-03-17T07:01:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
889
java
package chuang.sdklibrary.util.banner; import android.support.v4.view.PagerAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public abstract class BannerAdapter extends PagerAdapter { @Override public Object instantiateItem(ViewGroup container, int position) { View view = getView(LayoutInflater.from(container.getContext()), position); container.addView(view); return view; } public int getPositionForIndicator(int position) { return position; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } public abstract View getView(LayoutInflater layoutInflater, int position); @Override public boolean isViewFromObject(View view, Object o) { return view == o; } }
fb499c2cd0a09338e3ef37abf6cbdbe405925274
875504314b9fc791cbc349063ff33af2eb0683ee
/src/main/java/com/imooc/config/WechatAccountConfig.java
af86c3844329dd31a76873770ceef9c0a87e528c
[]
no_license
dingli950411/springBoot_sell
2c7281a86c2081259aee95a04aa1b25e7d2d0ded
aedd1fbcfc51e4cfd63fb9dfc1dc0757151dd6e7
refs/heads/master
2020-07-12T23:18:04.871075
2019-08-28T13:06:21
2019-08-28T13:06:21
204,932,944
0
0
null
null
null
null
UTF-8
Java
false
false
900
java
package com.imooc.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.Map; @Data @Component @ConfigurationProperties(prefix = "wechat") public class WechatAccountConfig { /** * 公众平台id */ private String mpAppId; /** * 公众平台秘钥 */ private String mpAppSecret; /** * 开放平台id */ private String openAppId; /** * 开放平台秘钥 */ private String openAppSecret; /** 商户号 */ private String mchId; /** 商户秘钥 */ private String mchKey; /** 商户证书路径 */ private String keyPath; /** * 微信支付异步通知地址 */ private String notifyUrl; /** * 微信模板id */ private Map<String,String> template; }
ecf9a409ea6adbc1459139842235075ded411f4f
fc79bc2fe072c3b71ae29bfc0df13e1197d02bda
/core/src/main/java/org/jboss/elemento/ObserverCallback.java
8bfecd7b5bf409ab543d068b75cf3d3a0987b854
[ "Apache-2.0" ]
permissive
treblereel/elemento
b072af96822a4b715aed43e205efe1f745d07d2f
6a4092182ba2cd880c15e5117ab8e367656820c8
refs/heads/master
2020-12-18T10:35:39.070766
2020-01-20T19:49:13
2020-01-20T19:49:13
235,348,466
0
0
Apache-2.0
2020-01-21T13:25:31
2020-01-21T13:25:30
null
UTF-8
Java
false
false
987
java
/* * Copyright 2015-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.elemento; import elemental2.dom.HTMLElement; import elemental2.dom.MutationRecord; /** * Callback for {@link Elements#onAttach(HTMLElement, ObserverCallback)} and {@link Elements#onDetach(HTMLElement, * ObserverCallback)} */ @FunctionalInterface public interface ObserverCallback { void onObserved(MutationRecord mutationRecord); }
fb13b0f2c8d06288cc4336c284264b2e6ca35a01
8f1b2860a8948ec01153ce01c86ab35b0c9c53e5
/src/main/java/com/patterns/adapter/newhrsystem/Employee.java
69eb7b92334861de97e141f35812efa48dfc375a
[]
no_license
TomaszTomasiak/patterns
29fc881fd14e7fb60156cf92097f0cb526389a15
e30643b49785bec48bc5b52646536eaa075467ff
refs/heads/master
2023-02-23T09:07:58.885668
2021-01-29T16:34:18
2021-01-29T16:34:18
332,729,536
0
0
null
null
null
null
UTF-8
Java
false
false
1,451
java
package com.patterns.adapter.newhrsystem; import java.math.BigDecimal; public class Employee { final private String peselId; final private String firstName; final private String lastName; final private BigDecimal baseSalary; public Employee(String peselId, String firstName, String lastName, BigDecimal baseSalary) { this.peselId = peselId; this.firstName = firstName; this.lastName = lastName; this.baseSalary = baseSalary; } public String getPeselId() { return peselId; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public BigDecimal getBaseSalary() { return baseSalary; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Employee)) return false; Employee employee = (Employee) o; return peselId != null ? peselId.equals(employee.peselId) : employee.peselId == null; } @Override public int hashCode() { return peselId != null ? peselId.hashCode() : 0; } @Override public String toString() { return "Employee{" + "peselId='" + peselId + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", baseSalary=" + baseSalary + '}'; } }
5101f878af5e76251c1e356e227ca1af117dbb50
ce57f69faa8a3568af0dfbda83bbc1951fe25b19
/src/main/java/cn/clate/kezhan/utils/Tools.java
874571ef4a9857ca66ca89b083d2f6428a67ac6d
[]
no_license
Nora0713/Kezhan_BackEnd
139be9ef77639e06855a3a3687249dd1587bb66f
66f501ec2fcff91ea59ff02740f114612901bd38
refs/heads/master
2021-09-10T07:44:48.150691
2018-03-22T09:57:53
2018-03-22T09:57:53
125,643,928
1
1
null
2018-03-18T06:15:26
2018-03-17T15:38:48
Java
UTF-8
Java
false
false
2,293
java
package cn.clate.kezhan.utils; import org.nutz.lang.Strings; import org.nutz.mvc.Mvcs; import javax.servlet.http.HttpServletRequest; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Tools { public static String MD5(String src){ try { MessageDigest digest = MessageDigest.getInstance("md5"); byte[] result = digest.digest(src.getBytes()); StringBuilder buffer = new StringBuilder(); for (byte b : result) { int number = b & 0xff; String str = Integer.toHexString(number); if (str.length() == 1) { buffer.append("0"); } buffer.append(str); } return buffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return ""; } } public static String passwordEncrypt(String password){ return MD5(MD5(password) + Conf.get("user.passwordSalt")); } public static String getRandStr(int length) { String KeyString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; StringBuffer sb = new StringBuffer(); int len = KeyString.length(); for (int i = 0; i < length; i++) { sb.append(KeyString.charAt((int) Math.round(Math.random() * (len - 1)))); } return sb.toString(); } public static long getTimeStamp(){ return System.currentTimeMillis()/1000; } /** * 获得用户远程地址 */ public static String getRemoteAddr() { HttpServletRequest request = Mvcs.getReq(); String remoteAddr = request.getHeader("X-Real-IP"); if (Strings.isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("X-Forwarded-For"); } else if (Strings.isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("Proxy-Client-IP"); } else if (Strings.isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("WL-Proxy-Client-IP"); } String ip = remoteAddr != null ? remoteAddr : Strings.sNull(request.getRemoteAddr()); return ip; } }
e2749a93f4f3386f64aaaa0dce9f8f4c87758a85
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/22/22_8bb7bbc93179db35fa33d00c8db8243f3a6cb985/FirewallRule/22_8bb7bbc93179db35fa33d00c8db8243f3a6cb985_FirewallRule_t.java
165703c4d38bc5e27973adca8b68dadb3a714709
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
25,011
java
/** * Copyright (C) 2009-2013 enstratius, Inc. * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.dasein.cloud.network; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * <p> * Describes a specific firewall rule allowing access through the target firewall. Note that for egress rules, the "source" * is actually the target and the "target" is the source. * </p> * @author George Reese ([email protected]) * @version 2010.08 * @version 2012.02 Added annotations * @version 2013.01 added full permission support and non-global destinations (Issue #14, Issue #11) * @version 2013.02 added precedence * @version 2013.04 added support for proper sorting of -1 rules to the end (issue greese/dasein-cloud-aws/#8) * @since 2010.08 */ @SuppressWarnings("UnusedDeclaration") public class FirewallRule implements Comparable<FirewallRule> { static private @Nonnull RuleTarget toSourceDestination(@Nonnull String source) { String[] parts = source.split("\\."); if( parts.length == 4 ) { int idx = parts[3].indexOf("/"); boolean num = true; if( idx > 0 ) { parts[3] = parts[3].substring(0,idx); } for( String p : parts ) { try { Integer.parseInt(p); } catch( NumberFormatException ignore ) { num = false; break; } } if( num ) { return RuleTarget.getCIDR(source); } } return RuleTarget.getGlobal(source); } /** * Constructs an INGRESS/ALLOW firewall rule from the specified source to all instances associated with this firewall. * @param firewallRuleId the provider ID for this rule (or null if the provider does not identify its rules) * @param providerFirewallId the unique ID of the firewall with which this rule is associated * @param source a CIDR indicating the set of IP addresses from which the traffic originates * @param protocol the protocol over which the communication is allowed * @param port the port for the communication * @return a firewall rule matching the parameters specified * @deprecated Use {@link #getInstance(String, String, RuleTarget, Direction, Protocol, Permission, RuleTarget, int, int)} */ static public @Nonnull FirewallRule getInstance(@Nullable String firewallRuleId, @Nonnull String providerFirewallId, @Nonnull String source, @Nonnull Protocol protocol, int port) { FirewallRule rule = new FirewallRule(); rule.sourceEndpoint = toSourceDestination(source); rule.destinationEndpoint = RuleTarget.getGlobal(providerFirewallId); rule.direction = Direction.INGRESS; rule.endPort = port; rule.firewallId = providerFirewallId; rule.permission = Permission.ALLOW; rule.protocol = protocol; rule.startPort = port; rule.precedence = 0; rule.providerRuleId = (firewallRuleId == null ? getRuleId(rule.firewallId, rule.sourceEndpoint, rule.direction, rule.protocol, rule.permission, rule.destinationEndpoint, rule.startPort, rule.endPort): firewallRuleId); return rule; } /** * Constructs an INGRESS/ALLOW firewall rule from the specified source to the instances matching the specified target. * @param firewallRuleId the provider ID for this rule (or null if the provider does not identify its rules) * @param providerFirewallId the unique ID of the firewall with which this rule is associated * @param source a CIDR indicating the set of IP addresses from which the traffic originates * @param protocol the protocol over which the communication is allowed * @param target the type of resources that may be targeted by the inbound traffic * @param port the port for the communication * @return a firewall rule matching the parameters specified * @deprecated Use {@link #getInstance(String, String, RuleTarget, Direction, Protocol, Permission, RuleTarget, int, int)} */ static public @Nonnull FirewallRule getInstance(@Nullable String firewallRuleId, @Nonnull String providerFirewallId, @Nonnull String source, @Nonnull Protocol protocol, @Nonnull RuleTarget target, int port) { FirewallRule rule = new FirewallRule(); rule.sourceEndpoint = toSourceDestination(source); rule.destinationEndpoint = target; rule.direction = Direction.INGRESS; rule.endPort = port; rule.firewallId = providerFirewallId; rule.permission = Permission.ALLOW; rule.protocol = protocol; rule.startPort = port; rule.precedence = 0; rule.providerRuleId = (firewallRuleId == null ? getRuleId(rule.firewallId, rule.sourceEndpoint, rule.direction, rule.protocol, rule.permission, rule.destinationEndpoint, rule.startPort, rule.endPort): firewallRuleId); return rule; } /** * Constructs a firewall rule originating from/to the specified source CIDR and traveling in the specified direction to/from the specified target resources. * Due to some historical oddities, what "source" and "target" mean are dependent on the direction of travel. The source * is ALWAYS outside the firewall, and the target is ALWAYS behind the firewall. Therefore, under an EGRESS rule, the * source is the target and the target is the source. This reversal is not true for non-deprecated methods. * @param firewallRuleId the provider ID for this rule (or null if the provider does not identify its rules) * @param providerFirewallId the unique ID of the firewall with which this rule is associated * @param source a CIDR indicating the set of IP addresses from which the traffic originates * @param direction the direction of the network traffic being allowed/disallowed * @param protocol the protocol over which the communication is allowed * @param permission whether or not the traffic is being allowed/denied * @param target the type of resources that may be targeted by the inbound traffic * @param port the port for the communication * @return a firewall rule matching the parameters specified * @deprecated Use {@link #getInstance(String, String, RuleTarget, Direction, Protocol, Permission, RuleTarget, int, int)} */ static public @Nonnull FirewallRule getInstance(@Nullable String firewallRuleId, @Nonnull String providerFirewallId, @Nonnull String source, @Nonnull Direction direction, @Nonnull Protocol protocol, @Nonnull Permission permission, @Nonnull RuleTarget target, int port) { FirewallRule rule = new FirewallRule(); if( direction.equals(Direction.INGRESS) ) { rule.sourceEndpoint = toSourceDestination(source); rule.destinationEndpoint = target; } else { rule.sourceEndpoint = target; rule.destinationEndpoint = toSourceDestination(source); } rule.direction = direction; rule.endPort = port; rule.firewallId = providerFirewallId; rule.permission = permission; rule.protocol = protocol; rule.startPort = port; rule.precedence = 0; rule.providerRuleId = (firewallRuleId == null ? getRuleId(rule.firewallId, rule.sourceEndpoint, rule.direction, rule.protocol, rule.permission, rule.destinationEndpoint, rule.startPort, rule.endPort): firewallRuleId); return rule; } /** * Constructs a firewall rule originating from/to the specified source CIDR and traveling in the specified direction to/from the specified target resources. * Due to some historical oddities, what "source" and "target" mean are dependent on the direction of travel. The source * is ALWAYS outside the firewall, and the target is ALWAYS behind the firewall. Therefore, under an EGRESS rule, the * source is the target and the target is the source. This reversal is not true for non-deprecated methods. * @param firewallRuleId the provider ID for this rule (or null if the provider does not identify its rules) * @param providerFirewallId the unique ID of the firewall with which this rule is associated * @param source a CIDR indicating the set of IP addresses from which the traffic originates * @param direction the direction of the network traffic being allowed/disallowed * @param protocol the protocol over which the communication is allowed * @param permission whether or not the traffic is being allowed/denied * @param target the type of resources that may be targeted by the inbound traffic * @param startPort the end of the port range for the communication * @param endPort the end of the port range for the communication * @return a firewall rule matching the parameters specified * @deprecated Use {@link #getInstance(String, String, RuleTarget, Direction, Protocol, Permission, RuleTarget, int, int)} */ static public @Nonnull FirewallRule getInstance(@Nullable String firewallRuleId, @Nonnull String providerFirewallId, @Nonnull String source, @Nonnull Direction direction, @Nonnull Protocol protocol, @Nonnull Permission permission, @Nonnull RuleTarget target, int startPort, int endPort) { FirewallRule rule = new FirewallRule(); if( direction.equals(Direction.INGRESS) ) { rule.sourceEndpoint = toSourceDestination(source); rule.destinationEndpoint = target; } else { rule.sourceEndpoint = target; rule.destinationEndpoint = toSourceDestination(source); } rule.direction = direction; rule.endPort = endPort; rule.firewallId = providerFirewallId; rule.permission = permission; rule.protocol = protocol; rule.precedence = 0; rule.startPort = startPort; rule.providerRuleId = (firewallRuleId == null ? getRuleId(rule.firewallId, rule.sourceEndpoint, rule.direction, rule.protocol, rule.permission, rule.destinationEndpoint, rule.startPort, rule.endPort): firewallRuleId); return rule; } /** * Constructs a firewall rule matching traffic that originates from the specified source endpoint going to the * specified destination endpoint. For an INGRESS rule, the source is outside the network and the destination is * protected by this firewall. For an EGRESS rule, the source is a resource protected by this firewall and the * destination is some resources external to this. This straightforward approach differs from the way the deprecated * versions of this method treat source/target. * @param firewallRuleId the provider ID for this rule (or null if the provider does not identify its rules) * @param providerFirewallId the unique ID of the firewall with which this rule is associated * @param sourceEndpoint a rule target identifying the source of traffic associated with this rule * @param direction the direction of the network traffic being allowed/disallowed * @param protocol the protocol over which the communication is allowed * @param permission whether or not the traffic is being allowed/denied * @param destinationEndpoint a rule target identifying the destination of traffic associated with this rule * @param startPort the end of the port range for the communication * @param endPort the end of the port range for the communication * @return a firewall rule matching the parameters specified */ static public @Nonnull FirewallRule getInstance(@Nullable String firewallRuleId, @Nonnull String providerFirewallId, @Nonnull RuleTarget sourceEndpoint, @Nonnull Direction direction, @Nonnull Protocol protocol, @Nonnull Permission permission, @Nonnull RuleTarget destinationEndpoint, int startPort, int endPort) { FirewallRule rule = new FirewallRule(); rule.sourceEndpoint = sourceEndpoint; rule.destinationEndpoint = destinationEndpoint; rule.direction = direction; rule.endPort = endPort; rule.firewallId = providerFirewallId; rule.permission = permission; rule.protocol = protocol; rule.precedence = 0; rule.startPort = startPort; rule.providerRuleId = (firewallRuleId == null ? getRuleId(rule.firewallId, rule.sourceEndpoint, rule.direction, rule.protocol, rule.permission, rule.destinationEndpoint, rule.startPort, rule.endPort): firewallRuleId); return rule; } static public @Nonnull String getRuleId(@Nonnull String providerFirewallId, @Nonnull String source, @Nonnull Direction direction, @Nonnull Protocol protocol, @Nonnull Permission permission, @Nullable RuleTarget target, int startPort, int endPort) { if( target == null ) { if( Permission.ALLOW.equals(permission) ) { return providerFirewallId + ":" + source + ":" + direction + ":" + protocol + ":" + startPort + ":" + endPort; } else { return Permission.DENY + ":" + providerFirewallId + ":" + source + ":" + direction + ":" + protocol + ":" + startPort + ":" + endPort; } } else { return permission + ":" + providerFirewallId + ":" + source + ":" + direction + ":" + protocol + ":" + startPort + ":" + endPort + ":" + target; } } static public @Nonnull String getRuleId(@Nonnull String providerFirewallId, @Nonnull RuleTarget sourceEndpoint, @Nonnull Direction direction, @Nonnull Protocol protocol, @Nonnull Permission permission, @Nullable RuleTarget destinationEndpoint, int startPort, int endPort) { if( destinationEndpoint == null ) { if( Permission.ALLOW.equals(permission) ) { return providerFirewallId + ":" + sourceEndpoint + ":" + direction + ":" + protocol + ":" + startPort + ":" + endPort; } else { return Permission.DENY + ":" + providerFirewallId + ":" + sourceEndpoint + ":" + direction + ":" + protocol + ":" + startPort + ":" + endPort; } } else { return permission + ":" + providerFirewallId + ":" + sourceEndpoint + ":" + direction + ":" + protocol + ":" + startPort + ":" + endPort + ":" + destinationEndpoint; } } static public @Nullable FirewallRule parseId(@Nonnull String id) { String[] parts = id.split(":"); if( parts.length < 2 ) { return null; } Permission permission = Permission.ALLOW; int i = 0; if( parts[i].equalsIgnoreCase("DENY") ) { permission = Permission.DENY; i++; } else if( parts[i].equalsIgnoreCase("ALLOW") ) { i++; } if( parts.length < i+1 ) { return null; } String providerFirewallId = parts[i++]; if( parts.length < i+1 ) { return null; } Direction direction = null; RuleTarget source; String tname = parts[i++]; if( parts.length < i+1 ) { return null; } else { try { RuleTargetType t = RuleTargetType.valueOf(tname); String tmp = parts[i++]; direction = Direction.valueOf(tmp.toUpperCase()); switch( t ) { case GLOBAL: source = RuleTarget.getGlobal(tmp); break; case VM: source = RuleTarget.getVirtualMachine(tmp); break; case VLAN: source = RuleTarget.getVlan(tmp); break; case CIDR: source = RuleTarget.getCIDR(tmp); break; default: return null; } } catch( Throwable ignore ) { source = RuleTarget.getGlobal(providerFirewallId); } } if( direction == null ) { try { direction = Direction.valueOf(parts[i++].toUpperCase()); } catch( Throwable ignore ) { return null; } } if( parts.length < i+1 ) { return null; } Protocol protocol; try { protocol = Protocol.valueOf(parts[i++].toUpperCase()); } catch( Throwable ignore ) { return null; } if( parts.length < i+1 ) { return null; } int startPort; try { startPort = Integer.parseInt(parts[i++]); } catch( NumberFormatException ignore ) { return null; } if( parts.length < i+1 ) { return null; } int endPort; try { endPort = Integer.parseInt(parts[i++]); } catch( NumberFormatException ignore ) { return null; } RuleTarget target; if( parts.length < i+1 ) { target = RuleTarget.getGlobal(providerFirewallId); } else { tname = parts[i++]; if( parts.length < i+1 ) { target = RuleTarget.getGlobal(providerFirewallId); } else { try { RuleTargetType t = RuleTargetType.valueOf(tname); switch( t ) { case GLOBAL: target = RuleTarget.getGlobal(parts[i]); break; case VM: target = RuleTarget.getVirtualMachine(parts[i]); break; case VLAN: target = RuleTarget.getVlan(parts[i]); break; case CIDR: target = RuleTarget.getCIDR(parts[i]); break; default: return null; } } catch( Throwable ignore ) { target = RuleTarget.getGlobal(providerFirewallId); } } } return FirewallRule.getInstance(null, providerFirewallId, source, direction, protocol, permission, target, startPort, endPort); } private RuleTarget destinationEndpoint; private Direction direction; private int endPort; private String firewallId; private Permission permission; private int precedence; private Protocol protocol; private String providerRuleId; private RuleTarget sourceEndpoint; private int startPort; private FirewallRule() { } @Override public int compareTo(FirewallRule other) { if( other == null ) { return -1; } if( other == this ) { return 0; } if( direction.equals(other.direction) ) { if( precedence == other.precedence ) { return providerRuleId.compareTo(other.providerRuleId); } if( precedence == -1 ) { return 1; } else if( other.precedence == -1 ) { return -1; } return (new Integer(precedence)).compareTo(precedence); } return direction.compareTo(other.direction); } @Override public boolean equals(Object other) { if( other == null ) { return false; } if( other == this ) { return true; } //noinspection SimplifiableIfStatement if( !getClass().getName().equals(other.getClass().getName()) ) { return false; } return getProviderRuleId().equals(((FirewallRule)other).getProviderRuleId()); } /** * The source IP address or range of addresses in CIDR format. IP addresses matching * this CIDR have positive access to any server protected by this firewall to the port * range specified over the protocol specified. * <p>NOTE: Because sources can now be other firewalls, this value may no longer return an actual CIDR</p> * @return the source CIDR for this rule * @deprecated Use {@link #getSourceEndpoint()} */ public @Nullable String getCidr() { //noinspection deprecation return getSource(); } /** * @return the destination rule target for traffic matching this rule */ public @Nonnull RuleTarget getDestinationEndpoint() { return destinationEndpoint; } /** * @return the sub-target behind this firewall that limits routing of traffic. * @deprecated Use {@link #getDestinationEndpoint()} */ public @Nonnull RuleTarget getTarget() { if( destinationEndpoint == null ) { return RuleTarget.getGlobal(firewallId); } return destinationEndpoint; } /** * @return the direction in which this rule operates */ public @Nonnull Direction getDirection() { return (direction == null ? Direction.INGRESS : direction); } /** * @return the last port in the range of ports allowed by this rule */ public int getEndPort() { return endPort; } /** * @return the unique provider ID for the firewall behind this rule */ public @Nonnull String getFirewallId() { return firewallId; } /** * @return the permission behind this rule */ public @Nonnull Permission getPermission() { return (permission == null ? Permission.ALLOW : permission); } /** * @return the precedence level of this firewall rule */ public @Nonnegative int getPrecedence() { return precedence; } /** * @return the network protocol to allow through to the target ports */ public @Nonnull Protocol getProtocol() { return protocol; } /** * @return a unique ID that identifies this rule to the target cloud */ public @Nonnull String getProviderRuleId() { return providerRuleId; } /** * @return a string representing the source of this traffic * @deprecated Use {@link #getSourceEndpoint()} */ public @Nonnull String getSource() { String source; switch( sourceEndpoint.getRuleTargetType() ) { case GLOBAL: source = sourceEndpoint.getProviderFirewallId(); if( source == null ) { source = firewallId; } return source; case CIDR: //noinspection ConstantConditions return sourceEndpoint.getCidr(); case VM: //noinspection ConstantConditions return sourceEndpoint.getProviderVirtualMachineId(); case VLAN: //noinspection ConstantConditions return sourceEndpoint.getProviderVlanId(); } throw new RuntimeException("Invalid rule target type: " + sourceEndpoint.getRuleTargetType()); } /** * @return the source of the traffic associated with the rule */ public @Nonnull RuleTarget getSourceEndpoint() { return sourceEndpoint; } /** * @return the first port in the range of ports allowed by this rule */ public int getStartPort() { return startPort; } @Override public @Nonnull String toString() { return (direction + "/" + permission + ": " + sourceEndpoint + "->" + protocol + ":" + destinationEndpoint + " [" + startPort + "-" + endPort + "]"); } /** * Indicates a precedence order for this rule * @param precedence the numeric precedence * @return this */ public @Nonnull FirewallRule withPrecedence(@Nonnegative int precedence) { this.precedence = precedence; return this; } }
c3febc045f77249a49f26f4819a3592a066e2046
879ca3bf2f33818707caa13a192d397c72dd6240
/app/src/main/java/com/zczczy/by/xfy/tools/ListUtils.java
72820c9095c35ec3bcd8e367e8af50edf21e3e20
[]
no_license
zczczy/xfy
16141d8e5931df3f8b9eef073b01643f1672b51f
cc61eeffa5ec770214f0e05a11e5d8aa7c29c722
refs/heads/master
2021-01-09T21:55:51.229879
2015-12-22T00:57:11
2015-12-22T00:57:11
48,157,880
0
0
null
null
null
null
UTF-8
Java
false
false
5,211
java
package com.zczczy.by.xfy.tools; import java.util.List; public class ListUtils { /** * default join separator * */ public static final String DEFAULT_JOIN_SEPARATOR = ","; /** * get size of list * <p/> * <pre> * getSize(null) = 0; * getSize({}) = 0; * getSize({1}) = 1; * </pre> * * @param <V> * @param sourceList * @return if list is null or empty, return 0, else return {@link List#size()}. */ public static <V> int getSize(List<V> sourceList) { return sourceList == null ? 0 : sourceList.size(); } /** * is null or its size is 0 * <p/> * <pre> * isEmpty(null) = true; * isEmpty({}) = true; * isEmpty({1}) = false; * </pre> * * @param <V> * @param sourceList * @return if list is null or its size is 0, return true, else return false. */ public static <V> boolean isEmpty(List<V> sourceList) { return (sourceList == null || sourceList.size() == 0); } /** * join list to string, separator is "," * <p/> * <pre> * join(null) = ""; * join({}) = ""; * join({a,b}) = "a,b"; * </pre> * * @param list * @return join list to string, separator is ",". if list is empty, return "" */ public static String join(List<String> list) { return join(list, DEFAULT_JOIN_SEPARATOR); } /** * join list to string * <p/> * <pre> * join(null, '#') = ""; * join({}, '#') = ""; * join({a,b,c}, ' ') = "abc"; * join({a,b,c}, '#') = "a#b#c"; * </pre> * * @param list * @param separator * @return join list to string. if list is empty, return "" */ public static String join(List<String> list, char separator) { return join(list, new String(new char[]{separator})); } /** * join list to string. if separator is null, use {@link #DEFAULT_JOIN_SEPARATOR} * <p/> * <pre> * join(null, "#") = ""; * join({}, "#$") = ""; * join({a,b,c}, null) = "a,b,c"; * join({a,b,c}, "") = "abc"; * join({a,b,c}, "#") = "a#b#c"; * join({a,b,c}, "#$") = "a#$b#$c"; * </pre> * * @param list * @param separator * @return join list to string with separator. if list is empty, return "" */ public static String join(List<String> list, String separator) { if (isEmpty(list)) { return ""; } if (separator == null) { separator = DEFAULT_JOIN_SEPARATOR; } StringBuilder joinStr = new StringBuilder(); for (int i = 0; i < list.size(); i++) { joinStr.append(list.get(i)); if (i != list.size() - 1) { joinStr.append(separator); } } return joinStr.toString(); } /** * add distinct entry to list * * @param <V> * @param sourceList * @param entry * @return if entry already exist in sourceList, return false, else add it and return true. */ public static <V> boolean addDistinctEntry(List<V> sourceList, V entry) { return (sourceList != null && !sourceList.contains(entry)) ? sourceList.add(entry) : false; } /** * add all distinct entry to list1 from list2 * * @param <V> * @param sourceList * @param entryList * @return the count of entries be added */ public static <V> int addDistinctList(List<V> sourceList, List<V> entryList) { if (sourceList == null || isEmpty(entryList)) { return 0; } int sourceCount = sourceList.size(); for (V entry : entryList) { if (!sourceList.contains(entry)) { sourceList.add(entry); } } return sourceList.size() - sourceCount; } /** * remove duplicate entries in list * * @param <V> * @param sourceList * @return the count of entries be removed */ public static <V> int distinctList(List<V> sourceList) { if (isEmpty(sourceList)) { return 0; } int sourceCount = sourceList.size(); int sourceListSize = sourceList.size(); for (int i = 0; i < sourceListSize; i++) { for (int j = (i + 1); j < sourceListSize; j++) { if (sourceList.get(i).equals(sourceList.get(j))) { sourceList.remove(j); sourceListSize = sourceList.size(); j--; } } } return sourceCount - sourceList.size(); } /** * add not null entry to list * * @param sourceList * @param value * @return <ul> * <li>if sourceList is null, return false</li> * <li>if value is null, return false</li> * <li>return {@link List#add(Object)}</li> * </ul> */ public static <V> boolean addListNotNullValue(List<V> sourceList, V value) { return (sourceList != null && value != null) ? sourceList.add(value) : false; } }
d685881b42e0594561e559969b71527d7b8b895e
0b7345092059a917123cde7b8c685ed84bc06cc4
/src/main/java/com/genesys/application/exception/UserNotFoundException.java
8fe7762e675f6a5618b44cc365bf1400b52bf997
[]
no_license
yiwang2/spring-boot-aws
fbd7344334d73906749f4d37337ac0bbb4160ff8
78180a3ac620c0bae66d0b9369362376769861e3
refs/heads/main
2023-04-07T13:50:45.726028
2021-04-18T20:23:23
2021-04-18T20:23:23
344,105,293
0
0
null
null
null
null
UTF-8
Java
false
false
269
java
package com.genesys.application.exception; public class UserNotFoundException extends RuntimeException { private static final long serialVersionUID = -1803627348254029328L; public UserNotFoundException(String id) { super("Could not find user by id " + id); } }
37876eeebdc072938fd976b9db93ff9c197d07c7
d98e8d4308637135efcdfc61b69293709fc31d29
/lnahabedian-mtsa-26803a183c10/maven-root/mtsa/src/main/java/ltsa/lts/RandomCompositionEngine.java
de17a680f870f78b88b7ceb512badf80949b90b2
[]
no_license
FabianGomez/MTSATesting
63f036edc098ebceb23c772e5d9bdb66fb321052
4d2c9d95cab08f0345cb44017eb37bf7e97f21a1
refs/heads/master
2021-09-10T07:35:06.603016
2018-03-22T06:38:27
2018-03-22T06:38:27
112,141,922
0
0
null
null
null
null
UTF-8
Java
false
false
4,476
java
package ltsa.lts; import java.util.Iterator; import java.util.List; import ltsa.lts.util.LTSUtils; public class RandomCompositionEngine implements CompositionEngine { private StateMap analysed; private StateCodec coder; private long maxStateGeneration; private ModelExplorerContext ctx; private boolean deadlockDetected; LTSOutput output; public RandomCompositionEngine(StateCodec coder) { this.coder= coder; if (Options.useGeneratedSeed()) { analysed= new RandomHashStateMap(100001, Options.getRandomSeed()); } else { analysed= new RandomHashStateMap(100001); } maxStateGeneration= Options.getMaxStatesGeneration(); } // @Override public void initialize() { output.outln("Initializing RANDOM composition engine, seed= " + ((RandomHashStateMap) analysed).getSeed()); } public void setOutput(LTSOutput output) { this.output= output; } // @Override public StackCheck getStackChecker() { if (analysed instanceof StackCheck) return (StackCheck) analysed; else return null; } // @Override public void add(byte[] state) { analysed.add(state); } // @Override public void add(byte[] state, int depth) { analysed.add(state, depth); } // @Override public boolean deadlockDetected() { return deadlockDetected; } // @Override public String getExplorationStatistics() { return ""; } // @Override public StateMap getExploredStates() { return analysed; } // @Override public long getMaxStateGeneration() { return maxStateGeneration; } // @Override public ModelExplorerContext getModelExplorerContext() { return ctx; } // @Override public byte[] getNextState() { return analysed.getNextState(); } // @Override public boolean nextStateIsMarked() { return analysed.nextStateIsMarked(); } // @Override public void processNextState() { int[] state = coder.decode(getNextState()); analysed.markNextState(ctx.stateCount++); int depth= ((RandomHashStateMap) analysed).getNextStateDepth(); // determine eligible transitions List transitions = ModelExplorer.eligibleTransitions(ctx, state); if (transitions == null) { if (!ModelExplorer.isEND(ctx, state)) { // deadlockDetected = true; // HACK try to keep exploring ((RandomHashStateMap) analysed).unmarkNextState(); StateMapEntry poppedState= (StateMapEntry) ((RandomHashStateMap) analysed).popNextState(); analysed.add(poppedState.key); // CAN LEAD TO LOOPING! --ctx.stateCount; } else { // this is the end state if (ctx.endSequence < 0) ctx.endSequence = ctx.stateCount - 1; else { analysed.markNextState(ctx.endSequence); --ctx.stateCount; } } } else { Iterator e = transitions.iterator(); while (e.hasNext()) { int[] next = (int[]) e.next(); byte[] code = coder.encode(next); ctx.compTrans.add(ctx.stateCount-1, code, next[ctx.Nmach]); if (code == null) { int i = 0; while (next[i] >= 0) i++; if (!ctx.violated[i]) { // TODO move away and log // output.outln(" property " + ctx.sm[i].name + " violation."); } ctx.violated[i] = true; } else if (!analysed.contains(code)) { analysed.add(code, depth+1); } } } } // @Override public void pruneUnfinishedStates() { // TODO can be improved. int tauIndex= 0; for (int i= 0; i < ctx.actionName.length; i++) { if (ctx.actionName[i].equals("tau")) { tauIndex= i; break; } } ctx.stateCount++; int[] trapState= null; byte[] trapStateCode= null; while (!analysed.empty()) { if (!analysed.nextStateIsMarked()) { if (analysed.getNextStateNumber() == -1) { analysed.markNextState(ctx.stateCount++); } if (trapState == null) { byte[] nextState= analysed.getNextState(); trapState= LTSUtils.myclone(coder.decode(nextState)); for (int i= 0; i < trapState.length; i++) { trapState[i]= LTSConstants.TRAP_STATE; } trapStateCode= coder.encode(trapState); } ctx.compTrans.add(analysed.getNextStateNumber(), trapStateCode, tauIndex); } analysed.removeNextState(); } } // @Override public void removeNextState() { analysed.removeNextState(); } // @Override public void setMaxStateGeneration(long maxStates) { maxStateGeneration= maxStates; } // @Override public void setModelExplorerContext(ModelExplorerContext ctx) { this.ctx= ctx; } // @Override public void teardown() { analysed= null; } }
1856066d610ee165812ec66b1b4cbeed39dda5e7
90a2bbfbafba2cef15a4a514506c1ff6b2f0ef4e
/TrabalhandoComValidacaoEConversao/src/com/lucas/model/Endereco.java
57ea17b9eddd69e72538f6b67eddf2f3c652b63c
[]
no_license
LucasSyso/TrabalhandoComValidacaoEConversao
51fc3aa98c328b207ada4fe400a2a43f1591a507
a57c22345206a299673e75e3aad9ad066fc67c2d
refs/heads/master
2020-04-18T09:20:40.929460
2019-01-24T20:16:26
2019-01-24T20:16:26
167,430,858
0
0
null
null
null
null
UTF-8
Java
false
false
341
java
package com.lucas.model; public class Endereco { private String rua; private String numero; public String getRua() { return rua; } public void setRua(String rua) { this.rua = rua; } public String getNumero() { return numero; } public void setNumero(String numero) { this.numero = numero; } }
4797b26cedc62029d0271270489173d677f10e75
1633bd05558363b92b141d282ebc8f00ebb66f8b
/week-02/day-4/src/FunctionToCenter.java
592b0e21231579bc247afe07d42dd8f978a45875
[]
no_license
green-fox-academy/ed0wn
a13ce6fa4f15e46f67abb11282ea3c51cf89a1bf
a81183387ea2a83a1c8befd5d5457224938fbb30
refs/heads/master
2020-07-24T03:32:58.920080
2019-12-05T09:28:08
2019-12-05T09:28:08
207,789,405
1
0
null
null
null
null
UTF-8
Java
false
false
1,932
java
import javax.swing.*; import java.awt.*; import static javax.swing.JFrame.EXIT_ON_CLOSE; public class FunctionToCenter { public static void mainDraw(Graphics graphics) { // Create a function that draws a single line and takes 3 parameters: // The x and y coordinates of the line's starting point and the graphics // and draws a line from that point to the center of the canvas. // Fill the canvas with lines from the edges, every 20 px, to the center. int x= 0; int y= 0; for (int i = 0; i <= WIDTH/20*4; i++) { if(x<=WIDTH-20 && y==0 && x>=0 ){ line(x,y,graphics); x+=20; } else if (y<=HEIGHT-20 && x>=WIDTH-20){ line(x,y,graphics); y+=20; } else if (y>=HEIGHT-20 && (x>=WIDTH-20 || x>=0+20)){ line(x,y,graphics); x-=20; } else if (y<=HEIGHT && y>=0+20 && x==0){ line(x,y,graphics); y-=20; } } } public static void line(int x, int y, Graphics graphics) { graphics.drawLine(x, y, WIDTH / 2, HEIGHT / 2); } // Don't touch the code below static int WIDTH = 320; static int HEIGHT = 320; public static void main(String[] args) { JFrame jFrame = new JFrame("Drawing"); jFrame.setDefaultCloseOperation(EXIT_ON_CLOSE); ImagePanel panel = new ImagePanel(); panel.setPreferredSize(new Dimension(WIDTH, HEIGHT)); jFrame.add(panel); jFrame.setLocationRelativeTo(null); jFrame.setVisible(true); jFrame.pack(); } static class ImagePanel extends JPanel { @Override protected void paintComponent(Graphics graphics) { super.paintComponent(graphics); mainDraw(graphics); } } }
5caf059122e70d9af8cc986234d04aae840ccf56
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/19/19_805ed7a3c066c9242fee09a324c7aef20138417a/EclipseInstallGeneratorInfoProvider/19_805ed7a3c066c9242fee09a324c7aef20138417a_EclipseInstallGeneratorInfoProvider_s.java
07df3e72e5c5598b0bf2b6285c0fc8950f145e0a
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
18,393
java
/******************************************************************************* * Copyright (c) 2007, 2008 IBM Corporation and others. * 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.internal.provisional.p2.metadata.generator; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.*; import org.eclipse.equinox.internal.frameworkadmin.equinox.EquinoxFwConfigFileParser; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.metadata.generator.Activator; import org.eclipse.equinox.internal.p2.metadata.generator.Messages; import org.eclipse.equinox.internal.provisional.frameworkadmin.*; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; import org.eclipse.osgi.service.environment.EnvironmentInfo; import org.eclipse.osgi.util.NLS; import org.osgi.framework.*; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.util.tracker.ServiceTracker; public class EclipseInstallGeneratorInfoProvider implements IGeneratorInfo { private final static String FILTER_OBJECTCLASS = "(" + Constants.OBJECTCLASS + "=" + FrameworkAdmin.class.getName() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ private final static String filterFwName = "(" + FrameworkAdmin.SERVICE_PROP_KEY_FW_NAME + "=Equinox)"; //$NON-NLS-1$ //$NON-NLS-2$ //String filterFwVersion = "(" + FrameworkAdmin.SERVICE_PROP_KEY_FW_VERSION + "=" + props.getProperty("equinox.fw.version") + ")"; private final static String filterLauncherName = "(" + FrameworkAdmin.SERVICE_PROP_KEY_LAUNCHER_NAME + "=Eclipse.exe)"; //$NON-NLS-1$ //$NON-NLS-2$ //String filterLauncherVersion = "(" + FrameworkAdmin.SERVICE_PROP_KEY_LAUNCHER_VERSION + "=" + props.getProperty("equinox.launcher.version") + ")"; private final static String frameworkAdminFillter = "(&" + FILTER_OBJECTCLASS + filterFwName + filterLauncherName + ")"; //$NON-NLS-1$ //$NON-NLS-2$ private static final String ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR = "org.eclipse.equinox.simpleconfigurator"; //$NON-NLS-1$ private static final String ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR_MANIPULATOR = "org.eclipse.equinox.simpleconfigurator.manipulator"; //$NON-NLS-1$ private static final String ORG_ECLIPSE_EQUINOX_FRAMEWORKADMIN_EQUINOX = "org.eclipse.equinox.frameworkadmin.equinox"; //$NON-NLS-1$ private static final String ORG_ECLIPSE_EQUINOX_P2_RECONCILER_DROPINS = "org.eclipse.equinox.p2.reconciler.dropins"; //$NON-NLS-1$ /* * TODO: Temporary for determining whether eclipse installs * in a profile should support backward compatibility * with update manager. */ private static final String UPDATE_COMPATIBILITY = "eclipse.p2.update.compatibility"; //$NON-NLS-1$ private String os; /** * Returns a default name for the executable. * @param providedOS The operating system to return the executable for. If null, * the operating system is determined from the current runtime environment. */ public static String getDefaultExecutableName(String providedOS) { String theOS = providedOS; if (theOS == null) { EnvironmentInfo info = (EnvironmentInfo) ServiceHelper.getService(Activator.getContext(), EnvironmentInfo.class.getName()); theOS = info.getOS(); } if (theOS.equalsIgnoreCase("win32")) //$NON-NLS-1$ return "eclipse.exe"; //$NON-NLS-1$ if (theOS.equalsIgnoreCase("macosx")) //$NON-NLS-1$ return "Eclipse.app"; //$NON-NLS-1$ //FIXME Is this a reasonable default for all non-Windows platforms? return "eclipse"; //$NON-NLS-1$ } private boolean addDefaultIUs = true; private boolean append = false; private IArtifactRepository artifactRepository; private File baseLocation; private File[] bundleLocations; private File configLocation; private ArrayList defaultIUs; private List otherIUs; private File executableLocation; private File featuresLocation; private String flavor; private ServiceTracker frameworkAdminTracker; private Manipulator manipulator; private String[][] mappingRules; private IMetadataRepository metadataRepository; private boolean publishArtifactRepo = false; private boolean publishArtifacts = false; private boolean updateCompatibility = Boolean.valueOf(System.getProperty(UPDATE_COMPATIBILITY, "false")).booleanValue(); //$NON-NLS-1$ private String rootId; private String rootVersion; private String productFile = null; private String launcherConfig; private String versionAdvice; private URL siteLocation; private boolean reuseExistingPack200Files = false; public EclipseInstallGeneratorInfoProvider() { super(); } public boolean addDefaultIUs() { return addDefaultIUs; } public boolean append() { return append; } protected GeneratorBundleInfo createDefaultConfigurationBundleInfo() { GeneratorBundleInfo result = new GeneratorBundleInfo(); result.setSymbolicName("defaultConfigure"); //$NON-NLS-1$ result.setVersion("1.0.0"); //$NON-NLS-1$ result.setStartLevel(4); // These should just be in the install section now // result.setSpecialConfigCommands("installBundle(bundle:${artifact});"); return result; } protected GeneratorBundleInfo createDefaultUnconfigurationBundleInfo() { GeneratorBundleInfo result = new GeneratorBundleInfo(); result.setSymbolicName("defaultUnconfigure"); //$NON-NLS-1$ result.setVersion("1.0.0"); //$NON-NLS-1$ // These should just be in the uninstall section now // result.setSpecialConfigCommands("uninstallBundle(bundle:${artifact});"); return result; } /** * Obtains the framework manipulator instance. Throws an exception * if it could not be created. */ private void createFrameworkManipulator() { FrameworkAdmin admin = getFrameworkAdmin(); if (admin == null) throw new RuntimeException("Framework admin service not found"); //$NON-NLS-1$ manipulator = admin.getManipulator(); if (manipulator == null) throw new RuntimeException("Framework manipulator not found"); //$NON-NLS-1$ } public static GeneratorBundleInfo createLauncher() { GeneratorBundleInfo result = new GeneratorBundleInfo(); result.setSymbolicName("org.eclipse.equinox.launcher"); //$NON-NLS-1$ result.setVersion("0.0.0"); //$NON-NLS-1$ //result.setSpecialConfigCommands("manipulator.addProgramArgument('-startup'); manipulator.addProgramArgument(artifact);"); result.setSpecialConfigCommands("addProgramArg(programArg:-startup);addProgramArg(programArg:@artifact);"); //$NON-NLS-1$ result.setSpecialUnconfigCommands("removeProgramArg(programArg:-startup);removeProgramArg(programArg:@artifact);"); //$NON-NLS-1$ return result; } private Collection createLauncherBundleInfo(Set ius) { Collection result = new HashSet(); Collection launchers = getIUs(ius, "org.eclipse.equinox.launcher."); //$NON-NLS-1$ for (Iterator iterator = launchers.iterator(); iterator.hasNext();) { IInstallableUnit object = (IInstallableUnit) iterator.next(); if (object.getId().endsWith(".source")) //$NON-NLS-1$ continue; GeneratorBundleInfo temp = new GeneratorBundleInfo(); temp.setSymbolicName(object.getId()); temp.setVersion(object.getVersion().toString()); temp.setSpecialConfigCommands("addProgramArg(programArg:--launcher.library);addProgramArg(programArg:@artifact);"); //$NON-NLS-1$ temp.setSpecialUnconfigCommands("removeProgramArg(programArg:--launcher.library);removeProgramArg(programArg:@artifact);"); //$NON-NLS-1$ result.add(temp); } return result; } private GeneratorBundleInfo createSimpleConfiguratorBundleInfo() { GeneratorBundleInfo result = new GeneratorBundleInfo(); result.setSymbolicName(ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR); result.setVersion("0.0.0"); //$NON-NLS-1$ result.setStartLevel(1); result.setMarkedAsStarted(true); return result; } private GeneratorBundleInfo createDropinsReconcilerBundleInfo() { GeneratorBundleInfo result = new GeneratorBundleInfo(); result.setSymbolicName(ORG_ECLIPSE_EQUINOX_P2_RECONCILER_DROPINS); result.setVersion("0.0.0"); //$NON-NLS-1$ result.setMarkedAsStarted(true); result.setSpecialConfigCommands("mkdir(path:${installFolder}/dropins)"); //$NON-NLS-1$ result.setSpecialUnconfigCommands("rmdir(path:${installFolder}/dropins)"); //$NON-NLS-1$ return result; } private void expandBundleLocations() { if (bundleLocations == null) { bundleLocations = new File[] {}; return; } ArrayList result = new ArrayList(); for (int i = 0; i < bundleLocations.length; i++) { File location = bundleLocations[i]; if (location.isDirectory()) { File[] list = location.listFiles(); for (int j = 0; j < list.length; j++) result.add(list[j]); } else { result.add(location); } } bundleLocations = (File[]) result.toArray(new File[result.size()]); } public IArtifactRepository getArtifactRepository() { return artifactRepository; } public File getBaseLocation() { return baseLocation; } public File[] getBundleLocations() { return bundleLocations; } public ConfigData getConfigData() { return manipulator == null ? null : manipulator.getConfigData(); } public ConfigData loadConfigData(File location) { if (manipulator == null) return null; EquinoxFwConfigFileParser parser = new EquinoxFwConfigFileParser(Activator.getContext()); try { parser.readFwConfig(manipulator, location); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return manipulator.getConfigData(); } public File getConfigurationLocation() { return configLocation; } public ArrayList getDefaultIUs(Set ius) { if (defaultIUs != null) return defaultIUs; defaultIUs = new ArrayList(5); if (addDefaultIUs) { defaultIUs.addAll(createLauncherBundleInfo(ius)); defaultIUs.add(createLauncher()); defaultIUs.add(createSimpleConfiguratorBundleInfo()); defaultIUs.add(createDropinsReconcilerBundleInfo()); // defaultIUs.add(createDefaultConfigurationBundleInfo()); // defaultIUs.add(createDefaultUnconfigurationBundleInfo()); } return defaultIUs; } // TODO: This is kind of ugly. It's purpose is to allow us to craft CUs that we know about and need for our build // We should try to replace this with something more generic prior to release public Collection getOtherIUs() { if (otherIUs != null) return otherIUs; otherIUs = new ArrayList(); otherIUs.add(createDropinsReconcilerBundleInfo()); return otherIUs; } public File getExecutableLocation() { return executableLocation; } public File getFeaturesLocation() { return featuresLocation; } public String getFlavor() { //use 'tooling' as default flavor since we are not actively using flavors yet return flavor == null ? "tooling" : flavor; //$NON-NLS-1$ } private FrameworkAdmin getFrameworkAdmin() { if (frameworkAdminTracker == null) { try { Filter filter = Activator.getContext().createFilter(frameworkAdminFillter); frameworkAdminTracker = new ServiceTracker(Activator.getContext(), filter, null); frameworkAdminTracker.open(); } catch (InvalidSyntaxException e) { // never happens e.printStackTrace(); } } // try { // frameworkAdminTracker.waitForService(500); // } catch (InterruptedException e) { // // ignore // } FrameworkAdmin admin = (FrameworkAdmin) frameworkAdminTracker.getService(); if (admin == null) { startBundle(ORG_ECLIPSE_EQUINOX_FRAMEWORKADMIN_EQUINOX); startBundle(ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR_MANIPULATOR); admin = (FrameworkAdmin) frameworkAdminTracker.getService(); } return admin; } public boolean getIsUpdateCompatible() { return updateCompatibility; } private Collection getIUs(Set ius, String prefix) { Set result = new HashSet(); for (Iterator iterator = ius.iterator(); iterator.hasNext();) { IInstallableUnit tmp = (IInstallableUnit) iterator.next(); if (tmp.getId().startsWith(prefix)) result.add(tmp); } return result; } public File getJRELocation() { //assume JRE is relative to install location if (executableLocation == null) return null; return new File(executableLocation.getParentFile(), "jre"); //$NON-NLS-1$ } public String getLauncherConfig() { return launcherConfig; } public LauncherData getLauncherData() { return manipulator == null ? null : manipulator.getLauncherData(); } public String[][] getMappingRules() { return mappingRules; } public IMetadataRepository getMetadataRepository() { return metadataRepository; } public String getRootId() { return rootId; } public String getRootVersion() { if (rootVersion == null || rootVersion.length() == 0) return "0.0.0"; //$NON-NLS-1$ return rootVersion; } public String getProductFile() { return productFile; } public URL getSiteLocation() { return siteLocation; } public void initialize(File base) { // if the various locations are set in self, use them. Otherwise compute defaults File[] bundles = bundleLocations == null ? new File[] {new File(base, "plugins")} : bundleLocations; //$NON-NLS-1$ File features = featuresLocation == null ? new File(base, "features") : featuresLocation; //$NON-NLS-1$ File executable = executableLocation == null ? new File(base, getDefaultExecutableName(os)) : executableLocation; File configuration = configLocation == null ? new File(base, "configuration") : configLocation; //$NON-NLS-1$ initialize(base, configuration, executable, bundles, features); } public void initialize(File base, File config, File executable, File[] bundles, File features) { if (base == null || !base.exists()) throw new RuntimeException(NLS.bind(Messages.exception_sourceDirectoryInvalid, base == null ? "null" : base.getAbsolutePath())); //$NON-NLS-1$ this.baseLocation = base; if (config == null || config.exists()) this.configLocation = config; if (executable == null || executable.exists()) this.executableLocation = executable; if (bundles != null) bundleLocations = bundles; if (features != null) featuresLocation = features; expandBundleLocations(); // if the config or exe are not set then we cannot be generating any data related to the config so // don't bother setting up the manipulator. In fact, the manipulator will likely be invalid without // these locations. if (configLocation == null || executableLocation == null) return; createFrameworkManipulator(); LauncherData launcherData = manipulator.getLauncherData(); launcherData.setFwPersistentDataLocation(configLocation, true); launcherData.setLauncher(executableLocation); try { manipulator.load(); } catch (IllegalStateException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (FrameworkAdminRuntimeException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } public boolean publishArtifactRepository() { return publishArtifactRepo; } public boolean publishArtifacts() { return publishArtifacts; } public boolean reuseExistingPack200Files() { return reuseExistingPack200Files; } public void reuseExistingPack200Files(boolean publishPack) { reuseExistingPack200Files = publishPack; } public void setAddDefaultIUs(boolean value) { addDefaultIUs = value; } public void setAppend(boolean value) { append = value; } public void setArtifactRepository(IArtifactRepository value) { artifactRepository = value; } public void setExecutableLocation(String value) { executableLocation = new File(value); } public void setFlavor(String value) { flavor = value; } public void setIsUpdateCompatible(boolean isCompatible) { this.updateCompatibility = isCompatible; } public void setLauncherConfig(String value) { launcherConfig = value; } public void setMappingRules(String[][] value) { mappingRules = value; } public void setMetadataRepository(IMetadataRepository value) { metadataRepository = value; } public void setOS(String os) { this.os = os; } public void setPublishArtifactRepository(boolean value) { publishArtifactRepo = value; } public void setPublishArtifacts(boolean value) { publishArtifacts = value; } public void setRootId(String value) { rootId = value; } public void setRootVersion(String value) { rootVersion = value; } public void setProductFile(String file) { productFile = file; } /** * Sets the location of site.xml if applicable. */ public void setSiteLocation(URL location) { this.siteLocation = location; } private boolean startBundle(String bundleId) { PackageAdmin packageAdmin = (PackageAdmin) ServiceHelper.getService(Activator.getContext(), PackageAdmin.class.getName()); if (packageAdmin == null) return false; Bundle[] bundles = packageAdmin.getBundles(bundleId, null); if (bundles != null && bundles.length > 0) { for (int i = 0; i < bundles.length; i++) { try { if ((bundles[0].getState() & Bundle.RESOLVED) > 0) { bundles[0].start(); return true; } } catch (BundleException e) { // failed, try next bundle } } } return false; } public String getVersionAdvice() { return versionAdvice; } public void setVersionAdvice(String advice) { this.versionAdvice = advice; } }
0537379eaed265dc64a8fb7be7049daf4f91d188
f5d4c01294827d80b6cab4053b03eb9ce001b6af
/src/java/com/equant/csi/interfaces/cis/AbstractExtraction.java
b7aac742ec8bc6da9b871bdbf7f35195894590a4
[]
no_license
ajaygtl/goldRep
81dbc84d823a36d88c080ba6859649348d9d9fa8
734f5155833095a1a02c3d3d53140b48beaef6bf
refs/heads/master
2020-03-30T07:12:42.064907
2018-12-28T06:24:00
2018-12-28T06:24:00
150,923,121
0
0
null
2018-12-27T10:44:12
2018-09-30T02:43:57
Java
UTF-8
Java
false
false
5,199
java
package com.equant.csi.interfaces.cis; import java.rmi.RemoteException; import java.sql.Connection; import java.sql.SQLException; import java.util.Set; import javax.ejb.CreateException; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.rmi.PortableRemoteObject; import javax.sql.DataSource; import org.apache.log4j.Category; import com.equant.csi.ejb.biz.ServiceManager; import com.equant.csi.ejb.biz.ServiceManagerHome; import com.equant.csi.exceptions.CISException; import com.equant.csi.utilities.LoggerFactory; import com.equant.csi.weblogic.AbstractTimeService; public abstract class AbstractExtraction extends AbstractTimeService { protected static Category logger = LoggerFactory.getInstance(AbstractExtraction.class); protected static final Category cis_logger = LoggerFactory.getInstance("cis_extraction.CISIPProduct"); protected String m_productToRun; protected Set m_productToRunSet = null; protected static String m_jndiCISDataSourceName; protected static String m_jndiCSIDataSourceName; protected static String m_jndiGOLDDataSourceName; private DataSource m_cisDataSource; protected DataSource m_csiDataSource; protected DataSource m_goldDataSource; protected ServiceManager m_serviceManager; public boolean allowSimultaneousRun() { return false; } /** * help metho */ protected void setProductToRunHT() { if (m_productToRunSet == null && m_productToRun != null) { m_productToRunSet = CISManagerHelper.parseProductToRun(m_productToRun); } } /** * @param runType * @throws com.equant.csi.exceptions.CISException * */ protected void cisRun(int runType) throws CISException { Connection sybaseConn = null; Connection localConn = null; Connection goldConn = null; ServiceManager sm = null; try { sybaseConn = getCISDataSource().getConnection(); localConn = getLocalCSIDataSource().getConnection(); goldConn = getGOLDDataSource().getConnection(); sm = getServiceManager(); CISManagerHelper.cisSubRun(sybaseConn, localConn, runType, sm, goldConn, m_productToRunSet, cis_logger); } catch (NamingException ne) { logger.fatal(ne); } catch (CISException cise) { logger.fatal(cise); } catch (Exception e) { logger.fatal(e); } finally { try { logger.debug("close connection"); localConn.close(); sybaseConn.close(); goldConn.close(); } catch (SQLException e) { logger.fatal(e); } } } /** * Lookup for CIS datasource and return it * * @return CIS DataSource object * @throws NamingException */ DataSource getCISDataSource() throws NamingException { if (m_cisDataSource == null) { InitialContext ic = new InitialContext(); m_cisDataSource = (DataSource) ic.lookup(m_jndiCISDataSourceName); } return m_cisDataSource; } /** * Lookup for local CSI datasource and return it * * @return CSI DataSource object * @throws NamingException */ DataSource getLocalCSIDataSource() throws NamingException { if (m_csiDataSource == null) { InitialContext ic = new InitialContext(); m_csiDataSource = (DataSource) ic.lookup(m_jndiCSIDataSourceName); } return m_csiDataSource; } /** * @return * @throws NamingException */ DataSource getGOLDDataSource() throws NamingException { if (m_goldDataSource == null) { InitialContext ic = new InitialContext(); m_goldDataSource = (DataSource) ic.lookup(m_jndiGOLDDataSourceName); } return m_goldDataSource; } /** * Creates and returns an instance of ServiceManager EJB. * * @return the instance of ServiceManager EJB * @throws NamingException thrown for any error during retrieving * the object with JNDI * @throws javax.ejb.CreateException the creation of the ServiceManager object failed * @throws java.rmi.RemoteException the communication-related exceptions that may occur * during the execution of a remote method call */ ServiceManager getServiceManager() throws NamingException, CreateException, RemoteException { if (m_serviceManager == null) { InitialContext ic = new InitialContext(); // changed as part of gold infra. change // ServiceManagerHome home = (ServiceManagerHome) PortableRemoteObject.narrow(ic.lookup(ServiceManagerHome.class.getName()), ServiceManagerHome.class); ServiceManagerHome home = (ServiceManagerHome) PortableRemoteObject.narrow(ic.lookup("com.equant.csi.ejb.biz.ServiceManagerHome"), ServiceManagerHome.class); m_serviceManager = home.create(); } return m_serviceManager; } }
b419d0f20c1fc2a7ff30ef4e3f59551efbac807a
77eb5acb082bded62d8ffd14648e5bd990392fb4
/app/src/main/java/com/android/shopr/adapters/ProductsRecyclerViewAdapter.java
c1ad2d5855ba4809c503857ad82afc619bdef0b6
[]
no_license
abhinav272/Demo
e4e7eac8feea3a4b4c1ecc3520ae5c29d9224cce
ac599471cd816031fe2b58cb26d7fbdb15df519f
refs/heads/master
2020-06-21T01:56:03.209810
2017-07-16T14:58:14
2017-07-16T14:58:14
74,810,896
0
0
null
null
null
null
UTF-8
Java
false
false
3,961
java
package com.android.shopr.adapters; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Toast; import com.android.shopr.R; import com.android.shopr.adapters.viewholders.ProductImageViewHolder; import com.android.shopr.adapters.viewholders.SingleImageAndTextViewHolder; import com.android.shopr.model.Category; import com.android.shopr.model.CategoryWiseProducts; import com.android.shopr.model.Product; import com.android.shopr.model.StoreWiseCategories; import com.android.shopr.utils.Utils; import com.squareup.picasso.Picasso; import java.util.List; /** * Created by abhinav.sharma on 21/01/17. */ public class ProductsRecyclerViewAdapter extends RecyclerView.Adapter<ProductImageViewHolder> { private static final String TAG = ProductsRecyclerViewAdapter.class.getSimpleName(); private Context mContext; private DelegateEvent delegateEvent; private StoreWiseCategories mStoreWiseCategories; public ProductsRecyclerViewAdapter(Context mContext, StoreWiseCategories mStoreWiseCategories, DelegateEvent delegateEvent) { this.mContext = mContext; this.delegateEvent = delegateEvent; this.mStoreWiseCategories = mStoreWiseCategories; } public interface DelegateEvent { void delegateToHost(int categoryId, Product product); } @Override public void onViewDetachedFromWindow(ProductImageViewHolder holder) { super.onViewDetachedFromWindow(holder); holder.mImageView.clearAnimation(); // holder.mTextView.clearAnimation(); } @Override public ProductImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View layoutView = LayoutInflater.from(mContext).inflate(R.layout.product_image_and_description, parent, false); return new ProductImageViewHolder(layoutView); } @Override public void onBindViewHolder(ProductImageViewHolder holder, final int position) { Picasso.with(mContext).load(getItem(position).getImageUrl()).fit().centerCrop() .placeholder(new ColorDrawable(Utils.getRandomBackgroundColor())).into(holder.mImageView); holder.productName.setText(getItem(position).getProductName()); holder.originalPrice.setText(mContext.getString(R.string.ruppee_symbol)+getItem(position).getPriceBeforeDiscount()); holder.productDiscount.setText(getItem(position).getDiscount() + " OFF"); holder.priceAfterDiscount.setText(mContext.getString(R.string.ruppee_symbol)+getItem(position).getPriceAfterDiscount()); holder.mWatchThis.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.e(TAG, "onClick: watch this product " + getItem(position).getProductName()); Toast.makeText(mContext, "Watch product : " + getItem(position).getProductName(), Toast.LENGTH_SHORT).show(); } }); holder.mImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { delegateEvent.delegateToHost(mStoreWiseCategories.getCategoryId(), getItem(position)); } }); // Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.up_from_bottom); // holder.mTextView.startAnimation(animation); // holder.mImageView.startAnimation(animation); } @Override public int getItemCount() { return mStoreWiseCategories.getProducts().size(); } private Product getItem(int position) { return mStoreWiseCategories.getProducts().get(position); } }
83c755abba3e2a9515e65ee49d0d53730cfa1859
19efc41644f383d99f16db130a2cc5449b2e4c47
/src/main/java/com/valework/yingul/service/CardProviderService.java
0815d9bfc8da44d9d7000c57b83d8dd902c30095
[]
no_license
DanielChoque/backYingul
b30c40f98d7a8c7f10cfa28d7c3984b8e62f25d3
eca574f15b56ba92b9d3a7a0a2f2ad1c7c5f31a6
refs/heads/master
2021-05-12T07:24:42.734727
2018-01-12T14:07:14
2018-01-12T14:07:14
117,241,791
0
0
null
null
null
null
UTF-8
Java
false
false
292
java
package com.valework.yingul.service; import java.util.List; import com.valework.yingul.model.Yng_CardProvider; import com.valework.yingul.model.Yng_ListCreditCard; public interface CardProviderService { List<Yng_CardProvider> findByListCreditCard(Yng_ListCreditCard yng_ListCreditCard); }
49e4332d562c0e8e81ee96e8d89c4d188a50f3c4
44e7adc9a1c5c0a1116097ac99c2a51692d4c986
/aws-java-sdk-appstream/src/main/java/com/amazonaws/services/appstream/model/transform/LastReportGenerationExecutionErrorJsonUnmarshaller.java
d351f467d524d01afd0ba2334133e18c1b5c9dba
[ "Apache-2.0" ]
permissive
QiAnXinCodeSafe/aws-sdk-java
f93bc97c289984e41527ae5bba97bebd6554ddbe
8251e0a3d910da4f63f1b102b171a3abf212099e
refs/heads/master
2023-01-28T14:28:05.239019
2020-12-03T22:09:01
2020-12-03T22:09:01
318,460,751
1
0
Apache-2.0
2020-12-04T10:06:51
2020-12-04T09:05:03
null
UTF-8
Java
false
false
3,235
java
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.appstream.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.appstream.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * LastReportGenerationExecutionError JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class LastReportGenerationExecutionErrorJsonUnmarshaller implements Unmarshaller<LastReportGenerationExecutionError, JsonUnmarshallerContext> { public LastReportGenerationExecutionError unmarshall(JsonUnmarshallerContext context) throws Exception { LastReportGenerationExecutionError lastReportGenerationExecutionError = new LastReportGenerationExecutionError(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("ErrorCode", targetDepth)) { context.nextToken(); lastReportGenerationExecutionError.setErrorCode(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("ErrorMessage", targetDepth)) { context.nextToken(); lastReportGenerationExecutionError.setErrorMessage(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return lastReportGenerationExecutionError; } private static LastReportGenerationExecutionErrorJsonUnmarshaller instance; public static LastReportGenerationExecutionErrorJsonUnmarshaller getInstance() { if (instance == null) instance = new LastReportGenerationExecutionErrorJsonUnmarshaller(); return instance; } }
[ "" ]
87e6fd199c5182a6d922f5c13a06b1e91cac6f66
0991ae1b190af25771b5f3e0318ad2d050e579e6
/MarvinSimulator/app/src/test/java/ar/com/klee/marvin/expressions/ExpressionMatcherTest.java
6da1289953b2016f67573affbc7e9866aca6b501
[]
no_license
KleeAr/marvin
d6cc525c0b1e5ccbf85ddd8c372e71b5f65463b1
b6b8763830b3aa70777ad1c8e7549c1d428d1052
refs/heads/master
2021-01-25T05:35:34.509818
2015-11-20T14:48:41
2015-11-20T14:48:41
34,924,754
1
1
null
null
null
null
UTF-8
Java
false
false
2,109
java
package ar.com.klee.marvin.expressions; import org.junit.Test; import java.util.Map; import ar.com.klee.marvinSimulator.expressions.ExpressionMatcher; import ar.com.klee.marvinSimulator.expressions.exceptions.ExpressionMatcherException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * * Test class for the class ExpressionMatcherTest * * @author msalerno * */ public class ExpressionMatcherTest { private static final String TEMPLATE = "my name is {username} and i am {userage} years old"; private static final String MATIAS = "my name is Matias and i am 25 years old"; private static final String FEDE = "my name is Federico and i am 23 years old"; // Class under test private ExpressionMatcher expressionMatcher = new ExpressionMatcher(TEMPLATE); @Test public void testGetValuesFromExpression() { Map<String, String> variables = expressionMatcher.getValuesFromExpression(MATIAS); assertEquals("Matias", variables.get("username")); assertEquals("25", variables.get("userage")); variables = expressionMatcher.getValuesFromExpression(FEDE); assertEquals("Federico", variables.get("username")); assertEquals("23", variables.get("userage")); } @Test(expected = ExpressionMatcherException.class) public void testGetValuesFromExpressionWhenDoesntMatch() { // Will throw exception because it doesn't match expressionMatcher.getValuesFromExpression("My name is Barry Allen, and I'm the fastest man alive"); } @Test public void testMatches() { assertTrue(expressionMatcher.matches(MATIAS)); assertFalse("Must not match, since expression says 'was' instead of 'is'", expressionMatcher.matches("My name was Matias and i am 25 years old")); } @Test public void testIsSimilar() { assertTrue(expressionMatcher.isSimilar("My car is Matias")); assertEquals("my name is username and i am userage years old", expressionMatcher.getSuggestion()); } }
e1fa8d44518ff75f792d35455263380b24f796a3
522ee36e28c05b24f70f4c5c558917b2160a6324
/src/main/java/com/jzy/gui/WindowOfCalculateMod.java
67d20882dee5b7fb669f21b87cd95aa864e2f29e
[]
no_license
BiboRose/Mathematical-Caculation-Tools
0f5c7c9f2531accb166b9c417778831e77ebe386
b8630e7ac2f0f8c7cd2c7ab6b4cb8ec59bc09c4d
refs/heads/master
2022-12-01T03:30:30.813261
2020-07-26T09:13:53
2020-07-26T09:13:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,755
java
package com.jzy.gui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.math.BigInteger; import javax.swing.*; import com.jzy.util.StringTest; import com.jzy.xxaqsxjc.method0.Method0; /** * 最小非负余数和绝对值最小余数计算图形类 * * @author JinZhiyun * @version 1.0, 19/09/03 */ public class WindowOfCalculateMod { /** * 最小非负余数和绝对值最小余数计算 * * @param frm * @version 1.0, 19/09/03 * @author JinZhiyun */ public static void GUICalculateMod(JFrame frm) { JLabel j11 = new JLabel("2、最小非负余数和绝对值最小余数计算 :b^n mod m=?,请输入b,n,m"); j11.setBounds(50, 90, GUIWindow.FrameWidth, 25); frm.add(j11); JButton btn = new JButton("进入"); btn.setBounds(470, 90, 80, 25); frm.add(btn); btn.addActionListener(new ActionListener() { // 按钮响应事件 @Override public void actionPerformed(ActionEvent e) { JFrame frmHidden = new JFrame(); frmHidden.setBounds(2 * GUIWindow.FrameStartX, 2 * GUIWindow.FrameStartY, 900, 150); // 设置窗口初始位置和大小 frmHidden.setTitle("最小非负余数和绝对值最小余数计算 :b^n mod m=?,请输入b,n,m"); // 设置标题 frmHidden.setLayout(null); // 如过不设置为null默认,按钮会充满整个内容框,挡住背景颜色 GUICalculateModHidden(frmHidden); frmHidden.setVisible(true); // 显示窗口 } }); } /** * 点击进入后的最小非负余数和绝对值最小余数计算模块 * * @param frm * @version 1.0, 19/09/03 * @author JinZhiyun */ public static void GUICalculateModHidden(JFrame frm) { JLabel j12 = new JLabel("b="); j12.setBounds(50, 30, 20, 25); frm.add(j12); JTextField jtf1 = new JTextField(); // 创建文本行组件 jtf1.setBounds(70, 30, 150, 25); // 左边距,上边距,长,宽 frm.add(jtf1); JLabel j13 = new JLabel("n="); j13.setBounds(250, 30, 20, 25); frm.add(j13); JTextField jtf2 = new JTextField(); // 创建文本行组件 jtf2.setBounds(270, 30, 150, 25); // 左边距,上边距,长,宽 frm.add(jtf2); JLabel j14 = new JLabel("m="); j14.setBounds(450, 30, 20, 25); frm.add(j14); JTextField jtf3 = new JTextField(); // 创建文本行组件 jtf3.setBounds(470, 30, 150, 25); // 左边距,上边距,长,宽 frm.add(jtf3); JButton btn = new JButton("计算"); btn.setBounds(650, 30, 80, 25); frm.add(btn); JLabel j15 = new JLabel("最小非负余数="); j15.setBounds(50, 60, 90, 25); frm.add(j15); JTextField jtf4 = new JTextField(); // 创建文本行组件 jtf4.setBounds(140, 60, 150, 25); // 左边距,上边距,长,宽 jtf4.setEditable(false); frm.add(jtf4); JLabel j16 = new JLabel("绝对值最小余数="); j16.setBounds(320, 60, 110, 25); frm.add(j16); JTextField jtf5 = new JTextField(); // 创建文本行组件 jtf5.setBounds(430, 60, 150, 25); // 左边距,上边距,长,宽 jtf5.setEditable(false); frm.add(jtf5); btn.addActionListener(new ActionListener() { // 按钮响应事件 @Override public void actionPerformed(ActionEvent e) { if (StringTest.isInteger(jtf1.getText()) && StringTest.isLegalNonNegativeInteger(jtf2.getText()) && StringTest.isLegalPositiveInteger(jtf3.getText())) { BigInteger b = new BigInteger(jtf1.getText()); BigInteger n = new BigInteger(jtf2.getText()); BigInteger m = new BigInteger(jtf3.getText()); BigInteger r1 = Method0.calculateMod(b, n, m); BigInteger r2 = Method0.calculateAbsMinMod(b, n, m); jtf4.setText(r1.toString()); jtf5.setText(r2.toString()); } else { JOptionPane.showMessageDialog(null, "请确认您的输入是否合法!"); } } }); } } //~ Formatted by Jindent --- http://www.jindent.com
728e8e868e2fb082b1e4cc656496008ebab9b253
ca6380749c933725330613fd7239e1f2f53e172d
/src/com/revature/factory/TTTFactory.java
e37d3007821051ae105338161ee452a8b6165eb5
[]
no_license
klinejessica/projectcuatro
cadcc2257adbc0835e7039c782af104b025c42aa
070e52d6d783ef3ef29539393db423830ba0f144
refs/heads/master
2021-01-01T06:22:03.553553
2017-07-17T03:20:56
2017-07-17T03:20:56
97,278,786
0
0
null
null
null
null
UTF-8
Java
false
false
342
java
package com.revature.factory; import com.revature.data.Bracket; import com.revature.data.Round; import com.revature.ttt.match.TTTBracket; import com.revature.ttt.match.TTTRound; public class TTTFactory { public Round getRound(){ return new TTTRound(); } public Bracket getBracket(){ return new TTTBracket(); } }
042ccdb9f001052723138545bd002aa5c26bcec2
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/drjava_cluster/25403/tar_0.java
83fa2e654f5b58f94b77304e030ede94a5cd5072
[]
no_license
martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905613
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
22,367
java
/*BEGIN_COPYRIGHT_BLOCK * * This file is part of DrJava. Download the current version of this project: * http://sourceforge.net/projects/drjava/ or http://www.drjava.org/ * * DrJava Open Source License * * Copyright (C) 2001-2003 JavaPLT group at Rice University ([email protected]) * All rights reserved. * * Developed by: Java Programming Languages Team * Rice University * http://www.cs.rice.edu/~javaplt/ * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal with the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, subject to the following * conditions: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimers. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimers in the * documentation and/or other materials provided with the distribution. * - Neither the names of DrJava, the JavaPLT, Rice University, nor the * names of its contributors may be used to endorse or promote products * derived from this Software without specific prior written permission. * - Products derived from this software may not be called "DrJava" nor * use the term "DrJava" as part of their names without prior written * permission from the JavaPLT group. For permission, write to * [email protected]. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS WITH THE SOFTWARE. * END_COPYRIGHT_BLOCK*/ package edu.rice.cs.drjava.ui; import edu.rice.cs.drjava.model.OpenDefinitionsDocument; import edu.rice.cs.drjava.model.SingleDisplayModel; import edu.rice.cs.drjava.model.compiler.CompilerError; import edu.rice.cs.drjava.model.junit.JUnitError; import edu.rice.cs.drjava.model.junit.JUnitErrorModel; import edu.rice.cs.util.UnexpectedException; import edu.rice.cs.util.swing.BorderlessScrollPane; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.text.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.io.File; import java.util.List; import java.util.ArrayList; import java.util.HashMap; /** * The panel which displays all the testing errors. * In the future, it may also contain a progress bar. * * @version $Id$ */ public class JUnitPanel extends ErrorPanel{ private static final String START_JUNIT_MSG = "Testing in progress. Please wait...\n"; private static final String JUNIT_FINISHED_MSG = "All tests completed successfully.\n"; private static final String NO_TESTS_MSG = ""; private static final SimpleAttributeSet OUT_OF_SYNC_ATTRIBUTES = _getOutOfSyncAttributes(); private static final SimpleAttributeSet _getOutOfSyncAttributes() { SimpleAttributeSet s = new SimpleAttributeSet(); s.addAttribute(StyleConstants.Foreground, Color.red.darker()); s.addAttribute(StyleConstants.Bold, Boolean.TRUE); return s; } private static final SimpleAttributeSet TEST_PASS_ATTRIBUTES = _getTestPassAttributes(); private static final SimpleAttributeSet _getTestPassAttributes() { SimpleAttributeSet s = new SimpleAttributeSet(); s.addAttribute(StyleConstants.Foreground, Color.green.darker()); return s; } private static final SimpleAttributeSet TEST_FAIL_ATTRIBUTES = _getTestFailAttributes(); private static final SimpleAttributeSet _getTestFailAttributes() { SimpleAttributeSet s = new SimpleAttributeSet(); s.addAttribute(StyleConstants.Foreground, Color.red); return s; } private static final String TEST_OUT_OF_SYNC = "The document(s) being tested have been modified and should be recompiled!\n"; protected JUnitErrorListPane _errorListPane; private int _testCount; private boolean _testsSuccessful; private JUnitProgressBar _progressBar; private List<OpenDefinitionsDocument> _odds = new ArrayList<OpenDefinitionsDocument>(); private Action _showStackTraceAction = new AbstractAction("Show Stack Trace") { public void actionPerformed(ActionEvent ae) { if (_error != null) { _displayStackTrace(_error); } } }; private JButton _showStackTraceButton; /** The currently selected error. */ private JUnitError _error = null; private Window _stackFrame = null; private JTextArea _stackTextArea; private final JLabel _errorLabel = new JLabel(); private final JLabel _testLabel = new JLabel(); private final JLabel _fileLabel = new JLabel(); /** * Constructor. * @param model SingleDisplayModel in which we are running * @param frame MainFrame in which we are displayed */ public JUnitPanel(SingleDisplayModel model, MainFrame frame) { super(model, frame, "Test Output", "Test Progress"); _testCount = 0; _testsSuccessful = true; _progressBar = new JUnitProgressBar(); _showStackTraceButton = new JButton(_showStackTraceAction); customPanel.add(_progressBar, BorderLayout.NORTH); customPanel.add(_showStackTraceButton, BorderLayout.SOUTH); _errorListPane = new JUnitErrorListPane(); setErrorListPane(_errorListPane); } /** * Returns the JUnitErrorListPane that this panel manages. */ public JUnitErrorListPane getErrorListPane() { return _errorListPane; } protected JUnitErrorModel getErrorModel(){ return getModel().getJUnitModel().getJUnitErrorModel(); } /** * Updates all document styles with the attributes contained in newSet. * @param newSet Style containing new attributes to use. */ protected void _updateStyles(AttributeSet newSet) { super._updateStyles(newSet); OUT_OF_SYNC_ATTRIBUTES.addAttributes(newSet); StyleConstants.setBold(OUT_OF_SYNC_ATTRIBUTES, true); // should always be bold TEST_PASS_ATTRIBUTES.addAttributes(newSet); TEST_FAIL_ATTRIBUTES.addAttributes(newSet); } /** Called when work begins. */ public void setJUnitInProgress(List<OpenDefinitionsDocument> odds) { _odds = odds; setJUnitInProgress(); } /** called when work begins */ public void setJUnitInProgress() { _errorListPane.setJUnitInProgress(); } /** * Clean up when the tab is closed. */ protected void _close() { super._close(); getModel().getJUnitModel().resetJUnitErrors(); reset(); } /** * Reset the errors to the current error information. */ public void reset() { JUnitErrorModel juem = getModel().getJUnitModel().getJUnitErrorModel(); boolean testsHaveRun = false; if (juem != null) { _numErrors = juem.getNumErrors(); testsHaveRun = juem.haveTestsRun(); } else { _numErrors = 0; } _errorListPane.updateListPane(testsHaveRun); } /** * Resets the progress bar to start counting the given number of tests. */ public synchronized void progressReset(int numTests) { _progressBar.reset(); _progressBar.start(numTests); _testsSuccessful = true; _testCount = 0; } /** * Steps the progress bar forward by one test. * @param successful Whether the last test was successful or not. */ public synchronized void progressStep(boolean successful) { _testCount++; _testsSuccessful &= successful; _progressBar.step(_testCount, _testsSuccessful); } public synchronized void testStarted(String className, String testName) { } private void _displayStackTrace (JUnitError e) { _errorLabel.setText((e.isWarning() ? "Error: " : "Failure: ") + e.message()); _fileLabel.setText("File: "+(new File(e.fileName())).getName()); if (!e.testName().equals("")) { _testLabel.setText("Test: "+e.testName()); } else { _testLabel.setText(""); } _stackTextArea.setText(e.stackTrace()); _stackTextArea.setCaretPosition(0); _stackFrame.setVisible(true); } /** * A pane to show JUnit errors. It acts a bit like a listbox (clicking * selects an item) but items can each wrap, etc. */ public class JUnitErrorListPane extends ErrorPanel.ErrorListPane { private JPopupMenu _popMenu; private String _runningTestName; private boolean _warnedOutOfSync; private static final String JUNIT_WARNING = "junit.framework.TestSuite$1.warning"; /** * Maps any test names in the currently running suite to the position * that they appear in the list pane. */ private final HashMap<String, Position> _runningTestNamePositions; /** * Constructs the JUnitErrorListPane. */ public JUnitErrorListPane() { removeMouseListener(defaultMouseListener); _popMenu = new JPopupMenu(); _popMenu.add(_showStackTraceAction); _error = null; _setupStackTraceFrame(); addMouseListener(new PopupAdapter()); _runningTestName = null; _runningTestNamePositions = new HashMap<String, Position>(); _showStackTraceButton.setEnabled(false); } private String _getTestFromName(String name) { int paren = name.indexOf('('); if ((paren > -1) && (paren < name.length())) { return name.substring(0, paren); } else { throw new IllegalArgumentException("Name does not contain any parens: " + name); } } private String _getClassFromName(String name) { int paren = name.indexOf('('); if ((paren > -1) && (paren < name.length())) { return name.substring(paren + 1, name.length() - 1); } else { throw new IllegalArgumentException("Name does not contain any parens: " + name); } } /** * Provides the ability to display the name of the test being run. */ public synchronized void testStarted(String name) { String testName = _getTestFromName(name); String className = _getClassFromName(name); String fullName = className + "." + testName; if (fullName.equals(JUNIT_WARNING)) { return; } Document doc = getDocument(); int index = doc.getLength(); try { // Insert the classname if it has changed if (!className.equals(_runningTestName)) { _runningTestName = className; doc.insertString(index, " " + className + "\n", NORMAL_ATTRIBUTES); index = doc.getLength(); } // Insert the test name, remembering its position doc.insertString(index, " ", NORMAL_ATTRIBUTES); index = doc.getLength(); doc.insertString(index, testName + "\n", NORMAL_ATTRIBUTES); Position pos = doc.createPosition(index); _runningTestNamePositions.put(fullName, pos); setCaretPosition(index); } catch (BadLocationException ble) { // Inserting at end, shouldn't happen throw new UnexpectedException(ble); } } /** * Provides the ability to display the results of a test that has finished. */ public synchronized void testEnded(String name, boolean wasSuccessful, boolean causedError) { String testName = _getTestFromName(name); String fullName = _getClassFromName(name) + "." + testName; if (fullName.equals(JUNIT_WARNING)) { return; } Document doc = getDocument(); Position namePos = _runningTestNamePositions.get(fullName); AttributeSet set; if (!wasSuccessful || causedError) { set = TEST_FAIL_ATTRIBUTES; } else { set = TEST_PASS_ATTRIBUTES; } if (namePos != null) { int index = namePos.getOffset(); int length = testName.length(); if (doc instanceof StyledDocument) { ((StyledDocument)doc).setCharacterAttributes(index, length, set, false); } } } /** Puts the error pane into "junit in progress" state. */ public synchronized void setJUnitInProgress() { _errorListPositions = new Position[0]; progressReset(0); _runningTestNamePositions.clear(); _runningTestName = null; _warnedOutOfSync = false; DefaultStyledDocument doc = new DefaultStyledDocument(); _checkSync(doc); try { doc.insertString(doc.getLength(), START_JUNIT_MSG, BOLD_ATTRIBUTES); } catch (BadLocationException ble) { throw new UnexpectedException(ble); } setDocument(doc); selectNothing(); } /** * Used to show that testing was unsuccessful. */ protected synchronized void _updateWithErrors() throws BadLocationException { //DefaultStyledDocument doc = new DefaultStyledDocument(); DefaultStyledDocument doc = (DefaultStyledDocument) getDocument(); _checkSync(doc); _updateWithErrors("test", "failed", doc); } protected void _updateWithErrors(String failureName, String failureMeaning, DefaultStyledDocument doc) throws BadLocationException { // Print how many errors _replaceInProgressText(_getNumErrorsMessage(failureName, failureMeaning)); _insertErrors(doc); // Select the first error switchToError(0); } /** * Prints a message for the given error * @param error the error to print * @param doc the document in the error pane * * This code inserts the error text underneath the test name (which should be red) in the * pane. However, the highlighter is dependent on the errors being contiguous and at the * end of the document, so this is disabled pending an overhaul of the highlight manager. * protected void _insertErrorText(CompilerError error, Document doc) throws BadLocationException { // Show file and line number JUnitError err = (JUnitError)error; String test = err.testName(); String name = err.className() + "." + test; int index; Position pos = _runningTestNamePositions.get(name); if (pos != null) { index = pos.getOffset() + test.length() + 1; } else { index = doc.getLength(); } String toInsert = "File: "; doc.insertString(index, toInsert, BOLD_ATTRIBUTES); index += toInsert.length(); toInsert = error.getFileMessage() + " [line: " + error.getLineMessage() + "]\n"; doc.insertString(index, toInsert, NORMAL_ATTRIBUTES); index += toInsert.length(); if (error.isWarning()) { toInsert = _getWarningText(); } else { toInsert = _getErrorText(); } doc.insertString(index, toInsert, BOLD_ATTRIBUTES); index += toInsert.length(); toInsert = error.message() + "\n"; doc.insertString(index, toInsert, NORMAL_ATTRIBUTES); }*/ /** * Replaces the "Testing in progress..." text with the given message. * @param msg the text to insert */ private void _replaceInProgressText(String msg) throws BadLocationException { int start = 0; if (_warnedOutOfSync) { start = TEST_OUT_OF_SYNC.length(); } int len = START_JUNIT_MSG.length(); Document doc = getDocument(); if (doc.getLength() >= len + start) { doc.remove(start, len); doc.insertString(start, msg, BOLD_ATTRIBUTES); } } /** * Returns the string to identify a warning. * In JUnit, warnings (the odd case) indicate errors/exceptions. */ protected String _getWarningText() { return "Error: "; } /** * Returns the string to identify an error. * In JUnit, errors (the normal case) indicate TestFailures. */ protected String _getErrorText() { return "Failure: "; } /** * updates the list pane with no errors. */ protected synchronized void _updateNoErrors(boolean haveTestsRun) throws BadLocationException { //DefaultStyledDocument doc = new DefaultStyledDocument(); _checkSync(getDocument()); _replaceInProgressText(haveTestsRun ? JUNIT_FINISHED_MSG : NO_TESTS_MSG); selectNothing(); setCaretPosition(0); } /** * Checks the document being tested to see if it's in sync. If not, * displays a message in the document in the test output pane. */ private void _checkSync(Document doc) { if (_warnedOutOfSync) { return; } for (int i = 0; i < _odds.size(); i++) { if (!_odds.get(i).checkIfClassFileInSync()) { try { doc.insertString(0, TEST_OUT_OF_SYNC, OUT_OF_SYNC_ATTRIBUTES); _warnedOutOfSync = true; return; } catch (BadLocationException ble) { throw new UnexpectedException(ble); } } } } private void _setupStackTraceFrame() { //DrJava.consoleOut().println("Stack Trace for Error: \n"+ e.stackTrace()); JDialog _dialog = new JDialog(_frame,"JUnit Error Stack Trace",false); _stackFrame = _dialog; _stackTextArea = new JTextArea(); _stackTextArea.setEditable(false); _stackTextArea.setLineWrap(false); JScrollPane scroll = new BorderlessScrollPane(_stackTextArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); ActionListener closeListener = new ActionListener() { public void actionPerformed(ActionEvent e) { _stackFrame.setVisible(false); } }; JButton closeButton = new JButton("Close"); closeButton.addActionListener(closeListener); JPanel closePanel = new JPanel(new BorderLayout()); closePanel.setBorder(new EmptyBorder(5,5,0,0)); closePanel.add(closeButton, BorderLayout.EAST); JPanel cp = new JPanel(new BorderLayout()); _dialog.setContentPane(cp); cp.setBorder(new EmptyBorder(5,5,5,5)); cp.add(scroll, BorderLayout.CENTER); cp.add(closePanel, BorderLayout.SOUTH); JPanel topPanel = new JPanel(new GridLayout(0,1,0,5)); topPanel.setBorder(new EmptyBorder(0,0,5,0)); topPanel.add(_fileLabel); topPanel.add(_testLabel); topPanel.add(_errorLabel); cp.add(topPanel, BorderLayout.NORTH); _dialog.setSize(600, 500); // initial location is relative to parent (MainFrame) _dialog.setLocationRelativeTo(_frame); } /** * Overrides selectItem in ErrorListPane to update the current _error selected * and enabling the _showStackTraceButton. */ public void selectItem(CompilerError error) { super.selectItem(error); _error = (JUnitError)error; _showStackTraceButton.setEnabled(true); } /** * Overrides _removeListHighlight in ErrorListPane to disable the _showStackTraceButton. */ protected void _removeListHighlight() { super._removeListHighlight(); _showStackTraceButton.setEnabled(false); } /** * Updates the UI to a new look and feel. * Need to update the contained popup menu as well. * * Currently, we don't support changing the look and feel * on the fly, so this is disabled. * public void updateUI() { super.updateUI(); if (_popMenu != null) { SwingUtilities.updateComponentTreeUI(_popMenu); } }*/ private class PopupAdapter extends RightClickMouseAdapter { /** * Show popup if the click is on an error. * @param e the MouseEvent correponding to this click */ public void mousePressed(MouseEvent e) { if (_selectError(e)) { super.mousePressed(e); } } /** * Show popup if the click is on an error. * @param e the MouseEvent correponding to this click */ public void mouseReleased(MouseEvent e) { if (_selectError(e)) { super.mouseReleased(e); } } /** * Select the error at the given mouse event. * @param e the MouseEvent correponding to this click * @return true iff the mouse click is over an error */ private boolean _selectError(MouseEvent e) { //TODO: get rid of cast in the next line, if possible _error = (JUnitError)_errorAtPoint(e.getPoint()); if (_isEmptySelection() && _error != null) { _errorListPane.switchToError(_error); return true; } else { selectNothing(); return false; } } /** * Shows the popup menu for this mouse adapter. * @param e the MouseEvent correponding to this click */ protected void _popupAction(MouseEvent e) { _popMenu.show(e.getComponent(), e.getX(), e.getY()); } // public JUnitError getError() { // return _error; // } } } /** * A progress bar showing the status of JUnit tests. * Green until a test fails, then red. * Adapted from JUnit code. */ static class JUnitProgressBar extends JProgressBar { private boolean _hasError = false; public JUnitProgressBar() { super(); setForeground(getStatusColor()); } private Color getStatusColor() { if (_hasError) { return Color.red; } else { return Color.green; } } public void reset() { _hasError = false; setForeground(getStatusColor()); setValue(0); } public void start(int total) { setMaximum(total); reset(); } public void step(int value, boolean successful) { setValue(value); if (!_hasError && !successful) { _hasError= true; setForeground(getStatusColor()); } } } }
cb647d12006df17e7839529a733f58f83148d0ff
63f4635a8fc780872b678749724f122a310d5e13
/makefree/src/com/makefree/action/PwUpdateAction.java
4eae5636e6b2c280ca7b0dc78e82a9a7d8d1299d
[]
no_license
elquineas/makefree
c3652bb49485db528ff65b365a66058aa19a788a
b0b0e796ae887750d425916e6134a4857e91bddf
refs/heads/master
2020-05-20T03:13:07.737994
2019-06-03T08:21:51
2019-06-03T08:21:51
185,352,896
0
0
null
null
null
null
UTF-8
Java
false
false
719
java
package com.makefree.action; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class PwUpdateAction implements Action{ @Override public ActionForward excute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = "member/pwupdate.jsp"; HttpSession session = request.getSession(); if(session.getAttribute("loginUser") == null) { url = "index.makefree"; } ActionForward forward = new ActionForward(); forward.setPath(url); forward.setRedirect(false); return forward; } }
228ff0de090da958e0b494e9e11474fce3b1ee05
6d023fb3ac87321ed9aa916b36aab4a0ad61f990
/src/me/gl1tchcraft/core/commands/HealCommand.java
acc5048ca690d4225eae93706ff725dbd99da2ad
[]
no_license
ABravePanda/Gl1tchCraftCore
ccd3d09b7dfa34cfb5bb539daf5005273853428f
eafd9ab6a5608e04ff0275556b837ae68e082e90
refs/heads/master
2021-05-05T11:30:55.318605
2018-01-20T03:33:33
2018-01-20T03:33:33
118,204,949
0
0
null
null
null
null
UTF-8
Java
false
false
1,762
java
package me.gl1tchcraft.core.commands; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import me.gl1tchcraft.api.messages.GCMessagesAPI; import net.md_5.bungee.api.ChatColor; public class HealCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command cmd, String s, String[] args) { if (sender instanceof Player) { Player p = (Player) sender; if(cmd.getName().equalsIgnoreCase("heal")) { if(args.length == 0) { if(p.hasPermission("heal.core.gl1tchcraft")) { p.setHealth(20); p.setFoodLevel(20); p.sendMessage(ChatColor.GRAY + "You have been healed."); } else { p.sendMessage(GCMessagesAPI.noPermission);; } } if(args.length == 1) { if(p.hasPermission("healother.core.gl1tchcraft")) { Player target = Bukkit.getPlayer(args[0]); if(target != null) { target.setHealth(20); target.setFoodLevel(20); target.sendMessage(ChatColor.GRAY + "You have been healed."); p.sendMessage(ChatColor.GREEN + target.getName() + ChatColor.GRAY + " has been healed"); } else { p.sendMessage(ChatColor.RED + "Can't find " + args[0]); } } else { p.sendMessage(GCMessagesAPI.noPermission);; } } } } return true; } }
4d7416796ca19c758749fb8bf0fadb4a6c7ffe76
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/stanfordnlp--CoreNLP/5de590e4455531195b10f290baad3fdc8b9f3d91/before/DVModel.java
c4cfd05d412261d10b35dbec182704dc77448ea0
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
40,172
java
package edu.stanford.nlp.parser.dvparser; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.IOException; import java.io.PrintStream; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.regex.Pattern; import org.ejml.simple.*; import org.ejml.data.DenseMatrix64F; import edu.stanford.nlp.io.IOUtils; import edu.stanford.nlp.parser.lexparser.BinaryGrammar; import edu.stanford.nlp.parser.lexparser.BinaryRule; import edu.stanford.nlp.parser.lexparser.Options; import edu.stanford.nlp.parser.lexparser.UnaryGrammar; import edu.stanford.nlp.parser.lexparser.UnaryRule; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.util.ErasureUtils; import edu.stanford.nlp.util.Function; import edu.stanford.nlp.util.Generics; import edu.stanford.nlp.util.Index; import edu.stanford.nlp.util.Maps; import edu.stanford.nlp.util.Pair; import edu.stanford.nlp.util.TwoDimensionalMap; import edu.stanford.nlp.util.TwoDimensionalSet; public class DVModel implements Serializable { // The following data structures are all transient because the // SimpleMatrix object is not Serializable. We read and write them // in specialized readObject and writeObject calls. // Maps from basic category to the matrix transformation matrices for // binary nodes and unary nodes. // The indices are the children categories. For binaryTransform, for // example, we have a matrix for each type of child that appears. public transient TwoDimensionalMap<String, String, SimpleMatrix> binaryTransform; public transient Map<String, SimpleMatrix> unaryTransform; // score matrices for each node type public transient TwoDimensionalMap<String, String, SimpleMatrix> binaryScore; public transient Map<String, SimpleMatrix> unaryScore; public transient Map<String, SimpleMatrix> wordVectors; // cache these for easy calculation of "theta" parameter size int numBinaryMatrices, numUnaryMatrices; int binaryTransformSize, unaryTransformSize; int binaryScoreSize, unaryScoreSize; Options op; final int numCols; final int numRows; // we just keep this here for convenience transient SimpleMatrix identity; // the seed we used to use was 19580427 Random rand; static final String UNKNOWN_WORD = "*UNK*"; static final String UNKNOWN_NUMBER = "*NUM*"; static final String UNKNOWN_CAPS = "*CAPS*"; static final String UNKNOWN_CHINESE_YEAR = "*ZH_YEAR*"; static final String UNKNOWN_CHINESE_NUMBER = "*ZH_NUM*"; static final String UNKNOWN_CHINESE_PERCENT = "*ZH_PERCENT*"; static final String START_WORD = "*START*"; static final String END_WORD = "*END*"; static final boolean TRAIN_WORD_VECTORS = true; private static final Function<SimpleMatrix, DenseMatrix64F> convertSimpleMatrix = new Function<SimpleMatrix, DenseMatrix64F>() { @Override public DenseMatrix64F apply(SimpleMatrix matrix) { return matrix.getMatrix(); } }; private static final Function<DenseMatrix64F, SimpleMatrix> convertDenseMatrix = new Function<DenseMatrix64F, SimpleMatrix>() { @Override public SimpleMatrix apply(DenseMatrix64F matrix) { return SimpleMatrix.wrap(matrix); } }; private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); TwoDimensionalMap<String, String, DenseMatrix64F> binaryT = ErasureUtils.uncheckedCast(in.readObject()); binaryTransform = TwoDimensionalMap.treeMap(); binaryTransform.addAll(binaryT, convertDenseMatrix); Map<String, DenseMatrix64F> unaryT = ErasureUtils.uncheckedCast(in.readObject()); unaryTransform = Generics.newTreeMap(); Maps.addAll(unaryTransform, unaryT, convertDenseMatrix); TwoDimensionalMap<String, String, DenseMatrix64F> binaryS = ErasureUtils.uncheckedCast(in.readObject()); binaryScore = TwoDimensionalMap.treeMap(); binaryScore.addAll(binaryS, convertDenseMatrix); Map<String, DenseMatrix64F> unaryS = ErasureUtils.uncheckedCast(in.readObject()); unaryScore = Generics.newTreeMap(); Maps.addAll(unaryScore, unaryS, convertDenseMatrix); Map<String, DenseMatrix64F> wordV = ErasureUtils.uncheckedCast(in.readObject()); wordVectors = Generics.newTreeMap(); Maps.addAll(wordVectors, wordV, convertDenseMatrix); identity = SimpleMatrix.identity(numRows); } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); TwoDimensionalMap<String, String, DenseMatrix64F> binaryT = TwoDimensionalMap.treeMap(); binaryT.addAll(binaryTransform, convertSimpleMatrix); out.writeObject(binaryT); Map<String, DenseMatrix64F> unaryT = Generics.newTreeMap(); Maps.addAll(unaryT, unaryTransform, convertSimpleMatrix); out.writeObject(unaryT); TwoDimensionalMap<String, String, DenseMatrix64F> binaryS = TwoDimensionalMap.treeMap(); binaryS.addAll(binaryScore, convertSimpleMatrix); out.writeObject(binaryS); Map<String, DenseMatrix64F> unaryS = Generics.newTreeMap(); Maps.addAll(unaryS, unaryScore, convertSimpleMatrix); out.writeObject(unaryS); Map<String, DenseMatrix64F> wordV = Generics.newHashMap(); Maps.addAll(wordV, wordVectors, convertSimpleMatrix); out.writeObject(wordV); } /** * @param op the parameters of the parser */ public DVModel(Options op, Index<String> stateIndex, UnaryGrammar unaryGrammar, BinaryGrammar binaryGrammar) { this.op = op; rand = new Random(op.trainOptions.dvSeed); readWordVectors(); // Binary matrices will be n*2n+1, unary matrices will be n*n+1 numRows = op.lexOptions.numHid; numCols = op.lexOptions.numHid; // Build one matrix for each basic category. // We assume that each state that has the same basic // category is using the same transformation matrix. // Use TreeMap for because we want values to be // sorted by key later on when building theta vectors binaryTransform = TwoDimensionalMap.treeMap(); unaryTransform = Generics.newTreeMap(); binaryScore = TwoDimensionalMap.treeMap(); unaryScore = Generics.newTreeMap(); numBinaryMatrices = 0; numUnaryMatrices = 0; binaryTransformSize = numRows * (numCols * 2 + 1); unaryTransformSize = numRows * (numCols + 1); binaryScoreSize = numCols; unaryScoreSize = numCols; if (op.trainOptions.useContextWords) { binaryTransformSize += numRows * numCols * 2; unaryTransformSize += numRows * numCols * 2; } identity = SimpleMatrix.identity(numRows); for (UnaryRule unaryRule : unaryGrammar) { // only make one matrix for each parent state, and only use the // basic category for that String childState = stateIndex.get(unaryRule.child); String childBasic = basicCategory(childState); addRandomUnaryMatrix(childBasic); } for (BinaryRule binaryRule : binaryGrammar) { // only make one matrix for each parent state, and only use the // basic category for that String leftState = stateIndex.get(binaryRule.leftChild); String leftBasic = basicCategory(leftState); String rightState = stateIndex.get(binaryRule.rightChild); String rightBasic = basicCategory(rightState); addRandomBinaryMatrix(leftBasic, rightBasic); } } public DVModel(TwoDimensionalMap<String, String, SimpleMatrix> binaryTransform, Map<String, SimpleMatrix> unaryTransform, TwoDimensionalMap<String, String, SimpleMatrix> binaryScore, Map<String, SimpleMatrix> unaryScore, Map<String, SimpleMatrix> wordVectors, Options op) { this.op = op; this.binaryTransform = binaryTransform; this.unaryTransform = unaryTransform; this.binaryScore = binaryScore; this.unaryScore = unaryScore; this.wordVectors = wordVectors; this.numBinaryMatrices = binaryTransform.size(); this.numUnaryMatrices = unaryTransform.size(); if (numBinaryMatrices > 0) { this.binaryTransformSize = binaryTransform.iterator().next().getValue().getNumElements(); this.binaryScoreSize = binaryScore.iterator().next().getValue().getNumElements(); } else { this.binaryTransformSize = 0; this.binaryScoreSize = 0; } if (numUnaryMatrices > 0) { this.unaryTransformSize = unaryTransform.values().iterator().next().getNumElements(); this.unaryScoreSize = unaryScore.values().iterator().next().getNumElements(); } else { this.unaryTransformSize = 0; this.unaryScoreSize = 0; } this.numRows = op.lexOptions.numHid; this.numCols = op.lexOptions.numHid; this.identity = SimpleMatrix.identity(numRows); this.rand = new Random(op.trainOptions.dvSeed); } /** * Creates a random context matrix. This will be numRows x * 2*numCols big. These can be appended to the end of either a * unary or binary transform matrix to get the transform matrix * which uses context words. */ private SimpleMatrix randomContextMatrix() { SimpleMatrix matrix = new SimpleMatrix(numRows, numCols * 2); matrix.insertIntoThis(0, 0, identity.scale(op.trainOptions.scalingForInit * 0.1)); matrix.insertIntoThis(0, numCols, identity.scale(op.trainOptions.scalingForInit * 0.1)); matrix = matrix.plus(SimpleMatrix.random(numRows,numCols * 2,-1.0/Math.sqrt((double)numCols * 100.0),1.0/Math.sqrt((double)numCols * 100.0),rand)); return matrix; } /** * Create a random transform matrix based on the initialization * parameters. This will be numRows x numCols big. These can be * plugged into either unary or binary transform matrices. */ private SimpleMatrix randomTransformMatrix() { SimpleMatrix matrix; switch (op.trainOptions.transformMatrixType) { case DIAGONAL: matrix = SimpleMatrix.random(numRows,numCols,-1.0/Math.sqrt((double)numCols * 100.0),1.0/Math.sqrt((double)numCols * 100.0),rand).plus(identity); break; case RANDOM: matrix = SimpleMatrix.random(numRows,numCols,-1.0/Math.sqrt((double)numCols),1.0/Math.sqrt((double)numCols),rand); break; case OFF_DIAGONAL: matrix = SimpleMatrix.random(numRows,numCols,-1.0/Math.sqrt((double)numCols * 100.0),1.0/Math.sqrt((double)numCols * 100.0),rand).plus(identity); for (int i = 0; i < numCols; ++i) { int x = rand.nextInt(numCols); int y = rand.nextInt(numCols); int scale = rand.nextInt(3) - 1; // -1, 0, or 1 matrix.set(x, y, matrix.get(x, y) + scale); } break; case RANDOM_ZEROS: matrix = SimpleMatrix.random(numRows,numCols,-1.0/Math.sqrt((double)numCols * 100.0),1.0/Math.sqrt((double)numCols * 100.0),rand).plus(identity); for (int i = 0; i < numCols; ++i) { int x = rand.nextInt(numCols); int y = rand.nextInt(numCols); matrix.set(x, y, 0.0); } break; default: throw new IllegalArgumentException("Unexpected matrix initialization type " + op.trainOptions.transformMatrixType); } return matrix; } public void addRandomUnaryMatrix(String childBasic) { if (unaryTransform.get(childBasic) != null) { return; } ++numUnaryMatrices; // scoring matrix SimpleMatrix score = SimpleMatrix.random(1, numCols, -1.0/Math.sqrt((double)numCols),1.0/Math.sqrt((double)numCols),rand); unaryScore.put(childBasic, score.scale(op.trainOptions.scalingForInit)); SimpleMatrix transform; if (op.trainOptions.useContextWords) { transform = new SimpleMatrix(numRows, numCols * 3 + 1); // leave room for bias term transform.insertIntoThis(0,numCols + 1, randomContextMatrix()); } else { transform = new SimpleMatrix(numRows, numCols + 1); } SimpleMatrix unary = randomTransformMatrix(); transform.insertIntoThis(0, 0, unary); unaryTransform.put(childBasic, transform.scale(op.trainOptions.scalingForInit)); } public void addRandomBinaryMatrix(String leftBasic, String rightBasic) { if (binaryTransform.get(leftBasic, rightBasic) != null) { return; } ++numBinaryMatrices; // scoring matrix SimpleMatrix score = SimpleMatrix.random(1, numCols, -1.0/Math.sqrt((double)numCols),1.0/Math.sqrt((double)numCols),rand); binaryScore.put(leftBasic, rightBasic, score.scale(op.trainOptions.scalingForInit)); SimpleMatrix binary; if (op.trainOptions.useContextWords) { binary = new SimpleMatrix(numRows, numCols * 4 + 1); // leave room for bias term binary.insertIntoThis(0,numCols*2+1, randomContextMatrix()); } else { binary = new SimpleMatrix(numRows, numCols * 2 + 1); } SimpleMatrix left = randomTransformMatrix(); SimpleMatrix right = randomTransformMatrix(); binary.insertIntoThis(0, 0, left); binary.insertIntoThis(0, numCols, right); binaryTransform.put(leftBasic, rightBasic, binary.scale(op.trainOptions.scalingForInit)); } public void setRulesForTrainingSet(List<Tree> sentences, Map<Tree, byte[]> compressedTrees) { TwoDimensionalSet<String, String> binaryRules = TwoDimensionalSet.treeSet(); Set<String> unaryRules = new HashSet<String>(); Set<String> words = new HashSet<String>(); for (Tree sentence : sentences) { searchRulesForBatch(binaryRules, unaryRules, words, sentence); for (Tree hypothesis : CacheParseHypotheses.convertToTrees(compressedTrees.get(sentence))) { searchRulesForBatch(binaryRules, unaryRules, words, hypothesis); } } for (Pair<String, String> binary : binaryRules) { addRandomBinaryMatrix(binary.first, binary.second); } for (String unary : unaryRules) { addRandomUnaryMatrix(unary); } filterRulesForBatch(binaryRules, unaryRules, words); } /** * Filters the transform and score rules so that we only have the * ones which appear in the trees given */ public void filterRulesForBatch(Collection<Tree> trees) { TwoDimensionalSet<String, String> binaryRules = TwoDimensionalSet.treeSet(); Set<String> unaryRules = new HashSet<String>(); Set<String> words = new HashSet<String>(); for (Tree tree : trees) { searchRulesForBatch(binaryRules, unaryRules, words, tree); } filterRulesForBatch(binaryRules, unaryRules, words); } public void filterRulesForBatch(Map<Tree, byte[]> compressedTrees) { TwoDimensionalSet<String, String> binaryRules = TwoDimensionalSet.treeSet(); Set<String> unaryRules = new HashSet<String>(); Set<String> words = new HashSet<String>(); for (Map.Entry<Tree, byte[]> entry : compressedTrees.entrySet()) { searchRulesForBatch(binaryRules, unaryRules, words, entry.getKey()); for (Tree hypothesis : CacheParseHypotheses.convertToTrees(entry.getValue())) { searchRulesForBatch(binaryRules, unaryRules, words, hypothesis); } } filterRulesForBatch(binaryRules, unaryRules, words); } public void filterRulesForBatch(TwoDimensionalSet<String, String> binaryRules, Set<String> unaryRules, Set<String> words) { TwoDimensionalMap<String, String, SimpleMatrix> newBinaryTransforms = TwoDimensionalMap.treeMap(); TwoDimensionalMap<String, String, SimpleMatrix> newBinaryScores = TwoDimensionalMap.treeMap(); for (Pair<String, String> binaryRule : binaryRules) { SimpleMatrix transform = binaryTransform.get(binaryRule.first(), binaryRule.second()); if (transform != null) { newBinaryTransforms.put(binaryRule.first(), binaryRule.second(), transform); } SimpleMatrix score = binaryScore.get(binaryRule.first(), binaryRule.second()); if (score != null) { newBinaryScores.put(binaryRule.first(), binaryRule.second(), score); } if ((transform == null && score != null) || (transform != null && score == null)) { throw new AssertionError(); } } binaryTransform = newBinaryTransforms; binaryScore = newBinaryScores; numBinaryMatrices = binaryTransform.size(); Map<String, SimpleMatrix> newUnaryTransforms = Generics.newTreeMap(); Map<String, SimpleMatrix> newUnaryScores = Generics.newTreeMap(); for (String unaryRule : unaryRules) { SimpleMatrix transform = unaryTransform.get(unaryRule); if (transform != null) { newUnaryTransforms.put(unaryRule, transform); } SimpleMatrix score = unaryScore.get(unaryRule); if (score != null) { newUnaryScores.put(unaryRule, score); } if ((transform == null && score != null) || (transform != null && score == null)) { throw new AssertionError(); } } unaryTransform = newUnaryTransforms; unaryScore = newUnaryScores; numUnaryMatrices = unaryTransform.size(); Map<String, SimpleMatrix> newWordVectors = Generics.newTreeMap(); for (String word : words) { SimpleMatrix wordVector = wordVectors.get(word); if (wordVector != null) { newWordVectors.put(word, wordVector); } } wordVectors = newWordVectors; } private void searchRulesForBatch(TwoDimensionalSet<String, String> binaryRules, Set<String> unaryRules, Set<String> words, Tree tree) { if (tree.isLeaf()) { return; } if (tree.isPreTerminal()) { words.add(getVocabWord(tree.children()[0].value())); return; } Tree[] children = tree.children(); if (children.length == 1) { unaryRules.add(basicCategory(children[0].value())); searchRulesForBatch(binaryRules, unaryRules, words, children[0]); } else if (children.length == 2) { binaryRules.add(basicCategory(children[0].value()), basicCategory(children[1].value())); searchRulesForBatch(binaryRules, unaryRules, words, children[0]); searchRulesForBatch(binaryRules, unaryRules, words, children[1]); } else { throw new AssertionError("Expected a binarized tree"); } } public String basicCategory(String category) { if (op.trainOptions.dvSimplifiedModel) { return ""; } else { String basic = op.langpack().basicCategory(category); // TODO: if we can figure out what is going on with the grammar // compaction, perhaps we don't want this any more if (basic.length() > 0 && basic.charAt(0) == '@') { basic = basic.substring(1); } return basic; } } static final Pattern NUMBER_PATTERN = Pattern.compile("-?[0-9][-0-9,.:]*"); static final Pattern CAPS_PATTERN = Pattern.compile("[a-zA-Z]*[A-Z][a-zA-Z]*"); static final Pattern CHINESE_YEAR_PATTERN = Pattern.compile("[〇零一二三四五六七八九0123456789]{4}+年"); static final Pattern CHINESE_NUMBER_PATTERN = Pattern.compile("(?:[〇0零一二三四五六七八九0123456789十百万千亿]+[点多]?)+"); static final Pattern CHINESE_PERCENT_PATTERN = Pattern.compile("百分之[〇0零一二三四五六七八九0123456789十点]+"); /** * Some word vectors are trained with DG representing number. * We mix all of those into the unknown number vectors. */ static final Pattern DG_PATTERN = Pattern.compile(".*DG.*"); public void readWordVectors() { SimpleMatrix unknownNumberVector = null; SimpleMatrix unknownCapsVector = null; SimpleMatrix unknownChineseYearVector = null; SimpleMatrix unknownChineseNumberVector = null; SimpleMatrix unknownChinesePercentVector = null; wordVectors = Generics.newTreeMap(); int numberCount = 0; int capsCount = 0; int chineseYearCount = 0; int chineseNumberCount = 0; int chinesePercentCount = 0; System.err.println("Reading in the word vector file: " + op.lexOptions.wordVectorFile); int dimOfWords = 0; boolean warned = false; for (String line : IOUtils.readLines(op.lexOptions.wordVectorFile, "utf-8")) { String[] lineSplit = line.split("\\s+"); String word = lineSplit[0]; if (op.wordFunction != null) { word = op.wordFunction.apply(word); } dimOfWords = lineSplit.length - 1; if (op.lexOptions.numHid <= 0) { op.lexOptions.numHid = dimOfWords; System.err.println("Dimensionality of numHid not set. The length of the word vectors in the given file appears to be " + dimOfWords); } // the first entry is the word itself // the other entries will all be entries in the word vector if (dimOfWords > op.lexOptions.numHid) { if (!warned) { warned = true; System.err.println("WARNING: Dimensionality of numHid parameter and word vectors do not match, deleting word vector dimensions to fit!"); } dimOfWords = op.lexOptions.numHid; } else if (dimOfWords < op.lexOptions.numHid) { throw new RuntimeException("Word vectors file has dimension too small for requested numHid of " + op.lexOptions.numHid); } double vec[][] = new double[dimOfWords][1]; for (int i = 1; i <= dimOfWords; i++) { vec[i-1][0] = Double.parseDouble(lineSplit[i]); } SimpleMatrix vector = new SimpleMatrix(vec); wordVectors.put(word, vector); // TODO: factor out all of these identical blobs if (op.trainOptions.unknownNumberVector && (NUMBER_PATTERN.matcher(word).matches() || DG_PATTERN.matcher(word).matches())) { ++numberCount; if (unknownNumberVector == null) { unknownNumberVector = new SimpleMatrix(vector); } else { unknownNumberVector = unknownNumberVector.plus(vector); } } if (op.trainOptions.unknownCapsVector && CAPS_PATTERN.matcher(word).matches()) { ++capsCount; if (unknownCapsVector == null) { unknownCapsVector = new SimpleMatrix(vector); } else { unknownCapsVector = unknownCapsVector.plus(vector); } } if (op.trainOptions.unknownChineseYearVector && CHINESE_YEAR_PATTERN.matcher(word).matches()) { ++chineseYearCount; if (unknownChineseYearVector == null) { unknownChineseYearVector = new SimpleMatrix(vector); } else { unknownChineseYearVector = unknownChineseYearVector.plus(vector); } } if (op.trainOptions.unknownChineseNumberVector && (CHINESE_NUMBER_PATTERN.matcher(word).matches() || DG_PATTERN.matcher(word).matches())) { ++chineseNumberCount; if (unknownChineseNumberVector == null) { unknownChineseNumberVector = new SimpleMatrix(vector); } else { unknownChineseNumberVector = unknownChineseNumberVector.plus(vector); } } if (op.trainOptions.unknownChinesePercentVector && CHINESE_PERCENT_PATTERN.matcher(word).matches()) { ++chinesePercentCount; if (unknownChinesePercentVector == null) { unknownChinesePercentVector = new SimpleMatrix(vector); } else { unknownChinesePercentVector = unknownChinesePercentVector.plus(vector); } } } String unkWord = op.trainOptions.unkWord; if (op.wordFunction != null) { unkWord = op.wordFunction.apply(unkWord); } SimpleMatrix unknownWordVector = wordVectors.get(unkWord); wordVectors.put(UNKNOWN_WORD, unknownWordVector); if (unknownWordVector == null) { throw new RuntimeException("Unknown word vector not specified in the word vector file"); } if (op.trainOptions.unknownNumberVector) { if (numberCount > 0) { unknownNumberVector = unknownNumberVector.divide(numberCount); } else { unknownNumberVector = new SimpleMatrix(unknownWordVector); } wordVectors.put(UNKNOWN_NUMBER, unknownNumberVector); } if (op.trainOptions.unknownCapsVector) { if (capsCount > 0) { unknownCapsVector = unknownCapsVector.divide(capsCount); } else { unknownCapsVector = new SimpleMatrix(unknownWordVector); } wordVectors.put(UNKNOWN_CAPS, unknownCapsVector); } if (op.trainOptions.unknownChineseYearVector) { System.err.println("Matched " + chineseYearCount + " chinese year vectors"); if (chineseYearCount > 0) { unknownChineseYearVector = unknownChineseYearVector.divide(chineseYearCount); } else { unknownChineseYearVector = new SimpleMatrix(unknownWordVector); } wordVectors.put(UNKNOWN_CHINESE_YEAR, unknownChineseYearVector); } if (op.trainOptions.unknownChineseNumberVector) { System.err.println("Matched " + chineseNumberCount + " chinese number vectors"); if (chineseNumberCount > 0) { unknownChineseNumberVector = unknownChineseNumberVector.divide(chineseNumberCount); } else { unknownChineseNumberVector = new SimpleMatrix(unknownWordVector); } wordVectors.put(UNKNOWN_CHINESE_NUMBER, unknownChineseNumberVector); } if (op.trainOptions.unknownChinesePercentVector) { System.err.println("Matched " + chinesePercentCount + " chinese percent vectors"); if (chinesePercentCount > 0) { unknownChinesePercentVector = unknownChinesePercentVector.divide(chinesePercentCount); } else { unknownChinesePercentVector = new SimpleMatrix(unknownWordVector); } wordVectors.put(UNKNOWN_CHINESE_PERCENT, unknownChinesePercentVector); } if (op.trainOptions.useContextWords) { SimpleMatrix start = SimpleMatrix.random(op.lexOptions.numHid, 1, -0.5, 0.5, rand); SimpleMatrix end = SimpleMatrix.random(op.lexOptions.numHid, 1, -0.5, 0.5, rand); wordVectors.put(START_WORD, start); wordVectors.put(END_WORD, end); } } public int totalParamSize() { int totalSize = 0; totalSize += numBinaryMatrices * (binaryTransformSize + binaryScoreSize); totalSize += numUnaryMatrices * (unaryTransformSize + unaryScoreSize); if (TRAIN_WORD_VECTORS) { totalSize += wordVectors.size() * op.lexOptions.numHid; } return totalSize; } public static double[] paramsToVector(double scale, int totalSize, Iterator<SimpleMatrix> ... matrices) { double[] theta = new double[totalSize]; int index = 0; for (Iterator<SimpleMatrix> matrixIterator : matrices) { while (matrixIterator.hasNext()) { SimpleMatrix matrix = matrixIterator.next(); int numElements = matrix.getNumElements(); for (int i = 0; i < numElements; ++i) { theta[index] = matrix.get(i) * scale; ++index; } } } if (index != totalSize) { throw new AssertionError("Did not entirely fill the theta vector: expected " + totalSize + " used " + index); } return theta; } public static double[] paramsToVector(int totalSize, Iterator<SimpleMatrix> ... matrices) { double[] theta = new double[totalSize]; int index = 0; for (Iterator<SimpleMatrix> matrixIterator : matrices) { while (matrixIterator.hasNext()) { SimpleMatrix matrix = matrixIterator.next(); int numElements = matrix.getNumElements(); //System.out.println(Integer.toString(numElements)); // to know what matrices are for (int i = 0; i < numElements; ++i) { theta[index] = matrix.get(i); ++index; } } } if (index != totalSize) { throw new AssertionError("Did not entirely fill the theta vector: expected " + totalSize + " used " + index); } return theta; } @SuppressWarnings("unchecked") public double[] paramsToVector(double scale) { int totalSize = totalParamSize(); if (TRAIN_WORD_VECTORS) { return paramsToVector(scale, totalSize, binaryTransform.valueIterator(), unaryTransform.values().iterator(), binaryScore.valueIterator(), unaryScore.values().iterator(), wordVectors.values().iterator()); } else { return paramsToVector(scale, totalSize, binaryTransform.valueIterator(), unaryTransform.values().iterator(), binaryScore.valueIterator(), unaryScore.values().iterator()); } } @SuppressWarnings("unchecked") public double[] paramsToVector() { int totalSize = totalParamSize(); if (TRAIN_WORD_VECTORS) { return paramsToVector(totalSize, binaryTransform.valueIterator(), unaryTransform.values().iterator(), binaryScore.valueIterator(), unaryScore.values().iterator(), wordVectors.values().iterator()); } else { return paramsToVector(totalSize, binaryTransform.valueIterator(), unaryTransform.values().iterator(), binaryScore.valueIterator(), unaryScore.values().iterator()); } } public static void vectorToParams(double[] theta, Iterator<SimpleMatrix> ... matrices) { int index = 0; for (Iterator<SimpleMatrix> matrixIterator : matrices) { while (matrixIterator.hasNext()) { SimpleMatrix matrix = matrixIterator.next(); int numElements = matrix.getNumElements(); for (int i = 0; i < numElements; ++i) { matrix.set(i, theta[index]); ++index; } } } if (index != theta.length) { throw new AssertionError("Did not entirely use the theta vector"); } } @SuppressWarnings("unchecked") public void vectorToParams(double[] theta) { if (TRAIN_WORD_VECTORS) { vectorToParams(theta, binaryTransform.valueIterator(), unaryTransform.values().iterator(), binaryScore.valueIterator(), unaryScore.values().iterator(), wordVectors.values().iterator()); } else { vectorToParams(theta, binaryTransform.valueIterator(), unaryTransform.values().iterator(), binaryScore.valueIterator(), unaryScore.values().iterator()); } } public SimpleMatrix getWForNode(Tree node) { if (node.children().length == 1) { String childLabel = node.children()[0].value(); String childBasic = basicCategory(childLabel); return unaryTransform.get(childBasic); } else if (node.children().length == 2) { String leftLabel = node.children()[0].value(); String leftBasic = basicCategory(leftLabel); String rightLabel = node.children()[1].value(); String rightBasic = basicCategory(rightLabel); return binaryTransform.get(leftBasic, rightBasic); } throw new AssertionError("Should only have unary or binary nodes"); } public SimpleMatrix getScoreWForNode(Tree node) { if (node.children().length == 1) { String childLabel = node.children()[0].value(); String childBasic = basicCategory(childLabel); return unaryScore.get(childBasic); } else if (node.children().length == 2) { String leftLabel = node.children()[0].value(); String leftBasic = basicCategory(leftLabel); String rightLabel = node.children()[1].value(); String rightBasic = basicCategory(rightLabel); return binaryScore.get(leftBasic, rightBasic); } throw new AssertionError("Should only have unary or binary nodes"); } public SimpleMatrix getStartWordVector() { return wordVectors.get(START_WORD); } public SimpleMatrix getEndWordVector() { return wordVectors.get(END_WORD); } public SimpleMatrix getWordVector(String word) { return wordVectors.get(getVocabWord(word)); } public String getVocabWord(String word) { if (op.wordFunction != null) { word = op.wordFunction.apply(word); } if (op.trainOptions.lowercaseWordVectors) { word = word.toLowerCase(); } if (wordVectors.containsKey(word)) { return word; } //System.err.println("Unknown word: [" + word + "]"); if (op.trainOptions.unknownNumberVector && NUMBER_PATTERN.matcher(word).matches()) { return UNKNOWN_NUMBER; } if (op.trainOptions.unknownCapsVector && CAPS_PATTERN.matcher(word).matches()) { return UNKNOWN_CAPS; } if (op.trainOptions.unknownChineseYearVector && CHINESE_YEAR_PATTERN.matcher(word).matches()) { return UNKNOWN_CHINESE_YEAR; } if (op.trainOptions.unknownChineseNumberVector && CHINESE_NUMBER_PATTERN.matcher(word).matches()) { return UNKNOWN_CHINESE_NUMBER; } if (op.trainOptions.unknownChinesePercentVector && CHINESE_PERCENT_PATTERN.matcher(word).matches()) { return UNKNOWN_CHINESE_PERCENT; } if (op.trainOptions.unknownDashedWordVectors) { int index = word.lastIndexOf('-'); if (index >= 0 && index < word.length()) { String lastPiece = word.substring(index + 1); String wv = getVocabWord(lastPiece); if (wv != null) { return wv; } } } return UNKNOWN_WORD; } public SimpleMatrix getUnknownWordVector() { return wordVectors.get(UNKNOWN_WORD); } public void printMatrixNames(PrintStream out) { out.println("Binary matrices:"); for (TwoDimensionalMap.Entry<String, String, SimpleMatrix> binary : binaryTransform) { out.println(" " + binary.getFirstKey() + ":" + binary.getSecondKey()); } out.println("Unary matrices:"); for (String unary : unaryTransform.keySet()) { out.println(" " + unary); } } public void printMatrixStats(PrintStream out) { System.err.println("Model loaded with " + numUnaryMatrices + " unary and " + numBinaryMatrices + " binary"); for (TwoDimensionalMap.Entry<String, String, SimpleMatrix> binary : binaryTransform) { out.println("Binary transform " + binary.getFirstKey() + ":" + binary.getSecondKey()); double normf = binary.getValue().normF(); out.println(" Total norm " + (normf * normf)); normf = binary.getValue().extractMatrix(0, op.lexOptions.numHid, 0, op.lexOptions.numHid).normF(); out.println(" Left norm (" + binary.getFirstKey() + ") " + (normf * normf)); normf = binary.getValue().extractMatrix(0, op.lexOptions.numHid, op.lexOptions.numHid, op.lexOptions.numHid*2).normF(); out.println(" Right norm (" + binary.getSecondKey() + ") " + (normf * normf)); } } public void printAllMatrices(PrintStream out) { for (TwoDimensionalMap.Entry<String, String, SimpleMatrix> binary : binaryTransform) { out.println("Binary transform " + binary.getFirstKey() + ":" + binary.getSecondKey()); out.println(binary.getValue()); } for (TwoDimensionalMap.Entry<String, String, SimpleMatrix> binary : binaryScore) { out.println("Binary score " + binary.getFirstKey() + ":" + binary.getSecondKey()); out.println(binary.getValue()); } for (Map.Entry<String, SimpleMatrix> unary : unaryTransform.entrySet()) { out.println("Unary transform " + unary.getKey()); out.println(unary.getValue()); } for (Map.Entry<String, SimpleMatrix> unary : unaryScore.entrySet()) { out.println("Unary score " + unary.getKey()); out.println(unary.getValue()); } } public int binaryTransformIndex(String leftChild, String rightChild) { int pos = 0; for (TwoDimensionalMap.Entry<String, String, SimpleMatrix> binary : binaryTransform) { if (binary.getFirstKey().equals(leftChild) && binary.getSecondKey().equals(rightChild)) { return pos; } pos += binary.getValue().getNumElements(); } return -1; } public int unaryTransformIndex(String child) { int pos = binaryTransformSize * numBinaryMatrices; for (Map.Entry<String, SimpleMatrix> unary : unaryTransform.entrySet()) { if (unary.getKey().equals(child)) { return pos; } pos += unary.getValue().getNumElements(); } return -1; } public int binaryScoreIndex(String leftChild, String rightChild) { int pos = binaryTransformSize * numBinaryMatrices + unaryTransformSize * numUnaryMatrices; for (TwoDimensionalMap.Entry<String, String, SimpleMatrix> binary : binaryScore) { if (binary.getFirstKey().equals(leftChild) && binary.getSecondKey().equals(rightChild)) { return pos; } pos += binary.getValue().getNumElements(); } return -1; } public int unaryScoreIndex(String child) { int pos = (binaryTransformSize + binaryScoreSize) * numBinaryMatrices + unaryTransformSize * numUnaryMatrices; for (Map.Entry<String, SimpleMatrix> unary : unaryScore.entrySet()) { if (unary.getKey().equals(child)) { return pos; } pos += unary.getValue().getNumElements(); } return -1; } public Pair<String, String> indexToBinaryTransform(int pos) { if (pos < numBinaryMatrices * binaryTransformSize) { for (TwoDimensionalMap.Entry<String, String, SimpleMatrix> entry : binaryTransform) { if (binaryTransformSize < pos) { pos -= binaryTransformSize; } else { return Pair.makePair(entry.getFirstKey(), entry.getSecondKey()); } } } return null; } public String indexToUnaryTransform(int pos) { pos -= numBinaryMatrices * binaryTransformSize; if (pos < numUnaryMatrices * unaryTransformSize && pos >= 0) { for (Map.Entry<String, SimpleMatrix> entry : unaryTransform.entrySet()) { if (unaryTransformSize < pos) { pos -= unaryTransformSize; } else { return entry.getKey(); } } } return null; } public Pair<String, String> indexToBinaryScore(int pos) { pos -= (numBinaryMatrices * binaryTransformSize + numUnaryMatrices * unaryTransformSize); if (pos < numBinaryMatrices * binaryScoreSize && pos >= 0) { for (TwoDimensionalMap.Entry<String, String, SimpleMatrix> entry : binaryScore) { if (binaryScoreSize < pos) { pos -= binaryScoreSize; } else { return Pair.makePair(entry.getFirstKey(), entry.getSecondKey()); } } } return null; } public String indexToUnaryScore(int pos) { pos -= (numBinaryMatrices * (binaryTransformSize + binaryScoreSize) + numUnaryMatrices * unaryTransformSize); if (pos < numUnaryMatrices * unaryScoreSize && pos >= 0) { for (Map.Entry<String, SimpleMatrix> entry : unaryScore.entrySet()) { if (unaryScoreSize < pos) { pos -= unaryScoreSize; } else { return entry.getKey(); } } } return null; } /** * Prints to stdout the type and key for the given location in the parameter stack */ public void printParameterType(int pos, PrintStream out) { int originalPos = pos; Pair<String, String> binary = indexToBinaryTransform(pos); if (binary != null) { pos = pos % binaryTransformSize; out.println("Entry " + originalPos + " is entry " + pos + " of binary transform " + binary.first() + ":" + binary.second()); return; } String unary = indexToUnaryTransform(pos); if (unary != null) { pos = (pos - numBinaryMatrices * binaryTransformSize) % unaryTransformSize; out.println("Entry " + originalPos + " is entry " + pos + " of unary transform " + unary); return; } binary = indexToBinaryScore(pos); if (binary != null) { pos = (pos - numBinaryMatrices * binaryTransformSize - numUnaryMatrices * unaryTransformSize) % binaryScoreSize; out.println("Entry " + originalPos + " is entry " + pos + " of binary score " + binary.first() + ":" + binary.second()); return; } unary = indexToUnaryScore(pos); if (unary != null) { pos = (pos - (numBinaryMatrices * (binaryTransformSize + binaryScoreSize)) - numUnaryMatrices * unaryTransformSize) % unaryScoreSize; out.println("Entry " + originalPos + " is entry " + pos + " of unary score " + unary); return; } out.println("Index " + originalPos + " unknown"); } private static final long serialVersionUID = 1; }
b21b1e47cfa0e3896f9e2d2324cf099f321b90b0
518a13c0b180901a2dafbda2a8118acc44d54ed1
/app/src/main/java/com/technology/yuyidoctorpad/activity/PaintList/Model/IEle.java
b21ccb9578a5ed5d417ed518e8f69f15dd1adcf6
[]
no_license
liuhaidong123/YUYIDoctorPAD
2f17a798593571f5890860fc80d7919c0973a5a4
c4c637910153b2a51c6ae3ecc20e906d047c40d0
refs/heads/master
2021-09-26T12:36:24.480000
2018-10-30T08:51:15
2018-10-30T08:51:16
108,789,568
0
0
null
null
null
null
UTF-8
Java
false
false
351
java
package com.technology.yuyidoctorpad.activity.PaintList.Model; import com.technology.yuyidoctorpad.activity.PaintList.Bean.bean_MedicalRecordList; import java.util.List; /** * Created by wanyu on 2017/11/3. */ //电子病历 public interface IEle { void onSuccess(List<bean_MedicalRecordList.ResultBean>list); void onError(String msg); }
b17f076f4d17e68b48434ec476f3236868f86243
1e59523583a5226a6caee29c8a6ec7fc9ba0cdc9
/src/main/java/com/demo/domain/TrackPackageIdentifier.java
5a93cc10cb9b555befe7568bcd60be1b60bbcaeb
[]
no_license
mkujha/fedextracker
de6e96fa6608629094db46736dd8d303b7a758e8
c2e488f962d173b79c20656c4338a9d17238a38d
refs/heads/master
2021-01-11T21:19:55.544430
2017-01-23T16:19:08
2017-01-23T16:19:08
78,763,879
0
0
null
null
null
null
UTF-8
Java
false
false
2,599
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.01.20 at 07:44:04 PM EST // package com.demo.domain; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * The type and value of the package identifier that is to be used to retrieve the tracking * information for a package. * * * <p>Java class for TrackPackageIdentifier complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="TrackPackageIdentifier"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Type" type="{http://demo.com/ws/track/v12}TrackIdentifierType"/> * &lt;element name="Value" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TrackPackageIdentifier", propOrder = { "type", "value" }) public class TrackPackageIdentifier { @XmlElement(name = "Type", required = true) protected TrackIdentifierType type; @XmlElement(name = "Value", required = true) protected String value; /** * Gets the value of the type property. * * @return * possible object is * {@link TrackIdentifierType } * */ public TrackIdentifierType getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link TrackIdentifierType } * */ public void setType(TrackIdentifierType value) { this.type = value; } /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } }
c87ecf878094b59094c046623a83e67b449afb66
a2cab81f1027c7eb9a727302f11f327eddc6a044
/IR/SearchEngine-master/src/com/TemaLucene/BM25ModifiedSimilarity.java
dcc108d2b23a5ba96b283e873891ca8615ab72bf
[]
no_license
ciprianceausescu/Master_materiale
bc9397265a50c13b4e6359a0fab5d5a18bf2c79a
c4dc350c54e2a8c151f7800bf63c773a40609bae
refs/heads/master
2021-10-23T05:57:06.901517
2019-03-15T08:10:25
2019-03-15T08:10:25
111,453,004
0
0
null
null
null
null
UTF-8
Java
false
false
10,740
java
package com.TemaLucene; import org.apache.lucene.index.*; import org.apache.lucene.search.CollectionStatistics; import org.apache.lucene.search.Explanation; import org.apache.lucene.search.TermStatistics; import org.apache.lucene.search.similarities.Similarity; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.SmallFloat; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Created by Mircea on 08.05.2018. */ public class BM25ModifiedSimilarity extends Similarity { private final float k1; private final float b; protected boolean discountOverlaps; private static final float[] OLD_LENGTH_TABLE = new float[256]; private static final float[] LENGTH_TABLE = new float[256]; public BM25ModifiedSimilarity(float k1, float b) { this.discountOverlaps = true; if(Float.isFinite(k1) && k1 >= 0.0F) { if(!Float.isNaN(b) && b >= 0.0F && b <= 1.0F) { this.k1 = k1; this.b = b; } else { throw new IllegalArgumentException("illegal b value: " + b + ", must be between 0 and 1"); } } else { throw new IllegalArgumentException("illegal k1 value: " + k1 + ", must be a non-negative finite value"); } } public BM25ModifiedSimilarity() { this(1.2F, 0.75F); } protected float idf(long docFreq, long docCount) { return (float)Math.log(1.0D + ((double)(docCount - docFreq) + 0.5D) / ((double)docFreq + 0.5D)); } protected float sloppyFreq(int distance) { return 1.0F / (float)(distance + 1); } protected float scorePayload(int doc, int start, int end, BytesRef payload) { return 1.0F; } protected float avgFieldLength(CollectionStatistics collectionStats) { long sumTotalTermFreq; if(collectionStats.sumTotalTermFreq() == -1L) { if(collectionStats.sumDocFreq() == -1L) { return 1.0F; } sumTotalTermFreq = collectionStats.sumDocFreq(); } else { sumTotalTermFreq = collectionStats.sumTotalTermFreq(); } long docCount = collectionStats.docCount() == -1L?collectionStats.maxDoc():collectionStats.docCount(); return (float)((double)sumTotalTermFreq / (double)docCount); } public void setDiscountOverlaps(boolean v) { this.discountOverlaps = v; } public boolean getDiscountOverlaps() { return this.discountOverlaps; } public final long computeNorm(FieldInvertState state) { int numTerms = this.discountOverlaps?state.getLength() - state.getNumOverlap():state.getLength(); int indexCreatedVersionMajor = state.getIndexCreatedVersionMajor(); return indexCreatedVersionMajor >= 7?(long) SmallFloat.intToByte4(numTerms):(long)SmallFloat.floatToByte315((float)(1.0D / Math.sqrt((double)numTerms))); } public Explanation idfExplain(CollectionStatistics collectionStats, TermStatistics termStats) { long df = termStats.docFreq(); long docCount = collectionStats.docCount() == -1L?collectionStats.maxDoc():collectionStats.docCount(); float idf = this.idf(df, docCount); return Explanation.match(idf, "idf, computed as log(1 + (docCount - docFreq + 0.5) / (docFreq + 0.5)) from:", new Explanation[]{Explanation.match((float)df, "docFreq", new Explanation[0]), Explanation.match((float)docCount, "docCount", new Explanation[0])}); } public Explanation idfExplain(CollectionStatistics collectionStats, TermStatistics[] termStats) { double idf = 0.0D; List<Explanation> details = new ArrayList(); TermStatistics[] var6 = termStats; int var7 = termStats.length; for(int var8 = 0; var8 < var7; ++var8) { TermStatistics stat = var6[var8]; Explanation idfExplain = this.idfExplain(collectionStats, stat); details.add(idfExplain); idf += (double)idfExplain.getValue(); } return Explanation.match((float)idf, "idf(), sum of:", details); } public final SimWeight computeWeight(float boost, CollectionStatistics collectionStats, TermStatistics... termStats) { Explanation idf = termStats.length == 1?this.idfExplain(collectionStats, termStats[0]):this.idfExplain(collectionStats, termStats); float avgdl = this.avgFieldLength(collectionStats); float[] oldCache = new float[256]; float[] cache = new float[256]; for(int i = 0; i < cache.length; ++i) { oldCache[i] = this.k1 * (1.0F - this.b + this.b * OLD_LENGTH_TABLE[i] / avgdl); cache[i] = this.k1 * (1.0F - this.b + this.b * LENGTH_TABLE[i] / avgdl); } return new BM25ModifiedSimilarity.BM25Stats(collectionStats.field(), boost, idf, avgdl, oldCache, cache); } public final SimScorer simScorer(SimWeight stats, LeafReaderContext context) throws IOException { BM25ModifiedSimilarity.BM25Stats bm25stats = (BM25ModifiedSimilarity.BM25Stats)stats; return new BM25ModifiedSimilarity.BM25DocScorer(bm25stats, context.reader().getMetaData().getCreatedVersionMajor(), context.reader().getNormValues(bm25stats.field)); } private Explanation explainTFNorm(int doc, Explanation freq, BM25ModifiedSimilarity.BM25Stats stats, NumericDocValues norms, float[] lengthCache) throws IOException { List<Explanation> subs = new ArrayList(); subs.add(freq); subs.add(Explanation.match(this.k1, "parameter k1", new Explanation[0])); if(norms == null) { subs.add(Explanation.match(0.0F, "parameter b (norms omitted for field)", new Explanation[0])); return Explanation.match(freq.getValue() * (this.k1 + 1.0F) / (freq.getValue() + this.k1), "tfNorm, computed as (freq * (k1 + 1)) / (freq + k1) from:", subs); } else { byte norm; if(norms.advanceExact(doc)) { norm = (byte)((int)norms.longValue()); } else { norm = 0; } float doclen = lengthCache[norm & 255]; subs.add(Explanation.match(this.b, "parameter b", new Explanation[0])); subs.add(Explanation.match(stats.avgdl, "avgFieldLength", new Explanation[0])); subs.add(Explanation.match(doclen, "fieldLength", new Explanation[0])); return Explanation.match(freq.getValue() * (this.k1 + 1.0F) / (freq.getValue() + this.k1 * (1.0F - this.b + this.b * doclen / stats.avgdl)), "tfNorm, computed as (freq * (k1 + 1)) / (freq + k1 * (1 - b + b * fieldLength / avgFieldLength)) from:", subs); } } private Explanation explainScore(int doc, Explanation freq, BM25ModifiedSimilarity.BM25Stats stats, NumericDocValues norms, float[] lengthCache) throws IOException { Explanation boostExpl = Explanation.match(stats.boost, "boost", new Explanation[0]); List<Explanation> subs = new ArrayList(); if(boostExpl.getValue() != 1.0F) { subs.add(boostExpl); } subs.add(stats.idf); Explanation tfNormExpl = this.explainTFNorm(doc, freq, stats, norms, lengthCache); subs.add(tfNormExpl); return Explanation.match(boostExpl.getValue() * stats.idf.getValue() * tfNormExpl.getValue(), "score(doc=" + doc + ",freq=" + freq + "), product of:", subs); } public String toString() { return "BM25(k1=" + this.k1 + ",b=" + this.b + ")"; } public final float getK1() { return this.k1; } public final float getB() { return this.b; } static { int i; for(i = 1; i < 256; ++i) { float f = SmallFloat.byte315ToFloat((byte)i); OLD_LENGTH_TABLE[i] = 1.0F / (f * f); } OLD_LENGTH_TABLE[0] = 1.0F / OLD_LENGTH_TABLE[255]; for(i = 0; i < 256; ++i) { LENGTH_TABLE[i] = (float)SmallFloat.byte4ToInt((byte)i); } } private static class BM25Stats extends SimWeight { private final Explanation idf; private final float avgdl; private final float boost; private final float weight; private final String field; private final float[] oldCache; private final float[] cache; BM25Stats(String field, float boost, Explanation idf, float avgdl, float[] oldCache, float[] cache) { this.field = field; this.boost = boost; this.idf = idf; this.avgdl = avgdl; this.weight = idf.getValue() * boost; this.oldCache = oldCache; this.cache = cache; } } private class BM25DocScorer extends SimScorer { private final BM25ModifiedSimilarity.BM25Stats stats; private final float weightValue; private final NumericDocValues norms; private final float[] lengthCache; private final float[] cache; BM25DocScorer(BM25ModifiedSimilarity.BM25Stats stats, int indexCreatedVersionMajor, NumericDocValues norms) throws IOException { this.stats = stats; this.weightValue = stats.weight * (BM25ModifiedSimilarity.this.k1 + 1.0F); this.norms = norms; if(indexCreatedVersionMajor >= 7) { this.lengthCache = BM25ModifiedSimilarity.LENGTH_TABLE; this.cache = stats.cache; } else { this.lengthCache = BM25ModifiedSimilarity.OLD_LENGTH_TABLE; this.cache = stats.oldCache; } } public float score(int doc, float freq) throws IOException { float norm; if(this.norms == null) { norm = BM25ModifiedSimilarity.this.k1; } else if(this.norms.advanceExact(doc)) { norm = this.cache[(byte)((int)this.norms.longValue()) & 255]; } else { norm = this.cache[0]; } float coef = 1.0f; if (stats.field.equals("abstract")) { coef = 3.0f; } return coef * this.weightValue * freq / (freq + norm); } public Explanation explain(int doc, Explanation freq) throws IOException { return BM25ModifiedSimilarity.this.explainScore(doc, freq, this.stats, this.norms, this.lengthCache); } public float computeSlopFactor(int distance) { return BM25ModifiedSimilarity.this.sloppyFreq(distance); } public float computePayloadFactor(int doc, int start, int end, BytesRef payload) { return BM25ModifiedSimilarity.this.scorePayload(doc, start, end, payload); } } }
510137b8b831f91fa5051b1fca4eef33a738ff07
3a89afb7662f5425add3eaaf36a2801119a8b67b
/io/Leggi.java
3e111e1a1d9d2adca07ceafd6afff01723771181
[]
no_license
mmiglia/SA2013-2014
1269c15fbc639b0454663b92267d5e49a8d05d59
377ee184c5241507e020fbb9454e1750b587c70f
refs/heads/master
2020-07-05T06:58:39.874974
2013-12-12T15:21:46
2013-12-12T15:21:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
389
java
package io; import java.io.*; public class Leggi { public static void main(String[] argv) { try { DataInputStream dis = new DataInputStream(new FileInputStream(argv[0])); while(dis.available() > 0) { //System.out.println(dis.readLong()); System.out.println(dis.readInt()); } dis.close(); } catch(IOException ioe) { ioe.printStackTrace(); } } }
a1ef02a79e58d85121e438f382357cc868d85bb6
e74f42ea2ab4730056a7dadae80681cb2defe46e
/src/main/java/com/hunantv/bigdata/troy/entity/MessageStatus.java
149ed5af5a6091c393f8ab30b4d36ce136c1d59e
[]
no_license
washhy/trony
b4516f0d9592e70ddade6b8b890fdd9cd9a53b2d
6c0593ec422f1b1bc3c4e27d7283d540d0272bc5
refs/heads/master
2020-08-18T02:52:32.721084
2016-03-11T03:22:26
2016-03-11T03:22:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
205
java
package com.hunantv.bigdata.troy.entity; /** * Created by wuxinyong on 15-1-21. */ public enum MessageStatus { BUILD_SUCC, BUILD_ERROR, PARSE_SUCC, PARSE_ERROR, VALID_SUCC, VALID_ERROR, IS_DEBUG, }
024358421ad06cd5468f70b09033b72c8d203930
b89fa5d4a3364a6ac40bce2b7330289064a0e04a
/src/it/unimib/disco/ab/ner/ParallelNerThread.java
232ceabae76c87ab4317c7b39212367cca06375d
[]
no_license
AlessandroBregoli/TopicModelStage
c9961a6b86a346075025dd900d9f595ad3bd13fe
389d744bebb12b0a54715768eed20516cf45ff79
refs/heads/master
2021-01-20T19:57:52.547798
2016-10-26T09:30:09
2016-10-26T09:30:09
56,488,582
1
0
null
null
null
null
UTF-8
Java
false
false
2,010
java
package it.unimib.disco.ab.ner; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import edu.stanford.nlp.util.Triple; import it.unimib.disco.ab.textPreprocessing.Sentence; //Applicazione del ner alle frasi restituite dal monitor public class ParallelNerThread extends Thread { ParallelNer monitor; public ParallelNerThread(ParallelNer monitor){ this.monitor = monitor; } @Override public void run(){ while(true){ long sentenceID = this.monitor.getSentenceId(); if(sentenceID < 0) return; Sentence sentence = this.monitor.sentences.sentences.get(sentenceID); NerMerge nerMerge = new NerMerge(sentence.text); for(int i = 0; i < this.monitor.classifier.length; i++){ List<Triple<String,Integer,Integer>> out = this.monitor.classifier[i].classifyToCharacterOffsets(sentence.text); for(Triple<String,Integer,Integer> triple: out){ nerMerge.add(triple); } } this.monitor.sentencesAcquisition();{ Iterator<CustomEntity> it = nerMerge.iterator(); while(it.hasNext()){ CustomEntity customEntity = it.next(); if(customEntity.entityClass.equals("0") || this.monitor.matcher.match(customEntity.entityString)) continue; LinkedList<Long> t = this.monitor.entities.get(customEntity); if(t == null){ t = new LinkedList<Long>(); t.add(sentenceID); this.monitor.entities.put(customEntity, t); } else{ if(t.getLast() <= sentenceID){ t.add(sentenceID); } else{ if(t.getFirst() >= sentenceID){ t.addFirst(sentenceID); }else{ for(int i = t.size()- 2; i >= 0; i--){ if(t.get(i) <= sentenceID){ t.add(i+1, sentenceID); break; } } } } } } }this.monitor.sentencesRelease(); } } }
17461503f010efe2fb8f1040fed9a36d75161eb8
59e7cbb46b58502364d5f88073a2f1d6dedb7bee
/maven_day88/target/tomcat/work/Tomcat/localhost/maven_day88/org/apache/jsp/WEB_002dINF/pages/findBy_jsp.java
185d38ab5a9f8b1ed5208f389ca5cab072d6ae90
[]
no_license
easily123/repo1
04c1bc40391b84d15a803dcbed2bea7c349e5a55
a6f4a2e99383ca24c1203d792641fc8e5f2f12e7
refs/heads/master
2022-12-26T11:54:00.264329
2019-06-14T08:21:31
2019-06-14T08:21:31
191,897,324
0
0
null
2022-12-16T04:24:45
2019-06-14T07:31:59
Java
UTF-8
Java
false
false
7,412
java
/* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/7.0.47 * Generated at: 2019-06-13 00:11:27 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp.WEB_002dINF.pages; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class findBy_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody; private javax.el.ExpressionFactory _el_expressionfactory; private org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public void _jspInit() { _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } public void _jspDestroy() { _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody.release(); } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n"); out.write(" <title>Insert title here</title>\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); out.write("<form>\r\n"); out.write(" <table width=\"100%\" border=1>\r\n"); out.write(" <tr>\r\n"); out.write(" <td>商品名称</td>\r\n"); out.write(" <td> "); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${item.name }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write(" </td>\r\n"); out.write(" </tr>\r\n"); out.write(" <tr>\r\n"); out.write(" <td>商品价格</td>\r\n"); out.write(" <td> "); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${item.price }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write(" </td>\r\n"); out.write(" </tr>\r\n"); out.write(" <tr>\r\n"); out.write(" <td>生成日期</td>\r\n"); out.write(" <td> "); if (_jspx_meth_fmt_005fformatDate_005f0(_jspx_page_context)) return; out.write(" </td>\r\n"); out.write(" </tr>\r\n"); out.write(" <tr>\r\n"); out.write(" <td>商品简介</td>\r\n"); out.write(" <td>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${item.detail}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write(" </td>\r\n"); out.write(" </tr>\r\n"); out.write(" </table>\r\n"); out.write("</form>\r\n"); out.write("</body>\r\n"); out.write("</html>"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { out.clearBuffer(); } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } private boolean _jspx_meth_fmt_005fformatDate_005f0(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:formatDate org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag _jspx_th_fmt_005fformatDate_005f0 = (org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag) _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag.class); _jspx_th_fmt_005fformatDate_005f0.setPageContext(_jspx_page_context); _jspx_th_fmt_005fformatDate_005f0.setParent(null); // /WEB-INF/pages/findBy.jsp(25,17) name = value type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fformatDate_005f0.setValue((java.util.Date) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${item.createtime}", java.util.Date.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); // /WEB-INF/pages/findBy.jsp(25,17) name = pattern type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fformatDate_005f0.setPattern("yyyy-MM-dd HH:mm:ss"); int _jspx_eval_fmt_005fformatDate_005f0 = _jspx_th_fmt_005fformatDate_005f0.doStartTag(); if (_jspx_th_fmt_005fformatDate_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody.reuse(_jspx_th_fmt_005fformatDate_005f0); return true; } _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody.reuse(_jspx_th_fmt_005fformatDate_005f0); return false; } }