text
stringlengths
10
2.72M
package com.example.ujianweb1.controller; import java.io.IOException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.example.ujianweb1.entity.Curiculum; import com.example.ujianweb1.repository.CuriculumRepository; import com.example.ujianweb1.service.CuriculumService; import com.example.ujianweb1.utility.FileUtility; @Controller public class CuriculumController { @Autowired CuriculumRepository curiculumRepository; @Autowired CuriculumService curiculumService; @GetMapping("/curiculum/view") public String viewIndexTraveller(Model model) { model.addAttribute("listCuriculum", curiculumRepository.findAll()); return "view_curiculumvitae"; } @GetMapping("/curiculum/add") public String viewAddTraveller(Model model) { // buat penampung data mahasiswa di halaman htmlnya model.addAttribute("curiculum",new Curiculum()); return "add_curiculum"; } @PostMapping("/curiculum/view") public String addCuriculum(@RequestParam(value = "file") MultipartFile file, @ModelAttribute Curiculum curiculum, Model model) throws IOException { String fileName = StringUtils.cleanPath(file.getOriginalFilename()); String uploadDir = "user-photos/" ; FileUtility.saveFile(uploadDir, fileName, file); curiculum.setFile_cv("/"+uploadDir + fileName); // buat penampung data curiculum di halaman htmlnya curiculumService.saveCuriculum(curiculum); model.addAttribute("listCuriculum",curiculumRepository.findAll()); return "view_curiculumvitae"; } }
package com.zyy.generate.custom; import com.zyy.generate.config.BeanConfig; import com.zyy.generate.core.Generate; import com.zyy.generate.util.StrUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; /** * @author yangyang.zhang * @date 2019年08月17日22:36:09 */ @Component public class DaoGenerate implements Generate { @Override public String getTemplateName() { return "dao.ftl"; } @Override public String getPackagePath(BeanConfig beanConfig) { return StrUtils.getPackagePath(beanConfig.getDaoPackage(), beanConfig); } @Override public String getName(BeanConfig beanConfig, String beanName) { return StringUtils.join(beanConfig.getDaoNamePre(), beanName, beanConfig.getDaoNameSuf()); } @Override public String getFileType() { return "java"; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.function.Predicate; class Condition <E> implements Predicate<String> //// class for filtration { @Override public boolean test(String str) //// overriding method for filtration { return str.length() < 5 && str.startsWith("a"); } } public class Task3 { public static void main (String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in) ); //// input defenition ArrayList<String> arrstr = new ArrayList<>(); //// array of words String whlstr = ""; //// whole input string while (true) //// reading from keyboard { String input = reader.readLine(); if (input.isEmpty()) break; ////arrstr.add(whlstr); whlstr += input; } ////System.out.println(whlstr); String[] words = whlstr.split("\\s"); //// adding words in the array for(String subStr:words) { arrstr.add(subStr); } Condition ofwords = new Condition(); arrstr.stream().filter(ofwords).forEach(System.out::println); //// filter and output of words } }
package polydungeons.block; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Material; import net.minecraft.block.MaterialColor; import net.minecraft.item.ItemStack; import net.minecraft.loot.context.LootContext; import net.minecraft.sound.BlockSoundGroup; import java.util.Arrays; import java.util.Collections; import java.util.List; public class HardenedBlock extends Block { public HardenedBlock() { super(Settings.of(Material.STONE, MaterialColor.RED) .requiresTool().strength(50.0F, 1200.0F) .sounds(BlockSoundGroup.NETHER_BRICKS)); } }
package com.example.world.config; import java.util.Set; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import com.example.world.dao.CountryDao; @Configuration @ComponentScan(basePackages = { "com.example.world.dao", "com.example.world.service" }, excludeFilters = { @Filter(type = FilterType.ANNOTATION, classes = { Service.class }) }) public class AppConfig { @Autowired private CountryDao countryDao; // SpEL: Spring Expression Language @Value("#{elma.getAllContinents()}") public Set<String> kitalar; @Value("#{ 2 + 2}") private int x; @Value("${os.name}") private String osName; @PostConstruct public void init() { System.err.println("Kitalar: " + kitalar); System.err.println("x=" + x); System.err.println("osName: " + osName); } @Bean("continents") @Scope("singleton") public Set<String> getContinents() { return countryDao.getAllContinents(); } }
package com.ifli.mbcp.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.math.BigDecimal; import java.util.Date; import java.util.Set; import java.util.TreeSet; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import com.ifli.mbcp.dao.LeadDAO; import com.ifli.mbcp.domain.AddressType; import com.ifli.mbcp.domain.BDMCode; import com.ifli.mbcp.domain.BMRMCode; import com.ifli.mbcp.domain.BranchCode; import com.ifli.mbcp.domain.Channel; import com.ifli.mbcp.domain.City; import com.ifli.mbcp.domain.CustomerAddress; import com.ifli.mbcp.domain.CustomerDetails; import com.ifli.mbcp.domain.IndividualProposal; import com.ifli.mbcp.domain.InsurancePlan; import com.ifli.mbcp.domain.Lead; import com.ifli.mbcp.domain.LeadCategory; import com.ifli.mbcp.domain.LeadGeneratorCode; import com.ifli.mbcp.domain.LeadStatus; import com.ifli.mbcp.domain.LeadType; import com.ifli.mbcp.domain.MaritalStatus; import com.ifli.mbcp.domain.PremiumFrequency; import com.ifli.mbcp.domain.Proposal; import com.ifli.mbcp.domain.Salutation; import com.ifli.mbcp.domain.State; import com.ifli.mbcp.service.impl.LeadServiceImpl; import com.ifli.mbcp.util.MBCPConstants; /** * * @author Niranjan * */ public class LeadServiceTest extends BaseMBCPTest { /** * @Mock Annotation will mock the instance of the given type (LeadDAOImpl in * our case) name = "leadDAO" here indicates the property name, which * is good to have as we are using property injection <a href= * "http://ahlearns.wordpress.com/2012/03/02/spring-3-autowired-unit-tests-with-mockito/" * >Reference </a> */ @Mock(name = "leadDAO") private LeadDAO leadDAO; /** * @InjectMock will inject all the @Mock annotated fields in this class to * the corresponding instance, LeadServiceImpl in our case */ @InjectMocks private LeadService leadService = new LeadServiceImpl(); /* * Test case specific fields */ private Lead lead; private CustomerDetails custDetails; private Salutation salutation; private MaritalStatus maritalStatus; private CustomerAddress address; private LeadCategory leadCategory; private LeadType leadType; private LeadStatus leadStatus; private BranchCode branchCode; private BDMCode bdmCode; private BMRMCode bmrmCode; private LeadGeneratorCode leadGeneratorCode; private Channel channel; @Before public void init() { populateLead(); /* * Define the Mock behavior for all the methods which are expected to be * invoked by Injected Mock i.e, LeadDAO in our case */ doReturn(1l).when(leadDAO).save(lead); doNothing().doThrow(new RuntimeException()).when(leadDAO).saveOrUpdate(lead); doNothing().doThrow(new RuntimeException()).when(leadDAO).update(lead); // This is one more flavor for mocking method behavior when(leadDAO.findById(Lead.class, (long) 1)).thenReturn(lead); } /** * A Lead instance is available with all the mandatory fields pre-populated, * which can be saved directly using the service, before execution of every * test method */ public void populateLead() { lead = new Lead(); custDetails = new CustomerDetails(); salutation = new Salutation(); salutation.setSalutationId((long) 1); custDetails.setSalutation(salutation); custDetails.setFirstName("Tom"); custDetails.setMiddleName("Dick"); custDetails.setLastName("Harry"); custDetails.setGender(MBCPConstants.MALE); custDetails.setMobileNumber("9856321457"); maritalStatus = new MaritalStatus(); maritalStatus.setId((long) 1); custDetails.setMaritalStatus(maritalStatus); address = new CustomerAddress(); address.setAddressLine1("#304, 306"); address.setAddressLine2("Bhau Patil Road, Pune IT Park"); address.setAddressLine3("Aundh"); AddressType addressType = new AddressType(); addressType.setId((long) 1); address.setAddressType(addressType); State state = new State(); state.setStateId((long) 1); address.setState(state); City city = new City(); city.setCityId((long) 1); address.setCity(city); address.setPinCode("506001"); Set<CustomerAddress> customerAddresses = new TreeSet<CustomerAddress>(); customerAddresses.add(address); custDetails.setCustomerAddress(customerAddresses); Set<Proposal> proposals = new TreeSet<Proposal>(); IndividualProposal p = new IndividualProposal(); proposals.add(p); InsurancePlan plan = new InsurancePlan(); plan.setId((long) 1); PremiumFrequency premiumFrequency = new PremiumFrequency(); premiumFrequency.setId((long) 1); p.setInsuranceProduct(plan); p.setPremiumAmount(BigDecimal.valueOf(50000d)); p.setPremiumFrequency(premiumFrequency); lead.setProposalsMade(proposals); leadCategory = new LeadCategory(); leadCategory.setId((long) 1); leadType = new LeadType(); leadType.setId((long) 1); leadStatus = new LeadStatus(); leadStatus.setId((long) 1); branchCode = new BranchCode(); branchCode.setId((long) 1); bdmCode = new BDMCode(); bdmCode.setId((long) 1); bmrmCode = new BMRMCode(); bmrmCode.setId((long) 1); leadGeneratorCode = new LeadGeneratorCode(); leadGeneratorCode.setId((long) 1); channel = new Channel(); channel.setId((long) 1); lead.setLeadCustomerDetails(custDetails); lead.setBdmCode(bdmCode); lead.setBmRmCode(bmrmCode); lead.setBranchCode(branchCode); lead.setChannelSelection(channel); lead.setLeadCategory(leadCategory); lead.setLeadGeneratorCode(leadGeneratorCode); lead.setLeadStatus(leadStatus); lead.setLeadType(leadType); lead.setCreatedDate(new Date()); lead.setModifiedDate(new Date()); } @Test public void testAddLead() throws Exception { printTitle(); // Just save the available Lead with the default data Long leadId = (Long) leadService.addLead(lead); assertNotNull("Lead not created", leadId); assertEquals(1l, leadId.longValue()); } @Test public void testUpdateLead() throws Exception { printTitle(); // add Comments lead.setComments("Hello, This is Service Unit test"); // Change the BranchCode BranchCode newBranchCode = new BranchCode(); newBranchCode.setId((long) 2); lead.setBranchCode(newBranchCode); leadService.updateLead(lead); /* * TODO Is this the right way to test void methods? I think so, just * checking whether the service pertaining DAO methods are executed as * many times as required will serve the purpose- Niranjan */ // verify(leadDAO, times(1)).saveOrUpdate(lead); verify(leadDAO, times(1)).update(lead); } @Test public void testGetLeadById() throws Exception { printTitle(); Lead l = leadService.getLeadByID(1l); assertEquals(l.getLeadCustomerDetails().getFirstName(), "Tom"); } }
package model; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import sun.print.DialogOwner; import java.util.ArrayList; import java.util.Observable; import java.util.zip.DeflaterOutputStream; public class Data { private static ArrayList<DownlaodFile> data_files_all = new ArrayList<>(); public static ArrayList<DownlaodFile> getFiles() { return data_files_all; } public static void setFiles(DownlaodFile file) { data_files_all.add(file); } public static ArrayList<DownlaodFile> finished_files() { ArrayList<DownlaodFile> finishe_files = new ArrayList<>(); for (DownlaodFile file : getFiles()) { if (file.getStatus_int() == 2) { finishe_files.add(file); } } return finishe_files; } public static ArrayList<DownlaodFile> failed_files() { ArrayList<DownlaodFile> faile_files = new ArrayList<>(); for (DownlaodFile file : getFiles()) { if (file.getStatus_int() == 3) { faile_files.add(file); } } return faile_files; } public static ObservableList list_all (){ ObservableList<DownlaodFile> filess = FXCollections.observableArrayList(getFiles()); filess.removeAll(FXCollections.observableArrayList(getFiles())); filess.addAll(FXCollections.observableArrayList(getFiles())); return filess; } public static ArrayList<DownlaodFile> paused_files() { ArrayList<DownlaodFile> pause_files = new ArrayList<>(); for (DownlaodFile file : getFiles()) { if (file.getStatus_int() == 3) { pause_files.add(file); } } return pause_files; } public static ArrayList<DownlaodFile> downloading_files() { ArrayList<DownlaodFile> downloadin_files = new ArrayList<DownlaodFile>(); for (DownlaodFile file : getFiles()) { if (file.getStatus_int() == 3) { downloadin_files.add(file); } } return downloadin_files; } public static ArrayList<DownlaodFile> mp3_files() { ArrayList<DownlaodFile> song_files = new ArrayList<>(); for (DownlaodFile file : Data.getFiles()) { if (file.getFile_type().equalsIgnoreCase("mp3")) { song_files.add(file); } } return song_files; } public static ArrayList<DownlaodFile> video_files() { ArrayList<DownlaodFile> movie_files = new ArrayList<>(); for (DownlaodFile file : Data.getFiles()) { if (file.getFile_type().equalsIgnoreCase("mp4") || file.getFile_type().equalsIgnoreCase("mkv")) { movie_files.add(file); } } return movie_files; } public static ArrayList<DownlaodFile> rar_files() { ArrayList<DownlaodFile> zip_files = new ArrayList<>(); for (DownlaodFile file : Data.getFiles()) { if (file.getFile_type().equalsIgnoreCase("rar") || file.getFile_type().equalsIgnoreCase("zip")) { zip_files.add(file); } } return zip_files; } public static ArrayList<DownlaodFile> document_files() { ArrayList<DownlaodFile> doc_files = new ArrayList<>(); for (DownlaodFile file : Data.getFiles()) { if (file.getFile_type().equalsIgnoreCase("pdf") || file.getFile_type().equalsIgnoreCase("doc") || file.getFile_type().equalsIgnoreCase("docx")) { doc_files.add(file); } } return doc_files; } public static ArrayList<DownlaodFile> program_files() { ArrayList<DownlaodFile> prog_files = new ArrayList<>(); for (DownlaodFile file : Data.getFiles()) { if (file.getFile_type().equalsIgnoreCase("exe") || file.getFile_type().equalsIgnoreCase("msi")) { prog_files.add(file); } } return prog_files; } public static double get_persent_search_by_url(String url) { for (DownlaodFile df : getFiles()) { if (df.getUrl().equalsIgnoreCase(url)) { return df.get_download_persent(); } } return -1; } }
package hib_1_1_eg; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; @Entity public class Software { @Id private int sid; private String sname; @OneToOne(mappedBy="software") @JoinColumn private Company company; public Software() {} public Software(int sid, String sname) { super(); this.sid = sid; this.sname = sname; } public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } @Override public String toString() { return "Software [sid=" + sid + ", sname=" + sname + ", company=" + company + "]"; } }
package com.tencent.mm.ui.chatting.b; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.chatting.b.b.g; import com.tencent.mm.ui.chatting.b.j.2; import com.tencent.mm.ui.chatting.i; class j$2$1 implements OnClickListener { final /* synthetic */ g tOT; final /* synthetic */ 2 tOU; final /* synthetic */ Context val$context; j$2$1(2 2, Context context, g gVar) { this.tOU = 2; this.val$context = context; this.tOT = gVar; } public final void onClick(DialogInterface dialogInterface, int i) { x.i("MicroMsg.ChattingMoreBtnBarHelper", "delete message"); i.a(this.val$context, this.tOT.ctL(), this.tOU.tOS); this.tOU.tOS.cuQ(); } }
package com.jscherrer.personal.deployment.spotinstance; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.RequestSpotInstancesRequest; import com.jscherrer.personal.testhelpers.AWSTestConstants; import com.jscherrer.personal.testhelpers.BaseAwsTester; import org.assertj.core.api.Assertions; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; public class SpotInstanceRequesterTest extends BaseAwsTester { private static final Logger LOG = LoggerFactory.getLogger(SpotInstanceRequesterTest.class); @BeforeClass public static void setUp() throws UnknownHostException { setupSecurityGroup(); } @Test public void instanceRequestCanCreateOneInstance() { RequestSpotInstancesRequest spotInstanceRequest = new RequestSpotInstancesRequest(); spotInstanceRequest.setSpotPrice("0.03"); int instanceCount = 1; spotInstanceRequest.setInstanceCount(instanceCount); makeRequestUsingInstanceRequest(spotInstanceRequest); Assertions.assertThat(instanceIds).hasSize(instanceCount); } @Test public void instanceRequestCanCreateTwoInstances() { RequestSpotInstancesRequest spotInstanceRequest = new RequestSpotInstancesRequest(); spotInstanceRequest.setSpotPrice("0.03"); int instanceCount = 2; spotInstanceRequest.setInstanceCount(instanceCount); makeRequestUsingInstanceRequest(spotInstanceRequest); Assertions.assertThat(instanceIds).hasSize(instanceCount); } @Test public void canDescribeOneInstance() { RequestSpotInstancesRequest spotInstanceRequest = new RequestSpotInstancesRequest(); spotInstanceRequest.setSpotPrice("0.03"); int instanceCount = 1; spotInstanceRequest.setInstanceCount(instanceCount); makeRequestUsingInstanceRequest(spotInstanceRequest); Assertions.assertThat(instanceIds).hasSize(instanceCount); List<Instance> instances = spotInstanceRequester.describeInstances(instanceIds); Assertions.assertThat(instances).hasSize(instanceCount); Assertions.assertThat(instances.get(0).getInstanceId()).isEqualTo(instanceIds.get(0)); } @Test public void canDescribeTwoInstances() { RequestSpotInstancesRequest spotInstanceRequest = new RequestSpotInstancesRequest(); spotInstanceRequest.setSpotPrice("0.03"); int instanceCount = 2; spotInstanceRequest.setInstanceCount(instanceCount); makeRequestUsingInstanceRequest(spotInstanceRequest); Assertions.assertThat(instanceIds).hasSize(instanceCount); List<Instance> instances = spotInstanceRequester.describeInstances(instanceIds); Assertions.assertThat(instances).hasSize(instanceCount); Assertions.assertThat(instances) .extracting(Instance::getInstanceId) .containsExactlyInAnyOrderElementsOf(instanceIds); } private void makeRequestUsingInstanceRequest(RequestSpotInstancesRequest spotInstanceRequest) { ArrayList<String> testSecurityGroups = new ArrayList<>(); testSecurityGroups.add(AWSTestConstants.SECURITY_GROUP_NAME); requestIds = spotInstanceRequester.makeSpotRequest(spotInstanceRequest, testSecurityGroups); spotInstanceRequester.waitForActiveInstances(requestIds); instanceIds = spotInstanceRequester.getInstanceIds(requestIds); for (String instanceId : instanceIds) { LOG.info("instanceId: " + instanceId); } } }
package com.tencent.mm.plugin.webview.ui.tools.bag; import android.os.Bundle; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.ScaleAnimation; import com.tencent.mm.compatible.f.b; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.sdk.platformtools.ac; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.aa.a; import org.json.JSONObject; public enum j { ; private long ngz; private WebViewBag qcn; public String qco; private a qcp; public boolean qcq; public a qcr; private j(String str) { this.ngz = -1; this.qcr = new a(); } public final void nc(boolean z) { x.i("MicroMsg.WebViewBagMgr", "checkResumeBag mInWebViewUIFromBag:%b", new Object[]{Boolean.valueOf(this.qcq)}); if (bi.oW(this.qcr.url) || this.qcq) { bVg(); x.i("MicroMsg.WebViewBagMgr", "checkResumeBag hide bag"); } else if (this.qcn == null || this.qcn.getVisibility() != 0) { nd(z); x.i("MicroMsg.WebViewBagMgr", "checkResumeBag show bag"); } else { x.i("MicroMsg.WebViewBagMgr", "already show"); } } public final void bWU() { x.i("MicroMsg.WebViewBagMgr", "clearBag mCurrentUrl:%s", new Object[]{this.qcr.url}); bVg(); a aVar = this.qcr; aVar.url = null; aVar.bWP = null; aVar.dRk = 0; aVar.scene = 0; aVar.uec = new JSONObject(); aVar.save(); cKK(); } final void nd(boolean z) { x.i("MicroMsg.WebViewBagMgr", "showBag url:%s", new Object[]{this.qcr.url}); if (!b.bv(ad.getContext())) { x.w("MicroMsg.WebViewBagMgr", "showBag: no float window permission"); } else if (bi.oW(this.qcr.url)) { bWU(); } else { boolean z2 = this.qcn == null; if (this.qcn == null) { this.qcp = new a(new 2(this)); this.qcn = new WebViewBag(ad.getContext(), null); this.qcn.setListener(new 3(this)); this.qcn.setOnClickListener(new 4(this)); } aK(1.0f); this.qcn.setTouchEnable(true); this.qcn.setIcon(this.qcr.bWP); bWW(); this.qco = ac.ce(String.format("bagId#%d#%s", new Object[]{Long.valueOf(System.currentTimeMillis()), this.qcr.url})); x.i("MicroMsg.WebViewBagMgr", "bag showed needAttach:%b mCurrentBagId:%s", new Object[]{Boolean.valueOf(z2), this.qco}); if (z2) { if (z) { this.qcn.setVisibility(4); cKJ(); this.qcn.setVisibility(0); this.qcn.bWT(); return; } cKJ(); } else if (this.qcn.getVisibility() != 0) { this.qcn.setVisibility(0); if (z) { this.qcn.bWT(); } } else { x.i("MicroMsg.WebViewBagMgr", "already showed"); } } } public final void bWV() { x.i("MicroMsg.WebViewBagMgr", "removeBag"); if (this.qcn != null) { WebViewBag webViewBag = this.qcn; 5 5 = new 5(this); Animation alphaAnimation = new AlphaAnimation(1.0f, 0.0f); Animation scaleAnimation = new ScaleAnimation(1.0f, 0.0f, 1.0f, 0.0f, 1, 0.5f, 1, 0.5f); Animation animationSet = new AnimationSet(true); animationSet.addAnimation(alphaAnimation); animationSet.addAnimation(scaleAnimation); animationSet.setDuration(80); animationSet.restrictDuration(100); animationSet.setAnimationListener(5); animationSet.setFillAfter(true); webViewBag.ido.startAnimation(animationSet); } } public final void bVg() { if (this.qcn != null) { this.qcn.setVisibility(8); } } public final void aK(float f) { if (this.qcn != null) { this.qcn.setAlpha(f); if (f == 0.0f) { this.qcn.setVisibility(8); } else { this.qcn.setVisibility(0); } } } final void a(String str, int i, String str2, Bundle bundle) { this.qcr.url = str; this.qcr.bWP = str2; this.qcr.scene = i; this.qcr.dRk = bi.VF(); this.qcr.uec = n.an(bundle); this.qcr.save(); } private void cKJ() { x.i("MicroMsg.WebViewBagMgr", "attachBag"); WindowManager windowManager = (WindowManager) ad.getContext().getSystemService("window"); LayoutParams layoutParams = new WindowManager.LayoutParams(); layoutParams.type = 2002; layoutParams.format = 1; layoutParams.packageName = ad.getContext().getPackageName(); layoutParams.flags = 40; layoutParams.gravity = 51; layoutParams.width = b.qbm; layoutParams.height = b.qbm; layoutParams.x = this.qcr.qcw; layoutParams.y = this.qcr.qcv; try { windowManager.addView(this.qcn, layoutParams); bWW(); } catch (Exception e) { x.e("MicroMsg.WebViewBagMgr", "add failed %s", new Object[]{e}); } } private void cKK() { x.i("MicroMsg.WebViewBagMgr", "unAttachBag"); if (this.qcn != null) { try { ((WindowManager) ad.getContext().getSystemService("window")).removeView(this.qcn); } catch (Exception e) { x.e("MicroMsg.WebViewBagMgr", "remove failed %s", new Object[]{e}); } this.qcn = null; } else { x.e("MicroMsg.WebViewBagMgr", "unAttachBag mBag null"); } if (this.qcp != null) { try { ((WindowManager) ad.getContext().getSystemService("window")).removeView(this.qcp.qba); } catch (Exception e2) { x.e("MicroMsg.BagCancelController", "whenBagUnAttach remove failed %s", new Object[]{e2}); } this.qcp = null; } } private void bWW() { x.i("MicroMsg.WebViewBagMgr", "setAngryInfo mBagInfo.lastActiveTime:%d", new Object[]{Long.valueOf(this.qcr.dRk)}); if ("1".equals((String) g.Ei().DT().get(a.tab, "0"))) { this.qcn.j(60000, 100, this.qcr.dRk + 2000); } else { this.qcn.j(3600000, 30000, this.qcr.dRk + 3600000); } } private void AR(int i) { x.v("MicroMsg.WebViewBagMgr", "kvReport op:%d", new Object[]{Integer.valueOf(i)}); h.mEJ.h(11576, new Object[]{this.qcr.url, Integer.valueOf(i), Integer.valueOf(0), Long.valueOf(System.currentTimeMillis() - this.qcr.dRk)}); } }
package com.test; import com.test.domain.User; import com.test.mapper.UserMapper; import com.test.sqlsession.SimpleSqlSession; /** * @author wyj * @date 2018/10/20 */ public class SimpleMyBatisTest { public static void main(String[] args) { SimpleSqlSession simpleSqlSession = new SimpleSqlSession(); UserMapper userMapper = simpleSqlSession.getMapper(UserMapper.class); User user = userMapper.getUserByPrimaryKey(1); System.out.println(user); } }
package com.unitbv.labs.tema2springboot; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.unitbv.labs.tema2springboot.dao.PersonDAO; import com.unitbv.labs.tema2springboot.entities.Person; @RestController public class PersonController { @GetMapping("/people/get/{id}") public Person getPerson(@PathVariable int id) throws Exception { PersonDAO personDAO = new PersonDAO(); Person person = personDAO.findById(id); if (person == null) { throw new Exception("Person not found for id " + id); } return person; } @DeleteMapping("/people/delete/{id}") public ResponseEntity<Object> deletePerson(@PathVariable int id) { PersonDAO personDAO = new PersonDAO(); Person person = personDAO.findById(id); if (person == null) { return ResponseEntity.notFound().build(); } personDAO.delete(person); return ResponseEntity.noContent().build(); } @PostMapping("/people/add") public void createPerson(@RequestBody Person person) { PersonDAO personDAO = new PersonDAO(); personDAO.createOrUpdate(person); } @PutMapping("/people/update/{id}") public ResponseEntity<Object> updatePerson(@RequestBody Person person, @PathVariable int id) { PersonDAO personDAO = new PersonDAO(); Person foundPerson = personDAO.findById(id); if (foundPerson == null) { return ResponseEntity.notFound().build(); } person.setId(id); personDAO.update(person); return ResponseEntity.noContent().build(); } }
package lnyswz.oa.dao.impl; import java.util.List; import lnyswz.oa.bean.User; import lnyswz.oa.dao.UserDAO; import lnyswz.oa.utils.AbstractPagerManager; import lnyswz.oa.utils.PagerModel; public class UserDAOImpl extends AbstractPagerManager implements UserDAO { public void addUser(User user) { this.getHibernateTemplate().save(user); } public void deleteUser(int userId) { this.getHibernateTemplate().delete(this.getHibernateTemplate().load(User.class, userId)); } public void modifyUser(User user) { this.getHibernateTemplate().update(user); } public User findUser(int userId) { return (User)this.getHibernateTemplate().load(User.class, userId); } public User findUserByName(String username) { List<User> users = this.getHibernateTemplate().find("from User u where u.name = ?", username); if(users.size() == 1){ return users.get(0); } //User user = (User)this.getSession().createCriteria(User.class).add(Expression.eq("name", username)).uniqueResult(); return null; } public PagerModel findUsers() { return this.searchPaginated("from UserInfo"); } }
package com.trainex.fragment.insignup; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.trainex.R; import com.trainex.uis.login_signup.SignUpActivity; public class TermsFragment extends Fragment { private ImageView imgTermsBack; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_terms, container,false); imgTermsBack = (ImageView) view.findViewById(R.id.imgTermsBack); imgTermsBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SignUpActivity.backToSignUp(); } }); return view; } }
package com.example.bhavana.energysaverapp; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.os.Build; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.example.bhavana.energysaverapp.Model.Profile; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import javax.net.ssl.HttpsURLConnection; public class MainActivity extends ActionBarActivity { public static Profile profile; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final String mainMenuItems[] = { "My Profile", //"Add Bill", "Scan Bar Code", "Get Bill from Site", "Show Usage Statistics", "Solutions" //"View Carbon Footprints" }; ArrayAdapter<String> myArrayAdapter = new ArrayAdapter<String>( getActivity(), R.layout.list_item_layout, R.id.list_item_menu_item, mainMenuItems); final View rootView = inflater.inflate(R.layout.fragment_main, container, false); ListView myListView = (ListView) rootView.findViewById(R.id.listView_menu); myListView.setAdapter(myArrayAdapter); //final PlaceholderFragment currentView = this; myListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String itemText = (String) ((TextView) view).getText(); if(mainMenuItems[0].equalsIgnoreCase(itemText)) { Intent i = new Intent(view.getContext(), ProfileActivity.class); startActivity(i); } // Redirect to BarCode Scanner App else if(mainMenuItems[1].equalsIgnoreCase(itemText)) { IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity()); scanIntegrator.initiateScan(); } // Redirect to a website else if(mainMenuItems[2].equalsIgnoreCase(itemText)) { Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")); startActivity(i); } else if(mainMenuItems[3].equalsIgnoreCase(itemText)) { Intent i = new Intent(view.getContext(), StatisticsActivity.class); startActivity(i); } else if(mainMenuItems[4].equalsIgnoreCase(itemText)) { Intent i = new Intent(view.getContext(), SolutionsActivity.class); startActivity(i); } /*else if (mainMenuItems[5].equalsIgnoreCase(itemText)) { // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String coolClimateAPIJsonStr = null; // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast //URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7"); String zipcode = MainActivity.profile.getPostalCode(); if (zipcode == null || zipcode.length() == 0) { Toast successToast = Toast.makeText(view.getContext(), "Please enter Zipcode in Profile!", Toast.LENGTH_SHORT); successToast.show(); return; } try { URL url = new URL("https://apis.berkeley.edu:443/coolclimate/footprint-defaults?input_location=" + zipcode + "&input_income=1&input_location_mode=1&input_size=0"); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); // String userCredentials = "username:password"; //String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes())); urlConnection.setRequestProperty("App_id", "1c59b0f9"); urlConnection.setRequestProperty("App_key", "d85b07f8673cb00694d6eab51fe3dd16"); // urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //urlConnection.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length)); //urlConnection.setRequestProperty("Content-Language", "en-US"); urlConnection.setUseCaches(false); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return; } coolClimateAPIJsonStr = buffer.toString(); } catch (IOException e) { Log.e("PlaceholderFragment", "Error ", e); // If the code didn't successfully get the weather data, there's no point in attemping // to parse it. return; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e("PlaceholderFragment", "Error closing stream", e); } } } }*/ } public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == 0) { if (resultCode == RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); String format = intent.getStringExtra("SCAN_RESULT_FORMAT"); // Handle successful scan Toast myToast = new Toast(getActivity()); myToast.setText("contents:" + contents + "|format:" + format); myToast.show(); } else if (resultCode == RESULT_CANCELED) { // Handle cancel } } }; }); return rootView; } } }
package mainGame; import org.newdawn.slick.Animation; import org.newdawn.slick.Graphics; import asset.AnimationManager; public class BreakerAnimation { private boolean ready = false; private boolean update = false; private int tick = 0; private Animation animation; private int maxTick = 100; public BreakerAnimation() { this.animation = AnimationManager.loadAnimation("texture/breakingAnimation.png", 64, 64, 0, 10, 0,1); } public void resetbar() { this.tick = 0; this.ready = false; } public void Draw(Graphics g,int x, int y) { if(this.update) { int imageindex = (int)Math.floor(this.tick/(maxTick/10)); if(!(imageindex > 9)) { g.drawImage(this.animation.getImage(imageindex),x,y); } } } public void update() { if(this.update) { tick++; if(this.tick > maxTick) { this.tick = 0; this.ready = true; } } } public boolean isReady() { return ready; } public void setReady(boolean ready) { this.ready = ready; } public boolean isUpdate() { return update; } public void setUpdate(boolean update) { this.update = update; } public int getMaxTick() { return maxTick; } public void setMaxTick(int maxTick) { this.maxTick = maxTick; } public Animation getAnimation() { return animation; } public int getTick() { return this.tick; } public void setTick(int tick) { this.tick = tick; } public void setAnimation(Animation animation) { this.animation = animation; } }
package de.markory.macgamble.web.rest; import java.util.Date; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.markory.macgamble.web.rest.data.Bet; import de.markory.macgamble.web.rest.data.BetData; import de.markory.macgamble.web.rest.data.Participant; @Path("/bet") public class BetRestService { @GET @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON }) public BetData getBet() { BetData betData = new BetData(); Participant philipp = new Participant(); Participant ramona = new Participant(); ramona.setName("Ramona"); philipp.setName("Philipp"); betData.setBettingDebt("100€"); betData.setName("My first bet!"); betData.setDescription("I bet i can fly!"); betData.setDateOfBet(new Date()); Bet bet1 = new Bet(); bet1.setDescription("Ich wette ich kann fliegen!"); bet1.addParticipants(ramona); bet1.addParticipants(philipp); Bet bet2 = new Bet(); bet2.setDescription("Ich wette er kann nicht fliegen!"); bet2.addParticipants(ramona); bet2.addParticipants(philipp); betData.addBet(bet1); betData.addBet(bet2); return betData; } }
package com.joy.http; import android.content.Context; import com.joy.http.qyer.QyerReqFactory; import com.joy.http.volley.Request; import com.joy.http.volley.RequestLauncher; import com.joy.http.volley.VolleyLog; import com.joy.http.volley.toolbox.Volley; import java.util.Map; /** * Created by Daisw on 16/9/8. */ public class JoyHttp { private static volatile RequestLauncher mLauncher; private static final int DEFAULT_TIMEOUT_MS = 10 * 1000; private static final int DEFAULT_MAX_RETRIES = 0; private static int mTimeoutMs = DEFAULT_TIMEOUT_MS; private static int mRetryCount = DEFAULT_MAX_RETRIES; private JoyHttp() { } public static void initialize(Context appContext, boolean debug) { if (mLauncher == null) { synchronized (JoyHttp.class) { if (mLauncher == null) { VolleyLog.DEBUG = debug; mLauncher = Volley.newLauncher(appContext); // mLauncher.addRequestFinishedListener(mReqFinishLis); } } } } public static void initialize(Context appContext, Map<String, String> defaultParams, boolean debug) { QyerReqFactory.setDefaultParams(defaultParams); initialize(appContext, debug); } public static void shutDown() { if (mLauncher != null) { // mLauncher.removeRequestFinishedListener(mReqFinishLis); mLauncher.abortAll(); mLauncher.stop(); mLauncher = null; } QyerReqFactory.clearDefaultParams(); } public static RequestLauncher getLauncher() { return mLauncher; } // private static RequestQueue.RequestFinishedListener mReqFinishLis = request -> { // if (VolleyLog.DEBUG) { // VolleyLog.d("~~Global monitor # request finished. tag: %s, sequence number: %d", request.getTag(), request.getSequence()); // } // }; public static void setTimeoutMs(int timeoutMs) { mTimeoutMs = timeoutMs; } public static int getTimeoutMs() { return mTimeoutMs; } public static void setRetryCount(int retryCount) { mRetryCount = retryCount; } public static int getRetryCount() { return mRetryCount; } public static boolean isRequestLaunched(Object tag) { return mLauncher != null && mLauncher.isLaunched(tag); } /** * Cancels all requests in this queue for which the given filter applies. * * @param filter The filtering function to use */ public static void abort(RequestLauncher.RequestFilter filter) { if (mLauncher != null) { mLauncher.abort(filter); } } /** * Cancels all requests in this queue with the given tag. Tag must be non-null * and equality is by identity. */ public static void abort(Object tag) { if (mLauncher != null) { mLauncher.abort(tag); } } public static void abortAll() { if (mLauncher != null) { mLauncher.abortAll(); } } public static void abort(Request<?> request) { if (mLauncher != null) { mLauncher.abort(request); } } }
package com.deltastuido.message; import java.util.Collection; public class MiuMail { public MiuMail(String title, String content, String title2, String content2) { // TODO Auto-generated constructor stub } public MiuMail(String sender, Collection<String> receivers, String title, String content) { // TODO Auto-generated constructor stub } }
package com.example.healthmanage.ui.activity.memberinfo; import androidx.lifecycle.MutableLiveData; import com.example.healthmanage.base.BaseApplication; import com.example.healthmanage.base.BaseViewModel; import com.example.healthmanage.bean.network.response.MemberInfoResponse; import com.example.healthmanage.bean.UsersInterface; import com.example.healthmanage.bean.UsersRemoteSource; import com.example.healthmanage.data.network.exception.ExceptionHandle; import com.example.healthmanage.utils.ToolUtil; import com.example.healthmanage.bean.recyclerview.DataItem; import java.util.ArrayList; import java.util.List; public class MemberInfoViewModel extends BaseViewModel { public MutableLiveData<String> memberName = new MutableLiveData<>(""); public MutableLiveData<String> memberPhone = new MutableLiveData<>(""); public MutableLiveData<String> memberAvatar = new MutableLiveData<>(""); String[] name = {"姓名:", "性别:", "年龄:", "联系电话:", "出生年月:", "所在城市:", "上次登录时间", "其他:", "预留:"}; UsersRemoteSource usersRemoteSource = new UsersRemoteSource(); public MutableLiveData<List<DataItem>> dataItemMutableLiveData = new MutableLiveData<>(); private List<DataItem> dataItemList; private List<String> data; public void getMemberInfo(long memberId) { usersRemoteSource.getMemberInfo(memberId, BaseApplication.getToken(), new UsersInterface.GetMemberInfoCallback() { @Override public void getSucceed(MemberInfoResponse memberInfoResponse) { data = new ArrayList<>(); dataItemList = new ArrayList<>(); data.add(ToolUtil.isNull(memberInfoResponse.getData().getNickName())); data.add(ToolUtil.isNull(memberInfoResponse.getData().getSex() == 0 ? "男" : "女")); data.add(ToolUtil.isNull("20")); data.add(ToolUtil.isNull(memberInfoResponse.getData().getPhone())); data.add(ToolUtil.isNull(memberInfoResponse.getData().getBirthday())); data.add(ToolUtil.isNull(memberInfoResponse.getData().getCityName())); data.add(ToolUtil.isNull(memberInfoResponse.getData().getLastLoginTime())); data.add(ToolUtil.isNull("暂无其他")); data.add(ToolUtil.isNull("暂无预留")); dataItemList.add(new DataItem(name, data)); dataItemMutableLiveData.setValue(dataItemList); } @Override public void getFailed(String msg) { } @Override public void error(ExceptionHandle.ResponseException e) { } }); } }
package org.newdawn.slick.tests; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame; import org.newdawn.slick.Color; import org.newdawn.slick.Game; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import org.newdawn.slick.geom.Polygon; import org.newdawn.slick.geom.Rectangle; import org.newdawn.slick.geom.Shape; import org.newdawn.slick.geom.ShapeRenderer; import org.newdawn.slick.geom.TexCoordGenerator; import org.newdawn.slick.geom.Vector2f; public class TexturePaintTest extends BasicGame { private Polygon poly = new Polygon(); private Image image; private Rectangle texRect = new Rectangle(50.0F, 50.0F, 100.0F, 100.0F); private TexCoordGenerator texPaint; public TexturePaintTest() { super("Texture Paint Test"); } public void init(GameContainer container) throws SlickException { this.poly.addPoint(120.0F, 120.0F); this.poly.addPoint(420.0F, 100.0F); this.poly.addPoint(620.0F, 420.0F); this.poly.addPoint(300.0F, 320.0F); this.image = new Image("testdata/rocks.png"); this.texPaint = new TexCoordGenerator() { public Vector2f getCoordFor(float x, float y) { float tx = (TexturePaintTest.this.texRect.getX() - x) / TexturePaintTest.this.texRect.getWidth(); float ty = (TexturePaintTest.this.texRect.getY() - y) / TexturePaintTest.this.texRect.getHeight(); return new Vector2f(tx, ty); } }; } public void update(GameContainer container, int delta) throws SlickException {} public void render(GameContainer container, Graphics g) throws SlickException { g.setColor(Color.white); g.texture((Shape)this.poly, this.image); ShapeRenderer.texture((Shape)this.poly, this.image, this.texPaint); } public static void main(String[] argv) { try { AppGameContainer container = new AppGameContainer((Game)new TexturePaintTest()); container.setDisplayMode(800, 600, false); container.start(); } catch (SlickException e) { e.printStackTrace(); } } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\tests\TexturePaintTest.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.example.android.newsapp.data; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteAbortException; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.List; public class NewsTableDb { private static final String TAG = NewsTableDb.class.getSimpleName(); private SQLiteDatabase database; public NewsTableDb(Context context) { database = new NewsDbHelper(context).getWritableDatabase(); } /* Perform a select all query on news table and return the cursor */ public Cursor selectAll() { if (database == null) { throw new SQLiteAbortException("Database is close"); } return database.query( NewsContract.NewsEntry.TABLE_NAME, null, null, null, null, null, null ); } public void close() { if (database != null) { database.close(); } } /* Delete all news rows and replace it with the latest results */ public void updateNewsItems(List<ContentValues> newData) { if (database == null) { throw new SQLiteAbortException("Database is closed"); } deleteAllNews(); bulkInsert(newData); } /* Check the "news" table if it is empty.*/ public boolean isTableEmpty() { Cursor cursor = database.query( NewsContract.NewsEntry.TABLE_NAME, null, null, null, null, null, null); return !cursor.moveToFirst() || cursor.getCount() == 0; } /* Delete all the rows of News table and Log the number of rows deleted, should be 10! */ private void deleteAllNews() { // Passing null will delete the table, passing 1 will delete all rows of the table String selection = "1"; String[] whereArgs = null; int rowsDeleted = database.delete(NewsContract.NewsEntry.TABLE_NAME, selection, whereArgs); Log.d(TAG, "deleteAllNews() - rows deleted: " + rowsDeleted); } /* Insert the data in SQLite as a bulk and log the number of rows inserted (should be 10). */ private void bulkInsert(List<ContentValues> data) { database.beginTransaction(); try { int rowsInserted = 0; for (ContentValues cv : data) { long _id = database.insert(NewsContract.NewsEntry.TABLE_NAME, null, cv); if (_id != -1) { rowsInserted++; } } Log.d(TAG, "bulkInsert() - rows inserted: " + rowsInserted); database.setTransactionSuccessful(); } finally { database.endTransaction(); } } }
package by.epam.concexamples.synchronizer.cyclicbarier; import java.util.concurrent.CyclicBarrier; /** * Created by Alex on 21.10.2016. * * Из-за аварии на трассе появилась машина безопасности. Гонщики должны сбавить скорость и следовать за ней, * до того как уберут все следы аварии. После этого гонка возобновится когда гонщики займут места * на стартовой решетке и машина безопасности покинет трассу. */ public class Runner { private final static int NUMBER_OF_CARS = 5; private static final CyclicBarrier BARRIER = new CyclicBarrier(NUMBER_OF_CARS, new Race()); public static void main(String[] args) { Car[] cars = new Car[NUMBER_OF_CARS]; cars[0] = new Car("Fernando Alonso", BARRIER); cars[1] = new Car("Kimi Raikkonen", BARRIER); cars[2] = new Car("Lewis Hamilton", BARRIER); cars[3] = new Car("Nico Rosberg", BARRIER); cars[4] = new Car("Sebastian Vettel", BARRIER); for (Car _car : cars){ _car.start(); } } }
package com.polsl.edziennik.desktopclient.view.teacher.panels; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import com.polsl.edziennik.desktopclient.controller.utils.factory.GuiComponentFactory; import com.polsl.edziennik.desktopclient.controller.utils.factory.IGuiComponentAbstractFactory; import com.polsl.edziennik.desktopclient.controller.utils.factory.interfaces.ILabel; import com.polsl.edziennik.modelDTO.person.TeacherDTO; public class TeacherSimplePreviewPanel extends JPanel { public static final int TEXT_SIZE = 30; protected JLabel name; protected JLabel lastName; protected JLabel academicTitle; protected JLabel room; protected JLabel email; protected JLabel exercises; protected JTextField nameText; protected JTextField secondNameText; protected JTextField lastNameText; protected JTextField emailText; protected JTextField academicTitleText; protected JTextField roomText; protected CellConstraints cc; protected TeacherDTO currentTeacher; protected IGuiComponentAbstractFactory factory = GuiComponentFactory.getInstance(); protected ILabel label; public TeacherSimplePreviewPanel(String title) { setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(title), BorderFactory.createEmptyBorder(0, 6, 6, 6))); FormLayout layout = new FormLayout( "pref,4dlu, 100dlu, 4dlu, min", "pref, 2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref"); setLayout(layout); label = factory.createLabel(); create(); setComponents(); setEnabled(false); setEditable(false); } public void setComponents() { cc = new CellConstraints(); add(academicTitle, cc.xy(1, 3)); add(academicTitleText, cc.xy(3, 3)); add(name, cc.xy(1, 5)); add(nameText, cc.xy(3, 5)); add(lastName, cc.xy(1, 7)); add(lastNameText, cc.xy(3, 7)); add(email, cc.xy(1, 9)); add(emailText, cc.xy(3, 9)); add(room, cc.xy(1, 11)); add(roomText, cc.xy(3, 11)); } public void clear() { nameText.setText(""); lastNameText.setText(""); academicTitleText.setText(""); roomText.setText(""); emailText.setText(""); } @Override public void setEnabled(boolean b) { nameText.setEnabled(b); lastNameText.setEnabled(b); academicTitleText.setEnabled(b); emailText.setEnabled(b); roomText.setEnabled(b); } public void setEditable(boolean b) { nameText.setEditable(b); lastNameText.setEditable(b); academicTitleText.setEditable(b); emailText.setEditable(b); roomText.setEditable(b); } public void create() { name = label.getLabel("name"); lastName = label.getLabel("lastName"); email = label.getLabel("email"); academicTitle = label.getLabel("academicTitle"); room = label.getLabel("room"); nameText = new JTextField(TEXT_SIZE); lastNameText = new JTextField(TEXT_SIZE); emailText = new JTextField(TEXT_SIZE); academicTitleText = new JTextField(TEXT_SIZE); roomText = new JTextField(TEXT_SIZE); } public void setData(TeacherDTO t) { clear(); if (t != null) { nameText.setText(t.getFirstName()); lastNameText.setText(t.getLastName()); emailText.setText(t.getEmail()); academicTitleText.setText(t.getAcademicTitle()); roomText.setText(t.getRoom()); } currentTeacher = t; } public void setCurrentTeacher() { currentTeacher.setAcademicTitle(academicTitleText.getText()); currentTeacher.setFirstName(nameText.getText()); currentTeacher.setLastName(lastNameText.getText()); currentTeacher.setEmail(emailText.getText()); currentTeacher.setRoom(roomText.getText()); } @Override public void disable() { clear(); setEnabled(false); } }
package com.tencent.tencentmap.mapsdk.a; public interface tt { void a(); void b(); }
package littleservantmod.profession; import java.util.Map; import com.google.common.collect.Maps; import littleservantmod.api.IServant; import littleservantmod.api.LittleServantModAPI; import littleservantmod.api.profession.behavior.IBehavior; import littleservantmod.api.profession.mode.IMode; import littleservantmod.entity.ai.EntityAIFollow; import littleservantmod.entity.ai.EntityAIWanderAvoidWater; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.passive.EntityRabbit; import net.minecraft.util.ResourceLocation; /** 無職 */ public class ProfessionUnemployed extends ProfessionLSMBase { public IMode modeBasic; public IBehavior behaviorBasic; public ProfessionUnemployed() { //Mode this.modeBasic = LittleServantModAPI.professionManager.getBasicMode(); //Behavior this.behaviorBasic = LittleServantModAPI.professionManager.getBasicBehavior(); } @Override public void initAI(IServant servant) { super.initAI(servant); //うさぎについていく servant.addAI(500, new EntityAIFollow(servant.getEntityInstance(), EntityRabbit.class, 0.5D)); //ウロウロ servant.addAI(800, new EntityAIWanderAvoidWater(servant.getEntityInstance(), 0.5D)); //うさぎを見る servant.addAI(900, new EntityAIWatchClosest(servant.getEntityInstance(), EntityRabbit.class, 4.0F)); } @Override public boolean isEnableProfession(IServant servant) { return servant.getOwner() == null; } @Override public Map<ResourceLocation, IMode> initModes(IServant servant) { Map<ResourceLocation, IMode> map = Maps.newLinkedHashMap(); map.put(LittleServantModAPI.professionManager.getBasicModeKey(), this.modeBasic); return map; } @Override public Map<ResourceLocation, IBehavior> initBehavior(IServant servant) { Map<ResourceLocation, IBehavior> map = Maps.newLinkedHashMap(); map.put(LittleServantModAPI.professionManager.getBasicBehaviorKey(), behaviorBasic); return map; } @Override public IMode getDefaultMode(IServant servant) { return this.modeBasic; } @Override public IBehavior getDefaultBehavior(IServant servant) { return this.behaviorBasic; } }
public class Main { public static void main(String[] args) { Person p = new Person(); p.name = "Elona"; p.age = 22; p.job ="Teacher"; Person p2 = new Person(); p2.name = "Enanna"; p2.age = 20; p2.job ="Teacher"; p.friend= p2; Car c = new Car(); c.year = 1995; c.brand = "Volvo"; //c.brand = "Toyota"; p2.car = c; p.car = c; //p2.car.brand = "Nissan"; System.out.println(p.name+ " heter jag"); System.out.println("Min vän heter "+p.friend.name); System.out.println("Min bil är en "+p.car.brand); } }
package schr0.tanpopo.api; import javax.annotation.Nullable; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; public abstract class EssenceCauldronCraft { public abstract Item getKeyItem(); @Nullable public abstract ItemStack getResultStack(ItemStack stackKeyItem); public int getEssenceCost(ItemStack stackKeyItem) { return 1; } public int getStackCost(ItemStack stackKeyItem) { return 1; } public int getTickTime(ItemStack stackKeyItem) { return (1 * 20); } }
package com.qswy.app.activity.forum; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.qswy.app.R; import com.qswy.app.activity.BaseActivity; import com.qswy.app.adapter.MyPostAdapter; import com.qswy.app.model.Temp; import java.util.ArrayList; public class MyPostActivity extends BaseActivity implements View.OnClickListener{ private ListView mListView; private MyPostAdapter mAdapter; private ArrayList<Temp> temps = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_my_post); super.onCreate(savedInstanceState); } @Override protected void initView() { ivBack = (ImageView) findViewById(R.id.iv_public_back); tvTitle = (TextView) findViewById(R.id.tv_public_title); mListView = (ListView) findViewById(R.id.lv_mypost_list); } @Override protected void initialization() { tvTitle.setText("我的帖子"); for (int i=0;i<6;i++){ temps.add(new Temp()); } mAdapter = new MyPostAdapter(this,R.layout.activity_my_post_item,temps); mListView.setAdapter(mAdapter); } @Override protected void loadData() { } @Override protected void initListener() { ivBack.setOnClickListener(this); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(MyPostActivity.this,ForumDetailsActivity.class); startActivity(intent); } }); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.iv_public_back: finish(); break; } } }
package com.example.sbilskiy.testflickrphotoviewer; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import android.widget.TextView; import java.util.concurrent.ExecutionException; /** * Created by s.bilskiy on 27.06.2016. */ public class ImageActivity extends AppCompatActivity { Bitmap bit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.imageview_activity); Intent intent = getIntent(); String Large=intent.getStringExtra("photolink"); String Title=intent.getStringExtra("Title"); String Description=intent.getStringExtra("description"); String User=intent.getStringExtra("user"); if (Description.isEmpty()){ Description="no description"; } CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar); collapsingToolbar.setTitle(Title); String Date=intent.getStringExtra("date"); try { bit=new Tasks.DownloadImageTask().execute(Large).get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } ImageView iv= (ImageView) findViewById(R.id.img_view); TextView tvTitle=(TextView)findViewById(R.id.tvDescripton); TextView tvDate=(TextView)findViewById(R.id.tvDateAdded); TextView tvUser=(TextView)findViewById(R.id.tvLoadedBy); iv.setImageBitmap(bit); tvTitle.setText(Description); tvDate.setText(Date); tvUser.setText(User); } }
package com.tencent.mm.g.b.a; import com.tencent.mm.plugin.report.a; public final class j extends a { public long cip = 0; public long ciq = 0; public final int getId() { return 15522; } public final String wE() { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(this.cip); stringBuffer.append(","); stringBuffer.append(this.ciq); String stringBuffer2 = stringBuffer.toString(); KD(stringBuffer2); return stringBuffer2; } public final String wF() { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("ReportScene:").append(this.cip); stringBuffer.append("\r\n"); stringBuffer.append("ResetScece:").append(this.ciq); return stringBuffer.toString(); } }
import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class StatementResultDemo { public static void main(String[] args) { DBSource dbsource = null; Connection conn = null; Statement stmt = null; try { dbsource = new SimpleDBSource(); conn = dbsource.getConnection(); stmt = conn.createStatement(); stmt.executeUpdate("INSERT INTO t_message VALUES(1, 'justin', " + "'justin@mail.com', 'mesage...')"); ResultSet result = stmt.executeQuery("SELECT * FROM t_message"); while (result.next()) { System.out.print(result.getInt(1) + "\t"); System.out.print(result.getString(2) + "\t"); System.out.print(result.getString(3) + "\t"); System.out.println(result.getString(4)); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { dbsource.closeConnection(conn); } catch (SQLException e) { e.printStackTrace(); } } } } }
package cn.itcast.travel.dao; import cn.itcast.travel.domain.PageBean; import cn.itcast.travel.domain.Route; import cn.itcast.travel.domain.RouteImg; import cn.itcast.travel.domain.Seller; import java.util.List; public interface RouteDao { List<Route> findLimit(String cid, String pageNo, String city); PageBean findPage(String cid,String city); List<RouteImg> findImg(String rid); Seller findSeller(String sid); Route findRoute(String rid); }
/* * Sonar Piwik Plugin * Copyright (C) 2010 Intelliware Development Inc. * dev@sonar.codehaus.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.piwik; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import static org.junit.matchers.JUnitMatchers.containsString; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.apache.commons.configuration.Configuration; import org.junit.Before; import org.junit.Test; public class PiwikWebFooterTest { private Configuration configuration; @Before public void setUp() { configuration = mock(Configuration.class); } @Test public void shouldSkipOutputWhenWebsiteIdOrServerMissing() { PiwikWebFooter subject = new PiwikWebFooter(configuration); assertThat(subject.getHtml(), nullValue()); } @Test public void shouldIncludePiwikScriptWhenWebsiteIdAndServerPresent() { withValidWebsiteId(); withServer("server.com"); PiwikWebFooter subject = new PiwikWebFooter(configuration); assertThat(subject.getHtml(), notNullValue()); } private void withServer(String server) { when(configuration.getString(eq(PiwikPlugin.PIWIK_SERVER_PROPERTY), anyString())).thenReturn(server); } @Test public void shouldBuildServerPathFromServerAndPath() { withValidWebsiteId(); withServer("server.com"); withRelativePath("test/path"); PiwikWebFooter subject = new PiwikWebFooter(configuration); assertThat(subject.getHtml(), containsString("\"http://server.com/test/path/\"")); } @Test public void shouldBeOptionalToProvidePath() { withValidWebsiteId(); withServer("server.com"); PiwikWebFooter subject = new PiwikWebFooter(configuration); assertThat(subject.getHtml(), containsString("\"http://server.com/\"")); } private void withRelativePath(String path) { when(configuration.getString(eq(PiwikPlugin.PIWIK_PATH_PROPERTY), anyString())).thenReturn(path); } private void withValidWebsiteId() { when(configuration.getString(eq(PiwikPlugin.PIWIK_WEBSITEID_PROPERTY), anyString())).thenReturn("TestId"); } }
package com.dao; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.model.Employee; import com.repositary.EmployeeRepositary; @Repository public class EmployeeDaoImpl implements Employeedaoif{ @Autowired EmployeeRepositary employeeRepositary; @Override public void createEmp(Employee employee) { employeeRepositary.save(employee); } @Override public List<Employee> viewAllEmp() { // TODO Auto-generated method stub return (List<Employee>) employeeRepositary.findAll(); } @Override public void deleteEmp(int id) { employeeRepositary.delete(id); } }
package company.com; public class ListLinker { public static Person head=null; void insert(String cod,String fn, String ln, String a, String gend, String adrs) { Person P1=new Person(); P1.COD=cod; P1.first_name=fn; P1.last_name=ln; P1.age=a; P1.gender=gend; P1.address=adrs; P1.next=null; if(head==null) { head=P1; } else { Person n=head; while(n.next!=null) { n=n.next; } n.next=P1; } } }
package com.tangdi.production.mpnotice.platform.service.impl; import java.net.URLEncoder; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.tangdi.production.mpnotice.http.client.HttpRequestClient; import com.tangdi.production.mpnotice.http.client.HttpResp; import com.tangdi.production.mpnotice.constants.NoticeCT; import com.tangdi.production.mpnotice.constants.WeixinConfig; import com.tangdi.production.mpnotice.platform.service.MessagePushService; import com.tangdi.production.mpnotice.utils.ParamValidate; import com.tangdi.production.mpnotice.utils.SHA1; import com.tangdi.production.mpnotice.weixin.utils.WXXMLParse; import com.tangdi.production.mpnotice.utils.TdExpBasicFunctions; /*** * 微信消息推送接口 * * @author sunhaining * */ @Service @SuppressWarnings({ "rawtypes", "unchecked" }) public class WXMessagePushServiceImpl implements MessagePushService { private static final Logger log = LoggerFactory.getLogger(WXMessagePushServiceImpl.class); @Autowired private HttpRequestClient httpRequestClient; @Override public Map<String, Object> signIn(Map param) throws Exception { Map responseMap = new HashMap(); String signature = param.get("signature") == null ? "" : param.get("signature").toString(); String timestamp = param.get("timestamp") == null ? "" : param.get("timestamp").toString(); String nonce = param.get("nonce") == null ? "" : param.get("nonce").toString(); String[] str = { WeixinConfig.WEIXIN_TOKEN, timestamp, nonce }; Arrays.sort(str); String bigStr = str[0] + str[1] + str[2]; String digest = new SHA1().getDigestOfString(bigStr.getBytes()).toLowerCase(); log.info("原数据:{},加密后数据:{}", signature, digest); responseMap.put("digest", digest); return responseMap; } @Override public Map<String, Object> getAccessToken(Map param) throws Exception { Map<String, Object> atMap = new HashMap<String, Object>(); try { HttpResp httpResp = httpRequestClient.sendGet(WeixinConfig.WEIXIN_ACCESSTOKENURI); if (httpResp != null) { log.info("HttpResp->" + httpResp.toString()); String jsonString = httpResp.getContent(); JsonNode jsonNode = new ObjectMapper().readValue(jsonString, JsonNode.class); log.info("第三方返回值:" + jsonString); atMap.put(NoticeCT.WEIXIN_ACCESSTOKEN, jsonNode.get("access_token").asText()); atMap.put(NoticeCT.WEIXIN_ACCESSTOKEN_EXPIRESIN, jsonNode.get("expires_in").asText()); log.info("accessToken值:{}", atMap); } } catch (Exception e) { log.info("获取accessToken失败:{}", e.getMessage()); } return atMap; } @Override public Map<String, Object> getOAuthAccessToken(Map param) throws Exception { Map<String, Object> atMap = new HashMap<String, Object>(); try { String code = param.get(NoticeCT.WEIXIN_CODE).toString(); log.info("code值:{}", code); HttpResp httpResp = httpRequestClient.sendGet(String.format(WeixinConfig.WEIXIN_OAUTHACCESSTOKENURI, code)); if (httpResp != null) { log.info("HttpResp->" + httpResp.toString()); String jsonString = httpResp.getContent(); JsonNode jsonNode = new ObjectMapper().readValue(jsonString, JsonNode.class); log.info("第三方返回值:" + jsonString); atMap.put(NoticeCT.WEIXIN_ACCESSTOKEN, jsonNode.get("access_token").asText()); atMap.put(NoticeCT.WEIXIN_OPENID, jsonNode.get("openid").asText()); log.info("accessToken和openId返回值:{}", atMap); } } catch (Exception e) { log.info("获取accessToken失败:{}", e.getMessage()); } return atMap; } @Override public String pushNotice(String protocolType, Map param) throws Exception { String rstStr = ""; if (NoticeCT.PROTOCOLTYPE_XML.equals(protocolType)) { log.info("当前数据类型为XML"); ParamValidate.doing(param, NoticeCT.PUSHUSER, NoticeCT.PUSHMSGTYPE, NoticeCT.PUSHDESCRIPTION); Map<String, Object> paramSend = new TreeMap<String, Object>(); log.info("获取用户 openId:{}", param.get(NoticeCT.PUSHUSER)); paramSend.put("ToUserName", param.get(NoticeCT.PUSHUSER)); paramSend.put("FromUserName", WeixinConfig.WEIXIN_FROMUSERNAME); paramSend.put("CreateTime", TdExpBasicFunctions.GETDATE()); paramSend.put("MsgType", param.get(NoticeCT.PUSHMSGTYPE)); if (NoticeCT.PUSHMSGTYPE_TEXT.equals(param.get(NoticeCT.PUSHMSGTYPE))) { paramSend.put("Content", NoticeCT.PUSHDESCRIPTION); } else if (NoticeCT.PUSHMSGTYPE_NEWS.equals(param.get(NoticeCT.PUSHMSGTYPE))) { paramSend.put("ArticleCount", "1"); paramSend.put("Title", param.get(NoticeCT.PUSHTITLE)); paramSend.put("Description", param.get(NoticeCT.PUSHDESCRIPTION)); paramSend.put("PicUrl", WeixinConfig.WEIXIN_BINDPREVIEWPIC); paramSend.put("Url", String.format(WeixinConfig.WEIXIN_BINDURL, URLEncoder.encode(WeixinConfig.WEIXIN_BINDPREVIEWURL, "UTF-8"))); } rstStr = WXXMLParse.generate(paramSend); } else if (NoticeCT.PROTOCOLTYPE_JSON.equals(protocolType)) { log.info("当前数据类型为JSON"); ObjectMapper objectMapper = new ObjectMapper(); rstStr = objectMapper.writeValueAsString(param); } else { throw new Exception("数据类型错误,目前只支持xml、json!"); } return rstStr; } @Override public String encryp(String data) throws Exception { return null; } }
package unclassified; import java.util.Arrays; /** * 17.6 in Ctci */ public class ShortestSequenceToSorted { public static void main(String[] args) { System.out.println(almostSorted(new int[]{1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19})); System.out.println(almostSorted(new int[]{1, 5, 4})); System.out.println(almostSorted(new int[]{5, 4})); System.out.println(almostSorted(new int[]{0, 1, 4, 5, 4, 6, 8})); } public static String almostSorted(int[] input) { int[] tmp = input.clone(); Arrays.sort(input); // nlogn int minIndex = -1, maxIndex = input.length; // n complexity for (int i = 0; (i < input.length) && (minIndex == -1 || maxIndex == input.length); i++) { if (input[i] != tmp[i] && minIndex == -1) { minIndex = i; } if (input[input.length - i - 1] != tmp[input.length - i - 1] && maxIndex == input.length) { maxIndex = input.length - i - 1; } } return minIndex + " " + maxIndex; } }
package com.example.asingh95.pocketlab; import processing.core.PApplet; /** * Created by asingh95 on 3/8/2016. */ public class Scale extends PApplet{ int j = 0; int degree = 95; @Override public void settings() { size(1000,1280); } @Override public void setup() { background(200); thermoScale(); // font = loadFont("ArialNarrow-Bold-32.vlw"); // textFont(font); drawTempMarker(); } @Override public void draw() { int marker; temperature0(); marker = degree*5; if(j<marker) { temperatureInc(j); j++; }//if } void thermoScale() { noStroke(); fill(255); rect(440, 225, 120, 700); noStroke(); fill(0, 0,255); // noFill(); ellipse(500, 925, 225, 225); }//thermoScale() void temperature0() { noStroke(); fill(0,0,255); rect(440, 810, 120, 25); }//temperature0() void temperatureInc(int i) { noStroke(); fill(i,0,(255-i)); rect(440, (810 - (i-1)), 120, 25); }//temperatureInc() void drawTempMarker() { //textAlign(RIGHT); //textSize(24); //fill(255,255,73); //text("Farenheit", 150, 125); for(int a = 0; a < 6; a++) { strokeWeight(4); stroke(0); line(440, 810-(a*100), 410, 810-(a*100)); //line(270, 340-(a*40), 285, 340-(a*40)); //textAlign(RIGHT); //textSize(14); //fill(0,0,255); //text(a*20,200, 340-(a*40)); //textAlign(LEFT); //textSize(14); //fill(0,0,255); //celcius = ceil(((a*20)-32)*(5/9)); // text(celcius,300, 340-(a*40)); }//for for(int a = 0; a < 5; a++) { strokeWeight(2); stroke(0); line(440, 760-(a*100), 420, 760-(a*100)); //textAlign(RIGHT); //textSize(10); // fill(0); //text((a*20)+10,210, 320-(a*40)); }//for for(int a = 0; a <10; a++) { strokeWeight(1); stroke(0); line(440, 785-(a*50), 430, 785-(a*50)); }//for }//drawTempMarker() }
import java.io.Serializable; import java.util.LinkedList; /* * 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. */ /** * * @author aluno */ public class Questao implements Serializable { private String perg; private LinkedList <Alternativas> alternativas = new LinkedList<>(); public LinkedList<Alternativas> listaDeAlternativas(){ return alternativas; } public Questao(){ } public Questao(String perg){ this.perg = perg; } public void adicionaAlternativa(Alternativas alt){ alternativas.add(alt); } public String getPergunta(){ return perg; } public void setPergunta (String perg){ this.perg = perg; } public int QuestaoCerta(){ for (Alternativas a : alternativas){ if(a.getEhCerta()== true){ return alternativas.indexOf(a)+1; } } return -1; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.kot.application.configuration; import com.kot.application.dao.DbService; import org.springframework.context.annotation.Bean; /** * * @author pawel */ public class DbServiceConfig { @Bean public DbService dbService() { return new DbService(); } }
/** * @Author: lty * @Date: 2020/11/18 09:07 */ public abstract class BaseCommand { public void basedo(){ System.out.println("log>>方法前置处理.."); doit(); System.out.println("log>>方法后置处理.."); } protected abstract void doit(); }
package com.library.bexam.form; import java.util.List; /** * 组织机构实体 * @author caoqian * @date 20181220 */ public class OrgForm { //机构id private int id; //机构名称 private String name; //机构类型 private int type; private String tag; private List<OrgForm> children; public OrgForm() { } public OrgForm(int id, String name, int type, List<OrgForm> children) { this.id = id; this.name = name; this.type=type; this.children = children; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getType() { return type; } public void setType(int type) { this.type = type; } public List<OrgForm> getChildren() { return children; } public void setChildren(List<OrgForm> children) { this.children = children; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } }
package templates_and_tests; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import scala.Tuple2; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import java.util.concurrent.ThreadLocalRandom; /** * Group 32 * File for the Homework n.2 of "Big Data Computing" Course" * * This file: * 1-Reads the collection of documents into an RDD docs and subdivides the into K parts; * 2-Runs three MapReduce Word count algorithms and returns their individual running times, carefully measured. * 3-Prints the average length of the distinct words appearing in the collection. * * @author Giovanni Candeo 1206150 * @author Nicolo Levorato 1156744 * */ public class G32HM2_speedtest { //number of partitions private static int k = 0; /** * Main method * @param args args[0] contains the name of the file txt we want to count * args[1] contains the number of k partitions */ public static void main(String[] args) { if (args.length == 0) { throw new IllegalArgumentException("expecting the file name"); } SparkConf conf = new SparkConf(true) .setAppName("homework2.G32HM2") .setMaster("local[*]"); JavaSparkContext sc = new JavaSparkContext(conf); //RDD contains 10122 docs composed by a single line of numerous strings JavaRDD<String> collection = sc.textFile(args[0]).cache(); //number of partitions K, received as an input in the command line k = Integer.parseInt(args[1]); //we make k partitions of the initial collection JavaRDD<String> collectionRepartitioned = collection.repartition(k); collectionRepartitioned.cache().count(); ArrayList<Long> speedTest = new ArrayList<>(); long start; long end; /*---------Word Count 1---------*/ start = System.currentTimeMillis(); JavaPairRDD<String,Long> dWordCount1Pairs =collectionRepartitioned .flatMapToPair(G32HM2_speedtest::countSingleWordsFromString) .reduceByKey(Long::sum); //i need this for computing the actual RDD transformation dWordCount1Pairs.cache().count(); //waitHere(); end = System.currentTimeMillis(); speedTest.add(end-start); /*---------Word Count 2.1-------*/ start = System.currentTimeMillis(); JavaPairRDD<String, Long> dWordCount2Pairs =collectionRepartitioned .flatMapToPair(G32HM2_speedtest::countSingleWordsFromString) .groupBy(G32HM2_speedtest::assignRandomKey) .flatMapToPair(G32HM2_speedtest::aggregateWCperKeySubset) .reduceByKey(Long::sum); dWordCount2Pairs.cache().count(); //waitHere(); end = System.currentTimeMillis(); speedTest.add(end-start); /*---------Word Count 2.2-------*/ start = System.currentTimeMillis(); JavaPairRDD<String, Long> dWordCount2Pairs2 = collectionRepartitioned .mapPartitionsToPair(G32HM2_speedtest::wordCountInPartition2) .reduceByKey(Long::sum); dWordCount2Pairs2.cache().count(); //waitHere(); end = System.currentTimeMillis(); speedTest.add(end-start); /*-------------------------------*/ /* //We can also print the pairs with this - WATCH OUT: output are big files! printWordCount(dWordCount1Pairs,"wc1output.txt"); printWordCount(dWordCount2Pairs,"wc2_1output.txt"); printWordCount(dWordCount2Pairs2,"wc2_2output.txt"); */ /* Prints the average length of the distinct words appearing in the documents */ long numberOfWoccurrences = dWordCount2Pairs2.count(); long entireWordLength = dWordCount2Pairs2.map((x) -> Long.valueOf(x._1().length())).reduce(Long::sum); float averageLenghtOfDistW = (float) entireWordLength / numberOfWoccurrences; System.out.printf("Average length of the distinct words in the collection: %f characters\n", averageLenghtOfDistW); /* Print the time speed test */ System.out.println("" + "\n------ Algorithm time measurement ------\n" + "Improved count 1: "+speedTest.get(0)+" ms\n" + "Improved count 2.1: "+speedTest.get(1)+" ms\n" + "Improved count 2.2: "+speedTest.get(2)+" ms\n" + "----------------------------------------"); } /** * This function receives a subset and and count the words in that subset. * * @param subsetbykey a subset of keys * @return word count in the subset */ private static Iterator<Tuple2<String,Long>> aggregateWCperKeySubset(Tuple2<Long, Iterable<Tuple2<String, Long>>> subsetbykey) { Iterable<Tuple2<String, Long>> tuple2s = subsetbykey._2(); HashMap<String,Long> count = new HashMap<>(); for(Tuple2<String,Long> singolaCoppia : tuple2s){ count.merge(singolaCoppia._1(),singolaCoppia._2(),Long::sum); } ArrayList<Tuple2<String,Long>> pairs= new ArrayList<>(); for(Map.Entry<String, Long> e : count.entrySet()){ pairs.add(new Tuple2<>(e.getKey(), e.getValue())); } return pairs.iterator(); } /** * Count the word occurrences in a document represented by a single line of strings. * * @param document input document as a single string line. * @return iterator of tuple composed by word and his count. */ private static Iterator<Tuple2<String,Long>> countSingleWordsFromString(String document) { String[] tokens = document.split(" "); HashMap<String, Long> wordCountInDocument = new HashMap<>(); ArrayList<Tuple2<String, Long>> wcPairs = new ArrayList<>(); for (String token : tokens) { wordCountInDocument.put(token, 1L + wordCountInDocument .getOrDefault(token, 0L)); } for (Map.Entry<String, Long> e : wordCountInDocument .entrySet()) { wcPairs.add(new Tuple2<>(e.getKey(), e.getValue())); } return wcPairs.iterator(); } /** * Assigns a random key to the input document s * @param s input document s * @return random Long value that will represent a random key. */ private static Long assignRandomKey(String s) { return ThreadLocalRandom.current().nextLong(0, (int) Math.sqrt(k)); } private static Long assignRandomKey(Tuple2<String,Long> s){ return ThreadLocalRandom.current().nextLong(0, (int) Math.sqrt(k)); } /** * This function operate on single partitions * * @param documentsPartitioned single partition of documents. * @return word count occurrences in the partition **/ private static Iterator<Tuple2<String,Long>> wordCountInPartition2(Iterator<String> documentsPartitioned) { HashMap<String,Long> wordCountInPartition = new HashMap<>(); //i need this to return a correct iterator ArrayList<Tuple2<String,Long>> wordCountIterator = new ArrayList<>(); //per ogni documento della partizione conto le occorrenze di parole e aggiorno a fine ciclo il conteggio principale while(documentsPartitioned.hasNext()){ HashMap<String,Long> wordCountInDocument = new HashMap<>(); String[] tokens = documentsPartitioned.next().split(" "); //count word occurrences in document for(String token : tokens){ wordCountInDocument.merge(token,1L,Long::sum); } //document has been wordcounted, time to update the main value for (Map.Entry<String, Long> e : wordCountInDocument.entrySet()) { wordCountInPartition.merge(e.getKey(),e.getValue(),Long::sum); } } for (Map.Entry<String, Long> e : wordCountInPartition.entrySet()) { wordCountIterator.add(new Tuple2<>(e.getKey(), e.getValue())); } return wordCountIterator.iterator(); } /** * Utility function * Prints the RDD to visualize the word count pairs in a txt file. * * @param dWordCountPairsRDD the RDD that is printed to file * @param filename the output file of the print */ private static void printWordCount(JavaPairRDD<String,Long> dWordCountPairsRDD, String filename){ Map<String, Long> lWordCountPairs = dWordCountPairsRDD.collectAsMap(); FileWriter fileWriter = null; try { fileWriter = new FileWriter(filename); } catch (IOException e) { e.printStackTrace(); } PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.print(lWordCountPairs.toString()); printWriter.close(); } /** * Utility function * Stops the execution of the program to interact with the Spark webapp. */ private static void waitHere(){ System.out.println("press enter to finish the program"); try{ System.in.read(); }catch (IOException e) { e.printStackTrace(); } } }
package cn.law.work.citypicker; /** * Created by IntelliJ IDEA. * User: Jungle Law * Date: 2018/12/16 * Time: 18:31 */ public class Item { private String name = ""; private int code; private boolean isSelected; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public boolean isSelected() { return isSelected; } public void setSelected(boolean selected) { isSelected = selected; } }
package de.jmda.gen.java; import de.jmda.gen.Generator; import de.jmda.gen.GeneratorException; /** * @author ruu.jmda@gmail.com */ public interface MethodNameGenerator extends Generator { void setMethodName(String methodName); String getMethodName() throws GeneratorException; }
package com.example.headfirst.order; /** * create by Administrator : zhanghechun on 2020/3/31 */ public class Stereo { public void on(){ System.out.println("开启"); } public void off(){ System.out.println("关闭"); } public void setCd(){ System.out.println("装上CD"); } public void setDVD(){ System.out.println("装上dvd"); } public void Radio(){ System.out.println("装上广播"); } public void Volume(int i){ System.out.println("音量:"+i); } }
package ar.edu.itba.pod.legajo50272; import java.io.Serializable; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import ar.edu.itba.event.EventInformation; import ar.edu.itba.event.RemoteEventDispatcher; import ar.edu.itba.node.Node; import ar.edu.itba.node.NodeInformation; import ar.edu.itba.pod.agent.runner.Agent; import ar.edu.itba.pod.multithread.MultiThreadEventDispatcher; public class RemoteEventDispatcherImpl extends MultiThreadEventDispatcher implements RemoteEventDispatcher { // The events to broadcast private BlockingQueue<EventInformation> eventsToSend = new LinkedBlockingQueue<EventInformation>(); // The history of events private List<EventInformation> events = Collections.synchronizedList(new ArrayList<EventInformation>()); private Set<EventInformation> eventsSet = Collections.synchronizedSet(new HashSet<EventInformation>()); // Current position in the history of events that has to be sent private Map<NodeInformation, Integer> indexPerNode = new ConcurrentHashMap<NodeInformation, Integer>(); // The current node private final RemoteSimulation node; private class EventBroadcastTask implements Runnable { @Override public void run() { try { while(true){ EventInformation event = eventsToSend.take(); for(NodeInformation dest: node.getConnectedNodes()) if(!dest.equals(node.getNodeInformation())){ Registry registry = LocateRegistry.getRegistry(dest.host(), dest.port()); RemoteEventDispatcher remoteEventDispatcher = (RemoteEventDispatcher) registry.lookup(Node.DISTRIBUTED_EVENT_DISPATCHER); boolean received = remoteEventDispatcher.publish(event); if(!received && Math.random() > 0.5) break; } } } catch (InterruptedException e) { return; }catch (Exception e) { e.printStackTrace(); } } } private class CheckerTask implements Runnable { @Override public void run() { try { while(true){ Thread.sleep(1000); synchronized (node.getConnectedNodes()) { List<NodeInformation> connectedNodes = new ArrayList<NodeInformation>(node.getConnectedNodes()); if(connectedNodes.size() > 1){ connectedNodes.remove(node.getNodeInformation()); NodeInformation dest = connectedNodes.get((int)Math.floor(Math.random()*connectedNodes.size())); Registry registry = LocateRegistry.getRegistry(dest.host(), dest.port()); RemoteEventDispatcher remoteEventDispatcher = (RemoteEventDispatcher) registry.lookup(Node.DISTRIBUTED_EVENT_DISPATCHER); for(EventInformation newEvent: remoteEventDispatcher.newEventsFor(node.getNodeInformation())) publish(newEvent); } } } } catch (InterruptedException e) { return; } catch (Exception e) { e.printStackTrace(); } } } private class CleanerTask implements Runnable { @Override public void run() { try { while(true){ Thread.sleep(60000); int min = -1; List<NodeInformation> nodesToRemove = new ArrayList<NodeInformation>(); synchronized (indexPerNode) { if(!indexPerNode.isEmpty()){ for(NodeInformation nodeInformation: indexPerNode.keySet()) if(!node.getConnectedNodes().contains(nodeInformation)) nodesToRemove.add(nodeInformation); for(NodeInformation nodeInformation: nodesToRemove) indexPerNode.remove(nodeInformation); for(Integer lastMessageSended: indexPerNode.values()) if(min == -1 || lastMessageSended < min) min = lastMessageSended; for(int i = 0; i < min; i++){ EventInformation event = events.remove(0); eventsSet.remove(event); } for(Entry<NodeInformation, Integer> entry: indexPerNode.entrySet()) entry.setValue(entry.getValue() - min); } } } } catch (InterruptedException e) { return; } catch (Exception e) { e.printStackTrace(); } } } public RemoteEventDispatcherImpl(RemoteSimulation node) throws RemoteException { super(); UnicastRemoteObject.exportObject(this, 0); this.node = node; node.execute(new EventBroadcastTask()); node.execute(new CheckerTask()); node.execute(new CleanerTask()); } @Override public boolean publish(EventInformation event) throws RemoteException, InterruptedException { if(eventsSet.add(event)){ // Append the event to the history of events this.events.add(event); // Add to the queue of events to broadcast this.eventsToSend.offer(event); // Publish the event locally synchronized (this) { super.publish(event.source(), event.event()); } return true; } return false; } @Override public Set<EventInformation> newEventsFor(NodeInformation nodeInformation) throws RemoteException { Set<EventInformation> ans = new HashSet<EventInformation>(); synchronized (indexPerNode) { int length = events.size(); Integer index = indexPerNode.get(nodeInformation); if(index == null){ indexPerNode.put(nodeInformation, 0); index = 0; } if(index > length - 1) return ans; for(int i = index; i < length; i++) ans.add(events.get(i)); indexPerNode.put(nodeInformation, length - 1); } return ans; } @Override public BlockingQueue<Object> moveQueueFor(Agent agent) throws RemoteException { return super.deregister(agent); } @Override public void publish(Agent source, Serializable event) throws InterruptedException { EventInformation eventInformation = new EventInformation(event, this.node.getNodeInformation().id(), source); eventInformation.setReceivedTime(System.nanoTime()); try { publish(eventInformation); } catch (RemoteException e) { e.printStackTrace(); } } }
package programmers.level1; public class PrimeNum { // class Solution { // public int solution(int n) { // int answer = 0; // int[] arr = new int[n + 1]; // // for (int i = 2; i <= n; i++) // arr[i] = i; // // for (int i = 2; i <= n; i++) { // for (int j = 2; j <= n; j++) { // if (arr[i] % j == 0 && arr[i] != j) { // arr[i] = 0; // break; // } // } // } // // for (int target : arr) // if (target != 0) // answer++; // // return answer; // } // } // 에라토스테네스의 체 class Solution { public int solution(int n) { int answer = 0; int[] arr = new int[n+1]; for(int i=2; i<=n; i++) arr[i] = i; for(int i=2; i*i<=n; i++){ if(arr[i] != 0){ for(int j=i*i; j<=n; j+=i){ arr[j] = 0; } } } for(int i=2; i<=n; i++) if(arr[i] != 0) answer++; return answer; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: Stefan Irimescu * */ package sparksoniq.jsoniq.runtime.iterator.postfix; import sparksoniq.exceptions.InvalidSelectorException; import sparksoniq.exceptions.UnexpectedTypeException; import sparksoniq.jsoniq.item.Item; import sparksoniq.jsoniq.item.ObjectItem; import sparksoniq.jsoniq.item.StringItem; import sparksoniq.exceptions.IteratorFlowException; import sparksoniq.jsoniq.runtime.iterator.LocalRuntimeIterator; import sparksoniq.jsoniq.runtime.iterator.RuntimeIterator; import sparksoniq.jsoniq.runtime.iterator.primary.StringRuntimeIterator; import sparksoniq.jsoniq.runtime.metadata.IteratorMetadata; public class ObjectLookupItertor extends LocalRuntimeIterator { public ObjectLookupItertor(RuntimeIterator object, StringRuntimeIterator stringRuntimeIterator, IteratorMetadata iteratorMetadata) { super(null, iteratorMetadata); this._children.add(object); this._children.add(stringRuntimeIterator); } @Override public Item next() { if(_hasNext == true){ this._children.get(0).open(_currentDynamicContext); this._children.get(1).open(_currentDynamicContext); _object = (ObjectItem) this._children.get(0).next(); Item _lookupKey = this._children.get(1).next(); if(this._children.get(1).hasNext() || _lookupKey.isObject() || _lookupKey.isArray()) throw new InvalidSelectorException("Type error; There is not exactly one supplied parameter for an array selector: " + _lookupKey.serialize(), getMetadata()); if(!_lookupKey.isString()) throw new UnexpectedTypeException("Non numeric array lookup for " + _lookupKey.serialize(), getMetadata()); this._children.get(0).close(); this._children.get(1).close(); _hasNext = false; return _object.getItemByKey(((StringItem)_lookupKey).getStringValue()); } throw new IteratorFlowException("Invalid next call in Object Lookup", getMetadata()); } private ObjectItem _object = null; }
import java.math.BigDecimal; import java.util.List; public class Multiplier { public int multiple(int a, int b) { return a*b; } public int multiple(int a, int b, int c, int d) { return a*b*c*d; } public double multiple(double a, double b) { return a*b; } public int multiple(List<Integer> a) { int t = 1; for(int i = 0; i < a.size(); i++) { t = t* a.get(i); } return t; } public BigDecimal mutiple(BigDecimal a, BigDecimal b) { return a.multiply(b); } }
package org.buaa.ly.MyCar.http.dto; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.buaa.ly.MyCar.entity.Account; import java.sql.Timestamp; import java.util.Collection; import java.util.List; @Data @EqualsAndHashCode(callSuper = false) @JsonInclude(JsonInclude.Include.NON_NULL) public class AccountDTO extends DTOBase { Integer id; String username; @JSONField(deserialize = false) String password; String name; String phone; Integer role; Integer sid; Integer status; String token; @JsonProperty(value = "create_time") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8") Timestamp createTime; public Account build() { return build(this, Account.class); } static public AccountDTO build(Account account) { return build(account, AccountDTO.class); } static public List<AccountDTO> build(Collection<Account> accounts) { return build(accounts, AccountDTO.class); } @Override public String toString() { return JSON.toJSONString(this); } }
package view.defaultargumentcomponents; import graphana.graphs.GraphLibrary; import javax.swing.*; public class VertexComboBox extends JComboBox { private static final long serialVersionUID = 1L; public VertexComboBox() { this.setEditable(true); } public <VertexType, EdgeType> void fillItems(GraphLibrary<VertexType, EdgeType> graph) { for (VertexType vertex : graph.getVertices()) { this.addItem(graph.vertexToString(vertex)); } } }
import java.util.Scanner; public class Principal { public static Scanner in = new Scanner (System.in); public static void main(String[] args) { System.out.println("Escolha uma letra"); String s = in.next(); switch(s) { case "a": System.out.println("O número maior é "+maior(15,9)); break; case"b": System.out.println("O menor número é "+menor(3,1)); break; case"c": System.out.println("Meu nome é "+nome()); break; case"d": vazio(); break; case"e": System.out.println(nota(7,10)); break; case"f": System.out.println("O fatorial é "+fat(5)); break; case"g": System.out.println(primo(4)); break; case"h": int k = 5; if(nota(6,6)){ System.out.println("Conceito A"); }else { if(media1(6,6) >= 4 && media1(6,6) < 7 ) { if((media1(6,6)+ k)/2 >= 5) { System.out.println("Conceito B"); }else { System.out.println("Reprovado"); } } } break; case "i": calculadora(); break; case "j": safadao(6,5,1998); break; case"k": System.out.println(cores(2,1)); break; } } //Letra a public static int maior (int a, int b ) { if (a>b) { return a; }else { return b; } } //Letra b public static int menor (int a, int b) { if(a<b) { return a; }else { return b; } } //Letra c public static String nome() { return "Rebeca"; } //Letra d public static void vazio() { for(int i = 0; i<100; i++) { if(i%2 == 0) { System.out.println("Rebeca"); }else { System.out.println("Silva"); } } } //Letra e public static boolean nota(int a, int b) { if(((a+b)/2)>=7) { return true; }else { return false; } } //Letra f public static int fat (int a) { for(int i=a; i>1; i--) { a=a*(i-1);} return a; } //Letra g public static boolean primo(int a) { int b = 0; for(int i=2; i<a; i++) { if(a%i==0) { b = b+1; } } if(b==0) { System.out.println("Número é primo: "); return true; }else { System.out.println("Número é primo: "); return false; } } //Letra h public static int media1(int a, int b) { int media = ((a+b)/2); return media; } //Letra i public static void calculadora() { System.out.println("CALCULADORA"); System.out.println("OPERAÇÕES"); System.out.println("SOMAR: +"); System.out.println("SOBTRAIR: -"); System.out.println("DIVIDIR: /"); System.out.println("MULTIPLICAR: *"); System.out.println("DIGITE O PRIMEIRO NÚMERO"); int r = in.nextInt(); System.out.println("DIGITE A OPERAÇÃO"); String c = in.next(); System.out.println("DIGITE O SEGUNDO NÚMERO"); int p = in.nextInt(); int resultado; if(c == "+" || c == "-" || c == "/" || c == "*") { switch(c) { case "+": resultado = r + p; System.out.println("="+resultado); break; case "-": resultado = r - p; System.out.println("="+resultado); break; case "/": resultado = r / p; System.out.println("="+resultado); break; case "*": resultado = r * p; System.out.println("="+resultado); break; } }else { System.out.println("OPERAÇÃO INVALIDA"); } } //Letra j.1 public static void safadao(int d, int m, int a) { float k = somatorio(m)+(a/100)*(50-d); System.out.println("safadeza ="+k); float b = (100 - k); System.out.println("anjo ="+b); } public static int somatorio (int m) { for(int i=m; i>=1; i--) { m = (m+(i-1)); }return m; } //Letra k public static String cores (int a, int b) { if(a%2 == 0 && b%2 == 0) { return "Azul"; } if(a%2 != 0 && b%2 != 0) { return "Vermelho"; }else { return "Amarelo"; } } }
package ua.project.protester.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import ua.project.protester.annotation.UniqueEmail; import javax.validation.constraints.NotNull; @NoArgsConstructor @AllArgsConstructor @Data public class UserDto { @UniqueEmail(message = "User with given email already exist") @NotNull(message = "provide an email") private String email; @NotNull(message = "provide a password") private String password; }
package com.tencent.mm.plugin.appbrand.dynamic.d; import android.os.Bundle; import com.tencent.mm.modelappbrand.r; import com.tencent.mm.plugin.appbrand.dynamic.d.a.b; class a$b$3 implements r { final /* synthetic */ b fvM; a$b$3(b bVar) { this.fvM = bVar; } public final void b(boolean z, String str, Bundle bundle) { } }
package com.boot.spring.repository; import java.util.List; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.boot.spring.model.Client; @Repository public interface ClientsRepository extends CrudRepository<Client, Long> { List<Client> findAll(); }
package com.yinghai.a24divine_user.constant; /** * Created by:fanson * Created on:2017/10/24 13:28 * Describe:Http网络结果返回的code */ public class ConResultCode { /** * 请求成功 */ public static final int SUCCESS = 1; /** * 微信登陆成功,尚未绑定 */ public static final int IS_NEW_USER = 2; /** * 缺少参数 */ public static final int LOSS_PARAMS = 101; /** * 未登记、数据不存在 */ public static final int NOT_REGISTER = 102; /** * 密码错误 */ public static final int PASSWORD_ERROR = 103; /** * 验证码过期 */ public static final int VERIFICATION_OVERDUE = 105; /** * 操作失败 */ public static final int OPERATE_FAILED = 106; /** * 异地登录或数据出错,需要重新登录 */ public static final int RETRY_LOGIN = 111; /** * 预约时间早于当前时间 */ public static final int BOOK_TIME_ERROR = 117; /** * 商品库存不足 */ public static final int PRODUCT_SOLD_OUT = 115; /** * 订单状态异常 */ public static final int SOLD_OUT = 508; /** * 重复收藏 */ public static final int REPEAT_COLLECT = 1021; /** * 重复关注 */ public static final int REPEAT_FOLLOW = 1022; /** * 已取消收藏,请勿重复 */ public static final int REPEAT_CANCEL_COLLECT = 1023; }
// vim: set filetype=java tabstop=2 shiftwidth=2 expandtab : package org.fhcrc.honeycomb.metapop; import java.util.Set; import java.util.HashSet; /** A <class>Location</class> represents a set of row/column coordinates. * Created on 27 Jan, 2012 * @author Adam Waite * @version $Rev: 1201 $, $Date: 2012-02-03 14:33:54 -0800 (Fri, 03 Feb 2012) $ */ public class Location { private final int row; private final int col; public Location(int row, int col) { this.row = row; this.col = col; } public Location(Location l) { this(l.getRow(), l.getCol()); } public int getRow() { return row; } public int getCol() { return col; } public static Set<Location> deepCopy(Set<Location> ls) { Set<Location> new_locs = new HashSet<Location>(ls.size()); for (Location l:ls) new_locs.add(new Location(l)); return new_locs; } public Location deepCopy() { return new Location(this); } @Override public String toString() { return new String("\nrow: "+row+" col: "+col); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Location)) return false; Location loc = (Location) obj; return loc.getRow() == row && loc.getCol() == col; } @Override public int hashCode() { return (Integer.toString(row) + Integer.toString(col)).hashCode(); } }
package Leetcode; /** * 给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围, * 并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。 * @author AD * */ public class NumIslands { private int[][] d = {{-1, 0}, {0,1}, {1, 0}, {0, -1}}; public int numIslands(char[][] grid) { int res = 0; if (grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0) { return 0; } boolean[][] visited = new boolean[grid.length][grid[0].length]; for (int i = 0; i < visited.length; i++) { for (int j = 0; j < visited[0].length; j++) { visited[i][j] = false; } } for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == 1 && !visited[i][j]) { res = res + 1; isLand(grid, i, j, visited); } } } return res; } private void isLand(char[][] grid, int startX, int startY, boolean[][] visited) { visited[startX][startY] = true; for (int i = 0; i < 4; i++) { int newX = startX + d[i][0]; int newY = startY + d[i][1]; if (newX >= 0 && newX < grid.length && newY >= 0 && newY < grid[0].length && grid[newX][newY] == 1 && !visited[newX][newY]) { isLand(grid, newX, newY, visited); } } return; } public static void main(String[] args) { char[][] grid = {{1, 1, 1, 1, 0}, {1, 1, 0, 1, 0}, {1, 1, 0, 0, 0}, {0, 0, 1, 0, 1}}; NumIslands numIslands = new NumIslands(); int res = numIslands.numIslands(grid); System.out.println(res); } }
package rontikeky.beraspakone.kurir; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import rontikeky.beraspakone.R; /** * Created by Acer on 2/24/2018. */ public class KurirAdapter extends RecyclerView.Adapter<KurirAdapter.KurirViewHolder> { List<responseKurir> mKurir; private Context mCtx; public KurirAdapter() { super(); mKurir = new ArrayList<responseKurir>(); responseKurir namaKurir = new responseKurir(); namaKurir.setKurirNama("Kiosk Kurir"); namaKurir.setmThumbnail(R.drawable.nonvacum); namaKurir.setBiayaEstimsi("10000"); mKurir.add(namaKurir); namaKurir = new responseKurir(); namaKurir.setKurirNama("Gojek Kurir"); namaKurir.setmThumbnail(R.drawable.vacum); namaKurir.setBiayaEstimsi("10000"); mKurir.add(namaKurir); } @Override public KurirViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_kurir, parent, false); KurirViewHolder viewHolder = new KurirViewHolder(v); return viewHolder; } @Override public int getItemCount() { return mKurir.size(); } class KurirViewHolder extends RecyclerView.ViewHolder { public ImageView imgThumb; public TextView nmKurir, estimasiHrg; public KurirViewHolder(View itemView) { super(itemView); imgThumb = (ImageView) itemView.findViewById(R.id.imgKurir); nmKurir = (TextView) itemView.findViewById(R.id.namaKurir); estimasiHrg = (TextView) itemView.findViewById(R.id.estimasiHarga); } } @Override public void onBindViewHolder(KurirViewHolder holder, int position) { responseKurir listKurir = mKurir.get(position); holder.imgThumb.setImageResource(listKurir.getmThumbnail()); holder.nmKurir.setText(listKurir.getKurirNama()); holder.estimasiHrg.setText(listKurir.getBiayaEstimsi()); } }
package pl.dostrzegaj.soft.flicloader; import java.io.File; import java.util.Objects; class PhotoFile { private final File file; private RelativePath relativePath; public PhotoFile(File root, File file) { this.file = file; this.relativePath = new RelativePath(root, file); } public File getFile() { return file; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PhotoFile photoFile = (PhotoFile) o; return Objects.equals(file, photoFile.file) && Objects.equals(relativePath, photoFile.relativePath); } @Override public int hashCode() { return Objects.hash(file, relativePath); } @Override public String toString() { final StringBuilder sb = new StringBuilder("PhotoFile{"); sb.append("file=").append(file); sb.append('}'); return sb.toString(); } public RelativePath getRelativePath() { return relativePath; } }
/* * 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 calculation; import java.util.HashMap; /** * * @author tranh */ public final class Basic_Stats_Operations { //sample set public double[] array; //calculate mean of a set public Basic_Stats_Operations(double[] array) { this.array = array; } public Basic_Stats_Operations(int[] array) { this.array = convert(array); } public double get_mean() { double accumulation = 0; for (double d : array) { accumulation += d; } return accumulation / array.length; } //calculate median of a set public double get_median() { int n = array.length; return n % 2 == 0 ? (array[n / 2] + array[(n / 2 - 1)]) / 2 : array[(int) Math.floor(n / 2)]; } //calculate the mode of a set public double get_mode() { HashMap map = new HashMap(); int max_occurence = 1; double mode = array[0]; //loop through the set and find the mode value of the set for (double d : array) { double current_index_val = d; if (map.containsKey(current_index_val)) { int curr_occ_num = (Integer) map.get(current_index_val); curr_occ_num++; map.put(d, curr_occ_num); if (curr_occ_num >= max_occurence) { mode = current_index_val; max_occurence = curr_occ_num; } } else { map.put(d, 1); } } return mode; } //Calculate the standard deviation of the set public double get_variance() { double accumulation = 0; double mean = get_mean(); for (double d : array) { accumulation += Math.pow(d - mean, 2); } return accumulation / (array.length - 1); } public double get_standard_deviation() { return Math.sqrt(get_variance()); } public double get_std_err() { return get_standard_deviation() / Math.sqrt(array.length); } public double[] get_z_score() { double[] temp = new double[array.length]; int counter = 0; for (double d : array) { temp[counter] = (d - get_mean()) / get_standard_deviation(); counter++; } return temp; } public double get_z_score(double point) { return (point - get_mean()) / get_standard_deviation(); } public double get_z_score(int point) { return this.get_z_score(point * 1.0); } //Convert set of integers to equivalent floats private double[] convert(int[] array) { double[] temp = new double[array.length]; int counter = 0; for (int i : array) { temp[counter] = i * 1.0; counter++; } return temp; } }
package com.tencent.mm.plugin.facedetect.views; import android.app.ActivityManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Point; import android.graphics.Rect; import android.graphics.SurfaceTexture; import android.util.AttributeSet; import android.view.TextureView.SurfaceTextureListener; import com.tencent.mm.plugin.appbrand.jsapi.r; import com.tencent.mm.plugin.facedetect.FaceProNative.FaceResult; import com.tencent.mm.plugin.facedetect.model.FaceDetectReporter; import com.tencent.mm.plugin.facedetect.model.f; import com.tencent.mm.plugin.facedetect.model.g; import com.tencent.mm.sdk.platformtools.ah; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.base.MMTextureView; public class FaceDetectCameraView extends MMTextureView implements SurfaceTextureListener { private static a iTl = null; private boolean heV; private int height; private long iNs; b iSU; private SurfaceTexture iSV; private ActivityManager iSW; private long iSX; private long iSY; private int iSZ; private boolean iTa; private boolean iTb; private boolean iTc; private final Object iTd; private boolean iTe; private boolean iTf; private final Object iTg; private final Object iTh; private Rect iTi; private c iTj; private boolean iTk; public b iTm; private byte[] iTn; private boolean iTo; private long iTp; private int width; static /* synthetic */ void f(FaceDetectCameraView faceDetectCameraView) { if (faceDetectCameraView.iTe && faceDetectCameraView.iSX > 0) { x.i("MicroMsg.FaceDetectCameraView", "hy: already request scanning face and now automatically capture"); ah.A(new 1(faceDetectCameraView)); } } public FaceDetectCameraView(Context context, AttributeSet attributeSet) { this(context, attributeSet, 0); } public FaceDetectCameraView(Context context, AttributeSet attributeSet, int i) { super(context, attributeSet, i); this.iSU = null; this.iSV = null; this.iSX = FaceDetectView.iTW; this.iSY = -1; this.iNs = -1; this.iSZ = 1; this.iTa = false; this.iTb = false; this.iTc = false; this.iTd = new Object(); this.iTe = false; this.iTf = false; this.heV = false; this.iTg = new Object(); this.iTh = new Object(); this.iTi = null; this.width = r.CTRL_INDEX; this.height = 576; this.iTj = null; this.iTk = false; this.iTm = null; this.iTn = null; this.iTo = false; this.iTp = -1; this.iSW = (ActivityManager) getContext().getSystemService("activity"); x.i("MicroMsg.FaceDetectCameraView", "hy: face vedio debug: %b", new Object[]{Boolean.valueOf(this.iTk)}); this.iTm = new c(this, (byte) 0); iTl = new a(this, (byte) 0); setOpaque(false); setSurfaceTextureListener(this); } public final Point getEncodeVideoBestSize() { return this.iTm.aKK(); } final void setCallback(b bVar) { this.iSU = bVar; } public final void a(c cVar) { this.iTm.a(cVar); this.iNs = -1; } public final synchronized void a(Rect rect, long j) { aKE(); this.iTi = rect; aKG(); this.iTm.dg(j); } private static void aKE() { x.i("MicroMsg.FaceDetectCameraView", "hy: request clear queue"); f.aJK(); } public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i2) { x.i("MicroMsg.FaceDetectCameraView", "hy: onSurfaceTextureAvailable"); crS(); this.iTa = true; this.iSV = surfaceTexture; if (this.iTf) { a(this.iTj); } } public final void aKF() { this.heV = false; this.iTm.aKJ(); aKE(); int aJP = f.iNu.aJP(); x.i("MicroMsg.FaceDetectCameraView", "alvinluo pause motion time: %d", new Object[]{Long.valueOf(System.currentTimeMillis())}); FaceDetectReporter.aJU().s(aJP, r2); } private synchronized void aKG() { x.i("MicroMsg.FaceDetectCameraView", "alvinluo capture face"); f.iNu.aJO(); g gVar = f.iNu.iNv.iPA; if (gVar.iNy == null) { x.e("MicroMsg.FaceDetectNativeManager", "hy: init motion no instance"); } else { x.i("MicroMsg.FaceDetectNativeManager", "hy: start init motion"); gVar.iNy.engineGetCurrMotion(); } int aJP = f.iNu.aJP(); x.i("MicroMsg.FaceDetectCameraView", "alvinluo start motion time: %d", new Object[]{Long.valueOf(System.currentTimeMillis())}); FaceDetectReporter.aJU().r(aJP, r2); } public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i2) { x.i("MicroMsg.FaceDetectCameraView", "hy: onSurfaceTextureSizeChanged"); this.iSV = surfaceTexture; } public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) { x.i("MicroMsg.FaceDetectCameraView", "hy: onSurfaceTextureDestroyed"); this.iTa = false; return false; } public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) { } protected void onAttachedToWindow() { super.onAttachedToWindow(); x.i("MicroMsg.FaceDetectCameraView", "hy: attached"); } final synchronized FaceResult aKH() { FaceResult aJR; f.aJK(); int aJO = f.iNu.aJO(); aJR = f.iNu.iNv.iPA.aJR(); String str = "MicroMsg.FaceDetectCameraView"; String str2 = "hy: motionResult: %d, finalResult: %d"; Object[] objArr = new Object[2]; objArr[0] = Integer.valueOf(aJO); objArr[1] = Integer.valueOf(aJR != null ? aJR.result : -10000); x.i(str, str2, objArr); return aJR; } public final Bitmap getPreviewBm() { return getBitmap(); } protected void onMeasure(int i, int i2) { super.onMeasure(i, i2); this.width = getMeasuredWidth(); this.height = getMeasuredHeight(); x.i("MicroMsg.FaceDetectCameraView", "hy: camera view on measure to %d, %d", new Object[]{Integer.valueOf(this.width), Integer.valueOf(this.height)}); } public final int getCameraRotation() { return this.iTm.getRotation(); } public final int getPreviewWidth() { return this.iTm.getPreviewWidth(); } public final int getPreviewHeight() { return this.iTm.getPreviewHeight(); } }
package kh.cocoa.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import kh.cocoa.dao.EmailDAO; import kh.cocoa.dto.EmailDTO; import kh.cocoa.dto.FilesDTO; import kh.cocoa.statics.DocumentConfigurator; @Service public class EmailService implements EmailDAO{ @Autowired private EmailDAO edao; @Override public void sendEmail(EmailDTO dto) { edao.sendEmail(dto); } @Override public int getSeq() { return edao.getSeq(); } @Override public List<EmailDTO> sendToMeList(String email, int startRowNum, int endRowNum) { return edao.sendToMeList(email, startRowNum, endRowNum); } @Override public List<EmailDTO> receiveList(String email, int startRowNum, int endRowNum) { return edao.receiveList(email, startRowNum, endRowNum); } @Override public List<EmailDTO> sendList(String email, int startRowNum, int endRowNum) { return edao.sendList(email, startRowNum, endRowNum); } @Override public List<EmailDTO> deleteList(String email, int startRowNum, int endRowNum) { return edao.deleteList(email, startRowNum, endRowNum); } @Override public EmailDTO getEmail(String seq) { return edao.getEmail(seq); } @Override public int getToMeCount(String email) { return edao.getToMeCount(email); } @Override public int getReceiveCount(String email) { return edao.getReceiveCount(email); } @Override public int getSendCount(String email) { return edao.getSendCount(email); } @Override public int getDeleteCount(String email) { return edao.getDeleteCount(email); } public String getNavi(String email, String status, int cpage) { int recordTotalCount = 0; if(status.contentEquals("receive")) { //받은 메일함 recordTotalCount = getReceiveCount(email); }else if(status.contentEquals("send")) { recordTotalCount = getSendCount(email); }else if(status.contentEquals("delete")) { recordTotalCount = getDeleteCount(email); }else if(status.contentEquals("sendToMe")) { recordTotalCount = getToMeCount(email); } int pageTotalCount = recordTotalCount / DocumentConfigurator.recordCountPerPage; if (recordTotalCount % DocumentConfigurator.recordCountPerPage != 0) { pageTotalCount++; } //보안코드 if (cpage < 1) { cpage = 1; } else if (cpage > pageTotalCount) { cpage = pageTotalCount; } int startNavi = (cpage - 1) / DocumentConfigurator.naviCountPerPage * DocumentConfigurator.naviCountPerPage + 1; int endNavi = startNavi + DocumentConfigurator.naviCountPerPage - 1; if (endNavi > pageTotalCount) { endNavi = pageTotalCount; } boolean needPrev = true; boolean needNext = true; if (startNavi == 1) { needPrev = false; } if (endNavi == pageTotalCount) { needNext = false; } StringBuilder sb = new StringBuilder(); if(status.contentEquals("receive")) { if (needPrev) { sb.append("<a href=/email/receiveList.email?cpage=" + (startNavi - 1) + ">< </a>"); } for (int i = startNavi; i <= endNavi; i++) { sb.append("<a href=/email/receiveList.email?cpage=" + i + "> " + i + " </a>"); } if (needNext) { sb.append("<a href=/email/receiveList.email?cpage=" + (endNavi + 1) + "> > </a>"); } }else if(status.contentEquals("send")) { if (needPrev) { sb.append("<a href=/email/sendList.email?cpage=" + (startNavi - 1) + ">< </a>"); } for (int i = startNavi; i <= endNavi; i++) { sb.append("<a href=/email/sendList.email?cpage=" + i + "> " + i + " </a>"); } if (needNext) { sb.append("<a href=/email/sendList.email?cpage=" + (endNavi + 1) + "> > </a>"); } }else if(status.contentEquals("delete")) { if (needPrev) { sb.append("<a href=/email/deleteList.email?cpage=" + (startNavi - 1) + ">< </a>"); } for (int i = startNavi; i <= endNavi; i++) { sb.append("<a href=/email/deleteList.email?cpage=" + i + "> " + i + " </a>"); } if (needNext) { sb.append("<a href=/email/deleteList.email?cpage=" + (endNavi + 1) + "> > </a>"); } }else if(status.contentEquals("sendToMe")) { if (needPrev) { sb.append("<a href=/email/sendToMeList.email?cpage=" + (startNavi - 1) + ">< </a>"); } for (int i = startNavi; i <= endNavi; i++) { sb.append("<a href=/email/sendToMeList.email?cpage=" + i + "> " + i + " </a>"); } if (needNext) { sb.append("<a href=/email/sendToMeList.email?cpage=" + (endNavi + 1) + "> > </a>"); } } return sb.toString(); } @Override public void deleteToMeEmail(String seq) { edao.deleteToMeEmail(seq); } @Override public void deleteReceiveEmail(String seq) { edao.deleteReceiveEmail(seq); } @Override public void deleteSendEmail(String seq) { edao.deleteSendEmail(seq); } @Override public void deleteToMeNEmail(String seq) { edao.deleteToMeNEmail(seq); } @Override public void deleteReceiveNEmail(String seq) { edao.deleteReceiveNEmail(seq); } @Override public void deleteSendNEmail(String seq) { edao.deleteSendNEmail(seq); } }
package com.kodilla.testing.colection; import java.util.ArrayList; public class OddNumbersExterminator { private ArrayList<Integer> numbersList; public void exterminate(ArrayList<Integer> numbers) { ArrayList<Integer> evenNumbersList = new ArrayList<Integer>(); if(numbers == null) { numbersList = null; } else { for(Integer num : numbers) { if(num % 2 == 0) { evenNumbersList.add(num); } } numbersList = evenNumbersList; } } public ArrayList<Integer> getNumbersList() { return numbersList; } public void setNumbersList(ArrayList<Integer> numbersList) { this.numbersList = numbersList; } }
package az.com.socar.workerpermission.model; import az.com.socar.workerpermission.persistance.entity.Permission; import az.com.socar.workerpermission.persistance.entity.User; public class NotificationDto extends PermissionModelDto { private Long fromUserId; private Long toUserId; private User user; private Permission permission; public Long getFromUserId() { return fromUserId; } public void setFromUserId(Long fromUserId) { this.fromUserId = fromUserId; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Long getToUserId() { return toUserId; } public void setToUserId(Long toUserId) { this.toUserId = toUserId; } public Permission getPermission() { return permission; } public void setPermission(Permission permission) { this.permission = permission; } }
package chapter06; import java.util.Scanner; public class Exercise06_06 { public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.println("Enter number"); int n=input.nextInt(); displayPattern(n); } public static void displayPattern(int n) { for (int i = 1; i <= n; i++) { for (int j = n -i; 0 < j; j--) { System.out.print(" "); } for (int k = i; 0 < k; k--) { System.out.printf("%-3d", k); } System.out.println(); } } }
package com.example.farahjabeen.gymmaster; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import android.widget.VideoView; import android.support.v7.widget.Toolbar; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerView; public class BicepCurlsActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener { public static final String API_KEY = "AIzaSyDnM32PTFmNpUMe1Izj81ITA6hjsZ2CZ14 \t"; public static final String VIDEO_ID = "3OZ2MT_5r3Q"; private Toolbar mToolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bicep_curls); mToolbar = (Toolbar) findViewById(R.id.atoolbar); setSupportActionBar(mToolbar); getSupportActionBar().setTitle("Biceps Curls"); YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube); youTubePlayerView.initialize(API_KEY , this); } private Toolbar getSupportActionBar() { return mToolbar; } private void setSupportActionBar(Toolbar mToolbar) { } @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) { youTubePlayer.setPlayerStateChangeListener(playerStateChangeListener); youTubePlayer.setPlaybackEventListener(playbackEventListener); if(!wasRestored) { youTubePlayer.cueVideo(VIDEO_ID); } } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) { Toast.makeText(this,"Failured to Initial state" ,Toast.LENGTH_LONG).show(); } private YouTubePlayer.PlaybackEventListener playbackEventListener = new YouTubePlayer.PlaybackEventListener() { @Override public void onPlaying() { } @Override public void onPaused() { } @Override public void onStopped() { } @Override public void onBuffering(boolean arg0) { } @Override public void onSeekTo(int arg0) { } }; private YouTubePlayer.PlayerStateChangeListener playerStateChangeListener = new YouTubePlayer.PlayerStateChangeListener() { @Override public void onLoading() { } @Override public void onLoaded(String arg0) { } @Override public void onAdStarted() { } @Override public void onVideoStarted() { } @Override public void onVideoEnded() { } @Override public void onError(YouTubePlayer.ErrorReason arg0) { } }; }
package org.camunda.bpm.example.loanapproval.rest; import java.util.HashSet; import java.util.Set; import javax.ws.rs.core.Application; import org.camunda.bpm.engine.rest.exception.ProcessEngineExceptionHandler; import org.camunda.bpm.engine.rest.exception.RestExceptionHandler; import org.camunda.bpm.engine.rest.impl.ProcessEngineRestServiceImpl; import org.camunda.bpm.engine.rest.mapper.JacksonConfigurator; import org.codehaus.jackson.jaxrs.JacksonJsonProvider; import org.codehaus.jackson.jaxrs.JsonMappingExceptionMapper; import org.codehaus.jackson.jaxrs.JsonParseExceptionMapper; public class RestProcessEngineDeployment extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> classes = new HashSet<Class<?>>(); classes.add(ProcessEngineRestServiceImpl.class); classes.add(JacksonConfigurator.class); classes.add(JacksonJsonProvider.class); classes.add(JsonMappingExceptionMapper.class); classes.add(JsonParseExceptionMapper.class); classes.add(ProcessEngineExceptionHandler.class); classes.add(RestExceptionHandler.class); return classes; } }
package com.smxknife.kafka.demo02; import org.apache.kafka.clients.consumer.*; import org.apache.kafka.common.TopicPartition; import java.time.Duration; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * @author smxknife * 2020/8/31 */ public class _02_4_Consumer_Manual_conmmitSync_with_partition_buffer_callback { public static void main(String[] args) { Properties properties = KafkaProperties.consumer(); properties.put(ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG, _02_2_ConsumerInterceptor.class.getName()); properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties); System.out.println("====== 禁止了自动提交,采用手动同步提交 (按分区粒度批量提交) ======="); String topic = "offset-test"; consumer.subscribe(Collections.singleton(topic)); int minBatchCommitSize = 10; Map<TopicPartition, Integer> partitionCounterMap = new ConcurrentHashMap<>(); while (true) { ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofSeconds(1)); Set<TopicPartition> partitions = consumerRecords.partitions(); partitions.forEach(partition -> { List<ConsumerRecord<String, String>> records = consumerRecords.records(partition); records.forEach(record -> { System.out.println("-- consume record : value = " + record.value() + " | offset = " + record.offset()); Integer counter = partitionCounterMap.compute(partition, (key, val) -> { int count = 1; if (Objects.nonNull(val)) { count = val + 1; } return count; }); System.out.println(">>>>>>>>>>>>>>>>> " + counter); long lastOffset = records.get(records.size() - 1).offset(); //records if (Objects.nonNull(counter) && counter.intValue() >= minBatchCommitSize) { System.out.println(partition + " counter = " + counter.intValue()); OffsetAndMetadata offsetAndMetadata = new OffsetAndMetadata(lastOffset + 1); consumer.commitSync(Collections.singletonMap(partition, offsetAndMetadata)); partitionCounterMap.put(partition, 0); } }); }); } } }
package com.ahmetkizilay.yatlib4j.lists.members; import com.ahmetkizilay.yatlib4j.oauthhelper.OAuthHolder; public class RemoveListMembers { private static final String BASE_URL = "https://api.twitter.com/1.1/lists/members/destroy.json"; private static final String HTTP_METHOD = "POST"; public static RemoveListMembers.Response sendRequest(RemoveListMembers.Parameters params, OAuthHolder oauthHolder) { throw new UnsupportedOperationException(); } public static class Response { } public static class Parameters { } }
package br.com.horadeaprender.iu; import android.content.Intent; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import br.com.horadeaprender.R; import br.com.horadeaprender.model.Questao; public class EnviarQuestaoActivity extends AppCompatActivity { public String TAG = "EnviarQuestaoActivity"; private ViewHolder vh; private Questao questao; FirebaseFirestore db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_enviar_questao); vh = new ViewHolder(); questao = new Questao(); db = FirebaseFirestore.getInstance(); carregarDados(); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return super.onSupportNavigateUp(); } @Override public void onBackPressed() { finish(); } private void carregarDados(){ // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.opcoes_simulado_aray, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner vh.spinnerOpSimulado.setAdapter(adapter); } public class ViewHolder { Spinner spinnerOpSimulado = findViewById(R.id.spinner_tipo_simulado); EditText edtPergunta = findViewById(R.id.edt_pergunta); EditText edtAlternativa = findViewById(R.id.edt_alternativa); EditText edtCorreta = findViewById(R.id.edt_correta); EditText edtComentario = findViewById(R.id.edt_comentario); Button buttonAdicionarAlternativa = findViewById(R.id.buttonAdicionarAlternativa); Button getButtonAdicionarComentario = findViewById(R.id.buttonAdicionarComentario); Button buttonVerPreview = findViewById(R.id.buttonVerPreview); Button buttonEnviar = findViewById(R.id.buttonEnviar); TextView textViewPreview = findViewById(R.id.textView_preview); public ViewHolder() { supportNaviagteUp(); buttonAdicionarAlternativa.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { questao.getAlternativas().add(edtAlternativa.getText().toString()); edtAlternativa.setText(""); Snackbar.make(v, "Alternativa adicionada!", Snackbar.LENGTH_LONG).setAction("Action", null).show(); } }); getButtonAdicionarComentario.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { questao.getComentarios().add(edtComentario.getText().toString()); edtComentario.setText(""); Snackbar.make(v, "comentário adicionado!", Snackbar.LENGTH_LONG).setAction("Action", null).show(); } }); buttonVerPreview.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { questao.setTipoSimulado(spinnerOpSimulado.getSelectedItem().toString()); questao.setEnuciado(edtPergunta.getText().toString()); questao.setAlternativaCorreta(edtCorreta.getText().toString()); textViewPreview.setText(questao.toString()); } }); buttonEnviar.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { questao.setTipoSimulado(spinnerOpSimulado.getSelectedItem().toString()); questao.setEnuciado(edtPergunta.getText().toString()); questao.setAlternativaCorreta(edtCorreta.getText().toString()); db.collection("simulados").document(questao.getTipoSimulado()).collection("perguntas") .add(questao) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { Log.d(TAG, "DocumentSnapshot written with ID: " + documentReference.getId()); finish(); telaSucesso(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); Toast.makeText(getApplicationContext(), "Erro ao enviar questão", Toast.LENGTH_SHORT).show(); onBackPressed(); } }); } }); } private void supportNaviagteUp() { getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } private void telaSucesso(){ Intent intent = new Intent(this, SucessoEnviaQuestaoActivity.class); startActivity(intent); } }
package com.example.fy.blog; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import com.example.fy.blog.ui.MainActivity; /** * Created by fy on 2016/3/19. */ public class WelcomePage extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = new View(this); view.setBackgroundResource(R.drawable.blog_start); setContentView(view); // Intent intent = new Intent(this,MainActivity.class); // startActivity(intent); AlphaAnimation aa = new AlphaAnimation(0.3f,1.0f); aa.setDuration(2000); view.startAnimation(aa); aa.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { startActivity(new Intent(WelcomePage.this,MainActivity.class)); // Intent intent = new Intent("android.intent.action.second"); // startActivity(intent); finish(); } @Override public void onAnimationRepeat(Animation animation) { } }); } }
package com.idleelf.stick; import android.graphics.PointF; import android.util.Log; /** * Stick class * * @author Yang Tao * */ public class Stick { private PointF mStartPoint; private PointF mEndPoint; private PointF mMiddlePoint; private float mAngle; private float mLength; /** * * @param startPoint * , coordinate of the start point * @param angle * , angle between the stick and y axis.Positive if * couter-clockwise. * @param length * , length of the stick. */ public Stick(PointF mMiddlePoint, int angle, float length) { this.mMiddlePoint = mMiddlePoint; this.mAngle = angle; this.mLength = length; this.mEndPoint = new PointF(); this.mStartPoint = new PointF(); calcPoint(); } public Stick() { this.mStartPoint = new PointF(); this.mEndPoint = new PointF(); this.mMiddlePoint = new PointF(); this.mAngle = 0; this.mLength = 0; } public void setAngle(int angle) { this.mAngle = angle; calcPoint(); Log.d("STICK DEMO", "angle=" + angle); } public PointF startPoint() { return this.mStartPoint; } public PointF endPoint() { return this.mEndPoint; } protected void calcPoint() { this.mStartPoint.x = this.mMiddlePoint.x + this.mLength * (float) Math.sin(toRad(this.mAngle)); this.mStartPoint.y = this.mMiddlePoint.y + this.mLength * (float) Math.cos(toRad(this.mAngle)); this.mEndPoint.x = this.mMiddlePoint.x - this.mLength * (float) Math.sin(toRad(this.mAngle)); this.mEndPoint.y = this.mMiddlePoint.y - this.mLength * (float) Math.cos(toRad(this.mAngle)); } private float toRad(float angle) { return (float) (angle / 180 * Math.PI); } @Override public String toString() { return "startPoint:(" + this.mStartPoint.x + "," + this.mEndPoint.y + "), endPoint:" + this.mEndPoint.x + "," + this.mEndPoint.y + ")"; } }
package com.hxsb.model.BUY_ERP_GET_REFUND_RECORD; import java.util.Date; public class SCM_HX07_Refundment2 { private Long billdtlid; private Long billid; private Integer dtlRefundstatus; private Date dtlRefundtime; private String dtlRefserialno; public Long getBilldtlid() { return billdtlid; } public void setBilldtlid(Long billdtlid) { this.billdtlid = billdtlid; } public Long getBillid() { return billid; } public void setBillid(Long billid) { this.billid = billid; } public Integer getDtlRefundstatus() { return dtlRefundstatus; } public void setDtlRefundstatus(Integer dtlRefundstatus) { this.dtlRefundstatus = dtlRefundstatus; } public Date getDtlRefundtime() { return dtlRefundtime; } public void setDtlRefundtime(Date dtlRefundtime) { this.dtlRefundtime = dtlRefundtime; } public String getDtlRefserialno() { return dtlRefserialno; } public void setDtlRefserialno(String dtlRefserialno) { this.dtlRefserialno = dtlRefserialno; } @Override public String toString() { return "SCM_HX07_Refundment2 [billdtlid=" + billdtlid + ", billid=" + billid + ", dtlRefundstatus=" + dtlRefundstatus + ", dtlRefundtime=" + dtlRefundtime + ", dtlRefserialno=" + dtlRefserialno + "]"; } }
public class Figure implements Cloneable { String color; Integer sqare; public Figure(String _color, Integer _sqare){ this.color = _color; this.sqare = _sqare; } public Figure(){} public Integer getSqare() { return sqare; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public void setSqare(Integer sqare) { this.sqare = sqare; } @Override public String toString() { return "Figure color: " + this.color + ", sqare = " + this.sqare + ". Hash = " + this.hashCode(); } public Figure clone() { try { return (Figure)super.clone(); } catch( CloneNotSupportedException ex ) { throw new InternalError(); } } @Override public boolean equals(Object obj) { if(obj == this) { return true; } if (obj instanceof Figure){ Figure o = (Figure) obj; return o.sqare.equals(this.sqare) && o.color.equals(this.color); } else return false; } }
public class E23 { public static void main(String[] args) { String word = "Mississippi"; String result = word.replace("i", "ii"); System.out.println("The length of the string " + result + " is: " + result.length()); result = result.replace("ss", "s"); System.out.println("The length of the string " + result + " is: " + result.length()); } }
package com.lxy.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 配置Servlet启动时加载 * @author 15072 * */ public class ServletDemo4 extends HttpServlet { /** * 默认的情况下第一次访问的时候init被调用 */ public void init() throws ServletException { System.out.println("init..."); // 初始化数据库的链接 } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 写的内容 // 获取表单输入的内容 // 自己逻辑,通过名称查询数据库,把张三的姓名查到了 // 把张三返回浏览器 System.out.println("doGet..."); response.getWriter().write("hello demo4..."); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.udacity.jdnd.course3.critter.dao; import com.udacity.jdnd.course3.critter.entity.Customer; import com.udacity.jdnd.course3.critter.entity.Employee; import com.udacity.jdnd.course3.critter.user.EmployeeSkill; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.time.DayOfWeek; import java.util.*; @Repository @Transactional public class EmployeeDaoImpl implements EmployeeDao { @Autowired NamedParameterJdbcTemplate jdbcTemplate; private static final String NAME = "name"; private static final String SKILLS = "skills"; private static final String DAYS_AVAILABLE = "days_available"; private static final String EMPLOYEE_ID = "employee_id"; private static final String FILTERED_SKILL_TABLE = "FILTERED_SKILL_TABLE"; private static final String DELETE_EMPLOYEE_SKILLS = "DELETE FROM employee_skills WHERE employee_id = :" + EMPLOYEE_ID; private static final String DELETE_EMPLOYEE_DAYS_AVAILABLE = "DELETE FROM employee_days_available WHERE employee_id = :" + EMPLOYEE_ID; private static final String SELECT_EMPLOYEE_BY_ID = "SELECT * FROM employee " + "WHERE id = :id"; private static final String INSERT_EMPLOYEE_SKILLS = "INSERT INTO employee_skills (employee_id, skills) " + "VALUES(:" + EMPLOYEE_ID + ", :" + SKILLS + ")"; private static final String SELECT_EMPLOYEE_SKILLS = "SELECT skills FROM employee_skills WHERE employee_id = :" + EMPLOYEE_ID; private static final String INSERT_EMPLOYEE_DAYS_AVAILABLE = "INSERT INTO employee_days_available (employee_id, days_available) " + "VALUES(:" + EMPLOYEE_ID + ", :" + DAYS_AVAILABLE + ")"; private static final String SELECT_EMPLOYEE_DAYS_AVAILABLE = "SELECT days_available FROM employee_days_available WHERE employee_id = :" + EMPLOYEE_ID; private static final String SELECT_EMPLOYEE_IDS_BY_DAYS_AVAILABLE_AND_SKILLS = "SELECT skill.employee_id FROM ("; private static final RowMapper<Employee> employeeRowMapper = new BeanPropertyRowMapper<>(Employee.class); @Override public Employee findEmployeeById(Long id) { Employee employee = jdbcTemplate.queryForObject( SELECT_EMPLOYEE_BY_ID, new MapSqlParameterSource().addValue("id", id), new BeanPropertyRowMapper<>(Employee.class)); employee.setSkills(getSkills(id)); employee.setDaysAvailable(getDays(id)); return employee; } @Override public Long addEmployee(Employee employee) { SimpleJdbcInsert sji = new SimpleJdbcInsert(jdbcTemplate.getJdbcTemplate()) .withTableName("employee") .usingGeneratedKeyColumns("id"); Long employeeId = sji.executeAndReturnKey(new BeanPropertySqlParameterSource(employee)).longValue(); // add skills to employee_skills addSkills(employeeId, employee.getSkills()); // add daysAvailable to employee_days_available addDaysAvailable(employeeId, employee.getDaysAvailable()); return employeeId; } @Override public void updateEmployee(Employee employee) { Long employeeId = employee.getId(); // update skills deleteSkills(employeeId); addSkills(employeeId, employee.getSkills()); // update days available deleteDaysAvailable(employeeId); addDaysAvailable(employeeId, employee.getDaysAvailable()); } @Override public List<Long> findEmployeesForService(Set<EmployeeSkill> skills, DayOfWeek day) { String filteredSkillTable = "SELECT employee_id FROM employee_skills"; if (skills != null && skills.size() > 0) { int index = 0; for (EmployeeSkill skill : skills) { if (index == 0) { filteredSkillTable += " WHERE skills = '" + skill.toString() + "'"; } else { filteredSkillTable += " OR skills = '" + skill.toString() + "'"; } index++; } filteredSkillTable += " GROUP BY employee_id HAVING count(employee_id)>" + (skills.size() - 1); } String query = SELECT_EMPLOYEE_IDS_BY_DAYS_AVAILABLE_AND_SKILLS + filteredSkillTable + ") skill INNER JOIN employee_days_available d " + "ON d.employee_id = skill.employee_id WHERE d.days_available = :" + DAYS_AVAILABLE; try { return jdbcTemplate.query( query, new MapSqlParameterSource() .addValue(DAYS_AVAILABLE, day.toString()), resultSet -> { List<Long> ids = new ArrayList<>(); while (resultSet.next()) { Long id = resultSet.getLong("employee_id"); if (!ids.contains(id)) { ids.add(id); } } return ids; } ); } catch (Exception e) { return new ArrayList<>(); } } private void deleteSkills(Long employeeId) { jdbcTemplate.update( DELETE_EMPLOYEE_SKILLS, new MapSqlParameterSource() .addValue(EMPLOYEE_ID, employeeId)); } private void addSkills(Long employeeId, Set<EmployeeSkill> skills) { if (skills != null) { for (EmployeeSkill skill : skills) { jdbcTemplate.update(INSERT_EMPLOYEE_SKILLS, new MapSqlParameterSource() .addValue(EMPLOYEE_ID, employeeId) .addValue(SKILLS, skill.toString()) ); } } } private void deleteDaysAvailable(Long employeeId) { jdbcTemplate.update( DELETE_EMPLOYEE_DAYS_AVAILABLE, new MapSqlParameterSource() .addValue(EMPLOYEE_ID, employeeId)); } private void addDaysAvailable(Long employeeId, Set<DayOfWeek> daysAvailable) { if (daysAvailable != null) { for (DayOfWeek day : daysAvailable) { jdbcTemplate.update(INSERT_EMPLOYEE_DAYS_AVAILABLE, new MapSqlParameterSource() .addValue(EMPLOYEE_ID, employeeId) .addValue(DAYS_AVAILABLE, day.toString()) ); } } } private Set<EmployeeSkill> getSkills(Long employeeId) { return jdbcTemplate.query( SELECT_EMPLOYEE_SKILLS, new MapSqlParameterSource() .addValue(EMPLOYEE_ID, employeeId), resultSet -> { Set<EmployeeSkill> skills = new HashSet<>(); while (resultSet.next()) { EmployeeSkill skill = EmployeeSkill.valueOf(resultSet.getString("skills")); skills.add(skill); } return skills; } ); } private Set<DayOfWeek> getDays(Long employeeId) { return jdbcTemplate.query( SELECT_EMPLOYEE_DAYS_AVAILABLE, new MapSqlParameterSource() .addValue(EMPLOYEE_ID, employeeId), resultSet -> { Set<DayOfWeek> days = new HashSet<>(); while (resultSet.next()) { DayOfWeek day = DayOfWeek.valueOf(resultSet.getString("days_available")); days.add(day); } return days; } ); } }
package unalcol.types.collection.vector; import unalcol.clone.Clone; import unalcol.service.ServiceCore; import unalcol.sort.Order; /** * <p>Title: SortedVector</p> * <p> * <p>Description: Insert operation for sorted vectors</p> * <p> * <p>Copyright: Copyright (c) 2009</p> * <p> * <p>Company: Kunsamu</p> * * @author Jonatan Gomez Perdomo * @version 1.0 */ public class SortedVector<T> extends Vector<T> { static { ServiceCore.set(SortedVector.class, Clone.class, new SortedVectorCloneService<Object>()); } protected SortedVectorSearch<T> search = new SortedVectorSearch<T>(); protected Order<T> order; public SortedVector(T[] buffer, int n, Order<T> order) { super(buffer, n); this.order = order; } public SortedVector(T[] buffer, Order<T> order) { super(buffer); this.order = order; } public SortedVector(Vector<T> buffer, Order<T> order) { super(buffer.buffer, buffer.size()); this.order = order; } public SortedVector(Order<T> order) { super(); this.order = order; } public int findIndex(T data) { return search.find(this, data, order); } public boolean add(T data) { int index = search.findRight(this, data, order); if (index == this.size()) { return super.add(data); } else { rightShift(index); this.buffer[index] = data; } return true; } public boolean set(int index, T data) throws IndexOutOfBoundsException { if ((0 <= index && index < size) && (size == 1 || (index == 0 && order.compare(data, buffer[1]) <= 0) || (index == size - 1 && order.compare(buffer[index - 1], data) <= 0) || (size > 2 && order.compare(buffer[index - 1], data) <= 0 && order.compare(data, buffer[index + 1]) <= 0))) { this.buffer[index] = data; return true; } else { throw new ArrayIndexOutOfBoundsException(index); } } public boolean add(int index, T data) throws IndexOutOfBoundsException { if ((0 <= index && index <= size) && (size == 0 || (index == 0 && order.compare(data, buffer[0]) <= 0) || (index == size && order.compare(buffer[index - 1], data) <= 0) || (size > 1 && order.compare(buffer[index - 1], data) <= 0 && order.compare(data, buffer[index]) <= 0))) { rightShift(index); this.buffer[index] = data; return true; } else { throw new ArrayIndexOutOfBoundsException(index); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package org.apache.clerezza.utils.smushing; import org.apache.clerezza.BlankNodeOrIRI; import org.apache.clerezza.Graph; import org.apache.clerezza.IRI; import org.apache.clerezza.Triple; import org.apache.clerezza.ontologies.OWL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * A utility to equate duplicate nodes in an Mgraph. This unifies owl:sameAs * resources. * * @author reto */ public class SameAsSmusher extends BaseSmusher { static final Logger log = LoggerFactory.getLogger(SameAsSmusher.class); /** * This will ensure that all properties of sameAs resources are associated * to the preferedIRI as returned by {@code getPreferedIRI} * * @param mGraph * @param owlSameStatements * @param addCanonicalSameAsStatements if true owl:sameAsStatements with the preferedIRI as object will be added */ public void smush(Graph mGraph, Graph owlSameStatements, boolean addCanonicalSameAsStatements) { log.info("Starting smushing"); // This hashmap contains a uri (key) and the set of equivalent uris (value) final Map<BlankNodeOrIRI, Set<BlankNodeOrIRI>> node2EquivalenceSet = new HashMap<BlankNodeOrIRI, Set<BlankNodeOrIRI>>(); log.info("Creating the sets of equivalent uris of each subject or object in the owl:sameAs statements"); // Determines for each subject and object in all the owl:sameAs statements the set of ewquivalent uris for (Iterator<Triple> it = owlSameStatements.iterator(); it.hasNext(); ) { final Triple triple = it.next(); final IRI predicate = triple.getPredicate(); if (!predicate.equals(OWL.sameAs)) { throw new RuntimeException("Statements must use only <http://www.w3.org/2002/07/owl#sameAs> predicate."); } final BlankNodeOrIRI subject = triple.getSubject(); //literals not yet supported final BlankNodeOrIRI object = (BlankNodeOrIRI) triple.getObject(); Set<BlankNodeOrIRI> equivalentNodes = node2EquivalenceSet.get(subject); // if there is not a set of equivalent uris then create a new set if (equivalentNodes == null) { equivalentNodes = node2EquivalenceSet.get(object); if (equivalentNodes == null) { equivalentNodes = new HashSet<BlankNodeOrIRI>(); } } else { Set<BlankNodeOrIRI> objectSet = node2EquivalenceSet.get(object); if ((objectSet != null) && (objectSet != equivalentNodes)) { //merge two sets for (BlankNodeOrIRI res : objectSet) { node2EquivalenceSet.remove(res); } for (BlankNodeOrIRI res : objectSet) { node2EquivalenceSet.put(res, equivalentNodes); } equivalentNodes.addAll(objectSet); } } // add both subject and object of the owl:sameAs statement to the set of equivalent uris equivalentNodes.add(subject); equivalentNodes.add(object); // use both uris in the owl:sameAs statement as keys for the set of equivalent uris node2EquivalenceSet.put(subject, equivalentNodes); node2EquivalenceSet.put(object, equivalentNodes); log.info("Sets of equivalent uris created."); } // This set contains the sets of equivalent uris Set<Set<BlankNodeOrIRI>> unitedEquivalenceSets = new HashSet<Set<BlankNodeOrIRI>>(node2EquivalenceSet.values()); smush(mGraph, unitedEquivalenceSets, addCanonicalSameAsStatements); } }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final import java.math.BigDecimal; import java.util.HashSet; import java.util.Set; /** * JbpmProcessdefinition generated by hbm2java */ public class JbpmProcessdefinition implements java.io.Serializable { private BigDecimal id; private JbpmNode jbpmNode; private String name; private Long version; private Boolean isterminationimplicit; private Set jbpmActions = new HashSet(0); private Set jbpmDelegations = new HashSet(0); private Set jbpmModuledefinitions = new HashSet(0); private Set jbpmNodesForProcessdefinition = new HashSet(0); private Set jbpmProcessinstances = new HashSet(0); private Set jbpmTasks = new HashSet(0); private Set jbpmEvents = new HashSet(0); private Set jbpmTransitions = new HashSet(0); private Set jbpmNodesForSubprocessdefinition = new HashSet(0); public JbpmProcessdefinition() { } public JbpmProcessdefinition(BigDecimal id) { this.id = id; } public JbpmProcessdefinition(BigDecimal id, JbpmNode jbpmNode, String name, Long version, Boolean isterminationimplicit, Set jbpmActions, Set jbpmDelegations, Set jbpmModuledefinitions, Set jbpmNodesForProcessdefinition, Set jbpmProcessinstances, Set jbpmTasks, Set jbpmEvents, Set jbpmTransitions, Set jbpmNodesForSubprocessdefinition) { this.id = id; this.jbpmNode = jbpmNode; this.name = name; this.version = version; this.isterminationimplicit = isterminationimplicit; this.jbpmActions = jbpmActions; this.jbpmDelegations = jbpmDelegations; this.jbpmModuledefinitions = jbpmModuledefinitions; this.jbpmNodesForProcessdefinition = jbpmNodesForProcessdefinition; this.jbpmProcessinstances = jbpmProcessinstances; this.jbpmTasks = jbpmTasks; this.jbpmEvents = jbpmEvents; this.jbpmTransitions = jbpmTransitions; this.jbpmNodesForSubprocessdefinition = jbpmNodesForSubprocessdefinition; } public BigDecimal getId() { return this.id; } public void setId(BigDecimal id) { this.id = id; } public JbpmNode getJbpmNode() { return this.jbpmNode; } public void setJbpmNode(JbpmNode jbpmNode) { this.jbpmNode = jbpmNode; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Long getVersion() { return this.version; } public void setVersion(Long version) { this.version = version; } public Boolean getIsterminationimplicit() { return this.isterminationimplicit; } public void setIsterminationimplicit(Boolean isterminationimplicit) { this.isterminationimplicit = isterminationimplicit; } public Set getJbpmActions() { return this.jbpmActions; } public void setJbpmActions(Set jbpmActions) { this.jbpmActions = jbpmActions; } public Set getJbpmDelegations() { return this.jbpmDelegations; } public void setJbpmDelegations(Set jbpmDelegations) { this.jbpmDelegations = jbpmDelegations; } public Set getJbpmModuledefinitions() { return this.jbpmModuledefinitions; } public void setJbpmModuledefinitions(Set jbpmModuledefinitions) { this.jbpmModuledefinitions = jbpmModuledefinitions; } public Set getJbpmNodesForProcessdefinition() { return this.jbpmNodesForProcessdefinition; } public void setJbpmNodesForProcessdefinition(Set jbpmNodesForProcessdefinition) { this.jbpmNodesForProcessdefinition = jbpmNodesForProcessdefinition; } public Set getJbpmProcessinstances() { return this.jbpmProcessinstances; } public void setJbpmProcessinstances(Set jbpmProcessinstances) { this.jbpmProcessinstances = jbpmProcessinstances; } public Set getJbpmTasks() { return this.jbpmTasks; } public void setJbpmTasks(Set jbpmTasks) { this.jbpmTasks = jbpmTasks; } public Set getJbpmEvents() { return this.jbpmEvents; } public void setJbpmEvents(Set jbpmEvents) { this.jbpmEvents = jbpmEvents; } public Set getJbpmTransitions() { return this.jbpmTransitions; } public void setJbpmTransitions(Set jbpmTransitions) { this.jbpmTransitions = jbpmTransitions; } public Set getJbpmNodesForSubprocessdefinition() { return this.jbpmNodesForSubprocessdefinition; } public void setJbpmNodesForSubprocessdefinition(Set jbpmNodesForSubprocessdefinition) { this.jbpmNodesForSubprocessdefinition = jbpmNodesForSubprocessdefinition; } }
package com.fleet.markdown.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import org.springframework.web.servlet.ViewResolver; @Component @Configuration public class MarkdownConfig { @Bean public ViewResolver viewResolver() { MarkdownViewResolver viewResolver = new MarkdownViewResolver(); viewResolver.setSuffix(".md"); return viewResolver; } }
package com.advancetopics.testcases; import java.io.File; import java.io.FileInputStream; import java.util.concurrent.TimeUnit; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openqa.selenium.WebDriver; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.fb.testcases.CommonUtility; import com.hrms.pages.LoginPage; import com.hrms.synerzip.Constants; public class ReadNumericData { WebDriver driver; @BeforeMethod() public void setup(){ driver=CommonUtility.setupFirefoxBrowser(); } @Test() public void readJxlData() { driver.get(Constants.URL); driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS); try{ File excelfile = new File("AdvanceSeleniumTestData\\testdata.xlsx"); FileInputStream fis = new FileInputStream(excelfile); XSSFWorkbook wb=new XSSFWorkbook(fis); XSSFSheet sh1= wb.getSheetAt(0); String username =sh1.getRow(1).getCell(0).getStringCellValue(); String password=sh1.getRow(1).getCell(1).getStringCellValue(); LoginPage login=new LoginPage(driver); login.loginTohrms(username,password); }catch(Exception e){ System.out.println(e.getMessage()); } } }
package com.goldgov.gtiles.core.web.remotecall; import java.io.IOException; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.net.URISyntaxException; import java.util.ResourceBundle; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import com.goldgov.gtiles.core.Keys; import com.goldgov.gtiles.core.install.InstallInfo; import com.goldgov.gtiles.core.web.GTilesContext; import com.goldgov.gtiles.core.web.remotecall.config.RemoteConfigLoader; import com.goldgov.gtiles.core.web.remotecall.config.impl.FileRemoteConfigLoader; import com.goldgov.gtiles.utils.SpringBeanUtils; /** * 远程服务健康检查,用于检查路由表中配置的服务器信息是否处于服务中的状态, * 可能根据远程系统返回的健康状态同时返回一些定义的交互信息,需配合{@link com.goldgov.gtiles.core.web.remotecall.HealthReportServlet HealthReportServlet}使用 * @author LiuHG * @version 1.0 * @see {@link com.goldgov.gtiles.core.web.remotecall.HealthReportServlet HealthReportServlet} */ public abstract class RemoteServiceHealthCheck { private ResourceBundle config = ResourceBundle.getBundle("config"); public static final String HEALTH_CHECK_REQUEST = "gtiles/healthCheck"; private Log logger = LogFactory.getLog(this.getClass()); private Timer timer = new Timer("RemoteServiceHealthCheck"); private int checkPeriod = 300000; private RemoteConfigLoader remoteConfigLoader; private int connectTimeout = 30000; private boolean isRunning = false; public void start(){ start(-1); } public void start(int period){ try { String enableHealthCheck = config.getString("healthCheck_enable"); if(!Boolean.valueOf(enableHealthCheck)){ return; } } catch (Exception e) { return; } if(isRunning){ return; } if(period <= 0){ period = checkPeriod; } loadRemoteConfig(); timer.schedule(new TimerTask(){ @Override public void run() { if(!remoteConfigLoader.onlyOnce()){ loadRemoteConfig(); } HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); CloseableHttpClient httpClient = httpClientBuilder.build(); processTasksWithRemoteConfig(httpClient); try { httpClient.close(); } catch (IOException e) {} }}, period,period); isRunning = true; } protected RemoteConfig[] loadRemoteConfig(){ if(remoteConfigLoader == null){ try { remoteConfigLoader = SpringBeanUtils.getBean(RemoteConfigLoader.class); } catch (Exception e) { remoteConfigLoader = new FileRemoteConfigLoader(); } } RemoteConfig[] routeConfigs = remoteConfigLoader.load(); GTilesContext.clearRemoteConfigs(); for (RemoteConfig remoteConfig : routeConfigs) { GTilesContext.putRemoteConfigs(remoteConfig,false); } return routeConfigs; } public void processTasksWithRemoteConfig(CloseableHttpClient httpClient){ RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(connectTimeout) .setConnectTimeout(connectTimeout) .build(); Set<RemoteConfig> remoteConfigs = GTilesContext.getRemoteConfigs().keySet(); for (RemoteConfig remoteConfig : remoteConfigs) { logger.info("开始检测远程服务:"+remoteConfig.getHostName()); HttpPost httpPost = null; try { httpPost = new HttpPost(remoteConfig.getAliveCheckUrl().toURI()); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } httpPost.setConfig(requestConfig); InstallInfo installInfo = GTilesContext.getInstallInfo(); httpPost.addHeader(Keys.REMOTE_INFO_HEADER_NAME, new String(installInfo.getSignature())); CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); // ByteArrayOutputStream responeOutputStream = new ByteArrayOutputStream(); // FileCopyUtils.copy(entity.getContent(), responeOutputStream); // if(checkResponesState(response)){ logger.info("远程服务活动中:"+remoteConfig.getHostName()); doTask(entity,remoteConfig); GTilesContext.putRemoteConfigs(remoteConfig,true); } EntityUtils.consume(response.getEntity()); } catch (ConnectTimeoutException e) { clearUnavailableRoute(remoteConfig); logger.warn("连接远程服务器Connect超时(" + connectTimeout + "ms):"+remoteConfig.getHostName()); } catch (SocketTimeoutException e) { clearUnavailableRoute(remoteConfig); logger.warn("连接远程服务器Socket超时(" + connectTimeout + "ms):"+remoteConfig.getHostName()); } catch (ClientProtocolException e) { clearUnavailableRoute(remoteConfig); throw new RuntimeException("连接远程服务器发生错误", e); } catch (ConnectException e) { logger.warn("连接远程服务器中断,目标服务器可能已经停止:"+remoteConfig.getHostName()); clearUnavailableRoute(remoteConfig); } catch (IOException e) { clearUnavailableRoute(remoteConfig); throw new RuntimeException("连接远程服务器发生I/O错误", e); } finally { if(response != null){ try { response.close(); } catch (IOException e) {} } } } } /** * 清除指定的路由配置为失效 * @param remoteConfig */ protected void clearUnavailableRoute(RemoteConfig remoteConfig){ GTilesContext.putRemoteConfigs(remoteConfig,false); } private boolean checkResponesState(CloseableHttpResponse response) { StatusLine statusLine = response.getStatusLine(); if(statusLine.getStatusCode() == HttpServletResponse.SC_NOT_FOUND){ logger.warn("获取远程模块信息错误,远程未开启模块侦测地址功能"); return false; }else if(statusLine.getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED){ logger.warn("获取远程模块信息错误,您没有权限进行模块信息的获取"); return false; }else if(statusLine.getStatusCode() >= HttpServletResponse.SC_INTERNAL_SERVER_ERROR){ logger.error("获取远程模块信息错误,服务器端发生异常"); return false; }else if(statusLine.getStatusCode() == HttpServletResponse.SC_MOVED_TEMPORARILY){ Header[] headers = response.getHeaders("Location"); if(headers != null){ for (Header header : headers) { if(header.getValue().indexOf("/install/installWizard") != -1){ logger.error("获取远程模块信息错误,远程目标系统可能尚未安装成功"); return false; } } } logger.error("获取远程模块信息错误,发生HTTP 302 未知错误"); return false; } return true; } public boolean isRunning(){ return isRunning; } public abstract void doTask(HttpEntity entity, RemoteConfig remoteConfig) throws IOException; public void setRemoteConfigLoader(RemoteConfigLoader remoteConfigLoader) { this.remoteConfigLoader = remoteConfigLoader; } // public void addTask(HealthTask task) { // if(!tasks.contains(task)){ // tasks.add(task); // } // } }
// // GCALDaemon is an OS-independent Java program that offers two-way // synchronization between Google Calendar and various iCalalendar (RFC 2445) // compatible calendar applications (Sunbird, Rainlendar, iCal, Lightning, etc). // // Apache License // Version 2.0, January 2004 // http://www.apache.org/licenses/ // // Project home: // http://gcaldaemon.sourceforge.net // package org.gcaldaemon.gui.editors; import java.awt.BorderLayout; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JLabel; import javax.swing.JTextField; import org.gcaldaemon.gui.ConfigEditor; import org.gcaldaemon.gui.Messages; import org.gcaldaemon.gui.config.MainConfig; /** * String property editor. * * Created: May 25, 2007 20:00:00 PM * * @author Andras Berkes */ public final class StringEditor extends AbstractEditor implements KeyListener { // --- SERIALVERSION --- private static final long serialVersionUID = -6372164282525166544L; // --- GUI --- private final JLabel label = new JLabel(); private final JTextField field = new JTextField(); // --- CONSTRUCTOR --- public StringEditor(MainConfig config, ConfigEditor editor, String key, String defaultValue) throws Exception { super(config, editor, key); BorderLayout borderLayout = new BorderLayout(); borderLayout.setHgap(5); setLayout(borderLayout); add(label, BorderLayout.WEST); add(field, BorderLayout.CENTER); label.setText(Messages.getString(key) + ':'); field.setText(config.getConfigProperty(key, defaultValue)); field.addKeyListener(this); label.setPreferredSize(LABEL_SIZE); } // --- VALUE CHANGED --- public final void keyReleased(KeyEvent evt) { String path = field.getText(); path = path.replace('\\', '/'); if (!path.equals(config.getConfigProperty(key, ""))) { config.setConfigProperty(key, path); editor.status(key, path); } } public final void keyPressed(KeyEvent evt) { } public final void keyTyped(KeyEvent evt) { } }
package com.TokChatBackend.daosImpl; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.TokChatBackend.daos.BlogDao; import com.TokChatBackend.models.Blog; import com.TokChatBackend.models.BlogComment; @Repository("blogDao") @Transactional public class BlogDaoImpl implements BlogDao { @Autowired SessionFactory sessionfactory; @Override public boolean addBlog(Blog blogobj) { try{ System.out.println(blogobj.getBlogName()+" "+blogobj.getBlogContext()); Session session=sessionfactory.getCurrentSession(); session.saveOrUpdate(blogobj); return true; } catch(Exception e) { e.printStackTrace(); } return false; } @Override public boolean deleteBlog(Blog blog) { try{ Session session=sessionfactory.getCurrentSession(); session.delete(blog); return true; } catch(Exception e) { e.printStackTrace(); } return false; } @Override public boolean updateBlog(Blog blog) { try{ Session session=sessionfactory.getCurrentSession(); session.update(blog); return true; } catch(Exception e) { e.printStackTrace(); } return false; } @Override public Blog getBlog(int blogId) { try{ Session session=sessionfactory.getCurrentSession(); Blog blog =(Blog)session.get(Blog.class, blogId); return blog; } catch(Exception e) { e.printStackTrace(); } return null; } @Override public boolean approveBlog(Blog blog) { try{ Session session=sessionfactory.getCurrentSession(); blog.setStatus("Approved"); session.update(blog); return true; } catch(Exception e) { e.printStackTrace(); } return false; } @Override public boolean rejectBlog(Blog blog) { try{ Session session=sessionfactory.getCurrentSession(); blog.setStatus("Rejected"); session.update(blog); return true; } catch(Exception e) { e.printStackTrace(); } return false; } @Override public List<Blog> listBlogs(String email,String role) { try{ Session session=sessionfactory.getCurrentSession(); Query querry=null; if(role.equals("Role_User")){ querry=session.createQuery("from Blog where email=:abc"); querry.setParameter("abc",email); } else { querry=session.createQuery("from Blog"); } List<Blog> blogList=querry.list(); return blogList; } catch(Exception e) { e.printStackTrace(); } return null; } @Override public List<Blog> listAllApprovedBlogs() { try{ Session session=sessionfactory.getCurrentSession(); Query querry=session.createQuery("from Blog where status='Approved'"); List<Blog> blogList=querry.list(); return blogList; } catch(Exception e) { e.printStackTrace(); } return null; } @Override public List<Blog> listPendingBlogs() { try{ Session session=sessionfactory.getCurrentSession(); Query querry=session.createQuery("from Blog where status='Pending'"); List<Blog> blogList=querry.list(); return blogList; } catch(Exception e) { e.printStackTrace(); } return null; } @Override public boolean incrementLikes(Blog blog) { try{ Session session=sessionfactory.getCurrentSession(); session.update(blog); return true; } catch(Exception e) { e.printStackTrace(); } return false; } @Override public boolean addBlogComment(BlogComment blogComment) { try{ Session session=sessionfactory.getCurrentSession(); session.saveOrUpdate(blogComment); return true; } catch(Exception e) { e.printStackTrace(); } return false; } @Override public boolean deleteBlogComment(BlogComment blogComment) { try{ Session session=sessionfactory.getCurrentSession(); session.delete(blogComment); return true; } catch(Exception e) { e.printStackTrace(); } return false; } @Override public BlogComment getBlogComment(int commentId) { try{ Session session=sessionfactory.getCurrentSession(); BlogComment blogcom=(BlogComment)session.get(BlogComment.class, commentId); return blogcom; } catch(Exception e) { e.printStackTrace(); } return null; } @Override public List<BlogComment> listBlogComments(int blogId) { try{ Session session=sessionfactory.getCurrentSession(); Query querry=session.createQuery("from BlogComment"); List<BlogComment> blogCommentList=querry.list(); return blogCommentList; } catch(Exception e) { e.printStackTrace(); } return null; } }
package Keming; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.UUID; // // 扫描整个硬盘目录,检查程序的工作情况。并做出修改 // // public class Find12 extends HashMap<String, String>{ final static String DISKINFONAME = "diskinfo.dat"; final static int ID=0; final static int TYPE=1; final static int PATH=2; final static int SIZE=3; static String[] frecFields = new String[4]; static FileWriter diskinfoWriter; public Find12(File diskinfo) throws IOException { super(); load(diskinfo); diskinfoWriter = new FileWriter(DISKINFONAME); } @Override public String put(String key, String value) { // // save parent-son pair into file // try { String output = key + "\t" + value + "\n"; diskinfoWriter.write( output ); System.out.print(output); } catch (IOException e) { e.printStackTrace(); } // // accumulate existing value and save it // String savedValue = get(key); if( savedValue == null ) { savedValue = value; } else { savedValue += "<-->" + value ; } // String[] uuids = savedValue.split("<-->"); // for(String uuid : uuids) { // if ( uuid.length()!=36 ) { // System.out.println("DEBUG"); // } // } return super.put(key, savedValue); } public void load(File diskinfo) throws IOException { InputStream is; try { is = new FileInputStream(diskinfo); BufferedReader buf = new BufferedReader(new InputStreamReader(is)); String line = buf.readLine(); while(line != null) { String[] columns = line.split("\t"); // System.out.print(columns.length+ "\t" + line + "\n); if( columns.length == 2) { String value = get(columns[0]); if( value == null ) { value = ""; } value += columns[1] + "<-->"; super.put(columns[0], value); } else { is.close(); if ( new File(DISKINFONAME).delete() ) { return; } else { throw new IOException(DISKINFONAME + " has wrong data format. please delete it."); } } line = buf.readLine(); } is.close(); System.out.println(this); } catch (FileNotFoundException e) { e.printStackTrace(); } } static public String merge(String[] frecFields) { StringBuilder sb = new StringBuilder(); for(int i=0; i<frecFields.length; i++) { sb.append( frecFields[i] ); if(i<frecFields.length - 1 ) { sb.append("\t"); } } return sb.toString(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); for(String key : this.keySet() ) { String value = this.get(key); sb.append(key); sb.append("\t"); sb.append(value); sb.append("\n"); } return sb.toString(); } public void close() throws IOException { diskinfoWriter.close(); } // // 增加FNodeDB保存每个文件的信息。从文件系统角度看,每一个目录或者文件可被称罚一个文件结点 // 所有文件结点的焦点,数据库。这个例子里,使用字符串来记录数据,每一行代表一条记录,记录一个 // 文件结点的全部信息,包括唯一ID,路径,文件大小等,用制表符分开 // static class FNodeDB { final static String FNODEDBNAME = "fnodedb.dat"; static FileWriter fnodeWriter; static HashMap<String, String> idMap; static HashMap<String, String> pathMap; static FileInputStream fis; public FNodeDB() throws IOException { idMap = new HashMap<String, String>(); pathMap = new HashMap<String, String>(); load(); fnodeWriter = new FileWriter(FNODEDBNAME, true); } public void load() throws IOException { try { fis = new FileInputStream(new File(FNODEDBNAME)); BufferedReader buf = new BufferedReader(new InputStreamReader(fis)); String line = buf.readLine(); while(line != null) { // System.out.print(columns.length+ "\t" + line + "\n"); frecFields = line.split("\t"); idMap.put(frecFields[ID], line); pathMap.put(frecFields[PATH], line); line = buf.readLine(); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if( fis !=null ) { fis.close(); } } } public String recorderSave(File directory) throws IOException { String uuidString; String fnoderec = pathMap.get(directory.getAbsolutePath()); if ( fnoderec==null ) { uuidString = UUID.randomUUID().toString(); frecFields[ID] = uuidString; frecFields[PATH] = directory.getAbsolutePath(); if( directory.isDirectory() ) frecFields[TYPE] = "d"; else frecFields[TYPE] = "f"; frecFields[SIZE] = new Long(directory.length()).toString(); fnoderec = merge(frecFields); idMap.put(uuidString, fnoderec); pathMap.put(directory.getAbsolutePath(), fnoderec); // if( fnoderec.charAt(fnoderec.length()-1) == '\n') { // System.out.println("debug"); // } fnodeWriter.write( fnoderec + "\n" ); } else { frecFields = fnoderec.split("\t"); } return frecFields[ID]; } public void close() throws IOException { fnodeWriter.close(); } } static FNodeDB fnodeDB; public void tree2map(File directory) throws IOException { fnodeDB = new FNodeDB(); _tree2map(directory, null); fnodeDB.close(); } public void _tree2map(File directory, String parentUUID) throws IOException { String uuid = fnodeDB.recorderSave(directory); // if( uuid.length() != 36 ) // System.out.println(uuid.length()); if( parentUUID == null ) { this.put("root", uuid); } else { this.put(parentUUID, uuid); } File[] subfiles = directory.listFiles(); if( subfiles != null ) { for( File subfile : subfiles ) { _tree2map(subfile, uuid); } } } public void map2tree() { _map2tree(this.get("root"), "", "."); } private String fnodeInfo(String[] fields) { if( fields.length < 4) { return fields[0]; } else { String path = fields[PATH]; String dirs[] = path.split("\\\\"); String filename = dirs[dirs.length-1]; return filename + "\t" + fields[SIZE]; } } public void _map2tree(String directoryUUID, String indent, String fnodedbRec) { frecFields = fnodedbRec.split("\t"); System.out.println(indent + "\\--" + fnodeInfo(frecFields) ); String subfileSet = this.get(directoryUUID); if(subfileSet!=null) { String[] subfiles = this.get(directoryUUID).split("<-->"); for(int i=0; i<subfiles.length; i++) { String subfileUUID = subfiles[i]; String fnodedbRec2 = FNodeDB.idMap.get(subfileUUID); if( i < subfiles.length - 1 ) _map2tree( subfileUUID, indent + " |", fnodedbRec2 ); else _map2tree( subfileUUID, indent + " ", fnodedbRec2 ); } } } static public void test(String filename) throws IOException { FileInputStream fis = null; try { fis = new FileInputStream(new File(filename)); BufferedReader buf = new BufferedReader(new InputStreamReader(fis)); String line = buf.readLine(); while(line != null) { System.out.print( line + "\n"); line = buf.readLine(); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if( fis !=null ) { fis.close(); } } } public static void main(String[] argv) throws IOException { // new File(DISKINFONAME).delete(); // new File(FNodeDB.FNODEDBNAME).delete(); Find12 diskinfo = new Find12(new File(DISKINFONAME)); diskinfo.tree2map(new File(".")); diskinfo.close(); diskinfo.map2tree(); } }
/** * Implementation of a Linked List with an Object reference as data; forward and backward links point to adjacent Nodes. * */ public class LinkedList { private Object opaqueObject; private LinkedList prevNode; private LinkedList nextNode; /** * Constructs a new element with object objValue, * followed by object address * * @param opaqueObject Address of Object */ public LinkedList(Object opaqueObject, LinkedList node) { setObject(opaqueObject); setPrevNode(node); setNextNode(null); } /** * Clone an object, * * @param node object to clone */ public LinkedList(LinkedList node) { opaqueObject = node.opaqueObject; prevNode = node.prevNode; nextNode = node.nextNode; } /** * Setter for opaqueObjecg in LinkedList object * * @param opaqueObject Address of Object */ public void setObject(Object opaqueObject) { this.opaqueObject = opaqueObject; } /** * Setter for prevNode in LinkedList object * * @node A LinkedList object that is prevNode to current Object */ public void setPrevNode(LinkedList node) { this.prevNode = node; } /** * Setter for nextNode in LinkedList object * * @node A LinkedList object that is nextNode to current Object */ public void setNextNode(LinkedList node) { this.nextNode = node; } /** * Returns opaqueObject for this element * * @return The opaqueObject associated with this element */ public Object getObject() { return opaqueObject; } /** * Returns reference to previous object in list * * @return The pointer is to the previous object in the list */ public LinkedList getPrevious() { return prevNode; } /** * Returns reference to next object in list * * @return The pointer is to the next object in the list */ public LinkedList getNext() { return nextNode; } }
package com.macapps.developer.extratime.provider; import android.net.Uri; import android.provider.BaseColumns; /** * Created by Developer on 24/7/2017. */ public class ActionContract { public static final String AUTHORITY="com.macapps.developer.extratime.provider"; public static final Uri BASE_CONTENT_URI= Uri.parse("content://"+AUTHORITY); public static final String PATH_ACTIONS="actions"; public static final class ActionEntry implements BaseColumns{ public static final Uri CONTENT_URI= BASE_CONTENT_URI.buildUpon().appendPath(PATH_ACTIONS).build(); public static final String TABLE_NAME="actions"; public static final String COLUMN_ACTION_ID="actionID"; public static final String COLUMN_ACTION_LOGO="actionLOGO"; public static final String COLUMN_ACTION_HOURS="actionHOURS"; } }
package library.common; public class tSalesProductHeaderData { public synchronized String get_intIdAbsenUser() { return _intIdAbsenUser; } public synchronized void set_intIdAbsenUser(String _intIdAbsenUser) { this._intIdAbsenUser = _intIdAbsenUser; } public synchronized String get_intSync() { return _intSync; } public synchronized void set_intSync(String _intSync) { this._intSync = _intSync; } public synchronized String get_txtBranchCode() { return _txtBranchCode; } public synchronized void set_txtBranchCode(String _txtBranchCode) { this._txtBranchCode = _txtBranchCode; } public synchronized String get_txtBranchName() { return _txtBranchName; } public synchronized void set_txtBranchName(String _txtBranchName) { this._txtBranchName = _txtBranchName; } public synchronized String get_intSubmit() { return _intSubmit; } public synchronized void set_intSubmit(String _intSubmit) { this._intSubmit = _intSubmit; } public synchronized String get_intSumItem() { return _intSumItem; } public synchronized void set_intSumItem(String _intSumItem) { this._intSumItem = _intSumItem; } public synchronized String get_intSumAmount() { return _intSumAmount; } public synchronized void set_intSumAmount(String _intSumAmount) { this._intSumAmount = _intSumAmount; } public synchronized String get_UserId() { return _UserId; } public synchronized void set_UserId(String _UserId) { this._UserId = _UserId; } public synchronized String get_intId() { return _intId; } public synchronized void set_intId(String _intId) { this._intId = _intId; } public synchronized String get_txtNIK() { return _txtNIK; } public synchronized void set_txtNIK(String _txtNIK) { this._txtNIK = _txtNIK; } public synchronized String get_txtKeterangan() { return _txtKeterangan; } public synchronized void set_txtKeterangan(String _txtKeterangan) { this._txtKeterangan = _txtKeterangan; } public synchronized String get_dtDate() { return _dtDate; } public synchronized void set_dtDate(String _dtDate) { this._dtDate = _dtDate; } public synchronized String get_OutletCode() { return _OutletCode; } public synchronized void set_OutletCode(String _OutletCode) { this._OutletCode = _OutletCode; } public synchronized String get_OutletName() { return _OutletName; } public synchronized void set_OutletName(String _OutletName) { this._OutletName = _OutletName; } private String _intId; private String _txtNIK; private String _txtKeterangan; private String _dtDate; private String _OutletCode; private String _OutletName; private String _intSumItem; private String _intSumAmount; private String _UserId; private String _intSubmit; private String _intSync; private String _txtBranchCode; private String _txtBranchName; private String _intIdAbsenUser; public String Property_UserId="UserId"; public String Property_intSumItem="intSumItem"; public String Property_intSumAmount="intSumAmount"; public String Property_intId="intId"; public String Property_txtNIK="txtNIK"; public String Property_txtKeterangan="txtKeterangan"; public String Property_txtDate="dtDate"; public String Property_OutletCode="OutletCode"; public String Property_OutletName="OutletName"; public String Property_intSubmit="intSubmit"; public String Property_intSync="intSync"; public String Property_txtBranchCode="txtBranchCode"; public String Property_txtBranchName="txtBranchName"; public String Property_intIdAbsenUser="intIdAbsenUser"; public String Property_ListOftSalesProductHeaderData="ListOftSalesProductHeaderData"; public tSalesProductHeaderData() { super(); // TODO Auto-generated constructor stub } public String Property_All=Property_intId +","+ Property_OutletCode +","+ Property_OutletName +","+ Property_txtDate +","+ Property_txtKeterangan +","+ Property_txtNIK +","+ Property_intSumAmount +","+ Property_intSumItem +","+ Property_UserId +","+ Property_intSubmit +","+ Property_intSync +","+ Property_txtBranchCode +","+ Property_txtBranchName+","+Property_intIdAbsenUser ; }
package com.microsilver.mrcard.basicservice.dto; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @JsonInclude(value=Include.NON_NULL) @Data public class RespBaseDto<T> { @ApiModelProperty(value = "状态码") private int state = 0; @ApiModelProperty(value = "信息") private String message; @ApiModelProperty(value = "泛型") private T data; }
package com.qrpos.model.json; import java.io.Serializable; import java.math.BigDecimal; public class FisKaydetSonucJson implements Serializable { private static final long serialVersionUID = -5376633737912498989L; private int status; private Long hataKodu; private String hataDetay; private String uyeIsim; private BigDecimal oncekiBakiye; private BigDecimal kalanBakiye; public FisKaydetSonucJson() { super(); } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Long getHataKodu() { return hataKodu; } public void setHataKodu(Long hataKodu) { this.hataKodu = hataKodu; } public String getHataDetay() { return hataDetay; } public void setHataDetay(String hataDetay) { this.hataDetay = hataDetay; } public BigDecimal getOncekiBakiye() { return oncekiBakiye; } public void setOncekiBakiye(BigDecimal oncekiBakiye) { this.oncekiBakiye = oncekiBakiye; } public BigDecimal getKalanBakiye() { return kalanBakiye; } public void setKalanBakiye(BigDecimal kalanBakiye) { this.kalanBakiye = kalanBakiye; } public String getUyeIsim() { return uyeIsim; } public void setUyeIsim(String uyeIsim) { this.uyeIsim = uyeIsim; } }
package com.ssm.lab.dto; import com.ssm.lab.bean.ExperimentWorkload; import com.ssm.lab.bean.ExperimentWorkloadItem; import java.util.List; public class ExperimentWorkloadInfo { private ExperimentWorkload workload; private List<ExperimentWorkloadItem> items; public ExperimentWorkload getWorkload() { return workload; } public void setWorkload(ExperimentWorkload workload) { this.workload = workload; } public List<ExperimentWorkloadItem> getItems() { return items; } public void setItems(List<ExperimentWorkloadItem> items) { this.items = items; } }
package com.sample.bitnotifier.ui.dialog; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.sample.bitnotifier.R; import com.sample.bitnotifier.application.BitNotifierApplication; import com.sample.bitnotifier.interfaces.OnDataChangeListener; import com.sample.bitnotifier.model.BitCoin; import com.sample.bitnotifier.model.BitCoinModel; import com.sample.bitnotifier.utils.SharedPrefUtils; import java.util.Locale; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class EditDialogFragment extends DialogFragment { @Inject SharedPrefUtils sharedPrefUtils; @BindView(R.id.last_traded_price) TextView lastTradedPrice; @BindView(R.id.value) EditText valueEdit; @BindView(R.id.range) EditText rangeEdit; @BindView(R.id.notification) Button notification; private OnDataChangeListener listener; @OnClick(R.id.ok) void onOk() { saveData(); if (listener != null) { listener.onDataChange(); } dismiss(); } @OnClick(R.id.notification) void onNotificationToggle() { if (getString(R.string.start_notification).equalsIgnoreCase(notification.getText().toString())) { notification.setText(getString(R.string.stop_notification)); } else { notification.setText(getString(R.string.start_notification)); } } @OnClick(R.id.cancel) void onCancel() { dismiss(); } private static final String BITCOIN = "bitcoin"; private BitCoin bitCoin; public EditDialogFragment() { // Required empty public constructor } public static EditDialogFragment newInstance(BitCoin bitCoin) { EditDialogFragment editDialogFragment = new EditDialogFragment(); Bundle bundle = new Bundle(); bundle.putParcelable(BITCOIN, bitCoin); editDialogFragment.setArguments(bundle); return editDialogFragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); BitNotifierApplication.getApplicationComponent().inject(this); if (getArguments() != null) { bitCoin = getArguments().getParcelable(BITCOIN); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_edit_dialog, container, false); ButterKnife.bind(this, view); initViews(); return view; } private void initViews() { BitCoinModel bitCoinModel = bitCoin.getBitCoinModel(); lastTradedPrice.setText(bitCoinModel.getLast_traded_price()); valueEdit.setText(String.format(Locale.ENGLISH, "%d", bitCoinModel.getSetValue())); rangeEdit.setText(String.format(Locale.ENGLISH, "%d", bitCoinModel.getRange())); if (sharedPrefUtils.getNotifyStatus(bitCoin.getTitle())) { notification.setText(getString(R.string.stop_notification)); } else { notification.setText(getString(R.string.start_notification)); } } private void saveData() { String value = valueEdit.getText().toString().trim(); String range = rangeEdit.getText().toString().trim(); if (TextUtils.isEmpty(value)) { value = "0"; } else if (TextUtils.isEmpty(range)) { range = "0"; } sharedPrefUtils.setValue(Long.parseLong(value), bitCoin.getTitle()); sharedPrefUtils.setRange(Long.parseLong(range), bitCoin.getTitle()); if (getString(R.string.start_notification).equalsIgnoreCase(notification.getText().toString())) { sharedPrefUtils.setNotify(false, bitCoin.getTitle()); } else { sharedPrefUtils.setNotify(true, bitCoin.getTitle()); } } public void setChangeListener(OnDataChangeListener listener) { this.listener = listener; } }
package com.example.opencval; import android.annotation.TargetApi; import android.app.Application; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.SurfaceView; import android.view.WindowManager; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import org.opencv.android.BaseLoaderCallback; import org.opencv.android.CameraBridgeViewBase; import org.opencv.android.LoaderCallbackInterface; import org.opencv.android.OpenCVLoader; import org.opencv.core.Mat; import java.util.Collections; import java.util.List; import static android.Manifest.permission.CAMERA; public class jeoncook2 extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 { private static final String TAG = "opencv"; private Mat matInput; private CameraBridgeViewBase mOpenCvCameraView; static { System.loadLibrary("opencv_java4"); System.loadLibrary("native-lib"); } class MyApp extends Application { private String myState; public String getState(){ return myState; } public void setState(String s){ myState = s; } } private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) { @Override public void onManagerConnected(int status) { switch (status) { case LoaderCallbackInterface.SUCCESS: { mOpenCvCameraView.enableView(); } break; default: { super.onManagerConnected(status); } break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.jeoncook2); mOpenCvCameraView = (CameraBridgeViewBase)findViewById(R.id.activity_surface_view); mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE); mOpenCvCameraView.setCvCameraViewListener(this); mOpenCvCameraView.setCameraIndex(1); // front-camera(1), back-camera(0) } @Override public void onPause() { super.onPause(); if (mOpenCvCameraView != null) mOpenCvCameraView.disableView(); } @Override public void onResume() { super.onResume(); if (!OpenCVLoader.initDebug()) { Log.d(TAG, "onResume :: Internal OpenCV library not found."); OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_2_0, this, mLoaderCallback); } else { Log.d(TAG, "onResum :: OpenCV library found inside package. Using it!"); mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS); } } public void onDestroy() { super.onDestroy(); if (mOpenCvCameraView != null) mOpenCvCameraView.disableView(); } @Override public void onCameraViewStarted(int width, int height) { } @Override public void onCameraViewStopped() { } @Override public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) { matInput = inputFrame.rgba(); int c = matInput.cols(); int r = matInput.rows(); double[] a = matInput.get(5,128); double[] b = matInput.get(135,128); int red = (int) Math.round(a[0]); int green = (int) Math.round(a[1]); int blue = (int) Math.round(a[2]);; int redb = (int) Math.round(b[0]); int greenb = (int) Math.round(b[1]); int blueb = (int) Math.round(b[2]); int beforered = rgbset.getBeforered(); int beforegreen = rgbset.getBeforegreen(); int beforeblue = rgbset.getBeforeblue(); int nextred = rgbset.getBeforered(); int nextgreen = rgbset.getBeforegreen(); int nextblue = rgbset.getBeforeblue(); if((beforered-25)<=red && red<=(beforered+25) && (beforegreen-25)<= green &&green<=(beforegreen+25) && (beforeblue-25)<=blue && blue <=(beforeblue+25)){ Intent intent = new Intent(jeoncook2.this, jeoncomplete.class); intent.addFlags(intent.FLAG_ACTIVITY_CLEAR_TASK); intent.addFlags(intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } if((nextred-25)<=redb && redb<=(nextred+25) && (nextgreen-25)<= greenb &&greenb<=(nextgreen+25) && (nextblue-25)<=blueb && blueb <=(nextblue+25)){ Intent intent = new Intent(jeoncook2.this, jeoncook1.class); intent.addFlags(intent.FLAG_ACTIVITY_CLEAR_TASK); intent.addFlags(intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } return matInput; } protected List<? extends CameraBridgeViewBase> getCameraViewList() { return Collections.singletonList(mOpenCvCameraView); } //여기서부턴 퍼미션 관련 메소드 private static final int CAMERA_PERMISSION_REQUEST_CODE = 200; protected void onCameraPermissionGranted() { List<? extends CameraBridgeViewBase> cameraViews = getCameraViewList(); if (cameraViews == null) { return; } for (CameraBridgeViewBase cameraBridgeViewBase: cameraViews) { if (cameraBridgeViewBase != null) { cameraBridgeViewBase.setCameraPermissionGranted(); } } } @Override protected void onStart() { super.onStart(); boolean havePermission = true; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(CAMERA) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{CAMERA}, CAMERA_PERMISSION_REQUEST_CODE); havePermission = false; } } if (havePermission) { onCameraPermissionGranted(); } } @Override @TargetApi(Build.VERSION_CODES.M) public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == CAMERA_PERMISSION_REQUEST_CODE && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { onCameraPermissionGranted(); }else{ showDialogForPermission("앱을 실행하려면 퍼미션을 허가하셔야합니다."); } super.onRequestPermissionsResult(requestCode, permissions, grantResults); } @TargetApi(Build.VERSION_CODES.M) private void showDialogForPermission(String msg) { AlertDialog.Builder builder = new AlertDialog.Builder( jeoncook2.this); builder.setTitle("알림"); builder.setMessage(msg); builder.setCancelable(false); builder.setPositiveButton("예", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id){ requestPermissions(new String[]{CAMERA}, CAMERA_PERMISSION_REQUEST_CODE); } }); builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { finish(); } }); builder.create().show(); } }
package org.lvzr.fast.bigdata.hbase; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.BinaryComparator; import org.apache.hadoop.hbase.filter.CompareFilter; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.filter.RowFilter; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; public class HBaseFilter { private static final String TABLE_NAME = "t1"; private static HBaseAdmin hBaseAdmin; private static final String rowKey = "r1"; private static Configuration conf; static { conf = HBaseConfiguration.create(); conf.addResource("hbase-site.xml"); try { hBaseAdmin = new HBaseAdmin(conf); } catch (Exception e) { e.printStackTrace(); } } public static void createTable(String tableName, String[] columns) throws Exception { dropTable(tableName); HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName); for (String columnName : columns) { HColumnDescriptor column = new HColumnDescriptor(columnName); hTableDescriptor.addFamily(column); } hBaseAdmin.createTable(hTableDescriptor); System.out.println("create table successed"); } public static void dropTable(String tableName) throws Exception { if (hBaseAdmin.tableExists(tableName)) { hBaseAdmin.disableTable(tableName); hBaseAdmin.deleteTable(tableName); } System.out.println("drop table successed"); } public static HTable getHTable(String tableName) throws Exception { return new HTable(conf, tableName); } public static void insert(String tableName, Map<String, String> map) throws Exception { HTable hTable = getHTable(tableName); byte[] row1 = Bytes.toBytes(rowKey); Put p1 = new Put(row1); for (String columnName : map.keySet()) { byte[] value = Bytes.toBytes(map.get(columnName)); String[] str = columnName.split(":"); byte[] family = Bytes.toBytes(str[0]); byte[] qualifier = null; if (str.length > 1) { qualifier = Bytes.toBytes(str[1]); } p1.add(family, qualifier, value); } hTable.put(p1); Get g1 = new Get(row1); Result result = hTable.get(g1); System.out.println("Get: " + result); System.out.println("insert successed"); } public static void delete(String tableName, String rowKey) throws Exception { HTable hTable = getHTable(tableName); List<Delete> list = new ArrayList<Delete>(); Delete d1 = new Delete(Bytes.toBytes(rowKey)); list.add(d1); hTable.delete(list); Get g1 = new Get(Bytes.toBytes(rowKey)); Result result = hTable.get(g1); System.out.println("Get: " + result); System.out.println("delete successed"); } public static void selectOne(String tableName, String rowKey) throws Exception { HTable hTable = getHTable(tableName); Get g1 = new Get(Bytes.toBytes(rowKey)); Result result = hTable.get(g1); foreach(result); System.out.println("selectOne end"); } private static void foreach(Result result) throws Exception { for (KeyValue keyValue : result.raw()) { StringBuilder sb = new StringBuilder(); sb.append(Bytes.toString(keyValue.getRow())).append("\t"); sb.append(Bytes.toString(keyValue.getFamily())).append("\t"); sb.append(Bytes.toString(keyValue.getQualifier())).append("\t"); sb.append(keyValue.getTimestamp()).append("\t"); sb.append(Bytes.toString(keyValue.getValue())).append("\t"); System.out.println(sb.toString()); } } public static void selectAll(String tableName) throws Exception { HTable hTable = getHTable(tableName); Scan scan = new Scan(); ResultScanner resultScanner = null; try { resultScanner = hTable.getScanner(scan); for (Result result : resultScanner) { foreach(result); } } catch (Exception e) { e.printStackTrace(); } finally { if (resultScanner != null) { resultScanner.close(); } } System.out.println("selectAll end"); } public static void main(String[] args) throws Exception { String tableName = "tableTest"; String[] columns = new String[] { "column_A", "column_B" }; createTable(tableName, columns); Map<String, String> map = new HashMap<String, String>(); map.put("column_A", "AAA"); map.put("column_B:1", "b1"); map.put("column_B:2", "b2"); insert(tableName, map); selectOne(tableName, rowKey); selectAll(tableName); delete(tableName, rowKey); dropTable(tableName); createTable(tableName, columns); insert(tableName, map); // 获取表 Connection conn = ConnectionFactory.createConnection(conf); HTable table = (HTable) conn.getTable(TableName.valueOf(TABLE_NAME)); // 创建一个扫描对象 Scan scan = new Scan(); // 创建一个RowFilter过滤器 //Filter filter = new RowFilter(CompareFilter.CompareOp.EQUAL, new BinaryComparator(Bytes.toBytes("abc"))); // 将过滤器加入扫描对象 //scan.setFilter(filter); // 输出结果 ResultScanner results = table.getScanner(scan); for (Result result : results) { for (Cell cell : result.rawCells()) { System.out.println( "行键:" + new String(CellUtil.cloneRow(cell)) + "\t" + "列族:" + new String(CellUtil.cloneFamily(cell)) + "\t" + "列名:" + new String(CellUtil.cloneQualifier(cell)) + "\t" + "值:" + new String(CellUtil.cloneValue(cell)) + "\t" + "时间戳:" + cell.getTimestamp()); } } // 关闭资源 results.close(); table.close(); conn.close(); System.out.println("finished...."); } }
package com.example.romanwisdom.rwatch; /** * Created by Roman on 2/10/2017. */ import android.annotation.TargetApi; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.provider.Telephony; import android.telephony.SmsMessage; import android.util.Log; import android.widget.Toast; @TargetApi(23) public class SMSBroadcastReceiver extends BroadcastReceiver { private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; private static final String TAG = "SMSBroadcastReceiver"; @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "Intent recieved: " + intent.getAction()); Log.i(TAG, "Context: " + context.toString()); //Toast.makeText(context, intent.getAction().toString(), Toast.LENGTH_LONG).show(); SmsMessage[] msgs = Telephony.Sms.Intents.getMessagesFromIntent(intent); SmsMessage smsMessage = msgs[0]; Intent i = new Intent("smsBroadcast"); i.putExtra("smsMessageBody", smsMessage.getMessageBody()); i.putExtra("smsSender", smsMessage.getOriginatingAddress()); context.sendBroadcast(i); } }