text
stringlengths
10
2.72M
package com.shashi.customer.resources; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.MatrixParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.shashi.customer.model.Customer; import com.shashi.customer.model.HeaderInfo; import com.shashi.customer.service.CustomerService; // This is the Resource Class for JAX-RS where we are defining all the HTTP Mehtods @Service @Path("/customer") public class CustomerResource { // Injecting Customer Serivce Dependency @Autowired private CustomerService cs; // Normal GET method @GET public Response health() { return Response.ok().build(); } // POST Method of HTTP to create the Customer @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public Response create(final Customer customer) { final Customer entity = cs.create(customer); return Response.ok().entity(entity).build(); } // PUT method of HTTP to modify the Customer @PUT @Consumes({ MediaType.APPLICATION_JSON }) public Response modify(final Customer customer) { cs.modify(customer); return Response.noContent().type(MediaType.APPLICATION_JSON).build(); } // GET method of HTTP to get the specific Customer information by ID @Path("/{customerId}") @GET @Produces({ MediaType.APPLICATION_JSON }) public Response findById(@PathParam("customerId") final Long id) { final Customer entity = cs.find(id); return Response.ok().entity(entity).build(); } // DELETE method of the HTTP to delete the Customer @Path("/{customerId}") @DELETE public Response removeById(@PathParam("customerId") final Long id) { cs.remove(id); return Response.noContent().build(); } // GET method of HTTP to get List of all the Customers @Path("/all") @GET @Produces({ MediaType.APPLICATION_JSON }) public Response getAll() { final List<Customer> customers = cs.getAll(); final GenericEntity<List<Customer>> entity = new GenericEntity<>(customers, List.class); return Response.ok().entity(entity).build(); } // GET method of the HTTP to Search the Customer by First and Last Name @Path("/search") @GET @Produces({ MediaType.APPLICATION_JSON }) public Response search(@QueryParam("fName") final String firstName, @QueryParam("lName") final String lastName) { final List<Customer> customers = cs.search(firstName, lastName); final GenericEntity<List<Customer>> entity = new GenericEntity<>(customers, List.class); return Response.ok().entity(entity).build(); } // Get method with @MatrixParam @Path("/matrix") @GET @Produces({ MediaType.APPLICATION_JSON }) public Response searchByMatrix(@MatrixParam("fName") final String firstName, @MatrixParam("lName") final String lastName) { final List<Customer> customers = cs.search(firstName, lastName); final GenericEntity<List<Customer>> entity = new GenericEntity<>(customers, List.class); return Response.ok().entity(entity).build(); } // Get method with @HeaderParam @Path("/hdr") @GET @Produces({ MediaType.APPLICATION_JSON }) public Response getHdrValues(@HeaderParam("auth-token") String authToken, @HeaderParam("app-name") String appName, @HeaderParam("app-version") String appVersion, @HeaderParam("content-type") String contentType) { HeaderInfo entity = HeaderInfo.builder().appName(appName).appVersion(appVersion).authToken(authToken) .contentType(contentType).build(); return Response.ok().entity(entity).build(); } // Get method with @Context to send the Header as an Object @Path("/hdrContext") @GET @Produces({ MediaType.APPLICATION_JSON }) public Response getHdrByContext(@Context HttpHeaders header) { String appName = header.getHeaderString("app-name"); String appVersion = header.getHeaderString("app-version"); String authToken = header.getHeaderString("auth-token"); String contentType = header.getHeaderString("content-type"); HeaderInfo entity = HeaderInfo.builder().appName(appName).appVersion(appVersion).authToken(authToken) .contentType(contentType).build(); return Response.ok().entity(entity).build(); } }
package com.cbs.edu.spring_annotations; import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages = {"com.cbs.edu.spring_annotations"}) public class ComponentScanConfig { }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package DAO; import Bean.Section; import Utility.DBConn; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author mengqwang */ public class SectionDAO { public int getSectionVenue(Section s) throws SQLException { ResultSet rs=null; DBConn db=new DBConn(); int sectionID=s.getSectionID(); int venueID=0; String sql="SELECT [Venue_ID] FROM [SECTION] WHERE [Section_ID]="+sectionID; rs=db.doSelect(sql); if(rs.next()) { venueID=rs.getInt(1); } return venueID; } public int isTodaySection(Section s) { try { DBConn db=new DBConn(); String sql="SELECT DATEDIFF(day,[Time],GETDATE()) AS DiffDate FROM [SECTION] WHERE [Section_ID]="+s.getSectionID(); ResultSet rs=null; rs=db.doSelect(sql); int days=0; if(rs.next()) { days=rs.getInt("DiffDate"); } if(days==0) return 1; else return 0; } catch (SQLException ex) { Logger.getLogger(SectionDAO.class.getName()).log(Level.SEVERE, null, ex); } return 0; } public void getSection(int sid,Section s) { try { ResultSet rs=null; DBConn db=new DBConn(); String sql="SELECT * FROM [SECTION] WHERE [Section_ID]="+sid; rs=db.doSelect(sql); int mid=0; Timestamp time = null; int vid=0; int price=0; if(rs.next()) { mid=rs.getInt("Movie_ID"); time=rs.getTimestamp("Time"); vid=rs.getInt("Venue_ID"); price=rs.getInt("Price"); } s.setMovieID(mid); s.setSectionID(sid); s.setPrice(price); s.setTime(time); s.setVenueID(vid); } catch (SQLException ex) { Logger.getLogger(SectionDAO.class.getName()).log(Level.SEVERE, null, ex); } } public boolean isRefundSection(Section s) { try { DBConn db=new DBConn(); ResultSet rs; String sql="SELECT DATEDIFF(hour,GETDATE(),'"+s.getTime()+"') AS DiffDate"; rs=db.doSelect(sql); if(rs.next()) { int diff=rs.getInt("DiffDate"); if(diff>=3) return true; else return false; } } catch (SQLException ex) { Logger.getLogger(SectionDAO.class.getName()).log(Level.SEVERE, null, ex); } return false; } public void deleteSection(int sectionID) throws SQLException{ DBConn db=new DBConn(); db.doDelete("DELETE FROM [Section] WHERE Section_ID =" + sectionID); db.doDelete("DELETE FROM [Booking] WHERE Section_ID =" + sectionID); } public void addSection(Section section) throws SQLException{ int movieID = section.getMovieID(); int venueID = section.getVenueID(); Timestamp time = section.getTime(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm"); int price = section.getPrice(); DBConn db=new DBConn(); String StrTime=sdf.format(time); String sql="INSERT INTO [SECTION](Movie_ID,Time,Venue_ID,price) VALUES('"+movieID+"','"+StrTime+"','"+venueID+"','"+price+"')"; db.doInsert(sql); //db.doInsert("INSERT INTO [SECTION](Movie_ID,Venue_ID,price) VALUES('"+movieID+"','"+venueID+"','"+price+"')"); } public void editSection(Section section) throws SQLException{ int venue = section.getVenueID(); int price = section.getPrice(); int sectionID=section.getSectionID(); Timestamp time = section.getTime(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm"); String StrTime=sdf.format(time); DBConn db=new DBConn(); db.doUpdate("UPDATE [Section] SET Venue_ID = '"+venue+"', Price ='"+price+"', Time = '"+StrTime+"' WHERE Section_id="+sectionID); } }
package ru.gb.jtwo.lesson_3.homework_3; public class Person { public String phone; public String email; public Person(String phoneNumber, String email) { this.phone = phoneNumber; this.email = email; } }
package com.imooc.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CorsConfig { public CorsConfig() { } @Bean public CorsFilter corsFilter(){ //1.添加Cors配置信息 CorsConfiguration corsConfig = new CorsConfiguration(); corsConfig.addAllowedHeader("*"); corsConfig.addAllowedMethod("*"); corsConfig.addAllowedOrigin("http://localhost:8080"); corsConfig.addAllowedOrigin("http://47.113.217.116:8080"); corsConfig.addAllowedOrigin("http://47.113.217.116:8088"); corsConfig.addAllowedOrigin("http://47.113.217.116"); corsConfig.setAllowCredentials(true);//设置是否发送cookie信息 //为url提供映射路径 UrlBasedCorsConfigurationSource corsConfigSource = new UrlBasedCorsConfigurationSource(); corsConfigSource.registerCorsConfiguration("/**",corsConfig); //返回重新定义好的url return new CorsFilter(corsConfigSource); } }
package oberon; import file.FileUtils; import file.RTFFile; import gui.comp.FileChooser; import gui.db.TableView; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; import javax.swing.JFileChooser; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.jdesktop.swingx.JXTable; import utils.Application; import db.Model; /** Maps the acronym (abbreviation) to the Acronym object. */ public class Acronyms extends TreeMap<String, Acronym> { private Application app; private Model model; private transient TableView view; public Acronyms (final Application app) { this.app = app; makeModel(); makeView(); } public synchronized Acronym add (final Acronym acronym) { if (!containsKey (acronym.getAbbrev())) { super.put (acronym.getAbbrev(), acronym); model.addRowValues (false, acronym, acronym.getDefinitions()); } return acronym; } public synchronized int remove (final Acronym acronym) { int row = findModelRow (acronym); if (row >= 0) { model.removeRow (row); super.remove (acronym.getAbbrev()); return 1; } return 0; } public Model getModel() { return model; } public TableView getView() { return view; } @Override public synchronized void clear() { super.clear(); while (model.getRowCount() > 0) model.removeRow (0); app.updateState (Menus.States.hasData.toString(), false); } public Acronym getAcronym (final int row) { return (Acronym) model.getValueAt (row, 1); } public void approve (final int row, final boolean approved) { model.setValueAt (approved, row, 0); } public boolean isApproved (final Acronym acronym) { int row = findModelRow (acronym); return row >= 0 && (Boolean) model.getValueAt (row, 0); } public boolean isApproved (final int row) { return (Boolean) model.getValueAt (row, 0); } public void updateModel (final Acronym acronym) { SwingUtilities.invokeLater (new Runnable() { public void run() { int row = findModelRow (acronym); if (row >= 0) { boolean approved = isApproved (row); model.setValueAt (acronym.getDefinitions(), row, 2); if (!approved) approve (row, false); // hack to reset } } }); } public synchronized int findModelRow (final Acronym acronym) { for (int modelRow = 0; modelRow < model.getRowCount(); modelRow++) if (acronym == (Acronym) model.getValueAt (modelRow, 1)) return modelRow; return -1; } public void scrollTo (final int modelRow) { int viewRow = view.getView().convertRowIndexToView (modelRow); TableView.scrollTo (view.getView(), viewRow); } public void repaint() { view.getView().repaint(); } public List<Acronym> getSelected() { List<Acronym> selected = new ArrayList<Acronym>(); JXTable v = view.getView(); if (v.getSelectedRowCount() > 0) // just consider selected rows for (int viewRow : v.getSelectedRows()) { int row = v.convertRowIndexToModel (viewRow); selected.add ((Acronym) model.getValueAt (row, 1)); } return selected; } public List<Acronym> getUndefined() { List<Acronym> undefined = new ArrayList<Acronym>(); for (Acronym acronym : values()) if (!acronym.isDefined()) undefined.add (acronym); return undefined; } public List<Acronym> getApproved() { List<Acronym> approved = new ArrayList<Acronym>(); for (int row = 0, rows = model.getRowCount(); row < rows; row++) if ((Boolean) model.getValueAt (row, 0)) // approved approved.add ((Acronym) model.getValueAt (row, 1)); return approved; } public void exportToExcel() { TableView.exportToExcel (view.getView(), view.getName()); } public void exportToHTML() { TableView.exportToHTML (view.getView(), view.getName()); } public void exportToRTF (final File inFile) { int exported = 0; FileChooser fc = new FileChooser ("Export RTF File", inFile.getPath()); fc.setDialogType (JFileChooser.SAVE_DIALOG); fc.setRegexFilter (".+[.]rtf", "Rich Text Format (*.rtf) files"); String name = FileUtils.getNameWithoutSuffix (inFile) + " Acronyms.rtf"; fc.setSelectedFile (new File (name)); if (fc.showOpenDialog (null) == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); RTFFile rtf = null; try { rtf = new RTFFile (file.getPath()); rtf.createTable (2); rtf.addRow (new String[] { "Acronym", "Term/Definition" }); for (Acronym ac : getApproved()) { rtf.addRow (new String[] { ac.getAbbrev(), ac.getSelected().getText() }); exported++; } app.getProgress().reset (exported + " acronyms publised to: " + file); } catch (IOException x) { x.printStackTrace(); } finally { if (rtf != null) rtf.close(); } } } public void print() { TableView.print (view.getView()); } private Model makeModel() { model = new Model ("Acronyms"); model.addColumn ("Approved", Boolean.class); model.addColumn ("Acronym", Acronym.class); model.addColumn ("Definitions", Definitions.class); model.setColumnEditable (1, false); return model; } private void makeView() { view = new TableView (model, new TableRenderer()); view.getView().getTableHeader().setReorderingAllowed (false); view.getView().setDefaultEditor (Definitions.class, new ComboEditor()); view.getView().setEditable (true); ListSelectionListener listener = new TableSelectionListener(); view.getView().getSelectionModel().addListSelectionListener (listener); } private class TableSelectionListener implements ListSelectionListener { public void valueChanged (final ListSelectionEvent event) { int count = view.getView().getSelectedRowCount(); app.updateState (Menus.States.acronymSelected.toString(), count == 1); app.updateState (Menus.States.acronymsSelected.toString(), count > 0); } } }
package com.logzc.webzic.compass.service; import com.logzc.webzic.annotation.Service; /** * Created by lishuang on 2016/7/19. */ @Service public class UserService { }
package images; public class RGB { public static final RGB BLACK = new RGB(0,0,0); public static final RGB WHITE = new RGB(1,1,1); public static final RGB RED = new RGB(1,0,0); public static final RGB GREEN = new RGB(0,1,0); public static final RGB BLUE = new RGB(0,0,1); private double red, green, blue; public RGB(double red, double green, double blue) { this.red = red; this.green = green; this.blue = blue; } public RGB(double grey) { red = green = blue = grey; } public double getRed() { return red; } public double getGreen() { return green; } public double getBlue() { return blue; } public RGB invert() { return new RGB(1 - red, 1 - green, 1 - blue); } public RGB filter(RGB filter) { return new RGB(filter.red * red, filter.green * green, filter.blue * blue); } public static RGB superpose(RGB rgb1, RGB rgb2) { double nRed, nGreen, nBlue; nRed = (rgb1.red + rgb2.red < 1) ? rgb1.red + rgb2.red : 1; nGreen = (rgb1.green + rgb2.green < 1) ? rgb1.green + rgb2.green : 1; nBlue = (rgb1.blue + rgb2.blue < 1) ? rgb1.blue + rgb2.blue : 1; return new RGB(nRed, nGreen, nBlue); } private static double setNColor(double c1,double c2,double alpha) { double ret =alpha*c1 + (1-alpha) * c2; if(ret >1)return 1; if(ret <0)return 0; return ret; } public static RGB mix(RGB rgb1, RGB rgb2, double alpha) { double nRed, nGreen, nBlue; nRed = setNColor(rgb1.red,rgb2.red,alpha); nGreen = setNColor(rgb1.green,rgb2.green,alpha); nBlue = setNColor(rgb1.blue,rgb2.blue,alpha); return new RGB(nRed, nGreen, nBlue); } public String toString() { return String.format("<%.4f, %.4f, %.4f>",red,green,blue); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.context.failures; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.platform.testkit.engine.EngineTestKit; import org.springframework.beans.BeanInstantiationException; import org.springframework.beans.factory.BeanCreationException; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.GenericApplicationContext; import org.springframework.test.context.failures.TrackingApplicationContextFailureProcessor.LoadFailure; import org.springframework.test.context.junit.jupiter.FailingTestCase; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; /** * Tests for failures that occur while loading an {@link ApplicationContext}. * * @author Sam Brannen * @since 6.0 */ class ContextLoadFailureTests { @BeforeEach @AfterEach void clearFailures() { TrackingApplicationContextFailureProcessor.loadFailures.clear(); } @Test void customBootstrapperAppliesApplicationContextFailureProcessor() { assertThat(TrackingApplicationContextFailureProcessor.loadFailures).isEmpty(); EngineTestKit.engine("junit-jupiter") .selectors(selectClass(ExplosiveContextTestCase.class))// .execute() .testEvents() .assertStatistics(stats -> stats.started(1).succeeded(0).failed(1)); assertThat(TrackingApplicationContextFailureProcessor.loadFailures).hasSize(1); LoadFailure loadFailure = TrackingApplicationContextFailureProcessor.loadFailures.get(0); assertThat(loadFailure.context()).isExactlyInstanceOf(GenericApplicationContext.class); assertThat(loadFailure.exception()) .isInstanceOf(BeanCreationException.class) .cause().isInstanceOf(BeanInstantiationException.class) .rootCause().isInstanceOf(StackOverflowError.class).hasMessage("Boom!"); } @FailingTestCase @SpringJUnitConfig static class ExplosiveContextTestCase { @Test void test1() { /* no-op */ } @Configuration(proxyBeanMethods = false) static class Config { @Bean String explosion() { throw new StackOverflowError("Boom!"); } } } }
/* * 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 BLL; import java.awt.Frame; import java.text.NumberFormat; import java.util.Locale; import javax.swing.JOptionPane; /** * * @author Huy Nhan */ public class ChuyenDoi_ThongBao { public static void ThongBao_Loi (String NoiDung, String TieuDe){ JOptionPane.showMessageDialog(new Frame(), NoiDung, TieuDe, JOptionPane.ERROR_MESSAGE); } public static void ThongBao_ThanhCong (String NoiDung, String TieuDe){ JOptionPane.showMessageDialog(new Frame(), NoiDung, TieuDe, JOptionPane.OK_OPTION); } public static String TienVietNam(double chuoi) { String chuyenDoi = ""; //chuyển đổi sang tiền tệ việt nam Locale lc_vn = new Locale("vi", "VN"); //khai báo chuyển đổi từ double sang tiền tệ NumberFormat nf_cur_vn = NumberFormat.getCurrencyInstance(lc_vn); //format chuỗi nhập vào thành tiền tệ chuyenDoi = nf_cur_vn.format(chuoi); //trả về tiền tệ (Việt Nam) return chuyenDoi; } public static String TienTeVeString(String chuoi) { String ChuyenDoi = chuoi; if (chuoi != null) { ChuyenDoi = chuoi.substring(0, chuoi.indexOf(' '))//trả về giá trị từ đầu đên đấu cách đầu tiên trong tiền tệ .replace('.', ' ')//thay thế đấu chấm trong tiền tệ thành đấu cách .replaceAll("\\s+", "");//loại bỏ tất cẩ các khoảng trống trong chuỗi } //trả về giá trị sau khi chuyển đổi return ChuyenDoi; } }
package com.jfronny.raut.api; import net.minecraft.item.ItemStack; import net.minecraft.recipe.Ingredient; import net.minecraft.recipe.Recipe; import java.util.function.Predicate; public class RecipeContentRemovalPredicate implements Predicate<Recipe<?>> { private final ItemStack content; public RecipeContentRemovalPredicate(ItemStack stack) { this.content = stack; } @Override public boolean test(Recipe<?> recipe) { return recipe.getPreviewInputs().contains(Ingredient.ofStacks(content)); } }
package com.uchain.core.producerblock; import com.uchain.cryptohash.BinaryData; import com.uchain.cryptohash.PublicKey; import com.uchain.main.ConsensusSettings; import com.uchain.main.Witness; public class ProducerUtil { /** * 获取给定时间点的生产者 * * @param timeMs time from 1970 in ms * @return */ public static Witness getWitness(Long timeMs, ConsensusSettings settings) { long slot = timeMs / settings.getProduceInterval(); long index = slot % (settings.getWitnessList().size() * settings.getProducerRepetitions()); index /= settings.getProducerRepetitions(); return settings.getWitnessList().get((int) index); //获取 } public static Boolean isTimeStampValid(Long timeStamp, ConsensusSettings settings) { if (timeStamp % settings.getProduceInterval() == 0) return true; else return false; } public static Boolean isProducerValid(Long timeStamp, PublicKey producer, ConsensusSettings settings) { boolean isValid = false; if (PublicKey.apply(new BinaryData(getWitness(timeStamp, settings).getPubkey())).toBin().equals(producer.toBin())){ if (isTimeStampValid(timeStamp, settings)) { isValid = true; } } return isValid; } }
package com.example.demo.blog.service.impl; import com.example.demo.blog.entity.Article; import com.example.demo.blog.mapper.ArticleMapper; import com.example.demo.blog.service.IArticleService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author ldx * @since 2020-02-26 */ @Service public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService { }
package com.gxtc.huchuan.ui.live.list; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.view.View; import com.gxtc.commlibrary.base.BaseTitleActivity; import com.gxtc.huchuan.R; import com.gxtc.huchuan.adapter.BaseTabLayoutPagerAdapter; import com.gxtc.huchuan.bean.LiveHeadTitleBean; import com.gxtc.huchuan.widget.CustomViewPager; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by Gubr on 2017/2/27. */ public class LiveListActivity extends BaseTitleActivity implements View.OnClickListener { private final static String ID = "id"; private final static String TITLE = "title"; @BindView(R.id.tb_live_tab) TabLayout mTbLiveTab; @BindView(R.id.viewpager) CustomViewPager mViewpager; private LiveHeadTitleBean mBean; private List<LiveListFragment> mLiveListFragments; private BaseTabLayoutPagerAdapter<LiveListFragment, LiveHeadTitleBean.ChatTypeSonBean> mLiveListPagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_live_list); } @Override public void initView() { mBean = (LiveHeadTitleBean) getIntent().getSerializableExtra("bean"); String title = mBean.getTypeName(); getBaseHeadView().showTitle(title); getBaseHeadView().showBackButton(this); } @Override public void initData() { mLiveListFragments = new ArrayList<>(); for (LiveHeadTitleBean.ChatTypeSonBean bean : mBean.getChatTypeSon()) { mLiveListFragments.add(getLiveListFragment(bean)); } mViewpager.setOffscreenPageLimit(mBean.getChatTypeSon().size()-1); mLiveListPagerAdapter = new BaseTabLayoutPagerAdapter<>(getSupportFragmentManager(), mLiveListFragments, mBean.getChatTypeSon()); mViewpager.setAdapter(mLiveListPagerAdapter); mTbLiveTab.setTabMode(TabLayout.MODE_SCROLLABLE); mTbLiveTab.setupWithViewPager(mViewpager); } @Override public void initListener() { } @Override public void onClick(View v) { switch (v.getId()) { case R.id.headBackButton: finish(); break; } } public static void startActivity(Context context, LiveHeadTitleBean bean) { Intent intent = new Intent(context, LiveListActivity.class); intent.putExtra("bean", bean); context.startActivity(intent); } public LiveListFragment getLiveListFragment(LiveHeadTitleBean.ChatTypeSonBean bean) { Bundle bundle = new Bundle(); bundle.putSerializable("bean", bean); LiveListFragment liveListFragment = new LiveListFragment(); liveListFragment.setArguments(bundle); return liveListFragment; } }
package com.github.dockerjava.api.command; import com.github.dockerjava.api.NotFoundException; public interface ExecContainerCmd extends BaseExecCmd<ExecContainerCmd, String> { @Override public String exec() throws NotFoundException; public static interface Exec extends DockerCmdExec<ExecContainerCmd, String> { } }
package com.example.parcial3capas.repositories; import com.example.parcial3capas.domain.Departamento; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface DepartamentoRepo extends JpaRepository<Departamento, Integer> { Departamento findByDepartamento(String departamento); Departamento findByCodigoDepartamento(Integer ID); }
package com.needii.dashboard.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.Table; /** * The persistent class for the admins database table. * */ @Entity @Table(name="wards") @NamedQuery(name="Ward.findAll", query="SELECT w FROM Ward w") public class Ward extends BaseModel { private static final long serialVersionUID = 1L; @Id private int id; @Column(name = "district_id") private int districtId; private String name; private boolean status; public int getId() { return id; } public void setId(int id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the status */ public boolean getStatus() { return status; } /** * @param status the status to set */ public void setStatus(boolean status) { this.status = status; } public int getDistrictId() { return districtId; } public void setDistrictId(int districtId) { this.districtId = districtId; } }
package com.hcl.neo.eloader.network.handler; public abstract class TransportFactory { public abstract Transporter createTransporter(); }
package com.deepak.proxy; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.stereotype.Controller; /** * Deepak Singhvi */ @SpringBootApplication @EnableDiscoveryClient @EnableZuulProxy @Configuration @ComponentScan @EnableAutoConfiguration @Controller public class ProxyServer { public static void main(String args[]) { SpringApplication.run(ProxyServer.class, args); } }
package com.meehoo.biz.web.controller.basic.setting; import com.meehoo.biz.core.basic.param.HttpResult; import com.meehoo.biz.core.basic.service.setting.IProvinceCityAreaService; import com.meehoo.biz.core.basic.vo.setting.ProvinceCityAreaSelectVO; import com.meehoo.biz.core.basic.vo.setting.ProvinceSelectVO; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2016-10-19. * 获取省市区信息 */ @Api(tags = "省市区信息") @Controller @RequestMapping("/sysmanage/provinceCityArea") public class ProvinceCityAreaController { private final IProvinceCityAreaService provinceCityAreaService; @Autowired public ProvinceCityAreaController(IProvinceCityAreaService provinceCityAreaService) { this.provinceCityAreaService = provinceCityAreaService; } /** * @api {get} /address/getProvinceCityArea 按省份名称查询 * @apiName getProvinceCityArea * @apiGroup address * @apiVersion 0.1.0 * @apiDescription 按省份名称查询 * * @apiParam {string} provinceName 省份名称,精确查询 * * @apiSuccess {String} flag 0成功 1失败 2未登录 * @apiSuccess {String} msg 提示信息 * @apiSuccess {Object[]} data 省市区数据 * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "msg": "成功", * "flag": "0", * "data":[ * { "label": "四川省", "value": "p51c00a00", "children":[ { "label": "成都市", "value": "p51c01a00", "children":[ {"label": "锦江区", "value": "p51c01a04"}, {"label": "青羊区", "value": "p51c01a05"}, {"label": "金牛区", "value": "p51c01a06"}, {"label": "武侯区", "value": "p51c01a07"}, {"label": "成华区", "value": "p51c01a08"}, {"label": "龙泉驿区", "value": "p51c01a12"}, {"label": "青白江区", "value": "p51c01a13"}, {"label": "新都区", "value": "p51c01a14"}, {"label": "温江区", "value": "p51c01a15"}, {"label": "金堂县", "value": "p51c01a21"}, {"label": "双流县", "value": "p51c01a22"}, {"label": "郫县", "value": "p51c01a24"}, {"label": "大邑县", "value": "p51c01a29"}, {"label": "蒲江县", "value": "p51c01a31"}, {"label": "新津县", "value": "p51c01a32"}, {"label": "都江堰市", "value": "p51c01a81"}, {"label": "彭州市", "value": "p51c01a82"}, {"label": "邛崃市", "value": "p51c01a83"}, {"label": "崇州市", "value": "p51c01a84"} ] }, {"label": "自贡市", "value": "p51c03a00", "children":[{"label": "自流井区",…}, {"label": "攀枝花市", "value": "p51c04a00", "children":[{"label": "东区",…}, {"label": "泸州市", "value": "p51c05a00", "children":[{"label": "江阳区",…}, {"label": "德阳市", "value": "p51c06a00", "children":[{"label": "旌阳区",…}, {"label": "绵阳市", "value": "p51c07a00", "children":[{"label": "涪城区",…}, {"label": "广元市", "value": "p51c08a00", "children":[{"label": "利州区",…}, {"label": "遂宁市", "value": "p51c09a00", "children":[{"label": "船山区",…}, {"label": "内江市", "value": "p51c10a00", "children":[{"label": "市中区",…}, {"label": "乐山市", "value": "p51c11a00", "children":[{"label": "市中区",…}, {"label": "南充市", "value": "p51c13a00", "children":[{"label": "顺庆区",…}, {"label": "眉山市", "value": "p51c14a00", "children":[{"label": "东坡区",…}, {"label": "宜宾市", "value": "p51c15a00", "children":[{"label": "翠屏区",…}, {"label": "广安市", "value": "p51c16a00", "children":[{"label": "广安区",…}, {"label": "达州市", "value": "p51c17a00", "children":[{"label": "通川区",…}, {"label": "雅安市", "value": "p51c18a00", "children":[{"label": "雨城区",…}, {"label": "巴中市", "value": "p51c19a00", "children":[{"label": "巴州区",…}, {"label": "资阳市", "value": "p51c20a00", "children":[{"label": "雁江区",…}, {"label": "阿坝藏族羌族自治州", "value": "p51c32a00", "children":[{"label": "汶川县",…}, {"label": "甘孜藏族自治州", "value": "p51c33a00", "children":[{"label": "康定市",…}, {"label": "凉山彝族自治州", "value": "p51c34a00", "children":[{"label": "西昌市",…} ] } * ] * } * */ @ApiOperation("按省份名称查询") @GetMapping("getProvinceCityArea") @ResponseBody public HttpResult<List<ProvinceSelectVO>> getProvinceCityArea(String provinceName) { try { ProvinceCityAreaSelectVO provinceCityAreaSelectVO = provinceCityAreaService.getProvinceCityAreaSelectVOForApi(provinceName); List<ProvinceSelectVO> provinceSelectVOList = provinceCityAreaSelectVO.getProvinceSelectVOList(); return HttpResult.success(provinceSelectVOList); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } /** * @api {get} /address/getAllProvinceCityArea 获取所有省市区 * @apiName getAllProvinceCityArea * @apiGroup address * @apiVersion 0.1.0 * @apiDescription 获取所有省市区,提供给级联下拉菜单使用 * * * @apiSuccess {String} flag 0成功 1失败 2未登录 * @apiSuccess {String} msg 提示信息 * @apiSuccess {Object[]} data 省市区数据 * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "msg": "成功", * "flag": "0", * "data":[ * { "label": "北京市", "value": "p11c00a00", //编号 "children":[ { "label": "北京市", "value": "p11c01a00", "children":[ {"label": "东城区", "value": "p11c01a01"}, {"label": "西城区", "value": "p11c01a02"}, {"label": "朝阳区", "value": "p11c01a05"}, {"label": "丰台区", "value": "p11c01a06}, {"label": "石景山区", "value": "p11c01a07"}, {"label": "海淀区", "value": "p11c01a08"}, {"label": "门头沟区", "value": "p11c01a09"}, {"label": "房山区", "value": "p11c01a11"}, {"label": "通州区", "value": "p11c01a12"}, {"label": "顺义区", "value": "p11c01a13"}, {"label": "昌平区", "value": "p11c01a14"}, {"label": "大兴区", "value": "p11c01a15"}, {"label": "怀柔区", "value": "p11c01a16"}, {"label": "平谷区", "value": "p11c01a17"}, {"label": "密云县", "value": "p11c01a28"}, {"label": "延庆县", "value": "p11c01a29"} ] } ] }, { "label": "重庆市", "value": "p50c00a00", "children":[ { "label": "重庆市", "value": "p50c01a00", "children":[ {"label": "万州区", "value": "p50c01a01"}, {"label": "涪陵区", "value": "p50c01a02"}, {"label": "渝中区", "value": "p50c01a03"}, {"label": "大渡口区", "value": "p50c01a04"}, {"label": "江北区", "value": "p50c01a05"}, {"label": "沙坪坝区", "value": "p50c01a06"}, {"label": "九龙坡区", "value": "p50c01a07"}, {"label": "南岸区", "value": "p50c01a08"}, {"label": "北碚区", "value": "p50c01a09"}, {"label": "綦江区", "value": "p50c01a10"}, {"label": "大足区", "value": "p50c01a11"}, {"label": "渝北区", "value": "p50c01a12"}, {"label": "巴南区", "value": "p50c01a13"}, {"label": "黔江区", "value": "p50c01a14"}, {"label": "长寿区", "value": "p50c01a15"}, {"label": "江津区", "value": "p50c01a16"}, {"label": "合川区", "value": "p50c01a17"}, {"label": "永川区", "value": "p50c01a18"}, {"label": "南川区", "value": "p50c01a19"}, {"label": "璧山区", "value": "p50c01a20"}, {"label": "铜梁区", "value": "p50c01a51"}, {"label": "潼南区", "value": "p50c01a52"}, {"label": "荣昌区", "value": "p50c01a53"}, {"label": "开州区", "value": "p50c01a34"}, {"label": "梁平县", "value": "p50c01a28"}, {"label": "城口县", "value": "p50c01a29"}, {"label": "丰都县", "value": "p50c01a30"}, {"label": "垫江县", "value": "p50c01a31"}, {"label": "武隆县", "value": "p50c01a32"}, {"label": "忠县", "value": "p50c01a33"}, {"label": "云阳县", "value": "p50c01a35"}, {"label": "奉节县", "value": "p50c01a36"}, {"label": "巫山县", "value": "p50c01a37"}, {"label": "巫溪县", "value": "p50c01a38"}, {"label": "石柱土家族自治县", "value": "p50c01a40"}, {"label": "秀山土家族苗族自治县", "value": "p50c01a41"}, {"label": "酉阳土家族苗族自治县", "value": "p50c01a42"}, {"label": "彭水苗族土家族自治县", "value": "p50c01a43"} ] } ] }, * ] * } * */ @ApiOperation("获取所有省市区") @GetMapping("getAllProvinceCityArea") @ResponseBody public HttpResult<List<ProvinceSelectVO>> getAllProvinceCityArea() { try { ProvinceCityAreaSelectVO provinceCityAreaSelectVO = provinceCityAreaService.getAllProvinceCityAreaSelectVO(""); List<ProvinceSelectVO> provinceSelectVOList = provinceCityAreaSelectVO.getProvinceSelectVOList(); List<ProvinceSelectVO> needFrontProvinceList = new ArrayList<>(); List<ProvinceSelectVO> behindProvinceList = new ArrayList<>(); for (ProvinceSelectVO provinceSelectVO : provinceSelectVOList) { switch (provinceSelectVO.getLabel()) { case "重庆市": case "四川省": case "湖北省": case "陕西省": case "贵州省": case "云南省": needFrontProvinceList.add(provinceSelectVO); break; default: behindProvinceList.add(provinceSelectVO); break; } } needFrontProvinceList.addAll(behindProvinceList); return HttpResult.success(needFrontProvinceList); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } /** * @api {get} /address/getNextSingleMenu 获取省市区下拉列表中下一级 * @apiGroup address * @apiName getNextSingleMenu * @apiVersion 0.1.1 * @apiDescription 获取省市区下拉列表中下一级(只查一级)的列表内容(例如,查询河北省的所有地级市,查询石家庄市的所有区县) * * @apiParam {String} code 前台传来的查询编码,code为空表示查询所有的省,code为省编码表示查询这个省下面的所有地级市,code为市编码表示查询这个市下面的所有区县 * * @apiSuccessExample Success-Response: * * { "msg": "操作成功", "flag": "0", "data":{ "provinceSelectVOList":[ {"label": "北京市", "value": "p11c00a00", "children": null}, {"label": "天津市", "value": "p12c00a00", "children": null}, {"label": "河北省", "value": "p13c00a00", "children": null}, {"label": "山西省", "value": "p14c00a00", "children": null}, {"label": "内蒙古自治区", "value": "p15c00a00", "children": null}, {"label": "辽宁省", "value": "p21c00a00", "children": null}, {"label": "吉林省", "value": "p22c00a00", "children": null}, {"label": "黑龙江省", "value": "p23c00a00", "children": null}, {"label": "上海市", "value": "p31c00a00", "children": null}, {"label": "江苏省", "value": "p32c00a00", "children": null}, {"label": "浙江省", "value": "p33c00a00", "children": null}, {"label": "安徽省", "value": "p34c00a00", "children": null}, {"label": "福建省", "value": "p35c00a00", "children": null}, {"label": "江西省", "value": "p36c00a00", "children": null}, {"label": "山东省", "value": "p37c00a00", "children": null}, {"label": "河南省", "value": "p41c00a00", "children": null}, {"label": "湖北省", "value": "p42c00a00", "children": null}, {"label": "湖南省", "value": "p43c00a00", "children": null}, {"label": "广东省", "value": "p44c00a00", "children": null}, {"label": "广西壮族自治区", "value": "p45c00a00", "children": null}, {"label": "海南省", "value": "p46c00a00", "children": null}, {"label": "重庆市", "value": "p50c00a00", "children": null}, {"label": "四川省", "value": "p51c00a00", "children": null}, {"label": "贵州省", "value": "p52c00a00", "children": null}, {"label": "云南省", "value": "p53c00a00", "children": null}, {"label": "西藏自治区", "value": "p54c00a00", "children": null}, {"label": "陕西省", "value": "p61c00a00", "children": null}, {"label": "甘肃省", "value": "p62c00a00", "children": null}, {"label": "青海省", "value": "p63c00a00", "children": null}, {"label": "宁夏回族自治区", "value": "p64c00a00", "children": null}, {"label": "新疆维吾尔自治区", "value": "p65c00a00", "children": null}, {"label": "台湾省", "value": "p71c00a00", "children": null}, {"label": "香港特别行政区", "value": "p81c00a00", "children": null}, {"label": "澳门特别行政区", "value": "p82c00a00", "children": null} ] } } * * @apiSuccessExample Success-Response: * *{ "msg": "操作成功", "flag": "0", "data":{ "provinceSelectVOList":[ { "label": "河北省", "value": "p13c00a00", "children":[ {"label": "石家庄市", "value": "p13c01a00", "children": null}, {"label": "唐山市", "value": "p13c02a00", "children": null}, {"label": "秦皇岛市", "value": "p13c03a00", "children": null}, {"label": "邯郸市", "value": "p13c04a00", "children": null}, {"label": "邢台市", "value": "p13c05a00", "children": null}, {"label": "保定市", "value": "p13c06a00", "children": null}, {"label": "张家口市", "value": "p13c07a00", "children": null}, {"label": "承德市", "value": "p13c08a00", "children": null}, {"label": "沧州市", "value": "p13c09a00", "children": null}, {"label": "廊坊市", "value": "p13c10a00", "children": null}, {"label": "衡水市", "value": "p13c11a00", "children": null} ] } ] } } * * @apiSuccessExample Success-Response: * * { "msg": "操作成功", "flag": "0", "data":{ "provinceSelectVOList":[ { "label": "河北省", "value": "p13c00a00", "children":[ { "label": "石家庄市", "value": "p13c01a00", "children":[ {"label": "长安区", "value": "p13c01a02"}, {"label": "桥西区", "value": "p13c01a04"}, {"label": "新华区", "value": "p13c01a05"}, {"label": "井陉矿区", "value": "p13c01a07"}, {"label": "裕华区", "value": "p13c01a08"}, {"label": "藁城区", "value": "p13c01a09"}, {"label": "鹿泉区", "value": "p13c01a10"}, {"label": "栾城区", "value": "p13c01a11"}, {"label": "井陉县", "value": "p13c01a21"}, {"label": "正定县", "value": "p13c01a23"}, {"label": "行唐县", "value": "p13c01a25"}, {"label": "灵寿县", "value": "p13c01a26"}, {"label": "高邑县", "value": "p13c01a27"}, {"label": "深泽县", "value": "p13c01a28"}, {"label": "赞皇县", "value": "p13c01a29"}, {"label": "无极县", "value": "p13c01a30"}, {"label": "平山县", "value": "p13c01a31"}, {"label": "元氏县", "value": "p13c01a32"}, {"label": "赵县", "value": "p13c01a33"}, {"label": "晋州市", "value": "p13c01a83"}, {"label": "新乐市", "value": "p13c01a84"} ] } ] } ] } } * */ @ApiOperation("获取省市区下拉列表中下一级") @GetMapping("getNextSingleMenu") @ResponseBody public HttpResult<ProvinceCityAreaSelectVO> getNextSingleMenu(String code){ try { ProvinceCityAreaSelectVO provinceCityAreaSelectVO = null; if(code == null){ //如果编码为空,说明查询的是省 provinceCityAreaSelectVO = provinceCityAreaService.getOnlyProvince(); }else if(code.indexOf("a00") > -1 && code.indexOf("c00") > -1){ //如果编码包含a00和c00,说明查询的是市 String provinceCode = code.substring(0, 3); provinceCityAreaSelectVO = provinceCityAreaService.getOnlyCity(provinceCode); }else{ //否则,查询的是区 String provinceCode = code.substring(0, 3); String cityCode = code.substring(3,6); provinceCityAreaSelectVO = provinceCityAreaService.getOnlyArea(provinceCode, cityCode); } return HttpResult.success(provinceCityAreaSelectVO); }catch (Exception e){ e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } }
package com.springboot.racemanage.controller.restful; import com.springboot.racemanage.controller.restful.restfulDO.ResultDO; import com.springboot.racemanage.dao.LogDao; import com.springboot.racemanage.po.*; import com.springboot.racemanage.service.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.*; import java.util.stream.IntStream; @RestController @RequestMapping("/restful/student") @Transactional public class StudentControllerRestful { @Autowired ProjectService projectService; @Autowired TaskService taskService; @Autowired TeamerService teamerService; @Autowired InviteService inviteService; @Autowired StudentService studentService; @Autowired private MessageService messageService; @Autowired private TermService termService; @Autowired private RaceService raceService; @Autowired private LogService logService; @Autowired private RaceinfoService raceinfoService; @RequestMapping(value = "/newMsgNum",method = RequestMethod.GET) public Integer newMsgNum(@RequestParam("stuUUID")String stuUUID) { int num; num = messageService.countByToUuidAndStatus(stuUUID, 1); return num; } @RequestMapping(value = "/newTaskNum",method = RequestMethod.GET) public Integer newTaskNum(@RequestParam("stuUUID") String stuUUID) { List<String> toList = teamerService.findUuidByStuUuid(stuUUID); Integer num=0; for (String aToList : toList) { num += taskService.countByStatusAndToUuid(2, aToList); } return num; } @RequestMapping(value = "/newInvititionNum",method = RequestMethod.GET) public int newInvititionNum(@RequestParam("stuUUID") String stuUUID) { return inviteService.countByToUuidAndStatus(stuUUID, 1); } @RequestMapping(value = "/newTaskList",method = RequestMethod.GET) public List<Task> newTaskList(@RequestParam("stuUUID")String stuUUID) { List<Teamer> teamerList = teamerService.findByStuUuid(stuUUID); List<Task> taskList = new ArrayList<Task>(); IntStream.range(0, teamerList.size()).forEach(i -> taskList.addAll(taskService.findByStatusAndToUuid(2, taskList.get(i).getUuid()))); return taskList; } @RequestMapping(value = "/newMessageList",method = RequestMethod.GET) public List<Message> newMessageList(@RequestParam("stuUUID")String stuUUID) { return messageService.findByToUuidAndStatus(stuUUID, 1); } @RequestMapping(value = "/newInviteList",method = RequestMethod.GET) public List<Invite> newInviteList(@RequestParam("stuUUID")String stuUUID) { return inviteService.findByToUuidAndStatus(stuUUID, 1); } @RequestMapping(value = "/notCompleteTaskNum",method = RequestMethod.GET) public Integer notCompleteTaskNum(@RequestParam("teamerUUID")String teamerUUID) { return taskService.countByStatusNotAndToUuidAndProgress(0, teamerUUID, 2); } @RequestMapping(value = "/completedTaskNum",method = RequestMethod.GET) public Integer completedTaskNum(@RequestParam("teamerUUID")String teamerUUID) { return taskService.countByStatusNotAndToUuidAndProgress(0, teamerUUID, 1); } @RequestMapping(value = "/login") public ResultDO login(@RequestParam("stuNumber") String stuNumber, @RequestParam("password") String password) { System.out.println(stuNumber); System.out.println(password); Student student = studentService.findFirstByStuNumberAndStuPasswordAndStuStatus(stuNumber, password, 1); System.out.println(student); ResultDO resultDO = new ResultDO(); if (student != null) { resultDO.setResult(student); resultDO.setCode(1); } else { resultDO.setCode(0); } return resultDO; } // @RequestMapping("/loginTest") // public String loginTest(@RequestParam("Number") String stuNumber, // @RequestParam("passWord") String password) { // Student student = studentService.findFirstByStuNumberAndStuPasswordAndStuStatus(stuNumber, password, 1); // if (student != null) { // return "OK"; // }else { // return "Wrong"; // } // } @RequestMapping(value = "/getMyProjectList") public ResultDO getMyProjectList(@RequestParam("stuUUID") String stuUUID) { List<Teamer> teamerList = teamerService.findByStatusAndStuUuid(1,stuUUID); List<Project> projectList = new ArrayList<>(); for (Teamer t:teamerList) { projectList.add(projectService.findFirstByUuid(t.getProUuid())); } ResultDO resultDO = new ResultDO(); if (teamerList == null) { resultDO.setCode(0); resultDO.setMsg("可能是stuUUID不正确"); return resultDO; } resultDO.setResult(projectList); resultDO.setCode(1); resultDO.setMsg("正常结果"); return resultDO; } @RequestMapping("/getMyRaceList") public ResultDO getMyRaceList(@RequestParam("stuUUID") String stuUUID, //progress all:所有进度的赛事 complete:已完成的赛事 @RequestParam("progress")String progress) { Term term = termService.findFirstByStatusOrderByTerm(1); List<Race> myRaceList = null; ResultDO resultDO = new ResultDO(); switch (progress) { case "all": myRaceList = raceService.getStuRaceListByTerm(stuUUID, term.getTerm()); break; case "complete": myRaceList = raceService.getAchivementListByStuUuid(stuUUID); break; default: resultDO.setCode(0); resultDO.setMsg("progress字段不合法 progress可选:all,complete"); break; } if (myRaceList != null) { resultDO.setCode(1); resultDO.setMsg("正常结果"); resultDO.setResult(myRaceList); } else { resultDO.setCode(0); resultDO.setMsg("查询失败"); } return resultDO; } @RequestMapping("/getAllRaceByPageNo") public ResultDO getAllRaceByPageNo(@RequestParam("pageNo")Integer pageNo) { List<Race> raceList = raceService.findByPageNo(pageNo); ResultDO resultDO = new ResultDO(); resultDO.setMsg("正常结果"); resultDO.setCode(1); resultDO.setResult(raceList); return resultDO; } @RequestMapping("/getAllRaceInfoByPageNo") public ResultDO getAllRaceInfoByPageNo(@RequestParam("pageNo")Integer pageNo) { List<Raceinfo> raceInfoList = raceinfoService.findByPageNo(pageNo); ResultDO resultDO = new ResultDO(); resultDO.setMsg("正常结果"); resultDO.setCode(1); resultDO.setResult(raceInfoList); return resultDO; } @RequestMapping("/getProjectDetail") public ResultDO getProjectDetail(@RequestParam("proUUID")String proUUID,@RequestParam("stuUUID")String stuUUID) { Project project = projectService.findFirstByUuid(proUUID); System.out.println(project); Teamer myTeamer = teamerService.findFirstByStatusAndStuUuidAndProUuid(1, stuUUID, proUUID); List<Task> myTaskList = taskService.findByToUuidAndStatusNot(myTeamer.getUuid(), 0); List<Teamer> proTeamerList = teamerService.findByStatusAndProUuid(1, proUUID); //名字太不优雅 回来想到更好的就改下 List<Map> logandteamernameList = logService.getLogAndTeamerNameByProUuid(proUUID); Map<String, Object> result = new HashMap<>(); result.put("project", project); result.put("myTaskList", myTaskList); result.put("proTeamerList", proTeamerList); result.put("log", logandteamernameList); ResultDO resultDO = new ResultDO(); resultDO.setResult(result); resultDO.setCode(1); resultDO.setMsg("请求成功"); return resultDO; } @RequestMapping("/getStuNameByUUID") public ResultDO getStuNameByUUID(@RequestParam("stuUUID")String stuUUID) { String stuName = studentService.findStuNameByStuStatusAndStuUuid(1, stuUUID); ResultDO resultDO = new ResultDO(); resultDO.setResult(stuName); resultDO.setMsg("查询成功"); resultDO.setCode(1); return resultDO; } @RequestMapping("/applyRace") public ResultDO applyRace(@RequestParam("projectUUID")String projectUUID, @RequestParam("raceInfoUUID")String raceInfoUUID) { Project project = projectService.findFirstByUuid(projectUUID); Raceinfo raceinfo = raceinfoService.findFirstByUuid(raceInfoUUID); ResultDO resultDO = new ResultDO(); Term term = termService.findFirstByStatusOrderByTerm(1); Race race = getRace(raceInfoUUID, project, raceinfo, term); int sqlCode = raceService.insertSelective(race); if (sqlCode == 1) { resultDO.setMsg("报名成功"); resultDO.setCode(1); resultDO.setResult("报名成功"); return resultDO; } else { resultDO.setCode(0); resultDO.setMsg("报名失败"); resultDO.setResult("报名失败"); return resultDO; } } @RequestMapping("/getCanApplyProject") public ResultDO getCanApplyProject(@RequestParam("stuUUID")String stuUUID, @RequestParam("raceInfoUUID")String raceInfoUUID) { List<Project> projectList = projectService.getProjectForRaceinfoDetail(stuUUID, raceInfoUUID); ResultDO resultDO = new ResultDO(); if (projectList != null) { resultDO.setCode(1); resultDO.setMsg("请求成功"); resultDO.setResult(projectList); } else { resultDO.setCode(0); resultDO.setMsg("请求失败"); } return resultDO; } private Race getRace(@RequestParam("raceInfoUUID") String raceInfoUUID, Project project, Raceinfo raceinfo, Term term) { Race race = new Race(); race.setDescription(raceinfo.getDescription()); race.setKind(raceinfo.getKind()); race.setProname(project.getName()); race.setProUuid(project.getUuid()); race.setRaceinfoUuid(raceInfoUUID); race.setRacename(raceinfo.getRacename()); race.setRaceteacher(project.getTname()); race.setStatus(1); race.setTerm(term.getTerm()); race.settUuid(project.gettUuid()); race.setUuid(UUID.randomUUID().toString()); return race; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.http.server.reactive; import java.net.InetSocketAddress; import java.net.URI; import reactor.core.publisher.Flux; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.http.HttpCookie; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.server.RequestPath; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.MultiValueMap; /** * Wraps another {@link ServerHttpRequest} and delegates all methods to it. * Subclasses can override specific methods selectively. * * @author Rossen Stoyanchev * @since 5.0 */ public class ServerHttpRequestDecorator implements ServerHttpRequest { private final ServerHttpRequest delegate; public ServerHttpRequestDecorator(ServerHttpRequest delegate) { Assert.notNull(delegate, "Delegate is required"); this.delegate = delegate; } public ServerHttpRequest getDelegate() { return this.delegate; } // ServerHttpRequest delegation methods... @Override public String getId() { return getDelegate().getId(); } @Override public HttpMethod getMethod() { return getDelegate().getMethod(); } @Override public URI getURI() { return getDelegate().getURI(); } @Override public RequestPath getPath() { return getDelegate().getPath(); } @Override public MultiValueMap<String, String> getQueryParams() { return getDelegate().getQueryParams(); } @Override public HttpHeaders getHeaders() { return getDelegate().getHeaders(); } @Override public MultiValueMap<String, HttpCookie> getCookies() { return getDelegate().getCookies(); } @Override @Nullable public InetSocketAddress getLocalAddress() { return getDelegate().getLocalAddress(); } @Override @Nullable public InetSocketAddress getRemoteAddress() { return getDelegate().getRemoteAddress(); } @Override @Nullable public SslInfo getSslInfo() { return getDelegate().getSslInfo(); } @Override public Flux<DataBuffer> getBody() { return getDelegate().getBody(); } /** * Return the native request of the underlying server API, if possible, * also unwrapping {@link ServerHttpRequestDecorator} if necessary. * @param request the request to check * @param <T> the expected native request type * @throws IllegalArgumentException if the native request can't be obtained * @since 5.3.3 */ public static <T> T getNativeRequest(ServerHttpRequest request) { if (request instanceof AbstractServerHttpRequest abstractServerHttpRequest) { return abstractServerHttpRequest.getNativeRequest(); } else if (request instanceof ServerHttpRequestDecorator serverHttpRequestDecorator) { return getNativeRequest(serverHttpRequestDecorator.getDelegate()); } else { throw new IllegalArgumentException( "Can't find native request in " + request.getClass().getName()); } } @Override public String toString() { return getClass().getSimpleName() + " [delegate=" + getDelegate() + "]"; } }
package com.ggtf.xieyingwu.cloudphoto.utils; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import java.io.File; /** * Created by xieyingwu on 2017/5/22. */ public class HeaderUtil { private static final int REQUEST_CODE_TAKE = 100; private static final int REQUEST_CODE_PICK = 101; private static final int REQUEST_CODE_CROP = 102; private File headerFile; public void openCameraForHeader(Activity ac, File headerFile) { this.headerFile = headerFile; Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(headerFile)); ac.startActivityForResult(takeIntent, REQUEST_CODE_TAKE); } public void pickPicForHeader(Activity ac) { Intent pickIntent = new Intent(Intent.ACTION_PICK, null); pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); ac.startActivityForResult(pickIntent, REQUEST_CODE_PICK); } private void cropPicForHeader(Activity ac, Uri uri) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("outputX", 300); intent.putExtra("outputY", 300); intent.putExtra("return-data", true); ac.startActivityForResult(intent, REQUEST_CODE_CROP); } public void onActivityResult(Activity ac, int requestCode, int resultCode, Intent data) { if (resultCode != Activity.RESULT_OK) return; switch (requestCode) { case REQUEST_CODE_TAKE: cropPicForHeader(ac, Uri.fromFile(headerFile)); break; case REQUEST_CODE_PICK: cropPicForHeader(ac, data.getData()); break; case REQUEST_CODE_CROP: saveHeader(data); break; } } private void saveHeader(Intent data) { Log.w("TAG", "saveHeader()"); Bundle extras = data.getExtras(); if (extras != null) { Bitmap photo = extras.getParcelable("data"); // TODO: 2017/5/22 存储裁剪的最终图片到本地 } } }
package com.eot3000.groups; import com.eot3000.BasicsPlugin; import org.bukkit.OfflinePlayer; import java.util.ArrayList; import java.util.List; public class Bank { private static ArrayList<Bank> banks = new ArrayList<>(); private static ArrayList<String> names = new ArrayList<>(); private int balance; private OfflinePlayer owner; private ArrayList<AccountPlayer> players = new ArrayList<>(); private String name; public ArrayList<AccountPlayer> getPlayers() { return new ArrayList<>(players); } public OfflinePlayer getOwner(){ return owner; } public static Bank getBank(String name){ for(Bank f:banks){ if(f.name.equalsIgnoreCase(name)){ return f; } } return null; } public void addPlayer(OfflinePlayer player){ players.add(BasicsPlugin.getInstance().getAccount(player)); } public int getBalance() { return balance; } public void delete(){ this.balance = 0; this.name = null; this.owner = null; this.players = null; banks.remove(this); } public void withdraw(double d){ balance -= d; } public void deposit(double d){ balance += d; } public static List<Bank> getBanks(){ return new ArrayList<>(banks); } public static List<String> getBankNames(){ return new ArrayList<>(names); } public Bank(OfflinePlayer owner, String name){ if(!(getBank(name) == null)){ throw new ExceptionInInitializerError(); } this.owner = owner; this.players.add(BasicsPlugin.getInstance().getAccount(owner)); this.name = name; banks.add(this); names.add(name); } }
package com.example.jv.fotoroom; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.yandex.disk.client.Credentials; import com.yandex.disk.client.ListItem; import com.yandex.disk.client.ProgressListener; import com.yandex.disk.client.TransportClient; import com.yandex.disk.client.exceptions.WebdavException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; /** * Created by JV on 08.01.2016. */ public class SlideShowFragment extends Fragment { public static final String TAG = "SlideShowFragment"; private static final String ITEM_LIST = "SlideShowList.itemList"; protected static final String CREDENTIALS = "SlideShow.credentials"; private Credentials credentials; private ViewPager viewPager; private Handler handler; private int currentPage = 0; public static SlideShowFragment newInstance(Credentials credentials, List<ListItem> item) { SlideShowFragment fragment = new SlideShowFragment(); Bundle args = new Bundle(); args.putParcelable(CREDENTIALS, credentials); args.putParcelableArrayList(ITEM_LIST, new ArrayList<ListItem>(item)); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); credentials = getArguments().getParcelable(CREDENTIALS); ArrayList<ListItem> itemList = getArguments().getParcelableArrayList(ITEM_LIST); handler = new Handler(); DownloadFileClass downLoader = new DownloadFileClass(); downLoader.loadFile(getActivity(), credentials, itemList); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.main, container, false); viewPager = (ViewPager) root.findViewById(R.id.pager); return root; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.example_action_bar, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case android.R.id.home: getFragmentManager().popBackStack(); break; default: return super.onOptionsItemSelected(item); } return true; } public void pagerSetAdapter(final ArrayList<File> fileList){ final Handler handler = new Handler(); viewPager.setAdapter(new MyAdapter(getChildFragmentManager(), fileList, credentials)); currentPage = 0; final Runnable Update = new Runnable() { public void run() { //if (currentPage == fileList.size() - 1) { // currentPage = 0; //} viewPager.setCurrentItem(currentPage++, true); } }; Timer swipeTimer = new Timer(); swipeTimer.schedule(new TimerTask() { @Override public void run() { handler.post(Update); } }, 200, 2000); } public static class MyAdapter extends FragmentPagerAdapter { private ArrayList<File> fileAdapterList; private Credentials credentials; public MyAdapter(FragmentManager fm, ArrayList<File> fileList, Credentials credentials) { super(fm); fileAdapterList = fileList; this.credentials = credentials; } @Override public int getCount() { return fileAdapterList.size(); } @Override public Fragment getItem(int position) { //Log.d(TAG, "size of list=" + fileAdapterList.size()); //Log.d(TAG, "p osition=" + position); return PageFragment.newInstance(fileAdapterList.get(position)); } @Override public CharSequence getPageTitle(int position) { return "Child Fragment " + position; } } class DownloadFileClass implements ProgressListener { private ArrayList<File> fileList; private File result; private boolean cancelled; public void loadFile(final Context context, final Credentials credentials, final ArrayList<ListItem> itemList) { fileList = new ArrayList<>(); final ImageValidator imageValid = new ImageValidator(); new Thread(new Runnable() { @Override public void run () { TransportClient client = null; try { client = TransportClient.getInstance(context, credentials); for (int i = 0; i < itemList.size(); ++i) { if (imageValid.validate(itemList.get(i).getDisplayName())) { result = new File(context.getFilesDir(), new File(itemList.get(i).getFullPath()).getName()); client.downloadFile(itemList.get(i).getFullPath(), result, DownloadFileClass.this); fileList.add(result); } } downloadComplete(); } catch (IOException ex) { Log.d(TAG, "loadFile", ex); //sendException(ex); } catch (WebdavException ex) { Log.d(TAG, "loadFile", ex); // sendException(ex); } finally { if (client != null) { client.shutdown(); } } } }).start(); } @Override public void updateProgress (final long loaded, final long total) { } @Override public boolean hasCancelled () { return cancelled; } public void downloadComplete() { handler.post(new Runnable() { @Override public void run() { pagerSetAdapter(fileList); } }); } public void cancelDownload() { cancelled = true; } } }
package com.techelevator; public class VendingMachineCLI { public static void main(String[] args) { Printer.splashScreen(); FileIO.loadCsv(); Inventory.buildInventory(); SalesReport.loadRunningSalesMap(); MainMenu.run(); } }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public * * License as published by the Free Software Foundation; either * * version 3 of the License, or any later version. * * * * Data Crow is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this program. If not, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.console.windows.reporting; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JCheckBox; import javax.swing.JPanel; import net.datacrow.console.ComponentFactory; import net.datacrow.console.Layout; import net.datacrow.console.components.DcNumberField; import net.datacrow.core.migration.itemexport.ItemExporterSettings; import net.datacrow.core.resources.DcResources; public class ReportSettingsPanel extends JPanel { private JCheckBox cbResizeImages = ComponentFactory.getCheckBox(DcResources.getText("lblScaleImages")); private JCheckBox cbCopyImages = ComponentFactory.getCheckBox(DcResources.getText("lblCopyImage")); private DcNumberField nfWidth = ComponentFactory.getNumberField(); private DcNumberField nfHeight = ComponentFactory.getNumberField(); private DcNumberField nfMaxTextLength = ComponentFactory.getNumberField(); public ReportSettingsPanel() { super(); build(); } private void applySelection() { cbResizeImages.setEnabled(cbCopyImages.isSelected()); cbResizeImages.setSelected(!cbCopyImages.isSelected() ? false : cbResizeImages.isSelected()); nfWidth.setEnabled(cbResizeImages.isSelected()); nfHeight.setEnabled(cbResizeImages.isSelected()); } public void saveSettings(ItemExporterSettings properties, boolean saveToDisk) { properties.set(ItemExporterSettings._COPY_IMAGES, cbCopyImages.isSelected()); properties.set(ItemExporterSettings._SCALE_IMAGES, cbResizeImages.isSelected()); properties.set(ItemExporterSettings._MAX_TEXT_LENGTH, nfMaxTextLength.getValue()); properties.set(ItemExporterSettings._IMAGE_WIDTH, nfWidth.getValue()); properties.set(ItemExporterSettings._IMAGE_HEIGHT,nfHeight.getValue()); if (saveToDisk) properties.save(); } public void applySettings(ItemExporterSettings properties) { cbCopyImages.setSelected(properties.getBoolean(ItemExporterSettings._COPY_IMAGES)); cbResizeImages.setSelected(properties.getBoolean(ItemExporterSettings._SCALE_IMAGES)); nfMaxTextLength.setValue(properties.getInt(ItemExporterSettings._MAX_TEXT_LENGTH)); nfWidth.setValue(properties.getInt(ItemExporterSettings._IMAGE_WIDTH)); nfHeight.setValue(properties.getInt(ItemExporterSettings._IMAGE_HEIGHT)); applySelection(); } @Override public void setEnabled(boolean b) { cbResizeImages.setEnabled(b); cbCopyImages.setEnabled(b); nfWidth.setEnabled(b); nfHeight.setEnabled(b); nfMaxTextLength.setEnabled(b); } private void build() { setLayout(Layout.getGBL()); ResizeListener rl = new ResizeListener(); cbResizeImages.addActionListener(rl); cbCopyImages.addActionListener(rl); Dimension size = new Dimension(100, ComponentFactory.getPreferredFieldHeight()); nfHeight.setMinimumSize(size); nfHeight.setPreferredSize(size); nfWidth.setMinimumSize(size); nfWidth.setPreferredSize(size); JPanel panelImages = new JPanel(); panelImages.setLayout(Layout.getGBL()); panelImages.add(cbCopyImages, Layout.getGBC( 0, 0, 1, 1, 1.0, 1.0 ,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets( 5, 5, 5, 5), 0, 0)); panelImages.add(cbResizeImages, Layout.getGBC( 0, 1, 1, 1, 1.0, 1.0 ,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets( 5, 5, 5, 5), 0, 0)); panelImages.add(nfWidth, Layout.getGBC( 0, 2, 1, 1, 1.0, 1.0 ,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets( 5, 5, 5, 5), 0, 0)); panelImages.add(ComponentFactory.getLabel(DcResources.getText("lblWidth")), Layout.getGBC( 1, 2, 1, 1, 1.0, 1.0 ,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets( 5, 5, 5, 5), 0, 0)); panelImages.add(nfHeight, Layout.getGBC( 0, 3, 1, 1, 1.0, 1.0 ,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets( 5, 5, 5, 5), 0, 0)); panelImages.add(ComponentFactory.getLabel(DcResources.getText("lblHeight")), Layout.getGBC( 1, 3, 1, 1, 1.0, 1.0 ,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets( 5, 5, 5, 5), 0, 0)); panelImages.setBorder(ComponentFactory.getTitleBorder(DcResources.getText("lblImages"))); nfMaxTextLength.setMinimumSize(new Dimension(40, ComponentFactory.getPreferredFieldHeight())); nfMaxTextLength.setPreferredSize(new Dimension(40, ComponentFactory.getPreferredFieldHeight())); JPanel panelText = new JPanel(); panelText.setLayout(Layout.getGBL()); panelText.add(ComponentFactory.getLabel(DcResources.getText("lblMaxTextLength")), Layout.getGBC( 0, 0, 1, 1, 1.0, 1.0 ,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets( 5, 5, 5, 5), 0, 0)); panelText.add(nfMaxTextLength, Layout.getGBC( 1, 0, 1, 1, 1.0, 1.0 ,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets( 5, 5, 5, 5), 0, 0)); panelText.setBorder(ComponentFactory.getTitleBorder(DcResources.getText("lblText"))); add(panelImages, Layout.getGBC( 0, 0, 1, 1, 1.0, 1.0 ,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets( 5, 5, 5, 5), 0, 0)); add(panelText, Layout.getGBC( 0, 1, 1, 1, 1.0, 1.0 ,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets( 5, 5, 5, 5), 0, 0)); } private class ResizeListener implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { applySelection(); } } }
package tk.paarshvchitra.textilepro.textilepro; /** * Created by PRIYANKA on 08-12-2014. */ public interface NavigationDrawerCallbacks { void onNavigationDrawerItemSelected(int position); }
package com.imagsky.exception; public class UnsupportedModuleBizException extends BaseException { private static final long serialVersionUID = 1L; private String unsupportedModuleBizCode = null; public UnsupportedModuleBizException(String unsupportedModuleBizType) { super("App Code \"" + unsupportedModuleBizType + "\" not supported by the the system.", "ErrorCodeConstants.ERR_SYS_MODULE_BIZ_CLASS_NOT_FOUND"); this.unsupportedModuleBizCode = unsupportedModuleBizType; } public UnsupportedModuleBizException(String unsupportedModuleBizType, Throwable cause) { super("ErrorCodeConstants.ERR_SYS_MODULE_BIZ_CLASS_NOT_FOUND", cause); this.unsupportedModuleBizCode = unsupportedModuleBizType; } public String getUnsupportedAppCode() { return this.unsupportedModuleBizCode; } }
package Revise.graphs; public class SurroundedRegionIslandProblem { public void solve(char[][] board) { if (board == null || board.length == 0) return; int m = board.length; int n = board[0].length; for (int i = 0; i < m; i++) { //check for left end if (board[i][0] == 'O') { merge(board, i, 0); } //check for right end if (board[i][n - 1] == 'O') { merge(board, i, n - 1); } } for (int j = 0; j < n; j++) { //check for top end if (board[0][j] == 'O') { merge(board, 0, j); } //check for bottom end if (board[m - 1][j] == 'O') { merge(board, m - 1, j); } } //process the board for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'O') { board[i][j] = 'X'; } else if (board[i][j] == '#') { board[i][j] = 'O'; } } } } public void merge(char[][] board, int i, int j) { if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return; if (board[i][j] != 'O') return; board[i][j] = '#'; merge(board, i - 1, j); merge(board, i + 1, j); merge(board, i, j - 1); merge(board, i, j + 1); } public static void main(String a[]) { SurroundedRegionIslandProblem s = new SurroundedRegionIslandProblem(); char[][] board = new char[][]{ {'X', 'X', 'X', 'X'}, {'X', 'O', 'X', 'X'}, {'X', 'O', 'O', 'X'}, {'X', 'O', 'X', 'X'}, {'X', 'X', 'O', 'O'}, }; s.solve(board); System.out.println(board); } }
package employeeScheduler.model; import java.util.ArrayList; /** * Object created by schedule builder. It contains structure of defined work shifts combined with employees. */ public class ResultingSchedule { private ArrayList<Integer>[][] result; private ArrayList<EmployeeSchedule> employeesSchedules; private Integer days; private Integer shifts; private ArrayList<Integer> maxEmployeesPerShift; public ResultingSchedule(Integer days, Integer shifts, Integer employeesNumber) { this.setDays(days); this.setShifts(shifts); maxEmployeesPerShift = new ArrayList<>(); employeesSchedules = new ArrayList<>(); for (int i=0;i<employeesNumber;i++){ getEmployeesSchedules().add(new EmployeeSchedule(i)); } result = new ArrayList[days][shifts]; for (int i = 0; i < days; i++) for (int j = 0; j < shifts; j++) { result[i][j] = new ArrayList<>(); } } public void addShiftMaxEmployee(Integer shiftNumber, Integer maxEmployees){ maxEmployeesPerShift.add(shiftNumber,maxEmployees); } public Integer getMaxEmployeesPerShift(Integer shiftNumber){ return maxEmployeesPerShift.get(shiftNumber); } public String toString() { String stringSchedule = ""; if (getDays() ==0){ return "No schedule"; } for (int i = 0; i < getShifts(); i++){ for (int j = 0; j < getDays(); j++) { stringSchedule += result[j][i].toString(); } stringSchedule += "\n"; } return stringSchedule; } public ArrayList<Integer> getEmployeeListOnShift(Integer day, Integer shift) { return result[day][shift]; } public ArrayList<Integer>[][] getResult() { return result; } public void addEmployee(Integer day, Integer shift, Integer employeeID) { getEmployeesSchedules().get(employeeID).addShift(day,shift); result[day][shift].add(employeeID); } public ArrayList<EmployeeSchedule> getEmployeesSchedules() { return employeesSchedules; } public Integer getDays() { return days; } public void setDays(Integer days) { this.days = days; } public Integer getShifts() { return shifts; } public void setShifts(Integer shifts) { this.shifts = shifts; } }
package org.desertworkz; import java.net.InetSocketAddress; import com.sun.net.httpserver.HttpServer; public class Main { public static void main(String[] args) throws Exception { // test data Handlers.addCounterService("accounts", new String[]{"C1"}); Handlers.addCounterService("collections", new String[]{"C1", "C2"}); Handlers.addCounterService("taxation", new String[]{"C2"}); Handlers.addCounterService("finance", new String[]{"C3"}); HttpServer server = HttpServer.create(new InetSocketAddress("0.0.0.0", 8000), 0); server.createContext("/newTicket", new Handlers.newTicket()); server.createContext("/nextTicket", new Handlers.nextTicket()); server.setExecutor(null); // creates a default executor server.start(); } }
package com.sda.geometry; public abstract class FlatShape { double width; double height; public FlatShape(double width, double height) { this.width = width; this.height = height; } void printDimensions (double width, double height){ System.out.println(String.format("FlatShape [x, y] = [%f, %f]", width, height)); } abstract double getArea(double x, double y); }
package hibernate_test; import hibernate_test.entity.Employee; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** В данном классе реализовано удаление работника(-ов) в соответствии с параметрами запроса. * Для примера, я удалял работника по имени */ public class DeleteEmployee { public static void main(String[] args) { SessionFactory factory = new Configuration() .configure("hibernate.cfg.xml") .addAnnotatedClass(Employee.class) .buildSessionFactory(); try { Session session = factory.getCurrentSession(); session.beginTransaction(); // Без Query // Employee emp = session.get(Employee.class, 7); // session.delete(emp); session.createQuery("delete Employee " + "where name = 'Julia'").executeUpdate(); session.getTransaction().commit(); System.out.println("DONE!"); } finally { factory.close(); } } }
package lab4; import akka.actor.*; import akka.japi.pf.ReceiveBuilder; import akka.routing.RoundRobinPool; import java.time.Duration; import java.util.Collections; public class RouterActor extends AbstractActor { private ActorRef storageActor; private SupervisorStrategy strategy; private ActorRef testerActor; RouterActor(ActorSystem system){ this.storageActor = system.actorOf(Props.create(StorageActor.class), "StorageActor"); this.strategy = new OneForOneStrategy( Constans.retriesCount, Duration.ofMinutes(1), Collections.singletonList(Exception.class) ); this.testerActor = system.actorOf( new RoundRobinPool(Constans.workersCount) .withSupervisorStrategy(strategy) .props(Props.create(TesterActor.class, storageActor)) ); } private void runTests(TestPackage testPackage){ for (TestData test: testPackage.getTests()){ test.setParentPackage(testPackage); testerActor.tell(test, ActorRef.noSender()); } } @Override public Receive createReceive(){ return ReceiveBuilder.create() .match(TestPackage.class, msg -> runTests(msg)) .match(String.class, msg -> storageActor.forward(msg, getContext())) .build(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.jearl.logback; import ch.qos.logback.classic.Level; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.slf4j.Marker; /** * * @author can */ public class LogService implements Log { private final org.slf4j.Logger logger; // private static final Integer STACKTRACE_LIMIT = 10; public LogService(Class clazz) { logger = LoggerFactory.getLogger(clazz); } @Override public void changeLevelTreshold(Level l) { throw new UnsupportedOperationException("Not supported yet."); } public static void putMDC(CustomLogField logField, String value) { if (value != null) { MDC.put(logField.getValue(), (String) value); } } private void putArgument(CustomLogField logField, Object arg) { String putValue = null; if (arg != null) { if (arg instanceof ErrorCategory) { putValue = ((ErrorCategory) arg).getValue(); } else { putValue = arg.toString(); } putMDC(logField, putValue); } } private String convert(Integer value) { if (value == null) { return null; } return value.toString(); } @Override public void trace(String msg) { if (isTraceEnabled()) { logger.trace((String) msg); MDC.clear(); } } @Override public void trace(String msg, Throwable t) { if (isTraceEnabled()) { logger.trace((String) msg, t); MDC.clear(); } } @Override public boolean isTraceEnabled() { return this.logger.isTraceEnabled(); } @Override public void info(String msg) { if (isInfoEnabled()) { this.logger.info(msg); } } @Override public void info(String msg, Throwable t) { if (isInfoEnabled()) { this.logger.info(msg, t); } } @Override public void debug(String msg) { if (isDebugEnabled()) { this.logger.debug((String) msg); } } @Override public void debug(String msg, Throwable t) { if (isDebugEnabled()) { this.logger.debug((String) msg, t); } } @Override public void debug(Integer userid, ErrorCategory category, String msg, Throwable t) { if (isDebugEnabled()) { putArgument(CustomLogField.LOG_USER, convert(userid)); putArgument(CustomLogField.ERROR_CATEGORY, category); this.logger.debug(msg, t); MDC.clear(); } } @Override public void debug(String appContainer, Integer userid, ErrorCategory category, String msg, Throwable t) { if (isDebugEnabled()) { putArgument(CustomLogField.LOG_USER, convert(userid)); putArgument(CustomLogField.ERROR_CATEGORY, category); this.logger.debug((String) msg, t); MDC.clear(); } } @Override public boolean isDebugEnabled() { return this.logger.isDebugEnabled(); } @Override public void warn(String appContainer, String msg) { if (isWarnEnabled()) { putArgument(CustomLogField.LOG_CONTAINER, appContainer); this.logger.warn(msg); MDC.clear(); } } @Override public void warn(String appContainer, String msg, Throwable t) { if (isWarnEnabled()) { putArgument(CustomLogField.LOG_CONTAINER, appContainer); this.logger.warn(msg, t); MDC.clear(); } } @Override public void warn(String appContainer, Integer userid, ErrorCategory category, String msg, Throwable t) { if (isWarnEnabled()) { putArgument(CustomLogField.LOG_CONTAINER, appContainer); putArgument(CustomLogField.LOG_USER, convert(userid)); putArgument(CustomLogField.ERROR_CATEGORY, category); this.logger.warn(msg, t); MDC.clear(); } } @Override public void error(String appContainer, String msg) { if (isErrorEnabled()) { logger.error((String) msg); MDC.clear(); } } @Override public void error(String appContainer, String msg, ErrorCategory category) { if (isErrorEnabled()) { putArgument(CustomLogField.LOG_CONTAINER, appContainer); putArgument(CustomLogField.ERROR_CATEGORY, category); logger.error((String) msg); MDC.clear(); } } @Override public void error(String appContainer, Integer userid, String msg, ErrorCategory category) { if (isErrorEnabled()) { putArgument(CustomLogField.LOG_USER, userid); putArgument(CustomLogField.ERROR_CATEGORY, category); putArgument(CustomLogField.LOG_CONTAINER, appContainer); logger.error((String) msg); MDC.clear(); } } @Override public void error(String appContainer, Integer userid, String msg) { if (isErrorEnabled()) { putArgument(CustomLogField.LOG_USER, convert(userid)); putArgument(CustomLogField.LOG_CONTAINER, appContainer); logger.error((String) msg); MDC.clear(); } } @Override public void error(String appContainer, String msg, ErrorCategory category, Throwable t) { if (isErrorEnabled()) { putArgument(CustomLogField.ERROR_CATEGORY, category); putArgument(CustomLogField.LOG_CONTAINER, appContainer); logger.error((String) msg, t); MDC.clear(); } } @Override public void error(String appContainer, Integer userid, ErrorCategory category, String msg) { if (isErrorEnabled()) { putArgument(CustomLogField.LOG_USER, convert(userid)); putArgument(CustomLogField.ERROR_CATEGORY, category); putArgument(CustomLogField.LOG_CONTAINER, appContainer); this.logger.error(msg); MDC.clear(); } } @Override public void error(String appContainer, Integer userid, ErrorCategory category, String msg, Throwable t) { if (isErrorEnabled()) { putArgument(CustomLogField.LOG_USER, convert(userid)); putArgument(CustomLogField.ERROR_CATEGORY, category); putArgument(CustomLogField.LOG_CONTAINER, appContainer); this.logger.error(msg, t); MDC.clear(); } } @Override public void logNestedException(Level level, String msg, Throwable t) { throw new UnsupportedOperationException("Not supported yet."); } public StringBuilder getPrintedStackTrace(Throwable t, int limit) { StringBuilder builder = new StringBuilder(); if (t != null) { StackTraceElement[] traceElements = t.getStackTrace(); if (traceElements != null) { int iterationCount = traceElements.length; if (iterationCount > limit) { iterationCount = limit; } for (int i = 0; i < iterationCount; i++) { builder.append("at "); builder.append("---"); builder.append(traceElements[i].getClassName()); builder.append("."); builder.append(traceElements[i].getMethodName()); builder.append("."); builder.append("("); builder.append(traceElements[i].getFileName()); builder.append(traceElements[i].getLineNumber()); builder.append(")"); builder.append("\n"); } } } return builder; } public String getReadyErrorCauseMessage(Throwable t, int limit) { if (t != null) { String msg = ""; if (t.getMessage() != null) { msg = t.toString(); } msg += "\n"; msg += getPrintedStackTrace(t, limit); return msg; } else { return null; } } @Override public String getName() { return this.logger.getName(); } @Override public void trace(String string, Object o) { if (isTraceEnabled()) { this.logger.trace(string, o); } } @Override public void trace(String string, Object o, Object o1) { if (isTraceEnabled()) { this.logger.trace(string, o, o1); } } @Override public void trace(String string, Object[] os) { if (isTraceEnabled()) { this.logger.trace(string, os); } } @Override public boolean isTraceEnabled(Marker marker) { return this.logger.isTraceEnabled(marker); } @Override public void trace(Marker marker, String string) { if (isTraceEnabled(marker)) { this.logger.trace(marker, string); } } @Override public void trace(Marker marker, String string, Object o) { if (isTraceEnabled(marker)) { this.logger.trace(marker, string, o); } } @Override public void trace(Marker marker, String string, Object o, Object o1) { if (isTraceEnabled(marker)) { this.logger.trace(marker, string, o, o1); } } @Override public void trace(Marker marker, String string, Object[] os) { if (isTraceEnabled(marker)) { this.logger.trace(marker, string, os); } } @Override public void trace(Marker marker, String string, Throwable thrwbl) { if (isTraceEnabled(marker)) { this.logger.trace(marker, string, thrwbl); } } @Override public void debug(String string, Object o) { if (isDebugEnabled()) { this.logger.debug(string, o); } } @Override public void debug(String string, Object o, Object o1) { if (isDebugEnabled()) { this.logger.debug(string, o, o1); } } @Override public void debug(String string, Object[] os) { if (isDebugEnabled()) { this.logger.debug(string, os); } } @Override public boolean isDebugEnabled(Marker marker) { return this.logger.isDebugEnabled(marker); } @Override public void debug(Marker marker, String string) { if (isDebugEnabled(marker)) { this.logger.debug(marker, string); } } @Override public void debug(Marker marker, String string, Object o) { if (isDebugEnabled(marker)) { this.logger.debug(marker, string, o); } } @Override public void debug(Marker marker, String string, Object o, Object o1) { if (isDebugEnabled(marker)) { this.logger.debug(marker, string, o, o1); } } @Override public void debug(Marker marker, String string, Object[] os) { if (isDebugEnabled(marker)) { this.logger.debug(marker, string, os); } } @Override public void debug(Marker marker, String string, Throwable thrwbl) { if (isDebugEnabled(marker)) { this.logger.debug(marker, string, thrwbl); } } @Override public void info(String string, Object o) { if (isInfoEnabled()) { this.logger.info(string, o); } } @Override public void info(String string, Object o, Object o1) { if (isInfoEnabled()) { this.logger.info(string, o, o1); } } @Override public void info(String string, Object[] os) { if (isInfoEnabled()) { this.logger.info(string, os); } } @Override public boolean isInfoEnabled(Marker marker) { return this.logger.isInfoEnabled(marker); } @Override public boolean isInfoEnabled() { return this.logger.isInfoEnabled(); } @Override public void info(Marker marker, String string) { if (isInfoEnabled(marker)) { this.logger.info(marker, string); } } @Override public void info(Marker marker, String string, Object o) { if (isInfoEnabled(marker)) { this.logger.info(marker, string, o); } } @Override public void info(Marker marker, String string, Object o, Object o1) { if (isInfoEnabled(marker)) { this.logger.info(marker, string, o, o1); } } @Override public void info(Marker marker, String string, Object[] os) { if (isInfoEnabled(marker)) { this.logger.info(marker, string, os); } } @Override public void info(Marker marker, String string, Throwable thrwbl) { if (isInfoEnabled(marker)) { this.logger.info(marker, string, thrwbl); } } @Override public boolean isWarnEnabled() { return this.logger.isWarnEnabled(); } @Override public void warn(String string) { if (isWarnEnabled()) { this.logger.warn(string); } } @Override public void warn(String string, Object o) { if (isWarnEnabled()) { this.logger.warn(string, o); } } @Override public void warn(String string, Object[] os) { if (isWarnEnabled()) { this.warn(string, os); } } @Override public void warn(String string, Object o, Object o1) { if (isWarnEnabled()) { this.logger.warn(string, o, o1); } } @Override public void warn(String string, Throwable thrwbl) { if (isWarnEnabled()) { this.logger.warn(string, thrwbl); } } @Override public boolean isWarnEnabled(Marker marker) { return this.logger.isWarnEnabled(); } @Override public void warn(Marker marker, String string) { if (isWarnEnabled(marker)) { this.logger.warn(marker, string); } } @Override public void warn(Marker marker, String string, Object o) { if (isWarnEnabled(marker)) { this.logger.warn(marker, string, o); } } @Override public void warn(Marker marker, String string, Object o, Object o1) { if (isWarnEnabled(marker)) { this.logger.warn(marker, string, o, o1); } } @Override public void warn(Marker marker, String string, Object[] os) { if (isWarnEnabled(marker)) { this.logger.warn(marker, string, os); } } @Override public void warn(Marker marker, String string, Throwable thrwbl) { if (isWarnEnabled(marker)) { this.logger.warn(marker, string, thrwbl); } } @Override public boolean isErrorEnabled() { return this.logger.isErrorEnabled(); } @Override public void error(String string) { if (isErrorEnabled()) { this.logger.error(string); } } @Override public void error(String string, Object o) { if (isErrorEnabled()) { this.logger.error(string, o); } } @Override public void error(String string, Object o, Object o1) { if (isErrorEnabled()) { this.logger.error(string, o, o1); } } @Override public void error(String string, Object[] os) { if (isErrorEnabled()) { this.logger.error(string, os); } } @Override public void error(String string, Throwable thrwbl) { if (isErrorEnabled()) { this.logger.error(string, thrwbl); } } @Override public boolean isErrorEnabled(Marker marker) { return this.logger.isErrorEnabled(marker); } @Override public void error(Marker marker, String string) { if (isErrorEnabled(marker)) { this.logger.error(marker, string); } } @Override public void error(Marker marker, String string, Object o) { if (isErrorEnabled(marker)) { this.logger.error(marker, string, o); } } @Override public void error(Marker marker, String string, Object o, Object o1) { if (isErrorEnabled(marker)) { this.logger.error(marker, string, o, o1); } } @Override public void error(Marker marker, String string, Object[] os) { if (isErrorEnabled(marker)) { this.logger.error(marker, string, os); } } @Override public void error(Marker marker, String string, Throwable thrwbl) { if (isErrorEnabled(marker)) { this.logger.error(marker, string, thrwbl); } } }
package com.microservice.studentservice.service; import com.microservice.studentservice.entity.Student; import com.microservice.studentservice.feignClients.CustomFeignClient; import com.microservice.studentservice.repository.StudentRepository; import com.microservice.studentservice.request.StudentRequest; import com.microservice.studentservice.response.AddressResponse; import com.microservice.studentservice.response.StudentResponse; import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; @Service public class StudentServiceImpl implements StudentService{ @Autowired private StudentRepository studentRepository; @Autowired private CommonService commonService ; @Autowired CustomFeignClient customFeignClient ; @Override public StudentResponse createStudent(StudentRequest studentRequest) { // Here, Entity is Student. So, convert Student Request object into Student to save into database. Student student = new Student() ; student.setAddressId(studentRequest.getAddressId()); student.setFirstName(studentRequest.getFirstName()); student.setLastName(studentRequest.getLastName()); student.setEmail(studentRequest.getEmail()); student = studentRepository.save(student) ; // Now, create a response dto from Student object so that we can view the saved object in postman. StudentResponse studentResponse = new StudentResponse(student) ; // calling address-service using web-client. // studentResponse.setAddressResponse(getAddressById(student.getAddressId())); // calling address-service using feign-client studentResponse.setAddressResponse(commonService.getAddressById(student.getAddressId())); return studentResponse ; } @Override public StudentResponse getStudentById(long id) { Student student = studentRepository.findById(id).get() ; StudentResponse studentResponse = new StudentResponse(student) ; // studentResponse.setAddressResponse(getAddressById(student.getAddressId())); // calling address-service using address-feign-client studentResponse.setAddressResponse(commonService.getAddressById(student.getAddressId())); return studentResponse ; } }
package com.application.operations; import java.beans.PropertyVetoException; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.sql.SQLException; import java.util.List; import com.application.db.TagsDao; import com.application.db.dto.General; public class CopyFile { private static Path sourceFile; private static Path destFile; public static File IMG_FOLDER = null; public static void createDirectory(int id, String directory, String name) throws SQLException, IOException, PropertyVetoException { List<General> tags = TagsDao.showTags(id); for (int i = 0; i < tags.size(); i++) { IMG_FOLDER = new File(directory + "\\" + (tags.get(i).getTags())); if (!IMG_FOLDER.exists()) { IMG_FOLDER.mkdir(); } copyFileUsingApacheCommonsIO(directory + "\\" + name, IMG_FOLDER.getPath() + "\\" + name); } } public static void copyFileUsingApacheCommonsIO(String source, String dest) throws IOException { sourceFile = Paths.get(source); destFile = Paths.get(dest); Files.copy(sourceFile, destFile, StandardCopyOption.REPLACE_EXISTING); } public static void deletePicture(String directory, String name, String tag) throws IOException { Path path = Paths.get(directory + "\\" + tag + "\\" + name); Files.delete(path); File folder = new File(directory + "\\" + tag); if (!(folder.list().length > 0)) { Files.delete(Paths.get(folder.toString())); } } }
/** * #dynamic-programming #math #todo * * <p>Solution 1: DP a0 <= a1 <= ... <= am <= bm <= b(m-1) <= ... <= b0 <= b0 >= b1 >= .. >= bm * * <p>Solution 2: math 1 -- n 1 2 3 x x x | x x x x | x x x x x x x x 2 * m + n-1 (position) * * <p>-> C(2m+n-1, n-1) * * <p>Method basic: dp[i][x][y] -- so cach tao duoc 2 day a, b do dai i phan tu cuoi cua a la x va * cua b la y * * <p>m * n * n -> n^2 * m ~= 10^7 * * <p>dp[i+1] <=> dp[i] */ import java.util.Scanner; public class TwoArrays { private static long MOD = 1000000007L; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); long[][] L = new long[2 * m][n + 1]; for (int i = 0; i < 2 * m; i++) { long sumTmp = 0; for (int j = 1; j <= n; j++) { if (i == 0 || j == 1) { L[i][j] = 1; sumTmp = 1; continue; } /* L[i][j] = sum(L[i-1][k]), k = 1 .. j L[i][j+1] = sum(L[i-1][k]), k = 1 .. j+1 */ L[i][j] = (L[i - 1][j] + sumTmp) % MOD; sumTmp = L[i][j]; } } long result = 0; for (int j = 1; j <= n; j++) { result = (result + L[2 * m - 1][j]) % MOD; } System.out.println(result); } }
package com.smart.droidies.tamil.natkati.library; import java.io.IOException; import java.util.List; import java.util.Locale; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.Resources; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.os.AsyncTask; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.smart.droidies.tamil.natkati.R; import com.smart.droidies.tamil.natkati.library.util.Constant; import com.smart.droidies.tamil.natkati.library.util.LocationUtil; public class LocationPreference extends DialogPreference { private SharedPreferences locPreference; private boolean bDefault; private TextView txtLatitude; private TextView txtLongitude; private TextView txtLocation; private double latitude; private double longitude; private String location; private RadioGroup rgLocation = null; private RadioButton rbDefault = null; private RadioButton rbDynamic = null; public LocationPreference(Context context, AttributeSet attrs) { super(context, attrs); locPreference = getContext().getSharedPreferences(Constant.PREFERENCES_NAME, 0); if (locPreference.getString(Constant.C_PREF_LATITUDE, null) == null) { loadDefaultlocation(); savePreference(); } setDialogLayoutResource(R.layout.location); setNegativeButtonText(R.string.cancel); setPositiveButtonText(R.string.save); setDialogIcon(null); } @Override protected void onBindDialogView(View view) { super.onBindDialogView(view); View viewLoc = (View) view; locPreference = getContext().getSharedPreferences(Constant.PREFERENCES_NAME, 0); // Collecting location from preference loadUserlocation(); txtLatitude = (TextView) viewLoc.findViewById(R.id.txtLatitude); txtLongitude = (TextView) viewLoc.findViewById(R.id.txtLongitude); txtLocation = (TextView) viewLoc.findViewById(R.id.txtLocation); rgLocation = (RadioGroup) viewLoc.findViewById(R.id.radioLocation); rbDefault = (RadioButton) viewLoc.findViewById(R.id.locDefault); rbDynamic = (RadioButton) viewLoc.findViewById(R.id.locDynamic); displayLocation(); rgLocation.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (rbDefault.isChecked()) { loadDefaultlocation(); displayLocation(); } else if (rbDynamic.isChecked()) { new LocationTask().execute(); } } }); } private void savePreference() { Editor editor = locPreference.edit(); editor.putString(Constant.C_PREF_LATITUDE, "" + latitude); editor.putString(Constant.C_PREF_LONGITUDE, "" + longitude); if (location != null) { editor.putString(Constant.C_PREF_LOCATION, location); } else { editor.putString(Constant.C_PREF_LOCATION, Constant.C_LOC_UNKNOWN); } editor.putBoolean(Constant.C_PREF_LOC_DEFAULT, bDefault); editor.commit(); } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); if (positiveResult) { savePreference(); } } private void displayLocation() { txtLatitude.setText("" + latitude); txtLongitude.setText("" + longitude); txtLocation.setText(location); } private void loadDefaultlocation() { Resources res = getContext().getResources(); String strLatitude = res.getString(R.string.default_latitude); String strLongitude = res.getString(R.string.default_longitude); location = res.getString(R.string.default_location); bDefault = true; if (strLatitude != null) { latitude = Double.parseDouble(strLatitude); } if (strLongitude != null) { longitude = Double.parseDouble(strLongitude); } } private void loadUserlocation() { String strLatitude = locPreference.getString(Constant.C_PREF_LATITUDE, null); String strLongitude = locPreference.getString(Constant.C_PREF_LONGITUDE, null); location = locPreference.getString(Constant.C_PREF_LOCATION, null); bDefault = locPreference.getBoolean(Constant.C_PREF_LOC_DEFAULT, false); if (strLatitude != null) { latitude = Double.parseDouble(strLatitude); } if (strLongitude != null) { longitude = Double.parseDouble(strLongitude); } } private class LocationTask extends AsyncTask<Void, Void, Location> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = ProgressDialog.show(getContext(), "", "Loading"); } protected Location doInBackground(Void... urls) { Location objLocation = null; boolean interrupted = false; int counter = 0; do { counter++; objLocation = LocationUtil.getLocation(getContext()); if (counter > 5 || objLocation != null) { break; } try { Thread.sleep(2000); } catch (InterruptedException e) { interrupted = true; // e.printStackTrace(); } } while (!interrupted); return objLocation; } protected void onPostExecute(Location objLoc) { if (dialog != null) { dialog.dismiss(); } try { LocationUtil.unregisterReceiver(getContext()); } catch (Exception e) { // Suppressing expression } if (objLoc != null) { latitude = objLoc.getLatitude(); longitude = objLoc.getLongitude(); location = collectLocationName(latitude, longitude); displayLocation(); bDefault = false; } else { Toast.makeText(getContext(), "Could not collect your current location. Pelase check your network settings", Toast.LENGTH_LONG).show(); } } } private String collectLocationName(double platitude, double plongitude) { String location = Constant.C_LOC_UNKNOWN; Geocoder geocoder; List<Address> addresses = null; geocoder = new Geocoder(getContext(), new Locale("en", "US")); try { addresses = geocoder.getFromLocation(latitude, longitude, 1); } catch (IOException e) { e.printStackTrace(); } if (addresses != null && addresses.get(0) != null) { if (addresses.get(0).getAddressLine(1) != null) { location = addresses.get(0).getAddressLine(1); } else if (addresses.get(0).getAddressLine(0) != null) { location = addresses.get(0).getAddressLine(0); } else if (addresses.get(0).getAddressLine(2) != null) { location = addresses.get(0).getAddressLine(2); } } if (location.contains(",")) { location = location.substring(0, location.indexOf(",")); } return location; } }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.webui.common.identities.ext; import pl.edu.icm.unity.exceptions.IllegalIdentityValueException; import pl.edu.icm.unity.server.utils.UnityMessageSource; import pl.edu.icm.unity.stdext.identity.EmailIdentity; import pl.edu.icm.unity.types.basic.IdentityParam; import pl.edu.icm.unity.types.basic.VerifiableEmail; import pl.edu.icm.unity.types.confirmation.ConfirmationInfo; import pl.edu.icm.unity.webui.common.ComponentsContainer; import pl.edu.icm.unity.webui.common.identities.IdentityEditor; import com.vaadin.server.UserError; import com.vaadin.ui.CheckBox; import com.vaadin.ui.TextField; /** * {@link EmailIdentity} editor * @author P. Piernik */ public class EmailIdentityEditor implements IdentityEditor { private UnityMessageSource msg; private TextField field; private CheckBox confirmed; private boolean required; private boolean adminMode; public EmailIdentityEditor(UnityMessageSource msg) { this.msg = msg; } @Override public ComponentsContainer getEditor(boolean required, boolean adminMode) { field = new TextField(new EmailIdentity().getHumanFriendlyName(msg) + ":"); field.setRequired(required); this.required = required; this.adminMode = adminMode; ComponentsContainer ret = new ComponentsContainer(field); if (adminMode) { confirmed = new CheckBox(msg.getMessage( "VerifiableEmailAttributeHandler.confirmedCheckbox")); ret.add(confirmed); } return ret; } @Override public IdentityParam getValue() throws IllegalIdentityValueException { String emailVal = field.getValue().trim(); if (emailVal.equals("")) { if (!required) return null; String err = msg.getMessage("EmailIdentityEditor.emailEmpty"); field.setComponentError(new UserError(err)); throw new IllegalIdentityValueException(err); } field.setComponentError(null); try { new EmailIdentity().validate(emailVal); } catch (IllegalIdentityValueException e) { field.setComponentError(new UserError(e.getMessage())); throw e; } VerifiableEmail ve = new VerifiableEmail(emailVal); if (adminMode) ve.setConfirmationInfo(new ConfirmationInfo(confirmed.getValue())); return EmailIdentity.toIdentityParam(ve, null, null); } @Override public void setDefaultValue(IdentityParam value) { VerifiableEmail ve = EmailIdentity.fromIdentityParam(value); field.setValue(ve.getValue()); if (adminMode) confirmed.setValue(ve.isConfirmed()); } @Override public void setLabel(String value) { field.setCaption(value); } }
package org.dajlab.mondialrelayapi.soap; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p> * Classe Java pour ret_WSI2_DetailPointRelais complex type. * * <p> * Le fragment de schéma suivant indique le contenu attendu figurant dans cette * classe. * * <pre> * &lt;complexType name="ret_WSI2_DetailPointRelais"> * &lt;complexContent> * &lt;extension base="{http://www.mondialrelay.fr/webservice/}ret_"> * &lt;sequence> * &lt;element name="Num" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="LgAdr1" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="LgAdr2" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="LgAdr3" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="LgAdr4" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CP" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Ville" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Pays" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Localisation1" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Localisation2" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Horaires_Lundi" type="{http://www.mondialrelay.fr/webservice/}ArrayOfString" minOccurs="0"/> * &lt;element name="Horaires_Mardi" type="{http://www.mondialrelay.fr/webservice/}ArrayOfString" minOccurs="0"/> * &lt;element name="Horaires_Mercredi" type="{http://www.mondialrelay.fr/webservice/}ArrayOfString" minOccurs="0"/> * &lt;element name="Horaires_Jeudi" type="{http://www.mondialrelay.fr/webservice/}ArrayOfString" minOccurs="0"/> * &lt;element name="Horaires_Vendredi" type="{http://www.mondialrelay.fr/webservice/}ArrayOfString" minOccurs="0"/> * &lt;element name="Horaires_Samedi" type="{http://www.mondialrelay.fr/webservice/}ArrayOfString" minOccurs="0"/> * &lt;element name="Horaires_Dimanche" type="{http://www.mondialrelay.fr/webservice/}ArrayOfString" minOccurs="0"/> * &lt;element name="Information" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="URL_Photo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="URL_Plan" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ret_WSI2_DetailPointRelais", propOrder = { "num", "lgAdr1", "lgAdr2", "lgAdr3", "lgAdr4", "cp", "ville", "pays", "localisation1", "localisation2", "horairesLundi", "horairesMardi", "horairesMercredi", "horairesJeudi", "horairesVendredi", "horairesSamedi", "horairesDimanche", "information", "urlPhoto", "urlPlan" }) public class RetWSI2DetailPointRelais extends Ret { @XmlElement(name = "Num") protected String num; @XmlElement(name = "LgAdr1") protected String lgAdr1; @XmlElement(name = "LgAdr2") protected String lgAdr2; @XmlElement(name = "LgAdr3") protected String lgAdr3; @XmlElement(name = "LgAdr4") protected String lgAdr4; @XmlElement(name = "CP") protected String cp; @XmlElement(name = "Ville") protected String ville; @XmlElement(name = "Pays") protected String pays; @XmlElement(name = "Localisation1") protected String localisation1; @XmlElement(name = "Localisation2") protected String localisation2; @XmlElement(name = "Horaires_Lundi") protected ArrayOfString horairesLundi; @XmlElement(name = "Horaires_Mardi") protected ArrayOfString horairesMardi; @XmlElement(name = "Horaires_Mercredi") protected ArrayOfString horairesMercredi; @XmlElement(name = "Horaires_Jeudi") protected ArrayOfString horairesJeudi; @XmlElement(name = "Horaires_Vendredi") protected ArrayOfString horairesVendredi; @XmlElement(name = "Horaires_Samedi") protected ArrayOfString horairesSamedi; @XmlElement(name = "Horaires_Dimanche") protected ArrayOfString horairesDimanche; @XmlElement(name = "Information") protected String information; @XmlElement(name = "URL_Photo") protected String urlPhoto; @XmlElement(name = "URL_Plan") protected String urlPlan; /** * Obtient la valeur de la propriété num. * * @return possible object is {@link String } * */ public String getNum() { return num; } /** * Définit la valeur de la propriété num. * * @param value * allowed object is {@link String } * */ public void setNum(String value) { this.num = value; } /** * Obtient la valeur de la propriété lgAdr1. * * @return possible object is {@link String } * */ public String getLgAdr1() { return lgAdr1; } /** * Définit la valeur de la propriété lgAdr1. * * @param value * allowed object is {@link String } * */ public void setLgAdr1(String value) { this.lgAdr1 = value; } /** * Obtient la valeur de la propriété lgAdr2. * * @return possible object is {@link String } * */ public String getLgAdr2() { return lgAdr2; } /** * Définit la valeur de la propriété lgAdr2. * * @param value * allowed object is {@link String } * */ public void setLgAdr2(String value) { this.lgAdr2 = value; } /** * Obtient la valeur de la propriété lgAdr3. * * @return possible object is {@link String } * */ public String getLgAdr3() { return lgAdr3; } /** * Définit la valeur de la propriété lgAdr3. * * @param value * allowed object is {@link String } * */ public void setLgAdr3(String value) { this.lgAdr3 = value; } /** * Obtient la valeur de la propriété lgAdr4. * * @return possible object is {@link String } * */ public String getLgAdr4() { return lgAdr4; } /** * Définit la valeur de la propriété lgAdr4. * * @param value * allowed object is {@link String } * */ public void setLgAdr4(String value) { this.lgAdr4 = value; } /** * Obtient la valeur de la propriété cp. * * @return possible object is {@link String } * */ public String getCP() { return cp; } /** * Définit la valeur de la propriété cp. * * @param value * allowed object is {@link String } * */ public void setCP(String value) { this.cp = value; } /** * Obtient la valeur de la propriété ville. * * @return possible object is {@link String } * */ public String getVille() { return ville; } /** * Définit la valeur de la propriété ville. * * @param value * allowed object is {@link String } * */ public void setVille(String value) { this.ville = value; } /** * Obtient la valeur de la propriété pays. * * @return possible object is {@link String } * */ public String getPays() { return pays; } /** * Définit la valeur de la propriété pays. * * @param value * allowed object is {@link String } * */ public void setPays(String value) { this.pays = value; } /** * Obtient la valeur de la propriété localisation1. * * @return possible object is {@link String } * */ public String getLocalisation1() { return localisation1; } /** * Définit la valeur de la propriété localisation1. * * @param value * allowed object is {@link String } * */ public void setLocalisation1(String value) { this.localisation1 = value; } /** * Obtient la valeur de la propriété localisation2. * * @return possible object is {@link String } * */ public String getLocalisation2() { return localisation2; } /** * Définit la valeur de la propriété localisation2. * * @param value * allowed object is {@link String } * */ public void setLocalisation2(String value) { this.localisation2 = value; } /** * Obtient la valeur de la propriété horairesLundi. * * @return possible object is {@link ArrayOfString } * */ public ArrayOfString getHorairesLundi() { return horairesLundi; } /** * Définit la valeur de la propriété horairesLundi. * * @param value * allowed object is {@link ArrayOfString } * */ public void setHorairesLundi(ArrayOfString value) { this.horairesLundi = value; } /** * Obtient la valeur de la propriété horairesMardi. * * @return possible object is {@link ArrayOfString } * */ public ArrayOfString getHorairesMardi() { return horairesMardi; } /** * Définit la valeur de la propriété horairesMardi. * * @param value * allowed object is {@link ArrayOfString } * */ public void setHorairesMardi(ArrayOfString value) { this.horairesMardi = value; } /** * Obtient la valeur de la propriété horairesMercredi. * * @return possible object is {@link ArrayOfString } * */ public ArrayOfString getHorairesMercredi() { return horairesMercredi; } /** * Définit la valeur de la propriété horairesMercredi. * * @param value * allowed object is {@link ArrayOfString } * */ public void setHorairesMercredi(ArrayOfString value) { this.horairesMercredi = value; } /** * Obtient la valeur de la propriété horairesJeudi. * * @return possible object is {@link ArrayOfString } * */ public ArrayOfString getHorairesJeudi() { return horairesJeudi; } /** * Définit la valeur de la propriété horairesJeudi. * * @param value * allowed object is {@link ArrayOfString } * */ public void setHorairesJeudi(ArrayOfString value) { this.horairesJeudi = value; } /** * Obtient la valeur de la propriété horairesVendredi. * * @return possible object is {@link ArrayOfString } * */ public ArrayOfString getHorairesVendredi() { return horairesVendredi; } /** * Définit la valeur de la propriété horairesVendredi. * * @param value * allowed object is {@link ArrayOfString } * */ public void setHorairesVendredi(ArrayOfString value) { this.horairesVendredi = value; } /** * Obtient la valeur de la propriété horairesSamedi. * * @return possible object is {@link ArrayOfString } * */ public ArrayOfString getHorairesSamedi() { return horairesSamedi; } /** * Définit la valeur de la propriété horairesSamedi. * * @param value * allowed object is {@link ArrayOfString } * */ public void setHorairesSamedi(ArrayOfString value) { this.horairesSamedi = value; } /** * Obtient la valeur de la propriété horairesDimanche. * * @return possible object is {@link ArrayOfString } * */ public ArrayOfString getHorairesDimanche() { return horairesDimanche; } /** * Définit la valeur de la propriété horairesDimanche. * * @param value * allowed object is {@link ArrayOfString } * */ public void setHorairesDimanche(ArrayOfString value) { this.horairesDimanche = value; } /** * Obtient la valeur de la propriété information. * * @return possible object is {@link String } * */ public String getInformation() { return information; } /** * Définit la valeur de la propriété information. * * @param value * allowed object is {@link String } * */ public void setInformation(String value) { this.information = value; } /** * Obtient la valeur de la propriété urlPhoto. * * @return possible object is {@link String } * */ public String getURLPhoto() { return urlPhoto; } /** * Définit la valeur de la propriété urlPhoto. * * @param value * allowed object is {@link String } * */ public void setURLPhoto(String value) { this.urlPhoto = value; } /** * Obtient la valeur de la propriété urlPlan. * * @return possible object is {@link String } * */ public String getURLPlan() { return urlPlan; } /** * Définit la valeur de la propriété urlPlan. * * @param value * allowed object is {@link String } * */ public void setURLPlan(String value) { this.urlPlan = value; } }
/* * 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 agh.musicapplication.mappservices; import agh.musicapplication.mappservices.interfaces.GradeCoutingServiceInterface; import java.util.HashMap; import java.util.Map; import javax.transaction.Transactional; import org.springframework.stereotype.Service; /** * * @author Agatka */ @Service @Transactional public class GradeCountingService{ public GradeHolder countNewGrade(int oldCount, double oldGrade, int newGrade) { GradeHolder holder = null; int c; double g; if (oldCount == 0) { holder = new GradeHolder(1, (double) newGrade); } else { double newValue = (oldGrade * oldCount + 1.0 * newGrade) / (double) (oldCount + 1.0); holder = new GradeHolder(oldCount+1, newValue); } return holder; } public class GradeHolder{ private int count; private double grade; public GradeHolder(int count, double grade) { this.count = count; this.grade = grade; } public int getCount() { return count; } public double getGrade() { return grade; } } }
package com.mercadolibre.bootcampmelifrescos.model; import lombok.*; import javax.persistence.*; import java.util.HashSet; import java.util.Set; @Entity @Table(name="product") @Data @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode(exclude = {"seller", "purchaseOrderProducts"}) @ToString(exclude = {"purchaseOrderProducts", "seller"}) public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name="name") private String name; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "seller_id", referencedColumnName = "id") private Seller seller; @Column(name="amount") private Float amount; @ManyToOne @JoinColumn(name = "category_id", referencedColumnName = "id") private Category category; @OneToMany(mappedBy = "id") private Set<PurchaseOrderProducts> purchaseOrderProducts; public Product(long id, String name, Seller seller, Category category) { this.id = id; this.name =name; this.seller = seller; this.category = category; } }
package com.zantong.mobilecttx.chongzhi.dto; /** * 充值订单列表请求实体 * @author Sandy * create at 16/6/1 下午7:34 */ public class RechargeOrderDTO { private String userId; //用户ID private int currentIndex; //当前页 private int orderStatus; //订单状态 public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public int getCurrentIndex() { return currentIndex; } public void setCurrentIndex(int currentIndex) { this.currentIndex = currentIndex; } public int getOrderStatus() { return orderStatus; } public void setOrderStatus(int orderStatus) { this.orderStatus = orderStatus; } }
package com.wangcheng.base; /** * description: * * @author WangCheng * create in 2019/3/7 11:51 */ public class ShortTest { public static void main(StringTest[] args) { test01(); } private static void test01() { short num = 1; //num = num + 5;编译报错 num += 5; System.out.println(num); } }
package com.davivienda.sara.reintegros.general.helper; import com.davivienda.sara.constantes.CodigoError; import com.davivienda.sara.reintegros.general.ReintegrosHelperInterface; import com.davivienda.sara.reintegros.general.ReintegrosGeneralObjectContext; import com.davivienda.sara.tablas.reintegros.session.ReintegrosSessionLocal; import com.davivienda.sara.entitys.Reintegros; import com.davivienda.sara.procesos.reintegros.session.ProcesoReintegrosSessionLocal; import com.davivienda.sara.procesos.reintegros.notas.session.ReintegrosNotasProcesosSessionLocal; import com.davivienda.sara.constantes.TipoCuenta; import com.davivienda.sara.procesos.autenticacion.webservice.session.AutenticacionLdapWSProcesosSessionLocal; import com.davivienda.sara.tablas.confmodulosaplicacion.session.ConfModulosAplicacionLocal; import com.davivienda.sara.entitys.config.ConfModulosAplicacion; import com.davivienda.utilidades.conversion.FormatoFecha; import com.davivienda.sara.constantes.RedCajero; import com.davivienda.sara.constantes.EstadoReintegro; import com.davivienda.utilidades.Constantes; import com.davivienda.utilidades.conversion.Cadena; import com.davivienda.utilidades.conversion.JSon; import java.math.BigDecimal; import java.util.Collection; import java.util.Date; import java.util.logging.Level; import javax.ejb.EJBException; import org.json.JSONArray; import org.json.JSONObject; /** * ReintegrosRevisarServletHelper - 27/08/2008 Descripción : Helper para el * manejo de los requerimientos de Reintegros Versión : 1.0 * * @author jjvargas Davivienda 2008 */ public class ReintegrosGuardarAutorizacionServletHelper implements ReintegrosHelperInterface { private ReintegrosSessionLocal session = null; private ReintegrosGeneralObjectContext objectContext = null; private ReintegrosNotasProcesosSessionLocal reintegrosNotasProcesosSessionLocal; private ProcesoReintegrosSessionLocal procesoReintegrosSession; private String respuestaJSon; private AutenticacionLdapWSProcesosSessionLocal autenticacionLdapWSProcesosSessionLocal; private ConfModulosAplicacionLocal confModulosAplicacionSession; public ReintegrosGuardarAutorizacionServletHelper(ReintegrosSessionLocal session, ProcesoReintegrosSessionLocal procesoReintegrosSession, ReintegrosNotasProcesosSessionLocal reintegrosNotasProcesosSessionLocal, AutenticacionLdapWSProcesosSessionLocal autenticacionLdapWSProcesosSessionLocal, ConfModulosAplicacionLocal confModulosAplicacionSession, ReintegrosGeneralObjectContext objectContext) { this.session = session; this.procesoReintegrosSession = procesoReintegrosSession; this.reintegrosNotasProcesosSessionLocal = reintegrosNotasProcesosSessionLocal; this.autenticacionLdapWSProcesosSessionLocal = autenticacionLdapWSProcesosSessionLocal; this.confModulosAplicacionSession = confModulosAplicacionSession; this.objectContext = objectContext; } public String obtenerDatos() { respuestaJSon = ""; String respuesta = ""; Collection<Reintegros> items = null; try { try { //DESCOMENTAREAR SOLO PARA PRUEBAS if (getAutenticacion()) { actualizarJsonSelecionados(objectContext.getAtributoJsonArray("events")); } //actualizarJsonSelecionados(objectContext.getAtributoJsonArray("events")); else { respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_EN_AUTENTICACION.getCodigo(), "Datos de Autenticacion Errados"); } } catch (EJBException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); if (ex.getLocalizedMessage().contains("EntityServicioExcepcion")) { //respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), ex.getMessage()); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), Constantes.MSJ_QUERY_ERROR); } if (ex.getLocalizedMessage().contains("IllegalArgumentException")) { //respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), ex.getMessage()); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), Constantes.MSJ_QUERY_ERROR); } if (ex.getLocalizedMessage().contains("NoResultException")) { //respuestaJSon = JSon.getJSonRespuesta(CodigoError.REGISTRO_NO_EXISTE.getCodigo(), "No hay registros que cumplan los criterios de la consulta"); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), Constantes.MSJ_QUERY_SIN_DATA); } } catch (Exception ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); //respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), "Error interno en la consulta"); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), Constantes.MSJ_QUERY_ERROR); } } catch (IllegalArgumentException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); //respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), ex.getMessage()); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), Constantes.MSJ_QUERY_ERROR); } if (items != null && this.respuestaJSon.length() <= 1) { respuesta = aJSon(items); // paso los items a JSON } else { respuesta = this.respuestaJSon; } return respuesta; } //obtengo el reintegro pro la llave formada por codigoCajero , fechaProceso , fechaProceso private Reintegros getReintegroXLlave(Integer codigoCajero, Date fechaProceso, Integer numeroTransaccion) throws Exception { Reintegros regReintegros = null; try { Date fechaHisto = objectContext.getConfigApp().FECHA_HISTORICAS_CONSULTA; regReintegros = session.getReintegroXLlave(codigoCajero, fechaProceso, numeroTransaccion, fechaHisto); } catch (EJBException ex) { if (ex.getLocalizedMessage().contains("EntityServicioExcepcion")) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), ex.getMessage()); } if (ex.getLocalizedMessage().contains("IllegalArgumentException")) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), ex.getMessage()); } if (ex.getLocalizedMessage().contains("NoResultException")) { respuestaJSon = JSon.getJSonRespuesta(CodigoError.REGISTRO_NO_EXISTE.getCodigo(), "No hay registros que cumplan los criterios de la consulta"); } } return regReintegros; } private String aJSon(Collection<Reintegros> items) { String cadenaJSon = ""; try { Integer idRegistro = 0; JSONObject resp = new JSONObject(); JSONArray respItems = new JSONArray(); for (Reintegros item : items) { JSONObject itemJSon = new JSONObject(); itemJSon.put("idRegistro", ++idRegistro); itemJSon.put("codigoCajero", item.getReintegrosPK().getHCodigocajero().toString()); itemJSon.put("codigoOcca", item.getHCodigoocca().toString()); itemJSon.put("numeroTransaccion", item.getReintegrosPK().getHTalon().toString()); itemJSon.put("numeroCuenta", item.getHNumerocuenta()); itemJSon.put("numeroTarjeta", item.getTTarjeta()); itemJSon.put("fecha", com.davivienda.utilidades.conversion.Fecha.aCadena(item.getReintegrosPK().getHFechasistema(), FormatoFecha.FECHA_HORA)); itemJSon.put("valor", com.davivienda.utilidades.conversion.Numero.aFormatoDecimal(item.getHValor())); itemJSon.put("valorAjustar", com.davivienda.utilidades.conversion.Numero.aFormatoDecimal(item.getValorajustado())); itemJSon.put("statusTransaccion", item.getTCodigoterminaciontransaccion()); itemJSon.put("valorAjustado", com.davivienda.utilidades.conversion.Numero.aFormatoDecimal(item.getTValorentregado())); itemJSon.put("redEnruta", RedCajero.getRedCajero(Cadena.aInteger(item.getHNumerocuenta().substring(0, 4))).toString()); itemJSon.put("usuarioRevisa", item.getUsuariorevisa()); itemJSon.put("checkSeleccion", true); } resp.put("identifier", "idRegistro"); resp.put("label", "codigoCajero"); resp.put("items", respItems); cadenaJSon = resp.toString(); } catch (Exception ex) { objectContext.getConfigApp().loggerApp.severe("No se puede pasar a JSON \n " + ex.getMessage()); cadenaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_PARSEAR_REGISTRO.getCodigo(), ex.getMessage()); } return cadenaJSon; } private boolean actualizarReintegro(Integer codigoCajero, Date fechaProceso, Integer numeroTransaccion, Long valorajustado, String numeroCuenta, Long valor, int estadoReintegro, String concepto) { String usuario = ""; String mensajeError = ""; usuario = objectContext.getIdUsuarioEnSesion(); Reintegros regReintegros = null; boolean estadoTransaccion = false; try { regReintegros = findByPrimayKey(codigoCajero, fechaProceso, numeroTransaccion); if (regReintegros != null) { if (estadoReintegro == EstadoReintegro.REINTEGROCANCELADO.codigo) { regReintegros.setEstadoreintegro(estadoReintegro); procesoReintegrosSession.actualizar(regReintegros); estadoTransaccion = true; } else { mensajeError = GuardarStratusNotaCredito(codigoCajero, new BigDecimal(valorajustado), regReintegros.getHNumerocuenta(), regReintegros.getTipoCuentaReintegro(), numeroTransaccion.toString(), concepto); if (mensajeError.substring(0, 1).equals("B")) { regReintegros.setEstadoreintegro(EstadoReintegro.FINALIZADOEXITOSO.codigo); regReintegros.setFechareintegro(com.davivienda.utilidades.conversion.Fecha.getDateHoy()); estadoTransaccion = true; } else { regReintegros.setEstadoreintegro(EstadoReintegro.ERRORSTRATUS.codigo); } regReintegros.setErrorreintegro(mensajeError); regReintegros.setUsuarioautoriza(usuario); procesoReintegrosSession.actualizar(regReintegros); } } } catch (Exception ex) { respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), "Error interno en la consulta"); } return estadoTransaccion; } //obtengo el reintegro pro la llave formada por codigoCajero , fechaProceso , fechaProceso private Reintegros findByPrimayKey(Integer codigoCajero, Date fechaProceso, Integer numeroTransaccion) throws Exception { Reintegros regReintegros = null; try { Date fechaHisto = objectContext.getConfigApp().FECHA_HISTORICAS_CONSULTA; regReintegros = session.findByPrimayKey(codigoCajero, fechaProceso, numeroTransaccion, fechaHisto); } catch (EJBException ex) { if (ex.getLocalizedMessage().contains("EntityServicioExcepcion")) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), ex.getMessage()); } if (ex.getLocalizedMessage().contains("IllegalArgumentException")) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), ex.getMessage()); } if (ex.getLocalizedMessage().contains("NoResultException")) { respuestaJSon = JSon.getJSonRespuesta(CodigoError.REGISTRO_NO_EXISTE.getCodigo(), "No hay registros que cumplan los criterios de la consulta"); } } return regReintegros; } public String GuardarStratusNotaCredito(Integer codigoCajero, BigDecimal valor, String cuenta, Integer tipoCuenta, String talon, String concepto) { String respuesta = ""; String tipoNota = "Nota Credito "; String strExepcion = ""; try { String usuario = objectContext.getUsuarioEnSesion().getUsuario(); respuesta = reintegrosNotasProcesosSessionLocal.realizarNotaCredito(codigoCajero, valor, cuenta, tipoCuenta, usuario, talon, concepto); tipoNota = tipoNota + TipoCuenta.getTipoCuenta(tipoCuenta).nombre; objectContext.getConfigApp().loggerApp.info("El usuario : " + usuario + " realizo una " + tipoNota + " al cajero " + codigoCajero.toString() + " por valor : " + valor.toString() + " a la cuenta : " + cuenta + " con respuesta:" + respuesta); if (respuesta != null) { if (respuesta.length() > 0) { if (respuesta.substring(0, 1).equals("B")) { respuesta = respuesta + " " + tipoNota + " Realizada con Exito"; } else if (respuesta.substring(0, 1).equals("M")) { respuesta = respuesta + " NO se pudo Realizar la " + tipoNota; } else { if (respuesta.substring(0, 1).equals("F")) { respuesta = respuesta + " Por favor verificar el Estado de la " + tipoNota; } } } else { respuesta = respuesta + " Por favor verificar el Estado de la " + tipoNota; } } else { respuesta = respuesta + " Por favor verificar el Estado de la " + tipoNota; } } catch (EJBException ex) { if (ex.getMessage() == null) { strExepcion = ex.getCause().getMessage(); } else { strExepcion = ex.getMessage(); } objectContext.getConfigApp().loggerApp.log(Level.SEVERE, strExepcion); objectContext.setError(strExepcion, CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo()); respuesta = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), strExepcion); } catch (Exception ex) { objectContext.setError(ex.getMessage(), CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo()); respuesta = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), ex.getMessage()); } return respuesta; } private boolean getAutenticacion() { boolean blnAutorizado = false; String respuesta = ""; String grupoSaraNotaCredito = ""; String[] gruposUsuario; try { grupoSaraNotaCredito = getParametro("SARA.GRUPO_NOTA_CREDITO", ""); respuesta = autenticacionLdapWSProcesosSessionLocal.autenticarLdap(objectContext.getUsuarioLdap(), objectContext.getClaveLdap()); if (respuesta != null) { if (respuesta.length() > 0) { if (respuesta.substring(0, 1).equals("B")) { gruposUsuario = respuesta.split(";"); for (int i = 0; i < gruposUsuario.length; i++) { if (grupoSaraNotaCredito.equals(gruposUsuario[i])) { blnAutorizado = true; } } } else { respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_NO_DEFINIDO.codigo, respuesta); } } } } catch (Exception ex) { objectContext.setError(ex.getMessage(), CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo()); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), ex.getMessage()); } return blnAutorizado; } private String getParametro(String strParametro, String strValorDefault) { String strValParametro = ""; try { ConfModulosAplicacion registroEntityConsulta = new ConfModulosAplicacion("SARA", strParametro); registroEntityConsulta = confModulosAplicacionSession.buscar(registroEntityConsulta.getConfModulosAplicacionPK()); strValParametro = registroEntityConsulta.getValor(); } catch (Exception ex) { java.util.logging.Logger.getLogger("globalApp").info("Error obteniendo el valor del parametro: " + strParametro + " " + ex.getMessage()); strValParametro = strValorDefault; } return strValParametro; } //obtengo el reintegro pro la llave formada por codigoCajero , fechaProceso , fechaProceso private Reintegros getReintegroXCuentaValor(Integer codigoCajero, Date fechaProceso, Integer numeroTransaccion, String numeroCuenta, Long valor) throws Exception { Reintegros regReintegros = null; try { Date fechaHisto = objectContext.getConfigApp().FECHA_HISTORICAS_CONSULTA; regReintegros = session.getReintegroXCuentaValor(codigoCajero, fechaProceso, numeroTransaccion, numeroCuenta, valor, fechaHisto); } catch (EJBException ex) { if (ex.getLocalizedMessage().contains("EntityServicioExcepcion")) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), ex.getMessage()); } if (ex.getLocalizedMessage().contains("IllegalArgumentException")) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), ex.getMessage()); } if (ex.getLocalizedMessage().contains("NoResultException")) { respuestaJSon = JSon.getJSonRespuesta(CodigoError.REGISTRO_NO_EXISTE.getCodigo(), "No hay registros que cumplan los criterios de la consulta"); } } return regReintegros; } private void actualizarJsonSelecionados(JSONArray myArrayList) { JSONObject itemJSon = null; Date fecha = null; Long valorajustado = null; Long valor = null; String strValor = ""; String strValorAjustado = ""; respuestaJSon = "el estado de las Notas Credito es:"; boolean estadoTransaccion = false; try { if (myArrayList != null) { for (int i = 0; i < myArrayList.length(); i++) { itemJSon = new JSONObject(myArrayList.getString(i)); String concepto, comision = ""; if (itemJSon.get("checkSeleccion").toString().equals("true")) { strValorAjustado = itemJSon.get("valorAjustar").toString().replace(".", "").replace(",", ""); valorajustado = Cadena.aLong(strValorAjustado); strValor = itemJSon.get("valor").toString().replace(".", "").replace(",", ""); int estadoReintegro = (int) itemJSon.get("estadoReintegro"); concepto = itemJSon.getString("concepto"); if (concepto.equals("479") || concepto.equals("104")) {//Reintegro por valor de comision comision = itemJSon.getString("comision").toString().replace(".", "").replace(",", ""); strValor = comision; valorajustado = Cadena.aLong(comision); } valor = Cadena.aLong(strValor); fecha = com.davivienda.utilidades.conversion.Cadena.aDate(itemJSon.get("fecha").toString(), FormatoFecha.FECHA_HORA); estadoTransaccion = actualizarReintegro(Cadena.aInteger(itemJSon.get("codigoCajero").toString()), fecha, Cadena.aInteger(itemJSon.get("numeroTransaccion").toString()), valorajustado, itemJSon.get("numeroCuenta").toString(), valor, estadoReintegro, concepto); if (estadoReintegro == EstadoReintegro.REINTEGROCANCELADO.codigo) { respuestaJSon = respuestaJSon + " para codigo cajero: " + itemJSon.get("codigoCajero").toString() + " ,Talon: " + itemJSon.get("numeroTransaccion").toString() + " ,Valor: " + strValorAjustado + " la solicitud de rechazo del registro fué "; } else { respuestaJSon = respuestaJSon + " para codigo cajero: " + itemJSon.get("codigoCajero").toString() + " ,Talon: " + itemJSon.get("numeroTransaccion").toString() + " ,Valor: " + strValorAjustado + " la Transacion fué "; } if (estadoTransaccion) { respuestaJSon = respuestaJSon + " Exitosa; "; } else { respuestaJSon = respuestaJSon + " Errada; "; } } } } respuestaJSon = JSon.getJSonRespuesta(0, respuestaJSon); } catch (org.json.JSONException ex) { respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_PARSEAR_REGISTRO.getCodigo(), "Error leyendo arrayJson Grid", ex); } } }
package dz.Hanimall.Lar; import dz.Hanimall.Lar.inputs.KeyManager; import dz.Hanimall.Lar.worlds.World; public class Master { private Game game; private World world; public Master(Game game){ this.game = game; } public KeyManager getKeyManager(){ return game.getKeyManager(); } public int getWidth(){ return game.getWidth(); } public int getHeight(){ return game.getHeight(); } public Game getGame() { return game; } public void setGame(Game game) { this.game = game; } public World getWorld() { return world; } public void setWorld(World world) { this.world = world; } }
package com.example.sborick.raintoday.Alerts; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * Created by sborick on 1/24/2017. */ public class WeatherDataGetter { final String KEY = "807b43d6ad36e9be1387424334babb16"; public String getWeatherData(String location) { HttpURLConnection connection = null; BufferedReader reader = null; String output = ""; try { String resource = "https://api.darksky.net/forecast/"+ KEY +"/"+ location +"?exclude=currently,minutely,hourly,alerts,flags"; Log.d("service", resource); URL url = new URL(resource); connection = (HttpURLConnection) url.openConnection(); connection.connect(); InputStream stream = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder buffer = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { buffer.append(line).append("\n"); } output = buffer.toString(); } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } return output; } }
import java.io.File; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Veuillez saisir le chemin du répertoire que vous souhaitez lister :"); String chemin = sc.nextLine(); File fichier = new File(chemin); if (fichier.exists() && fichier.isDirectory() == true ){ System.out.println("Ce chemein est correct, il mène à un dossier."); }else if ( fichier.exists() && fichier.isFile() == true){ System.out.println("Ce chemein est correct, il mène à un fichier."); }else System.out.println("Ce chemin est incorrect."); } }
/* * The MIT License * * Copyright 2017, Juliano Macedo. * See LICENSE file for details. * */ package haversine; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; /** * <p> * JUnit test for the class {@link HaversineAlgorithm}.</p> * <i>Coordinates source: https://www.distancecalculator.net</i> * * @author Juliano Macedo < /macedoj at GitHub > * @version 0.2 */ public class HaversineAlgorithmTest { private double startLati; private double startLong; private double endLati; private double endLong; public HaversineAlgorithmTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * <code>assertNotEquals</code> test using empty variables to verify the * result returned by the distanceInKm method. */ @Test public void testDistanceInKmEmptyVars() { double expResult = 12.34; double result = HaversineAlgorithm.distanceInKm(startLati, startLong, endLati, endLong); assertNotEquals(expResult, result, 0.0); } /** * <code>assertNotEquals</code> test using empty variables to verify the * result returned by the distanceInMi method. */ @Test public void testDistanceInMiEmptyVars() { double expResult = -56.78; double result = HaversineAlgorithm.distanceInMi(startLati, startLong, endLati, endLong); assertNotEquals(expResult, result, 0.0); } /** * Test of distanceInKm method, with Porto Alegre to São Paulo example. */ @Test public void testDistancePoaSampaInKm() { startLati = -30.0331; startLong = -51.23; endLati = -23.5475; endLong = -46.6361; double expResult = 852.989246230814; double result = HaversineAlgorithm.distanceInKm(startLati, startLong, endLati, endLong); assertEquals(expResult, result, 0.0); } /** * Test of distanceInKm method, with Goiânia to São Paulo example. */ @Test public void testDistanceGynSampaInKm() { startLati = -16.6786; startLong = -49.2539; endLati = -23.5475; endLong = -46.6361; double expResult = 811.1442335297786; double result = HaversineAlgorithm.distanceInKm(startLati, startLong, endLati, endLong); assertEquals(expResult, result, 0.0); } /** * Test of distanceInKm method, with Brasília to Manaus example. */ @Test public void testDistanceBsbMaoInKm() { startLati = -15.7797; startLong = -47.9297; endLati = -3.1019; endLong = -60.025; double expResult = 1933.7761523338133; double result = HaversineAlgorithm.distanceInKm(startLati, startLong, endLati, endLong); assertEquals(expResult, result, 0.0); } /** * Test of distanceInKm method, with Brasília to Fortaleza example. */ @Test public void testDistanceBsbForInKm() { startLati = -15.7797; startLong = -47.9297; endLati = -3.7172; endLong = -38.5431; double expResult = 1689.0504616271794; double result = HaversineAlgorithm.distanceInKm(startLati, startLong, endLati, endLong); assertEquals(expResult, result, 0.0); } /** * Test of distanceInKm method, with Madrid to Barcelona example. */ @Test public void testDistanceMadBarInKm() { startLati = 40.4165; startLong = -3.7026; endLati = 41.3888; endLong = 2.159; double expResult = 504.24594512972055; double result = HaversineAlgorithm.distanceInKm(startLati, startLong, endLati, endLong); assertEquals(expResult, result, 0.0); } /** * Test of distanceInKm method, with Moscow to Saint Petersburg example. */ @Test public void testDistanceMosStpInKm() { startLati = 55.7522; startLong = 37.6156; endLati = 59.9386; endLong = 30.3141; double expResult = 634.4331164612092; double result = HaversineAlgorithm.distanceInKm(startLati, startLong, endLati, endLong); assertEquals(expResult, result, 0.0); } /** * Test of distanceInMi method, with Porto Alegre to São Paulo example. */ @Test public void testDistancePoaSampaInMi() { startLati = -30.0331; startLong = -51.23; endLati = -23.5475; endLong = -46.6361; double expResult = 530.0227809196872; double result = HaversineAlgorithm.distanceInMi(startLati, startLong, endLati, endLong); assertEquals(expResult, result, 0.0); } /** * Test of distanceInMi method, with Goiânia to São Paulo example. */ @Test public void testDistanceGynSampaInMi() { startLati = -16.6786; startLong = -49.2539; endLati = -23.5475; endLong = -46.6361; double expResult = 504.02150353263204; double result = HaversineAlgorithm.distanceInMi(startLati, startLong, endLati, endLong); assertEquals(expResult, result, 0.0); } /** * Test of distanceInMi method, with Brasília to Manaus example. */ @Test public void testDistanceBsbMaoInMi() { startLati = -15.7797; startLong = -47.9297; endLati = -3.1019; endLong = -60.025; double expResult = 1201.592421551814; double result = HaversineAlgorithm.distanceInMi(startLati, startLong, endLati, endLong); assertEquals(expResult, result, 0.0); } /** * Test of distanceInMi method, with Brasília to Fortaleza example. */ @Test public void testDistanceBsbForInMi() { startLati = -15.7797; startLong = -47.9297; endLati = -3.7172; endLong = -38.5431; double expResult = 1049.5269743917422; double result = HaversineAlgorithm.distanceInMi(startLati, startLong, endLati, endLong); assertEquals(expResult, result, 0.0); } /** * Test of distanceInMi method, with Madrid to Barcelona example. */ @Test public void testDistanceMadBarInMi() { startLati = 40.4165; startLong = -3.7026; endLati = 41.3888; endLong = 2.159; double expResult = 313.3238071711996; double result = HaversineAlgorithm.distanceInMi(startLati, startLong, endLati, endLong); assertEquals(expResult, result, 0.0); } /** * Test of distanceInMi method, with Moscow to Saint Petersburg example. */ @Test public void testDistanceMosStpInMi() { startLati = 55.7522; startLong = 37.6156; endLati = 59.9386; endLong = 30.3141; double expResult = 394.21834000861804; double result = HaversineAlgorithm.distanceInMi(startLati, startLong, endLati, endLong); assertEquals(expResult, result, 0.0); } }
package randomNameGenerator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; /** * Generates random names. * @author Patrick Murphy * */ public class NameGenerator { private Random rand = new Random(); private int maxLength; private List<Character> allVowels = new ArrayList<Character>(); private List<Character> vowelsNoY = new ArrayList<Character>(); private List<Character> noRepeats = new ArrayList<Character>(); private List<Character> noRepeatsUnlessVowelFirst = new ArrayList<Character>(); private List<Character> mustFollowVowel = new ArrayList<Character>(); private List<Character> higherH = new ArrayList<Character>(); private char[] lowerVowels = {'a','e','i','o'}; private char[] upperVowels = {'A','E','I','O'}; private char[] lowerNV1 = {'n','r','s','t'}; private char[] upperNV1 = {'N','R','S','T'}; private char[] lowerNV2 = {'c','d','f','g','h','l','m','p'}; private char[] upperNV2 = {'C','D','F','G','H','L','M','P'}; private char[] lowerNV3 = {'b','j','k','q','w','x','z','y'}; private char[] upperNV3 = {'B','J','K','Q','W','X','Z','Y'}; private char[] trailingSpec1 = {'l','r'}; private char[] trailingSpec2 = {'b','d','k','l','m','n','t','v'}; public NameGenerator() { Collections.addAll(allVowels,'a','A','e','E','i','I','o','O','u','U','y','Y'); Collections.addAll(vowelsNoY,'a','A','e','E','i','I','o','O','u','U'); Collections.addAll(noRepeats, 'x','X','u','U','b','B','i','I','y','Y'); Collections.addAll(noRepeatsUnlessVowelFirst, 's','S','f','F','t','T','r','R'); Collections.addAll(higherH, 's','S','t','T','c','C','p','P'); } /** * Generates a random name and returns it. * Could be as short as 3 letter, and as long as maxLength. * @param maxLength * @return random name */ public String generate(int maxLength) { int nameLength; if(maxLength<4) { nameLength = 3; } else { nameLength = rand.nextInt(maxLength-3)+3; } this.maxLength = maxLength; StringBuilder name = new StringBuilder(1); name.append(randomLetter(true)); for(int i = 1;i<nameLength;i++) { name.append(nextLetter(name.toString())); } return name.toString(); } /* * Returns an appropriate next letter based on the previous two letter. */ private char nextLetter(String name) { char nextChar; boolean validChar; do { if(name.length()>=2) { char oneAway = name.charAt(name.length()-1); char twoAway = name.charAt(name.length()-2); boolean oneAwayVowel = isVowel(name.charAt(name.length()-1)); boolean twoAwayVowel = isVowel(name.charAt(name.length()-2)); if(maxLength==3) { { if(allVowels.contains(name.charAt(name.length()-1))) { nextChar = anotherVowel(); } else { nextChar = anotherNonVowel(); } } } else if(higherH.contains(oneAway) && boolChance(5,10)) { nextChar = 'h'; } else if(name.length()==maxLength-1) { if(allVowels.contains(name.charAt(0))) { nextChar = anotherVowel(); } else { nextChar = anotherNonVowel(); } } //if last 2 are vowels 999 out of 1000 chance of non vowel else if(oneAwayVowel && twoAwayVowel) { nextChar = anotherVowel(); } //if last 2 are non vowels 999 out of 1000 chance of vowel else if(!oneAwayVowel && !twoAwayVowel) { nextChar = anotherNonVowel(); } else { nextChar = randomLetter(boolChance(1,1000)); } validChar = validateChar(nextChar,name); } else { if(name.charAt(0) == 'Y') { nextChar = anotherNonVowel(); } if(vowelsNoY.contains(name.charAt(0))) { nextChar = anotherVowel(); } else { nextChar = anotherNonVowel(); } validChar = validateChar(nextChar,name); } }while(!validChar); return nextChar; } private char anotherVowel() { char nextChar; boolean anotherVowel =boolChance(1,7000); if(anotherVowel) { nextChar = randomVowel(boolChance(1,500)); } else { nextChar = randomNonVowel(boolChance(1,500)); } return nextChar; } private char anotherNonVowel() { char nextChar; boolean anotherNonVowel = boolChance(1,7000); if(anotherNonVowel) { nextChar = randomNonVowel(boolChance(1,500)); } else { nextChar = randomVowel(boolChance(1,500)); } return nextChar; } /* * checks the random letter and validates it based on a set of criteria */ private boolean validateChar(char c, String str) { boolean validChar = true; char oneAway = str.charAt(str.length()-1); if(str.length()>1) { char twoAway = str.charAt(str.length()-2); if(noRepeatsUnlessVowelFirst.contains(c) && oneAway == c && !isVowel(twoAway)) { validChar = boolChance(5,100); } } if(noRepeats.contains(c) && oneAway == c) { validChar = boolChance(2,100); } if(str.length()==1 && noRepeatsUnlessVowelFirst.contains(c) && oneAway == c) { validChar = boolChance(5,100); } if(mustFollowVowel.contains(c) && !isVowel(oneAway)) { validChar = boolChance(2,100); } validChar = appropriateNext(c); if(c=='y') { validChar = boolChance(4,10); } return validChar; } private boolean appropriateNext(char c) { boolean valid = false; switch(c) { case 'b': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,100,trailingSpec1); if(valid == false) valid = letterPercent(c,15,'h'); if(valid == false) valid = boolChance(3,100); return valid; case 'B': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,100,trailingSpec1); if(valid == false) valid = letterPercent(c,15,'h'); if(valid == false) valid = boolChance(3,100); return valid; case 'c': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,100,'r'); if(valid == false) valid = letterPercent(c,100,'h'); if(valid == false) valid = letterPercent(c,100,'k'); if(valid == false) valid = boolChance(3,100); return valid; case 'C': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,100,'r'); if(valid == false) valid = letterPercent(c,100,'h'); if(valid == false) valid = letterPercent(c,100,'k'); if(valid == false) valid = boolChance(3,100); return valid; case 'd': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,100,'r'); if(valid == false) valid = letterPercent(c,15,'h'); if(valid == false) valid = boolChance(3,100); return valid; case 'D': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,100,'r'); if(valid == false) valid = letterPercent(c,15,'h'); if(valid == false) valid = boolChance(3,100); return valid; case 'f': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,100,trailingSpec1); if(valid == false) valid = boolChance(3,100); return valid; case 'F': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,100,trailingSpec1); if(valid == false) valid = boolChance(3,100); return valid; case 'g': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,100,trailingSpec1); if(valid == false) valid = letterPercent(c,15,'h'); if(valid == false) valid = boolChance(3,100); return valid; case 'G': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,100,trailingSpec1); if(valid == false) valid = letterPercent(c,15,'h'); if(valid == false) valid = boolChance(3,100); return valid; case 'h': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,40,trailingSpec2); if(valid == false) valid = boolChance(3,100); return valid; case 'H': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,40,trailingSpec2); if(valid == false) valid = boolChance(3,100); return valid; case 'j': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,20,'h'); if(valid == false) valid = boolChance(3,100); return valid; case 'J': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,20,'h'); if(valid == false) valid = boolChance(3,100); return valid; case 'k': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,100,trailingSpec1); if(valid == false) valid = boolChance(3,100); return valid; case 'K': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,100,trailingSpec1); if(valid == false) valid = boolChance(3,100); return valid; case 'l': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,50,'l'); if(valid == false) valid = boolChance(3,100); return valid; case 'L': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = boolChance(3,100); return valid; case 'm': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,30,'b'); if(valid == false) valid = letterPercent(c,40,'c'); if(valid == false) valid = boolChance(3,100); return valid; case 'M': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,30,'b'); if(valid == false) valid = letterPercent(c,60,'c'); if(valid == false) valid = boolChance(3,100); return valid; case 'n': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,30,'p'); if(valid == false) valid = boolChance(5,100); return valid; case 'N': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,30,'p'); if(valid == false) valid = boolChance(3,100); return valid; case 'p': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,40,'h'); if(valid == false) valid = boolChance(3,100); return valid; case 'P': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,40,'h'); if(valid == false) valid = boolChance(3,100); return valid; case 'q': valid = letterPercent(c,50,lowerVowels); if(valid == false) valid = letterPercent(c,50,upperVowels); if(valid == false) valid = letterPercent(c,100,'u'); if(valid == false) valid = boolChance(3,100); return valid; case 'Q': valid = letterPercent(c,50,lowerVowels); if(valid == false) valid = letterPercent(c,50,upperVowels); if(valid == false) valid = letterPercent(c,100,'u'); if(valid == false) valid = boolChance(3,100); return valid; case 'r': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,100,trailingSpec2); if(valid == false) valid = boolChance(3,100); return valid; case 'R': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,100,trailingSpec2); if(valid == false) valid = boolChance(3,100); return valid; case 's': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,70,'t'); if(valid == false) valid = letterPercent(c,100,'h'); if(valid == false) valid = boolChance(3,100); return valid; case 'S': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,70,'t'); if(valid == false) valid = letterPercent(c,100,'h'); if(valid == false) valid = boolChance(3,100); return valid; case 't': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,70,'t'); if(valid == false) valid = letterPercent(c,100,'h'); if(valid == false) valid = boolChance(3,100); return valid; case 'T': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,70,'t'); if(valid == false) valid = letterPercent(c,100,'h'); if(valid == false) valid = boolChance(3,100); return valid; case 'v': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,30,trailingSpec1); if(valid == false) valid = boolChance(3,100); return valid; case 'V': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,30,trailingSpec1); if(valid == false) valid = boolChance(3,100); return valid; case 'w': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,50,trailingSpec2); if(valid == false) valid = boolChance(3,100); return valid; case 'W': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,50,trailingSpec2); if(valid == false) valid = boolChance(3,100); return valid; case 'x': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = boolChance(3,100); return valid; case 'X': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = boolChance(3,100); return valid; case 'z': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,30,trailingSpec1); if(valid == false) valid = boolChance(3,100); return valid; case 'Z': valid = letterPercent(c,100,lowerVowels); if(valid == false) valid = letterPercent(c,100,upperVowels); if(valid == false) valid = letterPercent(c,30,trailingSpec1); if(valid == false) valid = boolChance(3,100); return valid; default: return true; } } /* * Returns a random vowel character. * Requires a boolean, to tell if it is upper or lower case. */ private char randomVowel(boolean isUpper) { char[] vowels; if(isUpper) { vowels = upperVowels; } else { vowels = lowerVowels; } int i = rand.nextInt(10); if(i<7) { int j = rand.nextInt(vowels.length); return vowels[j]; } else if(i<9) { if(isUpper) { return 'U'; } else { return 'u'; } } else { if(isUpper) { return 'Y'; } else { return 'y'; } } } /* * Returns a boolean based on percent chance if the letter is specified in tests. * Otherwise it returns true if the letter is not in tests. */ private boolean letterPercent(char c,int percent,char ... tests) { boolean testsContains = false; for(char el: tests) { if(el==c) { testsContains = true; } } if(testsContains) { if(boolChance(percent,100)) { return true; } else { return false; } } else { return true; } } /* * Returns a random non vowel character. * Requires a boolean, to tell if it is upper or lower case. * It is most likely to return characters in the top which are the most common non vowels in the English language. * It is less likely to return characters in the mid, and it is least likely in bot. */ private char randomNonVowel(boolean isUpper) { char[] top; char[] mid; char[] bot; if(isUpper) { top = upperNV1; mid = upperNV2; bot = upperNV3; } else { top = lowerNV1; mid = lowerNV2; bot = lowerNV3; } int i = rand.nextInt(10); if(i<7) { int j = rand.nextInt(top.length); return top[j]; } else if(i<9) { int j = rand.nextInt(mid.length); return mid[j]; } else; { int j = rand.nextInt(bot.length); return bot[j]; } } /* * Returns a random letter. * Higher chance of returning a lower case letter. */ private char randomLetter(boolean cap) { boolean capital = cap; boolean vowel = rand.nextBoolean(); if(vowel) { return randomVowel(capital); } else { return randomNonVowel(capital); } } /* * returns a boolean based on chance defined by the parameters. * chance is the likelihood of rolling true out of outOf. */ private boolean boolChance(int chance, int outOf) { int roll = rand.nextInt(outOf); boolean result; if(roll<chance) { result = true; } else { result = false; } return result; } /* * Returns true if c is a vowel. * Otherwise it returns false. */ private boolean isVowel(char c) { if(allVowels.contains(c)) { return true; } else return false; } }
package com.beike.wap.service.impl; import java.util.Date; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.beike.wap.dao.MWapTypeDao; import com.beike.wap.entity.MWapType; import com.beike.wap.service.MWapTypeService; /** * Title : GoodsServiceImpl * <p/> * Description :商品服务实现类 * <p/> * CopyRight : CopyRight (c) 2011 * </P> * Company : qianpin.com </P> JDK Version Used : JDK 5.0 + * <p/> * Modification History : * <p/> * * <pre> * NO. Date Modified By Why & What is modified * </pre> * * <pre>1 2011-09-20 lvjx Created * * <pre> * <p/> * * @author lvjx * @version 1.0.0.2011-09-20 */ @Service("wapTypeService") public class MWapTypeServiceImpl implements MWapTypeService { /* * @see com.beike.wap.service.WapTypeService#addWapType(java.util.List) */ @Override public int addWapType(final List<MWapType> wapTypeList) throws Exception { int flag = 0; flag = wapTypeDao.addWapType(wapTypeList); return flag; } /* * @see com.beike.wap.service.WapTypeService#queryWapType(int, int, * java.util.Date) */ @Override public int queryWapType(int typeType, int typePage, Date currentDate, String typeArea) throws Exception { int sum = 0; sum = wapTypeDao .queryWapType(typeType, typePage, currentDate, typeArea); return sum; } @Override public MWapType findById(Long id) { // TODO Auto-generated method stub return null; } @Resource(name = "wapTypeDao") public MWapTypeDao wapTypeDao; }
package pl.edu.agh.to2.controllers; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCombination; import javafx.scene.input.KeyEvent; import javafx.scene.layout.AnchorPane; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import pl.edu.agh.to2.commands.Command; import pl.edu.agh.to2.commands.CommandStack; import pl.edu.agh.to2.commands.ProceduresStack; import pl.edu.agh.to2.commands.UnknownCommand; import pl.edu.agh.to2.interpreter.Parser; import pl.edu.agh.to2.interpreter.ParserPL; import pl.edu.agh.to2.interpreter.expressions.Expression; import pl.edu.agh.to2.interpreter.expressions.TerminalExpressionLIST; import pl.edu.agh.to2.interpreter.expressions.TerminalExpressionNUMBER; import pl.edu.agh.to2.interpreter.expressions.TerminalExpressionPROCEDUREVARIABLE; import pl.edu.agh.to2.models.Call; import pl.edu.agh.to2.models.CallStack; import pl.edu.agh.to2.models.Procedure; import pl.edu.agh.to2.models.Turtle; import java.io.File; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.stream.Collectors; public class OverviewController { private CommandStack commands; private ProceduresStack procedures; private CallStack calls; private Parser parser; private AppController appController; private Turtle turtle; private File file = null; private static final Logger logger = LogManager.getLogger(OverviewController.class); @FXML private ImageView turtleImage; @FXML private AnchorPane pane; @FXML private TextField textField; @FXML private ComboBox<Call> comboBox_history; @FXML private TextArea console; @FXML private MenuItem closeItem; @FXML private MenuItem saveItem; @FXML private MenuItem saveAsItem; @FXML private MenuItem loadItem; @FXML private MenuItem undoItem; @FXML private MenuItem redoItem; @FXML private Button button_undo; @FXML private Button button_redo; public OverviewController() { parser = new ParserPL(this); commands = new CommandStack(); procedures = new ProceduresStack(); } @FXML private void undo() { commands.undo(); } @FXML private void redo() { commands.redo(); } @FXML private void reset() { setDefaultState(); } @FXML private void initialize() { setDefaultState(); redoItem.setAccelerator(KeyCombination.keyCombination("CTRL+SHIFT+Z")); redoItem.setOnAction(event -> commands.redo()); undoItem.setAccelerator(KeyCombination.keyCombination("CTRL+SHIFT+X")); undoItem.setOnAction(event -> commands.undo()); saveItem.setAccelerator(KeyCombination.keyCombination("CTRL+S")); saveItem.setOnAction(event -> { logger.debug("Starting saving the file"); File newFile = appController.handleFileSaving(file, commands.toString(), true); this.file = newFile != null ? newFile : this.file; }); saveAsItem.setOnAction(event -> { logger.debug("Starting saving the file as"); File newFile = appController.handleFileSaving(file, commands.toString(), false); this.file = newFile != null ? newFile : this.file; }); loadItem.setOnAction(event -> { logger.debug("Starting loading data"); File newFile = appController.handleFileChoosing(file); if (newFile == null) { logger.debug("User resigned from opening file"); } else { this.file = newFile; setDefaultState(); ArrayDeque<String> commands = appController.handleFileReading(newFile); commands.forEach(command -> { logger.debug(command); if (command.length() > 0) calls.addCall(new Call(command)); console.appendText("\n" + command); console.setScrollTop(Double.MAX_VALUE); executeCommand(command); }); executeCommand(parser.evaluate(true)); } logger.debug("Finished loading data"); }); closeItem.setAccelerator(KeyCombination.keyCombination("CTRL+Q")); closeItem.setOnAction(event -> System.exit(0)); } private void setDefaultState() { this.pane.getChildren().clear(); this.pane.getChildren().add(turtleImage); this.commands = new CommandStack(); this.procedures = new ProceduresStack(); this.calls = new CallStack(); this.comboBox_history.itemsProperty().bind(calls.totalProperty()); initializeTurtle(pane.getPrefWidth() / 2 - this.turtleImage.getFitWidth() / 2, pane.getPrefHeight() / 2 - this.turtleImage.getFitHeight() / 2, true, 90); comboBox_history.valueProperty().addListener((obs, oldItem, newItem) -> { if (newItem != null) { textField.setText(newItem.getCallRaw()); } }); undoItem.disableProperty().bind(commands.historyEmptyProperty()); redoItem.disableProperty().bind(commands.futureEmptyProperty()); button_undo.disableProperty().bind(commands.historyEmptyProperty()); button_redo.disableProperty().bind(commands.futureEmptyProperty()); this.textField.setText(""); this.console.setText("Witaj w Logomocji by Wiesław Stanek & Wojciech Chmielarz"); this.console.textProperty().addListener(event -> this.console.setScrollTop(Double.MAX_VALUE)); } @FXML public void handleKeyPressed(KeyEvent keyEvent) { String s; Call call; switch (keyEvent.getCode()) { case ENTER: s = textField.getText().trim(); if (s.length() > 0 && s.split("\\s").length > 0) { textField.setText(""); calls.addCall(new Call(s)); console.appendText("\n" + s); if (procedures.getProcedures().get(s.split(" ")[0]) != null) { executeProcedure(s); } else { executeCommand(s); } } else { console.appendText("\n"); executeCommand(parser.evaluate(true)); } break; case UP: call = calls.getPrev(); if (call != null) textField.setText(call.getCallRaw()); break; case DOWN: call = calls.getNext(); textField.setText(call == null ? "" : call.getCallRaw()); break; } } private void executeProcedure(String command) { String procedureName = command.split(" ")[0]; Procedure procedure = procedures.getProcedures().get(procedureName); ArrayList<Expression> args = new ArrayList<>(Arrays .stream(command.split(" ")) .skip(1) .map(x -> new TerminalExpressionNUMBER(Integer.parseInt(x), x)) .collect(Collectors.toList())); ArrayList<Expression> copy = new ArrayList<>(procedure.getExpressions()); //shallow copy ArrayList<Expression> exp = new ArrayList<>(procedure.getExpressions()); //shallow copy for (Expression expression : procedure.getExpressions()) { if (expression instanceof TerminalExpressionPROCEDUREVARIABLE) { for (Expression arg : procedure.getArguments()) { if (expression.getRaw().equals(arg.getRaw())) { int index = exp.indexOf(expression); exp.remove(index); int index2 = new ArrayList<>(procedure.getArguments()).indexOf(arg); exp.add(index, args.get(index2)); } } } if (expression instanceof TerminalExpressionLIST) { ((TerminalExpressionLIST) expression).emptify(); } } procedure.setExpressions(new ArrayDeque<>(exp)); ((ParserPL) parser).removeExpressions(); ((ParserPL) parser).getExpressions().addAll(exp); executeCommand(parser.evaluate(false)); procedure.setExpressions(new ArrayDeque<>(copy)); } public void executeCommand(String command) { if (!command.equals("już") && procedures.getActiveProcedure() != null) { Procedure procedure = procedures.getActiveProcedure(); parser.parse(command); procedure.addExpressions(((ParserPL) parser).getExpressions()); ((ParserPL) parser).removeExpressions(); } else { ((ParserPL) parser).removeExpressions(); parser.parse(command); executeCommand(parser.evaluate(false)); } } private void executeCommand(Command command) { if (command instanceof UnknownCommand) console.setText(console.getText() + "\n" + command.toString()); commands.execute(command); } public void initializeTurtle(double x, double y, boolean visible, double angle) { turtle = new Turtle(x, y, visible, angle, turtleImage); } public void setAppController(AppController appController) { this.appController = appController; } public ArrayDeque<Node> clearCanvas() { this.pane.getChildren().remove(this.turtleImage); ArrayDeque<Node> children = new ArrayDeque<>(this.pane.getChildren()); this.pane.getChildren().clear(); this.pane.getChildren().add(this.turtleImage); return children; } public void setDefaultPosition() { turtle.setPosition(pane.getPrefWidth() / 2 - this.turtleImage.getFitWidth() / 2, pane.getPrefHeight() / 2 - this.turtleImage.getFitHeight() / 2, 90); } public Turtle getTurtle() { return turtle; } public AnchorPane getPane() { return pane; } public TextArea getConsole() { return console; } public ProceduresStack getProceduresStack() { return procedures; } }
package car_rent.rent; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class DeleteOptionServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String optionId = req.getParameter("optionId"); Integer id = null; try { id = Integer.valueOf(optionId); } catch (Exception e) { e.printStackTrace(); } if (id != null) { OptionRepository.delete(id); } resp.sendRedirect("adminPanelOptionList.jsp"); } }
package org.wxy.weibo.cosmos.network.api; import org.wxy.weibo.cosmos.bean.ByMeBean; import org.wxy.weibo.cosmos.bean.CommentsShowBean; import org.wxy.weibo.cosmos.bean.CreateBean; import org.wxy.weibo.cosmos.bean.DestroyBean; import org.wxy.weibo.cosmos.bean.MentionsBean; import org.wxy.weibo.cosmos.bean.ReplyBean; import org.wxy.weibo.cosmos.bean.ToMeBean; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Query; public interface IComments { //评论 @POST("2/comments/create.json") Call<CreateBean> create(@Query("access_token")String access_token, @Query("comment")String comment, @Query("id")long id); //获取评论 @GET("2/comments/show.json") Call<CommentsShowBean> show(@Query("access_token")String access_token, @Query("id")long id, @Query("page") int page); //发出评论 @GET("2/comments/by_me.json") Call<ByMeBean> byme(@Query("access_token")String token, @Query("page")int page); //收到评论 @GET("2/comments/to_me.json") Call<ToMeBean> tome(@Query("access_token")String token, @Query("page")int page); //@我的评论 @GET("2/comments/mentions.json") Call<MentionsBean> mentions(@Query("access_token")String token, @Query("page")int page); //删除一条发出的评论 @POST("2/comments/destroy.json") Call<DestroyBean> destroy(@Query("access_token")String token, @Query("cid")long id); //回复一条评论 @POST("2/comments/reply.json") Call<ReplyBean> reply(@Query("access_token")String token, @Query("cid")long cid, @Query("id")long id, @Query("comment") String text); }
/* * 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.mycompany; import javax.ejb.Singleton; import javax.interceptor.Interceptors; /** * * @author kerch */ @Singleton(mappedName = "calculator") @Interceptors({MyCalculatorInterceptor.class}) public class CalculatorImpl implements Calculator { @Override public int add(int a, int b) { return a + b; } @Override public int subtract(int a, int b) { long start = System.currentTimeMillis(); System.out.println("Claculator.subtract"); while (System.currentTimeMillis() - start <= 20000) { } return a - b; } }
class varArray { public void m1(int arr[]) { for(int x:arr) { System.out.println(x); } } public static void main(String[]args) { varArray o = new varArray(); int n1[] = {10}; int n2[] = {10,20}; int n3[] = {1,2,3,4,5}; o.m1(n3); } }
package com.sjzy.data.monitor; import com.alibaba.druid.pool.DruidDataSource; import com.sjzy.data.monitor.common.Constants; import com.sjzy.data.monitor.db.DBMailHelper; import com.sjzy.data.monitor.mail.SendMailSmtp; import com.sjzy.data.monitor.pojo.JobInfoDemo; import com.sjzy.data.monitor.pojo.SHDemo; import com.sjzy.data.monitor.pojo.TwoTuple; import com.sjzy.data.monitor.utils.ConnectLinuxUtil; import com.sjzy.data.monitor.utils.MysqlUtil; import org.springframework.jdbc.core.JdbcTemplate; import java.util.*; /** * Created by wpp on 2020/8/14. */ public class jobMonitor { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); Date firstTime = cal.getTime(); int period = Constants.SECOND * 60 * 5; DruidDataSource dataSource = new DBMailHelper().getDataSource(args[0]); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); Timer timer = new Timer(); timer.schedule(new wppMailTimerTask(args[0],jdbcTemplate), firstTime, period); dataSource.close(); } /** * 关键类 */ public static class wppMailTimerTask extends TimerTask { private String path = null; private JdbcTemplate jdbcTemplate = null; private wppMailTimerTask() { } private wppMailTimerTask(String path,JdbcTemplate jdbcTemplate) { this.path = path; this.jdbcTemplate = jdbcTemplate; } @Override public void run() { //获取job信息,并处理 List<JobInfoDemo> iPJobInfo = ConnectLinuxUtil.getJobInfo(Constants.MONITOR_IPS, Constants.EXEC_JPS_CMD); List<JobInfoDemo> mysqlJobInfo = MysqlUtil.getJobInfo(jdbcTemplate); //获取内存信息,并处理 List<SHDemo> ipSoftInfo = ConnectLinuxUtil.getSoftInfo(Constants.MONITOR_IPS, Constants.EXEC_SOFT_CMD); List<SHDemo> mysqlSoftInfo = MysqlUtil.getSoftInfo(jdbcTemplate); //获取磁盘信息,并处理 List<SHDemo> ipHardInfo = ConnectLinuxUtil.getHardInfo(Constants.MONITOR_IPS, Constants.EXEC_HARD_CMD); List<SHDemo> mysqlHardInfo = MysqlUtil.getHardInfo(jdbcTemplate); //是否发送邮件 TwoTuple<Boolean,String> tmp = isSend(mysqlJobInfo,iPJobInfo,mysqlSoftInfo,ipSoftInfo,mysqlHardInfo,ipHardInfo); //如果发送邮件,则。。。。 if ( tmp.first ){ SendMailSmtp.SendMail(tmp.second,path); //更改记录 MysqlUtil.changeJobInfo(iPJobInfo,jdbcTemplate); MysqlUtil.changeSHInfo(mysqlSoftInfo,ipSoftInfo,mysqlHardInfo,ipHardInfo,jdbcTemplate); } } } public static TwoTuple<Boolean,String> isSend(List<JobInfoDemo> mysqlJobInfo, List<JobInfoDemo> iPJobInfo, List<SHDemo> mysqlSoftInfo, List<SHDemo> ipSoftInfo, List<SHDemo> mysqlHardInfo, List<SHDemo> ipHardInfo) { return ConnectLinuxUtil.getMailMessage(mysqlJobInfo,iPJobInfo,mysqlSoftInfo,ipSoftInfo,mysqlHardInfo,ipHardInfo); } }
package com.hty.spring5.core.function; import com.hty.spring5.core.model.ResultWrapper; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Mono; @Component public class HelloHandler { public Mono<ServerResponse> handleHello1(ServerRequest request) { String name = request.queryParam("name").orElse(""); return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8).syncBody(ResultWrapper.asSuccess(name)); } }
package in.vamsoft.excersise2; import java.util.ArrayList; import java.util.List; import in.vamsoft.excersise1.shape1.Circle; public class CircleListTest { public static void main(String[] args) { List<Circle> circles = new ArrayList<>(); while (Math.random() > 0.01) { circles.add(new Circle(10*Math.random())); } for(Circle c: circles) { System.out.printf("Area: %8.3f%n", c.getArea()); } } }
package me.libme.baidu.mapdata.searchindex.impl.place; import me.libme.baidu.mapdata.searchindex.impl.ReferencePoint; import me.libme.baidu.mapdata.searchindex.impl.place.response.BaiduPlaceResponse; import me.libme.baidu.mapdata.searchindex.keyword.KeywordSearch; import me.libme.baidu.mapdata.searchindex.keyword.SearchParam; import me.libme.baidu.mapdata.searchindex.point.Point; import me.libme.kernel._c.http.JHttp; import me.libme.kernel._c.json.JJSON; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Created by J on 2018/3/5. */ public class SimpleBaiduSearch implements KeywordSearch { private final KeywordSearchParser keywordSearchParser; private final SearchConf _default; public SimpleBaiduSearch(KeywordSearchParser keywordSearchParser, SearchConf _default) { this.keywordSearchParser = keywordSearchParser; this._default = _default; } private void collect(SearchConf searchConf, List<Point> points){ String url=keywordSearchParser.parse(searchConf); try { String response = (String) JHttp._get().setTimeout(5000).setSocketTimeout(100000) .execute(url); BaiduPlaceResponse baiduPlaceResponse = JJSON.get().parse(response, BaiduPlaceResponse.class); baiduPlaceResponse.getResults() .forEach(result->{ ReferencePoint baiduPoint=new ReferencePoint(); baiduPoint.setName(result.getName()); baiduPoint.setLatitude(String.valueOf(result.getLocation().getLat())); baiduPoint.setLongitude(String.valueOf(result.getLocation().getLng())); baiduPoint.setCppEventSource("BAIDU"); baiduPoint.setAddr(result.getAddress()); baiduPoint.setId(baiduPoint.logicUniqueId()); points.add(baiduPoint); }); int total=baiduPlaceResponse.getTotal(); int maxNum=total/Integer.valueOf(searchConf.getPageSize()); int nextNum=Integer.valueOf(searchConf.getPageNum())+1; if(nextNum<=maxNum){ searchConf.setPageNum(""+nextNum); collect(searchConf,points); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public List<Point> search(SearchParam searchParam) { try { SearchConf target=_default.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } searchConf.setQuery(searchParam.keyword()); List<Point> points=new ArrayList<>(); collect(searchConf,points); return points; } }
package com.edgit.server.security.authentication; import java.io.Serializable; import java.util.Hashtable; import java.util.Properties; import java.util.StringTokenizer; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.LdapContext; import com.edgit.server.domain.User; import com.edgit.server.jpa.GitFile; public class LdapServer implements Serializable { private static final long serialVersionUID = 1L; // the suffix (base DN) associated with the partition public static final String PARTITION_SUFIX = "o=ed"; public static final String USERS = String.format("ou=edgit,%s", PARTITION_SUFIX); private DirContext context; private LdapPartitionManager partitionManager; public LdapServer() { try { this.context = getContext(); } catch (NamingException e) { // context could not be initialized e.printStackTrace(); } partitionManager = new LdapPartitionManager(context); } public LdapPartitionManager getPartitionManager() { return partitionManager; } public DirContext getContext() throws NamingException { if (context == null) { Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); properties.put(Context.PROVIDER_URL, "ldap://localhost:10389/"); properties.put(Context.SECURITY_AUTHENTICATION, "simple"); properties.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system"); properties.put(Context.SECURITY_CREDENTIALS, "secret"); return new InitialDirContext(properties); } return context; } public User authenticate(String identification, String password) { try { String dn = findDistinctNameOfAccount(context, USERS, identification); // throws NamingException if not verified verifyPassword(context, dn, password); User user = retrieveUser(context, dn, ""); return user; } catch (NamingException e) { return null; } } private String findDistinctNameOfAccount(DirContext ctx, String ldapSearchBase, String identification) throws NamingException { String filter = "(&(objectClass=edgitClient)(|(uid={0})(mail={0})))"; SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); controls.setReturningAttributes(new String[0]); controls.setReturningObjFlag(true); NamingEnumeration<SearchResult> enm = ctx.search(ldapSearchBase, filter, new String[] { identification }, controls); String dn = null; if (enm.hasMore()) { SearchResult result = enm.next(); dn = result.getNameInNamespace(); } if (dn == null || enm.hasMore()) { // uid not found or not unique throw new NamingException("Authentication failed"); } enm.close(); return dn; } /** * Verifies the user's password. Try to initialize the cloned context * environment. If the user credentials are different from the originals, it * throws an exception. * <p> * A cloning of the context environment is done so the original environment * it's not modified. * * @param ctx * The original context * @param dn * The distinct name to user * @param password * The password to be checked * @throws NamingException * if a naming exception is encountered */ private void verifyPassword(DirContext ctx, String dn, String password) throws NamingException { // Bind with a DN and given password @SuppressWarnings("unchecked") Hashtable<String, String> environment = (Hashtable<String, String>) ctx.getEnvironment().clone(); environment.put(Context.SECURITY_PRINCIPAL, dn); environment.put(Context.SECURITY_CREDENTIALS, password); new InitialDirContext(environment).close(); } private User retrieveUser(DirContext cxt, String dn, String subcontext) throws NamingException { User user = new User(); // Perform a lookup of the object itself using JNDI LdapContext obj = (LdapContext) cxt.lookup(dn); Attributes attributes = obj.getAttributes(subcontext); Attribute username = attributes.get("uid"); Attribute firstName = attributes.get("cn"); Attribute lastName = attributes.get("sn"); Attribute emailAddress = attributes.get("mail"); String rootRepositoryStr = attributes.get("rootRepository").get().toString(); GitFile userRoot = new GitFile(); StringTokenizer st = new StringTokenizer(rootRepositoryStr, ";"); while (st.hasMoreElements()) { String element = st.nextToken(); String[] kv = element.split(":"); String key = getKey(kv); String value = getValue(kv); switch (key) { case "id": userRoot.setFileId(Long.parseLong(value)); break; case "folder": userRoot.setFolder(null); break; case "filename": userRoot.setFilename(value); break; case "description": userRoot.setDescription(value); break; case "isFile": userRoot.setIsFile(Boolean.parseBoolean(value)); default: ; } } user.setUsername(username.get().toString()); user.setFirstName(firstName.get().toString()); user.setLastName(lastName.get().toString()); user.setEmailAddress(emailAddress.get().toString()); user.setRootRepository(userRoot); return user; } private String getKey(String[] kv) { return kv[0]; } private String getValue(String[] kv) { try { return kv[1]; } catch (ArrayIndexOutOfBoundsException e) { return ""; } } }
package com.codigo.smartstore.webapi.generators; import java.io.Serializable; import java.util.Properties; import org.hibernate.HibernateException; import org.hibernate.MappingException; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.id.enhanced.SequenceStyleGenerator; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.service.ServiceRegistry; import org.hibernate.type.LongType; import org.hibernate.type.Type; public final class StringPrefixedSequenceIdGenerator extends SequenceStyleGenerator { public static final String VALUE_PREFIX_PARAMETER = "valuePrefix"; public static final String VALUE_PREFIX_DEFAULT = ""; private String valuePrefix; public static final String NUMBER_FORMAT_PARAMETER = "numberFormat"; public static final String NUMBER_FORMAT_DEFAULT = "%d"; private String numberFormat; @Override public Serializable generate(final SharedSessionContractImplementor session, final Object object) throws HibernateException { return this.valuePrefix + String.format(this.numberFormat, super.generate(session, object)); } @Override public void configure(final Type type, final Properties params, final ServiceRegistry serviceRegistry) throws MappingException { super.configure(LongType.INSTANCE, params, serviceRegistry); this.valuePrefix = ConfigurationHelper.getString(VALUE_PREFIX_PARAMETER, params, VALUE_PREFIX_DEFAULT); this.numberFormat = ConfigurationHelper.getString(NUMBER_FORMAT_PARAMETER, params, NUMBER_FORMAT_DEFAULT); } }
package graphics_control.drawables; /** * Drawable interface. */ public interface Drawable { void draw(); }
import java.util.Arrays; class Solution { public int solution(int[] people, int limit) { int answer = 0; int cnt = 0; int weight = 0; int i = 0; Arrays.sort(people); while(cnt != people.length) { if(i <= people.length-1 && weight + people[i] <= limit) { weight += people[i]; i++; cnt++; } else { answer++; weight = 0; } } answer += 1; return answer; } }
package vape.springmvc.services; import java.util.List; import vape.springmvc.entity.ProductosPrecio; public interface ProductosPrecioServices { public List <ProductosPrecio> getProductosPrecio(); }
package edu.ua.lccmarc2json; import java.math.BigDecimal; import java.util.Comparator; public class NumbersDescribedByTopicComparator implements Comparator<String> { @Override public int compare(String numbersDescribedByFirstTopic, String numbersDescribedBySecondTopic) { // Extract the numerical component of the first classification number in each String. BigDecimal numberForFirstTopic = getNumberForTopic(numbersDescribedByFirstTopic); BigDecimal numberForSecondTopic = getNumberForTopic(numbersDescribedBySecondTopic); // If the first classification number in either String does not have a numerical component... if ((numberForFirstTopic == null) || (numberForSecondTopic == null)) { // Return the result of the comparison of the Strings. return numbersDescribedByFirstTopic.compareTo(numbersDescribedBySecondTopic); } // Else, if both classification numbers have numerical components... else { // Return the result of the comparison of the two numerical components. return numberForFirstTopic.compareTo(numberForSecondTopic); } } // Extract the numerical component of the first classification number in the given String. private BigDecimal getNumberForTopic(String numbersDescribedByTopic) { // Start with a blank string. String numberForTopic = ""; // Create a loop variable. int i = 0; // Move past all of the leading uppercase letters. while (i < numbersDescribedByTopic.length()) { // Get the next character. char c = numbersDescribedByTopic.charAt(i); // If the character is an uppercase letter... if (Character.isLetter(c) && Character.isUpperCase(c)) { // Increment the loop variable and continue looping. ++i; continue; } // Else, if the character is not an uppercase letter... else { // All leading uppercase letters have been moved past; exit the loop. break; } } // Get the numerical component. while (i < numbersDescribedByTopic.length()) { // Get the next character. char c = numbersDescribedByTopic.charAt(i); // If the character is a digit or a decimal point... if (Character.isDigit(c) || (c == '.')) { // The character is part of the numerical component; add it to the number for the topic. numberForTopic += c; // Increment the loop variable and continue looping. ++i; continue; } // Else, if the character is not a digit or a decimal point... else { // The numerical component has passed; exit the loop. break; } } // If the number for the topic consists of at least two characters and the last character in the number for the topic is a decimal point... if ((numberForTopic.length() >= 2) && (numberForTopic.charAt(numberForTopic.length() - 1) == '.')) { // Remove it. numberForTopic = numberForTopic.substring(0, numberForTopic.length() - 2); } // If the classification number has a numerical component... if (!numberForTopic.isEmpty()) // Return the numerical component as a BigDecimal. return new BigDecimal(numberForTopic); // Else, if the classification number does not have a numerical component... else { // Return null. return null; } } }
public class Diemthi { public static void main(String[] args) { float dtoan = 7F, dly = 7F, dhoa = 8F; int hstoan = 2, hsly = 1, hshoa = 1; float diemtb; diemtb = (dtoan * hstoan + dly * hsly + dhoa * hshoa)/4; System.out.println("Điểm toán = " + dtoan + ", Hệ số = " + hstoan); System.out.println("Điểm lý = " + dly + ", Hệ số = " + hsly); System.out.println("Điểm hóa = " + dhoa + ", Hệ số = " + hshoa); System.out.println("Điểm trung bình ba môn = " + diemtb); } }
package com.test.single; /** * KMP算法,在不匹配时,找规律,让模式串多滑动几位 * * n : 主串长度 * m : 模式串长度 * * 简介:遇到坏字符时,主串不再重新匹配,而是将模式串,直接从某个字符串开始匹配 * 时间复杂度:最坏 = n * m; 最好 = n * 空间复杂度:m * * @author YLine * * 2019年4月8日 上午11:34:30 */ public class SolutionKMP implements SingleModelSolution { @Override public int matching(String mainStr, String patternStr) { if (patternStr.length() == 0) { return 0; } int[] nextArray = next(patternStr); int mainIndex = 0, patternIndex = 0; while (mainIndex < mainStr.length() && patternIndex < patternStr.length()) { // 相匹配,则主串和模式串,继续匹配 if (mainStr.charAt(mainIndex) == patternStr.charAt(patternIndex)) { mainIndex++; patternIndex++; } else { if (patternIndex == 0) // 如果,主串和模式串首个就不匹配,则主串继续移动,模式串停留在首位 { mainIndex++; patternIndex = 0; } else // 如果,主串和模式串,有前缀,则主串不移动,模式串获取下一次匹配的开始位置 { // mainIndex = mainIndex; patternIndex = nextArray[patternIndex]; } } } // 如果,模式串溢出,则表明,模式串已经被完全匹配了 if (patternIndex == patternStr.length()) { return mainIndex - patternIndex; } return -1; } private static final int TAG = -5; /** * A --> {0} * AB --> {0, 0} * aabaaac --> {0, 0, 1, 0, 1, 2, 2} * ABCDABDABAB --> {0, 0, 0, 0, 0, 1, 2, 0, 1, 2, 1} * SSSSSSSSSSS --> {0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9} * * 字符串下标 -> 下一次模式串开始匹配的位置 * * @param needle 字符串 * @return 获取某个下标不匹配时,下一次重新开始匹配的位置 */ public static int[] next(String needle) { int[] next = new int[needle.length()]; next[0] = TAG; int k = TAG; int index = 0; while (index < needle.length() - 1) { if (k == TAG) // a,开始位置,直接置为0 { index++; k = 0; next[index] = 0; } else if (needle.charAt(k) == needle.charAt(index)) // b,下一个值相等 { index++; k++; next[index] = k; } else // c,下一个值不相等 { k = next[k]; } } next[0] = 0; return next; } }
package br.com.devweb.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; 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.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import br.com.devweb.models.Curso; import br.com.devweb.repository.CursoRepository; @RestController @RequestMapping("/api/curso") public class CursoController { @Autowired private CursoRepository cursoRepository; @GetMapping("/getAll") public ResponseEntity<List<Curso>> getAll(){ List<Curso> curso = cursoRepository.findAll(); return curso!=null ? ResponseEntity.ok(curso): ResponseEntity.noContent().build(); } @GetMapping("/getOne/{id}") public ResponseEntity<Curso> getOne(@PathVariable("id") int id){ Curso curso = cursoRepository.findById(id); return curso!=null?ResponseEntity.ok(curso):ResponseEntity.noContent().build(); } @PostMapping public ResponseEntity<Curso> save(@RequestBody Curso curso){ long cont = cursoRepository.count(); cursoRepository.save(curso); if(cont<cursoRepository.count()) { return ResponseEntity.ok(curso); }else { return ResponseEntity.noContent().build(); } } @DeleteMapping("delete/{id}") public ResponseEntity<Curso> delete(@PathVariable("id") int id){ cursoRepository.deleteById(id); Curso curso = cursoRepository.findById(id); return curso==null? ResponseEntity.ok(curso) : ResponseEntity.noContent().build(); } }
package com.alex; import com.alex.exceptions.PetIsDeadException; import com.alex.pets.Bunny; import com.alex.plants.Clover; import org.junit.Assert; import org.junit.Test; public class Bunnytest { @Test public void testBunnyHaveCorrectName() { Bunny bunny = new Bunny("Bugz", "Shinshilla", "Gray"); Assert.assertEquals("Check bunny has correct name", "Bugz", bunny.getName()); } @Test public void testBunnyHaveCorrectBreed() { Bunny bunny = new Bunny("Bugz", "Shinshilla", "Gray"); Assert.assertEquals("Shinshilla", bunny.getBreed()); } @Test public void testBunnyHaveCorrectColor() { Bunny bunny = new Bunny("Bugz", "Shinshilla", "Gray"); Assert.assertEquals("Gray", bunny.getColor()); } @Test public void testBunnyEatClover() { Clover clover = new Clover("Clover"); Bunny bunny = new Bunny("Bugz", "Shinshilla", "Gray"); bunny.eat(clover); Assert.assertFalse("Check that Clover poisoning Bunny", bunny.isAlive()); } @Test(expected = PetIsDeadException.class) public void testBunnyIsThrowExpected() { Bunny bunny = new Bunny("Bugz", "Shinshilla", "Gray"); bunny.kill(); bunny.eat(new Clover("Grass")); } }
package kui.eureka_recommend.entity; import java.util.Objects; public class Interest { private int id; private int n_no; private float val; private long timestamp; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getN_no() { return n_no; } public void setN_no(int n_no) { this.n_no = n_no; } public float getVal() { return val; } public void setVal(float val) { this.val = val; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } @Override public int hashCode() { return Objects.hash(getId(),getN_no()); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Interest other = (Interest) obj; if (id != other.id) return false; if (n_no != other.n_no) return false; return true; } @Override public String toString() { return "Interest [id=" + id + ", n_no=" + n_no + ", val=" + val + ", timestamp=" + timestamp + "]"; } }
import java.io.*; import java.util.*; public class Main { static BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static void main(String[] args) throws IOException{ try{ int n = readInt(); double counter = 0; String[]arr = new String[n]; double percentage = 0; for(int i = 0; i<n; i++){ String val = readLine(); String line[] = val.split(" "); arr[i] = val; if(line[1].equals("added")){ counter+=Double.parseDouble(line[0]); } else if(line[1].equals("increased")){ percentage+=Double.parseDouble(line[0]); } } percentage/=100; percentage+=1; counter*=percentage; for(int i = 0; i<n; i++){ String line[] = arr[i].split(" "); if(line[1].equals("more")){ counter*=1+(Double.parseDouble(line[0])/100); } } String ans = Double.toString(counter); String[]arr1 = ans.split("\\.0"); pr.println(arr1[0]); pr.close(); } catch (Exception e){ System.out.println(0); } } static String next () throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(input.readLine().trim()); return st.nextToken(); } static long readLong () throws IOException { return Long.parseLong(next()); } static int readInt () throws IOException { return Integer.parseInt(next()); } static double readDouble () throws IOException { return Double.parseDouble(next()); } static String readLine () throws IOException { return input.readLine().trim(); } }
/* * @lc app=leetcode.cn id=41 lang=java * * [41] 缺失的第一个正数 */ // @lc code=start class Solution { public int firstMissingPositive(int[] nums) { // <=0的数 n+1; int N = nums.length; for (int i = 0; i < N; i++){ if(nums[i] <= 0){ nums[i] = N + 1; } } // 对应下标标记为负数,标识存在数字:index+1 for (int i = 0; i < N; i++){ int index = Math.abs(nums[i]) - 1; if(index < N){ nums[index] = - Math.abs(nums[index]); } } // 查找第一个确实的正数 for (int i = 0; i < N; i++){ if(nums[i] > 0){ return i+1; } } return N+1; } } // @lc code=end
package com.example2.util; import java.util.List; import com.example2.models.User; public interface Accessor { public abstract List<User> getAllUsers(); public abstract User getUser(String userName); public abstract boolean saveUser(User user); }
package OOP.Constructors; public class Main { public static void main(String[] args) { // Box myBox = new Box(); // System.out.println(myBox.getSquare()); //250 // Peredaem parametri pri initializatsii Box myBox = new Box(10,20,30); System.out.println(myBox.getSquare()); } }
package systemplus.com.br.cadastrodepessoas; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import java.util.List; import retrofit.RestAdapter; import systemplus.com.br.cadastrodepessoas.adapter.PessoasAdapter; import systemplus.com.br.cadastrodepessoas.client.PessoaCliente; import systemplus.com.br.cadastrodepessoas.fragment.Formulario; import systemplus.com.br.cadastrodepessoas.fragment.Pessoas; import systemplus.com.br.cadastrodepessoas.model.Pessoa; import systemplus.com.br.cadastrodepessoas.service.PessoaService; public class CadastroActivity extends AppCompatActivity { private List<Pessoa> listaPessoas; private Fragment fragment; private PessoaService service; private PessoasAdapter adapter; private RestAdapter restAdapter; private PessoaCliente cliente; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cadastro); listaDePessoas(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_start, menu); MenuItem itemConfirmar = menu.findItem(R.id.menu_confirmar_cadastro); itemConfirmar.setVisible(false); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_carregar_lista: listaDePessoas(); fragment = new Pessoas(listaPessoas, adapter, service, cliente); break; case R.id.menu_adicionar_lista: fragment = new Formulario(cliente); break; } loadFragment(fragment); return super.onOptionsItemSelected(item); } private void loadFragment(Fragment fragment) { FragmentManager manager = getSupportFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); transaction.addToBackStack(null); transaction.replace(R.id.fragment_container, fragment); transaction.commit(); } private void listaDePessoas() { adapter = new PessoasAdapter(this, listaPessoas); restAdapter = new RestAdapter.Builder() .setEndpoint(PessoaService.BASE_URL).build(); service = restAdapter.create(PessoaService.class); cliente = new PessoaCliente(this, service); listaPessoas = cliente.getPessoas(); } }
package com.soldevelo.vmi.scheduler.service; import com.soldevelo.vmi.config.acs.model.HostParams; import com.soldevelo.vmi.logging.entities.Node; public interface NodeSelector { Node selectUdpNode(HostParams hostParams); Node selectHttpDownloadNode(HostParams hostParams); Node selectHttpUploadNode(HostParams hostParams); Node selectFtpDownloadNode(HostParams hostParams); Node selectFtpUploadNode(HostParams hostParams); }
package items; import board.blockingobject.Player; import board.square.Square; import board.square.effect.Effect; import util.parameters.ItemUseParameter; public abstract class Item implements Effect { /** * Uses an item * @param sq * The square to use this item on * @param param * The abstract parameter object */ public abstract void use(Square sq, ItemUseParameter param); /** * checks if the item can be picked up. * @return true if the player can pickup the item, false if it can't */ public abstract boolean canPickup(); /** * Checks if the item can be picked up by a specific player * * @param player The player that tries to pick up the item * @return True if the player can pickup the item, false if he can't */ public abstract boolean canPickup(Player player); /** * Returns whether an item can be used on the given square * * @param sq * Square on which the item is being used * * @return Boolean * Returns true if the item can be used on the given square, * returns false if not. */ public abstract boolean canUseOnSquare(Square sq); /** * Checks if the square with this item on it is accessible. * * @return True if accessible * False otherwise. */ public boolean isAccessible(){ return true; } /** * Method that gets called when an item is picked up * * @param player The player that picks up the item * * @throws IllegalStateException * The item can't be picked up */ public void onPickup(Player player) throws IllegalStateException{ if(!canPickup()) throw new IllegalStateException(); } }
/** * General utility classes for use in unit and integration tests. */ @NonNullApi @NonNullFields package org.springframework.test.util; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
package com.example.contentobserverexample; import android.content.ContentResolver; import android.content.Context; import android.database.ContentObserver; import android.os.Handler; import android.provider.Settings; import android.text.TextUtils; import android.util.AttributeSet; import android.widget.TextView; public class CustomTextView extends TextView{ private Context mContext; public CustomTextView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub mContext = context; } @Override protected void onAttachedToWindow() { // TODO Auto-generated method stub super.onAttachedToWindow(); new SettingsObserver(new Handler()).observe();; } class SettingsObserver extends ContentObserver{ public SettingsObserver(Handler handler) { super(handler); // TODO Auto-generated constructor stub } void observe(){ ContentResolver resolver = CustomTextView.this.mContext.getContentResolver(); resolver.registerContentObserver(Settings.System.getUriFor("example_observer_string"), false, this); updateSettings(); } @Override public void onChange(boolean selfChange) { // TODO Auto-generated method stub //super.onChange(selfChange); updateSettings(); } } void updateSettings(){ //edit String ganti_txt = Settings.System.getString(mContext.getContentResolver(),"example_observer_string"); if(TextUtils.isEmpty(ganti_txt)){ ganti_txt = "Kosong"; } setText(ganti_txt); //edit } }
package org.ordogene.algorithme.models; import java.util.Objects; import org.ordogene.file.models.JSONEntity; public class Entity { private final String name; private int quantity; private int maxQuantity; public Entity(String name, int quantity) { this(name, quantity, quantity); } private Entity(String name, int quantity, int maxQuantity) { if(quantity < 0){ throw new IllegalArgumentException("the quantity of an entity cannot be negative"); } this.name = Objects.requireNonNull(name); this.quantity = quantity; this.maxQuantity = maxQuantity; } public static Entity createEntity(JSONEntity je) { Objects.requireNonNull(je); return new Entity(je.getName(),je.getQuantity()); } public int getQuantity() { return quantity; } public int getMaxQuantity() { return maxQuantity; } public void addQuantity(int q) { if(quantity + q < 0) { throw new IllegalArgumentException("The end quantity can't be negative."); } quantity += q; maxQuantity += q; } public void putInPending(int q) { if(quantity - q < 0) { throw new IllegalArgumentException("The end quantity can't be negative."); } if(q < 0) { throw new IllegalArgumentException("The quantity to put in pending can't be negative."); } quantity -= q; } public void freePending(int q) { if(quantity + q > maxQuantity) { throw new IllegalArgumentException("The end quantity can't exceed the maximum quantity"); } if(q < 0) { throw new IllegalArgumentException("The quantity to free can't be negative."); } quantity += q; } public String getName() { return name; } public Entity copy() { return new Entity(name, quantity, maxQuantity); } @Override public int hashCode() { final int prime = 31; int result = prime * name.hashCode(); result = prime * result + quantity; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Entity)) return false; Entity entity = (Entity) obj; if (!name.equals(entity.name)) return false; if (quantity != entity.quantity) return false; return true; } @Override public String toString() { return "Entity [name=" + name + ", quantity=" + quantity + "]"; } }
package ca.brocku.cosc3p97.bigbuzzerquiz.messages.host; import android.util.Log; import ca.brocku.cosc3p97.bigbuzzerquiz.messages.common.Request; import ca.brocku.cosc3p97.bigbuzzerquiz.messages.common.Sender; import ca.brocku.cosc3p97.bigbuzzerquiz.models.Host; /** * Responsible for handling the incoming ready request from the player */ public class ReadyRequestHandler extends HostRequestHandler { private static final String TAG = "PlayRequestHandler"; /** * A constructor which takes a reference to the host that it is serving * @param host the host which this handler is serving */ public ReadyRequestHandler(Host host) { super(host); } /** * Handle the request passed as an argument. If a response is necessary then it can be * built and then passed back the calling player using the replyToSender reference passed * as an argument. * @param request the request details * @param replyToSender a reference to the player that is making the request */ @Override public void handle(Request request, Sender replyToSender) { ready(replyToSender); } /** * Make a call to the host to let inform that the player is ready. * @param sender */ public void ready(Sender sender) { Log.i(TAG, "ready: invoked"); host.ready(); } }
package pl.kate.pogodynka.model; import com.fasterxml.jackson.annotation.*; import lombok.Data; import javax.annotation.Generated; import java.util.HashMap; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "id", "main", "description", "icon" }) @Generated("jsonschema2pojo") @Data public class Weather { @JsonProperty("id") private Integer id; @JsonProperty("main") private String main; @JsonProperty("description") private String description; @JsonProperty("icon") private String icon; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); }
package com.logzc.webzic.collection; import org.junit.Test; import java.util.ArrayList; import java.util.List; /** * Created by lishuang on 2016/8/3. */ public class ListTest { @Test public void testNull(){ List<String> stringList=new ArrayList<>(); stringList.add("lishuang"); stringList.add("age"); stringList.add(null); stringList.add(null); stringList.add("address"); System.out.println(stringList); String a=stringList.get(2); System.out.println(a); } }
/* * 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 model; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Nasser */ @Entity @Table(name = "administradora") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Administradora.findAll", query = "SELECT a FROM Administradora a"), @NamedQuery(name = "Administradora.findByIdadministradora", query = "SELECT a FROM Administradora a WHERE a.idadministradora = :idadministradora"), @NamedQuery(name = "Administradora.findByDescricao", query = "SELECT a FROM Administradora a WHERE a.descricao = :descricao"), @NamedQuery(name = "Administradora.findBySite", query = "SELECT a FROM Administradora a WHERE a.site = :site"), @NamedQuery(name = "Administradora.findByContato", query = "SELECT a FROM Administradora a WHERE a.contato = :contato"), @NamedQuery(name = "Administradora.findByMaquineta", query = "SELECT a FROM Administradora a WHERE a.maquineta = :maquineta"), @NamedQuery(name = "Administradora.findByBanco", query = "SELECT a FROM Administradora a WHERE a.banco = :banco"), @NamedQuery(name = "Administradora.findByAgencia", query = "SELECT a FROM Administradora a WHERE a.agencia = :agencia"), @NamedQuery(name = "Administradora.findByConta", query = "SELECT a FROM Administradora a WHERE a.conta = :conta")}) public class Administradora implements Serializable { @Transient private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this); private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "idadministradora") private Integer idadministradora; @Column(name = "descricao") private String descricao; @Column(name = "site") private String site; @Column(name = "contato") private String contato; @Column(name = "maquineta") private String maquineta; @Column(name = "banco") private String banco; @Column(name = "agencia") private String agencia; @Column(name = "conta") private String conta; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idadministradora") private List<Auxcartao> auxcartaoList; public Administradora() { } public Administradora(Integer idadministradora) { this.idadministradora = idadministradora; } public Integer getIdadministradora() { return idadministradora; } public void setIdadministradora(Integer idadministradora) { Integer oldIdadministradora = this.idadministradora; this.idadministradora = idadministradora; changeSupport.firePropertyChange("idadministradora", oldIdadministradora, idadministradora); } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { String oldDescricao = this.descricao; this.descricao = descricao; changeSupport.firePropertyChange("descricao", oldDescricao, descricao); } public String getSite() { return site; } public void setSite(String site) { String oldSite = this.site; this.site = site; changeSupport.firePropertyChange("site", oldSite, site); } public String getContato() { return contato; } public void setContato(String contato) { String oldContato = this.contato; this.contato = contato; changeSupport.firePropertyChange("contato", oldContato, contato); } public String getMaquineta() { return maquineta; } public void setMaquineta(String maquineta) { String oldMaquineta = this.maquineta; this.maquineta = maquineta; changeSupport.firePropertyChange("maquineta", oldMaquineta, maquineta); } public String getBanco() { return banco; } public void setBanco(String banco) { String oldBanco = this.banco; this.banco = banco; changeSupport.firePropertyChange("banco", oldBanco, banco); } public String getAgencia() { return agencia; } public void setAgencia(String agencia) { String oldAgencia = this.agencia; this.agencia = agencia; changeSupport.firePropertyChange("agencia", oldAgencia, agencia); } public String getConta() { return conta; } public void setConta(String conta) { String oldConta = this.conta; this.conta = conta; changeSupport.firePropertyChange("conta", oldConta, conta); } @XmlTransient public List<Auxcartao> getAuxcartaoList() { return auxcartaoList; } public void setAuxcartaoList(List<Auxcartao> auxcartaoList) { this.auxcartaoList = auxcartaoList; } @Override public int hashCode() { int hash = 0; hash += (idadministradora != null ? idadministradora.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Administradora)) { return false; } Administradora other = (Administradora) object; if ((this.idadministradora == null && other.idadministradora != null) || (this.idadministradora != null && !this.idadministradora.equals(other.idadministradora))) { return false; } return true; } @Override public String toString() { return "model.Administradora[ idadministradora=" + idadministradora + " ]"; } public void addPropertyChangeListener(PropertyChangeListener listener) { changeSupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(listener); } }
import java.io.*; import javax.servlet.ServletException; import javax.servlet.RequestDispatcher; import javax.servlet.http.*; public class Login extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) // object of HttpServletResponse interface is response which will be send to the client,here res is a response throws ServletException, IOException{ res.setContentType("text/html"); PrintWriter out = res.getWriter(); String n=req.getParameter("userName"); String p=req.getParameter("userPass"); if(p.equals("servlet")){ /* here we need the object of RequestDispatcher interface to call its methods(forward() or include()), therefore we use the getRequestDispatcher() method to get this object */ RequestDispatcher rd=req.getRequestDispatcher("servlet2"); //The getRequestDispatcher() method of ServletRequest interface returns the object of RequestDispatcher interface. rd.forward(req, res); /*another way, we can use(see below) instead of above two lines */ // req.getRequestDispatcher("servlet2").forward(req,res); } else{ out.print("Sorry UserName or Password Error!"); RequestDispatcher rd=req.getRequestDispatcher("/index.html"); rd.include(req, res); } } }
package com.example.controlecigarro; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class Inicial extends AppCompatActivity { Button charuto,cigarro,vape,narguile,cachimbo; static int i; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_inicial); getSupportActionBar().hide(); cigarro=findViewById(R.id.cigarro); charuto=findViewById(R.id.charuto); vape=findViewById(R.id.vape); narguile = findViewById(R.id.narguile); cachimbo=findViewById(R.id.cachimbo); } public void cigarro(View view){ i = 1; Intent i = new Intent(this, Contagem.class); startActivity(i); } public void charuto(View view){ i = 2; Intent i = new Intent(this, Contagem.class); startActivity(i); } public void vape(View view){ i = 3; Intent i = new Intent(this, Contagem.class); startActivity(i); } public void narguile(View view){ i = 4; Intent i = new Intent(this, Contagem.class); startActivity(i); } public void cachimbo(View view){ i = 5; Intent i = new Intent(this, Contagem.class); startActivity(i); } }
package com.jushu.video.api; /** * @author 大奉 * @date 2020/1/10 11:44 * @blame 大奉 */ public class Pages { public static final String KEY_PAGE = "page.pageNo"; public static final String KEY_PAGESIZE = "page.pageSize"; public static int MAX_RECORDS = 1000000; // 100w public static int DEFAULT_PAGESIZE = 10; private int resultCount; // 总记录数, 可写 private int pageSize; // 每页记录数, 初始化时传入 private int pageCount; // 总页数 private int pageNo; // 当前页码, 初始化时传入 private int firstIndex; // 当前页的第一条记录在所有记录中的位置 private int lastIndex; private boolean firstPage; // 当前页是否是第一页 private boolean lastPage; // 当前页是否是最后一页 public Pages( ) { this( 1, DEFAULT_PAGESIZE ); this.onResultCountChanged( ); } public Pages( int pageNo, int pageSize ) { this.onResultCountChanged( ); this.pageNo = ( pageNo < 1 ) ? 1 : pageNo; this.pageSize = ( pageSize < 1 || pageSize > MAX_RECORDS ) ? DEFAULT_PAGESIZE : pageSize; } /** * 当总记录数改变后事件处理 */ private void onResultCountChanged( ) { // 第一步,计算总页数 if ( resultCount > 0 ) { if ( resultCount % pageSize == 0 ) { pageCount = resultCount / pageSize; } else { pageCount = resultCount / pageSize + 1; } } pageCount = ( pageCount <= 0 ) ? 1 : pageCount; // 调整当前页码 pageNo = ( pageNo > pageCount ) ? pageCount : pageNo; // 计算当前页的第一条记录在所有记录中的位置 firstIndex = ( pageNo - 1 ) * pageSize; lastIndex = pageNo * pageSize; firstPage = ( pageNo == 1 ); lastPage = ( pageNo == pageCount ); } public int getPageNo( ) { return pageNo; } public void setPageNo( int pageNo ) { this.pageNo = pageNo; } public int getPageSize( ) { return pageSize; } public void setPageSize( int pageSize ) { if ( pageSize < 1 || pageSize > MAX_RECORDS ){ return; } this.pageSize = pageSize; } public int getResultCount( ) { return resultCount; } public void setResultCount( int resultCount ) { this.resultCount = resultCount; onResultCountChanged( ); } public int getPageCount( ) { return pageCount; } public int getFirstIndex( ) { return firstIndex; } public int getLastIndex( ) { return lastIndex; } public boolean isFirstPage( ) { return firstPage; } public boolean isLastPage( ) { return lastPage; } public void setDefaultPageSize( int defaultPageSize ) { Pages.DEFAULT_PAGESIZE = defaultPageSize; } public void setMAX_RECORDS( int maxRecords ) { Pages.MAX_RECORDS = maxRecords; } }
package PresentationLayer.ActionListener; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class NavButtonListener implements ActionListener { private JPanel jPanel; private CardLayout cardLayout; private String page; public NavButtonListener(JPanel jPanel, CardLayout cardLayout, String page) { this.jPanel = jPanel; this.cardLayout = cardLayout; this.page = page; } @Override public void actionPerformed(ActionEvent e) { this.cardLayout.show(this.jPanel, this.page); } }
package com.lwc.auth.api; import com.lwc.auth.bo.AuthBo; import com.lwc.auth.fallback.AuthApiFallback; import com.lwc.common.Result; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.MediaType; import org.springframework.security.jwt.Jwt; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @FeignClient(name = "eip-user-service", path = "/api/v1/department", fallback = AuthApiFallback.class) public interface AuthApi { @PostMapping(value = "/checkIgnore", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) Result<Boolean> checkIgnore(@RequestBody AuthBo authBo); @PostMapping(value = "/hasPermission", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) Result<Boolean> hasPermission(@RequestBody AuthBo authBo); @PostMapping(value = "/getJwt", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) Result<Jwt> getJwt(@RequestBody AuthBo authBo); }
package com.uapp.useekr.fragments.create_transaction_pages; import android.content.Intent; import android.support.design.widget.TextInputEditText; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import com.uapp.useekr.R; import com.uapp.useekr.fragments.BaseFragment; import com.uapp.useekr.models.Transaction; import butterknife.BindView; /** * Created by root on 12/2/17. */ public class PaymentPage extends BasePage { @BindView(R.id.edit_transaction_create_payment_amount) TextInputEditText editAmount; @Override protected int contentLayout() { return R.layout.fragment_page_payment; } @Override protected int contentTitle() { return R.string.payment_details; } @Override protected void initialize() { editAmount.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { Intent intent = getActivity().getIntent(); Transaction transaction = (Transaction) intent.getSerializableExtra("transaction"); String amount = charSequence.toString(); if (!amount.isEmpty()) { transaction.setAmount(Double.parseDouble(amount)); intent.putExtra("transaction", transaction); getActivity().setIntent(intent); } } @Override public void afterTextChanged(Editable editable) { } }); } @Override void updateTransaction(View view, Transaction transaction) { TextInputEditText editAmount = view.findViewById(R.id.edit_transaction_create_payment_amount); String amount = editAmount.getText().toString(); if (!amount.isEmpty()) { transaction.setAmount(Double.parseDouble(amount)); } } }
package com.example.calculator; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class MainActivityOther extends AppCompatActivity { TextView textView; String firstArgument = ""; String secondArgument = ""; boolean isInputFirstArgument = true; boolean isCalculatedNow = false; String operation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textViewResult); } public void onClick(View v) { String value; switch (v.getId()) { case R.id.btnZero: // кнопка 0 textView.setText(addSymbol("0")); break; case R.id.btnOne: // кнопка 1 textView.setText(addSymbol("1")); break; case R.id.btnTwo: // кнопка 2 textView.setText(addSymbol("2")); break; case R.id.btnThree: // кнопка 3 textView.setText(addSymbol("3")); break; case R.id.btnFour: // кнопка 4 textView.setText(addSymbol("4")); break; case R.id.btnFive: // кнопка 5 textView.setText(addSymbol("5")); break; case R.id.btnSix: // кнопка 6 textView.setText(addSymbol("6")); break; case R.id.btnSeven: // кнопка 7 textView.setText(addSymbol("7")); break; case R.id.btnEight: // кнопка 8 textView.setText(addSymbol("8")); break; case R.id.btnNine: // кнопка 9 textView.setText(addSymbol("9")); break; case R.id.btnDot: // кнопка . if(isInputFirstArgument && !firstArgument.contains(".") || !isInputFirstArgument && !secondArgument.contains(".")) textView.setText(addSymbol(".")); break; case R.id.btnCancel: // кнопка C resetValues(); textView.setText(""); break; case R.id.btnNegative: // кнопка +/- if(isInputFirstArgument && !firstArgument.contains("-")){ firstArgument = "-" + firstArgument; textView.setText(firstArgument); }else if(isInputFirstArgument && firstArgument.contains("-")){ firstArgument = firstArgument.replace("-",""); textView.setText(firstArgument); } else if(!isInputFirstArgument && !secondArgument.contains("-")){ secondArgument = "-" + secondArgument; textView.setText(secondArgument); } else if(!isInputFirstArgument && secondArgument.contains("-")){ secondArgument = secondArgument.replace("-",""); textView.setText(secondArgument); } break; case R.id.btnPercent: // кнопка % setOperation("%"); break; case R.id.btnDivide: // кнопка / setOperation("/"); break; case R.id.btnMux: // кнопка * setOperation("*"); break; case R.id.btnMinus: // кнопка - setOperation("-"); break; case R.id.btnPlus: // кнопка + setOperation("+"); break; case R.id.btnResult: // кнопка = try{ firstArgument = calculateResult(operation); textView.setText(firstArgument); } catch (Exception ex){ System.out.println("Error!!! " + ex.getMessage()); } break; default: break; } } private void resetValues() { isInputFirstArgument = true; firstArgument = ""; secondArgument = ""; } private void setOperation(String operation) { this.operation = operation; if(isInputFirstArgument){ isInputFirstArgument = false; } else if(!isCalculatedNow){ firstArgument = calculateResult(operation); } } private String calculateResult(String operation) { double result = 0; switch (operation){ case "+": result = Double.parseDouble(firstArgument) + Double.parseDouble(secondArgument); break; case "-": result = Double.parseDouble(firstArgument) - Double.parseDouble(secondArgument); break; case "*": result = Double.parseDouble(firstArgument) * Double.parseDouble(secondArgument); break; case "/": result = Double.parseDouble(firstArgument) / Double.parseDouble(secondArgument); break; case "%": result = Double.parseDouble(firstArgument) / 100 * Double.parseDouble(secondArgument); break; } isCalculatedNow = true; return String.valueOf(result); } private String addSymbol(String addingSymbol) { if(isInputFirstArgument){ firstArgument = firstArgument + addingSymbol; return firstArgument; } else{ if(!isCalculatedNow){ secondArgument = secondArgument + addingSymbol; } else{ secondArgument = addingSymbol; isCalculatedNow = false; } return secondArgument; } } }
package com.yash.lambda; @FunctionalInterface public interface ComputeInterface { public int compute(int no1,int no2); }
package cn.okay.officialwebsitetest.otherlevelpagetest; import cn.okay.page.officialwebsite.OffciaHomePage; import cn.okay.page.officialwebsite.fourthpage.FourthPage; import cn.okay.page.officialwebsite.secondpage.ParentPage; import cn.okay.page.officialwebsite.thirdpage.ThirdPage; import cn.okay.testbase.OffcialAbstracTestCase; import org.testng.annotations.Test; /** * Created by yutz on 2018/2/5. */ public class FourthPageTest extends OffcialAbstracTestCase { @Test(testName = "FourthPageTest1",description = "点击推荐文章的第一篇文章",groups = "offcial") public void clickFirstRecommendMoudleToOtherRecommend() throws Exception { OffciaHomePage offciaHomePage =new OffciaHomePage(driver); ParentPage parentPage= offciaHomePage.clickToParentPage(); ThirdPage thirdPage =parentPage.clickToThirdPage(); FourthPage fourthPage= thirdPage.clickArticleListFirst(); fourthPage=fourthPage.clickFirstRecommendMoudle(); } @Test(testName = "FourthPageTest2",description = "点击导航链接进入首页",groups = "offcial") public void clickFirstBarToHomePage() throws Exception { OffciaHomePage offciaHomePage =new OffciaHomePage(driver); ParentPage parentPage= offciaHomePage.clickToParentPage(); ThirdPage thirdPage =parentPage.clickToThirdPage(); FourthPage fourthPage= thirdPage.clickBannerImgToFourthPage(); offciaHomePage =fourthPage.clickFirstBarBtnToHomePage(); } @Test(testName = "FourthPageTest3",description = "页面滑动到底部后点击回到顶部按钮",groups = "offcial") public void clickToPageTop() throws Exception { OffciaHomePage offciaHomePage =new OffciaHomePage(driver); ParentPage parentPage= offciaHomePage.clickToParentPage(); ThirdPage thirdPage =parentPage.clickToThirdPage(); FourthPage fourthPage= thirdPage.clickBannerImgToFourthPage(); fourthPage.clickToPageTop(); } }
package controllers; import com.google.inject.Inject; import model.User; import play.mvc.Controller; import play.mvc.Result; import repositories.UserRepository; import services.UserService; /** * Created by lamdevops on 6/24/17. */ public class UserController extends Controller{ private final UserRepository userRepository; @Inject public UserController(UserRepository userRepository) { this.userRepository = userRepository; } public Result addUser() { User user = new User.UserBuilder() .setName("Lam") .setEmail("nguyenlam@gmail.com") .setAddress("521/64 Binh Duong 1, Binh Duong") .createBuilder(); userRepository.insert(user); return ok(user.toString()); } }
package se.kth.iv1350.amazingpos.controller; import se.kth.iv1350.amazingpos.integration.*; import se.kth.iv1350.amazingpos.model.*; /** * This is the application’s only controller class. All * calls to the model pass through here. */ public class Controller { private AccountingSystem accountingSystem; private InventorySystem inventorySystem; private DiscountRegistry discountRegistry; private CustomerRegistry customerRegistry; private Printer printer; private CashCounter cashCounter; private ItemRegistry itemRegistry; private Sale sale; private ItemDescription validItem; /** * Creates a new instance. * * @param systemCreator Used to get all classes that handle external database * calls. * @param registryCreator Used to get all classes that handle customers database * * @param paymentCreator Used to get all classes that are needed to end the sale * like cash Counter and interface to printer. */ public Controller(SystemCreator systemCreator, RegistryCreator registryCreator, PaymentCreator paymentCreator) { this.accountingSystem = systemCreator.getAccountingSystem(); this.inventorySystem = systemCreator.getInventorySystem(); this.discountRegistry = registryCreator.getDiscountRegistry(); this.customerRegistry = registryCreator.getCustomerRegistry(); this.cashCounter = paymentCreator.getCashCounter(); this.printer = paymentCreator.getPrinter(); this.itemRegistry = new ItemRegistry(); } /** * Starts a new sale. This method must be called before doing anything else during a sale. */ public void startSale() { this.sale = new Sale(); } /** * Search for a item matching the specified itemIdentifier. * * @param itemIdentifier This item we are looking after if it * exists in our item registry then it will be added to sale. * @param quantity The amount of that item. * * @return A string describes sale information if item exists * or a string message if item is not invalid. */ public String scanItem(String itemIdentifier, int quantity) { validItem = itemRegistry.findItem(itemIdentifier); if (validItem!= null) { return sale.countItem(validItem, quantity); } else { return "this item is unavailable or invalid!"; } } /** * Shows the total price with VAT rate * for all item in the end of item list. * * @return A string contains the total price * and total VAt. */ public String showTotalPriceAndVAT() { return sale.updateTotalPriceAndVAT(); } /** * @param customerID represents a customer that * we looking after in customer registry. If customer exists * , it will be sended as eligible customer for discount to DiscountRegistry. * * @return A string contains the percentage rate of whole sale. */ public void discount(String customerID) { CustomerRegistry existingCust = customerRegistry.customerControl(customerID); DiscountRegistry eligibleCustomer = discountRegistry.discountControl(existingCust); sale.applyDiscount(eligibleCustomer); } /** * Handles sale payment. Updates the balance of the cash counter * where the payment was performed. Calculates change. Prints the * receipt. Updates the inventory system and accounting system. * * @param paidAmt The paid amount. * * a warning message will be printed out if the paid amount is lower * than total price. */ public void pay(Amount paidAmt) { if ((paidAmt.getAmount() - sale.getTotalPriceAfterDiscount()) >= 0){ SalePayment payment = new SalePayment(paidAmt, cashCounter); sale.pay(payment); sale.printReceipt(printer); sale.updateExternalSystem(accountingSystem, inventorySystem); } else { System.out.println("The paid amount is lower than total price"); } } /** * Get the value of sale * * @return The current sale. */ public Sale getSale() { return this.sale; } }
package com.ibisek.outlanded; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.ibisek.outlanded.storage.Templates; import com.ibisek.outlanded.storage.TemplatesDao; public class TemplateConfigurationActivity extends Activity { final int SPINNER_LAYOUT_A = android.R.layout.simple_spinner_dropdown_item; final int SPINNER_LAYOUT_B = android.R.layout.simple_list_item_1; final int SPINNER_LAYOUT_C = android.R.layout.simple_spinner_item; private Spinner spinner; private EditText templateEdit; private Button addBtn; private Button removeBtn; private TemplatesDao templatesDao; private Templates templates; private List<CharSequence> spinnerItems = new ArrayList<CharSequence>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_template_configuration); spinner = (Spinner) findViewById(R.id.spinner); templateEdit = (EditText) findViewById(R.id.templateEdit); templateEdit.setOnTouchListener(new TemplateEditOnTouchListener()); addBtn = (Button) findViewById(R.id.addBtn); removeBtn = (Button) findViewById(R.id.removeBtn); templatesDao = new TemplatesDao(this); templates = templatesDao.loadTemplates(); // spinner setup: ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, updateSpinnerItems()); adapter.setDropDownViewResource(SPINNER_LAYOUT_A); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new SpinnerItemSelectedListener()); addBtn.setOnClickListener(new AddButtonListener()); removeBtn.setOnClickListener(new RemoveBtnListener()); } @Override protected void onResume() { super.onResume(); // update selection: spinner.setSelection(templates.getSelectedIndex()); templateEdit.setText(templates.getSelectedTemplate()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.configuration, menu); return true; } private List<CharSequence> updateSpinnerItems() { spinnerItems.clear(); for (String template : templates.getTemplates()) { spinnerItems.add(template.substring(0, template.length() > 16 ? 16 : template.length()) + ".."); } return spinnerItems; } /** * Checks, whether currently listed template has been modified. If so, updates * it in the templates list. */ private void checkCurrentTemplateDirty() { int selectedTemplateIndex = templates.getSelectedIndex(); if (selectedTemplateIndex >= 0 && selectedTemplateIndex < templates.getNumTemplates()) { String templateText = templateEdit.getText().toString(); String oldTemplateText = templates.getTemplates().get(selectedTemplateIndex); // keep the template if modified if (!templateText.equals(oldTemplateText)) { templates.getTemplates().set(selectedTemplateIndex, templateText); updateSpinnerItems(); ((ArrayAdapter<CharSequence>) spinner.getAdapter()).notifyDataSetChanged(); } } } @Override public void onBackPressed() { checkCurrentTemplateDirty(); templatesDao.saveTemplates(templates); // go back to main with the information of selected template: Intent i = new Intent(this, MainActivity.class); finish(); // super.onBackPressed(); // and go back to main } private class AddButtonListener implements OnClickListener { @Override public void onClick(View v) { templates.getTemplates().add(getString(R.string.template_help)); updateSpinnerItems(); ((ArrayAdapter<CharSequence>) spinner.getAdapter()).notifyDataSetChanged(); // select the last (new) one: spinner.setSelection(templates.getNumTemplates() - 1); templateEdit.selectAll(); // select the help text String msg = getString(R.string.template_created); Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show(); } } private class RemoveBtnListener implements OnClickListener { @Override public void onClick(View v) { int selectedIndex = spinner.getSelectedItemPosition(); Log.d("", "selectedIndex=" + selectedIndex); if (templates.getNumTemplates() > 1) { // we must retain at least one // template templates.removeTemplate(selectedIndex); updateSpinnerItems(); ((ArrayAdapter<CharSequence>) spinner.getAdapter()).notifyDataSetChanged(); // select index-1 (or 0) item int newIndex = templates.getSelectedIndex(); spinner.setSelection(newIndex); templateEdit.setText(templates.getSelectedTemplate()); String msg = getString(R.string.template_removed); Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show(); } } } private class TemplateEditOnTouchListener implements OnTouchListener { @Override public boolean onTouch(View view, MotionEvent event) { // if the editor contains help text, select all: String val = templateEdit.getText().toString(); String helpText = TemplateConfigurationActivity.this.getString(R.string.template_help); if (helpText.equals(val)) templateEdit.selectAll(); return false; } } private class SpinnerItemSelectedListener implements OnItemSelectedListener { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Log.d("", String.format("onItemSelected(): pos=%s; id=%s", position, id)); checkCurrentTemplateDirty(); templates.setSelectedIndex(position); // newly selected templateEdit.setText(templates.getSelectedTemplate()); } @Override public void onNothingSelected(AdapterView<?> parent) { Log.d("", String.format("onNothingSelected(): parent=%s", parent)); } } }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * _12_IntegerToRoma */ public class _12_IntegerToRoman { private static Map<Integer, String> map; private static List<Integer> sList = new ArrayList<>(); static { sList.add(1000); sList.add(900); sList.add(500); sList.add(400); sList.add(100); sList.add(90); sList.add(50); sList.add(40); sList.add(10); sList.add(9); sList.add(5); sList.add(4); sList.add(1); map = new HashMap<>(); map.put(1000, "M"); map.put(900, "CM"); map.put(500, "D"); map.put(400, "CD"); map.put(100, "C"); map.put(90, "XC"); map.put(50, "L"); map.put(40, "XL"); map.put(10, "X"); map.put(9, "IX"); map.put(5, "V"); map.put(4, "IV"); map.put(1, "I"); } public String intToRoman(int num) { StringBuilder stringBuilder = new StringBuilder(); int anchorP = 0; while (num != 0) { for (int i = anchorP; i < 13; ++i) { int integer = sList.get(i); if (integer <= num) { stringBuilder.append(map.get(integer)); num -= integer; anchorP = i; break; } } } return stringBuilder.toString(); } }