blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
34bf10119e3b57dd8c0b4ad6e889821c4490a230
ed5159d056e98d6715357d0d14a9b3f20b764f89
/test/irvine/oeis/a271/A271036Test.java
5f73d798d4040aea3d41d1bfaf1494eb21b1a066
[]
no_license
flywind2/joeis
c5753169cf562939b04dd246f8a2958e97f74558
e5efd6971a0062ac99f4fae21a7c78c9f9e74fea
refs/heads/master
2020-09-13T18:34:35.080552
2019-11-19T05:40:55
2019-11-19T05:40:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
195
java
package irvine.oeis.a271; import irvine.oeis.AbstractSequenceTest; /** * Tests the corresponding class. * @author Sean A. Irvine */ public class A271036Test extends AbstractSequenceTest { }
aed701c72064011b31aa09475628ffe8146940a1
2bc2eadc9b0f70d6d1286ef474902466988a880f
/tags/mule-2.0.0-M2/tests/integration/src/test/java/org/mule/test/usecases/ReceiverComponent.java
90a29a769e360cd0b29329a26aeb6f057b32871e
[]
no_license
OrgSmells/codehaus-mule-git
085434a4b7781a5def2b9b4e37396081eaeba394
f8584627c7acb13efdf3276396015439ea6a0721
refs/heads/master
2022-12-24T07:33:30.190368
2020-02-27T19:10:29
2020-02-27T19:10:29
243,593,543
0
0
null
2022-12-15T23:30:00
2020-02-27T18:56:48
null
UTF-8
Java
false
false
682
java
/* * $Id$ * -------------------------------------------------------------------------------------- * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com * * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package org.mule.test.usecases; import org.mule.umo.UMOEventContext; import org.mule.umo.lifecycle.Callable; public class ReceiverComponent implements Callable { public Object onCall(UMOEventContext eventContext) throws Exception { return "Received: " + eventContext.getMessageAsString(); } }
[ "tcarlson@bf997673-6b11-0410-b953-e057580c5b09" ]
tcarlson@bf997673-6b11-0410-b953-e057580c5b09
b8caa1c768014d3d2d328c69c6ae433e8f476d82
b58d2fbfb65e960c72f12de96e6ccaf8c560bea2
/CodeForces/src/pr1/Main.java
0f48c547eaaa2650f83d17123a81122a0d65aaad
[]
no_license
f13mash/competitive-programming
dff53a025dbf719c805fdcd2315655d970cf6174
83227ebf38345b8fe3c55ad35e2c6f8a3401977c
refs/heads/master
2021-01-01T18:49:19.733824
2014-01-14T13:06:12
2014-01-14T13:06:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,863
java
package pr1; import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) { MyScanner sc = new MyScanner(); int n = sc.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) arr[i] = sc.nextInt(); Arrays.sort(arr); int[] cnt = new int[8]; boolean ans = true; for(int i : arr) { cnt[i]++; if(i ==5 || i == 7){ ans = false; break; } } StringBuilder out = new StringBuilder(); int fours = cnt[4]; if(cnt[4] > cnt[2] || cnt[4] > cnt[1] || !ans) { ans = false; } else { for(int i=0;i<cnt[4];i++) { out.append(1+" "+2+" "+4+"\n"); } cnt[2] -= cnt[4]; cnt[1] -= cnt[4]; cnt[4] = 0; } int sixes = cnt[6]; if(cnt[6] != (cnt[2]+cnt[3]) || cnt[6] != cnt[1] || !ans) { ans = false; } else { for(int i=0;i<cnt[6];i++) { if(cnt[2] > 0){ out.append(1+" "+2+" "+6+"\n"); cnt[2]--; } else{ out.append(1+" "+3+" "+6+"\n"); cnt[3]--; } } cnt[6]=cnt[2]=cnt[3]=cnt[1]=0; } String pri = out.toString().trim(); if(!ans) { pri = "-1"; } System.out.println(pri); } //-----------MyScanner class for faster input---------------------------------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str=""; try { str = br.readLine().toString(); } catch (IOException e) { e.printStackTrace(); } return str; } } //---------------------------------------------------------------------------- }
46fe1c83625fe4fed188dbd77de77d1070159cb3
13d611b767c05261f6400a42b2a9ff461e2ec907
/src/main/java/com/raoulvdberge/refinedstorage/item/ItemBlockEnergyItem.java
7eeee367df1062a15380eb3823ee6c7488b3b3d1
[ "MIT" ]
permissive
uwx/refinedstorage
656830f69f8ccc61737b5fa52cf495588939b6a2
c38a4206d7388e28b51436ce90f1037ca54e8c8a
refs/heads/mc1.12
2023-04-01T01:34:44.041814
2018-08-31T08:27:59
2018-08-31T08:27:59
132,574,657
0
0
MIT
2019-05-16T05:54:39
2018-05-08T07:58:07
Java
UTF-8
Java
false
false
3,176
java
package com.raoulvdberge.refinedstorage.item; import com.raoulvdberge.refinedstorage.block.Direction; import net.minecraft.block.Block; import net.minecraft.client.resources.I18n; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.NonNullList; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.energy.CapabilityEnergy; import net.minecraftforge.energy.IEnergyStorage; import javax.annotation.Nullable; import java.util.List; public abstract class ItemBlockEnergyItem extends ItemBlockBase { public static final int TYPE_NORMAL = 0; public static final int TYPE_CREATIVE = 1; public ItemBlockEnergyItem(Block block, Direction direction) { super(block, direction, true); setMaxDamage(ItemEnergyItem.CAPACITY); setMaxStackSize(1); } @Override public ICapabilityProvider initCapabilities(ItemStack stack, NBTTagCompound tag) { return new CapabilityProviderEnergy(stack); } @Override public boolean isDamageable() { return true; } @Override public boolean isRepairable() { return false; } @Override public double getDurabilityForDisplay(ItemStack stack) { IEnergyStorage energy = stack.getCapability(CapabilityEnergy.ENERGY, null); return 1D - ((double) energy.getEnergyStored() / (double) energy.getMaxEnergyStored()); } @Override public int getRGBDurabilityForDisplay(ItemStack stack) { IEnergyStorage energy = stack.getCapability(CapabilityEnergy.ENERGY, null); return MathHelper.hsvToRGB(Math.max(0.0F, (float) energy.getEnergyStored() / (float) energy.getMaxEnergyStored()) / 3.0F, 1.0F, 1.0F); } @Override public boolean isDamaged(ItemStack stack) { return stack.getItemDamage() != TYPE_CREATIVE; } @Override public void setDamage(ItemStack stack, int damage) { // NO OP } @Override public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> items) { if (!isInCreativeTab(tab)) { return; } items.add(new ItemStack(this, 1, TYPE_NORMAL)); ItemStack fullyCharged = new ItemStack(this, 1, TYPE_NORMAL); IEnergyStorage energy = fullyCharged.getCapability(CapabilityEnergy.ENERGY, null); energy.receiveEnergy(energy.getMaxEnergyStored(), false); items.add(fullyCharged); items.add(new ItemStack(this, 1, TYPE_CREATIVE)); } @Override public void addInformation(ItemStack stack, @Nullable World world, List<String> tooltip, ITooltipFlag flag) { super.addInformation(stack, world, tooltip, flag); if (stack.getItemDamage() != TYPE_CREATIVE) { IEnergyStorage energy = stack.getCapability(CapabilityEnergy.ENERGY, null); tooltip.add(I18n.format("misc.refinedstorage:energy_stored", energy.getEnergyStored(), energy.getMaxEnergyStored())); } } }
14a3d8cae933fc983edb94396544009742b5174c
e482a16413e10e72f87d904858973a79044be946
/app/src/main/java/com/equipazo/domain/User.java
7ac7fb241e6ba98ae8da90750d1f50439582cf33
[]
no_license
gurroz/equipazo-backend
53f198603c339b5d4449b8ac6ff7efc5589bd238
a10f7b4683fc846772e50fcaa8878197c57cd13e
refs/heads/master
2023-02-10T02:14:20.007278
2020-11-08T12:53:17
2020-11-08T12:53:17
290,498,512
0
0
null
null
null
null
UTF-8
Java
false
false
240
java
package com.equipazo.domain; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @Setter @Getter @AllArgsConstructor public class User { private Long id; private String name; private String mobile; }
fd0472bfecdc0fe1f9479a8927b9653ef3d8cb7e
60cb2435588f965ff42eb0d51c547793f88c5994
/CampChallenge_java/018.DB操作/challenge18_4.java
b3dc5646d1a6223489b030197156cbe6e37677d6
[]
no_license
YoshimatsuEmi/GEEKJOB_Challenge
8b992e1173bdd7986b222df66cfa0d05bff7168f
16f25ab1a4514f77c88cde3a3fd324a2ec9d9d34
refs/heads/master
2020-03-17T09:38:05.686109
2018-07-19T09:57:23
2018-07-19T09:57:23
133,482,398
0
0
null
null
null
null
UTF-8
Java
false
false
4,356
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. */ import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.sql.*; /** * * @author 44yos */ @WebServlet(urlPatterns = {"/challenge18_4"}) public class challenge18_4 extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { Connection db_con = null; try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); db_con = DriverManager.getConnection("jdbc:mysql://localhost:3306/challenge_db?serverTimezone=JST","root",""); PreparedStatement db_st = null; String sql = "SELECT * FROM profiles WHERE profilesID=1"; db_st = db_con.prepareStatement(sql); ResultSet db_data = null; db_data = db_st.executeQuery(); while (db_data.next()){ String str1 = db_data.getString("profilesID"); String str2 = db_data.getString("name"); String str3 = db_data.getString("tel"); String str4 = db_data.getString("age"); String str5 = db_data.getString("birthday"); out.println(str1+", "+str2+", "+str3+", "+str4+", "+str5+"<br>"); } db_data.close(); db_st.close(); db_con.close(); }catch (ClassNotFoundException ex) { out.println("エラー:クラスが見つかりませんでした<br>"+ex); }catch (InstantiationException ex) { out.println("エラー:インスタンス化<br>"+ex); }catch (IllegalAccessException ex) { out.println("エラー:アクセス<br>"+ex); } catch (SQLException ex) { out.println("エラー:SQL<br>"+ex); } finally{ try{ if(db_con != null){ db_con.close(); } }catch(Exception e){ out.println("Exception2! :"+e.toString()); } } } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
93039c6764d1011cfdfeb8c0833f8f658b39ea2f
d29ef5d0e87c4af706380a6b090f1024d5cf2366
/src/model/slavegang.java
325c7b30b54574ba399680d3c0b8fedb088e7cb8
[]
no_license
carr91/snowwhite
b6ee45fb54bc4043d729403651a0f20173ee2622
b426468aa9050a53a1e91a3c05ac05683a40ab47
refs/heads/master
2021-01-01T20:01:31.737084
2014-06-02T03:18:10
2014-06-02T03:19:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,119
java
package model; import java.util.ArrayList; import java.util.Iterator; import java.util.List; //task 5 - This is the composite class, containing a number of slaves. public class slavegang implements slavecomponent { private String name; public slavegang(String name){ this.name = name; } List<slavecomponent> slaves = new ArrayList<slavecomponent>(); public void add(slavecomponent SC) { slaves.add(SC); } public void remove(slavecomponent SC) { slaves.remove(SC); } public slavecomponent getChild(int i) { return slaves.get(i); } //use an iterator because each slave worships in its own way - public void worship() { Iterator<slavecomponent> slavesIterator = slaves.iterator(); while (slavesIterator.hasNext()){ slavecomponent sc = slavesIterator.next(); sc.worship(); } } //use an iterator because each slave eats in its own way - public void eat() { Iterator<slavecomponent> slavesIterator = slaves.iterator(); while (slavesIterator.hasNext()){ slavecomponent sc = slavesIterator.next(); sc.eat(); } } }
27122e0b752f9991beaa941e94bb612eb8b281b4
97f8be92810bafdbf68b77c8a938411462d5be4b
/3rdParty/rocksdb/6.8/java/src/test/java/org/rocksdb/RocksIteratorTest.java
a8f773b57ecbfd77e5a7c0cd36c1d0e127b8d01f
[ "Apache-2.0", "BSD-3-Clause", "ICU", "LGPL-2.1-or-later", "BSD-4-Clause", "GPL-1.0-or-later", "Python-2.0", "OpenSSL", "Bison-exception-2.2", "JSON", "ISC", "GPL-2.0-only", "MIT", "BSL-1.0", "LicenseRef-scancode-public-domain", "CC0-1.0", "BSD-2-Clause", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "LicenseRef-scancode-unknown-license-reference", "Zlib" ]
permissive
solisoft/arangodb
022fefd77ca704bfa4ca240e6392e3afebdb474e
efd5a33bb1ad1ae3b63bfe1f9ce09b16116f62a2
refs/heads/main
2021-12-24T16:50:38.171240
2021-11-30T11:52:58
2021-11-30T11:52:58
436,619,840
2
0
Apache-2.0
2021-12-09T13:05:46
2021-12-09T13:05:46
null
UTF-8
Java
false
false
7,769
java
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). package org.rocksdb; import static org.assertj.core.api.Assertions.assertThat; import java.nio.ByteBuffer; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class RocksIteratorTest { @ClassRule public static final RocksNativeLibraryResource ROCKS_NATIVE_LIBRARY_RESOURCE = new RocksNativeLibraryResource(); @Rule public TemporaryFolder dbFolder = new TemporaryFolder(); @Test public void rocksIterator() throws RocksDBException { try (final Options options = new Options() .setCreateIfMissing(true) .setCreateMissingColumnFamilies(true); final RocksDB db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath())) { db.put("key1".getBytes(), "value1".getBytes()); db.put("key2".getBytes(), "value2".getBytes()); try (final RocksIterator iterator = db.newIterator()) { iterator.seekToFirst(); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key1".getBytes()); assertThat(iterator.value()).isEqualTo("value1".getBytes()); ByteBuffer key = ByteBuffer.allocateDirect(2); ByteBuffer value = ByteBuffer.allocateDirect(2); assertThat(iterator.key(key)).isEqualTo(4); assertThat(iterator.value(value)).isEqualTo(6); assertThat(key.position()).isEqualTo(0); assertThat(key.limit()).isEqualTo(2); assertThat(value.position()).isEqualTo(0); assertThat(value.limit()).isEqualTo(2); byte[] tmp = new byte[2]; key.get(tmp); assertThat(tmp).isEqualTo("ke".getBytes()); value.get(tmp); assertThat(tmp).isEqualTo("va".getBytes()); key = ByteBuffer.allocateDirect(12); value = ByteBuffer.allocateDirect(12); assertThat(iterator.key(key)).isEqualTo(4); assertThat(iterator.value(value)).isEqualTo(6); assertThat(key.position()).isEqualTo(0); assertThat(key.limit()).isEqualTo(4); assertThat(value.position()).isEqualTo(0); assertThat(value.limit()).isEqualTo(6); tmp = new byte[4]; key.get(tmp); assertThat(tmp).isEqualTo("key1".getBytes()); tmp = new byte[6]; value.get(tmp); assertThat(tmp).isEqualTo("value1".getBytes()); iterator.next(); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key2".getBytes()); assertThat(iterator.value()).isEqualTo("value2".getBytes()); iterator.next(); assertThat(iterator.isValid()).isFalse(); iterator.seekToLast(); iterator.prev(); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key1".getBytes()); assertThat(iterator.value()).isEqualTo("value1".getBytes()); iterator.seekToFirst(); iterator.seekToLast(); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key2".getBytes()); assertThat(iterator.value()).isEqualTo("value2".getBytes()); iterator.status(); key.clear(); key.put("key1".getBytes()); key.flip(); iterator.seek(key); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.value()).isEqualTo("value1".getBytes()); assertThat(key.position()).isEqualTo(4); assertThat(key.limit()).isEqualTo(4); key.clear(); key.put("key2".getBytes()); key.flip(); iterator.seekForPrev(key); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.value()).isEqualTo("value2".getBytes()); assertThat(key.position()).isEqualTo(4); assertThat(key.limit()).isEqualTo(4); } try (final RocksIterator iterator = db.newIterator()) { iterator.seek("key0".getBytes()); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key1".getBytes()); iterator.seek("key1".getBytes()); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key1".getBytes()); iterator.seek("key1.5".getBytes()); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key2".getBytes()); iterator.seek("key2".getBytes()); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key2".getBytes()); iterator.seek("key3".getBytes()); assertThat(iterator.isValid()).isFalse(); } try (final RocksIterator iterator = db.newIterator()) { iterator.seekForPrev("key0".getBytes()); assertThat(iterator.isValid()).isFalse(); iterator.seekForPrev("key1".getBytes()); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key1".getBytes()); iterator.seekForPrev("key1.5".getBytes()); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key1".getBytes()); iterator.seekForPrev("key2".getBytes()); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key2".getBytes()); iterator.seekForPrev("key3".getBytes()); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key2".getBytes()); } } } @Test public void rocksIteratorReleaseAfterCfClose() throws RocksDBException { try (final Options options = new Options() .setCreateIfMissing(true) .setCreateMissingColumnFamilies(true); final RocksDB db = RocksDB.open(options, this.dbFolder.getRoot().getAbsolutePath())) { db.put("key".getBytes(), "value".getBytes()); // Test case: release iterator after default CF close try (final RocksIterator iterator = db.newIterator()) { // In fact, calling close() on default CF has no effect db.getDefaultColumnFamily().close(); iterator.seekToFirst(); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key".getBytes()); assertThat(iterator.value()).isEqualTo("value".getBytes()); } // Test case: release iterator after custom CF close ColumnFamilyDescriptor cfd1 = new ColumnFamilyDescriptor("cf1".getBytes()); ColumnFamilyHandle cfHandle1 = db.createColumnFamily(cfd1); db.put(cfHandle1, "key1".getBytes(), "value1".getBytes()); try (final RocksIterator iterator = db.newIterator(cfHandle1)) { cfHandle1.close(); iterator.seekToFirst(); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key1".getBytes()); assertThat(iterator.value()).isEqualTo("value1".getBytes()); } // Test case: release iterator after custom CF drop & close ColumnFamilyDescriptor cfd2 = new ColumnFamilyDescriptor("cf2".getBytes()); ColumnFamilyHandle cfHandle2 = db.createColumnFamily(cfd2); db.put(cfHandle2, "key2".getBytes(), "value2".getBytes()); try (final RocksIterator iterator = db.newIterator(cfHandle2)) { db.dropColumnFamily(cfHandle2); cfHandle2.close(); iterator.seekToFirst(); assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key2".getBytes()); assertThat(iterator.value()).isEqualTo("value2".getBytes()); } } } }
2e641650a0573d85dc5a92e56748712209bc6d4e
44d6c9eefe15d7bd9bf32adfa2fafe42cd36b44c
/src/main/java/FinalCheck1/repository/Order.java
9daaaf334ed44dfe2d6af7a6265a16b94f782e66
[]
no_license
Danussh18/SystemDesignHandsOn
dc4b306860e49e076484015cf45a90e6b9645ec2
e299bd36ba9ca7ee76ff2628d8df55ec9139a64d
refs/heads/master
2023-06-01T07:58:15.111135
2021-06-15T10:45:24
2021-06-16T08:13:11
375,563,810
1
0
null
null
null
null
UTF-8
Java
false
false
165
java
package FinalCheck1.repository; public abstract class Order { private Channel channel; private ProductType productType; public abstract void processOrder(); }
3961baa86db7e7752962bc6912bd852dd536f08f
583347e7218530b1f0c0fe6bae9c70b1400356f1
/SpringBoot_Example_03_Git/src/test/java/com/example/demo/SpringBootExample03GitApplicationTests.java
d3eb2c3be3b70d8f8b73f2b4edab6630297a05d9
[]
no_license
dohuyen/Springboot_example
278b012878dc1aa85aed9e00cb2fadabc61aa5f1
df49b118a460d4243e675dca630738a84ae2fb06
refs/heads/master
2020-04-27T06:24:59.823964
2019-03-06T09:48:00
2019-03-06T09:48:00
174,107,124
0
0
null
null
null
null
UTF-8
Java
false
false
349
java
package com.example.demo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringBootExample03GitApplicationTests { @Test public void contextLoads() { } }
d9072f1875f0fc15394cb9c4a55d0fbbafd64140
8fe0b3a5515e7ecc9f0a8c2401e4738ed35ee92f
/test/test/StringInMemory.java
489f63ba89a49246036a2e4a24c43f88a64de357
[]
no_license
WangYaRuGitHub/WangYaRUGitHub
93fc5eb93ee653e6a3b95996d8d04a45ae9bc8bd
1c2f94b229f2b2caaf4ff4311fc7657a91734671
refs/heads/main
2023-06-02T11:39:43.523539
2021-06-07T05:51:15
2021-06-07T05:51:15
310,239,774
0
0
null
null
null
null
UTF-8
Java
false
false
4,575
java
package org.example.test; import org.junit.Assert; import org.junit.Test; public class StringInMemory { // true:都是常量池中的字面量 @Test public void test1(){// 测试通过 String s1 = "hello"; String s2 = "hello"; Assert.assertTrue(s1 == s2); } // true:s3 = "he" + "llo" // JVM在编译期间会进行优化:s3为字面量拼接的字符串"hello",存在常量池 @Test public void test2(){// 测试通过 String s1 = "hello"; String s2 = "hel" + "lo"; Assert.assertTrue(s1 == s2); } // s2创建了以下对象 // 1."hello":存在字符串常量池,如果常量池已有"hello"就不创建 // 2.new String("hello"):存在堆中 // s1为常量池的"hello"对象,s2为堆中的对象new String("hello") @Test public void test3(){// 测试不能通过 String s1 = "hello"; String s2 = new String("hello"); Assert.assertTrue(s1 == s2); } // 调用intern方法时,如果池已经包含与equals(Object)方法确定的 // 相当于此String对象的字符串,则返回来自池的字符串。 否则,此 // String对象将添加到池中,并返回对此String对象的引用。 // 由此可见,对于任何两个字符串s和t,s.intern() == t.intern() // 是true当且仅当s.equals(t)是true。 @Test public void test4(){// 测试通过 String s1 = "hello"; String s2 = new String("hello"); Assert.assertTrue(s1 == s2.intern()); } // s4是用s2和s3两个常量池中的对象相加新生成的对象,存在堆中 @Test public void test5(){// 测试不能通过 String s1 = "hello"; String s2 = "hel"; String s3 = "lo"; String s4 = s2 + s3; Assert.assertTrue(s1 == s4); } /** * 常量池:计算机、软件 * 堆:new String("计算机软件") * "计算机软件"会在常量池中创建字符串对象并返回引用 */ @Test public void test6(){//false String s = new StringBuilder("计算机").append("软件").toString(); Assert.assertTrue(s == "计算机软件"); } /** * 常量池:计算机、软件 * 堆:new String("计算机软件") * 调用s.intern()---> 常量池生成字符串引用,指向堆中的s,并返回该引用 * 之后的"计算机软件"字符串,都是从常量池中获取,但是指向堆中的s对象 */ @Test public void test7(){//true String s = new StringBuilder("计算机").append("软件").toString(); // s.intern()在字符串常量池生成一个引用,指向s,"计算机软件"这个字符串是s Assert.assertTrue(s.intern() == "计算机软件"); Assert.assertTrue(s.intern() == s); Assert.assertTrue(s == "计算机软件"); } @Test public void test7_1() {//false String s = new StringBuilder("计算机").append("软件").toString(); // 先执行"计算机软件",会字符串常量池生成一个字符串对象,之后intern返回是字符串对象的引用 Assert.assertTrue("计算机软件" == s.intern());//true Assert.assertTrue(s.intern() == s);//false Assert.assertTrue(s == "计算机软件"); } /** * 常量池:计算机软件 * 堆:new String("计算机软件")--->指向常量池的字符串 * s.intern()--->返回常量池字符串对象的引用 */ @Test public void test8(){ String s = new StringBuilder("计算机软件").toString(); Assert.assertTrue(s.intern() == "计算机软件");//true Assert.assertTrue(s.intern() == s);//false } /** * jvm在初始化时,会默认加载一些资源,这些资源中包含一些字符串, * 如"java",会加载到常量池。 * s.intern()返回常量池中的字符串对象 * s为堆中的new String("java") */ @Test public void test111(){ String s = new StringBuilder("ja").append("va").toString(); Assert.assertTrue(s.intern() == s); } @Test public void test111_2(){ String s = new StringBuilder("计算机").append("软件").toString(); // s.intern()在字符串常量池生成一个引用,指向s,"计算机软件"这个字符串是s Assert.assertTrue(s.intern() == s); } }
ce2226d80798143a9b6f15844c76c71f6c659931
8b17272413668917779558f3c3cd1448b3353c5e
/HelpDesk/src/main/java/com/gercev/config/WebSecurityConfig.java
35da4bda16e220441c5e17e91665b503a849f3d6
[]
no_license
VladislavGercev/HD
7f0426ab8d5301ba66b902a2ef5555a5e6bda354
21e7ecd0bd8b8978991d526b3a23c18dc448c5fe
refs/heads/master
2023-08-15T03:53:48.366028
2021-10-07T14:17:55
2021-10-07T14:17:55
407,473,544
0
0
null
null
null
null
UTF-8
Java
false
false
3,195
java
package com.gercev.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.Arrays; @Configuration @EnableWebSecurity @ComponentScan(basePackages = {"com.gercev"}) public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer { @Autowired private UserDetailsService userDetailsService; @Override public void configure(HttpSecurity http) throws Exception { http .csrf().disable() .cors() .and() .authorizeRequests().anyRequest() .permitAll() .antMatchers(HttpMethod.POST, "/tickets").hasAnyAuthority("EMPLOYEE", "MANAGER") .antMatchers(HttpMethod.PUT, "/tickets/{Id}").hasAnyAuthority("EMPLOYEE", "MANAGER") .antMatchers(HttpMethod.DELETE, "attachments/{id}").hasAnyAuthority("EMPLOYEE", "MANAGER") .antMatchers(HttpMethod.POST, "/tickets/{id}/attachments").hasAnyAuthority("EMPLOYEE", "MANAGER") .and() .httpBasic(); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(this.userDetailsService) .passwordEncoder(passwordEncoder()); } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration().applyPermitDefaultValues(); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "DELETE","PUT")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } // @Bean // public CorsConfigurationSource corsConfigurationSource() { // UrlBasedCorsConfigurationSource source = new // UrlBasedCorsConfigurationSource(); // source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues()); // return source; // } }
fd537fbd0b6834604ad8b35c63315aff5d70c3c8
4a56d0c8f4a7a7c16cfd11ba0462cc76236e16a4
/app/src/main/java/com/binary/giphy/models/searchdetail/FixedWidthSmallStill.java
e1d1c6f232a937f6f1de0b0a25ce248861cc0e22
[]
no_license
duongnguyenuet/Giphy
6400609e3abe93fcada12c74f78d7ba7bb1f681b
2abf9b5f38779b7a30411a21d1d1669df6c75b5c
refs/heads/master
2021-05-05T13:13:41.067395
2017-10-20T02:01:20
2017-10-20T02:01:20
104,978,327
0
0
null
null
null
null
UTF-8
Java
false
false
988
java
package com.binary.giphy.models.searchdetail; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Created by duong on 9/19/2017. */ public class FixedWidthSmallStill { @SerializedName("url") @Expose private String url; @SerializedName("width") @Expose private String width; @SerializedName("height") @Expose private String height; public FixedWidthSmallStill(String url, String width, String height) { this.url = url; this.width = width; this.height = height; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getWidth() { return width; } public void setWidth(String width) { this.width = width; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } }
219078ae985e50fe99d2db09377d6ba828378629
f3d64239373fbdb8d0b62d54c3fe5121f97c9c06
/heima-leadnews-model/src/main/java/com/heima/model/user/pojos/ApUserEquipment.java
51ee2a330e2a70ce4656567cb5e68e425464dd51
[]
no_license
bin392328206/sixfinger-leadnews
b164cc58d0cc8f1706f5d97b8fdf4bd0e25652c9
e9bd62bd62205fc53ad1d937d56bbf6a0587363f
refs/heads/master
2022-10-08T19:33:41.593136
2020-04-08T05:01:17
2020-04-08T05:01:17
253,957,042
2
0
null
2022-10-05T18:21:34
2020-04-08T01:44:45
Java
UTF-8
Java
false
false
262
java
package com.heima.model.user.pojos; import lombok.Data; import java.util.Date; @Data public class ApUserEquipment { private Integer id; private Integer userId; private Integer equipmentId; private Date lastTime; private Date createdTime; }
ba47ce521a654f6cd13f76f9f5db663b114d094d
8572c91b73fb4b791e27d712af70497fd319266e
/retrofit/retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/CallExecuteObservable.java
8d1d4761fcb59a325e203e508d3dfa3ee70551c2
[ "Apache-2.0" ]
permissive
yuchuangu85/AndroidCommonLibrary
7908a0dce11e4e32cd5386b62354da2432e727a0
86b30a7b049b1f76e532197e58b185322b70a810
refs/heads/master
2022-10-15T22:49:52.834171
2021-05-17T15:51:16
2021-05-17T15:51:16
192,298,435
16
6
null
2022-10-04T23:55:02
2019-06-17T07:41:12
Java
UTF-8
Java
false
false
2,790
java
/* * Copyright (C) 2016 Jake Wharton * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package retrofit2.adapter.rxjava2; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.CompositeException; import io.reactivex.exceptions.Exceptions; import io.reactivex.plugins.RxJavaPlugins; import retrofit2.Call; import retrofit2.Response; final class CallExecuteObservable<T> extends Observable<Response<T>> { private final Call<T> originalCall; CallExecuteObservable(Call<T> originalCall) { this.originalCall = originalCall; } @Override protected void subscribeActual(Observer<? super Response<T>> observer) { // Since Call is a one-shot type, clone it for each new observer. Call<T> call = originalCall.clone(); CallDisposable disposable = new CallDisposable(call); observer.onSubscribe(disposable); if (disposable.isDisposed()) { return; } boolean terminated = false; try { Response<T> response = call.execute(); if (!disposable.isDisposed()) { observer.onNext(response); } if (!disposable.isDisposed()) { terminated = true; observer.onComplete(); } } catch (Throwable t) { Exceptions.throwIfFatal(t); if (terminated) { RxJavaPlugins.onError(t); } else if (!disposable.isDisposed()) { try { observer.onError(t); } catch (Throwable inner) { Exceptions.throwIfFatal(inner); RxJavaPlugins.onError(new CompositeException(t, inner)); } } } } private static final class CallDisposable implements Disposable { private final Call<?> call; private volatile boolean disposed; CallDisposable(Call<?> call) { this.call = call; } @Override public void dispose() { disposed = true; call.cancel(); } @Override public boolean isDisposed() { return disposed; } } }
268ec720f54b20ff6a01ac9b76f4ac75114aea58
2f3ea10de6c6f80726829e917c088f8b27ba48de
/DPat_Command/src/GarageDoor.java
639550a047e3d4828c8da30cff91a83fdbbc40b6
[]
no_license
mbhushan/algoz
c6b0cbd3b9da33bd278b397cece6860e78d1dac3
d4c9f3514c7f8ad653dd37c49b8fe9f714add61c
refs/heads/master
2023-05-12T09:47:43.792983
2023-05-04T04:02:01
2023-05-04T04:02:01
15,223,554
7
8
null
null
null
null
UTF-8
Java
false
false
190
java
public class GarageDoor { public void up() { System.out.println("garage door is open :)"); } public void down() { System.out.println("garage door is closed :)"); } }
6b5678ad5a835d06b612e663463fb5ab3ceea27c
13b89199b2147bd1c7d3a062a606f0edd723c8d6
/AlgorithmStudy/src/baekjoon/시뮬레이션/헤일스톤수열.java
81fc93770d5534ee387e82f59fb0d9d99ba20a3a
[]
no_license
chlals862/Algorithm
7bcbcf09b5d4ecad5af3a99873dc960986d1709f
ab4a6d0160ad36404b64ad4b32ce38b67994609f
refs/heads/master
2022-11-28T13:05:58.232855
2022-11-23T09:56:27
2022-11-23T09:56:27
243,694,528
1
1
null
null
null
null
UTF-8
Java
false
false
1,144
java
package baekjoon.시뮬레이션; /* * step1. n이 짝수 -> 2로 나눔 * step2. n이 홀수 -> 3을 곱함 +1 * * n이 1이면 종료 * output -> 가장 큰 값 출력 * */ import java.util.Scanner; public class 헤일스톤수열 { static int max = 0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int inputNum = sc.nextInt(); for (int i = 0; i < inputNum; i++) { int a = sc.nextInt(); int max = 0; max = a; //a가 1이 아닐때 계속 반복 while(a != 1) { //가장 큰 값 구하기 if(max <= a) { //System.out.println("max"+max); //System.out.println("a"+a); max =a; } if(a % 2 == 0 ) { a = a/2; //나누기가 '/'지 왜 '%'야................. } else if(a % 2 != 0 && a != 1) { a = a*3+1; } } System.out.println(max); } } } /*while ( == 1) { if (num[i] % 2 == 0) { max = num[i % 2]; System.out.println("짝수"); } else if (num[i] % 3 == 0) { max = num[i * 3] + 1; System.out.println("홀수"); } }*/ //System.out.println(Math.max(num[i], max));
390691608fc488d0cdf07c63ed0240d8e427a3de
3fa34c3c16b9cbeded214d3d5dad3c5463b49c9c
/src/main/java/com/meals/sys/service/impl/SysRoleServiceImpl.java
337ee0fdcf4ad9df5bacab9d5e168258539d448a
[ "Apache-2.0" ]
permissive
mebugs/meals
e998b584ec12025cc64ded3045e0c8fc4a125a88
73b45cad5248ae06d30dc946a73c8a1b468552e1
refs/heads/master
2023-03-05T13:58:17.194070
2021-02-18T09:28:29
2021-02-18T09:28:29
323,201,296
0
0
null
null
null
null
UTF-8
Java
false
false
3,206
java
package com.meals.sys.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.meals.data.cons.Constant; import com.meals.sys.entity.SysRole; import com.meals.sys.mapper.SysRoleMapper; import com.meals.sys.service.ISysAuthService; import com.meals.sys.service.ISysRoleAuthService; import com.meals.sys.service.ISysRoleService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.meals.task.thread.ThreadAuthRole; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * <p> * 服务实现类 * </p> * * @author 米虫先生/mebugs.com * @since 2020-10-19 */ @Service public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService { @Autowired private ISysRoleAuthService sysRoleAuthService; @Autowired private ISysAuthService sysAuthService; @Autowired private ThreadAuthRole threadAuthRole; /** * 获取角色分页 * @return */ @Override public IPage<SysRole> rolePage(Page page, String name) { LambdaQueryWrapper<SysRole> query = Wrappers.<SysRole>lambdaQuery(); if(StringUtils.isNotBlank(name)) { query.like(SysRole::getName,name); } return this.page(page,query); } /** * 获取角色的完整信息 * @param id * @return */ @Override public SysRole getRoleInfo(Long id) { SysRole role = this.getById(id); if(role!=null) { //查询权限勾选集 List<Long> roleAuthIds = sysRoleAuthService.getRoleAuthIds(role.getId()); role.setAuthIds(roleAuthIds); //查询权限树 role.setAuthTree(sysAuthService.getAuthTree(Constant.ROLE,role.getId(),roleAuthIds)); return role; } return null; } /** * 保存角色数据 新增修改通用方法 * @return */ @Override public boolean saveOne(SysRole sysRole) { boolean changUserCache = false; if(sysRole.getId() != null) { //表示需要同步刷新相关用户的缓存信息 changUserCache = true; } this.saveOrUpdate(sysRole); //无论新增还是修改先保存主表 再提交关联表 sysRoleAuthService.updateRoleAuth(sysRole.getId(),sysRole.getAuthIds()); //启动异步线程去刷新缓存 threadAuthRole.syncRoleAuth(sysRole.getId(),changUserCache,false); return true; } /** * 删除角色 * @return */ @Override public boolean delRole(Long id) { this.removeById(id); //启动异步线程去刷新缓存 threadAuthRole.syncRoleAuth(id,true,true); return true; } }
bae92a1ab2dfa200fb86185d296befd895ce1212
1cfd9d759b818c282d25dc3086c511a0a07d7955
/src/main/java/com/mossle/core/mail/MailService.java
231dae820c79a47ce5f20a9864984b062fdde5c4
[ "Apache-2.0" ]
permissive
eseawind/lemon
13c3b94101aad0dc70255b38bbd7b068aaabcf45
b434e32cb49ed128589e15e7af1af387d31c7799
refs/heads/master
2021-01-21T02:37:44.624589
2013-11-26T01:53:25
2013-11-26T01:53:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,156
java
package com.mossle.core.mail; import java.net.UnknownHostException; import java.util.Arrays; import javax.mail.internet.MimeMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; /** * 简单的邮件发送服务. * * TODO: 支持附件 * * @author Lingo */ public class MailService { /** logger. */ private static Logger logger = LoggerFactory.getLogger(MailService.class); public static final int MODE_NORMAL = 0; public static final int MODE_TEST = 1; /** java mail sender. */ private JavaMailSender javaMailSender; private HostGenerator hostGenerator = new HostGeneratorImpl(); // ~ ====================================================================== /** default from. */ private String defaultFrom; /** default to. */ private String[] defaultToArray; /** default cc. */ private String[] defaultCcArray; /** default bcc. */ private String[] defaultBccArray; /** default subject. */ private String defaultSubject; /** default content. */ private String defaultContent; // ~ ====================================================================== /** use html. */ private boolean useHtml = false; /** encoding. */ private String encoding = "UTF-8"; // ~ ====================================================================== /** * 发送模式. * * 如果为0,表示正常发送 如果为1,表示把邮件都发给指定的测试邮箱 */ private int mode = MODE_NORMAL; /** * 测试模式下发送到的测试邮箱. * * [email protected];[email protected]也自动处理成了数组 */ private String testMail = "[email protected]"; // ~ ====================================================================== /** * send message. */ public void send() { send(defaultFrom, defaultToArray, defaultSubject, defaultContent); } /** * send message with to. */ public void send(String to) { send(defaultFrom, convertArray(to), defaultSubject, defaultContent); } /** * send message with to, subject, content. */ public void send(String to, String subject, String content) { send(defaultFrom, convertArray(to), subject, content); } /** * send message with from, to, subject, content. */ public void send(String from, String to, String subject, String content) { send(from, convertArray(to), subject, content); } /** * send message with from, to, subject, content. */ public void send(String from, String[] to, String subject, String content) { send(from, to, defaultCcArray, defaultBccArray, subject, content); } /** * send message with from, to, cc, bcc, subject, content. */ public void send(String from, String[] to, String[] cc, String[] bcc, String subject, String content) { if (mode == MODE_NORMAL) { this.sendRealMail(from, to, cc, bcc, subject, content); } else if (mode == MODE_TEST) { this.sendTestMail(from, to, cc, bcc, subject, content); } else { logger.warn("unknown mode : {}", mode); } } /** * 发送测试用的邮件. */ protected void sendTestMail(String from, String[] to, String[] cc, String[] bcc, String subject, String content) { String address = ""; try { address = hostGenerator.generateLocalAddress(); } catch (UnknownHostException ex) { logger.error("", ex); } String decoratedContent = "address : " + address + "\nfrom : " + from + "\nto : " + Arrays.asList(to) + "\n"; if (cc != null) { decoratedContent = "cc : " + Arrays.asList(cc) + "\n"; } if (bcc != null) { decoratedContent = "bcc : " + Arrays.asList(bcc) + "\n"; } decoratedContent += ("subject : " + subject + "\ncontent : " + content); String decoratedSubject = "[test]" + subject; String decoratedFrom = address; logger.info("send mail from {} to {}", decoratedFrom, testMail); logger.info("subject : {}, content : {}", decoratedSubject, decoratedContent); this.sendRealMail(decoratedFrom, convertArray(testMail), null, null, decoratedSubject, decoratedContent); } /** * 实际发送邮件. */ protected void sendRealMail(String from, String[] to, String[] cc, String[] bcc, String subject, String content) { try { MimeMessage msg = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(msg, true, encoding); helper.setFrom(from); helper.setSubject(subject); helper.setTo(to); helper.setText(content, useHtml); if (cc != null) { helper.setCc(cc); } if (bcc != null) { helper.setBcc(bcc); } javaMailSender.send(msg); logger.debug("send mail from {} to {}", from, to); } catch (Exception e) { logger.error("send mail error", e); } } // ~ ====================================================================== public String[] convertArray(String str) { if (str == null) { return null; } if (str.indexOf(';') != -1) { return str.split(";"); } else { return new String[] { str }; } } // ~ ====================================================================== /** * set mail sender. */ public void setJavaMailSender(JavaMailSender javaMailSender) { this.javaMailSender = javaMailSender; } public void setHostGenerator(HostGenerator hostGenerator) { this.hostGenerator = hostGenerator; } /** * set default from. */ public void setDefaultFrom(String defaultFrom) { this.defaultFrom = defaultFrom; } /** * set default to. */ public void setDefaultTo(String defaultTo) { this.defaultToArray = convertArray(defaultTo); } /** * set default to. */ public void setDefaultTo(String[] defaultTo) { if (defaultTo == null) { this.defaultToArray = null; } else { this.defaultToArray = new String[defaultTo.length]; System.arraycopy(defaultTo, 0, this.defaultToArray, 0, defaultTo.length); } } /** * set default cc. */ public void setDefaultCc(String defaultCc) { this.defaultCcArray = convertArray(defaultCc); } /** * set default cc. */ public void setDefaultCc(String[] defaultCc) { if (defaultCc == null) { this.defaultCcArray = null; } else { this.defaultCcArray = new String[defaultCc.length]; System.arraycopy(defaultCc, 0, this.defaultCcArray, 0, defaultCc.length); } } /** * set default bcc. */ public void setDefaultBcc(String defaultBcc) { this.defaultBccArray = convertArray(defaultBcc); } /** * set default bcc. */ public void setDefaultBcc(String[] defaultBcc) { if (defaultBcc == null) { this.defaultBccArray = null; } else { this.defaultBccArray = new String[defaultBcc.length]; System.arraycopy(defaultBcc, 0, this.defaultBccArray, 0, defaultBcc.length); } } /** * set default subject. */ public void setDefaultSubject(String defaultSubject) { this.defaultSubject = defaultSubject; } /** * set default content. */ public void setDefaultContent(String defaultContent) { this.defaultContent = defaultContent; } // ~ ====================================================================== /** @return use html. */ public boolean isUseHtml() { return useHtml; } /** * @param set * useHtml boolean. */ public void setUseHtml(boolean useHtml) { this.useHtml = useHtml; } /** @return encoding. */ public String getEncoding() { return encoding; } /** * @param encoding * String. */ public void setEncoding(String encoding) { this.encoding = encoding; } // ~ ====================================================================== /** return mode. */ public int getMode() { return mode; } /** set mode. */ public void setMode(int mode) { this.mode = mode; } public String getTestMail() { return testMail; } /** set test mail. */ public void setTestMail(String testMail) { this.testMail = testMail; } }
173e7947877ecdd98f48b2571621a78d449b6819
3afea60a934862ed72ad6813d560a84fa35844d1
/StudioWorkSpace/SM-MusicList/app/src/main/java/com/smartmux/musiclist/fragments/FragmentFolder.java
55e848e780dc4e74e8cf1b455cf7b5e1359a9260
[]
no_license
Phenix-Collection/Android-1
033b86b962c6d50939336a4fd827d73922eeb78c
18f185b5cdb6a7edff766169468587aa2dbfd9b5
refs/heads/master
2021-12-15T01:06:22.296429
2017-07-07T08:55:39
2017-07-07T08:55:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,501
java
package com.smartmux.musiclist.fragments; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.smartmux.musiclist.R; import com.smartmux.musiclist.adapter.AllSongsListAdapter; import com.smartmux.musiclist.models.SongDetail; import java.io.File; import java.util.ArrayList; public class FragmentFolder extends Fragment { ListView folderList; private ArrayList<String> mfolderArray = new ArrayList<String>(); ArrayAdapter<String> adapter; AllSongsListAdapter mAllSongsListAdapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_allsongs, null); if(mfolderArray.size()>0){ mfolderArray.clear(); } File dir = Environment.getExternalStorageDirectory(); if (dir.exists() && dir.isDirectory()) { File[] files = dir.listFiles(); if (files != null) { getFolder(files); } } setFolderList(v); return v; } private void setFolderList(View v){ folderList = (ListView)v.findViewById(R.id.recycler_allSongs); adapter = new ArrayAdapter<String>( getActivity(), R.layout.font_row, mfolderArray); folderList.setAdapter(adapter); folderList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { getMusicFile(mfolderArray.get(position)); } }); } private void getMusicFile(String path){ // File root = new File(path); init(path); // if(root.isDirectory()) { // mfolderArray.clear(); // File[] item = root.listFiles(); // for (File rootItem : item) { // if (rootItem.getName().endsWith(".mp3")) { // mfolderArray.add("" + rootItem.getName()); // } // } // // adapter = new ArrayAdapter<String>( // getActivity(), R.layout.font_row, mfolderArray); // // folderList.setAdapter(adapter); // }else{ // Toast.makeText(getActivity(),"song",Toast.LENGTH_SHORT).show(); // mAllSongsListAdapter = new AllSongsListAdapter(getActivity(), songList); // folderList.setAdapter(mAllSongsListAdapter); // } } Cursor cursor = null; ArrayList<SongDetail> songsList = new ArrayList<>(); final String[] projectionSongs = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ALBUM_ID}; private void init(String filepath){ Uri uri = Uri.parse(filepath); Log.e("URI" , "" + uri); // Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0"; // sortOrder = MediaStore.Audio.Media.DATE_ADDED + " desc"; String sortOrder = MediaStore.Audio.Media.DEFAULT_SORT_ORDER; cursor = (getActivity()).getContentResolver().query(uri, projectionSongs, null, null, null); // cursor = ((Activity) context).getContentResolver().query(uri, projectionSongs, null, null, sortOrder); songsList = getSongsFromCursor(cursor); mAllSongsListAdapter = new AllSongsListAdapter(getActivity(), songsList,-1); folderList.setAdapter(mAllSongsListAdapter); } private void getFolder(File[] rootFile){ for (File rootItem : rootFile) { if (rootItem.exists()){ if(rootItem.isDirectory()) { File[] item = rootItem.listFiles(); getFolder(item); }else{ if (rootItem.getName().endsWith(".mp3")) { Log.e("SONG", "" + rootItem.getName()); Log.e("FOLDER", "" + rootItem.getParent()); mfolderArray.add(""+rootItem.getParent()); break; } } } } } private ArrayList<SongDetail> getSongsFromCursor(Cursor cursor) { ArrayList<SongDetail> generassongsList = new ArrayList<SongDetail>(); try { if (cursor != null && cursor.getCount() >= 1) { int _id = cursor.getColumnIndex(MediaStore.Audio.Media._ID); int artist = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST); int album_id = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID); int title = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE); int data = cursor.getColumnIndex(MediaStore.Audio.Media.DATA); int display_name = cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME); int duration = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION); while (cursor.moveToNext()) { int ID = cursor.getInt(_id); String ARTIST = cursor.getString(artist); String TITLE = cursor.getString(title); String DISPLAY_NAME = cursor.getString(display_name); String DURATION = cursor.getString(duration); String Path = cursor.getString(data); SongDetail mSongDetail = new SongDetail(ID, album_id, ARTIST, TITLE, Path, DISPLAY_NAME, DURATION); generassongsList.add(mSongDetail); } } closeCrs(); } catch (Exception e) { closeCrs(); e.printStackTrace(); } return generassongsList; } private void closeCrs() { if (cursor != null) { try { cursor.close(); } catch (Exception e) { Log.e("tmessages", e.toString()); } } } }
6bdbd7a7f1c459a7c952b5835047026b87d4f700
769196d5d281c6f17b12a64c4f3ef623993ca8e1
/app/src/main/java/com/nebeek/newsstand/data/models/Comment.java
2efb0fc705fab68ff5fa850e58a4145eb724199e
[]
no_license
mehdikazemi8/newsstand
c55daff523d36fd0925ae31bfce3e04606d8da95
ce3ede96f8ba67670a4d498358e93b6d132e5cdb
refs/heads/master
2020-07-01T23:22:18.547042
2018-05-26T13:44:18
2018-05-26T13:44:18
201,339,940
0
0
null
null
null
null
UTF-8
Java
false
false
1,606
java
package com.nebeek.newsstand.data.models; //@AutoValue //public abstract class Comment { public class Comment { private String username; private String comment; private String likeCount; private String dislikeCount; public Comment() { } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getLikeCount() { return likeCount; } public void setLikeCount(String likeCount) { this.likeCount = likeCount; } public String getDislikeCount() { return dislikeCount; } public void setDislikeCount(String dislikeCount) { this.dislikeCount = dislikeCount; } /* abstract String username(); abstract String comment(); abstract Integer likeCount(); abstract Integer dislikeCount(); static Builder builder() { return new AutoValue_Comment.Builder(); } @AutoValue.Builder abstract static class Builder { abstract Builder username(String username); abstract Builder comment(String comment); abstract Builder likeCount(Integer likeCount); abstract Builder dislikeCount(Integer dislikeCount); abstract Comment build(); } public static TypeAdapter<AutoValue_Comment> typeAdapter(Gson gson) { return new AutoValue_Comment.GsonTypeAdapter(gson); } */ }
f1a5f0072fa90a98d94a7384f4b4dca1e11c35b5
466a7a7ab1bf61e34cf1617aa399b6863f3e677f
/src/main/java/com/imooc/sell/service/Impl/ProductServiceImpl.java
bbd3629809deb2bf5f07f2d8a9d49dadf11a82d2
[]
no_license
TyronnLueXinyu/sell
94afb292e50a409d544869050c620cc8273bad66
fbebb744d72801007b0389f2446804658f5ef819
refs/heads/master
2020-04-09T16:13:01.776094
2018-12-11T08:37:38
2018-12-11T08:37:38
160,445,228
1
0
null
null
null
null
UTF-8
Java
false
false
1,155
java
package com.imooc.sell.service.Impl; import com.imooc.sell.dataobject.ProductInfo; import com.imooc.sell.enums.ProductStatusEnum; import com.imooc.sell.repository.ProductInfoRepository; import com.imooc.sell.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.List; /** * @Author: TyronnLue * @Date: 2018-12-10 16:20 */ @Service public class ProductServiceImpl implements ProductService{ @Autowired private ProductInfoRepository repository; @Override public ProductInfo findOne(String productId) { return repository.findOne(productId); } @Override public List<ProductInfo> findUpAll() { return repository.findByProductStatus(ProductStatusEnum.UP.getCode()); } @Override public Page<ProductInfo> findAll(Pageable pageable) { return repository.findAll(pageable); } @Override public ProductInfo save(ProductInfo productInfo) { return repository.save(productInfo); } }
ea50c4fe78bed91a976f8d642c23ffd37a3dd5b1
e3d97a4a07acf610921d2a43df4e9466babd9061
/src/main/java/de/umr/raft/raftlogreplicationdemo/replication/impl/clients/ClusterManagementClient.java
0fb43ed2c725644afa2cd76c096746146fd6ffd5
[]
no_license
christian-konrad/chronicledb-cloud
026ecf0a123e2d4232240b012f0074feb1a9c9f7
fd00915faa0383d56ca85040cca27f25f1fd839a
refs/heads/master
2023-04-06T22:44:08.791051
2022-09-19T10:29:45
2022-09-19T10:29:45
394,248,374
1
0
null
2022-08-14T20:02:43
2021-08-09T10:31:39
JavaScript
UTF-8
Java
false
false
3,228
java
package de.umr.raft.raftlogreplicationdemo.replication.impl.clients; import de.umr.raft.raftlogreplicationdemo.config.RaftConfig; import de.umr.raft.raftlogreplicationdemo.replication.api.statemachines.messages.clustermanagement.ClusterManagementOperationMessage; import de.umr.raft.raftlogreplicationdemo.replication.impl.ClusterManagementServer; import org.apache.ratis.protocol.RaftGroup; import org.apache.ratis.protocol.RaftGroupId; import org.apache.ratis.protocol.RaftPeer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.UUID; @Component public class ClusterManagementClient extends RaftReplicationClient<ClusterManagementOperationMessage> { public static ClusterManagementOperationMessage createRegisterPartitionOperationMessage(String stateMachineClassname, String partitionName, int replicationFactor) { return ClusterManagementOperationMessage.Factory.createRegisterPartitionOperationMessage(stateMachineClassname, partitionName, replicationFactor); } public static ClusterManagementOperationMessage createProvisionPartitionOperationMessage(String stateMachineClassname, String partitionName) { return ClusterManagementOperationMessage.Factory.createProvisionPartitionOperationMessage(stateMachineClassname, partitionName); } public static ClusterManagementOperationMessage createAcknowledgePartitionRegistrationOperationMessage(String stateMachineClassname, String partitionName) { return ClusterManagementOperationMessage.Factory.createAcknowledgePartitionRegistrationOperationMessage(stateMachineClassname, partitionName); } public static ClusterManagementOperationMessage createDetachPartitionOperationMessage(String stateMachineClassname, String partitionName) { return ClusterManagementOperationMessage.Factory.createDetachPartitionOperationMessage(stateMachineClassname, partitionName); } public static ClusterManagementOperationMessage createListPartitionsOperationMessage(String stateMachineClassname) { return ClusterManagementOperationMessage.Factory.createListPartitionsOperationMessage(stateMachineClassname); } public static ClusterManagementOperationMessage createHeartbeatOperationMessage(RaftPeer raftPeer) { return ClusterManagementOperationMessage.Factory.createHeartbeatOperationMessage(raftPeer); } public static ClusterManagementOperationMessage createGetHealthOperationMessage() { return ClusterManagementOperationMessage.Factory.createGetHealthOperationMessage(); } public static ClusterManagementOperationMessage getStateMachineForRaftGroupOperationMessage(RaftGroupId raftGroupId) { return ClusterManagementOperationMessage.Factory.getStateMachineForRaftGroupOperationMessage(raftGroupId); } @Override protected UUID getRaftGroupUUID() { return ClusterManagementServer.BASE_GROUP_UUID; } @Override protected RaftGroup getRaftGroup(UUID raftGroupUUID) { return raftConfig.getManagementRaftGroup(getRaftGroupUUID()); } @Autowired public ClusterManagementClient(RaftConfig raftConfig) { super(raftConfig); } }
36c12b590f37654a47ba23320ef34fe0061cb046
f2d8ab5e446043d10914ad8825bbc8780be17fb2
/app/src/main/java/com/newthink/user02/venteembarquee/MyBaseAdapterInvent.java
2b29fc17c0e81bb3799ca87e9a93d0a6a6b90891
[]
no_license
soufDev/TourManageFrontOffice
a52a6ec556c55f136b26aff38e375176d7ff9a33
74241a1eb2261aba1073aad8dd3e19abd84d730c
refs/heads/master
2021-01-09T23:36:11.392130
2016-11-08T18:09:09
2016-11-08T18:09:09
73,213,306
0
0
null
null
null
null
UTF-8
Java
false
false
2,661
java
package com.newthink.user02.venteembarquee; import android.content.Context; import android.database.DataSetObserver; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.TextView; import java.util.ArrayList; /** * Created by User02 on 28/03/2016. */ public class MyBaseAdapterInvent extends BaseAdapter { ArrayList<Produit> myList = new ArrayList<Produit>(); LayoutInflater inflater; Context context; private int[] colors = new int[] { 0x24373737, 0x0BF4F4F4 }; public MyBaseAdapterInvent(Context context, ArrayList<Produit> myList) { this.myList = myList; this.context = context; inflater = LayoutInflater.from(this.context); } @Override public void registerDataSetObserver(DataSetObserver observer) { } @Override public void unregisterDataSetObserver(DataSetObserver observer) { } public int getCount() { return myList.size(); } public Produit getItem(int position) { return myList.get(position); } public long getItemId(int position) { return 0; } @Override public boolean hasStableIds() { return false; } public View getView(int position, View convertView, ViewGroup parent) { MyViewHolder mViewHolder; if (convertView == null) { convertView = inflater.inflate(R.layout.style_list_pr_clo, parent, false); mViewHolder = new MyViewHolder(convertView); convertView.setTag(mViewHolder); } else { mViewHolder = (MyViewHolder) convertView.getTag(); } Produit currentListData = getItem(position); int colorPos = position % colors.length; convertView.setBackgroundColor(colors[colorPos]); mViewHolder.id.setText(String.valueOf(currentListData.getIdProduit())); mViewHolder.design.setText(currentListData.getDesignation()); mViewHolder.qtestime.setText(String.valueOf(currentListData.getStockFinalEstime())); mViewHolder.qtereel.setText(String.valueOf(currentListData.getStockFinalReel())); return convertView; } private class MyViewHolder { TextView id, design,qtestime,qtereel; public MyViewHolder(View item) { id = (TextView) item.findViewById(R.id.Idproduit); design = (TextView) item.findViewById(R.id.Designation); qtestime = (TextView) item.findViewById(R.id.qtestime); qtereel = (TextView) item.findViewById(R.id.qtereel); } } }
9d38ff5795aed80dc6f6a5ef109b54d80369178b
12f5c96134f242ff198e20e0eb65c286f9f9c583
/AcademyBC/src/test/java/stepDefinitions/WhenLogin.java
c12073a29196164db44dd3c6b805b1fe0de204d5
[]
no_license
DanielCoPer/proyecto1Jenkin
cb97fcff7d1d48b303b6943c1e81a84e73d78d79
94133e1ebf4a3f4268eff6594a4713a9fb3ef61d
refs/heads/master
2023-05-11T13:23:45.619185
2019-11-15T18:37:37
2019-11-15T18:37:37
221,963,156
0
0
null
2023-05-09T18:15:16
2019-11-15T16:31:46
HTML
UTF-8
Java
false
false
1,069
java
package stepDefinitions; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import io.cucumber.java.en.When; public class WhenLogin { WebDriver driver = GivenLogin.driver; @When("User enter valid email address {string}") public void user_enter_valid_email_address(String email) { driver.findElement(By.id("email")).sendKeys(email);; } @When("User enter valid password {string}") public void user_enter_valid_password(String password) { driver.findElement(By.id("passwd")).sendKeys(password);; } @When("User click sign in button") public void user_click_sign_in_button() { driver.findElement(By.id("SubmitLogin")).click(); } @When("User enter invalid password {string}") public void user_enter_invalid_password(String inpass) { driver.findElement(By.id("passwd")).sendKeys(inpass); } @When("User click Sign in button without enter information") public void user_click_Sign_in_button_without_enter_information() { driver.findElement(By.id("SubmitLogin")).click(); } }
00d8a01b2c048ce24fe69821ee1ba343e17b586b
0e3cb1b644b7fb2f41b840a53649bd6e17f7c9d1
/Prova2-Q1/src/MyMidlet.java
26e0014522bde1f25d03f468a18e4d861f3d24f2
[]
no_license
leonardotdleal/JavaME
8b50401e3b3a1f2f85c5e07945d54f0ef476f845
cac6d1fe36eb77f2ba47c78c87b7503b8be51f33
refs/heads/master
2021-01-20T11:55:08.770593
2018-10-26T20:13:49
2018-10-26T20:13:49
101,694,477
1
0
null
null
null
null
WINDOWS-1250
Java
false
false
1,559
java
import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; public class MyMidlet extends MIDlet implements CommandListener { private Name name = new Name(); private Wellcome wellcome = new Wellcome(); private Exit exit = new Exit(); public MyMidlet() { // TODO Auto-generated constructor stub } protected void destroyApp(boolean arg0) throws MIDletStateChangeException { // TODO Auto-generated method stub } protected void pauseApp() { // TODO Auto-generated method stub } protected void startApp() throws MIDletStateChangeException { // TODO Auto-generated method stub name.setCommandListener(this); wellcome.setCommandListener(this); exit.setCommandListener(this); Display.getDisplay(this).setCurrent(name); } public void commandAction(Command command, Displayable displayable) { if((displayable == name) && (command.getCommandType() == Command.OK)) { wellcome.append("Olá Sr(a). " + name.getNome() + ". Seja bem-vindo."); Display.getDisplay(this).setCurrent(wellcome); } else if((displayable == wellcome) && (command.getCommandType() == Command.OK)) { exit.append("Obrigado e volte sempre Sr(a). " + name.getNome()); Display.getDisplay(this).setCurrent(exit); } else if((displayable == exit) && (command.getCommandType() == Command.EXIT)) { this.notifyDestroyed(); } } }
96264eb57ea92786f3e727e6adef294ca6fb4c00
f0266bc7d56c656a796daad96de744afbb495a28
/Units/Unit5/Lab03/Driver03.java
c6be87467e966e505e222091b9dd67c6142f691d
[]
no_license
BatHoovy/FreshmanCS
46cc652ded4d82fafdd2c1cfc40692e2145c1e1e
48c9c4794bee6aaec1afac7828f5e0717fde6c21
refs/heads/master
2021-06-10T07:20:00.888475
2015-08-20T14:09:22
2015-08-20T14:09:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,508
java
import java.util.Random; public class Driver03 { static Random random = new Random(); public static void main(String[] args) { int[] array = {100, 101, 102, 103, 104, 105, 106, 107, 108, 109}; print(array); scramble(array); print(array); sort(array); print(array); } public static void print(int[] array) { System.out.println("Array"); System.out.println("---------------"); for(int x = 0; x < array.length; x++) { System.out.println(array[x]); } System.out.println(""); } public static void scramble(int[] array) { for(int i = 0; i < array.length; i++) { swap(array, i, random.nextInt(6)); } } public static void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } public static void sort(int[] array) { int maxPos; for(int k = 0; k < array.length; k++) { maxPos = findMax(array, array.length - k - 1); swap(array, maxPos, array.length - k - 1); } } public static int findMax(int[] array, int upper) { int maxIndex = 0; for(int y = upper; y >= 0; y--) { if(array[y] > array[maxIndex]) { maxIndex = y; } } return maxIndex; } }
8609608b079a039cec0a2717f516417d620f88cd
dcfd2a997def2463ef522b3992d27feb0f618df5
/src/main/java/ru/job4j/presentation/CreateUser.java
5ec8d085c4769ff339fb478f0a6fc2210835849d
[]
no_license
BaikovSergey/Simple-TODO-list
fc4a3621d6c4b199ee332017ddbca45ae516d423
6ce3d0ef74e0d048e8b8cf3abd493f5a1e9f5d1b
refs/heads/master
2022-12-22T09:53:40.773476
2020-09-22T06:25:52
2020-09-22T06:25:52
290,427,053
0
0
null
null
null
null
UTF-8
Java
false
false
739
java
package ru.job4j.presentation; import ru.job4j.application.TODOList; import ru.job4j.domain.User; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CreateUser extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); TODOList.instOf().createUser(new User(req.getParameter("name"), req.getParameter("email"), req.getParameter("password"))); req.getRequestDispatcher("index.jsp").forward(req, resp); } }
a83537e578c8ff12c9627cd2cf4a04b69ef2cf90
a7e7946a3ac16c9a2d26d39ae3b8708e9eee8031
/test2.java
69c0dac8155c28a232660be31e79f23475636022
[]
no_license
Swoofty/BlueJ-junk
033ca37adda0837f540efea7634564fe75864f87
ec3cd9459adfa4df0af8e66c5d63b1ecd7200622
refs/heads/master
2022-04-06T20:16:15.455451
2020-02-26T18:53:59
2020-02-26T18:53:59
218,333,998
0
0
null
null
null
null
UTF-8
Java
false
false
218
java
import java.util.Scanner; public class test2 { public static void main(String[] args){ int s = 13; String countToString = Integer.toString(s); System.out.print(countToString.substring(1,2)); } }
cddb493f773ac82014d5fbb42bc2067d189a5622
8c4d7032a417e9adfb451a6fa0be160416aac9a3
/src/framework/entities/Food.java
ee20c5621971c2de23af9ab17704b96e6b048bfd
[]
no_license
JoeyJohnJo/Snake
7a13c64b4120f6adaefa0a83ebc8b49898115968
29192a46b057877def6e8c4a74f51c074078ede0
refs/heads/master
2021-05-20T13:18:10.893395
2020-04-20T17:42:23
2020-04-20T17:42:23
252,314,002
0
0
null
null
null
null
UTF-8
Java
false
false
2,394
java
package framework.entities; import framework.Frame; import java.awt.Graphics; import java.awt.Color; import java.awt.Rectangle; import java.util.Random; //Normalmente esta classe daria extends numa classe entity, mas como é um jogo pequeno é desnecessario //A comida nao precisa atualizar nada ent nao precisa de metodo tick public class Food{ private int x, y; // posicao da comida private int width = 10; //largura private int height = 10; //altura public Food() { //Pega dois numeros aleatorios pra ser a posicao da comida int randX = new Random().nextInt(Frame.SCALED_WIDTH - width); // O maximo por x sendo a largura da tela int randY = new Random().nextInt(Frame.SCALED_HEIGHT - height); // o maximo pro y sendo a altura da tela //Checa se os numeros aleatorios n coincidem com a posicao de algum bloco da cobra for (Block b : Snake.getBlocks()) { //Se coincidir com alguma parte da cobra, pega um novo numero aleatorio if (randX > b.x && randX < b.x + b.getWidth() && randY > b.y && randY < b.y + b.getHeight()) { randX = new Random().nextInt(Frame.SCALED_WIDTH - width); randY = new Random().nextInt(Frame.SCALED_HEIGHT - height); } } /*Tecnicamente esse check não é perfeito, precisaria colocar el * em algum loop pra ver se o novo numero aleatorio também não coincide com algum bloco do corpo * mas no geral isso é improvavel*/ //Define o x e y nessa nova posicao aleatoria x = randX; y = randY; } //Renderiza a comida public void render(Graphics g) { g.setColor(Color.RED); g.fillRect(x, y, width, height); //Só um quadrado vermelho na posicao x e y } //Diz se foi comido ou nao public boolean isCollected(Snake head) { Rectangle self = new Rectangle(); self.setBounds(x, y, width, height); //Faz um retangulo com os dados da comida Rectangle snake = new Rectangle(); snake.setBounds(head.getHead().x, head.getHead().y, head.getHead().getWidth(), head.getHead().getHeight()); //Faz um retangulo com os dados da cabeça da cobra return self.intersects(snake); //Se os dois retangulos se cruzarem retorna verdadeiro, se nao, retorna falso } }
2eae7c30750c07db9077a7bec165f99a5af92ef7
ebc7fa3c299035709871422f7b8300d0f4a078d5
/src/pl/greenislanddev/prawojazdy/business/sequencer/TrainingQuestionsSequencer.java
17a4679a3cb79927326296b6434b3c6099ca19dc
[]
no_license
mkorszun/prawo_jazdy
e4c60441992fa669075cd2e31e77fe1b9ba15d0f
110494ed25204f4a22bb7f339b19d258cb7f89c8
refs/heads/master
2016-09-06T03:17:34.987166
2011-10-24T19:13:44
2011-10-24T19:13:44
15,591,562
0
0
null
2014-02-26T10:16:23
2014-01-02T19:19:08
Java
UTF-8
Java
false
false
893
java
package pl.greenislanddev.prawojazdy.business.sequencer; public class TrainingQuestionsSequencer implements QuestionsSequencer { private static final long serialVersionUID = 3134709162175737587L; private Long begin; private Long current; private int numberOfQuestions; public TrainingQuestionsSequencer(int maxQuestions) { this(1L, maxQuestions); } public TrainingQuestionsSequencer(Long begin, int maxQuestions) { this.begin = begin; this.current = begin; this.numberOfQuestions = maxQuestions; } public Long next() { return ++current; } public Long previous() { return --current; } public Long getCurrent() { return current; } public void setCurrent(Long current) { this.current = current; } public void reset() { current = begin; } public int numberOfQuestions() { return numberOfQuestions; } }
[ "luiswk@164134ba-525f-4017-81ba-4730e249e764" ]
luiswk@164134ba-525f-4017-81ba-4730e249e764
6205116acecf5e2f23a165267a6bdbcd665805e6
ea8ad1e7ca4f0becc5ccf9d9f48100f394aaae09
/Sign/src/com/example/sign/SignSelectActivity.java
345bb1295336794c72a1ec8c5b040b6fac22d2f0
[]
no_license
ruicao93/android
d421413c8e659fa9d35cc43e7b0e6fa9a79b6e6f
20ea47be90761b775c4d8fc8fe4f4ad634d85e76
refs/heads/master
2021-05-27T18:22:03.945409
2014-07-07T05:25:56
2014-07-07T05:25:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,043
java
package com.example.sign; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.content.Intent; import android.view.View.OnClickListener; import android.widget.*; public class SignSelectActivity extends Activity{ private String studentID = null; private Button restSignBut = null; private Button courseSignBut = null; private Button historySignBut = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sign_select); Intent tmp = super.getIntent(); studentID = tmp.getStringExtra("studentID"); restSignBut = (Button)super.findViewById(R.id.restSignBut); courseSignBut = (Button)super.findViewById(R.id.courseSignBut); historySignBut = (Button)super.findViewById(R.id.historySignBut); restSignBut.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent it = new Intent(SignSelectActivity.this,RestSignActivity.class); it.putExtra("studentID", studentID); SignSelectActivity.this.startActivity(it); } }); courseSignBut.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent it = new Intent(SignSelectActivity.this,CourseSignActivity.class); it.putExtra("studentID", studentID); SignSelectActivity.this.startActivity(it); } }); historySignBut.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent it = new Intent(SignSelectActivity.this,HistorySignActivity.class); it.putExtra("studentID", studentID); SignSelectActivity.this.startActivity(it); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
49bfa0d80ea0bafd8c495d19e9ba1f3f6625532a
c2395e983bf55e54d2bf4a0ef7959e8d8abb1146
/src/main/java/leetcode/AddStrings.java
3a97daab0ccf6e001674cc991069cdf10f66cbea
[]
no_license
chayangdz/mytest
f4bee9cf835fff0058f336af50c6ea0585f749d8
d8210b3e7b7b0fb303a82c19bd0519b6e0f14c50
refs/heads/master
2023-06-01T02:55:13.811228
2023-05-13T06:25:39
2023-05-13T06:25:39
77,722,345
0
0
null
null
null
null
UTF-8
Java
false
false
1,106
java
package leetcode; /** * 字符串相加 * * @author zhayang <[email protected]> * Created on 2022-10-05 */ public class AddStrings { /** * 思路:定义两个指针,i和j,指向两个字符串的末尾,也就是数字的最低位 * 定义一个变量add,记录相加之后的进位 */ private static String addStrings(String s1, String s2) { int i = s1.length() - 1; int j = s2.length() - 1; int add = 0; StringBuilder builder = new StringBuilder(); while (i > 0 || j > 0 || add > 0) { int x = i >= 0 ? s1.charAt(i) - '0' : 0; int y = j >= 0 ? s2.charAt(j) - '0' : 0; int result = x + y + add; builder.append(result % 10); add = result / 10; i--; j--; } return builder.reverse().toString(); } public static void main(String[] args) { String s1 = "12345000000000000000"; String s2 = "66867890000000000000000"; String result = addStrings(s1, s2); System.out.println(result); } }
5de4c35256e3ffd2b661da5f1a060573dc2e0ae6
c29a7d66787b343be5a8ce8dd320666cd5062cad
/app/src/main/java/github/com/datastructuresandalgorithms/algorithms/BigCount.java
248da1fc33dcb1062489110e30b03a53e323930e
[]
no_license
skcodestack/DataStructuresAndAlgorithms
08818ee3cfbbef83ce5c5689e0c9d25eccb84914
1f3cc55c7cd564ecd181a0f8bf7de0952f41bef4
refs/heads/master
2021-01-25T09:21:48.733398
2017-11-27T10:42:55
2017-11-27T10:42:55
93,826,532
0
0
null
null
null
null
UTF-8
Java
false
false
2,379
java
package github.com.datastructuresandalgorithms.algorithms; import android.util.Log; /** * Email [email protected] * Github https://github.com/skcodestack * Created by sk on 2017/11/20 * Version 1.0 * Description: 大数相乘 */ public class BigCount { private static final String TAG = "BigCount"; /** * * 126 * 138 = 17388 * 3 + 2 + 8= 3 * r[i] = a[i]*b[i-1] + a[i-1]*b[i-1] * * @param a * @param b * @return */ private void multiply(String a, String b){ Log.e(TAG,"乘数一:"+a); Log.e(TAG,"乘数二:"+b); int aLen = a.length(); int bLen = b.length(); char[] s1 = a.toCharArray(); char[] s2 = b.toCharArray(); // 高低位对调 covertdata(s1,aLen); covertdata(s2,bLen); //两数乘 multiply(s1,aLen,s2,bLen); } private void multiply(char[] a ,int nLen,char[] b,int mLen){ int size = nLen + mLen +1; int[] re = new int[size]; for (int i = 0; i < nLen; i++) { for (int j = 0; j < mLen; j++) { re[i + j] = Integer.parseInt(String.valueOf(a[i]))* Integer.parseInt(String.valueOf(b[j])); } } int m = 0; // 进位处理 for (m = 0; m < size; m++) { int carry = re[m] / 10; re[m] = re[m] % 10; if (carry > 0) re[m + 1] += carry; } // 找到最高位 for (m = size - 1; m >= 0;) { if (re[m] > 0) break; m--; } // 由最高位开始打印乘积 System.out.print("乘积:"); for (int i = 0; i <= m; i++) { System.out.print(re[m - i]); } System.out.println(""); } /** * 方便计算 * @param data * @param len */ private static void covertdata(char data[], int len) { //高低位对调 for (int i = 0; i < len / 2; i++) { data[i] += data[len - 1 - i]; data[len - 1 - i] = (char) (data[i] - data[len - 1 - i]); data[i] = (char) (data[i] - data[len - 1 - i]); } } public void run(){ String a = "54656564451213232656454112"; String b = "3651248796532156465845212565589545"; multiply(a, b); } }
c506b6519a0437edf6e50a7f10d59aa19e547b4e
8dba736c1251704554d44d75f9c00d4098de8037
/app/src/main/java/com/josecuentas/android_security/security/CheckInstallPlayStore.java
36c1f4fb11d23512b6d6b019ed68373438a69748
[]
no_license
PibeDx/Android-Security
e8861b17151a50eb6c8bb4950d31e3d0512f8ca1
a96355ead7d1f2137eb37d3ecb01f1ee10e2ad93
refs/heads/master
2021-01-22T04:15:48.482945
2017-05-25T22:06:25
2017-05-25T22:06:25
92,448,338
0
0
null
null
null
null
UTF-8
Java
false
false
609
java
package com.josecuentas.android_security.security; import android.content.Context; /** * Created by jcuentas on 25/05/17. */ public class CheckInstallPlayStore { private static final String PLAY_STORE_APP_ID = "com.android.vending"; /* * Verifica si la aplicacion fue instalada desde el playstore * */ public static boolean verifyInstaller(final Context context) { final String installer = context.getPackageManager() .getInstallerPackageName(context.getPackageName()); return installer != null && installer.startsWith(PLAY_STORE_APP_ID); } }
e0d597b3a1c27f93b7f58b6c94a8f4ac3814f195
447520f40e82a060368a0802a391697bc00be96f
/apks/comparison_qark/de.number26.android/classes_dex2jar/com/google/android/gms/maps/model/BitmapDescriptorFactory.java
cddf3b4fb5c71fed2f535c56d795f2e140fa858b
[ "Apache-2.0" ]
permissive
iantal/AndroidPermissions
7f3343a9c29d82dbcd4ecd98b3a50ddf8d179465
d623b732734243590b5f004d167e542e2e2ae249
refs/heads/master
2023-07-19T01:29:26.689186
2019-09-30T19:01:42
2019-09-30T19:01:42
107,239,248
0
0
Apache-2.0
2023-07-16T07:41:38
2017-10-17T08:22:57
null
UTF-8
Java
false
false
3,505
java
package com.google.android.gms.maps.model; import android.graphics.Bitmap; import android.os.RemoteException; import com.google.android.gms.common.internal.Hide; import com.google.android.gms.common.internal.zzbq; import com.google.android.gms.maps.model.internal.zza; public final class BitmapDescriptorFactory { public static final float HUE_AZURE = 210.0F; public static final float HUE_BLUE = 240.0F; public static final float HUE_CYAN = 180.0F; public static final float HUE_GREEN = 120.0F; public static final float HUE_MAGENTA = 300.0F; public static final float HUE_ORANGE = 30.0F; public static final float HUE_RED = 0.0F; public static final float HUE_ROSE = 330.0F; public static final float HUE_VIOLET = 270.0F; public static final float HUE_YELLOW = 60.0F; private static zza zza; private BitmapDescriptorFactory() {} public static BitmapDescriptor defaultMarker() { try { BitmapDescriptor localBitmapDescriptor = new BitmapDescriptor(zza().zza()); return localBitmapDescriptor; } catch (RemoteException localRemoteException) { throw new RuntimeRemoteException(localRemoteException); } } public static BitmapDescriptor defaultMarker(float paramFloat) { try { BitmapDescriptor localBitmapDescriptor = new BitmapDescriptor(zza().zza(paramFloat)); return localBitmapDescriptor; } catch (RemoteException localRemoteException) { throw new RuntimeRemoteException(localRemoteException); } } public static BitmapDescriptor fromAsset(String paramString) { try { BitmapDescriptor localBitmapDescriptor = new BitmapDescriptor(zza().zza(paramString)); return localBitmapDescriptor; } catch (RemoteException localRemoteException) { throw new RuntimeRemoteException(localRemoteException); } } public static BitmapDescriptor fromBitmap(Bitmap paramBitmap) { try { BitmapDescriptor localBitmapDescriptor = new BitmapDescriptor(zza().zza(paramBitmap)); return localBitmapDescriptor; } catch (RemoteException localRemoteException) { throw new RuntimeRemoteException(localRemoteException); } } public static BitmapDescriptor fromFile(String paramString) { try { BitmapDescriptor localBitmapDescriptor = new BitmapDescriptor(zza().zzb(paramString)); return localBitmapDescriptor; } catch (RemoteException localRemoteException) { throw new RuntimeRemoteException(localRemoteException); } } public static BitmapDescriptor fromPath(String paramString) { try { BitmapDescriptor localBitmapDescriptor = new BitmapDescriptor(zza().zzc(paramString)); return localBitmapDescriptor; } catch (RemoteException localRemoteException) { throw new RuntimeRemoteException(localRemoteException); } } public static BitmapDescriptor fromResource(int paramInt) { try { BitmapDescriptor localBitmapDescriptor = new BitmapDescriptor(zza().zza(paramInt)); return localBitmapDescriptor; } catch (RemoteException localRemoteException) { throw new RuntimeRemoteException(localRemoteException); } } private static zza zza() { return (zza)zzbq.zza(zza, "IBitmapDescriptorFactory is not initialized"); } @Hide public static void zza(zza paramZza) { if (zza != null) { return; } zza = (zza)zzbq.zza(paramZza); } }
1541f4b498e8fdf3adcea3ff131fd49def097bea
c20c86afd692b188fab6564e324328267f3b78d7
/tests/src/main/java/org/nervos/appchain/tests/TokenTransactionTest.java
34b3e9e5ae0f8ea2119fd3ebe07c6f4f3ac2bfc9
[ "Apache-2.0" ]
permissive
aihua/cryptcurrence-appchainj-android
d5697ae23420713b2b8505903935be4e282a592e
10183d2a9271fb809e3fba80ccb6bb71bc4e7c92
refs/heads/master
2020-04-04T23:32:32.446076
2018-11-05T09:32:50
2018-11-05T09:32:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,095
java
package org.nervos.appchain.tests; import java.math.BigInteger; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Properties; import java.util.Random; import org.nervos.appchain.abi.FunctionEncoder; import org.nervos.appchain.abi.FunctionReturnDecoder; import org.nervos.appchain.abi.TypeReference; import org.nervos.appchain.abi.datatypes.Address; import org.nervos.appchain.abi.datatypes.Function; import org.nervos.appchain.abi.datatypes.Type; import org.nervos.appchain.abi.datatypes.Uint; import org.nervos.appchain.abi.datatypes.generated.Uint256; import org.nervos.appchain.protocol.AppChainj; import org.nervos.appchain.protocol.AppChainjFactory; import org.nervos.appchain.protocol.core.DefaultBlockParameter; import org.nervos.appchain.protocol.core.DefaultBlockParameterName; import org.nervos.appchain.protocol.core.methods.request.Call; import org.nervos.appchain.protocol.core.methods.request.Transaction; import org.nervos.appchain.protocol.core.methods.response.TransactionReceipt; import org.nervos.appchain.protocol.http.HttpService; public class TokenTransactionTest { private static Properties props; private static String testNetIpAddr; private static int chainId; private static int version; private static String privateKey; private static String fromAddress; private static String toAddress; private static String binPath; private static final String configPath = "tests/src/main/resources/config.properties"; private static Random random; private static BigInteger quota; private static String value; private static AppChainj service; static { try { props = Config.load(configPath); } catch (Exception e) { System.out.println("Failed to read properties from config file"); e.printStackTrace(); } chainId = Integer.parseInt(props.getProperty(Config.CHAIN_ID)); version = Integer.parseInt(props.getProperty(Config.VERSION)); testNetIpAddr = props.getProperty(Config.TEST_NET_ADDR); privateKey = props.getProperty(Config.SENDER_PRIVATE_KEY); fromAddress = props.getProperty(Config.SENDER_ADDR); toAddress = props.getProperty(Config.TEST_ADDR_1); binPath = props.getProperty(Config.TOKEN_BIN); HttpService.setDebug(false); service = AppChainjFactory.build(new HttpService(testNetIpAddr)); random = new Random(System.currentTimeMillis()); quota = BigInteger.valueOf(1000000); value = "0"; } static String loadContractCode(String binPath) throws Exception { return new String(Files.readAllBytes(Paths.get(binPath))); } static String deployContract(String contractCode) throws Exception { long currentHeight = service.appBlockNumber().send() .getBlockNumber().longValue(); long validUntilBlock = currentHeight + 80; BigInteger nonce = BigInteger.valueOf(Math.abs(random.nextLong())); long quota = 9999999; Transaction tx = Transaction.createContractTransaction( nonce, quota, validUntilBlock, version, chainId, value, contractCode); String rawTx = tx.sign(privateKey, false, false); return service.appSendRawTransaction(rawTx) .send().getSendTransactionResult().getHash(); } static TransactionReceipt getTransactionReceipt(String txHash) throws Exception { return service.appGetTransactionReceipt(txHash) .send().getTransactionReceipt(); } static String contractFunctionCall( String contractAddress, String funcCallData) throws Exception { long currentHeight = service.appBlockNumber() .send().getBlockNumber().longValue(); long validUntilBlock = currentHeight + 80; BigInteger nonce = BigInteger.valueOf(Math.abs(random.nextLong())); long quota = 1000000; Transaction tx = Transaction.createFunctionCallTransaction( contractAddress, nonce, quota, validUntilBlock, version, chainId, value, funcCallData); String rawTx = tx.sign(privateKey, false, false); return service.appSendRawTransaction(rawTx) .send().getSendTransactionResult().getHash(); } static String transfer( String contractAddr, String toAddr, BigInteger value) throws Exception { Function transferFunc = new Function( "transfer", Arrays.<Type>asList(new Address(toAddr), new Uint256(value)), Collections.<TypeReference<?>>emptyList() ); String funcCallData = FunctionEncoder.encode(transferFunc); return contractFunctionCall(contractAddr, funcCallData); } //eth_call static String call( String from, String contractAddress, String callData) throws Exception { Call call = new Call(from, contractAddress, callData); return service.appCall(call, DefaultBlockParameterName.fromString("latest")).send().getValue(); } static String getBalance(String fromAddr, String contractAddress) throws Exception { Function getBalanceFunc = new Function( "getBalance", Arrays.<Type>asList(new Address(fromAddr)), Arrays.<TypeReference<?>>asList(new TypeReference<Uint>() { }) ); String funcCallData = FunctionEncoder.encode(getBalanceFunc); String result = call(fromAddr, contractAddress, funcCallData); List<Type> resultTypes = FunctionReturnDecoder.decode(result, getBalanceFunc.getOutputParameters()); return resultTypes.get(0).getValue().toString(); } public static void main(String[] args) throws Exception { // deploy contract String contractCode = loadContractCode(binPath); System.out.println(contractCode); String deployContractTxHash = deployContract(contractCode); System.out.println("wait to deploy contract"); Thread.sleep(10000); // get contract address from receipt TransactionReceipt txReceipt = getTransactionReceipt(deployContractTxHash); if (txReceipt.getErrorMessage() != null) { System.out.println("There is something wrong in deployContractTxHash. Error: " + txReceipt.getErrorMessage()); System.exit(1); } String contractAddress = txReceipt.getContractAddress(); System.out.println("Contract deployed successfully. Contract address: " + contractAddress); // call contract function(eth_call) String balaneFrom = getBalance(fromAddress, contractAddress); String balanceTo = getBalance(toAddress, contractAddress); System.out.println(fromAddress + " has " + balaneFrom + " tokens."); System.out.println(toAddress + " has " + balanceTo + " tokens."); // call contract function String transferTxHash = transfer(contractAddress, toAddress, BigInteger.valueOf(1000)); System.out.println("wait for transfer transaction."); Thread.sleep(10000); TransactionReceipt transferTxReceipt = getTransactionReceipt(transferTxHash); if (transferTxReceipt.getErrorMessage() != null) { System.out.println("Failed to call transfer method in contract. Error: " + transferTxReceipt.getErrorMessage()); System.exit(1); } System.out.println("call transfer method success and receipt is " + transferTxHash); balaneFrom = getBalance(fromAddress, contractAddress); balanceTo = getBalance(toAddress, contractAddress); System.out.println(fromAddress + " has " + balaneFrom + " tokens."); System.out.println(toAddress + " has " + balanceTo + " tokens."); System.out.println("Complete"); System.exit(0); } }
827989baaff05192bf4ba1f4e8fcdb66ab56ca3e
be73270af6be0a811bca4f1710dc6a038e4a8fd2
/crash-reproduction-moho/results/MOCKITO-9b-4-24-NSGA_II-LineCoverage:ExceptionType:StackTraceSimilarity/org/mockito/internal/handler/MockHandlerImpl_ESTest_scaffolding.java
8b36defa0bb7da8d7924284318f7dbf50a4e8580
[]
no_license
STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application
cf118b23ecb87a8bf59643e42f7556b521d1f754
3bb39683f9c343b8ec94890a00b8f260d158dfe3
refs/heads/master
2022-07-29T14:44:00.774547
2020-08-10T15:14:49
2020-08-10T15:14:49
285,804,495
0
0
null
null
null
null
UTF-8
Java
false
false
448
java
/** * Scaffolding file used to store all the setups needed to run * tests automatically generated by EvoSuite * Mon Apr 06 10:23:11 UTC 2020 */ package org.mockito.internal.handler; import org.evosuite.runtime.annotation.EvoSuiteClassExclude; import org.junit.BeforeClass; import org.junit.Before; import org.junit.After; @EvoSuiteClassExclude public class MockHandlerImpl_ESTest_scaffolding { // Empty scaffolding for empty test suite }
955046d146a4e07389c4d2337601522e93502986
42b8010852b80d8a31e5dbe4e594786d2a215274
/app/src/main/java/com/example/cards/DrawLayout.java
d3f6725d3ce03d2c5dcceb203f6a840ced2f615f
[]
no_license
jordan-weaver/Cards
962b2ba7a6a73ccf7cffa21689c2aa71af2ec5dc
966ce57f3ef56d73dc382d558f2310a7d05ddd1e
refs/heads/master
2020-04-19T21:58:26.178058
2019-04-01T01:03:59
2019-04-01T01:03:59
168,456,629
2
0
null
null
null
null
UTF-8
Java
false
false
4,320
java
package com.example.cards; import android.content.Context; import android.util.AttributeSet; import android.widget.ImageView; import android.widget.RelativeLayout; import java.util.ArrayList; public class DrawLayout extends RelativeLayout implements CardHolder { RelativeLayout drawLayout; ArrayList<CardView> currentDraw; ArrayList<CardView> drawStack; public DrawLayout(Context context) { super(context); drawLayout = findViewById(R.id.draw_layout); currentDraw = new ArrayList<>(); drawStack = new ArrayList<>(); } public DrawLayout(Context context, AttributeSet attr) { super(context, attr); drawLayout = findViewById(R.id.draw_layout); currentDraw = new ArrayList<>(); drawStack = new ArrayList<>(); } public DrawLayout(Context context, AttributeSet attr, int def) { super(context, attr, def); drawLayout = findViewById(R.id.draw_layout); currentDraw = new ArrayList<>(); drawStack = new ArrayList<>(); } private void addDrawToStack() { if(currentDraw.size() > 0) { currentDraw.get(currentDraw.size() - 1).setTouchable(false); } CardView curr; while(currentDraw.size() > 0) { curr = currentDraw.remove(0); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT); params.addRule(RelativeLayout.ALIGN_PARENT_LEFT); curr.setLayoutParams(params); drawStack.add(curr); } } public Card[] returnDeck() { addDrawToStack(); Card[] result = new Card[drawStack.size()]; CardView cv; for(int i = 0; i < drawStack.size(); ++i) { cv = drawStack.get(i); result[i] = cv.card; } drawLayout.removeViewsInLayout(0, drawLayout.getChildCount()); drawStack.clear(); currentDraw.clear(); return result; } @Override public void addCards(ArrayList<CardView> cards) { addDrawToStack(); CardView curr; for(int i = 0; i < cards.size(); ++i) { curr = cards.get(i); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); switch (i) { case 0: params.addRule(RelativeLayout.ALIGN_PARENT_LEFT); break; case 1: params.addRule(RelativeLayout.CENTER_IN_PARENT); break; case 2: params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); break; default: throw new IllegalArgumentException("Too mamy cards passes to draw"); } curr.setScaleType(ImageView.ScaleType.FIT_CENTER); curr.setAdjustViewBounds(true); curr.setPadding(1, 1, 1, 1); curr.setLayoutParams(params); curr.setTouchable(false); currentDraw.add(curr); drawLayout.addView(curr); } currentDraw.get(currentDraw.size() - 1).setTouchable(true); } @Override public void removeCards(ArrayList<CardView> cards) { if(cards.size() != 1) { throw new IllegalArgumentException("attempted to remove more than 1 card from draw"); } else { CardView draggable = currentDraw.get(currentDraw.size() - 1); CardView remove = cards.get(0); if (remove.equals(draggable)) { currentDraw.remove(draggable); drawLayout.removeView(draggable); if (currentDraw.size() <= 0 && drawStack.size() > 0) { currentDraw.add(drawStack.remove(drawStack.size() - 1)); } // if available set next card in draw to allow touch events if(currentDraw.size() > 0) { draggable = currentDraw.get(currentDraw.size() - 1); draggable.setTouchable(true); } } } } }
d35e377fd410b2222efe3ea1f37dcafdd8cf7bc4
e6f6f4a47259366b75979f340ddf9efba5e7c574
/blogPessoal/blogPessoal/src/main/java/org/generation/blogPessoal/repository/UsuarioRepository.java
c64859bd162c9fc0211cf711d2dc46612f2fff84
[]
no_license
erufluk/FrontEnd
306a248bcc57d4c02ac3aa6e00ba94d2d5ec97cb
c4adca2265f1ffad34b9c0cbd268081a6e3fce55
refs/heads/componente-menu-rodape
2023-03-12T04:29:42.762669
2021-02-28T03:55:17
2021-02-28T03:55:17
340,766,919
0
0
null
2021-02-28T03:55:18
2021-02-20T22:28:57
HTML
UTF-8
Java
false
false
323
java
package org.generation.blogPessoal.repository; import java.util.Optional; import org.generation.blogPessoal.model.Usuario; import org.springframework.data.jpa.repository.JpaRepository; public interface UsuarioRepository extends JpaRepository <Usuario, Long> { public Optional<Usuario> findByUsuario(String usuario); }
cf6efc308e4bc2aabafbe1a4e32a677b6d1ad628
c280745d495eebafc027d1ca12eb7a803628546a
/src/main/java/com/cristhian/barros/Examen/controllers/ProductosController.java
34f181381a5dea1eb942f0710a4e5ba881186f2e
[]
no_license
CrisMasterson/Examen-II-BarrosC
18b29518f5d9a13a09a82d55ee4859f77edb903a
67b3001df6dada802a93a6d2c972f5a68fcdfef4
refs/heads/main
2023-06-03T23:43:51.351183
2021-06-24T14:45:04
2021-06-24T14:45:04
379,956,891
0
0
null
null
null
null
UTF-8
Java
false
false
1,776
java
package com.cristhian.barros.Examen.controllers; import com.cristhian.barros.Examen.entities.Productos; import com.cristhian.barros.Examen.entities.Productos; import com.cristhian.barros.Examen.repositories.ProductosRepository; import com.cristhian.barros.Examen.repositories.ProductosRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import java.util.List; import java.util.Optional; @Controller public class ProductosController { private ProductosRepository productosRepository; @Autowired public ProductosController(ProductosRepository productRepository) { this.productosRepository = productRepository; } public List<Productos> findAllProduct() { return this.productosRepository.findAll(); } public Optional<Productos> findProductById(int id){ return this.productosRepository.findById(id); } public void createProduct(Productos productos){ this.productosRepository.save(productos); } public boolean editProductById(int id, Productos productos){ Optional<Productos> productOptional = this.findProductById(id); if( !productOptional.isPresent()) return false; Productos productosdb = productOptional.get(); productosdb.setMarca(productos.getMarca()); productosdb.setModelo(productos.getModelo()); productosdb.setPrice(productos.getPrice()); productosRepository.save(productosdb); return true; } public boolean deleteProductById(int id) { Optional<Productos> productOptional = this.findProductById(id); if (!productOptional.isPresent()) return false; productosRepository.deleteById(id); return true; } }
957dc97afadc8ecc4e31d33580930ad6239eec95
24a4f1d96e427d522780dc0e93a981f2d04dca89
/src/main/java/com/he/树/q104二叉树的最大深度/Solution.java
0fc65a930a786794739c08a8af4b17e9e26c37ab
[]
no_license
Ahhhnnn/leetcode
59d2d919de6b884e2f8b19615d5effb0b38b3f2a
21a2cff612232b03549a3a5dd0cb12c355345004
refs/heads/master
2021-06-26T23:32:24.817655
2021-06-15T10:32:41
2021-06-15T10:32:41
232,350,399
1
1
null
null
null
null
UTF-8
Java
false
false
1,188
java
package com.he.树.q104二叉树的最大深度; /** * 给定一个二叉树,找出其最大深度。 * * 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 * * 说明: 叶子节点是指没有子节点的节点。 * * 示例: * 给定二叉树 [3,9,20,null,null,15,7], * * 3 * / \ * 9 20 * / \ * 15 7 * 返回它的最大深度 3 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class Solution { public static void main(String[] args) { TreeNode treeNode = new TreeNode(1); treeNode.left= new TreeNode(2); int i = maxDepth(treeNode); System.out.println(i); } private static int maxDepth(TreeNode root) { return root == null ? 0 : 1 + Math.max(maxDepth(root.left),maxDepth(root.right)); } //Definition for a binary tree node. public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } }
3ee21b6a2f7b30ed4a631b8969708173ae818c44
14ba4e57ca99081711ff82842cffbde4c55aca45
/src/main/java/am/iunetworks/KinzangChedup/week5/Q4SmallestLargest.java
2910e5f7397078ceeae8c265fc2880ada97254b4
[]
no_license
jzigda/test-ttpl
9eb8402d1eb7fb6e308747cecb91eb81bca2ddb4
aff92621ed7f4745d993d27bc36755eb45e90eb2
refs/heads/master
2022-12-10T02:45:22.931368
2020-09-05T14:54:41
2020-09-05T14:54:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,146
java
package am.iunetworks.KinzangChedup.week5; /** * Created by kinza on 9/2/2020. */ public class Q4SmallestLargest { public static void main(String[] args) { Q4SmallestLargest ss = new Q4SmallestLargest(); System.out.println(ss.sortString("bhutan")); } public String sortString(String s) { StringBuilder sb = new StringBuilder(); int count = s.length(); int[] frequency = new int[26]; for (int i = 0; i < count; i++) { frequency[s.charAt(i) - 'a']++; System.out.println(s.charAt(i) - 'a'); } while (count > 0) { for (int i = 0; i < frequency.length; i++) { if (frequency[i] != 0) { sb.append((char)(i+97)); frequency[i]--; count--; } } for (int i = frequency.length-1; i >= 0; i--) { if (frequency[i] != 0) { sb.append((char)(i+97)); frequency[i]--; count--; } } } return sb.toString(); } }
192cfdfbc79da063051d232dbdaa78db2ee1d487
5d2050d824d86900daa9c8171f9335dacfa88d79
/Exercises01_02.java
5c202707006152a23d06fcc3758f16290c6c0bc7
[]
no_license
Chongt2/Java
ce9347a33dd376adbcd8691abd0cc65fe462ad6e
b42bb9b4082d7209919d913927f59e4b397da59b
refs/heads/master
2020-05-24T11:46:22.130019
2019-05-18T02:18:43
2019-05-18T02:18:43
187,254,215
0
0
null
null
null
null
UTF-8
Java
false
false
312
java
package package0; public class Exercises01_02 { public static void main(String[] args) { System.out.println("Welcome to Java"); System.out.println("Welcome to Java"); System.out.println("Welcome to Java"); System.out.println("Welcome to Java"); System.out.println("Welcome to Java"); } }
b21f75bf4fb7fbe2febe3bb7e650ab25076a3040
88c220eb69dc05e8eb428265dda4214addd900a0
/app/src/main/java/de/zitzmanncedric/abicalc/listener/OnButtonTouchListener.java
66d105e06f792fa0d623c644ee34efca8f55dea7
[]
no_license
z3ttee/abikalkulator-android
19568d041c6df25eec2aa820731d975bca53f0d0
73bbfccf7645df8bee7b39d6e9db772f69b28d14
refs/heads/master
2021-02-18T00:45:51.186730
2020-04-04T12:37:49
2020-04-04T12:37:49
245,141,519
0
0
null
null
null
null
UTF-8
Java
false
false
2,192
java
package de.zitzmanncedric.abicalc.listener; import android.annotation.SuppressLint; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import de.zitzmanncedric.abicalc.AppCore; import de.zitzmanncedric.abicalc.R; /** * Klasse zum Behandeln von Touch-Events */ public class OnButtonTouchListener implements View.OnTouchListener { private float scaleValue; /** * Konstruktor der Klasse. Das System setzt automatisch die Standardwerte */ public OnButtonTouchListener() { TypedValue value = new TypedValue(); AppCore.getInstance().getResources().getValue(R.dimen.default_scaleDown, value, true); this.scaleValue = value.getFloat(); } /** * Optionaler Konstruktor. Standardwerte können definiert werden * @param scaleValue Dezimalwert. Das UI-Element nimmt die neue Größe beim Touch-Event an. */ public OnButtonTouchListener(float scaleValue) { this.scaleValue = scaleValue; } /** * Behandlung des Touch-Events. Ein UI-Element wird beim berühren verkleinert. Das dient der Darstellung eines Button-Klicks. * @param view UI-Element, das berührt wurde * @param motionEvent MotionEvent, welches ausgelöst wurde (z.B. BUTTON_PRESS oder SCROLL) * @return false, weil das Event nicht dafür sorgen soll, dass Events wir Klick-Events nicht mehr stattfinden sollen */ @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouch(View view, MotionEvent motionEvent) { int scaleDuration = 40; if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){ view.animate().scaleX(scaleValue).scaleY(scaleValue).setDuration(scaleDuration).setInterpolator(new AccelerateDecelerateInterpolator()); } else { if(motionEvent.getAction() == MotionEvent.ACTION_UP || motionEvent.getAction() == MotionEvent.ACTION_CANCEL) { view.animate().scaleX(1f).scaleY(1f).setDuration(scaleDuration).setInterpolator(new AccelerateDecelerateInterpolator()); } } return false; } }
ac5b16ae58f63d3c516e157a4ecd85851dfcce55
06d5f713633f537bdda55f3466936c6c74904bc5
/domain/src/test/java/com/denis/domain/ApplicationStub.java
d488f89d9927ad324ef42f473bae81add4777fc4
[]
no_license
deniszink/MyPocket
7000f7ecad9832ec2b0ea5411ddc5305839b9788
9770929578e9c0f1e83ebdf494a4a9931e17e956
refs/heads/master
2020-12-11T03:48:50.987216
2016-05-30T08:02:17
2016-05-30T08:02:17
48,385,712
0
0
null
null
null
null
UTF-8
Java
false
false
743
java
/** * Copyright (C) 2015 android10.org Open Source Project * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.denis.domain; import android.app.Application; public class ApplicationStub extends Application { }
4e0e06210f6944a3cdf26dedeb0d1c100e62c229
d3993fa621ac9f7d1fbfba19332fa9a6c6650399
/SdwKG2Solr/src/sdw/aksw/org/solr/SolrFieldValue.java
17961b5a768c8874b8dbf7fbe7f06fa854ae8adf
[ "Apache-2.0" ]
permissive
AKSW/SmartDataWebKG
894a4e80562ade4eb933a81167555996869610f0
cd2a48c86f66bc59841805406bcb3e8168038859
refs/heads/master
2023-01-07T21:33:05.892937
2017-12-13T15:29:14
2017-12-13T15:29:14
49,487,841
2
1
Apache-2.0
2023-01-02T22:13:06
2016-01-12T09:02:50
Java
UTF-8
Java
false
false
302
java
package sdw.aksw.org.solr; import java.util.Collection; /** * Basic interface for storing information for SOLR fields * * @author kay * */ public interface SolrFieldValue<T> { public boolean isEmpty(); public void addFieldValue(T ... values); public Collection<T> getFieldValues(); }
b9cbe1ccf851ab234e672687d095bda6d9b41f6a
9cb3baa6dce0e5a002c3d9258e1060f92cf7c894
/src/main/java/pl/krystian/RegisterClasses/AddUserToDatabase.java
872f1211b6cd4f9ff2745dab56a8b21028cf5d47
[]
no_license
433MHz/MiniProject-Java-backend
5e0db61be775f7435cde72404bb98c9a706fda6e
4ddddf1155972a91005bd7d5967aee332cbbdec8
refs/heads/master
2023-02-10T15:49:06.216180
2021-01-04T18:24:32
2021-01-04T18:24:32
326,218,537
1
0
null
2021-01-04T18:24:33
2021-01-02T16:04:58
Java
UTF-8
Java
false
false
1,584
java
package pl.krystian.RegisterClasses; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class AddUserToDatabase extends CheckData{ @Autowired MessageForClientFromRegister messageForClient; public MessageForClientFromRegister add(DataFromClientForRegister data) { String login = data.getLogin(); String password = data.getPassword(); String repeatedPassword = data.getRepeatedPassword(); int option = 0; if(isLoginTooShort(login)) option = 1; else if(isLoginTooLong(login)) option = 2; else if(isPasswordTooShort(password)) option = 3; else if(isPasswordTooLong(password)) option = 4; else if(!arePasswordsSame(password, repeatedPassword)) option = 5; else if(isLoginInDatabase(login)) option = 6; else if(database.addUser(data)) option = 7; switch (option) { case 1: messageForClient.setAll("Login need to be longer than 8 digits", false); break; case 2: messageForClient.setAll("Login need to be lesser than 64 digits", false); break; case 3: messageForClient.setAll("Password need to be longer than 8 digits", false); break; case 4: messageForClient.setAll("Password need to be lesser than 64 digits", false); break; case 5: messageForClient.setAll("Passwords are not same", false); break; case 6: messageForClient.setAll("This login is occupied", false); break; case 7: messageForClient.setAll("User register success", true); break; default: break; } return messageForClient; } }
7ac8996bb80b83498e994766cb7b0c9390439f44
6b2ad4c354639c65ddea3251e88ced4385c31567
/level16/lesson07/task02/Solution.java
cfcd996bc1116b61986997a7bec48b91e66c4fc3
[]
no_license
lndsknht/JavaRushHomeWork
326d5f0ed4ed4ffa76ecb7b2c9cba4b256a1a31e
b18339f579570a8223ae6aba0bcf676b8eb51c23
refs/heads/master
2021-01-10T08:15:05.149776
2015-09-30T14:19:27
2015-09-30T14:19:29
40,826,987
0
0
null
null
null
null
UTF-8
Java
false
false
2,634
java
package com.javarush.test.level16.lesson07.task02; /* Stopwatch (Секундомер) 1. Разберись, что делает программа. 2. Реализуй логику метода doSeveralSteps так, чтобы учитывалась скорость бегуна. 2.1. Метод getSpeed() в классе Runner показывает, сколько шагов в секунду делает бегун. Нужно, чтобы бегун действительно делал заданное количество шагов в секунду. Если Иванов делает 4 шага в секунду, то за 2 секунды он сделает 8 шагов. Если Петров делает 2 шага в секунду, то за 2 секунды он сделает 4 шага. 2.2. Метод sleep в классе Thread принимает параметр типа long. */ public class Solution { public static volatile boolean isStopped = false; public static void main(String[] args) throws InterruptedException { Runner ivanov = new Runner("Ivanov", 4); Runner petrov = new Runner("Petrov", 2); //на старт! //внимание! //марш! ivanov.start(); petrov.start(); Thread.sleep(2000); isStopped = true; Thread.sleep(1000); } public static class Stopwatch extends Thread { private Runner owner; private int stepNumber; public Stopwatch(Runner runner) { this.owner = runner; } public void run() { try { while (!isStopped) { doSeveralSteps(); } } catch (InterruptedException e) { } } private void doSeveralSteps() throws InterruptedException { stepNumber++; Thread.sleep((long)(1000/owner.getSpeed())); System.out.println(owner.getName() + " делает шаг №" + stepNumber + "!"); //add your code here - добавь код тут } } public static class Runner { private String name; private double speed; Stopwatch stopwatch; public Runner(String name, double speed) { this.name = name; this.speed = speed; this.stopwatch = new Stopwatch(this); } public String getName() { return name; } public double getSpeed() { return speed; } public void start() { stopwatch.start(); } } }
edb5d4ab3eb2122ef6ffccfbb6e8ab834db0ddb7
5b4a5e568a6c006b25bfce48614b5ac531c4afc8
/src/main/java/servlets/AdvertServlet.java
b334b022e2a5d093ce519af5990e422cfc160b5a
[]
no_license
etiennegalea/Software-Testing
035376aa2469624dbd1c6de13546fde13a907cfd
20966634a0296532facbb34c7beaa71fa2a7e910
refs/heads/master
2021-06-09T07:26:29.206223
2017-01-11T00:23:17
2017-01-11T00:23:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,348
java
package servlets; import cps3222.classes.AdPlatform; import cps3222.classes.Affiliate; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name = "AdvertServlet", urlPatterns = "/adclick") public class AdvertServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { AdPlatform adplatform = (AdPlatform)request.getSession().getAttribute("adplatform"); int userID = (Integer) request.getSession().getAttribute("userid"); adplatform.AdClicked(userID); request.getSession().setAttribute("userbalance", adplatform.getAffiliatesDatabase().get(userID).getBalance()); request.getSession().setAttribute("usertrackedbalance", adplatform.getAffiliatesDatabase().get(userID).getCumulativeBalance()); request.getSession().setAttribute("affiliatetype", adplatform.getAffiliatesDatabase().get(userID).getType().name()); response.sendRedirect("accountadmin.jsp"); } }
6e34953bcc097b97c911e28f9b85b886348f921a
60707ec4529ff69d1aee1d0cee5d68a2290a2440
/app/src/main/java/br/com/firebase/whatsapp/adapter/TableAdapter.java
43c404da3a4eabba59baf043c75a747dffff33af
[]
no_license
douglasjava/whatshapp
a1b827b2c14d6679a07d5c59769dd1f6856975b9
6336cf736d14934bedbb47221fffbafb099b9059
refs/heads/master
2021-05-04T18:16:44.068769
2018-02-22T21:01:50
2018-02-22T21:01:50
120,111,524
0
1
null
null
null
null
UTF-8
Java
false
false
1,100
java
package br.com.firebase.whatsapp.adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import br.com.firebase.whatsapp.fragments.ContatosFragment; import br.com.firebase.whatsapp.fragments.ConversasFragment; /** * Created by Marques on 15/02/2018. */ public class TableAdapter extends FragmentStatePagerAdapter { private String[] tituloAbas = {"CONVERSAS", "CONTATOS"}; public TableAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { Fragment fragment = null; switch (position) { case 0: fragment = new ConversasFragment(); break; case 1: fragment = new ContatosFragment(); break; } return fragment; } @Override public int getCount() { return tituloAbas.length; } @Override public CharSequence getPageTitle(int position) { return tituloAbas[position]; } }
dc3c91236362060e41b741e182103265b5a215a3
b2f07a21849eaf9e2ca7a1822081ebb6b2708b02
/src/me/noip/yanny/utils/CustomItemStack.java
3bbb89fa418961347994a8414323b37188af0f7b
[]
no_license
yanny7/YannyCraft
c5c3e3cca9670a29cca3aa8e59f0b114d879fe42
4b5d0615e46ef0b6109b6713b43ca03df664346d
refs/heads/master
2020-12-31T07:19:27.182865
2017-03-18T18:52:03
2017-03-18T18:52:03
80,561,036
1
0
null
null
null
null
UTF-8
Java
false
false
974
java
package me.noip.yanny.utils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; public class CustomItemStack extends ItemStack { public CustomItemStack(Material material) { super(material); } public CustomItemStack(ItemStack itemStack) { super(itemStack); } @Override public int hashCode() { byte hash = 1; int hash1 = hash * 31 + this.getTypeId(); hash1 = hash1 * 31 + this.getAmount(); hash1 = hash1 * 31 + (this.hasItemMeta()?(this.getItemMeta() == null?this.getItemMeta().hashCode():this.getItemMeta().hashCode()):0); return hash1; } @Override public boolean isSimilar(ItemStack stack) { return stack != null && (stack == this || this.getTypeId() == stack.getTypeId() && this.hasItemMeta() == stack.hasItemMeta() && (!this.hasItemMeta() || Bukkit.getItemFactory().equals(this.getItemMeta(), stack.getItemMeta()))); } }
621f2939e0e9f2f212d24715b40cb247a53c43a6
840d440b9b95f2e86831f5e225d7286a0bd39e6d
/APlesson_05/APLesson_05.1/Equals.java
e659f6ad2bb81de11b08ae0d5893033df1cf615b
[]
no_license
anubhadada/Bhadada_Anu
4d414430402f82333c21233bfb596e99ce7ad919
ca4a675ca451603b983bca32ec66a011268c6799
refs/heads/master
2021-06-17T13:21:29.741245
2017-06-09T17:50:32
2017-06-09T17:50:32
67,243,982
0
0
null
null
null
null
UTF-8
Java
false
false
363
java
import java.util.Scanner; public class Equals { public static void main(String[]args) { Scanner kb = new Scanner(System.in); System.out.println("Enter a word: "); String word1 = kb.next(); String word2 = "word"; if (word1.equals(word2)) System.out.println("The words are equal!"); else System.out.println("The words are not equal."); } }
d3d0196552be5d98cd79302ec1ef9746e8d798ca
3afb81adc8ee12801cc7edbee971d3222cf7dda2
/src/com/wjit/course/message/req/LocationMessage.java
1edd5d32fa1f79142233e56f838844e26642b83c
[]
no_license
wjit5/wechat
59a2b22ee160d7c7a66bd5d690508fda1fa0cd7e
fe50cb7735d152b9e56307564b0ea25c4682ef60
refs/heads/master
2021-01-16T17:46:23.891409
2016-01-22T09:33:42
2016-01-22T09:33:42
null
0
0
null
null
null
null
GB18030
Java
false
false
878
java
package com.wjit.course.message.req; /** * 地理位置消息 * * @author WANGJIAN * @date 2015-12-8 */ public class LocationMessage extends BaseMessage{ //地理位置维度 private String Location_X; //地理位置经度 private String Location_Y; //地图缩放大小 private String Scale; //地理位置信息 private String Label; public String getLocation_X() { return Location_X; } public void setLocation_X(String locationX) { Location_X = locationX; } public String getLocation_Y() { return Location_Y; } public void setLocation_Y(String locationY) { Location_Y = locationY; } public String getScale() { return Scale; } public void setScale(String scale) { Scale = scale; } public String getLabel() { return Label; } public void setLabel(String label) { Label = label; } }
5a2071d1d526d999793579a123d0c43d3c2aec06
71c9c52781d901f593f48f92736b473ce9429b84
/Website_stuff/Java/CSC 221/src/BasicProgramBuilder.java
4b8a945c4c2df649a310b9254697d11005debfa8
[]
no_license
dcs4412/devinsimpson
3a7338b1559063767b51bee9187b1e7ce8f37970
cf79bc506e8782f4fff4199a30fe9ce87b8bab57
refs/heads/master
2021-01-25T10:07:39.976495
2015-02-12T02:56:17
2015-02-12T02:56:17
30,518,342
0
0
null
2015-02-12T02:56:18
2015-02-09T04:19:26
Java
UTF-8
Java
false
false
96,881
java
import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.border.BevelBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; /** * team project CSC 221 * * this project is designed to allow the user to learn the basics of programming by seeing and editing * classes, methods, variables and comments * * saving and loading possible to continue work on projects * * use can select what and where a programs classes, comments, methods and variables to understand how programs * are written * * they can name and select modifiers for classes, methods and variables * * exporting to java documents is possible for the currently viewed class or all the classes in a program * for further editing in a real java development environment * * and extra credit feature allows users to add one comment to their methods and variables so they can accurately * explain the purpose and function of them * * everything in this program was written by me, Devin Simpson * * @author Devin Simpson * */ public class BasicProgramBuilder extends JFrame implements ItemListener { /** * */ private static final long serialVersionUID = 1L; private JPanel creationPanel, selectionPanel, classPanel, infoPanel, classUpdatePanel; private JPanel classTextPanel, methodTextPanel, instanceVariableTextPanel, createClassPanel, createMethodPanel, createInsatcenVariablePanel, buttonPanel; private Color c = Color.LIGHT_GRAY, varColor = new Color(c.getRed() + 10, c.getRed() + 30, c.getRed() + 10), mColor = new Color( c.getRed() + 30, c.getRed() + 30, c.getRed() + 60), cColor = new Color(c.getRed() + 50, c.getRed() + 12, c.getRed() + 50); // colors for each panel based on weather private JPanel classCollectionPanel; private JList visualPanel; private DefaultListModel visual; private String className, visability = "public", returnType = "void", hierarchy = "n", selectedCreatedPanel = "class"; private int classID = 0; // determines where created methods and varables // are placed private boolean staticSelect = true, instanceB = false, methodB = false, // show // if // class, // method // or // variable // buttons // are // clicked classB = true; private JTextField cName = new JTextField(), mName = new JTextField(), vName = new JTextField(), commentReplace = new JTextField(); private JButton methodCreationSelect, classCreationSelect, // buttons to // switch // between // creating a // new class, // method or // variable instanceVariableCreationSelect; private JComboBox visableVar, staticSVar, returnTVar, visableC, hierarchyC, visableM, hierarchyM, staticSM, returnTM; // defined at class level // to allow reseting at // will private ArrayList<ProgramElements> myProgramElements = new ArrayList<ProgramElements>(); private ArrayList<SelectionButton> classSelectionButton = new ArrayList<SelectionButton>(); private ArrayList<Integer> classUniqueDefaultNameGenerator = new ArrayList<Integer>();// used // to // keep // class // names // unique private JLabel statusLabel;// used to show informational // messages private JPanel CreationCards = new JPanel(new CardLayout()); // hold the // class, // method, // variable, // and blank // creation // panels private JPanel textCards = new JPanel(new CardLayout()),// hold the class, // method, and // variable // description // panels classCollectionCards = new JPanel(new CardLayout()),// the JButtons // container for // selecting // different // created // classes classTextCards = new JPanel(new CardLayout()),// there are three // class description // panels, each with // a different // number of // JButtons ButtonCards = new JPanel(new CardLayout()),// displays weather or // not the class, // method, and variable // buttons are displayed UpdateCards = new JPanel(new CardLayout()),// different combinations // of the add, replace, // and delete buttons FinishCards = new JPanel(new CardLayout()),// changes between finish // and continue working // buttons commentTitleCards = new JPanel(new CardLayout());// generates title // of program // element being // commented private JPanel displayPanel; EventHandler eh = new EventHandler(); /** * main method for basic program builder * * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub BasicProgramBuilder bbp = new BasicProgramBuilder(); bbp.setVisible(true); } /** * constructor for basic program builder */ public BasicProgramBuilder() { setTitle("Basic Program Builder"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(1006, 800); Container cp = getContentPane(); cp.setLayout(new BorderLayout()); creationPanel = makeCreationPanel(); displayPanel = buildDisplayPanel(); buildMenu(); cp.add(creationPanel, BorderLayout.WEST); cp.add(displayPanel, BorderLayout.EAST); cName.setText("Class1"); mName.setText("method1"); vName.setText("property1"); } /* * builds the overall display panel that contains all the printed program * elements */ private JPanel buildDisplayPanel() { JPanel p = new JPanel(); visual = new DefaultListModel(); visualPanel = new JList(visual); visualPanel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); visualPanel.setSelectedIndex(0); Font f = new Font("Arial", Font.PLAIN, 20); visualPanel.setFont(f); visualPanel.addListSelectionListener(eh); visualPanel.setVisibleRowCount(40); JScrollPane listScrollPane = new JScrollPane(visualPanel); listScrollPane.setPreferredSize(new Dimension(500, 800)); p.setLayout(new BorderLayout()); p.add(listScrollPane, BorderLayout.CENTER); return p; } /* * builds the containing panel for all the creation and text panels that * display the creation controls */ private JPanel makeCreationPanel() { // TODO Auto-generated method stub JPanel p = new JPanel(); p.setPreferredSize(new Dimension(500, 800)); p.setLayout(new BorderLayout()); infoPanel = buildInfoPanel(); createClassPanel = buildCreateClassPanel(); selectionPanel = buildSelectionPanel(); createClassPanel = buildCreateClassPanel(); createMethodPanel = buildCreateMethodPanel(); createInsatcenVariablePanel = buildCreateVariablePanel(); CreationCards.add("create class panel", createClassPanel); CreationCards.add("create method panel", createMethodPanel); CreationCards.add("create instance panel", createInsatcenVariablePanel); JPanel panel = ReplaceCommentPanel(); CreationCards.add("replace comment panel", panel); p.add(infoPanel, BorderLayout.NORTH); p.add(CreationCards, BorderLayout.CENTER); p.add(selectionPanel, BorderLayout.SOUTH); JPanel pan = buildCreateNothingPanel(); CreationCards.add("no creation panel", pan); return p; } /* * builds the containing panel for the class, method, and variable * description panels */ private JPanel buildInfoPanel() { JPanel p = new JPanel(); p.setBackground(Color.darkGray); p.setPreferredSize(new Dimension(500, 300)); p.setLayout(new BorderLayout()); JPanel statusBar = createStatusBar(); classTextPanel = buildEmptyClassTextPanel(); classTextCards.add("empty class text", classTextPanel); methodTextPanel = buildMethodTextPanel(); instanceVariableTextPanel = buildVariableTextPanel(); buttonPanel = buildClassOnlyButtonPanel(); ButtonCards.add("class only button panel", buttonPanel); textCards.add("class text panel", classTextCards); textCards.add("method text panel", methodTextPanel); textCards.add("instance text panel", instanceVariableTextPanel); p.add(statusBar, BorderLayout.NORTH); p.add(textCards, BorderLayout.CENTER); p.add(ButtonCards, BorderLayout.SOUTH); buttonPanel = buildButtonPanel(); ButtonCards.add("full button panel", buttonPanel); buttonPanel = buildNoButtonPanel(); ButtonCards.add("no button panel", buttonPanel); return p; } /* * panel that displays the class, method, and variable buttons that allows * user to switch between the three creation panels */ private JPanel buildButtonPanel() { JPanel p = new JPanel(); p.setPreferredSize(new Dimension(500, 25)); p.setLayout(new BorderLayout()); classCreationSelect = new JButton("Class"); classCreationSelect.setBackground(Color.RED); classCreationSelect.addActionListener(eh); classCreationSelect.setPreferredSize(new Dimension(160, 25)); methodCreationSelect = new JButton("Method"); methodCreationSelect.setBackground(Color.green); methodCreationSelect.addActionListener(eh); methodCreationSelect.setPreferredSize(new Dimension(160, 25)); instanceVariableCreationSelect = new JButton("Variable"); instanceVariableCreationSelect.setBackground(Color.green); instanceVariableCreationSelect.addActionListener(eh); instanceVariableCreationSelect.setPreferredSize(new Dimension(180, 25)); p.add(instanceVariableCreationSelect, BorderLayout.WEST); p.add(methodCreationSelect, BorderLayout.CENTER); p.add(classCreationSelect, BorderLayout.EAST); return p; } /* * displays the class button only to show that only classes can be created * at this time */ private JPanel buildClassOnlyButtonPanel() { JPanel p = new JPanel(); p.setBackground(cColor); p.setSize(500, 50); classCreationSelect = new JButton("First Class"); classCreationSelect.setBackground(Color.RED); classCreationSelect.addActionListener(eh); p.add(classCreationSelect, BorderLayout.CENTER); return p; } /* * panel that removes any button to show that the period for creating * classes, methods, and variables has ended */ private JPanel buildNoButtonPanel() { JPanel p = new JPanel(); p.setBackground(cColor); p.setSize(500, 50); return p; } /* * builds class description panel that contains both the main method button * and default constructor button */ private JPanel buildFullClassTextPanel() { JPanel p = new JPanel(); p.setSize(500, 200); JButton main = new JButton("main method"); JButton defaultC = new JButton("default constructor"); String str = "A class is the most general representation of an object. In each \n" + "class there exists the blueprint for all the objects made from it." + "\n\nFor example if a class called bicycle was made, it would represent all" + "\nthe properties and functionality of bicycles. A single bicycle would" + "\nbe an instance of the class bicycle, an object called bicycle." + "\n\nEach class is named based on a couple of modifiers and a name\n(that is usually capitalized)." + "\n\nmodifiers \n\npublic: sets the visability of the class so that it can be accessed" + "\nby other classes.\n\nprivate: sets the visability of the class so that it can be accessed" + "\nonly by the class containing it.\n\nabstract: designates the class as a container for further,more specific" + "\n,classes thus creating a hierarchy of classes.These classes can now\nhave abstract methods.\n\n" + "final: designates the class to be the final class in the hierarchy of\nclasses." + "\n\nAn example of a common class would be:\n\npublic Class CommonClass{\n\n\n}"; JTextArea area = new JTextArea(str, 10, 35); area.setEditable(false); JScrollPane spane; spane = new JScrollPane(area); main.addActionListener(eh); defaultC.addActionListener(eh); p.add(spane); p.add(main); p.add(defaultC); p.setBackground(cColor); return p; } /* * builds class description panel that contains only the default constructor * button */ private JPanel buildConstructorClassTextPanel() { JPanel p = new JPanel(); p.setSize(500, 200); JButton defaultC = new JButton("default constructor"); defaultC.addActionListener(eh); String str = "A class is the most general representation of an object. In each \n" + "class there exists the blueprint for all the objects made from it." + "\n\nFor example if a class called bicycle was made, it would represent all" + "\nthe properties and functionality of bicycles. A single bicycle would" + "\nbe an instance of the class bicycle, an object called bicycle." + "\n\nEach class is named based on a couple of modifiers and a name\n(that is usually capitalized)." + "\n\nmodifiers \n\npublic: sets the visability of the class so that it can be accessed" + "\nby other classes.\n\nprivate: sets the visability of the class so that it can be accessed" + "\nonly by the class containing it.\n\nabstract: designates the class as a container for further,more specific" + "\n,classes thus creating a hierarchy of classes.These classes can now\nhave abstract methods.\n\n" + "final: designates the class to be the final class in the hierarchy of\nclasses." + "\n\nAn example of a common class would be:\n\npublic Class CommonClass{\n\n\n}"; JTextArea area = new JTextArea(str, 10, 35); area.setEditable(false); JScrollPane spane; spane = new JScrollPane(area); p.add(spane); p.add(defaultC); p.setBackground(cColor); return p; } /* * builds class description panel that contains no other buttons */ private JPanel buildEmptyClassTextPanel() { JPanel p = new JPanel(); p.setSize(500, 200); p.setBackground(cColor); String str = "A class is the most general representation of an object. In each \n" + "class there exists the blueprint for all the objects made from it." + "\n\nFor example if a class called bicycle was made, it would represent all" + "\nthe properties and functionality of bicycles. A single bicycle would" + "\nbe an instance of the class bicycle, an object called bicycle." + "\n\nEach class is named based on a couple of modifiers and a unique\nname (that is usually capitalized)." + "\n\nmodifiers \n\npublic: sets the visability of the class so that it can be accessed" + "\nby other classes.\n\nprivate: sets the visability of the class so that it can be accessed" + "\nonly by the class containing it.\n\nabstract: designates the class as a container for further,more specific" + "\n,classes thus creating a hierarchy of classes.These classes can now\nhave abstract methods.\n\n" + "final: designates the class to be the final class in the hierarchy of\nclasses." + "\n\nAn example of a common class would be:\n\npublic Class CommonClass{\n\n\n}"; JTextArea area = new JTextArea(str, 10, 35); area.setEditable(false); JScrollPane spane; spane = new JScrollPane(area); p.add(spane); return p; } /* * builds method description panel for when method button is clicked */ private JPanel buildMethodTextPanel() { JPanel p = new JPanel(); p.setSize(500, 200); p.setBackground(mColor); String str = "A method is a section of code within a class that carries out a\nsepecific funtion." + "the method performs its funtion when it is called\nat some point in the class simply by typing its name.\n\n" + "The method is named by defining some modifiers, a return type and\na unique name." + "\n\nmodifiers\n\npublic: sets the visability of the method so that any class can call" + "\nthis method. This method can be overridden by a class lower in a\nclass hierarchy." + "\n\nprivate: only the class containing the method may call it. Method\ncannot be overridden." + "\n\nprotected: only classes that are lower within the class hierarchy may\ncall this method." + "\n\nabstract: (only for abstract classes) defined a method who functionality\nwill be only specified in class lower in the class hierarchy\n" + "(these classes must contain these overridden methods)." + "\n\nfinal: this class cannout be overwridden by any other class, unlike\nprivate, it can be used outside its containing class, but cannot be" + "\noverridden.\n\nstatic: these methods are for classes and not for objects like the rest." + "\nthey can be called without an object being reference unlike the other\nmodifiers. They can access static data, but not instance varables." + "\n\nreturn types\nthere are many possible data types to return, but this program only\nhandles the following:" + "\n\nint: method must return data in the Integer format when it is called." + "\n\ndouble: method must return data in the double format when it is called." + "\n\nfloat: method must return data in the float format when it is called." + "\n\nString: method must return data in the String format when it is called." + "\n\nvoid: method must preform an action and does not return any data\ntype." + "\n\nnames for methods usually start with the first word uncapitalized" + "\nwith the first letter every proceeding word captialized." + "\n\nAn example of a common method would be:\n\npublic Int getInt(){\n\n}"; JTextArea area = new JTextArea(str, 10, 35); area.setEditable(false); JScrollPane spane; spane = new JScrollPane(area); p.add(spane); return p; } /* * builds variable description panel for when variable button is clicked */ private JPanel buildVariableTextPanel() { JPanel p = new JPanel(); p.setSize(500, 200); p.setBackground(varColor); String str = "Variables are the specific data that define something in a program. This" + "\ndata is stored in the form of specific data types such a integers " + "\nor strings." + "\n\nThe scope of the variable determines where it can be referenced or" + "\nchanged. This means that if a variable is created at the class level," + "\nevery part of the class has access to the variable, if it is created at" + "\nthe method level, it can only be used within that particular method." + "\n\ninstance varables define the propeties of an object, static(or class)" + "\nvariablesdefine the properties of a class." + "\n\nA variable is named by defining a visibility modifier, deciding weather" + "\nthe varable is an insatnce or static(class) variable, a data type, and" + "\na unique name." + "\n\nvisibility modifiers" + "\n\npublic: the variable can be accessed out side of its containing " + "\nclass." + "\n\nprivate: variable can only be accessed within its containing class." + "\n\nprotected: varable can be accessed by a class lower in its class" + "\nhierarchy ." + "\n\nthere are many data types for varables to be,but this program only" + "\nhandles the following: " + "\n\nString: variable is a String." + "\n\nint: variable is a integer." + "\n\ndouble: variable is a double." + "\n\nfloat: variable is a float." + "\n\nnames for methods usually start with the first word uncapitalized" + "\nwith the first letter every proceeding word captialized." + "\n\nAn example of a common variable would be:" + "\n\npublic int integerValue;"; JTextArea area = new JTextArea(str, 10, 35); JScrollPane spane; spane = new JScrollPane(area); p.add(spane); return p; } /* * builds status bar to verbally show what creation screen is being * displayed */ private JPanel createStatusBar() { JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); statusLabel = new JLabel("Create Class selected"); panel.add(statusLabel, BorderLayout.CENTER); panel.setBorder(new BevelBorder(BevelBorder.LOWERED)); return panel; } /* * builds the panel that allows the user to create variables */ private JPanel buildCreateVariablePanel() { JPanel p = new JPanel(); p.setPreferredSize(new Dimension(500, 100)); p.setBackground(varColor); p.setLayout(new GridLayout(2, 4)); JLabel visableLabel = new JLabel(" Visability"); JLabel staticLabel = new JLabel(" instance or class?"); JLabel returnLabel = new JLabel(" data type"); JLabel nameLabel = new JLabel(" name"); String[] visiabilityOptions = { "public", "private", "protected" }; String[] staticOptions = { "static", "no" }; String[] returnOptions = { "String", "int", "double", "float", }; visableVar = new JComboBox(visiabilityOptions); staticSVar = new JComboBox(staticOptions); returnTVar = new JComboBox(returnOptions); visableVar.addItemListener(this); staticSVar.addItemListener(this); returnTVar.addItemListener(this); p.add(visableLabel); p.add(staticLabel); p.add(returnLabel); p.add(nameLabel); p.add(visableVar); p.add(staticSVar); p.add(returnTVar); p.add(vName); return p; } /* * builds the panel that allows the user to create classeseate Class Panel */ private JPanel buildCreateClassPanel() { JPanel p = new JPanel(); p.setPreferredSize(new Dimension(500, 100)); p.setBackground(cColor); p.setLayout(new GridLayout(2, 3)); JLabel visableLabel = new JLabel(" Visability"); JLabel abstractLabel = new JLabel(" abstract or final modifiers"); JLabel nameLabel = new JLabel(" name"); String[] visiabilityOptions = { "public", "private" }; String[] hierarchyOptions = { "neither", "abstract", "final" }; visableC = new JComboBox(visiabilityOptions); hierarchyC = new JComboBox(hierarchyOptions); visableC.addItemListener(this); hierarchyC.addItemListener(this); p.add(visableLabel); p.add(abstractLabel); p.add(nameLabel); p.add(visableC); p.add(hierarchyC); p.add(cName); return p; } /* * builds the panel that allows the user to create methods */ private JPanel buildCreateMethodPanel() { JPanel p = new JPanel(); p.setPreferredSize(new Dimension(500, 100)); p.setBackground(mColor); p.setLayout(new GridLayout(2, 5)); JLabel visableLabel = new JLabel(" Visability"); JLabel abstractLabel = new JLabel(" other modifiers"); JLabel staticLabel = new JLabel(" static?"); JLabel returnLabel = new JLabel(" return type"); JLabel nameLabel = new JLabel(" name"); String[] visiabilityOptions = { "public", "private", "protected" }; String[] hierarchyOptions = { "neither", "abstract", "final" }; String[] staticOptions = { "static", "no" }; String[] returnOptions = { "void", "String", "int", "double", "float", }; visableM = new JComboBox(visiabilityOptions); hierarchyM = new JComboBox(hierarchyOptions); staticSM = new JComboBox(staticOptions); returnTM = new JComboBox(returnOptions); visableM.addItemListener(this); hierarchyM.addItemListener(this); staticSM.addItemListener(this); returnTM.addItemListener(this); p.add(visableLabel); p.add(abstractLabel); p.add(staticLabel); p.add(returnLabel); p.add(nameLabel); p.add(visableM); p.add(hierarchyM); p.add(staticSM); p.add(returnTM); p.add(mName); return p; } /* * builds panel that is displayed when finish is click, thus preventing any * further program elements from being created for that class */ private JPanel buildCreateNothingPanel() { JPanel p = new JPanel(); p.setBackground(cColor); p.setPreferredSize(new Dimension(500, 100)); return p; } /* * builds a specific label for when a comment is created so a user is * reminded of what they commented */ private JPanel ReplaceCommentDialog(int ID, int in) { JPanel p = new JPanel(); if (ID > 0) { int index = 0; if (in == Integer.MAX_VALUE) { index = visualPanel.getSelectedIndex(); } else { index = in; } ProgramElements rC = null; for (ProgramElements pro : myProgramElements) { if (pro.getClassID() == ID && pro.getPosition() == (index - 1)) { rC = pro; } } JLabel c = new JLabel("current comment for " + rC.getOriginalCommentName()); p.add(c); } return p; } /* * builds a text field for a user to replace a selected comment */ private JPanel ReplaceCommentPanel() { JPanel p = new JPanel(); p.setLayout(new BorderLayout()); p.setPreferredSize(new Dimension(500, 100)); JPanel pan = ReplaceCommentDialog(0, 0); commentTitleCards.add("0defualt0", pan); commentReplace = new JTextField(); p.add(commentReplace, BorderLayout.CENTER); p.add(commentTitleCards, BorderLayout.NORTH); return p; } /* * builds a containing panel of all the created classes selection buttons, * update buttons, and finish or continue working buttons */ private JPanel buildSelectionPanel() { JPanel p = new JPanel(); p.setPreferredSize(new Dimension(500, 400)); p.setBackground(Color.lightGray); p.setLayout(new BorderLayout()); classPanel = buildClassPanel(); JScrollPane cSpane = new JScrollPane(classPanel); cSpane.setPreferredSize(new Dimension(500, 350)); classCollectionCards.add("classPanel", cSpane); classUpdatePanel = buildAddOnlyUpdateClassPanel(); UpdateCards.add("add only update panel", classUpdatePanel); JPanel pan = Finishbutton(); FinishCards.add("finish button", pan); p.add(UpdateCards, BorderLayout.NORTH); p.add(FinishCards, BorderLayout.SOUTH); p.add(classCollectionCards, BorderLayout.CENTER); classUpdatePanel = buildNoReplaceUpdateClassPanel(); UpdateCards.add("no replace update panel", classUpdatePanel); classUpdatePanel = buildUpdateClassPanel(); UpdateCards.add("full update panel", classUpdatePanel); classUpdatePanel = buildExportUpdateClassPanel(); UpdateCards.add("add export update panel", classUpdatePanel); classUpdatePanel = buildUpdateReplaceDeletePanel(); UpdateCards.add("replace and delete panel", classUpdatePanel); JPanel c = ContinueWorkButton(); FinishCards.add("continue working", c); return p; } /* * creates a finish button at the bottom of the creation panel that allows * the user to complete their class and export it ,this prevents the user * from making changes to the class */ private JPanel Finishbutton() { JPanel p = new JPanel(); p.setPreferredSize(new Dimension(500, 50)); JButton finish = new JButton("finish"); finish.setPreferredSize(new Dimension(500, 30)); finish.setBackground(Color.orange); finish.addActionListener(eh); p.add(finish); return p; } /* * creates a continue work button at the bottom of the creation panel that * allows the user to un-finish the class and make changes to it, this * prevents the user from exporting the class */ private JPanel ContinueWorkButton() { JPanel p = new JPanel(); p.setPreferredSize(new Dimension(500, 50)); JButton con = new JButton("continue working"); con.setPreferredSize(new Dimension(500, 30)); con.setBackground(Color.orange); con.addActionListener(eh); p.add(con); return p; } /* * builds the collection of created classes selection buttons to allow the * user to switch between their classes */ private JPanel buildClassPanel() { JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); for (SelectionButton s : classSelectionButton) { s.setMaximumSize(new Dimension(500, 35)); s.setBackground(cColor); s.addActionListener(eh); p.add(s); } return p; } /* * builds the update panel with the add, delete and replace button visible * valid only in certain circumstances, such as if a class is selected and * the class button is clicked or if a method or variable is selected and * the method or variable button is clicked */ private JPanel buildUpdateClassPanel() { JPanel p = new JPanel(); p.setLayout(new BorderLayout()); p.setPreferredSize(new Dimension(500, 50)); JButton add = new JButton("Add!"); add.setBackground(Color.cyan); add.addActionListener(eh); JButton delete = new JButton("delete"); delete.setBackground(Color.pink); delete.addActionListener(eh); delete.setPreferredSize(new Dimension(150, 25)); add.setPreferredSize(new Dimension(170, 25)); JButton replace = new JButton("replace"); replace.setBackground(Color.magenta); replace.addActionListener(eh); replace.setPreferredSize(new Dimension(160, 25)); classCollectionPanel = buildClassCollectionPanel(); p.add(add, BorderLayout.EAST); p.add(delete, BorderLayout.CENTER); p.add(replace, BorderLayout.WEST); p.add(classCollectionPanel, BorderLayout.SOUTH); return p; } /* * builds update panel that only has the delete and replace buttons visible * this is for when a comment is selected in the display panel */ private JPanel buildUpdateReplaceDeletePanel() { JPanel p = new JPanel(); p.setLayout(new BorderLayout()); JButton delete = new JButton("delete"); delete.setBackground(Color.pink); delete.addActionListener(eh); delete.setPreferredSize(new Dimension(250, 25)); JButton replace = new JButton("replace"); replace.setBackground(Color.magenta); replace.addActionListener(eh); replace.setPreferredSize(new Dimension(250, 25)); classCollectionPanel = buildClassCollectionPanel(); p.add(delete, BorderLayout.CENTER); p.add(replace, BorderLayout.WEST); p.add(classCollectionPanel, BorderLayout.SOUTH); return p; } /* * builds the update panel with only the add button, this is used when there * are no existing program elements */ private JPanel buildAddOnlyUpdateClassPanel() { JPanel p = new JPanel(); p.setLayout(new BorderLayout()); p.setPreferredSize(new Dimension(500, 50)); JButton add = new JButton("Add!"); add.setBackground(Color.cyan); add.addActionListener(eh); add.setPreferredSize(new Dimension(500, 50)); p.add(add, BorderLayout.EAST); classCollectionPanel = buildClassCollectionPanel(); p.add(classCollectionPanel, BorderLayout.SOUTH); return p; } /* * update panel that only contains an add and delete button used in the case * when the a class is highlighted on the visual panel but the variable or * method button are clicked or in the instance that a variable or method is * highlighted on the visual panel and the class button is selected this * prevents a user from breaking the format of class on top and below and * methods and variables within */ private JPanel buildNoReplaceUpdateClassPanel() { JPanel p = new JPanel(); p.setLayout(new BorderLayout()); p.setPreferredSize(new Dimension(500, 50)); JButton add = new JButton("Add!"); add.setBackground(Color.cyan); add.addActionListener(eh); JButton delete = new JButton("delete"); delete.setBackground(Color.pink); delete.addActionListener(eh); delete.setPreferredSize(new Dimension(250, 25)); add.setPreferredSize(new Dimension(250, 25)); classCollectionPanel = buildClassCollectionPanel(); p.add(add, BorderLayout.EAST); p.add(delete, BorderLayout.CENTER); p.add(classCollectionPanel, BorderLayout.SOUTH); return p; } /* * replaces the update panel with an export current button when the user * clicks finish */ private JPanel buildExportUpdateClassPanel() { JPanel p = new JPanel(); p.setLayout(new BorderLayout()); p.setPreferredSize(new Dimension(500, 50)); JButton ex = new JButton("Export Current"); ex.setBackground(Color.yellow); ex.addActionListener(eh); ex.setPreferredSize(new Dimension(500, 25)); classCollectionPanel = buildClassCollectionPanel(); p.add(ex, BorderLayout.CENTER); p.add(classCollectionPanel, BorderLayout.SOUTH); return p; } /* * displays the the label for class button selection */ private JPanel buildClassCollectionPanel() { JPanel p = new JPanel(); p.setPreferredSize(new Dimension(500, 25)); JLabel cL = new JLabel("Saved Classes"); p.add(cL); return p; } /* * builds the menu of the basic program builder with three Jmenu options * file menu, export menu, and extra menu */ private void buildMenu() { JMenuBar menuBar = new JMenuBar(); JMenu exportMenu = buildexportMenu(); JMenu OptionsMenu = buildOptionsMenu(); JMenu fileMenu = buildFileMenu(); menuBar.add(fileMenu); menuBar.add(exportMenu); menuBar.add(OptionsMenu); setJMenuBar(menuBar); } /* * builds the menu options under the extra menu button this is the add * comment feature */ private JMenu buildOptionsMenu() { JMenu oM = new JMenu("Extra"); JMenuItem menuItem = new JMenuItem("add comment"); menuItem.addActionListener(eh); oM.add(menuItem); return oM; } /* * builds the menu options under the export menu button these are export * current, and export all */ private JMenu buildexportMenu() { JMenu exportMenu = new JMenu("Export"); JMenuItem menuItem = new JMenuItem("Export Current"); menuItem.addActionListener(eh); exportMenu.add(menuItem); menuItem = new JMenuItem("Export All"); menuItem.addActionListener(eh); exportMenu.add(menuItem); return exportMenu; } /* * builds the menu options under the file menu button these options are new, * save, load, and exit */ private JMenu buildFileMenu() { JMenu fileMenu = new JMenu("File"); JMenuItem menuItem = new JMenuItem("New"); menuItem.addActionListener(eh); fileMenu.add(menuItem); menuItem = new JMenuItem("Open"); menuItem.addActionListener(eh); fileMenu.add(menuItem); menuItem = new JMenuItem("Save"); menuItem.addActionListener(eh); fileMenu.add(menuItem); menuItem = new JMenuItem("Exit"); menuItem.addActionListener(eh); fileMenu.add(menuItem); return fileMenu; } /* * sets all the card layouts to display the finished selected class */ private void ShowFinishMode() { ((CardLayout) classCollectionCards.getLayout()).show( classCollectionCards, "new classes"); ((CardLayout) UpdateCards.getLayout()).show(UpdateCards, "add export update panel"); ((CardLayout) FinishCards.getLayout()).show(FinishCards, "continue working"); ((CardLayout) ButtonCards.getLayout()).show(ButtonCards, "no button panel"); ((CardLayout) CreationCards.getLayout()).show(CreationCards, "no creation panel"); ((CardLayout) textCards.getLayout()) .show(textCards, "class text panel"); ((CardLayout) classTextCards.getLayout()).show(classTextCards, "empty class text"); } /* * reads an object file and returns an array list of all the program * elements */ private ArrayList<ProgramElements> loadFile() throws IOException { ArrayList<ProgramElements> p = null; JFileChooser fileSelect = new JFileChooser(); int returnvalue = fileSelect.showOpenDialog(null); if (returnvalue == JFileChooser.APPROVE_OPTION) { File file = fileSelect.getSelectedFile(); FileInputStream fis; try { fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis); // read object from object input stream Object o = ois.readObject(); // cast object correctly p = (ArrayList<ProgramElements>) o; } catch (FileNotFoundException e) { System.out.println("File not found"); e.printStackTrace(); } catch (IOException e) { System.out.println("Problems reading file"); e.printStackTrace(); } catch (ClassNotFoundException e) { System.out.println("Class information not found"); e.printStackTrace(); } } return p; } /* * allows user to save their program elements as an object file, name and * location is determined by user * * @throws IOException */ private void saveFile() throws IOException { JFileChooser fileSelect = new JFileChooser(); int returnvalue = fileSelect.showSaveDialog(null); if (returnvalue == JFileChooser.APPROVE_OPTION) { File file = fileSelect.getSelectedFile(); try { FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos); // write object (i.e. state of object) to object output stream oos.writeObject(myProgramElements); } catch (FileNotFoundException e) { System.out.println("File not found"); e.printStackTrace(); } catch (IOException e) { System.out.println("Problems writing file!"); e.printStackTrace(); } } } /* * checks method and variable names to be unique within their selected class * * @param name * @param type * @return weather or not the name already exists in the selected class */ private boolean checkForUniqueName(String name, String type) { for (ProgramElements p : myProgramElements) { if (p.getName().equals(name) && p.getClassID() == classID && p.getType().equals(type)) { return false; } } return true; } /* * re orders the program elements fist by class id and then by the position * of the object in the JList to make saving, loading and exporting much * easier since all the elements are always in order. */ private void reOrderMyProgams() { int numberOfClasses = 0; int index = 0; for (ProgramElements p : myProgramElements) { if (p.getType().equals("class") && p.isfinished() == false) { numberOfClasses++; } } int max = 0; for (ProgramElements p : myProgramElements) { if (p.getPosition() > max) { max = p.getPosition(); } } ArrayList<ProgramElements> tempProgram = new ArrayList<ProgramElements>(); ArrayList<ProgramElements> tempProgramClassID = new ArrayList<ProgramElements>(); ArrayList<ProgramElements> tempProgramPos = new ArrayList<ProgramElements>(); int[] classIDs = new int[numberOfClasses]; int[] numberOfPositions = new int[numberOfClasses]; for (ProgramElements p : myProgramElements) { // get all existing class // ids if (p.getPosition() == 0) { classIDs[index] = p.getClassID(); index++; } } for (int i = 0; i < numberOfPositions.length; i++) { // get how many // elements are // in each class int size = 0; for (ProgramElements p : myProgramElements) { if (p.getClassID() == classIDs[i]) { size++; } } numberOfPositions[i] = size; } int p = 0; while (p < numberOfClasses) { int count = 0; int pos = 0; for (ProgramElements pro : myProgramElements) { // get all the // elements with the // same class ids if (pro.getClassID() == classIDs[p]) { tempProgramClassID.add(pro); count++; } } if (count == numberOfPositions[p]) { while (pos < numberOfPositions[p]) { // reorder the specific // class by the position // values of the // elements for (ProgramElements t : tempProgramClassID) { if (t.getPosition() == pos) { tempProgramPos.add(t); pos++; } } } } if (pos == numberOfPositions[p]) { // add the reordered elemnts to a // temp array for (ProgramElements t : tempProgramPos) { tempProgram.add(t); } tempProgramClassID = new ArrayList<ProgramElements>(); tempProgramPos = new ArrayList<ProgramElements>(); p++; } } myProgramElements = new ArrayList<ProgramElements>(); // emtpy array // list for (ProgramElements t : tempProgram) { // place the sorted array back // into the array list myProgramElements.add(t); } } /* * generates a unique name for each class, method, and variable, by checking * the class name array list and the variable and method vales saved on the * selected class */ private void resetTextField() { int numberOfSpecificMethods = 1; for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.getType().equals("class") && p.isfinished() == false) { numberOfSpecificMethods = p.getHighestMethod(); } } int numberOfSpecificVariables = 1; for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.getType().equals("class") && p.isfinished() == false) { numberOfSpecificVariables = p.getHighestVariable(); } } mName.setText("method" + numberOfSpecificMethods); cName.setText("Class" + (classUniqueDefaultNameGenerator .get(classUniqueDefaultNameGenerator.size() - 1) + 1)); vName.setText("property" + numberOfSpecificVariables); } /* * handles all the button clicks and list changes for the basic program * builder */ private class EventHandler implements ActionListener, ListSelectionListener { /** * method to handle all the JButtons being clicked add will create a new * class, method or variable based on the class, method or variable button * being clicked. * replace allows class names and modifiers to replace currently selected one, * a method or variable with a method or variable, and comments with other * comments, if a commented method or variable is replaced, its comment will * be deleted * the class, method, and variable buttons change the creation screens and force every * other action to be based around their selected program element * delete, will delete individual methods, variables, and comments,but will remove * all the program elements of a class that is deleted, if a method or variable is * commented, its comment will also be deleted. * finish will create an ending bracket at the end of the class and allow user to export * the class * continue working removes the bracket and allows user to continue editing the class, but * can no longer export * export current exports the currently selected class * export all exports all classes * new erases all the program elements and recreates the opening view form the program * save allows the user to save their work to an object file * open reads in an object file and populated the display panel with the first class and all * appropriate selection buttons * clicking a selection button populates the display panel with all the program elements of the * selected class * add comment allows the user to add one comment to a variable or method * */ public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals("Add!")) { int index = visualPanel.getSelectedIndex(); // get selected // index if (index == -1) { // no selection, so insert at beginning index = 0; } else { // add after the selected item index++; } if (selectedCreatedPanel.equals("class")) { ((CardLayout) UpdateCards.getLayout()).show(UpdateCards, "full update panel"); int count = 1; for (ProgramElements p : myProgramElements) { if (p.getType().equals("class")) count++; } index = 0; String n = cName.getText(); int checkName = 0; if (count > 1) { for (ProgramElements p : myProgramElements) { if (p.getName().equals(n)) { checkName++; } } } className = n; if (checkName == 0) { Class c = new Class(visability, hierarchy, className); c.setClassID(count); classID = count; SelectionButton b = new SelectionButton(c.getName()); classSelectionButton.add(b); myProgramElements.add(c); if (c.getClassID() == 1) { ((CardLayout) ButtonCards.getLayout()).show( ButtonCards, "full button panel"); } classPanel = buildClassPanel(); JScrollPane cSpane = new JScrollPane(classPanel); cSpane.setPreferredSize(new Dimension(500, 400)); classCollectionCards.add("new classes", cSpane); ((CardLayout) classCollectionCards.getLayout()).show( classCollectionCards, "new classes"); visual.clear(); c.setPosition(index); classUniqueDefaultNameGenerator.add(c.getClassID()); visual.insertElementAt(c.printToList(), index); classTextPanel = buildFullClassTextPanel(); classTextCards.add("full text panel", classTextPanel); ((CardLayout) classTextCards.getLayout()).show( classTextCards, "full text panel"); classTextPanel = buildConstructorClassTextPanel(); classTextCards.add("constructor text panel", classTextPanel); } else JOptionPane .showMessageDialog(null, "each class in your program must have a unique name"); } else if (selectedCreatedPanel.equals("method")) { String n = mName.getText(); className = n; if (checkForUniqueName(n, "method")) { Method m = new Method(visability, hierarchy, returnType, className, staticSelect); if (classID == 0) { m.setClassID(1); } else { m.setClassID(classID); } ProgramElements classOfMethod = null; for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.getType().equals("class") && p.isfinished() == false) { classOfMethod = p; } } classOfMethod.setHighestMethod(1); myProgramElements.add(m); m.setPosition(index); for (ProgramElements p : myProgramElements) { if ((p.getPosition() == m.getPosition() || p .getPosition() > m.getPosition()) && p != m && p.getClassID() == classID) { p.setPosition(p.getPosition() + 1); } } visual.insertElementAt(m.printToList(), index); } else { ProgramElements className = null; for (ProgramElements p : myProgramElements) { if (p.getType().equals("class") && p.getClassID() == classID) { className = p; } } JOptionPane.showMessageDialog(null, "You must have a unique name for every method in " + className.getName()); } } else if (selectedCreatedPanel.equals("instance")) { String n = vName.getText(); className = n; if (checkForUniqueName(n, "instance")) { Variable iV = new Variable(visability, staticSelect, returnType, className); if (classID == 0) { iV.setClassID(1); } else { iV.setClassID(classID); } myProgramElements.add(iV); ProgramElements classOfVariable = null; for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.getType().equals("class") && p.isfinished() == false) { classOfVariable = p; } } classOfVariable.setHighestVariable(1); iV.setPosition(index); for (ProgramElements p : myProgramElements) { if ((p.getPosition() == iV.getPosition() || p .getPosition() > iV.getPosition()) && p != iV && p.getClassID() == classID) { p.setPosition(p.getPosition() + 1); } } visual.insertElementAt(iV.printToList(), index); } else { ProgramElements className = null; for (ProgramElements p : myProgramElements) { if (p.getType().equals("class") && p.getClassID() == classID) { className = p; } } JOptionPane.showMessageDialog(null, "You must have a unique name for every variable in " + className.getName()); } } reOrderMyProgams(); visualPanel.setSelectedIndex(index); int classCount = 1; int methodCount = 1; int variableCount = 1; for (ProgramElements p : myProgramElements) { if (p.getPosition() == 0) { classCount++; } if (p.getType().equals("method") && p.getClassID() == classID) { methodCount++; } if (p.getType().equals("instance") && p.getClassID() == classID) { variableCount++; } } resetTextField(); } else if (s.equals("replace")) { int index = visualPanel.getSelectedIndex(); int commentCheck = 0; ProgramElements selectedp = null; ProgramElements classOfReplacement = null; for (ProgramElements p : myProgramElements) { if (p.getPosition() == index && p.getClassID() == classID) { selectedp = p; } } for (ProgramElements p : myProgramElements) { if (p.getClassID() == selectedp.getClassID() && p.getType().equals("class")) { classOfReplacement = p; } } if (selectedp.isComment()) { //replaces comment with other comment visual.clear(); String comment = commentReplace.getText(); selectedp.setComment(comment); for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID) { visual.insertElementAt(p.printToList(), p.getPosition()); } } } else if (selectedp.getType().equals("class")) {//replaces class data with new class data SelectionButton cB = null; for (SelectionButton sel : classSelectionButton) { if (sel.getText().equals(selectedp.getName())) { cB = sel; } } String name = cName.getText(); int nameCheck = 0; for (ProgramElements p : myProgramElements) { if (p.getName().equals(name)) { nameCheck++; } } if (nameCheck == 0) { selectedp.setName(name); selectedp.setHierarchy(hierarchy); selectedp.setVisability(visability); cB.setName(name); cB.setText(name); visual.remove(index); visual.insertElementAt(selectedp.printToList(), index); } else { JOptionPane.showMessageDialog(null, "every class in a program \n" + "must have a unique name"); } } else if (selectedp.getType().equals("method")) { selectedp.removedComment(); if (methodB == true) {//replaces method with other method ProgramElements comment = null; for (ProgramElements p : myProgramElements) { if (p.getName().equals( selectedp.getName() + "c" + selectedp.getClassID())) { commentCheck++; comment = p; } else if (p.getName().equals( selectedp.getClassName() + "'s main method" + "c" + selectedp.getClassID()) //if replacing main method && selectedp.isMain()) { commentCheck++; comment = p; } else if (p.getName().equals( selectedp.getClassName() + "'s default Constructor" + selectedp.getPosition() + "c" + selectedp.getClassID()) //if replacing default constructor && p.isConstructor()) { commentCheck++; comment = p; } } if (comment != null) { visual.remove(comment.getPosition()); myProgramElements.remove(comment); } String name = mName.getText(); if (checkForUniqueName(name, "method")) { selectedp.setName(name); selectedp.setStatic(staticSelect); selectedp.setReturnType(returnType); selectedp.setVisability(visability); selectedp.setHierarchy(hierarchy); selectedp.setPosition(selectedp.getPosition() - commentCheck); if (selectedp.isMain()) { classOfReplacement.addMain(false); ((CardLayout) classTextCards.getLayout()).show( classTextCards, "full text panel"); } for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.getPosition() > selectedp .getPosition()) { p.setPosition(p.getPosition() - commentCheck); } } if (selectedp.isMain()) { selectedp.removeMain(); ProgramElements classOfMethod = null; for (ProgramElements p : myProgramElements) { if (p.getType().equals("class") && p.getClassID() == classID && p.isfinished() == false) { classOfMethod = p; } } classOfMethod.setHighestMethod(1); resetTextField(); } reOrderMyProgams(); visual.clear(); checkClassTextCorrectness(); for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID) { visual.insertElementAt(p.printToList(), p.getPosition()); } } } else { JOptionPane .showMessageDialog( null, "every method name must be unique\n" + " withing their respective class"); } } else if (instanceB == true) { //replaces method with variable ProgramElements comment = null; for (ProgramElements p : myProgramElements) { if (p.getName().equals( selectedp.getName() + "c" + selectedp.getClassID())) { commentCheck++; comment = p; } else if (p.getName().equals( selectedp.getClassName() + "'s main method" + "c" + selectedp.getClassID()) //if replacing main method && selectedp.isMain()) { commentCheck++; comment = p; } else if (p.getName().equals( selectedp.getClassName() + "'s default Constructor" + selectedp.getPosition() + "c" + selectedp.getClassID())//if replacing default constructor && p.isConstructor()) { commentCheck++; comment = p; } } if (comment != null) { visual.remove(comment.getPosition()); myProgramElements.remove(comment); } String n = vName.getText(); className = n; if (checkForUniqueName(n, "instance")) { int id = selectedp.getClassID(); myProgramElements.remove(selectedp); Variable i = new Variable(visability, staticSelect, returnType, className); i.setClassID(id); i.setPosition(index - commentCheck); myProgramElements.add(i); for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.getPosition() > i.getPosition()) { p.setPosition(p.getPosition() - commentCheck); } } reOrderMyProgams(); visual.clear(); checkClassTextCorrectness(); for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID) { visual.insertElementAt(p.printToList(), p.getPosition()); } } } else { JOptionPane .showMessageDialog( null, "every variable name must be unique\n" + " withing their respective class"); } } } else if (selectedp.getType().equals("instance")) { //replaces variable with new variable selectedp.removedComment(); if (instanceB == true) { ProgramElements comment = null; for (ProgramElements p : myProgramElements) { if (p.getName().equals( selectedp.getName() + "c" + selectedp.getClassID())) { commentCheck++; comment = p; } } if (comment != null) { visual.remove(comment.getPosition()); myProgramElements.remove(comment); } String name = vName.getText(); if (checkForUniqueName(name, "instance")) { selectedp.setName(name); selectedp.setStatic(staticSelect); selectedp.setReturnType(returnType); selectedp.setVisability(visability); selectedp.setPosition(selectedp.getPosition() - commentCheck); for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.getPosition() > selectedp .getPosition()) { p.setPosition(p.getPosition() - commentCheck); } } reOrderMyProgams(); visual.clear(); checkClassTextCorrectness(); for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID) { visual.insertElementAt(p.printToList(), p.getPosition()); } } } else { JOptionPane .showMessageDialog( null, "every variable name must be unique\n" + " withing their respective class"); } } else if (methodB == true) { //replaces variable with method int id = selectedp.getClassID(); ProgramElements comment = null; for (ProgramElements p : myProgramElements) { if (p.getName().equals( selectedp.getName() + "c" + selectedp.getClassID())) { commentCheck++; comment = p; } } if (comment != null) { visual.remove(comment.getPosition()); myProgramElements.remove(comment); } myProgramElements.remove(selectedp); String n = mName.getText(); if (checkForUniqueName(n, "method")) { className = n; Method m = new Method(visability, hierarchy, returnType, className, staticSelect); m.setClassID(id); m.setPosition(index - commentCheck); myProgramElements.add(m); for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.getPosition() > m.getPosition()) { p.setPosition(p.getPosition() - commentCheck); } } reOrderMyProgams(); visual.clear(); checkClassTextCorrectness(); for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID) { visual.insertElementAt(p.printToList(), p.getPosition()); } } } } System.out.println(commentCheck); resetTextField(); } else { JOptionPane.showMessageDialog(null, "every method name must be unique\n" + " withing their respective class"); } visualPanel.setSelectedIndex(index - commentCheck); } else if (s.equals("Class")) { int index = visualPanel.getSelectedIndex(); classB = true; instanceB = false; methodB = false; visableC.setSelectedIndex(0); hierarchyC.setSelectedIndex(0); resetTextField(); visability = "public"; hierarchy = "n"; selectedCreatedPanel = "class"; int commentCheck = 0; for (ProgramElements p : myProgramElements) { if (p.getPosition() == index && p.getClassID() == classID && p.isComment()) { commentCheck++; } } if (commentCheck == 0) { if (index == 0) { ((CardLayout) UpdateCards.getLayout()).show( UpdateCards, "full update panel"); } else { ((CardLayout) UpdateCards.getLayout()).show( UpdateCards, "no replace update panel"); } ((CardLayout) CreationCards.getLayout()).show( CreationCards, "create class panel"); } methodCreationSelect.setBackground(Color.green); classCreationSelect.setBackground(Color.RED); instanceVariableCreationSelect.setBackground(Color.green); ((CardLayout) textCards.getLayout()).show(textCards, "class text panel"); selectedCreatedPanel = "class"; statusLabel.setText("Create Class Selected"); for (SelectionButton b : classSelectionButton) { b.setBackground(cColor); } checkClassTextCorrectness(); } else if (s.equals("Method")) { for (SelectionButton b : classSelectionButton) { b.setBackground(mColor); } resetTextField(); visability = "public"; returnType = "void"; hierarchy = "n"; staticSelect = true; int index = visualPanel.getSelectedIndex(); classB = false; instanceB = false; methodB = true; visableM.setSelectedIndex(0); hierarchyM.setSelectedIndex(0); staticSM.setSelectedIndex(0); returnTM.setSelectedIndex(0); int commentCheck = 0; for (ProgramElements p : myProgramElements) { if (p.getPosition() == index && p.getClassID() == classID && p.isComment()) { commentCheck++; } } if (commentCheck == 0) { if (index > 0) { ((CardLayout) UpdateCards.getLayout()).show( UpdateCards, "full update panel"); } else { ((CardLayout) UpdateCards.getLayout()).show( UpdateCards, "no replace update panel"); } ((CardLayout) CreationCards.getLayout()).show( CreationCards, "create method panel"); } methodCreationSelect.setBackground(Color.RED); classCreationSelect.setBackground(Color.green); instanceVariableCreationSelect.setBackground(Color.green); ((CardLayout) textCards.getLayout()).show(textCards, "method text panel"); selectedCreatedPanel = "method"; statusLabel.setText("Create Method Selected"); } else if (s.equals("Variable")) { visability = "public"; returnType = "string"; staticSelect = true; resetTextField(); visableVar.setSelectedIndex(0); staticSVar.setSelectedIndex(0); returnTVar.setSelectedIndex(0); int index = visualPanel.getSelectedIndex(); classB = false; instanceB = true; methodB = false; int commentCheck = 0; for (ProgramElements p : myProgramElements) { if (p.getPosition() == index && p.getClassID() == classID && p.isComment()) { commentCheck++; } } if (commentCheck == 0) { if (index > 0) { ((CardLayout) UpdateCards.getLayout()).show( UpdateCards, "full update panel"); } else { ((CardLayout) UpdateCards.getLayout()).show( UpdateCards, "no replace update panel"); } ((CardLayout) CreationCards.getLayout()).show( CreationCards, "create instance panel"); } methodCreationSelect.setBackground(Color.green); classCreationSelect.setBackground(Color.green); instanceVariableCreationSelect.setBackground(Color.RED); for (SelectionButton b : classSelectionButton) { b.setBackground(varColor); } ((CardLayout) textCards.getLayout()).show(textCards, "instance text panel"); statusLabel.setText("Create Variable Selected"); selectedCreatedPanel = "instance"; } else if (s.equals("delete")) { int index = visualPanel.getSelectedIndex(); int commentCheck = 0; ProgramElements deleteP = null; for (ProgramElements p : myProgramElements) { if (p.getPosition() == index && p.getClassID() == classID) { deleteP = p; } } if (deleteP.isComment()) { ProgramElements commentItem = null; for (ProgramElements p : myProgramElements) { if (p.getName() .equals(deleteP.getOriginalCommentName())) { commentItem = p; } } commentItem.removedComment(); } int id = deleteP.getClassID(); if (deleteP.getType().equals("class")) { SelectionButton sB = null; for (SelectionButton sel : classSelectionButton) { if (sel.getText().equals(deleteP.getName())) { sB = sel; } } int lastClass = 0; int classIDCheck = deleteP.getClassID(); for (ProgramElements p : myProgramElements) { if (deleteP.getClassID() == p.getClassID()) { lastClass++; } } classSelectionButton.remove(sB); classPanel = buildClassPanel(); JScrollPane cSpane = new JScrollPane(classPanel); cSpane.setPreferredSize(new Dimension(500, 400)); classCollectionCards.add("new classes", cSpane); ((CardLayout) classCollectionCards.getLayout()).show( classCollectionCards, "new classes"); Iterator<ProgramElements> it = myProgramElements.iterator(); while (it.hasNext()) { //id a class is deleted , all its elements must also be deleted ProgramElements p = it.next(); if (p.getClassID() == deleteP.getClassID()) { it.remove(); } } visual.clear(); int stop = 0; for (ProgramElements p : myProgramElements) { if (p.getClassID() < classIDCheck) { classIDCheck = p.getClassID(); stop++; } else if (p.getClassID() > classIDCheck && stop == 0) { classIDCheck = p.getClassID(); stop++; } } for (ProgramElements p : myProgramElements) { if (p.getClassID() == classIDCheck) { visual.insertElementAt(p.printToList(), p.getPosition()); visualPanel.setSelectedIndex(p.getPosition()); } } if (classB == true) { checkClassTextCorrectness(); ((CardLayout) CreationCards.getLayout()).show( CreationCards, "create class panel"); ((CardLayout) textCards.getLayout()).show(textCards, "class text panel"); for (SelectionButton button : classSelectionButton) { button.setBackground(cColor); } } else if (methodB == true) { ((CardLayout) CreationCards.getLayout()).show( CreationCards, "create method panel"); ((CardLayout) textCards.getLayout()).show(textCards, "method text panel"); for (SelectionButton button : classSelectionButton) { button.setBackground(mColor); } } else if (instanceB == true) { ((CardLayout) textCards.getLayout()).show(textCards, "instance text panel"); ((CardLayout) CreationCards.getLayout()).show( CreationCards, "create instance panel"); for (SelectionButton button : classSelectionButton) { button.setBackground(varColor); } } classID = classIDCheck; } else if (deleteP.getType().equals("method")) { visual.clear(); if (deleteP.isMain()) { for (ProgramElements p : myProgramElements) { if (p.getClassID() == deleteP.getClassID() && p.getType().equals("class")) { p.addMain(false); ((CardLayout) classTextCards.getLayout()).show( classTextCards, "full text panel"); } } } commentCheck = 0; ProgramElements comment = null; for (ProgramElements p : myProgramElements) { if (p.isComment() && p.getPosition() == (deleteP.getPosition() - 1) && p.getClassID() == deleteP.getClassID()) { comment = p; commentCheck++; } } if (comment != null) { myProgramElements.remove(comment); } myProgramElements.remove(deleteP); for (ProgramElements p : myProgramElements) { if (p.getClassID() == id) { if (p.getPosition() > index) { p.setPosition(p.getPosition() - (1 + commentCheck)); } visual.insertElementAt(p.printToList(), p.getPosition()); } } } else if (deleteP.getType().equals("instance")) { commentCheck = 0; ProgramElements comment = null; for (ProgramElements p : myProgramElements) { if (p.getName().equals( deleteP.getName() + "c" + deleteP.getClassID())) { comment = p; commentCheck++; } } if (comment != null) { myProgramElements.remove(comment); } visual.clear(); myProgramElements.remove(deleteP); for (ProgramElements p : myProgramElements) { if (p.getClassID() == id && p.getPosition() > index) { p.setPosition(p.getPosition() - (1 + commentCheck)); } visual.insertElementAt(p.printToList(), p.getPosition()); } } if (myProgramElements.size() == 0) { //show beginning screen if everything is deleted ((CardLayout) classTextCards.getLayout()).show( classTextCards, "empty class text"); ((CardLayout) UpdateCards.getLayout()).show(UpdateCards, "add only update panel"); ((CardLayout) ButtonCards.getLayout()).show(ButtonCards, "class only button panel"); ((CardLayout) CreationCards.getLayout()).show( CreationCards, "create class panel"); ((CardLayout) textCards.getLayout()).show(textCards, "class text panel"); selectedCreatedPanel = "class"; classB = true; methodB = false; instanceB = false; } resetTextField(); visualPanel.setSelectedIndex(index - (1 + commentCheck)); } else if (s.equals("finish")) { if (myProgramElements.size() == 0) { // make sure class exists JOptionPane .showMessageDialog(null, "you must first create a class before you can finish it!"); } else { for (SelectionButton selec : classSelectionButton) { selec.setBackground(cColor); } int index = 0; ProgramElements currentClass = null; for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.getType().equals("class")) { currentClass = p; } if (p.getClassID() == classID) { index++; } } Class c = new Class(true, currentClass.getName(), currentClass.getClassID()); c.setPosition(index); myProgramElements.add(c); visual.insertElementAt(c.printToList(), index); ShowFinishMode(); } } else if (s.equals("main method")) { int index = visualPanel.getSelectedIndex(); ProgramElements currentPro = null; for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.getType().equals("class")) { currentPro = p; } } Method main = new Method("m", currentPro.getName()); main.setPosition(index + 1); currentPro.addMain(true); main.setClassID(currentPro.getClassID()); myProgramElements.add(main); ((CardLayout) classTextCards.getLayout()).show(classTextCards, "constructor text panel"); visual.insertElementAt(main.printToList(), index + 1); for (ProgramElements p : myProgramElements) { if ((p.getPosition() == main.getPosition() || p.getPosition() > main .getPosition()) && p != main && p.getClassID() == classID) { p.setPosition(p.getPosition() + 1); } } reOrderMyProgams(); visualPanel.setSelectedIndex(index + 1); } else if (s.equals("default constructor")) { int index = visualPanel.getSelectedIndex(); ProgramElements currentPro = null; for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.getType().equals("class")) { currentPro = p; } } Method cons = new Method("c", currentPro.getName()); cons.setPosition(index + 1); cons.setClassID(currentPro.getClassID()); myProgramElements.add(cons); for (ProgramElements p : myProgramElements) { if ((p.getPosition() == cons.getPosition() || p.getPosition() > cons .getPosition()) && p != cons && p.getClassID() == classID) { p.setPosition(p.getPosition() + 1); } } visual.insertElementAt(cons.printToList(), index + 1); reOrderMyProgams(); visualPanel.setSelectedIndex(index + 1); } else if (s.equals("First Class")) { JOptionPane.showMessageDialog(null, "select the parameters for your first class \n" + "and click add to begin"); } else if (s.equals("Exit")) { System.exit(0); } else if (s.equals("add comment")) { int stop = 0; String commentName = ""; if (myProgramElements.size() > 0) { int index = visualPanel.getSelectedIndex(); ProgramElements commentP = null; for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.getPosition() == index) { commentP = p; } } if (commentP.isfinished()) { JOptionPane .showMessageDialog(null, "Error, you cannot comment the ending bracket!"); stop++; } else if (commentP.isComment()) { JOptionPane.showMessageDialog(null, "Error, you cannot comment a comment!"); stop++; } else if (commentP.hasComment()) { JOptionPane .showMessageDialog( null, "Error, " + commentP.getName() + " already has a comment, replace " + "\nthe current one if you need to change it "); stop++; } else if (commentP.getType().equals("class")) { JOptionPane.showMessageDialog(null, "comments are not valid for classes, sorry"); stop++; } else { if (stop == 0) { String name = ""; if (commentP.isConstructor()) { name = commentP.getClassName() + "'s default constructor" + commentP.getPosition(); } else if (commentP.isMain()) { name = commentP.getClassName() + "'s main method"; } else { name = commentP.getName(); } String comment = JOptionPane .showInputDialog("enter the discription of " + name); if (commentP.getType().equals("method")) { String cName = ""; if (commentP.isMain()) { cName = commentP.getClassName() + "'s main method"; } else if (commentP.isConstructor()) { cName = commentP.getClassName() + "'s default Constructor"; } else { cName = commentP.getName(); } Method m = new Method(comment, cName, commentP.getClassID()); m.setPosition(index); m.setClassID(classID); commentName = m.getName(); myProgramElements.add(m); for (ProgramElements p : myProgramElements) { if ((p.getPosition() == m.getPosition() || p .getPosition() > m.getPosition()) && p != m && p.getClassID() == classID) { p.setPosition(p.getPosition() + 1); } } visual.insertElementAt(m.printToList(), index); } else if (commentP.getType().equals("instance")) { Variable i = new Variable(comment, commentP.getName(), commentP.getClassID()); i.setPosition(index); i.setClassID(classID); commentName = i.getName(); myProgramElements.add(i); for (ProgramElements p : myProgramElements) { if ((p.getPosition() == i.getPosition() || p .getPosition() > i.getPosition()) && p != i && p.getClassID() == classID) { p.setPosition(p.getPosition() + 1); } } visual.insertElementAt(i.printToList(), index); } } commentP.setItemHavingComment(); creationPanel = ReplaceCommentDialog(classID, Integer.MAX_VALUE); commentTitleCards.add(commentName, creationPanel); reOrderMyProgams(); visualPanel.setSelectedIndex(index); } } else JOptionPane.showMessageDialog(null, "you must first create a class, variable, or method\n" + "before you can comment it"); } else if (s.equals("Save")) { if (myProgramElements.size() > 0) { try { saveFile(); } catch (IOException save) { // TODO Auto-generated catch block save.printStackTrace(); } } else JOptionPane.showMessageDialog(null, "must create at least one class to save"); } else if (s.equals("Open")) { myProgramElements = new ArrayList<ProgramElements>(); classUniqueDefaultNameGenerator = new ArrayList<Integer>(); classSelectionButton = new ArrayList<SelectionButton>(); int finishCheck = 0; try { ArrayList<ProgramElements> loaded = loadFile(); classID = 0; visual.clear(); classCollectionCards.removeAll(); int start = 0; try { start = loaded.get(0).getClassID(); } catch (NullPointerException nul) { } classTextPanel = buildFullClassTextPanel(); classTextCards.add("full text panel", classTextPanel); classTextPanel = buildConstructorClassTextPanel(); classTextCards .add("constructor text panel", classTextPanel); classID = start; if (loaded != null) { for (ProgramElements l : loaded) { if (l.getType().equals("class")) { if (l.isfinished()) { Class c = new Class(true, l.getName(), l.getClassID()); c.setPosition(l.getPosition()); c.setClassID(l.getClassID()); myProgramElements.add(c); if (l.getClassID() == start && l.isfinished()) { ShowFinishMode(); finishCheck++; classUniqueDefaultNameGenerator.add(l .getClassID()); } } else { Class c = new Class(l.getVisability(), l.getHierarchy(), l.getName()); c.setClassID(l.getClassID()); c.setPosition(l.getPosition()); c.setHighestMethod((l.getHighestMethod() - 1)); c.setHighestVariable((l .getHighestVariable() - 1)); SelectionButton b = new SelectionButton( c.getName()); c.addMain(l.hasMain()); classSelectionButton.add(b); classID = l.getClassID(); myProgramElements.add(c); classPanel = buildClassPanel(); JScrollPane cSpane = new JScrollPane( classPanel); cSpane.setPreferredSize(new Dimension(500, 400)); classCollectionCards.add("classes", cSpane); classUniqueDefaultNameGenerator.add(l .getClassID()); ((CardLayout) classCollectionCards .getLayout()).show( classCollectionCards, "classes"); } } else if (l.getType().equals("method")) { if (l.isComment()) { Method m = new Method(l.getComment(), l.getOriginalCommentName(), l.getClassID()); m.setClassID(l.getClassID()); m.setPosition(l.getPosition()); myProgramElements.add(m); } else if (l.isMain()) { Method m = new Method("m", l.getClassName()); m.setClassID(l.getClassID()); m.setPosition(l.getPosition()); myProgramElements.add(m); } else if (l.isConstructor()) { Method m = new Method("c", l.getClassName()); m.setClassID(l.getClassID()); m.setPosition(l.getPosition()); myProgramElements.add(m); } else { Method m = new Method(l.getVisability(), l.getHierarchy(), l.getReturnType(), l.getName(), l.getStatic()); m.setClassID(l.getClassID()); m.setPosition(l.getPosition()); myProgramElements.add(m); ((CardLayout) classTextCards.getLayout()) .show(classTextCards, "full text panel"); } } else if (l.getType().equals("instance")) { if (l.isComment()) { Variable i = new Variable(l.getComment(), l.getOriginalCommentName(), l.getClassID()); i.setClassID(l.getClassID()); i.setPosition(l.getPosition()); myProgramElements.add(i); } else { Variable v = new Variable( l.getVisability(), l.getStatic(), l.getReturnType(), l.getName()); v.setClassID(l.getClassID()); v.setPosition(l.getPosition()); myProgramElements.add(v); } } } int position = 0; int checkMain = 0; for (ProgramElements p : myProgramElements) { if (p.hasMain()) { checkMain++; } else ((CardLayout) classTextCards.getLayout()).show( classTextCards, "full text panel"); if (p.getClassID() == start) { position++; visual.insertElementAt(p.printToList(), p.getPosition()); } } for (ProgramElements p : myProgramElements) { if (p.isComment()) { creationPanel = ReplaceCommentDialog( p.getClassID(), p.getPosition() + 1); commentTitleCards.add(p.getName(), creationPanel); } } if (finishCheck == 0) { if (checkMain > 0) { ((CardLayout) classTextCards.getLayout()).show( classTextCards, "constructor text panel"); } else { ((CardLayout) classTextCards.getLayout()).show( classTextCards, "full text panel"); } visualPanel.setSelectedIndex(position - 1); ((CardLayout) ButtonCards.getLayout()).show( ButtonCards, "full button panel"); if (position - 1 > 0) { ((CardLayout) UpdateCards.getLayout()).show( UpdateCards, "no replace update panel"); } else { ((CardLayout) UpdateCards.getLayout()).show( UpdateCards, "full update panel"); } } else { ((CardLayout) classTextCards.getLayout()).show( classTextCards, "empty class text"); } selectedCreatedPanel = "class"; classB = true; methodB = false; instanceB = false; classID = start; resetTextField(); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else if (s.equals("Exit")) { System.exit(0); } else if (s.equals("New")) { classUniqueDefaultNameGenerator = new ArrayList<Integer>(); myProgramElements = new ArrayList<ProgramElements>(); visual.clear(); classB = true; methodB = false; instanceB = false; selectedCreatedPanel = "class"; classTextCards.removeAll(); ((CardLayout) CreationCards.getLayout()).show(CreationCards, "create class panel"); classSelectionButton = new ArrayList<SelectionButton>(); classTextPanel = buildEmptyClassTextPanel(); classTextCards.add("empty text panel", classTextPanel); ((CardLayout) classTextCards.getLayout()).show(classTextCards, "empty text panel"); ((CardLayout) UpdateCards.getLayout()).show(UpdateCards, "add only update panel"); ((CardLayout) ButtonCards.getLayout()).show(ButtonCards, "class only button panel"); classPanel = buildClassPanel(); JScrollPane cSpane = new JScrollPane(classPanel); cSpane.setPreferredSize(new Dimension(500, 400)); classCollectionCards.add("classes", cSpane); ((CardLayout) classCollectionCards.getLayout()).show( classCollectionCards, "classes"); resetTextField(); } else if (s.equals("Export Current")) { int check = 0; int amount = 0; ProgramElements exportClass = null; for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID) { amount++; } if (p.getPosition() == 0 && p.getClassID() == classID) { exportClass = p; } if (p.isfinished() && p.getClassID() == classID) { check++; } } if (check > 0) { JFileChooser fileSelect = new JFileChooser(); fileSelect.setDialogTitle("where do you want to export " + exportClass.getName() + ".java"); File file = new File(exportClass.getName() + ".java"); fileSelect.setSelectedFile(file); int returnvalue = fileSelect.showSaveDialog(null); if (returnvalue == JFileChooser.APPROVE_OPTION) { File fi = fileSelect.getCurrentDirectory(); String fileName = fi.getPath() + "\\" + file.getName(); // make sure the name is always the class name + .java //despite what user types in try { int position = 0; FileWriter fw = new FileWriter(fileName); // write // to // file PrintWriter pw = new PrintWriter(fw); while (position < (amount - 1)) { for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.getPosition() == position) { pw.println(p.toString()); position++; } } } pw.close(); } catch (FileNotFoundException f) { f.printStackTrace(); } catch (IOException f) { // TODO Auto-generated catch block f.printStackTrace(); } } } else JOptionPane .showMessageDialog( null, "Your current class is not finished!\n" + "please finish your class before trying to export it"); } else if (s.equals("Export All")) { int classCheck = 0; int finishCheck = 0; for (ProgramElements p : myProgramElements) { if (p.getType().equals("class") && p.isfinished() == false) { classCheck++; } else if (p.getType().equals("class") && p.isfinished()) { finishCheck++; } } int index = 0; int[] classIDs = new int[finishCheck]; for (ProgramElements p : myProgramElements) { if (p.getType().equals("class") && p.isfinished() == false) { classIDs[index] = p.getClassID(); index++; } } String name = ""; File[] files = new File[classCheck]; for (int i = 0; i < classIDs.length; i++) { for (ProgramElements p : myProgramElements) { if (p.getClassID() == classIDs[i] && p.getType().equals("class") && p.isfinished() == false) { name = p.getName() + ".java"; File file = new File(name); files[i] = file; } } } if (classCheck == finishCheck) { JFileChooser fileSelect = new JFileChooser(); fileSelect .setDialogTitle("where do you want to export your classes?"); fileSelect.setSelectedFiles(files); int returnvalue = fileSelect.showSaveDialog(null); if (returnvalue == JFileChooser.APPROVE_OPTION) { File fi = fileSelect.getCurrentDirectory(); //make sure classes end up in a user defined location fileSelect.setSelectedFiles(files); String[] fileNames = new String[files.length]; for (int i = 0; i < fileNames.length; i++) { fileNames[i] = fi.getPath() + "\\" + fileSelect.getSelectedFiles()[i] .getPath(); // make sure the names are always the class name + .java //despite what user types in } try { for (int i = 0; i < files.length; i++) { int amount = 0; for (ProgramElements p : myProgramElements) { if (p.getClassID() == classIDs[i]) { amount++; } if (p.getClassID() == classIDs[i] && p.getType().equals("class") && p.isfinished() == false) { name = p.getName(); } } int position = 0; File f = new File(fileNames[i]); FileWriter fw = new FileWriter(f); // write // to // file PrintWriter pw = new PrintWriter(fw); while (position < (amount - 1)) { for (ProgramElements p : myProgramElements) { if (p.getClassID() == classIDs[i] && p.getPosition() == position) { pw.println(p.toString()); position++; } } } pw.close(); } } catch (FileNotFoundException f) { f.printStackTrace(); } catch (IOException f) { // TODO Auto-generated catch block f.printStackTrace(); } } } else JOptionPane .showMessageDialog( null, "All of your classes are not yet finished!\n" + "please make sure to finish all of your classes\n" + "before trying to export them"); } else if (s.equals("continue working")) { ProgramElements selectedClass = null; ProgramElements remove = null; int position = 0; for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.getPosition() == 0) { selectedClass = p; } if (p.getClassID() == classID && p.isfinished()) { remove = p; position = p.getPosition(); } } visual.removeElementAt(position); myProgramElements.remove(remove); resetBacktoWork(selectedClass); resetTextField(); if (methodB == true) { ((CardLayout) CreationCards.getLayout()).show( CreationCards, "create method panel"); ((CardLayout) textCards.getLayout()).show(textCards, "method text panel"); for (SelectionButton selec : classSelectionButton) { selec.setBackground(mColor); } } else if (instanceB == true) { ((CardLayout) textCards.getLayout()).show(textCards, "instance text panel"); ((CardLayout) CreationCards.getLayout()).show( CreationCards, "create instance panel"); for (SelectionButton selec : classSelectionButton) { selec.setBackground(varColor); } } } else { SelectionButton sB = (SelectionButton) e.getSource(); ProgramElements selectedClass = null; for (ProgramElements m : myProgramElements) { if (sB.getText().equals(m.getName())) { selectedClass = m; } } int checkforFinish = 0; for (ProgramElements p : myProgramElements) { if (p.getClassID() == selectedClass.getClassID() && p.isfinished()) { checkforFinish++; } } if (checkforFinish == 1) { ShowFinishMode(); for (SelectionButton button : classSelectionButton) { button.setBackground(cColor); } } else { resetBacktoWork(selectedClass); } classID = selectedClass.getClassID(); visual.clear(); int position = 0; for (ProgramElements p : myProgramElements) { if (selectedClass.getClassID() == p.getClassID()) { position++; visual.insertElementAt(p.printToList(), p.getPosition()); } } if (classB == true && checkforFinish == 0) { checkClassTextCorrectness(); ((CardLayout) CreationCards.getLayout()).show( CreationCards, "create class panel"); ((CardLayout) textCards.getLayout()).show(textCards, "class text panel"); for (SelectionButton button : classSelectionButton) { button.setBackground(cColor); } } else if (methodB == true && checkforFinish == 0) { ((CardLayout) CreationCards.getLayout()).show( CreationCards, "create method panel"); ((CardLayout) textCards.getLayout()).show(textCards, "method text panel"); for (SelectionButton button : classSelectionButton) { button.setBackground(mColor); } } else if (instanceB == true && checkforFinish == 0) { ((CardLayout) textCards.getLayout()).show(textCards, "instance text panel"); ((CardLayout) CreationCards.getLayout()).show( CreationCards, "create instance panel"); for (SelectionButton button : classSelectionButton) { button.setBackground(varColor); } } visualPanel.setSelectedIndex(position - 1); resetTextField(); } } @Override /** * keeps track of where the user is selecting and displays the appropriate panels */ public void valueChanged(ListSelectionEvent e) { // TODO Auto-generated method stub int index = visualPanel.getSelectedIndex(); int commentCheck = 0; int finishCheck = 0; ProgramElements comment = null; for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.getPosition() == index && p.isComment()) { commentCheck++; comment = p; } else if (p.getClassID() == classID && p.isfinished()) { finishCheck++; } } if (finishCheck == 0) { if (commentCheck == 0) { trackButtons(index); if (classB == true) { checkClassTextCorrectness(); for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.isfinished()) { ShowFinishMode(); } } ((CardLayout) CreationCards.getLayout()).show( CreationCards, "create class panel"); } else if (methodB == true) { ((CardLayout) CreationCards.getLayout()).show( CreationCards, "create method panel"); } else if (instanceB == true) { ((CardLayout) CreationCards.getLayout()).show( CreationCards, "create instance panel"); } } else { ((CardLayout) classTextCards.getLayout()).show( classTextCards, "empty class text"); ((CardLayout) UpdateCards.getLayout()).show(UpdateCards, "replace and delete panel"); ((CardLayout) CreationCards.getLayout()).show( CreationCards, "replace comment panel"); ((CardLayout) commentTitleCards.getLayout()).show( commentTitleCards, comment.getName()); commentReplace.setText(comment.getComment()); } } } } /* * method to show appropriate panels for when user decides to continue work after clicking finish */ private void resetBacktoWork(ProgramElements selectedClass) { ((CardLayout) UpdateCards.getLayout()).show(UpdateCards, "full update panel"); ((CardLayout) FinishCards.getLayout()).show(FinishCards, "finish button"); ((CardLayout) ButtonCards.getLayout()).show(ButtonCards, "full button panel"); if (classB == true) { ((CardLayout) CreationCards.getLayout()).show(CreationCards, "create class panel"); methodCreationSelect.setBackground(Color.green); classCreationSelect.setBackground(Color.RED); instanceVariableCreationSelect.setBackground(Color.green); ((CardLayout) textCards.getLayout()).show(textCards, "class text panel"); } else if (methodB == true) { ((CardLayout) CreationCards.getLayout()).show(CreationCards, "create method panel"); methodCreationSelect.setBackground(Color.RED); classCreationSelect.setBackground(Color.green); instanceVariableCreationSelect.setBackground(Color.green); } else if (instanceB == true) { ((CardLayout) CreationCards.getLayout()).show(CreationCards, "create instance panel"); methodCreationSelect.setBackground(Color.green); classCreationSelect.setBackground(Color.green); instanceVariableCreationSelect.setBackground(Color.RED); ((CardLayout) textCards.getLayout()).show(textCards, "instance text panel"); } if (selectedClass.hasMain()) { ((CardLayout) classTextCards.getLayout()).show(classTextCards, "constructor text panel"); } else { ((CardLayout) classTextCards.getLayout()).show(classTextCards, "full text panel"); } } /* * method to make sure correct class description panel is being displayed */ private void checkClassTextCorrectness() { int mainCheck = 0; for (ProgramElements p : myProgramElements) { if (p.getClassID() == classID && p.isMain()) { mainCheck++; } } if (mainCheck == 0) { ((CardLayout) classTextCards.getLayout()).show(classTextCards, "full text panel"); } else { ((CardLayout) classTextCards.getLayout()).show(classTextCards, "constructor text panel"); } } /* * method that shows the right panels when a new area of the display panel is selected */ private void trackButtons(int index) { if (index == 0 && classB == true) { ((CardLayout) UpdateCards.getLayout()).show(UpdateCards, "full update panel"); } else if ((instanceB == true || methodB == true) && index > 0) { ((CardLayout) UpdateCards.getLayout()).show(UpdateCards, "full update panel"); } else if ((instanceB == true || methodB == true) && index == 0) { ((CardLayout) UpdateCards.getLayout()).show(UpdateCards, "no replace update panel"); } else if (index > 0 && classB == true) { ((CardLayout) UpdateCards.getLayout()).show(UpdateCards, "no replace update panel"); } } @Override /** * determines the specific modifiers for the program elements when a new one is created, or an old one is replaced */ public void itemStateChanged(ItemEvent e) { // TODO Auto-generated method stub String s = (String) e.getItem(); if (s.equals("private")) { visability = "private"; } else if (s.equals("public")) { visability = "public"; } else if (s.equals("protected")) { visability = "protected"; } else if (s.equals("abstract")) { hierarchy = "abstract"; } else if (s.equals("final")) { hierarchy = "final"; } else if (s.equals("neither")) { hierarchy = "n"; } else if (s.equals("no")) { staticSelect = false; } else if (s.equals("static")) { staticSelect = true; } else if (s.equals("void")) { returnType = "void"; } else if (s.equals("float")) { returnType = "float"; } else if (s.equals("int")) { returnType = "int"; } else if (s.equals("double")) { returnType = "double"; } else if (s.equals("String")) { returnType = "String"; } } }
41bf8699390c65bddf6ade27ce1b62d77be64277
5095b037518edb145fbecbe391fd14757f16c9b9
/gameserver/src/main/java/l2s/gameserver/model/items/Inventory.java
89cfdef0c1c14a5dd4c32a487a70792ce0ed8cf9
[]
no_license
merlin-tribukait/lindvior
ce7da0da95c3367b05e0230379411f3544f4d9f3
21a3138a43cc03c7d6b8922054b4663db8e63a49
refs/heads/master
2021-05-28T20:58:13.697507
2014-10-09T15:58:04
2014-10-09T15:58:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
24,449
java
package l2s.gameserver.model.items; import java.util.Comparator; import l2s.commons.dao.JdbcEntityState; import l2s.commons.listener.Listener; import l2s.commons.listener.ListenerList; import l2s.gameserver.data.xml.holder.ItemHolder; import l2s.gameserver.listener.inventory.OnEquipListener; import l2s.gameserver.model.Playable; import l2s.gameserver.model.Player; import l2s.gameserver.model.items.ItemInstance.ItemLocation; import l2s.gameserver.model.items.listeners.StatsListener; import l2s.gameserver.templates.item.EtcItemTemplate.EtcItemType; import l2s.gameserver.templates.item.ItemTemplate; import l2s.gameserver.templates.item.WeaponTemplate.WeaponType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class Inventory extends ItemContainer { private static final Logger _log = LoggerFactory.getLogger(Inventory.class); public static final int PAPERDOLL_UNDER = 0; public static final int PAPERDOLL_REAR = 1; public static final int PAPERDOLL_LEAR = 2; public static final int PAPERDOLL_NECK = 3; public static final int PAPERDOLL_RFINGER = 4; public static final int PAPERDOLL_LFINGER = 5; public static final int PAPERDOLL_HEAD = 6; public static final int PAPERDOLL_RHAND = 7; public static final int PAPERDOLL_LHAND = 8; public static final int PAPERDOLL_GLOVES = 9; public static final int PAPERDOLL_CHEST = 10; public static final int PAPERDOLL_LEGS = 11; public static final int PAPERDOLL_FEET = 12; public static final int PAPERDOLL_BACK = 13; public static final int PAPERDOLL_LRHAND = 14; public static final int PAPERDOLL_HAIR = 15; public static final int PAPERDOLL_DHAIR = 16; public static final int PAPERDOLL_RBRACELET = 17; public static final int PAPERDOLL_LBRACELET = 18; public static final int PAPERDOLL_DECO1 = 19; public static final int PAPERDOLL_DECO2 = 20; public static final int PAPERDOLL_DECO3 = 21; public static final int PAPERDOLL_DECO4 = 22; public static final int PAPERDOLL_DECO5 = 23; public static final int PAPERDOLL_DECO6 = 24; public static final int PAPERDOLL_BELT = 25; public static final int PAPERDOLL_MAX = 26; public static final int[] PAPERDOLL_ORDER = { Inventory.PAPERDOLL_UNDER, Inventory.PAPERDOLL_REAR, Inventory.PAPERDOLL_LEAR, Inventory.PAPERDOLL_NECK, Inventory.PAPERDOLL_RFINGER, Inventory.PAPERDOLL_LFINGER, Inventory.PAPERDOLL_HEAD, Inventory.PAPERDOLL_RHAND, Inventory.PAPERDOLL_LHAND, Inventory.PAPERDOLL_GLOVES, Inventory.PAPERDOLL_CHEST, Inventory.PAPERDOLL_LEGS, Inventory.PAPERDOLL_FEET, Inventory.PAPERDOLL_BACK, Inventory.PAPERDOLL_LRHAND, Inventory.PAPERDOLL_HAIR, Inventory.PAPERDOLL_DHAIR, Inventory.PAPERDOLL_RBRACELET, Inventory.PAPERDOLL_LBRACELET, Inventory.PAPERDOLL_DECO1, Inventory.PAPERDOLL_DECO2, Inventory.PAPERDOLL_DECO3, Inventory.PAPERDOLL_DECO4, Inventory.PAPERDOLL_DECO5, Inventory.PAPERDOLL_DECO6, Inventory.PAPERDOLL_BELT // Пояс }; public class InventoryListenerList extends ListenerList<Playable> { public void onEquip(int slot, ItemInstance item) { for(Listener<Playable> listener : getListeners()) ((OnEquipListener) listener).onEquip(slot, item, getActor()); } public void onUnequip(int slot, ItemInstance item) { for(Listener<Playable> listener : getListeners()) ((OnEquipListener) listener).onUnequip(slot, item, getActor()); } } public static class ItemOrderComparator implements Comparator<ItemInstance> { private static final Comparator<ItemInstance> instance = new ItemOrderComparator(); public static final Comparator<ItemInstance> getInstance() { return instance; } @Override public int compare(ItemInstance o1, ItemInstance o2) { if(o1 == null || o2 == null) return 0; return o1.getLocData() - o2.getLocData(); } } protected final int _ownerId; protected final ItemInstance[] _paperdoll = new ItemInstance[PAPERDOLL_MAX]; protected final InventoryListenerList _listeners = new InventoryListenerList(); protected int _totalWeight; // used to quickly check for using of items of special type protected long _wearedMask; protected Inventory(int ownerId) { _ownerId = ownerId; addListener(StatsListener.getInstance()); } public abstract Playable getActor(); protected abstract ItemLocation getBaseLocation(); protected abstract ItemLocation getEquipLocation(); public int getOwnerId() { return _ownerId; } protected void onRestoreItem(ItemInstance item) { _totalWeight += item.getTemplate().getWeight() * item.getCount(); } @Override protected void onAddItem(ItemInstance item) { item.setOwnerId(getOwnerId()); item.setLocation(getBaseLocation()); item.setLocData(findSlot()); if(item.getJdbcState().isSavable()) { item.save(); } else { item.setJdbcState(JdbcEntityState.UPDATED); item.update(); } sendAddItem(item); refreshWeight(); } @Override protected void onModifyItem(ItemInstance item) { item.setJdbcState(JdbcEntityState.UPDATED); item.update(); sendModifyItem(item); refreshWeight(); } @Override protected void onRemoveItem(ItemInstance item) { if(item.isEquipped()) unEquipItem(item); sendRemoveItem(item); item.setLocData(-1); refreshWeight(); } @Override protected void onDestroyItem(ItemInstance item) { item.setCount(0L); item.delete(); } protected void onEquip(int slot, ItemInstance item) { _listeners.onEquip(slot, item); item.setLocation(getEquipLocation()); item.setLocData(slot); item.setEquipped(true); item.setJdbcState(JdbcEntityState.UPDATED); sendModifyItem(item); _wearedMask |= item.getTemplate().getItemMask(); } protected void onUnequip(int slot, ItemInstance item) { item.setLocation(getBaseLocation()); item.setLocData(findSlot()); item.setEquipped(false); item.setJdbcState(JdbcEntityState.UPDATED); item.setChargedSpiritshot(ItemInstance.CHARGED_NONE); item.setChargedSoulshot(ItemInstance.CHARGED_NONE); sendModifyItem(item); _wearedMask &= ~item.getTemplate().getItemMask(); _listeners.onUnequip(slot, item); } /** * Находит и возвращает пустой слот в инвентаре. */ private int findSlot() { ItemInstance item; int slot = 0; loop: for(slot = 0; slot < _items.size(); slot++) { for(int i = 0; i < _items.size(); i++) { item = _items.get(i); if(item.isEquipped() || item.getTemplate().isQuest()) // игнорируем надетое и квестовые вещи continue; if(item.getEquipSlot() == slot) // слот занят? continue loop; } break; } return slot; // слот не занят, возвращаем } public ItemInstance getPaperdollItem(int slot) { return _paperdoll[slot]; } public ItemInstance[] getPaperdollItems() { return _paperdoll; } public int getPaperdollItemId(int slot) { ItemInstance item = getPaperdollItem(slot); if(item != null) return item.getItemId(); else if(slot == PAPERDOLL_HAIR) { item = _paperdoll[PAPERDOLL_DHAIR]; if(item != null) return item.getItemId(); } return 0; } public int getPaperdollVisualId(int slot) { ItemInstance item = getPaperdollItem(slot); if(item != null) { if(item.getVisualId() > 0) return item.getVisualId(); } else if(slot == PAPERDOLL_HAIR) { item = _paperdoll[PAPERDOLL_DHAIR]; if(item != null) { if(item.getVisualId() > 0) return item.getVisualId(); } } return 0; } public int getPaperdollObjectId(int slot) { ItemInstance item = _paperdoll[slot]; if(item != null) return item.getObjectId(); else if(slot == PAPERDOLL_HAIR) { item = _paperdoll[PAPERDOLL_DHAIR]; if(item != null) return item.getObjectId(); } return 0; } public void addListener(OnEquipListener listener) { _listeners.add(listener); } public void removeListener(OnEquipListener listener) { _listeners.remove(listener); } public ItemInstance setPaperdollItem(int slot, ItemInstance item) { ItemInstance old; writeLock(); try { old = _paperdoll[slot]; if(old != item) { if(old != null) { _paperdoll[slot] = null; onUnequip(slot, old); } if(item != null) { _paperdoll[slot] = item; onEquip(slot, item); } } } finally { writeUnlock(); } return old; } public long getWearedMask() { return _wearedMask; } public void unEquipItem(ItemInstance item) { if(item.isEquipped()) unEquipItemInBodySlot(item.getBodyPart(), item); } public void unEquipItemInBodySlot(int bodySlot) { unEquipItemInBodySlot(bodySlot, null); } private void unEquipItemInBodySlot(int bodySlot, ItemInstance item) { int pdollSlot = -1; switch(bodySlot) { case ItemTemplate.SLOT_NECK: pdollSlot = PAPERDOLL_NECK; break; case ItemTemplate.SLOT_L_EAR: pdollSlot = PAPERDOLL_LEAR; break; case ItemTemplate.SLOT_R_EAR: pdollSlot = PAPERDOLL_REAR; break; case ItemTemplate.SLOT_L_EAR | ItemTemplate.SLOT_R_EAR: if(item == null) return; if(getPaperdollItem(PAPERDOLL_LEAR) == item) pdollSlot = PAPERDOLL_LEAR; if(getPaperdollItem(PAPERDOLL_REAR) == item) pdollSlot = PAPERDOLL_REAR; break; case ItemTemplate.SLOT_L_FINGER: pdollSlot = PAPERDOLL_LFINGER; break; case ItemTemplate.SLOT_R_FINGER: pdollSlot = PAPERDOLL_RFINGER; break; case ItemTemplate.SLOT_L_FINGER | ItemTemplate.SLOT_R_FINGER: if(item == null) return; if(getPaperdollItem(PAPERDOLL_LFINGER) == item) pdollSlot = PAPERDOLL_LFINGER; if(getPaperdollItem(PAPERDOLL_RFINGER) == item) pdollSlot = PAPERDOLL_RFINGER; break; case ItemTemplate.SLOT_HAIR: pdollSlot = PAPERDOLL_HAIR; break; case ItemTemplate.SLOT_DHAIR: pdollSlot = PAPERDOLL_DHAIR; break; case ItemTemplate.SLOT_HAIRALL: setPaperdollItem(PAPERDOLL_DHAIR, null); // This should be the same as in DHAIR pdollSlot = PAPERDOLL_HAIR; break; case ItemTemplate.SLOT_HEAD: pdollSlot = PAPERDOLL_HEAD; break; case ItemTemplate.SLOT_R_HAND: pdollSlot = PAPERDOLL_RHAND; break; case ItemTemplate.SLOT_L_HAND: pdollSlot = PAPERDOLL_LHAND; break; case ItemTemplate.SLOT_GLOVES: pdollSlot = PAPERDOLL_GLOVES; break; case ItemTemplate.SLOT_LEGS: pdollSlot = PAPERDOLL_LEGS; break; case ItemTemplate.SLOT_CHEST: case ItemTemplate.SLOT_FULL_ARMOR: case ItemTemplate.SLOT_FORMAL_WEAR: pdollSlot = PAPERDOLL_CHEST; break; case ItemTemplate.SLOT_BACK: pdollSlot = PAPERDOLL_BACK; break; case ItemTemplate.SLOT_FEET: pdollSlot = PAPERDOLL_FEET; break; case ItemTemplate.SLOT_UNDERWEAR: pdollSlot = PAPERDOLL_UNDER; break; case ItemTemplate.SLOT_BELT: pdollSlot = PAPERDOLL_BELT; break; case ItemTemplate.SLOT_LR_HAND: setPaperdollItem(PAPERDOLL_LHAND, null); pdollSlot = PAPERDOLL_RHAND; break; case ItemTemplate.SLOT_L_BRACELET: pdollSlot = PAPERDOLL_LBRACELET; break; case ItemTemplate.SLOT_R_BRACELET: pdollSlot = PAPERDOLL_RBRACELET; // При снятии правого браслета, снимаем и талисманы тоже setPaperdollItem(Inventory.PAPERDOLL_DECO1, null); setPaperdollItem(Inventory.PAPERDOLL_DECO2, null); setPaperdollItem(Inventory.PAPERDOLL_DECO3, null); setPaperdollItem(Inventory.PAPERDOLL_DECO4, null); setPaperdollItem(Inventory.PAPERDOLL_DECO5, null); setPaperdollItem(Inventory.PAPERDOLL_DECO6, null); break; case ItemTemplate.SLOT_DECO: if(item == null) return; else if(getPaperdollItem(PAPERDOLL_DECO1) == item) pdollSlot = PAPERDOLL_DECO1; else if(getPaperdollItem(PAPERDOLL_DECO2) == item) pdollSlot = PAPERDOLL_DECO2; else if(getPaperdollItem(PAPERDOLL_DECO3) == item) pdollSlot = PAPERDOLL_DECO3; else if(getPaperdollItem(PAPERDOLL_DECO4) == item) pdollSlot = PAPERDOLL_DECO4; else if(getPaperdollItem(PAPERDOLL_DECO5) == item) pdollSlot = PAPERDOLL_DECO5; else if(getPaperdollItem(PAPERDOLL_DECO6) == item) pdollSlot = PAPERDOLL_DECO6; break; default: _log.warn("Requested invalid body slot: " + bodySlot + ", Item: " + item + ", ownerId: '" + getOwnerId() + "'"); return; } if(pdollSlot >= 0) setPaperdollItem(pdollSlot, null); } public void equipItem(ItemInstance item) { int bodySlot = item.getBodyPart(); //TODO [G1ta0] затычка на статы повышающие HP/MP/CP double hp = getActor().getCurrentHp(); double mp = getActor().getCurrentMp(); double cp = getActor().getCurrentCp(); switch(bodySlot) { case ItemTemplate.SLOT_LR_HAND: { setPaperdollItem(PAPERDOLL_LHAND, null); setPaperdollItem(PAPERDOLL_RHAND, item); break; } case ItemTemplate.SLOT_L_HAND: { final ItemInstance rHandItem = getPaperdollItem(PAPERDOLL_RHAND); final ItemTemplate rHandItemTemplate = rHandItem == null ? null : rHandItem.getTemplate(); final ItemTemplate newItem = item.getTemplate(); if(newItem.getItemType() == EtcItemType.ARROW || newItem.getItemType() == EtcItemType.ARROW_QUIVER) { // arrows can be equipped only with bow if(rHandItemTemplate == null) return; if(rHandItemTemplate.getItemType() != WeaponType.BOW) return; if(rHandItemTemplate.getGrade() != newItem.getGrade()) return; } else if(newItem.getItemType() == EtcItemType.BOLT || newItem.getItemType() == EtcItemType.BOLT_QUIVER) { // bolts can be equipped only with crossbow if(rHandItemTemplate == null) return; if(rHandItemTemplate.getItemType() != WeaponType.CROSSBOW) return; if(rHandItemTemplate.getGrade() != newItem.getGrade()) return; } else if(newItem.getItemType() == EtcItemType.LURE) { // baits can be equipped only with rods if(rHandItemTemplate == null) return; if(rHandItemTemplate.getItemType() != WeaponType.ROD) return; if(!getActor().isPlayer()) return; Player owner = (Player) getActor(); owner.setVar("LastLure", String.valueOf(item.getObjectId()), -1); } else { // unequip two-hand weapon if(rHandItemTemplate != null && rHandItemTemplate.getBodyPart() == ItemTemplate.SLOT_LR_HAND) setPaperdollItem(PAPERDOLL_RHAND, null); } setPaperdollItem(PAPERDOLL_LHAND, item); break; } case ItemTemplate.SLOT_R_HAND: { setPaperdollItem(PAPERDOLL_RHAND, item); break; } case ItemTemplate.SLOT_L_EAR: case ItemTemplate.SLOT_R_EAR: case ItemTemplate.SLOT_L_EAR | ItemTemplate.SLOT_R_EAR: { if(_paperdoll[PAPERDOLL_LEAR] == null) setPaperdollItem(PAPERDOLL_LEAR, item); else if(_paperdoll[PAPERDOLL_REAR] == null) setPaperdollItem(PAPERDOLL_REAR, item); else setPaperdollItem(PAPERDOLL_LEAR, item); break; } case ItemTemplate.SLOT_L_FINGER: case ItemTemplate.SLOT_R_FINGER: case ItemTemplate.SLOT_L_FINGER | ItemTemplate.SLOT_R_FINGER: { if(_paperdoll[PAPERDOLL_LFINGER] == null) setPaperdollItem(PAPERDOLL_LFINGER, item); else if(_paperdoll[PAPERDOLL_RFINGER] == null) setPaperdollItem(PAPERDOLL_RFINGER, item); else setPaperdollItem(PAPERDOLL_LFINGER, item); break; } case ItemTemplate.SLOT_NECK: setPaperdollItem(PAPERDOLL_NECK, item); break; case ItemTemplate.SLOT_FULL_ARMOR: setPaperdollItem(PAPERDOLL_LEGS, null); setPaperdollItem(PAPERDOLL_CHEST, item); break; case ItemTemplate.SLOT_CHEST: setPaperdollItem(PAPERDOLL_CHEST, item); break; case ItemTemplate.SLOT_LEGS: { // handle full armor ItemInstance chest = getPaperdollItem(PAPERDOLL_CHEST); if(chest != null && chest.getBodyPart() == ItemTemplate.SLOT_FULL_ARMOR) setPaperdollItem(PAPERDOLL_CHEST, null); else if(getPaperdollItemId(PAPERDOLL_CHEST) == ItemTemplate.ITEM_ID_FORMAL_WEAR) setPaperdollItem(PAPERDOLL_CHEST, null); setPaperdollItem(PAPERDOLL_LEGS, item); break; } case ItemTemplate.SLOT_FEET: if(getPaperdollItemId(PAPERDOLL_CHEST) == ItemTemplate.ITEM_ID_FORMAL_WEAR) setPaperdollItem(PAPERDOLL_CHEST, null); setPaperdollItem(PAPERDOLL_FEET, item); break; case ItemTemplate.SLOT_GLOVES: if(getPaperdollItemId(PAPERDOLL_CHEST) == ItemTemplate.ITEM_ID_FORMAL_WEAR) setPaperdollItem(PAPERDOLL_CHEST, null); setPaperdollItem(PAPERDOLL_GLOVES, item); break; case ItemTemplate.SLOT_HEAD: if(getPaperdollItemId(PAPERDOLL_CHEST) == ItemTemplate.ITEM_ID_FORMAL_WEAR) setPaperdollItem(PAPERDOLL_CHEST, null); setPaperdollItem(PAPERDOLL_HEAD, item); break; case ItemTemplate.SLOT_HAIR: ItemInstance old = getPaperdollItem(PAPERDOLL_DHAIR); if(old != null && old.getBodyPart() == ItemTemplate.SLOT_HAIRALL) setPaperdollItem(PAPERDOLL_DHAIR, null); setPaperdollItem(PAPERDOLL_HAIR, item); break; case ItemTemplate.SLOT_DHAIR: ItemInstance slot2 = getPaperdollItem(PAPERDOLL_DHAIR); if(slot2 != null && slot2.getBodyPart() == ItemTemplate.SLOT_HAIRALL) setPaperdollItem(PAPERDOLL_HAIR, null); setPaperdollItem(PAPERDOLL_DHAIR, item); break; case ItemTemplate.SLOT_HAIRALL: setPaperdollItem(PAPERDOLL_HAIR, null); setPaperdollItem(PAPERDOLL_DHAIR, item); break; case ItemTemplate.SLOT_R_BRACELET: setPaperdollItem(PAPERDOLL_RBRACELET, item); break; case ItemTemplate.SLOT_L_BRACELET: setPaperdollItem(PAPERDOLL_LBRACELET, item); break; case ItemTemplate.SLOT_UNDERWEAR: setPaperdollItem(PAPERDOLL_UNDER, item); break; case ItemTemplate.SLOT_BACK: setPaperdollItem(PAPERDOLL_BACK, item); break; case ItemTemplate.SLOT_BELT: setPaperdollItem(PAPERDOLL_BELT, item); break; case ItemTemplate.SLOT_DECO: if(_paperdoll[PAPERDOLL_DECO1] == null) setPaperdollItem(PAPERDOLL_DECO1, item); else if(_paperdoll[PAPERDOLL_DECO2] == null) setPaperdollItem(PAPERDOLL_DECO2, item); else if(_paperdoll[PAPERDOLL_DECO3] == null) setPaperdollItem(PAPERDOLL_DECO3, item); else if(_paperdoll[PAPERDOLL_DECO4] == null) setPaperdollItem(PAPERDOLL_DECO4, item); else if(_paperdoll[PAPERDOLL_DECO5] == null) setPaperdollItem(PAPERDOLL_DECO5, item); else if(_paperdoll[PAPERDOLL_DECO6] == null) setPaperdollItem(PAPERDOLL_DECO6, item); else setPaperdollItem(PAPERDOLL_DECO1, item); break; case ItemTemplate.SLOT_FORMAL_WEAR: // При одевании свадебного платья руки не трогаем setPaperdollItem(PAPERDOLL_LEGS, null); setPaperdollItem(PAPERDOLL_HEAD, null); setPaperdollItem(PAPERDOLL_FEET, null); setPaperdollItem(PAPERDOLL_GLOVES, null); setPaperdollItem(PAPERDOLL_CHEST, item); break; default: _log.warn("unknown body slot:" + bodySlot + " for item id: " + item.getItemId()); return; } //TODO [G1ta0] затычка на статы повышающие HP/MP/CP getActor().setCurrentHp(hp, false); getActor().setCurrentMp(mp); getActor().setCurrentCp(cp); if(getActor().isPlayer()) ((Player) getActor()).autoShot(); } protected abstract void sendAddItem(ItemInstance item); protected abstract void sendModifyItem(ItemInstance item); protected abstract void sendRemoveItem(ItemInstance item); /** * Refresh the weight of equipment loaded */ protected void refreshWeight() { int weight = 0; readLock(); try { ItemInstance item; for(int i = 0; i < _items.size(); i++) { item = _items.get(i); weight += item.getTemplate().getWeight() * item.getCount(); } } finally { readUnlock(); } if(_totalWeight == weight) return; _totalWeight = weight; onRefreshWeight(); } protected abstract void onRefreshWeight(); public int getTotalWeight() { return _totalWeight; } public boolean validateCapacity(ItemInstance item) { long slots = 0; if(!item.isStackable() || getItemByItemId(item.getItemId()) == null) slots++; return validateCapacity(slots); } public boolean validateCapacity(int itemId, long count) { ItemTemplate item = ItemHolder.getInstance().getTemplate(itemId); return validateCapacity(item, count); } public boolean validateCapacity(ItemTemplate item, long count) { long slots = 0; if(!item.isStackable() || getItemByItemId(item.getItemId()) == null) slots = count; return validateCapacity(slots); } public boolean validateCapacity(long slots) { if(slots == 0) return true; if(slots < Integer.MIN_VALUE || slots > Integer.MAX_VALUE) return false; if(getSize() + (int) slots < 0) return false; return getSize() + slots <= getActor().getInventoryLimit(); } public boolean validateWeight(ItemInstance item) { long weight = item.getTemplate().getWeight() * item.getCount(); return validateWeight(weight); } public boolean validateWeight(int itemId, long count) { ItemTemplate item = ItemHolder.getInstance().getTemplate(itemId); return validateWeight(item, count); } public boolean validateWeight(ItemTemplate item, long count) { long weight = item.getWeight() * count; return validateWeight(weight); } public boolean validateWeight(long weight) { if(weight == 0L) return true; if(weight < Integer.MIN_VALUE || weight > Integer.MAX_VALUE) return false; if(getTotalWeight() + (int) weight < 0) return false; return getTotalWeight() + weight <= getActor().getMaxLoad(); } public abstract void restore(); public abstract void store(); public static int getPaperdollIndex(int slot) { switch(slot) { case ItemTemplate.SLOT_UNDERWEAR: return PAPERDOLL_UNDER; case ItemTemplate.SLOT_R_EAR: return PAPERDOLL_REAR; case ItemTemplate.SLOT_L_EAR: return PAPERDOLL_LEAR; case ItemTemplate.SLOT_NECK: return PAPERDOLL_NECK; case ItemTemplate.SLOT_R_FINGER: return PAPERDOLL_RFINGER; case ItemTemplate.SLOT_L_FINGER: return PAPERDOLL_LFINGER; case ItemTemplate.SLOT_HEAD: return PAPERDOLL_HEAD; case ItemTemplate.SLOT_R_HAND: return PAPERDOLL_RHAND; case ItemTemplate.SLOT_L_HAND: return PAPERDOLL_LHAND; case ItemTemplate.SLOT_LR_HAND: return PAPERDOLL_LRHAND; case ItemTemplate.SLOT_GLOVES: return PAPERDOLL_GLOVES; case ItemTemplate.SLOT_CHEST: case ItemTemplate.SLOT_FULL_ARMOR: case ItemTemplate.SLOT_FORMAL_WEAR: return PAPERDOLL_CHEST; case ItemTemplate.SLOT_LEGS: return PAPERDOLL_LEGS; case ItemTemplate.SLOT_FEET: return PAPERDOLL_FEET; case ItemTemplate.SLOT_BACK: return PAPERDOLL_BACK; case ItemTemplate.SLOT_HAIR: case ItemTemplate.SLOT_HAIRALL: return PAPERDOLL_HAIR; case ItemTemplate.SLOT_DHAIR: return PAPERDOLL_DHAIR; case ItemTemplate.SLOT_R_BRACELET: return PAPERDOLL_RBRACELET; case ItemTemplate.SLOT_L_BRACELET: return PAPERDOLL_LBRACELET; case ItemTemplate.SLOT_DECO: return PAPERDOLL_DECO1; //return first we deal with it later case ItemTemplate.SLOT_BELT: return PAPERDOLL_BELT; } return -1; } @Override public int getSize() { return super.getSize() - getQuestSize(); } public int getAllSize() { return super.getSize(); } public int getQuestSize() { int size = 0; for(ItemInstance item : getItems()) if(item.getTemplate().isQuest()) size++; return size; } }
120ada52fa7c90ecf67ecc14206b0b48b91c832d
1e4114f31fc0d4dba102452a4d3c84a8d0470dac
/Proyecto_Servidor/src/data/Usuario.java
0855cdd1e4fd818cf5f26b649f5a4b1aa72ead47
[]
no_license
jonmanzanal/Diseno
02b10415263f8d9bf47aaf62359876f1b3a48f44
2e7da8bc08a37c99ffe16e3b6ca59ab188803ae8
refs/heads/master
2020-12-01T09:04:28.745234
2020-01-10T16:37:36
2020-01-10T16:37:36
230,597,717
0
0
null
null
null
null
UTF-8
Java
false
false
1,618
java
package data; import java.util.HashSet; import java.util.Set; import javax.jdo.annotations.PersistenceCapable; @PersistenceCapable public class Usuario { private long idusu; private String email; private String nombre; private String apellidos; private Aeropuerto aeropuertopordefecto; private int tiporedsocial; private Set<Reserva> reserva; public Usuario() { super(); this.email = ""; this.nombre=""; this.apellidos = ""; this.aeropuertopordefecto = null; this.tiporedsocial = 0; this.reserva = new HashSet<Reserva>(); } public long getId_usu() { return idusu; } public void setId_usu(long id_usu) { this.idusu = id_usu; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getApellidos() { return apellidos; } public void setApellidos(String apellidos) { this.apellidos = apellidos; } public Aeropuerto getAeropuertopordefecto() { return aeropuertopordefecto; } public void setAeropuertopordefecto(Aeropuerto aeropuertopordefecto) { this.aeropuertopordefecto = aeropuertopordefecto; } public int getTiporedsocial() { return tiporedsocial; } public void setTiporedsocial(int tiporedsocial) { this.tiporedsocial = tiporedsocial; } public Set<Reserva> getReserva() { return reserva; } public void setReserva(Set<Reserva> reserva) { this.reserva = reserva; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } }
ac3935e442b8aee2a2e159e60aeda9b85f91280d
a0631dd1a08a9841cc9f835ae02a7dd23eff0dea
/PADC-MyanmarAttractions/app/src/main/java/com/padc/aml/myanmarattractions/controllers/ControllerAccountControl.java
d0776a290f70d99c85447657bb4702879634da22
[]
no_license
kolunar/PADC-W7-Ex
c7773dccb4062a4bb578371c7206ffb6d162b1dc
7988e4285498934ad301a08c5501414bc8aa5327
refs/heads/master
2021-01-17T20:24:54.876655
2016-07-23T06:21:08
2016-07-23T06:21:08
64,002,026
0
0
null
null
null
null
UTF-8
Java
false
false
288
java
package com.padc.aml.myanmarattractions.controllers; /** * Created by aung on 7/15/16. */ public interface ControllerAccountControl { void onRegister(String name, String email, String password, String dateOfBirth, String country); void onLogin(String email, String password); }
6ef0bcd1bf71266bf961751550a08c701d8348aa
c3abad6ba7dcab5ce0d3ed100abf6433a36d13c1
/src/lab4/partc/TaxPercentage.java
e113bd3655333da4cb3edaa226b51f2d2e8f7b21
[]
no_license
binhtv/MPP_Group3
47d7068f3cbc23bf66dd63135613e07a5bdff86a
32af7cb12a2cd3c8816c0278dc3a8f1a295d3afd
refs/heads/master
2020-03-28T07:07:17.639643
2019-05-31T03:27:27
2019-05-31T03:27:27
147,882,019
0
0
null
null
null
null
UTF-8
Java
false
false
273
java
package lab4.partc; public enum TaxPercentage { FICA(0.23), STATE(0.05), LOCAL(0.01), MEDICARE(0.03), SOCIAL_SECURITY(0.075); private double value; private TaxPercentage(double value) { this.value = value; } public double getValue() { return value; } }
9fa6be00e25ed6592220f2e61aef59867e1a9df7
1b6d0132737eb454eb80250351e4512d9550f778
/agent/src/main/java/org/eiennohito/MessageSender.java
c440c5870831f5d30e91c679829e221408b02d47
[ "Apache-2.0" ]
permissive
eiennohito/disk-usage-aggregator
cdddcc65f5feb57e91421a1ce372095df94b6226
9e397d3f956b8f9f454bce8462d49ca9a0da1647
refs/heads/master
2016-08-11T08:28:54.375032
2016-04-19T06:13:13
2016-04-19T06:13:13
46,117,263
0
0
null
null
null
null
UTF-8
Java
false
false
222
java
package org.eiennohito; import java.io.IOException; import java.nio.ByteBuffer; /** * @author eiennohito * @since 2016/02/18 */ public interface MessageSender { void sendBuffer(ByteBuffer buf) throws IOException; }
2032c401842eeab31be5a119852cf8c7749400c7
eae9d658d9113dd71eb1c55c6099eca2fc337acc
/MiniMat/src/com/alexyuan/Entity/Cretures/Enemy/TinyMon.java
e9306d7aaa50c9f05489a1124cbf88eecd968316
[ "Apache-2.0" ]
permissive
Alex-Shanyi-Yuan/MiniMat
b8b63333321e47fa8cced27fde2bf3f04353c781
5e1d232d44b4f0c76fe7c5e4e4d5adeb961e6297
refs/heads/master
2020-12-30T01:02:51.511972
2020-04-25T21:24:02
2020-04-25T21:24:02
238,806,033
0
0
null
null
null
null
UTF-8
Java
false
false
3,484
java
package com.alexyuan.Entity.Cretures.Enemy; import com.alexyuan.LoadFile.Textures; import com.alexyuan.Math.AABB; import com.alexyuan.Math.Vector2f; import com.alexyuan.util.Camera; public class TinyMon extends Enemy { public TinyMon(Camera cam, Vector2f origin, int size) { super(cam, Textures.getMon(), origin, size); damage = 10; acc = 1f; deacc = 2f; maxSpeed = 2f; r_attackrange = 40; r_sense = 300; sense = new AABB(new Vector2f(pos.getX() + size / 2 - r_sense / 2, pos.getY() + size / 2 - r_sense / 2), r_sense); attackrange = new AABB(new Vector2f(pos.getX() + bounds.getXOffset() + bounds.getWidth() / 2 - r_attackrange / 2 , pos.getY() + bounds.getYOffset() + bounds.getHeight() / 2 - r_attackrange / 2 ), r_attackrange); attackSpeed = 500; attackDuration = 500; force = 3f; bounds.setWidth(42); bounds.setHeight(20); bounds.setXOffset(12); bounds.setYOffset(40); healthLength = 50; maxHealth = 300; health = 300; ATTACK = 1; FALLEN = 6; UP = 5; DOWN = 13; LEFT = 9; RIGHT = 1; ANIMATIONSPEED = 5; ani.setNumFrames(5, UP); ani.setNumFrames(5, DOWN); ani.setNumFrames(7, LEFT + ATTACK); ani.setNumFrames(7, RIGHT + ATTACK); ani.setNumFrames(7, LEFT + FALLEN); ani.setNumFrames(7, RIGHT + FALLEN); } @Override public void animate() { if(attacking && !fallen) { if(currentAnimation == RIGHT || currentAnimation == DOWN) { if ((currentAnimation != RIGHT + ATTACK || ani.getDelay() == -1)) setAnimation(RIGHT + ATTACK, sprite.getSpriteArray(RIGHT + ATTACK), attackDuration / 100); }else if (currentAnimation == LEFT || currentAnimation == UP) { if ((currentAnimation != LEFT + ATTACK || ani.getDelay() == -1)) setAnimation(LEFT + ATTACK, sprite.getSpriteArray(LEFT + ATTACK), attackDuration / 100); } } else if (left) { if ((currentAnimation != LEFT || ani.getDelay() == -1)) { setAnimation(LEFT, sprite.getSpriteArray(LEFT), ANIMATIONSPEED); } } else if (right) { if ((currentAnimation != RIGHT || ani.getDelay() == -1)) { setAnimation(RIGHT, sprite.getSpriteArray(RIGHT), ANIMATIONSPEED); } }else if (up) { if ((currentAnimation != UP || ani.getDelay() == -1)) { setAnimation(UP, sprite.getSpriteArray(UP), ANIMATIONSPEED); } } else if (down) { if ((currentAnimation != DOWN || ani.getDelay() == -1)) { setAnimation(DOWN, sprite.getSpriteArray(DOWN), ANIMATIONSPEED); } } else if (fallen) { if(currentAnimation == RIGHT || currentAnimation == DOWN) { if ((currentAnimation != RIGHT + FALLEN || ani.getDelay() == -1)) setAnimation(RIGHT + FALLEN, sprite.getSpriteArray(RIGHT + FALLEN), 15); }else if (currentAnimation == LEFT || currentAnimation == UP) { if ((currentAnimation != LEFT + FALLEN || ani.getDelay() == -1)) setAnimation(LEFT + FALLEN, sprite.getSpriteArray(LEFT + FALLEN), 15); } }else if(dx == 0 && dy == 0) { if(hasIdle && currentAnimation != IDLE) { setAnimation(IDLE, sprite.getSpriteArray(IDLE), 10); } else { setAnimation(currentAnimation, sprite.getSpriteArray(currentAnimation), -1); } } } }
5ffa5fa971ebb50f558ce218e0ef5e81998fd896
fe4cabfb49ec8709ad7516dd0d2e274c0c0680d1
/TesteDataBase/app/src/main/java/com/example/testebd/MainActivity.java
f7486cf04cb1fe3fb5780b6e74ffa45482249f75
[]
no_license
LucasMaximoFerreira/TesteDataBase
22a161ef7c157f65006d27f862f0a61a57a2e773
e3cf133654d63b9e69768a42eed3165038bd00c8
refs/heads/master
2022-12-29T18:54:24.331630
2020-10-06T22:38:21
2020-10-06T22:38:21
301,871,011
0
0
null
null
null
null
UTF-8
Java
false
false
1,066
java
package com.example.testebd; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import dao.conectarBD; import model.dadosEntreTela; import model.teste; public class MainActivity extends AppCompatActivity implements View.OnClickListener { EditText txtnome; Button btncad1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtnome = findViewById(R.id.txtnome); btncad1 = findViewById(R.id.btncad1); btncad1.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btncad1: dadosEntreTela.setNomeTela(txtnome.getText().toString()); Intent telaCad = new Intent(this, testebd2.class); startActivity(telaCad); break; } } }
1bb58d7cef8567115993622b35f06d67608c2196
f3ee3758bf2753673be058586ec7708a92a5fa1d
/src/main/java/com/digitalreasoning/exercise_2/SentenceBuilder.java
0de354b793289b7a28269e0db99147677db702b0
[]
no_license
matawanny/digitalreasoning_exercise_2
7aef74f0674f96d28e65ad0e56febbff4291fc49
678d7da641d8c168f5faf1d0b5003fcd588ba900
refs/heads/master
2020-06-01T10:19:08.389430
2015-04-06T08:11:52
2015-04-06T08:11:52
33,471,435
0
0
null
null
null
null
UTF-8
Java
false
false
1,627
java
package com.digitalreasoning.exercise_2; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.digitalreasoning.nlf.FieldType; import com.digitalreasoning.nlf.TField; import com.digitalreasoning.nlf.TSentence; public class SentenceBuilder { private Map<String, Integer> wordSet; private Map<String, Integer> punctuationSet; private Integer spaceTotal; private List<TField> matchedEntitySet; public SentenceBuilder(Map<String, Integer> wordSet, Map<String, Integer> punctuationSet, Integer spaceTotal, List<TField> matchedEntitySet) { super(); this.wordSet = wordSet; this.punctuationSet = punctuationSet; this.spaceTotal = spaceTotal; this.matchedEntitySet = matchedEntitySet; } public TSentence CreateSentence(){ TSentence sentence = new TSentence(); List<TField> ls = sentence.getField(); for (Map.Entry<String, Integer> entry : wordSet.entrySet()) { TField field = new TField(); field.setValue(entry.getKey()); field.setTotal(entry.getValue()); field.setFieldtype(FieldType.WORD); ls.add(field); } for (Map.Entry<String, Integer> entry : punctuationSet.entrySet()) { TField field = new TField(); field.setValue(entry.getKey()); field.setTotal(entry.getValue()); field.setFieldtype(FieldType.PUNCTUATION); ls.add(field); } TField field = new TField(); field.setTotal(spaceTotal); field.setFieldtype(FieldType.WHITESPACE); ls.add(field); for(TField t: matchedEntitySet){ ls.add(t); } return sentence; } }
338aba48c836fb45d9ae8a68bfbfa0661502b0d3
d4b17a1dde0309ea8a1b2f6d6ae640e44a811052
/lang_interface/java/com/intel/daal/services/Environment.java
37174e0aec448d5bc09c55b7c9c67ca5cabf3423
[ "Apache-2.0", "Intel" ]
permissive
h2oai/daal
c50f2b14dc4a9ffc0b7f7bcb40b599cadac6d333
d49815df3040f3872a1fdb9dc99ee86148e4494e
refs/heads/daal_2018_beta_update1
2023-05-25T17:48:44.312245
2017-09-29T13:30:10
2017-09-29T13:30:10
96,125,165
2
3
null
2017-09-29T13:30:11
2017-07-03T15:26:26
C++
UTF-8
Java
false
false
2,692
java
/* file: Environment.java */ /******************************************************************************* * Copyright 2014-2017 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /** * @defgroup env_detect Managing the Computational Environment * @brief Provides methods to interact with the environment, including processor detection and control by the number of threads. * @ingroup services * @{ */ package com.intel.daal.services; /** * <a name="DAAL-CLASS-SERVICES__ENVIRONMENT"></a> * @brief Provides information about computational environment. */ public class Environment { protected static native int cGetCpuId(int enable); protected static native int cSetCpuId(int cpuid); protected static native int cEnableInstructionsSet(int enable); protected static native void cSetNumberOfThreads(int numThreads); protected static native int cGetNumberOfThreads(); /** @private */ static { System.loadLibrary("JavaAPI"); } /** * Detects the processor type * \param[in] enable An enabling flag * \return The CPU ID */ public static int getCpuId(CpuTypeEnable enable) { return cGetCpuId(enable.getValue()); } /** * Set the processor type * \param[in] cpuid CPU ID * \return CPU ID if success; -1 if error */ public static int setCpuId(CpuType cpuid) { return cSetCpuId(cpuid.getValue()); } /** * Set * \param[in] enable An enabling flag * \return CPU ID */ public static int enableInstructionsSet(CpuTypeEnable enable) { return cEnableInstructionsSet(enable.getValue()); } /** * Sets the number of threads to be used in the application * @param numThreads The number of threads to set */ public static void setNumberOfThreads(int numThreads) { cSetNumberOfThreads(numThreads); } /** * Returns number of threads used by the application * @return Number of threads */ public static int getNumberOfThreads() { return cGetNumberOfThreads(); } } /** @} */
a8eac53e048044dc106b7ce2ae5b645d33ca5e0f
93f53a9167dc1ad042dc4a707f10f78a42f69118
/src/main/java/info/unproj/model/Order.java
a5b00557d0510accecccf263064b2c1ee57de96d
[]
no_license
babenko021019/eshop
17686a628bbb3b13fa30de1a118296153420f1bd
c9fdb4f04f42132dfeadf93dac107f5146f2500c
refs/heads/master
2022-11-13T06:20:36.526123
2020-06-30T10:04:28
2020-06-30T10:04:28
275,787,783
0
0
null
null
null
null
UTF-8
Java
false
false
695
java
package info.unproj.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Data @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "orders") public class Order { @Column(name = "id") @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @ManyToOne(targetEntity = Item.class) private Item item; @Column(name = "amount") private Integer amount; @ManyToOne(targetEntity = Cart.class) private Cart cart; public Order(Item item, Integer amount, Cart cart) { this.item = item; this.amount = amount; this.cart = cart; } }
4954d0b1cc5b26e58ea34b92567a5da7a3408d37
bb5192bc6c532e5de5de924a2e813891ff262c1d
/app/src/main/java/in/tsdo/elw/PermissionDialogFragment.java
b73c30ebd3ce8e71c51c1d912ca8ce15f68c94df
[]
no_license
TsFreddie/EssentialLayoutWhitelist
cfb2482d1fe292e724725093b2f147d798a32db9
c13544d1b11b61ce82976e1696b65e298a8a63ab
refs/heads/master
2021-07-21T03:16:36.239906
2017-10-30T22:18:18
2017-10-30T22:18:18
103,077,258
28
5
null
null
null
null
UTF-8
Java
false
false
1,133
java
package in.tsdo.elw; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.widget.Toast; public class PermissionDialogFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the Builder class for convenient dialog construction AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(R.string.root_grant) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if (!((MainActivity)getActivity()).rootGrantPermission()) { Toast.makeText(getContext(), R.string.root_failed, Toast.LENGTH_SHORT).show(); }; } }) .setNegativeButton(android.R.string.no, null); // Create the AlertDialog object and return it return builder.create(); } }
94062394eb03c936c8df306316993518dd28091a
063f3b313356c366f7c12dd73eb988a73130f9c9
/erp_ejb/src_facturacion/com/bydan/erp/facturacion/business/entity/CentroCostoGrupoProductoAdditional.java
17b15321ed6db996805ff6945468431265d4d5df
[ "Apache-2.0" ]
permissive
bydan/pre
0c6cdfe987b964e6744ae546360785e44508045f
54674f4dcffcac5dbf458cdf57a4c69fde5c55ff
refs/heads/master
2020-12-25T14:58:12.316759
2016-09-01T03:29:06
2016-09-01T03:29:06
67,094,354
0
0
null
null
null
null
UTF-8
Java
false
false
1,887
java
/* * ============================================================================ * GNU Lesser General Public License * ============================================================================ * * BYDAN - Free Java BYDAN library. * Copyright (C) 2008 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. * * BYDAN Corporation */ /*Empresa: com.bydan *Programador: ByDan *Descripcion: Clase que contiene todos los Accesos a BDD de tabla CentroCostoGrupoProducto * Fecha Creacion: martes, 28 de mayo de 2013 **CAMBIOS***** * Motivo Cambio: * Nombre Programador: * Fecha Cambio: ************** */ package com.bydan.erp.facturacion.business.entity; import java.util.ArrayList; import javax.persistence.MappedSuperclass; import com.bydan.framework.erp.business.entity.DatoGeneral; import com.bydan.framework.erp.business.entity.*;//GeneralEntity; @MappedSuperclass @SuppressWarnings("unused") public class CentroCostoGrupoProductoAdditional extends GeneralEntity { //CONTROL_INICIO public CentroCostoGrupoProductoAdditional() throws Exception { super(); try { } catch(Exception e) { throw e; } } //CONTROL_FUNCION1 }
dc1ed48b99844810c93d8c33b4be86a13effc906
9e31bf197a8e02475589c5e537f745f59f88e412
/DataBaseUse/src/Mysql/MysqlExample2.java
049282d2fec08dfe32d7c3c582afeb327e762c53
[]
no_license
enginayna/Mysql
7fc02fe882b985177614674d4603e7847527c977
162c283f55ac062affe7384ed7ef04d45dc7b2d4
refs/heads/master
2020-04-28T04:41:10.446786
2019-03-11T11:55:01
2019-03-11T11:55:01
174,988,808
0
0
null
null
null
null
UTF-8
Java
false
false
3,166
java
package Mysql; import java.util.Scanner; public class MysqlExample2 { public static Scanner input = new Scanner(System.in); public static MysqlExample data = new MysqlExample("root", "localhost", ""); public static void main(String[] args) { /*System.out.println("Welcome to Database"); String selection = "1. Show Table\n" + "2. Add Personnel\n" + "3. Upadate Name\n" + "4. Update Surname\n" + "5. Update Identity Number\n" + "6. Update Email\n" + "7. Delete Personnel\n" + "0. Exit"; System.out.println(selection); selection();*/ data.showLine(1); } public static void selection() { int selection = 1; while (selection > 0) { System.out.println("Selection : "); selection = input.nextInt(); switch (selection) { case 1: showTable(); break; case 2: addPersonnel(); break; case 3: updateName(); break; case 4: updateSurname(); break; case 5: updadeIdentityNumber(); break; case 6: updateEmail(); break; case 7: deletePersonnel(); case 0: System.out.println("Good Bye"); break; default: System.out.println("You wrong entered. Please try again\n\n"); break; } } } public static void showTable() { data.showTable(); } public static void addPersonnel() { System.out.println("Name : "); String name = input.nextLine(); input.nextLine(); System.out.println("Surname : "); String surname = input.nextLine(); System.out.println("Identity Number : "); long identityNumber = input.nextLong(); input.nextLine(); System.out.println("Email : "); String email = input.nextLine(); System.out.println("Data saved successfully"); data.addPersonnel(name, surname, identityNumber, email); } public static void updateName() { System.out.println("New Name : "); String name = input.nextLine(); System.out.println("To be updated : "); int ID = input.nextInt(); System.out.println("Data updated successfully"); data.updateName(name, ID); } public static void updateSurname() { System.out.println("New Surname : "); String surname = input.nextLine(); System.out.println("To be updated : "); int ID = input.nextInt(); System.out.println("Data updated successfully"); data.updateSurname(surname, ID); } public static void updadeIdentityNumber() { System.out.println("New Name : "); long identityNumber = input.nextLong(); System.out.println("To be updated : "); int ID = input.nextInt(); System.out.println("Data updated successfully"); data.updateIdentityNumber(identityNumber, ID); } public static void updateEmail() { System.out.println("New Email : "); String email = input.nextLine(); System.out.println("To be updated : "); int ID = input.nextInt(); System.out.println("Data updated successfully"); data.updateEmail(email, ID); } public static void deletePersonnel() { System.out.println("To be deleted ID : "); int ID = input.nextInt(); System.out.println("Data deleted successfully"); data.deletePersonnel(ID); } }
8e80e75f379e17eb6b2e1f5af376b20c5952d988
cf525a10265820a0e571dc983791729bdb5809b2
/src/com/kurisu/skill/util/NumberInsert.java
2dd1f7034029f63c1115feba03e62a2654a185ae
[]
no_license
PWKurisu/SKHSkill
8f88691bfe4900bbe21d22a209c6ebf09b9fb150
65e797e4a0ea39948f909bf49074835cba037728
refs/heads/master
2022-12-12T21:31:34.370712
2020-09-08T12:53:04
2020-09-08T12:53:04
291,028,574
0
0
null
null
null
null
UTF-8
Java
false
false
550
java
package com.kurisu.skill.util; public class NumberInsert { public static String insert(int var, int point) { return insert(Integer.toString(var), point); } public static String insert(long var, int point) { return insert(Long.toString(var), point); } private static String insert(String str, int point) { return str.length() == 3 ? new StringBuilder(str).insert(0, "0").insert(1, ".").toString() : new StringBuilder(str).insert(str.length()-point, ".").toString(); } }
7f3613d5cb9674171023d5ab6fcda53a558f2f7e
782943bedae1c708590cd98588f56e7d4095cbf9
/app/src/test/java/okedroid/com/notes_app/ExampleUnitTest.java
f89c5c882ba7b1ddd9b7bea72f53be8d181c8ef9
[]
no_license
pandekartik007/Notes_app
f191c737c9318ad600d79de27f48e43af070e2b0
cf79c53fb275a9035b2562f6f2d29b1dae6c09f3
refs/heads/master
2020-06-17T08:35:25.326158
2019-07-08T18:17:06
2019-07-08T18:17:06
195,863,881
0
0
null
null
null
null
UTF-8
Java
false
false
383
java
package okedroid.com.notes_app; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
f9fca04e776d1c5882015762e75053872b9924f1
07ad7abba4cde32df52b3012e666863f7ba6ba09
/backend/src/main/java/com/mobilise/backend/user/UserService.java
19c70ca6157fa57d67b039bb6df2bf207d9e202e
[]
no_license
Iliyan-Y/mobilise-frontend-assessment
2dcc4a4401718f47a56bb86bd3e338a39c6c97c9
3760daea94b80942ddcd369c27b7177d3cd34d16
refs/heads/main
2023-04-02T11:52:47.136634
2021-04-05T18:08:20
2021-04-05T18:08:20
354,046,607
0
0
null
null
null
null
UTF-8
Java
false
false
1,767
java
package com.mobilise.backend.user; import org.jasypt.util.text.StrongTextEncryptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Map; import java.util.Optional; @Service public class UserService { private final UserRepository userRepository; private final StrongTextEncryptor textEncryptor = new StrongTextEncryptor(); @Autowired public UserService(UserRepository userRepository) { this.userRepository = userRepository; textEncryptor.setPassword("SuperSecret"); } public User getUserByUsername(String username) { return userRepository.findByUsername(username) .orElseThrow(() -> new IllegalStateException("User not found")); } public Map<String, String> createUser(User user) { Optional<User> isUser = userRepository.findByUsername(user.getUsername()); if (isUser.isPresent()) { throw new IllegalStateException("User already exists"); } user.setPassword(encrypt(user.getPassword())); userRepository.save(user); System.out.println("Player " + user.toString() + " created !"); return user.toJson(); } public Map<String, String> login(String username, String password){ User user = getUserByUsername(username); if (decrypt(user.getPassword()).equals(password)) { return Map.of("userId", user.getId(), "username", user.getUsername()); }else { return Map.of("message","Incorrect password"); } } private String encrypt(String myText) { String myEncryptedText = textEncryptor.encrypt(myText); return myEncryptedText; } private String decrypt(String myEncryptedText) { String plainText = textEncryptor.decrypt(myEncryptedText); return plainText; } }
b4456b52999490b2211121521f1385d57428e1d7
1ab76730a29b3da3ecf2624dad7c6f173b4ff80c
/src/main/java/iosr/facebookapp/fetcher/logging/events/PostsReadEvent.java
1599bec88e23c325e2c0dbe147c98fdb54e9312a
[]
no_license
lk2-iosr/fetcher
d951ac6efaccd71b011454c89d36e7c8ce99bdaa
70ff97fae712c05206104470467e14966bcd0a3e
refs/heads/master
2021-09-05T10:07:51.740427
2018-01-26T08:57:06
2018-01-26T08:57:06
112,945,207
0
0
null
2018-01-26T08:57:06
2017-12-03T16:44:59
Java
UTF-8
Java
false
false
494
java
package iosr.facebookapp.fetcher.logging.events; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class PostsReadEvent extends Event { @JsonProperty("page") private final String page; @JsonCreator public PostsReadEvent(@JsonProperty("eventType") final String eventType, @JsonProperty("page") final String page) { this.eventType = eventType; this.page = page; } }
2a3f9d07dd662b3d47d6fbaa9637e6ba342152b5
be609a4c07073521cd84c09ef242690cf45a583d
/schedule-console/src/main/java/com/asiainfo/monitor/busi/service/impl/APIShowCacheSVImpl.java
abb6ceb4d8b8b9cc40ee023179200592e814a442
[ "Apache-2.0" ]
permissive
zhengpeng2006/aischedule
23d852ae656f0674684fec39c393c7b1f67af931
5ff3138b8efb6f7c6f365dcdf34fc3d40400877b
refs/heads/master
2020-04-23T01:32:47.970514
2019-01-10T08:45:45
2019-01-10T08:45:45
170,816,132
0
1
Apache-2.0
2019-02-15T06:52:34
2019-02-15T06:52:32
null
UTF-8
Java
false
false
12,484
java
package com.asiainfo.monitor.busi.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.ai.appframe2.bo.DataContainer; import com.ai.appframe2.common.DataContainerInterface; import com.ai.appframe2.complex.mbean.standard.cache.CacheSummary; import com.ai.appframe2.service.ServiceFactory; import com.asiainfo.monitor.busi.asyn.operation.impl.BusiCacheTypeAsynOperate; import com.asiainfo.monitor.busi.asyn.operation.impl.FrameCacheTypeAsynOperate; import com.asiainfo.monitor.busi.config.ServerConfig; import com.asiainfo.monitor.busi.service.interfaces.IAIMonServerSV; import com.asiainfo.monitor.busi.service.interfaces.IAPIShowCacheSV; import com.asiainfo.monitor.busi.stat.BusiCacheMultitaskStat; import com.asiainfo.monitor.busi.stat.FrameCacheMultitaskStat; import com.asiainfo.monitor.interapi.api.cache.BusiCacheMonitorApi; import com.asiainfo.monitor.interapi.config.AIBusinessCacheInfo; import com.asiainfo.monitor.interapi.config.AIFrameCache; import com.asiainfo.monitor.interapi.config.AIFrameCacheInfo; import com.asiainfo.monitor.tools.common.SimpleResult; import com.asiainfo.monitor.tools.i18n.AIMonLocaleFactory; import com.asiainfo.monitor.tools.util.TypeConst; import com.asiainfo.monitor.tools.util.Util; public class APIShowCacheSVImpl implements IAPIShowCacheSV { private static transient Log log=LogFactory.getLog(APIShowCacheSVImpl.class); /** * 读取框架缓存类型 * @param appIds * @return * @throws Exception */ public List getFrameCacheType(Object[] appIds) throws Exception { List result = new ArrayList(); try { FrameCacheTypeAsynOperate asynOperate = new FrameCacheTypeAsynOperate(); int threadCount = (appIds.length >> 1) + 1; //返回虚拟机可用CPU数量 int cpuCount = Runtime.getRuntime().availableProcessors(); if (threadCount > (cpuCount * 3)) { threadCount = cpuCount * 3; } List list = asynOperate.asynOperation(threadCount, -1, appIds, -1); if (list != null && list.size() > 0) { for (int i = 0; i < list.size(); i++) { SimpleResult sr = (SimpleResult) list.get(i); if (sr != null && sr.isSucc()) { if (sr.getValue() != null && List.class.isAssignableFrom(sr.getValue().getClass())) { for (int j = 0; j < ((List) sr.getValue()).size(); j++) { String type = String.valueOf(((List) sr.getValue()).get(j)); if (!result.contains(type)) { result.add(type); } } } } } } } catch (Exception e) { log.error("Call APIShowCacheSVImpl's Method getFrameCacheType has Exception :" + e.getMessage()); } return result; } /** * 读取业务缓存类型 * @param appIds * @return * @throws Exception */ public List getBusiCacheType(Object[] appIds) throws Exception { List result = new ArrayList(); try { BusiCacheTypeAsynOperate asynOperate = new BusiCacheTypeAsynOperate(); int threadCount = (appIds.length >> 1) + 1; int cpuCount = Runtime.getRuntime().availableProcessors(); if (threadCount > (cpuCount * 3)) threadCount = cpuCount * 3; List list = asynOperate.asynOperation(threadCount, -1, appIds, -1); if (list != null && list.size() > 0) { for (int i = 0; i < list.size(); i++) { SimpleResult sr = (SimpleResult) list.get(i); if (sr != null && sr.isSucc()) { if (sr.getValue() != null) { String[] types = (String[]) sr.getValue(); if (types != null && types.length > 0) { for (int j = 0; j < types.length; j++) { if (!result.contains(types[j])) result.add(types[j]); } } } } } } } catch (Exception e) { log.error("Call APIShowCacheSVImpl's Method getFrameCacheType has Exception :" + e.getMessage()); } return result; } /** * 读取业务所有类型的缓存 * @param appId * @param type * @param key * @return * @throws Exception */ public List getBusiCache(String appId, String type, Integer start, Integer end) throws Exception { if (StringUtils.isBlank(appId)) return null; List result = new ArrayList(); try { IAIMonServerSV serverSV = (IAIMonServerSV) ServiceFactory .getService(IAIMonServerSV.class); ServerConfig appServer = serverSV.getServerByServerId(appId); if (appServer == null) { // 没找到应用实例[{0}] throw new Exception(AIMonLocaleFactory.getResource("MOS0000070", appId)); } if (appServer.getJmxSet() == null || appServer.getJmxSet().getValue().equals("OFF") || appServer.getJmxSet().getValue().equals("FALSE")) { // "应用端[appId:"+appId+"]未启动Jmx注册" throw new Exception(AIMonLocaleFactory.getResource("MOS0000071", appId)); } // 全部 if (AIMonLocaleFactory.getResource("MOS0000007").equals(type)) { type = ""; } CacheSummary[] busiCaches = BusiCacheMonitorApi.getAllCaches( appServer.getLocator_Type(), appServer.getLocator(), type); if (busiCaches != null) { for (int i = 0; i < busiCaches.length; i++) { Map tmp = new HashMap(); tmp.put("CLASSNAME", busiCaches[i].getClassName()); tmp.put("NEWCOUNT", busiCaches[i].getNewCount()); tmp.put("OLDCOUNT", busiCaches[i].getOldCount()); tmp.put("LASTREFRESHENDTIME", Util .formatDateFromLog(busiCaches[i] .getLastRefreshEndTime())); tmp.put("LASTREFRESHSTARTTIME", Util .formatDateFromLog(busiCaches[i] .getLastRefreshStartTime())); result.add(tmp); } } } catch (Exception e) { log.error("Call APIShowCacheSVImpl's Method getFrameCache has Exception :" + e.getMessage()); } return result; } /** * 根据多应用统计缓存信息 * @param appIds * @param type * @return * @throws Exception */ public DataContainerInterface[] getBusiCacheFromMultiAppForAppFrame(Object[] appIds, String type) throws Exception { if (appIds == null || appIds.length < 1) { return null; } List result = new ArrayList(); try { CacheSummary cs = null; Object[] objCache = null; Map tmp = null; int threadCount = (appIds.length >> 1) + 1; int cpuCount = Runtime.getRuntime().availableProcessors(); if (threadCount > (cpuCount * 3)) { threadCount = cpuCount * 3; } BusiCacheMultitaskStat cacheStat = new BusiCacheMultitaskStat( threadCount, -1, appIds, type); Map cacheMap = cacheStat.getSummary(); if (cacheMap != null && cacheMap.size() > 0) { objCache = cacheMap.values().toArray(); } for (int i = 0; i < objCache.length; i++) { DataContainerInterface item = new DataContainer(); cs = (CacheSummary) objCache[i]; item.set("CHK", false); item.set("CLASSNAME", cs.getClassName()); item.set("NEWCOUNT", cs.getNewCount()); item.set("OLDCOUNT", cs.getOldCount()); item.set("LASTREFRESHENDTIME", Util.formatDateFromLog(cs.getLastRefreshEndTime())); item.set("LASTREFRESHSTARTTIME", Util.formatDateFromLog(cs.getLastRefreshStartTime())); result.add(tmp); } } catch (Exception e) { log.error("Call APIShowCacheSVImpl's Method getBusiCacheFromMultiApp has Exception :" + e.getMessage()); // throw new Exception(e.getMessage()); } return (DataContainerInterface[]) result .toArray(new DataContainerInterface[0]); } /** * 读取框架所有类型的缓存 * @param appId * @param type * @param key * @return * @throws Exception */ public List getFrameCache(Object[] appIds, String type, String key, Integer start, Integer end) throws Exception { // 全部 if (StringUtils.isBlank(type) || AIMonLocaleFactory.getResource("MOS0000007").equals(type)) { type = " ";//放置空字符 } if (StringUtils.isBlank(key)) { key = " ";//放置空字符 } List result = new ArrayList(); try { AIFrameCacheInfo tmp = null; int threadCount = (appIds.length >> 1) + 1; int cpuCount = Runtime.getRuntime().availableProcessors(); if (threadCount > (cpuCount * 3)){ threadCount = cpuCount * 3; } String condition = type + TypeConst._SPLIT_CHAR + key; FrameCacheMultitaskStat stat = new FrameCacheMultitaskStat(threadCount, -1, appIds, condition); Map summary = stat.getSummary(); if (summary != null && summary.size() > 0) { Iterator it = summary.values().iterator(); AIFrameCache data = null; for (int i = start == -1 ? 0 : start - 1; i < (end == -1 ? summary.size() : end) && it.hasNext(); i++) { if (i < summary.size()) { tmp = new AIFrameCacheInfo(); data = (AIFrameCache) it.next(); // Map cacheData = new HashMap(); // cacheData.put("CHK", "false"); // cacheData.put("CACHE_TYPE", data.getType()); // cacheData.put("CACHE_KEY", data.getKey()); // if (data.getObj() != null) { // cacheData.put("CACHE_CODE", data.getObj().toString()); // } tmp.setType(data.getType()); tmp.setPrimarykey(data.getKey()); if (data.getObj() != null) { tmp.setHashcode(data.getObj().toString()); } result.add(tmp); } } } } catch (Exception e) { log.error("Call APIShowCacheSVImpl's Method getFrameCache has Exception :" + e.getMessage()); } return result; } /** * 根据多应用统计缓存信息 * @param appIds * @param type * @return * @throws Exception */ public List getBusiCacheFromMultiApp(Object[] appIds, String type)throws Exception { if (appIds == null || appIds.length < 1){ return null; } List result = new ArrayList(); try { CacheSummary cs = null; Object[] objCache = null; AIBusinessCacheInfo tmp = null; int threadCount = (appIds.length >> 1) + 1; int cpuCount = Runtime.getRuntime().availableProcessors(); if (threadCount > (cpuCount * 3)){ threadCount = cpuCount * 3; } BusiCacheMultitaskStat cacheStat = new BusiCacheMultitaskStat(threadCount, -1, appIds, type); Map cacheMap = cacheStat.getSummary(); if (cacheMap != null && cacheMap.size() > 0) { objCache = cacheMap.values().toArray(); } for (int i = 0; i < objCache.length; i++) { tmp = new AIBusinessCacheInfo(); cs = (CacheSummary) objCache[i]; // tmp.put("CHK", false); // tmp.put("CLASSNAME", cs.getClassName()); // tmp.put("NEWCOUNT", cs.getNewCount()); // tmp.put("OLDCOUNT", cs.getOldCount()); // tmp.put("LASTREFRESHENDTIME",Util.formatDateFromLog(cs.getLastRefreshEndTime())); // tmp.put("LASTREFRESHSTARTTIME",Util.formatDateFromLog(cs.getLastRefreshStartTime())); tmp.setClassname(cs.getClassName()); tmp.setNewcount(Long.toString(cs.getNewCount())); tmp.setOldcount(Long.toString(cs.getOldCount())); tmp.setLastrefreshendtime(Util.formatDateFromLog(cs.getLastRefreshEndTime())); tmp.setLastrefreshstarttime(Util.formatDateFromLog(cs.getLastRefreshStartTime())); result.add(tmp); } } catch (Exception e) { log.error("Call APIShowCacheSVImpl's Method getBusiCacheFromMultiApp has Exception :" + e.getMessage()); } return result; } /** * 读取业务缓存类型 * @param appId * @return * @throws Exception */ public List getBusiCacheType(String appId) throws Exception { if (StringUtils.isBlank(appId)) return null; List result = new ArrayList(); try { IAIMonServerSV serverSV = (IAIMonServerSV) ServiceFactory .getService(IAIMonServerSV.class); ServerConfig appServer = serverSV.getServerByServerId(appId); if (appServer == null) { // 没找到应用实例[{0}] throw new Exception(AIMonLocaleFactory.getResource("MOS0000070", appId)); } if (appServer.getJmxSet() == null || appServer.getJmxSet().getValue().equals("OFF") || appServer.getJmxSet().getValue().equals("FALSE")) { // "应用端[appId:"+appId+"]未启动Jmx注册" throw new Exception(AIMonLocaleFactory.getResource("MOS0000071", appId)); } String[] types = BusiCacheMonitorApi.getAllCacheType( appServer.getLocator_Type(), appServer.getLocator()); if (types != null && types.length > 0) { for (int i = 0; i < types.length; i++) { result.add(types[i]); } } } catch (Exception e) { log.error("Call APIShowCacheSVImpl's Method getFrameCacheType has Exception :" + e.getMessage()); } return result; } }
ec70ae6b21c7ff3abe8ceecc6c400e4f7b48c9d9
b637f838a56fefa12ab548faace0d0122041b28f
/src/main/java/com/mgaudin/chip8/instructions/SetRegisterToShiftedRightRegister.java
2c5019b9304f44b7103291c47b39041e576dcc05
[]
no_license
MaximeGaudin/Chip8_java
d35d5fb6fe7a54f200ecf1b3db51ae6cd619975d
67a50ef4cd72805f28005be37201bab9eacbfb9c
refs/heads/master
2020-03-19T06:58:31.818955
2018-06-05T12:12:15
2018-06-05T12:12:15
136,072,472
0
0
null
null
null
null
UTF-8
Java
false
false
1,009
java
package com.mgaudin.chip8.instructions; import com.mgaudin.chip8.*; import org.springframework.stereotype.Component; import static com.mgaudin.chip8.HexUtils.toHex; @Component public class SetRegisterToShiftedRightRegister extends PrioritizedInstructionExecutor { @Override public boolean matches(byte[] opcode) { return opcode[0] == 0x8 && opcode[3] == 0x6; } @Override public String prettyPrince(byte[] opcode) { return "V" + toHex(opcode[1], 1) + " = V" + toHex(opcode[2], 1) + " >> 1"; } /* * Store the value of register VY shifted right one bit in register VX * Set register VF to the least significant bit prior to the shift */ @Override public void execute(byte[] opcode, CPU cpu, Screen screen, Memory memory, Keyboard keyboard, Timers timers) { byte vY = memory.getRegister(opcode[2]); memory.setRegister((byte) 0x0F, (byte) (vY & 0b00000001)); memory.setRegister(opcode[1], (byte) (vY >> 1)); } }
888425cd2fef5781f0742a5d1dbaa94a855d6dad
fc6c869ee0228497e41bf357e2803713cdaed63e
/weixin6519android1140/src/sourcecode/com/google/android/gms/analytics/b.java
0f7037ded055b7b08f46e163fb87f56312ca21c3
[]
no_license
hyb1234hi/reverse-wechat
cbd26658a667b0c498d2a26a403f93dbeb270b72
75d3fd35a2c8a0469dbb057cd16bca3b26c7e736
refs/heads/master
2020-09-26T10:12:47.484174
2017-11-16T06:54:20
2017-11-16T06:54:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
409
java
package com.google.android.gms.analytics; @Deprecated public abstract interface b { @Deprecated public abstract int getLogLevel(); @Deprecated public abstract void setLogLevel(int paramInt); } /* Location: D:\tools\apktool\weixin6519android1140\jar\classes3-dex2jar.jar!\com\google\android\gms\analytics\b.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
65bfb7ed0c45d44c844349dc5cf808a6f262a0a8
b7bc39c604f7b83a7d7f0d750240fe86d8df7a5c
/java-project/src07/main/java/bitcamp/lms/Lesson.java
8064f6efa953cfc39fb4bf15f3576525bf5230d9
[]
no_license
ppappikko/bitcamp-java-2018-12
e79e023a00c579519ae67ba9f997b615fb539e5c
bd2a0b87c20a716d2b1e8cafc2a9cd54f683a37f
refs/heads/master
2021-08-06T17:31:37.187323
2019-07-19T04:55:07
2019-07-19T04:55:07
163,650,729
0
0
null
2020-04-30T16:14:59
2018-12-31T08:01:24
Java
UTF-8
Java
false
false
249
java
// 수업 데어터를 저장할 새로운 데이터 타입 정의 package bitcamp.lms; import java.sql.Date; public class Lesson { int num; String title; String content; Date startDate; Date endDate; int totalTime; int dayTime; }
346417e25e6cf2f30e9b7f7cd6005b54c04e07f8
19e3bfac6b9c381012c998d86e0d0a6bfcbafc6a
/Asteroids/core/src/com/neet/gamestates/GameOverState.java
e29e93276225343ce844c5a2792bf878b61a04e7
[]
no_license
MaestroShifu/Asteroids---Libgdx
47d2afc75811e7d3c12509445e295b5093f7f1a2
90fc71f98731c7163621bb8df524e8fc84a1a63b
refs/heads/master
2021-08-26T09:26:53.172291
2017-11-22T23:55:56
2017-11-22T23:55:56
111,743,170
0
0
null
null
null
null
UTF-8
Java
false
false
3,363
java
package com.neet.gamestates; import com.asteroids.game.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.neet.managers.GameKeys; import com.neet.managers.GameStateManager; import com.neet.managers.Save; public class GameOverState extends GameState{ private SpriteBatch sb; private ShapeRenderer sr; private boolean newHighScore; private char[] newName; private int currentChar; private BitmapFont gameOverFont; private BitmapFont font; public GameOverState(GameStateManager gsm) { super(gsm); } public void init() { sb = new SpriteBatch(); sr = new ShapeRenderer(); newHighScore = Save.gd.isHighScore(Save.gd.getTentativeScore()); if(newHighScore) { newName = new char[] {'A','A','A'}; currentChar = 0; } FreeTypeFontGenerator gen = new FreeTypeFontGenerator(Gdx.files.internal("fonts/Hyperspace Bold.ttf")); FreeTypeFontParameter param = new FreeTypeFontParameter(); param.size = 32; gameOverFont = gen.generateFont(param); param.size = 20; font = gen.generateFont(param); } public void update(float dt) { handleInput(); } public void draw() { sb.setProjectionMatrix(Game.cam.combined); //sr.setProjectionMatrix(Game.cam.combined); sb.begin(); String s; s = "Game Over"; GlyphLayout gt = new GlyphLayout(); gt.setText(gameOverFont, s); gameOverFont.draw(sb, s, (Game.WIDTH - gt.width) / 2, 220); if(!newHighScore) { sb.end(); return; } s = "New High Score: " + Save.gd.getTentativeScore(); gt.setText(font, s); font.draw(sb, s, (Game.WIDTH - gt.width) / 2, 180); for(int i = 0; i < newName.length; i++) { font.draw(sb, Character.toString(newName[i]), 230 + 14 * i, 120); } sb.end(); sr.begin(ShapeType.Line); sr.line(230 + 14 * currentChar, 100, 244 + 14 * currentChar, 100); sr.end(); } public void handleInput() { if(GameKeys.isPressed(GameKeys.ENTER)) { if(newHighScore) { Save.gd.addHighScore(Save.gd.getTentativeScore(), new String(newName)); Save.save(); } gsm.setState(GameStateManager.MENU); } if(GameKeys.isPressed(GameKeys.UP)) { if(newName[currentChar] == ' ') { newName[currentChar] = 'Z'; }else { newName[currentChar]--; if(newName[currentChar] < 'A') { newName[currentChar] = ' '; } } } if(GameKeys.isPressed(GameKeys.DOWN)){ if(newName[currentChar] == ' ') { newName[currentChar] = 'A'; }else { newName[currentChar]++; if(newName[currentChar] > 'Z') { newName[currentChar] = ' '; } } } if(GameKeys.isPressed(GameKeys.RIGHT)) { if (currentChar < newName.length - 1) { currentChar++; } } if(GameKeys.isPressed(GameKeys.LEFT)) { if (currentChar > 0) { currentChar--; } } //min 15 } public void dispose() { sb.dispose(); sr.dispose(); gameOverFont.dispose(); font.dispose(); } }
b94f1cc49a60c13fb896b10fd3a6d86cd51e05dc
345434d8704f1e63246bd36b91e0d838febc9f73
/app/src/main/java/com/company/NetSDK/SDKDEV_TALKDECODE_INFO.java
7e7ea51f5dea214a1006b4e5bedcabeccf433872
[]
no_license
solderzzc/xeyes
dfc2b6ed53fa092da4193d3ab1b1e807b0c59707
39e180b09169e962a2e1b260b6fe17bfcc48d63c
refs/heads/master
2020-03-07T07:09:50.691545
2016-12-07T15:49:56
2016-12-07T15:49:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
793
java
package com.company.NetSDK; import java.io.Serializable; /** * \if ENGLISH_LANG * Audio encode information * \else * SoRt1`BkPEO" * \endif */ public class SDKDEV_TALKDECODE_INFO implements Serializable { /** * */ private static final long serialVersionUID = 1L; /** * \if ENGLISH_LANG * Encode type * \else * 1`Bk@`PM * \endif */ public int encodeType; /** * \if ENGLISH_LANG * Bit:8/16 * \else * 6N;J}#,Hg8;r1 * \endif */ public int nAudioBit; /** * \if ENGLISH_LANG * Sampling rate such as 8000 or 16000 * \else * 2IQyBJ#,Hg8000;r16000 * \endif */ public int dwSampleRate; /** * \if ENGLISH_LANG * Pack Period,Unit ms * \else * 4r0|V\FZ, 5%N;ms * \endif */ public int nPacketPeriod; }
81c7b6f4874b68e760aa5b2ff9e77e8e6ab3f320
542d2de56a0f7c6a93daa4a5f39f00131ac6631d
/src/main/java/org/queeg/hadoop/tar/PathByteSink.java
65846947086f81995b274f27fd2bae52a730f29e
[ "Apache-2.0" ]
permissive
Noddy76/hadoop-tar
91492c144bc03feccbc0d4c003268c2e0333a728
3707c6a8db0c54ac9ad82251696ed882f29f569b
refs/heads/master
2021-01-01T05:40:18.867817
2019-01-16T14:53:13
2019-01-16T14:53:13
16,676,628
0
0
null
null
null
null
UTF-8
Java
false
false
1,184
java
/** * Copyright 2014 James Grant * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.queeg.hadoop.tar; import java.io.IOException; import java.io.OutputStream; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import com.google.common.io.ByteSink; public class PathByteSink extends ByteSink { private FileSystem fs; private Path path; public PathByteSink(Configuration conf, Path path) throws IOException { this.path = path; fs = path.getFileSystem(conf); } @Override public OutputStream openStream() throws IOException { return fs.create(path, true); } }
7dea9a4f68b084406eca870592de198b4af7424f
b844043af2a13e24c9a322dbb4afc51af7cf8dcc
/ib-terminal-api/src/main/java/com/henyep/ib/terminal/api/dto/request/ib/client/map/InsertFromWlRegistrationRequest.java
e458ae9893cabfa2ee9af0c3e0fcf625c5111822
[]
no_license
oscarYeung/ib_terminal
37b372ab9d33f4b029ee9a02bc519c0cc7e31c38
c83e464752e45aa356f1aad24ed2f2f5066b2e90
refs/heads/master
2022-12-24T04:49:03.603352
2019-12-11T04:09:26
2019-12-11T04:09:26
218,199,664
1
2
null
2022-12-16T09:45:08
2019-10-29T03:49:19
Java
UTF-8
Java
false
false
315
java
package com.henyep.ib.terminal.api.dto.request.ib.client.map; import com.henyep.ib.terminal.api.dto.request.IbRequestDto; public class InsertFromWlRegistrationRequest extends IbRequestDto<InsertFromWlRegistrationRequestDto>{ /** * */ private static final long serialVersionUID = -8014733204973360964L; }
868e4abc85a12cccdce29caf6335211f98e9d8a2
563e3f7b855c014c7dba23baf7e8a6fdcd187353
/src/ru/suhorukov/math/Rectangle.java
31336a384ddc48a9aef0803812b283ae3ceef681
[]
no_license
vitr1988/JavaITSuhorukov2016
baeee1eaf0f91036c3bf2ae297e689c85f98818c
b23b7620d78a6490a8cb2d6c4cfce3d3bc37bd32
refs/heads/master
2021-01-21T13:03:32.187786
2016-06-01T10:20:20
2016-06-01T10:20:20
52,803,467
0
2
null
null
null
null
UTF-8
Java
false
false
281
java
package ru.suhorukov.math; public class Rectangle extends Figure { private double length, width; public Rectangle(double a, double b){ this.length = a; this.width = b; } @Override double calclulateSquare() { return this.length * this.width; } }
6d97b1671b5fc4ac558f847c5e701caf7585401c
95ee563cf28a28f690241154e3a7c322317ee593
/src/main/java/com/n33/jvm/learn/classloader/chapther5/SimpleClassLoader.java
08bf3489524d194254da1e36b8aa8b958fa432bf
[]
no_license
sasa32456/thread_learn
b7c5dc0ece2617b758c56ccdbc0ad336d6678c55
cb8037605cb5a8b60990bf6862016d09eda0b1d2
refs/heads/master
2020-05-15T18:04:25.010607
2019-05-14T16:39:57
2019-05-14T16:39:57
182,416,450
0
0
null
null
null
null
UTF-8
Java
false
false
4,299
java
package com.n33.jvm.learn.classloader.chapther5; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; /** * 自定义类加载器 * * @author N33 * @date 2019/5/13 */ public class SimpleClassLoader extends ClassLoader { private final static String DEFAULT_DIR = "F:\\IdeaProjectsLearn\\zzz\\revert"; private String dir = DEFAULT_DIR; private String classLoaderName; public SimpleClassLoader() { super(); } public SimpleClassLoader(String classLoaderName) { super(); this.classLoaderName = classLoaderName; } public SimpleClassLoader(String classLoaderName, ClassLoader parent) { super(parent); this.classLoaderName = classLoaderName; } /** * xxx.xxx.xxx.xxx.AAA * xxx/xxx/xxx/xxx/AAA.class * * @param name * @return * @throws ClassNotFoundException */ @Override protected Class<?> findClass(String name) throws ClassNotFoundException { String classPath = name.replace(".", "/"); File classFile = new File(dir, classPath + ".class"); if (!classFile.exists()) { throw new ClassNotFoundException("The class " + name + " not found under " + dir); } byte[] classBytes = loadClassBytes(classFile); if (null == classBytes || classBytes.length == 0) { throw new ClassNotFoundException("load the class " + name + " failed"); } return this.defineClass(name, classBytes, 0, classBytes.length); } /** * 重写loadClass ,子先找,父后找 * * @param name * @param resolve * @return * @throws ClassNotFoundException */ @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Class<?> clazz = null; /** * Exception in thread "main" java.lang.ClassFormatError: Incompatible magic value 0 in class file com/n33/jvm/learn/classloader/chapther5/SimpleObject * at java.lang.ClassLoader.defineClass1(Native Method) * at java.lang.ClassLoader.defineClass(ClassLoader.java:763) * at java.lang.ClassLoader.defineClass(ClassLoader.java:642) * at com.n33.jvm.learn.classloader.chapther5.SimpleClassLoader.findClass(SimpleClassLoader.java:58) * at com.n33.jvm.learn.classloader.chapther5.SimpleClassLoader.loadClass(SimpleClassLoader.java:73) * at java.lang.ClassLoader.loadClass(ClassLoader.java:357) * at com.n33.jvm.learn.classloader.chapther5.SimpleClassLoaderTest.main(SimpleClassLoaderTest.java:12) * * * java的还是要父先找 */ if (name.startsWith("java.")) { try { ClassLoader system = ClassLoader.getSystemClassLoader(); clazz = system.loadClass(name); if (clazz != null) { if (resolve) { resolveClass(clazz); } return clazz; } } catch (Exception e) { //ignore } } try { clazz = findClass(name); } catch (Exception e) { } if (clazz == null && getParent() != null) { getParent().loadClass(name); } return clazz; } private byte[] loadClassBytes(File classFile) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileInputStream fis = new FileInputStream(classFile) ) { byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { baos.write(buffer,0,len); } baos.flush(); return baos.toByteArray(); } catch (IOException e) { e.printStackTrace(); return null; } } public String getDir() { return dir; } public void setDir(String dir) { this.dir = dir; } public String getClassLoaderName() { return classLoaderName; } public void setClassLoaderName(String classLoaderName) { this.classLoaderName = classLoaderName; } }
bfd35675417871f164a23d18d55358739e95c478
157b6cf46d813df587d07ecaa79733e1a4e008e9
/Project_Hospital/src/main/java/Controladores/UpdateL.java
904e039d719c093ff0465623937f4ad0a201a90f
[]
no_license
jamesvasqguz/Hospital
5093d9954b64802cf8ad7bf6b8d5e96630ab2bf5
e3c9f37d367d13a2b0ac726a7b76040f9481c129
refs/heads/master
2022-12-30T16:36:20.402854
2020-10-08T20:19:54
2020-10-08T20:19:54
295,066,794
0
0
null
null
null
null
UTF-8
Java
false
false
2,994
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 Controladores; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author jara */ @WebServlet(name = "UpdateL", urlPatterns = {"/UpdateL"}) public class UpdateL extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet UpdateL</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet UpdateL at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
60f429691a9ed346f68f1342da684c3a9457755e
8c18a37f359ce4d390b9c139fc7e4dbae664ccff
/src/test/java/samplegittest/SampleGitTest2.java
f41be662bf8042179a15f3d804c7597745bad489
[]
no_license
DineshKumar2018/samplegit
aaac8d63eb36d5dd4fb8edfc6d1baa8392d43094
68a1129bc11d7f89b51cd31f281628a2c7d08a59
refs/heads/master
2020-03-19T17:56:49.875566
2018-06-23T06:21:10
2018-06-23T06:21:10
136,785,959
0
0
null
null
null
null
UTF-8
Java
false
false
689
java
package samplegittest; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class SampleGitTest2 { @Test public void loginTest() throws IOException{ WebDriver wd=new FirefoxDriver(); wd.manage().window().maximize(); wd.get("http://www.ntltaxi.com/"); File src=((TakesScreenshot)wd).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(src, new File("C:\\SeleniumWorkspace\\samplegittest\\Screenshot\\test1.jpg")); } }
866d09ace0ec6f0094895441fdec1897691d0092
70eb32c4b72da6fe9c8158f2a0ddcd58afe5668d
/server/src/main/java/edu/brown/cs/student/groups/Person.java
446e8299465a7ac0b64d54849f56e108a85b8709
[]
no_license
madhavramesh/Study-Buddies
ba41335b9003648867f062f675c6661fde8c8c4a
f755558edbd16e892cb2e87a1177358d38fad10d
refs/heads/main
2023-08-31T21:42:11.348503
2021-10-28T02:39:57
2021-10-28T02:39:57
382,203,117
1
0
null
null
null
null
UTF-8
Java
false
false
2,224
java
package edu.brown.cs.student.groups; import edu.brown.cs.student.obsoletedistanceutils.DistanceUtils; import org.json.JSONException; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class Person { private final int id; private final String firstName; private final String lastName; private char[] times; private String dorm; private String preferences; private int groupId; private static int idGenerator; public Person(int id, String firstName, String lastName, String times, String dorm, String preferences, int groupId) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.times = times.toCharArray(); this.dorm = dorm; this.preferences = preferences; this.groupId = groupId; } int numIntersections(Person person) { Set<Character> otherTimes = new HashSet<>(); for (char c : person.getTimes()) { otherTimes.add(c); } int counter = 0; for (char c : this.times) { if (otherTimes.contains(c)) { ++counter; } } return counter; } double distance(Person person) throws IOException, JSONException { double[] loc1 = DistanceUtils.getLatLong(this.dorm); double[] loc2 = DistanceUtils.getLatLong(person.getDorm()); return DistanceUtils.haversineDistance(loc1, loc2); } public int getId() { return id; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public char[] getTimes() { return times; } public void setTimes(char[] times) { this.times = times; } public String getDorm() { return dorm; } public void setDorm(String dorm) { this.dorm = dorm; } public String getPreferences() { return preferences; } public void setPreferences(String preferences) { this.preferences = preferences; } public static int getIdGenerator() { return idGenerator; } public static void setIdGenerator(int idGenerator) { Person.idGenerator = idGenerator; } public int getGroupId() { return groupId; } public void setGroupId(int groupId) { this.groupId = groupId; } }
f98f7cc9bb836c54b27746fb013eeed613e9176e
0704a8046c4e3603b40a8da2334ad08085a7b72b
/sveditor/plugins/net.sf.sveditor.core/src/net/sf/sveditor/core/db/index/builder/SVDBIndexChangePlanRefresh.java
4dbb29502297695c16e3d5e407004937eb208290
[]
no_license
stanlyliusu/sveditor
de31f8ba449a048283483c387d906a7352e471f9
1346b843f3ce0e044f6859159f0f4e44337f1e44
refs/heads/master
2021-01-18T00:27:27.661005
2016-05-16T17:05:04
2016-05-16T17:05:04
59,161,275
1
0
null
2016-05-19T00:37:50
2016-05-19T00:37:50
null
UTF-8
Java
false
false
802
java
package net.sf.sveditor.core.db.index.builder; public class SVDBIndexChangePlanRefresh extends SVDBIndexChangePlan { public SVDBIndexChangePlanRefresh(ISVDBIndexChangePlanner planner) { super(planner, SVDBIndexChangePlanType.Refresh); } @Override public boolean canMerge(ISVDBIndexChangePlan other) { return (merge(other) != null); } @Override public ISVDBIndexChangePlan merge(ISVDBIndexChangePlan other) { // We can merge if the 'other' plan supersedes // or is identical to this one if (other.getPlanner() == getPlanner()) { if (other.getType() == SVDBIndexChangePlanType.RebuildIndex) { // Supersedes our refresh plan return other; } else if (other.getType() == SVDBIndexChangePlanType.Refresh) { // Equals return other; } } return null; } }
473b895e054f82f5cd57cd2125ae8b8e1faf7a96
de15a413878df4b3d39f5e3a11d51a313f854081
/src/main/java/com/demeng7215/cytsoulbound/CYTSoulbound.java
06e84dca1f4668a928c4f958824659194b2db78c
[]
no_license
Demeng7215/CYTSoulbound
4cec8e7a41f58630e6242cbe51bf679918d2ee04
a8b8892b9610b4439d5c119751aca7db7e636fa2
refs/heads/master
2020-09-22T11:31:29.104744
2019-12-01T14:39:06
2019-12-01T14:39:06
225,176,615
1
0
null
null
null
null
UTF-8
Java
false
false
1,700
java
package com.demeng7215.cytsoulbound; import com.demeng7215.cytsoulbound.commands.SoulboundCmd; import com.demeng7215.cytsoulbound.lib.DemLib; import com.demeng7215.cytsoulbound.lib.utils.Registerer; import com.demeng7215.cytsoulbound.lib.utils.files.CustomConfig; import com.demeng7215.cytsoulbound.lib.utils.messages.MessageUtils; import com.demeng7215.cytsoulbound.listeners.DeathEvent; import lombok.Getter; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.plugin.java.JavaPlugin; public final class CYTSoulbound extends JavaPlugin { @Getter private static CYTSoulbound plugin; // settings.yml private CustomConfig settings; @Override public void onEnable() { DemLib.setPlugin(this); MessageUtils.setPrefix(""); MessageUtils.log(null, "Starting enable for CYTSoulbound..."); plugin = this; MessageUtils.log(null, "Loading settings file..."); // Create or load the file. try { this.settings = new CustomConfig("settings.yml"); } catch (final Exception ex) { ex.printStackTrace(); return; } MessageUtils.log(null, "Registering commands..."); Registerer.registerCommand(new SoulboundCmd()); MessageUtils.log(null, "Registering listeners..."); Registerer.registerListeners(new DeathEvent()); MessageUtils.console("&aCYTSoulbound has been successfully enabled."); } @Override public void onDisable() { MessageUtils.console("&cCYTSoulbound has been successfully disabled."); } public FileConfiguration getSettings() { return settings.getConfig(); } }
4bfb9c30742101b4eee1be290782d6640a42f6ba
51e3931d2016790767fd66be945331c35ba50cf1
/app/src/main/java/com/pyrosegames/animedownloader/AnimeGalleryInfo.java
fce7d7cd99b7f0436ae3820780b1f128db1f3828
[]
no_license
riccardocescon/AnimeDownloaderAndroid
5fbc66c26fe0104e3c55879019e2b1dd0e636a49
4190729a85f11151d8944bbfda22b5bf6924384c
refs/heads/main
2023-07-19T07:29:39.461571
2021-08-29T12:26:15
2021-08-29T12:26:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,302
java
package com.pyrosegames.animedownloader; public class AnimeGalleryInfo { private String animeName; private String animeEps; private String downloadDate; public static int day = 0; public static int month = 1; public static int year = 2; public static int hour = 3; public static int minute = 4; public static int second = 5; public AnimeGalleryInfo(String animeName, String animeEps, String downloadDate){ this.animeName = animeName; this.animeEps = animeEps; this.downloadDate = downloadDate; } public String getAnimeName(){ return animeName; } public String getAnimeEps(){ return animeEps; } public String getDownloadDate(){ return downloadDate; } //Mon Aug 23 13:21:39 GMT+02:00 2021 public String getDate(){ String[] parts = downloadDate.split(" "); String strictedMonth = parts[1]; String day = parts[2]; String year = parts[parts.length - 1]; String month = ""; String compactHour = parts[3]; String[] hourParts = compactHour.split(":"); String hour = hourParts[0]; String minute = hourParts[1]; String second = hourParts[2]; switch (strictedMonth){ case "Jan": month = "01"; break; case "Feb": month = "02"; break; case "Mar": month = "03"; break; case "Apr": month = "04"; break; case "May": month = "05"; break; case "June": month = "06"; break; case "July": month = "07"; break; case "Aug": month = "08"; break; case "Sept": month = "09"; break; case "Oct": month = "10"; break; case "Nov": month = "11"; break; case "Dec": month = "12"; break; } String date = day + "/" + month + "/" + year + "/" + hour + "/" + minute + "/" + second; return date; } }
6ee7d4c4168596a5e982a45caa2d96d9bee868ce
91ebb2bdf62b7bdaf7d402da2c9c2a9131fdc93d
/Java/Java for Sale/SoftwareEngineering_2/src/alexander/parfenov/lab1/Task5.java
664daf99bfad31c8620618c7f1cf85fff3c85636
[]
no_license
Nik3000/University-projects
ea2223cfae4e62cf40771e4da01339b7fa414686
eaf23d727aa70e54132f262e7b3efb4f0fb50ad8
refs/heads/master
2020-04-13T02:06:00.600375
2018-12-23T13:30:15
2019-01-30T15:22:28
162,893,291
0
0
null
null
null
null
UTF-8
Java
false
false
672
java
package alexander.parfenov.lab1; import java.util.Scanner; public class Task5 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Введите год поступления"); int year1 = in.nextInt(); System.out.println("Введите текущий месяц"); int mouth = in.nextInt(); System.out.println("Введите текущий год"); int year2 = in.nextInt(); boolean flag = mouth <= 6; int a=year2-year1-Boolean.compare(flag,false); boolean flag2 = a >= 4; System.out.print(flag2); } }
9d5f4820353db01475f49cab5519e79d30e62ba4
3ac48897e424e78a72d5f2773782848e23342e83
/While_code.java
82501220a068179d773776d2f767436e8ac71478
[]
no_license
Alka20/Crossasyst_trainee
e85e5247242cae0f2a86cdc6c8cbefdaf0c25e09
2e9e3eaa7387818b95221cfacf697ad81e88a035
refs/heads/main
2023-09-01T19:45:29.307750
2021-10-11T09:34:33
2021-10-11T09:34:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
603
java
import java.util.*; class While_code { public static void main(String args[]) { Scanner input=new Scanner(System.in); int year; do { System.out.print("Enter a year or zero to quit"); year=input.nextInt(); if((year%4==0) && (year % 100 != 0)|| (year%400==0)) { System.out.printf("%d is a leap year \n",year); } else { System.out.printf("%d is not a leap year \n",year); } System.out.print("Enter Another year or zero to quit:"); year=input.nextInt(); }while(year != 0); System.out.println("Finished"); } }
1ae76bf6741c134b721ba7937cf6dc2e4da2456d
ba552bd81c3785bff1fd584f1c30846aac4a4da5
/source/tomcatandjavaweb/chr05/helloapp/src/mypack/Servlet2.java
8d9aab346dfa81b267a53d1d0720887e8331d21f
[]
no_license
closing/mydatabase
fe56dd3d43db296ef561ff3106f1bff34d6bd880
5730293d916a2a69028ce2bddb1caeb971656140
refs/heads/master
2021-05-12T06:13:42.540175
2019-04-10T00:34:28
2019-04-10T00:34:28
117,212,682
1
0
null
null
null
null
UTF-8
Java
false
false
848
java
package mypack; import javax.servlet.GenericServlet; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.ServletException; import javax.servlet.ServletContext; import javax.servlet.RequestDispatcher; import java.io.IOException; import java.io.PrintWriter; public class Servlet2 extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { int num1 = Integer.parseInt((String)request.getAttribute("num1")); int num2 = Integer.parseInt((String)request.getAttribute("num2")); int sum = num1 + num2; request.setAttribute("sum", sum); ServletContext context = getServletContext(); RequestDispatcher dispatcher = context.getRequestDispatcher("/servlet3"); dispatcher.forward(request, response); } }
e7c9bfd2a9498a98ad8b0686302557ac84f2c62d
a2353e4d9dc2b7797dee2587c66c950924b141e2
/control-stress-application/src/main/java/com/extl/jade/user/CreateVDCResponse.java
f653986b277337e39879e0df74cca2148fc43dbb
[ "Apache-2.0" ]
permissive
tuwiendsg/ADVISE
d06f8efe6658cb0d7b6502ff8d537cf9c1cd8f7e
b7ffadb286fc4e65fbd083b47842c8a62b338af8
refs/heads/master
2020-03-30T20:25:35.023813
2015-01-30T14:56:28
2015-01-30T14:56:28
19,457,103
1
0
null
null
null
null
UTF-8
Java
false
false
1,343
java
package com.extl.jade.user; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * Output result for method createVDC * * <p>Java class for createVDCResponse complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="createVDCResponse"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="job" type="{http://extility.flexiant.net}job" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "createVDCResponse", propOrder = { "job" }) public class CreateVDCResponse { protected Job job; /** * Gets the value of the job property. * * @return * possible object is * {@link Job } * */ public Job getJob() { return job; } /** * Sets the value of the job property. * * @param value * allowed object is * {@link Job } * */ public void setJob(Job value) { this.job = value; } }
88ce91ae767f48c1a3e8e5319e9ca8313cd6ad7b
92c2acdc360826412a9fa2560b4ee3e1cfb8ba95
/src/org/ctp/enchantmentsolution/nms/abilities/IronDefenseContacts.java
647b73f8b291033918e2ef02a188cd48de89660b
[]
no_license
crashtheparty/EnchantmentSolutionLegacy
2618b20aa866077bc1fc0b895a88d78ed21ab2e7
9c2e63b6f15c0c185d976ba19c51f2c4f068ed73
refs/heads/master
2020-04-10T07:43:03.532770
2019-05-21T04:19:12
2019-05-21T04:19:12
160,886,909
0
0
null
null
null
null
UTF-8
Java
false
false
878
java
package org.ctp.enchantmentsolution.nms.abilities; import java.util.Arrays; import java.util.List; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.ctp.enchantmentsolution.EnchantmentSolution; public class IronDefenseContacts { public static List<DamageCause> getDamageCauses(){ if(EnchantmentSolution.getPlugin().getBukkitVersion().getVersionNumber() > 6) { return Arrays.asList(DamageCause.BLOCK_EXPLOSION, DamageCause.CONTACT, DamageCause.CUSTOM, DamageCause.ENTITY_ATTACK, DamageCause.ENTITY_EXPLOSION, DamageCause.ENTITY_SWEEP_ATTACK, DamageCause.LIGHTNING, DamageCause.PROJECTILE, DamageCause.THORNS); } return Arrays.asList(DamageCause.BLOCK_EXPLOSION, DamageCause.CONTACT, DamageCause.CUSTOM, DamageCause.ENTITY_ATTACK, DamageCause.ENTITY_EXPLOSION, DamageCause.LIGHTNING, DamageCause.PROJECTILE, DamageCause.THORNS); } }
8af5e85f09fab5da377911f6d7b5581f6f7c1c96
1818336d41a50bace91a97c36fd50f196d8ea35b
/core/src/main/java/com/blackbox/foundation/common/PrivateProfilePredicate.java
07745222260235ba6b28c408bf26443f72ee00e5
[]
no_license
ayax79/bb
d7a9a4faaa6bdd2a548133290e3eb1d7ea857772
ce7743b000c8eb24a2ce7ab16dd711acf9cd3f41
refs/heads/master
2020-05-18T04:02:13.299916
2010-03-01T19:04:00
2010-03-01T19:04:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
362
java
package com.blackbox.foundation.common; import com.blackbox.foundation.user.Profile; import com.google.common.base.Predicate; /** * @author [email protected] */ public final class PrivateProfilePredicate implements Predicate<Profile> { @Override public boolean apply(Profile input) { return input.getMood().isMakePrivate(); } }
a1782cbdee1831767e20917ef725d7a8e334e903
09cd81858f117a6351b846649ec1bddbe1bd1c8d
/src/main/java/com/baizhi/shiro/ShiroFilter.java
0322302a27558aac208d5d6facb1788be18e1475
[]
no_license
huzxdgithub/LaterProject
0da88f2675e652e29e84476c06330c8c420babeb
514824ef03ccf1b133e9cdafb36a10ba2173c42a
refs/heads/master
2022-06-22T09:58:26.148847
2019-12-26T02:18:28
2019-12-26T02:18:28
190,301,888
0
0
null
2022-06-17T02:12:11
2019-06-05T01:01:13
JavaScript
UTF-8
Java
false
false
2,410
java
package com.baizhi.shiro; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.cache.CacheManager; import org.apache.shiro.cache.MemoryConstrainedCacheManager; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; @Component public class ShiroFilter { //创建 ShiroFilterFactoryBean对象 @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){ ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); //添加匿名资源 Map<String,String> map = new HashMap<>(); map.put("/backstage/**","anon"); map.put("/Admin/login","anon"); map.put("/login/**","anon"); //放入匿名资源 shiroFilterFactoryBean.setFilterChainDefinitionMap(map); //如果访问了非匿名资源并且未认证跳入该页面 shiroFilterFactoryBean.setLoginUrl("/login/login.jsp"); //添加SecurityManager 这个是SecurityManager的子类 shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager); return shiroFilterFactoryBean; } @Bean public DefaultWebSecurityManager defaultWebSecurityManager(MyRealm myRealm){ DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager(); //添加shiro缓存 MemoryConstrainedCacheManager memoryConstrainedCacheManager=new MemoryConstrainedCacheManager(); defaultWebSecurityManager.setCacheManager(memoryConstrainedCacheManager); //添加自定义Realm defaultWebSecurityManager.setRealm(myRealm); return defaultWebSecurityManager; } @Bean public MyRealm getMyRealm(){ MyRealm myRealm = new MyRealm(); //添加信息凭证 加密 加散列 加盐 盐在 myRealm里面的认证里面 HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); hashedCredentialsMatcher.setHashAlgorithmName("Md5"); hashedCredentialsMatcher.setHashIterations(1024); myRealm.setCredentialsMatcher(hashedCredentialsMatcher); return myRealm; } }
4bc2c259cced75a3fff016a47bd0f2d792717f6b
8becb26a281bb9e3f0ecfe3ee0d99b8c21e48274
/src/taeha/wheelloader/fseries_monitor/menu/mode/PressureCalibration.java
046fa1af5ba55dbd5de0b3c55ac69d48dcf8b741
[]
no_license
Itgunny/ECS_MS12_02_WLF_MONITOR_Android_APP
74f0afc2b15768cd6acf3b88c80afd04cec69656
faf5fc00cf5565b21c1af2682ca836251fc82257
refs/heads/master
2020-03-21T13:38:27.577658
2018-01-09T07:57:09
2018-01-09T07:57:09
138,617,293
0
0
null
null
null
null
UHC
Java
false
false
19,764
java
package taeha.wheelloader.fseries_monitor.menu.mode; import java.util.Timer; import java.util.TimerTask; import taeha.wheelloader.fseries_monitor.animation.AppearAnimation; import taeha.wheelloader.fseries_monitor.animation.ChangeFragmentAnimation; import taeha.wheelloader.fseries_monitor.animation.DisappearAnimation; import taeha.wheelloader.fseries_monitor.animation.MainBodyShiftAnimation; import taeha.wheelloader.fseries_monitor.animation.LeftRightShiftAnimation; import taeha.wheelloader.fseries_monitor.main.CAN1CommManager; import taeha.wheelloader.fseries_monitor.main.Home; import taeha.wheelloader.fseries_monitor.main.ParentFragment; import taeha.wheelloader.fseries_monitor.main.R; import taeha.wheelloader.fseries_monitor.main.R.string; import taeha.wheelloader.fseries_monitor.menu.preference.DisplayTypeFragment.EnableButtonTimerClass; import taeha.wheelloader.fseries_monitor.main.TextFitTextView; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Layout; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.AbsoluteLayout; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; public class PressureCalibration extends ParentFragment{ //CONSTANT//////////////////////////////////////// private static final int NORMAL = 0; private static final int SUCCESS = 2; private static final int SUCCESS_CAL2 = 4; private static final int TIMER_OVERFLOW_ERROR = 11; private static final int NOSENSOR_ERROR = 12; private static final int BOOMUP_SPEED_ERROR = 13; private static final int LOW_HYDRAULIC_OIL_ERROR = 14; // ++, --, 150204 bwk ////////////////////////////////////////////////// //RESOURCE//////////////////////////////////////// ImageButton imgbtnCancel; TextFitTextView textViewCancel; TextFitTextView textViewTitle; TextFitTextView textViewStart; TextView textViewText1; TextView textViewText2; TextView textViewText3; TextView textViewOrder4; TextView textViewText4; TextFitTextView textViewHYDTitle; TextFitTextView textViewHYDData; // ++, --, 150204 bwk TextView textViewWarning; ImageView imgViewStep1; ImageView imgViewStep2; ProgressBar progressBoomPressure; ////////////////////////////////////////////////// //VALUABLE//////////////////////////////////////// int HYD; // ++, --, 150204 bwk // Timer private Timer mCheckTimer = null; private Timer mEnableButtonTimer = null; private int StatusCNT; int Order; int CursurIndex; Handler HandleCursurDisplay; ////////////////////////////////////////////////// //Fragment//////////////////////////////////////// ////////////////////////////////////////////////// //ANIMATION/////////////////////////////////////// /////////////////////////////////////////////////// //TEST//////////////////////////////////////////// ////////////////////////////////////////////////// //Life Cycle Function///////////////////////////// @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub TAG = "PressureCalibration"; Log.d(TAG, "onCreateView"); mRoot = inflater.inflate(R.layout.menu_body_management_calibration_pressure, null); InitResource(); InitValuables(); InitButtonListener(); CursurDisplay(CursurIndex); ParentActivity.ScreenIndex = ParentActivity.SCREEN_STATE_MENU_MODE_ETC_CALIBRATION_PRESSURE_TOP; ParentActivity._MenuBaseFragment._MenuInterTitleFragment.SetTitleText(ParentActivity.getResources().getString(R.string.Boom_Pressure_Calibration), 172); if(CAN1Comm.Get_ComponentCode_1699_PGN65330_EHCU() == CAN1CommManager.STATE_COMPONENTCODE_EHCU) StartEnableButtonTimer(); HandleCursurDisplay = new Handler() { @Override public void handleMessage(Message msg) { CursurDisplay(msg.what); } }; return mRoot; } @Override public void onDestroyView() { // TODO Auto-generated method stub super.onDestroyView(); CancelCheckTimer(); CAN1Comm.Set_RequestBoomPressureCalibration_PGN61184_201(0); CAN1Comm.Set_RequestBoomBucketAngleSensorCalibration_PGN61184_201(0); CAN1Comm.Set_RequestAEB_PGN61184_201(0); CAN1Comm.Set_RequestBrakePedalPositionSensorCalibration_PGN61184_201(0); CAN1Comm.Set_RequestBucketDumpCalibration_PGN61184_201(0); CAN1Comm.TxCANToMCU(201); CAN1Comm.Set_RequestBoomPressureCalibration_PGN61184_201(3); CAN1Comm.Set_RequestBoomBucketAngleSensorCalibration_PGN61184_201(15); CAN1Comm.Set_RequestAEB_PGN61184_201(3); CAN1Comm.Set_RequestBrakePedalPositionSensorCalibration_PGN61184_201(3); CAN1Comm.Set_RequestBucketDumpCalibration_PGN61184_201(3); } //////////////////////////////////////////////// //Common Function////////////////////////////// @Override protected void InitResource() { // TODO Auto-generated method stub imgbtnCancel = (ImageButton)mRoot.findViewById(R.id.ImageButton_menu_body_management_calibration_pressure_low_cancel); textViewCancel = (TextFitTextView)mRoot.findViewById(R.id.textView_menu_body_management_calibration_pressure_low_cancel); textViewCancel.setText(getString(ParentActivity.getResources().getString(R.string.Cancel), 16)); textViewTitle = (TextFitTextView)mRoot.findViewById(R.id.textView_menu_body_management_calibration_pressure_title); textViewTitle.setText(getString(ParentActivity.getResources().getString(R.string.First_Calibration), 353)); textViewStart = (TextFitTextView)mRoot.findViewById(R.id.textView_menu_body_management_calibration_pressure_main_start); textViewStart.setText(getString(ParentActivity.getResources().getString(R.string.Start), 352)); textViewText1 = (TextView)mRoot.findViewById(R.id.textView_menu_body_management_calibration_pressure_main_step_1); textViewText1.setText(getString(ParentActivity.getResources().getString(R.string.Roll_in_the_bucket_at_max_range_lower_the_boom_at_min_height), 355)); textViewText2 = (TextView)mRoot.findViewById(R.id.textView_menu_body_management_calibration_pressure_main_step_2); textViewText2.setText(getString(ParentActivity.getResources().getString(R.string.Press_Start_button_lift_the_boom_with_the_hydraulic_control_in_detent_position), 356)); textViewText3 = (TextView)mRoot.findViewById(R.id.textView_menu_body_management_calibration_pressure_main_step_3); textViewText3.setText(getString(ParentActivity.getResources().getString(R.string.Boom_lifting_will_be_stopped_automatically_at_a_certain_position_and_calibration_is_completed), 357)); textViewOrder4 = (TextView)mRoot.findViewById(R.id.textView_menu_body_management_calibration_pressure_main_order_4); textViewText4 = (TextView)mRoot.findViewById(R.id.textView_menu_body_management_calibration_pressure_main_step_4); textViewText4.setText(getString(ParentActivity.getResources().getString(R.string.Engine_Mode_Set_P_Mode_For_Calibration), 473)); textViewHYDTitle = (TextFitTextView)mRoot.findViewById(R.id.textView_menu_body_management_calibration_pressure_main_HYD_Temp); textViewHYDTitle.setText(getString(ParentActivity.getResources().getString(R.string.HYD_Temp), 111)); textViewHYDData = (TextFitTextView)mRoot.findViewById(R.id.textView_menu_body_management_calibration_pressure_main_HYD_Temp_value); // ++, --, 150204 bwk textViewWarning = (TextView)mRoot.findViewById(R.id.textView_menu_body_management_calibration_pressure_main_warning); textViewWarning.setText(getString(ParentActivity.getResources().getString(R.string.Pressure_Calibration_Warning), 384)); imgViewStep1 = (ImageView)mRoot.findViewById(R.id.imageView_menu_body_management_calibration_pressure_step_1); imgViewStep2 = (ImageView)mRoot.findViewById(R.id.imageView_menu_body_management_calibration_pressure_step_2); progressBoomPressure = (ProgressBar)mRoot.findViewById(R.id.progressBar_menu_body_management_calibration_pressure); progressBoomPressure.setMax(115); // 23Sec. progressBoomPressure.setProgress(0); } protected void InitValuables() { // TODO Auto-generated method stub super.InitValuables(); StatusCNT = 0; Order = 0; CursurIndex = 1; } @Override protected void InitButtonListener() { // TODO Auto-generated method stub imgbtnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub ClickCancel(); } }); textViewStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub ClickStart(); } }); } @Override protected void GetDataFromNative() { // TODO Auto-generated method stub HYD = CAN1Comm.Get_HydraulicOilTemperature_101_PGN65431(); // ++, --, 150204 bwk } @Override protected void UpdateUI() { // TODO Auto-generated method stub HYDDisplay(textViewHYDData,HYD,ParentActivity.UnitTemp); // ++, --, 150204 bwk BoomPressureProgressDisplay(StatusCNT); } ///////////////////////////////////////////////////////////////////// public void ClickCancel(){ if(ParentActivity.AnimationRunningFlag == true) return; else ParentActivity.StartAnimationRunningTimer(); // ++, 150210 bwk /* ParentActivity._MenuBaseFragment.showCalibrationAnimation(); */ // ++, 150309 bwk //if(ParentActivity.OldScreenIndex == Home.SCREEN_STATE_MAIN_B_TOP){ //ParentActivity._MainChangeAnimation.StartChangeAnimation(ParentActivity._MainBBaseFragment); if(ParentActivity.OldScreenIndex == Home.SCREEN_STATE_MAIN_A_TOP || ParentActivity.OldScreenIndex == Home.SCREEN_STATE_MAIN_B_TOP){ ParentActivity.OldScreenIndex = Home.SCREEN_STATE_MENU_MODE_ETC_CALIBRATION_PRESSURE_TOP; ParentActivity.showMaintoKey(CAN1CommManager.WORK_LOAD); // --, 150309 bwk //ParentActivity._MainBBaseFragment.showWorkLoadAnimation(); } else if(ParentActivity.OldScreenIndex == Home.SCREEN_STATE_MENU_MODE_HYD_WORKLOAD_TOP) { ParentActivity.OldScreenIndex = Home.SCREEN_STATE_MENU_MODE_ETC_CALIBRATION_PRESSURE_TOP; ParentActivity._MenuBaseFragment.showBodyWorkLoad(); } else { // ++, 150409 cjg // ParentActivity._MenuBaseFragment.showCalibrationAnimation(); ParentActivity._MenuBaseFragment.showBodyModeAnimation(); ParentActivity._MenuBaseFragment._MenuModeFragment.setFirstScreen(Home.SCREEN_STATE_MENU_MODE_ETC_CALIBRATION_TOP); // --, 150409 cjg } } public void ClickStart(){ if(Order == 0){ CAN1Comm.Set_RequestBoomPressureCalibration_PGN61184_201(1); CAN1Comm.TxCANToMCU(201); CAN1Comm.Set_RequestBoomPressureCalibration_PGN61184_201(3); StatusCNT = 0; CancelCheckTimer(); StartCheckTimer(); }else if(Order == 1){ CAN1Comm.Set_RequestBoomPressureCalibration_PGN61184_201(2); CAN1Comm.TxCANToMCU(201); CAN1Comm.Set_RequestBoomPressureCalibration_PGN61184_201(3); progressBoomPressure.setMax(90); // 18Sec. StatusCNT = 0; CancelCheckTimer(); StartCheckTimer(); } StartButtonOnOff(false); } ///////////////////////////////////////////////////////////////////// public void Order2Display(){ textViewTitle.setText(getString(ParentActivity.getResources().getString(string.Second_Calibration), 354)); textViewText2.setText(getString( ParentActivity.getResources().getString(string.Set_P_mode_step_on_pedal_max_range_press_Start_button_lift_the_boom_with_the_hydraulic_control_in_detent_position), 358)); textViewOrder4.setVisibility(View.VISIBLE); textViewText4.setVisibility(View.VISIBLE); imgViewStep1.setImageResource(R.drawable.menu_management_boom_pressure_step_off); imgViewStep2.setImageResource(R.drawable.menu_management_boom_pressure_step_on); StatusCNT = 0; } public void BoomPressureProgressDisplay(int progress){ progressBoomPressure.setProgress(progress); } public void StartButtonOnOff(boolean flag){ if(flag == true){ textViewStart.setClickable(true); textViewStart.setAlpha((float)1.0); CursurIndex = 1; CursurDisplay(CursurIndex); }else{ textViewStart.setClickable(false); textViewStart.setAlpha((float)0.5); CursurIndex = 2; CursurDisplay(CursurIndex); } } ///////////////////////////////////////////////////////////////////// // ++, 150204 bwk public void HYDDisplay(TextView textData, int Data, int Unit){ if(Unit == Home.UNIT_TEMP_F){ textData.setText(": " + ParentActivity.GetTemp(Data,Unit) + " " + getString(ParentActivity.getResources().getString(string.F), 9)); }else{ textData.setText(": " + ParentActivity.GetTemp(Data,Unit) + " " + getString(ParentActivity.getResources().getString(string.C), 8)); } } // --, 150204 bwk public void CheckBoomPressureProgressStatus(int StatusCnt){ int Result; Result = CAN1Comm.Get_BoomPressureCalibrationStatus_1908_PGN61184_202(); Log.d(TAG,"Result : " + Integer.toString(Result)+" StatusCnt:"+Integer.toString(StatusCnt)); //if((StatusCnt >= 25) && (StatusCnt <= 90)) // 5 Sec ~ 15 Sec if((StatusCnt >= 25)) // 5 Sec ~ { if( (Result == 2) || (Result == 4) || (Result == 11) || (Result == 12) || (Result == 13) || (Result == 14)) // ++, --, 150204 bwk : Result = 14 추가 { CAN1Comm.Set_RequestBoomPressureCalibration_PGN61184_201(0); CAN1Comm.Set_RequestBoomBucketAngleSensorCalibration_PGN61184_201(0); CAN1Comm.Set_RequestAEB_PGN61184_201(0); CAN1Comm.Set_RequestBrakePedalPositionSensorCalibration_PGN61184_201(0); CAN1Comm.TxCANToMCU(201); CAN1Comm.Set_RequestBoomPressureCalibration_PGN61184_201(3); CAN1Comm.Set_RequestBoomBucketAngleSensorCalibration_PGN61184_201(15); CAN1Comm.Set_RequestAEB_PGN61184_201(3); CAN1Comm.Set_RequestBrakePedalPositionSensorCalibration_PGN61184_201(3); if(Order == 0){ StatusCNT = 115; }else if(Order == 1){ StatusCNT = 90; } switch (Result) { case NORMAL: break; case SUCCESS: Order = 1; Order2Display(); ParentActivity._PressureCalibrationResultPopup.setTextTitle( getString(ParentActivity.getResources().getString(string.First_boom_pressure_calibration_completed), 362)); ParentActivity._PressureCalibrationResultPopup.setExitFlag(false); ParentActivity.showPressureCalibrationResult(); Log.d(TAG,"SUCCESS"); break; case SUCCESS_CAL2: ParentActivity._PressureCalibrationResultPopup.setTextTitle( getString(ParentActivity.getResources().getString(string.Calibration_completed), 379)); ParentActivity._PressureCalibrationResultPopup.setExitFlag(true); ParentActivity.showPressureCalibrationResult(); break; case TIMER_OVERFLOW_ERROR: ParentActivity._PressureCalibrationResultPopup.setTextTitle( getString(ParentActivity.getResources().getString(string.Time_Out), 382)); ParentActivity._PressureCalibrationResultPopup.setExitFlag(false); ParentActivity.showPressureCalibrationResult(); Log.d(TAG,"TIMER_OVERFLOW_ERROR"); break; case NOSENSOR_ERROR: ParentActivity._PressureCalibrationResultPopup.setTextTitle( getString(ParentActivity.getResources().getString(string.Sensor_Error), 381)); ParentActivity._PressureCalibrationResultPopup.setExitFlag(false); ParentActivity.showPressureCalibrationResult(); Log.d(TAG,"NOSENSOR_ERROR"); break; case BOOMUP_SPEED_ERROR: ParentActivity._PressureCalibrationResultPopup.setTextTitle( getString(ParentActivity.getResources().getString(string.Boom_Up_Speed_Error), 383)); ParentActivity._PressureCalibrationResultPopup.setExitFlag(false); ParentActivity.showPressureCalibrationResult(); Log.d(TAG,"Boom_Up_Speed_Error"); break; // ++, 150204 bwk case LOW_HYDRAULIC_OIL_ERROR: if(Order == 0){ Order = 1; Order2Display(); // ++, 160317 bwk //ParentActivity._PressureCalibrationResultPopup.setTextTitle( // getString(ParentActivity.getResources().getString(string.Hydraulic_Oil_Temp_Error), 385)); // ++, --, 160323 bwk 다국어 숫자 잘못되어 있는거 수정함!!!!! ParentActivity._PressureCalibrationResultPopup.setTextTitle( getString(ParentActivity.getResources().getString(string.First_boom_pressure_calibration_completed), 362)); // --, 160317 bwk ParentActivity._PressureCalibrationResultPopup.setExitFlag(false); ParentActivity.showPressureCalibrationResult(); }else { ParentActivity._PressureCalibrationResultPopup.setTextTitle( getString(ParentActivity.getResources().getString(string.Calibration_completed), 379)); ParentActivity._PressureCalibrationResultPopup.setExitFlag(true); ParentActivity.showPressureCalibrationResult(); } Log.d(TAG,"Low_Hydraulic_Oil_Error"); break; // --, 150204 bwk } StartButtonOnOff(true); CancelCheckTimer(); } } } public class CheckTimerClass extends TimerTask{ @Override public void run() { // TODO Auto-generated method stub ParentActivity.runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub StatusCNT++; CheckBoomPressureProgressStatus(StatusCNT); UpdateUI(); } }); } } public void StartCheckTimer(){ CancelCheckTimer(); mCheckTimer = new Timer(); mCheckTimer.schedule(new CheckTimerClass(),0,200); } public void CancelCheckTimer(){ if(mCheckTimer != null){ mCheckTimer.cancel(); mCheckTimer.purge(); mCheckTimer = null; } } ///////////////////////////////////////////////////////////////////// public class EnableButtonTimerClass extends TimerTask{ @Override public void run() { // TODO Auto-generated method stub ParentActivity.runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub if(ParentActivity.AnimationRunningFlag == false) { CancelEnableButtonTimer(); ParentActivity.showCalibrationEHCUPopup(); } } }); } } public void StartEnableButtonTimer(){ CancelEnableButtonTimer(); mEnableButtonTimer = new Timer(); mEnableButtonTimer.schedule(new EnableButtonTimerClass(),1,50); } public void CancelEnableButtonTimer(){ if(mEnableButtonTimer != null){ mEnableButtonTimer.cancel(); mEnableButtonTimer.purge(); mEnableButtonTimer = null; } } ///////////////////////////////////////////////////////////////////// public void ClickLeft(){ switch (CursurIndex) { case 1: CursurIndex = 2; CursurDisplay(CursurIndex); break; case 2: if(textViewStart.isClickable() == true){ CursurIndex--; CursurDisplay(CursurIndex); } break; default: break; } } public void ClickRight(){ switch (CursurIndex) { case 1: CursurIndex++; CursurDisplay(CursurIndex); break; case 2: if(textViewStart.isClickable() == true){ CursurIndex = 1; CursurDisplay(CursurIndex); } break; default: break; } } public void ClickESC(){ ClickCancel(); } public void ClickEnter(){ switch (CursurIndex) { case 1: ClickStart(); break; case 2: ClickCancel(); break; default: break; } } public void CursurDisplay(int Index){ switch (Index) { case 1: textViewStart.setPressed(true); imgbtnCancel.setPressed(false); break; case 2: textViewStart.setPressed(false); imgbtnCancel.setPressed(true); break; default: break; } } ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// }
5476c2054c820d3d079a466d38fe2217a84e9349
5b0f09b299d0619ccce39660ffdedb941f4f970b
/src/github/leetcode/周赛/第160场周赛/找出给定方程的正整数解/Solution.java
43d18ffbf5f09ae38bd6f06976a055f28e1ff793
[]
no_license
hujingtiantian/java-leetcode
d2a16e71d50e932b9268fb593d816d38fbbe0d1b
caca9d8d38799e529df3cf670a296186826624ff
refs/heads/master
2020-08-30T02:03:48.410226
2020-01-02T08:45:32
2020-01-02T08:45:32
218,231,296
0
0
null
2020-01-02T08:45:34
2019-10-29T07:46:49
Java
UTF-8
Java
false
false
880
java
package github.leetcode.周赛.第160场周赛.找出给定方程的正整数解; import java.util.ArrayList; import java.util.List; /** * Created by hujingtian on 2019/10/27. */ public class Solution { public List<List<Integer>> findSolution(CustomFunction customfunction, int z) { List<List<Integer>> retList = new ArrayList<>(); for(int i = 1 ; i <= 1000 ; i++){ for(int j = 1 ; j <= 1000 ; j++){ if(customfunction.f(i,j) == z){ List addList = new ArrayList(); addList.add(i); addList.add(j); retList.add(addList); } } } return retList; } interface CustomFunction { // Returns positive integer f(x, y) for any given positive integer x and y. int f(int x, int y); }; }
be0bfa34b2566f24ac2fc2efe3ea30a491f15334
ec9503f878cf0ccf1532535e213cb2f0227c81e2
/DemoForLine/app/src/main/java/com/example/feicui/demoforline/pagerInfo/lead_pager0.java
6837b08f8a4733a11c6f0ac4d874f89c5a3620a2
[]
no_license
jionelamy/lineforone
dac86e1fa2626d70fe1731f40ef7ab92d6b33fab
915aac177ef804a59d469de52225e8d31c69c7e3
refs/heads/master
2021-01-08T12:55:10.889852
2016-07-26T14:26:51
2016-07-26T14:26:51
64,221,995
0
0
null
null
null
null
UTF-8
Java
false
false
819
java
package com.example.feicui.demoforline.pagerInfo; import android.content.Context; import android.support.v4.app.Fragment; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.FrameLayout; import com.example.feicui.demoforline.R; /** * Created by apple on 2016/7/26. */ public class lead_pager0 extends FrameLayout { public lead_pager0(Context context) { this(context, null); } public lead_pager0(Context context, AttributeSet attrs) { this(context, attrs, 0); } public lead_pager0(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { LayoutInflater.from(getContext()).inflate(R.layout.fragment_lead_pager1, this, true); } }
59cb985349dd596e96cef5c428c1993efbce3643
d75c4dd94f2023c73f37416406f2e8165c043558
/src/Entities/LegendsEntity.java
54cf0459e74fa4cc1c501edd33c483bf3b02cb54
[ "MIT" ]
permissive
jack-rg/LegendsOfValor
5fb23387f0961a1fbc140c6e554334f9907be174
3f031a94c11d65fbf6d57f5a98e9c92edc0c33ea
refs/heads/master
2023-04-04T18:40:59.067085
2021-04-20T13:08:47
2021-04-20T13:08:47
360,309,481
0
0
null
null
null
null
UTF-8
Java
false
false
2,522
java
/*=====================================================*/ /* Project Title: Legends Of Valor */ /* Course Name: GRS CS611 */ /* Semester: Spring '21 */ /* Project Authors: */ /* - Jack Giunta */ /* - Victoria-Rose Burke */ /* - Victor Vicente */ /*=====================================================*/ package Entities; import Entities.Classes.LegendsEntityClass; import Entities.Util.LegendsEntityStats; import Game.LegendsOfValor; import Map.Places.Place; import Util.Token; public abstract class LegendsEntity { private String name; private int ID; private Place currPlace; private Place spawnPlace; private Token token; /* =================== */ /* Constructor Methods */ /* =================== */ public LegendsEntity(int ID) { this.setID(ID); this.setName("Legends Entity #" + ID); } public LegendsEntity(int ID, String name) { this.setID(ID); this.setName(name); } /* ================ */ /* Abstract Methods */ /* ================ */ public abstract LegendsEntityClass getEntityClass(); public abstract void setEntityClass(LegendsEntityClass eClass); public abstract LegendsEntityStats getEntityStats(); public abstract void setLegendsEntityStats(LegendsEntityStats eStats); public abstract void respawn(); public abstract void updatePosition(int x, int y, LegendsOfValor game); public abstract void resetPosition(); public abstract void levelUp(); /* ===================== */ /* Getter/Setter Methods */ /* ===================== */ private void setID(int ID) { this.ID = ID; } public void setName(String name) { this.name = name; } public int getID() { return this.ID; } public String getName() { return this.name; } public Place getCurrPlace() { return currPlace; } public void setCurrPlace(Place currPlace) { this.currPlace = currPlace; } public Place getSpawnPlace() { return spawnPlace; } public void setSpawnPlace(Place spawnPlace) { this.spawnPlace = spawnPlace; } public Token getToken() { return token; } public void setToken(Token token) { this.token = token; } /* =========== */ /* Aux Methods */ /* =========== */ public boolean equals(LegendsEntity e) { return this.getID() == e.getID(); } public String toString() { return this.getName(); } }
872687469ee468c5f909fd2dc451a680f28717af
f0b9d714c8fd9d5f44f0f8adc8fe8ce23e7fbeb3
/zxingscanner/src/main/java/com/mylhyl/zxing/scanner/camera/AutoFocusManager.java
b419654ac04559238510b3b244f9367d3cdaf9f1
[]
no_license
zhengbobin/Android-Zxing
64b57a89c966bfaedab555b1629f5d7fe39d1657
635ee82691d5af3072c61a665149b2d43e8b5b1b
refs/heads/master
2021-01-19T18:22:39.339412
2017-08-14T09:34:11
2017-08-14T09:34:11
101,128,681
2
0
null
2017-08-23T02:29:35
2017-08-23T02:29:35
null
UTF-8
Java
false
false
4,301
java
/* * Copyright (C) 2012 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mylhyl.zxing.scanner.camera; import android.hardware.Camera; import android.os.AsyncTask; import android.util.Log; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.RejectedExecutionException; @SuppressWarnings("deprecation") final class AutoFocusManager implements Camera.AutoFocusCallback { private static final String TAG = AutoFocusManager.class.getSimpleName(); private static final long AUTO_FOCUS_INTERVAL_MS = 2000L; private static final Collection<String> FOCUS_MODES_CALLING_AF; static { FOCUS_MODES_CALLING_AF = new ArrayList<>(2); FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_AUTO); FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_MACRO); } private boolean stopped; private boolean focusing; private final boolean useAutoFocus; private final Camera camera; private AsyncTask<?, ?, ?> outstandingTask; AutoFocusManager(Camera camera) { this.camera = camera; String currentFocusMode = camera.getParameters().getFocusMode(); // 自动对焦 useAutoFocus = true && FOCUS_MODES_CALLING_AF.contains(currentFocusMode); //Log.i(TAG, "Current focus mode '" + currentFocusMode + "'; use auto focus? " + // useAutoFocus); start(); } @Override public synchronized void onAutoFocus(boolean success, Camera theCamera) { focusing = false; autoFocusAgainLater(); } private synchronized void autoFocusAgainLater() { if (!stopped && outstandingTask == null) { AutoFocusTask newTask = new AutoFocusTask(); try { newTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); outstandingTask = newTask; } catch (RejectedExecutionException ree) { Log.w(TAG, "Could not request auto focus", ree); } } } synchronized void start() { if (useAutoFocus) { outstandingTask = null; if (!stopped && !focusing) { try { camera.autoFocus(this); focusing = true; } catch (RuntimeException re) { // Have heard RuntimeException reported in Android 4.0.x+; continue? Log.w(TAG, "Unexpected exception while focusing", re); // Try again later to keep cycle going autoFocusAgainLater(); } } } } private synchronized void cancelOutstandingTask() { if (outstandingTask != null) { if (outstandingTask.getStatus() != AsyncTask.Status.FINISHED) { outstandingTask.cancel(true); } outstandingTask = null; } } synchronized void stop() { stopped = true; if (useAutoFocus) { cancelOutstandingTask(); // Doesn't hurt to call this even if not focusing try { camera.cancelAutoFocus(); } catch (RuntimeException re) { // Have heard RuntimeException reported in Android 4.0.x+; continue? Log.w(TAG, "Unexpected exception while cancelling focusing", re); } } } private final class AutoFocusTask extends AsyncTask<Object, Object, Object> { @Override protected Object doInBackground(Object... voids) { try { Thread.sleep(AUTO_FOCUS_INTERVAL_MS); } catch (InterruptedException e) { // continue } start(); return null; } } }