text
stringlengths
10
2.72M
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.context.support; import java.util.LinkedHashMap; import java.util.Map; import jakarta.servlet.ServletContext; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.config.Scope; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * {@link Scope} wrapper for a ServletContext, i.e. for global web application attributes. * * <p>This differs from traditional Spring singletons in that it exposes attributes in the * ServletContext. Those attributes will get destroyed whenever the entire application * shuts down, which might be earlier or later than the shutdown of the containing Spring * ApplicationContext. * * <p>The associated destruction mechanism relies on a * {@link org.springframework.web.context.ContextCleanupListener} being registered in * {@code web.xml}. Note that {@link org.springframework.web.context.ContextLoaderListener} * includes ContextCleanupListener's functionality. * * <p>This scope is registered as default scope with key * {@link org.springframework.web.context.WebApplicationContext#SCOPE_APPLICATION "application"}. * * @author Juergen Hoeller * @since 3.0 * @see org.springframework.web.context.ContextCleanupListener */ public class ServletContextScope implements Scope, DisposableBean { private final ServletContext servletContext; private final Map<String, Runnable> destructionCallbacks = new LinkedHashMap<>(); /** * Create a new Scope wrapper for the given ServletContext. * @param servletContext the ServletContext to wrap */ public ServletContextScope(ServletContext servletContext) { Assert.notNull(servletContext, "ServletContext must not be null"); this.servletContext = servletContext; } @Override public Object get(String name, ObjectFactory<?> objectFactory) { Object scopedObject = this.servletContext.getAttribute(name); if (scopedObject == null) { scopedObject = objectFactory.getObject(); this.servletContext.setAttribute(name, scopedObject); } return scopedObject; } @Override @Nullable public Object remove(String name) { Object scopedObject = this.servletContext.getAttribute(name); if (scopedObject != null) { synchronized (this.destructionCallbacks) { this.destructionCallbacks.remove(name); } this.servletContext.removeAttribute(name); return scopedObject; } else { return null; } } @Override public void registerDestructionCallback(String name, Runnable callback) { synchronized (this.destructionCallbacks) { this.destructionCallbacks.put(name, callback); } } @Override @Nullable public Object resolveContextualObject(String key) { return null; } @Override @Nullable public String getConversationId() { return null; } /** * Invoke all registered destruction callbacks. * To be called on ServletContext shutdown. * @see org.springframework.web.context.ContextCleanupListener */ @Override public void destroy() { synchronized (this.destructionCallbacks) { for (Runnable runnable : this.destructionCallbacks.values()) { runnable.run(); } this.destructionCallbacks.clear(); } } }
package net.awesomekorean.podo.lesson.lessons; import net.awesomekorean.podo.R; import java.io.Serializable; public class Lesson31 extends LessonInit_Lock implements Lesson, LessonItem, Serializable { private String lessonId = "L_31"; private String lessonTitle = "guess (future)"; private String lessonSubTitle = "~(으)ㄹ 것 같다"; private LessonItem specialLesson = new S_Lesson14(); private Integer dayCount = 17; private String[] wordFront = {"역", "방금", "기차", "내리다", "도착하다", "늦다", "출발하다"}; private String[] wordBack = {"station", "a minute ago", "train", "get off", "arrive", "late", "depart"}; private String[] wordPronunciation = {"-", "-", "-", "-", "[도차카다]", "[늗따]", "-"}; private String[] sentenceFront = { "지금 어디예요?", "서울역이에요.", "내렸어요.", "기차에서 내렸어요.", "방금 기차에서 내렸어요.", "언제 도착해요?", "도착하다", "도착할 것 같아요.", "10분 후에 도착할 것 같아요.", "미안해요.", "저는 택시 탔어요.", "저는 방금 택시 탔어요.", "늦다", "늦을 것 같아요.", "조금 늦을 것 같아요." }; private String[] sentenceBack = { "Where are you now?", "I'm at Seoul Station.", "I got off.", "I got off from the train.", "I just got off from the train.", "When do you arrive?", "Arrive", "I think I will arrive.", "I think I will arrive in 10 minutes.", "Sorry.", "I took a taxi.", "I just took a taxi.", "late", "I think I will be late.", "I think I will be a little late." }; private String[] sentenceExplain = { "-", "-", "'내리다' -> '내리' + '어요' = '내리어요' -> '내려요'\n'내려요' -> '내려(ㅆ어)요' = '내렸어요'", "-", "In an actual conversation, you can also casually say '아까'.\n\n'아까 기차에서 내렸어요.'", "-", "-", "When you guess the future behavior, you can use '~(으)ㄹ 것 같다'.\n\n'도착하다' -> '도착하' + 'ㄹ 것 같아요' = '도착할 것 같아요'", "-", "-", "'타요' -> '타(ㅆ어)요' = '탔어요'", "= '저는 아까 택시 탔어요'", "-", "'늦다' -> '늦' + '을 것 같아요' = '늦을 것 같아요'", "-" }; private String[] dialog = { "지금 어디예요?", "서울역이에요.\n방금 기차에서 내렸어요.", "언제 도착해요?", "10분 후에 도착할 것 같아요.", "미안해요.\n저는 방금 택시 탔어요.\n조금 늦을 것 같아요." }; private int[] peopleImage = {R.drawable.male_b,R.drawable.female_p}; private int[] reviewId = {4,8,14}; @Override public String getLessonSubTitle() { return lessonSubTitle; } @Override public String getLessonId() { return lessonId; } @Override public String[] getWordFront() { return wordFront; } @Override public String[] getWordPronunciation() { return wordPronunciation; } @Override public String[] getSentenceFront() { return sentenceFront; } @Override public String[] getDialog() { return dialog; } @Override public int[] getPeopleImage() { return peopleImage; } @Override public String[] getWordBack() { return wordBack; } @Override public String[] getSentenceBack() { return sentenceBack; } @Override public String[] getSentenceExplain() { return sentenceExplain; } @Override public int[] getReviewId() { return reviewId; } // 레슨어뎁터 아이템 @Override public String getLessonTitle() { return lessonTitle; } @Override public LessonItem getSLesson() { return specialLesson; } @Override public Integer getDayCount() { return dayCount; } }
package pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; public class Logout { WebDriver driver; WebElement welcome; WebElement logout; public Logout(WebDriver driver) { this.driver = driver; } public void logout() throws InterruptedException { driver.findElement(By.id("welcome")).click(); new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Logout"))); driver.findElement(By.linkText("Logout")).click(); Thread.sleep(30); // Verify that logout returns to home page new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.id("logInPanelHeading"))); Assert.assertEquals("LOGIN Panel", driver.findElement(By.id("logInPanelHeading")).getText()); // new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.id("btnLogin"))); // Assert.assertEquals("LOGIN", driver.findElement(By.id("btnLogin")).getText()); } }
package tk.jimmywang.attendance.app.activity; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Window; /** * Created by WangJin on 2014/7/2. */ public class BaseActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_NO_TITLE); //去掉标题 } public void getLogger(String tag,String msg){ Log.d("========" + tag, msg); } }
package Problem_2480; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); // 같은 눈이 3개가 나오면 10,000원+(같은 눈)×1,000원의 상금을 받게 된다. // 같은 눈이 2개만 나오는 경우에는 1,000원+(같은 눈)×100원의 상금을 받게 된다. // 모두 다른 눈이 나오는 경우에는 (그 중 가장 큰 눈)×100원의 상금을 받게 된다. if(a == b && b == c) System.out.println(10000+a*1000); else if(a==b|| b==c || c==a) { if(a==b) System.out.println(1000 + a*100); else if(b==c) System.out.println(1000 + b*100); else if(a==c) System.out.println(1000 + c*100); } else System.out.println(Math.max(a,Math.max(b,c))*100); sc.close(); } }
package com.netcracker.app.domain.info.services.resumes; import com.netcracker.app.domain.info.entities.resumes.ResumeImpl; import com.netcracker.app.domain.info.entities.vacancies.VacancyImpl; import com.netcracker.app.domain.info.repositories.resumes.ResumeImplRepository; import com.netcracker.app.domain.info.repositories.vacancies.VacancyImplRepository; import org.springframework.stereotype.Service; @Service public class ResumeImplService extends AbstractResumeService<ResumeImpl> { private final ResumeImplRepository repository; private final VacancyImplRepository vacancyImplRepository; public ResumeImplService(ResumeImplRepository repository, VacancyImplRepository vacancyImplRepository) { super(repository); this.repository = repository; this.vacancyImplRepository = vacancyImplRepository; } @Override public ResumeImpl getById(int id) throws Exception { if (repository.existsById(id)) { return repository.getById(id); } else { throw new Exception("Doesn't exist"); } } @Override public void updateVacancyId(VacancyImpl vacancy, int id) throws Exception { if (repository.existsById(id)) { ResumeImpl resume = repository.getById(id); //resume.setVacancyId(vacancyId); resume.setVacancy(vacancy); repository.saveAndFlush(resume); } else { throw new Exception("Doesn't exist"); } } @Override public void updateFirstName(String firstName, int id) throws Exception { if (repository.existsById(id) && firstName != null) { ResumeImpl resume = repository.getById(id); resume.setFirstName(firstName); repository.saveAndFlush(resume); } else { throw new Exception("Doesn't exist"); } } @Override public void updatePhone(String phone, int id) throws Exception { if (repository.existsById(id) && phone != null) { ResumeImpl resume = repository.getById(id); resume.setPhone(phone); repository.saveAndFlush(resume); } else { throw new Exception("Doesn't exist"); } } @Override public void updateLastName(String lastName, int id) throws Exception { if (repository.existsById(id) && lastName != null) { ResumeImpl resume = repository.getById(id); resume.setLastName(lastName); repository.saveAndFlush(resume); } else { throw new Exception("Doesn't exist"); } } @Override public void updateBirthDate(String birthDate, int id) throws Exception { if (repository.existsById(id) && birthDate != null) { ResumeImpl resume = repository.getById(id); resume.setBirthday(birthDate); repository.saveAndFlush(resume); } else { throw new Exception("Doesn't exist"); } } @Override public void updateEmail(String email, int id) throws Exception { if (repository.existsById(id) && email != null) { ResumeImpl resume = repository.getById(id); resume.setEmail(email); repository.saveAndFlush(resume); } else { throw new Exception("Doesn't exist"); } } @Override public void updateText(String text, int id) throws Exception { if (repository.existsById(id) && text != null) { ResumeImpl resume = repository.getById(id); resume.setText(text); repository.saveAndFlush(resume); } else { throw new Exception("Doesn't exist"); } } }
package com.redhat.service.bridge.actions.kafkatopic; import javax.enterprise.context.ApplicationScoped; import com.redhat.service.bridge.actions.ActionParameterValidator; import com.redhat.service.bridge.actions.ValidationResult; import com.redhat.service.bridge.infra.models.actions.BaseAction; @ApplicationScoped public class KafkaTopicActionValidator implements ActionParameterValidator { public static final String INVALID_TOPIC_PARAM_MESSAGE = "The supplied topic parameter is not valid"; @Override public ValidationResult isValid(BaseAction baseAction) { if (baseAction.getParameters() != null) { String topic = baseAction.getParameters().get(KafkaTopicAction.TOPIC_PARAM); if (topic == null || topic.isEmpty()) { return ValidationResult.invalid(INVALID_TOPIC_PARAM_MESSAGE); } return ValidationResult.valid(); } return ValidationResult.invalid(); } }
package me.darkeet.android.jni; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import com.google.webp.libwebp; import java.nio.ByteBuffer; /** * Name: WebpManager * User: Lee (darkeet.me@gmail.com) * Date: 2015/12/1 16:31 * Desc: webp格式图片处理 * <p/> * https://gist.github.com/markbeaton/3719812 * https://stackoverflow.com/questions/7032695/webp-for-android */ public class WebpManager { private WebpManager() { } static { System.loadLibrary("webp"); } /** * Decodes byte array to bitmap * * @param encoded Byte array with WebP bitmap data * @return Decoded bitmap */ public static Bitmap webpToBitmap(byte[] encoded) { int[] width = new int[]{0}; int[] height = new int[]{0}; byte[] decoded = libwebp.WebPDecodeARGB(encoded, encoded.length, width, height); int[] pixels = new int[decoded.length / 4]; ByteBuffer.wrap(decoded).asIntBuffer().get(pixels); return Bitmap.createBitmap(pixels, width[0], height[0], Bitmap.Config.ARGB_8888); } /** * Encodes bitmap into byte array * * @param bitmap Bitmap * @param quality Quality, should be between 0 and 100 * @return Encoded byte array */ public static byte[] bitmapToWebp(Bitmap bitmap, int quality) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); if (bitmap.getConfig().equals(Config.ARGB_8888)) { int bytes = height * bitmap.getRowBytes(); ByteBuffer buffer = ByteBuffer.allocate(bytes); bitmap.copyPixelsToBuffer(buffer); byte[] pixels = buffer.array(); return libwebp.WebPEncodeRGBA(pixels, width, height, width * 4, quality); } else { byte[] pixels = new byte[width * height * 4]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int pixel = bitmap.getPixel(i, j); int index = (j * width + i) * 4; pixels[index] = (byte) (pixel & 0xff); pixels[index + 1] = (byte) (pixel >> 8 & 0xff); pixels[index + 2] = (byte) (pixel >> 16 & 0xff); pixels[index + 3] = (byte) (pixel >> 24 & 0xff); } } return libwebp.WebPEncodeBGRA(pixels, width, height, width * 4, quality); } } }
package projekt33.kamkk.entity.dto; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; import lombok.Data; @Data public class CardDTO { private Long id; private String question; private String secret; @JsonBackReference("cardgroup-cards") private CardGroupDTO cardGroup; private String answer; @JsonFormat( shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" ) private Date createdAt; }
package com.example.admin1.mapapplication.activity; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Toast; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.toolbox.JsonObjectRequest; import com.example.admin1.mapapplication.R; import com.example.admin1.mapapplication.Webservice.ApiConstants; import com.example.admin1.mapapplication.Webservice.CommonUtils; import com.example.admin1.mapapplication.Webservice.JsonResponse; import com.example.admin1.mapapplication.Webservice.WebRequest; import com.example.admin1.mapapplication.interfaces.ApiServiceCaller; import com.example.admin1.mapapplication.model.Map; import com.example.admin1.mapapplication.utility.App; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import java.util.ArrayList; public class ApiMapActivity extends AppCompatActivity implements ApiServiceCaller { MapView mapView; GoogleMap googleMap; public Context context; Double lat, lon; ArrayList<String> arrayList; private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_api_map); context = this; Bundle bundle = null; if (savedInstanceState != null) { bundle = savedInstanceState.getBundle(MAP_VIEW_BUNDLE_KEY); } mapView = findViewById(R.id.api_map); arrayList = new ArrayList<>(); mapView.onCreate(savedInstanceState); mapView.onResume(); try { MapsInitializer.initialize(context.getApplicationContext()); } catch (Exception e) { e.printStackTrace(); } mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap mapView) { googleMap = mapView; // For showing a move to my location button if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } googleMap.setMyLocationEnabled(true); } }); getLocation(); } public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Bundle myBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY); if (myBundle == null) { myBundle = new Bundle(); outState.putBundle(MAP_VIEW_BUNDLE_KEY, myBundle); } mapView.onSaveInstanceState(myBundle); } @Override public void onAsyncSuccess(JsonResponse jsonResponse, String label) { switch (label) { case ApiConstants.GET_DETAILS: { if (jsonResponse != null) { if (jsonResponse.result != null && jsonResponse.result.equals(JsonResponse.SUCCESS)) { if (jsonResponse.locateus.size() != 0) for (int i = 0; i < jsonResponse.locateus.size(); i++) { try { lat = Double.parseDouble(jsonResponse.locateus.get(i).locate_us_latitude.toString()); lon = Double.parseDouble(jsonResponse.locateus.get(i).locate_us_longitude.toString()); } catch (NumberFormatException e) { lat = 0.0; lon = 0.0; e.printStackTrace(); } arrayList.add(jsonResponse.locateus.get(i).getName()); LatLng latLng = new LatLng(lat, lon); Log.i("cccccc", latLng.toString()); googleMap.addMarker(new MarkerOptions().position(latLng).title(jsonResponse.locateus.get(i).name).snippet(jsonResponse.locateus.get(i).address).draggable(false)); googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15.0f)); } } } else Toast.makeText(context, "abhvjvh", Toast.LENGTH_SHORT).show(); } } } public void getLocation() { try { JsonObjectRequest request = WebRequest.callPostMethod(context, "", null, Request.Method.GET, ApiConstants.GET_DETAILS, ApiConstants.GET_DETAILS, this, ""); App.getInstance().addToRequestQueue(request, ApiConstants.GET_DETAILS); } catch (Exception e) { e.printStackTrace(); } } public void onPause() { super.onPause(); mapView.onPause(); } @Override public void onDestroy() { super.onDestroy(); mapView.onDestroy(); } @Override public void onResume() { super.onResume(); mapView.onResume(); } public void onLowMemory() { super.onLowMemory(); mapView.onLowMemory(); } @Override public void onAsyncFail(String message, String label, NetworkResponse response) { Toast.makeText(context, "fail1", Toast.LENGTH_SHORT).show(); } @Override public void onAsyncCompletelyFail(String message, String label) { Toast.makeText(context, "fail2", Toast.LENGTH_SHORT).show(); } }
package net.dryuf.bigio; import java.nio.ByteOrder; /** * Endian conversion utilities. */ public class Endian { public static final boolean IS_LITTLE_ENDIAN = ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN); public static final boolean IS_BIG_ENDIAN = ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN); public static short swapLe16(short x) { if (IS_LITTLE_ENDIAN) return x; return Short.reverseBytes(x); } public static int swapLe32(int x) { if (IS_LITTLE_ENDIAN) return x; return Integer.reverseBytes(x); } public static long swapLe64(long x) { if (IS_LITTLE_ENDIAN) return x; return Long.reverseBytes(x); } public static short swapBe16(short x) { if (IS_BIG_ENDIAN) return x; return Short.reverseBytes(x); } public static int swapBe32(int x) { if (IS_BIG_ENDIAN) return x; return Integer.reverseBytes(x); } public static long swapBe64(long x) { if (IS_BIG_ENDIAN) return x; return Long.reverseBytes(x); } }
import org.viqueen.java.bytecode.decompiler.Decompiler; import org.viqueen.java.bytecode.decompiler.JavaDecompiler; module org.viqueen.java.bytecode { exports org.viqueen.java.bytecode; exports org.viqueen.java.bytecode.cpool; exports org.viqueen.java.bytecode.decompiler; requires java.base; uses Decompiler; provides Decompiler with JavaDecompiler; }
welcome to java cck;
package tests; import static org.junit.Assert.assertEquals; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import Entities.User; import Resources.SpringConfiguration; import SocialService.SocialService; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class GetUser_TestSteps { ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfiguration.class); SocialService service; Integer postUserResult; User getResult; @Given("^User is in the database$") public void user_is_in_the_database() throws Throwable { service = ctx.getBean(SocialService.class); postUserResult = service.postUser("Maayan", "Rechtman"); } @When("^a request to get the user is made$") public void a_request_to_get_the_user_is_made() throws Throwable { service = ctx.getBean(SocialService.class); getResult = service.getUser(postUserResult); service = ctx.getBean(SocialService.class); } @Then("^the response is the correct user$") public void the_response_is_the_correct_user() throws Throwable { assertEquals("Maayan", getResult.getfirstName()); assertEquals("Rechtman", getResult.getlastName()); assertEquals(postUserResult, getResult.getid()); } }
package com.swapping.springcloud.ms.member.domain; import com.swapping.springcloud.ms.core.base.BaseBean; import lombok.Getter; import lombok.Setter; import org.apache.commons.lang3.StringUtils; import org.springframework.data.jpa.domain.Specification; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.Date; import java.util.List; @Getter @Setter @Entity @Table public class Member extends BaseBean { @Column(nullable = false) private String memberName;//会员名称 private Date birthday;//生日 private String memberPhone;//会员电话 @Column(nullable = false) private String password;//密码 public static Specification<Member> where(Member member){ return new Specification<Member>() { @Override public Predicate toPredicate(Root<Member> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { //创建查询列表 List<Predicate> predicates = new ArrayList<>(); //字段memberName是否查询 String memberName = member.getMemberName(); if (StringUtils.isNotBlank(memberName)){ predicates.add(criteriaBuilder.like(root.get("memberName"),"%"+memberName+"%")); } //字段memberPhone是否查询 String memberPhone = member.getMemberPhone(); if (StringUtils.isNotBlank(memberPhone)) { predicates.add(criteriaBuilder.equal(root.get("memberPhone"),memberPhone)); } //字段password是否查询 String password = member.getPassword(); if (StringUtils.isNotBlank(password)) { predicates.add(criteriaBuilder.equal(root.get("password"),password)); } //生日 时间查询 Date birthday = member.getBirthday(); if (birthday != null){ LocalDate localDate = birthday.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); localDate = localDate.plusDays(1); Date endDate = java.sql.Date.valueOf(localDate); predicates.add(criteriaBuilder.between(root.get("birthday"),birthday,endDate)); } return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction(); } }; } }
package com.shihang.myframe.utils; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class JsonUtil { public static <T> T getBean(String json,Class<T> t){ if(CheckUtil.isJson(json)){ Gson gson = new Gson(); return gson.fromJson(json, t); }else{ return null; } } public static <T> List<T> getList(String jsonArray,TypeToken<List<T>> typetoken){ if(CheckUtil.isJsonArray(jsonArray)){ Gson gson = new Gson(); return gson.fromJson(jsonArray, typetoken.getType()); }else{ return null; } } public static String toJson(Object obj){ Gson gson = new Gson(); return gson.toJson(obj); } public static <T> Map<String, T> getGoodsMap(String json,Class<T> t){ Gson gson = new Gson(); Map<String,T> map = gson.fromJson(json, new TypeToken<HashMap<String, T>>(){}.getType()); return map; } }
package com.flushoutsolutions.foheart.slidingmenu.model; import android.graphics.drawable.BitmapDrawable; public class NavDrawerItem { private String title; public NavDrawerItem(String title){ this.title = title; } public String getTitle(){ return this.title; } public void setTitle(String title){ this.title = title; } }
package com.pointinside.android.api.content; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; public final class UnsecureTrustManagerFactory { private static X509TrustManager sUnsecureTrustManager = new SimpleX509TrustManager(); public static X509TrustManager getTrustManager() { return sUnsecureTrustManager; } private static void logCertificates(X509Certificate[] paramArrayOfX509Certificate, String paramString, boolean paramBoolean) {} private static class SimpleX509TrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) { UnsecureTrustManagerFactory.logCertificates(paramArrayOfX509Certificate, "Trusting client", false); } public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) { UnsecureTrustManagerFactory.logCertificates(paramArrayOfX509Certificate, "Trusting server", false); } public X509Certificate[] getAcceptedIssuers() { return null; } } } /* Location: D:\xinghai\dex2jar\classes-dex2jar.jar * Qualified Name: com.pointinside.android.api.content.UnsecureTrustManagerFactory * JD-Core Version: 0.7.0.1 */
package files.service; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * Lọc các file thay đổi để upcode. */ public class FileFilter { /** * Danh sách các file thay đổi. */ private final List<String> list = new LinkedList<>(); /** * Đọc danh sách các file thay đổi từ file text thống kê. * Đẩy vào danh sách. * @param inputFilePath Đường dẫn file */ public void getListFromInputFile(String inputFilePath) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFilePath), "UTF8")); String s; while ((s = reader.readLine()) != null) { // Loại bỏ dấu cách 2 đầu s = s.trim(); // Chuyển hết về dấu / của Linux, không sử dụng dấu \ của Windows s = s.replace("\\", "/"); // Bỏ qua dòng trắng if (s.isEmpty()) { continue; } // Nếu là thay đổi xóa thì bỏ qua if (s.startsWith("deleted:") || s.startsWith("D:")) { continue; } // "git status" hiển thị như sau: // modified: app/Http/Controllers/FeedbackController.php // "git diff --name-status HEAD HEAD~3" hiển thị như sau: // M app/Http/Controllers/FeedbackController.php // Xóa các ký tự đầu tiên s = s.replaceAll("^\\S+\\s+", ""); // Thêm vào danh sách list.add(s); } reader.close(); Collections.sort(list); } /** * Lọc các file để upcode PHP. * @param rootPath Đường dẫn */ public void filterPhpWeb(String rootPath) throws Exception { String destPath = "filtered"; File sourceRoot = new File(rootPath); if (sourceRoot.exists()) { File destRoot = new File(destPath); if (!destRoot.exists()) { destRoot.mkdir(); } for (String s : list) { // Tách thư mục và tên file int index = s.lastIndexOf("/"); String sourceFolder = s.substring(0, index + 1); String sourceFile = s.substring(index + 1); File destFolder = new File(destRoot, sourceFolder); if (!destFolder.exists()) { destFolder.mkdirs(); } File oldFile = new File(sourceRoot, sourceFolder + sourceFile); File newFile = new File(destFolder, sourceFile); if (oldFile.exists()) { System.out.println("... " + sourceFolder + sourceFile); Files.copy(oldFile.toPath(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } else { System.out.println("File not found: " + oldFile.toPath()); } } } } public void filterJavaWebNetbeans(String rootPath) throws Exception { String destPath = "filtered"; final File sourceRoot = new File(rootPath); if (sourceRoot.exists()) { File destRoot = new File(destPath); if (!destRoot.exists()) { destRoot.mkdir(); } for (String s : list) { // Tách thư mục và tên file int index = s.lastIndexOf("/"); String sourceFolder = s.substring(0, index + 1); String sourceFile = s.substring(index + 1); // Thư mục Java web sinh bởi Netbeans (dist) String buildFolder; if (sourceFolder.startsWith("web")) { buildFolder = sourceFolder.replace("web/", ""); } else if (sourceFolder.startsWith("src")) { buildFolder = sourceFolder.replace("src/java/", "WEB-INF/classes/"); } else { buildFolder = sourceFolder.replace("lib/", "WEB-INF/lib/"); } // File nguồn .java sẽ được dịch ra file .class String buildFile; if (sourceFile.endsWith(".java")) { buildFile = sourceFile.replace(".java", ".class"); } else { buildFile = sourceFile; } sourceFolder = buildFolder; sourceFile = buildFile; File destFolder = new File(destRoot, sourceFolder); if (!destFolder.exists()) { destFolder.mkdirs(); } File oldFile = new File(sourceRoot, sourceFolder + sourceFile); File newFile = new File(destFolder, sourceFile); if (oldFile.exists()) { System.out.println(sourceFolder + sourceFile); Files.copy(oldFile.toPath(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } else { System.out.println("File not found: " + oldFile.getPath()); } // Copy cả các file .class của lớp con if (sourceFile.endsWith(".class")) { int idx = sourceFile.lastIndexOf("."); String fileName = sourceFile.substring(0, idx); File[] files = new File(sourceRoot, sourceFolder).listFiles(); for (File f : files) { if (f.getName().startsWith(fileName + "$")) { // System.out.println(f.getName()); newFile = new File(destFolder, f.getName()); Files.copy(f.toPath(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } } } } } } public static void main(String[] args) throws Exception { String rootPath = args[0]; FileFilter fileFilter = new FileFilter(); fileFilter.getListFromInputFile("changes.txt"); fileFilter.filterPhpWeb(rootPath); } }
package model; /** * The Class Wall. * * @author Victor Zimmermann */ public class Wall extends Element { /** * Instantiates a new wall. * * @param x * the pos x * @param y * the pos y * @param id * the id */ public Wall(int x, int y, char id) { super(x, y, id); switch(id){ case 'R' : Image = "bone.png"; break; case 'H' : Image = "horizontal_bone.png"; break; case 'V' : Image = "vertical_bone.png"; break; } } public void setSprite(String Image) { // TODO Auto-generated method stub } }
package com.fb.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateUtils{ public static final String DATETIME = "yyyy-MM-dd HH:mm:ss"; public static final String DATE = "yyyy-MM-dd"; public static final String DATEYEAR = "yyyy"; public static final String DATEMONTH = "yyyy-MM"; public static final String DATEHMS = "HH:mm:ss"; public static final String DATEHOUR = "yyyy-MM-dd-HH"; public static final String DATETIMETIGHT = "yyyyMMddHHmmss"; public static final String DATETIGHT = "yyyyMMdd"; /** * @function 将日期转换成字符串 * @param date 日期 * @return 日期字符串 */ public static String formatDate(Date date) { if(date==null){ date = Calendar.getInstance().getTime(); } return formatDate(date,DATE); } /** * @function 将日期转换成字符串 * @param dateStr 日期 * @return 日期字符串 */ public static Date parseDateTime(String dateStr) { return parseDate(dateStr,DATETIME); } /** * @function 将日期转换成字符串 * @param date 日期 * @param pattern 格式 * @return 日期字符串 */ public static String formatDate(Date date,String pattern) { SimpleDateFormat sdf = new SimpleDateFormat(pattern); return sdf.format(date); } /** * 将字符串转换为日期 * @param dateStr 日期形式的字符串 * @return 日期 */ public static Date parseDate(String dateStr){ return parseDate(dateStr,DATE); } /** * 将字符串转换为日期 * @param dateStr 日期形式的字符串 * @param pattern 日期类型 * @return 日期 */ public static Date parseDate(String dateStr,String pattern){ SimpleDateFormat sdf = new SimpleDateFormat(pattern); try { return sdf.parse(dateStr); } catch (ParseException e) { return null; } } /** * 获取n分后的日期 * @param rptdate * @param n * @return */ public static Date getTheNextMinute(Date rptdate,Integer n){ Calendar cd = Calendar.getInstance(); cd.setTime(rptdate); cd.add(Calendar.MINUTE, n); return cd.getTime(); } /** * 获取n天后的日期 * @param rptdate * @param n * @return */ public static Date getTheNextDate(Date rptdate,Integer n){ Calendar cd = Calendar.getInstance(); cd.setTime(rptdate); cd.add(Calendar.DATE, n); return cd.getTime(); } }
package net.lantrack.framework.sysbase.interceptor; import net.lantrack.framework.core.StatusCode; import net.lantrack.framework.core.entity.ReturnEntity; import net.lantrack.framework.core.entity.ReturnPage; import net.lantrack.framework.core.entity.ReturnResult; import net.lantrack.framework.core.util.GsonUtil; import net.lantrack.framework.core.util.SpringContextHolder; import net.lantrack.framework.core.util.StrUtil; import net.lantrack.framework.springplugin.controller.BaseController; import net.lantrack.framework.sysbase.entity.SysLog; import net.lantrack.framework.sysbase.model.AnnoEtl; import net.lantrack.framework.sysbase.service.SysLogService; import net.lantrack.framework.sysbase.util.UserUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.web.method.HandlerMethod; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * 保存日志 2018年1月19日 * * @author lin */ public class LogUtil extends org.apache.commons.lang3.StringUtils { static SysLogService logservice = SpringContextHolder.getBean("sysLogServiceImp"); private static int logCorePoolSize = 10; private static ThreadPoolExecutor logThreadPool; public static ThreadPoolExecutor getLogPoolInstance() { if (logThreadPool == null) { logThreadPool = new ThreadPoolExecutor(logCorePoolSize, logCorePoolSize * 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } return logThreadPool; } /** * 获得用户远程地址 */ public static String getRemoteAddr(HttpServletRequest request) { String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } if ("0:0:0:0:0:0:0:1".equals(ip)) { InetAddress host; String hostAddress = "localhost"; try { host = InetAddress.getLocalHost(); hostAddress = host.getHostAddress();// ipv4当前ip } catch (UnknownHostException e) { e.printStackTrace(); }// 本地地址 ip = hostAddress; } // System.out.println("来访的ip="+ip); return ip; } /** * 在外部调用保存日志 * * @param title * @param type * @param status 2018年1月25日 * @author lin */ public static void saveLog(String title, String type, String status,String ...err) { SysLog log = new SysLog(); log.setType(type); if ("1".equals(status)) { log.setStatus("1"); log.setMessage("成功"); } if ("2".equals(status)) { log.setStatus("2"); log.setMessage("失败"); } log.setRemoteAddr(UserUtil.getSession().getHost()); log.setTitle(title); log.setCreateBy(UserUtil.getCurrentUser()); log.setUpdateBy(UserUtil.getCurrentUser()); logservice.save(log); } /** * 保存日志 * * @throws IOException */ public static void saveLog(HttpServletRequest request, long beginTim, long endTime, Object handler) throws IOException { ReturnEntity re = null; ReturnPage rp = null; Object obj = request.getAttribute("returnEntity"); if (obj != null) { re = (ReturnEntity) obj; } else { rp = (ReturnPage) request.getAttribute("returnPage"); } // 保存系统状态码默认为正常 int status = StatusCode.SERVER_NORMAL.getCode(); String msg = StatusCode.SERVER_NORMAL.getMsg(); ReturnResult result = null; if (re != null) { status = re.getStatus(); msg = re.getMessage(); result = (ReturnResult) re.getResult(); } else if (rp != null) { status = rp.getStatus(); msg = rp.getMessage(); result = (ReturnResult) rp.getResult(); } Integer rst = 1; String rmg = "操作成功"; // 操作状态码记录, if (result != null) { rst = result.getRst(); rmg = result.getRmg(); } SysLog log = new SysLog(); // 操作结果 log.setStatus(status == 47 ? rst.toString() : "2"); log.setMessage(status == 47 ? rmg : msg); log.setRemoteAddr(getRemoteAddr(request)); log.setUserAgent(request.getHeader("user-agent")); log.setRequestUri(request.getRequestURI()); log.setParams(request.getParameterMap()); log.setMethod(request.getMethod()); log.setCreateBy(UserUtil.getCurrentUser()); // log.setStarttime(Double.longBitsToDouble(beginTim)); // log.setEndtiime(Double.longBitsToDouble(endTime)); log.setProtime((endTime - beginTim) < 0 ? 0 : (double) (endTime - beginTim) / 1000); getLogPoolInstance().execute(new SaveLogThread(log, handler)); } /** * 保存日志线程 减少开销让在线程里处理搜索数据等信息 */ public static class SaveLogThread extends Thread { private Object handler; private SysLog log; public SaveLogThread(SysLog log, Object handler) { super(SaveLogThread.class.getSimpleName()); this.handler = handler; this.log = log; } // 获取日志标题 @Override public void run() { try { if (handler instanceof HandlerMethod) { Method m = ((HandlerMethod) handler).getMethod(); LogDesc desc = m.getAnnotation(LogDesc.class); if (desc == null) { return; } log.setTitle(StrUtil.join(desc.value())); LogType logType = desc.type(); if (logType != null) { log.setType(logType.getType()); } Class model = desc.modelClass(); if (model != null && !model.equals(String.class)) { Map<String, String> fieldDesc = AnnoEtl.getFieldDesc(model); if (fieldDesc == null || fieldDesc.size() == 0) { return; } String params = log.getParams(); if (params == null) return; Map<String, String[]> paramMap = new HashMap<String, String[]>(); if (params.contains(BaseController.formdata)) { // System.out.println(params); params = params.replace(BaseController.formdata + "=", ""); Object bean = GsonUtil.getSingleBean(params, model); if (bean != null) { Method[] methods = bean.getClass().getDeclaredMethods(); for (Method method : methods) { if (StringUtils.startsWith(method.getName(), "get")) { String field = StringUtils .uncapitalize(StringUtils.substring( method.getName(), 3)); Object fieldValue = method.invoke(bean); if (fieldValue != null) { // System.out.println(field + "--" // + fieldValue); if (fieldDesc.containsKey(field)) { field = fieldDesc.get(field); } String[] fieldVal = { fieldValue.toString() }; paramMap.put(field, fieldVal); } } } } } else { String[] split = params.split("&"); for (String parm : split) { String[] parmArray = parm.split("=",-1); String fieldName = ""; String fieldValue = ""; if (parmArray.length > 1) { fieldName = parmArray[0]; fieldValue = parmArray[1]; } if (fieldDesc.containsKey(fieldName)) { fieldName = fieldDesc.get(fieldName); } String[] arrVal = { fieldValue }; paramMap.put(fieldName, arrVal); } } log.setParams(paramMap); } if (StringUtils.isNotBlank(log.getTitle())) { // 只当日志的操作标题不为空时才保存这条日志记录 String ip = log.getRemoteAddr(); if (StringUtils.isNotBlank(ip) && !"0:0:0:0:0:0:0:1".equals(ip)) { logservice.save(log); } } } } catch (Exception e) { e.printStackTrace(); } } } }
package org.craftedsw.tripservicekata.trip; class TripDAOTest { }
package com.edu.realestate.dao; import java.sql.ResultSet; import java.sql.Statement; import java.util.List; import com.edu.realestate.model.Advertisement; import com.edu.realestate.model.Favorite; import com.edu.realestate.model.Utils; public class FavoriteDaoJDBC extends AbstractDaoJDBC implements FavoriteDao { private AdvertisementDao adao; public FavoriteDaoJDBC() { adao = new AdvertisementDaoJDBC(); } @Override public void create(Favorite fav) { try { Statement st = getConnection().createStatement(); String colComments = ""; String valComments = ""; if (fav.getComments() != null) { colComments = ", `comments`"; valComments = ", '" + Utils.toUTF8(fav.getComments().replace("'", "''")) + "'"; } String req = "INSERT INTO favoris " + "(`owner`, `advertisement_id`, `priority`" + colComments +") VALUES " + "('" + fav.getUsername() + "', " + fav.getAd().getId() + ", " + fav.getPriority() + valComments + ")"; st.executeUpdate(req); } catch (Exception e) { System.out.println("UserDaoJDBC create error : " + e.getLocalizedMessage()); } } @Override public Favorite read(Integer id) { // TODO Auto-generated method stub return null; } @Override public Favorite read(String username, int advertisementId) { Favorite fav = null; try { Statement st = getConnection().createStatement(); String req = "SELECT * FROM favoris WHERE owner = '" + username + "' AND advertisement_id = " + advertisementId; ResultSet rs = st.executeQuery(req); if (rs.next()) { Advertisement ad = adao.read(advertisementId); fav = new Favorite(rs.getInt("id"), username, ad, rs.getInt("priority"), rs.getString("comments")); } } catch (Exception e) { System.out.println("FavoriteDaoJDBC read error : " + e.getLocalizedMessage()); } return fav; } @Override public void update(Favorite fav) { // TODO Auto-generated method stub } @Override public void delete(Favorite fav) { try { Statement st = getConnection().createStatement(); String req = "DELETE FROM favoris WHERE id = " + fav.getId(); st.executeUpdate(req); } catch (Exception e) { System.out.println("FavoriteDaoJDBC delete error : " + e.getLocalizedMessage()); } } @Override public boolean isFavAd(String username, int advertisementId) { return read(username, advertisementId) != null; } @Override public List<Favorite> getFavByUser(String username) { // TODO Auto-generated method stub return null; } }
package com.god.gl.vaccination.main.home.activity; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import com.god.gl.vaccination.R; import com.god.gl.vaccination.apputils.PicBean; import com.god.gl.vaccination.base.BaseActivity; import com.god.gl.vaccination.main.my.activity.SearchActivity; import com.zhy.adapter.abslistview.CommonAdapter; import com.zhy.adapter.abslistview.ViewHolder; import butterknife.BindView; /** * @author gl * @date 2018/12/7 * @desc */ public class MoreActivity extends BaseActivity { @BindView(R.id.listView) ListView mListView; @Override protected int getActivityViewById() { return R.layout.activity_more; } @Override protected void initView(Bundle savedInstanceState) { mListView.setAdapter(new CommonAdapter<PicBean.ListBean>(mContext,R.layout.item_more,PicBean.getList()) { @Override protected void convert(ViewHolder viewHolder, PicBean.ListBean item, int position) { TextView tvName = viewHolder.getView(R.id.tv_name); tvName.setText(item.name); Drawable left = mContext.getResources().getDrawable(item.picRes); left.setBounds(0, 0, left.getMinimumWidth(), left.getMinimumHeight()); tvName.setCompoundDrawables(left, null, null, null); } }); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { switch (position){ case 0: startActivity(new Intent(mContext, RegistrationInfoActivity.class)); break; case 1: startActivity(new Intent(mContext, VacciantionRemindActivity.class)); break; case 2: startActivity(new Intent(mContext, SearchActivity.class)); break; case 3: startActivity(new Intent(mContext, EducationActivity.class)); break; case 4: startActivity(new Intent(mContext, DailyHealthActivity.class)); break; case 5: startActivity(new Intent(mContext, AttentionActivity.class) ); break; case 6: startActivity(new Intent(mContext, ProductsActivity.class) ); break; } } }); } @Override protected void handleData() { } }
package ru.job4j.tracker; public class TrackerSingleEager { private final static TrackerSingleEager INSTANCE = new TrackerSingleEager(); private TrackerSingleEager() { } public static TrackerSingleEager getInstance() { return INSTANCE; } public Item add(Item model) { return model; } }
package com.example.smklabusta.Model; import com.google.gson.annotations.SerializedName; public class PesanItem{ @SerializedName("id_chat") private String idChat; @SerializedName("pesan") private String pesan; @SerializedName("response_pesan") private String response_pesan; @SerializedName("created_at") private String createdAt; public void setIdChat(String idChat){ this.idChat = idChat; } public String getIdChat(){ return idChat; } public void setPesan(String pesan){ this.pesan = pesan; } public String getPesan(){ return pesan; } public String getResponse_pesan() { return response_pesan; } public void setResponse_pesan(String response_pesan) { this.response_pesan = response_pesan; } public void setCreatedAt(String createdAt){ this.createdAt = createdAt; } public String getCreatedAt(){ return createdAt; } }
package com.machao.base.service.imp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Service; import com.machao.base.dao.RoleRepository; import com.machao.base.model.persit.Role; import com.machao.base.service.RoleService; @Service public class RoleServiceImp extends BaseServiceImp<Role, Integer> implements RoleService { @Autowired private RoleRepository roleRepository; @Override public JpaRepository<Role, Integer> obtainJpaRepository() { return roleRepository; } }
package com.j1902.shopping.service.impl; import com.j1902.shopping.mapper.ItemMapper; import com.j1902.shopping.mapper.UserMapper; import com.j1902.shopping.pojo.Item; import com.j1902.shopping.pojo.User; import com.j1902.shopping.service.ItemPagService; import com.sun.mail.imap.protocol.ID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ItemPagServiceImpl implements ItemPagService { @Autowired ItemMapper itemMapper; @Autowired UserMapper userMapper; @Override public Item getById(Integer id) { Item item = itemMapper.selectByPrimaryKey(id); return item; } @Override public void updateById(User user) { userMapper.updateByPrimaryKey(user); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nz.ac.aut.prog2.minesweeper.ui; import nz.ac.aut.prog2.minesweeper.model.MineWorld; /** * * @author User */ public class main { public static void main (String[] args) { MineWorld world = new MineWorld(10, 10); final MineSweeperUI ui = new MineSweeperUI(world); java.awt.EventQueue.invokeLater(new Runnable(){ @Override public void run() { ui.setVisible(true); } }); } }
package com.mingrisoft; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.EventQueue; import java.awt.Font; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; public class HorizontalMenuTest extends JFrame { private static final long serialVersionUID = 1686879401938151474L; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { HorizontalMenuTest frame = new HorizontalMenuTest(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public HorizontalMenuTest() { setTitle("\u7EB5\u5411\u83DC\u5355\u680F"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); Container contentPane = getContentPane(); contentPane.setBackground(Color.WHITE); JMenuBar menuBar = new JMenuBar(); menuBar.setLayout(new BoxLayout(menuBar, BoxLayout.PAGE_AXIS)); contentPane.add(menuBar, BorderLayout.WEST); JMenu fileMenu = new HorizontalMenu("文件(F)"); fileMenu.setFont(new Font("微软雅黑", Font.PLAIN, 16)); fileMenu.add("新建(N)"); fileMenu.add("打开(O)..."); fileMenu.add("保存(S)"); fileMenu.add("另存为(A)..."); fileMenu.add("页面设置(U)..."); fileMenu.add("打印(P)..."); fileMenu.add("退出(X)"); menuBar.add(fileMenu); JMenu editMenu = new HorizontalMenu("编辑(E)"); editMenu.setFont(new Font("微软雅黑", Font.PLAIN, 16)); editMenu.add("撤销(U)"); editMenu.add("剪切(T)"); editMenu.add("复制(C)"); editMenu.add("粘贴(P)"); editMenu.add("删除(L)"); editMenu.add("查找(F)..."); editMenu.add("查找下一个(N)"); editMenu.add("替换(R)..."); editMenu.add("转到(G)..."); editMenu.add("全选(A)"); editMenu.add("时间/日期(D)"); menuBar.add(editMenu); JMenu formatMenu = new HorizontalMenu("格式(O)"); formatMenu.setFont(new Font("微软雅黑", Font.PLAIN, 16)); formatMenu.add("自动换行(W)"); formatMenu.add("字体(F)..."); menuBar.add(formatMenu); JMenu viewMenu = new HorizontalMenu("查看(V)"); viewMenu.setFont(new Font("微软雅黑", Font.PLAIN, 16)); viewMenu.add("状态栏(S)"); menuBar.add(viewMenu); JMenu helpMenu = new HorizontalMenu("帮助(H)"); helpMenu.setFont(new Font("微软雅黑", Font.PLAIN, 16)); helpMenu.add("查看帮助(H)"); helpMenu.add("关于记事本(A)"); menuBar.add(helpMenu); } }
package entity.mob.snake.weapon; import java.awt.Image; import main.Pictures; import entity.mob.snake.weapon.shell.Flame; public class Flamer extends Weapon { private static double flameSpeed = 16; @Override public void use(double angle) { double angle1; for(int q=0;q<3;q++) { angle1 = angle+Math.PI*(Math.random()-0.5)/6; new Flame().init(owner.getCX(), owner.getCY(), Math.cos(angle1)*flameSpeed, Math.sin(angle1)*flameSpeed, 0, 0, owner.getWorld(), owner); } } @Override protected void initPictures() { img = Pictures.flame_item; } }
package Movement; import GameControls.GameInfo; import Utilities.Coordinates; public class Random implements Movement{ double angle; double xVel; double yVel; double vel; public Random(){ angle = Math.random()*360; setVelocities(); } public Random(double angle, double vel){ this.angle=angle; this.vel=vel; setVelocities(); } public void setVelocities(){ xVel = Math.sin(angle)*vel; yVel = Math.cos(angle)*vel; } public Coordinates move(double xLoc, double yLoc, double vel) { if(this.vel!=vel){ this.vel=vel; setVelocities(); } xLoc += xVel; yLoc += yVel; if(xLoc>GameInfo.xEnd){ //bounce x axis xVel=-xVel; xLoc=GameInfo.xEnd+xVel; } if(xLoc<GameInfo.xBegin){ xVel=-xVel; xLoc=GameInfo.xBegin+xVel; } if(yLoc<GameInfo.yBegin){ //bounce y axis yVel=-yVel; yLoc = GameInfo.yBegin+yVel; } if(yLoc>GameInfo.yEnd){ yVel=-yVel; yLoc = GameInfo.yEnd+yVel; } return new Coordinates(xLoc, yLoc); } }
/** * File : Student.java * * Author : Elena Villalón * * Contents : Calculates for Collection of videos the StudentTest * for each of the video and the video 'totest', which is one * index in the Collection. Those videos that * have significant levels larger than alpha as defined in * StudentTest.java are may be similar to the test video. * Because the Student distribution is base on * normality of the data we perform another test among those * videos that are similar. We may also calculate the rank of the * matrices for the test video and all others similar to it. * * * Use: StudentTestPaired.java, SVDMat.java * */ package jalgo; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import jclient.VideoFile; import jmckoi.MatrixRetrieve; import org.apache.commons.math.MathException; import Jama.Matrix; public class Student { private List<String> thevideos = new ArrayList<String>(); private static final int RED =0; private static final int GREEN =1; private static final int BLUE =2; static boolean [][] signLevelG; static boolean [][] signLevelB; static boolean [][] signLevelR; static private int totest =0; //index of array to test against other videos static boolean matProj=false; private boolean weight = true; private boolean calculateRnk = false; //Results of test after completing main private static StringBuffer res[]= new StringBuffer[4] ; private static Logger mLog = Logger.getLogger(Student.class.getName()); private boolean debug = true; public void setTotest(int t){ totest =t; } public void setmatProj(boolean b){ matProj =b; } public static StringBuffer[] getRes(){ return res; } public void setWeight(boolean b){ weight = b; } public Student(boolean b){ if(!debug) mLog.setLevel(Level.WARNING); weight=b; } public Student(String args[], boolean wght) throws MathException{ if(!debug) mLog.setLevel(Level.WARNING); //true is for the mean otherwise it is the median MatrixRetrieve vstore = new MatrixRetrieve("TbVideoColt", wght, true); List<String> similar = new ArrayList<String>(); //videos are input as arguments of main if(args.length > 1) { vstore.retreiveMat(args); for(int a=0; a < args.length; ++a) thevideos.add(args[a]); } int cnt = args.length; //videos are input in a file if (args.length == 1){ //reading from file args[0].trim(); thevideos = VideoFile.readFile(args[0]); String [] argsf = thevideos.toArray(new String[thevideos.size()]); vstore.retreiveMat(argsf); cnt = argsf.length; } // int sz = thevideos.size(); String testvid = thevideos.get(totest); List<String> pass = new ArrayList<String>(); pass.addAll(thevideos); StudentTestPaired driver = new StudentTestPaired(pass, totest, wght); try{ StringBuffer r[] = driver.meanDifTest(vstore, true, totest); for(int k=0; k<3; ++k) this.res[k]=r[k]; }catch(MathException err){ } String rnkString; signLevelG = StudentTestPaired.getSignfLevelGreen(); signLevelB = StudentTestPaired.getSignfLevelBlue(); signLevelR = StudentTestPaired.getSignfLevelRed(); vstore.allFrmTest(vstore); Matrix [] blue = vstore.getMatB(); Matrix [] green = vstore.getMatG(); Matrix [] red = vstore.getMatR(); if(calculateRnk) similar = calculateSimRnk(testvid, red, green, blue); String toprint="\n\nTest video: "+ testvid + "\nStudent test at significant level= " + StudentTestPaired.alpha; if(calculateRnk){ String mess = "\nRGB video matrices with same ranks as test video matrices are: \n"; toprint =toprint + mess; } StringBuffer sim =new StringBuffer(toprint); if(calculateRnk){ for(String str: similar){ toprint+=str+"\t"; sim.append("\n"+str); } res[3] = sim; }else res[3]= new StringBuffer("\n\nNo rank calculations performed"); mLog.info(toprint); } public List<String> calculateSimRnk(String testvid,Matrix [] red, Matrix [] green, Matrix [] blue){ Matrix btest = blue[totest]; Matrix rtest = red[totest]; Matrix gtest = green[totest]; Matrix svdbtest=btest; Matrix svdrtest=rtest; Matrix svdgtest=gtest; int [] rnktest = new int[3]; boolean svd=false; boolean [] ind = new boolean[thevideos.size()]; boolean flag = false; int cnt=-1; for(int nn=0; nn <thevideos.size()-1;++nn ){ cnt++; if (nn == totest) { ind[cnt]=true; continue; } boolean mismo = signLevelR[cnt][0] && signLevelG[cnt][0] && signLevelB[cnt][0]; if(mismo) { svd = true; ind[cnt]= true; if(!flag){ SVDMat bt =new SVDMat(btest); rnktest[BLUE] = bt.rnk; //btest.rank(); svdbtest = bt.rnkBase; SVDMat rt = new SVDMat(rtest); rnktest[RED] = rt.rnk; //rtest.rank(); svdrtest = rt.rnkBase; SVDMat gt = new SVDMat(gtest); rnktest[GREEN] = gt.rnk; //gtest.rank(); svdgtest = gt.rnkBase; flag = true; } } } List<String> similarurl = new ArrayList<String>(); if(!flag){ prUsage("No similar videos found"); return(similarurl); } Matrix[]redSVD = new Matrix[thevideos.size()-1]; Matrix[]greenSVD = new Matrix[thevideos.size()-1]; Matrix[]blueSVD = new Matrix[thevideos.size()-1]; cnt=-1; for(int nn=0; nn <thevideos.size();++nn ){ cnt++; if(!ind[cnt]|| nn == totest) continue; if(signLevelR[cnt][0]){ Matrix tmpr = new Matrix(red[cnt].getArrayCopy()); SVDMat rt = new SVDMat(tmpr); redSVD[cnt]= rt.rnkBase; if( rt.rnk != rnktest[RED]) signLevelR[cnt][0] = false;//change to non-similar if not same rank } if(signLevelG[cnt][0]){ Matrix tmpg = new Matrix(green[cnt].getArrayCopy()); SVDMat gt = new SVDMat(tmpg); greenSVD[cnt]= gt.rnkBase; if( gt.rnk != rnktest[GREEN]) signLevelG[cnt][0] = false; } if(signLevelB[cnt][0]){ Matrix tmpb = new Matrix(blue[cnt].getArrayCopy()); SVDMat bt = new SVDMat(tmpb); blueSVD[cnt]= bt.rnkBase; if( bt.rnk != rnktest[BLUE]) signLevelB[cnt][0] = false; } } cnt=0; for(int nn=0; nn <thevideos.size();++nn ){ boolean mismo = signLevelR[cnt][0] && signLevelG[cnt][0] && signLevelB[cnt][0]; cnt++; if(mismo){ String url = thevideos.get(nn); similarurl.add( url); } } return similarurl; } public static void prUsage(String mess) { String mess2 = "Wrong number of frames in MedianTest"; JOptionPane.showMessageDialog(null, mess, "Median Failed", JOptionPane.ERROR_MESSAGE); mLog.warning(mess); } public static void main(String[] args) throws SQLException, MathException{ if(args.length<=0){ prUsage("StudentTest provide the videos to test"); return; } //Assume that we have weighted means Student sv =new Student(true); Student driver = new Student(args, sv.weight); for(int n=0; n <driver.res.length; ++n) mLog.info(driver.res[n].toString()+""); return; } }
/** * This class is generated by jOOQ */ package schema.tables; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Identity; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.TableImpl; import schema.BitnamiEdx; import schema.Keys; import schema.tables.records.ShoppingcartInvoiceRecord; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.4" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class ShoppingcartInvoice extends TableImpl<ShoppingcartInvoiceRecord> { private static final long serialVersionUID = 1949780199; /** * The reference instance of <code>bitnami_edx.shoppingcart_invoice</code> */ public static final ShoppingcartInvoice SHOPPINGCART_INVOICE = new ShoppingcartInvoice(); /** * The class holding records for this type */ @Override public Class<ShoppingcartInvoiceRecord> getRecordType() { return ShoppingcartInvoiceRecord.class; } /** * The column <code>bitnami_edx.shoppingcart_invoice.id</code>. */ public final TableField<ShoppingcartInvoiceRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.created</code>. */ public final TableField<ShoppingcartInvoiceRecord, Timestamp> CREATED = createField("created", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.modified</code>. */ public final TableField<ShoppingcartInvoiceRecord, Timestamp> MODIFIED = createField("modified", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.company_name</code>. */ public final TableField<ShoppingcartInvoiceRecord, String> COMPANY_NAME = createField("company_name", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.company_contact_name</code>. */ public final TableField<ShoppingcartInvoiceRecord, String> COMPANY_CONTACT_NAME = createField("company_contact_name", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.company_contact_email</code>. */ public final TableField<ShoppingcartInvoiceRecord, String> COMPANY_CONTACT_EMAIL = createField("company_contact_email", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.recipient_name</code>. */ public final TableField<ShoppingcartInvoiceRecord, String> RECIPIENT_NAME = createField("recipient_name", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.recipient_email</code>. */ public final TableField<ShoppingcartInvoiceRecord, String> RECIPIENT_EMAIL = createField("recipient_email", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.address_line_1</code>. */ public final TableField<ShoppingcartInvoiceRecord, String> ADDRESS_LINE_1 = createField("address_line_1", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.address_line_2</code>. */ public final TableField<ShoppingcartInvoiceRecord, String> ADDRESS_LINE_2 = createField("address_line_2", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.address_line_3</code>. */ public final TableField<ShoppingcartInvoiceRecord, String> ADDRESS_LINE_3 = createField("address_line_3", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.city</code>. */ public final TableField<ShoppingcartInvoiceRecord, String> CITY = createField("city", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.state</code>. */ public final TableField<ShoppingcartInvoiceRecord, String> STATE = createField("state", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.zip</code>. */ public final TableField<ShoppingcartInvoiceRecord, String> ZIP = createField("zip", org.jooq.impl.SQLDataType.VARCHAR.length(15), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.country</code>. */ public final TableField<ShoppingcartInvoiceRecord, String> COUNTRY = createField("country", org.jooq.impl.SQLDataType.VARCHAR.length(64), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.total_amount</code>. */ public final TableField<ShoppingcartInvoiceRecord, Double> TOTAL_AMOUNT = createField("total_amount", org.jooq.impl.SQLDataType.DOUBLE.nullable(false), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.course_id</code>. */ public final TableField<ShoppingcartInvoiceRecord, String> COURSE_ID = createField("course_id", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.internal_reference</code>. */ public final TableField<ShoppingcartInvoiceRecord, String> INTERNAL_REFERENCE = createField("internal_reference", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.customer_reference_number</code>. */ public final TableField<ShoppingcartInvoiceRecord, String> CUSTOMER_REFERENCE_NUMBER = createField("customer_reference_number", org.jooq.impl.SQLDataType.VARCHAR.length(63), this, ""); /** * The column <code>bitnami_edx.shoppingcart_invoice.is_valid</code>. */ public final TableField<ShoppingcartInvoiceRecord, Byte> IS_VALID = createField("is_valid", org.jooq.impl.SQLDataType.TINYINT.nullable(false), this, ""); /** * Create a <code>bitnami_edx.shoppingcart_invoice</code> table reference */ public ShoppingcartInvoice() { this("shoppingcart_invoice", null); } /** * Create an aliased <code>bitnami_edx.shoppingcart_invoice</code> table reference */ public ShoppingcartInvoice(String alias) { this(alias, SHOPPINGCART_INVOICE); } private ShoppingcartInvoice(String alias, Table<ShoppingcartInvoiceRecord> aliased) { this(alias, aliased, null); } private ShoppingcartInvoice(String alias, Table<ShoppingcartInvoiceRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public Schema getSchema() { return BitnamiEdx.BITNAMI_EDX; } /** * {@inheritDoc} */ @Override public Identity<ShoppingcartInvoiceRecord, Integer> getIdentity() { return Keys.IDENTITY_SHOPPINGCART_INVOICE; } /** * {@inheritDoc} */ @Override public UniqueKey<ShoppingcartInvoiceRecord> getPrimaryKey() { return Keys.KEY_SHOPPINGCART_INVOICE_PRIMARY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<ShoppingcartInvoiceRecord>> getKeys() { return Arrays.<UniqueKey<ShoppingcartInvoiceRecord>>asList(Keys.KEY_SHOPPINGCART_INVOICE_PRIMARY); } /** * {@inheritDoc} */ @Override public ShoppingcartInvoice as(String alias) { return new ShoppingcartInvoice(alias, this); } /** * Rename this table */ public ShoppingcartInvoice rename(String name) { return new ShoppingcartInvoice(name, null); } }
package two.essential; import java.util.StringTokenizer; /** * @author O. Tedikova * @version 1.0 */ public class TextRepresenter { public static String representText(String source) { StringTokenizer tokenizer = new StringTokenizer(source, " .\t\r\n", true); StringBuilder result = new StringBuilder(source.length()); boolean fullStop = true; while (tokenizer.hasMoreTokens()) { String nextToken = tokenizer.nextToken(); if (!isDelimiter(nextToken)) { if (!isAcronym(nextToken)) { nextToken = fullStop ? toMixedCase(nextToken) : nextToken.toLowerCase(); } fullStop = false; } else { if (".".equals(nextToken)) { fullStop = true; } } result.append(nextToken); } return result.toString(); } public static boolean isDelimiter(String token) { if (token.length() > 1) { return false; } else { switch (token.charAt(0)) { case ' ': case '\t': case '\r': case '\n': case '.': return true; default: return false; } } } public static boolean isAcronym(String word) { for (int i = 0; i < word.length(); i++) { if (!Character.isUpperCase(word.charAt(i))) { return false; } } return true; } public static String toMixedCase(String word) { char[] chars = new char[word.length()]; chars[0] = Character.toUpperCase(word.charAt(0)); for (int i = 1; i < chars.length; i++) { chars[i] = Character.toLowerCase(word.charAt(i)); } return new String(chars); } }
package cn.soulutions.phoneKeyBoard; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Scanner; /** * 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合,按照字典序升序排序,如果有重复的结果需要去重 * * 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。 * * * * 输入描述: * 输入2-9数字组合, 字符串长度 1<=length<=20 * * 输出描述: * 输出所有组合 * * 输入例子1: * 23 * * 输出例子1: * [ad, ae, af, bd, be, bf, cd, ce, cf] * * 输入例子2: * 92 * * 输出例子2: * [wa, wb, wc, xa, xb, xc, ya, yb, yc, za, zb, zc] * * 输入例子3: * 458 * * 输出例子3: * [gjt, gju, gjv, gkt, gku, gkv, glt, glu, glv, hjt, hju, hjv, hkt, hku, hkv, hlt, hlu, hlv, ijt, iju, ijv, ikt, iku, ikv, ilt, ilu, ilv] * * @author Chay * @date 2020/3/20 18:18 */ public class PhoneKeyBoardTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String input = sc.next(); System.out.println(solution(input)); } //对照表 public final static Map<String, String> CHECK_LIST = new HashMap<String, String>(8) {{ put("2", "abc"); put("3", "def"); put("4", "ghi"); put("5", "jkl"); put("6", "mno"); put("7", "pqrs"); put("8", "tuv"); put("9", "wxyz"); }}; /** * 采用递归思想,f(n)=n的全部情况*f(n-1) * * @param input * @return */ public static LinkedList<String> solution(String input) { //LinkedList链表方便扩容 LinkedList<String> result = new LinkedList<String>(); if (input.length() == 1) { String values = CHECK_LIST.get(input); char[] chars = values.toCharArray(); for (char c : chars) { result.add(String.valueOf(c)); } return result; } char[] chars = input.toCharArray(); //每次取第一个 String iTemp = CHECK_LIST.get(String.valueOf(chars[0])); char[] iChars = iTemp.toCharArray(); //递归后面的字符串 LinkedList<String> lastResult = solution(input.substring(1)); for(char c : iChars) { for (String s : lastResult) { result.add(String.valueOf(c) + s); } } return result; } }
package com.exam.dao; import com.exam.models.Post; import java.util.List; public interface PostDAO extends BaseDAO<Post, Long> { /** * Метод вовращает список постов на стене пользователя, ограниченный параметрами. * @param id идентификатор пользователя * @param offset начало отсчёта в списке результатов * @param limit ограничение записей * @return List of Posts */ List<Post> getByRecipient(Long id, int offset, int limit); /** * Вовращает количество постов на стене пользователя. * @param id идентефикатор пользователя * @return количество постов */ long getRows(Long id); }
package Revise.trees; /** Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. */ class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; } public ListNode() { } } public class SortedListToBST { public static TreeNode sortedListToBST(ListNode head) { if (head == null) return null; return sortedListToBSTRecursion(head, null); } public static TreeNode sortedListToBSTRecursion(ListNode head, ListNode tail) { if (head == tail) return null; ListNode sp = head; ListNode fp = head; while (fp != tail && fp.next != tail) { sp = sp.next; fp = fp.next.next; } TreeNode node = new TreeNode(sp.val); node.left = sortedListToBSTRecursion(head, sp); node.right = sortedListToBSTRecursion(sp.next, tail); return node; } public static ListNode buildLinkedList(int a[], ListNode l) { if(a.length == 0) return null; l = new ListNode(-1); ListNode t = l; for(int a1 : a) { t.next = new ListNode(a1); t = t.next; } return l.next; } public static void main(String a[]) { ListNode list = buildLinkedList(new int[]{4, 5, 7, 9}, new ListNode()); TreeNode result = sortedListToBST(list); System.out.println(result); } }
package com.mario.bean.odata; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.olingo.odata2.annotation.processor.core.util.AnnotationHelper.AnnotatedNavInfo; import org.springframework.beans.factory.annotation.Autowired; import com.mario.bean.Lecture; import com.mario.bean.repo.LectureRepo; import com.sap.dbs.dbx.i068191.annotation.processor.core.datasource.ODataInterface; import lombok.extern.slf4j.Slf4j; @Slf4j public class LectureODataAgent implements ODataInterface{ @Autowired LectureRepo lectureRepo; public List<?> getEntitySet(){ return lectureRepo.findAll(); } @Override public Object getEntity(Map<String, ?> keys) { log.debug("getEntity called"); Integer id = (Integer) keys.get("Id"); log.debug("getEntity id is " + id.intValue()); return lectureRepo.findById(id); } @Override public List<?> getRelatedEntity(Object source, String relatedEntityName, Map<String, Object> keys, Field sourceField) { return new ArrayList<>(); } @Override public void createEntity(Object dataToCreate) { log.debug("createEntity called"); Lecture p = (Lecture)dataToCreate; if (!lectureRepo.exists(p.getId())) { lectureRepo.save((Lecture)dataToCreate); } } @Override public void deleteEntity(Map<String, ?> keys) { log.debug("deleteEntity called"); Integer id = (Integer)keys.get("Id"); lectureRepo.delete(id); } @Override public void updateEntity(Object dataToUpdate) { log.debug("updateEntity called"); Lecture p = (Lecture)dataToUpdate; lectureRepo.save(p); } }
package treesngraphs; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Queue; public class NoLoops { public static boolean canFinish(int numCourses, int[][] prerequisites) { if (prerequisites.length == 0 || numCourses == 0) { return true; } HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>(); for (int[] prereq : prerequisites) { int course = prereq[0]; ArrayList<Integer> required; if (map.containsKey(course)) { required = map.get(course); } else { required = new ArrayList<Integer>(); } required.add(prereq[1]); map.put(course, required); } int[] visited = new int[numCourses]; for (int course : map.keySet()) { if(visited[course] != 2){ if(!dfsNotLoop(visited,map,course)) return false; } } return true; } private static boolean dfsNotLoop(int[] visited, HashMap<Integer, ArrayList<Integer>> map, int start) { if (visited[start] == 1) return false; visited[start] = 1; if (map.get(start) != null) { for (int r : map.get(start)) { if (visited[r] == 2) continue; if (!dfsNotLoop(visited, map, r)) return false; } } visited[start] = 2; return true; } public static int[] findOrder(int numCourses, int[][] prerequisites) { if (numCourses == 0) return new int[0]; int[] numPrereqs = new int[numCourses]; for(int[] prereq: prerequisites) numPrereqs[prereq[0]]++; // Enqueue all courses without prerequisites Queue<Integer> queue = new LinkedList<Integer>(); for(int course=0; course<numCourses;course++ ){ if(numPrereqs[course]==0) queue.offer(course); } ArrayList<Integer> result = new ArrayList<Integer>(); while (!queue.isEmpty()){ int course = queue.poll(); result.add(course); for(int[] prereq : prerequisites){ if(prereq[1] == course){ numPrereqs[prereq[0]]--; if(numPrereqs[prereq[0]] == 0){ queue.offer(numPrereqs[prereq[0]]); } } } } if (result.size() != numCourses) return new int[0]; int[] arr = new int[result.size()]; for(int i = 0; i < result.size(); i++) { arr[i] = result.get(i); } return arr; } }
package com.luosnn.tv; import cn.bmob.v3.BmobObject; /** * Created by 罗什什 on 2017/11/29. */ public class Bug extends BmobObject { String string; String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getString() { return string; } public void setString(String string) { this.string = string; } }
package com.decitone.mvp.mvp.presenter; import com.decitone.mvp.mvp.contract.UserContract; import com.decitone.mvp.mvp.model.entity.User; import com.jess.arms.mvp.BasePresenter; import com.jess.arms.mvp.IPresenter; import javax.inject.Inject; /** * Created by Administrator on 2017/6/14. */ public class UserPresenter extends BasePresenter<UserContract.Model ,UserContract.View> implements IPresenter{ @Inject public UserPresenter(UserContract.Model model, UserContract.View rootView) { super(model ,rootView); } public void requestUser(int id) { mModel.getUser(id); } }
package com.bitlab.constant; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.bitlab.connect.data.NodeHashMap; import com.bitlab.message.data.IPv6; import com.bitlab.message.data.NetAddr; import com.bitlab.util.ByteUtils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class Constants { private Constants () { } public static final int THREADS = 3;// Ilość wątków do obsługi połączeń /* Size of message */ public static final int DEFAULT_SIZE_OF_HEADER = 24; public static final int DEFAULT_SIZE_OF_VERSION = 85; /* Never change */ public static final int START_STRING = 0xf9beb4d9; // Main_net public static final int EMPTY_HASH = 0x5df6e0e2; // SHA256(SHA256("")); public static final int BUFFER_SIZE = 33554432; // 32MB public static final NodeType[] NODE_TYPES = NodeType.values(); public static final InvType[] INV_TYPES = InvType.values(); public static final int MSG_WITNESS_FLAG = 1 << 30; public static final int MSG_TYPE_MASK = 0xffffffff >> 2; /* Note that of those with the service bits flag, most only support a subset of possible options */ /* https://github.com/bitcoin/bitcoin/blob/master/src/chainparams.cpp */ public static final String[] SEED_DNS = { "seed.bitcoin.sipa.be", // Pieter Wuille, only supports x1, x5, x9, and xd "dnsseed.bluematt.me", // Matt Corallo, only supports x9 "dnsseed.bitcoin.dashjr.org", // Luke Dashjr "seed.bitcoinstats.com", // Christian Decker, supports x1 - xf "seed.bitcoin.jonasschnelli.ch", // Jonas Schnelli, only supports x1, x5, x9, and xd "seed.btc.petertodd.org" // Peter Todd, only supports x1, x5, x9, and xd }; /* Properties */ public static int PROTOCOL_VERSION; public static long NODE_TYPE; public static byte[] USER_AGENT; public static int USER_AGENT_BYTE; public static boolean DEBUG; public static int GOAL; /* Late init */ public static long NONCE; static { Properties properties = null; try { File data = new File("data"); if(!data.exists()) data.mkdir(); properties = new Properties(); InputStream is = new FileInputStream("setting.properties"); properties.load(is); is.close(); } catch (IOException e) { System.out.println("Setting.properties is missing or fail to mkdir"); System.exit(0); } for(String key : properties.stringPropertyNames()) { String property = properties.getProperty(key); switch (key) { case "USER_AGENT": USER_AGENT = ByteUtils.stringToBytes(property); USER_AGENT_BYTE = USER_AGENT.length; break; case "PROTOCOL_VERSION": PROTOCOL_VERSION = Integer.parseInt(property); break; case "NODE_TYPE": NODE_TYPE = Long.parseLong(property, 2); break; case "DEBUG": DEBUG = Boolean.parseBoolean(property); break; case "GOAL": GOAL = Integer.parseInt(property); break; } } } }
package org.vanilladb.comm.protocols.tcpfd; import org.vanilladb.comm.protocols.events.ProcessListInit; import net.sf.appia.core.Layer; import net.sf.appia.core.Session; import net.sf.appia.protocols.common.RegisterSocketEvent; import net.sf.appia.protocols.tcpcomplete.TcpUndeliveredEvent; public class TcpFailureDetectionLayer extends Layer { public TcpFailureDetectionLayer() { // Events that the protocol will create evProvide = new Class[] { Heartbeat.class, NextHeartbeat.class, FailureDetected.class, ProcessConnected.class, }; // Events that the protocol requires to work // This is a subset of the accepted events evRequire = new Class[] { ProcessListInit.class, RegisterSocketEvent.class, TcpUndeliveredEvent.class, }; // Events that the protocol will accept evAccept = new Class[] { ProcessListInit.class, RegisterSocketEvent.class, Heartbeat.class, NextHeartbeat.class, TcpUndeliveredEvent.class, }; } @Override public Session createSession() { return new TcpFailureDetectionSession(this); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.mvc.method.annotation; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.SocketTimeoutException; import java.util.Collections; import java.util.Locale; import jakarta.servlet.ServletException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.beans.FatalBeanException; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.context.support.StaticApplicationContext; import org.springframework.core.MethodParameter; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.ClassUtils; import org.springframework.web.HttpRequestHandler; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.support.WebApplicationObjectSupport; import org.springframework.web.method.HandlerMethod; import org.springframework.web.method.annotation.ModelMethodProcessor; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodReturnValueHandler; import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.FlashMap; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.resource.ResourceHttpRequestHandler; import org.springframework.web.testfixture.servlet.MockHttpServletRequest; import org.springframework.web.testfixture.servlet.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with {@link ExceptionHandlerExceptionResolver}. * * @author Rossen Stoyanchev * @author Arjen Poutsma * @author Kazuki Shimizu * @author Brian Clozel * @author Rodolphe Lecocq */ @SuppressWarnings("unused") public class ExceptionHandlerExceptionResolverTests { private static int DEFAULT_RESOLVER_COUNT; private static int DEFAULT_HANDLER_COUNT; private ExceptionHandlerExceptionResolver resolver; private MockHttpServletRequest request; private MockHttpServletResponse response; @BeforeAll public static void setupOnce() { ExceptionHandlerExceptionResolver resolver = new ExceptionHandlerExceptionResolver(); resolver.afterPropertiesSet(); DEFAULT_RESOLVER_COUNT = resolver.getArgumentResolvers().getResolvers().size(); DEFAULT_HANDLER_COUNT = resolver.getReturnValueHandlers().getHandlers().size(); } @BeforeEach public void setup() throws Exception { this.resolver = new ExceptionHandlerExceptionResolver(); this.resolver.setWarnLogCategory(this.resolver.getClass().getName()); this.request = new MockHttpServletRequest("GET", "/"); this.request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap()); this.response = new MockHttpServletResponse(); } @Test void nullHandler() { Object handler = null; this.resolver.afterPropertiesSet(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handler, null); assertThat(mav).as("Exception can be resolved only if there is a HandlerMethod").isNull(); } @Test void setCustomArgumentResolvers() { HandlerMethodArgumentResolver argumentResolver = new ServletRequestMethodArgumentResolver(); this.resolver.setCustomArgumentResolvers(Collections.singletonList(argumentResolver)); this.resolver.afterPropertiesSet(); assertThat(this.resolver.getArgumentResolvers().getResolvers().contains(argumentResolver)).isTrue(); assertMethodProcessorCount(DEFAULT_RESOLVER_COUNT + 1, DEFAULT_HANDLER_COUNT); } @Test void setArgumentResolvers() { HandlerMethodArgumentResolver argumentResolver = new ServletRequestMethodArgumentResolver(); this.resolver.setArgumentResolvers(Collections.singletonList(argumentResolver)); this.resolver.afterPropertiesSet(); assertMethodProcessorCount(1, DEFAULT_HANDLER_COUNT); } @Test void setCustomReturnValueHandlers() { HandlerMethodReturnValueHandler handler = new ViewNameMethodReturnValueHandler(); this.resolver.setCustomReturnValueHandlers(Collections.singletonList(handler)); this.resolver.afterPropertiesSet(); assertThat(this.resolver.getReturnValueHandlers().getHandlers().contains(handler)).isTrue(); assertMethodProcessorCount(DEFAULT_RESOLVER_COUNT, DEFAULT_HANDLER_COUNT + 1); } @Test void setResponseBodyAdvice() { this.resolver.setResponseBodyAdvice(Collections.singletonList(new JsonViewResponseBodyAdvice())); assertThat(this.resolver).extracting("responseBodyAdvice").asList().hasSize(1); this.resolver.setResponseBodyAdvice(Collections.singletonList(new CustomResponseBodyAdvice())); assertThat(this.resolver).extracting("responseBodyAdvice").asList().hasSize(2); } @Test void setReturnValueHandlers() { HandlerMethodReturnValueHandler handler = new ModelMethodProcessor(); this.resolver.setReturnValueHandlers(Collections.singletonList(handler)); this.resolver.afterPropertiesSet(); assertMethodProcessorCount(DEFAULT_RESOLVER_COUNT, 1); } @Test void resolveNoExceptionHandlerForException() throws NoSuchMethodException { Exception npe = new NullPointerException(); HandlerMethod handlerMethod = new HandlerMethod(new IoExceptionController(), "handle"); this.resolver.afterPropertiesSet(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, npe); assertThat(mav).as("NPE should not have been handled").isNull(); } @Test void resolveExceptionModelAndView() throws NoSuchMethodException { IllegalArgumentException ex = new IllegalArgumentException("Bad argument"); HandlerMethod handlerMethod = new HandlerMethod(new ModelAndViewController(), "handle"); this.resolver.afterPropertiesSet(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); assertThat(mav).isNotNull(); assertThat(mav.isEmpty()).isFalse(); assertThat(mav.getViewName()).isEqualTo("errorView"); assertThat(mav.getModel().get("detail")).isEqualTo("Bad argument"); } @Test void resolveExceptionResponseBody() throws UnsupportedEncodingException, NoSuchMethodException { IllegalArgumentException ex = new IllegalArgumentException(); HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); this.resolver.afterPropertiesSet(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); assertExceptionHandledAsBody(mav, "IllegalArgumentException"); } @Test // gh-26317 void resolveExceptionResponseBodyMatchingCauseLevel2() throws UnsupportedEncodingException, NoSuchMethodException { Exception ex = new Exception(new Exception(new IllegalArgumentException())); HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); this.resolver.afterPropertiesSet(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); assertExceptionHandledAsBody(mav, "IllegalArgumentException"); } @Test void resolveExceptionResponseWriter() throws Exception { IllegalArgumentException ex = new IllegalArgumentException(); HandlerMethod handlerMethod = new HandlerMethod(new ResponseWriterController(), "handle"); this.resolver.afterPropertiesSet(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); assertExceptionHandledAsBody(mav, "IllegalArgumentException"); } @Test // SPR-13546 void resolveExceptionModelAtArgument() throws Exception { IllegalArgumentException ex = new IllegalArgumentException(); HandlerMethod handlerMethod = new HandlerMethod(new ModelArgumentController(), "handle"); this.resolver.afterPropertiesSet(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); assertThat(mav).isNotNull(); assertThat(mav.getModelMap()).hasSize(1); assertThat(mav.getModelMap().get("exceptionClassName")).isEqualTo("IllegalArgumentException"); } @Test // SPR-14651 void resolveRedirectAttributesAtArgument() throws Exception { IllegalArgumentException ex = new IllegalArgumentException(); HandlerMethod handlerMethod = new HandlerMethod(new RedirectAttributesController(), "handle"); this.resolver.afterPropertiesSet(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); assertThat(mav).isNotNull(); assertThat(mav.getViewName()).isEqualTo("redirect:/"); FlashMap flashMap = (FlashMap) this.request.getAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE); assertThat((Object) flashMap).as("output FlashMap should exist").isNotNull(); assertThat(flashMap.get("exceptionClassName")).isEqualTo("IllegalArgumentException"); } @Test void resolveExceptionGlobalHandler() throws Exception { loadConfiguration(MyConfig.class); IllegalAccessException ex = new IllegalAccessException(); HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); assertExceptionHandledAsBody(mav, "AnotherTestExceptionResolver: IllegalAccessException"); } @Test void resolveExceptionGlobalHandlerOrdered() throws Exception { loadConfiguration(MyConfig.class); IllegalStateException ex = new IllegalStateException(); HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); assertExceptionHandledAsBody(mav, "TestExceptionResolver: IllegalStateException"); } @Test // gh-26317 void resolveExceptionGlobalHandlerOrderedMatchingCauseLevel2() throws Exception { loadConfiguration(MyConfig.class); Exception ex = new Exception(new Exception(new IllegalStateException())); HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); assertExceptionHandledAsBody(mav, "TestExceptionResolver: IllegalStateException"); } @Test // SPR-12605 void resolveExceptionWithHandlerMethodArg() throws Exception { loadConfiguration(MyConfig.class); ArrayIndexOutOfBoundsException ex = new ArrayIndexOutOfBoundsException(); HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); assertExceptionHandledAsBody(mav, "HandlerMethod: handle"); } @Test void resolveExceptionWithAssertionError() throws Exception { loadConfiguration(MyConfig.class); AssertionError err = new AssertionError("argh"); HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, new ServletException("Handler dispatch failed", err)); assertExceptionHandledAsBody(mav, err.toString()); } @Test void resolveExceptionWithAssertionErrorAsRootCause() throws Exception { loadConfiguration(MyConfig.class); AssertionError rootCause = new AssertionError("argh"); FatalBeanException cause = new FatalBeanException("wrapped", rootCause); Exception ex = new Exception(cause); // gh-26317 HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); assertExceptionHandledAsBody(mav, rootCause.toString()); } @Test //gh-27156 void resolveExceptionWithReasonResolvedByMessageSource() throws Exception { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class); StaticApplicationContext context = new StaticApplicationContext(ctx); Locale locale = Locale.ENGLISH; context.addMessage("gateway.timeout", locale, "Gateway Timeout"); context.refresh(); LocaleContextHolder.setLocale(locale); this.resolver.setApplicationContext(context); this.resolver.afterPropertiesSet(); SocketTimeoutException ex = new SocketTimeoutException(); HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); assertExceptionHandledAsBody(mav, ""); assertThat(this.response.getStatus()).isEqualTo(HttpStatus.GATEWAY_TIMEOUT.value()); assertThat(this.response.getErrorMessage()).isEqualTo("Gateway Timeout"); } @Test void resolveExceptionControllerAdviceHandler() throws Exception { loadConfiguration(MyControllerAdviceConfig.class); IllegalStateException ex = new IllegalStateException(); HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); assertExceptionHandledAsBody(mav, "BasePackageTestExceptionResolver: IllegalStateException"); } @Test // gh-26317 void resolveExceptionControllerAdviceHandlerMatchingCauseLevel2() throws Exception { loadConfiguration(MyControllerAdviceConfig.class); Exception ex = new Exception(new IllegalStateException()); HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); assertExceptionHandledAsBody(mav, "BasePackageTestExceptionResolver: IllegalStateException"); } @Test void resolveExceptionControllerAdviceNoHandler() throws Exception { loadConfiguration(MyControllerAdviceConfig.class); IllegalStateException ex = new IllegalStateException(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, null, ex); assertExceptionHandledAsBody(mav, "DefaultTestExceptionResolver: IllegalStateException"); } @Test // SPR-16496 void resolveExceptionControllerAdviceAgainstProxy() throws Exception { loadConfiguration(MyControllerAdviceConfig.class); IllegalStateException ex = new IllegalStateException(); HandlerMethod handlerMethod = new HandlerMethod(new ProxyFactory(new ResponseBodyController()).getProxy(), "handle"); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); assertExceptionHandledAsBody(mav, "BasePackageTestExceptionResolver: IllegalStateException"); } @Test // gh-22619 void resolveExceptionViaMappedHandler() throws Exception { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyControllerAdviceConfig.class); this.resolver.setMappedHandlerClasses(HttpRequestHandler.class); this.resolver.setApplicationContext(ctx); this.resolver.afterPropertiesSet(); IllegalStateException ex = new IllegalStateException(); ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handler, ex); assertExceptionHandledAsBody(mav, "DefaultTestExceptionResolver: IllegalStateException"); } private void assertMethodProcessorCount(int resolverCount, int handlerCount) { assertThat(this.resolver.getArgumentResolvers().getResolvers()).hasSize(resolverCount); assertThat(this.resolver.getReturnValueHandlers().getHandlers()).hasSize(handlerCount); } private void assertExceptionHandledAsBody(ModelAndView mav, String expectedBody) throws UnsupportedEncodingException { assertThat(mav).as("Exception was not handled").isNotNull(); assertThat(mav.isEmpty()).isTrue(); assertThat(this.response.getContentAsString()).isEqualTo(expectedBody); } private void loadConfiguration(Class<?> configClass) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(configClass); this.resolver.setApplicationContext(ctx); this.resolver.afterPropertiesSet(); } @Controller static class ModelAndViewController { public void handle() {} @ExceptionHandler public ModelAndView handle(Exception ex) throws IOException { return new ModelAndView("errorView", "detail", ex.getMessage()); } } @Controller static class ResponseWriterController { public void handle() {} @ExceptionHandler public void handleException(Exception ex, Writer writer) throws IOException { writer.write(ClassUtils.getShortName(ex.getClass())); } } interface ResponseBodyInterface { void handle(); @ExceptionHandler @ResponseBody String handleException(IllegalArgumentException ex); } @Controller static class ResponseBodyController extends WebApplicationObjectSupport implements ResponseBodyInterface { @Override public void handle() {} @Override @ExceptionHandler @ResponseBody public String handleException(IllegalArgumentException ex) { return ClassUtils.getShortName(ex.getClass()); } } @Controller static class IoExceptionController { public void handle() {} @ExceptionHandler(value = IOException.class) public void handleException() { } } @Controller static class ModelArgumentController { public void handle() {} @ExceptionHandler public void handleException(Exception ex, Model model) { model.addAttribute("exceptionClassName", ClassUtils.getShortName(ex.getClass())); } } @Controller static class RedirectAttributesController { public void handle() {} @ExceptionHandler public String handleException(Exception ex, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("exceptionClassName", ClassUtils.getShortName(ex.getClass())); return "redirect:/"; } } @RestControllerAdvice @Order(1) static class TestExceptionResolver { @ExceptionHandler public String handleException(IllegalStateException ex) { return "TestExceptionResolver: " + ClassUtils.getShortName(ex.getClass()); } @ExceptionHandler(ArrayIndexOutOfBoundsException.class) public String handleWithHandlerMethod(HandlerMethod handlerMethod) { return "HandlerMethod: " + handlerMethod.getMethod().getName(); } @ExceptionHandler(AssertionError.class) public String handleAssertionError(Error err) { return err.toString(); } } @RestControllerAdvice @Order(2) static class AnotherTestExceptionResolver { @ExceptionHandler({IllegalStateException.class, IllegalAccessException.class}) public String handleException(Exception ex) { return "AnotherTestExceptionResolver: " + ClassUtils.getShortName(ex.getClass()); } } @RestControllerAdvice @Order(3) static class ResponseStatusTestExceptionResolver { @ExceptionHandler(SocketTimeoutException.class) @ResponseStatus(code = HttpStatus.GATEWAY_TIMEOUT, reason = "gateway.timeout") public void handleException(SocketTimeoutException ex) { } } @Configuration static class MyConfig { @Bean public TestExceptionResolver testExceptionResolver() { return new TestExceptionResolver(); } @Bean public AnotherTestExceptionResolver anotherTestExceptionResolver() { return new AnotherTestExceptionResolver(); } @Bean public ResponseStatusTestExceptionResolver responseStatusTestExceptionResolver() { return new ResponseStatusTestExceptionResolver(); } } @RestControllerAdvice("java.lang") @Order(1) static class NotCalledTestExceptionResolver { @ExceptionHandler public String handleException(IllegalStateException ex) { return "NotCalledTestExceptionResolver: " + ClassUtils.getShortName(ex.getClass()); } } @RestControllerAdvice(assignableTypes = WebApplicationObjectSupport.class) @Order(2) static class BasePackageTestExceptionResolver { @ExceptionHandler public String handleException(IllegalStateException ex) { return "BasePackageTestExceptionResolver: " + ClassUtils.getShortName(ex.getClass()); } } @RestControllerAdvice @Order(3) static class DefaultTestExceptionResolver { @ExceptionHandler public String handleException(IllegalStateException ex) { return "DefaultTestExceptionResolver: " + ClassUtils.getShortName(ex.getClass()); } } @Configuration static class MyControllerAdviceConfig { @Bean public NotCalledTestExceptionResolver notCalledTestExceptionResolver() { return new NotCalledTestExceptionResolver(); } @Bean public BasePackageTestExceptionResolver basePackageTestExceptionResolver() { return new BasePackageTestExceptionResolver(); } @Bean public DefaultTestExceptionResolver defaultTestExceptionResolver() { return new DefaultTestExceptionResolver(); } } static class CustomResponseBodyAdvice implements ResponseBodyAdvice<Object> { @Override public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { return false; } @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { return null; } } }
package codewars; import java.util.ArrayList; import java.util.Comparator; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LongestCommonSubsequence { int countlcsRec; int countisMatch; public LongestCommonSubsequence() { // TODO Auto-generated constructor stub } public String lcs(String x, String y) { long startTime = System.nanoTime(); this.countlcsRec = 0; this.countisMatch = 0; String res = lcsRec(x,y); long estimatedTime = System.nanoTime() - startTime; System.out.println("countlcsRec:"+this.countlcsRec+";countisMatch"+this.countisMatch+";estimatedTime"+estimatedTime); return res.replace('Ô','?'); } public String lcsRec(String x, String y) { this.countlcsRec++; if (x.length() == 0 || y.length() == 0 || x == null || y == null) return ""; //System.out.println("x:" + x + ";y:" + y); String MaxResult = ""; String result = ""; for (int i = 0; i < x.length(); i++) { String currRes = x.substring(i, i+1); int posRes = y.indexOf(currRes); if (posRes >= 0) { result = currRes+lcsRec(x.substring(i+1),y.substring(posRes+1)); } if (result.length() > MaxResult.length()) {MaxResult = result;} } return MaxResult; } public boolean isMatch(String currRes, String y) { this.countisMatch++; currRes = changePattern(currRes); Matcher matcher = Pattern.compile(currRes).matcher(y); if (matcher.find()) { return true; } else return false; } public static String changePattern(String currRes) { int currLength = currRes.length(); for (int j = 1; j<currLength; j++) { currRes = currRes.substring(0,currLength-j)+".*"+currRes.substring(currLength-j); } return currRes; } public static void main(String[] args) { // System.out.println(lcs("bc", "abc")); // TODO Auto-generated method stub // LongestCommonSubsequence lcs = new LongestCommonSubsequence(); // System.out.println(lcs.lcs("acaf", "abcdef")); // System.out.println(lcs.lcs("anothertest","notatest")); // System.out.println(lcs.lcs("O0IF=;N4K6L6H1?J?Q?1SHOS<LIE2CRGK0QR<RL:;","Q:86F8GAK?KENR5GHNS9RMK<L5>3QS2AI0M;CNFA")); // System.out.println(lcs.lcs("L45@7;7H6QR33HJ<II7JG1M3D69IG9GFKGDJCRC?","A:CA25D0RD?3EHJK9R=MPKR=?8N4=28EA120??P?")); System.out.println(lcs.lcs("L8;FJG=P?;2PQ<L>LQ2D:4R@B644N5O99HRH86MNL>GJF?HEL@H9LGSS?SP<;","BQQSE05Q6=<I6B<HHMIR2B<G?O91KDC16SEEI5>>D7FK9@D:JH9NM3P?QP46")); // x:y: // System.out.println(lcs("abcdef","fffffffcdfffffffff")); // System.out.println(lcs("acaaaaaaaaaaaaaaaaaa","acbbbbabbbbbbbbbbbbbb")); // System.out.println(lcs("aaaaaaaaaaaaaaaaaac","bbbbbbcbbbbbbbbbbbbbac")); // System.out.println(lcs("fhjdshabcdjshfa","fhjdsabkdjshfa")); } }
package IFactory; import com.DaoImpl.SqliteGuitarDaoImpl; import com.DaoImpl.SqliteInventoryDaoImpl; import com.Idao.GuitarIDao; import com.Idao.InventoryIDao; public interface IDaoFactory { public GuitarIDao GetGuitarInstance() throws Exception; public InventoryIDao GetInventoryInstance() throws Exception; }
package com.example.issam.agenda; import android.util.Log; import com.example.issam.agenda.model.Persona; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import io.realm.DynamicRealm; import io.realm.DynamicRealmObject; import io.realm.FieldAttribute; import io.realm.RealmMigration; import io.realm.RealmObjectSchema; import io.realm.RealmSchema; public class Migration implements RealmMigration { @Override public void migrate(DynamicRealm realm, long oldVersion, long newVersion) { RealmSchema schema = realm.getSchema(); if (oldVersion == 0) { Log.d("Migration", "actualitzant a la versió 1"); RealmObjectSchema Schema = schema.get("Persona"); Schema.addField("edad_tmp",int.class).transform(new RealmObjectSchema.Function() { @Override public void apply(DynamicRealmObject obj) { String oldEdad = obj.getString("edad"); int edi = Integer.parseInt(oldEdad); obj.setInt("edad_tmp",edi); } }) .removeField("edad") .renameField("edad_tmp","edad"); Schema.addField("nacimiento",int.class, FieldAttribute.INDEXED,FieldAttribute.REQUIRED) .transform(new RealmObjectSchema.Function() { @Override public void apply(DynamicRealmObject obj) { Date date = new Date(); Calendar calendar = new GregorianCalendar(); calendar.setTime(date); int year = calendar.get(Calendar.YEAR); obj.set("nacimiento", year - obj.getInt("edad")); } }); oldVersion++; } } }
package com.gxtc.huchuan.ui.deal; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.gxtc.commlibrary.base.BaseTitleFragment; import com.gxtc.commlibrary.utils.EventBusUtil; import com.gxtc.huchuan.R; import com.gxtc.huchuan.adapter.DealTabAdapter; import com.gxtc.huchuan.bean.event.EventMenuBean; import com.gxtc.huchuan.ui.deal.deal.DealFragment; import com.gxtc.huchuan.ui.deal.liuliang.FlowFragment; import java.util.ArrayList; import java.util.List; import butterknife.BindView; /** * 交易Tabfragment * Created by Steven on 17/2/13. */ public class DealTabFragment extends BaseTitleFragment implements View.OnClickListener { private final int TAB_DEAL = 0x01; private final int TAB_FLOW = 0x02; @BindView(R.id.vp_deal_tab) ViewPager viewPager; private TextView tvDeal; private TextView tvFlow; private ImageView btnMenu; private DealTabAdapter adapter; @Override public View initView(LayoutInflater inflater, ViewGroup container) { View view = inflater.inflate(R.layout.fragment_deal_tab,container,false); View headTab = LayoutInflater.from(getContext()).inflate(R.layout.model_deal_tab, (ViewGroup) getBaseHeadView().getParentView(), false); tvDeal = (TextView) headTab.findViewById(R.id.tv_deal_tab_deal); tvFlow = (TextView) headTab.findViewById(R.id.tv_deal_tab_flow); btnMenu = (ImageView) headTab.findViewById(R.id.btn_menu_head); setActionBarTopPadding(headTab); ((RelativeLayout) getBaseHeadView().getParentView()).addView(headTab); getBaseHeadView().hideHeadLine(); return view; } @Override public void initListener() { tvDeal.setOnClickListener(this); tvFlow.setOnClickListener(this); btnMenu.setOnClickListener(this); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if(position == 0){ changeTab(TAB_DEAL); }else{ changeTab(TAB_FLOW); } } @Override public void onPageScrollStateChanged(int state) { } }); } @Override public void initData() { DealFragment dFragment = new DealFragment(); FlowFragment fFragment = new FlowFragment(); List<Fragment> fragments = new ArrayList<>(); fragments.add(dFragment); fragments.add(fFragment); adapter = new DealTabAdapter(getFragmentManager(),fragments); viewPager.setAdapter(adapter); changeTab(TAB_DEAL); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.tv_deal_tab_deal: changeTab(TAB_DEAL); viewPager.setCurrentItem(0); break; case R.id.tv_deal_tab_flow: changeTab(TAB_FLOW); viewPager.setCurrentItem(1); break; case R.id.btn_menu_head: EventBusUtil.post(new EventMenuBean()); break; } } private void changeTab(int tab){ tvDeal.setSelected(tab == TAB_DEAL); tvFlow.setSelected(tab == TAB_FLOW); } }
/* * 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 logica; import java.sql.SQLException; import java.util.List; import persistencia.PersistenciaPrestamo; import persistencia.PrestamoAlmacen; /** * clase logica del prestamo. * @author Giselle */ public class Prestamo implements InterfacePrestamo { private int numeroPrestamo; private String nombreSolicitante; private String matricula; private String fechaPrestamo; private String horaPrestamo; private String equipo; private String fechaDevolucion; private String horaDevolucion; private String salon; private PersistenciaPrestamo persistencia = new PrestamoAlmacen(); public Prestamo() { } public Prestamo(String nombreSolicitante, String matricula, String fechaPrestamo, String horaPrestamo, String equipo, String fechaDevolucion, String horaDevolucion, String salon) { this.nombreSolicitante = nombreSolicitante; this.matricula = matricula; this.fechaPrestamo = fechaPrestamo; this.horaPrestamo = horaPrestamo; this.equipo = equipo; this.fechaDevolucion = fechaDevolucion; this.horaDevolucion = horaDevolucion; this.salon = salon; } public Prestamo(int numeroPrestamo, String fechaPrestamo, String equipo, String matricula, String nombreSolicitante, String salon) { this.numeroPrestamo = numeroPrestamo; this.nombreSolicitante = nombreSolicitante; this.matricula = matricula; this.fechaPrestamo = fechaPrestamo; this.equipo = equipo; this.salon = salon; } public Prestamo(int numeroPrestamo, String fechaDevolucion, String horaDevolucion, String equipo) { this.numeroPrestamo = numeroPrestamo; this.fechaDevolucion = fechaDevolucion; this.horaDevolucion = horaDevolucion; this.equipo = equipo; } public int getNumeroPrestamo() { return numeroPrestamo; } public String getNombreSolicitante() { return nombreSolicitante; } public String getMatricula() { return matricula; } public String getFechaPrestamo() { return fechaPrestamo; } public String getHoraPrestamo() { return horaPrestamo; } public String getEquipo() { return equipo; } public String getFechaDevolucion() { return fechaDevolucion; } public String getHoraDevolucion() { return horaDevolucion; } public String getSalon() { return salon; } /** * registra un prestamo nuevo. * @param nombreSolicitante nombre del que solicita * @param matricula matricula de quien solicita * @param fechaPrestamo fecha cuando se solicita * @param horaPrestamo hora del prestamo * @param equipo el equipo que se presta * @param salon salon donde se ocupa * @throws SQLException Por si causa problemas la base */ @Override public void registrarPrestamo(String nombreSolicitante, String matricula, String fechaPrestamo, String horaPrestamo, String equipo, String salon) throws SQLException { this.persistencia.registrarPrestamo(nombreSolicitante, matricula, fechaPrestamo, horaPrestamo, equipo, salon); } /** * obtiene una lista de dos los prestamos registrados. * @return lista de prestamos registrados. * @throws SQLException Por si causa problemas la base */ @Override public List<Prestamo> obtenerTodosLosPrestamos() throws SQLException { return this.persistencia.obtenerTodosLosPrestamos(); } /** * obtiene solo los registros de los equipos con estado de prestados. * @return lista de equipos prestados. * @throws SQLException Por si causa problemas la base */ @Override public List<Prestamo> obtenerPrestados() throws SQLException { return this.persistencia.obtenerPrestados(); } /** * edita un registro de prestamos para poner que ha sido devuelto. * @param numeroPrestamo numero del prestamo a registrar * @param fechaDevolucion fecha cuando se devolvio * @param horaDevolucion hora a la que se devolvio * @param equipo equipo prestado * @throws SQLException Por si causa problemas la base */ @Override public void registrarDevolucion(int numeroPrestamo, String fechaDevolucion, String horaDevolucion, String equipo) throws SQLException { this.persistencia.registrarDevolucion(numeroPrestamo, fechaDevolucion, horaDevolucion, equipo); } }
/* ==================================================================== * * Copyright (c) Atos Origin INFORMATION TECHNOLOGY All rights reserved. * * ==================================================================== * */ package com.aof.webapp.action.prm.report; import java.io.FileInputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.util.MessageResources; import com.aof.component.domain.party.Party; import com.aof.component.domain.party.PartyHelper; import com.aof.component.domain.party.UserLogin; import com.aof.core.persistence.Persistencer; import com.aof.core.persistence.hibernate.Hibernate2Session; import com.aof.core.persistence.jdbc.SQLExecutor; import com.aof.core.persistence.jdbc.SQLResults; import com.aof.core.persistence.util.EntityUtil; import com.aof.util.Constants; import com.aof.util.UtilDateTime; import com.aof.webapp.action.ActionErrorLog; /** * @author Angus Chen * */ public class PreSaleMDRptAction extends ReportBaseAction { protected ActionErrors errors = new ActionErrors(); protected ActionErrorLog actionDebug = new ActionErrorLog(); public ActionForward perform (ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){ ActionErrors errors = this.getActionErrors(request.getSession()); Locale locale = getLocale(request); MessageResources messages = getResources(); try { SimpleDateFormat Date_formater = new SimpleDateFormat("yyyy-MM-dd"); Date nowDate = (java.util.Date)UtilDateTime.nowTimestamp(); String action = request.getParameter("FormAction"); String project = request.getParameter("project"); String FromDate = request.getParameter("dateStart"); String EndDate = request.getParameter("dateEnd"); if (project == null) project = ""; if (FromDate==null) FromDate=Date_formater.format(UtilDateTime.getDiffDay(nowDate,-10)); if (EndDate==null) EndDate=Date_formater.format(nowDate); if (action == null) action = "view"; if (action.equals("QueryForList")) { SQLResults sr = findQueryResult(request,FromDate,EndDate,project); request.setAttribute("QryList",sr); return (mapping.findForward("success")); } if (action.equals("ExportToExcel")) { return ExportToExcel(mapping,request, response,FromDate,EndDate,project); } }catch(Exception e){ e.printStackTrace(); } return (mapping.findForward("success")); } private SQLResults findQueryResult(HttpServletRequest request,String FromDate, String ToDate, String project) throws Exception { UserLogin ul = (UserLogin)request.getSession().getAttribute(Constants.USERLOGIN_KEY); net.sf.hibernate.Session session = Hibernate2Session.currentSession(); SQLExecutor sqlExec = new SQLExecutor(Persistencer.getSQLExecutorConnection(EntityUtil.getConnectionByName("jdbc/aofdb"))); String SqlStr = "select sum(ptd.ts_hrs_confirm) as actualhrs, pm.proj_name as pname, ul.name, p.description, ptd.ts_proj_id as pid"; SqlStr = SqlStr + " from projevent as pe inner join proj_ts_det as ptd on ptd.ts_projevent = pe.pevent_code"; SqlStr = SqlStr + " inner join proj_ts_mstr as ptm on ptm.tsm_id =ptd.tsm_id and pm.proj_status = 'WIP'"; SqlStr = SqlStr + " inner join user_login as ul on ptm.tsm_userlogin = ul.user_login_id"; SqlStr = SqlStr + " inner join proj_mstr as pm on pm.proj_id = ptd.ts_proj_id"; SqlStr = SqlStr + " inner join party as p on p.party_id = pm.cust_id"; SqlStr = SqlStr + " where pe.pevent_code = '14' and ptd.ts_status = 'approved' "; if (!project.trim().equals("")) { SqlStr = SqlStr + " and ptd.ts_proj_id like '%"+project.trim()+"%' or pm.proj_name like '%"+project.trim()+"%'"; } SqlStr = SqlStr + " and ptd.ts_date between '"+FromDate+"' and '"+ToDate+"'"; SqlStr = SqlStr + "group by ptd.ts_proj_id, pm.proj_name, ul.name, p.description,ptd.ts_proj_id"; SQLResults sr = sqlExec.runQueryCloseCon(SqlStr); return sr; } private ActionForward ExportToExcel (ActionMapping mapping, HttpServletRequest request, HttpServletResponse response,String FromDate, String ToDate,String project){ try { ActionErrors errors = this.getActionErrors(request.getSession()); if (!errors.empty()) { saveErrors(request, errors); return null; } //Get Excel Template Path String TemplatePath = GetTemplateFolder(); if (TemplatePath == null) return null; SQLResults sr = findQueryResult(request,FromDate,ToDate, project); if (sr== null || sr.getRowCount() == 0) return null; //Start to output the excel file response.reset(); response.setHeader("Content-Disposition", "attachment;filename=\""+ SaveToFileName + "\""); response.setContentType("application/octet-stream"); //Use POI to read the selected Excel Spreadsheet HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(TemplatePath+"\\"+ExcelTemplate)); //Select the first worksheet HSSFSheet sheet = wb.getSheet(FormSheetName); int fromYear = 0; int fromMonth = 0; int fromDay = 0; int toYear = 0; int toMonth = 0; int toDay = 0; Calendar fromCalendar = Calendar.getInstance(); if (FromDate != null && FromDate.trim().length() > 9) { fromYear = Integer.parseInt(FromDate.substring(0, 4)); fromMonth = Integer.parseInt(FromDate.substring(5, 7)); fromDay = Integer.parseInt(FromDate.substring(8, 10)); fromCalendar.set(Calendar.YEAR, fromYear); fromCalendar.set(Calendar.MONTH, fromMonth - 1); fromCalendar.set(Calendar.DATE, fromDay); } Date fromDate = fromCalendar.getTime(); Calendar toCalendar = Calendar.getInstance(); if (ToDate != null && ToDate.trim().length() > 9) { toYear = Integer.parseInt(ToDate.substring(0, 4)); toMonth = Integer.parseInt(ToDate.substring(5, 7)); toDay = Integer.parseInt(ToDate.substring(8, 10)); toCalendar.set(Calendar.YEAR, toYear); toCalendar.set(Calendar.MONTH, toMonth - 1); toCalendar.set(Calendar.DATE, toDay); } Date toDate = toCalendar.getTime(); DateFormat df = new SimpleDateFormat("dd-MMM-yy", Locale.ENGLISH); HSSFCell cell = null; cell = sheet.getRow(1).getCell((short)4); cell.setCellValue(df.format(fromDate) + " ~ " + df.format(toDate)); //List HSSFCellStyle boldTextStyle = sheet.getRow(ListStartRow).getCell((short)0).getCellStyle(); HSSFCellStyle normalStyle = sheet.getRow(ListStartRow).getCell((short)4).getCellStyle(); int ExcelRow = ListStartRow; HSSFRow HRow = null; for (int row =0; row < sr.getRowCount(); row++) { HRow = sheet.createRow(ExcelRow); cell = HRow.createCell((short)0); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//??cell???????????? cell.setCellValue(sr.getString(row,"pid")); cell.setCellStyle(boldTextStyle); cell = HRow.createCell((short)1); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//??cell???????????? cell.setCellValue(sr.getString(row,"pname")); cell.setCellStyle(boldTextStyle); cell = HRow.createCell((short)2); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//??cell???????????? cell.setCellValue(sr.getString(row,"description")); cell.setCellStyle(boldTextStyle); cell = HRow.createCell((short)3); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//??cell???????????? cell.setCellValue(sr.getString(row,"name")); cell.setCellStyle(boldTextStyle); cell = HRow.createCell((short)4); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//??cell???????????? cell.setCellValue(sr.getDouble(row,"actualhrs")); cell.setCellStyle(normalStyle); ExcelRow++; } //??Excel??? wb.write(response.getOutputStream()); //??Excel????? response.getOutputStream().close(); response.setStatus( HttpServletResponse.SC_OK ); response.flushBuffer(); } catch (Exception e) { e.printStackTrace(); } return null; } private final static String ExcelTemplate="PreSaleMDRpt.xls"; private final static String FormSheetName="Form"; private final static String SaveToFileName="Pre-Sale Man-Day report.xls"; private final int ListStartRow = 5; }
package appui; public class TestDisque { public static void main(String[] args) { Disque d1 = new Disque(); d1.setNomArtiste("DJ Angerfist"); d1.setTitreDisque("HardCore 2016"); d1.setNbrMorceau(101); d1.setDureeDisqueMilli(260000); Disque d2 = new Disque(); d2.setNomArtiste("Les bronzés font du ski"); d2.setTitreDisque("Les bobos en vacances"); d2.setNbrMorceau(24); d2.setDureeDisqueMilli(100000); Disque d3 = new Disque(); d3.setNomArtiste("Dubstep"); d3.setTitreDisque("Agar.IO"); d3.setNbrMorceau(7); d3.setDureeDisqueMilli(50000); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("Le disque 1 est : "+ d1.getTitreDisque()); System.out.println("Le disque 2 est : "+ d2.getTitreDisque()); System.out.println("Le disque 3 est : "+ d3.getTitreDisque()); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("La somme des morceaux est de "+ (d1.getNbrMorceau()+ d2.getNbrMorceau()+ d3.getNbrMorceau())+" titres"); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("La durée total des 3 disques est de "+ (d1.getDureeDisqueMilli()+ d2.getDureeDisqueMilli()+ d3.getDureeDisqueMilli())+" Millisecondes"); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println(d1); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println(d2); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println(d3); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); } }
package stringbasic; public class Pet { public enum Gender { MALE, FEMALE, UNKNOWN } private String name; //String private int yearOfBirth; //int, vagy LocalDate private Gender gender; //ENUM private String regNumber; //int, ha akarunk vele aritmetikai műveleteket csinálni, különben String public Pet(String name, int yearOfBirth, Gender gender, String regNumber) { this.name = name; this.yearOfBirth = yearOfBirth; this.gender = gender; this.regNumber = regNumber; } public String getName() { return name; } public int getYearOfBirth() { return yearOfBirth; } public Gender getGender() { return gender; } public String getRegNumber() { return regNumber; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class FactorOfNum { public static int convert(String str) { int val = 0; try { val = Integer.parseInt(str); } catch (NumberFormatException e) { System.out.println("Please Enter a Number!"); } return val; } public static void main(String[] args) { boolean finished = false; while (finished == false) { System.out.println("Enter a Positive Value"); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); System.out.println(">>> "); String userString = ""; try { userString = br.readLine(); } catch (IOException ioe) { System.out.println("IO Exception Raised!"); } int userInt = convert(userString); if (userInt % 2 == 0) { finished = true; int total = 1; for (int i = 1; i <= userInt; i++) { total = total * i; } System.out.println("Factorial of "+ userInt + " is " + total); } else { finished = false; } System.out.println("You are Done Thanks"); } } } // import java.io.BufferedReader; // import java.io.IOException; // import java.io.InputStreamReader; // // // public class FactorOfNum { // // static int factorial(int n) // { // if (n == 0) // return 1; // // return n*factorial(n-1); // } // // // Function to convert String to integer // public static int convert(String str) // { // int val = 0; // // Convert the String // try { // val = Integer.parseInt(str); // } // catch (NumberFormatException e) { // // This is thrown when the String // // contains characters other than digits // System.out.println("Please Enter a Number!"); // } // return val; // } // // // public static void main(String[] args) { // boolean finished = false; // // while (finished == false) { // System.out.println("Enter a Positive Value"); // // InputStreamReader isr = new InputStreamReader(System.in); // BufferedReader br = new BufferedReader(isr); // System.out.println(">>> "); // String userString = ""; // // try { // userString = br.readLine(); // // } catch (IOException ioe) { // System.out.println("IO Exception Raised!"); // // } // // int userInt = convert(userString); // // System.out.println("Factorial of "+ userInt + " is " + factorial(userInt)); // // if (userInt % 2 == 0 ){ // finished = true; // for(int i = 0; i <= userInt ; i++ ) { // // int factorial = i*i++; // // int num = 5; // // // } // // // // }else { // finished = false; // // } // // } // // // // // } // // }
package com.example.PollingApplication.services; import com.example.PollingApplication.domain.Vote; import com.example.PollingApplication.repositories.VoteRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @Service public class VoteService { @Autowired private VoteRepository voteRepository; public ResponseEntity<?> createVote(Long pollId, Vote vote) { vote = voteRepository.save(vote); // Set the headers for the newly created resource HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(vote.getId()).toUri()); return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED); } public Iterable<Vote> getAllVotes(Long pollId) { return voteRepository. findByPoll(pollId); } }
package net.sf.throughglass.glassware; import android.app.Service; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import net.sf.throughglass.utils.CustomTag; import ye2libs.utils.Log; /** * Created by yowenlove on 14-8-3. */ public class BLEFindService extends Service { private static final String TAG = CustomTag.make("PostService"); private BluetoothManager mBluetoothManager; private BluetoothAdapter mBluetoothAdapter; private static final int SCAN_PERIOD = 60000; private boolean mScanning = false; private Handler mHandler = new Handler(Looper.getMainLooper()); // Device scan callback. private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { Log.d(TAG, "onLeScan, device = %s, %s", device.getAddress(), device.getName()); } }; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); // Initializes Bluetooth adapter. mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = mBluetoothManager.getAdapter(); // check connection; scanLeDevice(true); } private void scanLeDevice(final boolean enable) { if (enable) { // Stops scanning after a pre-defined scan period. mHandler.postDelayed(new Runnable() { @Override public void run() { mScanning = false; mBluetoothAdapter.stopLeScan(mLeScanCallback); } }, SCAN_PERIOD); mScanning = true; mBluetoothAdapter.startLeScan(mLeScanCallback); } else { mScanning = false; mBluetoothAdapter.stopLeScan(mLeScanCallback); } } @Override public void onDestroy() { super.onDestroy(); // release connection scanLeDevice(false); } }
package org.camunda.bpm; import org.camunda.bpm.client.ExternalTaskClient; import org.camunda.bpm.engine.variable.Variables; import org.camunda.bpm.engine.variable.value.ObjectValue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class App { public static void main(String... args) throws InterruptedException { // bootstrap the client ExternalTaskClient client = ExternalTaskClient.create() .baseUrl("http://localhost:8080/engine-rest") .build(); // subscribe to the topic client.subscribe("creditScoreChecker") .lockDuration(1000) .handler((externalTask, externalTaskService) -> { // retrieve a variable from the Workflow Engine int defaultScore = externalTask.getVariable("defaultScore"); List<Integer> creditScores = new ArrayList<>(Arrays.asList(defaultScore, 9, 1, 4, 10)); // create an object typed variable ObjectValue creditScoresObject = Variables .objectValue(creditScores) .create(); // complete the external task externalTaskService.complete(externalTask, Collections.singletonMap("creditScores", creditScoresObject)); System.out.println("The External Task " + externalTask.getId() + " has been completed!"); }).open(); } }
package bilheteria; public class CartaoDeCredito { public boolean conferirDadosCartao(String nomecartao, String numcartao, String validade, String codigo) { return true; } }
package com.bistel.YMA.lib; public class SpecialFunction { private final static int ITMAX = 100; protected final static double EPS = 1e-8; private final static double FPMIN = 1e-8; public static double betai(double a,double b,double x) { double bt; if (x < 0.0 || x > 1.0) { System.out.println("Bad x in routine betai"); return -1; } if (x == 0.0 || x == 1.0) bt = 0.0; else bt = Math.exp(gammaln(a + b) - gammaln(a) - gammaln(b) + a * Math.log(x) + b * Math.log(1.0 - x)); if (x < (a + 1.0) / (a + b + 2.0)) return bt * betacf(a, b, x) / a; else return 1.0 - bt * betacf(b, a, 1.0 - x) / b; } public static double erf(double x) { return x < 0.0 ? -gammp(0.5,x*x) : gammp(0.5,x*x); } private static double gammaln(double xx) { double x, y, tmp, ser; final double[] cof = { 76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5 }; int j; y = x = xx; tmp = x + 5.5; tmp -= (x + 0.5) * Math.log(tmp); ser = 1.000000000190015; for (j = 0; j <= 5; j++) ser += cof[j] / ++y; return -tmp + Math.log(2.5066282746310005 * ser / x); } private static double betacf(double a,double b,double x) { double t, z, ans; z = Math.abs(x); t = 1.0 / (1.0 + 0.5 * z); ans = t * Math.exp(-z * z - 1.26551223 + t * (1.00002368 + t * (0.37409196 + t * (0.09678418 + t * (-0.18628806 + t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 + t * (-0.82215223 + t * 0.17087277))))))))); return x >= 0.0 ? ans : 2.0 - ans; } public static double erfcc(double x) { double t, z, ans; z = Math.abs(x); t = 1.0 / (1.0 + 0.5 * z); ans = t * Math.exp(-z * z - 1.26551223 + t * (1.00002368 + t * (0.37409196 + t * (0.09678418 + t * (-0.18628806 + t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 + t * (-0.82215223 + t * 0.17087277))))))))); return x >= 0.0 ? ans : 2.0 - ans; } public static double gammp(double a, double x) { //double gamser,gammcf,gln; StatDouble gamser = new StatDouble(); StatDouble gammcf = new StatDouble(); StatDouble gln = new StatDouble(); if (x < 0.0 || a <= 0.0) { //printf("Invalid arguments in routine gammp"); return -1; } if (x < (a+1.0)) { gser(gamser,a,x,gln); return gamser.getDouble(); } else { gcf(gammcf,a,x,gln); return 1.0-gammcf.getDouble(); } } public static double gammq(double a, double x) { StatDouble gamser = new StatDouble(); StatDouble gammcf = new StatDouble(); StatDouble gln = new StatDouble(); //double gamser, gammcf, gln; if (x < 0.0 || a <= 0.0) { return -1; //nrerror("Invalid arguments in routine gammq"); } if (x < (a + 1.0)) { gser(gamser, a, x, gln); return 1.0 - gamser.getDouble(); } else { gcf(gammcf, a, x, gln); return gammcf.getDouble(); } } private static void gser(StatDouble gamser, double a, double x, StatDouble gln) { int n; double sum, del, ap; gln.setDouble(gammaln(a)); if (x <= 0.0) { if (x < 0.0) { //printf("x less than 0 in routine gser"); return; } gamser.setDouble(0.0); return; } else { ap = a; del = sum = 1.0 / a; for (n = 1; n <= ITMAX; n++) { ++ap; del *= x / ap; sum += del; if (Math.abs(del) < Math.abs(sum) * EPS) { gamser.setDouble( sum * Math.exp(-x + a * Math.log(x) - gln.getDouble())); return; } } //printf("a too large, ITMAX too small in routine gser"); return; } } /*void static gser(double *gamser, double a, double x, double *gln) { int n; double sum, del, ap; *gln = gammln(a); if (x <= 0.0) { if (x < 0.0) { printf("x less than 0 in routine gser"); return; } *gamser = 0.0; return; } else { ap = a; del = sum = 1.0 / a; for (n = 1; n <= ITMAX; n++) { ++ap; del *= x / ap; sum += del; if (fabs(del) < fabs(sum) * EPS) { *gamser = sum * exp(-x + a * log(x) - (*gln)); return; } } printf("a too large, ITMAX too small in routine gser"); return; } }*/ private static void gcf(StatDouble gammcf, double a, double x,StatDouble gln) { int i; double an, b, c, d, del, h; gln.setDouble(gammaln(a)); b = x + 1.0 - a; c = 1.0 / FPMIN; d = 1.0 / b; h = d; for (i = 1; i <= ITMAX; i++) { an = -i * (i - a); b += 2.0; d = an * d + b; if (Math.abs(d) < FPMIN) d = FPMIN; c = b + an / c; if (Math.abs(c) < FPMIN) c = FPMIN; d = 1.0 / d; del = d * c; h *= del; if (Math.abs(del - 1.0) < EPS) break; } if (i > ITMAX) { //printf("a too large, ITMAX too small in gcf"); return; } gammcf.setDouble(Math.exp(-x + a * Math.log(x) - gln.getDouble()) * h); } /*void static gcf(double *gammcf, double a, double x, double *gln) { int i; double an, b, c, d, del, h; gln = gammln(a); b = x + 1.0 - a; c = 1.0 / FPMIN; d = 1.0 / b; h = d; for (i = 1; i <= ITMAX; i++) { an = -i * (i - a); b += 2.0; d = an * d + b; if (fabs(d) < FPMIN) d = FPMIN; c = b + an / c; if (fabs(c) < FPMIN) c = FPMIN; d = 1.0 / d; del = d * c; h *= del; if (fabs(del - 1.0) < EPS) break; } if (i > ITMAX) { printf("a too large, ITMAX too small in gcf"); return; } *gammcf = exp(-x + a * log(x) - (gln)) * h; }*/ }
package cn.qqtheme.framework.widght.tablebottom; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.widget.ImageView; import android.widget.LinearLayout; /** * Created by jianghw on 2017/6/26. * Description: * Update by: * Update day: */ @SuppressLint("AppCompatCustomView") public class UiItemImage extends ImageView { private Bitmap clickBitmap; private Bitmap unClickBitmap; private Paint mPaint; private int mAlpha; private Rect rect; public UiItemImage(Context context) { this(context, null, 0); } public UiItemImage(Context context, AttributeSet attrs) { this(context, attrs, 0); } public UiItemImage(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mAlpha = 0; } /** * 传递图片资源过来 * * @param clickDrawableRid R.layout.xxx * @param unClickDrawableRid */ public void initBitmap(int clickDrawableRid, int unClickDrawableRid) { //点击的图片 clickBitmap = BitmapFactory.decodeResource(getResources(), clickDrawableRid); //未点击的图片 unClickBitmap = BitmapFactory.decodeResource(getResources(), unClickDrawableRid); setLayoutParams(new LinearLayout.LayoutParams(clickBitmap.getWidth(), clickBitmap.getHeight())); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mAlpha = 0; } public void setUiAlpha(int alpha) { mAlpha = alpha; invalidate(); //重新调用onDraw方法 } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); int with = unClickBitmap.getWidth(); int height = unClickBitmap.getHeight(); rect = new Rect(0, 0, with, height); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mPaint != null) { mPaint.setAlpha(255 - mAlpha); canvas.drawBitmap(unClickBitmap, null, rect, mPaint); mPaint.setAlpha(mAlpha); canvas.drawBitmap(clickBitmap, null, rect, mPaint); } } }
package commands.client.game.sync; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public final class SyncCommandsUtil { private SyncCommandsUtil() {} public static Map<String, SyncGameClientCommand> generateMapForSameCommand( String name, Set<String> otherNames, SyncGameClientCommand command ) { Map<String, SyncGameClientCommand> map = otherNames.stream().collect(Collectors.toMap(n -> n, n -> command)); map.put(name, command); return map; } public static Map<String, SyncGameClientCommand> generateMapForDifferentCommand( String name, Set<String> otherNames, SyncGameClientCommand selfCommand, SyncGameClientCommand othersCommand ) { Map<String, SyncGameClientCommand> map = otherNames.stream().collect(Collectors.toMap(n -> n, n -> othersCommand)); map.put(name, selfCommand); return map; } }
package com.javarush.task.task22.task2211; import java.io.*; import java.nio.charset.Charset; /* Смена кодировки */ public class Solution { public static void main(String[] args) throws IOException { String nameFile = args[0]; String nameFileTo = args[0]; Charset charsetFrom = Charset.forName("Windows-1251"); Charset charsetTo = Charset.forName("UTF-8"); String string = ""; try(InputStream reader = new FileInputStream(nameFile)) { byte[] b = new byte[1000]; while (reader.available() != 0){ reader.read(b); string = string.concat(new String(b, charsetFrom)); } } try(OutputStream writer = new FileOutputStream(nameFileTo)){ writer.write(string.getBytes(charsetTo)); } } }
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.config.annotation; import java.util.ArrayList; import java.util.List; import org.springframework.cache.Cache; import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.web.servlet.resource.CachingResourceResolver; import org.springframework.web.servlet.resource.CachingResourceTransformer; import org.springframework.web.servlet.resource.CssLinkResourceTransformer; import org.springframework.web.servlet.resource.PathResourceResolver; import org.springframework.web.servlet.resource.ResourceResolver; import org.springframework.web.servlet.resource.ResourceTransformer; import org.springframework.web.servlet.resource.VersionResourceResolver; import org.springframework.web.servlet.resource.WebJarsResourceResolver; /** * Assists with the registration of resource resolvers and transformers. * * @author Rossen Stoyanchev * @since 4.1 */ public class ResourceChainRegistration { private static final String DEFAULT_CACHE_NAME = "spring-resource-chain-cache"; private static final boolean isWebJarsAssetLocatorPresent = ClassUtils.isPresent( "org.webjars.WebJarAssetLocator", ResourceChainRegistration.class.getClassLoader()); private final List<ResourceResolver> resolvers = new ArrayList<>(4); private final List<ResourceTransformer> transformers = new ArrayList<>(4); private boolean hasVersionResolver; private boolean hasPathResolver; private boolean hasCssLinkTransformer; private boolean hasWebjarsResolver; public ResourceChainRegistration(boolean cacheResources) { this(cacheResources, (cacheResources ? new ConcurrentMapCache(DEFAULT_CACHE_NAME) : null)); } public ResourceChainRegistration(boolean cacheResources, @Nullable Cache cache) { Assert.isTrue(!cacheResources || cache != null, "'cache' is required when cacheResources=true"); if (cacheResources) { this.resolvers.add(new CachingResourceResolver(cache)); this.transformers.add(new CachingResourceTransformer(cache)); } } /** * Add a resource resolver to the chain. * @param resolver the resolver to add * @return the current instance for chained method invocation */ public ResourceChainRegistration addResolver(ResourceResolver resolver) { Assert.notNull(resolver, "The provided ResourceResolver should not be null"); this.resolvers.add(resolver); if (resolver instanceof VersionResourceResolver) { this.hasVersionResolver = true; } else if (resolver instanceof PathResourceResolver) { this.hasPathResolver = true; } else if (resolver instanceof WebJarsResourceResolver) { this.hasWebjarsResolver = true; } return this; } /** * Add a resource transformer to the chain. * @param transformer the transformer to add * @return the current instance for chained method invocation */ public ResourceChainRegistration addTransformer(ResourceTransformer transformer) { Assert.notNull(transformer, "The provided ResourceTransformer should not be null"); this.transformers.add(transformer); if (transformer instanceof CssLinkResourceTransformer) { this.hasCssLinkTransformer = true; } return this; } protected List<ResourceResolver> getResourceResolvers() { if (!this.hasPathResolver) { List<ResourceResolver> result = new ArrayList<>(this.resolvers); if (isWebJarsAssetLocatorPresent && !this.hasWebjarsResolver) { result.add(new WebJarsResourceResolver()); } result.add(new PathResourceResolver()); return result; } return this.resolvers; } protected List<ResourceTransformer> getResourceTransformers() { if (this.hasVersionResolver && !this.hasCssLinkTransformer) { List<ResourceTransformer> result = new ArrayList<>(this.transformers); boolean hasTransformers = !this.transformers.isEmpty(); boolean hasCaching = hasTransformers && this.transformers.get(0) instanceof CachingResourceTransformer; result.add(hasCaching ? 1 : 0, new CssLinkResourceTransformer()); return result; } return this.transformers; } }
package otf.obj.msg.remote; import otf.model.ServerDataModel; /** * @author &#8904 * */ public class GetBolusFactorsRequest implements ExecutableRequest { /** * @see otf.obj.msg.remote.ExecutableRequest#execute() */ @Override public ExecutableResponse execute() { var factors = ServerDataModel.get().getBolusFactors(); var response = new GetBolusFactorsResponse(); response.setBolusFactors(factors); return response; } }
package tailminuseff.io; import eventutil.*; import java.io.File; import java.util.concurrent.Callable; public abstract class FileMonitor implements Callable<Void>, EventProducer<FileMonitorListener> { private final EventListenerList<FileMonitorListener> listeners = new EventListenerList<FileMonitorListener>(); private final File file; private boolean lastEventWasLine = true; public FileMonitor(File file) { this.file = file; } @Override public void addListener(FileMonitorListener listener) { listeners.addListener(listener); } public File getFile() { return file; } protected void invokeListenersWithAdded(String line) { lastEventWasLine = true; final LineAddedEvent evt = new LineAddedEvent(this, line); listeners.forEachLisener(listener -> listener.lineRead(evt)); } protected void invokeListenersWithReset() { if (lastEventWasLine) { final FileResetEvent evt = new FileResetEvent(this); listeners.forEachLisener(listener -> listener.fileReset(evt)); } lastEventWasLine = false; } @Override public void removeListener(FileMonitorListener listener) { listeners.removeListener(listener); } }
public class RealnumberInterval_V2{ public static void main(String [] args){ //Variabler.... int zeroToOne = 0; int oneToTwo = 0; int twoToThree = 0; int threeToFour = 0; int fourToFive = 0; int fiveToSix = 0; int sixToSeven = 0; int sevenToEight = 0; int eightToNine = 0; int nineToTen = 0; int max = 0; System.out.print("Write some numbers: "); while( !StdIn.isEmpty() ){ double number = StdIn.readDouble(); if(number >= 0 && number < 0.1){ zeroToOne++; if(zeroToOne > max){ max = zeroToOne; } } else if(number >= 0.1 && number < 0.2){ oneToTwo++; if(oneToTwo > max){ max = oneToTwo; } } else if(number >= 0.2 && number < 0.3){ twoToThree++; if(twoToThree > max){ max = twoToThree; } } else if(number >= 0.3 && number < 0.4){ threeToFour++; if(threeToFour > max){ max = threeToFour; } } else if(number >= 0.4 && number < 0.5){ fourToFive++; if(fourToFive > max){ max = fourToFive; } } else if(number >= 0.5 && number < 0.6){ fiveToSix++; if(fiveToSix > max){ max = fiveToSix; } } else if(number >= 0.6 && number < 0.7){ sixToSeven++; if(sixToSeven > max){ max = sixToSeven; } } else if(number >= 0.7 && number < 0.8){ sevenToEight++; if(sevenToEight > max){ max = sevenToEight; } } else if(number >= 0.8 && number < 0.9){ eightToNine++; if(eightToNine > max){ max = eightToNine; } } else if(number >= 0.9 && number < 1.0){ nineToTen++; if(nineToTen > max){ max = nineToTen; } } } //Printing... System.out.println("Tal mellan 0 och 0.1: " + zeroToOne); System.out.println("Tal mellan 0.1 och 0.2: " + oneToTwo); System.out.println("Tal mellan 0.2 och 0.3: " + twoToThree); System.out.println("Tal mellan 0.3 och 0.4: " + threeToFour); System.out.println("Tal mellan 0.4 och 0.5: " + fourToFive); System.out.println("Tal mellan 0.5 och 0.6: " + fiveToSix); System.out.println("Tal mellan 0.6 och 0.7: " + sixToSeven); System.out.println("Tal mellan 0.7 och 0.8: " + sevenToEight); System.out.println("Tal mellan 0.8 och 0.9: " + eightToNine); System.out.println("Tal mellan 0.9 och 1.0: " + nineToTen); //Setting scale of StdDraw double x0 = 0; double x1 = 2; double y0 = 0; double y1 = max; StdDraw.setYscale(y0, y1); StdDraw.setXscale(x0, x1); //Drawing stuff //StdDraw.line(x0,y0,x1,y1) //Staple 0-0.1 StdDraw.line(0,0,0,zeroToOne); StdDraw.line(0,zeroToOne,0.1,zeroToOne); StdDraw.line(0.1,zeroToOne,0.1,0); //Staple 0.1-0.2 StdDraw.line(0.2,0,0.2,oneToTwo); StdDraw.line(0.2,oneToTwo,0.3,oneToTwo); StdDraw.line(0.3,oneToTwo,0.3,0); //Staple 0.2-0.3 StdDraw.line(0.4,0,0.4,twoToThree); StdDraw.line(0.4,twoToThree,0.5,twoToThree); StdDraw.line(0.5,twoToThree,0.5, 0); //Staple 0.3-0.4 StdDraw.line(0.6,0,0.6,threeToFour); StdDraw.line(0.6,threeToFour,0.7,threeToFour); StdDraw.line(0.7,threeToFour,0.7,0); //Staple 0.4-0.5 StdDraw.line(0.8,0,0.8,fourToFive); StdDraw.line(0.8,fourToFive,0.9,fourToFive); StdDraw.line(0.9,fourToFive,0.9,0); //Staple 0.5-0.6 StdDraw.line(1.0,0,1.0,fiveToSix); StdDraw.line(1.0,fiveToSix,1.1,fiveToSix); StdDraw.line(1.1,fiveToSix,1.1,0); //Staple 0.6-0.7 StdDraw.line(1.2,0,1.2,sixToSeven); StdDraw.line(1.2,sixToSeven,1.3,sixToSeven); StdDraw.line(1.3,sixToSeven,1.3,0); //Staple 0.7-0.8 StdDraw.line(1.4,0,1.4,sevenToEight); StdDraw.line(1.4,sevenToEight,1.5,sevenToEight); StdDraw.line(1.5,sevenToEight,1.5,0); //Staple 0.8-0.9 StdDraw.line(1.6,0,1.6,eightToNine); StdDraw.line(1.6,eightToNine,1.7,eightToNine); StdDraw.line(1.7,eightToNine,1.7,0); //Staple 0.9-1.0 StdDraw.line(1.8,0,1.8,nineToTen); StdDraw.line(1.8,nineToTen,1.9,nineToTen); StdDraw.line(1.9,nineToTen,1.9,0); } }
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.recovery.dto; /** * Object that encapsulates the password recovery notification for a successful password recovery. */ public class PasswordRecoverDTO { /** * Response code. */ private String code; /** * Description about the response. */ private String message; /** * User notified channel. */ private String notificationChannel; /** * Confirmation code for notifications external management. * NOTE: This will be used when the notification channel is EXTERNAL. */ private String confirmationCode; /** * Code to resend recovery information to the user. */ private String resendCode; /** * Get the resend code. * * @return Resend code */ public String getResendCode() { return resendCode; } /** * Set resend code. * * @param resendCode Resend code */ public void setResendCode(String resendCode) { this.resendCode = resendCode; } /** * Get the response code. * * @return Response code */ public String getCode() { return code; } /** * Set the response code. * * @param code Response code */ public void setCode(String code) { this.code = code; } /** * Get the response message. * * @return Response message */ public String getMessage() { return message; } /** * Set the response message. * * @param message Response message */ public void setMessage(String message) { this.message = message; } /** * Get the channel which the notification was sent. * * @return Notification channel */ public String getNotificationChannel() { return notificationChannel; } /** * Set the channel which the notification was sent. * * @param notificationChannel Notification channel */ public void setNotificationChannel(String notificationChannel) { this.notificationChannel = notificationChannel; } /** * Get external confirmation code. * * @return External confirmation code */ public String getConfirmationCode() { return confirmationCode; } /** * Set external confirmation code. * * @param confirmationCode External confirmation code. */ public void setConfirmationCode(String confirmationCode) { this.confirmationCode = confirmationCode; } }
package io.redspark.gestta; import android.content.Intent; import android.support.design.widget.TextInputLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.afollestad.materialdialogs.MaterialDialog; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import io.redspark.gestta.database.User; import io.redspark.gestta.managers.LoginManager; import io.redspark.gestta.restfull.utils.IServiceResponse; public class LoginActivity extends AppCompatActivity { static final private String TAG = LoginActivity.class.getSimpleName(); @BindView(R.id.activity_login_input_layout_user) protected TextInputLayout mInputLayoutUser; @BindView(R.id.activity_login_input_layout_password) protected TextInputLayout mInputLayoutPassword; private final LoginManager mLoginManager = new LoginManager(); private MaterialDialog mProgressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ButterKnife.bind(this); mInputLayoutUser.getEditText().setText("markuscosta@gestta.com.br"); mInputLayoutPassword.getEditText().setText("123456aS"); } @OnClick(R.id.activity_login_button_enter) protected void performLogin() { String user = mInputLayoutUser.getEditText().getText().toString(); String password = mInputLayoutPassword.getEditText().getText().toString(); Log.d(TAG, "Perform Login - User: " + user + " | Password: " + password); mProgressDialog = new MaterialDialog.Builder(this) .cancelable(false) .widgetColorRes(R.color.primaryButton) .title("Aguarde") .content("Processando dados") .progress(true, 0) .show(); mLoginManager.performLogin(user, password, new IServiceResponse<User>() { @Override public void onSuccess(User data) { mProgressDialog.dismiss(); Toast.makeText(LoginActivity.this, "Bem Vindo " + data.getName(), Toast.LENGTH_LONG).show(); Intent goToMain = new Intent(LoginActivity.this, MainActivity.class); goToMain.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK ); startActivity(goToMain); } @Override public void onError(String error) { mProgressDialog.dismiss(); Log.e(TAG, error); } }); } @OnClick(R.id.activity_login_button_forgot) protected void openForgotPasswordScreen() { Intent goToForgotPassword = new Intent(this, ForgotPasswordActivity.class); startActivity(goToForgotPassword); } }
package com.example.shreyesh.sarinstituteofmedicalscience; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Locale; import static java.util.Locale.US; public class BookAppointmentActivity extends AppCompatActivity { private Toolbar bookAppointmentToolbar; private EditText appointmentDate, appointmentTime; private Button confirm; private String userid, username; private DatabaseReference doctorRef, appointmentRef, aRef; private FirebaseAuth firebaseAuth; private TextView doctorsName; private String currentUserID; private String[] days; private boolean res; private Calendar myCalender = Calendar.getInstance(); private Calendar mcurrentTime = Calendar.getInstance(); private int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY); private int minute = mcurrentTime.get(Calendar.MINUTE); private TimePickerDialog mTimePicker; private int c = 0; private Date actualFrom, actualTo; private String from, to, chosenTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_book_appointment); userid = getIntent().getStringExtra("userid"); username = getIntent().getStringExtra("username"); //Initialize views bookAppointmentToolbar = (Toolbar) findViewById(R.id.bookAppointmentToolbar); setSupportActionBar(bookAppointmentToolbar); getSupportActionBar().setTitle("Book Appointment"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); days = new String[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; firebaseAuth = FirebaseAuth.getInstance(); currentUserID = firebaseAuth.getCurrentUser().getUid(); appointmentDate = (EditText) findViewById(R.id.appointmentDate); appointmentTime = (EditText) findViewById(R.id.appointmentTime); confirm = (Button) findViewById(R.id.confirmAppointment); doctorsName = (TextView) findViewById(R.id.doctorNameAppointment); doctorsName.setText("Dr. " + username); doctorRef = FirebaseDatabase.getInstance().getReference().child("doctors"); appointmentRef = FirebaseDatabase.getInstance().getReference().child("appointments"); aRef = appointmentRef.child(currentUserID); final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int i, int i1, int i2) { myCalender.set(Calendar.YEAR, i); myCalender.set(Calendar.MONTH, i1); myCalender.set(Calendar.DAY_OF_MONTH, i2); updateLabel(); } }; appointmentDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new DatePickerDialog(BookAppointmentActivity.this, date, myCalender.get(Calendar.YEAR), myCalender.get(Calendar.MONTH), myCalender.get( Calendar.DAY_OF_MONTH)).show(); } }); appointmentTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mTimePicker = new TimePickerDialog(BookAppointmentActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) { String am_pm = "AM"; if (selectedHour > 12) { selectedHour = selectedHour - 12; am_pm = "PM"; } appointmentTime.setText(selectedHour + ":" + selectedMinute + " " + am_pm); } }, hour, minute, false);//Yes 24 hour time mTimePicker.setTitle("Select Time"); mTimePicker.show(); } }); confirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final String aDate = appointmentDate.getText().toString(); final String aTime = appointmentTime.getText().toString(); appointmentRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { res = true; c = 0; if (dataSnapshot.exists() && dataSnapshot.hasChildren()) { final Date date1 = new Date(aDate); final Calendar current = Calendar.getInstance(); current.set(Calendar.HOUR, 0); current.set(Calendar.MINUTE, 0); current.set(Calendar.SECOND, 0); current.set(Calendar.MILLISECOND, 0); final Date currentDate = current.getTime(); Calendar calendar = Calendar.getInstance(); calendar.setTime(date1); int day = calendar.get(Calendar.DAY_OF_WEEK); final String dayOfWeek = days[day - 1]; System.out.println("Day of week " + dayOfWeek); if (date1.before(currentDate)) { res = false; Toast.makeText(BookAppointmentActivity.this, "Cannot select past date", Toast.LENGTH_SHORT).show(); return; } for (DataSnapshot d1 : dataSnapshot.getChildren()) { for (DataSnapshot d : d1.getChildren()) { final String at = d.child("time").getValue().toString(); final String ad = d.child("date").getValue().toString(); final String id = d.child("doctorid").getValue().toString(); System.out.println(at); System.out.println(ad); System.out.println(id); final SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm"); final SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a"); if (at.equals(aTime) && ad.equals(aDate) && id.equals(userid)) { res = false; Toast.makeText(BookAppointmentActivity.this, "Not Available at this time", Toast.LENGTH_SHORT).show(); return; } doctorRef.child(userid).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.child(dayOfWeek.toLowerCase()).getValue().toString().equals("Not Available")) { res = false; if (c == 0) Toast.makeText(BookAppointmentActivity.this, "Doctor not available on this Day of the Week", Toast.LENGTH_SHORT).show(); c = 1; return; } else { if (c == 0) { System.out.println("This is "); String time[] = dataSnapshot.child(dayOfWeek.toLowerCase()).getValue().toString().split("-"); try { actualFrom = parseFormat.parse(time[0].substring(0, time[0].length() - 2) + ":00 " + time[0].substring(time[0].length() - 2)); actualTo = parseFormat.parse(time[1].substring(0, time[1].length() - 2) + ":00 " + time[1].substring(time[1].length() - 2)); from = displayFormat.format(actualFrom); to = displayFormat.format(actualTo); from = from.substring(0, from.indexOf(":")); to = to.substring(0, to.indexOf(":")); Date d = parseFormat.parse(aTime); chosenTime = displayFormat.format(d); chosenTime = chosenTime.substring(0, chosenTime.indexOf(":")); } catch (Exception e) { } System.out.println(from); System.out.println(to); if (!(Integer.parseInt(chosenTime) >= Integer.parseInt(from) && Integer.parseInt(chosenTime) <= Integer.parseInt(to))) { Toast.makeText(BookAppointmentActivity.this, "Time Outside Doctor's Hours", Toast.LENGTH_SHORT).show(); c = 1; return; } HashMap<String, String> appointmentMap = new HashMap<>(); appointmentMap.put("date", aDate); appointmentMap.put("time", aTime); appointmentMap.put("doctor", username); appointmentMap.put("doctorid", userid); aRef.push().setValue(appointmentMap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(BookAppointmentActivity.this, "Success", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(BookAppointmentActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } } }); c = 1; return; } } } @Override public void onCancelled(DatabaseError databaseError) { } }); if (res == false) break; } if (res == false) return; } } else { final Date date1 = new Date(aDate); final Calendar current = Calendar.getInstance(); current.set(Calendar.HOUR, 0); current.set(Calendar.MINUTE, 0); current.set(Calendar.SECOND, 0); current.set(Calendar.MILLISECOND, 0); final Date currentDate = current.getTime(); Calendar calendar = Calendar.getInstance(); calendar.setTime(date1); int day = calendar.get(Calendar.DAY_OF_WEEK); final String dayOfWeek = days[day - 1]; if (date1.before(currentDate)) { Toast.makeText(BookAppointmentActivity.this, "Cannot select past date", Toast.LENGTH_SHORT).show(); return; } doctorRef.child(userid).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.child(dayOfWeek.toLowerCase()).getValue().toString().equals("Not Available")) { Toast.makeText(BookAppointmentActivity.this, "Doctor not available on this Day of the Week", Toast.LENGTH_SHORT).show(); return; } HashMap<String, String> appointmentMap = new HashMap<>(); appointmentMap.put("date", aDate); appointmentMap.put("time", aTime); appointmentMap.put("doctor", username); appointmentMap.put("doctorid", userid); aRef.push().setValue(appointmentMap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(BookAppointmentActivity.this, "Success", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(BookAppointmentActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } } }); } @Override public void onCancelled(DatabaseError databaseError) { } }); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } }); } private void updateLabel() { String myFormat = "MM/dd/yyyy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(myFormat, US); appointmentDate.setText(simpleDateFormat.format(myCalender.getTime())); } }
package com.leejua.myproject.members; import lombok.*; import org.springframework.context.annotation.Lazy; import javax.persistence.*; import javax.validation.constraints.NotNull; @Lazy @Setter @Getter @ToString @Entity(name="member") @NoArgsConstructor public class Member { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long memberSeq; @Column(length = 30) @NotNull private String email; @Column(length = 20) @NotNull private String passwd; @Builder public Member(String email, String passwd){ this.email = email; this.passwd = passwd; } }
package io.nuls.cmd.client.processor.dex; import io.nuls.base.api.provider.Result; import io.nuls.base.api.provider.ServiceManager; import io.nuls.base.api.provider.dex.DexProvider; import io.nuls.base.api.provider.dex.facode.CoinTradingReq; import io.nuls.base.api.provider.dex.facode.EditTradingReq; import io.nuls.cmd.client.CommandBuilder; import io.nuls.cmd.client.CommandResult; import io.nuls.cmd.client.config.Config; import io.nuls.cmd.client.processor.CommandGroup; import io.nuls.cmd.client.processor.CommandProcessor; import io.nuls.cmd.client.utils.AssetsUtil; import io.nuls.core.core.annotation.Autowired; import io.nuls.core.core.annotation.Component; import java.math.BigInteger; @Component public class CreateTradingProcess implements CommandProcessor { @Autowired Config config; DexProvider dexProvider = ServiceManager.get(DexProvider.class); @Override public String getCommand() { return "createTrading"; } @Override public CommandGroup getGroup() { return CommandGroup.Dex; } @Override public String getHelp() { CommandBuilder builder = new CommandBuilder(); builder.newLine(getCommandDescription()) .newLine("\t<address> trading owner address -required") .newLine("\t<password> password -required") .newLine("\t<quoteAssetChainId> assetChainId of quote coin -required") .newLine("\t<quoteAssetId> assetId of quote coin -required") .newLine("\t<baseAssetChainId> assetChainId of base coin -required") .newLine("\t<baseAssetId> assetId of base coin -required") .newLine("\t<scaleQuoteDecimal> minimum reserved number of quote coin -required") .newLine("\t<scaleBaseDecimal> minimum reserved number of base coin -required") .newLine("\t<minQuoteAmount> Minimum transaction amount of quote coin -required") .newLine("\t<minBaseAmount> Minimum transaction amount of base coin -required"); return builder.toString(); } @Override public String getCommandDescription() { return "createTrading <address> <password> <quoteAssetChainId> <quoteAssetId> <baseAssetChainId> <baseAssetId> <scaleQuoteDecimal> <scaleBaseDecimal> <minQuoteAmount> <minBaseAmount> --create the coin trading"; } @Override public boolean argsValidate(String[] args) { checkArgsNumber(args, 10); checkAddress(config.getChainId(), args[1]); checkIsNumeric(args[3], "quoteAssetChainId"); checkIsNumeric(args[4], "quoteAssetId"); checkIsNumeric(args[5], "baseAssetChainId"); checkIsNumeric(args[6], "baseAssetId"); checkIsNumeric(args[7], "scaleQuoteDecimal"); checkIsNumeric(args[8], "scaleBaseDecimal"); checkIsDouble(args[9], "minQuoteAmount"); checkIsDouble(args[10], "minBaseAmount"); return true; } @Override public CommandResult execute(String[] args) { String address = args[1]; String password = args[2]; int quoteAssetChainId = Integer.parseInt(args[3]); int quoteAssetId = Integer.parseInt(args[4]); int baseAssetChainId = Integer.parseInt(args[5]); int baseAssetId = Integer.parseInt(args[6]); int scaleQuoteDecimal = Integer.parseInt(args[7]); int scaleBaseDecimal = Integer.parseInt(args[8]); int quoteDecimal = AssetsUtil.getAssetDecimal(quoteAssetChainId, quoteAssetId); int baseDecimal = AssetsUtil.getAssetDecimal(baseAssetChainId, baseAssetId); BigInteger minQuoteAmount = config.toSmallUnit(args[9], quoteDecimal); BigInteger minBaseAmount = config.toSmallUnit(args[10], baseDecimal); CoinTradingReq req = new CoinTradingReq(address, password, quoteAssetChainId,quoteAssetId,baseAssetChainId,baseAssetId, scaleQuoteDecimal, scaleBaseDecimal, minQuoteAmount, minBaseAmount); Result<String> result = dexProvider.createTrading(req); if (result.isFailed()) { return CommandResult.getFailed(result); } return CommandResult.getSuccess(result); } }
package com.worldchip.bbp.ect.service; import java.util.Calendar; import java.util.List; import com.worldchip.bbp.ect.activity.MyApplication; import com.worldchip.bbp.ect.db.ClockData; import com.worldchip.bbp.ect.db.DBGoldHelper; import com.worldchip.bbp.ect.entity.AlarmInfo; import com.worldchip.bbp.ect.receiver.AlarmReceiver; import com.worldchip.bbp.ect.util.HttpCommon; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.IBinder; public class BootService extends Service { @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); List<AlarmInfo> alarms = ClockData.getAllEnableClockAlarm(this); if (alarms != null && alarms.size() > 0) { for (AlarmInfo alarm : alarms) { int hours = alarm.getHours(); int musutes = alarm.getMusutes(); String time = ""; if(hours > 0 && hours < 24) { if(hours > 0 && hours < 10) { time = time + 0 + hours + ":"; }else{ time = time + hours + ":"; } }else{ time = time + "00" + ":"; } if(musutes > 0 && musutes < 60) { if(musutes > 0 && musutes < 10) { time = time + 0 + musutes; }else{ time = time + musutes; } }else{ time = time + "00"; } String weeks = alarm.getDaysofweek(); if(!weeks.equals("-1") && weeks != "-1") { int week[] = HttpCommon.stringToInts(weeks); for (int i = 0; i < week.length; i++) { if(HttpCommon.isThanTime(time.trim())) { setAlarm(alarm,week[i]); } } }else{ if(HttpCommon.isThanTime(time.trim())) { setEveryDayAlarm(alarm); } } } } } private void setAlarm(AlarmInfo alarm,int today) { AlarmManager am = (AlarmManager) this.getSystemService(Activity.ALARM_SERVICE); Intent intent = new Intent(this, AlarmReceiver.class); PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0); Calendar c = Calendar.getInstance(); c.set(Calendar.DAY_OF_WEEK, today); c.set(Calendar.HOUR_OF_DAY, alarm.getHours()); c.set(Calendar.MINUTE, alarm.getMusutes()); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi); am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 10000, pi); } private void setEveryDayAlarm(AlarmInfo alarm) { AlarmManager am = (AlarmManager) this.getSystemService(Activity.ALARM_SERVICE); Intent intent = new Intent(this, AlarmReceiver.class); PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0); Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, alarm.getHours()); c.set(Calendar.MINUTE, alarm.getMusutes()); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi); am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pi); } }
// FileUtil.java package org.google.code.netapps.scriptrunner; import java.io.*; /** * This class is a container of static methods for common usage. * * @version 1.0 05/16/2001 * @author Alexander Shvets */ public class FileUtil { /** * Disables creation of this class instances */ private FileUtil() {} /** * Gets the file content in form of bytes array. * * @param fileName the name of file to be converted * @return the content of a file in form of bytes array * @exception IOException if an I/O error occurs. */ public static byte[] getFileAsBytes(String fileName) throws IOException { File file = new File(fileName); FileInputStream fis = new FileInputStream(file); byte buffer[] = new byte[(int)file.length()]; fis.read(buffer); fis.close(); return buffer; } /** * Copies content from archive to a file * * @exception IOException if an I/O error occurs. */ public static void writeToFile(byte[] buffer, String fileName) throws IOException { OutputStream out = new BufferedOutputStream( new FileOutputStream(fileName), 4096); try { out.write(buffer); out.flush(); } finally { if(out != null) { out.close(); } } } /** * Deletes file (ordinary file or complete directory) * * @param file the file object */ public static void deleteFile(File file) { if(file.isDirectory()) { String[] list = file.list(); for(int i=0; i < list.length; i++) { deleteFile(new File(file + "/" + list[i])); } } file.delete(); } /** * Gets the extension for a given file name. * * @param fileName the name of file * @return the extension */ public static String getExtension(String fileName) { int index = fileName.lastIndexOf("."); if(index != -1) { return fileName.substring(index + 1).toLowerCase(); } return null; } }
package com.ca.rs.map; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import cucumber.api.DataTable; import gherkin.formatter.model.DataTableRow; import org.json.JSONException; import org.json.JSONObject; import javax.annotation.Nullable; import java.util.*; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; /** * Static class for turning a DataTable into a Map<String, String> */ public class DataTableParser { public static ImmutableMap<String, String> parseTemplateParamsDataTable(@Nullable DataTable dataTable) { // technically this is different from parseJsonDataTable, although practically not if (dataTable != null) { return parseSimpleMapDataTable(dataTable, "key", "value"); } else { return ImmutableMap.of(); } } public static ImmutableMap<String, List<String>> parseTemplateWithListParamsDataTable(@Nullable DataTable dataTable) { // technically this is different from parseJsonDataTable, although practically not if (dataTable != null) { return parseListedMapDataTable(dataTable, "key", "value"); } else { return ImmutableMap.of(); } } public static List<JSONObject> parseMultiObjectDataTable(@Nullable DataTable dataTable) throws JSONException { // technically this is different from parseJsonDataTable, although practically not if (dataTable != null) { return parseDataTableToJsonObject(dataTable, "key", "value"); } else { return (List<JSONObject>) JSONObject.NULL; } } private static ImmutableMap<String, String> parseSimpleMapDataTable(DataTable dataTable, String keyName, String valueName) { checkNotNull(dataTable, "data table must not be null"); checkNotNull(keyName, "key name must not be null"); checkNotNull(valueName, "value name must not be null"); List<DataTableRow> gherkinRows = dataTable.getGherkinRows(); ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); for (int i = 0; i < gherkinRows.size(); i++) { DataTableRow row = gherkinRows.get(i); checkArgument(row.getCells().size() == 2, "Expected 2 cells but got %s at line %s", row.getCells().size(), row.getLine()); Iterator<String> it = row.getCells().iterator(); String name = checkNotNullNorEmpty(it.next(), keyName + " column"); String value = checkNotNullNorEmpty(it.next(), valueName + " column"); // skip header if present if (i == 0 && keyName.equalsIgnoreCase(name) && valueName.equalsIgnoreCase(value)) { continue; } builder.put(name, value); } return builder.build(); } private static List<JSONObject> parseDataTableToJsonObject(DataTable dataTable, String keyName, String valueName) throws JSONException { checkNotNull(dataTable, "data table must not be null"); checkNotNull(keyName, "key name must not be null"); checkNotNull(valueName, "value name must not be null"); List<DataTableRow> gherkinRows = dataTable.getGherkinRows(); Map<String, JSONObject> map = new HashMap<>(); for (int i = 1; i < gherkinRows.size(); i++) { DataTableRow row = gherkinRows.get(i); Iterator<String> it = row.getCells().iterator(); String name = checkNotNullNorEmpty(it.next(), keyName + " column"); String value = checkNotNullNorEmpty(it.next(), valueName + " column"); if (map.keySet().contains(name.split("\\W")[0])) { JSONObject jsonObject = map.get(name.split("\\W")[0]); jsonObject.put(name.split("\\W")[1], value); } else { JSONObject jsonObject = new JSONObject(); jsonObject.put(name.split("\\W")[1], value); map.put(name.split("\\W")[0], jsonObject); } } return new ArrayList(map.values()); } private static ImmutableMap<String, List<String>> parseListedMapDataTable(DataTable dataTable, String keyName, String valueName) { checkNotNull(dataTable, "data table must not be null"); checkNotNull(keyName, "key name must not be null"); checkNotNull(valueName, "value name must not be null"); List<DataTableRow> gherkinRows = dataTable.getGherkinRows(); Map<String, List<String>> builderMap = Maps.newHashMap(); for (int i = 0; i < gherkinRows.size(); i++) { DataTableRow row = gherkinRows.get(i); checkArgument(row.getCells().size() == 2, "Expected 2 cells but got %s at line %s", row.getCells().size(), row.getLine()); Iterator<String> it = row.getCells().iterator(); String name = checkNotNullNorEmpty(it.next(), keyName + " column"); String value = checkNotNullNorEmpty(it.next(), valueName + " column"); // skip header if present if (i == 0 && keyName.equalsIgnoreCase(name) && valueName.equalsIgnoreCase(value)) { continue; } if (!builderMap.containsKey(name)) { builderMap.put(name, Lists.newArrayList()); } builderMap.get(name).add(value); } ImmutableMap.Builder<String, List<String>> builder = ImmutableMap.builder(); for (String key : builderMap.keySet()) { builder.put(key, ImmutableList.copyOf(builderMap.get(key))); } return builder.build(); } private static <T extends CharSequence> T checkNotNullNorEmpty(T cs, String propertyName) { checkNotNull(cs, "%s must not be null", propertyName); checkNotNull(propertyName, "propertyName must not be null"); checkArgument(cs.length() > 0, "%s must not be empty", propertyName); return cs; } }
package com.GestiondesClub.services; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.GestiondesClub.dao.EvenementRepository; import com.GestiondesClub.dto.ClubMembreDto; import com.GestiondesClub.dto.DemandeFinacneAll; import com.GestiondesClub.dto.Evenementdto; import com.GestiondesClub.dto.EventAllAffiche; import com.GestiondesClub.dto.eventProgDto; import com.GestiondesClub.entities.Club; import com.GestiondesClub.entities.DemandeAffiche; import com.GestiondesClub.entities.Evenement; import com.GestiondesClub.entities.ProgrammeEvent; @Service public class EvenementService { @Autowired private EvenementRepository eventRespo; public List<Evenementdto> getAllEvent() { return eventRespo.findAllEventBy(); } public Optional<Evenement> getEvenement(Long id) { return eventRespo.findById(id); } public Evenement save(Evenement event) { return eventRespo.save(event); } public List<Evenementdto> getEventsByClub(Club club) { return eventRespo.findByDemandeEvenementLeClub(club); } public eventProgDto findEventById(Long id) { return eventRespo.findEventById(id); } public List<EventAllAffiche> FindAllDemAff() { return eventRespo.findAllAfficheBy(); } public EventAllAffiche findAfficheEvent(long id) { return eventRespo.findByLesDemandeAfficheId(id); } public List<DemandeAffiche> saveDemAffiche(Evenement event) { Evenement e = eventRespo.save(event); return e.getLesDemandeAffiche(); } public Optional<Evenement> findById(long id) { return eventRespo.findById(id); } public List<DemandeFinacneAll> getAllDemFinance() { return eventRespo.findAllDemandeFinanceBy(); } public List<Evenementdto> getAllNotExp() { return eventRespo.findByDemandeEvenementDatePrevuEventAfterAndPublication(new Date(),true); } public Evenementdto findEvenementById(long id) { return eventRespo.findEventById(id); } }
package io.jee.alaska.util; import java.util.Random; import org.apache.commons.lang3.StringUtils; @Deprecated public class RandomUtils { public final static String ALL = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public final static String NUMBER = "0123456789"; public final static String UPPERCASS_AND_NUMBER = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public final static String LOWERCASS = "abcdefghijklmnopqrstuvwxyz"; public static String getRandom(String base, int length){ Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); } public static String getLetterAndNumber(int length){ String result = getRandom(ALL, length); while (StringUtils.isAlpha(result)||StringUtils.isNumeric(result)) { result = getRandom(ALL, length); } return result; } public static String getLetter(int length){ String result = getRandom(LOWERCASS, length); return result; } public static String getAll(int length) { return getRandom(ALL, length); } public static String getNumber(int length) { // length表示生成字符串的长度 return getRandom(NUMBER, length); } public static String getNumberFristNotZero(int length){ Random random = new Random(); StringBuffer sb = new StringBuffer(); boolean frist = true; for (int i = 0; i < length; i++) { int number = random.nextInt(NUMBER.length()); char f = NUMBER.charAt(number); if(frist){ while(f == '0'){ f = NUMBER.charAt(number); } frist = false; } sb.append(f); } return sb.toString(); } }
/* * 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 javafxservice; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.ChoiceBox; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; /** * * @author Mathew */ public class AddUserSceneController implements Initializable { @FXML private TextField username_fx; @FXML private PasswordField passwd_fx; @FXML private TextField name_fx; @FXML private TextField surname_fx; @FXML private ChoiceBox user_type_fx; @FXML private void handleAddOrder(ActionEvent event) throws IOException { String username = username_fx.getText(); String passwd = passwd_fx.getText(); String name = name_fx.getText(); String surname = surname_fx.getText(); int user_type = user_type_fx.getSelectionModel().getSelectedIndex(); if (username.equals("")) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error"); alert.setHeaderText(null); alert.setContentText("Please enter username!"); alert.showAndWait(); } else { if (passwd.equals("")) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error"); alert.setHeaderText(null); alert.setContentText("Please enter password!"); alert.showAndWait(); } else { if (name.equals("")) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error"); alert.setHeaderText(null); alert.setContentText("Please enter name!"); alert.showAndWait(); } else { if (surname.equals("")) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error"); alert.setHeaderText(null); alert.setContentText("Please enter surname!"); alert.showAndWait(); } else { if (user_type == -1) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error"); alert.setHeaderText(null); alert.setContentText("Please choose user type!"); alert.showAndWait(); } else { if (JavaFXService.serv.addUser(username, passwd, user_type, name, surname)) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Success"); alert.setHeaderText(null); alert.setContentText("User added!"); alert.showAndWait(); } else { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("SQL Error"); alert.setHeaderText(null); alert.setContentText("Querry Error!"); alert.showAndWait(); } } } } } } } @Override public void initialize(URL url, ResourceBundle rb) { user_type_fx.getItems().add("Admin"); user_type_fx.getItems().add("Employee"); user_type_fx.getItems().add("Client"); } }
package com.heihei.fragment; import android.view.View; import android.view.View.OnClickListener; import com.base.host.BaseFragment; import com.wmlives.heihei.R; public class TestFragment extends BaseFragment { // ----------------R.layout.fragment_test-------------Start private com.heihei.fragment.live.widget.GiftNumberView number_view; public void autoLoad_fragment_test() { // number_view = (com.heihei.fragment.live.widget.GiftNumberView) findViewById(R.id.number_view); } // ----------------R.layout.fragment_test-------------End @Override protected void loadContentView() { setContentView(R.layout.fragment_test); } @Override protected void viewDidLoad() { autoLoad_fragment_test(); // getView().setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // number_view.increaseNumber(1); // } // }); } @Override protected void refresh() { // TODO Auto-generated method stub } @Override public String getCurrentFragmentName() { // TODO Auto-generated method stub return "TestFragment"; } }
package cn.jaychang.scstudy.scconfigclientms; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @EnableEurekaClient @EnableDiscoveryClient @RestController @RefreshScope public class ConfigClientV3MsApplication { @Value("${foo}") String foo; @GetMapping("/hello") public String hello(){ return "hello "+foo; } public static void main(String[] args) { SpringApplication.run(ConfigClientV3MsApplication.class, args); } }
package com.jia.bigdata.mr.wordcount; import com.jia.bigdata.ExceptionWrapper; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import java.util.Arrays; import java.util.Objects; /** * @author tanjia * @email 378097217@qq.com * @date 2019/7/15 2:09 */ public class WordCounterMapper extends Mapper<LongWritable, Text, Text, IntWritable> { protected void map(final LongWritable key, final Text value, final Mapper.Context context) { Arrays.stream(value.toString().split("\\s+")).filter(Objects::nonNull).filter(StringUtils::isNotBlank).forEach(e -> ExceptionWrapper.run(() -> context.write(new Text(e), new IntWritable(1)))); } }
/** * Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT * Copyright (c) 2006-2018, Sencha Inc. * * licensing@sencha.com * http://www.sencha.com/products/gxt/license/ * * ================================================================================ * Commercial License * ================================================================================ * This version of Sencha GXT is licensed commercially and is the appropriate * option for the vast majority of use cases. * * Please see the Sencha GXT Licensing page at: * http://www.sencha.com/products/gxt/license/ * * For clarification or additional options, please contact: * licensing@sencha.com * ================================================================================ * * * * * * * * * ================================================================================ * Disclaimer * ================================================================================ * THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND * REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE * IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, * FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND * THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. * ================================================================================ */ package com.sencha.gxt.explorer.client.utils; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import com.sencha.gxt.core.client.util.Margins; import com.sencha.gxt.core.client.util.Util; import com.sencha.gxt.explorer.client.app.ui.ExampleContainer; import com.sencha.gxt.explorer.client.model.Example.Detail; import com.sencha.gxt.widget.core.client.ContentPanel; import com.sencha.gxt.widget.core.client.container.MarginData; import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer; import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData; @Detail( name = "Util Utils", category = "Utils", icon = "animation", minHeight = UtilExample.MIN_HEIGHT, minWidth = UtilExample.MIN_WIDTH) public class UtilExample implements IsWidget, EntryPoint { protected static final int MIN_HEIGHT = 400; protected static final int MIN_WIDTH = 400; private ContentPanel panel; /** * http://docs.sencha.com/gxt/latest/javadoc/ */ @Override public Widget asWidget() { if (panel == null) { HTML equality = createEquality(); HTML isint = createIsInt(); HTML isempty = createIsEmpty(); VerticalLayoutContainer vlc = new VerticalLayoutContainer(); vlc.add(equality, new VerticalLayoutData(1, -1, new Margins(20))); vlc.add(isint, new VerticalLayoutData(1, -1, new Margins(20))); vlc.add(isempty, new VerticalLayoutData(1, -1, new Margins(20))); panel = new ContentPanel(); panel.setHeading("Util Utils"); panel.add(vlc, new MarginData(20)); } return panel; } private HTML createIsInt() { String s = "Util.isInteger(\"101\"): " + Util.isInteger("101"); SafeHtml safeHtml = SafeHtmlUtils.fromTrustedString(s); HTML html = new HTML(safeHtml); return html; } private HTML createEquality() { String a = "A"; String b = null; String s = "Util.equalWithNull: " + Util.equalWithNull(a, b); SafeHtml safeHtml = SafeHtmlUtils.fromTrustedString(s); HTML html = new HTML(safeHtml); return html; } private HTML createIsEmpty() { String s = "Util.isEmptyString(\"\"): " + Util.isEmptyString(""); SafeHtml safeHtml = SafeHtmlUtils.fromTrustedString(s); HTML html = new HTML(safeHtml); return html; } @Override public void onModuleLoad() { new ExampleContainer(this).setMinHeight(MIN_HEIGHT).setMinWidth(MIN_WIDTH).doStandalone(); } }
//********************************************************** //1. f ��: ȸ�� v�� ���� //2. �wα׷���: SelectCompBean.java //3. �� ��: //4. ȯ ��: JDK 1.3 //5. �� o: 0.1 //6. �� ��: Administrator 2003-08-29 //7. �� d: // //********************************************************** package com.ziaan.etest; import java.sql.PreparedStatement; import java.sql.ResultSetMetaData; import com.ziaan.common.GetCodenm; import com.ziaan.library.DBConnectionManager; import com.ziaan.library.ErrorManager; import com.ziaan.library.ListSet; import com.ziaan.library.RequestBox; import com.ziaan.library.SQLString; import com.ziaan.library.StringManager; /** * @author Administrator * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class SelectCompBean { /** ȸ�纰 @param box receive from the form object and session @return String */ public static String getCompany(RequestBox box, boolean isChange, boolean isALL) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; ListSet ls = null; String sql = ""; String result = ""; try { String s_gadmin = box.getSession("gadmin"); String v_gadmin = StringManager.substring(s_gadmin, 0, 1); String s_userid = box.getSession("userid"); String ss_company = box.getStringDefault("s_company","ALL"); connMgr = new DBConnectionManager(); if(v_gadmin.equals("H")) { // ��0�׷���� sql = "select distinct a.comp, a.companynm"; sql += " from tz_comp a, tz_grcomp b,"; sql += " (select grcode from tz_grcodeman where userid = " + SQLString.Format(s_userid) + " and gadmin = " + SQLString.Format(s_gadmin) + ") c"; sql += " where a.comp = b.comp and b.grcode = c.grcode and a.comptype = '2'"; sql += " order by a.comp"; } else if(v_gadmin.equals("K")) { // ȸ�����, �μ����� sql = "select distinct a.comp, a.companynm"; sql += " from tz_comp a, tz_compman b"; sql += " where substr(a.comp, 1, 4) = substr(b.comp, 1, 4) and b.userid = " + SQLString.Format(s_userid) + " and b.gadmin = " + SQLString.Format(s_gadmin); sql += " and a.comptype = '2' order by a.comp"; } else { // Ultravisor, Supervisor, ��d����, ���� sql = "select distinct comp, companynm"; sql += " from tz_comp where comptype = '2'"; sql += " order by comp"; } ls = connMgr.executeQuery(sql); if(v_gadmin.equals("A") || v_gadmin.equals("F") || v_gadmin.equals("P") || v_gadmin.equals("H")) { // Ultra/Super or ��d���� or ���� or ��0�׷���� �� ��� 'ALL' ȸ�� ��� result = getSelectTag(ls, isChange, true, "s_company", ss_company); } else { result = getSelectTag(ls, isChange, false, "s_company", ss_company); } } catch (Exception ex) {ex.printStackTrace(); ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage()); } finally { if(ls != null) { try { ls.close(); }catch (Exception e) {} } if(pstmt != null) { try { pstmt.close(); } catch (Exception e1) {} } if(connMgr != null) { try { connMgr.freeConnection(); }catch (Exception e10) {} } } return result; } public static String getGpm(RequestBox box, boolean isChange, boolean isALL) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; ListSet ls = null; String sql = ""; String result = ""; try { String s_gadmin = box.getSession("gadmin"); String v_gadmin = StringManager.substring(s_gadmin, 0, 1); String s_userid = box.getSession("userid"); String ss_company = box.getStringDefault("s_company", "ALL"); // �ش� ȸ���� comp code String ss_gpm = box.getStringDefault("s_gpm", "ALL"); // �ش� ȸ���� comp code connMgr = new DBConnectionManager(); if(s_gadmin.equals("K6") || s_gadmin.equals("K7")) { // �μ����� or �μ��� sql = "select distinct a.comp, a.gpmnm"; sql += " from tz_comp a, tz_compman b"; sql += " where substr(a.comp, 1, 6) = substr(b.comp, 1, 6) and b.userid = " + SQLString.Format(s_userid) + " and b.gadmin = " + SQLString.Format(s_gadmin); if( !ss_company.equals("ALL")) { sql += " and a.comp like '" + GetCodenm.get_compval(ss_company) + "'"; } sql += " and a.comptype = '3' order by a.comp"; } else { sql = "select distinct comp, gpmnm"; sql += " from tz_comp where comptype = '3'"; if( !ss_company.equals("ALL")) { sql += " and comp like '" + GetCodenm.get_compval(ss_company) + "'"; } sql += " order by comp"; } ls = connMgr.executeQuery(sql); if( !s_gadmin.equals("K6") && !s_gadmin.equals("K7")) { // �μ����� or �μ��� �� �ƴѰ�� 'ALL' ���� ��� result = getSelectTag(ls, isChange, true, "s_gpm", ss_gpm); } else { result = getSelectTag(ls, isChange, false, "s_gpm", ss_gpm); } } catch (Exception ex) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage()); } finally { if(ls != null) { try { ls.close(); }catch (Exception e) {} } if(connMgr != null) { try { connMgr.freeConnection(); }catch (Exception e10) {} } } return result; } /** �μ��� @param box receive from the form object and session @return String */ public static String getDept(RequestBox box, boolean isChange, boolean isALL) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; ListSet ls = null; String sql = ""; String result = ""; try { String s_gadmin = box.getSession("gadmin"); String v_gadmin = StringManager.substring(s_gadmin, 0, 1); String s_userid = box.getSession("userid"); String ss_company = box.getStringDefault("s_company", "ALL"); // �ش� ȸ���� comp code String ss_gpm = box.getStringDefault("s_gpm", "ALL"); String ss_dept = box.getStringDefault("s_dept", "ALL"); connMgr = new DBConnectionManager(); if(s_gadmin.equals("K6") || s_gadmin.equals("K7")) { // �μ����� or �μ��� sql = "select distinct a.comp, a.deptnm"; sql += " from tz_comp a, tz_compman b"; sql += " where substr(a.comp, 1, 8) = substr(b.comp, 1, 8) and b.userid = " + SQLString.Format(s_userid) + " and b.gadmin = " + SQLString.Format(s_gadmin); if( !ss_gpm.equals("ALL")) { sql += " and a.comp like '" + GetCodenm.get_compval(ss_gpm) + "'"; } sql += " and a.comptype = '4' order by a.comp"; } else { sql = "select distinct comp, deptnm"; sql += " from tz_comp where comptype = '4'"; if( !ss_gpm.equals("ALL")) { sql += " and comp like '" + GetCodenm.get_compval(ss_gpm) + "'"; } sql += " order by comp"; } ls = connMgr.executeQuery(sql); if( !s_gadmin.equals("K6") && !s_gadmin.equals("K7")) { // �μ����� or �μ��� �� �ƴѰ�� 'ALL' ���� ��� result = getSelectTag(ls, isChange, true, "s_dept", ss_dept); } else { result = getSelectTag(ls, isChange, false, "s_dept", ss_dept); } } catch (Exception ex) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage()); } finally { if(ls != null) { try { ls.close(); }catch (Exception e) {} } if(connMgr != null) { try { connMgr.freeConnection(); }catch (Exception e10) {} } } return result; } public static String getPart(RequestBox box, boolean isChange, boolean isALL) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; ListSet ls = null; String sql = ""; String result = ""; try { String s_gadmin = box.getSession("gadmin"); String v_gadmin = StringManager.substring(s_gadmin, 0, 1); String s_userid = box.getSession("userid"); String ss_company = box.getStringDefault("s_company", "ALL"); // �ش� ȸ���� comp code String ss_gpm = box.getStringDefault("s_gpm", "ALL"); String ss_dept = box.getStringDefault("s_dept", "ALL"); String ss_part = box.getStringDefault("s_part", "ALL"); connMgr = new DBConnectionManager(); if(s_gadmin.equals("K6") || s_gadmin.equals("K7")) { // �μ����� or �μ��� sql = "select distinct a.comp, a.partnm"; sql += " from tz_comp a, tz_compman b"; sql += " where substr(a.comp, 1, 8) = substr(b.comp, 1, 8) and b.userid = " + SQLString.Format(s_userid) + " and b.gadmin = " + SQLString.Format(s_gadmin); if( !ss_part.equals("ALL")) { sql += " and a.comp like '" + GetCodenm.get_compval(ss_part) + "'"; } sql += " and a.comptype = '5' order by a.comp"; } else { sql = "select distinct comp, partnm"; sql += " from tz_comp where comptype = '5'"; if( !ss_dept.equals("ALL")) { sql += " and comp like '" + GetCodenm.get_compval(ss_dept) + "'"; } sql += " order by comp"; } ls = connMgr.executeQuery(sql); if( !s_gadmin.equals("K6") && !s_gadmin.equals("K7")) { // �μ����� or �μ��� �� �ƴѰ�� 'ALL' ���� ��� result = getSelectTag(ls, isChange, true, "s_part", ss_part); } else { result = getSelectTag(ls, isChange, false, "s_part", ss_part); } } catch (Exception ex) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage()); } finally { if(ls != null) { try { ls.close(); }catch (Exception e) {} } if(connMgr != null) { try { connMgr.freeConnection(); }catch (Exception e10) {} } } return result; } public static String getJikwi(RequestBox box, boolean isChange, boolean isALL) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; ListSet ls = null; String sql = ""; String result = ""; try { String s_gadmin = box.getSession("gadmin"); String v_gadmin = StringManager.substring(s_gadmin, 0, 1); String ss_jikwi = box.getStringDefault("s_jikwi", "ALL"); connMgr = new DBConnectionManager(); sql = "select distinct jikwi, jikwinm"; sql += " from tz_jikwi"; sql += " order by jikwi"; ls = connMgr.executeQuery(sql); if( v_gadmin.equals("A")) { // Ultra, SuperVisor 'ALL' ���� ��� result = getSelectTag(ls, isChange, true, "s_jikwi", ss_jikwi); } else { result = getSelectTag(ls, isChange, false, "s_jikwi", ss_jikwi); } } catch (Exception ex) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage()); } finally { if(ls != null) { try { ls.close(); }catch (Exception e) {} } if(connMgr != null) { try { connMgr.freeConnection(); }catch (Exception e10) {} } } return result; } /** ��޺� @param box receive from the form object and session @return String */ public static String getJikup(RequestBox box, boolean isChange, boolean isALL) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; ListSet ls = null; String sql = ""; String result = ""; try { String s_gadmin = box.getSession("gadmin"); String v_gadmin = StringManager.substring(s_gadmin, 0, 1); String ss_jikup = box.getStringDefault("s_jikup", "ALL"); connMgr = new DBConnectionManager(); sql = "select distinct jikup, jikupnm"; sql += " from tz_jikup"; sql += " order by jikup"; ls = connMgr.executeQuery(sql); if( v_gadmin.equals("A")) { // Ultra, SuperVisor 'ALL' ���� ��� result = getSelectTag(ls, isChange, true, "s_jikup", ss_jikup); } else { result = getSelectTag(ls, isChange, false, "s_jikup", ss_jikup); } } catch (Exception ex) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage()); } finally { if(ls != null) { try { ls.close(); }catch (Exception e) {} } if(connMgr != null) { try { connMgr.freeConnection(); }catch (Exception e10) {} } } return result; } public static String getJikun(RequestBox box, boolean isChange, boolean isALL) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; ListSet ls = null; String sql = ""; String result = ""; try { String s_gadmin = box.getSession("gadmin"); String v_gadmin = StringManager.substring(s_gadmin, 0, 1); String ss_jikun = box.getStringDefault("s_jikun", "ALL"); connMgr = new DBConnectionManager(); sql = "select distinct jikun, jikunnm"; sql += " from tz_jikun"; sql += " order by jikun"; ls = connMgr.executeQuery(sql); if( v_gadmin.equals("A")) { // Ultra, SuperVisor 'ALL' ���� ��� result = getSelectTag(ls, isChange, true, "s_jikun", ss_jikun); } else { result = getSelectTag(ls, isChange, false, "s_jikun", ss_jikun); } } catch (Exception ex) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage()); } finally { if(ls != null) { try { ls.close(); }catch (Exception e) {} } if(connMgr != null) { try { connMgr.freeConnection(); }catch (Exception e10) {} } } return result; } /** SELECT HTML @param box receive from the form object and session @return String */ public static String getSelectTag(ListSet ls, boolean isChange, boolean isALL, String selname, String optionselected) throws Exception { StringBuffer sb = null; try { sb = new StringBuffer(); sb.append("<select name = \"" + selname + "\""); if(isChange) sb.append(" onChange = \"whenSelection('change')\""); sb.append(">\r\n"); if(isALL) { sb.append("<option value = \"ALL\">ALL</option>\r\n"); } else if(isChange) { sb.append("<option value = \"----\">----</option>\r\n"); } while (ls.next()) { ResultSetMetaData meta = ls.getMetaData(); int columnCount = meta.getColumnCount(); sb.append("<option value = \"" + ls.getString(1) + "\""); if (optionselected.equals(ls.getString(1))) sb.append(" selected"); sb.append(">" + ls.getString(columnCount) + "</option>\r\n"); } sb.append("</select>\r\n"); } catch (Exception ex) { ErrorManager.getErrorStackTrace(ex, true); throw new Exception(ex.getMessage()); } return sb.toString(); } }
package com.danielvizzini.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayDeque; import org.junit.Test; @SuppressWarnings("javadoc") public class FileUtilTest { @Test public void testReadFile() { try { File file = new File("lib/hello_world.txt"); assertEquals(FileUtil.readFile(file), "Hello, world!"); } catch (IOException e) { fail("readFile() failed"); } } @Test public void testReadFileBlank() { try { File file = new File("lib/blank_file.txt"); assertEquals(FileUtil.readFile(file),""); } catch (IOException e) { fail("readFile() failed"); } } @Test public void testReadFileNone() { try { File file = new File("lib/non_existent_file.txt"); FileUtil.readFile(file); } catch (FileNotFoundException e) { assertTrue(true); } } @Test public void testReadFileLineByLine() { try { File file = new File("lib/hello_world.txt"); ArrayDeque<String> calculatedQueue = new ArrayDeque<String>(FileUtil.readFileLineByLine(file)); assertEquals(calculatedQueue.size(), 2); assertEquals(calculatedQueue.pop(), "Hello,"); assertEquals(calculatedQueue.pop(), "world!"); } catch (IOException e) { fail("readFile() failed"); } } @Test public void testReadFileLineByLineBlank() { try { File file = new File("lib/blank_file.txt"); assertEquals(FileUtil.readFileLineByLine(file).size(), 0); } catch (IOException e) { fail("readFile() failed"); } } @Test public void testReadFileLineByLineNone() { try { File file = new File("lib/non_existent_file.txt"); FileUtil.readFileLineByLine(file); } catch (FileNotFoundException e) { assertTrue(true); } } }
package datenbank; import java.sql.*; public class AuslesenEventveranstaltungen { public String getBuchung(String Usr, String Pwd) throws ClassNotFoundException, SQLException { //-------------Setzen der Variablen--------------------------- String sDbDrv = "com.mysql.jdbc.Driver"; String sDbUrl = "jdbc:mysql://localhost:3306/eventmanagementsystem"; String sUsr = Usr; String sPwd = Pwd; String stbl = "tbl_EventDaten"; String sSql = "Select * from "+stbl; String html = ""; if( null != sDbDrv && 0 < sDbDrv.length() && null != sDbUrl && 0 < sDbUrl.length() && null != sSql && 0 < sSql.length() ) { Connection cn = null; Statement st = null; ResultSet rs = null; try { Class.forName( sDbDrv ); cn = DriverManager.getConnection( sDbUrl, sUsr, sPwd ); st = cn.createStatement(); rs = st.executeQuery( sSql ); ResultSetMetaData rsmd = rs.getMetaData(); int n = rsmd.getColumnCount(); //schreiben des HTML codes html = html.concat("<table border=1 width=100%>"); html = html.concat( "<th width=11%><center>Event ID</center></th>" + "<th width=11%><center>Preis</center></th>" + "<th width=11%><center>Von</center></th>" + "<th width=11%><center>Bis</center></th>" + "<th width=11%><center>Startort</center></th>" + "<th width=11%><center>Zielort</center></th>" + "<th width=11%><center>Vermittlungssatz</center></th>" + "<th width=11%><center>Max Teilnehmerzahl</center></th>"); int x ; while (rs.next()) { html = html.concat("<tr><td>"+rs.getString(2)+"</td>"); //Event ID html = html.concat("<td>"+rs.getString(3)+"</td>"); //Preis html = html.concat("<td>"+rs.getString(4)+"</td>"); //Von html = html.concat("<td>"+rs.getString(5)+"</td>"); //Bis html = html.concat("<td>"+rs.getString(6)+"</td>"); //Startort html = html.concat("<td>"+rs.getString(7)+"</td>"); //Zielort html = html.concat("<td>"+rs.getString(11)+"</td>"); //Verlittlungssatz html = html.concat("<td>"+rs.getString(8)+"</td></tr>"); //Rechnung Erstellt } html = html.concat("</table>"); } finally { try { if( null != rs ) rs.close(); } catch( Exception ex ) { /*ok*/ } try { if( null != st ) st.close(); } catch( Exception ex ) { /*ok*/ } try { if( null != cn ) cn.close(); } catch( Exception ex ) { /*ok*/ } } }//ende if return html; }//Ende Function }
/* EPI problem? Not sure. Given an array of integers (positive and negative), * return max sum of a subarray. */ import java.util.*; public class MaxSum{ public static int maxSum(int[] A, int sz) { int maxSum = 0, Sum = 0; for (int i : A) { Sum += i; if (Sum < 0) Sum = 0; maxSum = Math.max(maxSum, Sum); } return maxSum; } public static void main(String[] args) { MaxSum t = new MaxSum(); int sz = 10; Random r = new Random(); int[] A = new int[sz]; final int RANGE_MAX = 10; final int RANGE_MIN = -10; // random numbers in range [-10,10) for (int i=0; i<sz; i++) A[i] = (r.nextInt(2*RANGE_MAX) - RANGE_MAX); for (int i=0; i<sz; i++) System.out.print(A[i] + " "); System.out.println("\nMax Sum: " + maxSum(A, sz)); } }
package com.zhibo.duanshipin.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.zhibo.duanshipin.R; import com.zhibo.duanshipin.activity.VideoPlayActivity; import com.zhibo.duanshipin.bean.UploadRecordBean; import com.zhibo.duanshipin.utils.Utils; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by ${CC} on 2017/12/4. */ public class UploadRecordapter extends RecyclerView.Adapter { Context mContext; private List<UploadRecordBean.DataBean> list; public UploadRecordapter(Context context, List<UploadRecordBean.DataBean> list) { this.mContext = context; this.list = list; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new UploadRecordapterHolder(LayoutInflater.from(mContext).inflate(R.layout.item_uploadrecord, parent, false)); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { final int pos = position; if (pos < 0 || pos > list.size() - 1) return; if (holder instanceof UploadRecordapterHolder) { final UploadRecordBean.DataBean bean = list.get(position); ((UploadRecordapterHolder) holder).tvName.setText("视频七牛地址:"+bean.getUrl()+"\n"+"\n"+bean.getContent() .replace("\n","\n" ) .replace("\\n","\n" ) .replace("\\\n","\n" ) .replace("\n","\n" ) .replace("\r","\n") .replace("\\r","\n") .replace("\\\r","\n") ); ((UploadRecordapterHolder) holder).tvTime.setText(Utils.getDataTimeWithMinute(bean.getTime())); ((UploadRecordapterHolder) holder).lvAllview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { VideoPlayActivity.startVideoPlay(mContext, bean.getUrl(), "", null, "视频七牛地址:"+bean.getUrl()+"\n"+"\n"+bean.getContent() .replace("\n","\n" ) .replace("\\n","\n" ) .replace("\\\n","\n" ) .replace("\n","\n" ) .replace("\r","\n") .replace("\\r","\n") .replace("\\\r","\n"), false,true, false,"","视频七牛地址:"+bean.getUrl()+"\n"+"\n"+bean.getContent() .replace("\n","\n" ) .replace("\\n","\n" ) .replace("\\\n","\n" ) .replace("\n","\n" ) .replace("\r","\n") .replace("\\r","\n") .replace("\\\r","\n")); } }); } } class UploadRecordapterHolder extends RecyclerView.ViewHolder { @BindView(R.id.tv_name) TextView tvName; @BindView(R.id.tv_time) TextView tvTime; @BindView(R.id.lv_allview) LinearLayout lvAllview; public UploadRecordapterHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } @Override public int getItemCount() { return list.size(); } }
import java.util.Arrays; class CheckAnagram { public static void main(String[] args) { String s1="peek"; String s2="KeeP"; s1=s1.toUpperCase(); s2=s2.toUpperCase(); char ar[]=s1.toCharArray(); char br[]=s2.toCharArray(); Arrays.sort(ar); Arrays.sort(br); if (Arrays.equals(ar,br)) System.out.println("Anagram"); else System.out.println("Not Anagram"); } }
package com.limegroup.gnutella.gui.options.panes; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.IOException; import javax.swing.JCheckBox; import javax.swing.JTextField; import org.gudy.azureus2.core3.config.COConfigurationManager; import org.limewire.i18n.I18nMarker; import com.limegroup.gnutella.gui.I18n; import com.limegroup.gnutella.gui.LabeledComponent; import com.limegroup.gnutella.gui.SizedTextField; import com.limegroup.gnutella.gui.GUIUtils.SizePolicy; import com.limegroup.gnutella.settings.ConnectionSettings; /** * This class defines the panel in the options window that allows the user to * set the login data for the proxy. */ public final class ProxyLoginPaneItem extends AbstractPaneItem { public final static String TITLE = I18n.tr("Login Details"); public final static String LABEL = I18n.tr("Configure username and password to be used for the proxy."); /** * Constant for the key of the locale-specific <tt>String</tt> for the * check box that enables / disables password authentification at the * proxy. */ private final String PROXY_AUTHENTICATE_CHECK_BOX_LABEL = I18nMarker.marktr("Enable Authentication (Does Not Work for HTTP Proxies):"); /** * Constant for the key of the locale-specific <tt>String</tt> for the * label on the username field. */ private final String PROXY_USERNAME_LABEL_KEY = I18nMarker.marktr("Username:"); /** * Constant for the key of the locale-specific <tt>String</tt> for the * label on the password field. */ private final String PROXY_PASSWORD_LABEL_KEY = I18nMarker.marktr("Password:"); /** * Constant <tt>JTextField</tt> instance that holds the username. */ private final JTextField PROXY_USERNAME_FIELD = new SizedTextField(12, SizePolicy.RESTRICT_BOTH); /** * Constant <tt>JTextField</tt> instance that holds the pasword. */ private final JTextField PROXY_PASSWORD_FIELD = new SizedTextField(12, SizePolicy.RESTRICT_BOTH); /** * Constant for the check box that determines whether or not to * authenticate at proxy settings */ private final JCheckBox CHECK_BOX = new JCheckBox(); /** * The constructor constructs all of the elements of this * <tt>AbstractPaneItem</tt>. * * @param key the key for this <tt>AbstractPaneItem</tt> that the * superclass uses to generate locale-specific keys */ public ProxyLoginPaneItem() { super(TITLE, LABEL); CHECK_BOX.addItemListener(new LocalAuthenticateListener()); LabeledComponent checkBox = new LabeledComponent( PROXY_AUTHENTICATE_CHECK_BOX_LABEL, CHECK_BOX, LabeledComponent.LEFT_GLUE, LabeledComponent.LEFT); LabeledComponent username = new LabeledComponent( PROXY_USERNAME_LABEL_KEY, PROXY_USERNAME_FIELD, LabeledComponent.LEFT_GLUE, LabeledComponent.LEFT); LabeledComponent password = new LabeledComponent( PROXY_PASSWORD_LABEL_KEY, PROXY_PASSWORD_FIELD, LabeledComponent.LEFT_GLUE, LabeledComponent.LEFT); add(checkBox.getComponent()); add(getVerticalSeparator()); add(username.getComponent()); add(getVerticalSeparator()); add(password.getComponent()); } /** * Defines the abstract method in <tt>AbstractPaneItem</tt>. * <p> * * Sets the options for the fields in this <tt>PaneItem</tt> when the * window is shown. */ public void initOptions() { String username = ConnectionSettings.PROXY_USERNAME.getValue(); String password = ConnectionSettings.PROXY_PASS.getValue(); boolean authenticate = ConnectionSettings.PROXY_AUTHENTICATE.getValue(); PROXY_USERNAME_FIELD.setText(username); PROXY_PASSWORD_FIELD.setText(password); //HTTP Authentication is not yet supported CHECK_BOX.setSelected( authenticate && ConnectionSettings.CONNECTION_METHOD.getValue() != ConnectionSettings.C_HTTP_PROXY); updateState(); } /** * Defines the abstract method in <tt>AbstractPaneItem</tt>. * <p> * * Applies the options currently set in this window, displaying an error * message to the user if a setting could not be applied. * * @throws IOException * if the options could not be applied for some reason */ public boolean applyOptions() throws IOException { final String username = PROXY_USERNAME_FIELD.getText(); final String password = PROXY_PASSWORD_FIELD.getText(); final boolean authenticate = CHECK_BOX.isSelected(); ConnectionSettings.PROXY_USERNAME.setValue(username); ConnectionSettings.PROXY_PASS.setValue(password); ConnectionSettings.PROXY_AUTHENTICATE.setValue(authenticate); // put proxy configuration in vuze options COConfigurationManager.setParameter("Proxy.Username", username); COConfigurationManager.setParameter("Proxy.Password", password); COConfigurationManager.save(); return false; } public boolean isDirty() { return !ConnectionSettings.PROXY_USERNAME.getValue().equals(PROXY_USERNAME_FIELD.getText()) || !ConnectionSettings.PROXY_PASS.getValue().equals(PROXY_PASSWORD_FIELD.getText()) || ConnectionSettings.PROXY_AUTHENTICATE.getValue() != CHECK_BOX.isSelected(); } private void updateState() { PROXY_USERNAME_FIELD.setEnabled(CHECK_BOX.isSelected()); PROXY_PASSWORD_FIELD.setEnabled(CHECK_BOX.isSelected()); PROXY_USERNAME_FIELD.setEditable(CHECK_BOX.isSelected()); PROXY_PASSWORD_FIELD.setEditable(CHECK_BOX.isSelected()); } /** * Listener class that responds to the checking and the unchecking of the * checkbox specifying whether or not to use authentication. It makes the * other fields editable or not editable depending on the state of the * JCheckBox. */ private class LocalAuthenticateListener implements ItemListener { public void itemStateChanged(ItemEvent e) { updateState(); } } }
package com.yash.function; import java.util.Optional; public class OptionalDemo { public int sum(Optional<Integer> o1,Optional<Integer> o2) { return o1.orElse(0)+o2.orElse(0); } public static void main(String[] args) { Optional<String> optionalString=Optional.of("Sabbir"); System.out.println("Whether value is present:"+optionalString.isPresent()); OptionalDemo od=new OptionalDemo(); Optional<Integer> o1=Optional.ofNullable(null); Optional<Integer> o2=Optional.of(20); System.out.println("Sum:"+od.sum(o1, o2)); } }
package dicegame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; /** * @author Maria Bartoszuk, w1510769 */ /** * Terminates the program run when the window frame is closed by the user. */ class WindowClosesApplication extends WindowAdapter { ScoreTracker tracker; WindowClosesApplication(ScoreTracker tracker) { this.tracker = tracker; } /** Exits the system when the window is closed. * Saves the won games for all the players. */ @Override public void windowClosing(WindowEvent e) { tracker.save(); System.exit(0); } }
package com.davivienda.sara.procesos.cuadrecifras.filtro.provisiones.servicio; import com.davivienda.sara.base.BaseServicio; import com.davivienda.sara.base.ProcesadorArchivoProvisionesInterface; import com.davivienda.sara.base.exception.EntityServicioExcepcion; import com.davivienda.sara.entitys.ProvisionHost; import com.davivienda.sara.entitys.ProvisionHostPK; import com.davivienda.sara.entitys.MovimientoCuadre; import com.davivienda.sara.constantes.TipoMovimientoCuadre; //import com.davivienda.sara.entitys.TipoMovimientoCuadre; import com.davivienda.sara.procesos.cuadrecifras.filtro.provisiones.estructura.ProvisionesArchivo; import com.davivienda.sara.procesos.cuadrecifras.filtro.provisiones.procesador.ProvisionesProcesadorArchivo; import com.davivienda.sara.tablas.provisionhost.servicio.ProvisionHostServicio; import com.davivienda.sara.tablas.movimientocuadre.servicio.MovimientoCuadreServicio; import com.davivienda.utilidades.archivoplano.ArchivoPlano; import java.io.FileNotFoundException; import java.util.Calendar; import java.util.Collection; import javax.persistence.EntityManager; import com.davivienda.sara.entitys.Cajero; import com.davivienda.utilidades.conversion.Fecha; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.logging.Level; /** * ProcesadorDiarioElectronicoServicio - 22/08/2008 Descripción : Versión : 1.0 * * @author jjvargas Davivienda 2008 */ public class ProcesadorProvisionesArchivoServicio extends BaseServicio { private ProvisionHostServicio provisionHostServicio; private MovimientoCuadreServicio movimientoCuadreServicio; public ProcesadorProvisionesArchivoServicio(EntityManager em) { super(em); provisionHostServicio = new ProvisionHostServicio(em); movimientoCuadreServicio = new MovimientoCuadreServicio(em); } /** * Carga un archivo de provisiones en la tabla ProvisionHost y * MovimientoCuadre * * @param fecha * @return * @throws java.io.FileNotFoundException * @throws com.davivienda.sara.base.exception.EntityServicioExcepcion * @throws java.lang.IllegalArgumentException */ @SuppressWarnings("empty-statement") public Integer cargarArchivoProvisiones(Calendar fecha) throws FileNotFoundException, EntityServicioExcepcion, IllegalArgumentException { Integer regsProcesados = -1; try { ArchivoPlano archivo = null; // configApp.loggerApp.info("Se inicia el proceso de carga para el cajero " + cajero.getCodigoCajero()); ProcesadorArchivoProvisionesInterface procesador = null; Collection<ProvisionHost> regsProvisionHost = null; ArrayList<ProvisionHost> regsProvisionHostCompara = new ArrayList<ProvisionHost>(); ProvisionHostPK ProvisionHostPKfecha = null; String directorio; directorio = configApp.DIRECTORIO_CUADRE; archivo = new ProvisionesArchivo(fecha, directorio); procesador = new ProvisionesProcesadorArchivo(archivo); // Leo los registros en el archivo asignado if (procesador != null) { regsProvisionHost = procesador.getRegistrosProvisiones(); } com.davivienda.sara.entitys.TipoMovimientoCuadre tmc; if (regsProvisionHost != null) { configApp.loggerApp.log(Level.INFO, "Inicia el proceso de carga para el archivo {0} con fecha {1} a las: {2} con {3} registros leidos", new Object[]{archivo.getNombreArchivo(), Fecha.aCadena(fecha, "yyyy/MM/dd"), Fecha.aCadena(Fecha.getCalendarHoy(), "HHmmss"), regsProvisionHost.size()}); for (ProvisionHost provisionHost : regsProvisionHost) { //OJOOO VALIDAR QUE SE CARGUE EL CAJERO EN EL ARCHIVO PLANO try { if (provisionHost != null) { Cajero cajero = em.find(new Cajero().getClass(), provisionHost.getCajero().getCodigoCajero()); if (cajero != null) { provisionHost.setCajero(cajero); if (buscarRegistro(regsProvisionHostCompara, provisionHost) == false) { MovimientoCuadre mc = obtenerMovimientoCuadreLinea(provisionHost); if (mc != null) { if (mc.getTipoMovimientoCuadre().getCodigoTipoMovimientoCuadre().equals(TipoMovimientoCuadre.AUMENTO_PROVISION_LINEA.codigo) || mc.getTipoMovimientoCuadre().getCodigoTipoMovimientoCuadre().equals(TipoMovimientoCuadre.DISMINUCION_PROVISION_LINEA.codigo)) { ProvisionHostPKfecha = provisionHost.getProvisionHostPK(); ProvisionHostPKfecha.setFecha(mc.getFecha()); provisionHost.setProvisionHostPK(ProvisionHostPKfecha); } configApp.loggerApp.info("Registro ProvisionHost codigo:" + provisionHost.getProvisionHostPK().getCodigoCajero() + " fecha: " + provisionHost.getProvisionHostPK().getFecha() + " hora: " + provisionHost.getProvisionHostPK().getHora() + " motivo: " + provisionHost.getProvisionHostPK().getMotivo() + " tipo: " + provisionHost.getProvisionHostPK().getTipo() + " valor: " + provisionHost.getValor()); ProvisionHost existeProvision = provisionHostServicio.buscar(provisionHost.getProvisionHostPK()); if (existeProvision == null) { provisionHostServicio.grabarProvisionHost(provisionHost); regsProcesados++; movimientoCuadreServicio.adicionar(mc); //em.persist(mc); ProvisionHost regprov = new ProvisionHost(); regprov = provisionHost; regsProvisionHostCompara.add(regprov); } else { configApp.loggerApp.info("Registro ProvisionHost " + provisionHost + " ya se encuentra en base de datos, no se cargara."); } } } else { configApp.loggerApp.info("Registro Repetido " + provisionHost.getCajero()); } } else { configApp.loggerApp.info("en Registro " + (regsProcesados + 1) + " No existe el cajero : " + provisionHost.getCajero().getCodigoCajero().toString()); } } } catch (Exception ex) { configApp.loggerApp.log(Level.WARNING, "Error: {0}", ex.getMessage()); } } configApp.loggerApp.info("Finaliza el proceso de carga para el archivo de provisiones del " + Fecha.aCadena(fecha, "yyyy/MM/dd") + " a las: " + Fecha.aCadena(Fecha.getCalendarHoy(), "HHmmss") + " con " + regsProcesados + " registros procesados"); } else { configApp.loggerApp.log(Level.INFO, "ProvisionHost esta nulo"); } } catch (Exception ex) { configApp.loggerApp.info("Error cargando el archivo provisiones descripcion Error : " + ex.getMessage());; } return regsProcesados; } //obtengo que objetos ProvisionHost vienen con llave repetida en el archivo private boolean buscarRegistro(ArrayList<ProvisionHost> regsProvisionHostCompara, ProvisionHost regProvisionHost) { boolean buscaReg = false; if (regsProvisionHostCompara != null) { Iterator iterador = regsProvisionHostCompara.listIterator(); while (iterador.hasNext()) { ProvisionHost provisionHost = (ProvisionHost) iterador.next(); //Obtengo el elemento contenido //pero visto como un provisionHost if (provisionHost.getProvisionHostPK().equals(regProvisionHost.getProvisionHostPK())) { buscaReg = true; } } } return buscaReg; } private MovimientoCuadre obtenerMovimientoCuadreLinea(ProvisionHost ph) { TipoMovimientoCuadre tm = null; MovimientoCuadre mc = new MovimientoCuadre(); mc.setIdUsuario("HOST"); if (ph.getProvisionHostPK().getMotivo() == 75 && ph.getProvisionHostPK().getTipo() == 99) { tm = TipoMovimientoCuadre.PROVISION_DIA_SIGUIENTE_IDO;//299 } //OJO REVISAR CON JOHN ESTE CASO if (ph.getProvisionHostPK().getMotivo() == 70 && ph.getProvisionHostPK().getTipo() == 98) { tm = TipoMovimientoCuadre.AUMENTO_PROVISION_LINEA;//215 } if (ph.getProvisionHostPK().getMotivo() == 70 && ph.getProvisionHostPK().getTipo() == 99) { tm = TipoMovimientoCuadre.DISMINUCION_PROVISION_LINEA;//216 } if (ph.getProvisionHostPK().getMotivo() == 112 && ph.getProvisionHostPK().getTipo() == 98) { tm = TipoMovimientoCuadre.AUMENTO_PROVISION_IDO;//210 } if (ph.getProvisionHostPK().getMotivo() == 112 && ph.getProvisionHostPK().getTipo() == 99) { tm = TipoMovimientoCuadre.DISMINUCION_PROVISION_IDO;//211 } if (ph.getProvisionHostPK().getMotivo() == 16 && ph.getProvisionHostPK().getTipo() == 98 && ph.getUsuarioHost().trim().length() == 0) { tm = TipoMovimientoCuadre.SOBRANTE_IDO;//220 } if (ph.getProvisionHostPK().getMotivo() == 16 && ph.getProvisionHostPK().getTipo() == 98 && ph.getUsuarioHost().trim().length() > 0) { tm = TipoMovimientoCuadre.SOBRANTE_MANUAL;//221 mc.setIdUsuario(ph.getUsuarioHost()); } if (ph.getProvisionHostPK().getMotivo() == 35 && ph.getProvisionHostPK().getTipo() == 99 && ph.getUsuarioHost().trim().length() == 0) { tm = TipoMovimientoCuadre.FALTANTE_IDO;//240 } //REVISAR ESTOS ITEMS FALTANTE_MANUAL Y SOBRANTE_MANUAL 16 99 Y 35 98 if (ph.getProvisionHostPK().getMotivo() == 35 && ph.getProvisionHostPK().getTipo() == 99 && ph.getUsuarioHost().trim().length() > 0) { tm = TipoMovimientoCuadre.FALTANTE_MANUAL;//241 mc.setIdUsuario(ph.getUsuarioHost()); } if (tm != null) { com.davivienda.sara.entitys.TipoMovimientoCuadre tmc; tmc = em.find(new com.davivienda.sara.entitys.TipoMovimientoCuadre().getClass(), tm.codigo); if (tmc != null) { mc.setCajero(ph.getCajero()); if (tm == TipoMovimientoCuadre.PROVISION_DIA_SIGUIENTE_IDO) { mc.setFecha(com.davivienda.utilidades.conversion.Fecha.getDate(ph.getProvisionHostPK().getFecha(), -1)); } else //ajuste para dejar estos items en la fecha que corresponda y no la que viene en el archivo del dia siguiente if (tm.equals(TipoMovimientoCuadre.AUMENTO_PROVISION_LINEA) || tm.equals(TipoMovimientoCuadre.DISMINUCION_PROVISION_LINEA)) { mc.setFecha(Fecha.getDate(ph.getProvisionHostPK().getFecha(), -1)); } else { mc.setFecha(ph.getProvisionHostPK().getFecha()); } mc.setTipoMovimientoCuadre(tmc); mc.setValorMovimiento(ph.getValor()); } else { mc = null; } } else { mc = null; } return mc; } }
package com.junhui; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.TextView; import com.junhui.widget.TouchProgressView; public class MainActivity extends AppCompatActivity implements TouchProgressView.OnProgressChangedListener { private static final String TAG = "MainActivity"; TextView tvProgress; TouchProgressView proViewDft; TouchProgressView proViewStyle1; TouchProgressView proViewStyle2; TouchProgressView proViewStyle3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { tvProgress = (TextView) findViewById(R.id.tv_progress); proViewDft = (TouchProgressView) findViewById(R.id.proview_dft); proViewDft.setProgress(15); proViewDft.setOnProgressChangedListener(this); proViewStyle1 = (TouchProgressView) findViewById(R.id.proview_style1); proViewStyle1.setOnProgressChangedListener(this); proViewStyle1.setLineColor(R.color.colorPrimary); proViewStyle1.setLineHeight(5); proViewStyle1.setProgress(50); proViewStyle2 = (TouchProgressView) findViewById(R.id.proview_style2); proViewStyle2.setOnProgressChangedListener(this); proViewStyle2.setPointColor(R.color.colorPrimary); proViewStyle2.setPointRadius(20); proViewStyle2.setProgress(33); proViewStyle3 = (TouchProgressView) findViewById(R.id.proview_style3); proViewStyle3.setOnProgressChangedListener(this); proViewStyle3.setLineColor(R.color.colorAccent); proViewStyle3.setLineHeight(10); proViewStyle3.setProgress(75); proViewStyle3.setPointColor(R.color.colorAccent); proViewStyle3.setPointRadius(20); } @Override public void onProgressChanged(View v, int progress) { String name = null; switch (v.getId()) { case R.id.proview_dft: name = "proViewDft"; break; case R.id.proview_style1: name = "proViewStyle1"; break; case R.id.proview_style2: name = "proViewStyle2"; break; case R.id.proview_style3: name = "proViewStyle3"; break; } Log.i(TAG, name + " 进度发生变化, progress == " + progress); tvProgress.setText(progress + "%"); } }
package com.metoo.module.chatting.service; import java.io.Serializable; import java.util.List; import java.util.Map; import com.metoo.core.query.support.IPageList; import com.metoo.core.query.support.IQueryObject; import com.metoo.module.chatting.domain.Chatting; public interface IChattingService { /** * 保存一个Chatting,如果保存成功返回true,否则返回false * * @param instance * @return 是否保存成功 */ boolean save(Chatting instance); /** * 根据一个ID得到Chatting * * @param id * @return */ Chatting getObjById(Long id); /** * 删除一个Chatting * * @param id * @return */ boolean delete(Long id); /** * 批量删除Chatting * * @param ids * @return */ boolean batchDelete(List<Serializable> ids); /** * 通过一个查询对象得到Chatting * * @param properties * @return */ IPageList list(IQueryObject properties); /** * 更新一个Chatting * * @param id * 需要更新的Chatting的id * @param dir * 需要更新的Chatting */ boolean update(Chatting instance); /** * * @param query * @param params * @param begin * @param max * @return */ List<Chatting> query(String query, Map params, int begin, int max); }
package com.github.fly_spring.demo03.aop; import org.springframework.stereotype.Service; /** * 使用方法规则被拦截类 * * @author william * */ @Service public class DemoMethodService { public void add() { System.out.println("*****DemoMethodService.add"); } }
/* * Created on 2004-05-18 */ package com.esum.ebms.v2.adapter; import java.io.Serializable; import com.esum.ebms.v2.packages.EbXMLMessage; import com.esum.ebms.v2.service.ServiceContext; /** * EBMS와 연동하기위한 Adapter 인터페이스. * Application은 이 인터페이스를 통해 EBMS와 연동할 수 있다. * * Copyright(c) eSum Technologies., inc. All rights reserved. */ public interface Adapter extends Serializable { /** * EbXML Message를 수신했을 경우, Payload를 포함한 메시지를 받게된다. * Adapter를 구현한 Application은 이 메소드를 통해 메시지를 받아서 처리 할 수 있다. * * @param messageId 수신한 메시지 ID * @param message EbXMLMessage */ public void onMessage(String messageId, EbXMLMessage message); /** * EBMS로부터 Ack Message를 수신했을 대 호출되는 인터페이스. * 송신한 메시지에 대해 ACK를 받도록 설정을 했다면, Application은 ACK 메시지를 이 메소드를 * 통해 받을 수 있다. 구현은 Application 에 의해 행해져야 한다. * * @param refMessageId ACK메시지가 참조하는 송신 메시지ID * @param message 수신한 메시지 */ public void onAcknowledge(String refMessageId, EbXMLMessage message); /** * 송신한 메시지에 대한 에러리스트를 수신받기 위한 인터페이스. * 송신한 메시지에 에러가 발생했을때 파트너MSH로부터 ErrorList를 받게 되며, EBMS는 이 메소드를 통해 * Application으로 전달한다. * * @param refMessageId ErrorList가 참조하는 송신 메시지ID * @param message EbXMLMessage */ public void onErrorList(String refMessageId, EbXMLMessage message); /** * EBMS를 통해 파트너에게 메시지를 송신한 후 EBMS로 부터 처리결과를 받는 메소드. * EBMS의 처리결과를 바로 받을 수 있으며, 수신한 ServiceContext의 정보를 통해 Application이 보낸 메시지의 전송상태를 * 확인할 수 있다. * * @param context 송신 상태 정보. */ public void onResponse(ServiceContext context); }
package com.xiv.gearplanner.controllers; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.xiv.gearplanner.models.*; import com.xiv.gearplanner.services.JobService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.io.IOException; import java.util.ArrayList; import java.util.List; @Controller @RequestMapping("/job") public class JobController { private JobService jobs; // Add job @Autowired public JobController(JobService jobs) { this.jobs = jobs; } @GetMapping("/view") public String viewJobTypes(Model model) { model.addAttribute("types", jobs.getJobs().findAll()); return "/view"; } @GetMapping("/add") public String addJobType(Model model) { model.addAttribute("types", jobs.getJobs().getTypes()); model.addAttribute("job", new Job()); return "job/add"; } @PostMapping("/add") public String submitJobType(@RequestParam("job-type") String type, @Valid Job job, Errors validation, Model model) { if(validation.hasErrors()) { model.addAttribute("job", job); model.addAttribute("types", jobs.getJobs().getTypes()); model.addAttribute("errors", validation); return "job/add"; } job.setType(jobs.getJobs().findTypeById(Long.parseLong(type))); jobs.save(job); return "redirect:/job/add"; } // An overview of all stored BIS in list format @GetMapping("/bis") public String viewStoredBISList(Model model) { model.addAttribute("jobs", jobs.getJobs().findAll()); model.addAttribute("bis",jobs.getSets().findAll()); return "job/bis/index"; } @GetMapping("/bis/view/{id}") public String viewBIS(@PathVariable Long id, Model model) { model.addAttribute("bis",jobs.getSets().findFirstById(id)); return "job/bis/view"; } }
import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.PriorityQueue; import java.util.Scanner; /** * Header * @Author: Aaron Lack, alack * Last edited: 4/20/20 * Class ShortestDistance, will make a read method of a file input, a write method, and the algorithm given below * Create a map instance variable that stores all the directed edges of the cities in the geography map * Also create a starting city instance variable that will be an empty string and will change as the file * is being read for the priority queue. * When making the object, type in the starting location and it will display shortest distance for all cities. * * Algorithm for shortest distance: * Let x be starting point: where x is a city * Add DistanceTo(x,0) to a priority queue * Declare a map shortestKnownDistance which will eventually contain shortest distance from x to all other cities * While the priority queue is not empty * Get the smallest element. * If the target is not a key in shortestKnownDistance * Let d be the distance to that target. * Put (target, d) into shortestKnownDistance * For all citites c that have a direct connection from target * Add DistanceTo(c, d+distance from target to c) to the priority queue * * Sample output: (in file): * {Pierre: 2, Pueblo: 5, "Phonenix: 4" when source is Pendleton} */ public class ShortestDistance { //This map is for all the direct connections distances private Map<String, HashSet<DistanceTo>> map = new HashMap<String, HashSet<DistanceTo>>(); private String startingCity = ""; //Constructor, make an object where you type in the starting city and call the read and write methods public ShortestDistance(String startingCity) throws FileNotFoundException { this.startingCity = startingCity; readFile(); writeFile(); } public void readFile() throws FileNotFoundException { //Read in a text file of all the distances possible for all the cities (edges in the graph) String startingPoint = ""; File inputFile = new File ("distances.txt"); Scanner in = new Scanner(inputFile); HashSet<DistanceTo> distances = new HashSet<>(); //tokens[0] is the starting city while(in.hasNextLine()) { String lines = in.nextLine(); String[] tokens = lines.split(" "); startingPoint = tokens[0]; DistanceTo d = new DistanceTo(tokens[1], Integer.parseInt(tokens[2])); if(!map.containsKey(startingPoint)) { distances.add(new DistanceTo(tokens[1], Integer.parseInt(tokens[2]))); map.put(startingPoint, new HashSet<>()); } map.get(startingPoint).add(d); } in.close(); } public Map<String, DistanceTo> findShortestDistance() throws FileNotFoundException { //put the values of distances map into a hashset to be used for shortestKnownDistance Map<String, DistanceTo> shortestKnownDistance = new HashMap<>(); PriorityQueue<DistanceTo> pq = new PriorityQueue<DistanceTo>(); //Starting point pq.add(new DistanceTo(startingCity, 0)); while(!pq.isEmpty()) { //Will get smallest element in priority queue DistanceTo smallestElement = pq.poll(); if(!shortestKnownDistance.containsKey(smallestElement.getTarget())) { String target = smallestElement.getTarget(); Integer distance = smallestElement.getDistance(); shortestKnownDistance.put(target,new DistanceTo(startingCity,distance)); //Iterate over the map and will get a distance too object. Then you will add it to the priority queue. Iterator<DistanceTo> iter = map.get(target).iterator(); while (iter.hasNext()) { DistanceTo smallest = iter.next(); pq.add(new DistanceTo(smallest.getTarget(), distance + smallest.getDistance())); } } } return shortestKnownDistance; } public void writeFile() throws FileNotFoundException { //Try catch is default for writing it. FileWriter out; try { out = new FileWriter("shortestDistances.txt"); out.write(findShortestDistance().toString() + "\n"); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String args[]) throws FileNotFoundException { //Create a ShortestDistance object and just pass in the city you want to start at //Then call the findShortestDistance method. ShortestDistance test = new ShortestDistance("Pueblo"); Map<String, DistanceTo> testMap = test.findShortestDistance(); for(String s : testMap.keySet()) { DistanceTo value = testMap.get(s); String shortestDistance = value.getTarget() + " to " + s.toString() + ": " + value.getDistance(); System.out.println(shortestDistance); } } }
package cc.ipotato.Enum.JdkEnum; public class Test { public static void main(String[] args) { // demo1(); // demo2(); demo3(); } private static void demo3() { Week3 mon = Week3.MON; System.out.println(mon); mon.show(); } private static void demo2() { Week2 mon = Week2.MON; System.out.println(mon); System.out.println(mon.getName()); } private static void demo1() { Week1 mon = Week1.MON; System.out.println(mon); } }
package com.digitalinnovationone.heroesmanagerapi; import com.digitalinnovationone.heroesmanagerapi.repository.HeroesRepository; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.reactive.server.WebTestClient; import static com.digitalinnovationone.heroesmanagerapi.constants.HeroesConstants.HEROES_ENDPOINT_LOCAL; @ExtendWith(SpringExtension.class) @DirtiesContext @AutoConfigureWebTestClient @SpringBootTest class HeroesManagerApiApplicationTests { @Autowired WebTestClient webTestClient; @Autowired HeroesRepository heroesRepository; @Test void contextLoads() { } @Test void getOneHeroById() { webTestClient.get().uri(HEROES_ENDPOINT_LOCAL.concat("/{id}"), "3") .exchange() .expectStatus().isOk() .expectBody(); } @Test void getOneHeroNotFound() { webTestClient.get().uri(HEROES_ENDPOINT_LOCAL.concat("/{id}"), "28743") .exchange() .expectStatus().isNotFound(); } @Test void deleteHero() { webTestClient.delete().uri(HEROES_ENDPOINT_LOCAL.concat("/{id}"), "7") .exchange() .expectStatus().isOk() .expectBody(Void.class); } @Test void deleteHeroNotFound() { webTestClient.delete().uri(HEROES_ENDPOINT_LOCAL.concat("/{id}"), "7") .exchange() .expectStatus().is5xxServerError(); } }