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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e337733cf3c18a8704454a8b6882a9b498fbc284 | 1bddb3fe57506f4af99223b48e987e81f4898273 | /src/com/monster/learn/NumMatchingSubseq.java | 94c8397a9154c78d6e9a1b84127c0ffd8c9580d8 | [
"MIT"
] | permissive | lybvinci/leetcode_practices | 82cf46025d81cbaa6ac899d9faa3d8cf73b1a216 | ba8de653a6737bc89d61d804491bff9bd401e2f9 | refs/heads/master | 2022-12-22T11:14:17.856062 | 2022-12-22T07:08:14 | 2022-12-22T07:08:14 | 138,813,322 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 583 | java | package com.monster.learn;
public class NumMatchingSubseq {
//5.16%
public int numMatchingSubseq(String s, String[] words) {
int ret = 0;
for (String word : words) {
char[] charArray = word.toCharArray();
int j = 0;
for (int i = 0; i < s.length(); i++) {
int index = s.indexOf(charArray[j],i);
if (index != -1) {
i = index;
if (s.charAt(i) == charArray[j]) {
j++;
if (j >= charArray.length) {
break;
}
}
} else {
break;
}
}
if (j >= charArray.length) {
ret++;
}
}
return ret;
}
}
| [
"liyanbo.monster@bytedance.com"
] | liyanbo.monster@bytedance.com |
bc316da683f23a1490483d36d56d5c8a4e0af7ea | ebeb4f81c127aed6028069ca8713806d25401104 | /vendor/github.com/antlr/antlr4/runtime-testsuite/test/org/antlr/v4/test/runtime/cpp/TestLeftRecursion.java | ddb786a3f09fb68996295ecdd353b1d418d8fe6b | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"MIT",
"BSD-2-Clause",
"Apache-2.0"
] | permissive | mikijov/rune | 9c825534af194f1cf6db0c933b743cd1c8b41890 | 22024919bf2535822f974ed7f167871076c0211e | refs/heads/master | 2022-06-17T13:59:57.896016 | 2022-06-09T03:26:20 | 2022-06-09T03:26:20 | 122,198,945 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 884 | java | /*
* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
package org.antlr.v4.test.runtime.cpp;
import org.antlr.v4.test.runtime.BaseRuntimeTest;
import org.antlr.v4.test.runtime.RuntimeTestDescriptor;
import org.antlr.v4.test.runtime.descriptors.LeftRecursionDescriptors;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class TestLeftRecursion extends BaseRuntimeTest {
public TestLeftRecursion(RuntimeTestDescriptor descriptor) {
super(descriptor,new BaseCppTest());
}
@Parameterized.Parameters(name="{0}")
public static RuntimeTestDescriptor[] getAllTestDescriptors() {
return BaseRuntimeTest.getRuntimeTestDescriptors(LeftRecursionDescriptors.class, "Cpp");
}
}
| [
"jovanovic.milutin@gmail.com"
] | jovanovic.milutin@gmail.com |
dd62ddb4445466ea41889cb4579ca88c8aad8a7a | ddf8c22b6eb9de9b1c560c364302d0c1283424d4 | /src/com/skamenialo/creditgranting/NeuralNetwork.java | 45cbfe67733fe3ac22ada85fb7d38411a02aac77 | [
"MIT"
] | permissive | skamenialo/NeuralNetwork_CreditGranting | 06d3db78674d849e2f2198307509bfcf507684ad | 9bcce2421362242c9141a7060aec0130b8820f7d | refs/heads/master | 2021-01-10T03:21:22.086998 | 2016-02-13T00:42:58 | 2016-02-13T00:42:58 | 50,060,080 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,668 | java | package com.skamenialo.creditgranting;
import com.skamenialo.creditgranting.gui.MainWindow;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class NeuralNetwork {
private int mAge,
mFail,
mMaxFail;
private Neuron[] mNeurons;
private MainWindow mFrame;
private boolean mLearn;
public List<Client> clients;
public NeuralNetwork(MainWindow frame, List<Client> clients) {
this.clients = clients;
mFrame = frame;
mLearn = false;
reset();
}
private void learn() {
System.out.println("\n\nDopuszczalna ilość błędów: " + mMaxFail);
mLearn = true;
do {
if (!mLearn) {
break;
}
mFrame.setAge(mAge);
mFail = 0;
for (Client c : clients) {
for (int j = 0; j < mNeurons.length; j++) {
if (c.d[j] != mNeurons[j].answer(c.x, false)) {
mNeurons[j].calculate(c.d[j], c.x);
mFail++;
}
}
}
mFrame.setFail(mFail);
mAge++;
Collections.shuffle(clients);
} while (mFail > mMaxFail);
mLearn = false;
mFrame.setEndFail(mFail);
System.out.println("Ilość epok po skończonej nauce: " + mAge
+ "\nIlość błędów po skończonej nauce: " + mFail);
}
private double verify(double[] x) {
double answer = 0;
for (int i = 0; i < mNeurons.length; i++) {
double odp = mNeurons[i].answer(x, true);
answer += odp;
System.out.println("Odpowiedź neuronu nr " + i + ": " + odp);
}
return answer;
}
private void setX() {
for (int i = 0; i < clients.size(); i++) {
System.out.print("x[" + i + "]\t");
clients.get(i).setX(clients);
System.out.println();
}
}
private void setD() {
int size = clients.size(),
i = 0;
for (Client c : clients) {
c.d = new int[size];
int KD[] = new int[size],
kD1[] = c.getD();
for (int j = 0; j < size; j++) {
int equal = 0,
notequal = 0,
kiD[] = clients.get(j).getD();
for (int k = 0; k < kD1.length; k++) {
if (kD1[k] == kiD[k]) {
equal++;
} else {
notequal++;
}
}
if (equal >= notequal) {
KD[j] = 1;
} else {
KD[j] = -1;
}
}
kD1 = new int[size];
int kD2[] = c.getD();
for (int j = 0; j < size; j++) {
int zero = 0,
one = 0,
kiD[] = clients.get(j).getD();
for (int k = 0; k < kD2.length; k++) {
if (kD2[k] == kiD[k]) {
if (kD2[k] == 0) {
zero++;
} else {
one++;
}
}
}
if (one >= zero) {
kD1[j] = 1;
} else {
kD1[j] = -1;
}
}
System.out.print("d[" + i + "]\t");
for (int j = 0; j < KD.length; j++) {
c.d[j] = KD[j] * kD1[j];
if (c.d[j] == 1) {
System.out.print(" ");
}
System.out.print(c.d[j] + "|");
}
System.out.println();
i++;
}
}
public List<Client> verifyElements(List<Client> clients) {
List<Client> verify = new ArrayList<>();
System.out.println("\nWejścia:");
int i = 0;
for (Client c : clients) {
verify.add(new Client(c.getAge(), c.getChildren(), c.getIncome(), c.getEmployment(), c.isLoan(), c.getAmountActiveLoan(), c.getAmountNewLoan()));
System.out.print("x[" + i + "] ");
verify.get(i).setX(verify);
System.out.println();
i++;
}
System.out.println();
for (Client c : verify) {
c.setGranted((verify(c.x) > 0));
System.out.println(c.isGrantedToString() + "\n");
}
return verify;
}
public void setFail(int fail) {
mMaxFail = fail;
}
public boolean isLearning() {
return mLearn;
}
public void addClient(Client client) {
clients.add(client);
reset();
}
public void reset() {
mAge = 0;
System.out.println("\nIlość elementów uczących: " + (clients.size()));
System.out.println("\nWejścia:");
setX();
System.out.println("\nWartość oczekiwana:");
setD();
mNeurons = new Neuron[8];
System.out.println("\nWagi neuronów przed nauką: ");
for (int i = 0; i < mNeurons.length; i++) {
mNeurons[i] = new Neuron();
System.out.println("n[" + i + "]=(" + mNeurons[i] + ")");
}
}
public void start() {
learn();
System.out.println("\n\nWagi neuronów po nauce: ");
for (int i = 0; i < mNeurons.length; i++) {
System.out.println("n[" + i + "]=(" + mNeurons[i] + ")");
}
}
public void stop() {
mLearn = false;
}
}
| [
"janowski.d@wp.pl"
] | janowski.d@wp.pl |
17adfc3dbe55d1429e22b49e23323abc54503a4c | 430c7b3287018863c4e4b03562ce07585139965a | /src/codeforces/Finales Septiembre/BrasilF.java | 75a75ca50d4e0d18dfcd71aecbbd265e7559ed3e | [] | no_license | santjuan/ICPCTraining2013 | 6d98f09042b4f6b738ddd2bdf2eae0d77cb511df | 193c84b49bcbe3a0158b569a5d370fa4601f6e4c | refs/heads/master | 2016-09-05T08:57:35.612606 | 2013-12-15T00:10:17 | 2013-12-15T00:10:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,599 | java | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.StringTokenizer;
public class BrasilF
{
static class Scanner
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String nextLine()
{
try
{
return br.readLine();
}
catch(Exception e)
{
throw(new RuntimeException());
}
}
public String next()
{
while(!st.hasMoreTokens())
{
String l = nextLine();
if(l == null)
return null;
st = new StringTokenizer(l);
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public double nextDouble()
{
return Double.parseDouble(next());
}
public int[] nextIntArray(int n)
{
int[] res = new int[n];
for(int i = 0; i < res.length; i++)
res[i] = nextInt();
return res;
}
public long[] nextLongArray(int n)
{
long[] res = new long[n];
for(int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public double[] nextDoubleArray(int n)
{
double[] res = new double[n];
for(int i = 0; i < res.length; i++)
res[i] = nextDouble();
return res;
}
public void sortIntArray(int[] array)
{
Integer[] vals = new Integer[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortLongArray(long[] array)
{
Long[] vals = new Long[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortDoubleArray(double[] array)
{
Double[] vals = new Double[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public String[] nextStringArray(int n)
{
String[] vals = new String[n];
for(int i = 0; i < n; i++)
vals[i] = next();
return vals;
}
public Integer nextInteger()
{
String s = next();
if(s == null)
return null;
return Integer.parseInt(s);
}
public int[][] nextIntMatrix(int n, int m)
{
int[][] ans = new int[n][];
for(int i = 0; i < n; i++)
ans[i] = nextIntArray(m);
return ans;
}
public char[][] nextGrid(int r)
{
char[][] grid = new char[r][];
for(int i = 0; i < r; i++)
grid[i] = next().toCharArray();
return grid;
}
public static <T> T fill(T arreglo, int val)
{
if(arreglo instanceof Object[])
{
Object[] a = (Object[]) arreglo;
for(Object x : a)
fill(x, val);
}
else if(arreglo instanceof int[])
Arrays.fill((int[]) arreglo, val);
else if(arreglo instanceof double[])
Arrays.fill((double[]) arreglo, val);
else if(arreglo instanceof long[])
Arrays.fill((long[]) arreglo, val);
return arreglo;
}
<T> T[] nextObjectArray(Class <T> clazz, int size)
{
@SuppressWarnings("unchecked")
T[] result = (T[]) java.lang.reflect.Array.newInstance(clazz, size);
for(int c = 0; c < 3; c++)
{
Constructor <T> constructor;
try
{
if(c == 0)
constructor = clazz.getDeclaredConstructor(Scanner.class, Integer.TYPE);
else if(c == 1)
constructor = clazz.getDeclaredConstructor(Scanner.class);
else
constructor = clazz.getDeclaredConstructor();
}
catch(Exception e)
{
continue;
}
try
{
for(int i = 0; i < result.length; i++)
{
if(c == 0)
result[i] = constructor.newInstance(this, i);
else if(c == 1)
result[i] = constructor.newInstance(this);
else
result[i] = constructor.newInstance();
}
}
catch(Exception e)
{
throw new RuntimeException(e);
}
return result;
}
throw new RuntimeException("Constructor not found");
}
public void printLine(int... vals)
{
if(vals.length == 0)
System.out.println();
else
{
System.out.print(vals[0]);
for(int i = 1; i < vals.length; i++)
System.out.print(" ".concat(String.valueOf(vals[i])));
System.out.println();
}
}
public void printLine(long... vals)
{
if(vals.length == 0)
System.out.println();
else
{
System.out.print(vals[0]);
for(int i = 1; i < vals.length; i++)
System.out.print(" ".concat(String.valueOf(vals[i])));
System.out.println();
}
}
public void printLine(double... vals)
{
if(vals.length == 0)
System.out.println();
else
{
System.out.print(vals[0]);
for(int i = 1; i < vals.length; i++)
System.out.print(" ".concat(String.valueOf(vals[i])));
System.out.println();
}
}
public void printLine(int prec, double... vals)
{
if(vals.length == 0)
System.out.println();
else
{
System.out.printf("%." + prec + "f", vals[0]);
for(int i = 1; i < vals.length; i++)
System.out.printf(" %." + prec + "f", vals[i]);
System.out.println();
}
}
public Collection <Integer> wrap(int[] as)
{
ArrayList <Integer> ans = new ArrayList <Integer> ();
for(int i : as)
ans.add(i);
return ans;
}
public int[] unwrap(Collection <Integer> collection)
{
int[] vals = new int[collection.size()];
int index = 0;
for(int i : collection) vals[index++] = i;
return vals;
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner();
while(true)
{
Integer nTemp = sc.nextInteger();
if(nTemp == null) return;
int n = nTemp;
int[] diffs = sc.nextIntArray(n);
int current = 0;
HashMap <Integer, Integer> map = new HashMap <Integer, Integer> ();
int id = 0;
for(int i : diffs)
{
map.put(current, id++);
current += i;
}
int size = current;
if(size % 3 != 0)
System.out.println(0);
else
{
int sideLength = size / 3;
int count = 0;
current = 0;
for(int i = 0; true; i++)
{
if(current >= sideLength) break;
int currentT = current;
current += diffs[i];
if(!map.containsKey((currentT + sideLength) % size)) continue;
if(!map.containsKey((currentT + sideLength + sideLength) % size)) continue;
count++;
}
System.out.println(count);
}
}
}
} | [
"santigutierrez1@gmail.com"
] | santigutierrez1@gmail.com |
9ff29cc3dd4f7440fbe91b1affaf1e2ed968a38c | 76eebf8c4aee0d369d0ca52946e1050f9387ab38 | /src/main/java/org/apache/fineract/UserAuthenticationService.java | 13a4e903006be692d3d0f2893704caa172012400 | [] | no_license | OrosBank/Oros-API | fd01fc944bae027395e6a2e6c4374ded2c3b4c4a | e0463730d39b94cb7604264217f0308fd4dbdbdf | refs/heads/master | 2020-04-01T20:59:53.370156 | 2018-10-18T13:54:05 | 2018-10-18T13:54:05 | 153,631,757 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,104 | java | package org.apache.fineract;
import java.util.ArrayList;
import java.util.List;
import org.apache.fineract.models.ChannelUsers;
import org.apache.fineract.models.Ebanking;
import org.apache.fineract.dao.EbankingDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class UserAuthenticationService implements UserDetailsService{
@Autowired
private EbankingDAO ebankingDAO;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//Ebanking userInfo = ebankingDAO.findUserInfo(username);
ChannelUsers userInfo = ebankingDAO.findUserAuthInfo(username);
System.out.println("UserInfo= " + userInfo);
if (userInfo == null) {
throw new UsernameNotFoundException("User " + username + " was not found in the database");
}
//List<String> roles= ebankingDAO.getUserRoles(username);
List<String> roles= ebankingDAO.getRoleNames(userInfo.getUserId());
List<GrantedAuthority> grantList= new ArrayList<GrantedAuthority>();
if(roles!= null) {
for(String role: roles) {
// ROLE_USER, ROLE_ADMIN,..
GrantedAuthority authority = new SimpleGrantedAuthority(role);
grantList.add(authority);
}
}
//UserDetails userDetails = (UserDetails) new User(userInfo.getUsername(),userInfo.getPassword(),grantList);
UserDetails userDetails = (UserDetails) new User(userInfo.getUsername(),userInfo.getBcryptEncodedAuthenticationKey(),grantList);
return userDetails;
}
}
| [
"einjoku@gmail.com"
] | einjoku@gmail.com |
c01067dc4766cfa8a2affc88b88f87056f624198 | e201b6597dd9d7db625e4fa389de9e915b9fe096 | /jql-core/src/main/java/io/github/benas/jql/domain/BaseDao.java | 7b3f6ed8a30d61be2857a175ffd046de9a5e25e5 | [
"MIT"
] | permissive | cybernetics/jql | 81ca405354198d258d70195a51fead9a5eb1499a | fa4e01a7a2360e61f1dd505a9b36ffdf87ca24f6 | refs/heads/master | 2021-01-22T14:02:14.497080 | 2016-07-27T14:45:16 | 2016-07-27T14:45:16 | 64,451,850 | 1 | 0 | null | 2016-07-29T05:01:59 | 2016-07-29T05:01:59 | null | UTF-8 | Java | false | false | 1,962 | java | /**
* The MIT License
*
* Copyright (c) 2016, Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.github.benas.jql.domain;
import org.springframework.jdbc.core.JdbcTemplate;
public abstract class BaseDao {
protected JdbcTemplate jdbcTemplate;
protected BaseDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
protected int getNextId(String table) {
Integer count = jdbcTemplate.queryForObject("select count(*) from " + table, Integer.class);
return count == 0 ? 1 : jdbcTemplate.queryForObject("select MAX(ID) + 1 from " + table, Integer.class);
}
// SQLITE 3 does not support boolean type..
protected int toSqliteBoolean(boolean bool) {
return bool ? 1 : 0;
}
protected boolean fromSqliteBoolean(int bool) {
return bool == 1;
}
}
| [
"mahmoud.benhassine@icloud.com"
] | mahmoud.benhassine@icloud.com |
5447adb7e0cd27ef7330a7a6c318d0586b875836 | ee556312afceee8c1a58cd184835c421e87fe88d | /src/IBM.java | 025a2e918023a5e94d09abd33fd22d12b01ae7ee | [] | no_license | meowracle/java_ses1_BMI | 3d47c85a686aa1c50f175da8ff60c8851e245b74 | fe90fee3cd7a3aa0be49ab4ff8810c8d3586e98e | refs/heads/master | 2020-09-04T02:47:45.090565 | 2019-11-05T02:39:02 | 2019-11-05T02:39:02 | 219,641,765 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 964 | java | public class IBM {
public double height;
public double weight;
public IBM(){
}
public IBM(double height, double weight) {
this.height = height;
this.weight = weight;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getBMI(){
double BMI = this.weight/Math.pow(height, 2);
return BMI;
}
public void displayResult(){
if (this.getBMI() < 18.5) {
System.out.println("Underweight");
} else if (this.getBMI() <25) {
System.out.println("Normal");
} else if (this.getBMI() <30) {
System.out.println("Overweight");
} else {
System.out.println("Obese");
}
}
}
| [
"aprilerd34@gmail.com"
] | aprilerd34@gmail.com |
88635ebddd946e2fe46dc6a4525f06506ae6d90f | 05fc541d57a925ce89118fa56ca72a4f7ceff8cb | /Liqilin-17990037/app/src/main/java/com/example/PersonFragment.java | aafd56db1e32a56ccac289a3e5339ef17fc1a93f | [] | no_license | LQLliqilin/dazuoye | edc90e0650ee047c41cf5863e715b885198179a0 | 25b4cb0a2c0a24b5a589791b9bcf876c6d16d315 | refs/heads/main | 2023-02-03T09:44:54.707386 | 2020-12-19T07:46:57 | 2020-12-19T07:46:57 | 322,794,882 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,223 | java | package com.example;
import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.liqilin.databinding.FragmentPersonBinding;
public class PersonFragment extends Fragment {
private FragmentPersonBinding binding;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding= FragmentPersonBinding.inflate(inflater,container,false);
// Inflate the layout for this fragment
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
binding.tvAccount.setText(Contants.username);
binding.llExit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Contants.username=null;
((Activity)requireContext()).finish();
}
});
}
} | [
"72777379+LQLliqilin@users.noreply.github.com"
] | 72777379+LQLliqilin@users.noreply.github.com |
d7c6192b7c5a040f3f08d82907b6e06b493d38f6 | 96c50af6562f35e30097a6d12b8955b8c68a6ac1 | /src/main/java/org/jooq/generated/information_schema/tables/Schemata.java | a4e69408e94646d7c2c27fc8dc46e1edd41a2a2c | [] | no_license | Monty1029/jooqdemo | 6a03fff44020154e63f34d94404ea0fed2d8818d | 48fcc60af144e82ee33bbb6e3ee712c1e669f642 | refs/heads/master | 2020-03-07T05:35:17.372653 | 2018-03-29T14:04:40 | 2018-03-29T14:04:40 | 127,300,145 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,672 | java | /**
* This class is generated by jOOQ
*/
package org.jooq.generated.information_schema.tables;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.generated.information_schema.InformationSchema;
import org.jooq.generated.information_schema.tables.records.SchemataRecord;
import org.jooq.impl.TableImpl;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.7.3"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Schemata extends TableImpl<SchemataRecord> {
private static final long serialVersionUID = 541880450;
/**
* The reference instance of <code>INFORMATION_SCHEMA.SCHEMATA</code>
*/
public static final Schemata SCHEMATA = new Schemata();
/**
* The class holding records for this type
*/
@Override
public Class<SchemataRecord> getRecordType() {
return SchemataRecord.class;
}
/**
* The column <code>INFORMATION_SCHEMA.SCHEMATA.CATALOG_NAME</code>.
*/
public final TableField<SchemataRecord, String> CATALOG_NAME = createField("CATALOG_NAME", org.jooq.impl.SQLDataType.VARCHAR.length(2147483647), this, "");
/**
* The column <code>INFORMATION_SCHEMA.SCHEMATA.SCHEMA_NAME</code>.
*/
public final TableField<SchemataRecord, String> SCHEMA_NAME = createField("SCHEMA_NAME", org.jooq.impl.SQLDataType.VARCHAR.length(2147483647), this, "");
/**
* The column <code>INFORMATION_SCHEMA.SCHEMATA.SCHEMA_OWNER</code>.
*/
public final TableField<SchemataRecord, String> SCHEMA_OWNER = createField("SCHEMA_OWNER", org.jooq.impl.SQLDataType.VARCHAR.length(2147483647), this, "");
/**
* The column <code>INFORMATION_SCHEMA.SCHEMATA.DEFAULT_CHARACTER_SET_NAME</code>.
*/
public final TableField<SchemataRecord, String> DEFAULT_CHARACTER_SET_NAME = createField("DEFAULT_CHARACTER_SET_NAME", org.jooq.impl.SQLDataType.VARCHAR.length(2147483647), this, "");
/**
* The column <code>INFORMATION_SCHEMA.SCHEMATA.DEFAULT_COLLATION_NAME</code>.
*/
public final TableField<SchemataRecord, String> DEFAULT_COLLATION_NAME = createField("DEFAULT_COLLATION_NAME", org.jooq.impl.SQLDataType.VARCHAR.length(2147483647), this, "");
/**
* The column <code>INFORMATION_SCHEMA.SCHEMATA.IS_DEFAULT</code>.
*/
public final TableField<SchemataRecord, Boolean> IS_DEFAULT = createField("IS_DEFAULT", org.jooq.impl.SQLDataType.BOOLEAN, this, "");
/**
* The column <code>INFORMATION_SCHEMA.SCHEMATA.REMARKS</code>.
*/
public final TableField<SchemataRecord, String> REMARKS = createField("REMARKS", org.jooq.impl.SQLDataType.VARCHAR.length(2147483647), this, "");
/**
* The column <code>INFORMATION_SCHEMA.SCHEMATA.ID</code>.
*/
public final TableField<SchemataRecord, Integer> ID = createField("ID", org.jooq.impl.SQLDataType.INTEGER, this, "");
/**
* Create a <code>INFORMATION_SCHEMA.SCHEMATA</code> table reference
*/
public Schemata() {
this("SCHEMATA", null);
}
/**
* Create an aliased <code>INFORMATION_SCHEMA.SCHEMATA</code> table reference
*/
public Schemata(String alias) {
this(alias, SCHEMATA);
}
private Schemata(String alias, Table<SchemataRecord> aliased) {
this(alias, aliased, null);
}
private Schemata(String alias, Table<SchemataRecord> aliased, Field<?>[] parameters) {
super(alias, InformationSchema.INFORMATION_SCHEMA, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public Schemata as(String alias) {
return new Schemata(alias, this);
}
/**
* Rename this table
*/
public Schemata rename(String name) {
return new Schemata(name, null);
}
}
| [
"dhanani.monty@gmail.com"
] | dhanani.monty@gmail.com |
e9249ef86184103466adacc73308873a0e245986 | 3a67f8174f75119b15b667439761a828e81824a2 | /src/test/java/TestSamples.java | 773b52108075b82162ecfad40accddca7223a173 | [] | no_license | Sathisha/RomanToDecimalValidateAndConvert | e1d972deead109f8c00e75fa0e37b4450371cd9f | bf84b7af04a694266fd050bee19bafdad12905c4 | refs/heads/master | 2020-03-27T00:51:35.461168 | 2018-08-22T06:20:09 | 2018-08-22T06:20:09 | 145,662,850 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 733 | java | import com.tw.merchant.roman.IntergalacticToRomanConverter;
import junit.framework.TestCase;
public class TestSamples extends TestCase {
IntergalacticToRomanConverter irc;
protected void setup() {
irc = new IntergalacticToRomanConverter();
irc.setCommodityCost(20);
irc.setCommodityName("Gold");
irc.getIntergalacticUnits().add("MM");
irc.getIntergalacticUnits().add("LL");
irc.getIntergalacticUnits().add("VV");
irc.getRomanDenomination().add("M");
irc.getRomanDenomination().add("L");
irc.getRomanDenomination().add("V");
}
public void testNumberConversion() {
setup();
assertTrue(irc.getDecimalValue() == 1055);
}
}
| [
"sathishachari@gmmail.com"
] | sathishachari@gmmail.com |
d038c2d6e605492154c29efbca883441212b8ffb | fbde03f7293a6390103b329a7236df0575a7f329 | /Word.java | 19a5acb0e5754e84aaf3da6ec2bf64fd37c196e7 | [] | no_license | CaseyChesshir/HaikuGenerator | 4d8ac597a7d96bf28ad40e21d94ab582c1f76931 | bc300a8fa633bfec29b9e8759a4418db60808ac8 | refs/heads/master | 2021-01-15T23:35:13.769807 | 2017-08-15T07:50:39 | 2017-08-15T07:50:39 | 30,612,446 | 0 | 0 | null | 2017-08-15T07:50:40 | 2015-02-10T20:15:46 | Java | UTF-8 | Java | false | false | 146 | java | public class Word{
public String w; // w = word
public int s; // s = syllables
public Word(String w, int s){
this.w = w;
this.s = s;
}
} | [
"casey.chesshir@me.com"
] | casey.chesshir@me.com |
732373ab0024aeb05a6ced0d6545c247b8b5ae0c | 0e123e17686e15d4cc1ecba319811cc1007f323b | /FitnessTracker/gen/com/example/fitnesstrackerproto/R.java | e36329a66e5e5c6405c28d4751b80427fedda2b4 | [] | no_license | alexis-stahlman/FitnessTracker | 4043fbf7a036f089b2e98f9006296cedecc793b9 | e69f5fd4f5780ff81ecf3f2036a98630a3eb945b | refs/heads/master | 2021-01-19T12:21:47.480641 | 2013-04-24T14:25:13 | 2013-04-24T14:25:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,421 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.fitnesstrackerproto;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int background=0x7f020000;
public static final int ic_launcher=0x7f020001;
public static final int point=0x7f020002;
public static final int splash=0x7f020003;
}
public static final class id {
public static final int Layout1=0x7f07001b;
public static final int Layout2=0x7f07001e;
public static final int Layout3=0x7f07001c;
public static final int Layout4=0x7f070024;
public static final int ListWorkout=0x7f070029;
public static final int addRunButton=0x7f07000d;
public static final int averageMPH=0x7f070006;
public static final int avgMPHEntry=0x7f070009;
public static final int backButton=0x7f07000b;
public static final int background=0x7f070000;
public static final int btn_add_update=0x7f07001f;
public static final int btn_addnew=0x7f070025;
public static final int btn_back=0x7f07001d;
public static final int btn_delete=0x7f070028;
public static final int btn_edit=0x7f070027;
public static final int calBurnedRan=0x7f070007;
public static final int calories=0x7f070019;
public static final int chronometer1=0x7f070012;
public static final int date=0x7f070017;
public static final int duration=0x7f070018;
public static final int edt_calories=0x7f070022;
public static final int edt_duration=0x7f070021;
public static final int edt_exercise=0x7f070020;
public static final int endRunButton=0x7f070010;
public static final int graph=0x7f070026;
public static final int layout_add_edit=0x7f07001a;
public static final int layout_item=0x7f070013;
public static final int layout_item_detail=0x7f070015;
public static final int layout_list=0x7f070023;
public static final int mainmenu=0x7f07002a;
public static final int mapview=0x7f070011;
public static final int menu_settings=0x7f07002c;
public static final int milesRan=0x7f070005;
public static final int milesRanEntry=0x7f07000c;
public static final int pauseRunButton=0x7f07000f;
public static final int rdb_select_item=0x7f070014;
public static final int runButton=0x7f070001;
public static final int runCalBurnedEntry=0x7f07000a;
public static final int runHeader=0x7f070003;
public static final int splash=0x7f07002b;
public static final int startRunButton=0x7f07000e;
public static final int timeRan=0x7f070004;
public static final int timeRanEntry=0x7f070008;
public static final int workout=0x7f070016;
public static final int workoutButton=0x7f070002;
}
public static final class layout {
public static final int activity_main_menu=0x7f030000;
public static final int activity_stats=0x7f030001;
public static final int activity_track_run=0x7f030002;
public static final int listitem=0x7f030003;
public static final int main=0x7f030004;
public static final int splash=0x7f030005;
}
public static final class menu {
public static final int activity_log_workout=0x7f060000;
public static final int activity_main_menu=0x7f060001;
public static final int activity_stats=0x7f060002;
public static final int activity_track_run=0x7f060003;
public static final int splash=0x7f060004;
}
public static final class string {
public static final int app_name=0x7f040000;
public static final int avg_mph=0x7f040015;
public static final int back=0x7f040001;
public static final int cal_burned=0x7f040016;
public static final int check_stats=0x7f040004;
public static final int end_run=0x7f040009;
public static final int enter_reps=0x7f04000e;
public static final int enter_workout=0x7f04000d;
public static final int exercise=0x7f040018;
public static final int hello_world=0x7f04000b;
public static final int log_workout=0x7f040003;
public static final int menu_settings=0x7f040005;
public static final int miles_ran=0x7f040014;
public static final int na=0x7f040011;
public static final int num_reps=0x7f040019;
public static final int pause_run=0x7f040008;
public static final int run=0x7f040012;
public static final int save_workout=0x7f04000f;
public static final int start_run=0x7f040007;
public static final int time_elapsed=0x7f04000a;
public static final int time_ran=0x7f040013;
/** LogWorkout Activity Strings
*/
public static final int title_activity_log_workout=0x7f04000c;
/** Stats Activity Strings
*/
public static final int title_activity_stats=0x7f040010;
/** TrackRun Activity Strings
*/
public static final int title_activity_track_run=0x7f040006;
public static final int total=0x7f04001a;
public static final int total_cal=0x7f04001b;
/** MainMenu Activity Strings
*/
public static final int track_run=0x7f040002;
public static final int workouts=0x7f040017;
}
public static final class style {
public static final int ActivityTheme=0x7f050001;
/**
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f050004;
public static final int Theme_Splash=0x7f050000;
public static final int Widget_AutoCompleteTextViewLight=0x7f050002;
public static final int Widget_DropDownItemLight=0x7f050003;
}
}
| [
"alexis.stahlman.10@cnu.edu"
] | alexis.stahlman.10@cnu.edu |
fc2e994b949cc097650607a6fe76afd130dc14a1 | b907f692c0cdd412a6c0d1c947196e0ecd1747bb | /springboot/kickstart-graphql/src/main/java/alvin/study/springboot/kickstart/app/api/schema/payload/DeleteOrgPayload.java | 2c62a70ff68f895dc965284990cd2a9a10e0bb12 | [] | no_license | alvin-qh/study-java | 64af09464325ab9de09cde6ce6240cf8d3e1653d | 63b9580f56575aa9d7b271756713a06c7e375c1a | refs/heads/master | 2023-08-22T05:53:39.790527 | 2023-08-20T16:06:11 | 2023-08-20T16:06:11 | 150,560,041 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 404 | java | package alvin.study.springboot.kickstart.app.api.schema.payload;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 删除组织实体的返回结果
*
* <p>
* 对应的 schema 参考 {@code classpath:graphql/org.graphqls} 文件内容
* </p>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DeleteOrgPayload {
private boolean deleted;
}
| [
"quhao317@163.com"
] | quhao317@163.com |
1189193dc7aeae1c0e3d30163171c3e6483aa402 | c0c59271e58938a1bf6074ae3779ded02c6407d5 | /src/main/java/com/example/reactappbackend/mapper/BoardMapper.java | 99b18215c65381cd3d1f826cfc873c2380609398 | [] | no_license | dbgusrb12/react-app-backend | dd160dd068670cbeab510475c830c55a28594d41 | dc28a950f4a3e3bec55121a6c67a5a6cff36a5b5 | refs/heads/master | 2023-02-05T02:25:17.813187 | 2020-12-24T08:36:03 | 2020-12-24T08:36:03 | 321,856,781 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 500 | java | package com.example.reactappbackend.mapper;
import com.example.reactappbackend.model.dto.Board;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface BoardMapper {
int boardListCount(Board board);
List<Board> boardList(Board board);
void insertBoard(Board board);
Board boardDetail(int boardId);
void updateBoard(Board board);
void deleteBoard(Integer boardId);
}
| [
"hg.yu@twolinecode.com"
] | hg.yu@twolinecode.com |
ad25f443f9960335a312452ea65292dbae4d4d58 | d4e5e650c4d82a9afd7e90b3cfbf4579c52d5043 | /MatZip/src/com/koreait/matzip/vo/RestaurantVO.java | 69f8662bd368c981318d8872738a81333ad77cfb | [] | no_license | DBhye/JSP | 00b45f32693405025d6028523bbf54b4d5439f6a | 6d5f48221db60749412a3b3a17086b823d9b4ab3 | refs/heads/master | 2022-12-16T18:03:45.509052 | 2020-09-16T08:50:01 | 2020-09-16T08:50:01 | 283,404,987 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,033 | java | package com.koreait.matzip.vo;
public class RestaurantVO {
private int i_rest;
private String nm;
private String addr;
private double lat;
private double lng;
private int cd_category;
private int i_user;
public int getI_rest() {
return i_rest;
}
public void setI_rest(int i_rest) {
this.i_rest = i_rest;
}
public String getNm() {
return nm;
}
public void setNm(String nm) {
this.nm = nm;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public int getCd_category() {
return cd_category;
}
public void setCd_category(int cd_category) {
this.cd_category = cd_category;
}
public int getI_user() {
return i_user;
}
public void setI_user(int i_user) {
this.i_user = i_user;
}
}
| [
"Administrator@DESKTOP-ISVFPRU"
] | Administrator@DESKTOP-ISVFPRU |
6a9769ab7f3b79192f2a104c6cba4c4c5e8ccd79 | f4642c2d9e07e993f0e076a8993a56a33b7c4883 | /app/src/main/java/com/joey/loanmarket/util/ToastUtil.java | 7d795560b65a2fd74588178de577d6c0ad797948 | [] | no_license | anzhuojinjie/FastMVP | ff7cfbb9fa808d54fbeac17bab196ffb530b7657 | 915540fa3870d2d689d13a3b2adbabe00f69008a | refs/heads/master | 2021-05-15T10:08:39.514113 | 2018-06-14T09:02:05 | 2018-06-14T09:02:05 | 108,235,652 | 6 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,682 | java | package com.joey.loanmarket.util;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.joey.loanmarket.R;
/**
* 创建时间: 2017/10/26.
* 创 建 人: joey.
* 功能描述:
*/
public class ToastUtil {
private Context mContext;
private static ToastUtil mInstance;
private Toast mToast;
private TYPE type = TYPE.TYPE_WARING;
private TextView mTextView;
private enum TYPE {
TYPE_OK, TYPE_WARING, TYPE_COLLECT, TYPE_CANCEL_COLLECT;
}
public static ToastUtil getInstance() {
return mInstance;
}
public static void initialize(Context ctx) {
mInstance = new ToastUtil(ctx);
}
private ToastUtil(Context ctx) {
mContext = ctx;
}
public void showToast(String text) {
if (mToast == null) {
mToast = Toast.makeText(mContext, text, Toast.LENGTH_SHORT);
View view = View.inflate(mContext, R.layout.view_toast, null);
mTextView = (TextView) view.findViewById(android.R.id.message);
mToast.setView(view);
}
mToast.setText(text);
int yOffset = 0;
int xOffset = 0;
View view = mToast.getView();
int width = 0;
int height = 0;
view.measure(0, 0);
width = view.getMeasuredWidth();
height = view.getMeasuredHeight();
int imageId = R.mipmap.ic_waring;
//根据type设置图片
switch (type) {
case TYPE_WARING:
imageId = R.mipmap.ic_waring;
break;
}
Drawable drawable = mContext.getResources().getDrawable(imageId);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
mTextView.setCompoundDrawables(null, drawable, null, null);
xOffset = (mContext.getResources().getDisplayMetrics().widthPixels - width) / 2;
yOffset = (mContext.getResources().getDisplayMetrics().heightPixels - height) / 2;
mToast.setGravity(Gravity.TOP | Gravity.LEFT, xOffset, yOffset);
mToast.show();
//还原为默认type
type = TYPE.TYPE_WARING;
}
public ToastUtil ok() {
type = TYPE.TYPE_OK;
return this;
}
public ToastUtil collect() {
type = TYPE.TYPE_COLLECT;
return this;
}
public ToastUtil cancelCollect() {
type = TYPE.TYPE_CANCEL_COLLECT;
return this;
}
public void cancelToast() {
if (mToast != null) {
mToast.cancel();
}
}
}
| [
"963893628@qq.com"
] | 963893628@qq.com |
9c9831cfff28239aad6634ecd8bdd96f07ee53c1 | 7d8e43ea868d794f022359ae3c5eee82ad188f88 | /MeetQuickly/app/src/main/java/com/andy/meetquickly/activity/user/OrderComplaintActivity.java | 566c28f9877b868cb5e91d08e0c0417781ee971b | [] | no_license | wananxin/MeetQuickly | d268ad34e1b5c868f6ba13d0883f455efe924012 | 31c0d39e5adad6623468193c2f37dd5c77777112 | refs/heads/master | 2020-07-26T16:14:40.621736 | 2019-09-16T03:46:39 | 2019-09-16T03:46:39 | 208,700,667 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,862 | java | package com.andy.meetquickly.activity.user;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.andy.meetquickly.R;
import com.andy.meetquickly.base.BaseActivity;
import com.andy.meetquickly.bean.UserBean;
import com.andy.meetquickly.cache.UserCache;
import com.andy.meetquickly.http.MQApi;
import com.andy.meetquickly.http.MyApiResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.vondear.rxtool.view.RxToast;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class OrderComplaintActivity extends BaseActivity {
@BindView(R.id.radioButton1)
RadioButton radioButton1;
@BindView(R.id.radioButton2)
RadioButton radioButton2;
@BindView(R.id.radioButton3)
RadioButton radioButton3;
@BindView(R.id.et_content)
EditText etContent;
@BindView(R.id.tv_et_numb)
TextView tvEtNumb;
@BindView(R.id.tv_submit)
TextView tvSubmit;
@BindView(R.id.radioGroup)
RadioGroup radioGroup;
String storeId;
String orderId;
UserBean userBean;
@Override
public int getLayoutId() {
return R.layout.activity_order_complaint;
}
@Override
public void initView() {
setBarTitle("投诉");
userBean = UserCache.getInstance().getUser();
storeId = this.getIntent().getStringExtra("storeId");
orderId = this.getIntent().getStringExtra("orderId");
}
@Override
public void initData() {
}
public static void start(Context context, String storeId, String orderId) {
Intent starter = new Intent(context, OrderComplaintActivity.class);
starter.putExtra("storeId", storeId);
starter.putExtra("orderId", orderId);
context.startActivity(starter);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: add setContentView(...) invocation
ButterKnife.bind(this);
}
@OnClick(R.id.tv_submit)
public void onViewClicked() {
if (!(radioButton1.isChecked() || radioButton2.isChecked() || radioButton3.isChecked())) {
RxToast.showToast("请选择投诉内容");
return;
}
String content;
if (radioButton1.isChecked()) {
content = radioButton1.getText().toString();
} else if (radioButton2.isChecked()) {
content = radioButton2.getText().toString();
} else {
content = radioButton3.getText().toString();
}
showWaitDialog((Activity) mContext);
MQApi.userComplainOrder(userBean.getUId(), storeId, orderId, content, etContent.getText().toString(), new SimpleCallBack<String>() {
@Override
public void onError(ApiException e) {
dissmissWaitDialog();
RxToast.showToast(e.toString());
}
@Override
public void onSuccess(String s) {
dissmissWaitDialog();
MyApiResult myApiResult =
new Gson().fromJson(s, new TypeToken<MyApiResult>() {
}.getType());
// JSON.parseObject(s,new MyApiResult<String>().getClass());
if (myApiResult.isOk()) {
RxToast.showToast("投诉成功");
finish();
} else {
RxToast.showToast(myApiResult.getMsg());
}
}
});
}
}
| [
"your email"
] | your email |
2b5f46a7ea563acaae5c509b9b026324ab1fed70 | dfea4a8aa5ca508721bfdd569286857e6dbdbbf0 | /src/io/codementor/vetting/ideapool/database/UserCRUD.java | 606d692dab36c6d4867bb9a9d83f0765bd815a9f | [] | no_license | krishna366/MyIdeaPool | 607b19c743726a000b65a21f6024479251e3924f | ff8ac588f78a168f48a8c174ae0d66754416add9 | refs/heads/master | 2020-04-10T19:28:01.372006 | 2019-12-22T18:46:05 | 2019-12-22T18:46:05 | 161,236,233 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,603 | java | package io.codementor.vetting.ideapool.database;
import org.sql2o.Connection;
import io.codementor.vetting.ideapool.model.User;
public class UserCRUD extends AbstractCRUD{
private final static String SQL_INSERT = "INSERT INTO `ideapool`.`users` (`name`,`email`,`password`,`avatar_url`,`refresh_token`) " +
" VALUES(:name,:email,:password,:avatarUrl,:refreshToken)";
private final static String SQL_UPDATE = "UPDATE `ideapool`.`users` SET `refresh_token` = :refreshToken,"+
"last_modified_at = CURRENT_TIMESTAMP()"+
"WHERE id = :id";
private final static String SQL_SELECT_SINGLE = "SELECT id,name,email,avatar_url,refresh_token FROM `ideapool`.`users` "+
"WHERE id = :id";
private final static String SQL_SELECT_VALIDATE = "SELECT id,name,email,avatar_url,refresh_token FROM `ideapool`.`users` "+
"WHERE email = :email and password = :password";
private final static String SQL_SELECT_RT = "SELECT id,name,email,avatar_url,refresh_token FROM `ideapool`.`users` "+
"WHERE refresh_token = :refreshToken";
private final static String SQL_SELECT_VALIDATE2 = "SELECT id,name,email,avatar_url,refresh_token FROM `ideapool`.`users` "+
"WHERE email = :email";
public static String createUser(String name,String email,String password,String avatarUrl,String refreshToken) {
Connection connection = getOpenedConnection();
try{
Object insertedId = connection.createQuery(SQL_INSERT, true)
.addParameter("name", name)
.addParameter("email", email )
.addParameter("password", password)
.addParameter("avatarUrl",avatarUrl)
.addParameter("refreshToken", refreshToken)
.executeUpdate()
.getKey();
//connection.commit();
return insertedId.toString();
} finally {
connection.close();
}
}
public static String updateUser(String id,String refreshToken) {
Connection connection = getOpenedConnection();
try{
Object insertedId = connection.createQuery(SQL_UPDATE, true)
.addParameter("id", Integer.parseInt(id))
.addParameter("refreshToken", refreshToken )
.executeUpdate()
.getKey();
// connection.commit();
//return insertedId.toString();
return id;
} finally {
connection.close();
}
}
public static User getUserFromId(String id) {
Connection connection = getOpenedConnection();
try {
User u = connection.createQuery(SQL_SELECT_SINGLE)
.addParameter("id", id)
.executeAndFetchFirst(User.class);
return u;
} finally {
connection.close();
}
}
public static User getUserFromRefreshToken(String refreshToken) {
Connection connection = getOpenedConnection();
try {
User u = connection.createQuery(SQL_SELECT_RT)
.addParameter("refreshToken", refreshToken)
.executeAndFetchFirst(User.class);
return u;
} finally {
connection.close();
}
}
public static User getUserFromEmailPassword(String email,String password) {
Connection connection = getOpenedConnection();
try {
User u = connection.createQuery(SQL_SELECT_VALIDATE)
.addParameter("email", email)
.addParameter("password", password)
.executeAndFetchFirst(User.class);
return u;
} finally {
connection.close();
}
}
public static User getUserFromEmail(String email) {
Connection connection = getOpenedConnection();
try {
User u = connection.createQuery(SQL_SELECT_VALIDATE2)
.addParameter("email", email)
.executeAndFetchFirst(User.class);
return u;
} finally {
connection.close();
}
}
public static void main(String[] args) {
String id = UserCRUD.createUser("krishna", "k@k.com", "md5", "url1","rt1");
User u1 = UserCRUD.getUserFromEmail("k@k.com");
System.out.println("u1 = "+u1);
/*
id = UserCRUD.updateUser(id,"rt2");
System.out.println("id = "+id);
User u1 = UserCRUD.getUserFromId(id);
System.out.println("u1 = "+u1);
User u2 = UserCRUD.getUserFromRefreshToken("rt2");
System.out.println("u2 = "+u2);
User u3 = UserCRUD.getUserFromEmailPassword("k@k.com", "md5");
System.out.println("u3 = "+u3);
*/
}
}
| [
"40491935+kchaitanya-uis@users.noreply.github.com"
] | 40491935+kchaitanya-uis@users.noreply.github.com |
7ebcbb74b78e985814a74bca75ee8be6ee89ac3d | 779b2bcc2a11198f9e4338ffe3a873ae6deff335 | /src/downloader/DownloadRunner.java | 9bdd449890f26d08672349bee427f56e50fb5ee8 | [] | no_license | ahmetkucuk/QueryHEKPlus | 1f40b93d8ffcba7a16f6201d71722e33885b6ec5 | 111b00b2a5aec58fea96d6026359d590a365e412 | refs/heads/master | 2021-01-10T14:53:53.149953 | 2015-10-30T02:58:56 | 2015-10-30T02:58:56 | 44,856,278 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 679 | java | package src.downloader;
/**
* Created by ahmetkucuk on 24/10/15.
*/
public class DownloadRunner {
static final String INPUT_FILE = "/Users/ahmetkucuk/Documents/GEORGIA_STATE/COURSES/Database_Systems/Project/image_downloader/SG_Records_Sample.txt";
static final String OUTPUT_DIR = "/Users/ahmetkucuk/Documents/GEORGIA_STATE/COURSES/Database_Systems/Project/image_downloader/images/";
static final String[] imageUrlAttributes = new String[]{"ref_url_1", "gs_imageurl"};
static final int waitBetween = 0;
public static void main(String[] args) {
new DownloadFromFeatures(INPUT_FILE, OUTPUT_DIR, imageUrlAttributes, 10, waitBetween).run();
}
}
| [
"ahmetkucuk92@gmail.com"
] | ahmetkucuk92@gmail.com |
a4d72aa4cd0fa45668f9820e858bb75a8af7aa91 | 124cbf33d1c30974183d3b66aac76c5d754e96ef | /Godzilla/src/main/java/com/godzilla/config/SpringWebConfig.java | 3fb883683359a5342c42e3b7e67115fe5f43a896 | [] | no_license | ivaninDarpatov/jira-0.02 | f20437c337ae6a06b24cbdc1b2b5c9531f123df0 | 9e800648dd88c1bd20be8d37bc27229583bac946 | refs/heads/master | 2021-01-11T18:17:43.416131 | 2016-10-17T06:57:22 | 2016-10-17T06:57:22 | 69,336,672 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,598 | java | package com.godzilla.config;
import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
@ComponentScan("com.godzilla")
public class SpringWebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/static/css/");
registry.addResourceHandler("/pdfs/**").addResourceLocations("/static/pdf/");
registry.addResourceHandler("/images/**").addResourceLocations("/static/images/");
registry.addResourceHandler("/fonts/**").addResourceLocations("/static/fonts/");
registry.addResourceHandler("/js/**").addResourceLocations("/static/js/");
}
@Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
// localization configuration
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver resolver = new SessionLocaleResolver();
resolver.setDefaultLocale(Locale.ENGLISH);
return resolver;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor changeInterceptor = new LocaleChangeInterceptor();
changeInterceptor.setParamName("language");
registry.addInterceptor(changeInterceptor);
}
}
| [
"ivanin.darpatov@gmail.com"
] | ivanin.darpatov@gmail.com |
501545560056b396686cb4f0217b1b245e7fa86a | 390e97b951f9fc2a58d94dcd4db3f0026b9be50d | /ferry_loading_3.java | 6367baf13fc3d4e676432c73b4718efa8fffd5bf | [] | no_license | abarna29/uva | 1c20ae552773d69e07ef625a4880f5578c7afcd7 | 88a5ced49c2497dd912f16be32a6a449c0c5b9ae | refs/heads/master | 2020-04-24T10:32:43.112131 | 2019-05-22T10:47:49 | 2019-05-22T10:47:49 | 171,897,321 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,824 | java | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int tc = in.nextInt();
while (tc-- > 0) {
int n = in.nextInt(),t = in.nextInt(),m = in.nextInt();
Queue<Car> q = new ArrayDeque<Car>();
for (int i = 0; i < m; i++) {
int arr=in.nextInt();
String side=in.next();
q.add(new Car(i, arr, side));
}
boolean l=true;
int time=0;
int result[]=new int[m];
while (!q.isEmpty()) {
Car c=q.peek();
int x=c.arr;
if (c.side==l)
{
int load=0;
Queue<Car>q2=new ArrayDeque<Car>();
while (!q.isEmpty())
{
c=q.poll();
if (c.arr<=time && c.side==l && load<n)
{
result[c.lno]=time+t;
load++;
}
else
q2.add(c);
}
q.addAll(q2);
if (load > 0)
{
l= !l;
time += t;
}
else
time = x;
}
else
{
int load = 0;
Queue<Car> q2 = new ArrayDeque<Car>();
while (!q.isEmpty())
{
c= q.poll();
if (c.arr <= time && c.side == l && load < n)
{
result[c.lno] = time + t;
load++;
}
else
q2.add(c);
}
q.addAll(q2);
l = !l;
if (x > time)
x -= time;
else
x = 0;
time += x + t;
}
}
for (int i = 0; i < m; i++)
System.out.println(result[i]);
if (tc > 0)
System.out.println();
}
}
static class Car
{
int arr, lno;
boolean side;
public Car(int i, int arr, String side)
{
lno= i;
this.arr = arr;
this.side =side.equals("left") ? true : false;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
53424be2ead07d89b96d7673d1efe08937b59c8f | 4b32d291155d6b5d075911714e58929bdb40f56c | /app/src/main/java/com/android/jwjy/wtjyproduct/ModelSimpleMonthView.java | bc2c8669f9cbc9517cd4fc6b9b77801ad40b4f0c | [] | no_license | ValerXu/WTJYProduct | be3fe8ae4402ed9581109099e1bdb7e6e1fc1f1c | d6c18ff82b93ee01e08c73988831ea19fbb4c9cd | refs/heads/master | 2022-12-13T02:49:07.710970 | 2020-09-10T07:49:56 | 2020-09-10T07:49:56 | 293,687,523 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,519 | java | package com.android.jwjy.wtjyproduct;
import android.content.Context;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.MonthView;
/**
* 高仿魅族日历布局
* Created by huanghaibin on 2017/11/15.
*/
public class ModelSimpleMonthView extends MonthView {
private int mRadius;
public ModelSimpleMonthView(Context context) {
super(context);
//兼容硬件加速无效的代码
setLayerType(View.LAYER_TYPE_SOFTWARE,mSelectedPaint);
//4.0以上硬件加速会导致无效
mSelectedPaint.setMaskFilter(new BlurMaskFilter(25, BlurMaskFilter.Blur.SOLID));
}
@Override
protected void onPreviewHook() {
mRadius = Math.min(mItemWidth, mItemHeight) / 5 * 2;
mSchemePaint.setStyle(Paint.Style.STROKE);
}
@Override
protected void onLoopStart(int x, int y) {
}
@Override
protected boolean onDrawSelected(Canvas canvas, Calendar calendar, int x, int y, boolean hasScheme) {
int cx = x + mItemWidth / 2;
int cy = y + mItemHeight / 2;
canvas.drawCircle(cx, cy, mRadius, mSelectedPaint);
return false;
}
@Override
protected void onDrawScheme(Canvas canvas, Calendar calendar, int x, int y) {
int cx = x + mItemWidth / 2;
int cy = y + mItemHeight / 2;
canvas.drawCircle(cx, cy, mRadius, mSchemePaint);
}
@Override
protected void onDrawText(Canvas canvas, Calendar calendar, int x, int y, boolean hasScheme, boolean isSelected) {
float baselineY = mTextBaseLine + y;
int cx = x + mItemWidth / 2;
if (isSelected) {
canvas.drawText(String.valueOf(calendar.getDay()),
cx,
baselineY,
mSelectTextPaint);
} else if (hasScheme) {
canvas.drawText(String.valueOf(calendar.getDay()),
cx,
baselineY,
calendar.isCurrentDay() ? mCurDayTextPaint :
calendar.isCurrentMonth() ? mSchemeTextPaint : mOtherMonthTextPaint);
} else {
canvas.drawText(String.valueOf(calendar.getDay()), cx, baselineY,
calendar.isCurrentDay() ? mCurDayTextPaint :
calendar.isCurrentMonth() ? mCurMonthTextPaint : mOtherMonthTextPaint);
}
}
}
| [
"1345418440@qq.com"
] | 1345418440@qq.com |
4c2add852380b912f57acf016ab7aeeb7e2b8c36 | 2d27b4d2aca7f590485f914a6fae6e979338a951 | /src/logic/predicates/ClassPredicate.java | dd4d0c144766bc2eeec7232ac40610ad34a41bb6 | [] | no_license | dafrito/Riviera | af71c4b40cafed972e6d8c21d87fab42684284bb | 1de0336961b78fde5593645c45e5077cbb49f773 | refs/heads/master | 2021-12-01T01:57:46.068373 | 2021-11-16T13:39:07 | 2021-11-16T13:40:31 | 674,718 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 987 | java | /**
*
*/
package logic.predicates;
import logic.adapters.Adapters;
/**
* Test whether given objects are of a specified type.
*
* @author Aaron Faanes
* @see Adapters#type()
*/
public class ClassPredicate implements Predicate<Object> {
private final Class<?> type;
public ClassPredicate(final Class<?> type) {
this.type = type;
}
public Class<?> getType() {
return type;
}
@Override
public boolean test(Object candidate) {
if (candidate == null) {
return false;
}
return this.type.isInstance(candidate);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof ClassPredicate)) {
return false;
}
ClassPredicate other = (ClassPredicate) obj;
return this.getType().equals(other.getType());
}
@Override
public int hashCode() {
return 31 * 17 + this.getType().hashCode();
}
@Override
public String toString() {
return String.format("ClassPredicate[%s]", this.getType());
}
}
| [
"dafrito@gmail.com"
] | dafrito@gmail.com |
844e9501630ecc6b37bc46ff7dc65353aaf75e83 | e77580e64bcfa2ab1e603faabb637c919955770b | /network/src/main/java/com/mayforever/network/newtcp/TCPServer.java | 4650d64b9615844f857529f14f81fa730184b6f4 | [] | no_license | mayforever/JavaTools | 7f555ba941b944c857232714b9e160a1faf85d9a | 164ddf9e47c51cc9d545c5a908106e509ac5510f | refs/heads/master | 2022-12-25T19:49:45.488317 | 2019-09-26T01:07:57 | 2019-09-26T01:07:57 | 106,786,043 | 0 | 0 | null | 2020-10-13T06:55:11 | 2017-10-13T06:22:40 | Java | UTF-8 | Java | false | false | 2,447 | java | package com.mayforever.network.newtcp;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
public class TCPServer {
private ServerListener listener_=null;
private AsynchronousServerSocketChannel asynchronousServerSocketChannel=null;
private int port_=0;
private String host_="";
private CHForTCPServer chForTcpServer = null;
public TCPServer(int port, String host){
// kids stop constructing
this.port_=port;
if(host != null){
this.host_=host;
}else{
this.host_ = "127.0.0.1";
}
chForTcpServer = new CHForTCPServer();
}
public void addListener(ServerListener listener){
if (listener != null){
// server listener initiating
// this listener is an self create interface
this.listener_=listener;
try {
// initializing asynchronous server
asynchronousServerSocketChannel = AsynchronousServerSocketChannel
.open();
// declare and initialize inetSocketAddress of the server
InetSocketAddress sAddr = new InetSocketAddress(this.host_, this.port_);
// bind the inetSocketAddress
asynchronousServerSocketChannel.bind(sAddr);
// ready the server to accept
asynchronousServerSocketChannel.accept(this.asynchronousServerSocketChannel, chForTcpServer);
} catch (IOException e1) {
this.listener_.socketError(e1);
}
}else{
// throws null pointer exception for listener
this.listener_.socketError(new NullPointerException());
}
}
public void stopListenning(){
try {
// closing socket
this.asynchronousServerSocketChannel.close();
} catch (Exception e) {
this.listener_.socketError(e);
}
}
// Hide the completed/failed
private class CHForTCPServer implements CompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel>{
public void completed(AsynchronousSocketChannel client, AsynchronousServerSocketChannel serverSocket) {
// initializing client socket
listener_.acceptSocket(client);
// ready the server to accept again
serverSocket.accept(serverSocket, this);
}
public void failed(Throwable exc, AsynchronousServerSocketChannel attachment) {
listener_.socketError((Exception)exc);
}
}
}
| [
"chonggomuvalencia@gmail.com"
] | chonggomuvalencia@gmail.com |
f93bcde03600b15c333e4275c8736bb6f6434d67 | 8ec089d0523b889e3424e0ce863f34d38332e585 | /CursoDioRestfullApp/restfull/src/main/java/digitalinnovation/exemplo/restfull/RestfullApplication.java | ca476a8625c9b488ad5d52cedd640db4eaafe126 | [] | no_license | sdias-code/digitalinnovationone | 0ecd88084b1a81ad157967d65c5936b56874f15a | 61c25f6695be06d0ce1f6234ec8948d0716c204f | refs/heads/master | 2022-11-10T21:13:20.039358 | 2020-07-06T04:40:25 | 2020-07-06T04:40:25 | 268,190,833 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 331 | java | package digitalinnovation.exemplo.restfull;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RestfullApplication {
public static void main(String[] args) {
SpringApplication.run(RestfullApplication.class, args);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
4d201aa3d8470c33d48f6784b0a79fdf00ef7ad2 | faea3406a16eae25d99aadc6bf7a950e59d4c240 | /bol14/Bol14.java | cd4316de74a8d16a686df3415ce21f23abb7bc63 | [] | no_license | DanielOuteda/Bol14 | 318016388cb8eeb6022641d3d2bf6c60f567cbe0 | 64129891b0d86dea169f0b0b12bd6b9ccbc44f40 | refs/heads/master | 2020-12-11T08:15:29.058037 | 2020-01-14T08:55:22 | 2020-01-14T08:55:22 | 233,797,933 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 981 | 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 bol14;
import java.util.Scanner;
/**
*
* @author doutedasolla
*/
public class Bol14 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ConversorTemperaturas obx = new ConversorTemperaturas();
System.out.println("Escribe la temperatura");
float gCentigrados = sc.nextFloat();
try {
obx.centigradosAFharenheit(gCentigrados);
} catch (TemperaturaErradaExcepcion ex) {
System.out.println("Error1 " + ex.toString());
}
try {
obx.centígradosAReamur(gCentigrados);
} catch (TemperaturaErradaExcepcion ex) {
System.out.println("Error2 " + ex.toString());
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
765c56096a14a28f8e7b122cae4e4fa87eae35c6 | c823f44bf9ac99d49225cf3760898c591981feb0 | /s1_eventos-api/src/test/java/co/edu/uniandes/csw/eventos/tests/postman/FacturaIT.java | 26bfb1e68250024735bf4bf1743ced85a6e8b19e | [
"MIT"
] | permissive | Uniandes-ISIS2603-backup/s1_Eventos_201910 | 75e807ded07b1e69ccce0ae4da1796b3188f7a4b | ef217517adabfd08ab51dcd724c2b806a363cfd3 | refs/heads/master | 2020-04-18T15:46:42.115404 | 2019-05-22T04:41:02 | 2019-05-22T04:41:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,366 | 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 co.edu.uniandes.csw.eventos.tests.postman;
import co.edu.uniandes.csw.eventos.dtos.FacturaDTO;
import co.edu.uniandes.csw.eventos.mappers.BusinessLogicExceptionMapper;
import co.edu.uniandes.csw.eventos.resources.FacturaResource;
import co.edu.uniandes.csw.postman.tests.PostmanTestBuilder;
import java.io.File;
import java.io.IOException;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
*
* @author Paula Molina Ruiz
*/
@RunWith(Arquillian.class)
public class FacturaIT {
private static final String COLLECTION = "Factura-Tests.postman_collection";
@Deployment(testable = true)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, "s1_eventos-api.war")//War del modulo api
// Se agrega las dependencias
.addAsLibraries(Maven.resolver().loadPomFromFile("pom.xml")
.importRuntimeDependencies().resolve()
.withTransitivity().asFile())
// Se agregan los compilados de los paquetes de servicios
.addPackage(FacturaResource.class.getPackage()) //No importa cual recurso usar, lo importante es agregar el paquet
.addPackage(FacturaDTO.class.getPackage()) //No importa cual dto usar, lo importante es agregar el paquete.
.addPackage(BusinessLogicExceptionMapper.class.getPackage())
// El archivo que contiene la configuracion a la base de datos.
.addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml")
// El archivo beans.xml es necesario para injeccion de dependencias.
.addAsWebInfResource(new File("src/main/webapp/WEB-INF/beans.xml"))
// El archivo web.xml es necesario para el despliegue de los servlets
.setWebXML(new File("src/main/webapp/WEB-INF/web.xml"))
.addAsWebInfResource(new File("src/main/webapp/WEB-INF/glassfish-resources.xml"));
}
@Test
@RunAsClient
public void postman() throws IOException {
PostmanTestBuilder tp = new PostmanTestBuilder();
tp.setTestWithoutLogin(COLLECTION, "Entorno-IT.postman_environment");
String desiredResult = "0";
Assert.assertEquals("Error en Iterations de: " + COLLECTION, desiredResult, tp.getIterations_failed());
Assert.assertEquals("Error en Requests de: " + COLLECTION, desiredResult, tp.getRequests_failed());
desiredResult = "3";
Assert.assertEquals("Error en Test-Scripts de: " + COLLECTION, desiredResult, tp.getTest_scripts_failed());
desiredResult = "0";
Assert.assertEquals("Error en Assertions de: " + COLLECTION, desiredResult, tp.getAssertions_failed());
}
}
| [
"pa.molina@uniandes.edu.co"
] | pa.molina@uniandes.edu.co |
90e118f8b4221813db9ee4680c53d483cec18b6b | 05fea25bdf762e0f8e87be6864696f4afafc1903 | /yycg_sys/src/main/java/yycg/base/dao/mapper/DictinfoMapper.java | b8052308c24df38041cd5e5e79dd56c280401655 | [] | no_license | yt1090063761/yycg_system | 43a702ae2890c1b8664c69ef3c7b7a016be080db | 9e52e7500b3043fe64b7fb8b1fd65bd492247bca | refs/heads/master | 2022-12-22T23:06:46.071391 | 2019-11-16T12:17:42 | 2019-11-16T12:17:42 | 222,093,512 | 0 | 0 | null | 2022-12-16T00:37:53 | 2019-11-16T12:06:14 | JavaScript | UTF-8 | Java | false | false | 847 | java | package yycg.base.dao.mapper;
import org.apache.ibatis.annotations.Param;
import yycg.base.pojo.Dictinfo;
import yycg.base.pojo.DictinfoExample;
import java.util.List;
public interface DictinfoMapper {
long countByExample(DictinfoExample example);
int deleteByExample(DictinfoExample example);
int deleteByPrimaryKey(String id);
int insert(Dictinfo record);
int insertSelective(Dictinfo record);
List<Dictinfo> selectByExample(DictinfoExample example);
Dictinfo selectByPrimaryKey(String id);
int updateByExampleSelective(@Param("record") Dictinfo record, @Param("example") DictinfoExample example);
int updateByExample(@Param("record") Dictinfo record, @Param("example") DictinfoExample example);
int updateByPrimaryKeySelective(Dictinfo record);
int updateByPrimaryKey(Dictinfo record);
} | [
"1090063761@qq.com"
] | 1090063761@qq.com |
67e47d4a824c8e71eeccb32df275ab80eb3003d4 | 96f9bac9891c89fe51b0a79de7ae7080f88f306e | /src/main/java/visitor/version4/Client.java | df2716269f199f79d38739226ceea984b46780ee | [] | no_license | xudesan33/grinding-design-pattern | dc510ef6686eea181a0c96ad9f32747e02481b6b | 5689cce027a3fb1bd4f3469ba0ac5969b0e8beb2 | refs/heads/master | 2023-05-08T02:00:37.711044 | 2021-06-02T11:05:20 | 2021-06-02T11:05:20 | 373,138,212 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,021 | java | package visitor.version4;
public class Client {
public static void main(String[] args) {
// 创建ObjectStruct
ObjectStructure os = new ObjectStructure();
// 准备点测试数据,创建客户对象,并加入ObjectStructure
Customer cm1 = new EnterpriseCustomer();
cm1.setName("ABC集团");
os.addElement(cm1);
Customer cm2 = new EnterpriseCustomer();
cm2.setName("CDE公司");
os.addElement(cm2);
Customer cm3 = new PersonalCustomer();
cm3.setName("张三");
os.addElement(cm3);
// 客户提出服务请求,传入服务请求的Visitor
ServiceRequestVisitor srVisitor = new ServiceRequestVisitor();
os.handleRequest(srVisitor);
// 要对客户进行偏好分析,传入偏好分析的Visitor
PredilectionAnalyzeVisitor paVisitor = new PredilectionAnalyzeVisitor();
os.handleRequest(paVisitor);
// 要对客户进行价值分析,传入价值分析的Visitor
WorthAnalyzeVisitor waVisitor = new WorthAnalyzeVisitor();
os.handleRequest(waVisitor);
}
} | [
"sander-xu@zamplus.com"
] | sander-xu@zamplus.com |
c47a47d3c312a64e0a8da0d0b1316bbad0cb5f34 | bf2cbb7b1185e65015c692bd8c18d6f8e1351c83 | /src/cn/edu/neu/model/Color.java | a0a74eda3a487327c2cc8f2f2129186f4e713310 | [] | no_license | believeMeYes/Shopping | dac428e3f2a507e6a9e1699bf24aacfe5ef5e9e0 | 4924440b5b96a59b9c2743b715523ae62c4f48c5 | refs/heads/master | 2021-06-22T09:01:46.385363 | 2017-08-15T04:45:41 | 2017-08-15T04:45:41 | 100,339,145 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,116 | java | package cn.edu.neu.model;
import java.util.List;
public class Color {
private int colorId;
private String colorName;
private List<Goods> goods;
public Color() {
super();
// TODO Auto-generated constructor stub
}
public Color(int colorId, String colorName, List<Goods> goods) {
super();
this.colorId = colorId;
this.colorName = colorName;
this.goods = goods;
}
public int getColorId() {
return colorId;
}
public void setColorId(int colorId) {
this.colorId = colorId;
}
public String getColorName() {
return colorName;
}
public void setColorName(String colorName) {
this.colorName = colorName;
}
public List<Goods> getGoods() {
return goods;
}
public void setGoods(List<Goods> goods) {
this.goods = goods;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(obj instanceof Color){
if(((Color) obj).getColorId()==this.getColorId())
return true;
}
return super.equals(obj);
}
@Override
public String toString() {
return "Color [colorId=" + colorId + ", colorName=" + colorName + ", goods=" + goods + "]";
}
}
| [
"993094738@qq.com"
] | 993094738@qq.com |
2adc00812f5930ea477d2f2ac417a19c4f7e4cdc | b2851ba8660d12d7459d935b050ab74332510223 | /core/src/com/bubbledone/main/TouchHandler.java | 03a184a80c619248cff086f9ed53e4a75576baad | [] | no_license | pato/bubbledone | 3a7c851bd8e6fff94ba5867ad02e4d6a153e674c | d987a05f1c7ef92855877e03fdfd59f8e4b7de32 | refs/heads/master | 2021-01-25T05:57:50.320558 | 2014-10-19T15:10:34 | 2014-10-19T15:10:34 | 25,403,230 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,707 | java | package com.bubbledone.main;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.input.GestureDetector.GestureListener;
import com.badlogic.gdx.math.Circle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.bubbledone.ui.CreateButton;
public class TouchHandler implements GestureListener {
private BubbleWorld world;
private OrthographicCamera cam;
private long last_tap;
private TaskBubble last;
public TouchHandler(BubbleWorld world, OrthographicCamera cam) {
this.world = world;
this.cam = cam;
}
@Override
public boolean touchDown(float x, float y, int pointer, int button) {
return false;
}
@Override
public boolean tap(float x, float y, int count, int button) {
// double tap handler
if (count < 2) return false;
Vector3 coords = cam.unproject(new Vector3(x, y, 0));
TaskBubble task = null;
for (TaskBubble t : world.getBubbles()) {
if (new Circle(t.getPosition(), t.getRadius()).contains(new Vector2(coords.x, coords.y))) {
task = t;
}
}
if (task == null) {
System.out.println("no match found");
return false;
}
return true;
}
@Override
public boolean longPress(float x, float y) {
// long press gets info
System.out.println("LONG TAP");
Vector3 coords = cam.unproject(new Vector3(x, y, 0));
// if you pressed the create button
CreateButton btn = world.getCreateButton();
if (new Circle(btn.getX(), btn.getY(), btn.getRadius()).contains(new Vector2(coords.x, coords.y))) {
world.newBubble();
}
// or if you pressed on a new bubble
TaskBubble task = null;
for (TaskBubble t : world.getBubbles()) {
if (new Circle(t.getPosition(), t.getRadius()).contains(new Vector2(coords.x, coords.y))) {
task = t;
}
}
if (task == null) {
System.out.println("no match found");
return false;
}
world.getBubbleInfoPopup().setTaskBubble(task);
world.getBubbleInfoPopup().display();
world.getCreateButton().hide();
return true;
}
@Override
public boolean fling(float velocityX, float velocityY, int button) {
return false;
}
@Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean panStop(float x, float y, int pointer, int button) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean zoom(float initialDistance, float distance) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2,
Vector2 pointer1, Vector2 pointer2) {
// TODO Auto-generated method stub
return false;
}
}
| [
"rohan@cs.utexas.edu"
] | rohan@cs.utexas.edu |
403900f65c9b1205c092a58d441cb8a005cdbaed | 07adce993d4c32135b42720ec4ab3a5d0e07e25a | /src/main/java/ncku/pd2final/Final/tower/DealWithBlood.java | 605140cfc7978e5d0f73e0bdd483869b21df69d8 | [] | no_license | secminhr/PD2-Final-backend | 7ff6fce6b3addfd90bb5bfab31e7fd18710e422d | 7eb5da1fc2160df296d1761df67651aac72053ff | refs/heads/master | 2023-05-12T20:48:15.656439 | 2021-06-07T13:22:04 | 2021-06-07T13:22:04 | 358,000,330 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 694 | java | package ncku.pd2final.Final.tower;
import java.util.Arrays;
import java.util.TimerTask;
public class DealWithBlood extends TimerTask {
private final CalculateBlood cal ;
private final int attackPoints;
private final double[][] purpose;
private final int time;
public DealWithBlood(CalculateBlood cal, int attackPoints, double[][] purpose, int time) {
this.cal = cal;
this.attackPoints = attackPoints;
this.purpose = Arrays.stream(purpose).map(double[]::clone).toArray(double[][]::new);
this.time = time;
}
@Override
public void run() {
System.out.println("t");
cal.blood(attackPoints, purpose, time);
}
}
| [
"secminhrian@gmail.com"
] | secminhrian@gmail.com |
142e3c516d1b1dc8a1b10633bf3314a3c1dbe15a | f70170e5fa236f14f9b4d5ab6f512290cf2f2712 | /shared/src/main/java/com/csc445/shared/packets/StateRequestPacket.java | 168f0e623bf5e42d6906acd0b76c2bd1861050d4 | [
"MIT"
] | permissive | ye-bhone-myat/Multicast-Project | 5b431d2e3b3474f495907b597e28d13a0c61b9db | e40f5bdc9ac22b8b1ff389529dfacc1b8ffc9c44 | refs/heads/master | 2020-05-17T11:18:11.366258 | 2019-05-13T03:46:03 | 2019-05-13T03:46:03 | 183,683,137 | 0 | 0 | MIT | 2019-04-26T19:25:33 | 2019-04-26T19:25:33 | null | UTF-8 | Java | false | false | 868 | java | package com.csc445.shared.packets;
import java.net.DatagramPacket;
import java.nio.ByteBuffer;
import java.util.Arrays;
public class StateRequestPacket extends Packet {
private short playNumber;
public StateRequestPacket() { // used for incoming request
super(Type.STATE_REQ);
}
public StateRequestPacket(short playNumber) {
super(Type.STATE_REQ);
this.playNumber = playNumber;
}
@Override
public void parseSocketData(DatagramPacket packet) {
final byte[] p = Arrays.copyOfRange(packet.getData(), 1, packet.getLength());
playNumber = ByteBuffer.wrap(p).getShort();
}
@Override
protected void createPacketData() {
addData(getType().getValue());
addByteArray(shortToByteArray(playNumber));
}
public short getPlayNumber() {
return playNumber;
}
}
| [
"landon.patmore@gmail.com"
] | landon.patmore@gmail.com |
f82553414b79b7869afc4d437d1b6f2f2ec64dc4 | 0e3959e521f809a6e6cb1e427faa47617338c586 | /src/main/java/com/hit/curricelumdesign/context/param/workfile/WorkFileBaseParam.java | 316256a9551ba54e7c200cdbc0735090d6d2439a | [] | no_license | bin19920301/curriculum-design | e1f02e9d731e7d76621c990edb31ced015a7b02e | 4394f8345f4253ac5ed59000b2e226f5e02a8609 | refs/heads/master | 2022-07-05T21:40:19.351774 | 2020-06-10T13:09:45 | 2020-06-10T13:09:45 | 224,962,903 | 1 | 0 | null | 2022-06-17T02:42:04 | 2019-11-30T05:11:48 | Java | UTF-8 | Java | false | false | 549 | java | package com.hit.curricelumdesign.context.param.workfile;
import com.hit.curricelumdesign.context.param.BaseRequestParam;
import javax.validation.constraints.NotNull;
public class WorkFileBaseParam extends BaseRequestParam {
/**
* id
*/
@NotNull
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "FileBaseParam{" +
"id=" + id +
'}';
}
}
| [
"24455913@qq.com"
] | 24455913@qq.com |
ad3a3ca34d35ee760bfc51f47d70de356a47bd07 | b016e43cbd057f3911ed5215c23a686592d98ff0 | /google-ads/src/main/java/com/google/ads/googleads/v8/enums/LeadFormDesiredIntentEnum.java | 9abd6f1e73143b9d6f17a5a09c35627350eb1bb0 | [
"Apache-2.0"
] | permissive | devchas/google-ads-java | d53a36cd89f496afedefcb6f057a727ecad4085f | 51474d7f29be641542d68ea406d3268f7fea76ac | refs/heads/master | 2021-12-28T18:39:43.503491 | 2021-08-12T14:56:07 | 2021-08-12T14:56:07 | 169,633,392 | 0 | 1 | Apache-2.0 | 2021-08-12T14:46:32 | 2019-02-07T19:56:58 | Java | UTF-8 | Java | false | true | 20,723 | java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v8/enums/lead_form_desired_intent.proto
package com.google.ads.googleads.v8.enums;
/**
* <pre>
* Describes the desired level of intent of generated leads.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum}
*/
public final class LeadFormDesiredIntentEnum extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum)
LeadFormDesiredIntentEnumOrBuilder {
private static final long serialVersionUID = 0L;
// Use LeadFormDesiredIntentEnum.newBuilder() to construct.
private LeadFormDesiredIntentEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private LeadFormDesiredIntentEnum() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new LeadFormDesiredIntentEnum();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private LeadFormDesiredIntentEnum(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v8.enums.LeadFormDesiredIntentProto.internal_static_google_ads_googleads_v8_enums_LeadFormDesiredIntentEnum_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v8.enums.LeadFormDesiredIntentProto.internal_static_google_ads_googleads_v8_enums_LeadFormDesiredIntentEnum_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum.class, com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum.Builder.class);
}
/**
* <pre>
* Enum describing the desired level of intent of generated leads.
* </pre>
*
* Protobuf enum {@code google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum.LeadFormDesiredIntent}
*/
public enum LeadFormDesiredIntent
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <pre>
* Not specified.
* </pre>
*
* <code>UNSPECIFIED = 0;</code>
*/
UNSPECIFIED(0),
/**
* <pre>
* Used for return value only. Represents value unknown in this version.
* </pre>
*
* <code>UNKNOWN = 1;</code>
*/
UNKNOWN(1),
/**
* <pre>
* Deliver more leads at a potentially lower quality.
* </pre>
*
* <code>LOW_INTENT = 2;</code>
*/
LOW_INTENT(2),
/**
* <pre>
* Deliver leads that are more qualified.
* </pre>
*
* <code>HIGH_INTENT = 3;</code>
*/
HIGH_INTENT(3),
UNRECOGNIZED(-1),
;
/**
* <pre>
* Not specified.
* </pre>
*
* <code>UNSPECIFIED = 0;</code>
*/
public static final int UNSPECIFIED_VALUE = 0;
/**
* <pre>
* Used for return value only. Represents value unknown in this version.
* </pre>
*
* <code>UNKNOWN = 1;</code>
*/
public static final int UNKNOWN_VALUE = 1;
/**
* <pre>
* Deliver more leads at a potentially lower quality.
* </pre>
*
* <code>LOW_INTENT = 2;</code>
*/
public static final int LOW_INTENT_VALUE = 2;
/**
* <pre>
* Deliver leads that are more qualified.
* </pre>
*
* <code>HIGH_INTENT = 3;</code>
*/
public static final int HIGH_INTENT_VALUE = 3;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static LeadFormDesiredIntent valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static LeadFormDesiredIntent forNumber(int value) {
switch (value) {
case 0: return UNSPECIFIED;
case 1: return UNKNOWN;
case 2: return LOW_INTENT;
case 3: return HIGH_INTENT;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<LeadFormDesiredIntent>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
LeadFormDesiredIntent> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<LeadFormDesiredIntent>() {
public LeadFormDesiredIntent findValueByNumber(int number) {
return LeadFormDesiredIntent.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum.getDescriptor().getEnumTypes().get(0);
}
private static final LeadFormDesiredIntent[] VALUES = values();
public static LeadFormDesiredIntent valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private LeadFormDesiredIntent(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum.LeadFormDesiredIntent)
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum)) {
return super.equals(obj);
}
com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum other = (com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum) obj;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Describes the desired level of intent of generated leads.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum)
com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnumOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v8.enums.LeadFormDesiredIntentProto.internal_static_google_ads_googleads_v8_enums_LeadFormDesiredIntentEnum_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v8.enums.LeadFormDesiredIntentProto.internal_static_google_ads_googleads_v8_enums_LeadFormDesiredIntentEnum_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum.class, com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum.Builder.class);
}
// Construct using com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v8.enums.LeadFormDesiredIntentProto.internal_static_google_ads_googleads_v8_enums_LeadFormDesiredIntentEnum_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum getDefaultInstanceForType() {
return com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum build() {
com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum buildPartial() {
com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum result = new com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum(this);
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum) {
return mergeFrom((com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum other) {
if (other == com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum.getDefaultInstance()) return this;
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum)
private static final com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum();
}
public static com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<LeadFormDesiredIntentEnum>
PARSER = new com.google.protobuf.AbstractParser<LeadFormDesiredIntentEnum>() {
@java.lang.Override
public LeadFormDesiredIntentEnum parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new LeadFormDesiredIntentEnum(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<LeadFormDesiredIntentEnum> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<LeadFormDesiredIntentEnum> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v8.enums.LeadFormDesiredIntentEnum getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
cf6b633d9f133e3db5b8fec16cd8817acbd4e2c0 | 884f85db711b4992fa04c968daac2c20f02ea170 | /mySolutions/面经/OCI/Braces Conversion.java | dee6f9bfdd884e0462e9eb576b83c0c98a9252da | [] | no_license | brandonhyc/note_collection | 32bfcc4f2f81386f60f5ce49cea2c15554d5305f | c2fbf457d5da366c67c7a1f17fb2be9b2833d441 | refs/heads/master | 2023-08-28T03:41:36.356702 | 2021-10-23T19:05:16 | 2021-10-23T19:05:16 | 113,705,752 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,809 | java | class Solution {
//https://www.1point3acres.com/bbs/thread-575215-2-1.html
public String longestValidParentheses(String s) {
boolean[] invalid = new boolean[s.length()];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '(') {
stack.push(i);
} else if (ch == ')' ) {
if (stack.size() == 0) {
invalid[i] = true;
} else {
stack.pop();
}
}
}
while (stack.size() != 0) {
int index = stack.pop();
invalid[index] = true;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < invalid.length; i++) {
if (s.charAt(i) == '(' || s.charAt(i) == ')') {
if (invalid[i]) {
sb.append((s.charAt(i) == '(') ? "1" : "-1");
} else {
sb.append(0);
}
} else {
sb.append(s.charAt(i));
}
}
return sb.toString();
}
}
public class MainClass {
public static String stringToString(String input) {
return JsonArray.readFrom("[" + input + "]").get(0).asString();
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
String s = ")21(21)a1("; // ANS: -1210210a11
String ret = new Solution().longestValidParentheses(s);
String out = String.valueOf(ret);
System.out.print(ret);
}
}
} | [
"brandon.heyc@gmail.com"
] | brandon.heyc@gmail.com |
6fa8f6f58ffe7aace4308c294330fd632f46619c | 16962fdcdc5211e5c187c764228f76b785096714 | /src/main/java/com/github/coupon/Main.java | 5b7bdf9f1f52a92967cf2c3633af500794d1ad63 | [] | no_license | yangzh994/coupon-service | b6af29b346f43fbd25cc22b1183867d96429bf95 | 1d80de2c6c0fe7b7b84b4bafc498341d07337ab5 | refs/heads/master | 2022-06-27T08:45:03.443494 | 2019-06-17T08:06:40 | 2019-06-17T08:06:40 | 191,363,438 | 1 | 0 | null | 2022-06-21T01:15:39 | 2019-06-11T12:04:26 | Java | UTF-8 | Java | false | false | 518 | java | package com.github.coupon;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@MapperScan("com.github.coupon.dao")
@EnableRetry
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class,args);
}
}
| [
"yangzhenhua@bizvane.cn"
] | yangzhenhua@bizvane.cn |
ddbd89918e23e620eb1d4ac52955747c718ce85e | b3424918f394ac7c27eafe365f205e2bc940d651 | /src/main/java/com/ath/voucher/VoucherWorker.java | befb8d75c42e4099264fb2e75a93978e3a8a6fc6 | [] | no_license | aarontharris/Voucher | b0a5d391c83e6c85e95d65150cf1d55e29969cf0 | 61569e6415bcbbba718efb51c51e2ecc56b9919f | refs/heads/master | 2020-12-03T00:40:05.231644 | 2017-07-04T17:44:09 | 2017-07-04T17:44:09 | 96,059,316 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,677 | java | package com.ath.voucher;
import android.support.annotation.Nullable;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class VoucherWorker {
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = Math.max( 2, Math.min( CPU_COUNT - 1, 4 ) );
private static final int MAX_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final long KEEP_LIFE_TIME_IN_SECOND = 30L;
private static final int INITAL_CAPACITY = 10;
public interface WorkerTask<INPUT, RESULT> {
RESULT doInBackground( INPUT input ) throws Exception;
}
@SuppressWarnings( "unchecked" )
private VoucherManager<Object> vms = VoucherManager.attain();
private final NonReentrantLockPool mLocks = new NonReentrantLockPool();
private Executor mExecutor = null;
public VoucherWorker() {
mExecutor = initExecutor();
}
protected Executor initExecutor() {
return new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAX_POOL_SIZE,
KEEP_LIFE_TIME_IN_SECOND,
TimeUnit.SECONDS,
new LinkedBlockingDeque( INITAL_CAPACITY )
);
}
protected final Executor getExecutor() {
return mExecutor;
}
/**
* <pre>
* Basic execution of a {@link Runnable}
* Uncaught exceptions within runnable will crash the app.
* </pre>
*/
public final void enqueue( Runnable run ) {
getExecutor().execute( run );
}
/**
* Get a voucher in exchange for your request.<br>
* Allows you to group requests by key so that only the first concurrent request goes async.
* Subsequent concurrent requests with the same key will be notified when the first completes.
*
* @param key a unique key will be generated if none is provided.
* @param task
* @return
*/
@NeverThrows
public final <INPUT, RESULT> Voucher<RESULT> enqueueVoucher( @Nullable String key, final INPUT input, final WorkerTask<INPUT, RESULT> task ) {
@SuppressWarnings( "unchecked" )
Voucher<RESULT> voucher = (Voucher<RESULT>) vms.newVoucher( key );
final String voucherKey = voucher.getKey();
if ( mLocks.tryLock( voucherKey ) ) {
try {
getExecutor().execute( new Runnable() {
@Override public void run() {
RESULT result = null;
Exception error = null;
try {
result = task.doInBackground( input );
// cache ?
} catch ( Exception e ) {
error = e;
} finally {
mLocks.unlock( voucherKey );
}
if ( error != null ) {
vms.notifyVouchersClearCache( voucherKey, new VoucherPayload<>( error ) );
} else {
vms.notifyVouchersClearCache( voucherKey, new VoucherPayload<>( (Object) result ) );
}
}
} );
} catch ( Exception e ) {
// Failed to attain executor -- should be extremely rare if ever but we want to be thorough
vms.notifyVouchersClearCache( voucherKey, new VoucherPayload<>( e ) );
mLocks.unlock( voucherKey );
}
}
return voucher;
}
}
| [
"aarontharris@gmail.com"
] | aarontharris@gmail.com |
6530d4a468c5ee243ed0a7634081476697c29fe2 | 6c3b264c5c5778d54c9b83538dd275a6e137fc00 | /ibas.receiptpayment/src/main/java/org/colorcoding/ibas/receiptpayment/logic/PaymentPaidTotalService.java | cbd785a2856d2f7fd87eb4ede823962338893246 | [
"Apache-2.0"
] | permissive | color-coding/ibas.receiptpayment | 8169d094b55d9535e944760ad5705b276f2de04a | b8f4ff53d61b330e47fd98eaf5b60a40923017d7 | refs/heads/master | 2023-08-13T03:47:37.525826 | 2023-05-23T07:18:45 | 2023-08-01T08:07:41 | 114,115,240 | 0 | 68 | Apache-2.0 | 2020-11-13T06:31:57 | 2017-12-13T11:57:10 | TypeScript | UTF-8 | Java | false | false | 2,679 | java | package org.colorcoding.ibas.receiptpayment.logic;
import java.math.BigDecimal;
import org.colorcoding.ibas.bobas.data.Decimal;
import org.colorcoding.ibas.bobas.i18n.I18N;
import org.colorcoding.ibas.bobas.logic.BusinessLogicException;
import org.colorcoding.ibas.bobas.mapping.LogicContract;
import org.colorcoding.ibas.bobas.message.Logger;
import org.colorcoding.ibas.bobas.message.MessageLevel;
import org.colorcoding.ibas.document.IDocumentPaidTotalOperator;
import org.colorcoding.ibas.receiptpayment.MyConfiguration;
import org.colorcoding.ibas.receiptpayment.bo.receipt.Receipt;
@LogicContract(IPaymentPaidTotalContract.class)
public class PaymentPaidTotalService extends DocumentPaidTotalService<IPaymentPaidTotalContract> {
@Override
protected boolean checkDataStatus(Object data) {
if (data instanceof IPaymentPaidTotalContract) {
IPaymentPaidTotalContract contract = (IPaymentPaidTotalContract) data;
if (contract.getBaseDocumentType() == null || contract.getBaseDocumentType().isEmpty()) {
Logger.log(MessageLevel.DEBUG, MSG_LOGICS_SKIP_LOGIC_EXECUTION, this.getClass().getName(),
"BaseDocumentType", "NULL or Empty");
return false;
}
if (contract.getBaseDocumentType().equals(MyConfiguration.applyVariables(Receipt.BUSINESS_OBJECT_CODE))) {
Logger.log(MessageLevel.DEBUG, MSG_LOGICS_SKIP_LOGIC_EXECUTION, this.getClass().getName(),
"BaseDocumentType", "Receipt");
return false;
}
}
return super.checkDataStatus(data);
}
@Override
protected IDocumentPaidTotalOperator fetchBeAffected(IPaymentPaidTotalContract contract) {
return this.fetchBeAffected(contract.getBaseDocumentType(), contract.getBaseDocumentEntry());
}
@Override
protected void impact(IPaymentPaidTotalContract contract) {
if (contract.getCurrency() != null && !contract.getCurrency().isEmpty()) {
if (!contract.getCurrency().equals(this.getBeAffected().getDocumentCurrency())) {
throw new BusinessLogicException(I18N.prop("msg_rp_payment_currency_mismatch", this.getBeAffected()));
}
}
if (contract.getAmount() == null || Decimal.isZero(contract.getAmount())) {
return;
}
BigDecimal total = this.getBeAffected().getPaidTotal();
if (total == null) {
total = Decimal.ZERO;
}
this.getBeAffected().setPaidTotal(total.add(contract.getAmount()));
}
@Override
protected void revoke(IPaymentPaidTotalContract contract) {
if (contract.getAmount() == null || Decimal.isZero(contract.getAmount())) {
return;
}
BigDecimal total = this.getBeAffected().getPaidTotal();
if (total == null) {
total = Decimal.ZERO;
}
this.getBeAffected().setPaidTotal(total.subtract(contract.getAmount()));
}
}
| [
"niuren.zhu@icloud.com"
] | niuren.zhu@icloud.com |
81f020bac9dfe3b01f11f8b36fd22c1a70c3ad8f | faaeeafeab7eecde051f287587e80f8c1f101392 | /QAstuff/workspace/selenium/src/junitTest/CalculatorTest.java | f0dfc9d42cb5ba9ec2a413bae8ed7735a4e2c2f0 | [] | no_license | dsm23/QAstuff | e2ec554a78e5d1054ded08f4aaa719fcc0d07ac8 | 1332e1025d90a44b9388b2771080b0eedca3d47e | refs/heads/master | 2021-01-20T09:38:03.050374 | 2017-07-10T17:46:42 | 2017-07-10T17:46:42 | 90,272,517 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 594 | java | package junitTest;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CalculatorTest {
@Test
public void evaluatesExpression1() {
Calculator calculator = new Calculator();
int sum = calculator.evaluate("1+2+3");
assertEquals(6, sum);
}
@Test
public void evaluatesExpression2() {
Calculator calculator = new Calculator();
int sum = calculator.evaluate("1+2+3");
assertEquals(7, sum);
}
@Test
public void evaluatesExpression3() {
Calculator calculator = new Calculator();
int sum = calculator.evaluate("1+2+3");
assertEquals(8, sum);
}
} | [
"ubuntu@ip-172-31-11-152.eu-west-2.compute.internal"
] | ubuntu@ip-172-31-11-152.eu-west-2.compute.internal |
3d3d61c13942e5fb68950dc53ab707e4ce43f41d | dfc951e95ec8df0ea74e2f62a67609c28f6e213f | /_/Chapter12/DialPhone/app/src/main/java/com/packtpub/androidcookbook/dialphone/MainActivity.java | 042a36fc1bd2403555999e42b942df12b46b57e2 | [
"Apache-2.0"
] | permissive | paullewallencom/android-978-1-7858-8619-5 | 0e9658296f4b82c56fd30e839dcc773c30867c5f | c0416774dfcbe3a6716cfb6aad76b79d256fc549 | refs/heads/main | 2023-02-15T11:16:39.458641 | 2020-12-30T08:05:49 | 2020-12-30T08:05:49 | 319,462,787 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,063 | java | package com.packtpub.androidcookbook.dialphone;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private boolean checkPermission(String permission) {
int permissionCheck = ContextCompat.checkSelfPermission(
this, permission);
return (permissionCheck == PackageManager.PERMISSION_GRANTED);
}
public void dialPhone(View view){
if (checkPermission("android.permission.CALL_PHONE")) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:0123456789"));
startActivity(intent);
}
}
}
| [
"paullewallencom@users.noreply.github.com"
] | paullewallencom@users.noreply.github.com |
0c47b1646168bb9f800f7842321ecab2ce9c8ba7 | df04d22d84f32eac535c5476d3873f6fb4055d4c | /src/main/java/com/nuaa/health/controller/FakeController.java | 57d5c162c17d1d710deb636e0333e0139e35b00e | [] | no_license | nuaa-meizizi/backend | bf3ef0a58b1e79335b64f2521aa3f3b20612df58 | 7b0015569438bdb11973d8ad36813142ee7f1fd8 | refs/heads/master | 2020-03-23T07:19:39.165464 | 2018-08-14T03:29:47 | 2018-08-14T03:29:47 | 141,263,961 | 0 | 0 | null | 2018-07-27T06:48:51 | 2018-07-17T09:14:13 | Java | UTF-8 | Java | false | false | 1,343 | java | package com.nuaa.health.controller;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.nuaa.health.service.SimulationService;
import com.nuaa.health.service.TokenService;
import com.nuaa.health.util.GenericJsonResult;
import com.nuaa.health.util.HResult;
@RestController
@RequestMapping(value = "fake")
public class FakeController {
@Autowired
SimulationService simulationService;
@Autowired
TokenService tokenService;
@RequestMapping(value = "/fakedata", method = RequestMethod.GET)
public GenericJsonResult<HashMap<String, Object>> fakeData(
@RequestParam(value = "token", required = true) String token) {
GenericJsonResult<HashMap<String, Object>> res = new GenericJsonResult<>(HResult.S_OK);
Long uid = tokenService.getUid(token);
if (uid == null) {
if (token.equals("anony")) { //匿名用户默认用uid控制
res.setData(simulationService.fakeData(1L));
}
else
res.setStatus(HResult.E_TOKEN_EXPIRE_OR_NOT_EXISTENCE);
} else {
res.setData(simulationService.fakeData(uid));
}
return res;
}
}
| [
"835410808@qq.com"
] | 835410808@qq.com |
b78370e4be8a7819a0850f15d80114c0812eb2d9 | 530a9ced2439bc29d8826873b028f4d20e855455 | /app/src/main/java/com/example/mj_uc/excursapp/vista/Help/HelpCreate.java | 00fc74ddd41bf322db47c6f5768b6aa685887303 | [] | no_license | mjucedag/excursApp | aa6c38c957905005137e0024eb90c5cf46aced5e | 01469e7cc143293423afe833db1ee8494e16be70 | refs/heads/master | 2021-05-06T23:10:18.966653 | 2017-12-14T00:10:48 | 2017-12-14T00:10:48 | 112,956,184 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 480 | java | package com.example.mj_uc.excursapp.vista.Help;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.TextView;
import com.example.mj_uc.excursapp.R;
/**
* The type Help create.
*/
public class HelpCreate extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.help_create);
}
}
| [
"mariajoseuceda@hotmail.com"
] | mariajoseuceda@hotmail.com |
eb68c14b65252641052adde9db622fff8f6f947f | 3e99f69cff3ac0e308323da25de9879bab5ed460 | /src/main/java/com/usfbank/app/service/impl/AccountManagementServiceImpl.java | d11f38212b14340126e9e0705c879cd43a062fdb | [] | no_license | MHarris-hub/Revature-Project-0 | f804cbd81ff07fb3cf7dffaf53a9e2cec6ea80fb | c6333f8b9a4fc311ab1d32b46005a060595b0271 | refs/heads/master | 2023-04-14T06:59:20.672032 | 2021-05-10T01:02:58 | 2021-05-10T01:02:58 | 361,473,332 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,111 | java | package com.usfbank.app.service.impl;
import com.usfbank.app.dao.AccountManagementDAO;
import com.usfbank.app.dao.impl.AccountManagementDAOImpl;
import com.usfbank.app.exception.AccountException;
import com.usfbank.app.model.Account;
import com.usfbank.app.model.Employee;
import com.usfbank.app.model.Transaction;
import com.usfbank.app.service.AccountManagementService;
import org.apache.log4j.Logger;
import java.math.BigDecimal;
import java.util.List;
public class AccountManagementServiceImpl implements AccountManagementService {
static Logger fileLogger = Logger.getLogger("file");
AccountManagementDAO accountManagement = new AccountManagementDAOImpl();
@Override
public boolean login(String username, String password, String userType) {
if (accountManagement.login(username, password, userType))
fileLogger.info("Login success for user: " + username);
else
fileLogger.info("Login failure for user: " + username);
return accountManagement.login(username, password, userType);
}
@Override
public BigDecimal getBalance(int accountID) {
return accountManagement.getBalance(accountID);
}
@Override
public void registerEmployee(Employee employee) {
accountManagement.registerEmployee(employee);
}
@Override
public void applyForAccount(Account account) {
accountManagement.applyForAccount(account);
}
@Override
public void deposit(int accountID, BigDecimal amount) throws AccountException {
accountManagement.deposit(accountID, amount);
}
@Override
public void withdraw(int accountID, BigDecimal amount) throws AccountException {
accountManagement.withdraw(accountID, amount);
}
@Override
public void transfer(int fromAccountID, int toAccountID, BigDecimal amount) throws AccountException {
accountManagement.transfer(fromAccountID, toAccountID, amount);
}
@Override
public List<Transaction> getTransactionLog(int accountID) {
return accountManagement.getTransactionLogByID(accountID);
}
} | [
"michael.jim.harris@gmail.com"
] | michael.jim.harris@gmail.com |
29216798e1daadad4fff70e04cb45d88aa4b95d7 | 7166a6f3a1b6875f1514bf478649a9d847802035 | /Design Patterns/src/patterns/creational/abstractfactory/Circle.java | 3eeb13a2a7a04d858b3ea1386574a4d26a88fcc9 | [] | no_license | AshishBagdane/Design-Patterns | 2ba9428045f73b96e3d53622807d41d5d5874ea4 | fdd2386aba3c896833d5181042acc683eee806ce | refs/heads/master | 2021-01-15T18:27:23.480272 | 2017-09-05T16:47:56 | 2017-09-05T16:47:56 | 99,789,523 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 211 | java | package patterns.creational.abstractfactory;
public class Circle implements Shape {
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("Circle Drawn");
}
}
| [
"Ashish@192.168.1.6"
] | Ashish@192.168.1.6 |
3f1ccaa40a9db636030e174d345253dca6b6c52e | ba1d3c78483b322179501dacfc5544d65b14cc4a | /StoneWall.java | 51409debd0ac004c3b1895862fc473482b9e5cb8 | [] | no_license | rodrigovz/codility | 18aef0a33c0300d93c83fbd5832c734824bd71db | 683296b09e6babb45a7675d0b94be7f0013577de | refs/heads/master | 2022-12-03T19:53:13.877803 | 2020-08-17T01:43:23 | 2020-08-17T01:43:23 | 287,614,587 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,233 | java | import java.util.*;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int[] h) {
// write your code in Java SE 8
// write your code in Java SE 8
Stack<Integer> stack = new Stack<>();
int sumStack = 0;
int result = 0;
for (int i=0;i<h.length;i++) {
if (stack.empty()) {
stack.push(h[i]);
sumStack = h[i];
result++;
continue;
}
if (h[i] == sumStack) {
continue;
} else if (h[i] < sumStack) {
while(!stack.empty() && sumStack > h[i]) {
Integer last = stack.pop();
sumStack -= last;
}
if (sumStack == h[i]) {
continue;
} else {
stack.push(h[i]-sumStack);
sumStack = h[i];
result++;
}
} else {
stack.push(h[i]-sumStack);
sumStack = h[i];
result++;
}
}
return result;
}
}
| [
"rodrigo@rooam.co"
] | rodrigo@rooam.co |
fc898a0687adc5a60e45864f02d3fbc688fc7dd6 | 5c58369b026f0a3721ebba657b728fafd224bd89 | /server/notification-server/src/main/java/org/java/notification/receiver/ReceiverService.java | c46bf90a2d6de9e123d60b75c38f048976a1c38e | [] | no_license | msamoylych/notification | 5c3cdc1cd84f018528363aac6a25c5d97737c993 | 20a246140b79650b390051240c60b1f64022b98d | refs/heads/master | 2020-04-05T13:06:23.622988 | 2017-07-28T13:40:35 | 2017-07-28T13:40:35 | 95,013,623 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,505 | java | package org.java.notification.receiver;
import org.java.notification.push.ApplicationStorage;
import org.java.notification.push.Push;
import org.java.notification.push.PushStorage;
import org.java.notification.push.application.Application;
import org.java.notification.receiver.model.PushModel;
import org.java.notification.receiver.model.RequestModel;
import org.java.notification.receiver.model.ResponseModel;
import org.java.notification.router.Router;
import org.java.notification.user.System;
import org.java.notification.user.SystemStorage;
import org.java.utils.StringUtils;
import org.java.utils.storage.StorageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
* Created by msamoylych on 22.06.2017.
*/
@Component
public class ReceiverService {
private static final Logger LOGGER = LoggerFactory.getLogger(ReceiverService.class);
private static final Random RND = new Random();
private static final ResponseModel UNDEFINED_SYSTEM_CODE = new ResponseModel("undefined-system-code");
private static final ResponseModel INVALID_SYSTEM_CODE = new ResponseModel("invalid-system-code");
private static final ResponseModel SYSTEM_LOCKED = new ResponseModel("system-locked");
private static final ResponseModel EMPTY_REQUEST = new ResponseModel("empty-request");
private static final ResponseModel DUPLICATE_PUSH = new ResponseModel("duplicate-push");
private final SystemStorage systemStorage;
private final ApplicationStorage applicationStorage;
private final PushStorage pushStorage;
private final Router router;
public ReceiverService(SystemStorage systemStorage, ApplicationStorage applicationStorage, PushStorage pushStorage,
Router router) {
this.systemStorage = systemStorage;
this.applicationStorage = applicationStorage;
this.pushStorage = pushStorage;
this.router = router;
}
@SuppressWarnings("unchecked")
public ResponseModel receive(HttpServletRequest httpServletRequest, RequestModel request) {
String remoteHost = httpServletRequest.getRemoteHost();
String remoteAddr = httpServletRequest.getRemoteAddr();
if (Objects.equals(remoteHost, remoteAddr)) {
LOGGER.info("Request from {}", remoteHost);
} else {
LOGGER.info("Request from {} ({})", remoteHost, remoteAddr);
}
String systemCode = request.system;
if (StringUtils.isEmpty(systemCode)) {
LOGGER.error("System code not specified");
return UNDEFINED_SYSTEM_CODE;
}
System system = systemStorage.system(systemCode);
if (system == null) {
LOGGER.error("System with code <{}> not found", systemCode);
return INVALID_SYSTEM_CODE;
}
if (system.locked()) {
LOGGER.error("{} is locked", system);
return SYSTEM_LOCKED;
}
List<PushModel> pushModels = request.pushes;
if (pushModels == null || pushModels.isEmpty()) {
LOGGER.error("Empty request");
return EMPTY_REQUEST;
}
LOGGER.info("Received {} push(es) from {}", pushModels.size(), system.name());
try {
List<Push<?>> pushes = new ArrayList<>(pushModels.size());
List<ResponseModel.Result> results = new ArrayList<>(pushModels.size());
for (PushModel pushModel : pushModels) {
ResponseModel.Result result = new ResponseModel.Result(pushModel.id);
results.add(result);
if (!checkPushModel(pushModel)) {
result.error = "invalid-push";
continue;
}
Application application = applicationStorage.application(system.id(), pushModel.pns, pushModel.packageName);
if (application == null) {
LOGGER.error("{}: application not found", pushModel);
result.error = "application-not-found";
continue;
}
Push push = new Push();
pushes.add(push);
push.system(system);
push.extId(pushModel.id);
push.application(application);
push.token(pushModel.token);
push.title(pushModel.title);
push.body(pushModel.body);
push.icon(pushModel.icon);
}
pushStorage.save(pushes);
Iterator<Push<?>> itr = pushes.iterator();
for (ResponseModel.Result result : results) {
if (result.error == null) {
result.msgId = itr.next().id();
}
}
router.route(pushes);
return new ResponseModel(results);
} catch (Throwable th) {
if (th instanceof StorageException && ((StorageException) th).isConstraintViolation()) {
LOGGER.error("Constraint violation");
return DUPLICATE_PUSH;
} else {
int err = RND.nextInt(1000000);
LOGGER.error("Error #{} occurred", err, th);
return new ResponseModel("error-#" + err);
}
}
}
private boolean checkPushModel(PushModel pushModel) {
if (StringUtils.isEmpty(pushModel.id)) {
LOGGER.error("PushModel id not specified");
return false;
}
if (!StringUtils.checkLength(pushModel.id, 36)) {
LOGGER.error("{}: id length more than 36 characters", pushModel);
return false;
}
if (!StringUtils.checkLength(pushModel.token, 256)) {
LOGGER.error("{}: token length more than 256 characters", pushModel);
return false;
}
if (!StringUtils.checkLength(pushModel.title, 256)) {
LOGGER.error("{}: title length more than 256 characters", pushModel);
return false;
}
if (!StringUtils.checkLength(pushModel.body, 4000)) {
LOGGER.error("{}: body length more than 4000 characters", pushModel);
return false;
}
if (!StringUtils.checkLength(pushModel.icon, 16)) {
LOGGER.error("{}: icon length more than 16 characters", pushModel);
return false;
}
return true;
}
}
| [
"msamoylych@sberbank-tele.com"
] | msamoylych@sberbank-tele.com |
bba9676aafed25b4983ddec3996cd207008e2bba | ccdbc8345410ff4082139869ca1cd17f923baaae | /apis/vcloud/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudComputeServiceAdapter.java | d46fce7787b2a2b3c86f7c7db809bde8039ff066 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | novel/jclouds | 678ff8e92a09a6c78da9ee2c9854eeb1474659a5 | ff2982c747b47e067f06badc73587bfe103ca37d | refs/heads/master | 2021-01-20T22:58:44.675667 | 2012-03-25T17:04:05 | 2012-03-25T17:04:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,818 | java | /**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.vcloud.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URI;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.logging.Logger;
import org.jclouds.ovf.Envelope;
import org.jclouds.vcloud.TaskInErrorStateException;
import org.jclouds.vcloud.TaskStillRunningException;
import org.jclouds.vcloud.VCloudClient;
import org.jclouds.vcloud.VCloudMediaType;
import org.jclouds.vcloud.domain.Org;
import org.jclouds.vcloud.domain.ReferenceType;
import org.jclouds.vcloud.domain.Status;
import org.jclouds.vcloud.domain.Task;
import org.jclouds.vcloud.domain.VApp;
import org.jclouds.vcloud.domain.VAppTemplate;
import org.jclouds.vcloud.suppliers.VAppTemplatesSupplier;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.ImmutableSet.Builder;
/**
* defines the connection between the {@link VCloudClient} implementation and the jclouds
* {@link ComputeService}
*
*/
@Singleton
public class VCloudComputeServiceAdapter implements ComputeServiceAdapter<VApp, VAppTemplate, VAppTemplate, Location> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
protected final VCloudClient client;
protected final Predicate<URI> successTester;
protected final InstantiateVAppTemplateWithGroupEncodedIntoNameThenCustomizeDeployAndPowerOn booter;
protected final Supplier<Map<String, Org>> nameToOrg;
protected final Supplier<Set<VAppTemplate>> templates;
protected final Function<VAppTemplate, Envelope> templateToEnvelope;
@Inject
protected VCloudComputeServiceAdapter(VCloudClient client, Predicate<URI> successTester,
InstantiateVAppTemplateWithGroupEncodedIntoNameThenCustomizeDeployAndPowerOn booter,
Supplier<Map<String, Org>> nameToOrg, VAppTemplatesSupplier templates,
Function<VAppTemplate, Envelope> templateToEnvelope) {
this.client = checkNotNull(client, "client");
this.successTester = checkNotNull(successTester, "successTester");
this.booter = checkNotNull(booter, "booter");
this.nameToOrg = checkNotNull(nameToOrg, "nameToOrg");
this.templates = checkNotNull(templates, "templates");
this.templateToEnvelope = checkNotNull(templateToEnvelope, "templateToEnvelope");
}
@Override
public NodeAndInitialCredentials<VApp> createNodeWithGroupEncodedIntoName(String group, String name,
Template template) {
return booter.createNodeWithGroupEncodedIntoName(group, name, template);
}
@Override
public Iterable<VAppTemplate> listHardwareProfiles() {
return supportedTemplates();
}
private Iterable<VAppTemplate> supportedTemplates() {
return Iterables.filter(templates.get(), new Predicate<VAppTemplate>() {
@Override
public boolean apply(VAppTemplate from) {
try {
templateToEnvelope.apply(from);
} catch (IllegalArgumentException e){
logger.warn("Unsupported: "+ e.getMessage());
return false;
}
return true;
}
});
}
@Override
public Iterable<VAppTemplate> listImages() {
return supportedTemplates();
}
@Override
public Iterable<VApp> listNodes() {
// TODO: parallel or cache
Builder<VApp> nodes = ImmutableSet.<VApp> builder();
for (Org org : nameToOrg.get().values()) {
for (ReferenceType vdc : org.getVDCs().values()) {
for (ReferenceType resource : client.getVDCClient().getVDC(vdc.getHref()).getResourceEntities().values()) {
if (resource.getType().equals(VCloudMediaType.VAPP_XML)) {
addVAppToSetRetryingIfNotYetPresent(nodes, vdc, resource);
}
}
}
}
return nodes.build();
}
@VisibleForTesting
void addVAppToSetRetryingIfNotYetPresent(Builder<VApp> nodes, ReferenceType vdc, ReferenceType resource) {
VApp node = null;
int i = 0;
while (node == null && i++ < 3) {
try {
node = client.getVAppClient().getVApp(resource.getHref());
nodes.add(node);
} catch (NullPointerException e) {
logger.warn("vApp %s not yet present in vdc %s", resource.getName(), vdc.getName());
}
}
}
@Override
public Iterable<Location> listLocations() {
// Not using the adapter to determine locations
return ImmutableSet.<Location>of();
}
@Override
public VApp getNode(String in) {
URI id = URI.create(in);
return client.getVAppClient().getVApp(id);
}
@Override
public void destroyNode(String id) {
URI vappId = URI.create(checkNotNull(id, "node.id"));
VApp vApp = cancelAnyRunningTasks(vappId);
if (vApp.getStatus() != Status.OFF) {
logger.debug(">> powering off VApp vApp(%s), current status: %s", vApp.getName(), vApp.getStatus());
try {
waitForTask(client.getVAppClient().powerOffVApp(vApp.getHref()));
vApp = client.getVAppClient().getVApp(vApp.getHref());
logger.debug("<< %s vApp(%s)", vApp.getStatus(), vApp.getName());
} catch (IllegalStateException e) {
logger.warn(e, "<< %s vApp(%s)", vApp.getStatus(), vApp.getName());
}
logger.debug(">> undeploying vApp(%s), current status: %s", vApp.getName(), vApp.getStatus());
try {
waitForTask(client.getVAppClient().undeployVApp(vApp.getHref()));
vApp = client.getVAppClient().getVApp(vApp.getHref());
logger.debug("<< %s vApp(%s)", vApp.getStatus(), vApp.getName());
} catch (IllegalStateException e) {
logger.warn(e, "<< %s vApp(%s)", vApp.getStatus(), vApp.getName());
}
}
logger.debug(">> deleting vApp(%s)", vApp.getHref());
waitForTask(client.getVAppClient().deleteVApp(vApp.getHref()));
logger.debug("<< deleted vApp(%s)", vApp.getHref());
}
VApp waitForPendingTasksToComplete(URI vappId) {
VApp vApp = client.getVAppClient().getVApp(vappId);
if (vApp.getTasks().size() == 0)
return vApp;
for (Task task : vApp.getTasks())
waitForTask(task);
return client.getVAppClient().getVApp(vappId);
}
VApp cancelAnyRunningTasks(URI vappId) {
VApp vApp = client.getVAppClient().getVApp(vappId);
if (vApp.getTasks().size() == 0)
return vApp;
for (Task task : vApp.getTasks()) {
try {
client.getTaskClient().cancelTask(task.getHref());
waitForTask(task);
} catch (TaskInErrorStateException e) {
}
}
return client.getVAppClient().getVApp(vappId);
}
public void waitForTask(Task task) {
if (!successTester.apply(task.getHref()))
throw new TaskStillRunningException(task);
}
@Override
public void rebootNode(String in) {
URI id = URI.create(checkNotNull(in, "node.id"));
waitForTask(client.getVAppClient().resetVApp(id));
}
@Override
public void resumeNode(String in) {
URI id = URI.create(checkNotNull(in, "node.id"));
waitForTask(client.getVAppClient().powerOnVApp(id));
}
@Override
public void suspendNode(String in) {
URI id = URI.create(checkNotNull(in, "node.id"));
waitForTask(client.getVAppClient().powerOffVApp(id));
}
}
| [
"adrian@jclouds.org"
] | adrian@jclouds.org |
2bc6523591109eb875c9e2e0f221b1c3a23d8b9e | 75a5b48a5ae41ffaac2cc517adfe1e8532d0bb17 | /src/main/java/com/itgorillaz/lnk2pwn/view/core/DefaultWindowController.java | 7398d034a6b1893b8e75c4e5442282917af0bf16 | [
"MIT"
] | permissive | it-gorillaz/lnk2pwn | ceb1a6115fefed4dcd289a309657278233f8d472 | 67b6adb867a154c09af09c71402988e2954e2a54 | refs/heads/master | 2020-04-07T22:14:32.236970 | 2018-11-23T17:18:49 | 2018-11-23T17:18:49 | 158,761,335 | 122 | 26 | null | null | null | null | UTF-8 | Java | false | false | 3,197 | java | package com.itgorillaz.lnk2pwn.view.core;
import java.awt.AWTEvent;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.AWTEventListener;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import org.springframework.stereotype.Component;
@Component
public class DefaultWindowController implements WindowController, AWTEventListener {
private Window window;
private JFrame root;
@Override
public void show(JFrame frame, BoundsPolicy policy) {
Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.WINDOW_EVENT_MASK);
this.root = frame;
this.initBounds(frame, policy);
frame.setVisible(true);
}
@Override
public Window getActiveWindow() {
return window;
}
@Override
public JFrame getRootFrame() {
return root;
}
@Override
public void eventDispatched(AWTEvent event) {
if (event instanceof WindowEvent) {
WindowEvent windowEvent = (WindowEvent) event;
switch(windowEvent.getID())
{
case WindowEvent.WINDOW_ACTIVATED:
window = windowEvent.getWindow();
break;
case WindowEvent.WINDOW_DEACTIVATED:
window = null;
break;
default:
break;
}
}
}
private void initBounds(JFrame frame, BoundsPolicy policy) {
if (!EventQueue.isDispatchThread()) {
throw new IllegalStateException("WindowController.show() should be called "
+ "from the Event Dispatch Thread.");
}
switch(policy) {
case CENTER_ONLY:
frame.setLocationRelativeTo(null);
break;
case MAXIMIZE_BOTH:
frame.setState(JFrame.MAXIMIZED_BOTH);
break;
case PACK_ONLY:
frame.pack();
break;
case PACK_AND_CENTER:
frame.pack();
frame.setLocationRelativeTo(null);
break;
case MAXIMIZE:
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimension = toolkit.getScreenSize();
Insets insets = toolkit.getScreenInsets(frame.getGraphicsConfiguration());
int width = dimension.width - (insets.left + insets.top);
int height = dimension.height - (insets.top + insets.bottom);
int x = insets.left;
int y = insets.right;
frame.pack();
frame.setSize(width, height);
frame.setLocation(x, y);
break;
case RESTORE_LAST_STATE:
break;
default:
break;
}
}
}
| [
"mail2.tommelo@gmail.com"
] | mail2.tommelo@gmail.com |
505cff0042dc2f93d6873d0ed26bee206a8a8a50 | 0b0b98a13f5e6f13d991758c4bf1615e038cd525 | /src/main/java/ch/spacebase/openclassic/api/entity/Controller.java | 8ee405711f81606a8b587db99673aeb7222af74d | [
"MIT"
] | permissive | good2000mo/OpenClassicAPI | 6101ede1ab9e79eeeb7023d13330f0eb54f44159 | c79038336a2bfb4c677313ee74d6c8b293d4d385 | refs/heads/master | 2020-05-20T02:49:07.861275 | 2013-04-30T01:45:58 | 2013-04-30T01:45:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,872 | java | package ch.spacebase.openclassic.api.entity;
import ch.spacebase.openclassic.api.block.Block;
import ch.spacebase.openclassic.api.block.BlockType;
import ch.spacebase.openclassic.api.entity.BlockEntity.BlockRemoveCause;
/**
* A Controller that handles actions on a BlockEntity.
*/
public abstract class Controller {
private BlockEntity parent;
public BlockEntity getParent() {
return this.parent;
}
protected final void attach(BlockEntity entity) {
if(entity == null) return;
this.parent = entity;
this.onAttached(this.parent);
}
protected final void detach() {
if(this.parent == null) return;
BlockEntity entity = this.parent;
this.parent = null;
this.onDetached(entity);
}
/**
* Called when the controller is attached to an entity.
* @param entity Entity being attached to.
*/
public abstract void onAttached(BlockEntity entity);
/**
* Called when the controller is detached from an entity.
* @param entity Entity being detached from.
*/
public abstract void onDetached(BlockEntity entity);
/**
* Called when the entity's block is removed.
* @param cause Cause of the block's removal.
* @param block Block that was removed.
* @return Whether to allow the removal.
*/
public boolean onBlockRemoval(BlockRemoveCause cause, Block block) {
if(cause == BlockRemoveCause.PLAYER) {
return false;
}
return true;
}
/**
* Called when the entity's block is set at a location.
* @param block Block being set.
* @return Whether to allow the set.
*/
public boolean onBlockSet(Block block) {
return true;
}
/**
* Called when the server ticks.
*/
public abstract void tick();
/**
* Gets the entity's BlockType.
* @return The entity's BlockType.
*/
public abstract BlockType getBlock();
/**
* Called when the entity dies.
*/
public abstract void onDeath();
}
| [
"good2000mo@hotmail.com"
] | good2000mo@hotmail.com |
f0b8b56c66126e0b6144104c7094ccd2aefa1bd8 | 10a83bd2a6ddea0f29eb6e3fd001cf51ae384afd | /Java8/src/com/info/Currency.java | 9521d921e00ec07a63beddfe3dc17a3b9805f89d | [] | no_license | RohanGaniga/Test | c5f8b5c6c04b23842765ad253adc80dbf86ac769 | 663a7263ca7725ea24f483f6a507b53ee074fea4 | refs/heads/master | 2023-01-27T16:11:53.497621 | 2020-11-27T11:08:10 | 2020-11-27T11:08:10 | 316,459,690 | 0 | 0 | null | 2020-11-27T11:08:11 | 2020-11-27T09:41:57 | Java | UTF-8 | Java | false | false | 971 | java | package com.info;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Scanner;
public class Currency {
public static void main(String[] args) {
Currency c = new Currency();
Scanner scan = new Scanner(System.in);
double cur = scan.nextDouble();
scan.close();
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
String us = nf.format(cur);
nf = NumberFormat.getCurrencyInstance(Locale.ENGLISH);
String india = nf.format(cur);
india = "Rs."+india.substring(1);
nf = NumberFormat.getCurrencyInstance(Locale.CHINA);
String china = nf.format(cur);
nf = NumberFormat.getCurrencyInstance(Locale.FRANCE);
String france = nf.format(cur);
//nf.setCurrency(US);
System.out.println("INDIA: " + india);
// System.out.println("India: " + india);
// System.out.println("China: " + china);
// System.out.println("France: " + france);
}
}
| [
"rganiga.ctr@sumologic.com"
] | rganiga.ctr@sumologic.com |
c199e28a9578df742e8fc4aac2a7930c5cbd096e | 9e2564e9b051f129de1868e0216e99ce01e5d873 | /src/main/java/com/baofeng/carebay/controller/PosterController.java | 2eab9902eda91ea9204e89911d4fa8508f315325 | [] | no_license | renlr/survival-web | 6fb3429563292d04a87d6b1a604e994583540522 | 4ecba1c659c90ceb941083aff4c74e3aed87066d | refs/heads/master | 2021-01-10T05:05:58.284430 | 2015-11-19T06:41:31 | 2015-11-19T06:41:31 | 46,473,513 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,864 | java | package com.baofeng.carebay.controller;
import java.io.File;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.baofeng.carebay.entity.Poster;
import com.baofeng.carebay.entity.WeekService;
import com.baofeng.carebay.service.IPosterService;
import com.baofeng.carebay.service.IWeekServiceService;
import com.baofeng.carebay.util.Constants;
import com.baofeng.utils.PageResult;
import com.baofeng.utils.ResultMsg;
@Controller
@RequestMapping("poster")
public class PosterController {
@Autowired
private IPosterService posterService;
@Autowired
private IWeekServiceService weekServiceService;
public IPosterService getPosterService() {
return posterService;
}
public void setPosterService(IPosterService posterService) {
this.posterService = posterService;
}
public IWeekServiceService getWeekServiceService() {
return weekServiceService;
}
public void setWeekServiceService(IWeekServiceService weekServiceService) {
this.weekServiceService = weekServiceService;
}
@RequestMapping(value = "/show", method = RequestMethod.GET)
public ModelAndView show() {
ModelAndView mav = new ModelAndView(com.baofeng.utils.Constants.COREWEB_BUILDITEMS + "/poster");
return mav;
}
/**
* 功能:分页数据
* */
@ResponseBody
@SuppressWarnings("rawtypes")
@RequestMapping(value = "/readPages", method = RequestMethod.POST)
public PageResult readPages(int page, int rows, String gid) {
PageResult pages = this.posterService.readAllPages(rows, page, gid);
return pages;
}
/**
* 功能:添加修改
* */
@RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(String id, String type, String indexs, String ductCat, String products, String funModule, String activity, String gid,
@RequestParam MultipartFile[] images) throws Exception {
ModelAndView mav = new ModelAndView(com.baofeng.utils.Constants.COREWEB_BUILDITEMS + "/poster");
Poster post = new Poster();
if (images != null && images.length > 0) {
for (MultipartFile $file : images) {
if (!$file.isEmpty()) {
String $name = $file.getOriginalFilename();
String ext = $name.substring($name.lastIndexOf("."), $name.length());
String sha1 = DigestUtils.shaHex($file.getInputStream());
String fileName = sha1 + ext;
String path = Constants.DEFAULT_UPLOADIMAGEPATH + File.separator + Constants.sha1ToPath(sha1);
Constants.mkdirs(path);
FileUtils.copyInputStreamToFile($file.getInputStream(), new File(path, fileName));
post.setImage(fileName);
post.setImageSha1(sha1);
}
}
}
post.setId(id);
post.setType(Integer.valueOf(type));
post.setIndexs(Integer.valueOf(indexs));
if (this.posterService.addPoster(post, type, ductCat, products, funModule, activity, gid)) {
WeekService week = this.weekServiceService.readWeekService(gid);
mav.addObject("week", week);
}
return mav;
}
/**
* 功能:编辑
* */
@ResponseBody
@RequestMapping(value = "/edit", method = RequestMethod.GET)
public Poster edit(String id) {
Poster post = this.posterService.readPoster(id);
if (post != null) {
return post;
}
return null;
}
/**
* 功能:编辑显示顺序
* */
@RequestMapping(value = "/saveIndexs", method = RequestMethod.POST)
public ModelAndView saveIndexs(String id1, String indexs1, String gid1) {
ModelAndView mav = new ModelAndView(com.baofeng.utils.Constants.COREWEB_BUILDITEMS + "/poster");
if (this.posterService.editIndexs(id1, indexs1)) {
WeekService week = this.weekServiceService.readWeekService(gid1);
mav.addObject("week", week);
mav.addObject("result", "success");
}
return mav;
}
/**
* 功能:上下线
* */
@ResponseBody
@RequestMapping(value = "/online", method = RequestMethod.GET)
public ResultMsg online(String id) {
ResultMsg result = new ResultMsg();
result.setResultMessage("errors");
if (this.posterService.onLinePoster(id)) {
result.setResultStatus(200);
result.setResultMessage("success");
}
return result;
}
/**
* 功能:删除
* */
@ResponseBody
@RequestMapping(value = "/delete", method = RequestMethod.GET)
public ResultMsg delete(String id) {
ResultMsg result = new ResultMsg();
result.setResultMessage("errors");
if (this.posterService.delPoster(id)) {
result.setResultMessage("success");
}
return result;
}
}
| [
"renlr@outlook.com"
] | renlr@outlook.com |
9fd034c7353c2a88063411d7d25b781fef101e9a | 6500848c3661afda83a024f9792bc6e2e8e8a14e | /gp_JADX/com/google/android/finsky/stream/controllers/assist/C4314e.java | d1f7ad8b87142b826329d88f3c6b5fcb01cf1221 | [] | no_license | enaawy/gproject | fd71d3adb3784d12c52daf4eecd4b2cb5c81a032 | 91cb88559c60ac741d4418658d0416f26722e789 | refs/heads/master | 2021-09-03T03:49:37.813805 | 2018-01-05T09:35:06 | 2018-01-05T09:35:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 598 | java | package com.google.android.finsky.stream.controllers.assist;
import android.view.View;
import android.view.View.OnClickListener;
import com.google.android.finsky.C1473m;
import com.google.android.finsky.p167r.C3960a;
final class C4314e implements OnClickListener {
public final /* synthetic */ C4311b f21764a;
C4314e(C4311b c4311b) {
this.f21764a = c4311b;
}
public final void onClick(View view) {
this.f21764a.m20036b(2820);
C1473m.f7980a.mo2265x();
C3960a.m18663a(false);
C1473m.f7980a.mo2265x();
C3960a.m18665b(false);
}
}
| [
"genius.ron@gmail.com"
] | genius.ron@gmail.com |
a044fe52e0c287c223420aad4d06f4d9a6da715a | b9b9565b63606a55f8be879244cd9aa5a245e778 | /sym4j/src/main/java/org/sym4j/domains/Interval.java | fe982ebe34eb07e683a0cd27d0b8915ca35dcbca | [] | no_license | javaNoviceProgrammer/science4j | 750929eb9deb2ded2bc7f7c93926e983d71dcee6 | 15d4e9f18ba3d8a1cd03d36237b39b3ba647c84e | refs/heads/main | 2023-08-01T01:15:50.291556 | 2021-09-10T12:04:46 | 2021-09-10T12:04:46 | 302,030,587 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,872 | java | package org.sym4j.domains;
import static org.sym4j.symbolic.symbols.Symbol.x;
import org.sym4j.math.Transformation;
import org.sym4j.symbolic.Expr;
import org.sym4j.symbolic.symbols.SymDouble;
public class Interval extends Domain1D {
Expr start;
Expr end;
public Interval(Expr start, Expr end) {
super("["+start+","+end+"]", x);
this.start = start;
this.end = end;
}
public Interval(Expr start, Expr end, Expr coordVar) {
super("["+start+","+end+"]", coordVar);
this.start = start;
this.end = end;
}
public Expr getStart() {
return start;
}
public Expr getEnd() {
return end;
}
/**
* Define a interval by giving two number of the bounds
* @param start
* @param end
* @return
*/
public static <T1, T2> Interval apply(T1 start, T2 end) {
Expr s = null, e = null;
if(start instanceof Number) {
s = new SymDouble(((Number)start).doubleValue());
} else {
s = (Expr)start;
}
if(end instanceof Number) {
e = new SymDouble(((Number)end).doubleValue());
} else {
e = (Expr)end;
}
return new Interval(s, e);
}
public static <T1, T2> Interval apply(T1 start, T2 end, Expr coordVar) {
Expr s = null, e = null;
if(start instanceof Number) {
s = new SymDouble(((Number)start).doubleValue());
} else {
s = (Expr)start;
}
if(end instanceof Number) {
e = new SymDouble(((Number)end).doubleValue());
} else {
e = (Expr)end;
}
return new Interval(s, e, coordVar);
}
@Override
public String toString() {
return "interval("+this.getCoordVars()[0]+","+start+","+end+","+this.getStepSize()+")";
}
@Override
public Domain transform(String label, Transformation trans) {
Expr from = trans.getFromVars()[0];
Expr to = trans.getToVars()[0];
Expr toSolve = trans.eqs[0].solve(to);
return new Interval(
toSolve.subs(from, start),
toSolve.subs(from, end),
to);
}
}
| [
"meisam@cpe-104-162-226-195.nyc.res.rr.com"
] | meisam@cpe-104-162-226-195.nyc.res.rr.com |
6856e60e6a91d25c384b356d5064c283766fa80f | 950047cc0e9b6daf65d909d7aba4d48ef1587c6a | /app/src/main/java/android/example/arabicdictionary/Dictionaries/TopWords.java | afc44ed7a13855f278d484a5e00dc05f20572f92 | [] | no_license | Yerr0r/LearnArabic | 2a95c27d0f1746c087c0394ac8ff929c35fd3f44 | 51b4ab098ce6e4937bb9811e687cbb1bbc98fd3f | refs/heads/master | 2020-12-29T16:47:05.841191 | 2020-02-06T11:40:56 | 2020-02-06T11:40:56 | 238,674,708 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 408 | java | package android.example.arabicdictionary.Dictionaries;
import android.example.arabicdictionary.R;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class TopWords extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_family_members);
}
}
| [
"incredible.soliman@yahoo.com"
] | incredible.soliman@yahoo.com |
acdd5423d17e843578daa9f25edc88de2774b5f9 | bdb02162bb00bfae64aa629b2d077e1c9bee0c4b | /src/main/java/com/bruno/pontointeligente/api/services/impl/EmpresaServiceImpl.java | f08a8fc6fdd210b74deb65d19d00af449351c449 | [] | no_license | BrunoAntonio/API-RESTful-avan-ada | f05b55c00965c6b2eae64b1154ae08ca0d8e68bf | 0401cb6f28453078beb7f5c2c040b8353c070f06 | refs/heads/master | 2020-04-25T11:20:46.151722 | 2019-02-26T15:49:32 | 2019-02-26T15:49:32 | 172,741,505 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,007 | java | package com.bruno.pontointeligente.api.services.impl;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bruno.pontointeligente.api.entities.Empresa;
import com.bruno.pontointeligente.api.repositories.EmpresaRepository;
import com.bruno.pontointeligente.api.services.EmpresaService;
@Service
public class EmpresaServiceImpl implements EmpresaService {
private static final Logger log = LoggerFactory.getLogger(EmpresaServiceImpl.class);
@Autowired
private EmpresaRepository empresaRepository;
@Override
public Optional<Empresa> buscarPorCnpj(String cnpj) {
log.info("Buscando uma empresa para o CNPJ {}", cnpj);
return Optional.ofNullable(empresaRepository.findByCnpj(cnpj));
}
@Override
public Empresa persistir(Empresa empresa) {
log.info("Persistindo empresa: {}", empresa);
return this.empresaRepository.save(empresa);
}
}
| [
"brunocabanas@hotmail.com"
] | brunocabanas@hotmail.com |
2df3369b74e36b8bfd0509bc0708d7cf96a47a5a | 214986576a591d58d2f8b5a6e3607ffb58b2aebd | /src/Position.java | 1c79f5cc78cb2b6e80bde6453bf9b280e9fe6769 | [] | no_license | SBTheTurtle/TeamProjectSER2016 | 9d5aa85d719acb5faf37402d37d3975e1b7b87ff | bf8648fd7691bce29e786b57d8e3d9874f219f92 | refs/heads/master | 2021-01-18T19:39:26.660090 | 2016-02-29T22:40:37 | 2016-02-29T22:40:37 | 52,829,894 | 0 | 0 | null | 2016-02-29T22:33:52 | 2016-02-29T22:33:52 | null | UTF-8 | Java | false | false | 1,494 | java | public class Position {
private boolean isWall = false;
private boolean isBlank = false;
private boolean isPellet = false;
private boolean isFork = false;
private GameObject occupiedBy = null;
public Position(boolean isWall, boolean isBlank, boolean isPellet, boolean isFork){
this.isWall = isWall;
this.isBlank = isBlank;
this.isPellet = isPellet;
this.isFork = isFork;
}
/**
* @return the isWall
*/
public boolean isWall(){
return isWall;
}
/**
* @return the isFork
*/
public boolean isFork(){
return isFork;
}
/**
*
* @return isBlank
*/
public boolean isBlank(){
return isBlank;
}
/**
*
* @return isPellet
*/
public boolean isPellet(){
return isPellet;
}
/**
* Removes the pellet from this position and makes it blank.
*/
public void removePellet(){
isBlank = true;
isPellet = false;
}
/**
* Checks to see if a space is occupied returns true is it is,
* false if it is not occupied.
* @return Whether the space is currently occupied
*/
public boolean getIsOccupiedBy() {
if(occupiedBy != null){
return true;
}
return false;
}
public GameObject getOccupiedBy() {
return occupiedBy;
}
/**
* Sets the position to be occupied by the object calling it.
* @param occupiedBy The object who called they function.
*/
public void setOccupiedBy(GameObject occupiedBy) {
this.occupiedBy = occupiedBy;
}
} | [
"janice@janicewallace.net"
] | janice@janicewallace.net |
7306867d717e82aa5ad43e86f21bf046d5f7e6eb | 95c26825a576ee5493a25a8258a91ad917af8100 | /app/src/main/java/com/petmeds1800/model/entities/PetEducationCategoriesResponse.java | 497b3d24c636654391ef3f3240d0d5c1025f9d2a | [] | no_license | kbirudoju/1800-PetMeds-Android | 7395b8b6918e62c632a9a9a3eb9f243a878c2c53 | 0ebab0f8932c6122c082ab6556e83b215327d172 | refs/heads/master | 2021-07-18T03:50:48.032175 | 2017-04-25T13:19:31 | 2017-04-25T13:19:31 | 108,044,745 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 392 | java | package com.petmeds1800.model.entities;
import java.util.List;
/**
* Created by Digvijay on 10/25/2016.
*/
public class PetEducationCategoriesResponse {
private Status status;
private List<PetEducationCategory> categories;
public Status getStatus() {
return status;
}
public List<PetEducationCategory> getCategories() {
return categories;
}
}
| [
"dgirase@dminc.com"
] | dgirase@dminc.com |
0a58d745c9e4947f5310dca562ba86671173c2d3 | dd8fb834f78b5ad65c1c6c1529ba851fc8865555 | /modules/Core/src/main/java/com/nelsontron/core/util/BukkitUtil.java | 58229abd20b1128f61dbf30848ad26e410b62554 | [
"Apache-2.0"
] | permissive | nelsondev/mine-code | 7fb5c3d203cc4be20ef20ca139f00750afcb0a40 | 451ce112469c760ea7affa06ee937aa3c12297a0 | refs/heads/master | 2023-05-25T23:26:41.944749 | 2020-05-01T05:42:44 | 2020-05-01T05:42:44 | 247,822,009 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,047 | java | package com.nelsontron.core.util;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.PluginCommand;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
public class BukkitUtil {
public static void registerCommands(JavaPlugin plugin, CommandExecutor executor, String ...commands) {
for (String label : commands) {
PluginCommand command = plugin.getCommand(label);
if (command == null) {
plugin.getLogger().severe("COMMAND \"" + label + "\" couldn't be registered...");
return;
}
command.setExecutor(executor);
}
}
public static Player getPlayer(String name) {
Player result = null;
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.getDisplayName().equalsIgnoreCase(name)) {
result = player;
break;
}
}
return result;
}
public static ChatColor getChatColor(String name) {
ChatColor result = null;
for (ChatColor c : ChatColor.class.getEnumConstants()) {
if (c.name().equalsIgnoreCase(name)) {
result = c;
}
}
return result;
}
public static FileConfiguration getSqliteConfig(JavaPlugin plugin) {
InputStream stream = plugin.getResource("sqlite.yml");
InputStreamReader reader;
reader = new InputStreamReader(Objects.requireNonNull(stream));
return YamlConfiguration.loadConfiguration(reader);
}
public static int randInt(int min, int max) {
// NOTE: This will (intentionally) not run as written so that folks
// copy-pasting have to think about how to initialize their
// Random instance. Initialization of the Random instance is outside
// the main scope of the question, but some decent options are to have
// a field that is initialized once and then re-used as needed or to
// use ThreadLocalRandom (if using at least Java 1.7).
//
// In particular, do NOT do 'Random rand = new Random()' here or you
// will get not very good / not very random results.
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
| [
"nelsontron@outlook.com"
] | nelsontron@outlook.com |
a95a11fb904579c4e0b6cf005f14e3517e145174 | 761566d67eccf34870735ffa7ea72ebeca88916a | /app/src/main/java/info/latenightbus/latenightbus/MainActivity.java | 4e4cecf60b543bc5134c3b5803da7d3e96dc31ca | [] | no_license | thilln/latenightbus | 2ca74301af1fcb9c3b67b2665f5789f23b7d0b0f | c467c71b5ae74a8a1bb1bf52f1f612d83c538586 | refs/heads/master | 2020-09-15T00:45:50.076738 | 2016-08-18T08:29:05 | 2016-08-18T08:29:05 | 65,978,838 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 343 | java | package info.latenightbus.latenightbus;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| [
"paul.thillen@hotmail.com"
] | paul.thillen@hotmail.com |
7eb6356376a6759d938a95d2fc6fd100bd813b34 | f0e6b626cff2a2d7ae23fb8fe2365acb608ee1c2 | /src/Test.java | 42288ce0d99f79d81a07fad57f943e022f9b3e57 | [] | no_license | siya2009/coreJavaPractise | ade0ce5d7545243dc1017521dd505ec302fd60fa | 8729f0bfa2b22c27bbb59082ed27be0fe977f0e2 | refs/heads/master | 2021-06-28T03:26:03.505593 | 2021-06-09T05:22:31 | 2021-06-09T05:22:31 | 234,552,533 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 434 | java | public class Test {
public static void main(String[] args) {
String s = "racebcar";
String reverse = "";
for (int i = s.length() -1; i >= 0; i--) {
reverse = reverse+s.charAt(i);
System.out.println(s.charAt(i));
}
System.out.println("Reverse string "+reverse);
if (s.equals(reverse)) {
System.out.println("String is palindrom");
}else {
System.out.println("String is not palindrom");
}
}
}
| [
"shashipratap333@gmail.com"
] | shashipratap333@gmail.com |
905da5317d217b03316cc1a7fd3cbfb09ccb34b5 | 5385695565725e18e059fb7f3073f20c1e4e13c1 | /branches/zhela_web/src/com/zhelazhela/cloudblog/domain/MessageList.java | 875fa887ea16636935b055482060af5d412c0d1e | [] | no_license | azulblaze/shareyourlife | 42928a8f8d4932d7b2aa023735cbe6a79394d2ad | 3524d29ec116cd88eb4db67b7162a5e9fb669935 | refs/heads/master | 2022-08-09T15:48:46.893671 | 2011-04-10T13:14:41 | 2011-04-10T13:14:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 369 | java | package com.zhelazhela.cloudblog.domain;
public class MessageList extends BaseList {
public MessageList(){
super("messagelist");
}
private java.util.List<Message> messages;
public java.util.List<Message> getMessages() {
return messages;
}
public void setMessages(java.util.List<Message> messages) {
this.messages = messages;
}
}
| [
"yan925@gmail.com"
] | yan925@gmail.com |
d22f8c82e1d7db67c1e8f376b7704d8d0217bb5c | d730aad001bd87894bbd699b249831ce803da8b7 | /src/wikipediapckg/pageRank/hadoop/job/WikiMapReduceIterator.java | 6a49cc3862b026c68a402725b22c46758149928c | [] | no_license | didinyah/Projet_TDLE | bcec7e4db40cb707cf3435c4030f3435ce475e05 | b1be2cb424b6a7cae42d2c8db5814296ccd1f195 | refs/heads/master | 2021-01-21T15:48:38.466766 | 2017-05-18T10:25:10 | 2017-05-18T10:25:10 | 91,857,326 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,187 | java | package wikipediapckg.pageRank.hadoop.job;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Locale;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class WikiMapReduceIterator
{
private static String OUTPUTFOLDER = "hadoop" ;
private static String OUTPUTFILENAME = "job2n";
private int iteration = 10;
private static double damping = 0.85;
private static int nombresPages = 1;
/**
* Classe utilisee pour le Mapper de texte il le prepare pour le {@link RankerReducer}
* @author dinar
*
*/
public static class RankerMapper
extends Mapper<LongWritable, Text, Text, Text>{
public void map(LongWritable key, Text value,
Context context)
throws IOException, InterruptedException {
StringTokenizer itrFile = new StringTokenizer(value.toString(),"\n");
while (itrFile.hasMoreTokens()) {
String ligne = itrFile.nextToken();
String[] elems = ligne.split("\t");
// Page_Or valeur liensExterne
if(elems.length == 2)
{
context.write(new Text(elems[0]), new Text("!"));
}
if(elems.length == 3)
{
String[] liens = elems[2].split(",");
if(liens.length != 0)
{
for( String lien : liens)
{
context.write(new Text(lien),
new Text(elems[0]+"\t"+elems[1]+"\t"+ liens.length ));
}
}
//Ecriture de lien original
context.write(new Text(elems[0]), new Text('|'+elems[2]));
}
}
}
}
/**
* Permet de reduire le mapiing du {@link RankerMapper} sous forme de
* @author dinar
*
*/
public static class RankerReducer
extends Reducer<Text,Text,Text,Text>{
public void reduce(Text key, Iterable<Text> values,
Context context
) throws IOException, InterruptedException {
//boolean pageEstExistante = false;
String link = "";
double sommePageAvecLien = 0;
for(Text val :values)
{
String mot = val.toString();
/*if(mot.equals("!"))
{
pageEstExistante = true;
}*/
if(mot.startsWith("|"))
{
link = "\t" +mot.substring(1);
}
else
{
String[] chiffres = mot.split("\t");
if(chiffres.length == 3)
{
double rank = Double.valueOf(chiffres[1]);
int nombreLiens = Integer.valueOf(chiffres[2]);
sommePageAvecLien += rank/nombreLiens;
}
}
}
//if(pageEstExistante)
//{
double newRank = (damping * sommePageAvecLien + (1-damping)/nombresPages);
if(!link.isEmpty())
context.write(key,new Text( String.format(Locale.ENGLISH,"%.10f",newRank)+link ));
else
context.write(key,new Text( String.format(Locale.ENGLISH,"%.10f",newRank)));
//}
}
}
/**
* Constructeur de base
* permet de definir la valeur de base de damping et le nomre d'iteration a faire
* @param damping la valeur constante utilise a chaque iteration du MapReducer
* @param iteration le nombre de mapreduce a effectue
*/
public WikiMapReduceIterator(double damping,int iteration)
{
this.iteration = iteration;
//this.iteration =1;
WikiMapReduceIterator.damping = damping;
}
/**
* permet de lancer loperation de Map Reduce
* @param input
* @return
* @throws IllegalArgumentException
* @throws IOException
* @throws ClassNotFoundException
* @throws InterruptedException
*/
public String launch(String input,int nombrePages) throws IllegalArgumentException, IOException, ClassNotFoundException, InterruptedException
{
File inputFile = new File(input);
if(!inputFile.exists())
{
throw new FileNotFoundException("le fichier n'existe pas");
}
WikiMapReduceIterator.nombresPages = nombrePages;
String oldPath = input;
for(int i = 0 ; i < iteration ;i++ )
{
if(i!= 0)
{
oldPath = oldPath+"/part-r-00000";
}
String newPath = OUTPUTFOLDER + "/" + OUTPUTFILENAME + i;
File outputfile = new File(newPath);
suppressionRecursive(outputfile);
Configuration conf = new Configuration();
Job job = new Job(conf,"iterationPageRank");
job.setJarByClass(WikiMapReduceIterator.class);
job.setMapperClass(RankerMapper.class);
//job.setCombinerClass(RankerReducer.class);
job.setReducerClass(RankerReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileInputFormat.setInputPaths(job, new Path(oldPath));
FileOutputFormat.setOutputPath(job, new Path(newPath));
//Lancement du job
job.waitForCompletion(true);
oldPath = newPath;
}
if(iteration!= 0)
{
oldPath = oldPath+"/part-r-00000";
}
return oldPath;
}
public void suppressionRecursive(File outputfile) {
if(outputfile.isDirectory())
{
for (File file : outputfile.listFiles())
{
suppressionRecursive(file);
}
}
outputfile.delete();
}
} | [
"dinark1995@gmail.com"
] | dinark1995@gmail.com |
d9ae2baa9736cb886ef25cf39f800344ee930b1b | 80576460f983a1ce5e11348e144257d6a2e12a97 | /Entidades/ContaCapitalEntidadesEJB/src/main/java/br/com/sicoob/cca/entidades/negocio/enums/EnumSituacaoArquivoRemessa.java | 3e7eb6a001dd27707ef609b184ab0d8c563d3e8c | [] | no_license | pabllo007/cca | 8d3812e403deccdca5ba90745b188e10699ff44c | 99c24157ff08459ea3e7c2415ff75bcb6a0102e4 | refs/heads/master | 2022-12-01T05:20:26.998529 | 2019-10-27T21:33:11 | 2019-10-27T21:33:11 | 217,919,304 | 0 | 0 | null | 2022-11-24T06:24:00 | 2019-10-27T21:31:25 | Java | ISO-8859-1 | Java | false | false | 1,606 | java | package br.com.sicoob.cca.entidades.negocio.enums;
public enum EnumSituacaoArquivoRemessa {
/** O atributo COD_SITUACAO_ARQUIVO_REMESSA_EM_ABERTO. */
COD_SITUACAO_ARQUIVO_REMESSA_EM_ABERTO(0,"EM ABERTO"),
/** O atributo COD_SITUACAO_ARQUIVO_REMESSA_PROCESSADO_PARA_DEBITO. */
COD_SITUACAO_ARQUIVO_REMESSA_PROCESSADO_PARA_DEBITO(1,"PROCESSADO PARA DEBITO"),
/** O atributo COD_SITUACAO_ARQUIVO_REMESSA_PROCESSADO_PARA_LIQUIDACAO. */
COD_SITUACAO_ARQUIVO_REMESSA_PROCESSADO_PARA_LIQUIDACAO(2,"PROCESSADO PARA LIQUIDACAO"),
/** O atributo COD_SITUACAO_ARQUIVO_REMESSA_ARQUIVO_INVALIDO. */
COD_SITUACAO_ARQUIVO_REMESSA_ARQUIVO_INVALIDO(3,"ARQUIVO INVALIDO"),
/** O atributo COD_SITUACAO_ARQUIVO_REMESSA_NAO_ENVIADO. */
COD_SITUACAO_ARQUIVO_REMESSA_NAO_ENVIADO(4,"NÃO ENVIADO"),
/** O atributo COD_SITUACAO_ARQUIVO_REMESSA_PROCESSADO_PARA_CREDITO. */
COD_SITUACAO_ARQUIVO_REMESSA_PROCESSADO_PARA_CREDITO(5,"PROCESSADO PARA CREDITO");
/** O atributo codigo. */
private Integer codigo;
/** O atributo descricao. */
private String descricao;
/**
* Instancia um novo EnumSituacaoContaCapital.
*
* @param codigo o valor de codigo
* @param descricao o valor de descricao
*/
private EnumSituacaoArquivoRemessa(Integer codigo, String descricao) {
this.codigo = codigo;
this.descricao = descricao;
}
/**
* Recupera o valor de codigo.
*
* @return o valor de codigo
*/
public Integer getCodigo() {
return codigo;
}
/**
* Recupera o valor de descricao.
*
* @return o valor de descricao
*/
public String getDescricao() {
return descricao;
}
}
| [
"="
] | = |
52635aa113745f54def407e8d3128c97997b7e4c | 5b8c2dd9fcd176f5c77b959c8357402e7ce0474d | /lambda-workflow-core/src/main/java/com/yatop/lambda/workflow/core/mgr/workflow/execution/queue/TaskQueueHelper.java | c94fa4ed5e8d980cd069cb44ad35f5fb46d76cb3 | [] | no_license | ruhengChen/lambda-mls | 6cbfc5804193f68bbc98a5900d7e3fa91cf6ef00 | 2450c25c25c91bb3af1946fbf21206a6636d71d0 | refs/heads/master | 2020-04-20T05:45:30.853959 | 2019-02-13T02:36:57 | 2019-02-13T02:36:57 | 168,664,310 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 103 | java | package com.yatop.lambda.workflow.core.mgr.workflow.execution.queue;
public class TaskQueueHelper {
}
| [
"tomlee714@126.com"
] | tomlee714@126.com |
49b5ad6b3ade3361ca99d69a4d7caf83a343c679 | 594d2bf8deb11f2f978b157536358702a6a97c76 | /src/main/java/org/crosslifebiblechurch/clifeserver/service/MongoUserDetailsService.java | 8a64079fa55e7e4c878e52aea3d68b50df9ffb62 | [
"Apache-2.0"
] | permissive | yuheji/SpringTest | f6ee432042222955d4d841b130fc255f94acd690 | 104bc451ab8a8f0c1408ae52979ba7ca881b7e1c | refs/heads/master | 2021-05-14T10:30:18.692319 | 2018-01-05T07:37:13 | 2018-01-05T07:37:13 | 116,356,430 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,314 | java | package org.crosslifebiblechurch.clifeserver.service;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.crosslifebiblechurch.clifeserver.utils.MongoUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.List;
public class MongoUserDetailsService implements UserDetailsService {
@Autowired
private MongoClient mongoClient;
/**
* Locates the user based on the username. In the actual implementation, the search
* may possibly be case sensitive, or case insensitive depending on how the
* implementation instance is configured. In this case, the <code>UserDetails</code>
* object that comes back may have a username that is of a different case than what
* was actually requested..
*
* @param username the username identifying the user whose data is required.
* @return a fully populated user record (never <code>null</code>)
* @throws UsernameNotFoundException if the user could not be found or the user has no
* GrantedAuthority
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
MongoDatabase database = mongoClient.getDatabase("springsecurity");
MongoCollection<org.bson.Document> collection = database.getCollection("users");
System.out.println("===Got user: " + username + "===");
//Find by username, get rest of info based on that
Document document = collection.find(Filters.eq("username", username)).first();
if(document!=null) {
String password = document.getString("password");
List<String> authorities = (List<String>) document.get("authorities");
return new MongoUserDetails(username, password, authorities.toArray(new String[authorities.size()]));
} else {
throw new UsernameNotFoundException("username not found");
}
}
}
| [
"josh@enthrallsports.com"
] | josh@enthrallsports.com |
6e22ff68a3422bb9effcf5a95c938a4786428d98 | 29fbe1e43a1bfadeea1db9f113be4751c9118aa2 | /JuniorArt/src/main/java/com/juniorArt/JuniorArt/models/Pedidos.java | 2e7934b898d7a23abef36ccf965e48e0aa190d5b | [] | no_license | LuizaSouza00/JuniorArt | 6f7b105f32915233a2094f8fe3f6a4b8e76cc030 | c41eaae20238659ce760a6f4d5b1135d5f359fea | refs/heads/master | 2020-09-29T01:35:10.283841 | 2019-12-09T16:30:06 | 2019-12-09T16:30:06 | 226,915,674 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,437 | java | package com.juniorArt.JuniorArt.models;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.validation.constraints.NotEmpty;
@Entity
public class Pedidos {
@Id
private String nome;
@NotEmpty
private String dataEntrega;
@NotEmpty
private String endereco;
@NotEmpty
private String descricao;
@NotEmpty
private String medidas;
@NotEmpty
private String formato;
@ManyToOne
private Usuario usuario;
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDataEntrega() {
return dataEntrega;
}
public void setDataEntrega(String dataEntrega) {
this.dataEntrega = dataEntrega;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public String getMedidas() {
return medidas;
}
public void setMedidas(String medidas) {
this.medidas = medidas;
}
public String getFormato() {
return formato;
}
public void setFormato(String formato) {
this.formato = formato;
}
}
| [
"20161204010015@LAJ291388.ifrn.local"
] | 20161204010015@LAJ291388.ifrn.local |
9ff23441be4f19917edd956cbaf1534195f8c6be | 0f693d225497b1d70b5259c8e19f368206a7c450 | /src/main/java/com/mousterian/schema/model/jdbc/Table.java | 593794765fcad0be703f12c1e10edac3e0823de0 | [] | no_license | Mousterian/schema-service | 4abfce76e26a69036d20b05955d9177ccd73d208 | aec13c7f8914955c91e4540ede337ef7309f4525 | refs/heads/master | 2021-01-19T20:15:24.823569 | 2017-09-16T21:26:42 | 2017-09-16T21:26:42 | 101,226,022 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 178 | java | package com.mousterian.schema.model.jdbc;
import lombok.Data;
import java.util.List;
public @Data class Table {
private String name;
private List<Column> columns;
}
| [
"psandison@hotmail.com"
] | psandison@hotmail.com |
7bbf701cdc5c566e22c6c03eacc1e104940b7383 | 3415b64a412cb56bb6ac1eabeef893e82a290c4b | /src/main/java/ua/logos/domain/CountryDTO.java | deeffe775676a9ccb013f392344c503fb5bd877f | [] | no_license | RomanPasichnyk/SpringBootHomework | f1aebf34776b873b1746f42460456ef4cfb0c52a | c9dca610f9ef7f02d7ca4b41777555b9e011cd02 | refs/heads/master | 2020-04-04T17:25:54.771287 | 2018-11-04T20:22:55 | 2018-11-04T20:22:55 | 156,120,321 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 217 | java | package ua.logos.domain;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class CountryDTO {
private Long id;
private String name;
}
| [
"rom.pasichnyk@gmail.com"
] | rom.pasichnyk@gmail.com |
3374e8344cfe73659a30f148f6c62240528250fb | ca7a501e6b72918d4ff50232a4ce16d194eff20f | /Java.Chess/src/com/company/engine/Classic/Pieces/King.java | 2f95c4fd05554a48c4a7f88e3a9842d06eccd3d9 | [] | no_license | NatetheGrate06/Jchess | 79e291fa300ae3e7fdb0d60ed2116db280341861 | 5d6ba3ea4a2fe0c01a6159d10a6498508030e62c | refs/heads/master | 2020-11-26T18:42:07.761326 | 2019-12-20T02:43:24 | 2019-12-20T02:43:24 | 229,176,117 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,863 | java | package com.company.engine.Classic.Pieces;
import com.company.engine.Classic.Alliance;
import com.company.engine.Classic.board.Board;
import com.company.engine.Classic.board.BoardUtils;
import com.company.engine.Classic.board.Move;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public final class King extends Piece {
private final static int[] CANDIDATE_MOVE_COORDINATES = { -9, -8, -7, -1, 1, 7, 8, 9 };
public King(final Alliance pieceAlliance,
final int piecePosition) {
super(PieceType.KING, pieceAlliance, piecePosition, true);
}
@Override
public Collection<Move> calculateLegalMoves(final Board board) {
final List<Move> legalMoves = new ArrayList<>();
for (final int currentCandidateOffset : CANDIDATE_MOVE_COORDINATES) {
if (isFirstColumnExclusion(this.piecePosition, currentCandidateOffset) ||
isEighthColumnExclusion(this.piecePosition, currentCandidateOffset)) {
continue;
}
final int candidateDestinationCoordinate = this.piecePosition + currentCandidateOffset;
if (BoardUtils.isValidTileCoordinate(candidateDestinationCoordinate)) {
final Piece pieceAtDestination = board.getPiece(candidateDestinationCoordinate);
if (pieceAtDestination == null) {
legalMoves.add(new Move.MajorMove(board, this, candidateDestinationCoordinate));
} else {
final Alliance pieceAtDestinationAllegiance = pieceAtDestination.getPieceAlliance();
if (this.pieceAlliance != pieceAtDestinationAllegiance) {
legalMoves.add(new Move.AttackMove(board, this, candidateDestinationCoordinate,
pieceAtDestination));
}
}
}
}
return Collections.unmodifiableList(legalMoves);
}
@Override
public King movePiece(final Move move) {
return new King(move.getMovedPiece().getPieceAlliance(), move.getDestinationCoordinate());
}
@Override
public String toString() {
return this.pieceType.toString();
}
private static boolean isFirstColumnExclusion(final int currentPosition, final int candidateOffset) {
return BoardUtils.EIGHTH_COLUMN[currentPosition] && ((candidateOffset == -9) ||
(candidateOffset == -1) || (candidateOffset == 7));
}
private static boolean isEighthColumnExclusion(final int currentPosition, final int candidateOffset) {
return BoardUtils.EIGHTH_COLUMN[currentPosition] && ((candidateOffset == -7) ||
(candidateOffset == 1) || (candidateOffset == 9));
}
} | [
"noreply@github.com"
] | noreply@github.com |
fc97da7a0900e6e6735d13fedba57a3296dd9c8c | e62c3b93b38d2d7781d38ba1cdbabfea2c1cf7af | /bocbiiclient/src/main/java/com/boc/bocsoft/mobile/bii/bus/fund/model/PsnFundScheduledSellModify/PsnFundScheduledSellModifyResullt.java | 0e72e569bdf4ab9967a80a379a57f471d1a0c8a7 | [] | no_license | soghao/zgyh | df34779708a8d6088b869d0efc6fe1c84e53b7b1 | 09994dda29f44b6c1f7f5c7c0b12f956fc9a42c1 | refs/heads/master | 2021-06-19T07:36:53.910760 | 2017-06-23T14:23:10 | 2017-06-23T14:23:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,179 | java | package com.boc.bocsoft.mobile.bii.bus.fund.model.PsnFundScheduledSellModify;
/**
* Created by huixiaobo on 2016/11/18.
* 039基金定期定额赎回修改—返回参数
*/
public class PsnFundScheduledSellModifyResullt {
/**基金交易流水号*/
private String fundSeq;
/**交易流水号*/
private String transactionId;
/**交易状态*/
private String tranState;
public String getFundSeq() {
return fundSeq;
}
public void setFundSeq(String fundSeq) {
this.fundSeq = fundSeq;
}
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public String getTranState() {
return tranState;
}
public void setTranState(String tranState) {
this.tranState = tranState;
}
@Override
public String toString() {
return "PsnFundScheduledSellModifyResullt{" +
"fundSeq='" + fundSeq + '\'' +
", transactionId='" + transactionId + '\'' +
", tranState='" + tranState + '\'' +
'}';
}
}
| [
"15609143618@163.com"
] | 15609143618@163.com |
a3419bc3c9b6652850ce384b32ffaf6d70b6ac9d | 8116e2b93b079a703ed2cd5315e4c5989e896569 | /Module2/src/library/Controllers/AddObject.java | 01a590eba3b4762b4fbe5ed52ed39ae4aa74205c | [] | no_license | PhanGiaKhanh/C0221G1-CodeGym. | 657e451e21d2c43d9b4018cc617c5eb5c94a8f4c | d28288850f4ace937146df2d556a40bdf71ada7a | refs/heads/main | 2023-08-19T20:02:22.677147 | 2021-09-29T09:52:26 | 2021-09-29T09:52:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,045 | java | package library.Controllers;
import library.commons.MessageException;
import library.commons.Regex;
import javax.swing.*;
import java.util.Scanner;
public class AddObject {
private static Scanner scanner = new Scanner(System.in);
public static String add(String property, String regex) {
String input = null;
while (true) {
try {
System.out.println("Nhập " + property + ": " + regex);
input = scanner.nextLine();
if (!input.matches(regex)) {
throw new MessageException("Lỗi định dạng " + property + ": " + regex);
}
return input;
} catch (MessageException v) {
System.err.println(v.getMessage());
}
}
}
public static String add(String property, String regex, String message) {
String input = null;
while (true){
try {
System.out.println("Nhập " + property + ": " + message);
input = scanner.nextLine();
if (!input.matches(regex)) {
throw new MessageException("Lỗi định dạng " + property + ": " + regex);
}
return input;
} catch (MessageException v) {
System.err.println(v.getMessage());
}
}
}
public static String kiemTraNgoaiLeNhapVao(String property, String regex, Exception exception) {
String nhapThuocTinh;
do {
try {
System.out.println("Nhập: " + property);
nhapThuocTinh = new Scanner(System.in).nextLine();
if (!nhapThuocTinh.matches(regex)) {
throw new Exception();
}
break;
} catch (Exception e) {
System.err.println(exception.getMessage());
System.err.println("Lỗi định dạng: " + regex + "\nNhập lại: ");
}
} while (true);
return nhapThuocTinh;
}
public static void main(String[] args) {
kiemTraNhapVaoTheoDinhDang("ten", Regex.NAME_VN,"Nhập sai tên","chữ cái");
}
public static String kiemTraNhapVaoTheoDinhDang(String thuocTinh, String regex, String tinNhan,String dinhDang) {
String nhap = null;
JOptionPane jOptionPane=new JOptionPane();
Scanner scanner = new Scanner(System.in);
while (true) {
try {
System.out.println("Nhập " + thuocTinh);
nhap = scanner.nextLine();
if (!nhap.matches(regex)) {
JOptionPane.showMessageDialog(jOptionPane,tinNhan,"Lỗi",JOptionPane.ERROR_MESSAGE);
throw new MessageException(tinNhan+"\nVui lòng nhập lại theo định dạng: "+dinhDang);
}
return nhap;
} catch (MessageException e) {
System.err.println(e.getMessage());
}
}
}
}
| [
"phangiakhanh90@gmail.com"
] | phangiakhanh90@gmail.com |
74258fd60df5db632351f4cbd9effa62c45535fc | 34221f3f7738d7a33c693e580dc6a99789349cf3 | /app/src/main/java/defpackage/dgh.java | b26c2f839b5b15ec107c8b60e9f4a0ede6f3e07f | [] | no_license | KobeGong/TasksApp | 0c7b9f3f54bc4be755b1f605b41230822d6f9850 | aacdd5cbf0ba073460797fa76f1aaf2eaf70f08e | refs/heads/master | 2023-08-16T07:11:13.379876 | 2021-09-25T17:38:57 | 2021-09-25T17:38:57 | 374,659,931 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 739 | java | package defpackage;
/* renamed from: dgh reason: default package */
/* compiled from: PG */
public enum dgh implements defpackage.din {
UNKNOWN_INSTRUCTION(0),
SYNC(1),
FULL_SYNC(2);
public static final defpackage.dio d = null;
private final int e;
public final int a() {
return this.e;
}
public static defpackage.dgh a(int i) {
switch (i) {
case 0:
return UNKNOWN_INSTRUCTION;
case 1:
return SYNC;
case 2:
return FULL_SYNC;
default:
return null;
}
}
private dgh(int i) {
this.e = i;
}
static {
d = new defpackage.dgi();
}
}
| [
"droidevapp1023@gmail.com"
] | droidevapp1023@gmail.com |
202b1653f3a3cca921ebc74926de01d42b34c671 | 6e56d3af5ce971e51bdd66f60334b424f66125e5 | /src/main/java/services/StorePostApi.java | 15fde244efc979988cdaf005aa8f0232954ad9a5 | [] | no_license | ElenaMayorova/Otus | d4be5f28ec802bf1096f9b4cf16045745dfd9410 | 4b5d956ff9b5fe8f837b775b426716cf650d9b92 | refs/heads/master | 2023-07-01T14:44:48.209174 | 2021-08-13T16:37:21 | 2021-08-13T16:37:21 | 375,042,753 | 0 | 0 | null | 2021-08-10T09:26:58 | 2021-06-08T14:39:37 | Java | UTF-8 | Java | false | false | 1,187 | java | package services;
import dto.StorePost;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import static io.restassured.RestAssured.given;
public class StorePostApi {
public static final String BASA_URI = "https://petstore.swagger.io/v2/";
private RequestSpecification spec;
public static final String STOREPOST = "/store/order";
public static final String STOREGET = "/store/order/{orderId}";
public StorePostApi() {
spec = given()
.baseUri(BASA_URI)
.contentType(ContentType.JSON);
}
public Response createStore(StorePost storePost) {
return
given(spec)
.with()
.body(storePost)
.log().all()
.when()
.post(STOREPOST);
}
public Response getStore(Integer id) {
return
given(spec)
.pathParam("orderId", id)
.log().all()
.when()
.get(STOREGET);
}
}
| [
"mayorova_helen@mail.ru"
] | mayorova_helen@mail.ru |
9d1ed40c41f32924f6d75d786d546b6bbfc85fd6 | 599650407dcace4dc83caeed81a30beb1c6a254f | /AsistenteNutricionalUdeA/app/build/generated/source/r/debug/android/support/v7/recyclerview/R.java | bf6e8b803752acfe8eac63b6630323a1585132b8 | [] | no_license | JoanMarin/UdeA | cf59f608a7687f3772266b8ec9a9cafaf2f7d985 | cd67f36bcfaa27dd5aca3f5ff657a6429744b098 | refs/heads/master | 2023-01-07T15:02:14.269710 | 2019-08-06T19:45:22 | 2019-08-06T19:45:22 | 200,914,137 | 1 | 0 | null | 2023-01-05T21:55:11 | 2019-08-06T19:43:21 | Jupyter Notebook | UTF-8 | Java | false | false | 12,033 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package android.support.v7.recyclerview;
public final class R {
public static final class attr {
public static final int coordinatorLayoutStyle = 0x7f03006f;
public static final int fastScrollEnabled = 0x7f030093;
public static final int fastScrollHorizontalThumbDrawable = 0x7f030094;
public static final int fastScrollHorizontalTrackDrawable = 0x7f030095;
public static final int fastScrollVerticalThumbDrawable = 0x7f030096;
public static final int fastScrollVerticalTrackDrawable = 0x7f030097;
public static final int font = 0x7f030098;
public static final int fontProviderAuthority = 0x7f03009a;
public static final int fontProviderCerts = 0x7f03009b;
public static final int fontProviderFetchStrategy = 0x7f03009c;
public static final int fontProviderFetchTimeout = 0x7f03009d;
public static final int fontProviderPackage = 0x7f03009e;
public static final int fontProviderQuery = 0x7f03009f;
public static final int fontStyle = 0x7f0300a0;
public static final int fontWeight = 0x7f0300a1;
public static final int keylines = 0x7f0300bb;
public static final int layoutManager = 0x7f0300bd;
public static final int layout_anchor = 0x7f0300be;
public static final int layout_anchorGravity = 0x7f0300bf;
public static final int layout_behavior = 0x7f0300c0;
public static final int layout_dodgeInsetEdges = 0x7f0300ec;
public static final int layout_insetEdge = 0x7f0300f5;
public static final int layout_keyline = 0x7f0300f6;
public static final int reverseLayout = 0x7f03012a;
public static final int spanCount = 0x7f030139;
public static final int stackFromEnd = 0x7f03013f;
public static final int statusBarBackground = 0x7f030143;
}
public static final class bool {
public static final int abc_action_bar_embed_tabs = 0x7f040000;
}
public static final class color {
public static final int notification_action_color_filter = 0x7f05004f;
public static final int notification_icon_bg_color = 0x7f050050;
public static final int ripple_material_light = 0x7f05005b;
public static final int secondary_text_default_material_light = 0x7f05005d;
}
public static final class dimen {
public static final int compat_button_inset_horizontal_material = 0x7f06004d;
public static final int compat_button_inset_vertical_material = 0x7f06004e;
public static final int compat_button_padding_horizontal_material = 0x7f06004f;
public static final int compat_button_padding_vertical_material = 0x7f060050;
public static final int compat_control_corner_material = 0x7f060051;
public static final int fastscroll_default_thickness = 0x7f06007b;
public static final int fastscroll_margin = 0x7f06007c;
public static final int fastscroll_minimum_range = 0x7f06007d;
public static final int item_touch_helper_max_drag_scroll_per_frame = 0x7f060085;
public static final int item_touch_helper_swipe_escape_max_velocity = 0x7f060086;
public static final int item_touch_helper_swipe_escape_velocity = 0x7f060087;
public static final int notification_action_icon_size = 0x7f06008a;
public static final int notification_action_text_size = 0x7f06008b;
public static final int notification_big_circle_margin = 0x7f06008c;
public static final int notification_content_margin_start = 0x7f06008d;
public static final int notification_large_icon_height = 0x7f06008e;
public static final int notification_large_icon_width = 0x7f06008f;
public static final int notification_main_column_padding_top = 0x7f060090;
public static final int notification_media_narrow_margin = 0x7f060091;
public static final int notification_right_icon_size = 0x7f060092;
public static final int notification_right_side_padding_top = 0x7f060093;
public static final int notification_small_icon_background_padding = 0x7f060094;
public static final int notification_small_icon_size_as_large = 0x7f060095;
public static final int notification_subtext_size = 0x7f060096;
public static final int notification_top_pad = 0x7f060097;
public static final int notification_top_pad_large_text = 0x7f060098;
}
public static final class drawable {
public static final int notification_action_background = 0x7f07007e;
public static final int notification_bg = 0x7f07007f;
public static final int notification_bg_low = 0x7f070080;
public static final int notification_bg_low_normal = 0x7f070081;
public static final int notification_bg_low_pressed = 0x7f070082;
public static final int notification_bg_normal = 0x7f070083;
public static final int notification_bg_normal_pressed = 0x7f070084;
public static final int notification_icon_background = 0x7f070085;
public static final int notification_template_icon_bg = 0x7f070086;
public static final int notification_template_icon_low_bg = 0x7f070087;
public static final int notification_tile_bg = 0x7f070088;
public static final int notify_panel_notification_icon_bg = 0x7f070089;
}
public static final class id {
public static final int action_container = 0x7f08000e;
public static final int action_divider = 0x7f080010;
public static final int action_image = 0x7f080011;
public static final int action_text = 0x7f080018;
public static final int actions = 0x7f080019;
public static final int async = 0x7f080023;
public static final int blocking = 0x7f080027;
public static final int bottom = 0x7f080028;
public static final int chronometer = 0x7f080034;
public static final int end = 0x7f08004b;
public static final int forever = 0x7f080058;
public static final int icon = 0x7f080065;
public static final int icon_group = 0x7f080066;
public static final int info = 0x7f08006d;
public static final int italic = 0x7f08006f;
public static final int item_touch_helper_previous_elevation = 0x7f080071;
public static final int left = 0x7f080073;
public static final int line1 = 0x7f080074;
public static final int line3 = 0x7f080075;
public static final int none = 0x7f080091;
public static final int normal = 0x7f080092;
public static final int notification_background = 0x7f080093;
public static final int notification_main_column = 0x7f080094;
public static final int notification_main_column_container = 0x7f080095;
public static final int right = 0x7f0800a3;
public static final int right_icon = 0x7f0800a4;
public static final int right_side = 0x7f0800a5;
public static final int start = 0x7f0800ca;
public static final int tag_transition_group = 0x7f0800cf;
public static final int text = 0x7f0800d0;
public static final int text2 = 0x7f0800d1;
public static final int time = 0x7f0800da;
public static final int title = 0x7f0800db;
public static final int top = 0x7f0800df;
}
public static final class integer {
public static final int status_bar_notification_info_maxnum = 0x7f090009;
}
public static final class layout {
public static final int notification_action = 0x7f0a0039;
public static final int notification_action_tombstone = 0x7f0a003a;
public static final int notification_template_custom_big = 0x7f0a0041;
public static final int notification_template_icon_group = 0x7f0a0042;
public static final int notification_template_part_chronometer = 0x7f0a0046;
public static final int notification_template_part_time = 0x7f0a0047;
}
public static final class string {
public static final int status_bar_notification_info_overflow = 0x7f0d0045;
}
public static final class style {
public static final int TextAppearance_Compat_Notification = 0x7f0e00f0;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0e00f1;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0e00f3;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0e00f6;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0e00f8;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0e0172;
public static final int Widget_Compat_NotificationActionText = 0x7f0e0173;
public static final int Widget_Support_CoordinatorLayout = 0x7f0e017f;
}
public static final class styleable {
public static final int[] CoordinatorLayout = { 0x7f0300bb, 0x7f030143 };
public static final int CoordinatorLayout_keylines = 0;
public static final int CoordinatorLayout_statusBarBackground = 1;
public static final int[] CoordinatorLayout_Layout = { 0x010100b3, 0x7f0300be, 0x7f0300bf, 0x7f0300c0, 0x7f0300ec, 0x7f0300f5, 0x7f0300f6 };
public static final int CoordinatorLayout_Layout_android_layout_gravity = 0;
public static final int CoordinatorLayout_Layout_layout_anchor = 1;
public static final int CoordinatorLayout_Layout_layout_anchorGravity = 2;
public static final int CoordinatorLayout_Layout_layout_behavior = 3;
public static final int CoordinatorLayout_Layout_layout_dodgeInsetEdges = 4;
public static final int CoordinatorLayout_Layout_layout_insetEdge = 5;
public static final int CoordinatorLayout_Layout_layout_keyline = 6;
public static final int[] FontFamily = { 0x7f03009a, 0x7f03009b, 0x7f03009c, 0x7f03009d, 0x7f03009e, 0x7f03009f };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x01010532, 0x01010533, 0x0101053f, 0x7f030098, 0x7f0300a0, 0x7f0300a1 };
public static final int FontFamilyFont_android_font = 0;
public static final int FontFamilyFont_android_fontWeight = 1;
public static final int FontFamilyFont_android_fontStyle = 2;
public static final int FontFamilyFont_font = 3;
public static final int FontFamilyFont_fontStyle = 4;
public static final int FontFamilyFont_fontWeight = 5;
public static final int[] RecyclerView = { 0x010100c4, 0x010100f1, 0x7f030093, 0x7f030094, 0x7f030095, 0x7f030096, 0x7f030097, 0x7f0300bd, 0x7f03012a, 0x7f030139, 0x7f03013f };
public static final int RecyclerView_android_orientation = 0;
public static final int RecyclerView_android_descendantFocusability = 1;
public static final int RecyclerView_fastScrollEnabled = 2;
public static final int RecyclerView_fastScrollHorizontalThumbDrawable = 3;
public static final int RecyclerView_fastScrollHorizontalTrackDrawable = 4;
public static final int RecyclerView_fastScrollVerticalThumbDrawable = 5;
public static final int RecyclerView_fastScrollVerticalTrackDrawable = 6;
public static final int RecyclerView_layoutManager = 7;
public static final int RecyclerView_reverseLayout = 8;
public static final int RecyclerView_spanCount = 9;
public static final int RecyclerView_stackFromEnd = 10;
}
}
| [
"root@EXA01.turbodiesel.local"
] | root@EXA01.turbodiesel.local |
07e714c8fc55b1e39cccaaa071b6cf86ca2fb967 | 1b78e63fbc25af7efe808dbeff64e86e653300f4 | /cchecker-service-fl/src/main/java/gov/nih/nci/cadsr/microservices/FormConverterUtil.java | f5e4fef7a8e876ba7e7d2ca0d5f96e7c9657821c | [] | no_license | CBIIT/cadsr-services | 2a6b208180a7010d1e494987cf48fd79032cd95b | 87ffa54338ebcdd6c3ce11a62085999b7a19a376 | refs/heads/master | 2023-06-26T07:21:10.844971 | 2022-03-31T15:38:39 | 2022-03-31T15:38:39 | 124,926,525 | 1 | 0 | null | 2023-06-14T22:36:22 | 2018-03-12T17:31:57 | Java | UTF-8 | Java | false | false | 4,455 | java | /*
* Copyright (C) 2019 FNFrederick National Laboratory for Cancer ResearchLCR - All rights reserved.
*/
package gov.nih.nci.cadsr.microservices;
import gov.nih.nci.ncicb.cadsr.common.resource.FormV2;
import gov.nih.nci.ncicb.cadsr.common.util.logging.Log;
import gov.nih.nci.ncicb.cadsr.common.util.logging.LogFactory;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.exolab.castor.xml.Marshaller;
/**
* Builds FL XML String for one FL Form.
*
* @author asafievan
*
*/
public class FormConverterUtil {
private static Log log = LogFactory.getLog(FormConverterUtil.class.getName());
static private FormConverterUtil _instance = null;
//FinalFormCartTransformv33 used in FL
//public static final String V1ExtendedToV2XSL = "/transforms/FinalFormCartTransformv33.xsl";
//Remove public ID form element
public static final String generateFormsXSL = "/transforms/GenerateFormsXml.xsl";
//Stop using ConvertFormCartV1ExtendedToV2.xsl to be in syn with what GS has
//public static final String V1ExtendedToV2XSL = "/transforms/ConvertFormCartV1ExtendedToV2.xsl";
public static final String stripEmptyNodesXSL = "/transforms/remove-empty-nodes.xsl";
protected Transformer transformerV1ToV2 = null;
protected Transformer transformerStripEmpty = null;
private String convertToV2(FormV2 crf) throws Exception
{
// Start with our standard conversion to xml (in V1 format)
StringWriter writer = new StringWriter();
try {
Marshaller.marshal(crf, writer);
} catch (Exception ex) {
log.debug("FormV2 " + crf);
throw ex;
}
// Now use our transformer to create V2 format
Source xmlInput = new StreamSource(new StringReader(writer.toString()));
ByteArrayOutputStream xmlOutputStream = new ByteArrayOutputStream();
Result xmlOutput = new StreamResult(xmlOutputStream);
try {
transformerV1ToV2.transform(xmlInput, xmlOutput);
} catch (TransformerException e) {
log.debug(writer.toString());
throw e;
}
String V2XML = xmlOutputStream.toString();
return V2XML;
}
/**
*
* @param crf not null
* @return String FL XML String
* @throws Exception
*/
public String convertFormToV2 (FormV2 crf) throws Exception
{
Source xmlInputV2Forms = new StreamSource(new StringReader(convertToV2(crf)));
ByteArrayOutputStream xmlOutputStreamStripEmpty = new ByteArrayOutputStream();
Result xmlOutputStripEmpty = new StreamResult(xmlOutputStreamStripEmpty);
try {
// Strip empty nodes from the transformed v2 form xml file
transformerStripEmpty.transform(xmlInputV2Forms, xmlOutputStripEmpty);
} catch (TransformerException e) {
log.debug(xmlInputV2Forms.toString());
throw e;
}
String V2XML = xmlOutputStreamStripEmpty.toString();
return V2XML;
}
protected FormConverterUtil() {
StreamSource xslSource = null;
StreamSource xslSourceStripEmpty = null;
try {
InputStream xslStream = this.getClass().getResourceAsStream(generateFormsXSL);
xslSource = new StreamSource(xslStream);
InputStream xslStreamRemoveEmptyNodes = this.getClass().getResourceAsStream(stripEmptyNodesXSL);
xslSourceStripEmpty = new StreamSource(xslStreamRemoveEmptyNodes);
}
catch(Exception e) {
log.error("FormConverterUtil error loading conversion xsl: " + generateFormsXSL + " OR " + stripEmptyNodesXSL + " exc: "+ e);
}
try {
log.debug("creating transformerV1ToV2");
transformerV1ToV2 = net.sf.saxon.TransformerFactoryImpl.newInstance().newTransformer(xslSource);
log.debug("creating transformerStripEmpty");
transformerStripEmpty = net.sf.saxon.TransformerFactoryImpl.newInstance().newTransformer(xslSourceStripEmpty);
} catch (TransformerException e) {
log.debug("transformerV1ToV2 exception: " + e.toString());
log.debug("transformerV1ToV2 exception: " + e.getMessage());
}
}
static public FormConverterUtil instance(){
if (_instance == null) {
_instance = new FormConverterUtil();
}
return _instance;
}
} | [
"natalia.asafieva@nih.gov"
] | natalia.asafieva@nih.gov |
a135883d99093cdad16cce4be094a679b6003fd1 | 065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be | /drjava_cluster/782/src_0.java | 7c9e42b331f8dd39daab6efebf1a987d72845881 | [] | 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 | 143,030 | java | /*BEGIN_COPYRIGHT_BLOCK
*
* This file is part of DrJava. Download the current version of this project from http://www.drjava.org/
* or http://sourceforge.net/projects/drjava/
*
* DrJava Open Source License
*
* Copyright (C) 2001-2005 JavaPLT group at Rice University (javaplt@rice.edu). 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 javaplt@rice.edu.
*
* 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.model;
import java.awt.Container;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.print.PageFormat;
import java.awt.print.PrinterJob;
import java.awt.print.PrinterException;
import java.awt.print.Pageable;
import java.awt.Font;
import java.awt.Color;
import javax.swing.ProgressMonitor;
import javax.swing.event.DocumentListener;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.Position;
import javax.swing.text.Segment;
import javax.swing.text.Style;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Vector;
import java.util.WeakHashMap;
import edu.rice.cs.util.ClassPathVector;
import edu.rice.cs.util.FileOps;
import edu.rice.cs.util.FileOpenSelector;
import edu.rice.cs.drjava.model.FileSaveSelector;
import edu.rice.cs.util.OperationCanceledException;
import edu.rice.cs.util.OrderedHashSet;
import edu.rice.cs.util.Pair;
import edu.rice.cs.util.SRunnable;
import edu.rice.cs.util.StringOps;
import edu.rice.cs.util.UnexpectedException;
import edu.rice.cs.util.docnavigation.INavigationListener;
import edu.rice.cs.util.docnavigation.NodeData;
import edu.rice.cs.util.docnavigation.NodeDataVisitor;
import edu.rice.cs.util.docnavigation.AWTContainerNavigatorFactory;
import edu.rice.cs.util.docnavigation.IDocumentNavigator;
import edu.rice.cs.util.docnavigation.INavigatorItem;
import edu.rice.cs.util.docnavigation.INavigatorItemFilter;
import edu.rice.cs.util.docnavigation.JTreeSortNavigator;
import edu.rice.cs.util.swing.DocumentIterator;
import edu.rice.cs.util.swing.Utilities;
import edu.rice.cs.util.text.AbstractDocumentInterface;
import edu.rice.cs.util.text.ConsoleDocument;
import edu.rice.cs.drjava.DrJava;
import edu.rice.cs.drjava.DrJavaRoot;
import edu.rice.cs.drjava.config.FileOption;
import edu.rice.cs.drjava.config.OptionConstants;
import edu.rice.cs.drjava.config.OptionEvent;
import edu.rice.cs.drjava.config.OptionListener;
import edu.rice.cs.drjava.model.print.DrJavaBook;
import edu.rice.cs.drjava.model.definitions.ClassNameNotFoundException;
import edu.rice.cs.drjava.model.definitions.DefinitionsDocument;
import edu.rice.cs.drjava.model.definitions.DefinitionsEditorKit;
import edu.rice.cs.drjava.model.definitions.InvalidPackageException;
import edu.rice.cs.drjava.model.definitions.DocumentUIListener;
import edu.rice.cs.drjava.model.definitions.CompoundUndoManager;
import edu.rice.cs.drjava.model.definitions.reducedmodel.HighlightStatus;
import edu.rice.cs.drjava.model.definitions.reducedmodel.IndentInfo;
import edu.rice.cs.drjava.model.definitions.reducedmodel.ReducedModelState;
import edu.rice.cs.drjava.model.debug.Breakpoint;
import edu.rice.cs.drjava.model.debug.DebugBreakpointData;
import edu.rice.cs.drjava.model.debug.DebugWatchData;
import edu.rice.cs.drjava.model.debug.Debugger;
import edu.rice.cs.drjava.model.debug.DebugException;
import edu.rice.cs.drjava.model.debug.NoDebuggerAvailable;
import edu.rice.cs.drjava.model.repl.DefaultInteractionsModel;
import edu.rice.cs.drjava.model.repl.InteractionsDocument;
import edu.rice.cs.drjava.model.repl.InteractionsDJDocument;
import edu.rice.cs.drjava.model.repl.InteractionsScriptModel;
import edu.rice.cs.drjava.model.compiler.CompilerModel;
import edu.rice.cs.drjava.model.junit.JUnitModel;
import edu.rice.cs.drjava.project.DocFile;
import edu.rice.cs.drjava.project.DocumentInfoGetter;
import edu.rice.cs.drjava.project.MalformedProjectFileException;
import edu.rice.cs.drjava.project.ProjectProfile;
import edu.rice.cs.drjava.project.ProjectFileIR;
import edu.rice.cs.drjava.project.ProjectFileParser;
import edu.rice.cs.drjava.model.cache.DCacheAdapter;
import edu.rice.cs.drjava.model.cache.DDReconstructor;
import edu.rice.cs.drjava.model.cache.DocumentCache;
/** In simple terms, a DefaultGlobalModel without an interpreter,compiler, junit testing, debugger or javadoc.
* Basically, has only document handling functionality
* @version $Id$
*/
public class AbstractGlobalModel implements SingleDisplayModel, OptionConstants, DocumentIterator {
/** A document cache that manages how many unmodified documents are open at once. */
protected DocumentCache _cache;
static final String DOCUMENT_OUT_OF_SYNC_MSG =
"Current document is out of sync with the Interactions Pane and should be recompiled!\n";
static final String CLASSPATH_OUT_OF_SYNC_MSG =
"Interactions Pane is out of sync with the current classpath and should be reset!\n";
// ----- FIELDS -----
/** A list of files that are auxiliary files to the currently open project.
* TODO: make part of FileGroupingState. */
protected LinkedList<File> _auxiliaryFiles = new LinkedList<File>();
/** Adds a document to the list of auxiliary files. The LinkedList class is not thread safe, so
* the add operation is synchronized.
*/
public void addAuxiliaryFile(OpenDefinitionsDocument doc) {
if (! doc.inProject()) {
File f;
try { f = doc.getFile(); }
catch(FileMovedException fme) { f = fme.getFile(); }
synchronized(_auxiliaryFiles) { _auxiliaryFiles.add(f); }
setProjectChanged(true);
}
}
/** Removes a document from the list of auxiliary files. The LinkedList class is not thread safe, so
* operations on _auxiliaryFiles are synchronized.
*/
public void removeAuxiliaryFile(OpenDefinitionsDocument doc) {
File file;
try { file = doc.getFile(); }
catch(FileMovedException fme) { file = fme.getFile(); }
String path = "";
try { path = file.getCanonicalPath(); }
catch(IOException e) { throw new UnexpectedException(e); }
synchronized(_auxiliaryFiles) {
ListIterator<File> it = _auxiliaryFiles.listIterator();
while (it.hasNext()) {
try {
if (it.next().getCanonicalPath().equals(path)) {
it.remove();
setProjectChanged(true);
break;
}
}
catch(IOException e) { /* Ignore f */ }
}
}
}
/** Keeps track of all listeners to the model, and has the ability to notify them of some event. Originally used
* a Command Pattern style, but this has been replaced by having EventNotifier directly implement all listener
* interfaces it supports. Set in constructor so that subclasses can install their own notifier with additional
* methods.
*/
final GlobalEventNotifier _notifier = new GlobalEventNotifier();
// ---- Definitions fields ----
/** Factory for new definitions documents and views.*/
protected final DefinitionsEditorKit _editorKit = new DefinitionsEditorKit(_notifier);
/** Collection for storing all OpenDefinitionsDocuments. */
protected final OrderedHashSet<OpenDefinitionsDocument> _documentsRepos =
new OrderedHashSet<OpenDefinitionsDocument>();
// ---- Input/Output Document Fields ----
/** The document used to display System.out and System.err, and to read from System.in. */
protected final ConsoleDocument _consoleDoc;
/** The document adapter used in the console document. */
protected final InteractionsDJDocument _consoleDocAdapter;
/** Indicates whether the model is currently trying to close all documents, and thus that a new one should not be
* created, and whether or not to update the navigator
*/
protected boolean _isClosingAllDocs;
/** A lock object to prevent print calls to System.out or System.err from flooding the JVM, ensuring the UI
* remains responsive.
*/
private final Object _systemWriterLock = new Object();
/** Number of milliseconds to wait after each println, to prevent the JVM from being flooded with print calls.
* TODO: why is this here, and why is it public?
*/
public static final int WRITE_DELAY = 5;
/** A PageFormat object for printing to paper. */
protected PageFormat _pageFormat = new PageFormat();
/** The active document pointer, which will never be null once the constructor is done.
* Maintained by the _gainVisitor with a navigation listener.
*/
private OpenDefinitionsDocument _activeDocument;
/** A pointer to the active directory, which is not necessarily the parent of the active document
* The user may click on a folder component in the navigation pane and that will set this field without
* setting the active document. It is used by the newFile method to place new files into the active directory.
*/
private File _activeDirectory;
/** The abstract container which contains views of open documents and allows user to navigate document focus among
* this collection of open documents
*/
protected IDocumentNavigator<OpenDefinitionsDocument> _documentNavigator =
new AWTContainerNavigatorFactory<OpenDefinitionsDocument>().makeListNavigator();
/** Light-weight parsing controller. */
protected LightWeightParsingControl _parsingControl;
/** @return the parsing control */
public LightWeightParsingControl getParsingControl() { return _parsingControl; }
// ----- CONSTRUCTORS -----
/** Constructs a new GlobalModel. Creates a new MainJVM and starts its Interpreter JVM. */
public AbstractGlobalModel() {
_cache = new DocumentCache();
_consoleDocAdapter = new InteractionsDJDocument();
_consoleDoc = new ConsoleDocument(_consoleDocAdapter);
_registerOptionListeners();
setFileGroupingState(makeFlatFileGroupingState());
_notifier.projectRunnableChanged();
_init();
}
private void _init() {
/** This visitor is invoked by the DocumentNavigator to update _activeDocument among other things */
final NodeDataVisitor<OpenDefinitionsDocument, Boolean> _gainVisitor = new NodeDataVisitor<OpenDefinitionsDocument, Boolean>() {
public Boolean itemCase(OpenDefinitionsDocument doc) {
OpenDefinitionsDocument oldDoc = AbstractGlobalModel.this.getActiveDocument();
_setActiveDoc(doc); // sets _activeDocument, the shadow copy of the active document
// Utilities.showDebug("Setting the active doc done");
File oldDir = _activeDirectory; // _activeDirectory can be null
File dir = doc.getParentDirectory(); // dir can be null
if (dir != null && ! dir.equals(oldDir)) {
/* If the file is in External or Auxiliary Files then then we do not want to change our project directory
* to something outside the project. ?? */
_activeDirectory = dir;
_notifier.currentDirectoryChanged(_activeDirectory);
}
return Boolean.valueOf(true);
}
public Boolean fileCase(File f) {
if (! f.isAbsolute()) { // should never happen because all file names are canonicalized
File root = _state.getProjectFile().getParentFile().getAbsoluteFile();
f = new File(root, f.getPath());
}
_activeDirectory = f; // Invariant: activeDirectory != null
_notifier.currentDirectoryChanged(f);
return Boolean.valueOf(true);
}
public Boolean stringCase(String s) { return Boolean.valueOf(false); }
};
_documentNavigator.addNavigationListener(new INavigationListener<OpenDefinitionsDocument>() {
public void gainedSelection(NodeData<? extends OpenDefinitionsDocument> dat) { dat.execute(_gainVisitor); }
public void lostSelection(NodeData<? extends OpenDefinitionsDocument> dat) {
// not important, only one document selected at a time
}
});
_documentNavigator.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
// Utilities.show("focusGained called with event " + e);
if (_documentNavigator.getCurrent() != null) // past selection is leaf node
_notifier.focusOnDefinitionsPane();
}
public void focusLost(FocusEvent e) { }
});
_isClosingAllDocs = false;
_ensureNotEmpty();
setActiveFirstDocument();
}
/** Returns a source root given a package and filename. */
protected File getSourceRoot(String packageName, File sourceFile) throws InvalidPackageException {
// Utilities.show("getSourceRoot(" + packageName + ", " + sourceFile + " called");
if (packageName.equals("")) {
// Utilities.show("Source root of " + sourceFile + " is: " + sourceFile.getParentFile());
return sourceFile.getParentFile();
}
ArrayList<String> packageStack = new ArrayList<String>();
int dotIndex = packageName.indexOf('.');
int curPartBegins = 0;
while (dotIndex != -1) {
packageStack.add(packageName.substring(curPartBegins, dotIndex));
curPartBegins = dotIndex + 1;
dotIndex = packageName.indexOf('.', dotIndex + 1);
}
// Now add the last package component
packageStack.add(packageName.substring(curPartBegins));
// Must use the canonical path, in case there are dots in the path
// (which will conflict with the package name)
try {
File parentDir = sourceFile.getCanonicalFile();
while (! packageStack.isEmpty()) {
String part = pop(packageStack);
parentDir = parentDir.getParentFile();
if (parentDir == null) throw new UnexpectedException("parent dir is null!");
// Make sure the package piece matches the directory name
if (! part.equals(parentDir.getName())) {
String msg = "The source file " + sourceFile.getAbsolutePath() +
" is in the wrong directory or in the wrong package. " +
"The directory name " + parentDir.getName() +
" does not match the package component " + part + ".";
throw new InvalidPackageException(-1, msg);
}
}
// OK, now parentDir points to the directory of the first component of the
// package name. The parent of that is the root.
parentDir = parentDir.getParentFile();
if (parentDir == null) {
// Utilities.show("parent dir of first component is null!");
throw new RuntimeException("parent dir of first component is null!");
}
// Utilities.show("Source root of " + sourceFile + " is: " + parentDir);
return parentDir;
}
catch (IOException ioe) {
String msg = "Could not locate directory of the source file: " + ioe;
throw new InvalidPackageException(-1, msg);
}
}
//-------- STATE --------//
protected FileGroupingState _state;
/** Delegates the compileAll command to the _state, a FileGroupingState.
* Synchronization is handled by the compilerModel.
*/
// public void compileAll() throws IOException {
// throw new UnsupportedOperationException("AbstractGlobalModel does not support compilation");
// }
/** @param state the new file grouping state. */
public void setFileGroupingState(FileGroupingState state) {
_state = state;
_notifier.projectRunnableChanged();
_notifier.projectBuildDirChanged();
_notifier.projectWorkDirChanged();
_notifier.projectModified();
}
protected FileGroupingState
makeProjectFileGroupingState(File pr, File main, File bd, File wd, File project, File[] files, ClassPathVector cp, File cjf, int cjflags) {
return new ProjectFileGroupingState(pr, main, bd, wd, project, files, cp, cjf, cjflags);
}
/** Notifies the project state that the project has been changed. */
public void setProjectChanged(boolean changed) {
// Utilities.showDebug("Project Changed to " + changed);
_state.setProjectChanged(changed);
_notifier.projectModified();
}
/** @return true if the project state has been changed. */
public boolean isProjectChanged() { return _state.isProjectChanged(); }
/** @return true if the model has a project open, false otherwise. */
public boolean isProjectActive() { return _state.isProjectActive(); }
/** @return the file that points to the current project file. Null if not currently in project view
*/
public File getProjectFile() { return _state.getProjectFile(); }
/** @return all files currently saved as source files in the project file.
* If _state not in project mode, returns null
*/
public File[] getProjectFiles() { return _state.getProjectFiles(); }
/** @return true the given file is in the current project file. */
public boolean inProject(File f) { return _state.inProject(f); }
/** A file is in the project if the source root is the same as the
* project root. this means that project files must be saved at the
* source root. (we query the model through the model's state)
*/
public boolean isInProjectPath(OpenDefinitionsDocument doc) { return _state.isInProjectPath(doc); }
/** Sets the class with the project's main method. */
public void setMainClass(File f) {
_state.setMainClass(f);
_notifier.projectRunnableChanged();
setProjectChanged(true);
}
/** @return the class with the project's main method. */
public File getMainClass() { return _state.getMainClass(); }
/** Sets the create jar file of the project. */
public void setCreateJarFile(File f) {
_state.setCreateJarFile(f);
setProjectChanged(true);
}
/** Return the create jar file for the project. If not in project mode, returns null. */
public File getCreateJarFile() { return _state.getCreateJarFile(); }
/** Sets the create jar flags of the project. */
public void setCreateJarFlags(int f) {
_state.setCreateJarFlags(f);
setProjectChanged(true);
}
/** Return the create jar flags for the project. If not in project mode, returns 0. */
public int getCreateJarFlags() { return _state.getCreateJarFlags(); }
/** throws UnsupportedOperationException */
public void junitAll() {
throw new UnsupportedOperationException("AbstractGlobalDocument does not support unit testing");
}
/** @return the root of the project sourc tree (assuming one exists). */
public File getProjectRoot() { return _state.getProjectRoot(); }
/** Sets the class with the project's main method. Degenerate version overridden in DefaultGlobalModel. */
public void setProjectRoot(File f) {
_state.setProjectRoot(f);
// _notifier.projectRootChanged();
setProjectChanged(true);
}
/** Sets project file to specifed value; used in "Save Project As ..." command in MainFrame. */
public void setProjectFile(File f) { _state.setProjectFile(f); }
/** @return the build directory for the project (assuming one exists). */
public File getBuildDirectory() { return _state.getBuildDirectory(); }
/** Sets the class with the project's main method. Degenerate version overridden in DefaultGlobalModel. */
public void setBuildDirectory(File f) {
_state.setBuildDirectory(f);
_notifier.projectBuildDirChanged();
setProjectChanged(true);
}
/** @return the working directory for the Master JVM (editor and GUI). */
public File getMasterWorkingDirectory() {
File workDir = DrJava.getConfig().getSetting(OptionConstants.WORKING_DIRECTORY);
if (workDir != null && workDir != FileOption.NULL_FILE) return workDir;
return new File(System.getProperty("user.dir"));
}
/** @return the working directory for the Slave (Interactions) JVM */
public File getWorkingDirectory() {
// Utilities.show("getWorkingDirectory() returns " + _state.getWorkingDirectory());
// Utilities.show("isProjectActive() return " + isProjectActive());
return _state.getWorkingDirectory();
}
/** Sets the working directory for the project; ignored in flat file model. */
public void setWorkingDirectory(File f) {
_state.setWorkingDirectory(f);
_notifier.projectWorkDirChanged();
setProjectChanged(true);
}
public void cleanBuildDirectory() throws FileMovedException, IOException {
_state.cleanBuildDirectory();
}
public List<File> getClassFiles() { return _state.getClassFiles(); }
/** Helper method used in subsequent anonymous inner class */
protected static String getPackageName(String classname) {
int index = classname.lastIndexOf(".");
if (index != -1) return classname.substring(0, index);
else return "";
}
class ProjectFileGroupingState implements FileGroupingState {
File _projRoot;
File _mainFile;
File _builtDir;
File _workDir;
File _projectFile;
final File[] projectFiles;
ClassPathVector _projExtraClassPath;
private boolean _isProjectChanged = false;
File _createJarFile;
int _createJarFlags;
//private ArrayList<File> _auxFiles = new ArrayList<File>();
HashSet<String> _projFilePaths = new HashSet<String>();
/** Degenerate constructor for a new project; only the file project name is known. */
ProjectFileGroupingState(File project) {
this(project.getParentFile(), null, null, null, project, new File[0], new ClassPathVector(), null, 0);
}
ProjectFileGroupingState(File pr, File main, File bd, File wd, File project, File[] files, ClassPathVector cp, File cjf, int cjflags) {
_projRoot = pr;
// System.err.println("Project root initialized to " + pr);
_mainFile = main;
_builtDir = bd;
_workDir = wd;
_projectFile = project;
projectFiles = files;
_projExtraClassPath = cp;
if (projectFiles != null) try { for (File file : projectFiles) { _projFilePaths.add(file.getCanonicalPath()); } }
catch(IOException e) { /*do nothing */ }
_createJarFile = cjf;
_createJarFlags = cjflags;
}
public boolean isProjectActive() { return true; }
/** Determines whether the specified doc in within the project file tree.
* No synchronization is required because only immutable data is accessed.
*/
public boolean isInProjectPath(OpenDefinitionsDocument doc) {
if (doc.isUntitled()) return false;
// If the file does not exist, we still want to tell if it's in the correct
// path. The file may have been in at one point and had been removed, in which
// case we should treat it as an untitled project file that should be resaved.
File f;
try { f = doc.getFile(); }
catch(FileMovedException fme) { f = fme.getFile(); }
return isInProjectPath(f);
}
/** Determines whether the specified file in within the project file tree.
* No synchronization is required because only immutable data is accessed.
*/
public boolean isInProjectPath(File f) { return FileOps.isInFileTree(f, getProjectRoot()); }
/** @return the absolute path to the project file. Since projectFile is final, no synchronization
* is necessary.
*/
public File getProjectFile() { return _projectFile; }
public boolean inProject(File f) {
String path;
if (f == null || ! isInProjectPath(f)) return false;
try {
path = f.getCanonicalPath();
return _projFilePaths.contains(path);
}
catch(IOException ioe) { return false; }
}
public File[] getProjectFiles() { return projectFiles; }
public File getProjectRoot() {
if (_projRoot == null || _projRoot.equals(FileOption.NULL_FILE)) return _projectFile.getParentFile();
// Utilities.show("File grouping state returning project root of " + _projRoot);
return _projRoot;
}
public File getBuildDirectory() { return _builtDir; }
public File getWorkingDirectory() {
try {
if (_workDir == null || _workDir == FileOption.NULL_FILE)
return _projectFile.getParentFile().getCanonicalFile(); // default is project root
return _workDir.getCanonicalFile();
}
catch(IOException e) { /* fall through */ }
return _workDir.getAbsoluteFile();
}
/** Sets project file to specifed value; used in "Save Project As ..." command in MainFrame. */
public void setProjectFile(File f) { _projectFile = f; }
public void setProjectRoot(File f) {
_projRoot = f;
// System.err.println("Project root set to " + f);
}
public void setBuildDirectory(File f) { _builtDir = f; }
public void setWorkingDirectory(File f) { _workDir = f; }
public File getMainClass() { return _mainFile; }
public void setMainClass(File f) { _mainFile = f; }
public void setCreateJarFile(File f) { _createJarFile = f; }
public File getCreateJarFile() { return _createJarFile; }
public void setCreateJarFlags(int f) { _createJarFlags = f; }
public int getCreateJarFlags() { return _createJarFlags; }
public boolean isProjectChanged() { return _isProjectChanged; }
public void setProjectChanged(boolean changed) { _isProjectChanged = changed; }
public boolean isAuxiliaryFile(File f) {
String path;
if (f == null) return false;
try { path = f.getCanonicalPath();}
catch(IOException ioe) { return false; }
synchronized(_auxiliaryFiles) {
for (File file : _auxiliaryFiles) {
try { if (file.getCanonicalPath().equals(path)) return true; }
catch(IOException ioe) { /* ignore file */ }
}
return false;
}
}
public void cleanBuildDirectory() throws FileMovedException, IOException{
File dir = this.getBuildDirectory();
// clear cached class file of all documents
for (OpenDefinitionsDocument doc: _documentsRepos) { doc.setCachedClassFile(null); }
cleanHelper(dir);
if (! dir.exists()) dir.mkdirs();
}
private void cleanHelper(File f) {
if (f.isDirectory()) {
File fs[] = f.listFiles(new FilenameFilter() {
public boolean accept(File parent, String name) {
return new File(parent, name).isDirectory() || name.endsWith(".class");
}
});
for (File kid: fs) { cleanHelper(kid); }
if (f.listFiles().length == 0) f.delete();
} else if (f.getName().endsWith(".class")) f.delete();
}
public List<File> getClassFiles() {
File dir = this.getBuildDirectory();
LinkedList<File> acc = new LinkedList<File>();
getClassFilesHelper(dir, acc);
if (! dir.exists()) dir.mkdirs();
return acc;
}
private void getClassFilesHelper(File f, LinkedList<File> acc) {
if (f.isDirectory()) {
File fs[] = f.listFiles(new FilenameFilter() {
public boolean accept(File parent, String name) {
return new File(parent, name).isDirectory() || name.endsWith(".class");
}
});
for (File kid: fs) { getClassFilesHelper(kid, acc); }
} else if (f.getName().endsWith(".class")) acc.add(f);
}
// ----- FIND ALL DEFINED CLASSES IN FOLDER ---
//throws UnsupportedOperationException
public void junitAll() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support JUnit testing");
}
public void jarAll() {
throw new UnsupportedOperationException("AbstractGlobaModel does not support jarring");
}
public ClassPathVector getExtraClassPath() { return _projExtraClassPath; }
public void setExtraClassPath(ClassPathVector cp) { _projExtraClassPath = cp; }
}
protected FileGroupingState makeFlatFileGroupingState() { return new FlatFileGroupingState(); }
class FlatFileGroupingState implements FileGroupingState {
public File getBuildDirectory() { return null; }
public File getProjectRoot() { return getWorkingDirectory(); }
public File getWorkingDirectory() {
try {
File[] roots = getSourceRootSet();
// Utilities.show("source root set is " + Arrays.toString(roots));
if (roots.length == 0) return getMasterWorkingDirectory();
return roots[0].getCanonicalFile();
}
catch(IOException e) { /* fall through */ }
return new File(System.getProperty("user.dir")); // a flat file configuration should have exactly one source root
}
public boolean isProjectActive() { return false; }
public boolean isInProjectPath(OpenDefinitionsDocument doc) { return false; }
public boolean isInProjectPath(File f) { return false; }
public File getProjectFile() { return null; }
public void setBuildDirectory(File f) { }
public void setProjectFile(File f) { }
public void setProjectRoot(File f) { }
public void setWorkingDirectory(File f) { }
public File[] getProjectFiles() { return null; }
public boolean inProject(File f) { return false; }
public File getMainClass() { return null; }
public void setMainClass(File f) { }
public void setCreateJarFile(File f) { }
public File getCreateJarFile() { return null; }
public void setCreateJarFlags(int f) { }
public int getCreateJarFlags() { return 0; }
public ClassPathVector getExtraClassPath() { return new ClassPathVector(); }
public void setExtraClassPath(ClassPathVector cp) { }
public boolean isProjectChanged() { return false; }
public void setProjectChanged(boolean changed) { /* Do nothing */ }
public boolean isAuxiliaryFile(File f) { return false; }
//throws UnsupportedOperationException
public void junitAll() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support unit tests");
}
public void cleanBuildDirectory() throws FileMovedException, IOException { }
public List<File> getClassFiles() { return new LinkedList<File>(); }
/** Jars all the open files.
throws UnsupportedOperationException */
public void jarAll() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support jarring");
}
}
/** Gives the title of the source bin for the navigator.
* @return The text used for the source bin in the tree navigator
*/
public String getSourceBinTitle() { return "[ Source Files ]"; }
/** Gives the title of the external files bin for the navigator
* @return The text used for the external files bin in the tree navigator.
*/
public String getExternalBinTitle() { return "[ External Files ]"; }
/** Gives the title of the aux files bin for the navigator.
* @return The text used for the aux files bin in the tree navigator.
*/
public String getAuxiliaryBinTitle() { return "[ Included External Files ]"; }
// ----- METHODS -----
/** Add a listener to this global model.
* @param listener a listener that reacts on events generated by the GlobalModel.
*/
public void addListener(GlobalModelListener listener) { _notifier.addListener(listener); }
/** Remove a listener from this global model.
* @param listener a listener that reacts on events generated by the GlobalModel
* This method is synchronized using the readers/writers event protocol incorporated in EventNotifier<T>.
*/
public void removeListener(GlobalModelListener listener) { _notifier.removeListener(listener); }
// getter methods for the private fields
public DefinitionsEditorKit getEditorKit() { return _editorKit; }
/** throws UnsupportedOperationException */
public DefaultInteractionsModel getInteractionsModel() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support interaction");
}
/** throws UnsupportedOperationException */
public InteractionsDJDocument getSwingInteractionsDocument() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support interaction");
}
/** throws UnsupportedOperationException */
public InteractionsDocument getInteractionsDocument() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support interaction");
}
public ConsoleDocument getConsoleDocument() { return _consoleDoc; }
public InteractionsDJDocument getSwingConsoleDocument() { return _consoleDocAdapter; }
public PageFormat getPageFormat() { return _pageFormat; }
public void setPageFormat(PageFormat format) { _pageFormat = format; }
/** throws UnsupportedOperationException */
public CompilerModel getCompilerModel() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support compilation");
}
/** throws UnsupportedOperationException */
public JUnitModel getJUnitModel() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support unit testing");
}
/** throws UnsupportedOperationException */
public JavadocModel getJavadocModel() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support javadoc");
}
public IDocumentNavigator<OpenDefinitionsDocument> getDocumentNavigator() { return _documentNavigator; }
public void setDocumentNavigator(IDocumentNavigator<OpenDefinitionsDocument> newnav) { _documentNavigator = newnav; }
/** Creates a new open definitions document and adds it to the list. Public for testing purposes.
* @return The new open document
*/
public OpenDefinitionsDocument newFile(File parentDir) {
final ConcreteOpenDefDoc doc = _createOpenDefinitionsDocument();
doc.setParentDirectory(parentDir);
doc.setFile(null);
addDocToNavigator(doc);
_notifier.newFileCreated(doc);
return doc;
}
/** Creates a new document, adds it to the list of open documents, and sets it to be active.
* @return The new open document
*/
public OpenDefinitionsDocument newFile() {
File dir = _activeDirectory;
if (dir == null) dir = getMasterWorkingDirectory();
OpenDefinitionsDocument doc = newFile(dir);
setActiveDocument(doc);
return doc;
}
/** Creates a new junit test case.
* @param name the name of the new test case
* @param makeSetUp true iff an empty setUp() method should be included
* @param makeTearDown true iff an empty tearDown() method should be included
* @return the new open test case
*/
public OpenDefinitionsDocument newTestCase(String name, boolean makeSetUp, boolean makeTearDown) {
boolean elementary = (DrJava.getConfig().getSetting(LANGUAGE_LEVEL) == 1);
StringBuffer buf = new StringBuffer();
if (! elementary) buf.append("import junit.framework.TestCase;\n\n");
buf.append("/**\n");
buf.append("* A JUnit test case class.\n");
buf.append("* Every method starting with the word \"test\" will be called when running\n");
buf.append("* the test with JUnit.\n");
buf.append("*/\n");
if (! elementary) buf.append("public ");
buf.append("class ");
buf.append(name);
buf.append(" extends TestCase {\n\n");
if (makeSetUp) {
buf.append("/**\n");
buf.append("* This method is called before each test method, to perform any common\n");
buf.append("* setup if necessary.\n");
buf.append("*/\n");
if (! elementary) buf.append("public ");
buf.append("void setUp() throws Exception {\n}\n\n");
}
if (makeTearDown) {
buf.append("/**\n");
buf.append("* This method is called after each test method, to perform any common\n");
buf.append("* clean-up if necessary.\n");
buf.append("*/\n");
if (! elementary) buf.append("public ");
buf.append("void tearDown() throws Exception {\n}\n\n");
}
buf.append("/**\n");
buf.append("* A test method.\n");
buf.append("* (Replace \"X\" with a name describing the test. You may write as\n");
buf.append("* many \"testSomething\" methods in this class as you wish, and each\n");
buf.append("* one will be called when running JUnit over this class.)\n");
buf.append("*/\n");
if (! elementary) buf.append("public ");
buf.append("void testX() {\n}\n\n");
buf.append("}\n");
String test = buf.toString();
OpenDefinitionsDocument openDoc = newFile();
try {
openDoc.insertString(0, test, null);
openDoc.indentLines(0, test.length());
}
catch (BadLocationException ble) {
throw new UnexpectedException(ble);
}
return openDoc;
}
/** This method is for use only by test cases. */
public DocumentCache getDocumentCache() { return _cache; }
//---------------------- Specified by ILoadDocuments ----------------------//
/** Open a file and add it to the pool of definitions documents. The provided file selector chooses a file,
* and on a successful open, the fileOpened() event is fired. This method also checks if there was previously
* a single unchanged, untitled document open, and if so, closes it after a successful opening.
* @param com a command pattern command that selects what file to open
* @return The open document, or null if unsuccessful
* @exception IOException
* @exception OperationCanceledException if the open was canceled
* @exception AlreadyOpenException if the file is already open
*/
public OpenDefinitionsDocument openFile(FileOpenSelector com) throws
IOException, OperationCanceledException, AlreadyOpenException {
// Close an untitled, unchanged document if it is the only one open
boolean closeUntitled = _hasOneEmptyDocument();
OpenDefinitionsDocument oldDoc = _activeDocument;
OpenDefinitionsDocument openedDoc = openFileHelper(com);
if (closeUntitled) closeFileHelper(oldDoc);
// Utilities.showDebug("DrJava has opened" + openedDoc + " and is setting it active");
setActiveDocument(openedDoc);
setProjectChanged(true);
// Utilities.showDebug("active doc set; openFile returning");
return openedDoc;
}
protected OpenDefinitionsDocument openFileHelper(FileOpenSelector com) throws IOException,
OperationCanceledException, AlreadyOpenException {
// This code is duplicated in MainFrame._setCurrentDirectory(File) for safety.
final File file = (com.getFiles())[0].getCanonicalFile(); // may throw an IOException if path is invalid
OpenDefinitionsDocument odd = _openFile(file);
// Utilities.showDebug("File " + file + " opened");
// Make sure this is on the classpath
try {
File classPath = odd.getSourceRoot();
addDocToClassPath(odd);
}
catch (InvalidPackageException e) {
// Invalid package-- don't add it to classpath
}
return odd;
}
/** Open multiple files and add them to the pool of definitions documents. The provided file selector chooses
* a collection of files, and on successfully opening each file, the fileOpened() event is fired. This method
* also checks if there was previously a single unchanged, untitled document open, and if so, closes it after
* a successful opening.
* @param com a command pattern command that selects what file
* to open
* @return The open document, or null if unsuccessful
* @exception IOException
* @exception OperationCanceledException if the open was canceled
* @exception AlreadyOpenException if the file is already open
*/
public OpenDefinitionsDocument openFiles(FileOpenSelector com)
throws IOException, OperationCanceledException, AlreadyOpenException {
// Close an untitled, unchanged document if it is the only one open
boolean closeUntitled = _hasOneEmptyDocument();
OpenDefinitionsDocument oldDoc = _activeDocument;
OpenDefinitionsDocument openedDoc = openFilesHelper(com);
if (closeUntitled) closeFileHelper(oldDoc);
setActiveDocument(openedDoc);
return openedDoc;
}
protected OpenDefinitionsDocument openFilesHelper(FileOpenSelector com)
throws IOException, OperationCanceledException, AlreadyOpenException {
final File[] files = com.getFiles();
if (files == null) { throw new IOException("No Files returned from FileSelector"); }
OpenDefinitionsDocument doc = _openFiles(files);
return doc;
}
// if set to true, and uncommented, the definitions document will
// print out a small stack trace every time getDocument() is called
// static boolean SHOW_GETDOC = false;
/** Opens all the files in the list, and notifies about the last file opened. */
private OpenDefinitionsDocument _openFiles(File[] files)
throws IOException, OperationCanceledException, AlreadyOpenException {
AlreadyOpenException storedAOE = null;
OpenDefinitionsDocument retDoc = null;
// SHOW_GETDOC = true;
LinkedList<File> filesNotFound = new LinkedList<File>();
final LinkedList<OpenDefinitionsDocument> filesOpened = new LinkedList<OpenDefinitionsDocument>();
for (final File f: files) {
if (f == null) throw new IOException("File name returned from FileSelector is null");
try {
//always return last opened Doc
retDoc = _rawOpenFile(f.getCanonicalFile());
filesOpened.add(retDoc);
}
catch (AlreadyOpenException aoe) {
retDoc = aoe.getOpenDocument();
//Remember the first AOE
if (storedAOE == null) storedAOE = aoe;
}
catch(FileNotFoundException e) { filesNotFound.add(f); }
}
for (final OpenDefinitionsDocument d: filesOpened) {
addDocToNavigator(d);
addDocToClassPath(d);
_notifier.fileOpened(d);
}
// SHOW_GETDOC = false;
for (File f: filesNotFound) { _notifier.fileNotFound(f); }
if (storedAOE != null) throw storedAOE;
if (retDoc != null) return retDoc;
else {
//if we didn't open any files, then it's just as if they cancelled it...
throw new OperationCanceledException();
}
}
//----------------------- End ILoadDocuments Methods -----------------------//
/** Opens all files in the specified folder dir and places them in the appropriate places in the document navigator.
* If "open folders recursively" is checked, this operation opens all files in the subtree rooted at dir.
*/
public void openFolder(File dir, boolean rec) throws IOException, OperationCanceledException, AlreadyOpenException {
if (dir == null) return; // just in case
ArrayList<File> files;
if (dir.isDirectory()) {
files = FileOps.getFilesInDir(dir, rec, new FileFilter() {
public boolean accept(File f) {
return f.isDirectory() ||
f.isFile() &&
f.getName().endsWith(DrJavaRoot.LANGUAGE_LEVEL_EXTENSIONS[DrJava.getConfig().getSetting(LANGUAGE_LEVEL)]);
}
});
if (isProjectActive())
Collections.sort(files, new Comparator<File>() {
public int compare(File o1,File o2) {
return - o1.getAbsolutePath().compareTo(o2.getAbsolutePath());
}
});
else
Collections.sort(files, new Comparator<File>() {
public int compare(File o1,File o2) {
return - o1.getName().compareTo(o2.getName());
}
});
int ct = files.size();
final File[] sfiles = files.toArray(new File[ct]);
openFiles(new FileOpenSelector() { public File[] getFiles() { return sfiles; } });
if (ct > 0 && _state.isInProjectPath(dir)) setProjectChanged(true);
}
}
/** Saves all open files, prompting for names if necessary.
* When prompting (i.e., untitled document), set that document as active.
* @param com a FileSaveSelector
* @exception IOException
*/
public void saveAllFiles(FileSaveSelector com) throws IOException {
OpenDefinitionsDocument curdoc = getActiveDocument();
saveAllFilesHelper(com);
setActiveDocument(curdoc); // Return focus to previously active doc
}
/** Called by saveAllFiles in DefaultGlobalModel */
protected void saveAllFilesHelper(FileSaveSelector com) throws IOException {
boolean isProjActive = isProjectActive();
OpenDefinitionsDocument[] docs;
synchronized(_documentsRepos) { docs = _documentsRepos.toArray(new OpenDefinitionsDocument[0]); }
for (final OpenDefinitionsDocument doc: docs) {
if (doc.isUntitled() && isProjActive) continue; // do not force Untitled document to be saved if projectActive()
aboutToSaveFromSaveAll(doc);
doc.saveFile(com);
}
}
/** Creates a new FileGroupingState for specificed project file and default values for other properties.
* @param projFile the new project file (which does not yet exist in the file system)
*/
public void createNewProject(File projFile) { setFileGroupingState(new ProjectFileGroupingState(projFile)); }
/** Configures a new project (created by createNewProject) and writes it to disk; only runs in event thread.
*/
public void configNewProject() throws IOException {
// FileGroupingState oldState = _state;
File projFile = getProjectFile();
ProjectProfile builder = new ProjectProfile(projFile);
// FileLists for project file
ArrayList<File> srcFileList = new ArrayList<File>();
LinkedList<File> auxFileList = new LinkedList<File>();
ArrayList<File> extFileList = new ArrayList<File>();
OpenDefinitionsDocument[] docs;
File projectRoot = builder.getProjectRoot();
// Utilities.show("Fetched project root is " + projectRoot);
ClassPathVector exCp = new ClassPathVector();
synchronized(_documentsRepos) { docs = _documentsRepos.toArray(new OpenDefinitionsDocument[0]); }
for (OpenDefinitionsDocument doc: docs) {
File f = doc.getFile();
if (doc.isUntitled()) extFileList.add(f);
else if (FileOps.isInFileTree(f, projectRoot)) {
builder.addSourceFile(new DocFile(f));
srcFileList.add(f);
}
else if (doc.isAuxiliaryFile()) {
builder.addAuxiliaryFile(new DocFile(f));
auxFileList.add(f);
}
else /* doc is external file */ extFileList.add(f);
}
File[] srcFiles = srcFileList.toArray(new File[srcFileList.size()]);
File[] extFiles = extFileList.toArray(new File[extFileList.size()]);
// write to disk
builder.write();
_loadProject(builder);
}
/** Writes the project profile augmented by usage info to specified file. Assumes DrJava is in project mode.
* @param file where to save the project
*/
public void saveProject(File file, Hashtable<OpenDefinitionsDocument, DocumentInfoGetter> info)
throws IOException {
ProjectProfile builder = new ProjectProfile(file);
// add project root
File pr = getProjectRoot();
if (pr != null) builder.setProjectRoot(pr);
// add opendefinitionsdocument
ArrayList<File> srcFileList = new ArrayList<File>();
LinkedList<File> auxFileList = new LinkedList<File>();
OpenDefinitionsDocument[] docs;
synchronized(_documentsRepos) { docs = _documentsRepos.toArray(new OpenDefinitionsDocument[0]); }
for (OpenDefinitionsDocument doc: docs) {
if (doc.isInProjectPath()) {
DocumentInfoGetter g = info.get(doc);
builder.addSourceFile(g);
srcFileList.add(g.getFile());
}
else if (doc.isAuxiliaryFile()) {
DocumentInfoGetter g = info.get(doc);
builder.addAuxiliaryFile(g);
auxFileList.add(g.getFile());
}
}
// add collapsed path info
if (_documentNavigator instanceof JTreeSortNavigator) {
String[] paths = ((JTreeSortNavigator<?>)_documentNavigator).getCollapsedPaths();
for (String s : paths) { builder.addCollapsedPath(s); }
}
ClassPathVector exCp = getExtraClassPath();
if (exCp != null) {
Vector<File> exCpF = exCp.asFileVector();
for (File f : exCpF) {
builder.addClassPathFile(f);
//System.out.println("Saving project classpath entry " + f);
}
}
// else System.err.println("Project ClasspathVector is null!");
// add build directory
File bd = getBuildDirectory();
if (bd != null) builder.setBuildDirectory(bd);
// add working directory
File wd = getWorkingDirectory(); // the value of WORKING_DIRECTORY to be stored in the project
if (wd != null && bd != FileOption.NULL_FILE) builder.setWorkingDirectory(wd);
// add jar main class
File mainClass = getMainClass();
if (mainClass != null) builder.setMainClass(mainClass);
// add create jar file
File createJarFile = getCreateJarFile();
if (createJarFile != null) builder.setCreateJarFile(createJarFile);
int createJarFlags = getCreateJarFlags();
if (createJarFlags != 0) builder.setCreateJarFlags(createJarFlags);
// add breakpoints and watches
try {
ArrayList<DebugBreakpointData> l = new ArrayList<DebugBreakpointData>();
for(Breakpoint bp: getDebugger().getBreakpoints()) { l.add(bp); }
builder.setBreakpoints(l);
}
catch(DebugException de) { /* ignore, just don't store breakpoints */ }
try {
builder.setWatches(getDebugger().getWatches());
}
catch(DebugException de) { /* ignore, just don't store watches */ }
// write to disk
builder.write();
// set the state if all went well
File[] srcFiles = srcFileList.toArray(new File[srcFileList.size()]);
synchronized(_auxiliaryFiles) { _auxiliaryFiles = auxFileList; }
setFileGroupingState(makeProjectFileGroupingState(pr, mainClass, bd, wd, file, srcFiles, exCp, createJarFile,
createJarFlags));
}
/** Parses the given project file and loads it int the document navigator and resets interactions pane. Assumes
* preceding project if any has already been closed.
*
* @param projectFile The project file to parse
* @return an array of source files in the project
*/
public File[] openProject(File projectFile) throws IOException, MalformedProjectFileException {
return _loadProject(ProjectFileParser.ONLY.parse(projectFile));
}
/** Loads the specified project into the document navigator and opens all of the files (if not already open).
* Assumes that any prior project has been closed.
* @param projectFile The project file to parse
* @return an array of document's files to open
*/
private File[] _loadProject(ProjectFileIR ir) throws IOException {
final DocFile[] srcFiles = ir.getSourceFiles();
final DocFile[] auxFiles = ir.getAuxiliaryFiles();
final File projectFile = ir.getProjectFile();
final File projectRoot = ir.getProjectRoot();
final File buildDir = ir.getBuildDirectory();
final File workDir = ir.getWorkingDirectory();
final File mainClass = ir.getMainClass();
final File[] projectClassPaths = ir.getClassPaths();
final File createJarFile = ir.getCreateJarFile();
int createJarFlags = ir.getCreateJarFlags();
// set breakpoints
try { getDebugger().removeAllBreakpoints(); }
catch(DebugException de) { /* ignore, just don't remove old breakpoints */ }
for (DebugBreakpointData dbd: ir.getBreakpoints()) {
try {
getDebugger().toggleBreakpoint(getDocumentForFile(dbd.getFile()), dbd.getOffset(), dbd.getLineNumber(),
dbd.isEnabled());
}
catch(DebugException de) { /* ignore, just don't add breakpoint */ }
}
// set watches
try { getDebugger().removeAllWatches(); }
catch(DebugException de) { /* ignore, just don't remove old watches */ }
for (DebugWatchData dwd: ir.getWatches()) {
try { getDebugger().addWatch(dwd.getName()); }
catch(DebugException de) { /* ignore, just don't add watch */ }
}
final String projfilepath = projectRoot.getCanonicalPath();
// Get the list of documents that are still open
// final List<OpenDefinitionsDocument> oldDocs = getOpenDefintionsDocuments();
// final FileGroupingState oldState = _state;
// Utilities.showDebug("openProject called with file " + projectFile);
// Sets up the filters that cause documents to load in differentnsections of the tree. The names of these
// sections are set from the methods such as getSourceBinTitle(). Changing this changes what is considered
// source, aux, and external.
List<Pair<String, INavigatorItemFilter<OpenDefinitionsDocument>>> l =
new LinkedList<Pair<String, INavigatorItemFilter<OpenDefinitionsDocument>>>();
l.add(new Pair<String, INavigatorItemFilter<OpenDefinitionsDocument>>(getSourceBinTitle(),
new INavigatorItemFilter<OpenDefinitionsDocument>() {
public boolean accept(OpenDefinitionsDocument d) { return d.isInProjectPath(); }
}));
l.add(new Pair<String, INavigatorItemFilter<OpenDefinitionsDocument>>(getAuxiliaryBinTitle(),
new INavigatorItemFilter<OpenDefinitionsDocument>() {
public boolean accept(OpenDefinitionsDocument d) { return d.isAuxiliaryFile(); }
}));
l.add(new Pair<String, INavigatorItemFilter<OpenDefinitionsDocument>>(getExternalBinTitle(),
new INavigatorItemFilter<OpenDefinitionsDocument>() {
public boolean accept(OpenDefinitionsDocument d) {
return !(d.inProject() || d.isAuxiliaryFile()) || d.isUntitled();
}
}));
IDocumentNavigator<OpenDefinitionsDocument> newNav =
new AWTContainerNavigatorFactory<OpenDefinitionsDocument>().makeTreeNavigator(projfilepath, getDocumentNavigator(), l);
setDocumentNavigator(newNav);
synchronized(_auxiliaryFiles) {
_auxiliaryFiles.clear();
for (File file: auxFiles) { _auxiliaryFiles.add(file); }
}
ClassPathVector extraClassPaths = new ClassPathVector();
for (File f : projectClassPaths) { extraClassPaths.add(f); }
// Utilities.show("Project Root loaded into grouping state is " + projRoot);
setFileGroupingState(makeProjectFileGroupingState(projectRoot, mainClass, buildDir, workDir, projectFile, srcFiles,
extraClassPaths, createJarFile, createJarFlags));
resetInteractions(getWorkingDirectory()); // Shutdown debugger and reset interactions pane in new working directory
ArrayList<File> projFiles = new ArrayList<File>();
File active = null;
for (DocFile f: srcFiles) {
File file = f;
if (f.lastModified() > f.getSavedModDate()) file = new File(f.getPath());
if (f.isActive() && active == null) active = file;
else projFiles.add(file);
}
for (DocFile f: auxFiles) {
File file = f;
if (f.lastModified() > f.getSavedModDate()) file = new File(f.getPath());
if (f.isActive() && active == null) active = file;
else projFiles.add(file);
}
// Insert active file as last file on list.
if (active != null) projFiles.add(active);
// Utilities.showDebug("Project files are: " + projFiles);
final List<OpenDefinitionsDocument> projDocs = getProjectDocuments(); // opened documents in the project source tree
// This code may be unnecessary; no files from the previous project (if any) can be open since it was already closed.
// But all other files open at time this project is loaded are eligible for inclusion in the new project. This
if (! projDocs.isEmpty())
Utilities.invokeAndWait(new SRunnable() {
public void run() {
for (OpenDefinitionsDocument d: projDocs) {
try {
final String path = fixPathForNavigator(d.getFile().getCanonicalPath());
_documentNavigator.refreshDocument(d, path); // this operation must run in event thread
}
catch(IOException e) { /* Do nothing */ }
}
}
});
// Utilities.showDebug("Preparing to refresh navigator GUI");
// call on the GUI to finish up by opening the files and making necessary gui component changes
final File[] filesToOpen = projFiles.toArray(new File[projFiles.size()]);
_notifier.projectOpened(projectFile, new FileOpenSelector() {
public File[] getFiles() { return filesToOpen; }
});
if (_documentNavigator instanceof JTreeSortNavigator) {
((JTreeSortNavigator<?>)_documentNavigator).collapsePaths(ir.getCollapsedPaths());
}
return srcFiles; // Unnecessarily returns src files in keeping with the previous interface.
}
/** Performs any needed operations on the model before closing the project and its files. This is not
* responsible for actually closing the files since that is handled in MainFrame._closeProject().
* Resets interations unless supressReset is true.
*/
public void closeProject(boolean suppressReset) {
setDocumentNavigator(new AWTContainerNavigatorFactory<OpenDefinitionsDocument>().
makeListNavigator(getDocumentNavigator()));
setFileGroupingState(makeFlatFileGroupingState());
// Reset rather than telling the user to reset. This was a design decision
// made by the class Spring 2005 after much debate.
if (! suppressReset) resetInteractions(getWorkingDirectory());
_notifier.projectClosed();
}
/** If the document is untitled, brings it to the top so that the
* user will know which is being saved.
*/
public void aboutToSaveFromSaveAll(OpenDefinitionsDocument doc) {
if (doc.isUntitled()) setActiveDocument(doc);
}
/** Closes an open definitions document, prompting to save if the document has been changed. Returns whether
* the file was successfully closed. Also ensures the invariant that there is always at least
* one open document holds by creating a new file if necessary.
* @return true if the document was closed
*/
public boolean closeFile(OpenDefinitionsDocument doc) {
List<OpenDefinitionsDocument> list = new LinkedList<OpenDefinitionsDocument>();
list.add(doc);
return closeFiles(list);
}
/** Attempts to close all open documents. Also ensures the invariant that there is always at least
* one open document holds by creating a new file if necessary.
//Bug when the first document, in list view, is selected:
//When "close all" documents is selected, each document in turn is set active
//Fix: close the currently active document last
* @return true if all documents were closed
*/
public boolean closeAllFiles() {
List<OpenDefinitionsDocument> docs = getOpenDefinitionsDocuments();
return closeFiles(docs);
}
/** This function closes a group of files assuming that the files are contiguous in the enumeration
* provided by the document navigator. This assumption is used in selecting which remaining document
* (if any) to activate.
* <p>
* The corner cases in which the file that is being closed had been externally
* deleted have been addressed in a few places, namely DefaultGlobalModel.canAbandonFile()
* and MainFrame.ModelListener.canAbandonFile(). If the DefinitionsDocument for the
* OpenDefinitionsDocument being closed is not in the cache (see model.cache.DocumentCache)
* then it is closed without prompting the user to save it. If it is in the cache, then
* we can successfully notify the user that the file is selected for closing and ask whether to
* saveAs, close, or cancel.
* @param docList the list od OpenDefinitionsDocuments to close
* @return whether all files were closed
*/
public boolean closeFiles(List<OpenDefinitionsDocument> docList) {
if (docList.size() == 0) return true;
/* Force the user to save or discard all modified files in docList */
for (OpenDefinitionsDocument doc : docList) { if (! doc.canAbandonFile()) return false; }
// If all files are being closed, create a new file before starTing in order to have
// a potentially active file that is not in the list of closing files.
if (docList.size() == getOpenDefinitionsDocumentsSize()) newFile();
// Set the active document to the document just after the last document or the document just before the
// first document in docList. A new file does not appear in docList.
_ensureNotActive(docList);
// Close the files in docList.
for (OpenDefinitionsDocument doc : docList) { closeFileWithoutPrompt(doc); }
return true;
}
/** Helper for closeFile. This method was the closeFile(...) method before projects were added to DrJava. */
protected boolean closeFileHelper(OpenDefinitionsDocument doc) {
// System.err.println("closing " + doc);
boolean canClose = doc.canAbandonFile();
if (canClose) return closeFileWithoutPrompt(doc);
return false;
}
/** Similar to closeFileHelper except that saving cannot be cancelled. */
protected void closeFileOnQuitHelper(OpenDefinitionsDocument doc) {
// System.err.println("closing " + doc);
doc.quitFile();
closeFileWithoutPrompt(doc);
}
/** Closes an open definitions document, without prompting to save if the document has been changed. Returns
* whether the file was successfully closed. NOTE: This method should not be called unless it can be
* absolutely known that the document being closed is not the active document. The closeFile() method in
* SingleDisplayModel ensures that a new active document is set, but closeFileWithoutPrompt is not.
* @return true if the document was closed.
*/
public boolean closeFileWithoutPrompt(final OpenDefinitionsDocument doc) {
// new Exception("Closed document " + doc).printStackTrace();
boolean found;
synchronized(_documentsRepos) { found = _documentsRepos.remove(doc); }
if (! found) return false;
// remove breakpoints for this file
Debugger dbg = getDebugger();
if (dbg.isAvailable()) {
Vector<Breakpoint> bps = new Vector<Breakpoint>(doc.getBreakpoints());
for (int i = 0; i < bps.size(); i++) {
Breakpoint bp = bps.get(i);
try { dbg.removeBreakpoint(bp); }
catch(DebugException de) { /* ignore */ }
}
}
Utilities.invokeLater(new SRunnable() {
public void run() { _documentNavigator.removeDocument(doc); } // this operation must run in event thread
});
_notifier.fileClosed(doc);
doc.close();
return true;
}
/** Closes all open documents without creating a new empty document. It cannot be cancelled by the user
* because it would leave the current project in an inconsistent state. Method is public for
* testing purposes.
*/
public void closeAllFilesOnQuit() {
OpenDefinitionsDocument[] docs;
synchronized(_documentsRepos) { docs = _documentsRepos.toArray(new OpenDefinitionsDocument[0]); }
for (OpenDefinitionsDocument doc : docs) {
closeFileOnQuitHelper(doc); // modifies _documentsRepos
}
}
/** Exits the program. Quits regardless of whether all documents are successfully closed. */
public void quit() {
try {
closeAllFilesOnQuit();
// Utilities.show("Closed all files");
dispose(); // kills the interpreter
}
catch(Throwable t) { /* do nothing */ }
finally { System.exit(0); }
}
/** Prepares this model to be thrown away. Never called in practice outside of quit(), except in tests.
* This version does not kill the interpreter. */
public void dispose() {
_notifier.removeAllListeners();
// Utilities.show("All listeners removed");
synchronized(_documentsRepos) { _documentsRepos.clear(); }
// Utilities.show("Document Repository cleared");
Utilities.invokeAndWait(new SRunnable() {
public void run() { _documentNavigator.clear(); } // this operation must run in event thread
});
}
//----------------------- Specified by IGetDocuments -----------------------//
public OpenDefinitionsDocument getDocumentForFile(File file) throws IOException {
// Check if this file is already open
OpenDefinitionsDocument doc = _getOpenDocument(file);
if (doc == null) {
// If not, open and return it
final File f = file;
FileOpenSelector selector =
new FileOpenSelector() { public File[] getFiles() { return new File[] {f}; } };
try { doc = openFile(selector);}
catch (AlreadyOpenException e) { doc = e.getOpenDocument(); }
catch (OperationCanceledException e) { throw new UnexpectedException(e); /* Cannot happen */ }
}
return doc;
}
/** Iterates over OpenDefinitionsDocuments, looking for this file.
* TODO: This is not very efficient!
*/
public boolean isAlreadyOpen(File file) { return (_getOpenDocument(file) != null); }
/** Returns the OpenDefinitionsDocument corresponding to the INavigatorItem/DefinitionsDocument passed in.
* @param doc the searched for Document
* @return its corresponding OpenDefinitionsDocument
*/
public OpenDefinitionsDocument getODDForDocument(AbstractDocumentInterface doc) {
/** This function needs to be phased out altogether; the goal is for the OpenDefinitionsDocument
* to also function as its own Document, so this function will be useless
*/
if (doc instanceof OpenDefinitionsDocument) return (OpenDefinitionsDocument) doc;
if (doc instanceof DefinitionsDocument) return ((DefinitionsDocument) doc).getOpenDefDoc();
throw new IllegalStateException("Could not get the OpenDefinitionsDocument for Document: " + doc);
}
/** Gets a DocumentIterator to allow navigating through open Swing Documents. */
public DocumentIterator getDocumentIterator() { return this; }
/** Returns the ODD preceding the given document in the document list.
* @param d the current Document
* @return the next Document
*/
public OpenDefinitionsDocument getNextDocument(AbstractDocumentInterface d) {
OpenDefinitionsDocument nextdoc = null; // irrelevant initialization required by javac
// try {
OpenDefinitionsDocument doc = getODDForDocument(d);
nextdoc = _documentNavigator.getNext(doc);
if (nextdoc == doc) nextdoc = _documentNavigator.getFirst(); // wrap around if necessary
OpenDefinitionsDocument res = getNextDocHelper(nextdoc);
// Utilities.showDebug("nextDocument(" + d + ") = " + res);
return res;
// }
// catch(DocumentClosedException dce) { return getNextDocument(nextdoc); }
}
private OpenDefinitionsDocument getNextDocHelper(OpenDefinitionsDocument nextdoc) {
if (nextdoc.isUntitled() || nextdoc.verifyExists()) return nextdoc;
// Note: verifyExists prompts user for location of the file if it is not found
// cannot find nextdoc; move on to next document
return getNextDocument(nextdoc);
}
/** Returns the ODD preceding the given document in the document list.
* @param d the current Document
* @return the previous Document
*/
public OpenDefinitionsDocument getPrevDocument(AbstractDocumentInterface d) {
OpenDefinitionsDocument prevdoc = null; // irrelevant initialization required by javac
// try {
OpenDefinitionsDocument doc = getODDForDocument(d);
prevdoc = _documentNavigator.getPrevious(doc);
if (prevdoc == doc) prevdoc = _documentNavigator.getLast(); // wrap around if necessary
return getPrevDocHelper(prevdoc);
// }
// catch(DocumentClosedException dce) { return getPrevDocument(prevdoc); }
}
private OpenDefinitionsDocument getPrevDocHelper(OpenDefinitionsDocument prevdoc) {
if (prevdoc.isUntitled() || prevdoc.verifyExists()) return prevdoc;
// Note: verifyExists() prompts user for location of prevdoc
// cannot find prevdoc; move on to preceding document
return getPrevDocument(prevdoc);
}
public int getDocumentCount() { return _documentsRepos.size(); }
/** Returns a new collection of all documents currently open for editing.
* This is equivalent to the results of getDocumentForFile for the set
* of all files for which isAlreadyOpen returns true.
* @return a random-access List of the open definitions documents.
*
* This essentially duplicates the method valuesArray() in OrderedHashSet.
*/
public List<OpenDefinitionsDocument> getOpenDefinitionsDocuments() {
synchronized(_documentsRepos) {
ArrayList<OpenDefinitionsDocument> docs = new ArrayList<OpenDefinitionsDocument>(_documentsRepos.size());
for (OpenDefinitionsDocument doc: _documentsRepos) { docs.add(doc); }
return docs;
}
}
/** @return the size of the collection of OpenDefinitionsDocuments */
public int getOpenDefinitionsDocumentsSize() { synchronized(_documentsRepos) { return _documentsRepos.size(); } }
/** @return true if all open documents are in sync with their primary class files. */
public boolean hasOutOfSyncDocuments() {
synchronized(_documentsRepos) {
for (OpenDefinitionsDocument doc: _documentsRepos) {
if (doc.isSourceFile() && ! doc.checkIfClassFileInSync()) return true;
}
return false;
}
}
// public OpenDefinitionsDocument getODDGivenIDoc(INavigatorItem idoc) {
// synchronized(_documentsRepos) { return _documentsRepos.getValue(idoc); }
// }
// public INavigatorItem getIDocGivenODD(OpenDefinitionsDocument odd) {
// synchronized(_documentsRepos) { return _documentsRepos.getKey(odd); }
// }
//----------------------- End IGetDocuments Methods -----------------------//
/**
* Set the indent tab size for all definitions documents.
* @param indent the number of spaces to make per level of indent
*/
void setDefinitionsIndent(int indent) {
OpenDefinitionsDocument[] docs;
synchronized(_documentsRepos) { docs = _documentsRepos.toArray(new OpenDefinitionsDocument[0]); }
for (OpenDefinitionsDocument doc: docs) { doc.setIndent(indent); }
}
/** A degenerate operation since this has no interactions model. */
public void resetInteractions(File wd) { /* do nothing */ }
/** Resets the console. Fires consoleReset() event. */
public void resetConsole() {
_consoleDoc.reset("");
_notifier.consoleReset();
}
/** throw new UnsupportedOperationException */
public void interpretCurrentInteraction() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support interactions");
}
/** throws UnsupportedOperationException */
public void loadHistory(FileOpenSelector selector) throws IOException {
throw new UnsupportedOperationException("AbstractGlobalModel does not support interactions");
}
/** throws UnsupportedOperationException */
public InteractionsScriptModel loadHistoryAsScript(FileOpenSelector selector) throws
IOException, OperationCanceledException {
throw new UnsupportedOperationException("AbstractGlobalModel does not support interactions");
}
/** throws UnsupportedOperationException */
public void clearHistory() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support interactions");
}
/** throws UnsupportedOperationException */
public void saveHistory(FileSaveSelector selector) throws IOException {
throw new UnsupportedOperationException("AbstractGlobalModel does not support interactions");
}
/** throws UnsupportedOperationException */
public void saveHistory(FileSaveSelector selector, String editedVersion) throws IOException {
throw new UnsupportedOperationException("AbstractGlobalModel does not support interactions");
}
/** Returns the entire history as a String with semicolons as needed. */
public String getHistoryAsStringWithSemicolons() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support interactions");
}
/** Throws UnsupportedOperationException */
public String getHistoryAsString() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support interactions");
}
/** Registers OptionListeners. Factored out code from the two constructor. */
private void _registerOptionListeners() {
// // Listen to any relevant config options
// DrJava.getConfig().addOptionListener(EXTRA_CLASSPATH,
// new ExtraClasspathOptionListener());
DrJava.getConfig().addOptionListener(BACKUP_FILES,
new BackUpFileOptionListener());
Boolean makeBackups = DrJava.getConfig().getSetting(BACKUP_FILES);
FileOps.DefaultFileSaver.setBackupsEnabled(makeBackups.booleanValue());
// DrJava.getConfig().addOptionListener(ALLOW_PRIVATE_ACCESS,
// new OptionListener<Boolean>() {
// public void optionChanged(OptionEvent<Boolean> oce) {
// getInteractionsModel().setPrivateAccessible(oce.value.booleanValue());
// }
// });
}
/** Appends a string to the given document using a particular attribute set.
* Also waits for a small amount of time (WRITE_DELAY) to prevent any one
* writer from flooding the model with print calls to the point that the
* user interface could become unresponsive.
* @param doc Document to append to
* @param s String to append to the end of the document
* @param style the style to print with
*/
protected void _docAppend(ConsoleDocument doc, String s, String style) {
synchronized(_systemWriterLock) {
try {
doc.insertBeforeLastPrompt(s, style);
// Wait to prevent being flooded with println's
_systemWriterLock.wait(WRITE_DELAY);
}
catch (InterruptedException e) {
// It's ok, we'll go ahead and resume
}
}
}
/** Prints System.out to the DrJava console. */
public void systemOutPrint(String s) {
_docAppend(_consoleDoc, s, ConsoleDocument.SYSTEM_OUT_STYLE);
}
/** Prints System.err to the DrJava console. */
public void systemErrPrint(String s) { _docAppend(_consoleDoc, s, ConsoleDocument.SYSTEM_ERR_STYLE); }
/** throws UnsupportedOperationException */
public void printDebugMessage(String s) {
throw new UnsupportedOperationException("AbstractGlobalModel does not support debugging");
}
/** throw new UnsupportedOperationException */
public void waitForInterpreter() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support interactions");
}
/** throws new UnsupportedOperationException */
public ClassPathVector getClassPath() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support classPaths");
}
/** Returns a project's extra classpaths; empty for FlatFileGroupingState
* @return The classpath entries loaded along with the project
*/
public ClassPathVector getExtraClassPath() { return _state.getExtraClassPath(); }
/** Sets the set of classpath entries to use as the projects set of classpath entries. This is normally used by the
* project preferences..
*/
public void setExtraClassPath(ClassPathVector cp) {
_state.setExtraClassPath(cp);
//System.out.println("Setting project classpath to: " + cp);
}
/** Gets an array of all sourceRoots for the open definitions documents, without duplicates. Note that if any of
* the open documents has an invalid package statement, it won't be adde to the source root set. On 8.7.02
* changed the sourceRootSet such that the directory DrJava was executed from is now after the sourceRoots
* of the currently open documents in order that whatever version the user is looking at corresponds to the
* class file the interactions window uses.
* TODO: Fix out of date comment, possibly remove this here?
*/
public File[] getSourceRootSet() {
HashSet<File> roots = new HashSet<File>();
OpenDefinitionsDocument[] docs;
synchronized(_documentsRepos) { docs = _documentsRepos.toArray(new OpenDefinitionsDocument[0]); }
// Utilities.show("Getting sourceRootSet for " + Arrays.toString(docs));
for (OpenDefinitionsDocument doc: docs) {
try {
File root = doc.getSourceRoot();
if (root != null) roots.add(root); // Can't create duplicate entries in a HashSet
}
catch (InvalidPackageException e) {
// Utilities.show("InvalidPackageException in getSourceRootSet");
/* file has invalid package statement; ignore it */
}
}
return roots.toArray(new File[roots.size()]);
}
/** Return the name of the file, or "(untitled)" if no file exists. Does not include the ".java" if it is present.
* TODO: move to a static utility class? Should we remove language level extensions as well?
*/
public String getDisplayFileName(OpenDefinitionsDocument doc) { return doc.getDisplayFileName(); }
/** Return the absolute path of the file with the given index, or "(untitled)" if no file exists. */
public String getDisplayFullPath(int index) {
OpenDefinitionsDocument doc = getOpenDefinitionsDocuments().get(index);
if (doc == null) throw new RuntimeException( "Document not found with index " + index);
return doc.getDisplayFullPath();
}
/** throws UnsupportedOperationException */
public Debugger getDebugger() {
// throw new UnsupportedOperationException("AbstractGlobalModel does not support debugging");
return NoDebuggerAvailable.ONLY;
}
/** throws UnsupportedOperationException */
public int getDebugPort() throws IOException {
throw new UnsupportedOperationException("AbstractGlobalModel does not support debugging");
}
/** Checks if any open definitions documents have been modified since last being saved.
* @return whether any documents have been modified
*/
public boolean hasModifiedDocuments() {
OpenDefinitionsDocument[] docs;
synchronized(_documentsRepos) { docs = _documentsRepos.toArray(new OpenDefinitionsDocument[0]); }
for (OpenDefinitionsDocument doc: docs) { if (doc.isModifiedSinceSave()) return true; }
return false;
}
/** Checks if any open definitions documents are untitled.
* @return whether any documents are untitled
*/
public boolean hasUntitledDocuments() {
OpenDefinitionsDocument[] docs;
synchronized(_documentsRepos) { docs = _documentsRepos.toArray(new OpenDefinitionsDocument[0]); }
for (OpenDefinitionsDocument doc: docs) { if (doc.isUntitled()) return true; }
return false;
}
/** Searches for a file with the given name on the current source roots and the augmented classpath.
* @param fileName name of the source file to look for
* @return the file corresponding to the given name, or null if it cannot be found
*/
public File getSourceFile(String fileName) {
File[] sourceRoots = getSourceRootSet();
for (File s: sourceRoots) {
File f = _getSourceFileFromPath(fileName, s);
if (f != null) return f;
}
Vector<File> sourcepath = DrJava.getConfig().getSetting(OptionConstants.DEBUG_SOURCEPATH);
return getSourceFileFromPaths(fileName, sourcepath);
}
/** Searches for a file with the given name on the provided paths. Returns null if the file is not found.
* @param fileName Name of the source file to look for
* @param paths An array of directories to search
* @return the file if it is found, or null otherwise
*/
public File getSourceFileFromPaths(String fileName, List<File> paths) {
for (File p: paths) {
File f = _getSourceFileFromPath(fileName, p);
if (f != null) return f;
}
return null;
}
/** Gets the file named filename from the given path, if it exists. Returns null if it's not there.
* @param filename the file to look for
* @param path the path to look for it in
* @return the file if it exists
*/
private File _getSourceFileFromPath(String fileName, File path) {
String root = path.getAbsolutePath();
File f = new File(root + System.getProperty("file.separator") + fileName);
return f.exists() ? f : null;
}
/** Jar the current documents or the current project */
public void jarAll() { _state.jarAll(); }
private static volatile int ID_COUNTER = 0; /* Seed for assigning id numbers to OpenDefinitionsDocuments */
// ---------- ConcreteOpenDefDoc inner class ----------
/** A wrapper around a DefinitionsDocument or potential DefinitionsDocument (if it has been kicked out of the cache)
* The GlobalModel interacts with DefinitionsDocuments through this wrapper.<br>
* This call was formerly called the <code>DefinitionsDocumentHandler</code> but was renamed (2004-Jun-8) to be more
* descriptive/intuitive. (Really? CC)
*/
class ConcreteOpenDefDoc implements OpenDefinitionsDocument, AbstractDocumentInterface {
// private boolean _modifiedSinceSave;
private volatile File _file;
private volatile long _timestamp;
/** Caret position, as set by the view. */
private int _caretPosition;
/** The folder containing this document */
private volatile File _parentDir;
protected volatile String _packageName = null;
private volatile DCacheAdapter _cacheAdapter;
protected volatile Vector<Breakpoint> _breakpoints;
private volatile int _initVScroll;
private volatile int _initHScroll;
private volatile int _initSelStart;
private volatile int _initSelEnd;
private volatile int _id;
private volatile DrJavaBook _book;
/** Standard constructor for a document read from a file. Initializes this ODD's DD.
* @param f file describing DefinitionsDocument to manage; should be in canonical form
*/
ConcreteOpenDefDoc(File f) throws IOException {
if (! f.exists()) throw new FileNotFoundException("file " + f + " cannot be found");
_file = f;
_parentDir = f.getParentFile(); // should be canonical
_timestamp = f.lastModified();
init();
}
/* Standard constructor for a new document (no associated file) */
ConcreteOpenDefDoc() {
_file = null;
_parentDir = null;
init();
}
//----------- Initialization -----------//
public void init() {
_id = ID_COUNTER++;
try {
// System.out.println("about to make reconstructor " + this);
DDReconstructor ddr = makeReconstructor();
// System.out.println("finished making reconstructor " + this);
_cacheAdapter = _cache.register(this, ddr);
} catch(IllegalStateException e) { throw new UnexpectedException(e); }
_breakpoints = new Vector<Breakpoint>();
}
//------------ Getters and Setters -------------//
/** Returns the file field for this document; does not check whether the file exists. */
public File file() { return _file; }
/** Returns the file for this document, null if the document is untitled (and hence has no file. If the document's
* file does not exist, this throws a FileMovedException. If a FileMovedException is thrown, you
* can retrieve the non-existence source file from the FileMovedException by using the getFile() method.
* @return the file for this document
*/
public File getFile() throws FileMovedException {
if (_file == null) return null;
if (_file.exists()) return _file;
else throw new FileMovedException(_file, "This document's file has been moved or deleted.");
}
/** Sets the file for this openDefinitionsDocument. */
public void setFile(File file) {
_file = file;
if (_file != null) _timestamp = _file.lastModified();
}
/** Returns the timestamp. */
public long getTimestamp() { return _timestamp; }
/** Whenever this document has been saved, this method should be called to update its "isModified" information. */
public void resetModification() {
getDocument().resetModification();
if (_file != null) _timestamp = _file.lastModified();
}
/** @return The parent directory; should be in canonical form. */
public File getParentDirectory() { return _parentDir; }
/** Sets the parent directory of the document only if it is "Untitled"
* @param pd The parent directory
*/
public void setParentDirectory(File pd) {
if (_file != null)
throw new IllegalArgumentException("The parent directory can only be set for untitled documents");
_parentDir = pd;
}
void setPackage(String pack) { _packageName = pack; }
public int getInitialVerticalScroll() { return _initVScroll; }
public int getInitialHorizontalScroll() { return _initHScroll; }
public int getInitialSelectionStart() { return _initSelStart; }
public int getInitialSelectionEnd() { return _initSelEnd; }
void setInitialVScroll(int i) { _initVScroll = i; }
void setInitialHScroll(int i) { _initHScroll = i; }
void setInitialSelStart(int i) { _initSelStart = i; }
void setInitialSelEnd(int i) { _initSelEnd = i; }
/** Gets the definitions document being handled.
* @return document being handled
*/
protected DefinitionsDocument getDocument() {
// Utilities.showDebug("getDocument() called on " + this);
try { return _cacheAdapter.getDocument(); }
catch(IOException ioe) { // document has been moved or deleted
// Utilities.showDebug("getDocument() failed for " + this);
try {
_notifier.documentNotFound(this, _file);
final String path = fixPathForNavigator(getFile().getCanonicalFile().getCanonicalPath());
Utilities.invokeAndWait(new SRunnable() {
public void run() { _documentNavigator.refreshDocument(ConcreteOpenDefDoc.this, path); }
});
return _cacheAdapter.getDocument();
}
catch(Throwable t) { throw new UnexpectedException(t); }
}
}
/** Returns the name of the top level class, if any.
* @throws ClassNameNotFoundException if no top level class name found.
*/
public String getFirstTopLevelClassName() throws ClassNameNotFoundException {
return getDocument().getFirstTopLevelClassName();
}
/** Returns the name of this file, or "(untitled)" if no file. */
public String getFileName() {
if (_file == null) return "(Untitled)";
return _file.getName();
}
/** Returns the name of the file for this document with an appended asterisk (if modified) or spaces */
public String getName() {
String fileName = getFileName();
if (isModifiedSinceSave()) fileName = fileName + "*";
else fileName = fileName + " "; // forces the cell renderer to allocate space for an appended "*"
return fileName;
}
/** Return the name of the file for this document or "(Untitled)" if no file exists. Excludes the ".java"
* extension if it is present. TODO: should language extensions be removed?
*/
public String getDisplayFileName() {
String fileName = getFileName();
// Remove ".java" if at the end of name
if (fileName.endsWith(".java")) {
int extIndex = fileName.lastIndexOf(".java");
if (extIndex > 0) fileName = fileName.substring(0, extIndex);
}
// Mark if modified
if (isModifiedSinceSave()) fileName = fileName + '*';
return fileName;
}
/** Return the absolute path of this document's file, or "(Untitled)" if no file exists. */
public String getDisplayFullPath() {
String path = "(Untitled)";
try {
File file = getFile();
if (file != null) path = file.getAbsolutePath();
}
catch (FileMovedException fme) {
// Recover, even though file was deleted
File file = fme.getFile();
path = file.getAbsolutePath();
}
// Mark if modified
if (isModifiedSinceSave()) path = path + " *";
return path;
}
/** Originally designed to allow undoManager to set the current document to be modified whenever an undo
* or redo is performed. Now it actually does this.
*/
public void updateModifiedSinceSave() { getDocument().updateModifiedSinceSave(); }
/** Getter for document id; used to sort documents into creation order */
public int id() { return _id; }
/** Returns the Pageable object for printing.
* @return A Pageable representing this document.
*/
public Pageable getPageable() throws IllegalStateException { return _book; }
/** Clears the pageable object used to hold the print job. */
public void cleanUpPrintJob() { _book = null; }
//--------------- Simple Predicates ---------------//
/** A file is in the project if the source root is the same as the
* project root. this means that project files must be saved at the
* source root. (we query the model through the model's state)
*/
public boolean isInProjectPath() { return _state.isInProjectPath(this); }
/** An open file is in the new project if the source root is the same as the new project root. */
public boolean isInNewProjectPath(File projRoot) {
try { return ! isUntitled() && FileOps.isInFileTree(getFile(), projRoot); }
catch(FileMovedException e) { return false; }
}
/** A file is in the project if it is explicitly listed as part of the project. */
public boolean inProject() { return ! isUntitled() && _state.inProject(_file); }
/** @return true if this is an auxiliary file. */
public boolean isAuxiliaryFile() { return ! isUntitled() && _state.isAuxiliaryFile(_file); }
/** @return true if this has a legal source file name (ends in extension ".java", ".dj0", ".dj1", or ".dj2". */
public boolean isSourceFile() {
if (_file == null) return false;
String name = _file.getName();
for (String ext: CompilerModel.EXTENSIONS) { if (name.endsWith(ext)) return true; }
return false;
}
/** Returns whether this document is currently untitled (indicating whether it has a file yet or not).
* @return true if the document is untitled and has no file
*/
public boolean isUntitled() { return _file == null; }
/** Returns true if the file exists on disk. Returns false if the file has been moved or deleted */
public boolean fileExists() { return _file != null && _file.exists(); }
//--------------- Major Operations ----------------//
/** Returns true if the file exists on disk. Prompts the user otherwise */
public boolean verifyExists() {
// Utilities.showDebug("verifyExists called on " + _file);
if (fileExists()) return true;
//prompt the user to find it
try {
_notifier.documentNotFound(this, _file);
File f = getFile();
if (f == null) return false;
String path = fixPathForNavigator(getFile().getCanonicalPath());
_documentNavigator.refreshDocument(this, path);
return true;
}
catch(Throwable t) { return false; }
// catch(DocumentFileClosed e) { /* not clear what to do here */ }
}
/** Makes a default DDReconstructor that will make the corresponding DefinitionsDocument. */
protected DDReconstructor makeReconstructor() {
return new DDReconstructor() {
// Brand New documents start at location 0
private int _loc = 0;
// Start out with empty lists of listeners on the very first time the document is made
private DocumentListener[] _list = { };
private List<FinalizationListener<DefinitionsDocument>> _finalListeners =
new LinkedList<FinalizationListener<DefinitionsDocument>>();
// Weak hashmap that associates a WrappedPosition with its offset when saveDocInfo was called
private WeakHashMap<DefinitionsDocument.WrappedPosition, Integer> _positions =
new WeakHashMap<DefinitionsDocument.WrappedPosition, Integer>();
public DefinitionsDocument make() throws IOException, BadLocationException, FileMovedException {
DefinitionsDocument tempDoc;
tempDoc = new DefinitionsDocument(_notifier);
tempDoc.setOpenDefDoc(ConcreteOpenDefDoc.this);
if (_file != null) {
FileReader reader = new FileReader(_file);
_editorKit.read(reader, tempDoc, 0);
reader.close(); // win32 needs readers closed explicitly!
}
_loc = Math.min(_loc, tempDoc.getLength()); // make sure not past end
_loc = Math.max(_loc, 0); // make sure not less than 0
tempDoc.setCurrentLocation(_loc);
for (DocumentListener d : _list) {
if (d instanceof DocumentUIListener) tempDoc.addDocumentListener(d);
}
for (FinalizationListener<DefinitionsDocument> l: _finalListeners) {
tempDoc.addFinalizationListener(l);
}
// re-create and update all positions
tempDoc.setWrappedPositionOffsets(_positions);
tempDoc.resetModification(); // Why is this necessary? A reconstructed document is already unmodified.
// tempDoc.setUndoManager(_undo);
assert ! tempDoc.isModifiedSinceSave();
try { _packageName = tempDoc.getPackageName(); }
catch(InvalidPackageException e) { _packageName = null; }
return tempDoc;
}
public void saveDocInfo(DefinitionsDocument doc) {
// These lines were commented out to fix a memory leak; evidently, the undomanager holds on to the document
// _undo = doc.getUndoManager();
// _undoListeners = doc.getUndoableEditListeners();
_loc = doc.getCurrentLocation();
_list = doc.getDocumentListeners();
_finalListeners = doc.getFinalizationListeners();
// save offsets of all positions
_positions.clear();
_positions = doc.getWrappedPositionOffsets();
}
public void addDocumentListener(DocumentListener dl) {
ArrayList<DocumentListener> tmp = new ArrayList<DocumentListener>();
for (DocumentListener l: _list) { if (dl != l) tmp.add(l); }
tmp.add(dl);
_list = tmp.toArray(new DocumentListener[tmp.size()]);
}
public String toString() { return ConcreteOpenDefDoc.this.toString(); }
};
}
/** Saves the document with a FileWriter. If the file name is already set, the method will use
* that name instead of whatever selector is passed in.
* @param com a selector that picks the file name if the doc is untitled
* @exception IOException
* @return true if the file was saved, false if the operation was canceled
*/
public boolean saveFile(FileSaveSelector com) throws IOException {
// System.err.println("saveFile called on " + this);
// System.err.println(this + " is untitled? " + isUntitled());
if (isUntitled()) return saveFileAs(com);
if (! isModifiedSinceSave()) return true;
// Didn't need to save since file is named and unmodified; return true, since the save wasn't "canceled"
FileSaveSelector realCommand = com;
try {
final File file = getFile();
// System.err.println("file name for doc to be saved is: " + file);
if (file != null) {
realCommand = new TrivialFSS(file);
// System.err.println("TrivialFSS set up");
}
}
catch (FileMovedException fme) {
// getFile() failed, prompt the user if a new one should be selected
if (com.shouldSaveAfterFileMoved(this, fme.getFile())) realCommand = com;
else return false;
// User declines to save as a new file, so don't save
}
// System.err.println("Calling saveFileAs");
return saveFileAs(realCommand);
}
/** Saves the document with a FileWriter. The FileSaveSelector will either provide a file name or prompt the
* user for one. It is up to the caller to decide what needs to be done to choose a file to save to. Once
* the file has been saved succssfully, this method fires fileSave(File). If the save fails for any
* reason, the event is not fired. This is synchronized against the compiler model to prevent saving and
* compiling at the same time- this used to freeze drjava.
* @param com a selector that picks the file name.
* @throws IOException if the save fails due to an IO error
* @return true if the file was saved, false if the operation was canceled
*/
public boolean saveFileAs(FileSaveSelector com) throws IOException {
try {
final OpenDefinitionsDocument openDoc = this;
// System.err.println("saveFileAs called");
final File file = com.getFile();
// System.err.println("saveFileAs called on " + file);
OpenDefinitionsDocument otherDoc = _getOpenDocument(file);
// Check if file is already open in another document
boolean openInOtherDoc = ((otherDoc != null) && (openDoc != otherDoc));
// If the file is open in another document, abort if user does not confirm overwriting it
if (openInOtherDoc) {
boolean shouldOverwrite = com.warnFileOpen(file);
if (! shouldOverwrite) return true; // operation not cancelled? Strange
}
if (! file.exists() || com.verifyOverwrite()) { // confirm that existing file can be overwritten
// System.err.println("Writing file " + file);
// Correct the case of the filename (in Windows)
if (! file.getCanonicalFile().getName().equals(file.getName())) file.renameTo(file);
// Check for # in the path of the file because if there
// is one, then the file cannot be used in the Interactions Pane
if (file.getAbsolutePath().indexOf("#") != -1) _notifier.filePathContainsPound();
// have FileOps save the file
// System.err.println("Calling FileOps.saveFile to save it");
FileOps.saveFile(new FileOps.DefaultFileSaver(file) {
public void saveTo(OutputStream os) throws IOException {
DefinitionsDocument doc = getDocument();
try {
doc.acquireReadLock(); // Technically required, but looks like overkill.
_editorKit.write(os, doc, 0, doc.getLength());
doc.releaseReadLock();
// Utilities.show("Wrote file containing:\n" + doc.getText());
}
catch (BadLocationException docFailed) { throw new UnexpectedException(docFailed); }
}
});
resetModification();
setFile(file);
try {
// This calls getDocument().getPackageName() because this may be untitled and this.getPackageName()
// returns "" if it's untitled. Right here we are interested in parsing the DefinitionsDocument's text
_packageName = getDocument().getPackageName();
}
catch(InvalidPackageException e) { _packageName = null; }
getDocument().setCachedClassFile(null);
checkIfClassFileInSync();
// Utilities.showDebug("ready to fire fileSaved for " + this);
_notifier.fileSaved(openDoc);
// Make sure this file is on the appropriate classpaths (does nothing in AbstractGlobalModel)
addDocToClassPath(this);
/* update the navigator */
_documentNavigator.refreshDocument(this, fixPathForNavigator(file.getCanonicalPath()));
/* set project changed flag */
setProjectChanged(true);
}
return true;
}
catch (OperationCanceledException oce) {
// Thrown by com.getFile() if the user cancels.
// We don't save if this happens.
return false;
}
}
/** This method tells the document to prepare all the DrJavaBook and PagePrinter objects. */
public void preparePrintJob() throws BadLocationException, FileMovedException {
String fileName = "(Untitled)";
File sourceFile = getFile();
if (sourceFile != null) fileName = sourceFile.getAbsolutePath();
_book = new DrJavaBook(getDocument().getText(), fileName, _pageFormat);
}
/** Prints the given document by bringing up a "Print" window. */
public void print() throws PrinterException, BadLocationException, FileMovedException {
preparePrintJob();
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPageable(_book);
if (printJob.printDialog()) printJob.print();
cleanUpPrintJob();
}
/** throws UnsupportedOperationException */
public void startCompile() throws IOException {
throw new UnsupportedOperationException("AbstractGlobalModel does not support compilation");
}
/** throws UnsupportedOperationException */
public void runMain() throws IOException, ClassNameNotFoundException {
throw new UnsupportedOperationException("AbstractGlobalModel does not support running");
}
/** throws UnsupportedOperationException */
public void startJUnit() throws IOException, ClassNotFoundException {
throw new UnsupportedOperationException("AbstractGlobalModel does not support unit testing");
}
/** throws UnsupportedOperationException */
public void generateJavadoc(FileSaveSelector saver) throws IOException {
throw new UnsupportedOperationException("AbstractGlobalModel does not support javadoc");
}
/** Determines if the document has been modified since the last save.
* @return true if the document has been modified
*/
public boolean isModifiedSinceSave() {
/* If the document has not been registered or it is virtualized (only stored on disk), then we know that
* it is not modified. This method can be called by debugging code (via getName() on a
* ConcreteOpenDefDoc) before the document has been registered (_cacheAdapter == null). */
if (_cacheAdapter != null && _cacheAdapter.isReady()) return getDocument().isModifiedSinceSave();
else return false;
}
public void documentSaved() { _cacheAdapter.documentSaved(getFileName()); }
public void documentModified() { _cacheAdapter.documentModified(); }
public void documentReset() { _cacheAdapter.documentReset(); }
/** Determines if the file for this document has been modified since it was loaded.
* @return true if the file has been modified
*/
public boolean isModifiedOnDisk() {
boolean ret = false;
try {
getDocument().aquireReadLock();
if (_file != null) ret = (_file.lastModified() > _timestamp);
}
finally { getDocument().releaseReadLock(); }
return ret;
}
/** Determines if document has a class file consistent with its current state. If this document is unmodified,
* this method examines the primary class file corresponding to this document and compares the timestamps of
* the class file to that of the source file. The empty untitled document is consider to be "in sync".
*/
public boolean checkIfClassFileInSync() {
// If modified, then definitely out of sync
if (isModifiedSinceSave()) {
getDocument().setClassFileInSync(false);
return false;
}
if (isUntitled()) return true;
// Look for cached class file
File classFile = getDocument().getCachedClassFile();
if (classFile == null) {
// Not cached, so locate the file
classFile = _locateClassFile();
getDocument().setCachedClassFile(classFile);
if ((classFile == null) || (!classFile.exists())) {
// couldn't find the class file
getDocument().setClassFileInSync(false);
return false;
}
}
// compare timestamps
File sourceFile;
try { sourceFile = getFile(); }
catch (FileMovedException fme) {
getDocument().setClassFileInSync(false);
return false;
}
if ((sourceFile == null) || (sourceFile.lastModified() > classFile.lastModified())) {
getDocument().setClassFileInSync(false);
return false;
}
else {
getDocument().setClassFileInSync(true);
return true;
}
}
/** Returns the class file for this source document by searching the source roots of open documents, the
* system classpath, and the "extra.classpath". Returns null if the class file could not be found.
*/
private File _locateClassFile() {
if (isUntitled()) return null;
String className;
try { className = getDocument().getQualifiedClassName(); }
catch (ClassNameNotFoundException cnnfe) { return null; /* No source class name */ }
String ps = System.getProperty("file.separator");
// replace periods with the System's file separator
className = StringOps.replace(className, ".", ps);
String fileName = className + ".class";
// Check source root set (open files)
ArrayList<File> roots = new ArrayList<File>();
if (getBuildDirectory() != null) roots.add(getBuildDirectory());
// Add the current document to the beginning of the roots list
try { roots.add(getSourceRoot()); }
catch (InvalidPackageException ipe) {
try {
File root = getFile().getParentFile();
if (root != null) roots.add(root);
}
catch(NullPointerException e) { throw new UnexpectedException(e); }
catch(FileMovedException fme) {
// Moved, but we'll add the old file to the set anyway
File root = fme.getFile().getParentFile();
if (root != null) roots.add(root);
}
}
File classFile = getSourceFileFromPaths(fileName, roots);
if (classFile != null) return classFile;
// Class not on source root set, check system classpath
String cp = System.getProperty("java.class.path");
String pathSeparator = System.getProperty("path.separator");
Vector<File> cpVector = new Vector<File>();
int i = 0;
while (i < cp.length()) {
int nextSeparator = cp.indexOf(pathSeparator, i);
if (nextSeparator == -1) {
cpVector.add(new File(cp.substring(i, cp.length())));
break;
}
cpVector.add(new File(cp.substring(i, nextSeparator)));
i = nextSeparator + 1;
}
classFile = getSourceFileFromPaths(fileName, cpVector);
if (classFile != null) return classFile;
// not on system classpath, check interactions classpath
return getSourceFileFromPaths(fileName, DrJava.getConfig().getSetting(EXTRA_CLASSPATH));
}
/** Determines if the definitions document has been changed by an outside agent. If the document has changed,
* asks the listeners if the GlobalModel should revert the document to the most recent version saved.
* @return true if document has been reverted
*/
public boolean revertIfModifiedOnDisk() throws IOException{
final OpenDefinitionsDocument doc = this;
if (isModifiedOnDisk()) {
boolean shouldRevert = _notifier.shouldRevertFile(doc);
if (shouldRevert) doc.revertFile();
return shouldRevert;
}
return false;
}
/* Degenerate version of close; does not remove breakpoints in this document */
public void close() {
removeFromDebugger();
_cacheAdapter.close();
}
public void revertFile() throws IOException {
//need to remove old, possibly invalid breakpoints
removeFromDebugger();
final OpenDefinitionsDocument doc = this;
try {
File file = doc.getFile();
if (file == null) throw new UnexpectedException("Cannot revert an Untitled file!");
//this line precedes .remove() so that an invalid file is not cleared before this fact is discovered.
FileReader reader = new FileReader(file);
doc.clear();
_editorKit.read(reader, doc, 0);
reader.close(); // win32 needs readers closed explicitly!
resetModification();
doc.checkIfClassFileInSync();
setCurrentLocation(0);
_notifier.fileReverted(doc);
}
catch (BadLocationException e) { throw new UnexpectedException(e); }
}
/** Asks the listeners if the GlobalModel can abandon the current document. Fires the canAbandonFile(File)
* event if isModifiedSinceSave() is true.
* @return true if the current document can be abandoned, false if the current action should be halted in
* its tracks (e.g., file open when the document has been modified since the last save).
*/
public boolean canAbandonFile() {
if (isModifiedSinceSave() || (_file != null && !_file.exists() && _cacheAdapter.isReady()))
return _notifier.canAbandonFile(this);
else return true;
}
/** Fires the quit(File) event if isModifiedSinceSave() is true. The quitFile() event asks the user if the
* the file should be saved before quitting.
*/
public void quitFile() {
if (isModifiedSinceSave() || (_file != null && !_file.exists() && _cacheAdapter.isReady()))
_notifier.quitFile(this);
}
/** Moves the definitions document to the given line, and returns the resulting character position.
* @param line Destination line number. If it exceeds the number of lines in the document, it is
* interpreted as the last line.
* @return Index into document of where it moved
*/
public int gotoLine(int line) {
getDocument().gotoLine(line);
return getDocument().getCurrentLocation();
}
/** Forwarding method to sync the definitions with whatever view component is representing them. */
public void setCurrentLocation(int location) { _caretPosition = location; getDocument().setCurrentLocation(location); }
/**
* Get the location of the cursor in the definitions according
* to the definitions document.
*/
public int getCurrentLocation() { return getDocument().getCurrentLocation(); }
/** @return the caret position as set by the view. */
public int getCaretPosition() { return _caretPosition; }
/**
* Forwarding method to find the match for the closing brace
* immediately to the left, assuming there is such a brace.
* @return the relative distance backwards to the offset before
* the matching brace.
*/
public int balanceBackward() { return getDocument().balanceBackward(); }
/**
* Forwarding method to find the match for the open brace
* immediately to the right, assuming there is such a brace.
* @return the relative distance forwards to the offset after
* the matching brace.
*/
public int balanceForward() { return getDocument().balanceForward(); }
/** throws UnsupportedOperationException */
public Breakpoint getBreakpointAt(int offset) {
throw new UnsupportedOperationException("AbstractGlobalModel does not support debugger");
}
/** throws UnsupportedOperationException */
public void addBreakpoint( Breakpoint breakpoint) {
throw new UnsupportedOperationException("AbstractGlobalModel does not support debugger");
}
/** throws UnsupportedOperationException */
public void removeBreakpoint(Breakpoint breakpoint) {
throw new UnsupportedOperationException("AbstractGlobalModel does not support debugger");
}
/** throws UnsupportedOperationException */
public Vector<Breakpoint> getBreakpoints() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support debugger");
}
/** throws UnsupportedOperationException */
public void clearBreakpoints() {
throw new UnsupportedOperationException("AbstractGlobalModel does not support debugger");
}
/** throws UnsupportedOperationException */
public void removeFromDebugger() { /* do nothing because it is called in methods in this class */ }
/** Finds the root directory for the source file for this document; null if document is Untitled.
* @return The root directory of the source files, based on the package statement.
* @throws InvalidPackageException if the package statement is invalid,
* or if it does not match up with the location of the source file.
*/
public File getSourceRoot() throws InvalidPackageException {
// Utilities.show("getSourceRoot() called on " + this);
if (_packageName == null) _packageName = getPackageName();
// Utilities.show("getSourceRoot() returned " + _getSourceRoot(_packageName));
return _getSourceRoot(_packageName);
}
/** Gets the name of the package this source file claims it's in (with the package keyword).
* It does this by minimally parsing the source file to find the package statement.
*
* @return The name of package this source file declares itself to be in, or the empty string if there is no
* package statement (and thus the source file is in the empty package).
* @exception InvalidPackageException if there is some sort of a <TT>package</TT> statement but it is invalid.
*/
public String getPackageName() throws InvalidPackageException {
if (isUntitled()) _packageName = "";
else if (_packageName == null) _packageName = getDocument().getPackageName();
return _packageName;
}
/** Finds the root directory of the source file.
* @param packageName Package name, already fetched from the document
* @return The root directory of the source file based on the package statement.
* @throws InvalidPackageException If the package statement is invalid, or if it does not match up with the
* location of the source file.
*/
File _getSourceRoot(String packageName) throws InvalidPackageException {
File sourceFile;
try {
sourceFile = getFile();
if (sourceFile == null)
throw new InvalidPackageException(-1, "Can not get source root for unsaved file. Please save.");
}
catch (FileMovedException fme) {
throw new
InvalidPackageException(-1, "File has been moved or deleted from its previous location. Please save.");
}
if (packageName.equals("")) { return sourceFile.getParentFile(); }
ArrayList<String> packageStack = new ArrayList<String>();
int dotIndex = packageName.indexOf('.');
int curPartBegins = 0;
while (dotIndex != -1) {
packageStack.add(packageName.substring(curPartBegins, dotIndex));
curPartBegins = dotIndex + 1;
dotIndex = packageName.indexOf('.', dotIndex + 1);
}
// Now add the last package component
packageStack.add(packageName.substring(curPartBegins));
// Must use the canonical path, in case there are dots in the path (which will conflict with the package name)
try {
File parentDir = sourceFile.getCanonicalFile();
while (! packageStack.isEmpty()) {
String part = pop(packageStack);
parentDir = parentDir.getParentFile();
if (parentDir == null) throw new RuntimeException("parent dir is null!");
// Make sure the package piece matches the directory name
if (! part.equals(parentDir.getName())) {
String msg = "The source file " + sourceFile.getAbsolutePath() +
" is in the wrong directory or in the wrong package. " +
"The directory name " + parentDir.getName() +
" does not match the package component " + part + ".";
throw new InvalidPackageException(-1, msg);
}
}
// OK, now parentDir points to the directory of the first component of the
// package name. The parent of that is the root.
parentDir = parentDir.getParentFile();
if (parentDir == null) {
throw new RuntimeException("parent dir of first component is null?!");
}
return parentDir;
}
catch (IOException ioe) {
String msg = "Could not locate directory of the source file: " + ioe;
throw new InvalidPackageException(-1, msg);
}
}
public String toString() { return getFileName(); }
/** Orders ODDs by their id's. */
public int compareTo(OpenDefinitionsDocument o) { return _id - o.id(); }
/** Implementation of the javax.swing.text.Document interface. */
public void addDocumentListener(DocumentListener listener) {
if (_cacheAdapter.isReady()) getDocument().addDocumentListener(listener);
else _cacheAdapter.getReconstructor().addDocumentListener(listener);
}
List<UndoableEditListener> _undoableEditListeners = new LinkedList<UndoableEditListener>();
public void addUndoableEditListener(UndoableEditListener listener) {
_undoableEditListeners.add(listener);
getDocument().addUndoableEditListener(listener);
}
public void removeUndoableEditListener(UndoableEditListener listener) {
_undoableEditListeners.remove(listener);
getDocument().removeUndoableEditListener(listener);
}
public UndoableEditListener[] getUndoableEditListeners() {
return getDocument().getUndoableEditListeners();
}
public Position createPosition(int offs) throws BadLocationException {
return getDocument().createPosition(offs);
}
public Element getDefaultRootElement() { return getDocument().getDefaultRootElement(); }
public Position getEndPosition() { return getDocument().getEndPosition(); }
public int getLength() { return getDocument().getLength(); }
public Object getProperty(Object key) { return getDocument().getProperty(key); }
public Element[] getRootElements() { return getDocument().getRootElements(); }
public Position getStartPosition() { return getDocument().getStartPosition(); }
public String getText(int offset, int length) throws BadLocationException {
return getDocument().getText(offset, length);
}
public void getText(int offset, int length, Segment txt) throws BadLocationException {
getDocument().getText(offset, length, txt);
}
public void insertString(int offset, String str, AttributeSet a) throws BadLocationException {
getDocument().insertString(offset, str, a);
}
public void append(String str, AttributeSet set) { getDocument().append(str, set); }
public void append(String str, Style style) { getDocument().append(str, style); }
public void putProperty(Object key, Object value) { getDocument().putProperty(key, value); }
public void remove(int offs, int len) throws BadLocationException { getDocument().remove(offs, len); }
public void removeDocumentListener(DocumentListener listener) {
getDocument().removeDocumentListener(listener);
}
public void render(Runnable r) { getDocument().render(r); }
/** End implementation of javax.swing.text.Document interface. */
/** If the undo manager is unavailable, no undos are available
* @return whether the undo manager can perform any undo's
*/
public boolean undoManagerCanUndo() { return _cacheAdapter.isReady() && getUndoManager().canUndo(); }
/**
* If the undo manager is unavailable, no redos are available
* @return whether the undo manager can perform any redo's
*/
public boolean undoManagerCanRedo() { return _cacheAdapter.isReady() && getUndoManager().canRedo(); }
/** Decorater patter for the definitions document. */
public CompoundUndoManager getUndoManager() { return getDocument().getUndoManager(); }
public int getLineStartPos(int pos) { return getDocument().getLineStartPos(pos); }
public int getLineEndPos(int pos) { return getDocument().getLineEndPos(pos); }
public int commentLines(int selStart, int selEnd) { return getDocument().commentLines(selStart, selEnd); }
public int uncommentLines(int selStart, int selEnd) {
return getDocument().uncommentLines(selStart, selEnd);
}
public void indentLines(int selStart, int selEnd) { getDocument().indentLines(selStart, selEnd); }
public int getCurrentCol() { return getDocument().getCurrentCol(); }
public boolean getClassFileInSync() { return getDocument().getClassFileInSync(); }
public int getIntelligentBeginLinePos(int currPos) throws BadLocationException {
return getDocument().getIntelligentBeginLinePos(currPos);
}
public int getOffset(int lineNum) { return getDocument().getOffset(lineNum); }
public String getQualifiedClassName() throws ClassNameNotFoundException {
return getDocument().getQualifiedClassName();
}
public String getQualifiedClassName(int pos) throws ClassNameNotFoundException {
return getDocument().getQualifiedClassName(pos);
}
public ReducedModelState getStateAtCurrent() { return getDocument().getStateAtCurrent(); }
public void resetUndoManager() {
// if it's not in the cache, the undo manager will be reset when it's reconstructed
if (_cacheAdapter.isReady()) getDocument().resetUndoManager();
}
public File getCachedClassFile() { return getDocument().getCachedClassFile(); }
public void setCachedClassFile(File f) { getDocument().setCachedClassFile(f); }
public DocumentListener[] getDocumentListeners() { return getDocument().getDocumentListeners(); }
//--------- DJDocument methods ----------
public void setTab(String tab, int pos) { getDocument().setTab(tab,pos); }
public int getWhiteSpace() { return getDocument().getWhiteSpace(); }
public boolean posInParenPhrase(int pos) { return getDocument().posInParenPhrase(pos); }
public boolean posInParenPhrase() { return getDocument().posInParenPhrase(); }
public String getEnclosingClassName(int pos, boolean fullyQualified) throws BadLocationException, ClassNameNotFoundException {
return getDocument().getEnclosingClassName(pos, fullyQualified);
}
public int findPrevEnclosingBrace(int pos, char opening, char closing) throws BadLocationException {
return getDocument().findPrevEnclosingBrace(pos, opening, closing);
}
public int findNextEnclosingBrace(int pos, char opening, char closing) throws BadLocationException {
return getDocument().findNextEnclosingBrace(pos, opening, closing);
}
public int findPrevNonWSCharPos(int pos) throws BadLocationException {
return getDocument().findPrevNonWSCharPos(pos);
}
public int getFirstNonWSCharPos(int pos) throws BadLocationException {
return getDocument().getFirstNonWSCharPos(pos);
}
public int getFirstNonWSCharPos(int pos, boolean acceptComments) throws BadLocationException {
return getDocument().getFirstNonWSCharPos(pos, acceptComments);
}
public int getFirstNonWSCharPos (int pos, char[] whitespace, boolean acceptComments)
throws BadLocationException {
return getDocument().getFirstNonWSCharPos(pos, whitespace, acceptComments);
}
public int getLineFirstCharPos(int pos) throws BadLocationException {
return getDocument().getLineFirstCharPos(pos);
}
public int findCharOnLine(int pos, char findChar) {
return getDocument().findCharOnLine(pos, findChar);
}
public String getIndentOfCurrStmt(int pos) throws BadLocationException {
return getDocument().getIndentOfCurrStmt(pos);
}
public String getIndentOfCurrStmt(int pos, char[] delims) throws BadLocationException {
return getDocument().getIndentOfCurrStmt(pos, delims);
}
public String getIndentOfCurrStmt(int pos, char[] delims, char[] whitespace) throws BadLocationException {
return getDocument().getIndentOfCurrStmt(pos, delims, whitespace);
}
public void indentLines(int selStart, int selEnd, int reason, ProgressMonitor pm)
throws OperationCanceledException {
getDocument().indentLines(selStart, selEnd, reason, pm);
}
public int findPrevCharPos(int pos, char[] whitespace) throws BadLocationException {
return getDocument().findPrevCharPos(pos, whitespace);
}
public boolean findCharInStmtBeforePos(char findChar, int position) {
return getDocument().findCharInStmtBeforePos(findChar, position);
}
public int findPrevDelimiter(int pos, char[] delims) throws BadLocationException {
return getDocument().findPrevDelimiter(pos, delims);
}
public int findPrevDelimiter(int pos, char[] delims, boolean skipParenPhrases) throws BadLocationException {
return getDocument().findPrevDelimiter(pos, delims, skipParenPhrases);
}
public void resetReducedModelLocation() { getDocument().resetReducedModelLocation(); }
public ReducedModelState stateAtRelLocation(int dist) { return getDocument().stateAtRelLocation(dist); }
public IndentInfo getIndentInformation() { return getDocument().getIndentInformation(); }
public void move(int dist) { getDocument().move(dist); }
public Vector<HighlightStatus> getHighlightStatus(int start, int end) {
return getDocument().getHighlightStatus(start, end);
}
public void setIndent(int indent) { getDocument().setIndent(indent); }
public int getIndent() { return getDocument().getIndent(); }
//-----------------------
/** This method is put here because the ODD is the only way to get to the defdoc. */
public void addFinalizationListener(FinalizationListener<DefinitionsDocument> fl) {
getDocument().addFinalizationListener(fl);
}
public List<FinalizationListener<DefinitionsDocument>> getFinalizationListeners() {
return getDocument().getFinalizationListeners();
}
// Styled Document Methods
public Font getFont(AttributeSet attr) { return getDocument().getFont(attr); }
public Color getBackground(AttributeSet attr) { return getDocument().getBackground(attr); }
public Color getForeground(AttributeSet attr) { return getDocument().getForeground(attr); }
public Element getCharacterElement(int pos) { return getDocument().getCharacterElement(pos); }
public Element getParagraphElement(int pos) { return getDocument().getParagraphElement(pos); }
public Style getLogicalStyle(int p) { return getDocument().getLogicalStyle(p); }
public void setLogicalStyle(int pos, Style s) { getDocument().setLogicalStyle(pos, s); }
public void setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace) {
getDocument().setCharacterAttributes(offset, length, s, replace);
}
public void setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace) {
getDocument().setParagraphAttributes(offset, length, s, replace);
}
public Style getStyle(String nm) { return getDocument().getStyle(nm); }
public void removeStyle(String nm) { getDocument().removeStyle(nm); }
public Style addStyle(String nm, Style parent) { return getDocument().addStyle(nm, parent); }
public String getText() {
DefinitionsDocument doc = getDocument();
doc.acquireReadLock();
try { return doc.getText(0, doc.getLength()); }
catch(BadLocationException e) { throw new UnexpectedException(e); }
finally { releaseReadLock(); }
}
public void clear() {
DefinitionsDocument doc = getDocument();
doc.acquireWriteLock();
try { doc.remove(0, doc.getLength()); }
catch(BadLocationException e) { throw new UnexpectedException(e); }
finally { releaseWriteLock(); }
}
/* Locking operations in DJDocument interface */
/** Swing-style readLock(). */
public void acquireReadLock() { getDocument().readLock(); }
/** Swing-style readUnlock(). */
public void releaseReadLock() { getDocument().readUnlock(); }
/** Swing-style writeLock(). */
public void acquireWriteLock() { getDocument().acquireWriteLock(); }
/** Swing-style writeUnlock(). */
public void releaseWriteLock() { getDocument().releaseWriteLock(); }
/** @return the number of lines in this document. */
public int getNumberOfLines() { return getDefaultRootElement().getElementIndex(getEndPosition().getOffset()-1); }
} /* End of ConcreteOpenDefDoc */
private static class TrivialFSS implements FileSaveSelector {
private File _file;
private TrivialFSS(File file) { _file = file; }
public File getFile() throws OperationCanceledException { return _file; }
public boolean warnFileOpen(File f) { return true; }
public boolean verifyOverwrite() { return true; }
public boolean shouldSaveAfterFileMoved(OpenDefinitionsDocument doc, File oldFile) { return true; }
}
/** Creates a ConcreteOpenDefDoc for a new DefinitionsDocument.
* @return OpenDefinitionsDocument object for a new document
*/
protected ConcreteOpenDefDoc _createOpenDefinitionsDocument() { return new ConcreteOpenDefDoc(); }
/** Creates a ConcreteOpenDefDoc for a given file f
* @return OpenDefinitionsDocument object for f
*/
protected ConcreteOpenDefDoc _createOpenDefinitionsDocument(File f) throws IOException { return new ConcreteOpenDefDoc(f); }
/** Returns the OpenDefinitionsDocument corresponding to the given File, or null if that file is not open.
* @param file File object to search for
* @return Corresponding OpenDefinitionsDocument, or null
*/
protected OpenDefinitionsDocument _getOpenDocument(File file) {
OpenDefinitionsDocument[] docs;
synchronized(_documentsRepos) { docs = _documentsRepos.toArray(new OpenDefinitionsDocument[0]); }
for (OpenDefinitionsDocument doc: docs) {
try {
File thisFile = null;
try { thisFile = doc.getFile(); }
catch (FileMovedException fme) { thisFile = fme.getFile(); } // File is invalid, but compare anyway
finally {
// Always do the comparison
if (thisFile != null) {
try {
// Compare canonical paths if possible
if (thisFile.getCanonicalFile().equals(file.getCanonicalFile())) return doc;
}
catch (IOException ioe) {
// Can be thrown from getCanonicalFile. If so, compare the files themselves
if (thisFile.equals(file)) return doc;
}
}
}
}
catch (IllegalStateException ise) { /* No file in doc; fail silently */ }
}
return null;
}
public List<OpenDefinitionsDocument> getNonProjectDocuments() {
List<OpenDefinitionsDocument> allDocs = getOpenDefinitionsDocuments();
List<OpenDefinitionsDocument> projectDocs = new LinkedList<OpenDefinitionsDocument>();
for (OpenDefinitionsDocument tempDoc : allDocs) {
if (!tempDoc.isInProjectPath()) projectDocs.add(tempDoc);
}
return projectDocs;
}
/** Returns the OpenDefinitionsDocuments that are located in the project source tree. */
public List<OpenDefinitionsDocument> getProjectDocuments() {
List<OpenDefinitionsDocument> allDocs = getOpenDefinitionsDocuments();
List<OpenDefinitionsDocument> projectDocs = new LinkedList<OpenDefinitionsDocument>();
for (OpenDefinitionsDocument tempDoc : allDocs)
if (tempDoc.isInProjectPath() || tempDoc.isAuxiliaryFile()) projectDocs.add(tempDoc);
return projectDocs;
}
/* Extracts relative path (from project origin) to parent of file identified by path. Assumes path does not end in
* File.separator. TODO: convert this method to take a File argument. */
public String fixPathForNavigator(String path) throws IOException {
String parent = path.substring(0, path.lastIndexOf(File.separator));
String topLevelPath;
String rootPath = getProjectRoot().getCanonicalPath();
if (! parent.equals(rootPath) && ! parent.startsWith(rootPath + File.separator))
/** it's an external file, so don't give it a path */
return "";
else
return parent.substring(rootPath.length());
}
/** Creates an OpenDefinitionsDocument for a file. Does not add to the navigator or notify that the file's open.
* This method should be called only from within another open method that will do all of this clean up.
* @param file the file to open
*/
private OpenDefinitionsDocument _rawOpenFile(File file) throws IOException, AlreadyOpenException{
OpenDefinitionsDocument openDoc = _getOpenDocument(file);
if (openDoc != null) throw new AlreadyOpenException(openDoc);
final ConcreteOpenDefDoc doc = _createOpenDefinitionsDocument(file);
if (file instanceof DocFile) {
DocFile df = (DocFile)file;
Pair<Integer,Integer> scroll = df.getScroll();
Pair<Integer,Integer> sel = df.getSelection();
doc.setPackage(df.getPackage());
doc.setInitialVScroll(scroll.getFirst());
doc.setInitialHScroll(scroll.getSecond());
doc.setInitialSelStart(sel.getFirst());
doc.setInitialSelEnd(sel.getSecond());
}
return doc;
}
/** This pop method enables an ArrayList to serve as stack. */
protected static <T> T pop(ArrayList<T> stack) { return stack.remove(stack.size() - 1); }
/** Creates an iNavigatorItem for a document, and adds it to the navigator. A helper for opening a file or creating
* a new file.
* @param doc the document to add to the navigator
*/
protected void addDocToNavigator(final OpenDefinitionsDocument doc) {
Utilities.invokeLater(new SRunnable() {
public void run() {
try {
if (doc.isUntitled()) _documentNavigator.addDocument(doc);
else {
String path = doc.getFile().getCanonicalPath();
_documentNavigator.addDocument(doc, fixPathForNavigator(path));
}
}
catch(IOException e) { _documentNavigator.addDocument(doc); }
}});
synchronized(_documentsRepos) { _documentsRepos.add(doc); }
}
/** Does nothing; overridden in DefaultGlobalModel. */
protected void addDocToClassPath(OpenDefinitionsDocument doc) { /* do nothing */ }
/** Creates a document from a file.
* @param file File to read document from
* @return openened document
*/
public OpenDefinitionsDocument _openFile(File file) throws IOException, AlreadyOpenException {
OpenDefinitionsDocument doc = _rawOpenFile(file);
addDocToNavigator(doc);
addDocToClassPath(doc);
_notifier.fileOpened(doc);
return doc;
}
private static class BackUpFileOptionListener implements OptionListener<Boolean> {
public void optionChanged (OptionEvent<Boolean> oe) {
Boolean value = oe.value;
FileOps.DefaultFileSaver.setBackupsEnabled(value.booleanValue());
}
}
//----------------------- SingleDisplay Methods -----------------------//
/** Returns the currently active document. */
public OpenDefinitionsDocument getActiveDocument() {return _activeDocument; }
/** Sets the currently active document by updating the selection model.
* @param doc Document to set as active
*/
public void setActiveDocument(final OpenDefinitionsDocument doc) {
/* The following code fixes a potential race because this method modifies the documentNavigator which is a swing
* component. Hence it must run in the event thread. Note that setting the active document triggers the execution
* of listeners some of which also need to run in the event thread.
*
* The _activeDoc field is set by _gainVisitor when the DocumentNavigator changes the active document.
*/
// if (_activeDocument == doc) return; // this optimization appears to cause some subtle bugs
// Utilities.showDebug("DEBUG: Called setActiveDocument()");
try {
Utilities.invokeAndWait(new SRunnable() {
public void run() { _documentNavigator.setActiveDoc(doc); }
});
}
catch(Exception e) { throw new UnexpectedException(e); }
}
public Container getDocCollectionWidget() { return _documentNavigator.asContainer(); }
/** Sets the active document to be the next one in the collection. */
public void setActiveNextDocument() {
OpenDefinitionsDocument key = _activeDocument;
OpenDefinitionsDocument nextKey = _documentNavigator.getNext(key);
if (key != nextKey) setActiveDocument(nextKey);
else setActiveDocument(_documentNavigator.getFirst());
/* selects the active document in the navigator, which signals a listener to call _setActiveDoc(...) */
}
/** Sets the active document to be the previous one in the collection. */
public void setActivePreviousDocument() {
OpenDefinitionsDocument key = _activeDocument;
OpenDefinitionsDocument prevKey = _documentNavigator.getPrevious(key);
if (key != prevKey) setActiveDocument(prevKey);
else setActiveDocument(_documentNavigator.getLast());
/* selects the active document in the navigator, which signals a listener to call _setActiveDoc(...) */
}
//----------------------- End SingleDisplay Methods -----------------------//
/** Returns whether there is currently only one open document which is untitled and unchanged. */
private boolean _hasOneEmptyDocument() {
return getOpenDefinitionsDocumentsSize() == 1 && _activeDocument.isUntitled() &&
! _activeDocument.isModifiedSinceSave();
}
/** Creates a new document if there are currently no documents open. */
private void _ensureNotEmpty() {
if ((!_isClosingAllDocs) && (getOpenDefinitionsDocumentsSize() == 0)) newFile(getMasterWorkingDirectory());
}
/** Makes sure that none of the documents in the list are active.
* Should only be executed in event thread.
*/
private void _ensureNotActive(List<OpenDefinitionsDocument> docs) {
if (docs.contains(getActiveDocument())) {
// Find the one that should be the new active document
IDocumentNavigator<OpenDefinitionsDocument> nav = getDocumentNavigator();
OpenDefinitionsDocument item = docs.get(docs.size()-1);
OpenDefinitionsDocument nextActive = nav.getNext(item);
if (!nextActive.equals(item)) {
setActiveDocument(nextActive);
return;
}
item = docs.get(0);
nextActive = nav.getPrevious(item);
if (!nextActive.equals(item)) {
setActiveDocument(nextActive);
return;
}
throw new RuntimeException("No document to set active before closing");
}
}
/** Sets the first document in the navigator as active. */
public void setActiveFirstDocument() {
List<OpenDefinitionsDocument> docs = getOpenDefinitionsDocuments();
// Utilities.show("Initial docs are " + docs);
/* The following will select the active document in the navigator, which will signal a listener to call _setActiveDoc(...)
*/
setActiveDocument(docs.get(0));
}
private void _setActiveDoc(INavigatorItem idoc) {
synchronized (this) { _activeDocument = (OpenDefinitionsDocument) idoc; }
refreshActiveDocument();
}
/** Invokes the activeDocumentChanged method in the global listener on the argument _activeDocument. This process
* sets up _activeDocument as the document in the definitions pane. It is also necessary after an "All Documents"
* search that wraps around. */
public void refreshActiveDocument() {
try {
_activeDocument.checkIfClassFileInSync();
// notify single display model listeners // notify single display model listeners
_notifier.activeDocumentChanged(_activeDocument);
} catch(DocumentClosedException dce) { /* do nothing */ }
}
}
| [
"375833274@qq.com"
] | 375833274@qq.com |
2dbaa4fbdf46f60b631f859e651d5a5079ab870c | 73066b7f697b4ccd4dca8f4e954f20e9b714af70 | /[OLC1]Practica1_201701187/src/Practica_1/Tabla_Follow.java | d7e2f31ee5fc0b4d13dbdc01f1e3acee7a3216c9 | [] | no_license | Pegre369/-OLC1-Practica1-201701187 | a79a1be54ebbc1c57dc905584c30d9034680ea0f | a5cf8cfd85b971610f34603099023fbd67b298db | refs/heads/master | 2022-04-11T18:08:50.229016 | 2020-03-13T00:04:24 | 2020-03-13T00:04:24 | 239,051,061 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,244 | java |
package Practica_1;
import java.awt.Desktop;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
public class Tabla_Follow {
public void TablaFollow(ArrayList<Lista_Follow> Acepatacion,String nombre) {
String Contenido;
Contenido = "<html>"
+ "<body>"
+ "<h1 align='center'>TABLA DE FOLLOW</h1></br>"
+ "<table cellpadding='10' border = '1' align='center'>"
+ "<tr>"
+ "<td><strong>Hoja"
+ "</strong></td>"
+ "<td><strong>Numero de hoja"
+ "</strong></td>"
+ "<td><strong>Follow"
+ "</strong></td>"
+ "</tr>";
String CadTokens = "";
String tempotk;
for (int i = 0; i < Acepatacion.size(); i++) {
tempotk = "";
tempotk = "<tr>"
+ "<td>" + Acepatacion.get(i).getHoja()
+ "</td>"
+ "<td>"
+ String.valueOf(Acepatacion.get(i).getNumero())
+ "</td>"
+ "<td>" + Acepatacion.get(i).getFollow()
+ "</td>"
+ "</tr>";
CadTokens = CadTokens + tempotk;
}
Contenido = Contenido + CadTokens
+ "</table>"
+ "</body>"
+ "</html>";
/*creando archivo html*/
File file = new File(nombre+".html");
try {
// Si el archivo no existe es creado
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(Contenido);
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
Desktop.getDesktop().open(file);
//archivo.delete();
} catch (Exception ex) {
}
/*File.WriteAllText("Reporte de Tokens.html", Contenido);
System.Diagnostics.Process.Start("Reporte de Tokens.html");*/
}
}
| [
"pedro.ordoniez@gmail.com"
] | pedro.ordoniez@gmail.com |
9b000073dae653af14954147bd77c08c0181d15c | 2891ab7d455728b4bcb51a6196b9cec5265f666f | /src/main/java/student_aleksandrs_jakovenko/lesson_2/level_1/Task2.java | aaefd3a2c5dc0128c7be6694d9a2b0dfddb7faa0 | [] | no_license | AlexJavaGuru/java_1_wednesday_2022 | 14eefec7c15ab7fce4d5b5a8ee545ff674e944df | dea5c75a855f4987bdf245aab7a05dddbb6ea9d0 | refs/heads/master | 2022-09-07T13:01:57.188817 | 2022-06-10T19:03:48 | 2022-06-10T19:03:48 | 449,743,084 | 11 | 7 | null | 2022-07-15T20:26:17 | 2022-01-19T15:16:45 | Java | UTF-8 | Java | false | false | 828 | java | package student_aleksandrs_jakovenko.lesson_2.level_1;
import java.util.Scanner;
class Task2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter first number:");
double firstNumber = scanner.nextDouble();
System.out.println("Enter second number:");
double secondNumber = scanner.nextDouble();
double sum = firstNumber + secondNumber;
double sub = firstNumber - secondNumber;
double mul = firstNumber * secondNumber;
double div = firstNumber / secondNumber;
System.out.println("Sum result: " + sum);
System.out.println("Subtraction result: " + sub);
System.out.println("Multiplication result: " + mul);
System.out.println("Divide result: " + div);
}
}
| [
"jako2577@gmail.com"
] | jako2577@gmail.com |
f3597a4e9950b0b286e066dc44fe3a1ef9a496ac | 6f6b7e373df41f7fc56e2a1dd1b0f52a53e828ce | /core/src/main/java/tv/huan/master/util/IpUtils.java | 39502968328fbfabac0afd92e638bffde2eb9e3f | [] | no_license | ianyang82/tyserver | be8361173e5d1a7f7d31b7ff68b00df22a20205d | 49f437bb9e4bf91df21465add100a6078109f886 | refs/heads/master | 2021-07-18T22:39:43.814365 | 2017-10-19T02:01:53 | 2017-10-19T02:01:53 | 106,662,468 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,418 | java | package tv.huan.master.util;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IpUtils {
private IpUtils() {
}
public static String getIpAddr(HttpServletRequest request) {
if (request == null) {
return "unknown";
}
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
public static String getLocalIp(){
InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
return null;
}
return addr.getHostAddress();
}
}
| [
"yangyang@huan.tv"
] | yangyang@huan.tv |
505c5935c6e8ec2975486520e010ec8cf1061032 | b37929282e1ce200ffeed494090f8794ef42b878 | /05 DBSimulator/src/main/java/hr/fer/zemris/java/hw05/db/ComparisonOperators.java | 5bd55c93dae1855a0b1888d2790f2339401919a0 | [] | no_license | hmatic/fer-java-course | b332c4645c30e787918149361ba5a77e75893efd | 6ce8c7992197b8d6e90787969a0a91a2873de8b7 | refs/heads/master | 2020-03-15T22:16:37.101287 | 2018-08-28T12:29:48 | 2018-08-28T12:29:48 | 132,370,110 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,605 | java | package hr.fer.zemris.java.hw05.db;
/**
* ComparisonOperators holds all comparison operators and their implementations.
* Most of the implementations are done using lambda expressions.
*
* @author Hrvoje Matić
* @version 1.0
*/
public class ComparisonOperators {
/**
* Operator which lexicographically compares two Strings
* and returns true if second String is LESS than first String, false otherwise.
*/
public static final IComparisonOperator LESS = (value1,value2)-> value1.compareTo(value2)<0;
/**
* Operator which lexicographically compares two Strings
* and returns true if second String is LESS or EQUAL to first String, false otherwise.
*/
public static final IComparisonOperator LESS_OR_EQUALS = (value1,value2)-> value1.compareTo(value2)<=0;
/**
* Operator which lexicographically compares two Strings
* and returns true if second String is GREATER than first String, false otherwise.
*/
public static final IComparisonOperator GREATER = (value1,value2)-> value1.compareTo(value2)>0;
/**
* Operator which lexicographically compares two Strings
* and returns true if second String is GREATER or EQUAL to first String, false otherwise.
*/
public static final IComparisonOperator GREATER_OR_EQUALS = (value1,value2)-> value1.compareTo(value2)>=0;
/**
* Operator which lexicographically compares two Strings
* and returns true if second String is EQUAL to first String, false otherwise.
*/
public static final IComparisonOperator EQUALS = (value1, value2) -> value1.equals(value2);
/**
* Operator which lexicographically compares two Strings
* and returns true if second String is NOT EQUAL to first String, false otherwise.
*/
public static final IComparisonOperator NOT_EQUALS = (value1, value2) -> !(value1.equals(value2));
/**
* Operator which lexicographically compares two Strings
* and returns true if second String matches first String, false otherwise.
* Inside this operator, you can use wildcard(*) which represents regex for multiple character on
* start, middle or end of string. Only one wildcard can be used, otherwise exception will be thrown.
* @throws IllegalArgumentException when more than one wildcard is used
*/
public static final IComparisonOperator LIKE = new IComparisonOperator() {
@Override
public boolean satisfied(String value1, String value2) {
if(value2.chars().filter(sign -> sign == '*').count()>1) {
throw new IllegalArgumentException("There can be only zero or one wildcard(*) in string.");
}
return value1.matches(value2.replace("*", ".*"));
}
};
}
| [
"hrvoje.matic@fer.hr"
] | hrvoje.matic@fer.hr |
af77943d258a88b7f4524b7235e0841def23d42c | 43f3fdf7f0bd5331db16412cc8eb12dfcde24d93 | /RabbitMQSender/src/main/java/com/rabbitmq/controllers/ProductController.java | c6ee769ac12f58a10e723b52aef18c9a1c6dc292 | [] | no_license | vayu143/RabbitGit | aa5f50ab6aaff86b0451cef30383f37c83ec9ee9 | 26c82d7b92b3a9c80f1f79b59e5a817b725bfc14 | refs/heads/master | 2021-01-22T21:22:00.143487 | 2017-03-18T18:08:22 | 2017-03-18T18:08:22 | 85,415,460 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 835 | java | package com.rabbitmq.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.rabbitmq.beans.Product;
import com.rabbitmq.service.MessageConvertingNSendingService;
@RestController
public class ProductController {
@Autowired
MessageConvertingNSendingService mcs;
@RequestMapping(value = "/sendproduct", method = RequestMethod.POST)
public void processMessage(@RequestBody Product product) throws JsonProcessingException {
mcs.convertMessageNSend(product);
}
}
| [
"vayu.iitian.nanda0@gmail.com"
] | vayu.iitian.nanda0@gmail.com |
7b2f54dfe6ac23762c7b7a5af54ecd13904fc88c | bd1c99e368e10c7e663ef92ff9111b5e81d4f97f | /ProjetoPOO/src/Tabuleiro.java | 2f8876dc98629d8d33a0076da7564805670a177d | [] | no_license | cleysonnn/POOTESTEPROJETO | 3dc7cf875beb62b1282f71de965095f5f1994c0a | 705a9fdd74cfac6816b156dc39ebfb524589d63e | refs/heads/master | 2020-06-30T15:02:26.127584 | 2019-08-06T14:30:40 | 2019-08-06T14:30:40 | 200,865,813 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,874 | java | import java.util.ArrayList;
import java.util.List;
public class Tabuleiro {
private ArrayList<Posicionavel> casas;
public Tabuleiro() {
this.casas = new ArrayList<Posicionavel>();
}
public void adicionaPosicionavel() {
this.casas.add(new Terreno("Leblon", 2, 100, 6, 30, 90, 270, 400, 500, 50, 50, 0, 6 ));
this.casas.add(new Terreno("av. Presidente Vargas",3,60,2,10,30,90,100,250,30,50,0,2 ));
this.casas.add(new Terreno("av. Nossa Senhora de Copacabana",4,60,2,10,30,90,100,250,30,50,0,2 ));
this.casas.add(new Terreno("Av. Brigadeiro Faria lima",6,240,20,100,300,750,925,1100,120,150,0,20 ));
this.casas.add(new Terreno("Av. Rebouças",8,220,18,90,250,700,875,1050,110,150,0,18 ));
this.casas.add(new Terreno("AV. 9 de Julho",9,220,18,90,250,700,875,1050,110,150,0,18 ));
this.casas.add(new Terreno("Av. Europa",11,200,16,80,220,600,800,1000,100,100,0,16 ));
this.casas.add(new Terreno("Rua Augusta",13,180,14,70,200,550,750,950,90,100,0,14 ));
this.casas.add(new Terreno("Av. Pacaembu",14,180,14,70,200,550,750,950,90,100,0,14 ));
this.casas.add(new Terreno("Interlagos",17,350,35,175,500,1100,1300,1500,175,200,0,35 ));
this.casas.add(new Terreno("Morumbi",19,400,50,200,600,1400,1700,2000,200,200,0,50 ));
this.casas.add(new Terreno("Flamengo",21,120,8,40,100,300,450,600,60,50,0,8 ));
this.casas.add(new Terreno("Botafogo",23,100,6,30,90,270,400,500,50,50,0,6 ));
this.casas.add(new Terreno("Av. Brasil",26,160,12,60,180,500,700,900,80,100,0,12 ));
this.casas.add(new Terreno("Av. Paulista",28,140,10,50,150,450,625,750,70,100,0,10 ));
this.casas.add(new Terreno("Jardim Europa",29,140,12,60,180,500,700,900,80,100,0,12 ));
this.casas.add(new Terreno("Copacabana",31,260,22,110,330,800,975,1150,130,150,0,22 ));
this.casas.add(new Terreno("Av. Vieira Souto",33,320,28,150,450,1000,1200,1400,160,200,0,28 ));
this.casas.add(new Terreno("Av. Atlâtica",34,300,26,130,390,900,1100,1275,150,200,0,26 ));
this.casas.add(new Terreno("Ipanema",36,300,26,130,390,900,1100,1275,150,200,0,26 ));
this.casas.add(new Terreno("Jardim Paulista",38,280,24,120,360,850,1025,1200,140,150,0,24 ));
this.casas.add(new Terreno("Brooklin",39,260,22,110,330,800,975,1150,130,150,0,22 ));
this.casas.add(new Companhia("Companhia Ferroviaria",5,200,100,50 ));
this.casas.add(new Companhia("Companhia de Aviaçao",7,200,100,50 ));
this.casas.add(new Companhia("Companhia de taxi",15,150,75,40 ));
this.casas.add(new Companhia("Companhia de Navegaçao",25,150,75,40 ));
this.casas.add(new Companhia("Companhia de Aviaçao",32,200,100,50 ));
this.casas.add(new Companhia("Companhia de Taxi Aereo",35,200,100,50 ));
}
public ArrayList<Posicionavel> getCasas() {
return casas;
}
public void setCasas(ArrayList<Posicionavel> casas) {
this.casas = casas;
}
} | [
"noreply@github.com"
] | noreply@github.com |
d7cea7505934ac249cf0706ee333689297879a0a | 01d9381ac8b635cde435fd1d18a94ace877d5903 | /app/src/main/java/com/app/restaurant0/model/InfoRes.java | 027d9b6d5e398f1155b3672cbb3f8c4f4f29ce8f | [] | no_license | danafrommoon/mob-app-tapishke | 0ba721e6bafefe35ae4556fc7d000225bd22752d | 02db0a5482d285d0575f2f5e911801c70d8527f4 | refs/heads/master | 2023-05-28T19:49:44.288457 | 2021-06-15T04:57:49 | 2021-06-15T04:57:49 | 377,039,216 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,650 | java | package com.app.restaurant0.model;
public class InfoRes {
String imgRes, nameRes, phoneRes, streetRes, priceRes, btnRes, descriptionRes;
public InfoRes() {}
public InfoRes(String imgRes, String nameRes, String phoneRes, String streetRes, String priceRes, String btnRes, String descriptionRes) {
this.imgRes = imgRes;
this.nameRes = nameRes;
this.phoneRes = phoneRes;
this.streetRes = streetRes;
this.priceRes = priceRes;
this.btnRes = btnRes;
this.descriptionRes = descriptionRes;
}
public String getImgRes() {
return imgRes;
}
public void setImgRes(String imgRes) {
this.imgRes = imgRes;
}
public String getNameRes() {
return nameRes;
}
public void setNameRes(String nameRes) {
this.nameRes = nameRes;
}
public String getPhoneRes() {
return phoneRes;
}
public void setPhoneRes(String phoneRes) {
this.phoneRes = phoneRes;
}
public String getStreetRes() {
return streetRes;
}
public void setStreetRes(String streetRes) {
this.streetRes = streetRes;
}
public String getPriceRes() {
return priceRes;
}
public void setPriceRes(String priceRes) {
this.priceRes = priceRes;
}
public String getBtnRes() {
return btnRes;
}
public void setBtnRes(String btnRes) {
this.btnRes = btnRes;
}
public String getDescriptionRes() {
return descriptionRes;
}
public void setDescriptionRes(String descriptionRes) {
this.descriptionRes = descriptionRes;
}
} | [
"a.orunbassarova@astanait.edu.kz"
] | a.orunbassarova@astanait.edu.kz |
465c6337e12dd11fbc54e261f0663000f7ff88e8 | 9254e7279570ac8ef687c416a79bb472146e9b35 | /iot-20180120/src/main/java/com/aliyun/iot20180120/models/GenerateOTAUploadURLRequest.java | ff82145dcdfbcde07d930cb7da1f5e33ad7aaaad | [
"Apache-2.0"
] | permissive | lquterqtd/alibabacloud-java-sdk | 3eaa17276dd28004dae6f87e763e13eb90c30032 | 3e5dca8c36398469e10cdaaa34c314ae0bb640b4 | refs/heads/master | 2023-08-12T13:56:26.379027 | 2021-10-19T07:22:15 | 2021-10-19T07:22:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 983 | java | // This file is auto-generated, don't edit it. Thanks.
package com.aliyun.iot20180120.models;
import com.aliyun.tea.*;
public class GenerateOTAUploadURLRequest extends TeaModel {
@NameInMap("IotInstanceId")
public String iotInstanceId;
@NameInMap("FileSuffix")
public String fileSuffix;
public static GenerateOTAUploadURLRequest build(java.util.Map<String, ?> map) throws Exception {
GenerateOTAUploadURLRequest self = new GenerateOTAUploadURLRequest();
return TeaModel.build(map, self);
}
public GenerateOTAUploadURLRequest setIotInstanceId(String iotInstanceId) {
this.iotInstanceId = iotInstanceId;
return this;
}
public String getIotInstanceId() {
return this.iotInstanceId;
}
public GenerateOTAUploadURLRequest setFileSuffix(String fileSuffix) {
this.fileSuffix = fileSuffix;
return this;
}
public String getFileSuffix() {
return this.fileSuffix;
}
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
48b8d2bfa8b2ef7daa4e7e0b9bf95177eec49197 | c657182ec00018f01c62325b076a7b9b529945d9 | /src/main/java/ru/bjcreslin/repository/UserRepository.java | 8a5641491102f8d380b443dfe8fb1a49324ea457 | [] | no_license | BJCreslin/trader-helper-application | ad76e71869de8554cca70466e621a021a8147312 | aa653b0fc96a669724c296cf5188d8b9a5ea5f8d | refs/heads/master | 2023-01-11T08:28:07.782771 | 2020-11-17T10:34:32 | 2020-11-17T10:34:32 | 307,972,046 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,459 | java | package ru.bjcreslin.repository;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import ru.bjcreslin.domain.User;
/**
* Spring Data JPA repository for the {@link User} entity.
*/
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
String USERS_BY_LOGIN_CACHE = "usersByLogin";
String USERS_BY_EMAIL_CACHE = "usersByEmail";
Optional<User> findOneByActivationKey(String activationKey);
List<User> findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant dateTime);
Optional<User> findOneByResetKey(String resetKey);
Optional<User> findOneByEmailIgnoreCase(String email);
Optional<User> findOneByLogin(String login);
@EntityGraph(attributePaths = "authorities")
@Cacheable(cacheNames = USERS_BY_LOGIN_CACHE)
Optional<User> findOneWithAuthoritiesByLogin(String login);
@EntityGraph(attributePaths = "authorities")
@Cacheable(cacheNames = USERS_BY_EMAIL_CACHE)
Optional<User> findOneWithAuthoritiesByEmailIgnoreCase(String email);
Page<User> findAllByLoginNot(Pageable pageable, String login);
}
| [
"jhipster-bot@jhipster.tech"
] | jhipster-bot@jhipster.tech |
03bd792086c12c720bfa89e3225959b3884be44d | 63e36d35f51bea83017ec712179302a62608333e | /OnePlusCamera/android/support/v4/view/VelocityTrackerCompat.java | 267baec9f8f94772819bfa59e41d9f2426836b6a | [] | no_license | hiepgaf/oneplus_blobs_decompiled | 672aa002fa670bdcba8fdf34113bc4b8e85f8294 | e1ab1f2dd111f905ff1eee18b6a072606c01c518 | refs/heads/master | 2021-06-26T11:24:21.954070 | 2017-08-26T12:45:56 | 2017-08-26T12:45:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,067 | java | package android.support.v4.view;
import android.os.Build.VERSION;
import android.view.VelocityTracker;
public class VelocityTrackerCompat
{
static final VelocityTrackerVersionImpl IMPL = new HoneycombVelocityTrackerVersionImpl();
static
{
if (Build.VERSION.SDK_INT < 11)
{
IMPL = new BaseVelocityTrackerVersionImpl();
return;
}
}
public static float getXVelocity(VelocityTracker paramVelocityTracker, int paramInt)
{
return IMPL.getXVelocity(paramVelocityTracker, paramInt);
}
public static float getYVelocity(VelocityTracker paramVelocityTracker, int paramInt)
{
return IMPL.getYVelocity(paramVelocityTracker, paramInt);
}
static class BaseVelocityTrackerVersionImpl
implements VelocityTrackerCompat.VelocityTrackerVersionImpl
{
public float getXVelocity(VelocityTracker paramVelocityTracker, int paramInt)
{
return paramVelocityTracker.getXVelocity();
}
public float getYVelocity(VelocityTracker paramVelocityTracker, int paramInt)
{
return paramVelocityTracker.getYVelocity();
}
}
static class HoneycombVelocityTrackerVersionImpl
implements VelocityTrackerCompat.VelocityTrackerVersionImpl
{
public float getXVelocity(VelocityTracker paramVelocityTracker, int paramInt)
{
return VelocityTrackerCompatHoneycomb.getXVelocity(paramVelocityTracker, paramInt);
}
public float getYVelocity(VelocityTracker paramVelocityTracker, int paramInt)
{
return VelocityTrackerCompatHoneycomb.getYVelocity(paramVelocityTracker, paramInt);
}
}
static abstract interface VelocityTrackerVersionImpl
{
public abstract float getXVelocity(VelocityTracker paramVelocityTracker, int paramInt);
public abstract float getYVelocity(VelocityTracker paramVelocityTracker, int paramInt);
}
}
/* Location: /Users/joshua/Desktop/system_framework/classes-dex2jar.jar!/android/support/v4/view/VelocityTrackerCompat.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | [
"joshuous@gmail.com"
] | joshuous@gmail.com |
e6dd13a2958f677872174f6b84ba106126a26fd8 | 8493b0a1e5fb16e2eb5654e5964f0d506167c487 | /src/main/java/com/bednarz/rentalsrestapi/repository/MockLocationRepository.java | fef1e496785a8990e33e66aa63a3886656503def | [] | no_license | RafalBednarz/rentals-rest-api | a14ab882f605b13a1532dc1391a98439c66ef482 | 5b46f792459c42e8d20c4e82d1f5c468433e989b | refs/heads/master | 2020-03-31T17:19:47.126311 | 2019-02-24T21:18:21 | 2019-02-24T21:18:21 | 152,418,864 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,786 | java | package com.bednarz.rentalsrestapi.repository;
import com.bednarz.rentalsrestapi.Location;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.springframework.stereotype.Repository;
import org.wololo.geojson.Feature;
import org.wololo.geojson.GeoJSON;
import org.wololo.geojson.Point;
import org.wololo.jts2geojson.GeoJSONWriter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Repository
public class MockLocationRepository {
private List<Feature> features;
MockLocationRepository() {
createInitialData();
}
public GeoJSON getAllLocations() {
GeoJSONWriter writer = new GeoJSONWriter();
return writer.write(features);
}
public GeoJSON getLocationsByPrice(String price) {
GeoJSONWriter writer = new GeoJSONWriter();
List featuresByPrice = features.stream().filter(f -> Integer.parseInt(f.getProperties().get("PRICE").toString()) < Integer.parseInt(price)).collect(Collectors.toList());
return writer.write(featuresByPrice);
}
public Location createAdvertisement(Location location) {
Map<String, Object> properties1 = ImmutableMap.of(
"NAME", location.title(),
"CITY", location.city(),
"PRICE", location.price(),
"TYPE", location.type());
Feature feature = new Feature(new Point(new double[]{location.longitudey(), location.latitudex()}), properties1);
features = new ImmutableList.Builder<Feature>().addAll(features).add(feature).build();
return location;
}
private void createInitialData() {
Map<String, Object> properties1 = ImmutableMap.of(
"NAME", "Apartment z dwoma pokojami",
"CITY", "KRAKOW",
"PRICE", 100,
"TYPE", Location.AdvertisementType.FLAT);
Feature feature1 = new Feature(new Point(new double[]{19.938503, 52.655769}), properties1);
Map<String, Object> properties2 = ImmutableMap.of(
"NAME", "Mieszkanie 100m2 na pokoje wynajem",
"CITY", "WARSZAWA",
"PRICE", 200,
"TYPE", Location.AdvertisementType.ROOM);
Feature feature2 = new Feature(new Point(new double[]{19.538503, 51.655769}), properties2);
Map<String, Object> properties3 = ImmutableMap.of(
"NAME", "Atrakcyjny pokój jednoosobowy ul.Miechowity",
"CITY", "GDANSK",
"PRICE", 300,
"TYPE", Location.AdvertisementType.FLAT);
Feature feature3 = new Feature(new Point(new double[]{19.738503, 52.455769}), properties3);
features = ImmutableList.of(feature1, feature2, feature3);
}
}
| [
"raf.bednarz@gmail.com"
] | raf.bednarz@gmail.com |
46b8b61a7bc9a02fadb8a61a8d568a1808f38bc0 | 8ea36703cbca015a3fd629d6ac6afbf424cadc9d | /library_multichoice_main/build/generated/source/r/test/debug/com/manuelpeinado/multichoiceadapter/R.java | de9252d1ee884ed3be04b5d10ebf1da87c1ed1dc | [] | no_license | ShaunLWM/NetLynx-GDSFileUpload | 83e0eac3f9fb2d343090443e5b6be3926c89c9b9 | 16dfdfb4b6a906eb0ab2df9b77f8d24f55b1ca25 | refs/heads/master | 2021-05-28T20:39:31.209109 | 2015-03-19T08:02:30 | 2015-03-19T08:02:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,136 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.manuelpeinado.multichoiceadapter;
public final class R {
public static final class attr {
public static final int checkableImageViewStyle = 0x7f010000;
public static final int itemClickInActionMode = 0x7f010002;
public static final int multiChoiceAdapterStyle = 0x7f010001;
}
public static final class color {
public static final int mca__holo_blue_light = 0x7f040000;
public static final int mca__holo_blue_light_transparent = 0x7f040001;
public static final int mca__list_item_bg_checked = 0x7f040002;
public static final int mca__list_item_bg_normal = 0x7f040003;
public static final int mca__list_item_bg_pressed = 0x7f040004;
}
public static final class dimen {
public static final int mca__listPreferredItemPaddingLeft = 0x7f060000;
}
public static final class drawable {
public static final int mca__gallery_selector = 0x7f020000;
public static final int mca__grid_item_fg_pressed = 0x7f020001;
public static final int mca__list_item_selector = 0x7f020002;
}
public static final class id {
public static final int openItem = 0x7f050001;
public static final int selectItem = 0x7f050000;
}
public static final class layout {
public static final int mca__simple_list_item_checkable_1 = 0x7f030000;
public static final int mca__simple_list_item_checkable_2 = 0x7f030001;
}
public static final class plurals {
public static final int selected_items = 0x7f070000;
}
public static final class style {
public static final int MultiChoiceAdapter_DefaultCheckableImageViewStyle = 0x7f080000;
public static final int MultiChoiceAdapter_DefaultSelectedItemStyle = 0x7f080001;
}
public static final class styleable {
public static final int[] CheckableImageView = { 0x01010109 };
public static final int CheckableImageView_android_foreground = 0;
public static final int[] MultiChoiceAdapter = { 0x7f010002 };
public static final int MultiChoiceAdapter_itemClickInActionMode = 0;
}
}
| [
"shaunblacksheep@gmail.com"
] | shaunblacksheep@gmail.com |
a731583284b1b2f58810dd4486fa0cf6bc175558 | 7bb3e77181bce2fd222ae3d1b87431b10f2b3461 | /clevercloud/sourcesOLD/org/clever/ClusterManager/Brain/BrainInterface.java | 5738a51b66be8a0a488174093477258b902d3adc | [] | no_license | apanarello/cleverNew | 457abbced532d5635b68e3b58ed4924e6e035cbd | e9cb034c2c821742d2a9bd8d5956b44c06fb341f | refs/heads/master | 2021-01-25T10:29:29.894358 | 2015-02-25T12:00:52 | 2015-02-25T12:00:52 | 22,683,614 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,377 | java | /*
* The MIT License
*
* Copyright 2011 Alessio Di Pietro
*.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.clever.ClusterManager.Brain;
import org.clever.Common.Communicator.Notification;
/**
*
* @author alessiodipietro
*/
public interface BrainInterface {
public void handleNotification(Notification notification);
}
| [
"apanarello@apanarello.(none)"
] | apanarello@apanarello.(none) |
045016742833fe17f741897302b8dfbf5142f27d | 343bde1daadac7a7113649bde007a7e08e23b8cc | /Springboot/src/main/java/com/sut/sa/g10/entity/Purchaseoder.java | 7ceb659921abc80215ee76a0cb0dab1c34c23878 | [] | no_license | pdxcnk/SA | e64bcae2f691318eeaa9e751d1c080f8e5347012 | 238c18687328f94cba7d31fc37fcfc92df1822fc | refs/heads/master | 2020-04-22T11:25:19.902726 | 2019-02-14T09:15:27 | 2019-02-14T09:15:27 | 170,339,882 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,247 | java | package com.sut.sa.g10.entity;
import lombok.*;
import javax.persistence.Id;
import javax.persistence.*;
import javax.persistence.GeneratedValue;
import javax.persistence.SequenceGenerator;
import javax.persistence.GenerationType;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Column;
import java.util.List;
import java.util.Date;
import javax.validation.constraints.NotNull;
import javax.persistence.ManyToOne;
@Entity
@Data
@Table(name = "Purchaseoder")
public class Purchaseoder {
@Id
@SequenceGenerator(name="purchaseoder_seq",sequenceName="purchaseoder_seq")
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="purchaseoder_seq")
@Column(name="idPurchaseoder")
private @NonNull Long id;
private Date date;
private String numb;
public Purchaseoder(){
}
@ManyToOne(fetch = FetchType.LAZY, targetEntity = Medicine.class)
@JoinColumn(name = "IDMedicine")
private Medicine medicine;
@ManyToOne(fetch = FetchType.LAZY, targetEntity = Company.class)
@JoinColumn(name = "IDCompany")
private Company company;
@ManyToOne(fetch = FetchType.LAZY, targetEntity = ClinicStaff.class)
@JoinColumn(name = "IDStaff")
private ClinicStaff clinicStaff;
public void setDate(Date date) {
this.date = date;
}
public Date getDate(){
return date;
}
public void setNumb(String numb){
this.numb = numb;
}
public String getNumb(){
return numb;
}
public void setMedicine(Medicine medicine){
this.medicine=medicine;
}
public Medicine getMedicine() {
return medicine;
}
public void setCompany(Company company){
this.company=company;
}
public Company getCompany() {
return company;
}
public void setClinicStaff(ClinicStaff clinicStaff){
this.clinicStaff=clinicStaff;
}
public ClinicStaff getClinicStaff() {
return clinicStaff;
}
public Purchaseoder (Medicine medicine,Company company,Date date,String numb,
ClinicStaff clinicStaff){
this.medicine = medicine;
this.company = company;
this.date = date;
this.numb = numb;
this.clinicStaff = clinicStaff;
}
}
| [
"JH_Joker89@hotmail.com"
] | JH_Joker89@hotmail.com |
5e55990c8b6631860a22e70b560c77f4ed76c867 | d6162d1b4eb83920b775011ebd614d9b27757cec | /leetcode/src/tech/punklu/leetcode/LC633.java | b5604de35351d3ad7c159277dc7f675e02ae1490 | [] | no_license | punk1u/DataStructureAndAlgorithm | 9a51959bc958f04d49fb144cd34ec9993b209b2b | de4d81af55c35d645adf192dfe3be60977850042 | refs/heads/main | 2023-06-17T23:00:32.942849 | 2021-07-16T04:48:54 | 2021-07-16T04:48:54 | 375,563,659 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,552 | java | package tech.punklu.leetcode;
/**
*
* 给定一个非负整数c,你要判断是否存在两个整数 a 和 b,使得a*a + b*b = c 。
*
*
* 示例 1:
*
* 输入:c = 5
* 输出:true
* 解释:1 * 1 + 2 * 2 = 5
*
* 示例 2:
* 输入:c = 3
* 输出:false
*
* 示例 3:
* 输入:c = 4
* 输出:true
*
* 示例 4:
* 输入:c = 2
* 输出:true
*
* 示例 5:
* 输入:c = 1
* 输出:true
*
* 提示:
* 0 <= c <= 231 - 1
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/sum-of-square-numbers
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class LC633 {
/**
* 执行用时:2 ms, 在所有 Java 提交中击败了96.61%的用户
* 内存消耗:35 MB, 在所有 Java 提交中击败了87.59%的用户
* @param c
* @return
*/
public static boolean judgeSquareSum(int c) {
boolean result = false;
int begin = 0;
int end = (int)Math.sqrt(c);
while (begin <= end){
int sum = (begin * begin) + (end * end);
if (sum > c){
end -= 1;
}else if (sum < c){
begin +=1;
}else if ( sum == c){
result = true;
break;
}
}
return result;
}
public static void main(String[] args) {
int c = 1000000;
boolean result = judgeSquareSum(c);
System.out.println(result);
}
}
| [
"punk1u@protonmail.com"
] | punk1u@protonmail.com |
b233989296501d6c556bc93aa72c358171636422 | 9caecfac0f5267fa7c9f0b9866a6a0ec0378dcf4 | /jwt-auth-service/src/main/java/com/app/registration/dto/TokenResponseDTO.java | ba7b5ef9bdeb740726d83e63cccd0e25f19e1480 | [
"MIT"
] | permissive | LathaSriram/MWCampaign | 27c94b8a0ec6b8c7d67f8a5b15d55fa9131fc5e9 | 4f158c6e950be83e934274fdb1fe7854a40f4c7c | refs/heads/master | 2023-02-01T08:26:27.039066 | 2020-12-13T22:26:28 | 2020-12-13T22:26:28 | 317,249,950 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 208 | java | package com.app.registration.dto;
public class TokenResponseDTO {
private String token;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
| [
"lathasriramulu2010@gmail.com"
] | lathasriramulu2010@gmail.com |
b814a05da56a0fd7015391c1728a95f530ba7ec7 | 04465e9a3604d40314ee99ee1d57d8996c9e8626 | /src/CopyBytes.java | fe8f12320ca9780d08dcc6d61eea2ff357222aa9 | [] | no_license | Koo8/ExceptionPractice | 0dfa328f444b5c0e67d4cdd3ef8fd15e8bbf6ca9 | 710bfa1d7ade1d8aeccb17131051048db867be8d | refs/heads/master | 2022-12-28T16:12:23.180466 | 2020-09-28T01:26:46 | 2020-09-28T01:26:46 | 295,836,606 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,161 | java | import java.io.*;
/**
* uses byte streams to copy xanadu.txt, one byte at a time
*/
public class CopyBytes {
public static void main(String[] args) {
// FileInputStream in = null;
// FileOutputStream out = null; // try catch finally block method
File file;
try(FileReader in = new FileReader("xanadu.txt"); // try with resources method
FileWriter out = new FileWriter("outagain2.txt")){
int c;
while((c = in.read())!= -1) {
out.write(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// finally {
// if(in != null) {
// try {
// in.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// if(out !=null) {
// try {
// out.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
}
}
| [
"kooeight@gmail.com"
] | kooeight@gmail.com |
5625d2c5f0053cd6ae319819b0d6fc239e6edc26 | 67ddca78bb10aae88780f6a128a587eb28c5d00e | /src/com/company/SaveBehavior.java | 6205e5a48dc1760d2bd279a20fb55f6e6c1b2a01 | [] | no_license | DIASNKTEAM/DP_Assignment1_Dias_Nurbergenov | 245f229d3959da13b1c5cf17e4587902d500381e | c751b05175b6ade96df9b05f2f1da3f4f109de6a | refs/heads/master | 2023-08-27T03:32:37.096848 | 2021-09-20T06:11:48 | 2021-09-20T06:11:48 | 408,329,766 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 171 | java | package com.company;
public class SaveBehavior implements FootballBehavior {
@Override
public void ball(){
System.out.println("I save balls!");
}
}
| [
"nurbergenovv.007@gmail.com"
] | nurbergenovv.007@gmail.com |
63d0ec22230f95767f45a5ed9dde1095d3914ea4 | e6c10e387b82879fbe9d4f12dc27e3669818452e | /src/lk/ijse/pizza/entity/Order.java | 4c328c1d73a4d3eccf18850f5fdbdefcc935e904 | [] | no_license | pavithraRanasinghe/First-project | 55653eadfffafae7310074d86c63abbc7f699f2c | 774da273ec01a0cb995b11c099a119e576160fe6 | refs/heads/master | 2020-06-27T17:09:36.212448 | 2020-03-03T04:26:56 | 2020-03-03T04:26:56 | 200,005,103 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,636 | 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 lk.ijse.pizza.entity;
import java.util.Date;
/**
*
* @author PAVITHRA
*/
public class Order {
private int orderID;
private int customerID;
private String orderDate;
private double totalAmount;
public Order() {
}
public Order(int orderID, int customerID, String orderDate, double totalAmount) {
this.orderID = orderID;
this.customerID = customerID;
this.orderDate = orderDate;
this.totalAmount = totalAmount;
}
public int getOrderID() {
return orderID;
}
public void setOrderID(int orderID) {
this.orderID = orderID;
}
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
public int getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
/**
* @return the totalAmount
*/
public double getTotalAmount() {
return totalAmount;
}
/**
* @param totalAmount the totalAmount to set
*/
public void setTotalAmount(double totalAmount) {
this.totalAmount = totalAmount;
}
@Override
public String toString() {
return "Order{" + "orderID=" + orderID + ", customerID=" + customerID + ", orderDate=" + orderDate + ", totalAmount=" + totalAmount + '}';
}
}
| [
"paviranasinghe20@gamil.com"
] | paviranasinghe20@gamil.com |
d6e1026f3d8b6eef1b5cc384345ee9fb28c51150 | 170fead82b6b96e4647d419f190a10a8a609ffe8 | /zxy-commons-mq/src/main/java/com/zxy/commons/mq/partition/package-info.java | ef3f8a20a8063234665a105940253a6c3130c111 | [
"Apache-2.0"
] | permissive | chenglinjava68/zxy-commons | b8732ed4d23d573eec89017e528a547d3a15ef80 | cda6024980d7ad334ed572927c55bf09802430c3 | refs/heads/master | 2021-01-19T19:58:49.649088 | 2017-03-15T02:04:33 | 2017-03-15T02:04:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 192 | java | /**
* 分区规划
*
* <p>
* <a href="package-info.java"><i>View Source</i></a>
*
* @author zhaoxunyong@qq.com
* @version 1.0
* @since 1.0
*/
package com.zxy.commons.mq.partition;
| [
"xunyong.zhao@mljr.com"
] | xunyong.zhao@mljr.com |
109855cd64e804a1393a33c6a43b413f6b1e02c3 | 5c8529526b3f69c029f2563a4361447cca7c5085 | /src/main/java/com/fjxokt/lolclient/lolrtmps/model/SummonerCatalog.java | 64f8ff5598954d6b435ddd4735aed608b3545c22 | [] | no_license | BigBlackBug/lolClient | 0c3eb13e5d56bff9f8f6d114dcf64ba4a5bc44ea | ff476f27e511453ebd27dc34388ce49fea05f8b7 | refs/heads/master | 2020-04-03T06:51:44.411608 | 2013-05-21T09:05:31 | 2013-05-21T09:05:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,412 | java | package com.fjxokt.lolclient.lolrtmps.model;
import java.util.ArrayList;
import java.util.List;
import com.gvaneyck.rtmp.TypedObject;
public class SummonerCatalog extends ClassType {
private List<TalentGroup> talentTree;
private List<RuneSlot> spellBookConfig;
@Override
protected String getTypeName() {
return "com.riotgames.platform.summoner.SummonerCatalog";
}
public SummonerCatalog(TypedObject to) {
super();
this.talentTree = new ArrayList<TalentGroup>();
Object[] objs = to.getArray("talentTree");
if (objs != null) {
for (Object o : objs) {
TypedObject tto = (TypedObject)o;
if (tto != null) {
talentTree.add(new TalentGroup(tto));
}
}
}
this.spellBookConfig = new ArrayList<RuneSlot>();
objs = to.getArray("spellBookConfig");
if (objs != null) {
for (Object o : objs) {
TypedObject tto = (TypedObject)o;
if (tto != null) {
spellBookConfig.add(new RuneSlot(tto));
}
}
}
}
public List<TalentGroup> getTalentTree() {
return talentTree;
}
public List<RuneSlot> getSpellBookConfig() {
return spellBookConfig;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("SummonerCatalog [talentTree=");
builder.append(talentTree);
builder.append(", spellBookConfig=");
builder.append(spellBookConfig);
builder.append("]");
return builder.toString();
}
}
| [
"fjxokt@gmail.com"
] | fjxokt@gmail.com |
b5792e936d3154d209cec39359980112dcdee3cc | b4c291a107a51158a8f81ccfc6692116c4971bdc | /Module21Hybridframework/src/test/java/Salesforce/Module21Hybridframework/product/SearchAndBuyItemTest.java | bf1e1e101aee7ca4c81f1daa78a6896b23f8122b | [] | no_license | pranabkdas85/DemoRepo | b094314a158fb98ad6bf35964a967b26f9102532 | 2205ae99e4d240a4caf80e6d1c6100a703b0c452 | refs/heads/master | 2021-01-19T18:58:50.276921 | 2017-10-30T12:18:39 | 2017-10-30T12:18:39 | 88,392,068 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,432 | java | package Salesforce.Module21Hybridframework.product;
import java.util.Hashtable;
import org.testng.SkipException;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.LogStatus;
import Salesforce.Module21Hybridframework.Keywords;
import Salesforce.Module21Hybridframework.base.BaseTest;
import Salesforce.Module21Hybridframework.util.Constants;
import Salesforce.Module21Hybridframework.util.DataUtil;
import Salesforce.Module21Hybridframework.util.Xls_Reader;
public class SearchAndBuyItemTest extends BaseTest{
@BeforeTest
public void init(){
xls = new Xls_Reader(Constants.ProductSuite_XLS);
testName = "SearchAndBuyItemTest";
}
@Test(dataProvider="getData")
public void filterMobileTest(Hashtable<String,String> data){
test = rep.startTest(testName);
test.log(LogStatus.INFO, data.toString());
if(DataUtil.isSkip(xls, testName) || data.get("Runmode").equals("N")){
test.log(LogStatus.SKIP, "Skipping the test as runmode is N");
throw new SkipException("Skipping the test as runmode is N");
}
test.log(LogStatus.INFO, "Starting "+testName);
app = new Keywords(test);
test.log(LogStatus.INFO, "Executing keywords");
app.executeKeywords(testName, xls,data);
// add the screenshot
//app.getGenericKeyWords().reportFailure("xxxx");
test.log(LogStatus.PASS, "PASS");
app.getGenericKeyWords().takeScreenShot();
}
}
| [
"Pranab Das"
] | Pranab Das |
3936d080a13d94ab72f14601b79437ec0b11e472 | 0f3e5ce19d9a8ea51db8957d2325af371b3a08a7 | /pet-clinic-data/src/main/java/com/sbk/sbkmvcpet/model/Visit.java | 3859277c8acca18b329c017ef4336c74c988ab46 | [] | no_license | iamthatos/sbk-mvc-pet | 21e82433246a118865ca85ea5d298bbdf50840ea | a14bece76f5927bc149fc3f4182f0c44396e5d0f | refs/heads/master | 2020-03-30T20:05:10.221174 | 2018-10-21T14:57:42 | 2018-10-21T14:57:42 | 151,572,281 | 0 | 0 | null | 2018-10-16T22:35:48 | 2018-10-04T13:01:17 | Java | UTF-8 | Java | false | false | 510 | java | package com.sbk.sbkmvcpet.model;
import lombok.*;
import javax.persistence.*;
import java.time.LocalDate;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "visits")
public class Visit extends BaseEntity {
@Column(name = "date")
private LocalDate date;
@Column(name = "description")
private String description;
@ManyToOne
@JoinColumn(name = "pet_id")
private Pet pet;
public LocalDate getDate() {
return date;
}
}
| [
"thato.seboko@gmail.com"
] | thato.seboko@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.