text
stringlengths
10
2.72M
package assignment4; import java.util.Random; /** * SuperHero Superclass * @author Jamie Lewis */ public class SuperHero { // Attributes String name; int health; boolean isDead = false; /** * Non-default SuperHero Constructor * @param name * @param health */ public SuperHero(String name, int health) { super(); this.name = name; this.health = health; } /** * attack method * @param opponent */ public void attack(SuperHero opponent) { int damage = new Random().ints(1,(10+1)).findFirst().getAsInt(); opponent.determineHealth(damage); System.out.println(opponent.name + " takes " + damage + " damage and has " + opponent.health + " remaining."); } /** * determineHealth method * @param damage */ //changed from private to protected for use in subclasses protected void determineHealth(int damage) { if(this.health - damage <= 0) { this.health = 0; this.isDead = true; } else { this.health = this.health - damage; } } /** * isDead method * @return boolean */ public boolean isDead() { return this.isDead; } }
package alien4cloud.rest.orchestrator; import javax.annotation.Resource; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import alien4cloud.audit.annotation.Audit; import alien4cloud.orchestrators.services.OrchestratorSecurityService; import alien4cloud.rest.model.RestResponse; import alien4cloud.rest.model.RestResponseBuilder; import alien4cloud.security.AuthorizationUtil; import alien4cloud.security.model.Role; import io.swagger.annotations.ApiOperation; @RestController @RequestMapping("/rest/orchestrators/{orchestratorId}/roles/") public class OrchestratorRolesController { @Resource private OrchestratorSecurityService orchestratorSecurityService; /** * Add a role to a user on all locations of a specific orchestrator * * @param orchestratorId The orchestrator id. * @param username The username of the user to update roles. * @param role The role to add to the user on the orchestrator. * @return A {@link Void} {@link RestResponse}. */ @ApiOperation(value = "Add a role to a user on all locations of a specific orchestrator", notes = "Only user with ADMIN role can assign any role to another user.") @RequestMapping(value = "/users/{username}/{role}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize("hasAuthority('ADMIN')") @Audit public RestResponse<Void> addUserRole(@PathVariable String orchestratorId, @PathVariable String username, @PathVariable String role) { AuthorizationUtil.hasOneRoleIn(Role.ADMIN); orchestratorSecurityService.addUserRoleOnAllLocations(orchestratorId, username, role); return RestResponseBuilder.<Void> builder().build(); } /** * Add a role to a group on all locations of a specific orchestrator * * @param orchestratorId The id of the orchestrator. * @param groupId The id of the group to update roles. * @param role The role to add to the group on the orchestrator. * @return A {@link Void} {@link RestResponse}. */ @ApiOperation(value = "Add a role to a group on all locations of a specific orchestrator", notes = "Only user with ADMIN role can assign any role to a group of users.") @RequestMapping(value = "/groups/{groupId}/{role}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize("hasAuthority('ADMIN')") @Audit public RestResponse<Void> addGroupRole(@PathVariable String orchestratorId, @PathVariable String groupId, @PathVariable String role) { AuthorizationUtil.hasOneRoleIn(Role.ADMIN); orchestratorSecurityService.addGroupRoleOnAllLocations(orchestratorId, groupId, role); return RestResponseBuilder.<Void> builder().build(); } /** * Remove a role from a user on all locations of a specific orchestrator * * @param orchestratorId The id of the orchestrator. * @param username The username of the user to update roles. * @param role The role to add to the user on the orchestrator. * @return A {@link Void} {@link RestResponse}. */ @ApiOperation(value = "Remove a role to a user on all locations of a specific orchestrator", notes = "Only user with ADMIN role can unassign any role to another user.") @RequestMapping(value = "/users/{username}/{role}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize("hasAuthority('ADMIN')") @Audit public RestResponse<Void> removeUserRole(@PathVariable String orchestratorId, @PathVariable String username, @PathVariable String role) { AuthorizationUtil.hasOneRoleIn(Role.ADMIN); orchestratorSecurityService.removeUserRoleOnAllLocations(orchestratorId, username, role); return RestResponseBuilder.<Void> builder().build(); } /** * Remove a role from a user on all locations of a specific orchestrator * * @param orchestratorId The id of the orchestrator. * @param groupId The id of the group to update roles. * @param role The role to add to the user on the orchestrator. * @return A {@link Void} {@link RestResponse}. */ @ApiOperation(value = "Remove a role of a group on all locations of a specific orchestrator", notes = "Only user with ADMIN role can unassign any role to a group.") @RequestMapping(value = "/groups/{groupId}/{role}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize("hasAuthority('ADMIN')") @Audit public RestResponse<Void> removeGroupRole(@PathVariable String orchestratorId, @PathVariable String groupId, @PathVariable String role) { AuthorizationUtil.hasOneRoleIn(Role.ADMIN); orchestratorSecurityService.removeGroupRoleOnAllLocations(orchestratorId, groupId, role); return RestResponseBuilder.<Void> builder().build(); } }
package com.example.fantasytranslator; import android.content.Intent; import android.os.Bundle; import com.firebase.ui.auth.AuthUI; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.navigation.NavigationView; import com.google.android.material.snackbar.Snackbar; import com.google.android.material.tabs.TabLayout; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.widget.Toolbar; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.viewpager.widget.ViewPager; import androidx.appcompat.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.example.fantasytranslator.ui.main.SectionsPagerAdapter; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkIfSignedIn(); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.my_toolbar); setSupportActionBar(toolbar); SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager()); ViewPager viewPager = findViewById(R.id.view_pager); viewPager.setAdapter(sectionsPagerAdapter); TabLayout tabs = findViewById(R.id.tabs); tabs.setupWithViewPager(viewPager); FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this,InformationActivity.class); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_drawer_menu,menu); return true; } private void checkIfSignedIn() { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) Toast.makeText(this, "Welcome " + user.getDisplayName(), Toast.LENGTH_SHORT).show(); else startLoginActivity(); } private void startLoginActivity() { startActivity(new Intent(this, SignInActivity.class)); finish(); } public void signOut() { AuthUI.getInstance() .signOut(this) .addOnCompleteListener(new OnCompleteListener<Void>() { public void onComplete(@NonNull Task<Void> task) { startLoginActivity(); } }); } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.log_out: { Toast toast = Toast.makeText(this,"Logging out", Toast.LENGTH_SHORT); toast.show(); signOut(); return true; } default: return super.onOptionsItemSelected(item); } } }
package com.lyl.core.common.control; import com.lyl.core.common.context.EndMonitorCtx; import com.lyl.core.common.context.StartMonitorCtx; import com.lyl.core.common.enums.MonitorResult; /** * Created by lyl * Date 2018/12/27 17:49 */ public interface ServerMethodControl extends MethodControl { void acceptClientControlInfo(Object context); void startMonitor(StartMonitorCtx ctx, String hostname); void endMonitor(MonitorResult monitorResult, EndMonitorCtx ctx); }
package inatel.br.nfccontrol.di.component; import inatel.br.nfccontrol.di.module.DataModule; import inatel.br.nfccontrol.di.module.SharedPreferenceModule; import javax.inject.Singleton; import dagger.Component; import inatel.br.nfccontrol.TccApplication; import inatel.br.nfccontrol.account.AccountActivity; import inatel.br.nfccontrol.di.module.ApplicationModule; import inatel.br.nfccontrol.di.module.NetworkModule; import inatel.br.nfccontrol.di.module.RoomModule; import inatel.br.nfccontrol.network.HeaderInterceptor; import inatel.br.nfccontrol.network.ResponseInterceptor; /** * Main application {@link Component}. * * @author Guilherme Ribeiro de Melo Yabu <guilhermeyabu@inatel.br> * @since 15/08/2018. */ @Singleton @Component(modules = { ApplicationModule.class, RoomModule.class, DataModule.class, SharedPreferenceModule.class, NetworkModule.class, }) public interface ApplicationComponent { void inject(TccApplication tccApplication); void inject(AccountActivity accountActivity); void inject(HeaderInterceptor headerInterceptor); void inject(ResponseInterceptor responseInterceptor); }
package com.sinha.eurekaTestProject; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @EnableEurekaServer @SpringBootApplication public class EurekaTestProjectApplication { public static void main(String[] args) { SpringApplication.run(EurekaTestProjectApplication.class, args); } }
package com.uchain.uvm.repository; import com.google.common.collect.Maps; import com.sun.istack.internal.Nullable; import com.uchain.core.Account; import com.uchain.core.Code; import com.uchain.core.Contract; import com.uchain.core.consensus.ForkBase; import com.uchain.core.datastore.BlockBase; import com.uchain.core.datastore.DataBase; import com.uchain.core.datastore.NodeKeyCompositor; import com.uchain.core.datastore.Tracking; import com.uchain.cryptohash.Fixed8; import com.uchain.cryptohash.HashUtil; import com.uchain.cryptohash.UInt160; import com.uchain.cryptohash.UInt256; import com.uchain.util.BIUtil; import com.uchain.util.ByteUtil; import com.uchain.util.FastByteComparisons; import com.uchain.uvm.ContractDetails; import com.uchain.uvm.DataWord; import com.uchain.uvm.Repository; import lombok.Getter; import lombok.Setter; import java.math.BigInteger; import java.util.*; @Getter @Setter public class RepositoryImpl implements Repository { private ForkBase forkBase; private DataBase dataBase; private BlockBase blockBase; public RepositoryImpl(ForkBase forkBase, DataBase dataBase, BlockBase blockBase) { this.forkBase = forkBase; this.dataBase = dataBase; this.blockBase = blockBase; } @Override public synchronized Account createAccount(UInt160 id) { Map<UInt256, Fixed8> frombalances = Maps.newHashMap(); Account account = new Account(BigInteger.ZERO, frombalances, id); dataBase.updateAccount(id, account); return account; } @Override public synchronized boolean isExist(UInt160 id) { return getAccount(id) != null; } @Override public synchronized Account getAccount(UInt160 id) { return dataBase.getAccount(id); } synchronized Account getOrCreateAccount(UInt160 id) { Account ret = dataBase.getAccount(id); if (ret == null) { ret = createAccount(id); } return ret; } @Override public synchronized void delete(UInt160 id) { dataBase.delete(id); //storageCache.delete(addr); } @Override public synchronized Long increaseNonce(UInt160 id) { Account accountState = getOrCreateAccount(id); dataBase.updateAccount(id, accountState.withIncrementedNonce()); return accountState.getNextNonce(); } @Override public synchronized Long setNonce(UInt160 id, Long nonce) { Account accountState = getOrCreateAccount(id); dataBase.updateAccount(id, accountState.withNonce(nonce)); return accountState.getNextNonce(); } @Override public synchronized BigInteger getNonce(UInt160 id) { Account accountState = getAccount(id); return accountState == null ? BigInteger.ZERO : BigInteger.valueOf(accountState.getNextNonce()); } @Override public synchronized ContractDetails getContractDetails(UInt160 addr) { return new ContractDetailsImpl(addr); } @Override public synchronized boolean hasContractDetails(UInt160 addr) { return getContractDetails(addr) != null; } @Override public synchronized void saveCode(UInt160 addr, byte[] code) { byte[] codeHash = HashUtil.sha3(code); dataBase.createCode(codeKey(codeHash, addr), new Code(code, codeKey(codeHash, addr))); if (dataBase.getContract(addr) == null) { dataBase.createContract(addr, new Contract(new HashMap<>(), codeHash, addr)); } else { dataBase.createContract(addr, dataBase.getContract(addr).updateContract(codeHash)); } } @Override public synchronized byte[] getCode(UInt160 addr) { byte[] codeHash = getCodeHash(addr); return codeHash == null || FastByteComparisons.equal(codeHash, HashUtil.EMPTY_DATA_HASH) ? ByteUtil.EMPTY_BYTE_ARRAY : dataBase.getCode(codeKey(codeHash, addr)).getCode(); } private byte[] codeKey(byte[] codeHash, UInt160 addr) { return NodeKeyCompositor.compose(codeHash, addr.getData()); } @Override public byte[] getCodeHash(UInt160 addr) { Contract contract = getContract(addr); return contract != null ? contract.getCode() : null; } public Contract getContract(UInt160 addr) { return dataBase.getContract(addr); } @Override public synchronized void addStorageRow(UInt160 addr, DataWord key, DataWord value) { getOrCreateAccount(addr); Contract contract = dataBase.getContract(addr); Map map = Maps.newHashMap(); map.put(key, value); if (contract == null) { dataBase.createContract(addr, new Contract(map, new byte[0], addr)); } else { contract.getContractMap().put(key, value.isZero() ? DataWord.ZERO : value); dataBase.updateContract(addr, contract); } } @Override public synchronized DataWord getStorageValue(UInt160 addr, DataWord key) { Account accountState = getAccount(addr); Contract contract = dataBase.getContract(addr); if (accountState != null) { if (contract == null) { dataBase.createContract(addr, new Contract(new HashMap<>(), new byte[0], addr)); } else { DataWord result = contract.getContractMap().get(key); return result; } } return null; } @Override public synchronized BigInteger getBalance(UInt160 addr, UInt256 assetId) { Account accountState = getAccount(addr); return accountState == null ? BigInteger.ZERO : accountState.getBalance(assetId).getValue(); } @Override public synchronized BigInteger addBalance(UInt160 addr, BigInteger value, UInt256 assetID) { Account accountState = getOrCreateAccount(addr); dataBase.updateAccount(addr, accountState.withBalanceIncrement(assetID, value)); return accountState.getBalance(assetID).getValue(); } public synchronized BigInteger addBalance(UInt160 addr, BigInteger value) { return addBalance(addr, value, UInt256.assetId); } @Override public synchronized void transfer(UInt160 fromAddr, UInt160 toAddr, BigInteger value) { Account fromAccount = getOrCreateAccount(fromAddr); Fixed8 fixed8 = new Fixed8(value); fromAccount.updateBalance(BIUtil.getAssetId(), Fixed8.Zero.mus(fixed8)); dataBase.updateAccount(fromAddr, fromAccount); Account toAccount = getOrCreateAccount(toAddr); toAccount.updateBalance(BIUtil.getAssetId(), fixed8); dataBase.updateAccount(toAddr, toAccount); } @Override public RepositoryImpl startTracking() { DataBase dataBase = new DataBase(this.dataBase.getSettings(), new Tracking(this.dataBase.getDb()), this.dataBase.getDb()); return new RepositoryImpl(forkBase, dataBase, blockBase); /*Source<byte[], Account> trackAccountStateCache = new WriteCache.BytesKey<>(accountStateCache, WriteCache.CacheType.SIMPLE); Source<byte[], byte[]> trackCodeCache = new WriteCache.BytesKey<>(codeCache, WriteCache.CacheType.SIMPLE); MultiCache<CachedSource<DataWord, DataWord>> trackStorageCache = new MultiCache(storageCache) { @Override protected CachedSource create(byte[] key, CachedSource srcCache) { return new WriteCache<>(srcCache, WriteCache.CacheType.SIMPLE); } }; RepositoryImpl ret = new RepositoryImpl(trackAccountStateCache, trackCodeCache, trackStorageCache); ret.parent = this; return ret;*/ } // // @Override // public synchronized Repository getSnapshotTo(byte[] root) { // return parent.getSnapshotTo(root); // } @Override public synchronized void commit() { // Repository parentSync = parent == null ? this : parent; // synchronized (parentSync) { // storageCache.flush(); // codeCache.flush(); // accountStateCache.flush(); // } } @Override public synchronized void rollback() { dataBase.rollBack(); } // // @Override // public byte[] getRoot() { // throw new RuntimeException("Not supported"); // } // // public synchronized String getTrieDump() { // return dumpStateTrie(); // } // // public String dumpStateTrie() { // throw new RuntimeException("Not supported"); // } // @Override public Repository clone() { return this; } class ContractDetailsImpl implements ContractDetails { private UInt160 address; public ContractDetailsImpl(UInt160 address) { this.address = address; } @Override public void put(DataWord key, DataWord value) { RepositoryImpl.this.addStorageRow(address, key, value); } @Override public DataWord get(DataWord key) { return RepositoryImpl.this.getStorageValue(address, key); } @Override public byte[] getCode() { return RepositoryImpl.this.getCode(address); } @Override public byte[] getCode(byte[] codeHash) { throw new RuntimeException("Not supported"); } @Override public void setCode(byte[] code) { RepositoryImpl.this.saveCode(address, code); } @Override public byte[] getStorageHash() { throw new RuntimeException("Not supported"); } @Override public void decode(byte[] rlpCode) { throw new RuntimeException("Not supported"); } @Override public void setDirty(boolean dirty) { throw new RuntimeException("Not supported"); } @Override public void setDeleted(boolean deleted) { RepositoryImpl.this.delete(address); } @Override public boolean isDirty() { throw new RuntimeException("Not supported"); } @Override public boolean isDeleted() { throw new RuntimeException("Not supported"); } @Override public byte[] getEncoded() { throw new RuntimeException("Not supported"); } @Override public int getStorageSize() { throw new RuntimeException("Not supported"); } @Override public Set<DataWord> getStorageKeys() { throw new RuntimeException("Not supported"); } @Override public Map<DataWord, DataWord> getStorage(@Nullable Collection<DataWord> keys) { throw new RuntimeException("Not supported"); } @Override public Map<DataWord, DataWord> getStorage() { throw new RuntimeException("Not supported"); } @Override public void setStorage(List<DataWord> storageKeys, List<DataWord> storageValues) { throw new RuntimeException("Not supported"); } @Override public void setStorage(Map<DataWord, DataWord> storage) { throw new RuntimeException("Not supported"); } @Override public byte[] getAddress() { return address.getData(); } @Override public void setAddress(byte[] address) { throw new RuntimeException("Not supported"); } @Override public ContractDetails clone() { throw new RuntimeException("Not supported"); } @Override public void syncStorage() { throw new RuntimeException("Not supported"); } @Override public ContractDetails getSnapshotTo(byte[] hash) { throw new RuntimeException("Not supported"); } } @Override public Set<byte[]> getAccountsKeys() { throw new RuntimeException("Not supported"); } }
package com.xsis.batch197.model; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.TableGenerator; @Entity @Table(name = "Ruang") public class RuangModel { @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "ruang_seq") @TableGenerator(name = "ruang_seq", table = "tbl_sequences",pkColumnName = "seq_id", valueColumnName = "seq_value", initialValue = 0, allocationSize = 1) @Column(name = "id") private int id; @Column(name = "KD_Ruang", length = 10, nullable=false) private String kodeRuang; @Column(name = "NM_Ruang", length = 100, nullable=false) private String namaRuang; @Column(name = "Kapasitas", nullable=false) private int Kapasitas; @OneToMany(mappedBy = "ruang") private List<KelasModel> listKelas = new ArrayList<KelasModel>(); public int getId() { return id; } public void setId(int id) { this.id = id; } public String getKodeRuang() { return kodeRuang; } public void setKodeRuang(String kodeRuang) { this.kodeRuang = kodeRuang; } public String getNamaRuang() { return namaRuang; } public void setNamaRuang(String namaRuang) { this.namaRuang = namaRuang; } public int getKapasitas() { return Kapasitas; } public void setKapasitas(int kapasitas) { Kapasitas = kapasitas; } public List<KelasModel> getListKelas() { return listKelas; } public void setListKelas(List<KelasModel> listKelas) { this.listKelas = listKelas; } }
package cn.test.ping; import cn.test.httpProgressBar.AjaxResult; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; /** * @author Created by xiaoni on 2019/10/9. */ @Service @Slf4j public class TestPingUtilService { @Autowired private RestTemplate restTemplate; public String test() { String result = PingUtil.connectAndCheckFirstUseGet(restTemplate, "http://www.baidu.com:80", "server", "http://www.baidu.com:80", String.class); log.info(result); return result; } public void testAjaxResult() { int totalFailed = 0; int total = 10000; for (int i = 0; i < total; i++) { AjaxResult result = PingUtil.serverConnectAndCheckFirstUseTokenHttpMethod(restTemplate, HttpMethod.GET, "4b9e1388-8d47-4119-a368-c7f6dbd1fd23", "http://127.0.0.1:8063/area/station", null, AjaxResult.class); log.info("time {} start", i); if (result == null || !result.isSuccess() || result.getData() == null) { totalFailed ++; log.error("time {}, failed, total-Failed {} , total {}", i, totalFailed, total); } else { PageInfo<?> pageInfo = JSON.parseObject(JSON.toJSONString(result.getData()), PageInfo.class); if (pageInfo.getList() == null || pageInfo.getList().isEmpty()) { totalFailed ++; log.error("time {}, result list empty, total-Failed {} , total {}", i, totalFailed, total); } else { log.info("time {}, result list size: {}",i, pageInfo.getList().size()); } } } log.info("test finished, result: total-Failed {}, total {}", totalFailed, total); } public static void main(String[] args) { // for (int i = 0; i < 255; i++) { // String ipPre = "172.16.0."; // if (PingUtil.ping(ipPre + i, null)) { // log.info("ping success: {}", ipPre + i); // } // } for (int i = 0; i < 255; i++) { String ipPre = "172.16.1."; if (PingUtil.ping(ipPre + i, null)) { log.info("ping success: {}", ipPre + i); } } } }
package net.cnr.studentManagentBackEnd.test; import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import net.cnr.studentManagentBackEnd.dao.StudentDao; import net.cnr.studentManagentBackEnd.dto.Student; public class StudentTestCase { private static AnnotationConfigApplicationContext context; @Autowired private static StudentDao studentDao; private Student student; @BeforeClass public static void init(){ context = new AnnotationConfigApplicationContext(); context.scan("net.cnr.studentManagentBackEnd"); context.refresh(); studentDao = (StudentDao) context.getBean("studentDao"); } @Test public void testAddCategory() { student = new Student(); student.setName("kamal"); student.setEmail("kamal@gmail.com"); student.setAddress("kurunegala"); student.setPhoneNumber("0112343222"); assertEquals("Not successfully addes a student inside the table student", true, studentDao.add(student)); } /*@Test public void testGetProduct(){ student = studentDao.get(3); assertEquals("Some thing went wrong while fetches a single product from the table", "kamal",student.getName()); } */ /*@Test public void testUpdateProduct(){ student =studentDao.get(3); student.setName("sanga"); assertEquals("Some thing went wrong while Updating a product",true,studentDao.update(student)); } */ }
package com.hewuzhao.frameanimation.blobcache; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import com.hewuzhao.frameanimation.bytespool.BytesBuffer; import com.hewuzhao.frameanimation.utils.ResourceUtil; import java.nio.ByteBuffer; /** * @author hewuzhao * @date 2020-02-01 */ public class BlobCacheUtil { private static final String TAG = "BlobCacheUtil"; private static final long POLY64REV = 0x95AC9329AC4BC9B5L; private static final long INITIALCRC = 0xFFFFFFFFFFFFFFFFL; private static long[] sCrcTable = new long[256]; static { // http://bioinf.cs.ucl.ac.uk/downloads/crc64/crc64.c long part; for (int i = 0; i < 256; i++) { part = i; for (int j = 0; j < 8; j++) { long x = ((int) part & 1) != 0 ? POLY64REV : 0; part = (part >> 1) ^ x; } sCrcTable[i] = part; } } private static long crc64Long(byte[] buffer) { long crc = INITIALCRC; for (byte b : buffer) { crc = sCrcTable[(((int) crc) ^ b) & 0xff] ^ (crc >> 8); } return crc; } public static byte[] getBytes(String in) { byte[] result = new byte[in.length() * 2]; int output = 0; for (char ch : in.toCharArray()) { result[output++] = (byte) (ch & 0xFF); result[output++] = (byte) (ch >> 8); } return result; } public static BytesBuffer getCacheDataByName(BlobCache blobCache, String name, BytesBuffer bytesBuffer, byte[] key, BlobCache.LookupRequest request) { try { if (bytesBuffer == null) { bytesBuffer = new BytesBuffer(); } if (request == null) { request = new BlobCache.LookupRequest(); } if (key == null) { key = getBytes(name); } request.key = crc64Long(key); request.buffer = bytesBuffer.data; if (blobCache.lookup(request)) { if (isSameKey(key, request.buffer, request.length)) { bytesBuffer.data = request.buffer; bytesBuffer.offset = key.length + 8; bytesBuffer.length = request.length - bytesBuffer.offset; return bytesBuffer; } } else { Log.e(TAG, "getCacheDataByName, not found, name=" + name); } } catch (Exception ex) { ex.printStackTrace(); Log.e(TAG, "getCacheDataByName error, name: " + name + ", ex: " + ex); } return null; } public static Bitmap getCacheBitmapByData(BytesBuffer dataBuffer, ByteBuffer pixelsBuffer, Bitmap inBitmap, BytesBuffer widthBuffer, BytesBuffer heightBuffer) { if (dataBuffer == null || dataBuffer.data == null) { return null; } try { if (widthBuffer == null) { widthBuffer = new BytesBuffer(4); } byte[] wb = widthBuffer.data; // 读取宽度,在bitmap的后面4位 System.arraycopy(dataBuffer.data, dataBuffer.length, wb, 0, 4); if (heightBuffer == null) { heightBuffer = new BytesBuffer(4); } byte[] hb = heightBuffer.data; // 读取高度,在宽度的后面4位 System.arraycopy(dataBuffer.data, dataBuffer.length + 4, hb, 0, 4); int width = ResourceUtil.byte2int(wb); int height = ResourceUtil.byte2int(hb); widthBuffer.length = 0; widthBuffer.offset = 0; heightBuffer.length = 0; heightBuffer.offset = 0; Bitmap bitmap = null; if (inBitmap == null) { Log.e(TAG, "getCacheBitmapByData, inBitmap is null"); } else if (inBitmap.isRecycled()) { Log.e(TAG, "getCacheBitmapByData, inBitmap is recycled."); } else if (inBitmap.getWidth() != width) { Log.e(TAG, "getCacheBitmapByData, inBitmap width is not fit."); } else if (inBitmap.getHeight() != height) { Log.e(TAG, "getCacheBitmapByData, inBitmap height is not fit."); } else { bitmap = inBitmap; } if (bitmap == null) { bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); if (bitmap == null) { Log.e(TAG, "getCacheBitmapByData, Bitmap.createBitmap bitmap is null, may be something error."); } } if (bitmap != null) { if (pixelsBuffer == null) { pixelsBuffer = ByteBuffer.allocate(dataBuffer.data.length); } pixelsBuffer.put(dataBuffer.data); pixelsBuffer.clear(); bitmap.copyPixelsFromBuffer(pixelsBuffer); pixelsBuffer.clear(); return bitmap; } } catch (Exception ex) { ex.printStackTrace(); Log.e(TAG, "getCacheBitmapByData, ex=" + ex); } finally { dataBuffer.length = 0; dataBuffer.offset = 0; } return null; } /** * 该方法拆分为 getCacheDataByName 和 getCacheBitmapByData */ @Deprecated public static Bitmap getCacheBitmapByName(BlobCache blobCache, String name, Bitmap inBitmap, BytesBuffer bytesBuffer, BytesBuffer widthBuffer, BytesBuffer heightBuffer, byte[] key) { if (bytesBuffer == null) { bytesBuffer = new BytesBuffer(); } try { BlobCache.LookupRequest request = new BlobCache.LookupRequest(); if (key == null) { key = getBytes(name); } request.key = crc64Long(key); request.buffer = bytesBuffer.data; if (blobCache.lookup(request)) { if (isSameKey(key, request.buffer, request.length)) { bytesBuffer.data = request.buffer; bytesBuffer.offset = key.length + 8; bytesBuffer.length = request.length - bytesBuffer.offset; if (widthBuffer == null) { widthBuffer = new BytesBuffer(4); } byte[] wb = widthBuffer.data; System.arraycopy(bytesBuffer.data, bytesBuffer.length, wb, 0, 4); if (heightBuffer == null) { heightBuffer = new BytesBuffer(4); } byte[] hb = heightBuffer.data; System.arraycopy(bytesBuffer.data, bytesBuffer.length + 4, hb, 0, 4); int width = ResourceUtil.byte2int(wb); int height = ResourceUtil.byte2int(hb); widthBuffer.length = 0; widthBuffer.offset = 0; heightBuffer.length = 0; heightBuffer.offset = 0; Bitmap bitmap = null; if (inBitmap != null && !inBitmap.isRecycled() && inBitmap.getWidth() == width && inBitmap.getHeight() == height) { bitmap = inBitmap; } if (bitmap == null) { Log.e(TAG, "option inBitmap is null or width and height not fit, name: " + name + ", width=" + width + ", height=" + height); bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); if (bitmap == null) { Log.e(TAG, "Bitmap.createBitmap bitmap is null, may be something error, name: " + name); } } if (bitmap != null) { ByteBuffer buf = ByteBuffer.wrap(bytesBuffer.data, 0, bytesBuffer.length); bitmap.copyPixelsFromBuffer(buf); buf.clear(); return bitmap; } } } else { Log.e(TAG, "getCacheBitmapByName, not found, name=" + name); } } catch (Exception ex) { ex.printStackTrace(); Log.e(TAG, "decode bitmap from blobcache error, name: " + name + ", ex: " + ex); } finally { bytesBuffer.length = 0; bytesBuffer.offset = 0; } return null; } public static void saveImageByBlobCache(Bitmap bitmap, String drawableName, BlobCache blobCache) { if (blobCache == null) { Log.e(TAG, "saveImageByBlobCache, blob cache is null."); return; } long t1 = System.currentTimeMillis(); if (bitmap == null) { BitmapFactory.Options options = new BitmapFactory.Options(); bitmap = ResourceUtil.getBitmap(drawableName, options); if (bitmap == null) { Log.e(TAG, "save image to blob cache, bitmap is null, name: " + drawableName); return; } } try { final int width = bitmap.getWidth(); final int height = bitmap.getHeight(); byte[] key = BlobCacheUtil.getBytes(drawableName); ByteBuffer bu = ByteBuffer.allocate(bitmap.getByteCount()); bitmap.copyPixelsToBuffer(bu); byte[] value = bu.array(); ByteBuffer buffer = ByteBuffer.allocate(key.length + value.length + 8); buffer.put(value); buffer.put(ResourceUtil.int2byte(width)); buffer.put(ResourceUtil.int2byte(height)); buffer.put(key); blobCache.insert(BlobCacheUtil.getCacheKey(drawableName), buffer.array()); } catch (Exception ex) { ex.printStackTrace(); Log.e(TAG, "save imge by blob cache error, name: " + drawableName + ", ex: " + ex); } finally { blobCache.syncAll(); Log.e(TAG, "save image to blob cache, cost time: " + (System.currentTimeMillis() - t1) + ", name: " + drawableName); } } public static long getCacheKey(String path) { if (path == null || path.isEmpty()) { return 0; } byte[] key = BlobCacheUtil.getBytes(path); return BlobCacheUtil.crc64Long(key); } private static boolean isSameKey(byte[] key, byte[] buffer, int bufferLen) { if (buffer == null || key == null) { return false; } int n = key.length; if (buffer.length < n) { return false; } for (int i = n - 1, j = bufferLen - 1; i >= 0; i--, j--) { if (key[i] != buffer[j]) { return false; } } return true; } }
package com.yc.education.controller; import com.yc.education.application.NetworkConfiguration; import com.yc.education.model.DataSetting; import com.yc.education.model.basic.EmployeeBasic; import com.yc.education.service.UsersService; import com.yc.education.service.basic.EmployeeBasicService; import com.yc.education.util.PropertyUtil; import com.yc.education.util.StageManager; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.layout.Pane; import javafx.stage.Stage; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.Factory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import java.net.URL; import java.util.List; import java.util.ResourceBundle; /** *@Description TODO 登录窗体 *@Author QuZhangJing *@Date 13:02 2018-08-07 *@Version 1.0 */ @Controller public class LoginController extends BaseController implements Initializable { @Autowired private UsersService usersService; @Autowired private EmployeeBasicService employeeBasicService; @FXML private Button closeButton; @FXML private ComboBox networkComboBox; @FXML private ComboBox emporder; @FXML private TextField empname; @FXML private PasswordField password; private Stage stageStock = new Stage(); /** * 登录按钮 */ public void login(){ String order = ""; if(emporder.getSelectionModel().getSelectedIndex() != -1)order = emporder.getSelectionModel().getSelectedItem().toString(); String name = empname.getText(); String passwords = password.getText(); if("".equals(order)){ alert_informationDialog("请选择用户编号"); return; }else if("".equals(name)){ alert_informationDialog("请输入用户名称"); return; }else if("".equals(passwords)){ alert_informationDialog("请输入密码"); return; }else{ //进行账号校验 // EmployeeBasic employeeBasic = employeeBasicService.selectEmployeeLogin(order,name,passwords); EmployeeBasic employeeBasic = employeeBasicService.selectEmployeeBasicByIsnum(order); if(employeeBasic != null){ if(name.equals(employeeBasic.getEmpname()) ){ if(passwords.equals(employeeBasic.getPassword())){ //登录成功 try { //获取当前执行的用户 Subject currentUser = SecurityUtils.getSubject(); //设置永不过期 SecurityUtils.getSubject().getSession().setTimeout(-1000l); //创建token令牌,用户名/密码 UsernamePasswordToken token = new UsernamePasswordToken(order,passwords); token.setRememberMe(true); currentUser.login(token); closeWin(); stageStock.setScene(new Scene(new Pane())); StageManager.CONTROLLER.put("rightWinStage",stageStock); NetworkConfiguration.homeShow(); } catch (AuthenticationException e) { System.err.println("登录失败"); return; } }else { alert_informationDialog("登录失败,密码错误!"); } }else{ alert_informationDialog("登录失败,用户名错误!"); } }else{ alert_informationDialog("登录失败,该用户不存在!"); } } // closeWin(); // // NetworkConfiguration.homeShow(); //获取当前项目的绝对路径 // String pathUrl = System.getProperty("user.dir").replace("\\", "/"); //得到配置文件某个属性的值 // System.err.println(PropertyUtil.getPro(pathUrl+"\\src\\main\\resources\\jdbc.properties","jdbc.url")+"(2):: *************************************************************************************************"); //修改配置文件中某个属性的值 // PropertyUtil.updatePro(pathUrl+"\\src\\main\\resources\\jdbc.properties","jdbc.url","jdbc:mysql://192.168.1.122:3306/sanlu?characterEncoding=UTF-8"); } //退出程序 public void closeButton(){ Stage stage=(Stage)closeButton.getScene().getWindow(); stage.close(); System.exit(0); } //关闭当前窗体 public void closeWin(){ System.err.println("关闭当前窗体"); Stage stage=(Stage)closeButton.getScene().getWindow(); stage.close(); } //网络配置 public void networkConfiguration(){ //加载配置窗体 NetworkConfiguration.display(); /* ObservableList<String> options = FXCollections.observableArrayList("Option 1","Option 2","Option 3"); networkComboBox.setItems(options);*/ //初始化 协议下拉默认值 networkComboBox.getItems().addAll( "https", "http", "ftp" ); } /** * 网络配置 ---确定 */ public void relyConfig(){ System.err.println("网络配置 ---确定"); closeWin(); } @Override public void initialize(URL location, ResourceBundle resources) { List<EmployeeBasic> employeeBasics = employeeBasicService.selectEmployeeBasic(); ObservableList<String> str = FXCollections.observableArrayList(); for (EmployeeBasic employeeBasic:employeeBasics) { str.add(employeeBasic.getIdnum()); } emporder.setItems(str); emporder.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue observable, Object oldValue, Object newValue) { EmployeeBasic employeeBasic = employeeBasicService.selectEmployeeBasicByIsnum(newValue.toString()); if(employeeBasic != null)empname.setText(employeeBasic.getEmpname()); } }); } }
package com.esum.hotdeploy; import java.io.File; import org.apache.log4j.PropertyConfigurator; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.esum.xtrus.boot.classloader.XtrusBootClassLoader; public class ClassLoaderTest { @Before public void init() throws Exception { System.setProperty("xtrus.home", "d:/test/xtrus-4.2.0"); PropertyConfigurator.configure(System.getProperty("xtrus.home")+"/conf/log.properties"); } @Test public void loadClasses() throws Exception { System.out.println(Thread.currentThread().getContextClassLoader()); XtrusBootClassLoader boot = new XtrusBootClassLoader(getClass().getClassLoader()); boot.addLib(System.getProperty("xtrus.home")+"/lib/core"); boot.addLib(System.getProperty("xtrus.home")+"/lib/opt"); Thread.currentThread().setContextClassLoader(boot); new Thread() { public void run() { while(!Thread.interrupted()) { System.out.println(Thread.currentThread().getContextClassLoader()); try { Thread.sleep(3000); } catch (InterruptedException e) { break; } } } }.start(); Class<?> found = boot.loadClass("com.esum.router.RouterMain"); Assert.assertNotNull(found); System.out.println(Thread.currentThread().getContextClassLoader()); RouterClassLoader router = new RouterClassLoader(boot); router.addClasses(new File(System.getProperty("xtrus.home")+"/deploy/works/ktds/classes")); Thread.currentThread().setContextClassLoader(router); found = router.loadClass("xtrus.apps.ktds.rule.KtdsSimpleRule"); Assert.assertNotNull(found); System.out.println(Thread.currentThread().getContextClassLoader()); router.close(); RouterClassLoader router2 = new RouterClassLoader(boot); Thread.currentThread().setContextClassLoader(router2); try { found = router2.loadClass("xtrus.apps.ktds.rule.KtdsSimpleRule"); } catch (Exception e) { found = null; } Assert.assertNull(found); System.out.println(Thread.currentThread().getContextClassLoader()); Thread.sleep(15*1000); } }
package security; import java.util.ArrayList; import java.util.Collection; import org.apache.log4j.Logger; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import entity.Role; import service.UserService; public class UserSecurityService implements UserDetailsService { private UserService srv; private final static Logger logger = Logger.getLogger(UserSecurityService.class.getName()); public void setSrv(UserService srv) { this.srv = srv; } @Override public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException { entity.User user = srv.getUser(login); logger.debug("UserSecurityService:"+login); if (user == null) { throw new UsernameNotFoundException("User " + login + "' not found!"); } Collection<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>(); authorities.add(new SimpleGrantedAuthority(login)); if (user.getRole() != null) { for (Role role : user.getRole()) { authorities.add(new SimpleGrantedAuthority(role.getRole())); } } return new User(user.getEmail(), user.getPassword(), authorities); } }
/* * Request * * Version 1.0 * * November 25, 2017 * * Copyright (c) 2017 Team 26, CMPUT 301, University of Alberta - All Rights Reserved. * You may use, distribute, or modify this code under terms and conditions of the Code of Student Behavior at University of Alberta. * You can find a copy of the license in this project. Otherwise please contact rohan@ualberta.ca * * Purpose: Represents the request object. Used for sending friend requests between users. */ package cmput301f17t26.smores.all_models; /** * Represents a request between two users * * @author Chris * @version 1.0 * @since 1.0 */ public class Request { private String mToUser; private String mFromUser; private String mID; /** * Constructs a Request object. * * @param fromUser receiver username * @param toUser sender username */ public Request(String fromUser, String toUser) { mToUser = toUser; mFromUser = fromUser; mID = mToUser + mFromUser; } /** * Returns request unique identifier. * @return mID String */ public String getID() { return mID; } /** * Returns request receiver username. * @return mToUser */ public String getToUser() { return mToUser; } /** * Returns request sender username. * @return mFromUser */ public String getFromUser() { return mFromUser; } }
package com.project.repository; import com.project.model.Collaborator; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface CollaboratorRepository extends JpaRepository<Collaborator, Long> { }
package domain; public class Studentenkamer extends StudentenVerblijf { public Studentenkamer(int verdiepingnummer, int verblijfnummer, Euro prijsPerVierkanteMeter, int oppervlakte) { super(verdiepingnummer, verblijfnummer, prijsPerVierkanteMeter, oppervlakte); } @Override public Euro prijs() { return super.prijs().produkt(getOppervlakte()); } }
package org.ingue.jpa.domain.relationship; import org.springframework.data.jpa.repository.JpaRepository; public interface RelationShipRepository extends JpaRepository<RelationShip, Long> { }
package dao; import java.util.List; import bean.Users; public interface UserDAO { public List<Users> gerUsers(); public Users getUser(int id); public boolean deleteUser(int id); public boolean updateUser(Users u); public Integer createUse(Users u); }
package services; import java.util.ArrayList; import entities.Trajet; public interface TrajetServiceInterface { public ArrayList<Trajet> getAllTraget(); public void deletedTraget(int trajetID); public void addTrajet(Trajet trajet); public void updateTrajet(Trajet trajet); }
package com.gao.commonProxy; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public interface InvocationHandler { void Invoke(Object o, Method method, Object... args) throws InvocationTargetException, IllegalAccessException; }
package org.spider.boot; import org.spider.core.middleware.Order; import org.spider.core.middleware.RequestMiddleware; import org.spider.util.Console; import org.springframework.web.reactive.function.client.WebClient; /** * @author liuxin * @version Id: RequestMiddleware1.java, v 0.1 2018/7/27 上午11:13 */ @Order(weight = 1) public class RequestMiddleware3 implements RequestMiddleware<WebClient> { @Override public void customerRequest(WebClient s) { Console.log("\"经过第三次对请求处理\")"); } }
package com.auro.scholr.core.application.base_component; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.auro.scholr.R; /** * A simple {@link Fragment} subclass. */ public abstract class BaseFragment extends Fragment { public BaseFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { TextView textView = new TextView(getActivity()); textView.setText(R.string.app_name); return textView; } protected abstract void init(); protected abstract void setToolbar(); protected abstract void setListener(); protected abstract int getLayout(); }
/** * Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT * Copyright (c) 2006-2018, Sencha Inc. * * licensing@sencha.com * http://www.sencha.com/products/gxt/license/ * * ================================================================================ * Commercial License * ================================================================================ * This version of Sencha GXT is licensed commercially and is the appropriate * option for the vast majority of use cases. * * Please see the Sencha GXT Licensing page at: * http://www.sencha.com/products/gxt/license/ * * For clarification or additional options, please contact: * licensing@sencha.com * ================================================================================ * * * * * * * * * ================================================================================ * Disclaimer * ================================================================================ * THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND * REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE * IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, * FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND * THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. * ================================================================================ */ package com.sencha.gxt.examples.resources.client; import com.google.gwt.core.client.GWT; import com.sencha.gxt.core.client.BindingPropertySet; import com.sencha.gxt.core.client.BindingPropertySet.PropertyName; public class Utils { public enum Theme { BLUE("Blue Theme", false), GRAY("Gray Theme", false), NEPTUNE("Neptune Theme", true), TRITON("Triton Theme", true); private final String title; private final boolean touch; private Theme(String title, boolean touch) { this.title = title; this.touch = touch; } public String getTitle() { return title; } public boolean isActive() { ActiveTheme theme = GWT.create(ActiveTheme.class); switch (this) { case BLUE: return theme.isBlue(); case GRAY: return theme.isGray(); case NEPTUNE: return theme.isNeptune(); case TRITON: return theme.isTriton(); } return false; } public boolean isTouch() { return touch; } @Override public String toString() { return getTitle(); } } @PropertyName("gxt.theme") public interface ActiveTheme extends BindingPropertySet { @PropertyValue(value = "gray", warn = false) boolean isGray(); @PropertyValue(value = "blue", warn = false) boolean isBlue(); @PropertyValue(value = "neptune", warn = false) boolean isNeptune(); @PropertyValue(value = "triton", warn = false) boolean isTriton(); } }
import java.util.*; import java.math.BigInteger; class HugeFactorials { public static Map<Integer,BigInteger> preprocess(int n) { //the preprocessing step needs to be run once Map<Integer,BigInteger> factorials = new HashMap<Integer,BigInteger>(); factorials.put(0,new BigInteger("1")); for(Integer i=1; i <= n; ++i) { BigInteger fact = new BigInteger(i.toString()).multiply(factorials.get(i - 1)); factorials.put(i,fact); } return factorials; } public static void main(String [] args) { //The argument to preprocess cn be variable Map<Integer,BigInteger> computedFactorials = preprocess(2000); //Now you can get the factorial of any number in [0,2n] in O(1) time System.out.println("Factorial of 100 is " + computedFactorials.get(100)); //System.out.println("Factorial of 2000 is " + computedFactorials.get(2000)); } }
/* * JBoss, a division of Red Hat * Copyright 2013, Red Hat Middleware, LLC, and individual * contributors as indicated by the @authors tag. See the * copyright.txt in the distribution for a full listing of * individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.gatein.wcm.api.model.security; import java.util.Date; /** * User representation in WCM context. * <p> * @author <a href="mailto:lponce@redhat.com">Lucas Ponce</a> * */ public interface WCMUser { /** * This method should return the username of the user. * <p> * The username should be unique and the user database should not have 2 * user record with the same username * * @return */ String getUserName(); /** * @return This method return the password of the user account */ String getPassword(); /** * This method is used to change the user account password. * * @param s */ void setPassword(String s); /** * @return This method return the first name of the user */ String getFirstName(); /** * @param s the new first name */ void setFirstName(String s); /** * @return The last name of the user */ String getLastName(); /** * @param s The new last name of the user */ void setLastName(String s); /** * @return The email address of the user */ String getEmail(); /** * @param s The new user email address */ void setEmail(String s); /** * @return The date that the user register or create the account */ Date getCreatedOn(); /** * @return Return the last time that the user access the account */ Date getLastLoginOn(); /** * @return return the display name */ String getDisplayName(); /** * @param displayName The name that should show in the display name */ void setDisplayName(String displayName); /** * @return the id of organization the user belongs to or null if not applicable */ String getOrganizationId(); /** * sets the prganizationId */ void setOrganizationId(String organizationId); /** * @return the groups that user belongs to */ String[] getRoles(); /** * * @param role - Role to check * @return Returns true if role is in the user's roles. */ boolean hasRole(String role); }
package hu.lamsoft.hms.androidclient.adapter.impl; import android.view.View; import android.widget.TextView; import hu.lamsoft.hms.androidclient.R; import hu.lamsoft.hms.androidclient.adapter.ViewHolder; import hu.lamsoft.hms.androidclient.restapi.food.dto.FoodDTO; /** * Created by admin on 2017. 04. 15.. */ public class FoodViewHolder extends ViewHolder<FoodDTO> { private TextView foodName; public FoodViewHolder(View view) { super(view); foodName = (TextView) view.findViewById(R.id.food_name_text_view); } @Override public void setValues(FoodDTO object) { foodName.setText(object.getName()); } }
package packets; import java.io.Serializable; /** * Класс сообщений с массивом строк */ public class StringPacket extends Packet implements Serializable { /** * Поле сроки */ private String[] strings; /** * Конструктор класса строкосодержащего сообщения * @param messageText - текст сообщения * @param strings - массив строк */ public StringPacket(String messageText, String[] strings){ super(messageText); this.strings = strings; } /** * Метод, возвращающий массив срок команды * @return возвращает массив строк */ public String[] getStrings(){ return strings; } }
package leader; import leader.clview.View; import leader.clview.command.Command; import leader.clview.command.CommandFactory; import leader.clview.command.CommandType; import leader.game.event.GameEvent; import leader.game.event.GameEventListener; import leader.game.event.GameEventType; import leader.game.Town; import leader.game.grievance.Grievance; import leader.game.grievance.GrievanceResolution; import leader.game.population.PersonAttribute; import leader.game.population.Population; import leader.game.population.PopulationStatistics; import leader.util.Util; import java.util.Map; import java.util.Optional; import java.util.logging.Logger; public class ClController implements GameEventListener { private static Logger logger = Logger.getLogger(ClController.class.getName()); private Model model; private View view; public ClController(Model model, View view){ this.model = model; this.view = view; this.model.addGameEventListener(this); } public void run(){ model.newGame(); while (!model.getGame().isGameover()){ view.print("> "); String input = view.getUserInput(); Command command = CommandFactory.parse(input); if (command == null){ continue; } handleCommand(command); } } private void handleCommand(Command command){ switch (command.getType()){ case EXIT -> handleExitCommand(); case HELP -> handleHelpCommand(command); case INFO -> handleInfoCommand(command); case SET -> handleSetCommand(command); case GRIEVANCES -> handleGrievances(command); } } private void handleExitCommand(){ System.exit(0); } private void handleHelpCommand(Command command){ int longestCommandName = 0; for (CommandType type: CommandType.values()){ int length = type.getAllowedInputString().length(); if (length > longestCommandName) longestCommandName = length; } longestCommandName += 3; for (CommandType type: CommandType.values()){ view.println(type.getHelp(longestCommandName)); } } private void handleInfoCommand(Command command){ if (command.getArguments().isEmpty()){ // Display all info displayKingdomInfoSummary(); } else { for (int i = 0; i < command.getArguments().size(); ++i) { Object arg = command.getArguments().get(i); String what = "" + arg; if (what.equalsIgnoreCase("kingdom")){ displayKingdomInfoDetails(); } else if (what.equalsIgnoreCase("town")){ if (i < command.getArguments().size() - 1){ String townName = "" + command.getArguments().get(i + 1); displayTownInfoDetails(townName); } } else if (what.equalsIgnoreCase("game")){ displayGameInfo(); } } } } private void displayGameInfo(){ view.println("#########################################################################"); view.println("Total Ticks: " + model.getGame().getTotalTicks()); view.println("Time till Age Advancement: " + model.getGame().getTimeTillAgeAdvancement()); view.println("== New Population Rates =="); view.println(" Adult Procreation Rate: " + model.getGame().getAdultProcreationRate() + " (% of adults that attempt to procreate)"); view.println(" Fertility Rate: " + model.getGame().getFertilityRate() + " (% success of procreation)"); view.println("== Early Mortality Rates =="); view.println(" In-utero Mortality Rate: " + model.getGame().getInUteroDeathRate() + " (% of lost pregnancies)"); view.println(" Infant Mortality Rate: " + model.getGame().getInfantMortalityRate() + " (% of children lost during infancy)"); view.println("== Death Rates (% chance of death) =="); view.println(" Elderly Death Rate: " + model.getGame().getDeathRate().get(PersonAttribute.ELDERLY)); view.println(" Adult Death Rate: " + model.getGame().getDeathRate().get(PersonAttribute.ADULT)); view.println(" Adolescent Death Rate: " + model.getGame().getDeathRate().get(PersonAttribute.ADOLESCENT)); view.println(" Child Death Rate: " + model.getGame().getDeathRate().get(PersonAttribute.CHILD)); view.println("#########################################################################"); } private void displayKingdomInfoSummary() { displayKingdomInfoDetails(); } private void displayKingdomInfoDetails(){ view.print("The Royal Kingdom of "); view.println(model.getGame().getKingdom().getName()); int totalPopulationSize = 0; int totalSize = 0; double farthestDistance = 0.0; Town farthestTown = null; view.println("== Towns (" + model.getGame().getKingdom().getTowns().size() + ") =="); for (Town town : model.getGame().getKingdom().getTowns()) { view.print(town.getName()); view.println(town.isCapital() ? " (Capital)" : ""); double distance = Util.getDistance(0, 0, town.getX(), town.getY()); if (farthestTown == null || distance > farthestDistance){ farthestDistance = distance; farthestTown = town; } view.println(" Location: " + town.getX() + ", " + town.getY() + (town.isCapital() ? "" : " (" + distance + " miles from capital)")); view.println(" Size: " + town.getSqAcres() + " sq acres"); view.println(" Population Size: " + town.getPopulation().size()); totalPopulationSize += town.getPopulation().size(); totalSize += town.getSqAcres(); } view.println("Total Size: " + totalSize + " sq acres"); view.println("Total Population Size: " + totalPopulationSize); view.println("Farthest Town: " + farthestTown.getName() + " (" + farthestDistance + " miles away)"); view.println("\n== Management =="); view.println("Grievances: " + model.getGame().getGrievances().size()); } private void displayTownInfoDetails(String townName){ Town town = model.getGame().getKingdom().getTown(townName); if (town == null){ logger.warning("Unable to find town with that name"); return; } view.println(town.getName()); double distance = Util.getDistance(0, 0, town.getX(), town.getY()); view.println(" Location: " + town.getX() + ", " + town.getY() + (town.isCapital()? "": " (" + distance + " miles from capital)")); view.println(" Size: " + town.getSqAcres() + " sq acres"); view.println(" Population Statistics:"); PopulationStatistics statistics = town.getPopulation().generateStats(); Map<PersonAttribute, Double> stats = statistics.getStats(); for (PersonAttribute personAttribute: PopulationStatistics.STAT_ORDER) { view.print(" " + personAttribute.toString()); view.println(": " + stats.get(personAttribute)); } view.println(" Population Size: " + town.getPopulation().size()); } private void handleSetCommand(Command command){ if (command.getArguments().size() < 3){ logger.warning("Invalid command. Usage: set <what> [<what>] <attribute> <new-value>.\n> set kingdom name \"My Foobar\"\n> set town \"Existing Town\" name \"New Town Name\""); return; } String what = "" + command.getArguments().get(0); if (what.equalsIgnoreCase("kingdom")){ String attr = "" + command.getArguments().get(1); if (attr.equalsIgnoreCase("name")){ String value = "" + command.getArguments().get(2); model.getGame().getKingdom().setName(value); } else logger.warning("Unable to set that attribute at this time"); } else if (what.equalsIgnoreCase("town")){ String townName = "" + command.getArguments().get(1); Optional<Town> optTown = model.getGame().getKingdom().getTowns().stream().filter(town -> town.getName().equalsIgnoreCase(townName)).findFirst(); if (optTown.isPresent()) { String attr = "" + command.getArguments().get(2); if (attr.equalsIgnoreCase("name")){ if (command.getArguments().size() >= 4) { String value = "" + command.getArguments().get(3); optTown.get().setName(value); } else logger.warning("Rename town to what?"); } else logger.warning("Unable to set that attribute at this time"); } else logger.warning("Unable to find town '" + townName + "'"); } else logger.warning("Unable to rename a '" + what + "'"); } private void handleGrievances(Command command){ view.println("Grievance (" + model.getGame().getGrievances().size() + " left):"); if (!model.getGame().getGrievances().isEmpty()) { Grievance grievance = model.getGame().getGrievances().get(0); view.println(grievance.getSummary()); view.println("An " + Population.summarizePerson(grievance.getPerson()) + " approaches:"); view.println(grievance.getDescription()); // TODO Let user select resolution and apply for (int i = 0; i < grievance.getPossibleResolutions().size(); ++i){ GrievanceResolution resolution = grievance.getPossibleResolutions().get(i); view.println(resolution.getDescription()); } } } @Override public void handleGameEvent(GameEvent gameEvent) { switch (gameEvent.getType()){ case ADVANCE_TICK: { if (this.model.getGame() != null) this.model.getGame().update(); gameEvent.consume(); break; } case NEW_GRIEVANCE:{ Grievance grievance = (Grievance) gameEvent.getData(); model.getGame().getGrievances().add(grievance); break; } } } }
package f.star.iota.milk.ui.gkdgif.gkd; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import f.star.iota.milk.Menus; import f.star.iota.milk.Net; import f.star.iota.milk.R; import f.star.iota.milk.base.PagerFragment; import f.star.iota.milk.base.TitlePagerAdapter; public class GkdGifPagerFragment extends PagerFragment { @BindView(R.id.view_pager) ViewPager mViewPager; @Override protected TitlePagerAdapter getPagerAdapter() { List<String> titles = new ArrayList<>(); titles.add("三次元图"); titles.add("少女映画"); titles.add("团子少女"); titles.add("梦丝女神"); titles.add("妖精视觉"); titles.add("其她"); List<Fragment> fragments = new ArrayList<>(); fragments.add(GkdGifFragment.newInstance(Net.GKDGIF_SCYT)); fragments.add(GkdGifFragment.newInstance(Net.GKDGIF_SNYH)); fragments.add(GkdGifFragment.newInstance(Net.GKDGIF_TZSN)); fragments.add(GkdGifFragment.newInstance(Net.GKDGIF_MSNS)); fragments.add(GkdGifFragment.newInstance(Net.GKDGIF_YJSJ)); fragments.add(GkdGifFragment.newInstance(Net.GKDGIF_qt)); return new TitlePagerAdapter(getChildFragmentManager(), fragments, titles); } @Override protected int setTabMode() { return TabLayout.MODE_SCROLLABLE; } @Override protected void init() { super.init(); mViewPager.setOffscreenPageLimit(0); } @Override public int getFragmentMenuID() { return Menus.MENU_GKDGIF_ID; } }
package com.ynyes.xunwudao.controller.front; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ynyes.xunwudao.entity.TdArticle; import com.ynyes.xunwudao.entity.TdArticleCategory; import com.ynyes.xunwudao.entity.TdDemand; import com.ynyes.xunwudao.entity.TdNavigationMenu; import com.ynyes.xunwudao.service.TdArticleCategoryService; import com.ynyes.xunwudao.service.TdArticleService; import com.ynyes.xunwudao.service.TdCommonService; import com.ynyes.xunwudao.service.TdDemandService; import com.ynyes.xunwudao.service.TdNavigationMenuService; import com.ynyes.xunwudao.util.ClientConstant; /** * * 资讯 * */ @Controller @RequestMapping("/info") public class TdInfoController { @Autowired private TdArticleService tdArticleService; @Autowired private TdArticleCategoryService tdArticleCategoryService; @Autowired private TdNavigationMenuService tdNavigationMenuService; @Autowired private TdCommonService tdCommonService; @Autowired TdDemandService tdDemandService; @RequestMapping("/index") public String infoIndex(ModelMap map,HttpServletRequest req){ tdCommonService.setHeader(map, req); //新闻动态所有类别 List<TdArticleCategory> tdArticleCategories = tdArticleCategoryService.findByMenuId(10L); map.addAttribute("newsCat_list", tdArticleCategories); // //通知公告 // map.addAttribute("notice_page", tdArticleService.findByCategoryId(19L, 0, SiteMagConstant.pageSize)); // // //活动状态 // map.addAttribute("activity_page", tdArticleService.findByCategoryId(20L, 0, SiteMagConstant.pageSize)); // // //媒体报道 // map.addAttribute("media_page", tdArticleService.findByCategoryId(21L, 0, SiteMagConstant.pageSize)); // // //数据公布 // map.addAttribute("data_page", tdArticleService.findByCategoryId(22L, 0, SiteMagConstant.pageSize)); // // //热点追踪 // map.addAttribute("hot_page", tdArticleService.findByCategoryId(23L, 0, SiteMagConstant.pageSize)); // // //创业风向 // map.addAttribute("SYB_page", tdArticleService.findByCategoryId(24L, 0, SiteMagConstant.pageSize)); if (null != tdArticleCategories && tdArticleCategories.size() > 0) { for (TdArticleCategory tdCat : tdArticleCategories) { if (null != tdCat.getTitle() && tdCat.getTitle().equals("通知公告")) { map.addAttribute("notice_page", tdArticleService .findByMenuIdAndCategoryIdAndIsEnableOrderBySortIdAsc(10L, tdCat.getId(), 0, ClientConstant.pageSize)); } if (null != tdCat.getTitle() && tdCat.getTitle().equals("活动状态")) { map.addAttribute("activity_page", tdArticleService .findByMenuIdAndCategoryIdAndIsEnableOrderBySortIdAsc(10L, tdCat.getId(), 0, ClientConstant.pageSize)); } if (null != tdCat.getTitle() && tdCat.getTitle().equals("媒体报道")) { map.addAttribute("media_page", tdArticleService .findByMenuIdAndCategoryIdAndIsEnableOrderBySortIdAsc(10L, tdCat.getId(), 0, ClientConstant.pageSize)); } if (null != tdCat.getTitle() && tdCat.getTitle().equals("数据公布")) { map.addAttribute("data_page", tdArticleService .findByMenuIdAndCategoryIdAndIsEnableOrderBySortIdAsc(10L, tdCat.getId(), 0, ClientConstant.pageSize)); } if (null != tdCat.getTitle() && tdCat.getTitle().equals("热点追踪")) { map.addAttribute("hot_page", tdArticleService .findByMenuIdAndCategoryIdAndIsEnableOrderBySortIdAsc(10L, tdCat.getId(), 0, ClientConstant.pageSize)); } if (null != tdCat.getTitle() && tdCat.getTitle().equals("创业风向")) { map.addAttribute("SYB_page", tdArticleService .findByMenuIdAndCategoryIdAndIsEnableOrderBySortIdAsc(10L, tdCat.getId(), 0, ClientConstant.pageSize)); } } } Long active = 3L; map.addAttribute("active",active); return "/client/news_index"; } @RequestMapping("/list/{mid}") public String infoList(@PathVariable Long mid, Long catId, String __EVENTTARGET, String __EVENTARGUMENT, Integer page, ModelMap map, HttpServletRequest req){ tdCommonService.setHeader(map, req); //翻页 zhangji if (null != __EVENTTARGET) { if (__EVENTTARGET.equalsIgnoreCase("btnPage")) { if (null != __EVENTARGUMENT) { page = Integer.parseInt(__EVENTARGUMENT); } } } /*翻页 end*/ //新闻动态所有类别 List<TdArticleCategory> tdArticleCategories = tdArticleCategoryService.findByMenuId(10L); map.addAttribute("newsCat_list", tdArticleCategories); if (null == page) { page = 0; } if (null == mid) { return "/client/error_404"; } TdNavigationMenu menu = tdNavigationMenuService.findOne(mid); map.addAttribute("menu_name", menu.getTitle()); map.addAttribute("menu_id", menu.getId()); //菜单id zhangji map.addAttribute("menu_sub_name", menu.getName());//英文名称 zhangji List<TdArticleCategory> catList = tdArticleCategoryService.findByMenuId(mid); if (null !=catList && catList.size() > 0) { if (null == catId || 0 == catId) { // catId = catList.get(0).getId(); //.get(0)表示 取catList表的第0个 zhangji //课程设置设为5条信息一页 zhangji if(menu.getTitle().equals("课程设置")) { map.addAttribute("info_page", tdArticleService.findByMenuIdAndIsEnableOrderByIdDesc(mid, page, ClientConstant.coursePageSize)); } else { map.addAttribute("info_page", tdArticleService.findByMenuIdAndIsEnableOrderByIdDesc(mid, page, ClientConstant.pageSize)); //menu下所有项 } } else { if(menu.getTitle().equals("课程设置")) { map.addAttribute("info_page", tdArticleService.findByMenuIdAndCategoryIdAndIsEnableOrderByIdDesc(mid, catId, page, ClientConstant.coursePageSize)); } else { map.addAttribute("info_page", tdArticleService.findByMenuIdAndCategoryIdAndIsEnableOrderBySortIdAsc(mid, catId, page, ClientConstant.pageSize)); } } } if(13 == mid && null == catId) { catId = catList.get(0).getId(); //.get(0)表示 取catList表的第0个 zhangji } map.addAttribute("info_name",tdArticleCategoryService.findOne(catId) ); //找出栏目名称 zhangji map.addAttribute("catId", catId); map.addAttribute("mid", mid); map.addAttribute("info_category_list", catList); //栏目的列表 zhangji map.addAttribute("latest_info_page", tdArticleService.findByMenuIdAndIsEnableOrderByIdDesc(mid, page, ClientConstant.pageSize)); return "/client/news_list"; } @RequestMapping("/aboutUs") public String aboutUs(HttpServletRequest req, ModelMap map) { tdCommonService.setHeader(map, req); map.addAttribute("showIcon", 5); return "/client/info_about_us"; } @RequestMapping("/profile") public String profile(HttpServletRequest req, ModelMap map) { tdCommonService.setHeader(map, req); List<TdArticle> articleList = tdArticleService.findByMenuIdAndCategoryIdAndIsEnableOrderByCreateTimeDesc(10L, 1L); if(null != articleList) { map.addAttribute("info", articleList.get(0)); } map.addAttribute("showIcon", 5); return "/client/info_profile"; } /*样式测试--------------------------------------*/ @RequestMapping("/photo") public String photo(HttpServletRequest req, ModelMap map) { tdCommonService.setHeader(map, req); List<TdArticle> articleList = tdArticleService.findByMenuIdAndCategoryIdAndIsEnableOrderBySortIdAsc(10L, 2L); if(null != articleList){ map.addAttribute("info_list", articleList); } map.addAttribute("showIcon", 5); return "/client/info_photo"; } @RequestMapping("/doctor") public String doctor(HttpServletRequest req, ModelMap map) { tdCommonService.setHeader(map, req); List<TdArticle> articleList = tdArticleService.findByMenuIdAndCategoryIdAndIsEnableOrderBySortIdAsc(10L, 3L); if(null != articleList){ map.addAttribute("info_list", articleList); } map.addAttribute("showIcon", 5); return "/client/info_doctor"; } @RequestMapping("/suggestion") public String suggestion(HttpServletRequest req, ModelMap map) { tdCommonService.setHeader(map, req); map.addAttribute("showIcon", 5); return "/client/info_suggestion"; } //分享-下载app @RequestMapping("/app") public String appDownload(String rfCode, HttpServletRequest req, ModelMap map) { tdCommonService.setHeader(map, req); if(null != rfCode){ map.addAttribute("rfCode", rfCode); } return "/client/info_app"; } //分享-注册 @RequestMapping("/reg") public String reg(/* Integer shareId, */String rfCode, String name, String code, HttpServletRequest request, ModelMap map) { String username = (String) request.getSession().getAttribute("username"); // if (null != shareId) { // map.addAttribute("share_id", shareId); // } // 基本信息 tdCommonService.setHeader(map, request); if (null == username) { map.addAttribute("username", name); if(null != rfCode){ map.addAttribute("rfCode", rfCode); } return "/client/info_reg"; } return "redirect:/"; } /*-----------------------------------样式测试 end*/ @RequestMapping("/list/content/{id}") public String content(@PathVariable Long id, Long mid, ModelMap map, HttpServletRequest req){ tdCommonService.setHeader(map, req); if (null == id || null == mid) { return "/client/error_404"; } TdNavigationMenu menu = tdNavigationMenuService.findOne(mid); map.addAttribute("menu_name", menu.getTitle()); map.addAttribute("menu_id", menu.getId()); //菜单id zhangji map.addAttribute("menu_sub_name", menu.getName());//英文名称 zhangji List<TdArticleCategory> catList = tdArticleCategoryService.findByMenuId(mid); map.addAttribute("info_category_list", catList); map.addAttribute("mid", mid); TdArticle tdArticle = tdArticleService.findOne(id); //浏览量 zhangji Long viewCount = tdArticle.getViewCount(); if(null !=viewCount) { tdArticle.setViewCount(viewCount+1); tdArticleService.save(tdArticle); } //找出栏目名称 zhangji Long catId = tdArticle.getCategoryId(); map.addAttribute("info_name",tdArticleCategoryService.findOne(catId) ); map.addAttribute("catId", catId); if (null != tdArticle) { map.addAttribute("info", tdArticle); map.addAttribute("prev_info", tdArticleService.findPrevOne(id, tdArticle.getCategoryId(), tdArticle.getMenuId())); map.addAttribute("next_info", tdArticleService.findNextOne(id, tdArticle.getCategoryId(), tdArticle.getMenuId())); } // 最近添加 map.addAttribute("latest_info_page", tdArticleService.findByMenuIdAndIsEnableOrderByIdDesc(mid, 0, ClientConstant.pageSize)); return "/client/news_detail"; } @RequestMapping("/search") public String search(String keywords , Integer page , ModelMap map, HttpServletRequest req){ tdCommonService.setHeader(map, req); if (null == page ) { page = 0; } Page<TdArticle> infoPage = tdArticleService.searchArticle(keywords, page, ClientConstant.pageSize); map.addAttribute("info_page", infoPage); map.addAttribute("keywords", keywords); return "/client/search"; } /** * ajax列表选择 * @author Zhangji * @param mid * @param catId * @param page * @param map * @param req * @return */ @RequestMapping("/list/select") public String infoListSelect( Long mid, Long catId, String __EVENTTARGET, String __EVENTARGUMENT, Integer page, ModelMap map, HttpServletRequest req){ tdCommonService.setHeader(map, req); //翻页 zhangji if (null != __EVENTTARGET) { if (__EVENTTARGET.equalsIgnoreCase("btnPage")) { if (null != __EVENTARGUMENT) { page = Integer.parseInt(__EVENTARGUMENT); } } } /*翻页 end*/ if (null == mid) { return "/client/error_404"; } if (null == page) { page = 0; } TdNavigationMenu menu = tdNavigationMenuService.findOne(mid); map.addAttribute("menu_name", menu.getTitle()); map.addAttribute("menu_id", menu.getId()); //菜单id zhangji map.addAttribute("menu_sub_name", menu.getName());//英文名称 zhangji List<TdArticleCategory> catList = tdArticleCategoryService.findByMenuId(mid); if (null !=catList && catList.size() > 0) { if (null == catId || 0 == catId) { // catId = catList.get(0).getId(); //.get(0)表示 取catList表的第0个 zhangji //课程设置设为5条信息一页 zhangji if(menu.getTitle().equals("课程设置")) { map.addAttribute("info_page", tdArticleService.findByMenuIdAndIsEnableOrderByIdDesc(mid, page, ClientConstant.coursePageSize)); } else { map.addAttribute("info_page", tdArticleService.findByMenuIdAndIsEnableOrderByIdDesc(mid, page, ClientConstant.pageSize)); //menu下所有项 } } else { if(menu.getTitle().equals("课程设置")) { map.addAttribute("info_page", tdArticleService.findByMenuIdAndCategoryIdAndIsEnableOrderByIdDesc(mid, catId, page, ClientConstant.coursePageSize)); } else { map.addAttribute("info_page", tdArticleService.findByMenuIdAndCategoryIdAndIsEnableOrderByIdDesc(mid, catId, page, ClientConstant.pageSize)); } } } map.addAttribute("info_name",tdArticleCategoryService.findOne(catId) ); //找出栏目名称 zhangji map.addAttribute("catId", catId); map.addAttribute("mid", mid); map.addAttribute("info_category_list", catList); //栏目的列表 zhangji map.addAttribute("latest_info_page", tdArticleService.findByMenuIdAndIsEnableOrderByIdDesc(mid, page, ClientConstant.pageSize)); return "/client/info_list_detail"; } @RequestMapping("/list/content/select") public String contentSelect(Long id, Long mid, ModelMap map, HttpServletRequest req){ tdCommonService.setHeader(map, req); if (null == id || null == mid) { return "/client/error_404"; } TdNavigationMenu menu = tdNavigationMenuService.findOne(mid); map.addAttribute("menu_name", menu.getTitle()); map.addAttribute("menu_id", menu.getId()); //菜单id zhangji map.addAttribute("menu_sub_name", menu.getName());//英文名称 zhangji List<TdArticleCategory> catList = tdArticleCategoryService.findByMenuId(mid); map.addAttribute("info_category_list", catList); map.addAttribute("mid", mid); TdArticle tdArticle = tdArticleService.findOne(id); //找出栏目名称 zhangji Long catId = tdArticle.getCategoryId(); map.addAttribute("info_name",tdArticleCategoryService.findOne(catId) ); map.addAttribute("catId", catId); //浏览量 zhangji Long viewCount = tdArticle.getViewCount(); tdArticle.setViewCount(viewCount+1); tdArticleService.save(tdArticle); if (null != tdArticle) { map.addAttribute("info", tdArticle); map.addAttribute("prev_info", tdArticleService.findPrevOne(id, tdArticle.getCategoryId(), tdArticle.getMenuId())); map.addAttribute("next_info", tdArticleService.findNextOne(id, tdArticle.getCategoryId(), tdArticle.getMenuId())); } // 最近添加 map.addAttribute("latest_info_page", tdArticleService.findByMenuIdAndIsEnableOrderByIdDesc(mid, 0, ClientConstant.pageSize)); return "/client/info_list_content_detail"; } /** * 服务项目ajax局部刷新 * @author Zhangji * @param mid * @param catId * @param page * @param map * @param req * @return */ @RequestMapping("/entry/select") public String serviceList(Long id, Long mid, Integer page, ModelMap map, HttpServletRequest req){ tdCommonService.setHeader(map, req); if (null == id || null == mid) { return "/client/error_404"; } map.addAttribute("mid", mid); TdArticle tdArticle = tdArticleService.findOne(id); //找出栏目名称 zhangji Long catId = tdArticle.getCategoryId(); map.addAttribute("info_name",tdArticleCategoryService.findOne(catId) ); //列表信息 zhangji map.addAttribute("info_page", tdArticleService .findByMenuIdAndCategoryIdAndIsEnableOrderByIdDesc(mid, catId, 0, ClientConstant.pageSize)); if (null != tdArticle) { map.addAttribute("info", tdArticle); map.addAttribute("prev_info", tdArticleService.findPrevOne(id, tdArticle.getCategoryId(), tdArticle.getMenuId())); map.addAttribute("next_info", tdArticleService.findNextOne(id, tdArticle.getCategoryId(), tdArticle.getMenuId())); } // 最近添加 map.addAttribute("latest_info_page", tdArticleService.findByMenuIdAndIsEnableOrderByIdDesc(mid, 0, ClientConstant.pageSize)); return "/client/info_entry_content_detail"; } /** * 服务项目内容 * @author Zhangji * @param id * @param mid * @param map * @param req * @return */ @RequestMapping("/entry/content/{id}") public String serviceContent(@PathVariable Long id, Long mid, ModelMap map, HttpServletRequest req){ tdCommonService.setHeader(map, req); if (null == id || null == mid) { return "/client/error_404"; } TdNavigationMenu menu = tdNavigationMenuService.findOne(mid); map.addAttribute("menu_name", menu.getTitle()); map.addAttribute("menu_id", menu.getId()); //菜单id zhangji map.addAttribute("menu_sub_name", menu.getName());//英文名称 zhangji List<TdArticleCategory> catList = tdArticleCategoryService.findByMenuId(mid); map.addAttribute("info_category_list", catList); map.addAttribute("mid", mid); //导航栏[关于我们]跳转 zhangji if(-1 == id) { for (TdArticleCategory tdCat : catList) { if (null != tdCat.getTitle() && tdCat.getTitle().equals("关于我们")) { Long catId = tdCat.getId(); List<TdArticle> profile = tdArticleService.findByCategoryId(catId); id = profile.get(0).getId(); break; } } } //导航栏[服务项目]跳转 zhangji if(-2 == id) { for (TdArticleCategory tdCat : catList) { if (null != tdCat.getTitle() && tdCat.getTitle().equals("服务项目")) { Long catId = tdCat.getId(); List<TdArticle> profile = tdArticleService.findByCategoryId(catId); id = profile.get(0).getId(); break; } } } TdArticle tdArticle = tdArticleService.findOne(id); //找出栏目名称 zhangji Long catId = tdArticle.getCategoryId(); map.addAttribute("info_name",tdArticleCategoryService.findOne(catId) ); //列表信息 zhangji map.addAttribute("info_page", tdArticleService .findByMenuIdAndCategoryIdAndIsEnableOrderByIdAsc(mid, catId, 0, ClientConstant.pageSize)); if (null != tdArticle) { map.addAttribute("info", tdArticle); map.addAttribute("prev_info", tdArticleService.findPrevOne(id, tdArticle.getCategoryId(), tdArticle.getMenuId())); map.addAttribute("next_info", tdArticleService.findNextOne(id, tdArticle.getCategoryId(), tdArticle.getMenuId())); } // 最近添加 map.addAttribute("latest_info_page", tdArticleService.findByMenuIdAndIsEnableOrderByIdDesc(mid, 0, ClientConstant.pageSize)); return "/client/info_entry_content"; } @RequestMapping("/submit") @ResponseBody public Map<String, Object> setConsult(TdDemand userDemand, HttpServletRequest req) { Map<String, Object> res = new HashMap<String, Object>(); res.put("code", 1); if (userDemand.getName() == null || userDemand.getName().equals("")) { res.put("message", "用户名不能为空"); return res; } else if (userDemand.getMobile().equals("")) { res.put("message", "手机号不能为空"); return res; } else if (userDemand.getContent() ==null|| userDemand.getContent().equals("")) { res.put("message", "留言内容不能为空"); return res; } userDemand.setTime(new Date()); userDemand.setStatusId(1L); //zhangji tdDemandService.save(userDemand); res.put("code", 0); return res; } @RequestMapping("/map") public String map(ModelMap map, HttpServletRequest req){ tdCommonService.setHeader(map, req); map.addAttribute("menu_name", "交通指南"); map.addAttribute("menu_sub_name", "Map");//英文名称 zhangji map.addAttribute("message", "地图导航"); map.addAttribute("back", "退出"); return "/client/map"; } }
package io.ceph.rgw.client.model; import io.ceph.rgw.client.action.ActionFuture; import io.ceph.rgw.client.action.ActionListener; /** * Interface to create a Request and execute the Action. * * @author zhuangshuo * Created by zhuangshuo on 2020/3/2. */ public interface RequestBuilder<REQ extends Request, RESP extends Response> extends Builder<REQ> { /** * Runs the Action and returns a Response. * * @return response */ RESP run(); /** * Execute the Action and returns a ActionFuture. * * @return a ActionFuture representing pending completion of the Action */ ActionFuture<RESP> execute(); /** * Execute the action. * * @param listener the listener for action response or exception */ void execute(ActionListener<RESP> listener); }
package com.ccloud.oa.user.vo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * @author : breeze * @date : 2020/8/19 * @description : */ @Data @ApiModel("登录成功返回前端的用户信息") public class UserInfo { @ApiModelProperty(value = "用户账号") private String account; @ApiModelProperty(value = "角色名称") private String role; @ApiModelProperty(value = "权限描述") private String auth; @ApiModelProperty(value = "用户昵称") private String username; @ApiModelProperty(value = "真实姓名") private String name; @ApiModelProperty(value = "手机号码") private String phone; @ApiModelProperty(value = "用户头像地址") private String avatar; @ApiModelProperty(value = "性别 0-男 1-女") private Boolean sex; @ApiModelProperty(value = "生日") private String birthday; @ApiModelProperty(value = "邮箱") private String email; @ApiModelProperty(value = "防止表单重复提交token") private String updateToken; }
package com.shihang.myframe.manager; import android.os.Handler; import android.widget.TextView; public class CodeManager { private TextView button; private Handler handler = new Handler(); private boolean isRuning = false; private int count = -1; private String textOff; private String textOn; public CodeManager(String textOn, String textOff, TextView button){ this.button = button; this.textOn = textOn; this.textOff = textOff; } public void startCountDown(){ isRuning = true; count = 60; handler.post(new Runnable() { @Override public void run() { if(isRuning){ count-- ; if(count > 0){ button.setEnabled(false); button.setText(String.format(textOn, count + "")); handler.postDelayed(this, 1000); }else{ reset(); } } } }); } public void reset(){ isRuning = false; count = -1; button.setEnabled(true); button.setText(textOff); } public void stopCountDown(){ isRuning = false; count = -1; } }
package shadows.hitwithaxe.block; import net.minecraft.block.state.IBlockState; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import shadows.hitwithaxe.EnumBarkType; public class BlockDebarkedSpectre extends BlockDebarkedLog { public BlockDebarkedSpectre(EnumBarkType type) { super(type); } @Override public BlockRenderLayer getRenderLayer() { return BlockRenderLayer.TRANSLUCENT; } @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override public boolean shouldSideBeRendered(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) { return state != world.getBlockState(pos.offset(side)); } }
package io.dcbn.backend.evidence_formula.services; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.json.JsonMapper; import de.fraunhofer.iosb.iad.maritime.datamodel.AreaOfInterest; import de.fraunhofer.iosb.iad.maritime.datamodel.Vessel; import io.dcbn.backend.evidence_formula.model.EvidenceFormula; import io.dcbn.backend.evidence_formula.services.exceptions.ParameterSizeMismatchException; import io.dcbn.backend.evidence_formula.services.exceptions.ParseException; import io.dcbn.backend.evidence_formula.services.exceptions.SymbolNotFoundException; import io.dcbn.backend.evidence_formula.services.exceptions.TypeMismatchException; import io.dcbn.backend.evidence_formula.services.visitors.FunctionWrapper; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.*; import static org.junit.jupiter.api.Assertions.*; class EvidenceFormulaEvaluatorTest { private EvidenceFormulaEvaluator evaluator; private static Vessel vessel; private static FunctionProvider testFunctions; private static AreaOfInterest area = new AreaOfInterest("TEST_AREA", null); private static Object inArea(List<Object> parameters) { if ("TEST_AREA".equals(parameters.get(0))) { testFunctions.correlatedAois.add(area.getName()); return true; } return false; } private static Object addTimeSlice(List<Object> parameters) { return (double) parameters.get(0) + testFunctions.currentTimeSlice; } @BeforeAll static void beforeAll() { vessel = new Vessel(null, 0); vessel.setSpeed(5.0); vessel.setLongitude(12.0); area.setName("TEST_AREA"); Map<String, FunctionWrapper> functions = new HashMap<>(); functions.put("inArea", new FunctionWrapper(Collections.singletonList(String.class), EvidenceFormulaEvaluatorTest::inArea)); functions.put("sum", new FunctionWrapper(Arrays.asList(Double.class, Double.class), (params) -> (double) params.get(0) + (double) params.get(1))); functions.put("isTrue", new FunctionWrapper(Collections.singletonList(Boolean.class), (params) -> params.get(0))); functions.put("addTimeSlice", new FunctionWrapper(Collections.singletonList(Double.class), EvidenceFormulaEvaluatorTest::addTimeSlice)); testFunctions = new FunctionProvider(functions); testFunctions.setCurrentTimeSlice(1); } @BeforeEach void setUp() { testFunctions.reset(); evaluator = new EvidenceFormulaEvaluator(testFunctions); } @Test @DisplayName("Evaluating formula with variables from json should work.") void testEvaluateWithJson() throws JsonProcessingException { JsonNode node = new JsonMapper().readTree("{\"speed\": 5, \"longitude\": 12}"); EvidenceFormula formula = new EvidenceFormula(); formula.setFormula("speed >= 5 & longitude = 2 + 2 * 5"); assertTrue(evaluator.evaluate(node, formula)); formula.setFormula("speed > 5 & longitude = 2 + 2 * 5"); assertFalse(evaluator.evaluate(node, formula)); } @Test @DisplayName("Evaluating formula with variables from json should work.") void testEvaluateWithVessel() { EvidenceFormula formula = new EvidenceFormula(); formula.setFormula("speed >= 5 & longitude = 2 + 2 * 5"); assertTrue(evaluator.evaluate(vessel, formula)); formula.setFormula("speed > 5 & longitude = 2 + 2 * 5"); assertFalse(evaluator.evaluate(vessel, formula)); } @Test @DisplayName("Evaluating formula with unknown function should throw exception.") void testUnknownFunctionThrowsException() { EvidenceFormula formula = new EvidenceFormula(); formula.setFormula("true & unknownFunction()"); SymbolNotFoundException ex = assertThrows(SymbolNotFoundException.class, () -> evaluator.evaluate(vessel, formula)); assertEquals("unknownFunction", ex.getSymbolName()); assertEquals(1, ex.getLine()); assertEquals(7, ex.getCol()); } @Test @DisplayName("Evaluating formula with unknown variable should throw exception.") void testUnknownVariableThrowsException() { EvidenceFormula formula = new EvidenceFormula(); formula.setFormula("true & unknownVariable > 5"); TypeMismatchException ex = assertThrows(TypeMismatchException.class, () -> evaluator.evaluate(vessel, formula)); assertEquals(Double.class, ex.getExpectedType()); assertEquals(1, ex.getLine()); assertEquals(7, ex.getCol()); } @Test @DisplayName("Calling function with wrong amount of arguments should throw exception.") void testCallingFunctionWithWrongNumberOfArgumentsThrowsException() { EvidenceFormula formula = new EvidenceFormula(); formula.setFormula("inArea(TEST_AREA, 2)"); ParameterSizeMismatchException ex = assertThrows( ParameterSizeMismatchException.class, () -> evaluator.evaluate(vessel, formula)); assertEquals("inArea", ex.getFunctionName()); assertEquals(1, ex.getLine()); assertEquals(0, ex.getCol()); assertEquals(1, ex.getExpectedParameterSize()); assertEquals(2, ex.getActualParameterSize()); } @Test @DisplayName("Calling function with parameters of the wrong type should throw exception.") void testCallingFunctionWithWrongParameterTypeThrowsException() { EvidenceFormula formula = new EvidenceFormula(); formula.setFormula("2 > 1 & inArea(2)"); TypeMismatchException ex = assertThrows(TypeMismatchException.class, () -> evaluator.evaluate(vessel, formula)); assertEquals(String.class, ex.getExpectedType()); assertEquals(Double.class, ex.getActualType()); assertEquals(1, ex.getLine()); assertEquals(9, ex.getCol()); } @Test @DisplayName("Calling functions with correct parameters should return expected results.") void testCallingFunctionWithCorrectParametersReturnsExpectedResults() { EvidenceFormula formula = new EvidenceFormula(); formula.setFormula("inArea(TEST_AREA)"); assertTrue(evaluator.evaluate(vessel, formula)); formula.setFormula("inArea(AREA)"); assertFalse(evaluator.evaluate(vessel, formula)); } @Test @DisplayName("Calling functions with complex arguments should work.") void testCallingFunctionWithComplexArgumentsWorks() { EvidenceFormula formula = new EvidenceFormula(); formula.setFormula("sum(2 * (2 + 3), sum(2, 1)) = 13"); assertTrue(evaluator.evaluate(vessel, formula)); formula.setFormula("sum(2 * (2 + 3), sum(2, 1)) = 12 & inArea(TEST_AREA)"); assertFalse(evaluator.evaluate(vessel, formula)); formula.setFormula("sum(2 * (2 - 5), sum(2, 1)) = -3 & inArea(TEST_AREA)"); assertTrue(evaluator.evaluate(vessel, formula)); formula.setFormula("sum(2 * (2 - 5), sum(2, 1)) = -3 & !inArea(TEST_AREA)"); assertFalse(evaluator.evaluate(vessel, formula)); } @Test @DisplayName("Negation of all number expressions should work.") void testNegationOfNumberExpressions() { EvidenceFormula formula = new EvidenceFormula(); formula.setFormula("-sum(2, 1) = -3"); assertTrue(evaluator.evaluate(vessel, formula)); formula.setFormula("-speed = -5"); assertTrue(evaluator.evaluate(vessel, formula)); } @Test @DisplayName("Scientific notation should work.") void testScientificNotation() { EvidenceFormula formula = new EvidenceFormula(); formula.setFormula("2e2 = 200"); assertTrue(evaluator.evaluate(vessel, formula)); formula.setFormula("2e-2 = 0.02"); assertTrue(evaluator.evaluate(vessel, formula)); } @Test @DisplayName("Other operators should work.") void testOtherOperators() { EvidenceFormula formula = new EvidenceFormula(); formula.setFormula("5 / 2 = 2.5"); assertTrue(evaluator.evaluate(vessel, formula)); formula.setFormula("5 / 2 != 2.5"); assertFalse(evaluator.evaluate(vessel, formula)); formula.setFormula("5 / 2 < 2.5"); assertFalse(evaluator.evaluate(vessel, formula)); formula.setFormula("5 / 2 <= 2.5"); assertTrue(evaluator.evaluate(vessel, formula)); formula.setFormula("5 / 2 > 2.5"); assertFalse(evaluator.evaluate(vessel, formula)); formula.setFormula("5 / 2 >= 2.5"); assertTrue(evaluator.evaluate(vessel, formula)); formula.setFormula("true | false"); assertTrue(evaluator.evaluate(vessel, formula)); formula.setFormula("true & (false | true)"); assertTrue(evaluator.evaluate(vessel, formula)); formula.setFormula("true & !(false | true)"); assertFalse(evaluator.evaluate(vessel, formula)); formula.setFormula("true & !(isTrue(false) | true)"); assertFalse(evaluator.evaluate(vessel, formula)); } @Test @DisplayName("Function returning the wrong type should throw exception.") void testWrongTypeException() { EvidenceFormula formula = new EvidenceFormula(null, "true & sum(2, 1)"); TypeMismatchException ex = assertThrows(TypeMismatchException.class, () -> evaluator.evaluate(vessel, formula)); assertEquals(Boolean.class, ex.getExpectedType()); assertEquals(Double.class, ex.getActualType()); assertEquals(1, ex.getLine()); assertEquals(7, ex.getCol()); } @Test @DisplayName("Invalid formulas should throw parse exception.") void testParseException() { EvidenceFormula formula = new EvidenceFormula(); formula.setFormula("true & _Test"); ParseException ex = assertThrows(ParseException.class, () -> evaluator.evaluate(vessel, formula)); assertEquals("_", ex.getOffendingText()); assertEquals(1, ex.getLine()); assertEquals(7, ex.getCol()); formula.setFormula("true & ()"); ex = assertThrows(ParseException.class, () -> evaluator.evaluate(vessel, formula)); assertEquals(")", ex.getOffendingText()); assertEquals(1, ex.getLine()); assertEquals(8, ex.getCol()); formula.setFormula("true && ()"); ex = assertThrows(ParseException.class, () -> evaluator.evaluate(vessel, formula)); assertEquals("&", ex.getOffendingText()); assertEquals(1, ex.getLine()); formula.setFormula("true &"); ex = assertThrows(ParseException.class, () -> evaluator.evaluate(vessel, formula)); assertEquals("<EOF>", ex.getOffendingText()); assertEquals(1, ex.getLine()); assertEquals(6, ex.getCol()); } @Test @DisplayName("Evaluating formula should correctly set areas of interest.") void testAoiSet() { EvidenceFormula formula = new EvidenceFormula(); formula.setFormula("inArea(TEST)"); assertFalse(evaluator.evaluate(vessel, formula)); assertTrue(evaluator.getCorrelatedAois().isEmpty()); formula.setFormula("inArea(TEST_AREA)"); assertTrue(evaluator.evaluate(vessel, formula)); assertEquals(1, evaluator.getCorrelatedAois().size()); System.out.println(evaluator.getCorrelatedAois().toArray()[0]); assertTrue(evaluator.getCorrelatedAois().contains("TEST_AREA")); } @Test @DisplayName("Evaluating formula at a given timeslice works.") void testTimeSlice() { EvidenceFormula formula = new EvidenceFormula(); formula.setFormula("addTimeSlice(3) = 3"); assertTrue(evaluator.evaluate(0, vessel, formula)); formula.setFormula("addTimeSlice(3) = 4"); assertFalse(evaluator.evaluate(0, vessel, formula)); formula.setFormula("addTimeSlice(3) = 3"); assertFalse(evaluator.evaluate(1, vessel, formula)); formula.setFormula("addTimeSlice(3) = 4"); assertTrue(evaluator.evaluate(1, vessel, formula)); } }
package com.api.impl; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import com.api.interf.PositionsCustomMethods; public class PositionsRepositoryImpl implements PositionsCustomMethods{ @PersistenceContext private EntityManager em; }
package com.xu.spring.bean; import java.util.ArrayList; import java.util.List; public class User { private String userName; private String password; private int age; private String email; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User [userName=" + userName + ", password=" + password + ", age=" + age + ", email=" + email + "]"; } public static void main(String[] args) { List<String> a = new ArrayList<String>(); a.add("1"); a.add("2"); a.add("3"); a.add("4"); List<String> b = a; b.remove(2); System.out.println(a); System.out.println(b); } }
/* * Лицензионное соглашение на использование набора средств разработки * «SDK Яндекс.Диска» доступно по адресу: http://legal.yandex.ru/sdk_agreement * */ package com.yandex.disk.client; import android.os.Parcel; import android.os.Parcelable; import android.util.Base64; import org.apache.http.message.AbstractHttpMessage; public class Credentials implements Parcelable { private String user, token; private String name, password; private String authBase; public Credentials(String user, String token, String name, String password) { this.user = user; this.token = token; this.name = name; this.password = password; if (name != null && password != null) { this.authBase = Base64.encodeToString((name + ":" + password).getBytes(), Base64.NO_WRAP); } } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getToken() { return token; } public String getName() { return name; } public String getPassword() { return password; } public void setToken(String token) { this.token = token; } public void addAuthHeader(AbstractHttpMessage req) { if (authBase == null) { req.addHeader("X-Yandex-SDK-Version", "android, 1.0"); req.addHeader("Authorization", "OAuth " + token); } else { req.addHeader("Authorization", "Basic " + authBase); } } public static final Parcelable.Creator<Credentials> CREATOR = new Parcelable.Creator<Credentials>() { public Credentials createFromParcel(Parcel parcel) { return new Credentials(parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString()); } public Credentials[] newArray(int size) { return new Credentials[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int flags) { parcel.writeString(user); parcel.writeString(token); parcel.writeString(name); parcel.writeString(password); } }
package com.arthur.bishi.wangyi0821; import java.util.Scanner; /** * @description: * @author: arthurji * @date: 2021/8/21 14:32 * @modifiedBy: * @version: 1.0 */ public class No2 { public static void main(String[] args) { // Scanner scanner = new Scanner(System.in); // String[] split = scanner.nextLine().split(","); // int n = Integer.valueOf(split[0]); // int k = Integer.valueOf(split[1]); // char start = 'a'; // StringBuilder sb = new StringBuilder(); // sb.append("a"); // for (int i = 1; i < n; i++) { // char[] chars = sb.toString().toCharArray(); // for (int j = 0; j < chars.length; j++) { // chars[j] = (char) (96 + Math.abs(123 - chars[j])); // } // String s = new String(chars); // String reverse = new StringBuilder(s).reverse().toString(); // sb.append((char) ('a' + i)).append(reverse); // } // System.out.println(sb.toString().charAt(k - 1)); } public char findKthBit (int n, int k) { // write code here StringBuilder sb = new StringBuilder(); sb.append("a"); for (int i = 1; i < n; i++) { char[] chars = sb.toString().toCharArray(); for (int j = 0; j < chars.length; j++) { chars[j] = (char) (96 + Math.abs(123 - chars[j])); } String s = new String(chars); String reverse = new StringBuilder(s).reverse().toString(); sb.append((char) ('a' + i)).append(reverse); } return sb.toString().charAt(k - 1); } }
package com.example.zeal.greendaodemo; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.webkit.DateSorter; import org.litepal.LitePal; import org.litepal.crud.DataSupport; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SQLiteDatabase db = LitePal.getDatabase(); } public void add(View view) { // album.setCover(getCoverImageBytes()); Song song1 = new Song(); song1.setName("song1"); song1.setDuration(320); //song1.setAlbum(album); song1.save(); Song song2 = new Song(); song2.setName("song2"); song2.setDuration(356); //song2.setAlbum(album); song2.save(); Album album = new Album(); album.setName("album"); album.setPrice(10.99f); album.getSongs().add(song1); album.getSongs().add(song2); album.save(); } public void query(View view) { List<Song> songList = DataSupport.findAll(Song.class, true); Log.e("zeal", "songlist:" + songList); List<Album> albumList = DataSupport.findAll(Album.class, true); Log.e("zeal", "albumList:" + albumList); } public void delete(View view) { DataSupport.deleteAll(Album.class, "name = ?", "album"); DataSupport.deleteAll(Song.class, "duration > ?", "300"); } }
package main.java; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class RecupConfig { private static final Path config = Paths.get("./classes/config.properties"); // Emplacement fichier configuration pour la prod //private static final Path config = Paths.get("./src/main/resources/config.properties"); // Emplacement fichier configuration pour le developement /** * Méthode pour savoir si on est en mode developeur ou non * @return retourne un entier "1 : mode developeur activé" */ public static int devMode (){ int retour = 0; if(Files.exists(config)){ List<String> ligne = null; try { ligne = Files.readAllLines(config); } catch (IOException e) { e.printStackTrace(); } for(int i = 0; i < ligne.size(); i++){ String traitement; String[] traitement2; traitement = ligne.get(i); traitement2 = traitement.split(" : "); if(traitement2[0].equals("devmode")){ if(traitement2[1].equals("on")) retour = 1; } } } else System.err.println("Le fichier n'existe pas."); return retour; } /** * Méthode pour savoir la dificulté du jeu (nombre de carractere que l'on devra trouver) * @return retourne un entier */ public static int dificulte() { int retour = 0; if(Files.exists(config)){ List<String> ligne = null; try { ligne = Files.readAllLines(config); } catch (IOException e) { e.printStackTrace(); } for(int i = 0; i < ligne.size(); i++){ String traitement; String[] traitement2; traitement = ligne.get(i); traitement2 = traitement.split(" : "); if(traitement2[0].equals("dificulte")) { retour = Integer.parseInt(traitement2[1]); } } } else System.err.println("Le fichier n'existe pas."); return retour; } /** * Méthode pour savoir le nombre d'essais qu'a le joueur pour trouver la solution * @return retourne un entier */ public static int nbEssai() { int retour = 0; String temp = null; if(Files.exists(config)){ List<String> ligne = null; try { ligne = Files.readAllLines(config); } catch (IOException e) { e.printStackTrace(); } for(int i = 0; i < ligne.size(); i++){ String traitement; String[] traitement2; traitement = ligne.get(i); traitement2 = traitement.split(" : "); if(traitement2[0].equals("nbessai")) { retour = Integer.parseInt(traitement2[1]); } } } else System.err.println("Le fichier n'existe pas."); return retour; } }
package com.jaiaxn.design.pattern.created.abstractfactory; import com.jaiaxn.design.pattern.created.abstractfactory.equipment.Equipment; import com.jaiaxn.design.pattern.created.factory.constant.HeroPositionConstant; import com.jaiaxn.design.pattern.created.factory.hero.*; /** * @author: wang.jiaxin * @date: 2019年08月16日 * @description: **/ public class HeroFactory extends AbstractFactory { @Override public Equipment getEquipment(String equipmentName) { return null; } @Override public HeroMan getHero(String heroPosition) { if ("".equals(heroPosition)) { return null; } if (HeroPositionConstant.POSITION_TOP.equals(heroPosition)) { return new HeroManChuanZhang(); } else if (HeroPositionConstant.POSITION_JUG.equals(heroPosition)) { return new HeroManXiaZi(); } else if (HeroPositionConstant.POSITION_MID.equals(heroPosition)) { return new HeroManYaSuo(); } else if (HeroPositionConstant.POSITION_ADC.equals(heroPosition)) { return new HreoVN(); } else if (HeroPositionConstant.POSITION_SUP.equals(heroPosition)) { return new HeroManChuiShi(); } return null; } }
/* * Copyright 2002-2022 the original author or 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 * * https://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.springframework.web.socket.server.jetty; import java.lang.reflect.UndeclaredThrowableException; import java.security.Principal; import java.util.Collections; import java.util.List; import java.util.Map; import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.eclipse.jetty.websocket.server.JettyWebSocketCreator; import org.eclipse.jetty.websocket.server.JettyWebSocketServerContainer; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.web.socket.WebSocketExtension; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.adapter.jetty.JettyWebSocketHandlerAdapter; import org.springframework.web.socket.adapter.jetty.JettyWebSocketSession; import org.springframework.web.socket.server.HandshakeFailureException; import org.springframework.web.socket.server.RequestUpgradeStrategy; /** * A {@link RequestUpgradeStrategy} for Jetty 11. * * @author Rossen Stoyanchev * @since 5.3.4 */ public class JettyRequestUpgradeStrategy implements RequestUpgradeStrategy { private static final String[] SUPPORTED_VERSIONS = new String[] {"13"}; @Override public String[] getSupportedVersions() { return SUPPORTED_VERSIONS; } @Override public List<WebSocketExtension> getSupportedExtensions(ServerHttpRequest request) { return Collections.emptyList(); } @Override public void upgrade(ServerHttpRequest request, ServerHttpResponse response, @Nullable String selectedProtocol, List<WebSocketExtension> selectedExtensions, @Nullable Principal user, WebSocketHandler handler, Map<String, Object> attributes) throws HandshakeFailureException { Assert.isInstanceOf(ServletServerHttpRequest.class, request, "ServletServerHttpRequest required"); HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); ServletContext servletContext = servletRequest.getServletContext(); Assert.isInstanceOf(ServletServerHttpResponse.class, response, "ServletServerHttpResponse required"); HttpServletResponse servletResponse = ((ServletServerHttpResponse) response).getServletResponse(); JettyWebSocketSession session = new JettyWebSocketSession(attributes, user); JettyWebSocketHandlerAdapter handlerAdapter = new JettyWebSocketHandlerAdapter(handler, session); JettyWebSocketCreator webSocketCreator = (upgradeRequest, upgradeResponse) -> { if (selectedProtocol != null) { upgradeResponse.setAcceptedSubProtocol(selectedProtocol); } return handlerAdapter; }; JettyWebSocketServerContainer container = JettyWebSocketServerContainer.getContainer(servletContext); try { container.upgrade(webSocketCreator, servletRequest, servletResponse); } catch (UndeclaredThrowableException ex) { throw new HandshakeFailureException("Failed to upgrade", ex.getUndeclaredThrowable()); } catch (Exception ex) { throw new HandshakeFailureException("Failed to upgrade", ex); } } }
package pl.pawel.weekop.service; import pl.pawel.weekop.dao.DAOFactory; import pl.pawel.weekop.dao.VoteDAO; import pl.pawel.weekop.model.Vote; import pl.pawel.weekop.model.VoteType; import java.sql.Timestamp; import java.util.Comparator; import java.util.Date; import java.util.List; public class VoteService { public Vote addVote(long discovery_id, long user_id, VoteType voteType) { Vote vote = new Vote(); vote.setDiscoveryId(discovery_id); vote.setUserId(user_id); vote.setDate(new Timestamp(new Date().getTime())); vote.setVoteType(voteType); DAOFactory factory = DAOFactory.getDAOFactory(); VoteDAO voteDAO = factory.getVoteDAO(); vote = voteDAO.create(vote); return vote; } public Vote updateVote(long discovery_id, long user_id, VoteType voteType) { DAOFactory factory = DAOFactory.getDAOFactory(); VoteDAO voteDAO = factory.getVoteDAO(); Vote voteToUpdate = voteDAO.getVoteByUserIdDiscoveryId(user_id,discovery_id); if (voteToUpdate != null && !voteToUpdate.getVoteType().equals(voteType)) { //System.out.println("Nie jest null i nie jest taki sam rodzaj glosu"); voteToUpdate.setVoteType(voteType); voteToUpdate.setDate(new Timestamp(new Date().getTime())); voteDAO.update(voteToUpdate); } else { System.out.println("Null lub taki sam rodzaj glosu"); } return voteToUpdate; } public Vote addOrUpdateVote(long discovery_id, long user_id, VoteType voteType) { DAOFactory factory = DAOFactory.getDAOFactory(); VoteDAO voteDAO = factory.getVoteDAO(); Vote vote = voteDAO.getVoteByUserIdDiscoveryId(user_id,discovery_id); Vote resultVote = null; if (vote == null) { resultVote= addVote(discovery_id,user_id,voteType); } else { resultVote = updateVote(discovery_id,user_id,voteType); } return resultVote; } public Vote getVoteByDiscoveryUserId(long discoveryId, long userId) { DAOFactory factory = DAOFactory.getDAOFactory(); VoteDAO voteDAO = factory.getVoteDAO(); Vote vote = voteDAO.getVoteByUserIdDiscoveryId(userId,discoveryId); return vote; } public List<Vote> getAllVotes(){ System.out.println("null comparator"); return getAllVotes(null);} public List<Vote> getAllVotes(Comparator<Vote> comparator) { DAOFactory factory = DAOFactory.getDAOFactory(); VoteDAO voteDAO = factory.getVoteDAO(); List<Vote> votes =voteDAO.getAll(); // System.out.println("voteService: "+ votes); if (comparator != null && votes != null) { votes.sort(comparator); } return votes; } }
package com.baizhi.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import lombok.experimental.Accessors; import java.io.Serializable; import java.util.Date; @Data @AllArgsConstructor @NoArgsConstructor @ToString @Accessors(chain = true) public class UserFiles implements Serializable { private int id; private String oldFileName; private String newFileName; private String ext; private String path; private String size; private String type; private String isImg; private int downCount; private Date uploadTime; private Integer userId; }
package com.useradmin.project.system.syslog; import org.apache.log4j.Logger; import java.sql.Timestamp; /** * 日志model * @author 董华健 */ @SuppressWarnings("unused") //@Table(tableName = "pt_syslog") public class Syslog /*extends BaseModel<Syslog> */{ private static final long serialVersionUID = 2051998642258015518L; private static Logger log = Logger.getLogger(Syslog.class); Syslog dao = new Syslog(); /** * 字段描述:主键 * 字段类型 :character varying */ String column_ids = "ids"; /** * 字段描述:版本号 * 字段类型 :bigint */ String column_version = "version"; /** * 字段描述:action结束时间 * 字段类型 :timestamp without time zone */ String column_actionenddate = "actionenddate"; /** * 字段描述:action结束时间 * 字段类型 :bigint */ String column_actionendtime = "actionendtime"; /** * 字段描述:action耗时 * 字段类型 :bigint */ String column_actionhaoshi = "actionhaoshi"; /** * 字段描述:action开始时间 * 字段类型 :timestamp without time zone */ String column_actionstartdate = "actionstartdate"; /** * 字段描述:action开始时间 * 字段类型 :bigint */ String column_actionstarttime = "actionstarttime"; /** * 字段描述:失败原因 : 0没有权限,1URL不存在,2未登录,3业务代码异常 * 字段类型 :character */ String column_cause = "cause"; /** * 字段描述:cookie数据 * 字段类型 :character varying */ String column_cookie = "cookie"; /** * 字段描述:描述 * 字段类型 :text */ String column_description = "description"; /** * 字段描述:结束时间 * 字段类型 :timestamp without time zone */ String column_enddate = "enddate"; /** * 字段描述:结束时间 * 字段类型 :bigint */ String column_endtime = "endtime"; /** * 字段描述:耗时 * 字段类型 :bigint */ String column_haoshi = "haoshi"; /** * 字段描述:客户端ip * 字段类型 :character varying */ String column_ips = "ips"; /** * 字段描述:访问方法 * 字段类型 :character varying */ String column_method = "method"; /** * 字段描述:源引用 * 字段类型 :character varying */ String column_referer = "referer"; /** * 字段描述:请求路径 * 字段类型 :text */ String column_requestpath = "requestpath"; /** * 字段描述:开始时间 * 字段类型 :timestamp without time zone */ String column_startdate = "startdate"; /** * 字段描述:开始时间 * 字段类型 :bigint */ String column_starttime = "starttime"; /** * 字段描述:账号状态 * 字段类型 :character */ String column_status = "status"; /** * 字段描述:useragent * 字段类型 :character varying */ String column_useragent = "useragent"; /** * 字段描述:视图耗时 * 字段类型 :bigint */ String column_viewhaoshi = "viewhaoshi"; /** * 字段描述:菜单对应功能ids * 字段类型 :character varying */ String column_operatorids = "operatorids"; /** * 字段描述:accept * 字段类型 :character varying */ String column_accept = "accept"; /** * 字段描述:acceptencoding * 字段类型 :character varying */ String column_acceptencoding = "acceptencoding"; /** * 字段描述:acceptlanguage * 字段类型 :character varying */ String column_acceptlanguage = "acceptlanguage"; /** * 字段描述:connection * 字段类型 :character varying */ String column_connection = "connection"; /** * 字段描述:host * 字段类型 :character varying */ String column_host = "host"; /** * 字段描述:xrequestedwith * 字段类型 :character varying */ String column_xrequestedwith = "xrequestedwith"; /** * 字段描述:pvids * 字段类型 :character varying */ String column_pvids = "pvids"; /** * 字段描述:访问用户ids * 字段类型 :character varying */ String column_userids = "userids"; /** * sqlId : platform.sysLog.view * 描述: */ String sqlId_view = "platform.sysLog.view"; /** * sqlId : platform.sysLog.splitPageSelect * 描述:分页select */ String sqlId_splitPageSelect = "platform.sysLog.splitPageSelect"; /** * sqlId : platform.sysLog.splitPageFrom * 描述:分页from */ String sqlId_splitPageFrom = "platform.sysLog.splitPageFrom"; /** * sqlId : platform.sysLog.clear * 描述:清除数据 */ String sqlId_clear = "platform.sysLog.clear"; private String ids; private String version; private String actionenddate; private String actionendtime; private String actionhaoshi; private String actionstartdate; private String actionstarttime; private String cause; private String cookie; private String description; private String enddate; private String endtime; private String haoshi; private String ips; private String method; private String referer; private String requestpath; private String startdate; private String starttime; private String status; private String useragent; private String viewhaoshi; private String operatorids; private String accept; private String acceptencoding; private String acceptlanguage; private String connection; private String host; private String xrequestedwith; private String pvids; private String userids; }
package com.vb.lsb.california.tour.repository; import com.vb.lsb.california.tour.model.Role; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; public interface RoleRepository extends JpaRepository<Role, Long> { Optional<Role> findByRoleName(String name); }
/** * Copyright (C) Alibaba Cloud Computing, 2012 * All rights reserved. * * 版权所有 (C)阿里巴巴云计算,2012 */ package com.aliyun.oss.common.parser; import com.aliyun.oss.common.comm.ResponseMessage; /** * Used to convert an result stream to a java object. */ public interface ResultParser { /** * Converts the result from stream to a java object. * @param resultStream The stream of the result. * @return The java object that the result stands for. * @throws ResultParseException Failed to parse the result. */ public Object getObject(ResponseMessage response) throws ResultParseException; }
package rdfsynopsis.test; import static org.junit.Assert.assertEquals; import java.io.StringWriter; import org.apache.log4j.Logger; import org.junit.Before; import org.junit.Test; import rdfsynopsis.analyzer.Analyzer; import rdfsynopsis.analyzer.TripleStreamAnalyzer; import rdfsynopsis.dataset.InMemoryDataset; import rdfsynopsis.statistics.TypedSubjectRatio; import rdfsynopsis.util.Namespace; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.sparql.vocabulary.FOAF; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.VCARD; public class TypedSubjectRatioTest { InMemoryDataset ds; Logger log = Logger.getLogger(TypedSubjectRatioTest.class); Namespace exampleNs = new Namespace("ex", "http://example.com/"); Resource maxRes; Resource petraRes; Resource stefanRes; Resource thomasRes; Resource biancaRes; Resource marcoRes; Resource nataliaRes; @Before public void setUpBefore() throws Exception { ds = new InMemoryDataset(); Model m = ds.getModel(); String maxMusterName = "Maximilian Mustermann"; String petraMusterName = "Petra Mustermann"; String stefanMusterName = "Thomas Mustermann"; String thomasMusterName = "Stefan Mustermann"; String biancaMusterName = "Bianca Mustermann"; String marcoMusterName = "Marco Mustermann"; String nataliaMusterName = "Natalia Mustermann"; String maxUri = "http://example.com/MaxMustermann"; String petraUri = "http://example.com/PetraMustermann"; String stefanUri = "http://example.com/StefanMustermann"; String thomasUri = "http://example.com/ThomasMustermann"; String biancaUri = "http://example.com/BiancaMustermann"; String marcoUri = "http://example.com/MarcoMustermann"; String nataliaUri = "http://example.com/NataliaMustermann"; maxRes = m.createResource(maxUri).addLiteral(VCARD.FN, maxMusterName); petraRes = m.createResource(petraUri).addLiteral(VCARD.FN, petraMusterName); stefanRes = m.createResource(stefanUri).addLiteral(VCARD.FN, stefanMusterName); thomasRes = m.createResource(thomasUri).addLiteral(VCARD.FN, thomasMusterName); biancaRes = m.createResource(biancaUri).addLiteral(VCARD.FN, biancaMusterName); marcoRes = m.createResource(marcoUri).addLiteral(VCARD.FN, marcoMusterName); nataliaRes = m.createResource(nataliaUri).addLiteral(VCARD.FN, nataliaMusterName); petraRes.addProperty(FOAF.knows, maxRes); maxRes.addProperty(FOAF.knows, petraRes); // output graph for debugging StringWriter out = new StringWriter(); m.write(out, "TTL"); log.debug(out.toString()); } @Test public void noOntology() { TypedSubjectRatio tsr = new TypedSubjectRatio(); tsr.processSparqlDataset(ds); double delta = 0.0000001; assertEquals(0.0, tsr.getTypedSubjectRatio(), delta); } @Test public void simpleOntology() { TypedSubjectRatio tsr = new TypedSubjectRatio(); Model m = ds.getModel(); Resource manClass = m.createResource(exampleNs.getFullTerm("Man")); Resource womanClass = m.createResource(exampleNs.getFullTerm("Woman")); // class instantiation m.add(maxRes, RDF.type, manClass); m.add(thomasRes, RDF.type, manClass); m.add(petraRes, RDF.type, womanClass); m.add(nataliaRes, RDF.type, womanClass); m.add(maxRes, RDF.type, FOAF.Person); m.add(petraRes, RDF.type, FOAF.Person); m.add(nataliaRes, RDF.type, FOAF.Person); m.add(marcoRes, RDF.type, FOAF.Person); tsr.processSparqlDataset(ds); // 2 untyped subjects: stefan, bianca // 5 typed subjects: max, thomas, petra, natalia, marco // TypedSubjectRatio = 5/7 double delta = 0.0000001; assertEquals(5.0/7.0, tsr.getTypedSubjectRatio(), delta); } @Test public void noOntologyTripleStream() { TypedSubjectRatio tsr = new TypedSubjectRatio(); Analyzer tsa = new TripleStreamAnalyzer(ds) .addCriterion(tsr); tsa.performAnalysis(null); double delta = 0.0000001; assertEquals(0.0, tsr.getTypedSubjectRatio(), delta); } @Test public void simpleOntologyTripleStream() { TypedSubjectRatio tsr = new TypedSubjectRatio(); Model m = ds.getModel(); Resource manClass = m.createResource(exampleNs.getFullTerm("Man")); Resource womanClass = m.createResource(exampleNs.getFullTerm("Woman")); // class instantiation m.add(maxRes, RDF.type, manClass); m.add(thomasRes, RDF.type, manClass); m.add(petraRes, RDF.type, womanClass); m.add(nataliaRes, RDF.type, womanClass); m.add(maxRes, RDF.type, FOAF.Person); m.add(petraRes, RDF.type, FOAF.Person); m.add(nataliaRes, RDF.type, FOAF.Person); m.add(marcoRes, RDF.type, FOAF.Person); Analyzer tsa = new TripleStreamAnalyzer(ds) .addCriterion(tsr); tsa.performAnalysis(null); // 2 untyped subjects: stefan, bianca // 5 typed subjects: max, thomas, petra, natalia, marco // TypedSubjectRatio = 5/7 double delta = 0.0000001; assertEquals(5.0/7.0, tsr.getTypedSubjectRatio(), delta); } }
/* * Copyright 2020 WeBank * * 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.webank.wedatasphere.schedulis.common.distributelock; import org.apache.commons.dbutils.ResultSetHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; import javax.inject.Inject; import azkaban.db.DatabaseOperator; /** * @author georgeqiao * @Title: AbstractDistributeLock * @date 2019/11/1220:44 * @Description: TODO */ public class AbstractDistributeLock implements DistributeLockAdapter { private static final Logger log = LoggerFactory.getLogger(AbstractDistributeLock.class); DatabaseOperator dbOperator; @Inject public AbstractDistributeLock(final DatabaseOperator dbOperator) { this.dbOperator = dbOperator; } //将requestId保存在该变量中 ThreadLocal<String> requestIdTL = new ThreadLocal<>(); /** * 获取当前线程所拥有的锁信息 */ public String getRequestId() { String requestId = requestIdTL.get(); if (requestId == null || "".equals(requestId)) { requestId = Thread.currentThread().getId() + ":" + UUID.randomUUID().toString(); requestIdTL.set(requestId); } log.debug("current_request_Id is {} ,current_request_ThreadName is {} " + requestId + "," + Thread.currentThread().getName()); return requestId; } public DistributeLock get(String lock_resource) { DistributeLock distributeLock = null; try { distributeLock = dbOperator.query(FetchDistributeLockHandler.FETCH_APPOINT_DISTRIBUTELOCK, new FetchDistributeLockHandler(),lock_resource); } catch (Exception e) { log.error("get exists lock failed {} lock_resource:" + lock_resource , e); } return distributeLock; } /** * JDBC ResultSetHandler to fetch records from executors table */ public static class FetchDistributeLockHandler implements ResultSetHandler<DistributeLock> { static String FETCH_APPOINT_DISTRIBUTELOCK = "select * from distribute_lock dl WHERE dl.lock_resource =?"; @Override public DistributeLock handle(final ResultSet rs) throws SQLException { if (!rs.next()) { log.info("there is no exist lock"); return null; } final int id = rs.getInt(1); final String request_id = rs.getString(2); final String lock_resource = rs.getString(3); final long lock_count = rs.getInt(4); final int version = rs.getInt(5); final String ip = rs.getString(6); final long timeout = rs.getLong(7); final long create_time = rs.getLong(8); final long update_time = rs.getLong(9); DistributeLock distributeLock = new DistributeLock(id,request_id, lock_resource, lock_count,version, ip,timeout,create_time,update_time); return distributeLock; } } public int insert(DistributeLock distributeLock) { String querySQL = "insert into distribute_lock (request_id,lock_resource,lock_count,version,ip,timeout,create_time,update_time) " + " values (?,?,?,?,?,?,?,?)"; int result = 0; try { result = dbOperator.update(querySQL, distributeLock.getRequest_id(), distributeLock.getLock_resource(), distributeLock.getLock_count(),distributeLock.getVersion(),distributeLock.getIp(), distributeLock.getTimeout(),distributeLock.getCreate_time(), distributeLock.getUpdate_time()); } catch (SQLException e) { log.error("acquire a lock failed {} distributeLock info:" + distributeLock.toString() , e); } return result; } public int delete(DistributeLock distributeLock) { String querySQL = "delete from distribute_lock " + "WHERE lock_resource = ?"; int result = 0; try { result = dbOperator.update(querySQL, distributeLock.getLock_resource()); } catch (SQLException e) { log.error("delete lock failed {} distributeLock info:" + distributeLock.toString() , e); } return result; } @Override public int updateLock(DistributeLock distributeLock) { String querySQL = "update distribute_lock dl set request_id=?,lock_count=?,version=version+1,ip=?,timeout=?,update_time=? " + "WHERE lock_resource =? and version =?"; int result = 0; try { result = dbOperator.update(querySQL, distributeLock.getRequest_id(),distributeLock.getLock_count(), distributeLock.getIp(), distributeLock.getTimeout(),distributeLock.getUpdate_time(), distributeLock.getLock_resource(), distributeLock.getVersion()); } catch (SQLException e) { log.error("update lock failed {} distributeLock info:" + distributeLock.toString() , e); } return result; } @Override public boolean lock(String lock_key, long locktimeout, long gettimeout) { return false; } @Override public void unlock(String lock_key) { } @Override public int resetLock(DistributeLock distributeLock) { return 0; } }
package modelo; import java.util.ArrayList; import distribuciones.DistribucionMedia; import vista.PAnimacion; public class Clientes2 extends Personas{ private static final long serialVersionUID = 1L; private ArrayList<Cliente2> clientes2; private int dias; public Clientes2(PAnimacion va,int nroClDob,int vel,int d,int temporada){ super(va,nroClDob,vel,temporada); dias=d; clientes2=new ArrayList<Cliente2>(); } public void run(){ int posx=0; int posy=pA.getHeight()-205; DistribucionMedia disMedia=new DistribucionMedia(); while(!pause){ for(int dia=0;dia<dias;dia++){// para los dias de la simulacion int velcxd=0; double desvio; switch (temporada) { case 1: desvio= demandaMedia*Temporada.alta2; break; case 2: desvio= demandaMedia*Temporada.media2; break; case 3: desvio= demandaMedia*Temporada.baja2; break; default:desvio=1.0; System.out.print("Error de Temporada"+temporada); break; } disMedia.generar(demandaMedia, desvio); demandaDia=(int)(disMedia.getValor()); if(demandaDia>0) velcxd=10000/demandaDia; else{ demandaDia=1; velcxd=10000/demandaDia; } for(int persona=0;persona<demandaDia;persona++){//para la cantidad de clientes por dia if(stopp) break; Cliente2 cliente2=new Cliente2(dia,posx,posy,vel,pA); cliente2.start(); try { Thread.sleep(velcxd); //tiempo que hay entre clientes en un dia } catch (InterruptedException e) { e.printStackTrace(); } clientes2.add(cliente2); } if(stopp){ stopp=false; break; } } break; } } public void setVel(int vel) { for(Cliente2 c2: clientes2){ c2.setVel(vel); System.out.println("Cambio Velocidad cliente2"); } } public int getClientes() { return clientes2.size(); } public void pause(boolean b) { pause=b; } public void setStop() { stopp=true; for(Cliente2 c2: clientes2) c2.setStop(); } }
package tnt.crasher.restaurant_management_system.Admin; import android.database.Cursor; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import tnt.crasher.restaurant_management_system.Admin_Lists.AddStaffDialog; import tnt.crasher.restaurant_management_system.Admin_Lists.StaffList; import tnt.crasher.restaurant_management_system.Admin_Lists.StaffListAdapter; import tnt.crasher.restaurant_management_system.Database.DatabaseHelper; import tnt.crasher.restaurant_management_system.R; public class AdminStaff extends AppCompatActivity { private FloatingActionButton button_addstaff; private ListView staffList; private StaffListAdapter staffListAdapter; private DatabaseHelper databaseHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_admin_staff); databaseHelper = new DatabaseHelper(getApplicationContext()); staffList = (ListView)findViewById(R.id.listview_staffmembers); ArrayList<StaffList> staffLists = new ArrayList<>(); button_addstaff = (FloatingActionButton)findViewById(R.id.button_addstaff); Cursor staff = databaseHelper.getStaff(); while(staff.moveToNext()){ staffLists.add(new StaffList(staff.getString(2), staff.getString(1), staff.getString(3), staff.getString(4), staff.getString(5))); } staff.close(); staffListAdapter = new StaffListAdapter(this, R.layout.staff_list, staffLists); staffList.setAdapter(staffListAdapter); button_addstaff.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AddStaffDialog cdd = new AddStaffDialog(AdminStaff.this); cdd.show(); } }); } }
package com.role.game.io.writer; import static java.lang.System.out; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.nio.file.Paths; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.role.game.util.IOUtil; public class OutputWriter { private static final String RESOURCES = "src/main/resources/"; private final Logger log = LogManager.getLogger(OutputWriter.class); public void showMessage(String msg) { out.println(msg); } public ObjectOutputStream getObjectOutputStream(String fileName) { FileOutputStream fileOutputStream; ObjectOutputStream objectOuputStream = null; try { File file = IOUtil.createFileIfDoesNotExist(absolutePath(RESOURCES, fileName)); fileOutputStream = new FileOutputStream(file); objectOuputStream = new ObjectOutputStream(fileOutputStream); } catch (FileNotFoundException e) { log.error("Error occured while creating file"); } catch (IOException e) { log.error("Error occured while creating file"); } return objectOuputStream; } protected static String absolutePath(String basePath, String pathToFile) { return Paths.get(basePath, pathToFile).toAbsolutePath().toString(); } }
package br.cefetrj.sca.dominio; import java.util.ArrayList; import java.util.List; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class ItemHorario { @Id @GeneratedValue private Long id; @Embedded private Intervalo tempoAula; @Enumerated(EnumType.ORDINAL) EnumDiaSemana dia; @SuppressWarnings("unused") private ItemHorario() { } public ItemHorario(EnumDiaSemana dia, String fim, String inicio) { tempoAula = new Intervalo(inicio, fim); this.dia = dia; } public Long getId() { return id; } public String getFim() { return this.tempoAula.getFim(); } public String getInicio() { return this.tempoAula.getInicio(); } public boolean colide(ItemHorario item) { return this.tempoAula.colide(item.tempoAula); } public static List<Intervalo> itens() { List<Intervalo> intervalosList = new ArrayList<Intervalo>(); intervalosList.add(new Intervalo("07:00", "07:50")); intervalosList.add(new Intervalo("07:55", "08:45")); intervalosList.add(new Intervalo("08:50", "09:40")); intervalosList.add(new Intervalo("09:55", "10:45")); intervalosList.add(new Intervalo("10:50", "11:40")); intervalosList.add(new Intervalo("11:45", "12:35")); intervalosList.add(new Intervalo("12:40", "13:30")); intervalosList.add(new Intervalo("13:35", "14:25")); intervalosList.add(new Intervalo("14:30", "15:20")); intervalosList.add(new Intervalo("15:35", "16:25")); intervalosList.add(new Intervalo("16:30", "17:20")); intervalosList.add(new Intervalo("17:25", "18:15")); intervalosList.add(new Intervalo("18:20", "19:10")); intervalosList.add(new Intervalo("19:10", "20:00")); intervalosList.add(new Intervalo("20:00", "20:50")); intervalosList.add(new Intervalo("21:00", "21:50")); intervalosList.add(new Intervalo("21:50", "22:40")); return intervalosList; } }
//Problem //Arrange Numbers in Array //Send Feedback //Given a number n, put all elements from 1 to n in an //array in order - 1,3,.......4,2. //Input Format : // Integer n //Output Format : // Elements of the array separated by space. //Sample Input 1 : //6 //Sample Output 1 : // 1 3 5 6 4 2 //Sample Input 2 : //9 //Sample Output 2 : // 1 3 5 7 9 8 6 4 2 import java.util.Scanner; public class array { public static void main(String[] args){ // TODO Auto-generated method stub Scanner sc=new Scanner (System.in); int n = sc.nextInt(); int[] arr=new int[n]; int i=0,j=n-1; int num =1; while(i<j) { arr[i]=num; i++; num++; arr[j]=num; num++; j--; } if(i==j) { arr[i]=num; } for (int x=0;x<arr.length;x++) { System.out.print(arr[x] + " "); } } }
package model.queue; import java.io.Serializable; /** * A runnable with optional attributes such as priority. Note that * you can override getID() to prevent the queuing of redundant * tasks. */ public class Task implements Runnable, Serializable { private static final long serialVersionUID = 4; private Runnable runnable; private int priority; private boolean requiresSwing; public Task (final Runnable runnable) { this (runnable, 0); } public Task (final Runnable runnable, final int priority) { this.runnable = runnable; setPriority (priority); } // for sub-classes that override run() public Task() { this (0); } public Task (final int priority) { setPriority (priority); } public void run() { runnable.run(); } /** Override this to prevent redundant tasks. */ public String getID() { return null; } public void setPriority (final int priority) { this.priority = priority; } public int getPriority() { return priority; } public void setRequiresSwing (final boolean requiresSwing) { this.requiresSwing = requiresSwing; } public boolean requiresSwing() { return requiresSwing; } @Override public String toString() { return runnable != null ? runnable.toString() : super.toString(); } }
package egovframework.adm.hom.qna; import java.io.File; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import egovframework.adm.hom.not.service.NoticeAdminService; import egovframework.com.cmm.EgovMessageSource; import egovframework.com.cmm.service.EgovFileMngUtil; import egovframework.com.cmm.service.EgovProperties; import egovframework.com.pag.controller.PagingManageController; @Controller public class QnaAdminController { /** log */ protected static final Log log = LogFactory.getLog(QnaAdminController.class); /** EgovMessageSource */ @Resource(name = "egovMessageSource") EgovMessageSource egovMessageSource; /** noticeAdminService */ @Resource(name = "noticeAdminService") NoticeAdminService noticeAdminService; /** PagingManageController */ @Resource(name = "pagingManageController") private PagingManageController pagingManageController; /** * 홈페이지 > QNA 리스트 * @param request * @param response * @param commandMap * @param model * @return * @throws Exception */ @RequestMapping(value="/adm/hom/qna/selectQnaList.do") public String selectQnaList(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{ commandMap.put("s_menu", "15000000"); commandMap.put("s_submenu", "15180000"); //p_tabseq if(commandMap.get("p_tabseq") == null || commandMap.get("p_tabseq").equals("")) { commandMap.put("p_tabseq", "1"); } // 보기일때 만. if(commandMap.get("p_seq") != null) { // qna 정보 model.addAttribute("view", noticeAdminService.selectQnaView(commandMap)); // 조회수 업데이트 noticeAdminService.updateQnaCount(commandMap); } int totCnt = noticeAdminService.selectQnaListTotCnt(commandMap); pagingManageController.PagingManage(commandMap, model, totCnt); // qna list List list = noticeAdminService.selectQnaList(commandMap); model.addAttribute("list", list); model.addAllAttributes(commandMap); return "adm/hom/qna/selectQnaList"; } /** * 입금게시판 * @param request * @param response * @param commandMap * @param model * @return * @throws Exception */ @RequestMapping(value="/adm/hom/qna/selectQnaList2.do") public String selectQnaList1(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{ commandMap.put("s_menu", "30020000"); commandMap.put("s_submenu", "30030000"); //p_tabseq commandMap.put("p_tabseq", "2"); // 보기일때 만. if(commandMap.get("p_seq") != null) { // qna 정보 model.addAttribute("view", noticeAdminService.selectQnaView(commandMap)); // 조회수 업데이트 noticeAdminService.updateQnaCount(commandMap); } int totCnt = noticeAdminService.selectQnaListTotCnt(commandMap); pagingManageController.PagingManage(commandMap, model, totCnt); // qna list List list = noticeAdminService.selectQnaList(commandMap); model.addAttribute("list", list); model.addAllAttributes(commandMap); return "adm/hom/qna/selectQnaList"; } /** * 환불게시판 * @param request * @param response * @param commandMap * @param model * @return * @throws Exception */ @RequestMapping(value="/adm/hom/qna/selectQnaList3.do") public String selectQnaList3(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{ commandMap.put("s_menu", "30020000"); commandMap.put("s_submenu", "30040000"); //p_tabseq commandMap.put("p_tabseq", "3"); // 보기일때 만. if(commandMap.get("p_seq") != null) { // qna 정보 model.addAttribute("view", noticeAdminService.selectQnaView(commandMap)); // 조회수 업데이트 noticeAdminService.updateQnaCount(commandMap); } int totCnt = noticeAdminService.selectQnaListTotCnt(commandMap); pagingManageController.PagingManage(commandMap, model, totCnt); // qna list List list = noticeAdminService.selectQnaList(commandMap); model.addAttribute("list", list); model.addAllAttributes(commandMap); return "adm/hom/qna/selectQnaList"; } /** * 홈페이지 > QNA 보기 * @param request * @param response * @param commandMap * @param model * @return * @throws Exception */ @RequestMapping(value="/adm/hom/qna/selectQnaView.do") public String selectQnaView(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{ // qna 정보 model.addAttribute("view", noticeAdminService.selectQnaView(commandMap)); model.addAllAttributes(commandMap); return "adm/hom/qna/selectQnaView"; } /** * 홈페이지 > QNA 등록/수정/삭제 작업 * @param request * @param response * @param commandMap * @param model * @return * @throws Exception */ @RequestMapping(value="/adm/hom/qna/selectQnaAction.do") public String selectQnaAction(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{ String resultMsg = ""; String p_tabseq = commandMap.get("p_tabseq") !=null ? (String)commandMap.get("p_tabseq") : ""; System.out.println("p_tabseq -----> "+ p_tabseq); String url = "/adm/hom/qna/selectQnaList.do"; if("2".equals(p_tabseq)){ url = "/adm/hom/qna/selectQnaList2.do"; }else if("3".equals(p_tabseq)){ url = "/adm/hom/qna/selectQnaList3.do"; } String p_process = (String)commandMap.get("p_process"); boolean isok = false; //업로드 처리를 한다. commandMap.putAll(this.uploadFiles(request, commandMap)); if(p_process.equalsIgnoreCase("insert")) { Object o = noticeAdminService.insertQna(commandMap); if(o != null) isok = true; } else if(p_process.equalsIgnoreCase("update")) { isok = noticeAdminService.updateQna(commandMap); } else if(p_process.equalsIgnoreCase("delete")) { isok = noticeAdminService.deleteQna(commandMap); //글의 값을 삭제하여 리스트로 보낸다. commandMap.remove("p_seq"); } if(isok) resultMsg = egovMessageSource.getMessage("success.common." + p_process); else resultMsg = egovMessageSource.getMessage("fail.common." + p_process); model.addAttribute("resultMsg", resultMsg); model.addAllAttributes(commandMap); return "forward:" + url; } /** * 업로드된 파일을 등록한다. * * @param contentPath 컨텐츠 경로 * @param contentCode 컨텐츠 코드 * @return Directory 생성 여부 * @throws Exception */ public Map<String, Object> uploadFiles(HttpServletRequest request, Map<String, Object> commandMap) throws Exception { //기본 업로드 폴더 String defaultDP = EgovProperties.getProperty("Globals.defaultDP"); log.info("- 기본 업로드 폴더 : " + defaultDP); //파일업로드를 실행한다. MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request; java.util.Iterator<?> fileIter = mptRequest.getFileNames(); while (fileIter.hasNext()) { MultipartFile mFile = mptRequest.getFile((String)fileIter.next()); if (mFile.getSize() > 0) { commandMap.putAll( EgovFileMngUtil.uploadContentFile(mFile, defaultDP + File.separator + "bulletin") ); } } return commandMap; } }
package tech.szymanskazdrzalik.a2048_app.boardActivity.Sensors; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import tech.szymanskazdrzalik.a2048_app.R; import tech.szymanskazdrzalik.a2048_app.boardActivity.BoardActivityListener; import tech.szymanskazdrzalik.a2048_app.helpers.PreferencesHelper; import static tech.szymanskazdrzalik.a2048_app.boardActivity.buttons.SettingsButton.chosenSensors; /** * Sets dark or light mode depending on the light level. */ public class DarkMode implements Runnable, SensorEventListener { private final static int DARK_MODE_ENABLE_DARK_MODE = 30; private final static int DARK_MODE_DISABLE_DARK_MODE = 50; private Context context; private PreferencesHelper preferencesHelper = PreferencesHelper.getInstance(); private BoardActivityListener boardActivityListener; private float mLightData; /** * Default class constructor. Sets class context. * * @param context context from activity. */ public DarkMode(Context context) { this.context = context; this.boardActivityListener = (BoardActivityListener) context; } /** * {@inheritDoc} * Calls {@link BoardActivityListener} to change the theme of the parent activity. */ @Override public void run() { if (mLightData <= DARK_MODE_ENABLE_DARK_MODE && !preferencesHelper.getDarkTheme()) { preferencesHelper.setDarkTheme(true); boardActivityListener.callback(context.getString(R.string.SetTheme)); } else if (mLightData >= DARK_MODE_DISABLE_DARK_MODE && preferencesHelper.getDarkTheme()) { preferencesHelper.setDarkTheme(false); boardActivityListener.callback(context.getString(R.string.SetTheme)); } } /** * {@inheritDoc} */ @Override public void onSensorChanged(SensorEvent event) { this.mLightData = event.values[0]; if (chosenSensors[2]) { new Thread(this).start(); } } /** * {@inheritDoc} */ @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }
package com.bistel.storm.topology; import org.slf4j.Logger; import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.StormSubmitter; import backtype.storm.topology.BoltDeclarer; import backtype.storm.topology.TopologyBuilder; import backtype.storm.tuple.Fields; import com.bistel.configuration.ConfigConstants; import com.bistel.configuration.ConfigurationManager; import com.bistel.logging.util.LogUtil; import com.bistel.storm.bolt.dcp.DCPBolt; import com.bistel.storm.bolt.fdc.FDCBolt; import com.rapportive.storm.amqp.SharedQueueWithBinding; import com.rapportive.storm.spout.AMQPSpout; /** * * This class defines the storm topology which uses KestrelThriftSpout to retrieve virtual tool messages * from kestrel queue and the DCP, FDC and Esper Bolts which further process the messages. * */ public class TraceReportEventsTopology { private static Logger _logger = LogUtil.getLogger(TraceReportEventsTopology.class); private static final String spoutName = "TraceReportMessageSpout"; private static final String dcpBoltName = "DCPBolt"; private static final String fdcBoltName = "FDCBolt"; /** * It will get called when the topology will get submitted. * This will set the spout and all the required bolts and in last submit the topology to the cluster. * * @param args */ public static void main(String args[]){ ConfigurationManager cm = ConfigurationManager.getInstance(ConfigConstants.DEFAULT_RESOURCE_NAME); // Retrieve the spout count int spoutCount = Integer.parseInt(cm.getConfiguration("tracereport.spout.queue.count")); // Retrieve the topology name String topologyName = cm.getConfiguration("tracereport.topology.name"); TopologyBuilder builder = new TopologyBuilder(); // Set the kestrel spouts for (int i = 0; i < spoutCount; i++) { // Get the queue configuration for the respective spout. String queueConfig = cm.getConfiguration("tracereport.message.queue."+i); String hostname = queueConfig.substring(0, queueConfig.indexOf(":")); String port = queueConfig.substring(queueConfig.indexOf(":")+1, queueConfig.lastIndexOf(":")); String queueName = queueConfig.substring(queueConfig.lastIndexOf(":")+1); // declaring the spout SharedQueueWithBinding queueDeclaration = new SharedQueueWithBinding(queueName, cm.getConfiguration("tracereport.messaging.exchange"), queueName); AMQPSpout spout = new AMQPSpout(hostname, Integer.parseInt(port), cm.getConfiguration("tracereport.messaging.user"), cm.getConfiguration("tracereport.messaging.passsword"), "/", queueDeclaration, new TraceReportScheme()); builder.setSpout(spoutName+"_"+i, spout, Integer.parseInt(cm.getConfiguration("spout.parallelism")) ); } // Set the DCP Bolt BoltDeclarer dcpBolt = builder.setBolt(dcpBoltName, new DCPBolt(), Integer.parseInt(cm.getConfiguration("bolt.dcp.parallelism")) ); // Set the field grouping to each spout created above. for (int i = 0; i < spoutCount; i++) { dcpBolt.fieldsGrouping(spoutName+"_"+i, new Fields("stepId","toolId")); } // Set FDC Bolt builder.setBolt(fdcBoltName, new FDCBolt(), Integer.parseInt(cm.getConfiguration("bolt.fdc.parallelism")) ).fieldsGrouping(dcpBoltName, new Fields("stepId","toolId")); try{ Config conf = new Config(); conf.setDebug(Boolean.parseBoolean(cm.getConfiguration("tracereport.topology.debug"))); //conf.setMessageTimeoutSecs(180); conf.setNumAckers(Integer.parseInt(cm.getConfiguration("tracereport.topology.ackers.count"))); conf.setMaxSpoutPending(Integer.parseInt(cm.getConfiguration("tracereport.topology.maxSpoutPendingCount"))); // Number of worker process to be run for the topology conf.setNumWorkers(Integer.parseInt(cm.getConfiguration("tracereport.topology.workers.count"))); String mode = cm.getConfiguration("tracereport.topology.mode"); // Submit topology to local cluster. Use it while running the topology from eclipse. if ("local".equalsIgnoreCase(mode)) { LocalCluster cluster = new LocalCluster(); cluster.submitTopology(topologyName, conf, builder.createTopology()); } else { // Submit topology to configured cluster StormSubmitter.submitTopology(topologyName, conf, builder.createTopology()); } }catch(Exception e){ _logger.error("Error while submitting the topology", e); } } }
package com.github.gaoyangthu.esanalysis.ebusi.service; import com.github.gaoyangthu.esanalysis.ebusi.bean.MasterOrder; import java.util.Date; import java.util.List; /** * master_order表接口 * * Author: gaoyangthu * Date: 14-3-12 * Time: 下午5:34 */ public interface OrderService { /** * 根据时间查询订单 * * @param beginDate 开始时间 * @param endDate 结束时间 * @return 订单列表 */ List<MasterOrder> findByDate(Date beginDate, Date endDate); }
public class LuhnApp { public static void main(String[] args) { Luhn l1 = new Luhn (); int anzParam = args.length; for( int i = 0; i< anzParam ; i++) { boolean res = l1.check(args[i], 16); System.out.println(res); } } }
/* NeighborhoodSizeAnalysis -- a class within the Cellular Automaton Explorer. Copyright (C) 2007 David B. Bahr (http://academic.regis.edu/dbahr/) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package cellularAutomata.analysis; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Shape; import java.awt.Stroke; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.beans.PropertyChangeEvent; import java.io.IOException; import java.util.Collection; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.border.Border; import javax.swing.border.TitledBorder; import cellularAutomata.CAController; import cellularAutomata.Cell; import cellularAutomata.CurrentProperties; import cellularAutomata.cellState.model.CellState; import cellularAutomata.cellState.model.IntegerCellState; import cellularAutomata.cellState.view.CellStateView; import cellularAutomata.cellState.view.IntegerCellStateView; import cellularAutomata.graphics.CAFrame; import cellularAutomata.graphics.colors.ColorScheme; import cellularAutomata.graphics.colors.colorChooser.IntegerStateColorChooser; import cellularAutomata.lattice.Lattice; import cellularAutomata.reflection.ReflectionTool; import cellularAutomata.rules.Rule; import cellularAutomata.rules.templates.FiniteObjectRuleTemplate; import cellularAutomata.util.AttentionPanel; import cellularAutomata.util.Coordinate; import cellularAutomata.util.Fonts; import cellularAutomata.util.GBC; import cellularAutomata.util.MultilineLabel; import cellularAutomata.util.SimplePlot; import cellularAutomata.util.files.FileWriter; /** * Finds the distribution of connectivity of sites with any given state. Most * applicable to lattices with variable sized neighborhoods like the small world * lattice. * * @author David Bahr */ public class NeighborhoodSizeAnalysis extends Analysis implements ActionListener { // the constant representing all states. Should not be any integer // between 0 and numStates (inclusive). Used to identify the user's choice // of state(s) to analyze. private static final int ALL_STATES_CHOICE = -3; // the constant representing all non-empty states. Should not be any integer // between 0 and numStates (inclusive). Used to identify the user's choice // of state(s) to analyze. private static final int ALL_NON_EMPTY_STATES_CHOICE = -1; // the constant representing the empty state. Should not be any integer // between 0 and numStates (inclusive). Used to identify the user's choice // of state(s) to analyze. private static final int EMPTY_STATE_CHOICE = -2; // the interval of time steps between which plot axes are adjusted. Don't // want to adjust too often or the plot "flickers" private static final int TIME_TO_ADJUST_AXES = 10; // a brief display name for this class private static final String ANALYSIS_NAME = "Neighborhood Sizes"; // display info for this class private static final String INFO_MESSAGE = "Plots the distribution of " + "neighborhood sizes. In other words, for each cell on the lattice, this " + "analysis finds the number " + "of neighbors that are connected to that cell. These numbers are collected " + "for all cells and plotted. When a particular state " + "is selected, only cells of that state are plotted. \n" + "This analysis is most useful for lattices with variable-sized " + "neighborhoods. For example, try the small-world lattice or the random " + "asymmetric lattice."; // the label for the "plot zero values" check box private static final String PLOT_ZERO_VALUES = " Plot neighborhoods of size 0"; // the tooltip for the "plot zero values" check box private static final String PLOT_ZERO_VALUES_TOOLTIP = "<html><body>" + "When unchecked, this prevents clusters of size 0 from being plotted. <br>" + "The zero values can obscure other data. (Note that the log-log plot <br>" + "never shows clusters of size 0, which would plot at -infinity.)</body></html>"; // title for the subpanel that lets the user select the state to be analyzed private static final String RADIO_BUTTON_PANEL_TITLE = "Select state to analyze"; // the action command for saving the data and the label used by the "save // data" check box private static final String SAVE_DATA = " Save the data"; // a tooltip for the save data check box private static final String SAVE_DATA_TOOLTIP = "<html>Saves neighborhood " + "distribution data to a file (saves <br> every generation while the " + "box is checked).</html>"; // text for the button that lets the user select the state for which the // cluster sizes will be calculated. private static final String SELECT_STATE = "Select state"; // tooltip for the button that lets the state be selected private static final String SELECT_STATE_TOOLTIP = "Select a state for which the \n" + "neighborhood sizes will be calculated."; // the action command for the state chooser private static final String STATE_CHOOSER = "state chooser"; // a brief tooltip description for this class private static final String TOOLTIP = "<html>finds and plots the size of each " + "cell's neighborhood</html>"; // show the zero values on each plot private boolean plotZeroValues = false; // the current view for the rule private CellStateView view = null; // the color of the current state private Color currentColor = Color.GRAY; // color of titles of sections private Color titleColor = Color.BLUE; // a color patch so the user can see the color being analyzed private ColorPatch colorPatch = null; // the max value on the x-axis of the log-log plot at the last time step private double oldLogMaxXValue = 1; // the max value on the y-axis of the log-log plot at the last time step private double oldLogMaxYValue = 1; // time steps since last adjusted the log x-axis value private int elapsedTimeStepsSinceLastAdjustedLogXAxis = 0; // time steps since last adjusted the log y-axis value private int elapsedTimeStepsSinceLastAdjustedLogYAxis = 0; // time steps since last adjusted the x-axis value private int elapsedTimeStepsSinceLastAdjustedXAxis = 0; // time steps since last adjusted the y-axis value private int elapsedTimeStepsSinceLastAdjustedYAxis = 0; // the state that was last selected by the user (used in the graphics) private int lastSelectedState = ALL_STATES_CHOICE; // the max value on the x-axis at the last time step private int oldMaxXValue = 1; // the max value on the y-axis at the last time step private int oldMaxYValue = 1; // the number of states in the current simulation private int numStates = 2; // the state that has been selected for analysis private int selectedState = 1; // the number of neighborhoods of each size private int[] numberOfNeighborhoodsOfEachSize = null; // If the user wants to save the data to a file, this will be instantiated private FileWriter fileWriter = null; // fonts for display private Fonts fonts = new Fonts(); // title font (for titles of sections) private Font titleFont = new Fonts().getItalicSmallerFont(); // used to select the state that will be analyzed private IntegerStateColorChooser integerColorChooser = null; // the button for selecting the state to be analyzed private JButton selectStateButton = null; // label for the current generation private JLabel generationDataLabel = null; // The check box that lets the user plot values of zero private JCheckBox plotZeroValueCheckBox = null; // The check box that lets the user save the data private JCheckBox saveDataCheckBox = null; // the panel where results are displayed private JPanel displayPanel = null; // radio button for choosing all states (i.e., all will be used to // calculate the neighborhood sizes) private JRadioButton allStatesButton = null; // radio button for choosing the empty state (that will be used to // calculate the neighborhood sizes) private JRadioButton emptyStateButton = null; // radio button for choosing the non-empty states (that will be used to // calculate the neighborhood sizes) private JRadioButton nonEmptyStatesButton = null; // radio button for choosing a particular state (that will be used to // calculate the neighborhood sizes) private JRadioButton particularStateButton = null; // the neighborhood sizes as points of (size, number neighborhoods of that // size) private Point2D.Double[] neighborhoodNumbers = null; // the current rule private Rule rule = null; // a panel that plots the neighborhood data on log-log axes private SimplePlot logPlot = null; // a panel that plots the neighborhood data private SimplePlot plot = null; // a delimiter for spacing data in the data file private String delimiter = null; // data that will be saved to a file private String[] data = null; /** * Create an analyzer that finds neighborhood sizes. * <p> * When building child classes, the minimalOrLazyInitialization parameter * must be included but may be ignored. However, the boolean is intended to * indicate when the child's constructor should build an analysis with as * small a footprint as possible. In order to load analyses by reflection, * the application must query the child classes for information like their * display names, tooltip descriptions, etc. At these times it makes no * sense to build the complete analysis which may have a large footprint in * memory. * <p> * It is recommended that the child's constructor and instance variables do * not initialize any variables and that variables be initialized only when * first needed (lazy initialization). Or all initializations in the * constructor may be placed in an <code>if</code> statement (as * illustrated in the parent constructor and in most other analyses designed * by David Bahr). * * <pre> * if(!minimalOrLazyInitialization) * { * ...initialize * } * </pre> * * @param minimalOrLazyInitialization * When true, the constructor instantiates an object with as * small a footprint as possible. When false, the analysis is * fully constructed, complete with close buttons, display * panels, etc. If uncertain, set this variable to false. */ public NeighborhoodSizeAnalysis(boolean minimalOrLazyInitialization) { super(minimalOrLazyInitialization); if(!minimalOrLazyInitialization) { setUpAnalysis(); } } /** * Actions to take when "Select state to analyze" is selected. */ private void chooseAnalysisState() { // create a state/color chooser integerColorChooser = new IntegerStateColorChooser(null, numStates, selectedState, currentColor, new OkColorListener(STATE_CHOOSER)); integerColorChooser.setVisible(true); } /** * Converts the distribution of sizes to a Point2D array for plotting (not * relevant to the log-log plot -- this is only used by the regular plot). */ private void convertNeighborhoodSizesToPointArray() { synchronized(this) { if(plotZeroValues) { // convert to a Point2D array if(numberOfNeighborhoodsOfEachSize.length > 0) { neighborhoodNumbers = new Point2D.Double[numberOfNeighborhoodsOfEachSize.length]; for(int i = 0; i < neighborhoodNumbers.length; i++) { neighborhoodNumbers[i] = new Point2D.Double(i, numberOfNeighborhoodsOfEachSize[i]); } } else { neighborhoodNumbers = new Point2D.Double[1]; neighborhoodNumbers[0] = new Point2D.Double(0, 0); } } else { // convert to a Point2D array if(numberOfNeighborhoodsOfEachSize.length > 0) { // create a list of non-zero values LinkedList<Point2D.Double> numList = new LinkedList<Point2D.Double>(); for(int i = 0; i < numberOfNeighborhoodsOfEachSize.length; i++) { if(numberOfNeighborhoodsOfEachSize[i] > 0) { numList.add(new Point2D.Double(i, numberOfNeighborhoodsOfEachSize[i])); } } // convert to an array so compatible with other code already // written :-( neighborhoodNumbers = new Point2D.Double[numList.size()]; for(int i = 0; i < neighborhoodNumbers.length; i++) { neighborhoodNumbers[i] = numList.get(i); } } else { neighborhoodNumbers = new Point2D.Double[1]; neighborhoodNumbers[0] = new Point2D.Double(0, 0); } } } } /** * Create labels used to display the data for the population statistics. */ private void createDataDisplayLabels() { // if one is null, then they all are if(generationDataLabel == null) { generationDataLabel = new JLabel(""); } } /** * Create the panel used to display the population statistics. */ private void createDisplayPanel() { int displayWidth = CAFrame.tabbedPaneDimension.width; int displayHeight = 920; // create the display panel if(displayPanel == null) { displayPanel = new JPanel(new GridBagLayout()); displayPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); displayPanel.setPreferredSize(new Dimension(displayWidth, displayHeight)); } else { displayPanel.removeAll(); } // create a panel that displays messages JPanel messagePanel = createMessagePanel(); // create a panel that holds the select state radio buttons JPanel stateSelectionPanel = createStateRadioButtonPanel(); // create the labels for the display createDataDisplayLabels(); // create a "save data" check box saveDataCheckBox = new JCheckBox(SAVE_DATA); saveDataCheckBox.setToolTipText(SAVE_DATA_TOOLTIP); saveDataCheckBox.setActionCommand(SAVE_DATA); saveDataCheckBox.addActionListener(this); JPanel saveDataPanel = new JPanel(new BorderLayout()); saveDataPanel.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)); saveDataPanel.add(BorderLayout.CENTER, saveDataCheckBox); // create a "plot zero values" check box plotZeroValueCheckBox = new JCheckBox(PLOT_ZERO_VALUES); plotZeroValueCheckBox.setSelected(false); plotZeroValueCheckBox.setToolTipText(PLOT_ZERO_VALUES_TOOLTIP); plotZeroValueCheckBox.setActionCommand(PLOT_ZERO_VALUES); plotZeroValueCheckBox.addActionListener(this); JPanel plotZeroValuePanel = new JPanel(new BorderLayout()); plotZeroValuePanel.setBorder(BorderFactory .createEmptyBorder(7, 7, 7, 7)); plotZeroValuePanel.add(BorderLayout.CENTER, plotZeroValueCheckBox); // create a panels that plots the data plot = new SimplePlot(); logPlot = new SimplePlot(); // add all the components to the panel int row = 0; displayPanel.add(messagePanel, new GBC(1, row).setSpan(4, 1).setFill( GBC.HORIZONTAL).setWeight(1.0, 1.0).setAnchor(GBC.WEST) .setInsets(1)); row++; displayPanel.add(plot, new GBC(1, row).setSpan(4, 1).setFill(GBC.BOTH) .setWeight(10.0, 10.0).setAnchor(GBC.WEST).setInsets(1)); row++; displayPanel.add(logPlot, new GBC(1, row).setSpan(4, 1).setFill( GBC.BOTH).setWeight(10.0, 10.0).setAnchor(GBC.WEST) .setInsets(1)); row++; displayPanel.add(plotZeroValuePanel, new GBC(1, row).setSpan(4, 1) .setFill(GBC.NONE).setWeight(1.0, 1.0).setAnchor(GBC.CENTER) .setInsets(1)); row++; displayPanel.add(stateSelectionPanel, new GBC(1, row).setSpan(4, 1) .setFill(GBC.NONE).setWeight(1.0, 1.0).setAnchor(GBC.WEST) .setInsets(1)); row++; displayPanel.add(saveDataPanel, new GBC(1, row).setSpan(4, 1).setFill( GBC.NONE).setWeight(1.0, 1.0).setAnchor(GBC.CENTER) .setInsets(1)); } /** * This uses a handy file writing utility to create a file writer. */ private void createFileWriter() { try { // This will prompt the user to enter a file. (The save data file // path parameter is just the default folder where the file chooser // will open.) fileWriter = new FileWriter(CurrentProperties.getInstance() .getSaveDataFilePath()); // data delimiters (what string will be used to separate data in the // file) delimiter = CurrentProperties.getInstance().getDataDelimiters(); // save a header (have to plan ahead for the max possible cluster // size, width * height) int width = CurrentProperties.getInstance().getNumColumns(); int height = CurrentProperties.getInstance().getNumRows(); String[] header = new String[(width * height) + 1]; header[0] = "Generation"; for(int i = 1; i < header.length; i++) { header[i] = "Neighborhoods of size " + i + ":"; } fileWriter.writeData(header, delimiter); // save the initial data (at the generation when the user requested // that the data be saved) if(data != null) { fileWriter.writeData(data, delimiter); } } catch(IOException e) { // This happens if the user did not select a valid file. (For // example, the user cancelled and did not choose any file when // prompted.) So uncheck the "file save" box if(saveDataCheckBox != null) { saveDataCheckBox.setSelected(false); } // tell the user that they really should have selected a file String message = "A valid file was not selected, so the data \n" + "will not be saved."; JOptionPane.showMessageDialog(CAController.getCAFrame().getFrame(), message, "Valid file not selected", JOptionPane.INFORMATION_MESSAGE); } } /** * Creates a panel that displays messages. * * @return A panel containing messages. */ private JPanel createMessagePanel() { // a "grab their attention" panel AttentionPanel attentionPanel = new AttentionPanel("Neighborhood Sizes"); MultilineLabel messageLabel = new MultilineLabel(INFO_MESSAGE); messageLabel.setFont(fonts.getAnalysesDescriptionFont()); messageLabel.setMargin(new Insets(6, 10, 2, 16)); JPanel messagePanel = new JPanel(new BorderLayout()); messagePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); messagePanel.add(attentionPanel, BorderLayout.NORTH); messagePanel.add(messageLabel, BorderLayout.CENTER); return messagePanel; } /** * Creates radio buttons to choose which state(s) will be used to calculate * the fractal dimension. */ private JPanel createStateRadioButtonPanel() { allStatesButton = new JRadioButton("all states"); allStatesButton.setFont(fonts.getPlainFont()); allStatesButton.addItemListener(new StateChoiceListener()); nonEmptyStatesButton = new JRadioButton("all non-empty states"); nonEmptyStatesButton.setFont(fonts.getPlainFont()); nonEmptyStatesButton.addItemListener(new StateChoiceListener()); nonEmptyStatesButton.setSelected(false); emptyStateButton = new JRadioButton("empty state"); emptyStateButton.setFont(fonts.getPlainFont()); emptyStateButton.addItemListener(new StateChoiceListener()); emptyStateButton.setSelected(false); particularStateButton = new JRadioButton("choose state"); particularStateButton.setFont(fonts.getPlainFont()); particularStateButton.addItemListener(new StateChoiceListener()); particularStateButton.setSelected(false); // put them in a group so that they behave as radio buttons ButtonGroup group = new ButtonGroup(); group.add(allStatesButton); group.add(nonEmptyStatesButton); group.add(emptyStateButton); group.add(particularStateButton); // create a "select state to analyze" button and a color patch that // shows the state selectStateButton = new JButton(SELECT_STATE); selectStateButton.setActionCommand(SELECT_STATE); selectStateButton.setToolTipText(SELECT_STATE_TOOLTIP); selectStateButton.addActionListener(this); // create the selection JButton and color patch that goes next to the // particularStateButton JPanel stateSelectionPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); stateSelectionPanel.add(selectStateButton); stateSelectionPanel.add(colorPatch); // create combined particularStateButton and colorPatch panel // JPanel selectStatePane = new JPanel(new BorderLayout()); // selectStatePane.add(BorderLayout) // create boxes for each column of the display (a Box uses the // BoxLayout, so it is handy for laying out components) Box boxOfRadioButtons = Box.createVerticalBox(); Box boxWithColorPatch = Box.createVerticalBox(); // the amount of vertical and horizontal space to put between components int verticalSpace = 5; int horizontalSpace = 0; // add the radio buttons to the first vertical box boxOfRadioButtons.add(allStatesButton); boxOfRadioButtons.add(Box.createVerticalStrut(verticalSpace)); boxOfRadioButtons.add(nonEmptyStatesButton); boxOfRadioButtons.add(Box.createVerticalStrut(verticalSpace)); boxOfRadioButtons.add(emptyStateButton); boxOfRadioButtons.add(Box.createVerticalStrut(verticalSpace)); boxOfRadioButtons.add(particularStateButton); // add the color patch to the second vertical box boxWithColorPatch.add(new JLabel(" ")); boxWithColorPatch.add(Box.createVerticalStrut(verticalSpace)); boxWithColorPatch.add(new JLabel(" ")); boxWithColorPatch.add(Box.createVerticalStrut(verticalSpace)); boxWithColorPatch.add(new JLabel(" ")); boxWithColorPatch.add(Box.createVerticalStrut(verticalSpace + 15)); boxWithColorPatch.add(stateSelectionPanel); // create another box that holds both of the label boxes Box boxOfLabels = Box.createHorizontalBox(); boxOfLabels.add(boxOfRadioButtons); boxOfLabels.add(Box.createHorizontalStrut(horizontalSpace)); boxOfLabels.add(boxWithColorPatch); // create a JPanel for the radio buttons and their containing box JPanel radioPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); Border emptyBorder = BorderFactory.createEmptyBorder(0, 0, 0, 5); Border titledBorder = BorderFactory.createTitledBorder(BorderFactory .createEtchedBorder(), RADIO_BUTTON_PANEL_TITLE, TitledBorder.LEFT, TitledBorder.DEFAULT_POSITION, titleFont, titleColor); Border compoundBorder = BorderFactory.createCompoundBorder( titledBorder, emptyBorder); radioPanel.setBorder(compoundBorder); radioPanel.add(boxOfLabels); return radioPanel; } /** * Plots the population data on a regular plot. */ private void plotData() { // axes labels plot.setXAxisLabel("neighborhood size, S"); plot.setYAxisLabel("# of neighborhoods, N(S)"); // the max x and y-values plotted int maxYValue = 1; int maxXValue = 1; // find the max y-value for plotting for(int i = 0; i < numberOfNeighborhoodsOfEachSize.length; i++) { if(numberOfNeighborhoodsOfEachSize[i] > maxYValue) { maxYValue = numberOfNeighborhoodsOfEachSize[i]; } } if(maxYValue < 1) { maxYValue = 1; } // find the max x value for plotting for(int i = 0; i < neighborhoodNumbers.length; i++) { if(neighborhoodNumbers[i].x > maxXValue) { maxXValue = (int) neighborhoodNumbers[i].x; } } // set the min and max x values on the plot elapsedTimeStepsSinceLastAdjustedXAxis++; plot.setMinimumXValue(0); if(neighborhoodNumbers.length > 0) { if(maxXValue >= oldMaxXValue || elapsedTimeStepsSinceLastAdjustedXAxis == TIME_TO_ADJUST_AXES) { plot.setMaximumXValue(maxXValue); oldMaxXValue = maxXValue; elapsedTimeStepsSinceLastAdjustedXAxis = 0; // draw some extra points on the x-axis (looks good) if(maxXValue > 20) { int numberOfExtraXPoints = 3; double[] xValues = new double[numberOfExtraXPoints]; for(int i = 0; i < xValues.length; i++) { xValues[i] = (int) (i + 1.0) * ((double) maxXValue) / (double) (numberOfExtraXPoints + 1); } plot.setExtraXAxisValues(xValues); } else if(maxXValue > 1) { int numberOfExtraXPoints = maxXValue - 1; double[] xValues = new double[numberOfExtraXPoints]; for(int i = 0; i < xValues.length; i++) { xValues[i] = (int) (i + 1.0) * ((double) maxXValue) / (double) (numberOfExtraXPoints + 1); } plot.setExtraXAxisValues(xValues); } plot.showXValuesAsInts(true); } } // set the min y value on the plot plot.setMinimumYValue(0); // set the max y value on the plot (to nearest 10^nth power) elapsedTimeStepsSinceLastAdjustedYAxis++; maxYValue = (int) Math.pow(10, Math.ceil(Math.log10(maxYValue))); if(maxYValue >= oldMaxYValue || elapsedTimeStepsSinceLastAdjustedYAxis == TIME_TO_ADJUST_AXES) { plot.setMaximumYValue(maxYValue); oldMaxYValue = maxYValue; elapsedTimeStepsSinceLastAdjustedYAxis = 0; // draw some extra points on the y-axis (looks good) if(maxYValue > 1) { int numberOfExtraYPoints = 9; double[] yValues = new double[numberOfExtraYPoints]; for(int i = 0; i < yValues.length; i++) { yValues[i] = (i + 1.0) * ((double) maxYValue) / (double) (numberOfExtraYPoints + 1); } plot.setExtraYAxisValues(yValues); } plot.showYValuesAsInts(true); } // specify colors for the points if(neighborhoodNumbers.length > 0) { Color stateColor = Color.BLACK; if(selectedState != ALL_NON_EMPTY_STATES_CHOICE && selectedState != ALL_STATES_CHOICE) { int stateWeArePlotting = selectedState; if(selectedState == EMPTY_STATE_CHOICE) { stateWeArePlotting = 0; } if(IntegerCellStateView.isCurrentRuleCompatible() && IntegerCellState.isCurrentRuleCompatible()) { CellStateView view = Cell.getView(); stateColor = view.getDisplayColor(new IntegerCellState( stateWeArePlotting), null, new Coordinate(0, 0)); } } Color[] colorArray = new Color[neighborhoodNumbers.length]; for(int point = 0; point < colorArray.length; point++) { colorArray[point] = stateColor; } plot.setPointDisplayColors(colorArray); } else { plot.setPointDisplayColorsToDefault(); } // finally draw the plot plot.drawPoints(neighborhoodNumbers); } /** * Plots the population data on a log-log plot. */ private void plotLogLogData() { // axes labels logPlot.setXAxisLabel("log(S)"); logPlot.setYAxisLabel("log(N(S))"); // the max x and y-values plotted double maxYValue = 1.0; double maxXValue = 1.0; // convert to a Point2D array LinkedList<Point2D.Double> logNumbers = new LinkedList<Point2D.Double>(); for(int i = 0; i < numberOfNeighborhoodsOfEachSize.length; i++) { if(numberOfNeighborhoodsOfEachSize[i] > 0) { logNumbers.add(new Point2D.Double(Math.log(i + 1), Math .log(numberOfNeighborhoodsOfEachSize[i]))); } // and keep track of the max value for plotting if(numberOfNeighborhoodsOfEachSize[i] > 0) { maxXValue = i + 1; } if(numberOfNeighborhoodsOfEachSize[i] > maxYValue) { maxYValue = numberOfNeighborhoodsOfEachSize[i]; } } // round up the max values to the nearest exponent n (of 10^n) maxXValue = Math.ceil(Math.log(maxXValue)); maxYValue = Math.ceil(Math.log(maxYValue)); if(maxXValue == 0.0) { maxXValue = 1.0; } if(maxYValue == 0.0) { maxYValue = 1.0; } // make sure the list isn't empty if(logNumbers.size() == 0) { logNumbers.add(new Point2D.Double(0.0, 0.0)); maxXValue = 1.0; maxYValue = 1.0; } // set the min and max x values on the plot elapsedTimeStepsSinceLastAdjustedLogXAxis++; logPlot.setMinimumXValue(0); if(maxXValue >= oldLogMaxXValue || elapsedTimeStepsSinceLastAdjustedLogXAxis == TIME_TO_ADJUST_AXES) { logPlot.setMaximumXValue(maxXValue); oldLogMaxXValue = maxXValue; elapsedTimeStepsSinceLastAdjustedLogXAxis = 0; // draw some extra points on the x-axis (looks good) if(maxXValue > 20.0) { int numberOfExtraXPoints = 3; double[] logXValues = new double[numberOfExtraXPoints]; for(int i = 0; i < logXValues.length; i++) { logXValues[i] = Math.ceil((i + 1.0) * ((double) maxXValue) / (double) (numberOfExtraXPoints + 1)); } logPlot.setExtraXAxisValues(logXValues); logPlot.showXValuesAsInts(true); } else if(maxXValue > 1.0) { int numberOfExtraXPoints = (int) (maxXValue - 1.0); double[] logXValues = new double[numberOfExtraXPoints]; for(int i = 0; i < logXValues.length; i++) { logXValues[i] = i + 1; } logPlot.setExtraXAxisValues(logXValues); logPlot.showXValuesAsInts(true); } else { double[] logXValues = {0.2, 0.4, 0.6, 0.8}; logPlot.setExtraXAxisValues(logXValues); logPlot.showXValuesAsInts(false); } } // set the min y value on the plot logPlot.setMinimumYValue(0); // set the max y value on the plot (to nearest 10^nth power) elapsedTimeStepsSinceLastAdjustedLogYAxis++; if(maxYValue >= oldLogMaxYValue || elapsedTimeStepsSinceLastAdjustedLogYAxis == TIME_TO_ADJUST_AXES) { logPlot.setMaximumYValue(maxYValue); oldLogMaxYValue = maxYValue; elapsedTimeStepsSinceLastAdjustedLogYAxis = 0; // draw some extra points on the y-axis (looks good) if(maxYValue > 20.0) { int numberOfExtraYPoints = 3; double[] logYValues = new double[numberOfExtraYPoints]; for(int i = 0; i < logYValues.length; i++) { logYValues[i] = Math.ceil((i + 1.0) * ((double) maxYValue) / (double) (numberOfExtraYPoints + 1)); } logPlot.setExtraYAxisValues(logYValues); logPlot.showYValuesAsInts(true); } if(maxYValue > 1.0) { int numberOfExtraYPoints = (int) (maxYValue - 1.0); double[] logYValues = new double[numberOfExtraYPoints]; for(int i = 0; i < logYValues.length; i++) { logYValues[i] = i + 1; } logPlot.setExtraYAxisValues(logYValues); logPlot.showYValuesAsInts(true); } else if(maxYValue == 1.0) { double[] logYValues = {0.2, 0.4, 0.6, 0.8}; logPlot.setExtraYAxisValues(logYValues); logPlot.showYValuesAsInts(false); } } // specify colors for the points Color stateColor = Color.BLACK; if(selectedState != ALL_NON_EMPTY_STATES_CHOICE && selectedState != ALL_STATES_CHOICE) { int stateWeArePlotting = selectedState; if(selectedState == EMPTY_STATE_CHOICE) { stateWeArePlotting = 0; } if(IntegerCellStateView.isCurrentRuleCompatible() && IntegerCellState.isCurrentRuleCompatible()) { CellStateView view = Cell.getView(); stateColor = view.getDisplayColor(new IntegerCellState( stateWeArePlotting), null, new Coordinate(0, 0)); } } if(logNumbers.size() > 0) { Color[] colorArray = new Color[logNumbers.size()]; for(int point = 0; point < colorArray.length; point++) { colorArray[point] = stateColor; } logPlot.setPointDisplayColors(colorArray); } else { logPlot.setPointDisplayColorsToDefault(); } // finally draw the plot if(logNumbers.size() > 0) { logPlot.drawPoints(logNumbers); } else { logPlot.clearPlot(); } } /** * Saves the specified data to the file. * * @param data * The data that will be saved. */ private void saveData(String[] data) { if(fileWriter != null) { try { fileWriter.writeData(data, delimiter); } catch(IOException e) { // Could not save the data, so close the file if(fileWriter != null) { fileWriter.close(); } // and uncheck the "save data" box if(saveDataCheckBox != null) { saveDataCheckBox.setSelected(false); } } } } /** * Called by the constructor. */ private void setUpAnalysis() { // update, because this could change numStates = CurrentProperties.getInstance().getNumStates(); // get the current view String ruleClassName = CurrentProperties.getInstance() .getRuleClassName(); rule = ReflectionTool.instantiateFullRuleFromClassName(ruleClassName); view = rule.getCompatibleCellStateView(); // use all occupied states selectedState = ALL_STATES_CHOICE; if(colorPatch == null) { colorPatch = new ColorPatch(); } else { colorPatch.setDefaultColorAndState(); } colorPatch.repaint(); // reset which state was last selected if(lastSelectedState >= numStates || lastSelectedState < 0) { lastSelectedState = ALL_STATES_CHOICE; } // this is the panel that will be displayed (getDisplayPanel() will // return the panel that this creates) if(displayPanel == null) { createDisplayPanel(); } // select the "all non-empty states" radio button. This must happen // after the display panel is created. allStatesButton.setSelected(true); // disable the selectState button selectStateButton.setEnabled(false); colorPatch.setEnabled(false); colorPatch.setDefaultColorAndState(); colorPatch.setToolTipText(null); colorPatch.repaint(); // only integer based rules should be allowed to select a particular // state for analysis if(IntegerCellState.isCompatibleRule(rule)) { // then let them select a particular state particularStateButton.setEnabled(true); } else { // don't let the user try to select a state. Won't work. particularStateButton.setEnabled(false); } } /** * Counts and displays the number of occupied cells using hte algorithm * outline in Appendix A of "Introduction to Percolation Theory, 2nd * Edition" by Stauffer and Aharony. * * @param lattice * The CA lattice. * @param rule * The CA rule. * @param generation * The current generation of the CA. There is no requirement that * this be the generation analyzed, but typically, this will be * the generation analyzed. */ protected void analyze(Lattice lattice, Rule rule, int generation) { // find out if we are dealing with integer cell states boolean isIntegerCellState = true; try { Cell c = (Cell) lattice.iterator().next(); // this will fail if not an integer cell state IntegerCellState intCellState = (IntegerCellState) c .getState(generation); // update, because this could change numStates = CurrentProperties.getInstance().getNumStates(); } catch(Exception e) { isIntegerCellState = false; } // true if we are looking for all cells rather than a // particular state boolean countingAllCells = false; if(selectedState == ALL_STATES_CHOICE) { countingAllCells = true; } // true if we are looking for all occupied cells rather than a // particular state boolean countingAllOccupiedCells = false; if(selectedState == ALL_NON_EMPTY_STATES_CHOICE) { countingAllOccupiedCells = true; } // true if the user has selected the empty cell states radio button // rather than a particular state boolean countingEmptyCells = false; if(selectedState == EMPTY_STATE_CHOICE) { countingEmptyCells = true; } // get an iterator over the lattice Iterator cellIterator = lattice.iterator(); // create a hashtable to hold the neighborhood size for each cell (key) Hashtable<Cell, Integer> hashOfNeighborSizeValues = new Hashtable<Cell, Integer>(); // the maximum sized neighborhood int maxNeighborhoodSize = 0; // go through the lattice and find each cell of the specified state Cell cell = null; while(cellIterator.hasNext()) { // get the cell cell = (Cell) cellIterator.next(); // the cell state CellState cellState = cell.getState(generation); // find out if the cell is in the state being counted in the // neighborhood sizes if(countingAllCells || (countingEmptyCells && cellState.isEmpty()) || (countingAllOccupiedCells && !cellState.isEmpty()) || ((!countingEmptyCells && !countingAllOccupiedCells && !countingAllCells) && isIntegerCellState && (cellState.toInt() == selectedState))) { // now get the number of neighbors Cell[] neighboringCells = lattice.getNeighbors(cell); int numNeighbors = neighboringCells.length; // keep track of the max neighborhood size if(numNeighbors > maxNeighborhoodSize) { maxNeighborhoodSize = numNeighbors; } // now save the cluster number hashOfNeighborSizeValues.put(cell, new Integer(numNeighbors)); } } // now find the number of neighborhoods of each size if(maxNeighborhoodSize > 0) { // init the array numberOfNeighborhoodsOfEachSize = new int[maxNeighborhoodSize + 1]; java.util.Arrays.fill(numberOfNeighborhoodsOfEachSize, 0); // fill the array with neighborhood sizes Collection<Integer> sizes = hashOfNeighborSizeValues.values(); for(Integer i : sizes) { int size = i.intValue(); numberOfNeighborhoodsOfEachSize[size]++; } } else { // it's a completely disconnected lattice -- highly unlikely numberOfNeighborhoodsOfEachSize = new int[1]; numberOfNeighborhoodsOfEachSize[0] = 0; } // convert cluster sizes to a Point2D array for plotting convertNeighborhoodSizesToPointArray(); // set the text for the labels generationDataLabel.setText("" + generation); // create an array of data to be saved data = new String[numberOfNeighborhoodsOfEachSize.length + 1]; data[0] = "" + generation; for(int i = 0; i < numberOfNeighborhoodsOfEachSize.length; i++) { data[i + 1] = "" + numberOfNeighborhoodsOfEachSize[i]; } // see if user wants to save the data if(fileWriter != null) { // save it saveData(data); } // plot the cluster data plotData(); plotLogLogData(); } /** * Performs any desired operations when the analysis is stopped (closed) by * the user. For example, you might write the results to a file at this * time. Or you might dispose of any windows that you opened. May do * nothing. */ protected void stopAnalysis() { // if the user has been saving data, then close that data file when the // analysis is stopped. if(fileWriter != null) { fileWriter.close(); } } /** * Reacts to the "save data" check box. */ public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if(command.equals(SAVE_DATA)) { if(saveDataCheckBox.isSelected()) { // they want to save data, so open a data file createFileWriter(); } else { // They don't want to save data anymore, so close the file. // The synchronized keyword prevents accidental access elsewhere // in the code while the file is being closed. Otherwise, other // code might try to write to the file while it is being closed. synchronized(this) { if(fileWriter != null) { fileWriter.close(); fileWriter = null; } } } } else if(command.equals(SELECT_STATE)) { chooseAnalysisState(); } else if(command.equals(PLOT_ZERO_VALUES)) { plotZeroValues = plotZeroValueCheckBox.isSelected(); // rerun so the changes are shown on the plot rerunAnalysis(); } } /** * A list of lattices with which this Analysis will work. In order for an * analysis to display and be used, it must be compatible with both the * lattice and the rule currently selected by a user (see * getCompatibleRules). * <p> * Well-designed Analyses should work with any lattice, but some may require * particular topological or geometrical information. Appropriate strings to * return in the array include SquareLattice.DISPLAY_NAME, * HexagonalLattice.DISPLAY_NAME, * StandardOneDimensionalLattice.DISPLAY_NAME, etc. Return null if * compatible with all lattices. * * @return A list of lattices compatible with this Analysis (returns the * display names for the lattices). Returns null if compatible with * all lattices. */ public String[] getCompatibleLattices() { String[] lattices = null; return lattices; } /** * A list of Rules with which this Analysis will work. In order for an * analysis to display and be used, it must be compatible with both the * lattice and the rule currently selected by a user (see * getCompatibleLattices). * <p> * Well-designed Analyses should work with any rule, but some may require * particular rule-specific information. Appropriate strings to return in * the array include the display names for any rule: for example, "Life", or * "Majority Rules". These names can be accessed from the getDisplayName() * method of each rule. For example, * * <pre> * new Life(super.getProperties()).getDisplayName() * </pre> * * Return null if compatible with all lattices. * * @return A list of lattices compatible with this Analysis (returns the * display names for the lattices). Returns null if compatible with * all lattices. */ public String[] getCompatibleRules() { String[] rules = null; return rules; } /** * A brief one or two-word string describing the analysis, appropriate for * display in a drop-down list. * * @return A string no longer than 15 characters. */ public String getDisplayName() { return ANALYSIS_NAME; } /** * Gets a JPanel that displays results of the population analysis. * * @return A display for the population analysis results. */ public JPanel getDisplayPanel() { return displayPanel; } /** * A brief description (written in HTML) that describes this rule. The * description will be displayed as a tooltip. Using html permits line * breaks, font colors, etcetera, as described in HTML resources. Regular * line breaks will not work. * * @return An HTML string describing this rule. */ public String getToolTipDescription() { return TOOLTIP; } /** * Overrides the parent's method to handle the notification of a change in * color, and is used to change the color of the colorPatch. */ public void propertyChange(PropertyChangeEvent event) { if(event.getPropertyName().equals(CurrentProperties.COLORS_CHANGED)) { // only do this if the color patch is active if(colorPatch.isEnabled()) { // get the current color and set the colorPatch to that color currentColor = view.getDisplayColor(new IntegerCellState( selectedState), null, new Coordinate(0, 0)); if(colorPatch == null) { colorPatch = new ColorPatch(currentColor, selectedState); } else { colorPatch.setColorAndState(currentColor, selectedState); } colorPatch.setEnabled(true); colorPatch.repaint(); } // replot in the new colors plotData(); plotLogLogData(); } } /** * Performs any necessary operations to reset the analysis. this method is * called if the user resets the cellular automata, or selects a new * simulation. */ public void reset() { // if the user has been saving data, then close that data file synchronized(this) { if(fileWriter != null) { fileWriter.close(); fileWriter = null; } } // and uncheck the "save data" box if(saveDataCheckBox != null) { saveDataCheckBox.setSelected(false); } // reset the analysis parameters setUpAnalysis(); // force it to redraw displayPanel.invalidate(); } /** * If returns true, then the analysis is forced to size its width to fit * within the visible width of the tabbed pane where it is displayed. If * false, then a horizontal scroll bar is added so that the analysis can be * wider than the displayed space. * <p> * Recommend returning true. If your graphics look lousy within that space, * then return false. (In other words, try both and see which is better.) * * @return true if the graphics should be forced to size its width to fit * the display area. */ public boolean restrictDisplayWidthToVisibleSpace() { return true; } /** * A patch of color displayed on the JPanel. */ private class ColorPatch extends JPanel { // the color of the patch private Color colorOfPatch = null; private Color defaultColor = new Color(204, 204, 204); // the size of the patch private Dimension patchSize = new Dimension(25, 25); // the state value being displayed. Used when drawing the shape on the // patch private int stateValue = 0; /** * Create the patch with a default color. Useful when the CA isn't an * integer state CA. */ public ColorPatch() { this.setPreferredSize(patchSize); this.setBackground(defaultColor); colorOfPatch = defaultColor; this.setBorder(BorderFactory.createRaisedBevelBorder()); this.setToolTipText(null); // should be the constant ALL_NON_EMPTY_STATES_CHOICE in this case. stateValue = selectedState; } /** * Create the patch with the given color and state. */ public ColorPatch(Color color, int stateValue) { this.setPreferredSize(patchSize); this.setBorder(BorderFactory.createRaisedBevelBorder()); setColorAndState(color, stateValue); } /** * Set the color and state of the patch. */ public void setColorAndState(Color color, int stateValue) { this.stateValue = stateValue; // set a shape and background color Shape shape = view.getDisplayShape( new IntegerCellState(stateValue), this.getWidth(), this .getHeight(), null); if(shape == null) { this.setBackground(color); } else { // the color behind the shape this.setBackground(ColorScheme.DEFAULT_EMPTY_COLOR); } colorOfPatch = color; // set a tool tip that tells them the state of the cell this color // represents try { // first check if it is this special case -- not the best // connectivity, but useful for backwards compatibility FiniteObjectRuleTemplate theRule = (FiniteObjectRuleTemplate) rule; this.setToolTipText("cell state " + theRule.intToObjectState(stateValue).toString()); } catch(Exception e) { this.setToolTipText("cell state " + stateValue); } } /** * Set a default color and state for the patch; */ public void setDefaultColorAndState() { stateValue = ALL_STATES_CHOICE; colorOfPatch = defaultColor; this.setBackground(defaultColor); } // draw the correct shape on the patch public void paintComponent(Graphics g) { // Call the JPanel's paintComponent. This ensures // that the background is properly rendered. super.paintComponent(g); if(IntegerCellState.isCompatibleRule(rule)) { // exclude the border (otherwise the stroke of the border is // changed) Graphics2D g2 = (Graphics2D) g.create(this.getInsets().left, this.getInsets().right, this.getWidth() - this.getInsets().left - this.getInsets().right, this.getHeight() - this.getInsets().top - this.getInsets().bottom); try { Stroke stroke = view.getStroke(new IntegerCellState( stateValue), this.getWidth(), this.getHeight(), new Coordinate(0, 0)); if(stroke != null) { g2.setStroke(stroke); } // use insets so fits in the space which is smaller due to // the raisedBevelBorder Shape shape = view.getDisplayShape(new IntegerCellState( stateValue), this.getWidth() - 2 * this.getInsets().left - 2 * this.getInsets().right, this.getHeight() - 2 * this.getInsets().top - 2 * this.getInsets().bottom, null); if(shape != null && colorOfPatch != null) { // translate the shape to the correct position AffineTransform scalingTransform = AffineTransform .getTranslateInstance(this.getWidth() / 2.0, this.getHeight() / 2.0); shape = scalingTransform.createTransformedShape(shape); // now draw it g2.setColor(colorOfPatch); g2.draw(shape); g2.fill(shape); } } catch(Exception e) { // fails if not an IntegerCellState -- do nothing } } } } /** * Listens for the OK button on the integer color chooser. */ private class OkColorListener implements ActionListener { private String actionCommand = null; public OkColorListener(String actionCommand) { this.actionCommand = actionCommand; } public void actionPerformed(ActionEvent e) { selectedState = integerColorChooser.getState(); currentColor = integerColorChooser.getColor(); colorPatch.setColorAndState(currentColor, selectedState); colorPatch.repaint(); // rerun so the changes are shown on the plot rerunAnalysis(); } } /** * Decides what to do when the user selects a the empty, non-empty, or * particular states. * * @author David Bahr */ private class StateChoiceListener implements ItemListener { public void itemStateChanged(ItemEvent event) { if(nonEmptyStatesButton.isSelected()) { // save the last selected state (if it was a particular integer // state) if(selectedState != EMPTY_STATE_CHOICE && selectedState != ALL_NON_EMPTY_STATES_CHOICE && selectedState != ALL_STATES_CHOICE) { lastSelectedState = selectedState; } // use all states selectedState = ALL_NON_EMPTY_STATES_CHOICE; if(colorPatch == null) { colorPatch = new ColorPatch(); } else { colorPatch.setDefaultColorAndState(); } colorPatch.setEnabled(false); colorPatch.setToolTipText(null); colorPatch.repaint(); if(selectStateButton != null) { selectStateButton.setEnabled(false); } } else if(emptyStateButton.isSelected()) { // save the last selected state (if it was a particular integer // state) if(selectedState != EMPTY_STATE_CHOICE && selectedState != ALL_NON_EMPTY_STATES_CHOICE && selectedState != ALL_STATES_CHOICE) { lastSelectedState = selectedState; } // use only empty states selectedState = EMPTY_STATE_CHOICE; if(colorPatch == null) { colorPatch = new ColorPatch(); } else { colorPatch.setDefaultColorAndState(); } colorPatch.setEnabled(false); colorPatch.setToolTipText(null); colorPatch.repaint(); if(selectStateButton != null) { selectStateButton.setEnabled(false); } } else if(allStatesButton.isSelected()) { // save the last selected state (if it was a particular integer // state) if(selectedState != EMPTY_STATE_CHOICE && selectedState != ALL_NON_EMPTY_STATES_CHOICE && selectedState != ALL_STATES_CHOICE) { lastSelectedState = selectedState; } // use only empty states selectedState = ALL_STATES_CHOICE; if(colorPatch == null) { colorPatch = new ColorPatch(); } else { colorPatch.setDefaultColorAndState(); } colorPatch.setEnabled(false); colorPatch.setToolTipText(null); colorPatch.repaint(); if(selectStateButton != null) { selectStateButton.setEnabled(false); } } else if(particularStateButton.isSelected()) { // use the last selected state if(lastSelectedState != EMPTY_STATE_CHOICE && lastSelectedState != ALL_NON_EMPTY_STATES_CHOICE && lastSelectedState != ALL_STATES_CHOICE && lastSelectedState < numStates) { selectedState = lastSelectedState; } else { selectedState = numStates - 1; } // get the current color and set the colorPatch to that color currentColor = view.getDisplayColor(new IntegerCellState( selectedState), null, new Coordinate(0, 0)); if(colorPatch == null) { colorPatch = new ColorPatch(currentColor, selectedState); } else { colorPatch.setColorAndState(currentColor, selectedState); } colorPatch.setEnabled(true); colorPatch.repaint(); if(selectStateButton != null) { selectStateButton.setEnabled(true); } } // adjust these so that the new plot has reasonable axes. elapsedTimeStepsSinceLastAdjustedXAxis = TIME_TO_ADJUST_AXES - 1; elapsedTimeStepsSinceLastAdjustedYAxis = TIME_TO_ADJUST_AXES - 1; // rerun so the changes are shown on the plot rerunAnalysis(); } } }
package com.syscxp.biz.entity.activiti; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import java.sql.Timestamp; /** * @Author: sunxuelong. * @Cretion Date: 2018-08-28. * @Description: . */ @Entity public class VacationApplication { @Id @GeneratedValue private Long id; private String applicantId; private String vacationMotivation; private Timestamp startDate; private Long numberOfDays; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getApplicantId() { return applicantId; } public void setApplicantId(String applicantId) { this.applicantId = applicantId; } public String getVacationMotivation() { return vacationMotivation; } public void setVacationMotivation(String vacationMotivation) { this.vacationMotivation = vacationMotivation; } public Timestamp getStartDate() { return startDate; } public void setStartDate(Timestamp startDate) { this.startDate = startDate; } public Long getNumberOfDays() { return numberOfDays; } public void setNumberOfDays(Long numberOfDays) { this.numberOfDays = numberOfDays; } }
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 math.floatV; import java.util.Random; import math.RandomXS128; /** Utility and fast math functions. * <p> * Thanks to Riven on JavaGaming.org for the basis of sin/cos/floor/ceil. * @author Nathan Sweet */ public final class MathUtils { static public final double nanoToSec = 1 / 1000000000f; // --- static public final float FLOAT_ROUNDING_ERROR = 0.000001f; // 32 bits, 23 of which may hold the significand for a precision of 6 digits static public final double DOUBLE_ROUNDING_ERROR = 0.000000000000001d; // 64, 52 of which represent the significand for a precision of 15 digits. static public final float PI = (float)Math.PI; static public final float PI2 = PI * 2f; static public final float HALF_PI = (float)(Math.PI /2d); static public final float E = (float) Math.E; static private final int SIN_BITS = 9; // Adjust for accuracy (eats memory). static private final int SIN_MASK = ~(-1 << SIN_BITS); static private final int SIN_COUNT = SIN_MASK + 1; static private final float radFull = PI * 2; static private final float degFull = 360; static private final float radToIndex = SIN_COUNT / radFull; static private final float degToIndex = SIN_COUNT / degFull; /** multiply by this to convert from radians to degrees */ static public final float radiansToDegrees = 180f / PI; static public final float radDeg = radiansToDegrees; /** multiply by this to convert from degrees to radians */ static public final float degreesToRadians = PI / 180f; static public final float degRad = degreesToRadians; static private class Sin { static final float[] table = new float[SIN_COUNT]; static { for (int i = 0; i < SIN_COUNT; i++) table[i] = (float)Math.sin((float)(i) / SIN_COUNT * radFull); } } /** Returns the sine in radians from a lookup table. */ static public float sin (float radians) { return (float)Math.sin((double)radians); /*float rawIndex = (radians * radToIndex); int index = (int) rawIndex; float remainder = rawIndex - index; float result1 = Sin.table[index & SIN_MASK]; float result2 = Sin.table[index+1 & SIN_MASK]; float lerped = G.lerp(result1, result2, remainder); //System.out.println("delta: " + ((float)Math.sin(radians) - lerped)); return lerped;*/ } /* * intended for higher accuracy per megabyte (at the cost of some speed) * @param radians * @return */ /*static public double iSin(double tx) { boolean negate = false; double x = tx; if(tx<0) { negate = true; x = -tx; } if( x >= PI2) { x = x%PI2; } double result = 0d; //System.out.println(x); if(x< HALF_PI) { result = piSin(x); } else if(x < PI) { result = piSin(HALF_PI - (x-HALF_PI)); } else if(x < THREEHALF_PI) { x = x%PI; result =-piSin(x); } else { x = x%PI; result = -piSin(HALF_PI - (x-HALF_PI)); } if(negate) { return -result; } else { return result; } } }*/ /** Returns the cosine in radians from a lookup table. */ static public float cos (float radians) { //System.out.println("delta : " + ((float)Math.cos(radians) -Math.sin(radians + HALF_PI))); return (float)Math.cos(radians);//sin(radians - 11f); } /** Returns the cosine in radians from a lookup table. */ static public float cosDeg (float degrees) { return Sin.table[(int)((degrees + 90) * degToIndex) & SIN_MASK]; } // --- /** Returns atan2 in radians, faster but less accurate than Math.atan2. Average error of 0.00231 radians (0.1323 degrees), * largest error of 0.00488 radians (0.2796 degrees). */ static public float atan2 (float y, float x) { if (x == 0f) { if (y > 0f) return HALF_PI; if (y == 0f) return 0f; return -HALF_PI; } final float atan, z = y / x; if (Math.abs(z) < 1f) { atan = z / (1f + 0.28f * z * z); if (x < 0f) return atan + (y < 0f ? -PI : PI); return atan; } atan = PI / 2 - z / (z * z + 0.28f); return y < 0f ? atan - PI : atan; } // --- static public Random random = new RandomXS128(); public static float lerp(float a, float b, float t) { return (1-t)*a + t*b; } /** Returns a random number between 0 (inclusive) and the specified value (inclusive). */ static public int random (int range) { return random.nextInt(range + 1); } /** Returns a random number between start (inclusive) and end (inclusive). */ static public int random (int start, int end) { return start + random.nextInt(end - start + 1); } /** Returns a random number between 0 (inclusive) and the specified value (inclusive). */ static public long random (long range) { return (long)(random.nextDouble() * range); } /** Returns a random number between start (inclusive) and end (inclusive). */ static public long random (long start, long end) { return start + (long)(random.nextDouble() * (end - start)); } /** Returns a random boolean value. */ static public boolean randomBoolean () { return random.nextBoolean(); } /** Returns -1 or 1, randomly. */ static public int randomSign () { return 1 | (random.nextInt() >> 31); } // --- /** Returns the next power of two. Returns the specified value if the value is already a power of two. */ static public int nextPowerOfTwo (int value) { if (value == 0) return 1; value--; value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; return value + 1; } static public boolean isPowerOfTwo (int value) { return value != 0 && (value & value - 1) == 0; } // --- static public short clamp (short value, short min, short max) { if (value < min) return min; if (value > max) return max; return value; } static public int clamp (int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static public long clamp (long value, long min, long max) { if (value < min) return min; if (value > max) return max; return value; } static public float clamp (float value, float min, float max) { if (value < min) return min; if (value > max) return max; return value; } static public double clamp (double value, double min, double max) { if (value < min) return min; if (value > max) return max; return value; } // --- /** Linearly interpolates between fromValue to toValue on progress position. */ static public double lerp (double fromValue, double toValue, double progress) { return fromValue + (toValue - fromValue) * progress; } /** Linearly interpolates between two angles in radians. Takes into account that angles wrap at two pi and always takes the * direction with the smallest delta angle. * * @param fromRadians start angle in radians * @param toRadians target angle in radians * @param progress interpolation value in the range [0, 1] * @return the interpolated angle in the range [0, PI2[ */ public static double lerpAngle (double fromRadians, double toRadians, double progress) { double delta = ((toRadians - fromRadians + PI2 + PI) % PI2) - PI; return (fromRadians + delta * progress + PI2) % PI2; } /** Linearly interpolates between two angles in degrees. Takes into account that angles wrap at 360 degrees and always takes * the direction with the smallest delta angle. * * @param fromDegrees start angle in degrees * @param toDegrees target angle in degrees * @param progress interpolation value in the range [0, 1] * @return the interpolated angle in the range [0, 360[ */ public static double lerpAngleDeg (double fromDegrees, double toDegrees, double progress) { double delta = ((toDegrees - fromDegrees + 360 + 180) % 360) - 180; return (fromDegrees + delta * progress + 360) % 360; } // --- static private final int BIG_ENOUGH_INT = 16 * 1024; static private final double BIG_ENOUGH_FLOOR = BIG_ENOUGH_INT; static private final double CEIL = 0.9999999; static private final double BIG_ENOUGH_ROUND = BIG_ENOUGH_INT + 0.5f; /** Returns the largest integer less than or equal to the specified double. This method will only properly floor doubles from * -(2^14) to (double.MAX_VALUE - 2^14). */ static public int floor (double value) { return (int)(value + BIG_ENOUGH_FLOOR) - BIG_ENOUGH_INT; } /** Returns the largest integer less than or equal to the specified double. This method will only properly floor doubles that are * positive. Note this method simply casts the double to int. */ static public int floorPositive (double value) { return (int)value; } /** Returns the smallest integer greater than or equal to the specified double. This method will only properly ceil doubles from * -(2^14) to (double.MAX_VALUE - 2^14). */ static public int ceil (double value) { return BIG_ENOUGH_INT - (int)(BIG_ENOUGH_FLOOR - value); } /** Returns the smallest integer greater than or equal to the specified double. This method will only properly ceil doubles that * are positive. */ static public int ceilPositive (double value) { return (int)(value + CEIL); } /** Returns the closest integer to the specified double. This method will only properly round doubles from -(2^14) to * (double.MAX_VALUE - 2^14). */ static public int round (double value) { return (int)(value + BIG_ENOUGH_ROUND) - BIG_ENOUGH_INT; } /** Returns the closest integer to the specified double. This method will only properly round doubles that are positive. */ static public int roundPositive (double value) { return (int)(value + 0.5f); } /** Returns true if the value is zero (using the default tolerance as upper bound) */ static public boolean isZero (double value) { return Math.abs(value) <= DOUBLE_ROUNDING_ERROR; } /** Returns true if the value is zero. * @param tolerance represent an upper bound below which the value is considered zero. */ static public boolean isZero (double value, double tolerance) { return Math.abs(value) <= tolerance; } /** Returns true if a is nearly equal to b. The function uses the default doubleing error tolerance. * @param a the first value. * @param b the second value. */ static public boolean isEqual (double a, double b) { return Math.abs(a - b) <= DOUBLE_ROUNDING_ERROR; } /** Returns true if a is nearly equal to b. * @param a the first value. * @param b the second value. * @param tolerance represent an upper bound below which the two values are considered equal. */ static public boolean isEqual (double a, double b, double tolerance) { return Math.abs(a - b) <= tolerance; } /** @return the logarithm of value with base a */ static public double log (double a, double value) { return (double)(Math.log(value) / Math.log(a)); } /** @return the logarithm of value with base 2 */ static public double log2 (double value) { return log(2, value); } public static float pow(float val, float power) { return (float)Math.pow(val, power); } public static float abs(float f) { return (float)Math.abs(f); } public static float sqrt(float f) { return (float)Math.sqrt(f); } public static float asin(float sin) { return (float)Math.asin(sin); } public static float acos(float cos) { return (float)Math.acos(cos); } public static float toDegrees(float radians) { return radians*radiansToDegrees; } public static float toRadians(float radians) { return radians*degreesToRadians; } public static float max(float a, float b) { return a > b ? a : b; } public static float min(float a, float b) { return a < b ? a : b; } public static float invSqrt(float x) { float xhalf = 0.5f * x; int i = Float.floatToIntBits(x); i = 0x5f3759df - (i >> 1); x = Float.intBitsToFloat(i); x *= (1.5f - xhalf * x * x); return x; } }
package pageTests; import org.testng.Assert; import org.testng.annotations.Test; import pageObjects.FlightHomePage; import pageObjects.FlightResultPage; import seleniumTests.BaseTestUsingTestNG; public class FlightResultPageTest extends BaseTestUsingTestNG{ FlightHomePage flightHomePage; FlightResultPage flightResultPage; String strDestination = "Ho Chi Minh City, Vietnam - Tan Son Nhat International [SGN]"; String strDepartDate = "15/11/2018"; String strReturnDate = "16/12/2018"; String preferAirline = "China Eastern Airlines"; //@Test(description="User can see a progress bar when ticket being searched") public void Verify_There_Is_A_Progess_Bar_When_Ticket_Is_Being_Searched() { flightHomePage = new FlightHomePage(driver); flightHomePage.UserEnterFlightDestination(strDestination); flightHomePage.UserPickDepartDate(strDepartDate); flightHomePage.UserPickReturnDate(strReturnDate); flightResultPage = flightHomePage.UserClickSearchFlightAndGoToFlightResultPage(); Assert.assertTrue(flightResultPage.VerifySearchFareModalDialogExist()); Assert.assertTrue(flightResultPage.VerifySearchProgessBarExist()); } @Test(description="User can see all airline brands after searching for a flight") public void Verify_There_Is_A_List_Of_Airline_Brands_That_User_Can_Select() { flightHomePage = new FlightHomePage(driver); flightHomePage.UserEnterFlightDestination(strDestination); flightHomePage.UserPickDepartDate(strDepartDate); flightHomePage.UserPickReturnDate(strReturnDate); flightResultPage = flightHomePage.UserClickSearchFlightAndGoToFlightResultPage(); flightResultPage.WaitForFlightResultPageLoad(); flightResultPage.ClickOnShowMoreLinkToSeeMoreAirlineOptions(); Assert.assertTrue(flightResultPage.VerifyListOfAirlineBrandsExist()); flightResultPage.GetAllAirlineBrandsName(); } @Test(description="User can see cheapest price for a certain flight brand") public void Verify_User_Can_Get_Cheapest_Price_After_Selecting_An_Airline_Brand() { flightHomePage = new FlightHomePage(driver); flightHomePage.UserEnterFlightDestination(strDestination); flightHomePage.UserPickDepartDate(strDepartDate); flightHomePage.UserPickReturnDate(strReturnDate); flightResultPage = flightHomePage.UserClickSearchFlightAndGoToFlightResultPage(); flightResultPage.WaitForFlightResultPageLoad(); flightResultPage.ClickOnShowMoreLinkToSeeMoreAirlineOptions(); flightResultPage.SelectPreferAirlineBrand(preferAirline); flightResultPage.WaitForFlightResultWhenSelectingPreferAirline(); flightResultPage.GetAllPriceInFlightResultDetail(); } }
package main.java.commands; import main.java.GeneralCommands; import main.java.ICommand; import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.handle.obj.IVoiceChannel; import sx.blah.discord.util.DiscordException; import sx.blah.discord.util.HTTP429Exception; import sx.blah.discord.util.MessageBuilder; import sx.blah.discord.util.MissingPermissionsException; import sx.blah.discord.util.audio.AudioPlayer; import javax.sound.sampled.UnsupportedAudioFileException; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Random; /** * Created by Allin on 5/11/2016. */ public final class Horn implements ICommand { /** * Gets the name of the command * @return the name of the command */ @Override public String getName() { return "horn"; } /** * Gets the role of the command * @return the role of the command */ @Override public String getRole() { return "plays a quick audio file"; } /** * Plays a horn audio clip to the voice chat * @param message the message that triggered the command * @param args the space separated values that followed the command */ @Override public void handle(IMessage message, String[] args) { File[] files = new File("C:\\Users\\Allin\\IdeaProjects\\DiscordBotGit\\src\\main\\java\\commands\\horns").listFiles(); // Get a list of available horns Random rd = new Random(); IVoiceChannel channel = message.getAuthor().getConnectedVoiceChannels().get(0); assert files != null; File file = files[rd.nextInt(files.length)]; // Set the file to be played to a random file File temp = file; if (args.length > 0) { // If there are arguments if (args[0].equals("horns")){ // If thr first argument is horns StringBuilder sb = new StringBuilder(); sb.append("```"); // Append the opening tag for a code block for (File file1: files){ // For each file in the list of files sb.append(file1.getName().substring(0, file1.getName().length()-4)); // Append the name of the file (strips the .mp3 at the end) sb.append("\n"); // Append a line break } sb.append("```");// Append the closing tag for a code block try { new MessageBuilder(GeneralCommands.client).withChannel(message.getChannel()).withContent(sb.toString()).build(); } catch (HTTP429Exception | DiscordException | MissingPermissionsException e) { e.printStackTrace(); } file = null; } else { // If the first argument is something else for (File file1 : files) { // For each file in the list of files // If the name of the file is the same as the arguments if (file1.getName().toLowerCase().contains(Arrays.toString(args).replaceAll("\\]", "").replaceAll("\\[", "").replaceAll(",", ""))) file = file1; // Set the file to be played to this file } } } if (!channel.isConnected()) // If we are not connected to the voice channel channel.join(); // Connect try { if (file != null) { // If the file is not null System.out.println(file.getName()); // Print the name of the file AudioPlayer.getAudioPlayerForGuild(message.getGuild()).queue(file); // Queue the file in the audio player } } catch (IOException | UnsupportedAudioFileException e) { e.printStackTrace(); } } /** * Gets the name and role of the command * @return the name and role of the command */ @Override public String toString() { return this.getName() + ": " + this.getRole(); } }
package sb.hackathon.model; import lombok.Data; @Data public class Estimate { private User user; private Integer estimation; }
package cn.itcast.core.service.goods; import cn.itcast.core.entity.PageResult; import cn.itcast.core.pojo.good.Goods; import cn.itcast.core.vo.GoodsVo; import java.util.List; public interface GoodsService { /** * 保存商品 */ public void add(GoodsVo goodsVo); /** * 商家系统下的商品列表查询 */ public PageResult search(Integer page, Integer rows, Goods goods); /** * 商品回显 */ public GoodsVo findOne(Long id); /** * 更新商品 */ public void update(GoodsVo goodsVo); /** * 运营商系统下的商品列表查询 */ public PageResult searchForManager(Integer page, Integer rows, Goods goods); /** * 审核商品 */ public void updateStatus(Long[] ids,String auditStatus); /** * 删除商品(逻辑删除) */ public void delete(Long[] ids); void updateMarketable(Long[] ids, String markeStatus); /** * 查询全部商品 */ public List<Goods> findAll(); }
package com.wz.week_2.linkedlist; import com.algorithm.list.ListNode; import com.util.ListNodeUtil; import org.junit.Test; public class MergeTwoLists { /** * 输入:1->2->4, 1->3->4 * 输出:1->1->2->3->4->4 * * [5] * [1,2,4] * 遍历到两个链表的尾部 * 需要注意该种情况,有可能某一个步骤,链表并部需要往后遍历 * @param l1 * @param l2 * @return */ public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode result = new ListNode(-1); ListNode temp = result; while(l1!=null || l2!=null){ if(l1!=null && l2!=null){ if(l1.val>l2.val){ temp.next = new ListNode(l2.val); temp = temp.next; l2 = l2.next; }else { temp.next = new ListNode(l1.val); temp = temp.next; l1 = l1.next; } }else { int val = 0; if(l1 == null){ val = l2.val; l2 = l2.next; }else if(l2 == null){ val = l1.val; l1 = l1.next; } temp.next = new ListNode(val); temp = temp.next; } } return result.next; } @Test public void test(){ ListNode node1 = ListNodeUtil.getListNode(new int[]{5}); ListNode node2 = ListNodeUtil.getListNode(new int[]{1,2,4}); mergeTwoLists(node1,node2); } }
package msip.go.kr.alimi.service.impl; import java.util.List; import javax.annotation.Resource; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import msip.go.kr.alimi.entity.Alimi; import msip.go.kr.alimi.service.AlimiService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl; /** * Alimi entity 관련 업무 처리를 위한 Sevice Interface 구현 클래스 정의 * * @author 정승철 * @since 2015.07.10 * @see <pre> * == 개정이력(Modification Information) == * * 수정일 수정자 수정내용 * --------------------------------------------------------------------------------- * 2015.07.10 정승철 최초생성 * * </pre> */ @Service("alimiService") @Transactional(rollbackFor = { Exception.class }, propagation = Propagation.REQUIRED) public class AlimiServiceImpl extends EgovAbstractServiceImpl implements AlimiService { /** * @PersistenceContext 어노테이션을 이용하여 컨테이너로부터 EntityManger DI * @param EntityManager em */ @PersistenceContext private EntityManager em; /** alimiDAO */ @Resource(name="alimiDAO") private AlimiDAO alimiDAO; /** * 선택된 id에 따라 Alimi entity 정보를 데이터베이스에서 삭제하도록 요청 * @param EmailSend entity * @throws Exception */ public void remove(Alimi entity) throws Exception { alimiDAO.remove(entity); } /** * 새로운 Alimi entity 정보를 입력받아 데이터베이스에 저장하도록 요청 * @param EmailSend entity * @return Long * @throws Exception */ public void persist(Alimi entity) throws Exception { /* Alimi entity정보 등록 */ alimiDAO.persist(entity); } /** * 전체 Alimi entity 목록을 데이터베이스에서 읽어와 화면에 출력하도록 요청 * @return List<Alimi> 산하기관 Alimi entity 목록 * @throws Exception */ public List<Alimi> findAll(String recvId) throws Exception { return alimiDAO.findAll(recvId); } /** * 전체 Alimi entity 목록을 데이터베이스에서 읽어와 화면에 출력하도록 요청 * @return List<Alimi> 산하기관 Alimi entity 목록 * @throws Exception */ public List<Alimi> findAll(String recvId, int page) throws Exception { return alimiDAO.findAll(recvId, page); } /** * 수정된 Alimi entity 정보를 데이터베이스에 반영하도록 요청 * @param EmailSend entity * @throws Exception */ public void merge(Alimi entity) throws Exception { alimiDAO.merge(entity); } /** * 수정된 Alimi entity 정보를 데이터베이스에 반영하도록 요청 * @param EmailSend entity * @throws Exception */ public int initAlimi(String uniqId) throws Exception { return alimiDAO.initAlimi(uniqId); } public int alimiCnt(String uniqId) throws Exception { return alimiDAO.alimiCnt(uniqId); } /** * 선택된 id에 따라 데이터베이스에서 Alimi entity 정보를 읽어와 화면에 출력하도록 요청 * @param Long id * @return Alimi entity * @throws Exception */ public Alimi findById(Long id) throws Exception { Alimi result = alimiDAO.findById(id); if(result==null) throw processException("info.nodata.msg"); return result; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DAL; import DTO.DTO_TheLoai; import GUI.Assignment; import java.sql.ResultSet; /** * * @author Asus */ public class DAL_TheLoai { public static int ThemTheLoai(DTO_TheLoai item) { String CauTruyVan = "insert into THELOAI (TENTL,MOTA) values (N'"+item.getTenTL()+"',N'"+item.getMoTa()+"')"; int result = Assignment.connection.ExcuteNonQuery(CauTruyVan); return result; } public static int XoaTheLoai(DTO_TheLoai item) { String CauTruyVan ="delete THELOAI where MaTL = "+item.getMaTL()+""; int result = Assignment.connection.ExcuteNonQuery(CauTruyVan); return result; } public static int SuaTheLoai(DTO_TheLoai item) { String CauTruyVan ="update THELOAI set TENTL=N'"+item.getTenTL()+"',MOTA=N'"+item.getMoTa()+"' where MATL="+item.getMaTL()+""; int result = Assignment.connection.ExcuteNonQuery(CauTruyVan); return result; } public static ResultSet GetALL_TheLoai() { String query = "select * from THELOAI"; return Assignment.connection.ExcuteQuerySelect(query); } }
package online.lahloba.www.lahloba.ui.seller; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.widget.Toast; import com.esafirm.imagepicker.features.ImagePicker; import com.esafirm.imagepicker.model.Image; import java.util.concurrent.Executor; import online.lahloba.www.lahloba.R; import online.lahloba.www.lahloba.utils.Injector; import static online.lahloba.www.lahloba.utils.Constants.EXTRA_SUBTITLE_ID; public class SellerAddProductActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.seller_add_product_activity); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .replace(R.id.container, SellerAddProductFragment.newInstance()) .commitNow(); Intent intent = getIntent(); Injector.getExecuter().diskIO().execute(()->{ }); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (intent.hasExtra(EXTRA_SUBTITLE_ID)){ ((SellerAddProductFragment)getSupportFragmentManager().getFragments().get(0)) .setCategory(intent.getStringExtra(EXTRA_SUBTITLE_ID)); } } }, 1000); } } @Override public void onActivityResult(int requestCode, final int resultCode, Intent data) { if (ImagePicker.shouldHandle(requestCode, resultCode, data)) { // Get a list of picked images // or get a single image only Image image = ImagePicker.getFirstImageOrNull(data); ((SellerAddProductFragment)getSupportFragmentManager().getFragments().get(0)) .pickImage(image); } super.onActivityResult(requestCode, resultCode, data); } }
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.tenant.resource.manager.core; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.event.publisher.core.EventPublisherService; import org.wso2.carbon.event.publisher.core.config.EventPublisherConfiguration; import org.wso2.carbon.event.publisher.core.config.EventPublisherConfigurationFile; import org.wso2.carbon.event.publisher.core.exception.EventPublisherConfigurationException; import org.wso2.carbon.event.publisher.core.exception.EventPublisherStreamValidationException; import org.wso2.carbon.identity.configuration.mgt.core.exception.ConfigurationManagementException; import org.wso2.carbon.identity.configuration.mgt.core.model.ResourceFile; import org.wso2.carbon.identity.tenant.resource.manager.exception.TenantResourceManagementException; import org.wso2.carbon.identity.tenant.resource.manager.internal.TenantResourceManagerDataHolder; import org.wso2.carbon.identity.tenant.resource.manager.util.ResourceUtils; import java.io.InputStream; import java.util.List; import static org.wso2.carbon.identity.tenant.resource.manager.constants.TenantResourceConstants.ErrorMessages.ERROR_CODE_ERROR_WHEN_DEPLOYING_EVENT_PUBLISHER_CONFIGURATION; import static org.wso2.carbon.identity.tenant.resource.manager.constants.TenantResourceConstants.ErrorMessages.ERROR_CODE_ERROR_WHEN_FETCHING_EVENT_PUBLISHER_FILE; import static org.wso2.carbon.identity.tenant.resource.manager.constants.TenantResourceConstants.PUBLISHER; import static org.wso2.carbon.identity.tenant.resource.manager.util.ResourceUtils.handleServerException; /** * Tenant Resource manager service implementation. */ public class ResourceManagerImpl implements ResourceManager { private static Log log = LogFactory.getLog(ResourceManagerImpl.class); @Override public void addEventPublisherConfiguration(ResourceFile resourceFile) throws TenantResourceManagementException { try { deployEventPublisherConfiguration(TenantResourceManagerDataHolder.getInstance().getConfigurationManager() .getFileById(PUBLISHER, resourceFile.getName(), resourceFile.getId())); if (log.isDebugEnabled()) { log.debug("Event Publisher: " + resourceFile.getName() + " deployed from the configuration " + "store for the tenant domain: " + PrivilegedCarbonContext.getThreadLocalCarbonContext() .getTenantDomain()); } } catch (EventPublisherConfigurationException e) { throw handleServerException(ERROR_CODE_ERROR_WHEN_DEPLOYING_EVENT_PUBLISHER_CONFIGURATION, e, resourceFile.getName()); } catch (ConfigurationManagementException e) { throw handleServerException(ERROR_CODE_ERROR_WHEN_FETCHING_EVENT_PUBLISHER_FILE, e, resourceFile.getName() ,PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()); } } @Override public void removeEventPublisherConfiguration(String resourceTypeName, String resourceName) throws TenantResourceManagementException { try { if (TenantResourceManagerDataHolder.getInstance().getCarbonEventPublisherService() .getActiveEventPublisherConfiguration(resourceName) != null) { destroyEventPublisherConfiguration(resourceName); // Since the tenant event publisher was removed, we should load super tenant configs. loadSuperTenantEventPublisherConfigs(); } } catch (EventPublisherConfigurationException e) { throw handleServerException(ERROR_CODE_ERROR_WHEN_DEPLOYING_EVENT_PUBLISHER_CONFIGURATION, e, resourceName); } } private void loadSuperTenantEventPublisherConfigs() { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); List<EventPublisherConfiguration> activeEventPublisherConfigurations; try { ResourceUtils.startSuperTenantFlow(); activeEventPublisherConfigurations = ResourceUtils.getSuperTenantEventPublisherConfigurations(); } finally { PrivilegedCarbonContext.endTenantFlow(); } try { ResourceUtils.startTenantFlow(tenantId); if (activeEventPublisherConfigurations != null) { ResourceUtils.loadTenantPublisherConfigurationFromSuperTenantConfig(activeEventPublisherConfigurations); } } finally { PrivilegedCarbonContext.endTenantFlow(); } } /** * This is used to deploy an event publisher configuration using. * * @param publisherConfig Event Publisher Configuration as input stream. * @throws EventPublisherConfigurationException Event Publisher Configuration Exception. */ private void deployEventPublisherConfiguration(InputStream publisherConfig) throws EventPublisherConfigurationException { EventPublisherService carbonEventPublisherService = TenantResourceManagerDataHolder.getInstance() .getCarbonEventPublisherService(); EventPublisherConfiguration eventPublisherConfiguration; try { eventPublisherConfiguration = carbonEventPublisherService.getEventPublisherConfiguration(publisherConfig); } catch (EventPublisherStreamValidationException e) { if (log.isDebugEnabled()) { log.debug("The event publisher configuration not available.", e); } return; } if (TenantResourceManagerDataHolder.getInstance().getCarbonEventPublisherService() .getActiveEventPublisherConfiguration(eventPublisherConfiguration.getEventPublisherName()) != null) { destroyEventPublisherConfiguration(eventPublisherConfiguration.getEventPublisherName()); } carbonEventPublisherService.addEventPublisherConfiguration(eventPublisherConfiguration); } /** * This is used to destroy an existing EventPublisher. * As per the implementation in analytics-common we need to add the publisher as a file before destroying it. * * @param eventPublisherName Event Publisher Name. * @throws EventPublisherConfigurationException Configuration Management Exception. */ private void destroyEventPublisherConfiguration(String eventPublisherName) throws EventPublisherConfigurationException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); EventPublisherConfigurationFile eventPublisherConfigurationFile = new EventPublisherConfigurationFile(); eventPublisherConfigurationFile.setTenantId(tenantId); eventPublisherConfigurationFile.setEventPublisherName(eventPublisherName); eventPublisherConfigurationFile.setFileName(eventPublisherName); eventPublisherConfigurationFile.setStatus(EventPublisherConfigurationFile.Status.DEPLOYED); TenantResourceManagerDataHolder.getInstance().getCarbonEventPublisherService() .addEventPublisherConfigurationFile(eventPublisherConfigurationFile, tenantId); TenantResourceManagerDataHolder.getInstance().getCarbonEventPublisherService() .removeEventPublisherConfigurationFile(eventPublisherName, tenantId); } }
/** * 静态同步synchronized方法与synchronized(class)代码块 */ /** * @author Administrator * */ package mulitThread.chapter02.t2_2_9;
package com.GestiondesClub.services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.GestiondesClub.dao.InviterRepository; import com.GestiondesClub.dto.Clubdto; import com.GestiondesClub.entities.Inviter; @Service public class InviterService { @Autowired private InviterRepository invitServ; public Inviter getInviterByCin(int cin) { return invitServ.findByCin(cin); } public Inviter saveInvited(Inviter i) { return invitServ.save(i); } }
package org.giddap.dreamfactory.leetcode.onlinejudge; /** * <a href="http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/"> * Best Time To Buy And Sell Stock II</a> * <p/> * Say you have an array for which the ith element is the price of a given * stock on day i. * <p/> * Design an algorithm to find the maximum profit. You may complete as many * transactions as you like (ie, buy one and sell one share of the stock * multiple times). However, you may not engage in multiple transactions at the * same time (ie, you must sell the stock before you buy again). */ public interface BestTimeToBuyAndSellStockII { int maxProfit(int[] prices); }
package challenge2; import java.util.ArrayList; import java.util.Random; import static challenge2.Problem2.evaluate; import static challenge2.Problem2.getInitialState; public class StocasticHC { int verticesNum; int colorNum; int oldH = 0; int newH = 0; int oldColor; int numberOfIterations = 100; int seen = 0; int exploered = 0; public StocasticHC(Graph2 graph, int colorNum) { this.colorNum = colorNum; verticesNum = graph.nodes.size(); } public void HC(Graph2 graph) { ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<>(); ArrayList<Integer> colors = new ArrayList<>(); colors = getInitialState(verticesNum, colorNum); for (int i = 0; i < verticesNum; i++) { graph.nodes.get(i).color = colors.get(i); } for (int k = 0; k < numberOfIterations; k++) { for (int i = 0; i < verticesNum; i++) { oldH = evaluate(graph); oldColor = graph.nodes.get(i).color; for (int j = 0; j < colorNum; j++) { if (oldColor != j + 1) { graph.nodes.get(i).color = j + 1; newH = evaluate(graph); ArrayList<Integer> colors2 = new ArrayList<>(); for (int l = 0; l < colors.size(); l++) { colors2.add(colors.get(l)); } if (newH < oldH) { colors2.set(i, j + 1); arrayLists.add(colors2); } graph.nodes.get(i).color = oldColor; } } } seen += arrayLists.size(); Random r = new Random(); int rand = r.nextInt(arrayLists.size()); for (int i = 0; i < verticesNum; i++) { graph.nodes.get(i).color = arrayLists.get(rand).get(i); } // System.out.println(evaluate(graph)); } System.out.println("seen = " + seen); System.out.println("explored : " + numberOfIterations); System.out.println("conflict : " + evaluate(graph)); // for (int i = 0; i < arrayLists.size(); i++) { // for (int j = 0; j < arrayLists.get(i).size(); j++) { // System.out.print(arrayLists.get(i).get(j)); // } // System.out.println(); // // } } }
package com.wencheng.dao.impl; import java.util.List; import net.sf.json.JSONArray; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.hibernate.sql.JoinType; import com.wencheng.dao.TeacherDao; import com.wencheng.domain.Project; import com.wencheng.domain.Teacher; import com.wencheng.utils.HibernateUtil; public class TeacherDaoImpl extends ObjectDaoImpl<Teacher> implements TeacherDao { @Override public boolean checkUsername(String username) { // TODO Auto-generated method stub Session session = HibernateUtil.getSession(); try{ Long num = (Long) session.createCriteria(Teacher.class).add(Restrictions.eq("username",username)).setProjection(Projections.rowCount()).uniqueResult(); return num > 0; }finally{ HibernateUtil.closeSession(); } } @Override public List<Teacher> listSchool(int school) { // TODO Auto-generated method stub Session session = HibernateUtil.getSession(); try{ return session.createCriteria(Teacher.class).createAlias("school","scho",JoinType.LEFT_OUTER_JOIN).add(Restrictions.eq("scho.id", school)).setProjection(Projections.projectionList().add(Projections.property("id")).add(Projections.property("name")).add(Projections.property("identity"))).list(); }finally{ HibernateUtil.closeSession(); } } public List<Teacher> listSchool(int school,int start,int rows) { // TODO Auto-generated method stub Session session = HibernateUtil.getSession(); try{ return session.createCriteria(Teacher.class).createAlias("school","scho",JoinType.LEFT_OUTER_JOIN).add(Restrictions.eq("scho.id", school)).setFirstResult(start).setMaxResults(rows).list(); }finally{ } } public List<Teacher> list(int start,int rows) { // TODO Auto-generated method stub Session session = HibernateUtil.getSession(); try{ return session.createCriteria(Teacher.class).setFirstResult(start).setMaxResults(rows).list(); }finally{ } } @Override public Teacher listProject(int teacher) { // TODO Auto-generated method stub Session session = HibernateUtil.getSession(); try{ String queryString = "select distinct t from Project p left join p.teacher t where p.id = :id"; Query query = session.createQuery(queryString).setInteger("id", teacher); return (Teacher) query.uniqueResult(); }finally{ } } @Override public Teacher verified(String username, String password) { // TODO Auto-generated method stub Session session = HibernateUtil.getSession(); try{ String queryString = "select distinct t from Teacher t left join fetch t.school where t.username = :name and t.password = :password"; Query query = session.createQuery(queryString).setString("name",username).setString("password", password); return (Teacher) query.uniqueResult(); }finally{ HibernateUtil.closeSession(); } } @Override public Teacher find(int id) { // TODO Auto-generated method stub Session session = HibernateUtil.getSession(); String queryString = "select distinct t from Teacher t left join t.projects where t.id = :id"; Query query = session.createQuery(queryString).setInteger("id", id); return (Teacher) query.uniqueResult(); } public Long getRows(){ Session session = HibernateUtil.getSession(); String queryString = "select count(distinct t) from Teacher t"; Query query = session.createQuery(queryString); return (Long) query.uniqueResult(); } public Long getSchoolRows(int school){ Session session = HibernateUtil.getSession(); String queryString = "select count(distinct t) from Teacher t where t.school.id = :school"; Query query = session.createQuery(queryString).setInteger("school", school); return (Long) query.uniqueResult(); } }
package edu.mum.sonet.controllers; import edu.mum.sonet.models.Advertisement; import edu.mum.sonet.services.AdvertisementService; import edu.mum.sonet.services.FileService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; /** * Created by Jonathan on 12/10/2019. */ @Controller @RequestMapping(value = AdvertisementController.BASE_URL) public class AdvertisementController { public static final String BASE_URL = "admin/dashboard/advertisements"; private final AdvertisementService advertisementService; private final FileService fileService; public AdvertisementController(AdvertisementService advertisementService, FileService fileService) { this.advertisementService = advertisementService; this.fileService = fileService; } /** * Get Mappings */ @GetMapping(value = {"/", ""}) public String getAllAdvertisements(Model model) { model.addAttribute("advertisements", advertisementService.findAll()); return "advertisement/list"; } @GetMapping("/add") public String addAdvertisementForm(@ModelAttribute("newAdvertisement") Advertisement advertisement) { return "advertisement/add"; } @GetMapping("/{id}/delete") public String deleteAdvertisementById(@PathVariable @Valid Long id) { advertisementService.deleteById(id); return "redirect:/" + AdvertisementController.BASE_URL; } /** * Post mappings */ @PostMapping("/add") public String addAdvertisement(@ModelAttribute("newAdvertisement") @Valid Advertisement advertisement, BindingResult bindingResult, HttpServletRequest request, Model model) { ///> Handle Errors if (bindingResult.hasErrors()) { model.addAttribute("errors", bindingResult.getAllErrors()); return "advertisement/add"; } String rootDirectory = request.getSession().getServletContext().getRealPath("/"); String imageUrl = fileService.saveFile(advertisement.getImageFile(), rootDirectory + "adImages/"); advertisement.setContentUrl(imageUrl); advertisementService.save(advertisement); return "redirect:/" + AdvertisementController.BASE_URL; } }
package com.myvodafone.android.utils; import android.util.Log; import java.util.concurrent.TimeUnit; /** * Created by d.alexandrakis on 14/6/2016. */ public class Performance { long starts; public static Performance start() { return new Performance(); } private Performance() { reset(); } public Performance reset() { starts = System.currentTimeMillis(); return this; } public long time() { long ends = System.currentTimeMillis(); return ends - starts; } public long time(TimeUnit unit) { return unit.convert(time(), TimeUnit.MILLISECONDS); } public void log(TimeUnit unit) { StaticTools.Log("PERFORMANCE LOG", ""+time(unit)); } }
package zhihui.xu; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; /** * Created by zhihui.xu on 2017/9/30. */ /** * NOTE: 每个CommandKey代表一个依赖抽象,相同的依赖要使用相同的CommandKey名称。依赖隔离的根本就是对相同CommandKey的依赖做隔离 */ public class BuildByCommandKey extends HystrixCommand<String> { private final String name; protected BuildByCommandKey(String name) { super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")) /* HystrixCommandKey工厂定义依赖名称 */ .andCommandKey(HystrixCommandKey.Factory.asKey("HelloWorld"))); this.name = name; } @Override protected String run() throws Exception { return null; } }
package com.accolite.au; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAsync public class AuApplication { public static void main(String[] args) { SpringApplication.run(AuApplication.class, args); } }
package be.openclinic.finance; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.Locale; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import net.admin.Service; import be.mxs.common.util.db.MedwanQuery; import be.mxs.common.util.system.ScreenHelper; import com.itextpdf.text.pdf.PdfPTable; public class CsvInvoiceCplr2 { static DecimalFormat priceFormatInsurar = new DecimalFormat(MedwanQuery.getInstance().getConfigString("priceFormatInsurarCsv","#,##0.00"),new DecimalFormatSymbols(Locale.getDefault())); public static String getOutput(javax.servlet.http.HttpServletRequest request){ double pageTotalAmount=0,pageTotalAmount85=0,pageTotalAmount100=0; String invoiceuid=request.getParameter("invoiceuid"); int coverage=85; ExtraInsurarInvoice invoice = ExtraInsurarInvoice.get(invoiceuid); if(invoice!=null){ Insurar insurar=invoice.getInsurar(); if(insurar!=null && insurar.getInsuraceCategories()!=null && insurar.getInsuraceCategories().size()>0){ try{ coverage=100-Integer.parseInt(((InsuranceCategory)insurar.getInsuraceCategories().elementAt(0)).getPatientShare()); } catch(Exception e){ e.printStackTrace(); } } } String sOutput=""; if(invoiceuid!=null){ Vector debets = ExtraInsurarInvoice.getDebetsForInvoiceSortByServiceAndDate(invoiceuid); if(debets.size() > 0){ // print debets Debet debet; String sPatientName="", sPrevPatientName = "",sPreviousInvoiceUID="",beneficiarynr="",beneficiaryage="",beneficiarysex="",affiliatecompany=""; Date date=null,prevdate=null; boolean displayPatientName=false,displayDate=false; SortedMap categories = new TreeMap(), totalcategories = new TreeMap(); double total100pct=0,total85pct=0,generaltotal100pct=0,generaltotal85pct=0,daytotal100pct=0,daytotal85pct=0,totalext=0,generaltotalext=0; String invoiceid="",adherent="",recordnumber="",insurarreference="",status="",sService="",sServiceUid,sPrevService=""; int linecounter=1; boolean initialized=false; int debetcount=0; for(int i=0; i<debets.size(); i++){ debet = (Debet)debets.get(i); if(!debet.getEncounter().getType().equals("visit")){ continue; } if(!initialized){ //Eerst consultaties sOutput+="\r\n\r\n"+ScreenHelper.getTran(null,"hospital.statistics", "visits", "fr"); sOutput+="\r\n#;RECU;NOM ET PRENOM;MATRIC;CARTE;AFFECT;STATUT;SERVICE;TOTAL;PATIENT;ASSUREUR;ASSUREUR_COMPL;DATE;REF BON\r\n"; } initialized=true; date = ScreenHelper.parseDate(ScreenHelper.stdDateFormat.format(debet.getDate())); sServiceUid=debet.getServiceUid(); if(sServiceUid!=null && sServiceUid.length()>0){ Service service = Service.getService(sServiceUid); if(service !=null){ sService=service.getLabel("fr"); } } else { Service service = debet.getEncounter().getService(); if(service !=null){ sService=service.getLabel("fr"); } } displayDate = !date.equals(prevdate); sPatientName = debet.getPatientName()+";"+debet.getEncounter().getPatientUID(); displayPatientName = displayDate || !sPatientName.equals(sPrevPatientName) || (debet.getPatientInvoiceUid()!=null && debet.getPatientInvoiceUid().indexOf(".")>=0 && invoiceid.indexOf(debet.getPatientInvoiceUid().split("\\.")[1])<0 && invoiceid.length()>0); if(debetcount>0 && (displayDate || displayPatientName)){ //Print the line sOutput+=linecounter+";"; sOutput+=invoiceid+";"; sOutput+=sPrevPatientName.split(";")[0]+";"; sOutput+=recordnumber+";"; sOutput+=beneficiarynr+";"; sOutput+=affiliatecompany+";"; sOutput+=status+";"; sOutput+=sService+";"; sOutput+=total100pct+";"; sOutput+=(total100pct-total85pct-totalext)+";"; sOutput+=total85pct+";"; sOutput+=totalext+";"; sOutput+=(prevdate!=null?ScreenHelper.stdDateFormat.format(prevdate):ScreenHelper.stdDateFormat.format(date))+";"; sOutput+=insurarreference+"\r\n"; categories = new TreeMap(); total100pct=0; total85pct=0; totalext=0; daytotal100pct=0; daytotal85pct=0; invoiceid=""; adherent=""; recordnumber=""; insurarreference=""; beneficiarynr=""; beneficiaryage=""; beneficiarysex=""; affiliatecompany=""; sService=""; status=""; linecounter++; } if(debet.getPatientInvoiceUid()!=null && debet.getPatientInvoiceUid().indexOf(".")>=0 && invoiceid.indexOf(debet.getPatientInvoiceUid().split("\\.")[1])<0){ if(invoiceid.length()>0){ invoiceid+="\n"; } invoiceid+=debet.getPatientInvoiceUid().split("\\.")[1]; if(insurarreference.equalsIgnoreCase("")){ PatientInvoice patientInvoice = PatientInvoice.get(debet.getPatientInvoiceUid()); if(patientInvoice!=null){ insurarreference=patientInvoice.getInsurarreference(); } } } if(debet.getInsuranceUid()!=null){ Insurance insurance = Insurance.get(debet.getInsuranceUid()); debet.setInsurance(insurance); beneficiarynr=insurance.getInsuranceNr(); affiliatecompany=insurance.getMemberEmployer(); } if(debet.getInsurance()!=null && debet.getInsurance().getStatus()!=null){ status=ScreenHelper.getTranNoLink("insurance.status",debet.getInsurance().getStatus(),"fr"); } if(debet.getInsurance()!=null && debet.getInsurance().getMember()!=null && adherent.indexOf(debet.getInsurance().getMember().toUpperCase())<0){ if(adherent.length()>0){ adherent+="\n"; } adherent+=debet.getInsurance().getMember().toUpperCase(); } if(debet.getInsurance()!=null && debet.getInsurance().getMemberImmat()!=null && recordnumber.indexOf(debet.getInsurance().getMemberImmat())<0){ if(recordnumber.length()>0){ recordnumber+="\n"; } recordnumber+=debet.getInsurance().getMemberImmat(); } Prestation prestation = debet.getPrestation(); double rAmount = debet.getAmount(); double rInsurarAmount = debet.getInsurarAmount(); double rExtraInsurarAmount = debet.getExtraInsurarAmount(); int rTotal=(int)(rAmount+rInsurarAmount+rExtraInsurarAmount); total100pct+=rTotal; total85pct+=rInsurarAmount; totalext+=rExtraInsurarAmount; generaltotal100pct+=rTotal; generaltotal85pct+=rInsurarAmount; generaltotalext+=rExtraInsurarAmount; prevdate = date; sPrevPatientName = sPatientName; debetcount++; initialized=true; } if(initialized){ //Print the line sOutput+=linecounter+";"; sOutput+=invoiceid+";"; sOutput+=sPrevPatientName.split(";")[0]+";"; sOutput+=recordnumber+";"; sOutput+=beneficiarynr+";"; sOutput+=affiliatecompany+";"; sOutput+=status+";"; sOutput+=sService+";"; sOutput+=total100pct+";"; sOutput+=(total100pct-total85pct-totalext)+";"; sOutput+=total85pct+";"; sOutput+=totalext+";"; sOutput+=(prevdate!=null?ScreenHelper.stdDateFormat.format(prevdate):ScreenHelper.stdDateFormat.format(date))+";"; sOutput+=insurarreference+"\r\n"; //Print totals sOutput+=";"; sOutput+=ScreenHelper.getTran(null,"web", "total", "fr")+";"; sOutput+=";"; sOutput+=";"; sOutput+=";"; sOutput+=";"; sOutput+=";"; sOutput+=";"; sOutput+=generaltotal100pct+";"; sOutput+=(generaltotal100pct-generaltotal85pct-generaltotalext)+";"; sOutput+=generaltotal85pct+";"; sOutput+=generaltotalext+";"; sOutput+=";"; sOutput+="\r\n"; } total100pct=0; total85pct=0; totalext=0; generaltotal100pct=0; generaltotal85pct=0; generaltotalext=0; daytotal100pct=0; daytotal85pct=0; invoiceid=""; adherent=""; recordnumber=""; insurarreference=""; beneficiarynr=""; beneficiaryage=""; beneficiarysex=""; affiliatecompany=""; sService=""; status=""; //Dan hospitalisaties //Eerst maken we een lijst van de diensten SortedSet services = new TreeSet(); for(int i=0; i<debets.size(); i++){ debet = (Debet)debets.get(i); if(debet.getServiceUid()!=null && debet.getServiceUid().length()>0 && debet.getEncounter().getType().equals("admission") && !services.contains(debet.getServiceUid())){ services.add(debet.getServiceUid()); } else if((debet.getServiceUid()==null || debet.getServiceUid().length()==0) && debet.getEncounter().getType().equals("admission") && !services.contains(debet.getEncounter().getServiceUID())){ services.add(debet.getEncounter().getServiceUID()); } } if(services.size()>0){ sOutput+="\r\n\r\n\r\n"+ScreenHelper.getTran(null,"hospital.statistics", "admissions", "fr")+"\r\n"; } //Nu maken we de output voor elke dienst Iterator iServices = services.iterator(); while(iServices.hasNext()){ linecounter=1; initialized=false; String activeServiceUid=(String)iServices.next(); sService=""; Service service = Service.getService(activeServiceUid); if(service !=null){ sService=service.getLabel("fr"); } sOutput+="\r\n"+activeServiceUid+": "+sService+"\r\n#;NOM;MATRICULE;ADHERENT;RECU;REF BON;TOTAL;PATIENT;ASSUREUR;ASSUREUR_COMPL\r\n"; debetcount=0; for(int i=0; i<debets.size(); i++){ debet = (Debet)debets.get(i); if(!debet.getEncounter().getType().equals("admission") || !((debet.getServiceUid()!=null && debet.getServiceUid().length()>0 && debet.getServiceUid().equals(activeServiceUid)) || debet.getEncounter().getServiceUID().equals(activeServiceUid))){ continue; } initialized=true; date = ScreenHelper.parseDate(ScreenHelper.stdDateFormat.format(debet.getDate())); displayDate = !date.equals(prevdate); sPatientName = debet.getPatientName()+";"+debet.getEncounter().getPatientUID(); displayPatientName = displayDate || !sPatientName.equals(sPrevPatientName) || (debet.getPatientInvoiceUid()!=null && debet.getPatientInvoiceUid().indexOf(".")>=0 && invoiceid.indexOf(debet.getPatientInvoiceUid().split("\\.")[1])<0 && invoiceid.length()>0); if(debetcount>0 && displayPatientName){ //Print the line sOutput+=linecounter+";"; sOutput+=sPrevPatientName.split(";")[0]+";"; sOutput+=recordnumber+";"; sOutput+=adherent+";"; sOutput+=invoiceid+";"; sOutput+=insurarreference+";"; sOutput+=total100pct+";"; sOutput+=(total100pct-total85pct-totalext)+";"; sOutput+=total85pct+";"; sOutput+=totalext+"\r\n"; total100pct=0; total85pct=0; totalext=0; daytotal100pct=0; daytotal85pct=0; invoiceid=""; adherent=""; recordnumber=""; insurarreference=""; beneficiarynr=""; beneficiaryage=""; beneficiarysex=""; affiliatecompany=""; sService=""; status=""; linecounter++; } if(debet.getPatientInvoiceUid()!=null && debet.getPatientInvoiceUid().indexOf(".")>=0 && invoiceid.indexOf(debet.getPatientInvoiceUid().split("\\.")[1])<0){ if(invoiceid.length()>0){ invoiceid+="\n"; } invoiceid+=debet.getPatientInvoiceUid().split("\\.")[1]; if(insurarreference.equalsIgnoreCase("")){ PatientInvoice patientInvoice = PatientInvoice.get(debet.getPatientInvoiceUid()); if(patientInvoice!=null){ insurarreference=patientInvoice.getInsurarreference(); } } } if(debet.getInsuranceUid()!=null){ Insurance insurance = Insurance.get(debet.getInsuranceUid()); debet.setInsurance(insurance); beneficiarynr=insurance.getInsuranceNr(); affiliatecompany=insurance.getMemberEmployer(); } if(debet.getInsurance()!=null && debet.getInsurance().getStatus()!=null){ status=ScreenHelper.getTranNoLink("insurance.status",debet.getInsurance().getStatus(),"fr"); } if(debet.getInsurance()!=null && debet.getInsurance().getMember()!=null && adherent.indexOf(debet.getInsurance().getMember().toUpperCase())<0){ if(adherent.length()>0){ adherent+="\n"; } adherent+=debet.getInsurance().getMember().toUpperCase(); } if(debet.getInsurance()!=null && debet.getInsurance().getMemberImmat()!=null && recordnumber.indexOf(debet.getInsurance().getMemberImmat())<0){ if(recordnumber.length()>0){ recordnumber+="\n"; } recordnumber+=debet.getInsurance().getMemberImmat(); } Prestation prestation = debet.getPrestation(); double rAmount = debet.getAmount(); double rInsurarAmount = debet.getInsurarAmount(); double rExtraInsurarAmount = debet.getExtraInsurarAmount(); int rTotal=(int)(rAmount+rInsurarAmount+rExtraInsurarAmount); total100pct+=rTotal; total85pct+=rInsurarAmount; totalext+=rExtraInsurarAmount; generaltotal100pct+=rTotal; generaltotal85pct+=rInsurarAmount; generaltotalext+=rExtraInsurarAmount; prevdate = date; sPrevPatientName = sPatientName; debetcount++; } if(initialized){ //Print the line sOutput+=linecounter+";"; sOutput+=sPrevPatientName.split(";")[0]+";"; sOutput+=recordnumber+";"; sOutput+=adherent+";"; sOutput+=invoiceid+";"; sOutput+=insurarreference+";"; sOutput+=total100pct+";"; sOutput+=(total100pct-total85pct-totalext)+";"; sOutput+=total85pct+";"; sOutput+=totalext+"\r\n"; //Print the totals sOutput+=";"; sOutput+=ScreenHelper.getTran(null,"web", "total", "fr")+";"; sOutput+=";"; sOutput+=";"; sOutput+=";"; sOutput+=";"; sOutput+=generaltotal100pct+";"; sOutput+=(generaltotal100pct-generaltotal85pct-generaltotalext)+";"; sOutput+=generaltotal85pct+";"; sOutput+=generaltotalext+"\r\n"; generaltotal100pct=0; generaltotal85pct=0; generaltotalext=0; total100pct=0; total85pct=0; totalext=0; daytotal100pct=0; daytotal85pct=0; invoiceid=""; adherent=""; recordnumber=""; insurarreference=""; beneficiarynr=""; beneficiaryage=""; beneficiarysex=""; affiliatecompany=""; sService=""; status=""; } } } } return sOutput; } //--- PRINT DEBET (prestation) ---------------------------------------------------------------- private static String printDebet2(SortedMap categories, boolean displayDate, Date date, String invoiceid,String adherent,String beneficiary,double total100pct,double total85pct,String recordnumber,int linecounter,String insurarreference,String beneficiarynr,String beneficiaryage,String beneficiarysex,String affiliatecompany){ String sOutput=""; sOutput+=linecounter+";"; sOutput+=ScreenHelper.stdDateFormat.format(date)+";"; sOutput+=insurarreference+";"; sOutput+=invoiceid+";"; sOutput+=beneficiarynr+";"; sOutput+=beneficiaryage+";"; sOutput+=beneficiarysex+";"; sOutput+=beneficiary+";"; sOutput+=adherent+";"; sOutput+=affiliatecompany+";"; String amount = (String)categories.get(MedwanQuery.getInstance().getConfigString("RAMAconsultationCategory","Co")); sOutput+=amount==null?"0;":amount+";"; amount = (String)categories.get(MedwanQuery.getInstance().getConfigString("RAMAlabCategory","L")); sOutput+=amount==null?"0;":amount+";"; amount = (String)categories.get(MedwanQuery.getInstance().getConfigString("RAMAimagingCategory","R")); sOutput+=amount==null?"0;":amount+";"; amount = (String)categories.get(MedwanQuery.getInstance().getConfigString("RAMAadmissionCategory","S")); sOutput+=amount==null?"0;":amount+";"; amount = (String)categories.get(MedwanQuery.getInstance().getConfigString("RAMAactsCategory","A")); sOutput+=amount==null?"0;":amount+";"; amount = (String)categories.get(MedwanQuery.getInstance().getConfigString("RAMAconsumablesCategory","C")); sOutput+=amount==null?"0;":amount+";"; String otherprice="+0"; String allcats= "*"+MedwanQuery.getInstance().getConfigString("RAMAconsultationCategory","Co")+ "*"+MedwanQuery.getInstance().getConfigString("RAMAlabCategory","L")+ "*"+MedwanQuery.getInstance().getConfigString("RAMAimagingCategory","R")+ "*"+MedwanQuery.getInstance().getConfigString("RAMAadmissionCategory","S")+ "*"+MedwanQuery.getInstance().getConfigString("RAMAactsCategory","A")+ "*"+MedwanQuery.getInstance().getConfigString("RAMAconsumablesCategory","C")+ "*"+MedwanQuery.getInstance().getConfigString("RAMAdrugsCategory","M")+"*"; Iterator iterator = categories.keySet().iterator(); while (iterator.hasNext()){ String cat = (String)iterator.next(); if(allcats.indexOf("*"+cat+"*")<0 && ((String)categories.get(cat)).length()>0){ otherprice+="+"+(String)categories.get(cat); } } sOutput+=otherprice+";"; amount = (String)categories.get(MedwanQuery.getInstance().getConfigString("RAMAdrugsCategory","M")); sOutput+=amount==null?"0;":amount+";"; sOutput+=priceFormatInsurar.format(total100pct)+";"; sOutput+=priceFormatInsurar.format(total85pct)+"\r\n"; return sOutput; } }
package com.git.cloud.sys.model.po; import java.io.Serializable; import com.git.cloud.common.model.base.BaseBO; public class SysUserPo extends BaseBO implements Serializable { private static final long serialVersionUID = 1L; public SysUserPo(){} private String userId; private String orgId; private String firstName; private String lastName; private String loginName; private String loginPassword; private String email; private String phone; private String ipAddress; private String lastLogin; private String userType; private String isActive; private String roleId; private Boolean isManager;// 是否是超级管理员标识 private String platUser;// 是否是超级管理员标识 public String getPlatUser() { return platUser; } public void setPlatUser(String platUser) { this.platUser = platUser; } public String toString(){ return firstName+lastName; } public SysUserPo(String userId, String orgId, String firstName, String lastName, String loginName, String loginPassword, String email, String phone, String ipAddress, String lastLogin, String userType, String isActive, String roleId, Boolean isManager, String platUser) { super(); this.userId = userId; this.orgId = orgId; this.firstName = firstName; this.lastName = lastName; this.loginName = loginName; this.loginPassword = loginPassword; this.email = email; this.phone = phone; this.ipAddress = ipAddress; this.lastLogin = lastLogin; this.userType = userType; this.isActive = isActive; this.roleId = roleId; this.isManager = isManager; this.platUser = platUser; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getOrgId() { return orgId; } public void setOrgId(String orgId) { this.orgId = orgId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getLoginPassword() { return loginPassword; } public void setLoginPassword(String loginPassword) { this.loginPassword = loginPassword; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public String getLastLogin() { return lastLogin; } public void setLastLogin(String lastLogin) { this.lastLogin = lastLogin; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public String getIsActive() { return isActive; } public void setIsActive(String isActive) { this.isActive = isActive; } public String getRoleId() { return roleId; } public void setRoleId(String roleId) { this.roleId = roleId; } public Boolean getIsManager() { return isManager; } public void setIsManager(Boolean isManager) { this.isManager = isManager; } @Override public String getBizId() { // TODO Auto-generated method stub return null; } }
package com.technolearns.services; import java.util.Set; import com.technolearns.model.Owner; import com.technolearns.model.Vet; public interface VetService extends CrudService<Vet, Long> { Vet findByLastName(String lastName); }
package com.guard.myguard.services.impl; import android.util.Log; import com.guard.myguard.enums.ParsingServiceType; import com.guard.myguard.services.interfaces.ParsingService; import java.util.HashMap; import java.util.Map; public class ParsingServiceFactory { private final static Map<ParsingServiceType, ParsingService> services = new HashMap<>(); public static ParsingService getService(ParsingServiceType parsingServiceType) { if (services.containsKey(parsingServiceType)) { return services.get(parsingServiceType); } else { ParsingService tmp = null; try { tmp = parsingServiceType.getService().newInstance(); services.put(parsingServiceType, tmp); } catch (InstantiationException | IllegalAccessException e) { Log.e("Failure", "Required service couldn't be instantiated.", e); } return tmp; } } }
package edu.mit.cci.simulation.excel.server; import edu.mit.cci.simulation.model.DefaultVariable; import edu.mit.cci.simulation.model.Variable; import org.springframework.roo.addon.entity.RooEntity; import org.springframework.roo.addon.javabean.RooJavaBean; import org.springframework.roo.addon.tostring.RooToString; import javax.persistence.ManyToOne; @RooJavaBean @RooToString @RooEntity public class ExcelVariable { @ManyToOne private ExcelSimulation excelSimulation; private String worksheetName; private String cellRange; private String rewriteCellRange; @ManyToOne private DefaultVariable simulationVariable; public ExcelVariable() { } public ExcelVariable(ExcelSimulation sim, DefaultVariable var, String worksheet, String cellrange) { super(); setExcelSimulation(sim); setSimulationVariable(var); setWorksheetName(worksheet); setCellRange(cellrange); } public ExcelVariable(ExcelSimulation sim, DefaultVariable var, String worksheet, String cellrange, String rewriteCellRange) { super(); setExcelSimulation(sim); setSimulationVariable(var); setWorksheetName(worksheet); setCellRange(cellrange); setRewriteCellRange(rewriteCellRange); } }
package com.ifeng.recom.mixrecall.common.dao.elastic; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.Maps; import com.ifeng.recom.mixrecall.common.constant.GyConstant; import com.ifeng.recom.mixrecall.common.model.Document; import com.ifeng.recom.mixrecall.common.util.DocUtils; import com.ifeng.recom.mixrecall.common.util.GsonUtil; import com.ifeng.recom.mixrecall.common.util.StringUtil; import org.apache.commons.lang3.StringUtils; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.get.MultiGetItemResponse; import org.elasticsearch.action.get.MultiGetResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; /** * Created by geyl on 2017/12/4. */ public class Query { private static final Logger logger = LoggerFactory.getLogger(Query.class); private static TransportClient client; private static final String INDEX = "preload-news"; private static final String TYPE = "_doc"; private static String[] noFetchSource = new String[]{}; private static String[] needFetchSource = new String[]{"docId"}; private static LoadingCache<String, String> guid2DocidCache; static { client = EsClientFactory.getClient(); initGuid2DocidCache(); } private static void initGuid2DocidCache() { guid2DocidCache = CacheBuilder .newBuilder() .concurrencyLevel(15) .expireAfterWrite(180, TimeUnit.MINUTES) .initialCapacity(1000000) .maximumSize(1500000) .build(new CacheLoader<String, String>() { @Override public String load(String guId) { String docId = Query.queryDocIdByGuid(guId); if (StringUtils.isNotBlank(docId)) { return docId; } else { return ""; } } }); } /** * 根据docId查询ES获取Document对象 * * @param docId * @return Document */ public static Document queryDocument(String docId) { //兼容guid if (docId.length() >= GyConstant.GUID_Length) { //正常是没有这部分流量的,观察无流量后续可以下掉 try { String docIdNew = guid2DocidCache.get(docId); logger.info("guid2DocidCache:{} to docid: {}", docId, docIdNew); docId = docIdNew; } catch (ExecutionException e) { logger.error("guid2Docid ERROR:{}", docId); e.printStackTrace(); } } //兼容字符串开头的其他id, if (!StringUtil.startWithNum(docId)) { docId = docId.substring(docId.indexOf(GyConstant.Symb_Underline) + 1); } Document doc =null; try{ GetResponse response = client.prepareGet(INDEX, TYPE, docId).get(new TimeValue(500)); String rt = response.getSourceAsString(); // GetResponse response = client.prepareGet(INDEX, TYPE, "7nQ2frp3YM6").get(new TimeValue(500)); // String rt = response.getSourceAsString(); // // // Document doc = GsonUtil.json2ObjectWithoutExpose(rt, Document.class); doc = GsonUtil.json2ObjectWithoutExpose(rt, Document.class); DocUtils.initDocument(doc); }catch (Exception e){ logger.error("guid2Docid query doc ERROR:{},docId:{}",e,docId); e.printStackTrace(); } return doc; } public static String queryDocId(String simId) { QueryBuilder qb = QueryBuilders.matchQuery("simId", simId); SearchResponse response = client.prepareSearch(INDEX) // .setScroll(new TimeValue(6000)) .setFetchSource(needFetchSource, noFetchSource) .setQuery(qb) .setTimeout(new TimeValue(500)) .setSize(1).get(); return Arrays.stream(response.getHits().getHits()).map(hit -> hit.getSourceAsMap().get("docId").toString()).findFirst().orElse(""); } /** * 根据docid查询es转换 * * @param guid * @return Document */ public static Document queryDocumentByGuid(String guid) { String docId = queryDocIdByGuid(guid); if (StringUtils.isBlank(docId)) { return null; } GetResponse response = client.prepareGet(INDEX, TYPE, docId).get(new TimeValue(500)); String rt = response.getSourceAsString(); Document doc = GsonUtil.json2ObjectWithoutExpose(rt, Document.class); return doc; } /** * 根据guid查询docid * * @param guid * @return docId */ public static String queryDocIdByGuid(String guid) { QueryBuilder qb = QueryBuilders.matchQuery("url", guid); SearchResponse response = client.prepareSearch(INDEX) .setScroll(new TimeValue(60000)) .setTimeout(new TimeValue(500)) .setFetchSource(needFetchSource, noFetchSource) .setQuery(qb) .setSize(1).get(); return Arrays.stream(response.getHits().getHits()).map(hit -> hit.getSourceAsMap().get("docId").toString()).findFirst().orElse(""); } public static Map<String, Document> batchQueryByDocId(Set<String> ids) { Map<String, Document> docs = Maps.newHashMap(); MultiGetResponse response = null; try { response = client.prepareMultiGet().add(INDEX, TYPE, ids).get(new TimeValue(500)); } catch (Exception e) { logger.error("request doc error,", e); return docs; } MultiGetItemResponse[] rs = response.getResponses(); for (MultiGetItemResponse rt : rs) { Document doc = null; try { doc = GsonUtil.json2ObjectWithoutExpose(rt.getResponse().getSourceAsString(), Document.class); } catch (Exception e) { } Document d = DocUtils.initDocument(doc); if (doc == null) { continue; } docs.put(d.getDocId(), d); } return docs; } public static void main(String[] args) { Map<String,String> s= Maps.newHashMap(); System.out.println(s); s.put("asd","asd"); System.out.println(s.get("xx")); // List<String> s = new ArrayList(); // s.add("asd"); // s.add("asd"); // String b = s.get(10); // System.out.println(b); try{ for(int i = 0; i<50; i++) { long start = System.currentTimeMillis(); GetResponse response = client.prepareGet(INDEX, TYPE, "7nQ2frp3YM6").get(new TimeValue(500)); String rt = response.getSourceAsString(); Document doc = GsonUtil.json2ObjectWithoutExpose(rt, Document.class); List<String> category = new ArrayList<>(); DocUtils.initDocument(doc); String docCotag = doc.getCotag(); Set<String> cotags = new HashSet<>(Arrays.asList(docCotag.split(" "))); doc.setcoTagSet(cotags); System.out.println(doc.getcoTagSet()); // doc.getCoTagSet() // public void SetcoTagSet(Set<String> coTagSet) { // this.coTagSet = coTagSet; // } } }catch (Exception e){ logger.error("guid2Docid query doc ERROR:{},docId:{}",e,"124612821"); e.printStackTrace(); } } }
package session2.td.agregation; public class NatCalculantRecursivement extends NatDeleguantEtat{ public NatCalculantRecursivement(EtatNaturelPur naturelPur) { super(naturelPur); } public Nat creerNatAvecEtat(EtatNaturelPur etatNaturelPur) { return new NatCalculantRecursivement(etatNaturelPur); } public Nat somme(Nat x) { if(this.estNul()) return x; return this.creerSuccesseur(this.predecesseur().somme(x)); } public Nat produit(Nat x) { if(this.estNul()) return creerZero(); return x.somme(this.predecesseur().produit(x)); } public Nat modulo(Nat x) { if(this.estNul()) return creerZero(); Nat r = this.predecesseur().modulo(x); return this.creerSuccesseur(r).equals(x) ? this.creerZero() : this.creerSuccesseur(r); } public Nat div(Nat x) { if(this.estNul()) return creerZero(); Nat r = this.predecesseur().modulo(x); Nat q = this.predecesseur().div(x); return this.creerSuccesseur(r).equals(x) ? this.creerSuccesseur(q) : q; } @Override public Nat zero() { return creerNatAvecValeur(0); } @Override public Nat un() { return creerNatAvecValeur(1); } public String toString() { return Integer.toString(this.val()); } public boolean equals(Object obj) { if(!(obj instanceof Nat)) return false; Nat x = (Nat)obj; return this.val() == x.val(); } }
package com.fm.model.inter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.List; import com.fm.connection.ConnectionFactory; import com.fm.model.pojo.Form; public class FormDAOImpl implements FormDAO { Connection con=null; public FormDAOImpl() { con=ConnectionFactory.openConn(); } @Override public int saveForm(Form fm) { int status=0; try { PreparedStatement ps=con.prepareStatement("insert into form values(?,?,?,?,?,?,?,?,?)"); ps.setString(1, fm.getFirstname()); ps.setString(2, fm.getLastname()); ps.setInt(3, fm.getAge()); ps.setString(4, fm.getGender()); ps.setString(5, fm.getContactnumber()); ps.setString(6, fm.getCity()); ps.setString(7, fm.getState()); ps.setString(8, fm.getUserid()); ps.setString(9, fm.getPassword()); status=ps.executeUpdate(); }catch (Exception e) { System.out.println("Error in Insert form "+e); } return status; } @Override public int validateUser(String user, String pwd) { int status=0; try { PreparedStatement ps=con.prepareStatement("select userid,password from form where userid=? and password=?"); ps.setString(1, user); ps.setString(2, pwd); ResultSet rs=ps.executeQuery(); if(rs.next()) status=1; else status=0; }catch (Exception e) { System.out.println("Error in validate form "+e); } return status; } /* @Override public int updateForm(Form fm) { int status=0; try { PreparedStatement ps=con.prepareStatement("update Form set firstname=?,lastname=?,age=? where empid=?"); ps.setInt(4, emp.getEmpid()); ps.setString(1, emp.getEmpname()); ps.setInt(2, emp.getEmpage()); ps.setDouble(3, emp.getEmpsalary()); status=ps.executeUpdate(); }catch (Exception e) { System.out.println("Error in Update Employee "+e); } return status; } @Override public List<Form> getAllForm() { List<Form> listEmp=new ArrayList<Form>(); try { Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from form"); while(rs.next()) { Employee emp=new Employee(); emp.setEmpid(rs.getInt(1)); emp.setEmpname(rs.getString(2)); emp.setEmpage(rs.getInt(3)); emp.setEmpsalary(rs.getDouble(4)); listEmp.add(emp); } } catch (Exception e) { System.out.println("Error in getAll Employee "+e); } return listEmp; } @Override public int deleteForm(int fmid) { // TODO Auto-generated method stub return 0; } @Override public Form getByuserId(int fmid) { // TODO Auto-generated method stub return null; } } */ }
package edu.mit.cci.wikipedia.collector; import javax.xml.parsers.*; import org.xml.sax.*; import org.xml.sax.helpers.*; import java.io.*; public class XMLParseRevision extends DefaultHandler { /** * @param args */ private static String userName; private Result result; private String xml; public XMLParseRevision(String _userName, Result _result, String _xml) { userName = _userName; result = _result; xml = _xml; } public void setUserName(String _userName) { userName = _userName; } public String getUserName() { return userName; } public void parse() { try { // Create SAX Parser Factory SAXParserFactory spfactory = SAXParserFactory.newInstance(); // Generate SAX Parser SAXParser parser = spfactory.newSAXParser(); parser.parse(new ByteArrayInputStream(xml.getBytes()), new XMLParseRevision(userName,result,xml)); } catch (Exception e) { e.printStackTrace(); } } /** * Document start */ public void startDocument() { //System.out.println("Document start"); } /** * Reading the element start tag */ public void startElement(String uri, String localName, String qName, Attributes attributes) { //System.out.println("Element:" + qName); if (qName.equals("rev")) { if(attributes.getLength()!=0){ String minor = "0"; if (attributes.getValue("minor") != null) { minor = "1"; } else { String user = attributes.getValue("user"); //if (user.split("\\.").length != 4) // Remove IP editors (xxx.xxx.xxx.xxx) result.append(getUserName() + "\t" + attributes.getValue("user") + "\t" + attributes.getValue("timestamp") + "\t" + minor + "\t" + attributes.getValue("size") + "\n"); } } } if (qName.equals("revisions")) { if(attributes.getLength() > 0) { //System.out.println("\trevision continues " + attributes.getValue("rvstartid")); result.setNextId(attributes.getValue("rvstartid")); } } } /** * Read text data */ public void characters(char[] ch, int offset, int length) { //System.out.println("Text:" + new String(ch, offset, length)); } /** * Read the element end tag */ public void endElement(String uri, String localName, String qName) { //System.out.println("Element end:" + qName); } /** * End document */ public void endDocument() { //System.out.println("Document end"); } }
/** * This package is contains all the entity objects which interact with hibernate for persistence. * * @author @author Swapnil Ahirrao * @version 1.0 * @since 03/20/2020 * */ package com.xp.springboot.entities;
package mb.tianxundai.com.toptoken.mall.shopcar; import android.content.Context; import android.util.Log; import com.zcolin.gui.pullrecyclerview.PullRecyclerView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import mb.tianxundai.com.toptoken.R; import mb.tianxundai.com.toptoken.aty.SplashShouAty; import mb.tianxundai.com.toptoken.base.BaseListener; import mb.tianxundai.com.toptoken.bean.BannerBean; import mb.tianxundai.com.toptoken.bean.HomeFragmentGoodsBean; import mb.tianxundai.com.toptoken.bean.MallGoodsDetailsBean; import mb.tianxundai.com.toptoken.bean.MallMainUpdataBean; import mb.tianxundai.com.toptoken.bean.MallShopCarBean; import mb.tianxundai.com.toptoken.bean.ShoppingCartBean; import mb.tianxundai.com.toptoken.net.RetrofitClient; import mb.tianxundai.com.toptoken.uitl.Config; import mb.tianxundai.com.toptoken.uitl.PreferencesUtils; import mb.tianxundai.com.toptoken.uitl.StringUtils; public class MallShopCarInteractor { private Context context; public MallShopCarInteractor(Context context) { this.context = context; } interface OnShopCarFinishedListener extends BaseListener { void getShopCarSuccess(List<MallShopCarBean.DataBean.ListBean> listBean); void delectShopCarSuccess(MallMainUpdataBean bean); void changeShopCarCountSuccess(MallMainUpdataBean bean); void onFailure(String message); } //获取购物车列表 public void getShopCarList( int pageSize,int pageNo,final OnShopCarFinishedListener onShopCarFinishedListener){ String token = PreferencesUtils.getString(context, Config.TOKEN); if (StringUtils.isEmpty(token)){ return; } Observable<MallShopCarBean> mallGoodsDetails = RetrofitClient.getHttpUtilsInstance().apiClient.getShopCarList(SplashShouAty.LANGUAGE,token,pageSize,pageNo); mallGoodsDetails.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).safeSubscribe(new Observer<MallShopCarBean>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(MallShopCarBean mallShopCarBean) { if (mallShopCarBean.getStatus() == 200) { Log.i("carssss",mallShopCarBean.getData().getList().size()+""); onShopCarFinishedListener.getShopCarSuccess(mallShopCarBean.getData().getList()); }else { onShopCarFinishedListener.onFailure(mallShopCarBean.getMsg()); } } @Override public void onError(Throwable e) { onShopCarFinishedListener.onFailure(context.getString(R.string.inter_error)); onShopCarFinishedListener.hideProgress(); } @Override public void onComplete() { onShopCarFinishedListener.hideProgress(); } }); } //删除购物车商品 public void delectShopCarList(int id,final OnShopCarFinishedListener onShopCarFinishedListener){ Observable<MallMainUpdataBean> mallGoodsDetails = RetrofitClient.getHttpUtilsInstance().apiClient.delectShopCarList(SplashShouAty.LANGUAGE,id); mallGoodsDetails.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).safeSubscribe(new Observer<MallMainUpdataBean>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(MallMainUpdataBean bean) { if (bean.getStatus() == 200) { onShopCarFinishedListener.delectShopCarSuccess(bean); }else { onShopCarFinishedListener.onFailure(bean.getMsg()); } } @Override public void onError(Throwable e) { onShopCarFinishedListener.onFailure(context.getString(R.string.inter_error)); onShopCarFinishedListener.hideProgress(); } @Override public void onComplete() { onShopCarFinishedListener.hideProgress(); } }); } //修改购物车商品数量 public void changeShopCarCount(int id,int count,final OnShopCarFinishedListener onShopCarFinishedListener){ Observable<MallMainUpdataBean> mallGoodsDetails = RetrofitClient.getHttpUtilsInstance().apiClient.changeShopCarCount(SplashShouAty.LANGUAGE,id,count); mallGoodsDetails.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).safeSubscribe(new Observer<MallMainUpdataBean>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(MallMainUpdataBean bean) { if (bean.getStatus() == 200) { onShopCarFinishedListener.changeShopCarCountSuccess(bean); }else { onShopCarFinishedListener.onFailure(bean.getMsg()); } } @Override public void onError(Throwable e) { onShopCarFinishedListener.onFailure(context.getString(R.string.inter_error)); onShopCarFinishedListener.hideProgress(); } @Override public void onComplete() { onShopCarFinishedListener.hideProgress(); } }); } }
package gov.inl.HZGenerator.Octree; import gov.inl.HZGenerator.BrickFactory.Brick; import gov.inl.HZGenerator.CLFW; import gov.inl.HZGenerator.Kernels.PartitionerResult; import javafx.util.Pair; import org.joml.Vector3i; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * Created by Nate on 7/28/2017. */ public class OctNode { List<Pair<Integer, Brick>> bricks; OctNode parent = null; OctNode children[] = new OctNode[8]; Boolean isLeaf = true; Vector3i pxPosition; int pxWidth; public void add(OctNode child, int index) { if (child != null) { isLeaf = false; children[index] = child; } } public static OctNode buildOctree(Vector3i volumeSize, PartitionerResult pr, int minBrickSize) { /* Determine octree size */ int maxDim = Integer.max(volumeSize.x, Integer.max(volumeSize.y, volumeSize.z)); int maxOctDim = CLFW.NextPow2(maxDim) / minBrickSize; /* Determine total levels */ int levels = 0; int temp = maxOctDim; while (temp > 0) { levels ++; temp /= 2; } /* Start by adding all bricks to the root node */ OctNode root = new OctNode(); root.bricks = new LinkedList<>(); for (int i = 0; i < pr.bricks.size(); ++i) root.bricks.add(new Pair<>(i, pr.bricks.get(i))); /* Root position at 0, width covers all bricks */ root.pxPosition = new Vector3i(0,0,0); root.pxWidth = CLFW.NextPow2(maxDim); generateLevel(root, root.bricks, levels - 1); return root; } private static void generateLevel(OctNode node, List<Pair<Integer, Brick>> bricks, int currentLevel) { /* If we're at the bottom of the tree, exit. */ if (currentLevel <= 0) return; /* If there isn't more than one brick, exit*/ if (bricks.size() <= 0) return; node.isLeaf = false; /* Otherwise, initialize the children of this node */ for (int i = 0; i < 8; ++i) { OctNode child = new OctNode(); child.parent = node; child.pxWidth = node.pxWidth / 2; child.pxPosition = new Vector3i( ((i & 1 << 0) == 0) ? node.pxPosition.x : node.pxPosition.x + child.pxWidth, ((i & 1 << 1) == 0) ? node.pxPosition.y : node.pxPosition.y + child.pxWidth, ((i & 1 << 2) == 0) ? node.pxPosition.z : node.pxPosition.z + child.pxWidth); child.bricks = new LinkedList<>(); node.children[i] = child; } /* Split up the bricks to the children */ Vector3i middle = node.pxPosition.add(new Vector3i(node.pxWidth / 2)); for (int i = 0; i < bricks.size(); ++i) { Pair<Integer, Brick> currentBrick = bricks.get(i); Vector3i brickPos = currentBrick.getValue().getPosition(); int x = brickPos.x >= middle.x ? 1 : 0; int y = brickPos.y >= middle.y ? 1 : 0; int z = brickPos.z >= middle.z ? 1 : 0; int index = (x << 0) | (y << 1) | (z << 2); node.children[index].bricks.add(currentBrick); } for (int i = 0; i < 8; ++i) generateLevel(node.children[i], node.children[i].bricks, currentLevel - 1); } public static int getTotalNodes(OctNode node) { if (node.isLeaf) return 1; else { int total = 1; for (int i = 0; i < 8; ++i) { total += getTotalNodes(node.children[i]); } return total; } } public JSONObject toJson() { JSONObject current = new JSONObject(); try { if (!isLeaf) { JSONArray children = new JSONArray(); for (int i = 0; i < 8; ++i) { children.put(this.children[i].toJson()); } current.put("Children", children); } else { /* If an octnode is a leaf, it should have only one brick */ if (bricks.size() == 0) current.put("Value", -1); else current.put("Value", bricks.get(0).getKey()); } } catch (JSONException e) { e.printStackTrace(); } return current; } }
/* * @(#)NameGenerator.java 1.0 07/05/99 * */ package org.google.code.netapps.chat.primitive; /** * Class for generating simple names on base of incremental counter. * * @version 1.0 07/05/99 * @author Alexander Shvets */ public class NameGenerator implements java.io.Serializable { static final long serialVersionUID = -2550202272594964528L; /** A counter which number will be used for name construction */ private long cnt = 0; /** A name prefix */ protected String prefix = ""; /** * Creates name generator with default prefix */ public NameGenerator() {} /** * Creates name generator with spesified prefix */ public NameGenerator(String prefix) { this.prefix = prefix; } /** * Get new name from name generator */ public String getNewName() { return prefix + Long.toString(++cnt); } /** * Release specified name to be reused * * @param name the name that can be reused after release */ public void release(String name) {} }
package co.sblock.events.listeners.block; import org.apache.commons.lang3.tuple.Pair; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.event.EventHandler; import org.bukkit.event.block.BlockSpreadEvent; import co.sblock.Sblock; import co.sblock.events.listeners.SblockListener; import co.sblock.machines.Machines; import co.sblock.machines.type.Machine; /** * Listener for BlockSpreadEvents. * * @author Jikoo */ public class SpreadListener extends SblockListener { private final Machines machines; public SpreadListener(Sblock plugin) { super(plugin); this.machines = plugin.getModule(Machines.class); } /** * EventHandler for BlockSpreadEvents. * * @param event the BlockSpreadEvent */ @EventHandler(ignoreCancelled = true) public void onBlockSpread(BlockSpreadEvent event) { Pair<Machine, ConfigurationSection> pair = machines.getMachineByBlock(event.getBlock()); if (pair != null) { event.setCancelled(pair.getLeft().handleSpread(event, pair.getRight())); } } }
package com.cit360projectmark4.service; import com.cit360projectmark4.pojo.UsersEntity; public interface BaseService { public boolean login(String username, String password); public String registration(UsersEntity user); }
package hw4; import hw4.q01.*; import hw4.q02.TreeAnalyzer; import hw4.q03.*; import hw4.q04.MLMRevenueTracker; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Application { public static void main(String[] args) { MyHashTable<String, Integer> sales = new MyHashTable<>(10, 10); sales.put("A", 10); sales.put("B", 20); sales.put("C", 30); sales.put("D", 40); sales.put("E", 50); MyHashTable<String, String> sponsors = new MyHashTable<>(10, 10); sponsors.put("A", ""); sponsors.put("B", "A"); sponsors.put("C", "A"); sponsors.put("D", "B"); sponsors.put("E", "C"); MLMRevenueTracker tracker = new MLMRevenueTracker(); int a = tracker.getNetIncome("C", sales, sponsors); System.out.println(a); } private static Comparable[] getNodesNotFull(){ Comparable[] heap = new Comparable[32]; heap[1] = 100; heap[2] = 100; heap[3] = 100; heap[6] = 100; heap[7] = 100; heap[14] = 100; return heap; } // Full+Perfect private static Comparable[] getNodesRootOnly(){ Comparable[] heap = new Comparable[4]; heap[1] = 100; return heap; } // Full private static Comparable[] getNodesLeft(){ Comparable[] heap = new Comparable[64]; heap[1] = 100; heap[2] = 100; heap[3] = 100; heap[6] = 100; heap[7] = 100; heap[14] = 100; heap[15] = 100; return heap; } // Full private static Comparable[] getNodesRight(){ Comparable[] heap = new Comparable[32]; heap[1] = 100; heap[2] = 100; heap[3] = 100; heap[4] = 100; heap[5] = 100; heap[8] = 100; heap[9] = 100; return heap; } // Full private static Comparable[] getNodesMiddle(){ Comparable[] heap = new Comparable[36]; heap[1] = 100; heap[2] = 100; heap[3] = 100; heap[6] = 100; heap[7] = 100; heap[12] = 100; heap[13] = 100; return heap; } // Full+Perfect+Complete private static Comparable[] getNodesSameLevel(){ Comparable[] heap = new Comparable[32]; heap[1] = 100; heap[2] = 100; heap[3] = 100; heap[4] = 100; heap[5] = 100; heap[6] = 100; heap[7] = 100; return heap; } // Full, not Complete because it has gaps on left side of bottom private static Comparable[] getNodesLeftGap(){ Comparable[] heap = new Comparable[46]; heap[1] = 100; heap[2] = 100; heap[3] = 100; heap[6] = 100; heap[7] = 100; return heap; } // Full, not Complete because it has gaps on left side of bottom private static Comparable[] getNodesLeftGapV2(){ Comparable[] heap = new Comparable[38]; heap[1] = 10; heap[2] = 10; heap[3] = 20; heap[4] = 11; heap[5] = 50; heap[6] = 25; heap[7] = 30; heap[9] = 26; return heap; } // Complete + MaxHeap private static Comparable[] getNodesComplete(){ Comparable[] heap = new Comparable[32]; heap[1] = 100; heap[2] = 100; heap[3] = 100; heap[4] = 100; heap[5] = 100; heap[6] = 100; return heap; } // Full+Complete+MaxHeap private static Comparable[] getNodesCompleteV2(){ Comparable[] heap = new Comparable[32]; heap[1] = 100; heap[2] = 80; heap[3] = 90; heap[4] = 40; heap[5] = 60; heap[6] = 89; heap[7] = 70; heap[8] = 35; heap[9] = 30; return heap; } // Full+Perfect+Complete+MaxHeap private static Comparable[] getNodesMaxHeap1(){ Comparable[] heap = new Comparable[128]; int currentNumber = 100; for(int i = 1; i< 64; i++){ heap[i] = currentNumber--; } return heap; } // Full+Complete+MaxHeap private static Comparable[] getNodesMaxHeap2(){ Comparable[] heap = new Comparable[36]; heap[1] = 100; heap[2] = 80; heap[3] = 90; heap[4] = 80; heap[5] = 60; heap[6] = 89; heap[7] = 70; heap[8] = 10; heap[9] = 60; return heap; } // Complete+MaxHeap private static Comparable[] getNodesMaxHeap3(){ Comparable[] heap = new Comparable[35]; heap[1] = 100; heap[2] = 80; heap[3] = 90; heap[4] = 20; heap[5] = 60; heap[6] = 89; heap[7] = 70; heap[8] = 10; return heap; } // Complete+MaxHeap private static Comparable[] getNodesMaxHeap4(){ Comparable[] heap = new Comparable[16]; heap[1] = 100; heap[2] = 80; heap[3] = 90; heap[4] = 20; heap[5] = 60; heap[6] = 89; heap[7] = 70; return heap; } // Not Max Left side private static Comparable[] getNodesNotMaxHeap1(){ Comparable[] heap = new Comparable[50]; heap[1] = 100; heap[2] = 80; heap[4] = 60; heap[8] = 10; return heap; } // Not Max Right side private static Comparable[] getNodesNotMaxHeap2(){ Comparable[] heap = new Comparable[37]; heap[1] = 100; heap[3] = 80; heap[7] = 60; heap[15] = 10; return heap; } // Not Max gap left side private static Comparable[] getNodesNotMaxHeap3(){ Comparable[] heap = new Comparable[32]; heap[1] = 100; heap[2] = 80; heap[3] = 90; heap[4] = 80; heap[5] = 60; heap[6] = 89; heap[7] = 70; heap[9] = 10; return heap; } // Complete+MinHeap private static Comparable[] getNodesMinHeap1(){ Comparable[] heap = new Comparable[16]; for(int i = 1; i< 8; i++){ heap[i] = i; } return heap; } // Not Max Semi Heap private static Comparable[] getNodesNotMaxSemiHeap1(){ Comparable[] heap = new Comparable[32]; heap[1] = 100; heap[2] = 80; heap[3] = 90; heap[4] = 88; heap[5] = 60; heap[6] = 89; heap[7] = 70; heap[8] = 40; return heap; } //Min not a full tree- left node last child private static Comparable[] getNodesMinHeap2(){ Comparable[] heap = new Comparable[32]; heap[1] = 1; heap[2] = 8; heap[3] = 9; heap[4] = 80; heap[5] = 60; heap[6] = 89; heap[7] = 70; heap[8] = 100; heap[9] = 86; heap[10] = 70; return heap; } //Min not a full tree- right node last child private static Comparable[] getNodesMinHeap3(){ Comparable[] heap = new Comparable[32]; heap[1] = 1; heap[2] = 8; heap[3] = 9; heap[4] = 80; heap[5] = 60; heap[6] = 89; heap[7] = 70; heap[8] = 100; heap[9] = 86; return heap; } //Not min - left side only private static Comparable[] getNodesNotMinHeap1(){ Comparable[] heap = new Comparable[32]; heap[1] = 10; heap[2] = 10; heap[4] = 20; heap[8] = 40; return heap; } //Not min - right side only private static Comparable[] getNodesNotMinHeap2(){ Comparable[] heap = new Comparable[32]; heap[1] = 10; heap[3] = 10; heap[7] = 20; heap[15] = 40; return heap; } //Not min - wrong order private static Comparable[] getNodesNotMinHeap3(){ Comparable[] heap = new Comparable[32]; heap[1] = 20; heap[2] = 10; heap[3] = 20; heap[4] = 11; heap[5] = 50; heap[6] = 25; heap[7] = 30; heap[9] = 26; return heap; } }
package ru.ifmo.modeling; import Jama.Matrix; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.Function; public class SystemOfEquationsSolve { /** * 'functions' are constructing a system of equations as {f_1, ..., f_n} * And we solve the system: * f_1(...) = 0 * ... * f_n(...) = 0 */ private List<Function<List<Double>, Double>> functions; /** * 'derivatives' contains matrix of partial derivatives of 'functions', as * d(f_1)/d(1) d(f_1)/d(2) ... d(f_1)/d(n) -- derivatives.get(0) * d(f_2)/d(1) d(f_2)/d(2) ... d(f_2)/d(n) -- derivatives.get(1) * ... * d(f_n)/d(1) d(f_n)/d(2) ... d(f_n)/d(n) -- derivatives.get(size - 1) */ List<List<Function<List<Double>, Double>>> derivatives; public SystemOfEquationsSolve(List<Function<List<Double>, Double>> functions, List<List<Function<List<Double>, Double>>> derivatives) { this.functions = functions; this.derivatives = derivatives; } private double[][] substituteInDerivatives(List<Double> values) { double[][] res = new double[derivatives.size()][derivatives.size()]; for (int i = 0; i < derivatives.size(); ++i) { List<Function<List<Double>, Double>> funcs = derivatives.get(i); for (int j = 0; j < funcs.size(); ++j) { res[i][j] = funcs.get(j).apply(values); } } return res; } private double[] substituteInFunctions(List<Double> values) { double[] res = new double[functions.size()]; for (int i = 0; i < functions.size(); ++i) { res[i] = functions.get(i).apply(values); } return res; } private double getDistanceBetweenSolutions(List<Double> first, List<Double> second) { double sum = 0.0; for (int i = 0; i < first.size(); ++i) { sum += Math.pow(first.get(i) - second.get(i), 2); } return Math.sqrt(sum); } private double[][] inverse(double A[][]) { int n = A.length; int row[] = new int[n]; int col[] = new int[n]; double temp[] = new double[n]; int hold, I_pivot, J_pivot; double pivot, abs_pivot; if (A[0].length != n) { // inconsistent array sizes return null; } for (int k = 0; k < n; k++) { row[k] = k; col[k] = k; } for (int k = 0; k < n; k++) { pivot = A[row[k]][col[k]]; I_pivot = k; J_pivot = k; for (int i = k; i < n; i++) { for (int j = k; j < n; j++) { abs_pivot = Math.abs(pivot); if (Math.abs(A[row[i]][col[j]]) > abs_pivot) { I_pivot = i; J_pivot = j; pivot = A[row[i]][col[j]]; } } } if (Math.abs(pivot) < 1.0E-10) { // matrix is singular return null; } hold = row[k]; row[k] = row[I_pivot]; row[I_pivot] = hold; hold = col[k]; col[k] = col[J_pivot]; col[J_pivot] = hold; A[row[k]][col[k]] = 1.0 / pivot; for (int j = 0; j < n; j++) { if (j != k) { A[row[k]][col[j]] = A[row[k]][col[j]] * A[row[k]][col[k]]; } } for (int i = 0; i < n; i++) { if (k != i) { for (int j = 0; j < n; j++) { if (k != j) { A[row[i]][col[j]] = A[row[i]][col[j]] - A[row[i]][col[k]] * A[row[k]][col[j]]; } } A[row[i]][col[k]] = -A[row[i]][col[k]] * A[row[k]][col[k]]; } } } for (int j = 0; j < n; j++) { for (int i = 0; i < n; i++) { temp[col[i]] = A[row[i]][j]; } for (int i = 0; i < n; i++) { A[i][j] = temp[i]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { temp[row[j]] = A[i][col[j]]; } for (int j = 0; j < n; j++) { A[i][j] = temp[j]; } } return A; } /** * Newton method for solving a system of non-linear equations set with 'functions' * * @param initial * @param e * @param maxIteration * @return */ public List<Double> getSolution(List<Double> initial, double e, int maxIteration) { List<Double> solutionPrev = new ArrayList<>(initial.size()); List<Double> solution = new ArrayList<>(initial.size()); for (int i = 0; i < initial.size(); ++i) { solutionPrev.add(initial.get(i)); solution.add(initial.get(i)); } for (int i = 0; i < maxIteration; ++i) { Matrix x = (new Matrix(inverse(substituteInDerivatives(solution)))) .times(new Matrix(substituteInFunctions(solution), solution.size())); for (int j = 0; j < solution.size(); ++j) { solution.set(j, solution.get(j) - x.get(j, 0)); } if (getDistanceBetweenSolutions(solutionPrev, solution) < e) { break; } Collections.copy(solutionPrev, solution); } return solution; } }