text
stringlengths 10
2.72M
|
|---|
package com.emed.shopping.service.admin.store.impl;
import com.emed.shopping.base.BaseResult;
import com.emed.shopping.base.BaseServiceImpl;
import com.emed.shopping.dao.mapper.admin.store.ShopStoreMapper;
import com.emed.shopping.dao.model.admin.store.ShopStore;
import com.emed.shopping.service.admin.store.ShopStoreService;
import com.emed.shopping.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Administrator on 2018/1/16 0016.
*/
@Service
public class ShopStoreServiceImpl extends BaseServiceImpl<ShopStore> implements ShopStoreService {
@Autowired
private ShopStoreMapper shopStoreMapper;
@Override
public BaseResult updateStoreInfo(HttpServletRequest request) {
ShopStore shopStore = new ShopStore();
shopStore.setId(Long.parseLong(request.getParameter("id")));
if(request.getParameter("recommend")!=null)
shopStore.setStoreRecommend(request.getParameter("recommend").equals("on")?"1":"2");
if(!request.getParameter("Village").equals("0"))
shopStore.setAreaId(Long.parseLong(request.getParameter("Village")));
if(request.getParameter("cardApprove")!=null)
shopStore.setCardApprove(request.getParameter("cardApprove").equals("实名认证")?"1":"0");
if(request.getParameter("realstoreApprove")!=null)
shopStore.setRealstoreApprove(request.getParameter("realstoreApprove").equals("实体店铺认证")?"1":"0");
shopStore.setStoreName(request.getParameter("storeName"));
shopStore.setStoreOwer(request.getParameter("storeOwer"));
shopStore.setScId(Long.parseLong(request.getParameter("className")));
shopStore.setStoreAddress(request.getParameter("storeAddress"));
shopStore.setStoreZip(request.getParameter("storeZip"));
shopStore.setStoreTelephone(request.getParameter("storeTelephone"));
shopStore.setValidity(DateUtils.parseDate(request.getParameter("validity")));
shopStore.setStoreStatus(Integer.parseInt(request.getParameter("storeStatus")));
int i = shopStoreMapper.updateByPrimaryKeySelective(shopStore);
if (i!=0){
return new BaseResult(200,"修改成功!",shopStore);
}else{
return new BaseResult(400,"修改失败,请联系管理员!",shopStore);
}
}
@Override
public void insertAndGetId(ShopStore shopStore) {
shopStoreMapper.insertAndGetId(shopStore);
}
}
|
// SPDX-License-Identifier: BSD-3-Clause
package org.xbill.DNS.dnssec;
/**
* Codes for DNSSEC security statuses along with a reason why the status was determined.
*
* @since 3.5
*/
final class JustifiedSecStatus {
SecurityStatus status;
int edeReason;
String reason;
/**
* Creates a new instance of this class.
*
* @param status The security status.
* @param reason The reason why the status was determined.
*/
JustifiedSecStatus(SecurityStatus status, int edeReason, String reason) {
this.status = status;
this.edeReason = edeReason;
this.reason = reason;
}
/**
* Applies this security status to a response message.
*
* @param response The response to which to apply this status.
*/
void applyToResponse(SMessage response) {
response.setStatus(this.status, edeReason, this.reason);
}
}
|
package com.example.thang.moviehype;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Patterns;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, OnFailureListener{
private Button signInWithGoogleButton, signInButton, signUpButton, forgotButton;
private ProgressBar progressBar;
private EditText usernameInput, passwordInput;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private GoogleSignInClient mGoogleSignInClient;
private final static int RC_SIGN_IN = 2;
@Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = findViewById(R.id.progress_Bar);
signInWithGoogleButton = findViewById(R.id.signInWithGoogleBtn);
signInButton = findViewById(R.id.signIn_Btn);
signUpButton = findViewById(R.id.signUpButton);
forgotButton = findViewById(R.id.forgotBtn);
usernameInput = findViewById(R.id.usernameField);
passwordInput = findViewById(R.id.passwordField);
mAuth = FirebaseAuth.getInstance();
passwordInput.setImeActionLabel("Sign In", KeyEvent.KEYCODE_ENTER);
passwordInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
userLogin();
return true;
}
});
signUpButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onClickSignUp();
}
});
forgotButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onClickForgot();
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(MainActivity.this, HomeActivity.class));
}
}
};
signInButton.setOnClickListener(this);
signInWithGoogleButton.setOnClickListener(this);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.signIn_Btn:
userLogin();
break;
case R.id.signInWithGoogleBtn:
onClickGoogleSignIn();
break;
}
}
private void userLogin() {
String username = usernameInput.getText().toString();
String password = passwordInput.getText().toString();
if(username.isEmpty()) {
usernameInput.setError("Please enter an Email");
usernameInput.requestFocus();
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(username).matches()) {
usernameInput.setError("Please enter a valid Email!");
usernameInput.requestFocus();
return;
}
if(password.isEmpty()) {
passwordInput.setError("Password required!");
passwordInput.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.signInWithEmailAndPassword(username, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if(task.isSuccessful()){
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
Toast.makeText(MainActivity.this, "Google Sign In went wrong", Toast.LENGTH_LONG).show();
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d("TAG", "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w("TAG", "signInWithCredential:failure", task.getException());
Toast.makeText(MainActivity.this, "Authentication Failed.", Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
private void onClickGoogleSignIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void onClickForgot() {
Intent forgotIntent = new Intent(MainActivity.this, ResetPasswordActivity.class);
startActivity(forgotIntent);
}
private void onClickSignUp() {
Intent signUpIntent = new Intent(MainActivity.this, SignUpActivity.class);
startActivity(signUpIntent);
}
@Override
public void onFailure(@NonNull Exception e) {
}
}
|
package codeWars.perfectPower;
import java.util.ArrayList;
import java.util.List;
public class PerfectPower {
public static int[] isPerfectPower(int n) {
System.out.println(n + ": ");
List<Integer> result = new ArrayList<Integer>();
for (int i = 2 ; i<=(int)(Math.ceil(Math.sqrt(n))) ; i++) {
double roof = Math.pow(n, 1D/i);
System.out.println(roof + " : " + i);
double cha = roof - Math.round(roof);
if(Math.abs(cha) < 0.000000000001){
result.add((int) Math.round(roof));
result.add(i);
}
}
if(result.size() == 0)
return null;
else{
int[] resultarr = new int[result.size()];
for(int i = 0 ; i<result.size() ; i++){
int tmp = result.get(i) ;
resultarr[i] = tmp;
}
return resultarr;
}
}
}
|
package controllers;
/**
* Created by Jonatan on 06/11/2015.
*/
public class Roles extends CRUD {
}
|
package db.jdbc;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Ref;
import java.sql.SQLException;
/**
* Base class for all database Formatters such as OracleFormatter.
*/
public abstract class SqlFormatter
{
/**
* Formats a blob to the following String "'<Blob length = " + blob.length()+">'"
* This method's output will not translate directly into the database. It is informational only.
*
* @param blob The blob to be translated
* @return The String representation of the blob
* @throws SQLException the sQL exception
*/
protected String format(final java.sql.Blob blob) throws SQLException
{
return "'<Blob length = " + blob.length() + ">'";
}
/**
* Formats a clob to the following String "'<Clob length = " + clob.length()+">'"
* This method's output will not translate directly into the database. It is informational only.
*
* @param clob The clob to be translated
* @return The String representation of the clob
* @throws SQLException the sQL exception
*/
protected String format(final java.sql.Clob clob) throws SQLException
{
return "'<Clob length = " + clob.length() + ">'";
}
/**
* Formats an Array to the following String "array.getBaseTypeName()"
* This method's output will not translate directly into the database. It is informational only.
*
* @param array The array to be translated
* @return The base name of the array
* @throws SQLException the sQL exception
*/
protected String format(final java.sql.Array array) throws SQLException
{
return array.getBaseTypeName();
}
/**
* Formats a Ref to the following String "ref.getBaseTypeName()"
* This method's output will not translate directly into the database. It is informational only.
*
* @param ref The ref to be translated
* @return The base name of the ref
* @throws SQLException the sQL exception
*/
protected String format(final java.sql.Ref ref) throws SQLException
{
return ref.getBaseTypeName();
}
/**
* Checks the String for null and returns "'" + string + "'".
*
* @param string String to be formatted
* @return formatted String (null returns "NULL")
* @throws SQLException the sQL exception
*/
protected String format(final java.lang.String string) throws SQLException
{
if (string.equals("NULL"))
return string;
else
return "'" + string + "'";
}
/**
* If object is null, Blob, Clob, Array, Ref, or String this returns the value from
* the protected methods in this class that take those Classes.
*
* @param o Object to be formatted
* @return formatted String
* @throws SQLException the sQL exception
*/
public String format(final Object o) throws SQLException
{
if (o == null)
return "NULL";
if (o instanceof Blob)
return format((Blob) o);
if (o instanceof Clob)
return format((Clob) o);
if (o instanceof Array)
return format((Array) o);
if (o instanceof Ref)
return format((Ref) o);
if (o instanceof String)
return format((String) o);
return o.toString();
}
}
|
package baitap;
abstract public class SinhVien {
public String hoTen;
public String nganh;
public SinhVien(String hoTen, String nganh) {
super();
this.hoTen = hoTen;
this.nganh = nganh;
}
abstract public double getDiemTrungBinh();
public String getHocLuc() {
double diemTrungBinh = getDiemTrungBinh();
if(diemTrungBinh<5) {
return "Hoc luc yeu";
}else if(5<=diemTrungBinh && diemTrungBinh<6.5) {
return "Hoc luc trung binh";
}else if(6.5<=diemTrungBinh && diemTrungBinh<7.5) {
return "Hoc luc kha";
}else if(7.5<=diemTrungBinh && diemTrungBinh<9) {
return "Hoc luc gioi";
}else{
return "Hoc luc xuat sac";
}
}
public void xuat() {
System.out.println("Ho ten: " + hoTen + "\n Nganh: "+ nganh +"\n Diem: "+ getDiemTrungBinh() + "\n Hoc luc: "+ getHocLuc());
}
}
|
package net.nima.trend.home.module.screen;
import net.nima.trend.biz.ao.FooAO;
import net.nima.trend.common.base.BaseScreen;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.TurbineRunData;
public class Index extends BaseScreen {
@Autowired
private FooAO fooAO;
@Override
public void execute(TurbineRunData runData, Context context) {
String msg = fooAO.getMessage();
context.put("msg", "welcome to webx");
}
}
|
/*
* MemInfo.java
* Written 2013 by M Koch
* Copyright abandoned. This file is in the public domain.
*/
package testcachesim;
public class MemInfo {
private CacheType type;
private String hexAddress;
private int decAddress;
private String size;
private Long timestamp;
private int usageCounter;
private int programCounter;
private String type2;
public MemInfo(CacheType type, String type2, String hexAddress, int decAddress, String size) {
this.type = type;
this.type2 = type2;
this.hexAddress = hexAddress;
this.decAddress = decAddress;
this.size = size;
this.timestamp = (long) 0;
this.usageCounter = 0;
this.programCounter = 0;
}
public String getType2() {
return type2;
}
public void setType2(String type2) {
this.type2 = type2;
}
public CacheType getType() {
return type;
}
public String getHexAddress() {
return hexAddress;
}
public int getDecAddress() {
return decAddress;
}
public String getSize() {
return size;
}
public int getUsageCounter() {
return usageCounter;
}
public void setUsageCounter(int counter) {
this.usageCounter = counter;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public String getAdress() {
return hexAddress;
}
public void incUsageCounter() {
usageCounter++;
}
public void setProgramCounter(int programCounter) {
this.programCounter = programCounter;
}
public int getProgramCounter() {
return programCounter;
}
}
|
package com.oa.schedule.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.oa.message.service.ShortMessageService;
import com.oa.page.PageUtils;
import com.oa.page.form.Page;
import com.oa.schedule.form.WorkComment;
import com.oa.schedule.form.WorkSchedule;
import com.oa.schedule.form.WorkSummary;
import com.oa.schedule.service.WorkCommentService;
import com.oa.schedule.service.WorkScheduleService;
import com.oa.schedule.service.WorkSummaryService;
import com.oa.user.form.UserInfo;
import com.oa.user.service.UserInfoService;
@Controller
@RequestMapping(value="/workSchedule/workScheduleManager")
public class WorkScheduleController {
@Autowired
private WorkScheduleService workScheduleService;
@Autowired
private WorkCommentService workCommentService;
@Autowired
private WorkSummaryService workSummaryService;
@Autowired
private UserInfoService userInfoService;
@Autowired
private ShortMessageService shortMessgeService;
@RequestMapping(value="/addWorkSchedule")
public String addWorkSchedule(@ModelAttribute("workSchedule") WorkSchedule workSchedule) {
workScheduleService.addWorkSchedule(workSchedule);
return "redirect:/workSchedule/workScheduleManager/listWorkSchedules";
}
@RequestMapping(value="/listWorkSchedules")
public String selectAllWorkSchedule(Map<String,Object> map,HttpServletRequest request) {
String pageNo = request.getParameter("pageNo");
pageNo=pageNo==null?"1":pageNo;
String pageSize = request.getParameter("pageSize");
pageSize=pageSize==null?"10":pageSize;
map.put("workSchedule", new WorkSchedule());
Page<WorkSchedule> page = PageUtils.createPage(Integer.parseInt(pageSize), workScheduleService.findAllWorkSchedules().size(),Integer.parseInt(pageNo));
List<WorkSchedule> workScheduleList = workScheduleService.findAllWorkScheduleByPage(page);
map.put("workScheduleList", workScheduleList);
map.put("page", page);
return "/workSchedule/workScheduleManager/workScheduleList";
}
@RequestMapping(value="/editWorkScheduleByName/{workScheduleTitle}")
public ModelAndView selectWorkScheduleByName(@PathVariable("workScheduleTitle")String workScheduleTitle) {
WorkSchedule item = workScheduleService.findWorkScheduleByWorkScheduleTitle(workScheduleTitle);
Map<String,Object> map = new HashMap<String,Object>();
map.put("workSchedule", item);
return new ModelAndView("/workSchedule/workScheduleManager/editWorkSchedule",map);
}
@RequestMapping(value="/editWorkScheduleById/{id}")
public ModelAndView selectWorkScheduleById(@PathVariable("id")int id) {
WorkSchedule workSchedule= workScheduleService.findWorkScheduleById(id);
Map<String,Object> model = new HashMap<String,Object>();
model.put("workSchedule", workSchedule);
return new ModelAndView("/workSchedule/workScheduleManager/editWorkSchedule",model);
}
@RequestMapping(value="/updateWorkSchedule", method=RequestMethod.POST)
public String updateWorkSchedule(@ModelAttribute("workSchedule")WorkSchedule workSchedule,HttpServletRequest request) {
workScheduleService.updateWorkSchedule(workSchedule);
return "redirect:/workSchedule/workScheduleManager/listWorkSchedules";
}
@RequestMapping(value="/deleteWorkSchedule/{id}")
public String deleteWorkSchedule(@PathVariable("id") Integer id) {
workScheduleService.deleteWorkSchedule(id);
return "redirect:/workSchedule/workScheduleManager/listWorkSchedules";
}
@RequestMapping(value = "/ajaxRequestUserInfoByLoginName", method = RequestMethod.GET)
public @ResponseBody Map<String, Object> ajaxRequestAllEmails(HttpServletRequest request) {
String loginName = request.getParameter("loginName");
List<UserInfo> userInfoList = shortMessgeService.findUserInfosByLoginName(loginName);
Map<String, Object> map = new HashMap<String, Object>();
map.put("userInfoList", userInfoList);
map.put("code", "200");
return map;
}
/*@RequestMapping(value = "/ajaxRequestGroupsByGroupName", method = RequestMethod.GET)
public @ResponseBody Map<String, Object> ajaxRequestGroups(HttpServletRequest request) throws Exception {
String groupName = request.getParameter("groupName");
String gName = URLDecoder.decode(groupName,"utf-8");
List<Group> groupList = groupService.selectGroupByWildName(gName);
Map<String, Object> map = new HashMap<String, Object>();
map.put("groupList", groupList);
map.put("code", "200");
return map;
}
*/
@RequestMapping(value="/addWorkSummary")
public String addWorkSummary(@ModelAttribute("workSummary") WorkSummary workSummary) {
workSummaryService.addWorkSummary(workSummary);
return "redirect:/workSchedule/workScheduleManager/listWorkSummarys";
}
@RequestMapping(value="/listWorkSummarys")
public String selectAllWorkSummary(Map<String,Object> map,HttpServletRequest request) {
String pageNo = request.getParameter("pageNo");
pageNo=pageNo==null?"1":pageNo;
String pageSize = request.getParameter("pageSize");
pageSize=pageSize==null?"10":pageSize;
map.put("workSummary", new WorkSummary());
Page<WorkSummary> page = PageUtils.createPage(Integer.parseInt(pageSize), workSummaryService.findAllWorkSummarys().size(),Integer.parseInt(pageNo));
List<WorkSummary> workSummaryList = workSummaryService.findAllWorkSummaryByPage(page);
map.put("workSummaryList", workSummaryList);
map.put("page", page);
return "/workSchedule/workScheduleManager/workSummaryList";
}
@RequestMapping(value="/editWorkSummaryById/{id}")
public ModelAndView selectWorkSummaryById(@PathVariable("id")int id) {
WorkSummary workSummary= workSummaryService.findWorkSummaryById(id);
Map<String,Object> model = new HashMap<String,Object>();
model.put("workSummary", workSummary);
return new ModelAndView("/workSchedule/workScheduleManager/editWorkSummary",model);
}
@RequestMapping(value="/updateWorkSummary", method=RequestMethod.POST)
public String updateWorkSummary(@ModelAttribute("workSummary")WorkSummary workSummary,HttpServletRequest request) {
workSummaryService.updateWorkSummary(workSummary);
return "redirect:/workSchedule/workScheduleManager/listWorkSummarys";
}
@RequestMapping(value="/deleteWorkSummary/{id}")
public String deleteWorkSummary(@PathVariable("id") Integer id) {
workSummaryService.deleteWorkSummary(id);
return "redirect:/workSchedule/workScheduleManager/listWorkSummarys";
}
@RequestMapping(value="/addWorkComment")
public @ResponseBody Map<String, Object> addWorkComment(@ModelAttribute("workComment") WorkComment workComment) {
Map<String, Object> modalMap = new HashMap<String, Object>();
try{
workCommentService.addWorkComment(workComment);
}catch(Exception e){
modalMap.put("code", 500);
modalMap.put("message", "fail");
}
modalMap.put("code", 200);
modalMap.put("message", "success");
return modalMap;
}
}
|
package com.grantingersoll.intell.index;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.mahout.classifier.ClassifierResult;
import org.apache.mahout.classifier.bayes.exceptions.InvalidDatastoreException;
import org.apache.mahout.classifier.bayes.model.ClassifierContext;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.SolrInputField;
import org.apache.solr.update.AddUpdateCommand;
import org.apache.solr.update.processor.UpdateRequestProcessor;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
/** A Solr <code>UpdateRequestProcessor</code> that uses the Mahout Bayes
* Classifier to add a category label to documents at index time.
* <p/>
* @see com.grantingersoll.intell.index.BayesUpdateRequestProcessorFactory
*
* * Used with permission from "Taming Text": http://lucene.li/1d
*
*
*/
public class BayesUpdateRequestProcessor extends UpdateRequestProcessor {
public static final String NULL = "nullDefault";
ClassifierContext ctx;
String inputField;
String outputField;
String defaultCategory;
Analyzer analyzer;
public BayesUpdateRequestProcessor(ClassifierContext ctx, Analyzer analyzer,
String inputField, String outputField, String defaultCategory, UpdateRequestProcessor next) {
super(next);
this.ctx = ctx;
this.analyzer = analyzer;
this.inputField = inputField;
this.outputField = outputField;
this.defaultCategory = defaultCategory;
if (this.defaultCategory == null) {
this.defaultCategory = NULL;
}
}
@Override
public void processAdd(AddUpdateCommand cmd) throws IOException {
SolrInputDocument doc = cmd.getSolrInputDocument();
ClassifierResult result = classifyDocument(doc);
if (result != null && result.getLabel() != NULL) {
doc.addField(outputField, result.getLabel());
}
super.processAdd(cmd);
}
public ClassifierResult classifyDocument(SolrInputDocument doc) throws IOException {
SolrInputField field = doc.getField(inputField);
if (field == null) return null;
if (!(field.getValue() instanceof String)) return null;
String[] tokens = tokenizeField((String) field.getValue());
try {
return ctx.classifyDocument(tokens, defaultCategory);
}
catch (InvalidDatastoreException e) {
throw new IOException("Invalid Classifier Datastore", e);
}
}
public String[] tokenizeField(String input) throws IOException {
ArrayList<String> tokenList = new ArrayList<String>(256);
TokenStream ts = analyzer.tokenStream(inputField, new StringReader(input));
while (ts.incrementToken()) {
tokenList.add(ts.getAttribute(CharTermAttribute.class).toString());
}
return tokenList.toArray(new String[tokenList.size()]);
}
}
|
/*
* Copyright (c) 2016 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.server.bulkops;
import pl.edu.icm.unity.server.translation.TranslationActionInstance;
import pl.edu.icm.unity.types.basic.Entity;
import pl.edu.icm.unity.types.translation.TranslationActionType;
/**
* Implementation performs an action on a given entity.
* @author K. Benedyczak
*/
public abstract class EntityAction extends TranslationActionInstance
{
public EntityAction(TranslationActionType actionType, String[] parameters)
{
super(actionType, parameters);
}
/**
* Performs an implementation specific action.
* @param entity entity to operate on.
*/
public abstract void invoke(Entity entity);
}
|
package Sorting;
public class MergeSort {
public static void main(String args[])
{
int[] data = new int[]{2,8,12,-3,6,5,8,-45,108,53,22,34,8};
mergeSort(data,0,12);
for (int i:data
) {
System.out.println(i);
}
}
private static void mergeSort(int[] data,int start,int end)
{
if(start<end)
{
int mid = (start+end)/2;
mergeSort(data,start,mid);
mergeSort(data,mid+1,end);
merge(data,start,end,mid);
}
}
private static void merge(int[] data,int start,int end ,int mid)
{
int[] auxArray = new int[end-start+1];
int left = start;
int right = mid+1;
int auxIndex = 0;
while(left<=mid&&right<=end)
{
if(data[left]<data[right])
{
auxArray[auxIndex] = data[right];
right++;
}
else
{
auxArray[auxIndex] = data[left];
left++;
}
auxIndex++;
}
while(left<=mid)
{
auxArray[auxIndex] = data[left];
left++;
}
while(right<=end)
{
auxArray[auxIndex] = data[right];
right++;
}
auxIndex=0;
for(int i=start;i<=end;i++,auxIndex++)
{
data[i]=auxArray[auxIndex];
}
}
}
|
package demo01.image;
/**
* @Description:
* @Author: lay
* @Date: Created in 19:15 2018/12/7
* @Modified By:IntelliJ IDEA
*/
public interface Image {
void display();
}
|
package com.example.tomevans.planitdemo;
//import android.app.Fragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ConfigureBudgetFragment extends Fragment {
/*Strings of input used for validation*/
String loanString,bursaryString,overdraftString;
/*Users input*/
EditText loanInput, bursaryInput, overdraftInput;
/*Input converted to int*/
int loan,bursary,overdraft;
Button calculate;
@Nullable
@Override
public View onCreateView (LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_configurebudget, null);
}
public void onViewCreated(View view, @Nullable Bundle savedInstanceState){
/*Text fields*/
loanInput = (EditText) getView().findViewById(R.id.loan);
bursaryInput = (EditText) getView().findViewById(R.id.bursary);
overdraftInput = (EditText) getView().findViewById(R.id.overdraft);
/*Button*/
calculate = (Button) getView().findViewById(R.id.calculate);
/*To pass from configbudget to budget*/
final Navigation budg = (Navigation) getActivity();
/*CALCULATE clicked, get inputs*/
calculate.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v){
/*Get strings*/
loanString = loanInput.getText().toString();
overdraftString = overdraftInput.getText().toString();
bursaryString = bursaryInput.getText().toString();
/*If any of the fields are empty, error message*/
if(loanString.trim().equals("") || overdraftString.trim().equals("") || bursaryString.trim().equals("")){
Toast.makeText(getContext(),"You must enter all values",Toast.LENGTH_SHORT).show();
} else { /*ELSE, continue as normal*/
int loan = Integer.parseInt(loanInput.getText().toString());
int bursary = Integer.parseInt(bursaryInput.getText().toString());
int overdraft = Integer.parseInt(overdraftInput.getText().toString());
int sum = loan + bursary + overdraft;
int monthly = sum/10;
int weekly = monthly/4;
budg.total = sum;
budg.monthly = monthly;
budg.weekly = weekly;
/*Go back to budget fragment*/
Fragment fragment = new BudgetFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
});
}
Fragment fragment = null;
}
|
package com.example.demo.controller;
import com.example.demo.domain.Movie;
import com.example.demo.service.MovieService;
import com.example.demo.dto.ResponseDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* Created by Summer on 2018/3/22.
*/
@RestController
@RequestMapping("/movie")
public class MovieController {
@Autowired
private MovieService movieService;
/**
* 查询电影信息
*
* @orderType 1:最新 2:最热
*/
@RequestMapping(value = "/getMovies", method = RequestMethod.GET)
public ResponseDO getMovies(@RequestParam(value = "id", required = false) Integer id,
@RequestParam(value = "orderType", required = false) Integer orderType,
@RequestParam(value = "movieType", required = false) String movieType,
@RequestParam(value = "year", required = false) Integer year,
@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "page_no", required = false, defaultValue = "1") Integer pageNo,
@RequestParam(value = "page_size", required = false, defaultValue = "10") Integer pageSize) {
return new ResponseDO(movieService.getMovies(id, orderType, movieType, year, keyword, pageNo, pageSize));
}
/**
* 更新电影信息
*/
@RequestMapping(value = "/update/Movies", method = RequestMethod.POST)
public ResponseDO updateMovies(@RequestBody Movie movie) {
return new ResponseDO(movieService.updateMovie(movie));
}
/**
* 删除电影信息
*/
@RequestMapping(value = "/delete/Movies")
public ResponseDO deleteMovies(@RequestParam(value = "id") Integer id) {
return new ResponseDO(movieService.deleteMovie(id));
}
/**
* 新增电影
*/
@RequestMapping(value = "/add/Movies", method = RequestMethod.POST)
public ResponseDO addMovies(@RequestBody Movie movie) {
return new ResponseDO(movieService.addMovie(movie));
}
/**
* 获取推荐电影
*/
@RequestMapping(value = "/recommend/Movies", method = RequestMethod.GET)
public ResponseDO getMovies(@RequestParam(value = "user_id", required = true) Integer userId) {
return new ResponseDO(movieService.recommendMovies(userId));
}
/**
* 初始推荐电影
*/
@RequestMapping(value = "/recommend/initMovies", method = RequestMethod.GET)
public ResponseDO getMovies() {
return new ResponseDO(movieService.getInitMovies());
}
}
|
package ro.ase.cts.proxy.clase;
public enum Moneda {
RON,
USD,
EUR;
}
|
/**
*
*/
package com.project.smart6.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author krish
*
*/
@Entity
@Table(name = "ipl_schedule")
public class IPLSchedule {
@Id
public int id;
public String match_no;
public String match_date_time;
public String team1_id;
public String team1_name;
public String team2_id;
public String team2_name;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the match_no
*/
public String getMatch_no() {
return match_no;
}
/**
* @param match_no the match_no to set
*/
public void setMatch_no(String match_no) {
this.match_no = match_no;
}
/**
* @return the match_date_time
*/
public String getMatch_date_time() {
return match_date_time;
}
/**
* @param match_date_time the match_date_time to set
*/
public void setMatch_date_time(String match_date_time) {
this.match_date_time = match_date_time;
}
/**
* @return the team1_id
*/
public String getTeam1_id() {
return team1_id;
}
/**
* @param team1_id the team1_id to set
*/
public void setTeam1_id(String team1_id) {
this.team1_id = team1_id;
}
/**
* @return the team1_name
*/
public String getTeam1_name() {
return team1_name;
}
/**
* @param team1_name the team1_name to set
*/
public void setTeam1_name(String team1_name) {
this.team1_name = team1_name;
}
/**
* @return the team2_id
*/
public String getTeam2_id() {
return team2_id;
}
/**
* @param team2_id the team2_id to set
*/
public void setTeam2_id(String team2_id) {
this.team2_id = team2_id;
}
/**
* @return the team2_name
*/
public String getTeam2_name() {
return team2_name;
}
/**
* @param team2_name the team2_name to set
*/
public void setTeam2_name(String team2_name) {
this.team2_name = team2_name;
}
}
|
package com.programapprentice.app;
import com.programapprentice.util.TreeNode;
import org.junit.Test;
/**
* User: program-apprentice
* Date: 9/29/15
* Time: 9:04 PM
*/
public class BinaryTreeUpsideDown_Test {
BinaryTreeUpsideDown_156 obj = new BinaryTreeUpsideDown_156();
@Test
public void test1() {
TreeNode root = new TreeNode(1);
root.right = new TreeNode(3);
root.left = new TreeNode(2);
root.left.right = new TreeNode(5);
root.left.left = new TreeNode(4);
TreeNode newRoot = obj.upsideDownBinaryTree(root);
}
}
|
package net.gupt.ebuy.pojo;
/**
* 购物车商品类:包括普通商品,以及商品数量
* @author glf
*
*/
public class CartItem {
private Product product;//商品
private int qty;//对应数量
public CartItem() {
}
public CartItem(Product p, int qty) {
this.setProduct(p);
this.setQty(qty);
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}
|
package hu.lamsoft.hms.androidclient.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import hu.lamsoft.hms.androidclient.R;
import hu.lamsoft.hms.androidclient.adapter.PageableDTOAdapter;
import hu.lamsoft.hms.androidclient.adapter.impl.MealViewHolder;
import hu.lamsoft.hms.androidclient.restapi.common.async.AsyncCallback;
import hu.lamsoft.hms.androidclient.restapi.customer.async.CustomerMealsAsyncTask;
import hu.lamsoft.hms.androidclient.restapi.customer.dto.CustomerMealDTO;
public class MealsFragment extends Fragment {
private DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
private PageableDTOAdapter<CustomerMealDTO, MealViewHolder> adapter;
private ListView listView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_meals, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = new PageableDTOAdapter<>(getActivity(), R.layout.list_item_meal, MealViewHolder.class);
listView = (ListView) getActivity().findViewById(R.id.meals_list_view);
listView.setAdapter(adapter);
new CustomerMealsAsyncTask(getDate("2016.01.01"), getDate("2018.01.01"), new AsyncCallback<List<CustomerMealDTO>>() {
@Override
public void onPostExecute(List<CustomerMealDTO> customerMealDTOs) {
adapter.add(customerMealDTOs);
adapter.notifyDataSetChanged();
}
}).execute();
}
private Date getDate(String dateString) {
try {
return dateFormat.parse(dateString);
} catch (ParseException e) {
return null;
}
}
}
|
package com.pykj.ykz.chapter4.test;
import com.pykj.ykz.chapter4.intercept.MyInterceptor;
import com.pykj.ykz.chapter4.intercept.ProxyBean;
import com.pykj.ykz.chapter4.service.HelloService;
import com.pykj.ykz.chapter4.service.impl.HelloServiceImpl;
import com.pykj.ykz.chapter4.service.impl.HelloTest;
/**
* @description: TODO
* @author: zhangpengxiang
* @time: 2020/4/21 11:31
*/
public class TestProxy {
public static void main(String[] args) {
test();
//helloTest();
}
private static void test() {
HelloService helloService = new HelloServiceImpl();
HelloService proxy = (HelloService) ProxyBean.getProxyBean(helloService, new MyInterceptor());
proxy.sayHello("zhangsan");
System.out.println("\n####################name is null##############\n");
proxy.sayHello(null);
}
private static void helloTest() {
HelloTest helloTest = new HelloTest();
HelloTest proxy = (HelloTest) ProxyBean.getProxyBean(helloTest, new MyInterceptor());
proxy.sayHello("zhangsan");
System.out.println("\n####################name is null##############\n");
proxy.sayHello(null);
}
}
|
package de.tu_darmstadt.elc.olw.jbi.component.producer;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.NormalizedMessage;
import javax.jbi.servicedesc.ServiceEndpoint;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.xml.transform.dom.DOMSource;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.servicemix.common.endpoints.ProviderEndpoint;
import org.jdom.Element;
import de.tu_darmstadt.elc.olw.api.constant.MaterialType;
import de.tu_darmstadt.elc.olw.api.misc.UUIDGenerator;
import de.tu_darmstadt.elc.olw.api.misc.io.FileExtractor;
import de.tu_darmstadt.elc.olw.api.restdb.RestClient;
import de.tu_darmstadt.elc.olw.jbi.component.main.ConverterComponent;
import de.tu_darmstadt.elc.olw.jbi.messages.ConverterMessage;
import de.tu_darmstadt.elc.olw.jbi.messages.Report;
import de.tu_darmstadt.elc.olw.jbi.messages.StandardMessage;
/**
*
* @author hungtu
* @org.apache.xbean.XBean element="reporter-provider"
*/
public class Reporter extends ProviderEndpoint {
private static final String HTML_BREAK="<br>";
private static Logger logger = Logger.getLogger(Reporter.class);
private String smtpHostName;
private String smtpHostPort;
private String adminAddress;
private String repositoryRoh;
private String repositoryKonv;
private String archiveWorkspace;
private String materialWorkspace;
// for restdb client
private String fakeLogIn;
private String apiURL;
// for emails
private String reporterAddress;
private String reporterMessageTemplate;
public Reporter() {
super();
}
public Reporter(ConverterComponent component, ServiceEndpoint endpoint) {
super(component, endpoint);
}
/**
* @return the smtpHostName
*/
public String getSmtpHostName() {
return smtpHostName;
}
/**
* @param smtpHostName
* the smtpHostName to set
*/
public void setSmtpHostName(String smtpHostName) {
this.smtpHostName = smtpHostName;
}
/**
* @return the smtpHostPort
*/
public String getSmtpHostPort() {
return smtpHostPort;
}
/**
* @param smtpHostPort
* the smtpHostPort to set
*/
public void setSmtpHostPort(String smtpHostPort) {
this.smtpHostPort = smtpHostPort;
}
/**
* @return the repositoryRoh
*/
public String getRepositoryRoh() {
return repositoryRoh;
}
/**
* @param repositoryRoh
* the repositoryRoh to set
*/
public void setRepositoryRoh(String repositoryRoh) {
this.repositoryRoh = repositoryRoh;
}
/**
* @return the repositoryKonv
*/
public String getRepositoryKonv() {
return repositoryKonv;
}
/**
* @param repositoryKonv
* the repositoryKonv to set
*/
public void setRepositoryKonv(String repositoryKonv) {
this.repositoryKonv = repositoryKonv;
}
/**
* @return the archiveWorkspace
*/
public String getArchiveWorkspace() {
return archiveWorkspace;
}
/**
* @param archiveWorkspace
* the archiveWorkspace to set
*/
public void setArchiveWorkspace(String archiveWorkspace) {
this.archiveWorkspace = archiveWorkspace;
}
/**
* @return the materialWorkspace
*/
public String getMaterialWorkspace() {
return materialWorkspace;
}
/**
* @param materialWorkspace
* the materialWorkspace to set
*/
public void setMaterialWorkspace(String materialWorkspace) {
this.materialWorkspace = materialWorkspace;
}
/**
* @return the fakeLogIn
*/
public String getFakeLogIn() {
return fakeLogIn;
}
/**
* @param fakeLogIn
* the fakeLogIn to set
*/
public void setFakeLogIn(String fakeLogIn) {
this.fakeLogIn = fakeLogIn;
}
/**
* @return the apiURL
*/
public String getApiURL() {
return apiURL;
}
/**
* @param apiURL
* the apiURL to set
*/
public void setApiURL(String apiURL) {
this.apiURL = apiURL;
}
/**
* @return the reporterAddress
*/
public String getReporterAddress() {
return reporterAddress;
}
/**
* @param reporterAddress
* the reporterAddress to set
*/
public void setReporterAddress(String reporterAddress) {
this.reporterAddress = reporterAddress;
}
/**
* @return the adminAddress
*/
public String getAdminAddress() {
return adminAddress;
}
/**
* @param adminAddress
* the adminAddress to set
*/
public void setAdminAddress(String adminAddress) {
this.adminAddress = adminAddress;
}
/**
* @return the reporterMessageTemplate
*/
public String getReporterMessageTemplate() {
return reporterMessageTemplate;
}
/**
* @param reporterMessageTemplate
* the reporterMessageTemplate to set
*/
public void setReporterMessageTemplate(String reporterMessageTemplate) {
this.reporterMessageTemplate = reporterMessageTemplate;
}
private String getAdminSubject(ConverterMessage msg, String reportSubject) {
if (msg.isUntoleratedError())
return "[CRITICAL-ERROR][" + msg.getmaterialUUID()
+ "] End-products cannot be created.";
else
return reportSubject;
}
private String getAdminContent(ConverterMessage msg, String reportContent) {
String uuidPath = UUIDGenerator.getPathFromUUID(msg.getmaterialUUID());
if (msg.isUntoleratedError())
return StandardMessage.getMailCriticalErrorContent(
msg.getmaterialUUID(), repositoryRoh + archiveWorkspace
+ "/" + uuidPath, repositoryKonv
+ materialWorkspace + "/" + uuidPath);
if (reportContent.equals(""))
return StandardMessage.getMailSuccessfulContent(
msg.getmaterialUUID(), repositoryKonv + materialWorkspace
+ "/" + uuidPath);
else
return StandardMessage.getMailErrorContent(msg.getmaterialUUID(),
repositoryKonv + materialWorkspace + "/" + uuidPath,
reportContent);
}
/**
* main process
*/
@Override
public void processInOut(MessageExchange exchange, NormalizedMessage in,
NormalizedMessage out) {
ConverterMessage msg = new ConverterMessage("reporter-message");
logger.info("Sending report ...");
try {
msg.loadNodeInfo(in);
} catch (Exception e) {
e.printStackTrace();
}
try {
updateDatabase(msg);
} catch (Exception e) {
logger.error("Error by updating database: " + e.getMessage());
}
try {
this.sendReportToAdmin(msg);
this.sendReportToUploader(msg);
} catch (NumberFormatException e) {
logger.error("Error by sending email" + e.getMessage());
} catch (MessagingException e) {
logger.error("Error by sending email" + e.getMessage());
} catch (IOException e) {
logger.error("Template for email cannot be found " + e.getMessage());
}
logger.info("Removing temporary folder ...");
try {
FileUtils.deleteDirectory(new File(msg.getLocalFolder()));
} catch (IOException e) {
e.printStackTrace();
}
msg.setServiceUnit("reporter");
try {
exchange.getMessage("out").setContent(
new DOMSource(msg.getMessage()));
} catch (javax.jbi.messaging.MessagingException e) {
e.printStackTrace();
}
}
/**
* inform the authors that their material is published
* @param msg
* @throws NumberFormatException
* @throws MessagingException
* @throws IOException
*/
private void sendReportToUploader(ConverterMessage msg)
throws NumberFormatException, MessagingException, IOException {
String[] emails = msg.getUploaderEmails().split(";");
if (emails[0].equals("")) {
emails[0] = adminAddress;
}
File xmlTemplateFile = new File(reporterMessageTemplate);
Element mainNode = FileExtractor.importXMLFile(xmlTemplateFile);
RestClient client = new RestClient(fakeLogIn, apiURL);
String materialName = client.queryDB(msg.getmaterialUUID(), "name");
String reportSubject = mainNode.getChildText("subject").replace("[Material_Name]", materialName);
String reportContent = mainNode.getChildText("content").replace("[Material_Name]", materialName);
for (String email : emails)
this.sendMail(
reportSubject,
reportContent.replace("[new_line]", HTML_BREAK),
email);
}
private void sendReportToAdmin(ConverterMessage msg)
throws NumberFormatException, MessagingException {
Report report = new Report();
String subject = "";
String content = "";
try {
report.generateReport(new File(msg.getUploadFolder()),
MaterialType.toMaterialType(msg.getMimeType()),
msg.getmaterialUUID());
} catch (Exception e) {
subject = "[CRITICAL-ERROR][" + msg.getmaterialUUID() + "]";
content = StandardMessage.getMailCriticalErrorContent(
msg.getmaterialUUID(), archiveWorkspace, materialWorkspace);
}
subject = this.getAdminSubject(msg, report.getSubject());
content = this.getAdminContent(msg, report.getContent());
this.sendMail(subject, content, adminAddress);
}
/**
* publish the material after conversion
* @param msg
*/
private void updateDatabase(ConverterMessage msg) {
logger.info("Updating database");
String uuid = msg.getmaterialUUID();
RestClient client = new RestClient(fakeLogIn, apiURL);
client.updateDB(uuid, "open", "true");
if (client.queryDB(uuid, "open").contains("true"))
logger.info("Material is published");
else {
logger.error("Material is not published");
client.updateDB(uuid, "open", "true");
}
client.updateDB(uuid, "characteristic",
MaterialType.getMaterialTypeCode(msg.getMimeType()));
logger.info("Characteristic: "
+ MaterialType.getMaterialTypeCode(msg.getMimeType()));
}
/**
* send email
*
* @param subject
* @param content
* @throws NumberFormatException
* @throws MessagingException
*/
private void sendMail(String subject, String content, String receiverAddress)
throws NumberFormatException, MessagingException {
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", smtpHostName);
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.timeout", "60000");
props.put("mail.smtp.connectiontimeout", "60000");
Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
Address[] address = new InternetAddress[1];
address[0] = new InternetAddress(reporterAddress);
message.addFrom(address);
message.setSubject(subject);
message.setContent(content, "text/html;charset=UTF-8");
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
receiverAddress));
transport.connect(smtpHostName, Integer.parseInt(smtpHostPort),
reporterAddress, "");
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
}
}
|
package com.gmail.filoghost.test;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.plugin.java.JavaPlugin;
import com.gmail.filoghost.holographicdisplays.api.Hologram;
import com.gmail.filoghost.holographicdisplays.api.HologramsAPI;
public class DeathHolograms extends JavaPlugin implements Listener {
public void onEnable() {
if (!Bukkit.getPluginManager().isPluginEnabled("HolographicDisplays")) {
getLogger().severe("*** HolographicDisplays is not installed or not enabled. ***");
getLogger().severe("*** This plugin will be disabled. ***");
this.setEnabled(false);
return;
}
Bukkit.getPluginManager().registerEvents(this, this);
}
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
Hologram hologram = HologramsAPI.createHologram(this, event.getEntity().getEyeLocation());
hologram.appendTextLine(ChatColor.RED + "Player " + ChatColor.GOLD + event.getEntity().getName() + ChatColor.RED + " died here!");
hologram.appendTextLine(ChatColor.GRAY + "Time of death: " + new SimpleDateFormat("H:m").format(new Date()));
}
}
|
import java.io.Serializable;
public class Task implements Serializable {
protected boolean done = false;
protected String status = "[\u2718]";
protected String todo = " ";
protected String icon = "[T]";
//markAsDone
public void markAsDone ( ){
this.done = true;
this.status = "[\u2713]";
}
public Task(String todo) {
this.todo = todo;
}
public String getTodo() {
return todo;
}
public String getStatus() {
return status;
}
public void setTodo(String todo) {
this.todo = todo;
}
public String toString(){
return this.getStatus() + this.icon + " " + this.getTodo();
}
}
|
package com.myxh.developernews.bean;
/**
* Created by asus on 2016/8/6.
*/
public class BaseData {
public boolean error;
public boolean isError() {
return error;
}
public void setError(boolean error) {
this.error = error;
}
}
|
/**
* Created by gudu on 10/20/2015.
*/
public class TestRobotBuilder {
public static void main(String[] args) {
RobotBuilder rb = new OldRobotBuild();
RobotEngineer re = new RobotEngineer(rb);
re.makeRobot();
Robot firstRobot = re.getRobot();
System.out.println("Robot Head Type: " + firstRobot.getRobotHead());
System.out.println("Robot Torso Type: " + firstRobot.getRobotTorso());
System.out.println("Robot Arms Type: " + firstRobot.getRobotArms());
System.out.println("Robot Legs Type: " + firstRobot.getRobotLegs());
}
}
|
/**
* Created by owen on 2017/10/31.
*/
public class ConvertSearchTree {
private TreeNode tail;
private TreeNode head;
public TreeNode Convert(TreeNode pRootOfTree) {
ConvertSub(pRootOfTree);
return head;
}
public void ConvertSub(TreeNode pRootOfTree) {
if (pRootOfTree == null) return;
Convert(pRootOfTree.left);
if (tail != null) {
tail.right = pRootOfTree;
pRootOfTree.left = tail;
tail = pRootOfTree;
} else {
head = pRootOfTree;
tail = pRootOfTree;
}
Convert(pRootOfTree.right);
}
}
|
/*
* 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 textsummarization;
import beans.UserBean;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import services.ManageUserServices;
/**
*
* @author dell1
*/
public class ManageUsers extends javax.swing.JPanel {
/**
* Creates new form ManageUsers
*/
private int addUpdateFlag=-1;
public ManageUsers() {
initComponents();
al = ManageUserServices.getAllRecords();
if (al.size() > 0) {
this.showRecord();
}
}
private ArrayList<UserBean> al = null;
private int count = 0;
private void showRecord() {
System.out.println(al.size());
UserBean objBean = al.get(count);
lblUserId.setText(String.valueOf(objBean.getUserId()));
txtUserName.setText(objBean.getUserName());
txtPassword.setText(objBean.getPassword());
ddlUserType.setSelectedItem(objBean.getUserType());
if (objBean.getUserStatus()) {
rbActive.setSelected(true);
} else {
rbInActive.setSelected(true);
}
if (objBean.getGender()) {
rbMale.setSelected(true);
} else {
rbFemale.setSelected(true);
}
txtName.setText(objBean.getName());
txtContact.setText(objBean.getContact());
txtEmailID.setText(objBean.getEmail());
txtAddress.setText(objBean.getAddress());
txtDOB.setText(objBean.getDob());
btnFirst.setEnabled(true);
btnPrevious.setEnabled(true);
btnLast.setEnabled(true);
btnNext.setEnabled(true);
btnAdd.setEnabled(true);
btnEdit.setEnabled(true);
if (count == 0) {
btnFirst.setEnabled(false);
btnPrevious.setEnabled(false);
} else if (count == (al.size() - 1)) {
btnLast.setEnabled(false);
btnNext.setEnabled(false);
}
enableAll(false);
}
public void enableAll(boolean flag) {
txtUserName.setEditable(flag);
txtPassword.setEditable(flag);
ddlUserType.setEnabled(flag);
rbActive.setEnabled(flag);
rbInActive.setEnabled(flag);
txtName.setEditable(flag);
txtAddress.setEditable(flag);
txtDOB.setEditable(flag);
txtContact.setEditable(flag);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
buttonGroup3 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
lblUserId = new javax.swing.JLabel();
txtPassword = new javax.swing.JTextField();
txtUserName = new javax.swing.JTextField();
rbActive = new javax.swing.JRadioButton();
rbInActive = new javax.swing.JRadioButton();
ddlUserType = new javax.swing.JComboBox<>();
jPanel2 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
txtName = new javax.swing.JTextField();
txtDOB = new javax.swing.JTextField();
txtContact = new javax.swing.JTextField();
txtEmailID = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
txtAddress = new javax.swing.JTextArea();
jLabel11 = new javax.swing.JLabel();
rbMale = new javax.swing.JRadioButton();
rbFemale = new javax.swing.JRadioButton();
btnFirst = new javax.swing.JButton();
btnPrevious = new javax.swing.JButton();
btnNext = new javax.swing.JButton();
btnLast = new javax.swing.JButton();
btnAdd = new javax.swing.JButton();
btnEdit = new javax.swing.JButton();
btnSave = new javax.swing.JButton();
btnCancel = new javax.swing.JButton();
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Official Information"));
jLabel1.setText(" User ID:");
jLabel2.setText("Password:");
jLabel3.setText("User Name:");
jLabel4.setText("User Status:");
jLabel5.setText("User Type:");
txtPassword.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtPasswordActionPerformed(evt);
}
});
buttonGroup2.add(rbActive);
rbActive.setText("Active");
buttonGroup2.add(rbInActive);
rbInActive.setText("Inactive");
ddlUserType.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "User", "Administrator" }));
ddlUserType.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ddlUserTypeActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(44, 44, 44)
.addComponent(lblUserId, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 1, Short.MAX_VALUE)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(rbActive, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(rbInActive, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(155, 155, 155))
.addComponent(ddlUserType, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPassword, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtUserName, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE)))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(11, 11, 11)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(lblUserId, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(11, 11, 11)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(15, 15, 15)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(14, 14, 14)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ddlUserType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(rbActive)
.addComponent(rbInActive))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Personal Information"));
jLabel6.setText("Name:");
jLabel7.setText("DOB:");
jLabel8.setText("Contact:");
jLabel9.setText("Email ID:");
jLabel10.setText("Gender");
txtAddress.setColumns(20);
txtAddress.setRows(5);
jScrollPane1.setViewportView(txtAddress);
jLabel11.setText("Address:");
buttonGroup1.add(rbMale);
rbMale.setText("Male");
buttonGroup1.add(rbFemale);
rbFemale.setText("Female");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtContact))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtEmailID))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(15, 15, 15)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(rbMale)
.addGap(18, 18, 18)
.addComponent(rbFemale)
.addGap(177, 177, 177))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(15, 15, 15)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(txtDOB, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(7, 7, 7)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(7, 7, 7)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtDOB, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtContact, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(11, 11, 11)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtEmailID, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(13, 13, 13)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(rbMale)
.addComponent(rbFemale))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
btnFirst.setText("First");
btnFirst.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFirstActionPerformed(evt);
}
});
btnPrevious.setText("Previous");
btnPrevious.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPreviousActionPerformed(evt);
}
});
btnNext.setText("Next");
btnNext.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnNextActionPerformed(evt);
}
});
btnLast.setText("Last");
btnLast.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLastActionPerformed(evt);
}
});
btnAdd.setText("Add");
btnAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddActionPerformed(evt);
}
});
btnEdit.setText("Edit");
btnEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEditActionPerformed(evt);
}
});
btnSave.setText("Save");
btnSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSaveActionPerformed(evt);
}
});
btnCancel.setText("Cancel");
btnCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnFirst, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnAdd, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(44, 44, 44)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnPrevious, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnEdit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(54, 54, 54)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnSave, javax.swing.GroupLayout.DEFAULT_SIZE, 65, Short.MAX_VALUE)
.addComponent(btnNext, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(51, 51, 51)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnCancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnLast, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap(319, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(5, 5, 5)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnFirst)
.addComponent(btnPrevious)
.addComponent(btnNext)
.addComponent(btnLast))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnAdd)
.addComponent(btnEdit)
.addComponent(btnSave)
.addComponent(btnCancel))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void ddlUserTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ddlUserTypeActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_ddlUserTypeActionPerformed
private void btnFirstActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFirstActionPerformed
count = 0;
showRecord();
// TODO add your handling code here:
}//GEN-LAST:event_btnFirstActionPerformed
private void btnLastActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLastActionPerformed
count = al.size() - 1;
showRecord();
// TODO add your handling code here:
}//GEN-LAST:event_btnLastActionPerformed
private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNextActionPerformed
count++;
showRecord();
// TODO add your handling code here:
}//GEN-LAST:event_btnNextActionPerformed
private void btnPreviousActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPreviousActionPerformed
count--;
showRecord();
// TODO add your handling code here:
}//GEN-LAST:event_btnPreviousActionPerformed
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
btnFirst.setEnabled(false);
btnPrevious.setEnabled(false);
btnLast.setEnabled(false);
btnNext.setEnabled(false);
btnEdit.setEnabled(false);
btnAdd.setEnabled(false);
btnSave.setEnabled(true);
btnCancel.setEnabled(true);
enableAll(true);
lblUserId.setText(String.valueOf(ManageUserServices.getNextId()));
txtUserName.setText("");
txtPassword.setText("");
txtName.setText("");
txtDOB.setText("");
txtContact.setText("");
txtEmailID.setText("");
txtAddress.setText("");
addUpdateFlag=0;
// TODO add your handling code here:
}//GEN-LAST:event_btnAddActionPerformed
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
btnFirst.setEnabled(false);
btnPrevious.setEnabled(false);
btnLast.setEnabled(false);
btnNext.setEnabled(false);
btnEdit.setEnabled(false);
btnAdd.setEnabled(false);
btnSave.setEnabled(true);
btnCancel.setEnabled(true);
enableAll(true);
addUpdateFlag=1;
// TODO add your handling code here:
}//GEN-LAST:event_btnEditActionPerformed
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
if (txtUserName.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "Please Enter username", "Empty Field", JOptionPane.INFORMATION_MESSAGE);
} else if (txtPassword.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "Please Enter password", "Empty Field", JOptionPane.INFORMATION_MESSAGE);
} else if (txtName.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "Please Enter Name", "Empty Field", JOptionPane.INFORMATION_MESSAGE);
} else if (txtContact.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "Please Enter Contact", "Empty Field", JOptionPane.INFORMATION_MESSAGE);
} else if (txtEmailID.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "Please Enter EmailId", "Empty Field", JOptionPane.INFORMATION_MESSAGE);
} else if (txtAddress.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "Please Enter Address", "Empty Field", JOptionPane.INFORMATION_MESSAGE);
} else if (txtDOB.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "Please Enter Date Of Birth", "Empty Field", JOptionPane.INFORMATION_MESSAGE);
} else {
UserBean objbean = new UserBean();
objbean.setUserId(Integer.parseInt(lblUserId.getText()));
objbean.setUserName(txtUserName.getText());
objbean.setPassword(txtPassword.getText());
objbean.setName(txtName.getText());
objbean.setContact(txtContact.getText());
objbean.setEmail(txtEmailID.getText());
objbean.setAddress(txtAddress.getText());
objbean.setDob(txtDOB.getText());
objbean.setUserType(String.valueOf(ddlUserType.getSelectedItem()));
if (rbActive.isSelected()) {
objbean.setUserStatus(true);
} else {
objbean.setUserStatus(false);
}if (rbMale.isSelected()) {
objbean.setGender(true);
} else {
objbean.setGender(false);
}
if(addUpdateFlag==0)
{
ManageUserServices.addRecord(objbean);
}
else if(addUpdateFlag==1)
{
ManageUserServices.UpdateById(objbean);
}
afterSave();
}
}//GEN-LAST:event_btnSaveActionPerformed
public void afterSave()
{
al=ManageUserServices.getAllRecords();
if(addUpdateFlag==0)
{
count=al.size()-1;
showRecord();
}
else if(addUpdateFlag==1)
{
showRecord();
}
addUpdateFlag=-1;
}
private void txtPasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPasswordActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtPasswordActionPerformed
private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
if(addUpdateFlag==0)
{
count=al.size()-1;
showRecord();
}
else if(addUpdateFlag==1)
{
showRecord();
}
else
{
MainFrame.c.setVisible(false);
}
addUpdateFlag=-1;
// TODO add your handling code here:
}//GEN-LAST:event_btnCancelActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAdd;
private javax.swing.JButton btnCancel;
private javax.swing.JButton btnEdit;
private javax.swing.JButton btnFirst;
private javax.swing.JButton btnLast;
private javax.swing.JButton btnNext;
private javax.swing.JButton btnPrevious;
private javax.swing.JButton btnSave;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.ButtonGroup buttonGroup3;
private javax.swing.JComboBox<String> ddlUserType;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lblUserId;
private javax.swing.JRadioButton rbActive;
private javax.swing.JRadioButton rbFemale;
private javax.swing.JRadioButton rbInActive;
private javax.swing.JRadioButton rbMale;
private javax.swing.JTextArea txtAddress;
private javax.swing.JTextField txtContact;
private javax.swing.JTextField txtDOB;
private javax.swing.JTextField txtEmailID;
private javax.swing.JTextField txtName;
private javax.swing.JTextField txtPassword;
private javax.swing.JTextField txtUserName;
// End of variables declaration//GEN-END:variables
}
|
package io.mickeckemi21.controller;
import io.mickeckemi21.model.Person;
import io.swagger.v3.oas.annotations.Hidden;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@Hidden
@RestController
public class PersonController {
@GetMapping("/person")
public Person getPerson() {
return new Person().setName("Nikola").setLastName("Micic");
}
@PostMapping(value = "/person", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public Person postPerson(@RequestBody Person person) {
return new Person().setName("Nikola").setLastName("Micic");
}
}
|
package com.technolearns.services.map;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import com.technolearns.model.Owner;
import com.technolearns.services.OwnerService;
import com.technolearns.services.PetService;
import com.technolearns.services.PetTypeService;
@Service
@Profile({ "default", "map" })
public class OwnerServiceMap extends AbstractMapService<Owner, Long> implements OwnerService {
private PetService petService;
private PetTypeService petTypeService;
public OwnerServiceMap(PetService petService, PetTypeService petTypeService) {
super();
this.petService = petService;
this.petTypeService = petTypeService;
}
@Override
public Owner save(Owner object) {
if (object != null) {
if (object.getPets() != null && !object.getPets().isEmpty()) {
object.getPets().forEach(pet -> {
if (pet.getPetType() != null) {
petTypeService.save(pet.getPetType());
}
petService.save(pet);
});
}
}
return super.save(object);
}
@Override
public Set<Owner> findAll() {
return super.findAll();
}
@Override
public Owner findById(Long id) {
return super.findById(id);
}
@Override
public void delete(Owner object) {
super.delete(object);
}
@Override
public void deleteById(Long id) {
super.deleteById(id);
}
@Override
public List<Owner> findByLastName(String lastName) {
return findAll().stream().filter(owner -> owner.getLastname().equals(lastName)).collect(Collectors.toList());
}
}
|
package solution;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class MaxProduct {
public int maxProduct(TreeNode root) {
return 0;
}
}
|
package com.volvobuses.client.main;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import com.volvobuses.client.service.VolvoBusesService;
public class VolvoBusesScheduledJob extends QuartzJobBean {
private static final Logger logger = LogManager.getLogger(VolvoBusesScheduledJob.class);
private VolvoBusesService volvoBusesService;
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
try {
volvoBusesService.startConectionDynafleeApi();
} catch (Exception e) {
logger.error("Error en ejecutar servicio : ", e);
}
}
public void setVolvoBusesService(VolvoBusesService volvoBusesService) {
this.volvoBusesService = volvoBusesService;
}
}
|
package edu.asu.commons.experiment;
import edu.asu.commons.conf.ConfigurationTest;
import edu.asu.commons.event.ChatRequest;
import edu.asu.commons.event.EventChannel;
import edu.asu.commons.event.EventTypeChannel;
import edu.asu.commons.net.Identifier;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class PersisterTest {
static class MockPersister extends Persister<ConfigurationTest.MockServerConfiguration, ConfigurationTest.MockRoundConfiguration> {
public MockPersister(ConfigurationTest.MockServerConfiguration experimentConfiguration) {
super(experimentConfiguration);
}
@Override
protected String getFailSafeSaveDirectory() {
return "/tmp/mock-persister-test-saves/";
}
}
static class MockDataModel implements DataModel<ConfigurationTest.MockServerConfiguration, ConfigurationTest.MockRoundConfiguration> {
private ConfigurationTest.MockServerConfiguration serverConfiguration;
public MockDataModel(ConfigurationTest.MockServerConfiguration serverConfiguration) {
this.serverConfiguration = serverConfiguration;
}
@Override
public ConfigurationTest.MockServerConfiguration getExperimentConfiguration() {
return serverConfiguration;
}
@Override
public ConfigurationTest.MockRoundConfiguration getRoundConfiguration() {
return null;
}
@Override
public List<Identifier> getAllClientIdentifiers() {
return null;
}
@Override
public EventChannel getEventChannel() {
return EventTypeChannel.getInstance();
}
}
private ConfigurationTest.MockServerConfiguration repeatedRoundConfiguration;
private ConfigurationTest.MockServerConfiguration standardConfiguration;
@Before
public void setUp() {
repeatedRoundConfiguration = ConfigurationTest.createRepeatedRoundConfiguration(10);
standardConfiguration = new ConfigurationTest.MockServerConfiguration();
}
public File getTestSaveFileDirectory() {
return new File(repeatedRoundConfiguration.getPersistenceDirectory());
}
@Test
public void testRepeatedRoundPersister() {
MockDataModel mockDataModel = new MockDataModel(repeatedRoundConfiguration);
MockPersister repeatedRoundPersister = new MockPersister(repeatedRoundConfiguration);
int numberOfMessages = 20;
ConfigurationTest.MockRoundConfiguration firstRound = repeatedRoundConfiguration.getCurrentParameters();
for (int roundNumber = 0; roundNumber < 2; roundNumber++) {
for (int i = 0; i < repeatedRoundConfiguration.getCurrentParameters().getRepeat(); i++) {
for (int j = 0; j < numberOfMessages; j++) {
repeatedRoundPersister.store(new ChatRequest(Identifier.ALL, "message #: " + numberOfMessages));
}
repeatedRoundPersister.persist(mockDataModel);
String roundIndexLabel = roundNumber + "." + i;
assertEquals(repeatedRoundConfiguration.getCurrentRoundLabel(), roundIndexLabel);
String roundSaveFilePath = repeatedRoundPersister.getDefaultRoundSaveFilePath(roundNumber + "." + i);
assertTrue(i + " ASSERT " + roundSaveFilePath + " exists", Files.exists(Paths.get(roundSaveFilePath)));
ConfigurationTest.MockRoundConfiguration nextRound = repeatedRoundConfiguration.nextRound();
repeatedRoundPersister.initialize(nextRound);
}
}
}
}
|
package com.mediafire.sdk.api.responses;
import com.mediafire.sdk.api.responses.data_models.ChangedItems;
public class DeviceGetChangesResponse extends ApiResponse {
private ChangedItems updated;
private ChangedItems deleted;
private long device_revision;
private long changes_list_block;
public long getDeviceRevision() {
return device_revision;
}
public long getChangesListBlock() {
return changes_list_block;
}
public ChangedItems getUpdatedItems() {
return updated;
}
public ChangedItems getDeletedItems() {
return deleted;
}
}
|
package com.stackroute.rohit;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class OccurrenceTwiceOrMore {
public Map<String, Boolean> checkOccurrence(String[] input){
Map<String,Integer> newmap=new HashMap<String, Integer>();
for(String str:input){
Integer n=newmap.get(str);
n=(n==null)?1:++n;
newmap.put(str,n);
}
Map<String,Boolean> wing=new HashMap<String, Boolean>();
for(Map.Entry<String,Integer> entry:newmap.entrySet()){
if(entry.getValue()>=2){
wing.put(entry.getKey(),true);
}
else
wing.put(entry.getKey(),false);
}
return wing;
}
}
|
package com.apon.taalmaatjes.backend.api;
import com.apon.taalmaatjes.backend.api.returns.Result;
import com.apon.taalmaatjes.backend.api.returns.VolunteerInstanceReturn;
import com.apon.taalmaatjes.backend.api.returns.mapper.VolunteerInstanceMapper;
import com.apon.taalmaatjes.backend.database.generated.tables.pojos.VolunteerPojo;
import com.apon.taalmaatjes.backend.database.generated.tables.pojos.VolunteerinstancePojo;
import com.apon.taalmaatjes.backend.database.generated.tables.pojos.VolunteermatchPojo;
import com.apon.taalmaatjes.backend.database.jooq.Context;
import com.apon.taalmaatjes.backend.database.mydao.VolunteerInstanceMyDao;
import com.apon.taalmaatjes.backend.database.mydao.VolunteerMatchMyDao;
import com.apon.taalmaatjes.backend.database.mydao.VolunteerMyDao;
import com.apon.taalmaatjes.backend.log.Log;
import com.apon.taalmaatjes.backend.util.DateTimeUtil;
import com.apon.taalmaatjes.backend.util.ResultUtil;
import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class VolunteerInstanceAPI {
private static VolunteerInstanceAPI ourInstance = new VolunteerInstanceAPI();
public static VolunteerInstanceAPI getInstance() {
return ourInstance;
}
private VolunteerInstanceAPI() { }
private Result result;
/**
* Get a volunteer instance based on the external identifiers.
* @param volunteerExtId The external identifier from the volunteer.
* @param volunteerInstanceExtId The external identifier from the instance.
* @return VolunteerInstanceReturn.
*/
public Result getVolunteerInstance(String volunteerExtId, String volunteerInstanceExtId) {
Context context;
try {context = new Context();} catch (SQLException e) {
return ResultUtil.createError("Context.error.create", e);
}
Log.logDebug("Start VolunteerAPI.getVolunteerInstance for volunteerExtId " + volunteerExtId + " and " + volunteerInstanceExtId);
// Get volunteerId.
VolunteerMyDao volunteerMyDao = new VolunteerMyDao(context);
Integer volunteerId = volunteerMyDao.getIdFromExtId(volunteerExtId);
if (volunteerId == null) {
return ResultUtil.createError("VolunteerInstanceAPI.error.noVolunteerExtIdFound");
}
// Get volunteerInstanceId.
VolunteerInstanceMyDao volunteerInstanceMyDao = new VolunteerInstanceMyDao(context);
Integer volunteerInstanceId = volunteerInstanceMyDao.getIdFromExtId(volunteerId, volunteerInstanceExtId);
if (volunteerInstanceId == null) {
return ResultUtil.createError("VolunteerInstanceAPI.error.noVolunteerInstanceExtIdFound");
}
// Get the volunteerInstancePojo
VolunteerinstancePojo volunteerinstancePojo = volunteerInstanceMyDao.fetchByIds(volunteerId, volunteerInstanceId);
VolunteerInstanceMapper volunteerInstanceMapper = new VolunteerInstanceMapper();
volunteerInstanceMapper.setVolunteerInstance(volunteerinstancePojo);
context.close();
Log.logDebug("End VolunteerAPI.getVolunteerInstance");
return ResultUtil.createOk(volunteerInstanceMapper.getVolunteerInstanceReturn());
}
/**
* Add a new volunteer instance.
* @param volunteerInstanceReturn The instance to addStudent.
* @return Nothing.
*/
public Result addVolunteerInstance(VolunteerInstanceReturn volunteerInstanceReturn) {
if (volunteerInstanceReturn.getDateStart() == null) {
return ResultUtil.createError("VolunteerInstanceAPI.error.fillDateStart");
}
if (volunteerInstanceReturn.getDateEnd() != null &&
volunteerInstanceReturn.getDateStart().compareTo(volunteerInstanceReturn.getDateEnd()) > 0) {
return ResultUtil.createError("VolunteerInstanceAPI.error.dateStartAfterDateEnd");
}
Context context;
try {context = new Context();} catch (SQLException e) {
return ResultUtil.createError("Context.error.create", e);
}
Log.logDebug("Start VolunteerAPI.addVolunteerMatch volunteerExtId " + volunteerInstanceReturn.getVolunteerExtId());
// Get volunteerId.
VolunteerMyDao volunteerMyDao = new VolunteerMyDao(context);
Integer volunteerId = volunteerMyDao.getIdFromExtId(volunteerInstanceReturn.getVolunteerExtId());
if (volunteerId == null) {
return ResultUtil.createError("VolunteerInstanceAPI.error.noVolunteerExtIdFound");
}
// Handle the complete adding / merging in another function.
if (!isVolunteerInstanceValidAndAdd(context, volunteerId, volunteerInstanceReturn.getDateStart(), volunteerInstanceReturn.getDateEnd(), null)) {
context.rollback();
return result;
}
// Commit, close and return.
try {
context.getConnection().commit();
} catch (SQLException e) {
return ResultUtil.createError("Context.error.commit", e);
}
context.close();
Log.logDebug("End VolunteerAPI.toggleMatch");
return ResultUtil.createOk();
}
/**
* Edit an existing volunteer instance.
* @param volunteerInstanceReturn The updated instance.
* @return Nothing.
*/
public Result updateVolunteerInstance(VolunteerInstanceReturn volunteerInstanceReturn) {
if (volunteerInstanceReturn.getDateStart() == null) {
return ResultUtil.createError("VolunteerInstanceAPI.error.fillDateStart");
}
if (volunteerInstanceReturn.getDateEnd() != null &&
volunteerInstanceReturn.getDateStart().compareTo(volunteerInstanceReturn.getDateEnd()) > 0) {
return ResultUtil.createError("VolunteerInstanceAPI.error.dateStartAfterDateEnd");
}
if (volunteerInstanceReturn.getVolunteerExtId() == null) {
return ResultUtil.createError("VolunteerInstanceAPI.error.fillVolunteerExtId");
}
if (volunteerInstanceReturn.getExternalIdentifier() == null) {
return ResultUtil.createError("VolunteerInstanceAPI.error.fillVolunteerInstanceExtId");
}
Context context;
try {context = new Context();} catch (SQLException e) {
return ResultUtil.createError("Context.error.create", e);
}
Log.logDebug("Start VolunteerAPI.updateVolunteerInstance volunteerExtId " + volunteerInstanceReturn.getVolunteerExtId());
// Get volunteerId.
VolunteerMyDao volunteerMyDao = new VolunteerMyDao(context);
Integer volunteerId = volunteerMyDao.getIdFromExtId(volunteerInstanceReturn.getVolunteerExtId());
if (volunteerId == null) {
return ResultUtil.createError("VolunteerInstanceAPI.error.noVolunteerExtIdFound");
}
// Get volunteerInstanceId
VolunteerInstanceMyDao volunteerInstanceMyDao = new VolunteerInstanceMyDao(context);
Integer volunteerInstanceId = volunteerInstanceMyDao.getIdFromExtId(volunteerId, volunteerInstanceReturn.getExternalIdentifier());
if (volunteerInstanceId == null) {
return ResultUtil.createError("VolunteerInstanceAPI.error.noVolunteerInstanceExtIdFound.");
}
// Handle the complete adding / merging in another function.
if (!isVolunteerInstanceValidAndAdd(context, volunteerId, volunteerInstanceReturn.getDateStart(), volunteerInstanceReturn.getDateEnd(), volunteerInstanceId)) {
context.rollback();
return result;
}
// Commit, close and return.
try {
context.getConnection().commit();
} catch (SQLException e) {
return ResultUtil.createError("Context.error.commit", e);
}
context.close();
Log.logDebug("End VolunteerAPI.updateVolunteerInstance");
return ResultUtil.createOk();
}
/**
* Check if the line can be added to the database. Merge the line if needed. Returns true if added (possibly merged)
* and return false if some verification failed.
* @param context .
* @param volunteerId .
* @param dateStart .
* @param dateEnd .
* @param volunteerInstanceId If this value is non-null, algorithm assumes it is an updateVolunteer instead of insert.
* @return boolean
*/
private boolean isVolunteerInstanceValidAndAdd(Context context, int volunteerId, Date dateStart, Date dateEnd, Integer volunteerInstanceId) {
VolunteerInstanceMyDao volunteerInstanceMyDao = new VolunteerInstanceMyDao(context);
// if [A,B] can be merged into [dateStart,dateEnd] with B=dateStart then mergeAfterVolunteerInstanceId will be B.
Integer mergeAfterVolunteerInstanceId = null;
// if [dateStart,dateEnd] can be merged into [A,B] with A=dateEnd then mergeAfterVolunteerInstanceId will be A.
Integer mergeBeforeVolunteerInstanceId = null;
for (VolunteerinstancePojo volunteerinstancePojo : volunteerInstanceMyDao.getInstanceForVolunteer(volunteerId)) {
// If we updateVolunteer instead of insert, we want to 'exclude' the to-be-updated volunteerinstance from the search.
if (volunteerInstanceId != null && volunteerinstancePojo.getVolunteerinstanceid().equals(volunteerInstanceId)) {
continue;
}
// If one of the following hold, return false:
// 1. dateStart is contained in (pojo.dateStart, pojo.dateEnd)
// 2. dateEnd is contained in (pojo.dateStart, pojo.dateEnd)
// 3. Range [pojo.dateStart, pojo.dateEnd] is contained within (dateStart, dateEnd).
// However, the above does not hold at all whenever pojo.dateStart = pojo.dateEnd (one day instance).
// So we only threat this case differently.
if (volunteerinstancePojo.getDateend() != null &&
volunteerinstancePojo.getDatestart().compareTo(volunteerinstancePojo.getDateend()) == 0) {
// We have 4 possibilities:
// 1. pojo.date \in (dateStart, dateEnd) => overlap so false.
// 2. pojo.date == dateStart || pojo.date + 1 DAY = dateStart => merge
// 3. pojo.date == dateEnd || pojo.date + 1 DAY = dateEnd => merge
// 4. none of the above => we do nothing, we can ignore this line.
if (DateTimeUtil.isBetweenWithoutEndpoints(volunteerinstancePojo.getDatestart(), dateStart, dateEnd)) {
result = ResultUtil.createError("VolunteerInstanceAPI.error.overlap");
return false;
}
// Merge before
if (volunteerinstancePojo.getDateend().compareTo(dateStart) == 0 ||
DateTimeUtil.nrOfDaysInBetween(volunteerinstancePojo.getDateend(), dateStart) == 1) {
mergeBeforeVolunteerInstanceId = volunteerinstancePojo.getVolunteerinstanceid();
}
// Merge after
if (dateEnd != null && (volunteerinstancePojo.getDatestart().compareTo(dateEnd) == 0 ||
DateTimeUtil.nrOfDaysInBetween(dateEnd, volunteerinstancePojo.getDatestart()) == 1)) {
mergeAfterVolunteerInstanceId = volunteerinstancePojo.getVolunteerinstanceid();
}
// In any case we can just go on searching.
continue;
}
if (DateTimeUtil.isBetweenWithoutEndpoints(dateStart,
volunteerinstancePojo.getDatestart(), volunteerinstancePojo.getDateend())) {
result = ResultUtil.createError("VolunteerInstanceAPI.error.overlap");
return false;
}
if (DateTimeUtil.isBetweenWithoutEndpoints(dateEnd,
volunteerinstancePojo.getDatestart(), volunteerinstancePojo.getDateend())) {
result = ResultUtil.createError("VolunteerInstanceAPI.error.overlap");
return false;
}
if (DateTimeUtil.isContained(volunteerinstancePojo.getDatestart(), volunteerinstancePojo.getDateend(),
dateStart, dateEnd)) {
result = ResultUtil.createError("VolunteerInstanceAPI.error.completeOverlap");
return false;
}
// Determine whether we can actually merge with this line.
// Merge after: (note that if both dates are null, we can never merge.
if (dateEnd != null && volunteerinstancePojo.getDatestart() != null &&
(volunteerinstancePojo.getDatestart().compareTo(dateEnd) == 0 ||
DateTimeUtil.nrOfDaysInBetween(dateEnd, volunteerinstancePojo.getDatestart()) == 1)) {
mergeAfterVolunteerInstanceId = volunteerinstancePojo.getVolunteerinstanceid();
}
// Merge before: (note that dateEnd must be non-null to merge. Also dateStart is never null).
if (volunteerinstancePojo.getDateend() != null &&
(volunteerinstancePojo.getDateend().compareTo(dateStart) == 0 ||
DateTimeUtil.nrOfDaysInBetween(volunteerinstancePojo.getDateend(), dateStart) == 1)) {
mergeBeforeVolunteerInstanceId = volunteerinstancePojo.getVolunteerinstanceid();
}
}
// If we actually reach this point, we know the line will be added to the database (merged or not).
VolunteerinstancePojo volunteerinstancePojo = new VolunteerinstancePojo();
volunteerinstancePojo.setVolunteerid(volunteerId);
// Merge after if possible.
if (mergeAfterVolunteerInstanceId != null) {
VolunteerinstancePojo mergedVolunteerinstancePojo = volunteerInstanceMyDao.fetchByIds(volunteerId, mergeAfterVolunteerInstanceId);
volunteerinstancePojo.setDateend(mergedVolunteerinstancePojo.getDateend());
volunteerInstanceMyDao.delete(mergedVolunteerinstancePojo);
} else {
// Date start must still be set.
volunteerinstancePojo.setDateend(dateEnd);
}
// Merge before if possible.
if (mergeBeforeVolunteerInstanceId != null) {
VolunteerinstancePojo mergedVolunteerinstancePojo = volunteerInstanceMyDao.fetchByIds(volunteerId, mergeBeforeVolunteerInstanceId);
volunteerinstancePojo.setDatestart(mergedVolunteerinstancePojo.getDatestart());
volunteerInstanceMyDao.delete(mergedVolunteerinstancePojo);
} else {
// Date start must still be set.
volunteerinstancePojo.setDatestart(dateStart);
}
if (volunteerInstanceId == null) {
volunteerInstanceMyDao.insertPojo(volunteerinstancePojo);
} else {
volunteerinstancePojo.setVolunteerinstanceid(volunteerInstanceId);
// Check that we can actually updateStudent.
List<Integer> merged = new ArrayList();
if (mergeAfterVolunteerInstanceId != null) {
merged.add(mergeAfterVolunteerInstanceId);
}
if (mergeBeforeVolunteerInstanceId != null) {
merged.add(mergeBeforeVolunteerInstanceId);
}
if (!allMatchesAreInsideInstance(context, volunteerinstancePojo, merged)) {
result = ResultUtil.createError("VolunteerInstanceAPI.error.matchWithoutInstance");
return false;
}
volunteerInstanceMyDao.update(volunteerinstancePojo);
}
return true;
}
/**
* Check if all the matches are still inside instances when we edit this instance.
* @param context .
* @param volunteerinstancePojo The new pojo.
* @return boolean
*/
private boolean allMatchesAreInsideInstance(Context context, VolunteerinstancePojo volunteerinstancePojo, List<Integer> removeInstanceIds) {
VolunteerMatchMyDao volunteerMatchMyDao = new VolunteerMatchMyDao(context);
VolunteerInstanceMyDao volunteerInstanceMyDao = new VolunteerInstanceMyDao(context);
List<VolunteerinstancePojo> volunteerinstancePojos = volunteerInstanceMyDao.getInstanceForVolunteer(volunteerinstancePojo.getVolunteerid());
// Remove the merged from the list.
List<VolunteerinstancePojo> removePojos = new ArrayList();
// Also remove the current pojo we are going to updateStudent, since we are going to "overwrite" this one.
removeInstanceIds.add(volunteerinstancePojo.getVolunteerinstanceid());
for (VolunteerinstancePojo v : volunteerinstancePojos) {
for (Integer i : removeInstanceIds) {
if (v.getVolunteerinstanceid().equals(i)) {
removePojos.add(v);
}
}
}
for (VolunteerinstancePojo v : removePojos) {
volunteerinstancePojos.remove(v);
}
volunteerinstancePojos.add(volunteerinstancePojo);
// Just check that all the matches are completely inside any pojo.
for (VolunteermatchPojo volunteermatchPojo : volunteerMatchMyDao.getMatchForVolunteer(volunteerinstancePojo.getVolunteerid())) {
if (!isMatchCompletelyInsideInstance(volunteermatchPojo, volunteerinstancePojos)) {
// There is a match that does not fit completely inside an instance. Therefore we cannot edit.
return false;
}
}
return true;
}
private boolean isMatchCompletelyInsideInstance(VolunteermatchPojo volunteermatchPojo, List<VolunteerinstancePojo> list) {
for (VolunteerinstancePojo v : list) {
if (DateTimeUtil.isContained(volunteermatchPojo.getDatestart(), volunteermatchPojo.getDateend(),
v.getDatestart(), v.getDateend())) {
return true;
}
}
return false;
}
private boolean isMatchCompletelyInsideInstance(VolunteermatchPojo volunteermatchPojo, VolunteerinstancePojo volunteerinstancePojo) {
List<VolunteerinstancePojo> volunteerInstancePojos = new ArrayList();
volunteerInstancePojos.add(volunteerinstancePojo);
return isMatchCompletelyInsideInstance(volunteermatchPojo, volunteerInstancePojos);
}
/**
* Delete instance from the database. Checks if there are no matches inside the instance.
* @param volunteerInstanceReturn The instance to delete.
* @return Nothing.
*/
public Result deleteVolunteerInstance(VolunteerInstanceReturn volunteerInstanceReturn) {
if (volunteerInstanceReturn.getVolunteerExtId() == null) {
return ResultUtil.createError("VolunteerInstanceAPI.error.fillVolunteerExtId");
}
if (volunteerInstanceReturn.getExternalIdentifier() == null) {
return ResultUtil.createError("VolunteerInstanceAPI.error.fillVolunteerInstanceExtId");
}
Context context;
try {context = new Context();} catch (SQLException e) {
return ResultUtil.createError("Context.error.create", e);
}
Log.logDebug("Start VolunteerAPI.deleteVolunteerInstance volunteerExtId " + volunteerInstanceReturn.getVolunteerExtId()
+ " volunteerInstanceExtId " + volunteerInstanceReturn.getExternalIdentifier());
// Get volunteerId.
VolunteerMyDao volunteerMyDao = new VolunteerMyDao(context);
Integer volunteerId = volunteerMyDao.getIdFromExtId(volunteerInstanceReturn.getVolunteerExtId());
if (volunteerId == null) {
return ResultUtil.createError("VolunteerInstanceAPI.error.noVolunteerExtIdFound");
}
// Get volunteerInstanceId
VolunteerInstanceMyDao volunteerInstanceMyDao = new VolunteerInstanceMyDao(context);
Integer volunteerInstanceId = volunteerInstanceMyDao.getIdFromExtId(volunteerId, volunteerInstanceReturn.getExternalIdentifier());
if (volunteerInstanceId == null) {
return ResultUtil.createError("VolunteerInstanceAPI.error.noVolunteerInstanceExtIdFound.");
}
VolunteerinstancePojo volunteerinstancePojo = volunteerInstanceMyDao.fetchByIds(volunteerId, volunteerInstanceId);
// Check that there are no matches contained inside the instance.
VolunteerMatchMyDao volunteerMatchMyDao = new VolunteerMatchMyDao(context);
for (VolunteermatchPojo volunteermatchPojo : volunteerMatchMyDao.getMatchForVolunteer(volunteerId)) {
if (isMatchCompletelyInsideInstance(volunteermatchPojo, volunteerinstancePojo)) {
// This match would fall outside of activity range, hence we cannot delete the instance.
return ResultUtil.createError("VolunteerInstanceAPI.error.matchWithoutInstance");
}
}
// Delete the instance.
volunteerInstanceMyDao.delete(volunteerinstancePojo);
// Commit, close and return.
try {
context.getConnection().commit();
} catch (SQLException e) {
return ResultUtil.createError("Context.error.commit", e);
}
context.close();
Log.logDebug("End VolunteerAPI.updateVolunteerInstance");
return ResultUtil.createOk();
}
}
|
package modul.systemu.asi.frontend.model;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "priority")
public class Priority {
@Id
@Column(unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "priority")
private List<Task> tasks = new ArrayList<Task>();
@OneToMany(mappedBy = "previousPriority")
private List<TaskHistory> taskHistoriesPreviousPriority = new ArrayList<TaskHistory>();
@OneToMany(mappedBy = "newPriority")
private List<TaskHistory> taskHistoriesNewPriority = new ArrayList<TaskHistory>();
public Priority(){
super();
}
public Priority(long id, String name){
super();
this.id = id;
this.name = name;
}
public List<TaskHistory> getTaskHistoriesPreviousPriority() {
return taskHistoriesPreviousPriority;
}
public void setTaskHistoriesPreviousPriority(List<TaskHistory> taskHistoriesPreviousPriority) {
this.taskHistoriesPreviousPriority = taskHistoriesPreviousPriority;
}
public List<TaskHistory> getTaskHistoriesNewPriority() {
return taskHistoriesNewPriority;
}
public void setTaskHistoriesNewPriority(List<TaskHistory> taskHistoriesNewPriority) {
this.taskHistoriesNewPriority = taskHistoriesNewPriority;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
/**
* Copyright (C) 2014-2017 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.commons.io.monitor;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.ReturnsMutableCopy;
import com.helger.commons.collection.ext.CommonsArrayList;
import com.helger.commons.collection.ext.ICommonsList;
import com.helger.commons.concurrent.SimpleReadWriteLock;
import com.helger.commons.concurrent.ThreadHelper;
import com.helger.commons.state.EChange;
import com.helger.commons.timing.StopWatch;
/**
* This class manages all the available {@link FileMonitor} objects.
*
* @author Philip Helger
*/
public class FileMonitorManager implements Runnable
{
public static final long DEFAULT_DELAY = 1000;
public static final int DEFAULT_MAX_FILES = 1000;
private static final Logger s_aLogger = LoggerFactory.getLogger (FileMonitorManager.class);
private final SimpleReadWriteLock m_aRWLock = new SimpleReadWriteLock ();
/** All FileMonitors contained */
private final ICommonsList <FileMonitor> m_aMonitorList = new CommonsArrayList<> ();
/** The low priority thread used for checking the files being monitored. */
private Thread m_aMonitorThread;
/**
* A flag used to determine if the monitor thread should be running. used for
* inter-thread communication
*/
private volatile boolean m_bShouldRun = true;
/** Set the delay between checks in milli seconds. */
private long m_nDelay = DEFAULT_DELAY;
/** Set the number of files to check until a delay will be inserted */
private int m_nChecksPerRun = DEFAULT_MAX_FILES;
public FileMonitorManager ()
{}
/**
* Get the delay between runs.
*
* @return The delay period in milliseconds.
*/
public long getDelay ()
{
return m_nDelay;
}
/**
* Set the delay between runs.
*
* @param nDelay
* The delay period in milliseconds.
* @return this
*/
@Nonnull
public FileMonitorManager setDelay (final long nDelay)
{
m_nDelay = nDelay > 0 ? nDelay : DEFAULT_DELAY;
return this;
}
/**
* get the number of files to check per run.
*
* @return The number of files to check per iteration.
*/
public int getChecksPerRun ()
{
return m_nChecksPerRun;
}
/**
* set the number of files to check per run. a additional delay will be added
* if there are more files to check
*
* @param nChecksPerRun
* a value less than 1 will disable this feature
* @return this
*/
@Nonnull
public FileMonitorManager setChecksPerRun (final int nChecksPerRun)
{
m_nChecksPerRun = nChecksPerRun;
return this;
}
/**
* Create a new {@link FileMonitor} based on the passed file listener.
*
* @param aListener
* The listener to be used. May not be <code>null</code>.
* @return The created {@link FileMonitor} that was already added.
* @see #addFileMonitor(FileMonitor)
*/
@Nonnull
public FileMonitor createFileMonitor (@Nonnull final IFileMonitorCallback aListener)
{
final FileMonitor aMonitor = new FileMonitor (aListener);
addFileMonitor (aMonitor);
return aMonitor;
}
/**
* Add a new {@link FileMonitor}.
*
* @param aMonitor
* The monitor to be added. May not be <code>null</code>.
* @return {@link EChange}
*/
@Nonnull
public EChange addFileMonitor (@Nonnull final FileMonitor aMonitor)
{
ValueEnforcer.notNull (aMonitor, "Monitor");
return m_aRWLock.writeLocked ( () -> m_aMonitorList.addObject (aMonitor));
}
/**
* Remove a {@link FileMonitor}.
*
* @param aMonitor
* The monitor to be remove. May be <code>null</code>.
* @return {@link EChange}
*/
@Nonnull
public EChange removeFileMonitor (@Nullable final FileMonitor aMonitor)
{
if (aMonitor == null)
return EChange.UNCHANGED;
return m_aRWLock.writeLocked ( () -> m_aMonitorList.removeObject (aMonitor));
}
@Nonnull
@ReturnsMutableCopy
public ICommonsList <FileMonitor> getAllFileMonitors ()
{
return m_aRWLock.readLocked ( () -> m_aMonitorList.getClone ());
}
/**
* @return The number of contained {@link FileMonitor} objects. Always ≥ 0.
*/
@Nonnegative
public int getFileMonitorCount ()
{
return m_aRWLock.readLocked ( () -> m_aMonitorList.size ());
}
/**
* Starts monitoring the files
*
* @throws IllegalStateException
* if the monitoring is already running
* @see #isRunning()
* @see #stop()
*/
public void start ()
{
if (m_aMonitorThread != null || !m_bShouldRun)
throw new IllegalStateException ("Thread is already running!");
m_aMonitorThread = new Thread (this, "ph-FileMonitor");
m_aMonitorThread.setDaemon (true);
m_aMonitorThread.setPriority (Thread.MIN_PRIORITY);
m_aMonitorThread.start ();
s_aLogger.info ("Started FileMonitor thread");
}
/**
* Stops monitoring the files.
*/
public void stop ()
{
if (m_aMonitorThread != null)
{
m_bShouldRun = false;
// A thread should never be restarted
m_aMonitorThread = null;
s_aLogger.info ("Stopped FileMonitor thread");
}
}
/**
* @return <code>true</code> if the monitoring thread is running,
* <code>false</code> if not.
*/
public boolean isRunning ()
{
return m_aMonitorThread != null && m_bShouldRun;
}
/**
* Asks the agent for each file being monitored to check its file for changes.
*/
public void run ()
{
mainloop: while (m_aMonitorThread != null && !m_aMonitorThread.isInterrupted () && m_bShouldRun)
{
final StopWatch aSW = StopWatch.createdStarted ();
// Create a copy to avoid concurrent modification
int nFileNameIndex = 0;
for (final FileMonitor aMonitor : getAllFileMonitors ())
{
// Remove listener for all deleted files
aMonitor.applyPendingDeletes ();
// For all monitored files
for (final FileMonitorAgent aAgent : aMonitor.getAllAgents ())
{
aAgent.checkForModifications ();
final int nChecksPerRun = getChecksPerRun ();
if (nChecksPerRun > 0 && (nFileNameIndex % nChecksPerRun) == 0)
ThreadHelper.sleep (getDelay ());
if (m_aMonitorThread == null || m_aMonitorThread.isInterrupted () || !m_bShouldRun)
break mainloop;
++nFileNameIndex;
}
// Add listener for all added files
aMonitor.applyPendingAdds ();
}
// Wait some time
ThreadHelper.sleep (getDelay ());
if (s_aLogger.isDebugEnabled ())
s_aLogger.debug ("Checking for file modifications took " + aSW.stopAndGetMillis () + " ms");
}
// Allow for restart
m_bShouldRun = true;
}
}
|
package com.xbang.bootdemo.annotation;
import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;
@Target({ElementType.METHOD})
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface LimitConfig {
//单位时间内允许访问的次数 默认是5
int value() default 5;
//单位时间 默认是1
long time() default 1;
//单位时间的单位 默认是秒
TimeUnit unit() default TimeUnit.SECONDS;
//默认每秒钟可以请求5次
}
|
package test.java;
import java.util.ArrayList;
import java.awt.Dimension;
import java.awt.Component;
import main.java.gui.GamePanel;
import main.java.gui.PiecePanel;
import main.java.gui.CellPanel;
import main.java.gui.StockPanel;
import main.java.gui.interaction.DragTarget;
import main.java.gui.interaction.DropTarget;
import main.java.model.Piece;
import main.java.model.Face;
import static org.junit.Assert.*;
import org.junit.Test;
public class GamePanelTest {
@Test
public void piecePanelTests() {
Face f0 = new Face(0, "", "", "");
Face f1 = new Face(1, "blue", "white", "zigzag");
Face f2 = new Face(2, "purple", "red", "circle");
Face f3 = new Face(3, "green", "blue", "triangle");
Face f4 = new Face(4, "red", "yellow", "line");
Piece p0 = new Piece(0, new Face[]{f0, f3, f3, f0}, 0, 0, 0);
Piece p1 = new Piece(1, new Face[]{f0, f2, f4, f3}, 1, 0, 0);
Piece p2 = new Piece(2, new Face[]{f0, f4, f4, f2}, 2, 0, 0);
Piece p3 = new Piece(3, new Face[]{f0, f0, f3, f4}, 3, 0, 0);
Piece p4 = new Piece(4, new Face[]{f3, f1, f3, f0}, 0, 1, 0);
Piece p5 = new Piece(5, new Face[]{f4, f3, f1, f1}, 1, 1, 0);
Piece p6 = new Piece(6, new Face[]{f4, f1, f2, f3}, 2, 1, 0);
Piece p7 = new Piece(7, new Face[]{f3, f0, f2, f1}, 3, 1, 0);
Piece p8 = new Piece(8, new Face[]{f3, f4, f4, f0}, 0, 2, 0);
Piece p9 = new Piece(9, new Face[]{f1, f3, f1, f4}, 1, 2, 0);
Piece p10 = new Piece(10, new Face[]{f2, f1, f4, f3}, 2, 2, 0);
Piece p11 = new Piece(11, new Face[]{f2, f0, f2, f1}, 3, 2, 0);
Piece p12 = new Piece(12, new Face[]{f4, f3, f0, f0}, 0, 3, 0);
Piece p13 = new Piece(13, new Face[]{f1, f2, f0, f3}, 1, 3, 0);
Piece p14 = new Piece(14, new Face[]{f4, f4, f0, f2}, 2, 3, 0);
Piece p15 = new Piece(15, new Face[]{f2, f0, f0, f4}, 3, 3, 0);
Piece[] pieces = {p15, p14, p13, p12, p11, p10, p9, p8, p7, p6, p5, p4, p3, p2, p1, p0};
GamePanel gp = new GamePanel();
ArrayList<DragTarget> dragTargets = gp.getDragTargets();
ArrayList<DropTarget> dropTargets = gp.getDropTargets();
assertTrue(dragTargets != null);
assertTrue(dropTargets != null);
assertTrue(dragTargets.size() == 0);
assertTrue(dropTargets.size() == 0);
gp.createGrid(16);
assertTrue(dropTargets.size() == 17);
for (int i = 0; i < 16; i++) {
assertTrue(dropTargets.get(i) instanceof CellPanel);
}
assertTrue(dropTargets.get(16) instanceof StockPanel);
gp.createPiecePanels(pieces);
assertTrue(dragTargets.size() == 16);
assertTrue(this.countPiecePanelsInPlay(dropTargets) == 16);
for (DragTarget dt : dragTargets) {
PiecePanel pp = (PiecePanel)dt;
assertTrue(pp.getPiece() != null);
assertTrue(pp.getImage() != null);
}
}
private int countPiecePanelsInPlay(ArrayList<DropTarget> dropTargets) {
int dragTargetsCountInPlay = 0;
for (DropTarget dt : dropTargets) {
Component[] childs = dt.getComponents();
if (dt.acceptMultipleChilds()) {
for (Component comp : childs)
if (comp instanceof PiecePanel) dragTargetsCountInPlay++;
} else {
if (childs.length == 1 && childs[0] instanceof PiecePanel)
dragTargetsCountInPlay += 1;
}
}
return dragTargetsCountInPlay;
}
}
|
package com.github.riyaz.bakingapp.screens.recipes;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import android.util.Log;
import com.github.riyaz.bakingapp.model.Recipe;
import com.github.riyaz.bakingapp.net.RecipeService;
import java.util.List;
import javax.inject.Inject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* {@link ViewModel} class for the {@link RecipeListActivity}
*
* @author Riyaz
*/
public class RecipeListViewModel extends ViewModel implements Callback<List<Recipe>>{
// Log TAG
private static final String TAG = RecipeListViewModel.class.getSimpleName();
// recipes stream
public final MutableLiveData<List<Recipe>> recipes = new MutableLiveData<>();
// idling resource
private final RecipeListIdlingResource idlingResource;
@Inject RecipeListViewModel(RecipeService service, RecipeListIdlingResource idlingResource){
// start fetching the recipes right away
this.idlingResource = idlingResource;
this.idlingResource.setIdle(false);
service.recipes().enqueue(this);
}
@Override public void onResponse(Call<List<Recipe>> call, Response<List<Recipe>> response) {
idlingResource.setIdle(true);
if(response.isSuccessful()){
List<Recipe> _recipes = response.body();
if(null != _recipes)
recipes.setValue(_recipes);
}
}
@Override public void onFailure(Call<List<Recipe>> call, Throwable t) {
Log.e(TAG, "Failed to fetch recipes", t);
}
}
|
/*
* Copyright (c) 2016, Innovaciones Tecnologicas
* All rights reserved.
*
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
*/
package com.innovaciones.reporte.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class CharacterEncodingFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
chain.doFilter(req, resp);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
public void destroy() {
}
}
|
package code.menu;
public class Default{
//TODO Labyrinthe z.B. "0-1_0-2_1-3_5-6_5-4_2-3_0-1"
public static final String L1 = "0-1_1-3_0-2_1-2";
public static final String L2 = "0-1_0-2_0-12_2-3_3-4_4-5_4-8_5-6_6-7_8-9_8-10_10-11_11-12";
public static final String L3 = "0-1_0-2_0-6_2-3_3-4_4-5_5-6_7-8_8-9_9-10_10-11_11-12";
public static final String L4 = "1-2_1-6_2-3_3-8_3-9_3-4_4-5_4-13_5-12_5-6_6-8_7-12_7-11_8-9_9-10_10-11_13-14_14-15_14-16";
public static final String L5 = "1-2_1-3_3-4_4-5_4-6_4-10_5-6_6-7_7-8_8-9_9-10_9-11_9-12_10-11_11-16_12-13_12-17_13-14_14-15_15-16_17-18";
}
|
package org.softRoad.services;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import org.softRoad.exception.ForbiddenException;
import org.softRoad.exception.InternalException;
import org.softRoad.exception.InvalidDataException;
import org.softRoad.models.AuditLog;
import org.softRoad.models.AuditLog.Action;
import org.softRoad.models.SoftRoadModel;
import org.softRoad.models.query.HqlQuery;
import org.softRoad.models.query.QueryUtils;
import org.softRoad.models.query.SearchCriteria;
import org.softRoad.security.AccessControlManager;
import org.softRoad.security.Permission;
import org.softRoad.utils.ModelUtils;
import javax.inject.Inject;
import javax.persistence.Column;
import javax.persistence.EntityManager;
import javax.persistence.JoinColumn;
import javax.persistence.Query;
import javax.transaction.Transactional;
import javax.ws.rs.core.Response;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class CrudService<T extends SoftRoadModel> {
private final Class<?> objClass;
@Inject
EntityManager entityManager;
@Inject
protected AccessControlManager acm;
@Inject
ObjectMapper mapper;
public CrudService(Class<?> objClass) {
this.objClass = objClass;
}
@Transactional
private void log(Action type, T obj) {
AuditLog log = new AuditLog();
log.user = acm.getCurrentUser();
log.action = type;
log.objectId = ModelUtils.getPrimaryKeyValue(obj, objClass);
log.objectType = objClass.getName();
try {
log.payload = mapper.writeValueAsString(convert(obj));
} catch (JsonProcessingException ex) {
throw new InternalException(ex);
}
AuditLog.persist(log);
}
protected void checkPermission(PermissionType type) {
checkState(hasPermission(type));
}
protected boolean hasPermission(PermissionType type) {
return acm.hasPermission(Permission.valueOf(type.name() + "_" + objClass.getSimpleName().toUpperCase()));
}
protected void checkState(boolean b) {
if (!b)
throw new ForbiddenException("Permission denied");
}
private Map<String, String> convert(T obj) {
Map<String, String> map = new HashMap<>();
obj.presentFields.forEach(fieldName -> {
Object columnValue = ModelUtils.getColumnValue(obj, obj.getClass(), fieldName);
map.put(fieldName, (columnValue == null ? null : columnValue.toString()));
});
return map;
}
@Transactional
public Response create(T obj) {
checkPermission(PermissionType.CREATE);
obj.persist();
log(Action.CREATE, obj);
return Response.status(Response.Status.CREATED).build();
}
@Transactional
public T get(Integer id) {
checkPermission(PermissionType.READ);
Optional first = entityManager.createNativeQuery(
String.format("select * from %s where id=:id", ModelUtils.getTableName(objClass), objClass), objClass)
.setParameter("id", id).getResultStream().findFirst();
if (first.isEmpty())
throw new InvalidDataException("Invalid id");
return (T) first.get();
}
@Transactional
public Response update(T obj) {
checkPermission(PermissionType.UPDATE);
HashMap<String, Object> params = new HashMap<>();
StringBuilder queryBuilder = new StringBuilder();
String table = ModelUtils.getTableName(obj.getClass());
queryBuilder.append("update ").append(table).append(" set ");
Integer pk = ModelUtils.getPrimaryKeyValue(obj, obj.getClass());
String pkName = ModelUtils.getPrimaryKeyField(obj, obj.getClass()).getName();
T oldObj = get(pk);
if (oldObj == null)
throw new InvalidDataException("Invalid id");
int ind = 0;
for (String fieldName : obj.presentFields) {
try {
Field field = obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Column column = field.getAnnotation(Column.class);
JoinColumn joinColumn = field.getAnnotation(JoinColumn.class);
String columnName = joinColumn != null ? joinColumn.name()
: column == null || Strings.isNullOrEmpty(column.name()) ? fieldName : column.name();
Object value = field.get(obj);
if (joinColumn != null)
value = ModelUtils.getPrimaryKeyValue(value, value.getClass());
params.put(columnName, value);
if (!columnName.equals(pkName)) {
if (ind > 0)
queryBuilder.append(", ");
ind++;
queryBuilder.append(columnName).append("=:").append(columnName);
}
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new InvalidDataException(e.getMessage());
}
}
queryBuilder.append(" where ").append(pkName).append("=:").append(pkName);
Query nativeQuery = entityManager.createNativeQuery(queryBuilder.toString());
params.keySet().forEach(key -> nativeQuery.setParameter(key, params.get(key)));
nativeQuery.executeUpdate();
log(Action.UPDATE, obj);
return Response.ok().build();
}
@Transactional
public Response delete(Integer id) {
checkPermission(PermissionType.DELETE);
T databaseObj = this.get(id);
if (databaseObj == null)
throw new InvalidDataException("Invalid id");
databaseObj.delete();
log(Action.DELETE, databaseObj);
return Response.ok().build();
}
@SuppressWarnings("unchecked")
public List<T> getAll(SearchCriteria searchCriteria) {
checkPermission(PermissionType.READ);
return QueryUtils.nativeQuery(entityManager, objClass)
.baseQuery(new HqlQuery("select * from " + ModelUtils.getTableName(objClass)))
.searchCriteria(searchCriteria).build().getResultList();
}
protected enum PermissionType {
CREATE, DELETE, UPDATE, READ
}
}
|
package com.ethan.df.factory_pattern.v_common;
/**
* 简单工厂模式
*/
public class TestMain {
public static void main(String[] args) {
Factory factory = new AppleFactory();
Fruit apple = factory.createProduct();
apple.printName();
}
}
|
package application;
import java.io.IOException;
import java.net.URL;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.layout.Pane;
public abstract class BaseController {
@FXML
public Pane root;
@FXML
public void initialize() {
init();
}
@FXML
protected abstract void init();
public static BaseController load(URL url) throws IOException {
FXMLLoader loader = new FXMLLoader(url);
loader.load();
return loader.getController();
}
public Pane getRoot() {
return root;
}
}
|
package cn.novelweb.tool.upload.fastdfs.protocol.storage;
import cn.novelweb.tool.upload.fastdfs.model.MateData;
import cn.novelweb.tool.upload.fastdfs.protocol.BaseResponse;
import cn.novelweb.tool.upload.fastdfs.protocol.storage.enums.StorageMetadataSetType;
import cn.novelweb.tool.upload.fastdfs.protocol.storage.request.SetMetadataRequest;
import java.util.Set;
/**
* <p>设置文件标签(文件元数据)</p>
* <p>2020-02-03 17:08</p>
*
* @author LiZW
**/
public class SetMetadataCommandAbstract extends AbstractStorageCommand<Void> {
/**
* 设置文件标签(元数据)
*
* @param groupName 组名称
* @param path 路径
* @param metaDataSet 元数据集合
* @param type 增加元数据的类型
*/
public SetMetadataCommandAbstract(String groupName, String path, Set<MateData> metaDataSet, StorageMetadataSetType type) {
this.request = new SetMetadataRequest(groupName, path, metaDataSet, type);
// 输出响应
this.response = new BaseResponse<Void>() {
};
}
}
|
package org.lfy.gateway.config;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;
/**
* RedisRateLimiterConfig
* 限流策略的配置类
* ① userKeyResolver : 根据请求参数中的username进行限流
* ② ipKeyResolver : 根据访问IP进行限流
* ③ ipKeyResolver : 根据访问URI进行限流
*
* @author lfy
* @date 2021/3/24
**/
@Configuration
public class RedisRateLimiterConfig {
@Primary
@Bean(name = "ipKeyResolver")
public KeyResolver ipKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
}
@Bean("uriKeyResolver")
public KeyResolver uriKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getURI().getPath());
}
@Bean("userKeyResolver")
KeyResolver userKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("userId"));
}
}
|
package com.metoo.module.chatting.service.impl;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.metoo.core.dao.IGenericDAO;
import com.metoo.core.query.GenericPageList;
import com.metoo.core.query.PageObject;
import com.metoo.core.query.support.IPageList;
import com.metoo.core.query.support.IQueryObject;
import com.metoo.module.chatting.domain.ChattingConfig;
import com.metoo.module.chatting.service.IChattingConfigService;
@Service
@Transactional
public class ChattingConfigServiceImpl implements IChattingConfigService{
@Resource(name = "chattingConfigDAO")
private IGenericDAO<ChattingConfig> chattingConfigDao;
public boolean save(ChattingConfig chattingConfig) {
/**
* init other field here
*/
try {
this.chattingConfigDao.save(chattingConfig);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public ChattingConfig getObjById(Long id) {
ChattingConfig chattingConfig = this.chattingConfigDao.get(id);
if (chattingConfig != null) {
return chattingConfig;
}
return null;
}
public boolean delete(Long id) {
try {
this.chattingConfigDao.remove(id);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean batchDelete(List<Serializable> chattingConfigIds) {
// TODO Auto-generated method stub
for (Serializable id : chattingConfigIds) {
delete((Long) id);
}
return true;
}
public IPageList list(IQueryObject properties) {
if (properties == null) {
return null;
}
String query = properties.getQuery();
String construct = properties.getConstruct();
Map params = properties.getParameters();
GenericPageList pList = new GenericPageList(ChattingConfig.class,construct, query,
params, this.chattingConfigDao);
if (properties != null) {
PageObject pageObj = properties.getPageObj();
if (pageObj != null)
pList.doList(pageObj.getCurrentPage() == null ? 0 : pageObj
.getCurrentPage(), pageObj.getPageSize() == null ? 0
: pageObj.getPageSize());
} else
pList.doList(0, -1);
return pList;
}
public boolean update(ChattingConfig chattingConfig) {
try {
this.chattingConfigDao.update( chattingConfig);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public List<ChattingConfig> query(String query, Map params, int begin, int max){
return this.chattingConfigDao.query(query, params, begin, max);
}
}
|
package com.example.km.genericapp.viewholders;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.example.km.genericapp.R;
/**
* Android version view holder.
*/
public class AndroidVersionViewHolder extends RecyclerView.ViewHolder {
public final TextView versionNameTextView;
public final TextView versionNumberTextView;
public final TextView apiLevelTextView;
public AndroidVersionViewHolder(View view) {
super(view);
versionNameTextView = (TextView) view.findViewById(R.id.versionName);
versionNumberTextView = (TextView) view.findViewById(R.id.versionNumber);
apiLevelTextView = (TextView) view.findViewById(R.id.apiLevel);
}
}
|
package com.cmm.pay;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.cmm.pay")
public class PaymentAutoConfiguration {
}
|
package com.citibank.ods.entity.pl.valueobject;
/**
* Classe que instancia os valores correspondente a um registro da tabela :
* TplContactCust
* @author Hamilton Matos
* @date 26/03/2007
*/
public class TplContactCustEntityVO extends BaseTplContactCustEntityVO
{
/**
* Codigo da Operacao realizada no registro: inclusao, alteracao, exclusao
*
* Comment for <code>m_opernCode</code>
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private String m_opernCode;
/**
* @return Returns the opernCode.
*/
public String getOpernCode()
{
return m_opernCode;
}
/**
* @param opernCode_ The opernCode to set.
*/
public void setOpernCode( String opernCode_ )
{
m_opernCode = opernCode_;
}
}
|
package com.zju.courier.dao;
import com.zju.courier.entity.APInfo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ApInfoDao {
List<APInfo> list();
APInfo query(int ap_id);
void update(@Param("apInfo") APInfo apInfo);
void insert(@Param("apInfo") APInfo apInfo);
void delete(int ap_id);
}
|
package com.allmsi.plugin.flow.service.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.allmsi.plugin.external.service.impl.FlowExternalService;
import com.allmsi.plugin.flow.model.external.FlowDealIdATypeModel;
import com.allmsi.plugin.flow.model.external.FlowUserModel;
import com.allmsi.plugin.flow.service.FlowUserService;
import com.allmsi.sys.config.PropertyConfig;
import com.allmsi.sys.config.SpringContextRegister;
import com.allmsi.sys.util.StrUtil;
@Service
public class FlowUserServiceImpl implements FlowUserService {
@Autowired
private PropertyConfig properties;
@Autowired
private SpringContextRegister springContextRegister;
private final String FLOW_USERLIST = "flow_userList";
private final String DEFAULT_FLOW_SERVICE = "defaultFlowExternalService";
@Override
public Map<String, FlowUserModel> getFlowUserSingle(String id) {
List<String> ids = new ArrayList<String>();
ids.add(id);
return getFlowUserList(ids);
}
@Override
public Map<String, FlowUserModel> getFlowUserList(List<String> ids) {
FlowExternalService flowExternalService = getFlowExternalService();
return flowExternalService.getFlowUserInfoList(ids);
}
@Override
public String getFlowDealSingle(String dealId, String dealType) {
if (StrUtil.isEmpty(dealId) || StrUtil.isEmpty(dealType)) {
return null;
}
FlowExternalService flowExternalService = getFlowExternalService();
return flowExternalService.getDealNameByDealIdAndType(dealId, dealType);
}
@Override
public Map<String, String> getFlowDealList(List<FlowDealIdATypeModel> dealIds) {
FlowExternalService flowExternalService = getFlowExternalService();
return flowExternalService.getDealNameByDealIdAndType(dealIds);
}
@Override
public Map<String, List<String>> getUserAuthIdSort(String userId) {
FlowExternalService flowExternalService = getFlowExternalService();
return flowExternalService.getUserAuthIdSort(userId);
}
private FlowExternalService getFlowExternalService() {
FlowExternalService flowExternalService = null;
String className = properties.getProperty(FLOW_USERLIST);
if (StrUtil.isEmpty(className)) {
flowExternalService = springContextRegister.getServiceImpl(FlowExternalService.class, DEFAULT_FLOW_SERVICE);
} else {
flowExternalService = springContextRegister.getServiceImpl(FlowExternalService.class, className);
}
return flowExternalService;
}
}
|
package commands;
import packets.Packet;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
/**
* Класс команды exit
*/
public class Exit implements Command{
/**
* Поле сканера. Нужно, чтобы закрыть все потоки перед завершением работы программы
*/
protected Scanner scanner;
/**
* Конструктор класса команды exit
* @param scanner - сканер
*/
public Exit(Scanner scanner){
this.scanner = scanner;
}
/**
* Метод, приводяший команду в исполнение
*/
@Override
public Packet execute(){
scanner.close();
LocalDateTime time = LocalDateTime.now();
System.out.println(time.format(DateTimeFormatter.ofPattern("dd.MM.yyyy-HH:mm:ss "))+
" Завершение работы.");
System.exit(0);
return null;
}
}
|
package es.ubu.lsi.model.asociacion;
import java.io.Serializable;
import javax.persistence.*;
@Entity
@Table(name="TipoIncidencia")
public class TipoIncidencia implements Serializable{
private static final long serialVersionUID = 1L;
@Id
private int id;
private String descripcion;
private int valor;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public int getValor() {
return valor;
}
public void setValor(int valor) {
this.valor = valor;
}
}
|
package de.uulm.mmci.scatter;
import java.util.List;
import android.graphics.Canvas;
public class Scenario implements Drawable {
private List<Icon> targets;
public Scenario(List<Icon> targets) {
this.targets = targets;
}
public List<Icon> getTargets() {
return this.targets;
}
public void setScenario(List<Icon> targets){
this.targets = targets;
}
@Override
public void doDraw(Canvas c) {
for (Icon i : targets) {
i.doDraw(c);
}
}
}
|
package xhu.wncg.firesystem.modules.controller.qo;
import xhu.wncg.firesystem.modules.pojo.Unit;
/**
* 场所表
*
* @author zhaobo
* @email 15528330581@163.com
* @version 2017-11-02 15:58:16
*/
public class UnitQO extends Unit {
String countKeys;
String startTime;
String endTime;
public String getCountKeys() {
return countKeys;
}
public void setCountKeys(String countKeys) {
this.countKeys = countKeys;
}
public String getStartTime() {
String str=String.format("yyyy-MM-dd HH:mm:ss",startTime);
return str;
}
public void setStartTime(String startTime) {
this.startTime=startTime;
}
public String getEndTime() {
String str=String.format("yyyy-MM-dd HH:mm:ss",endTime);
return str;
}
public void setEndTime(String endTime) {
this.endTime=endTime;
}
}
|
package com.gaoshin.top.plugin.generic;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.LinearLayout;
import com.gaoshin.top.plugin.LabeledTextEdit;
public class GenericShortcutEditor extends LinearLayout {
private LabeledTextEdit actionEditor;
private LabeledTextEdit dataEditor;
private LabeledTextEdit typeEditor;
public GenericShortcutEditor(Context context) {
super(context);
setOrientation(LinearLayout.VERTICAL);
setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
actionEditor = new LabeledTextEdit(context, "Action:", 1);
actionEditor.getContentView().setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
addView(actionEditor);
actionEditor.setValue(Intent.ACTION_VIEW);
actionEditor.setVisibility(View.GONE);
dataEditor = new LabeledTextEdit(context, "HTTP URL or file path:", 1);
dataEditor.getContentView().setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
addView(dataEditor);
typeEditor = new LabeledTextEdit(context, "Type(optional):", 3);
typeEditor.getContentView().setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
addView(typeEditor);
typeEditor.setVisibility(View.GONE);
}
public void setAction(String str) {
actionEditor.setValue(str);
}
public String getAction() {
return actionEditor.getValue();
}
public void setType(String str) {
typeEditor.setValue(str);
}
public String getType() {
return typeEditor.getValue();
}
public void setData(String str) {
dataEditor.setValue(str);
}
public String getData() {
return dataEditor.getValue();
}
}
|
package com.templates.controller;
import java.io.UnsupportedEncodingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.templates.pojo.Entry;
//这个注解不能使用RestController,不然会返回模板类型的页面
//@RestController
@Controller
@RequestMapping(value = "/springB")
//@EnableAutoConfiguration
@EnableConfigurationProperties({Entry.class})
@PropertySource("classpath:com/config/springbootapplication/application.properties")
public class controller {
@Autowired
Entry entry;
//
// @Value("com/config/springbootappliaction/${name}")
// private String name;
//
// @Value("${age}")
// private String age;
//
// @Value("${six}")
// private String six;
/*************/
@Value("${sb}")
private String loginjspcontroller;
/*************/
/***
* SpringBoot默认读取配置文件<appliction.properties>文件是在src/main/resources位置
* 那么我们可以通过@PropertySource注解来指定读取配置文件,并且通过@Value来获取相应的值
* 然后再赋值给申明变量,传递给方法体。这样就实现了我们方法体"动态"获取值
* @return
* @throws UnsupportedEncodingException
*/
@RequestMapping(value = "/{loginjspcontroller}")
public String loginjsp() throws UnsupportedEncodingException {
String flag = "姓名:"+ entry.getName() + "年龄:" + entry.getAge() + "性别:" + entry.getSix();
return "SpringBoot";
}
/***
* 通过创建pojo,并且对相应的pojo整体赋值具体参考 Entry.class。
* 这里有提别需要注明的是 在启动方法类中需要加注@EnableConfigurationProperties 来指定你的实体。这样才能获取到实体值
* @return
* @throws UnsupportedEncodingException
*/
@RequestMapping("/Students")
public String getStudents() throws UnsupportedEncodingException {
return "姓名:"+ entry.getName() + "年龄:" + entry.getAge() + "性别:" + entry.getSix();
}
/****
* springboot + templates解析器
* templates解析器默认的html解析位置静态文件解析位置
* <html> src/main/resources/templates
* css等 src/main/resources/static
* @return
* @throws UnsupportedEncodingException
*/
@RequestMapping("/st")
public String getStudentsJsp() throws UnsupportedEncodingException {
return "students";
}
/*****
* 通过new ModelAndView来通知templates获取html
* 同样,也可以不new ModelAndView,templates也可以解析html参考下面一个方法
* @return
* @throws UnsupportedEncodingException
*/
@RequestMapping("/view")
public ModelAndView showview() throws UnsupportedEncodingException {
ModelAndView mv=new ModelAndView();
mv.setViewName("index");
mv.addObject("name", "index");
Entry entry = new Entry();
mv.addObject("user", entry);
return mv;
}
/***
* 直接跳login.html。
* 通过application.properties来重新指定templates读取html路径或者静态资源
* @return
* @throws UnsupportedEncodingException
*/
@RequestMapping("/login")
public String getlogin() throws UnsupportedEncodingException {
return "login";
}
}
|
package com.example.khong.facerecognition;
public class Common {
public final static String SERVER_IP = "192.168.20.101:8080";
}
|
package com.niit.phonaholic.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
DataSource dataSource;
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth)throws Exception{
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username,password,enabled from user where username=?")
.authoritiesByUsernameQuery("select username,role from user where username=?");
}
@Override
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ADMIN')")
.antMatchers("/cart/**").access("hasRole('USER')")
.and()
.formLogin()
.loginPage("/login")
.and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.and().csrf().disable();
}
}
|
package com.minamid.accessiblememorygame.ui;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.minamid.accessiblememorygame.MainActivity;
import com.minamid.accessiblememorygame.R;
import com.minamid.accessiblememorygame.base.CustomFragment;
import com.minamid.accessiblememorygame.ui.game.GameBoardFragment;
import com.minamid.accessiblememorygame.ui.settings.SettingsFragment;
import com.minamid.accessiblememorygame.util.Config;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainFragment extends CustomFragment {
@BindView(R.id.button_start_game) Button button_start_game;
@BindView(R.id.button_settings) Button button_settings;
@BindView(R.id.imageView) ImageView imageView;
private SharedPreferences mSharedPreferences;
public static MainFragment newInstance() {
return new MainFragment();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_fragment, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button_start_game.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setConfigWithPreferences();
navigateTo(GameBoardFragment.newInstance(), true);
}
});
button_settings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigateTo(SettingsFragment.newInstance(), true);
}
});
bindImage(imageView, R.drawable.accessible_memory_game_logo_gray_3);
}
@Override
public void onResume() {
super.onResume();
((MainActivity)getActivity()).setSupportActionBar(false,
getString(R.string.app_name));
}
private void bindImage(ImageView imageView, int resourceId) {
Glide.with(getContext())
.load(resourceId)
.into(imageView);
}
private void setConfigWithPreferences() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
String numOfMatchesPerGame = mSharedPreferences.getString(getString(R.string.preference_num_of_matches_per_game_key), "10" );
String numOfCardsToMakeMatch = mSharedPreferences.getString(getString(R.string.preference_num_of_cards_to_form_match_key), "2" );
String timeBoardRevealed = mSharedPreferences.getString(getString(R.string.preference_time_revealed_key), "10" );
boolean accessibilityEnabled = mSharedPreferences.getBoolean("preference_accessibility_enabled_key",true);
Config.getInstance().setPairsToMatchToCompleteGame(Integer.parseInt(numOfMatchesPerGame));
Config.getInstance().setNumOfCardsToMakeMatch(Integer.parseInt(numOfCardsToMakeMatch));
Config.getInstance().setTimeBoardRevealed(Integer.parseInt(timeBoardRevealed));
Config.getInstance().setAccessibilityEnabled(accessibilityEnabled);
}
}
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package functionaltests.masterworker.clear;
import static junit.framework.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.objectweb.proactive.core.config.CentralPAPropertyRepository;
import org.objectweb.proactive.extensions.masterworker.ProActiveMaster;
import org.objectweb.proactive.extensions.masterworker.interfaces.Master;
import org.ow2.tests.FunctionalTest;
import functionaltests.SchedulerTHelper;
import functionaltests.masterworker.A;
public class TestClear extends FunctionalTest {
private Master<A, Integer> master;
private List<A> tasks1;
private List<A> tasks2;
private List<A> tasks3;
public static final int NB_TASKS = 30;
public static final int WAIT_STEP = 20;
@org.junit.Test
public void run() throws Throwable {
SchedulerTHelper.startScheduler();
//before
tasks1 = new ArrayList<A>();
tasks2 = new ArrayList<A>();
tasks3 = new ArrayList<A>();
for (int i = 0; i < NB_TASKS; i++) {
A t1 = new A(i, (NB_TASKS - i) * WAIT_STEP, false);
A t2 = new A(i + NB_TASKS, (NB_TASKS - i) * WAIT_STEP, false);
A t3 = new A(i + NB_TASKS * 2, (NB_TASKS - i) * WAIT_STEP, false);
tasks1.add(t1);
tasks2.add(t2);
tasks3.add(t3);
}
master = new ProActiveMaster<A, Integer>();
String[] classpath = new String[] {
System.getProperty("pa.scheduler.home") + "/classes/schedulerTests",
System.getProperty("pa.scheduler.home") + "/classes/scheduler" };
master.addResources("rmi://localhost:" + CentralPAPropertyRepository.PA_RMI_PORT.getValue() + "/",
"demo", "demo", classpath);
master.setResultReceptionOrder(Master.SUBMISSION_ORDER);
//middle
// We send a set of tasks to warm up the masterworker
master.solve(tasks1);
master.waitAllResults();
// We send a set of tasks that will be canceled in the middle of their computation
master.solve(tasks2);
Thread.sleep((NB_TASKS / 2) * WAIT_STEP);
master.clear();
// We send a final set of tasks
master.solve(tasks3);
List<Integer> ids = master.waitAllResults();
// We check that we received the results of the last set of tasks (and only these ones)
Iterator<Integer> it = ids.iterator();
int last = it.next();
assertTrue("First received should be n0" + NB_TASKS * 2 + " here it's " + last, last == NB_TASKS * 2);
while (it.hasNext()) {
int next = it.next();
assertTrue("Results recieved in submission order", last < next);
last = next;
}
//after
master.terminate(true);
}
}
|
package top.lvjp.rabbitmqmodel.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* <p>
*
* </p>
*
* @author lvjp
* @since 2019-05-03
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class BrokerMessageLog implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 消息唯一ID
*/
@TableId
private String messageId;
/**
* 消息内容
*/
private String message;
/**
* 重试次数
*/
private Integer tryCount;
/**
* 消息投递状态 0:投递中,1:投递成功,2:投递失败
*/
private Integer status;
/**
* 下一次重试时间
*/
private LocalDateTime nextRetry;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
|
package DAO.Dbtable;
import Helpers.DbTable;
/**
* Classe Cibo che estende l'helpers DbTable
*/
public class Cibo extends DbTable {
public Cibo(){
name="cibo";
sql="";
}
}
|
package code.graphics;
import code.global.GlobalVariables;
import code.intersectObjects.IntersectsObjectLevel2;
import code.player.Player;
import code.player.Sprite;
import javafx.geometry.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import static code.global.GlobalVariables.CANVAS_HEIGHT;
import static code.graphics.ImageController.BRICK_SINGLE_HORIZONTAL;
import static code.graphics.ImageController.BRICK_SINGLE_VERTICAL;
public class DrawLevel2 {
private static final int TREE_WIDTH_AND_HEIGHT = 20;
private static final int FOUNTAIN_HEIGHT = 50;
private static final String KEYBOARD_Q = "Q";
private static final String KEYBOARD_W = "W";
private static final String KEYBOARD_E = "E";
private static final String KEYBOARD_R = "R";
private static final String KEYBOARD_T = "T";
private static final String KEYBOARD_Y = "Y";
private static final String KEYBOARD_U = "U";
private static final String KEYBOARD_I = "I";
private static final String KEYBOARD_O = "O";
private static final String KEYBOARD_A = "A";
private static final String KEYBOARD_S = "S";
private static final String KEYBOARD_D = "D";
private static final String KEYBOARD_F = "F";
private static final String KEYBOARD_Z = "Z";
private static final String TREE_TYPE = "tree";
private static final String FLOWER_TYPE = "flower";
private static final String DWARF_TYPE = "dwarf";
private static final String FOUNTAIN_TYPE = "fountain";
private static final String FERN_TYPE = "fern";
private static final String SMALL_ROCK_TYPE = "smallRock";
private static final String BIG_ROCK_TYPE = "bigRock";
public static List<Sprite> plants = new ArrayList<>();
public static List<Rectangle2D> getPlants() {
return convertSpriteToRectList();
}
private static List<Rectangle2D> convertSpriteToRectList() {
List<Rectangle2D> rectangle2DList = new ArrayList<>();
for (Sprite plant : plants) {
rectangle2DList.add(plant.getBoundary());
}
return rectangle2DList;
}
public static void drawGarden() {
//draw garden
GlobalVariables.getGraphicContext().clearRect(GlobalVariables.CANVAS_X_Y, GlobalVariables.CANVAS_X_Y,
GlobalVariables.CANVAS_WIDTH, GlobalVariables.CANVAS_HEIGHT);
//draw garden grass
int y = 0;
for (int i = 0; i < 5; i++) {
int x = 0;
for (int j = 0; j < 5; j++) {
GlobalVariables.getGraphicContext().drawImage(ImageController.getGardenGrass(), x, y);
x += GlobalVariables.getCanvas().getWidth() / 5;
}
y += GlobalVariables.getCanvas().getHeight() / 5;
}
//draw gardenFence
int x = 0;
for (int i = 0; i < 15; i++) {
GlobalVariables.getGraphicContext().drawImage(ImageController.getGardenFence(), x, 0);
x += 90;
}
if (plants.size() == 0) {
Player.getInstance().render(GlobalVariables.getGraphicContext());
GlobalVariables.getIntersectsObject().addElement(IntersectsObjectLevel2.getDownBorder());
GlobalVariables.getIntersectsObject().addElement(IntersectsObjectLevel2.getUpperBorder());
GlobalVariables.getIntersectsObject().addElement(IntersectsObjectLevel2.getLeftBorder());
GlobalVariables.getIntersectsObject().addElement(IntersectsObjectLevel2.getRightBorder());
}
createPlant();
Player.getInstance().render(GlobalVariables.getGraphicContext());
//draw down border
for (int i = 0; i < 4 ; i++) {
GlobalVariables.getGraphicContext().drawImage(BRICK_SINGLE_HORIZONTAL, BRICK_SINGLE_VERTICAL.getWidth()
+ (i * BRICK_SINGLE_HORIZONTAL.getWidth()) - 25, CANVAS_HEIGHT - (2 * BRICK_SINGLE_HORIZONTAL.getHeight() - 20));
}
for (int i = 6; i < GlobalVariables.getCanvas().getWidth() ; i++) {
GlobalVariables.getGraphicContext().drawImage(BRICK_SINGLE_HORIZONTAL, BRICK_SINGLE_VERTICAL.getWidth()
+ (i * BRICK_SINGLE_HORIZONTAL.getWidth()) - 25, CANVAS_HEIGHT - (2 * BRICK_SINGLE_HORIZONTAL.getHeight() - 20));
}
for (Sprite plant1 : plants) {
if (plant1.intersects(Player.getInstance())) {
if (plant1.getY() + plant1.getHeight() > Player.getInstance().getY() + Player.getInstance().getHeight()) {
Player.getInstance().render(GlobalVariables.getGraphicContext());
plant1.render(GlobalVariables.getGraphicContext());
} else if (plant1.getY() + plant1.getHeight() <= Player.getInstance().getY() + Player.getInstance().getHeight()) {
plant1.render(GlobalVariables.getGraphicContext());
Player.getInstance().render(GlobalVariables.getGraphicContext());
}
} else {
plant1.render(GlobalVariables.getGraphicContext());
}
}
}
private static Plant plant() {
double x = Player.getInstance().getX() + Player.getInstance().getWidth();
double y = Player.getInstance().getY() + Player.getInstance().getHeight();
return new Plant(x, y);
}
private static void createPlant() {
boolean intersects = false;
if (GlobalVariables.getInput().contains(KEYBOARD_Q)) {
GlobalVariables.getInput().clear();
for (Sprite plant : plants) {
if (plant().getFirstTree() .intersects(plant)) {
intersects = true;
}
}
if (!intersects) {
plants.add(plant().getFirstTree());
addIntersectObjectLevel2(TREE_TYPE);
}
} else if (GlobalVariables.getInput().contains(KEYBOARD_W)) {
GlobalVariables.getInput().clear();
for (Sprite plant : plants) {
if (plant().getSecondTree() .intersects(plant)) {
intersects = true;
}
}
if (!intersects) {
plants.add(plant().getSecondTree());
addIntersectObjectLevel2(TREE_TYPE);
}
} else if (GlobalVariables.getInput().contains(KEYBOARD_E)) {
GlobalVariables.getInput().clear();
for (Sprite plant : plants) {
if (plant().getThirdTree() .intersects(plant)) {
intersects = true;
}
}
if (!intersects) {
plants.add(plant().getThirdTree());
addIntersectObjectLevel2(TREE_TYPE);
}
} else if (GlobalVariables.getInput().contains(KEYBOARD_R)) {
GlobalVariables.getInput().clear();
for (Sprite plant : plants) {
if (plant().getFirstFlower() .intersects(plant)) {
intersects = true;
}
}
if (!intersects) {
plants.add(plant().getFirstFlower());
addIntersectObjectLevel2(FLOWER_TYPE);
}
} else if (GlobalVariables.getInput().contains(KEYBOARD_T)) {
GlobalVariables.getInput().clear();
for (Sprite plant : plants) {
if (plant().getSecondFlower() .intersects(plant)) {
intersects = true;
}
}
if (!intersects) {
plants.add(plant().getSecondFlower());
addIntersectObjectLevel2(FLOWER_TYPE);
}
} else if (GlobalVariables.getInput().contains(KEYBOARD_Y)) {
GlobalVariables.getInput().clear();
for (Sprite plant : plants) {
if (plant().getThirdFlower() .intersects(plant)) {
intersects = true;
}
}
if (!intersects) {
plants.add(plant().getThirdFlower());
addIntersectObjectLevel2(FLOWER_TYPE);
}
} else if (GlobalVariables.getInput().contains(KEYBOARD_U)) {
GlobalVariables.getInput().clear();
for (Sprite plant : plants) {
if (plant().getDwarf() .intersects(plant)) {
intersects = true;
}
}
if (!intersects) {
plants.add(plant().getDwarf());
addIntersectObjectLevel2(DWARF_TYPE);
}
} else if (GlobalVariables.getInput().contains(KEYBOARD_I)) {
GlobalVariables.getInput().clear();
for (Sprite plant : plants) {
if (plant().getFountain() .intersects(plant)) {
intersects = true;
}
}
if (!intersects) {
plants.add(plant().getFountain());
addIntersectObjectLevel2(FOUNTAIN_TYPE);
}
} else if (GlobalVariables.getInput().contains(KEYBOARD_O)) {
GlobalVariables.getInput().clear();
for (Sprite plant : plants) {
if (plant().getFern() .intersects(plant)) {
intersects = true;
}
}
if (!intersects) {
plants.add(plant().getFern());
addIntersectObjectLevel2(FERN_TYPE);
}
} else if (GlobalVariables.getInput().contains(KEYBOARD_A)) {
GlobalVariables.getInput().clear();
for (Sprite plant : plants) {
if (plant().getSmallRock() .intersects(plant)) {
intersects = true;
}
}
if (!intersects) {
plants.add(plant().getSmallRock());
addIntersectObjectLevel2(SMALL_ROCK_TYPE);
}
} else if (GlobalVariables.getInput().contains(KEYBOARD_S)) {
GlobalVariables.getInput().clear();
for (Sprite plant : plants) {
if (plant().getBigRock() .intersects(plant)) {
intersects = true;
}
}
if (!intersects) {
plants.add(plant().getBigRock());
addIntersectObjectLevel2(BIG_ROCK_TYPE);
}
} else if (GlobalVariables.getInput().contains(KEYBOARD_D)) {
GlobalVariables.getInput().clear();
for (Sprite plant : plants) {
if (plant().getFourthTree() .intersects(plant)) {
intersects = true;
}
}
if (!intersects) {
plants.add(plant().getFourthTree());
addIntersectObjectLevel2(TREE_TYPE);
}
} else if (GlobalVariables.getInput().contains(KEYBOARD_F)) {
GlobalVariables.getInput().clear();
for (Sprite plant : plants) {
if (plant().getFifthTree() .intersects(plant)) {
intersects = true;
}
}
if (!intersects) {
plants.add(plant().getFifthTree());
addIntersectObjectLevel2(TREE_TYPE);
}
} else if (GlobalVariables.getInput().contains(KEYBOARD_Z)) {
GlobalVariables.getInput().clear();
removeIntersectObjectLevel2();
if (!plants.isEmpty()) {
plants.remove(plants.size() - 1);
}
}
}
private static void addIntersectObjectLevel2(String type) {
Sprite gardenObject = plants.get(plants.size() - 1);
Rectangle2D rectangle2D = null;
switch (type) {
case TREE_TYPE:
rectangle2D = new Rectangle2D(gardenObject.getX() + gardenObject.getWidth() / 2 - TREE_WIDTH_AND_HEIGHT,
gardenObject.getY() + gardenObject.getHeight() - TREE_WIDTH_AND_HEIGHT,
TREE_WIDTH_AND_HEIGHT, TREE_WIDTH_AND_HEIGHT);
break;
case FLOWER_TYPE:
rectangle2D = new Rectangle2D(gardenObject.getX(),
gardenObject.getY() + gardenObject.getHeight() - TREE_WIDTH_AND_HEIGHT,
gardenObject.getWidth(), TREE_WIDTH_AND_HEIGHT);
break;
case DWARF_TYPE:
rectangle2D = new Rectangle2D(gardenObject.getX(),
gardenObject.getY() + gardenObject.getHeight() - TREE_WIDTH_AND_HEIGHT,
gardenObject.getWidth(), TREE_WIDTH_AND_HEIGHT);
break;
case BIG_ROCK_TYPE:
rectangle2D = new Rectangle2D(gardenObject.getX(),
gardenObject.getY() + gardenObject.getHeight() - TREE_WIDTH_AND_HEIGHT,
gardenObject.getWidth(), TREE_WIDTH_AND_HEIGHT);
break;
case SMALL_ROCK_TYPE:
rectangle2D = new Rectangle2D(gardenObject.getX(),
gardenObject.getY() + gardenObject.getHeight() - TREE_WIDTH_AND_HEIGHT,
gardenObject.getWidth(), TREE_WIDTH_AND_HEIGHT);
break;
case FERN_TYPE:
rectangle2D = new Rectangle2D(gardenObject.getX(),
gardenObject.getY() + gardenObject.getHeight() - TREE_WIDTH_AND_HEIGHT,
gardenObject.getWidth(), TREE_WIDTH_AND_HEIGHT);
break;
case FOUNTAIN_TYPE:
rectangle2D = new Rectangle2D(gardenObject.getX(),
gardenObject.getY() + gardenObject.getHeight() - FOUNTAIN_HEIGHT,
gardenObject.getWidth(), FOUNTAIN_HEIGHT);
break;
}
if(rectangle2D != null) {
GlobalVariables.getIntersectsObject().addElement(rectangle2D);
}
}
private static void removeIntersectObjectLevel2() {
Rectangle2D rectangle2D = GlobalVariables.getIntersectsObject().getRectangle2DList()
.get(GlobalVariables.getIntersectsObject().getRectangle2DList().size() - 1);
GlobalVariables.getIntersectsObject().removeElement(rectangle2D);
}
}
|
package com.example.canyetismis.coursework2;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.provider.SyncStateContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.example.canyetismis.coursework2.MP3Player.MP3PlayerState;
import java.io.File;
import java.util.Timer;
import java.util.TimerTask;
import static com.example.canyetismis.coursework2.MP3PlayerHandler.PAUSE;
import static com.example.canyetismis.coursework2.MP3PlayerHandler.PLAY;
import static com.example.canyetismis.coursework2.MP3PlayerHandler.STOP;
public class MainActivity extends AppCompatActivity {
Button pauseButton;
Button playButton;
Button stopButton;
ProgressBar progressBar;
int time;
private MP3Service.MP3Binder binder = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pauseButton = (Button) findViewById(R.id.pauseButton);
playButton = (Button) findViewById(R.id.playButton);
stopButton = (Button) findViewById(R.id.stopButton);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
final ListView lv = (ListView) findViewById(R.id.musicList);
File musicDir = new File(
Environment.getExternalStorageDirectory().getPath()+ "/Music/");
File list[] = musicDir.listFiles();
lv.setAdapter(new ArrayAdapter<File>(this,
android.R.layout.simple_list_item_1, list));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter,
View myView,
int myItemInt,
long mylng) {
File selectedFromList =(File) (lv.getItemAtPosition(myItemInt));
Log.d("g53mdp", selectedFromList.getAbsolutePath());
// do something with selectedFromList...
//String song = selectedFromList.getAbsolutePath();
binder.load(selectedFromList.getAbsolutePath());
setProgressBar();
}
});
Intent intent = new Intent(this, MP3Service.class);
this.startService(intent);
this.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
binder = (MP3Service.MP3Binder) service;
setProgressBar();
}
@Override
public void onServiceDisconnected(ComponentName name) {
binder = null;
}
};
public void onPauseClicked(View v){
binder.pause();
setProgressBar();
}
public void onPlayClicked(View v){
binder.play();
setProgressBar();
}
public void onStopClicked(View v){
binder.stop();
setProgressBar();
binder.stopNotification();
}
class Progress extends TimerTask{
public void run(){
time = binder.getProgress();
Log.d("PROGRESS", Integer.toString(time));
progressBar.setProgress(time);
}
}
public void setProgressBar(){
int duration = binder.getDuration();
Log.d("g53mdp", Integer.toString(duration));
progressBar.setMax(duration);
Timer timer = new Timer();
timer.schedule(new Progress(),0,1000);
}
@Override
protected void onDestroy() {
Log.d("g53mdp", "onDestroy: ");
super.onDestroy();
if (serviceConnection != null) {
unbindService(serviceConnection);
serviceConnection = null;
}
binder.createNotificationChannel();
}
}
|
package io.breen.socrates.test.python;
import io.breen.socrates.criteria.Criteria;
import io.breen.socrates.file.python.PythonFile;
import io.breen.socrates.file.python.Variable;
import io.breen.socrates.submission.Submission;
import io.breen.socrates.submission.SubmittedFile;
import io.breen.socrates.test.*;
import javax.swing.text.Document;
import java.io.IOException;
public class VariableExistsTest extends VariableTest implements Automatable<PythonFile> {
private final Variable variable;
public VariableExistsTest(Variable variable) {
super(variable.pointValue, "variable '" + variable.name + "' is missing");
this.variable = variable;
}
@Override
public String toString() {
return "VariableExistsTest(variable=" + variable + ")";
}
@Override
public String getTestTypeName() {
return "variable check";
}
@Override
public boolean shouldPass(PythonFile parent, SubmittedFile target, Submission submission,
Criteria criteria, Document transcript, Document notes)
throws CannotBeAutomatedException, AutomationFailureException
{
try {
PythonInspector inspector = new PythonInspector(target.fullPath);
return inspector.variableExists(variable.name);
} catch (IOException x) {
throw new AutomationFailureException(x);
} catch (PythonError x) {
throw new CannotBeAutomatedException(
"Python error occurred looking for variable: " + x
);
}
}
}
|
package robotambulance.course;
public class Position implements Comparable<Position>{
private Vertice from;
private Vertice to;
private float distanceFrom;
public Position(Vertice from, Vertice to, float distanceFrom) {
super();
this.from = from;
this.to = to;
this.distanceFrom = distanceFrom;
}
public void setFrom(Vertice from) {
this.from = from;
}
public void setTo(Vertice to) {
this.to = to;
}
public void setDistanceFrom(float distanceFrom) {
this.distanceFrom = distanceFrom;
}
public Vertice getFrom() {
return from;
}
public Vertice getTo() {
return to;
}
public float getDistanceFrom() {
return distanceFrom;
}
@Override
public boolean equals(Object o) {
if(o!=null && o instanceof Position) {
Position pos = (Position) o;
return pos.getFrom().equals(this.getFrom())
|| pos.getTo().equals(this.getTo())
|| pos.getFrom().equals(this.getTo())
|| pos.getTo().equals(this.getFrom());
}
return false;
}
@Override
public String toString() {
return "Position [from=" + from + ", to=" + to + ", distanceFrom=" + distanceFrom + "]";
}
@Override
public int compareTo(Position pos) {
int c1 = from.compareTo(pos.from);
if(c1==0) {
int c2 = to.compareTo(pos.getTo());
return c2;
}
return c1;
}
}
|
package com.example.android.offline;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import com.sap.cloud.android.odata.espmcontainer.Customer;
import com.sap.cloud.android.odata.espmcontainer.SalesOrderHeader;
import com.sap.cloud.mobile.odata.DataQuery;
import com.sap.cloud.mobile.odata.LocalDateTime;
import com.sap.cloud.mobile.odata.SortOrder;
import static com.example.android.offline.MainActivity.factory;
import static com.example.android.offline.MainActivity.mToast;
import static com.example.android.offline.StorageManager.adapter;
public class CreateCustomerActivity extends AppCompatActivity {
EditText addressField;
EditText postalCodeField;
EditText phoneField;
EditText cityField;
EditText countryField;
EditText dobField;
EditText houseNumField;
EditText firstNameField;
EditText lastNameField;
EditText emailField;
StorageManager storageManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_customer);
setTitle("Create Customer");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
storageManager = StorageManager.getInstance();
firstNameField = findViewById(R.id.firstname_edittext);
lastNameField = findViewById(R.id.lastname_edittext);
emailField = findViewById(R.id.email_edittext);
addressField = findViewById(R.id.address_edittext);
postalCodeField = findViewById(R.id.postal_code_edittext);
phoneField = findViewById(R.id.phone_edittext);
cityField = findViewById(R.id.city_edittext);
countryField = findViewById(R.id.country_edittext);
dobField = findViewById(R.id.dob_edittext);
houseNumField = findViewById(R.id.house_num_edittext);
Bundle extras = getIntent().getExtras();
if (extras != null){
firstNameField.setText(extras.getString("firstName"));
lastNameField.setText(extras.getString("lastName"));
emailField.setText(extras.getString("email"));
addressField.setText(extras.getString("street"));
postalCodeField.setText(extras.getString("postalNumber"));
phoneField.setText(extras.getString("phoneNumber"));
cityField.setText(extras.getString("city"));
dobField.setText(extras.getString("dob"));
houseNumField.setText(extras.getString("houseNumber"));
countryField.setText(extras.getString("country"));
}
}
public void createMessageDialog(String message) {
AlertDialog alertDialog = new AlertDialog.Builder(CreateCustomerActivity.this).create();
alertDialog.setTitle(message);
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.colorPrimary, null));
}
public void onCreateCustomer() {
// First we create a customer with default properties
Customer newCustomer = new Customer();
// Next we set all the customer's properties using various data validation tactics to
// ensure that incorrect or invalid information has not been entered
newCustomer.setFirstName(firstNameField.getText().toString());
newCustomer.setLastName(lastNameField.getText().toString());
// Emails must follow a certain xxx@yyy.zzz form
if (emailField.getText().toString().matches("[^ ]*@[^ ]*\\.[^ ]*")) {
newCustomer.setEmailAddress(emailField.getText().toString());
}
else {
createMessageDialog("Please input a valid email address.");
return;
}
newCustomer.setStreet(addressField.getText().toString());
newCustomer.setPostalCode(postalCodeField.getText().toString());
// Phone numbers can only contain numbers
if (phoneField.getText().toString().matches("[0-9()\\- ]+")) {
newCustomer.setPhoneNumber(String.valueOf(phoneField.getText().toString()));
}
else {
createMessageDialog("Please input a valid phone number (digits, parentheses, dashes).");
return;
}
newCustomer.setCity(cityField.getText().toString());
// Country codes must be length 2, i.e. CA or US
if (countryField.getText().toString().length() == 2) {
newCustomer.setCountry(countryField.getText().toString().toUpperCase());
}
else {
createMessageDialog("Country code must be 2 characters.");
return;
}
// Date of birth must not be in the future
if (!dobField.getText().toString().isEmpty() && LocalDateTime.parse(dobField.getText().toString()) != null) {
LocalDateTime dob = LocalDateTime.parse(dobField.getText().toString());
if (dob.lessEqual(LocalDateTime.now())) {
newCustomer.setDateOfBirth(dob);
}
else {
createMessageDialog("Date of birth cannot be in the future.");
return;
}
}
newCustomer.setHouseNumber(houseNumField.getText().toString());
newCustomer.unsetDataValue(Customer.customerID);
storageManager.getOfflineODataProvider().createEntity(newCustomer, null, null);
Log.d(MainActivity.TAG, "Read Link: " + newCustomer.getReadLink());
Log.d(MainActivity.TAG, "Edit Link: " + newCustomer.getEditLink());
// Before uploading, the customer does not have an ID (it's generated by the server)
Log.d(MainActivity.TAG, "Customer ID is set: " + newCustomer.hasDataValue(Customer.customerID));
if (getIntent().getStringExtra("parent_activity") == null) {
adapter.notifyDataSetChanged();
}
else {
factory.postLiveData.getValue().invalidate();
}
Log.d("myDebuggingTag", "Successfully created the new customer locally.");
mToast = Toast.makeText(this, "Successfully created the new customer locally.", Toast.LENGTH_LONG);
mToast.show();
onBackPressed();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.create_customer_activity_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
}
else if (id == R.id.action_save) {
onCreateCustomer();
}
return super.onOptionsItemSelected(item);
}
}
|
package com.project;
public class ActionCooldown {
private int maxCooldown;
private int cooldown;
public ActionCooldown(int cooldown) {
this.maxCooldown = cooldown;
this.cooldown = cooldown;
}
public boolean isOffCooldown(){
return cooldown<=0;
}
public void updateCooldown(){
if(isOffCooldown()){
resetCooldown();
}
else{
lowerCooldown();
}
}
private void lowerCooldown(){
cooldown--;
}
private void resetCooldown(){
cooldown = maxCooldown;
}
}
|
import java.util.*;
public class LotteryDrawing {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请问您要从多少个数中抽取数字?");
int n = in.nextInt();
int[] a = new int[n];
System.out.println("请问您要抽取多少个数字?");
int k = in.nextInt();
int[] r = new int[k];
for(int i = 0 ;i<a.length;i++)
a[i]=i+1;
int e=0;
for(int j = 0;j<r.length;j++) {
e=(int)(Math.random()*n);
r[j]=a[e];
a[e]=a[n-1];
n--;
}
Arrays.sort(r);
for(int i : r)
System.out.println(i);
in.close();
}
}
|
package Model;
/**
*
* @author lala
*/
public class Simulator {
private final Road h = new Road(RoadSense.Horizontal);
private final Road h2 = new Road(RoadSense.Horizontal);
private final Road v = new Road(RoadSense.Vertical);
private final Road v2 = new Road(RoadSense.Vertical);
public Simulator() {
h.intersectRoads(v, 1, 1);
h.intersectRoads(v2, 2, 1);
h2.intersectRoads(v, 1, 2);
h2.intersectRoads(v2, 2, 2);
}
public double simulate(boolean[][] semaphoreHistory) {
for (int i = 0; i < 7200; i++) {
h.addCar();
h2.addCar();
v.addCar();
v2.addCar();
if (i % 10 == 0) {
boolean[] thisTime = semaphoreHistory[i % 12];
h.sem1NextStatus(thisTime[0]);
v.sem1NextStatus(!thisTime[0]);
h.sem2NextStatus(thisTime[1]);
v2.sem1NextStatus(!thisTime[1]);
h2.sem1NextStatus(thisTime[2]);
v.sem2NextStatus(!thisTime[2]);
h2.sem2NextStatus(thisTime[3]);
v2.sem2NextStatus(!thisTime[3]);
}
updateSimulator();
}
double fitness = (double) ((h.count() + v.count() + h2.count() + v2.count()) / ((double)4*7200));
this.reset();
return fitness;
}
private void updateSimulator() {
h.determineNextStatusInRange(0, 3);//a
h.updateInRange(0, 2);
v.determineNextStatusInRange(0, 3);//b
v.updateInRange(0, 2);
v2.determineNextStatusInRange(0, 3); //c
v2.updateInRange(0, 2);
h2.determineNextStatusInRange(0, 3); //h
h2.updateInRange(0, 2);
//First intersection TOP+LEFT
if (h.sem1.semStatus == SemaphoreStatus.OPEN) {
h.determineNextStatusInRange(4, 8); //j
v.determineNextStatusInRange(5, 8); //i
h.updateInRange(3, 7);
v.updateInRange(3, 3);
v.updateInRange(5, 7);
} else {
v.determineNextStatusInRange(4, 8); //i
h.determineNextStatusInRange(5, 8); //j
v.updateInRange(3, 7);
h.updateInRange(3, 3);
h.updateInRange(5, 7);
}
//TOP+RIGHT
if (h.sem2.semStatus == SemaphoreStatus.OPEN) {
h.determineNextStatusInRange(9, 13); //d
v2.determineNextStatusInRange(5, 8); //k
h.updateInRange(8, 13);
v2.updateInRange(3, 3);
v2.updateInRange(5, 7);
} else {
v2.determineNextStatusInRange(4, 8);//k
h.determineNextStatusInRange(10, 13); //d
v2.updateInRange(3, 7);
h.updateInRange(8, 8);
h.updateInRange(10, 13);
}
//BOTTOM LEFT
if (h2.sem1.semStatus == SemaphoreStatus.OPEN) {
h2.determineNextStatusInRange(4, 8);
v.determineNextStatusInRange(10, 13);
h2.updateInRange(3, 7);
v.updateInRange(8, 8);
v.updateInRange(10, 13);
} else {
v.determineNextStatusInRange(9, 13);
h2.determineNextStatusInRange(5, 8);
v.updateInRange(8, 13);
h2.updateInRange(3, 3);
h2.updateInRange(5, 7);
}
//BOTTOM RIGHT
if (h2.sem2.semStatus == SemaphoreStatus.OPEN) {
h2.determineNextStatusInRange(9, 13);
v2.determineNextStatusInRange(10, 13);
h2.updateInRange(8, 13);
v2.updateInRange(8, 8);
v2.updateInRange(10, 13);
} else {
v2.determineNextStatusInRange(9, 13);
h2.determineNextStatusInRange(10, 13);
v2.updateInRange(8, 13);
h2.updateInRange(8, 8);
h2.updateInRange(10, 13);
}
/*if(h.roadData.get(13).currentStatus == Status.BUSY)
System.out.println("Carretera horizontal1: +1");
if(h2.roadData.get(13).currentStatus == Status.BUSY)
System.out.println("Carretera horizontal2: +1");
if(v.roadData.get(13).currentStatus == Status.BUSY)
System.out.println("Carretera vertical1: +1");
if(v2.roadData.get(13).currentStatus == Status.BUSY)
System.out.println("Carretera vertical2: +1");*/
}
public void reset(){
h.reset();
h2.reset();
v.reset();
v2.reset();
}
}
|
package dev.liambloom.softwareEngineering.chapter9.lawFirm;
public class Client2
{
public static void main(String[] args)
{
Lawyer leia = new Lawyer();
System.out.print("Lawyer: ");
System.out.print(leia.getHours() + ", ");
System.out.printf("$%.2f, ", leia.getSalary());
System.out.print(leia.getVacationDays() + ", ");
System.out.println(leia.getVacationForm());
leia.sue();
System.out.println(" -------------------------------- \n\n");
Secretary sally = new Secretary();
System.out.print("Secretary: ");
System.out.print(sally.getHours() + ", ");
System.out.printf("$%.2f, ", sally.getSalary());
System.out.print(sally.getVacationDays() + ", ");
System.out.println(sally.getVacationForm());
sally.takeDictation("Sally is taking dictation!");
System.out.println(" -------------------------------- \n\n");
LegalSecretary lucy = new LegalSecretary();
System.out.print("Legal Secretary: ");
System.out.print(lucy.getHours() + ", ");
System.out.printf("$%.2f, ", lucy.getSalary());
System.out.print(lucy.getVacationDays() + ", ");
System.out.println(lucy.getVacationForm());
lucy.takeDictation("Lucy is taking dictation!");
lucy.fileLegalBriefs();
System.out.println(" -------------------------------- \n\n");
// BJP Section 9.1
HarvardLawyer harry = new HarvardLawyer();
System.out.print("Harvard Lawyer: ");
System.out.print(harry.getHours() + ", ");
System.out.printf("$%.2f, ", harry.getSalary());
System.out.print(harry.getVacationDays() + ", ");
System.out.println(harry.getVacationForm());
harry.sue();
System.out.println(" -------------------------------- \n\n");
Marketer mike = new Marketer();
System.out.print("Marketer: ");
System.out.print(mike.getHours() + ", ");
System.out.printf("$%.2f, ", mike.getSalary());
System.out.print(mike.getVacationDays() + ", ");
System.out.println(mike.getVacationForm());
mike.advertise();
System.out.println(" -------------------------------- \n\n");
Janitor jay = new Janitor();
System.out.print("Janitor: ");
System.out.print(jay.getHours() + ", ");
System.out.printf("$%.2f, ", jay.getSalary());
System.out.print(jay.getVacationDays() + ", ");
System.out.println(jay.getVacationForm());
jay.clean();
System.out.println(" -------------------------------- \n\n");
// BJP Section 9.2
//"True" resulting test data
System.out.println("\n\n >>>>>>>>>>>>>>>> TRUE equals() via getSalary() <<<<<<<<<<<<<< ");
Lawyer larry = new Lawyer();
Secretary suzy = new Secretary();
System.out.println("leia.equals(larry) = " + leia.equals(larry));
System.out.println("sally.equals(suzy) = " + sally.equals(suzy));
System.out.println("mike.equals(jay) = " + mike.equals(jay));
// "False" resulting test data
System.out.println("\n\n >>>>>>>>>>>>>>>> FALSE equals() via getSalary() <<<<<<<<<<<<<< ");
System.out.println("larry.equals(harry)= " + larry.equals(harry));
Secretary sara = new Secretary();
System.out.println("sally.equals(sara) = " + sally.equals(sara));
Janitor jim = new Janitor();
System.out.println("jim.equals(jay) = " + jim.equals(jay));
} // main
} // Employee_CLIENT_Chap9_SECOND_EXAMPLE_WithEquals
|
package edu.neu.ccs.cs5010;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CSVFileReader{
Candy candy;
List candyList;
/**
*
* @param csvFile the dreamCandy file to be readed
* @return the list form of candy children want
* @throws FileNotFoundException if file can not be found
*/
Set<String> candynameset = Stream.of("Twix","Snikers","Mars","Kit Kat","Whoopers",
"Milky Way","Toblerorn","Crunch","Baby Ruth","Almond Joy").collect(Collectors.toSet());
Set<String> candysizeset = Stream.of("Super","King","Regular","Fun").collect(Collectors.toSet());
public List<String> readFile(String csvFile) throws FileNotFoundException {
String line;
Candy candy;
candyList = new ArrayList();
//String[] candyList = null;
BufferedReader fileReader = new BufferedReader(new FileReader(csvFile));
Pattern candypattern = Pattern.compile(",");
String[] info = null;
//Matcher candyMatcher = candypattern.matcher(csvFile);
try {
line = fileReader.readLine();
info = candypattern.split(line);
//System.out.println(info);
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fileReader != null){
try{
fileReader.close();
}catch(IOException e){
e.getStackTrace();
}
}
}for(int i = 0; i< info.length;i++){
candyList.add(info[i]);
}//System.out.println(candyList);
return candyList;
}
/**
*
* @param candyList the list returned by readFile method
* @param
* @return
*/
public List<Candy> matchCandy(List<String> candyList){
Candy candy;
List<Candy> finalCandy = new ArrayList<Candy>();
StringBuilder sizebuild = null;
StringBuilder namebuild = null;
String candySize;
String candyName;
for(int i = 0;i<candyList.size();i++){
String[] sizeCheck = candyList.get(i).split("\\s+");
sizebuild = new StringBuilder();
sizebuild.append(sizeCheck[0]);
sizebuild.append(" ");
sizebuild.append(sizeCheck[1]);
candySize = sizebuild.toString();
namebuild.append(sizeCheck[2]);
candyName = namebuild.toString();
candy = new Candy(candySize,candyName);
finalCandy.add(candy);
System.out.println(finalCandy);
}return finalCandy;
}
/**
*
* @param csvFile
* @return true if the dream candy list is valid(all candy are there in the neignborhood)
* @throws FileNotFoundException
*/
public boolean checkList(String csvFile) throws FileNotFoundException {
List candylist = new CSVFileReader().readFile(csvFile);
boolean validOrNot = candynameset.containsAll(candylist);
return validOrNot;
}
}
|
package com.ecej.nove.base.locks;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
/**
*
* @author QIANG
*
*/
public class ZkPrimitive {
/**
* 代表一个没有数据的空节点
*/
protected static final byte[] emptyNode = new byte[] {};
/**
* 会话管理
*/
protected final ZkSessionManager zkSessionManager;
/**
* 基础节点
*/
protected final String baseNode;
/**
* ACL 策略
*/
protected final List<ACL> privileges;
/**
* 内部线程锁
*/
protected final Lock localLock;
/**
* 内部锁监视器.
*/
protected final Condition condition;
/**
* 当会话过期时被设置为true,否则为false
*/
protected volatile boolean broken = false;
/**
* 链接监听器
*/
protected final ConnectionListener connectionListener = new PrimitiveConnectionListener(this);
/**
* 监听器用于唤醒线程
*/
protected final Watcher signalWatcher;
/**
* 创建原始信息
*
* @param baseNode
* 根节点
* @param zkSessionManager
* 管理session
* @param privileges
* 节点特性
*/
protected ZkPrimitive(String baseNode, ZkSessionManager zkSessionManager, List<ACL> privileges) {
if (baseNode == null) {
throw new NullPointerException("No base node specified!");
}
this.baseNode = baseNode;
this.zkSessionManager = zkSessionManager;
this.privileges = privileges;
/* 使用公平锁 */
this.localLock = new ReentrantLock(true);
condition = this.localLock.newCondition();
signalWatcher = new SignallingWatcher(this);
ensureNodeExists();
}
/**
* 确保基础节点存在
*/
protected final void ensureNodeExists() {
try {
ZooKeeper zooKeeper = zkSessionManager.getZooKeeper();
Stat stat = zooKeeper.exists(baseNode, false);
if (stat == null) {
zooKeeper.create(baseNode, emptyNode, privileges, CreateMode.PERSISTENT);
}
} catch (KeeperException e) {
// if the node already exists, then we are happy, so ignore those exceptions
if (e.code() != KeeperException.Code.NODEEXISTS) {
throw new RuntimeException(e);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o.getClass() != this.getClass()) {
return false;
}
ZkPrimitive that = (ZkPrimitive) o;
return baseNode.equals(that.baseNode);
}
@Override
public int hashCode() {
return baseNode.hashCode();
}
protected void setConnectionListener() {
zkSessionManager.addConnectionListener(connectionListener);
}
protected void removeConnectionListener() {
zkSessionManager.removeConnectionListener(connectionListener);
}
/**
* 唤醒所有正在等待的线程
*/
protected void notifyParties() {
localLock.lock();
try {
condition.signalAll();
} finally {
localLock.unlock();
}
}
private static class PrimitiveConnectionListener extends ConnectionListenerSkeleton {
private final ZkPrimitive primitive;
private PrimitiveConnectionListener(ZkPrimitive primitive) {
this.primitive = primitive;
}
@Override
public void syncConnected() {
primitive.notifyParties();
}
@Override
public void expired() {
primitive.broken = true;
primitive.notifyParties();
}
}
private static class SignallingWatcher implements Watcher {
private final ZkPrimitive primitive;
private SignallingWatcher(ZkPrimitive primitive) {
this.primitive = primitive;
}
@Override
public void process(WatchedEvent event) {
primitive.notifyParties();
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package se.kth.kthfsdashboard.virtualization;
/**
*
* @author Alberto Lorente Leal <albll@kth.se>
*/
import java.io.Serializable;
import java.util.ArrayList;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
@ManagedBean
@SessionScoped
public class MessageController implements Serializable {
private ArrayList<String> messageStatus = new ArrayList();
private String lastMessage = "Preparing to submit operation";
public void addMessage(String message) {
messageStatus.add(message);
}
public void clearMessages() {
messageStatus.clear();
messageStatus.add("Preparing to submit operation");
}
public String showMessage() {
if (messageStatus.isEmpty()) {
return lastMessage;
} else {
String message = messageStatus.remove(0);
lastMessage = message;
return message;
}
}
public void addErrorMessage(String exception) {
statusMessage(null, FacesMessage.SEVERITY_WARN, "Warning", exception);
}
public void addSuccessMessage(String info) {
statusMessage("success", FacesMessage.SEVERITY_INFO, "Success",info);
}
private void statusMessage(String key, FacesMessage.Severity severity, String message, String detail) {
FacesMessage msg = new FacesMessage(severity, message, detail);
FacesContext.getCurrentInstance().addMessage(key, msg);
}
}
|
package different;
public class BankAccount {
int id;
double balance;
double popolnenieScheta(double sum1){
balance += sum1;
return balance;
}
double spisanieSoScheta(double sum2){
balance -= sum2;
return balance;
}
}
class BankTest{
public static void main(String[]args){
BankAccount b1 = new BankAccount();
b1.balance = 10;
b1.popolnenieScheta(12.3);
System.out.println(b1.balance);
b1.spisanieSoScheta(2.6);
System.out.println(b1.balance);
}
}
|
package imageasgraph;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import javax.imageio.ImageIO;
import mutators.Mutator;
import pixel.PixelAsColors;
import pixel.SimplePixel;
/**
* Represents an image as a Graph of Pixels.
*/
public class SimpleGraphOfPixels extends AbstractGraphOfPixels {
private Node.AbstractNode topLeft;
private int width;
private int height;
SimpleGraphOfPixels() {
this.topLeft = new Node.EmptyNode();
this.width = 0;
this.height = 0;
}
/**
* Asserts that this graph is not empty, and thus operations besides adding an initial node can be
* done on it.
*/
private void assertGraphNotEmpty() {
if (width == 0 && height == 0) {
throw new IllegalArgumentException("Graph is empty");
}
}
@Override
public void writeToFile(OutputType fileType, String fileName) throws IllegalArgumentException {
if (fileType == null || fileName == null) {
throw new IllegalArgumentException("One or both of the arguments is null");
}
switch (fileType) {
case ppm:
this.writePPM(fileName);
break;
case png:
this.writePNG(fileName);
break;
case jpeg:
this.writeJPG(fileName);
break;
default:
throw new IllegalArgumentException("Unsupported fileType");
}
}
/**
* Writes this image as a ppm file to the specified output.
*
* @param fileName The name of the file which will become the output
*/
protected void writePPM(String fileName) {
File output = new File(fileName + ".ppm");
FileWriter writer;
PrintWriter printer = null;
try {
writer = new FileWriter(output);
printer = new PrintWriter(writer);
printer.append("P3\n");
printer.append("# Generated from project\n");
printer.append(this.width + " ");
printer.append(this.height + "\n");
printer.append(PixelAsColors.maxColor + "\n");
for (Node currentNode : this) {
printer.append(currentNode.getRed() + "\n");
printer.append(currentNode.getGreen() + "\n");
printer.append(currentNode.getBlue() + "\n");
}
} catch (IOException e) {
throw new IllegalArgumentException("Invalid file");
} finally {
if (printer != null) {
printer.close();
}
}
}
@Override
public void applyMutator(Mutator mutator) {
this.assertGraphNotEmpty();
if (mutator == null) {
throw new IllegalArgumentException("Null mutator");
}
mutator.apply(this);
}
@Override
public Node getPixelAt(int x, int y) throws IllegalArgumentException {
this.assertGraphNotEmpty();
if (x >= width || y >= height || x < 0 || y < 0) {
throw new IllegalArgumentException("Invalid coordinates");
}
Node toReturn = this.topLeft;
for (int row = 0; row < y; row += 1) {
toReturn = toReturn.getBelow();
}
for (int column = 0; column < x; column += 1) {
toReturn = toReturn.getRight();
}
return toReturn;
}
@Override
public void insertRow(int below) throws IllegalArgumentException {
this.assertGraphNotEmpty();
if (below >= this.height || below < 0) {
throw new IllegalArgumentException("Index not in bounds");
}
Node.AbstractNode currentTop = this.topLeft;
for (int row = 0; row < below; row += 1) {
currentTop = currentTop.getBelowAsUpdatable();
}
Node.AbstractNode currentLeft = new Node.EmptyNode();
PixelAsColors white = new SimplePixel(255, 255, 255);
for (int col = 0; col < this.width; col += 1) {
Node.AbstractNode toAdd = new Node.PixelNode(new SimplePixel(white));
toAdd.updateAbove(currentTop);
toAdd.updateBelow(currentTop.getBelowAsUpdatable());
toAdd.updateLeft(currentLeft);
toAdd.getBelowAsUpdatable().updateAbove(toAdd);
currentTop.updateBelow(toAdd);
currentLeft.updateRight(toAdd);
currentLeft = toAdd;
currentTop = currentTop.getRightAsUpdatable();
}
currentLeft.updateRight(new Node.EmptyNode());
this.height += 1;
}
@Override
public void insertColumn(int after) throws IllegalArgumentException {
this.assertGraphNotEmpty();
if (after >= this.width || after < 0) {
throw new IllegalArgumentException("Index not in bounds");
}
Node.AbstractNode currentLeft = this.topLeft;
for (int col = 0; col < after; col += 1) {
currentLeft = currentLeft.getRightAsUpdatable();
}
Node.AbstractNode currentTop = new Node.EmptyNode();
PixelAsColors white = new SimplePixel(255, 255, 255);
for (int row = 0; row < this.height; row += 1) {
Node.AbstractNode toAdd = new Node.PixelNode(new SimplePixel(white));
toAdd.updateAbove(currentTop);
toAdd.updateLeft(currentLeft);
toAdd.updateRight(currentLeft.getRightAsUpdatable());
toAdd.getRightAsUpdatable().updateLeft(toAdd);
currentTop.updateBelow(toAdd);
currentLeft.updateRight(toAdd);
currentLeft = currentLeft.getBelowAsUpdatable();
currentTop = toAdd;
}
currentTop.updateBelow(new Node.EmptyNode());
this.width += 1;
}
@Override
void addFirstNode(Node.AbstractNode n) throws IllegalArgumentException {
if (n.equals(new Node.EmptyNode())) {
throw new IllegalArgumentException("Starting node cannot be empty");
}
if (width != 0 || height != 0) {
throw new IllegalArgumentException("This graph already has a starting node");
}
this.topLeft = n;
this.width = 1;
this.height = 1;
}
@Override
public int getHeight() {
return height;
}
@Override
public int getWidth() {
return width;
}
@Override
public Iterator<Node> iterator() {
return new GraphIterator(this.topLeft);
}
/**
* Writes this Graph as a PNG image file with the given string as it's name.
*
* @param fileName The name of the image file to be created
* @throws IllegalArgumentException If the name given is null
*/
protected void writePNG(String fileName) throws IllegalArgumentException {
if (fileName == null) {
throw new IllegalArgumentException("Null fileName");
}
BufferedImage toReturn = this.createBufferedImageForOutPut();
File outPut = new File(fileName + ".png");
try {
ImageIO.write(toReturn, "png", outPut);
} catch (IOException e) {
throw new IllegalArgumentException("Could not write to file");
}
}
/**
* Writes this Graph as a JPG image file with the given string as it's name.
*
* @param fileName The name of the image file to be created
* @throws IllegalArgumentException If the name given is null
*/
protected void writeJPG(String fileName) throws IllegalArgumentException {
if (fileName == null) {
throw new IllegalArgumentException("Null fileName");
}
BufferedImage toReturn = this.createBufferedImageNoAlpha();
File outPut = new File(fileName + ".jpeg");
try {
ImageIO.write(toReturn, "jpeg", outPut);
} catch (IOException e) {
throw new IllegalArgumentException("Could not write to file");
}
}
/**
* Creates a buffered image which represents the image that this graph does, with all the ARGB
* values copied over.
*
* @return The buffered image representation
*/
protected BufferedImage createBufferedImageForOutPut() {
BufferedImage toReturn = new BufferedImage(this.getWidth(), this.getHeight(),
BufferedImage.TYPE_INT_ARGB);
int col = 0;
int row = 0;
for (Node n : this) {
int rgb = (n.getOpacity() << 24 | n.getRed() << 16 | n.getGreen() << 8 | n.getBlue());
toReturn.setRGB(col, row, rgb);
col += 1;
if (col == this.getWidth()) {
col = 0;
row += 1;
}
}
return toReturn;
}
/**
* Creates a buffered image which represents the image that this graph does, with all the RGB
* values copied over.
*
* @return The buffered image representation
*/
protected BufferedImage createBufferedImageNoAlpha() {
BufferedImage toReturn = new BufferedImage(this.getWidth(), this.getHeight(),
BufferedImage.TYPE_INT_RGB);
int col = 0;
int row = 0;
for (Node n : this) {
int rgb = (n.getRed() << 16 | n.getGreen() << 8 | n.getBlue());
toReturn.setRGB(col, row, rgb);
col += 1;
if (col == this.getWidth()) {
col = 0;
row += 1;
}
}
return toReturn;
}
}
|
/*
* 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 Module;
/**
*
* @author LENOVO
*/
public class SessionLogin {
private static String idUser;
private static String nama;
private static String level;
private static String username;
private static String password;
private static String telepon;
private static String alamat;
private static String refresh = "false";
/**
* @return the idUser
*/
public static String getIdUser() {
return idUser;
}
/**
* @param aIdUser the idUser to set
*/
public static void setIdUser(String aIdUser) {
idUser = aIdUser;
}
/**
* @return the nama
*/
public static String getNama() {
return nama;
}
/**
* @param aNama the nama to set
*/
public static void setNama(String aNama) {
nama = aNama;
}
/**
* @return the level
*/
public static String getLevel() {
return level;
}
/**
* @param aLevel the level to set
*/
public static void setLevel(String aLevel) {
level = aLevel;
}
/**
* @return the username
*/
public static String getUsername() {
return username;
}
/**
* @param aUsername the username to set
*/
public static void setUsername(String aUsername) {
username = aUsername;
}
/**
* @return the refresh
*/
public static String getRefresh() {
return refresh;
}
/**
* @param aRefresh the refresh to set
*/
public static void setRefresh(String aRefresh) {
refresh = aRefresh;
}
/**
* @return the alamat
*/
public static String getAlamat() {
return alamat;
}
/**
* @param aAlamat the alamat to set
*/
public static void setAlamat(String aAlamat) {
alamat = aAlamat;
}
/**
* @return the password
*/
public static String getPassword() {
return password;
}
/**
* @param aPassword the password to set
*/
public static void setPassword(String aPassword) {
password = aPassword;
}
/**
* @return the telepon
*/
public static String getTelepon() {
return telepon;
}
/**
* @param aTelepon the telepon to set
*/
public static void setTelepon(String aTelepon) {
telepon = aTelepon;
}
}
|
package com.microsoft.hsg.android.hvsample;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.util.LruCache;
import android.widget.ImageView;
import android.widget.Toast;
import com.microsoft.hsg.HVException;
import com.microsoft.hsg.android.simplexml.HealthVaultApp;
import com.microsoft.hsg.android.simplexml.client.HealthVaultClient;
import com.microsoft.hsg.android.simplexml.client.RequestCallback;
import com.microsoft.hsg.android.simplexml.methods.getthings3.request.ThingRequestGroup2;
import com.microsoft.hsg.android.simplexml.methods.getthings3.response.ThingResponseGroup2;
import com.microsoft.hsg.android.simplexml.things.thing.Thing2;
import com.microsoft.hsg.android.simplexml.things.types.personalimage.PersonalImage;
import com.microsoft.hsg.android.simplexml.things.types.types.Record;
public class PersonalImageLoader implements ComponentCallbacks2 {
private ImageLruCache mCache;
private HealthVaultClient mHVClient;
private Activity mContext;
public PersonalImageLoader(Activity context,
HealthVaultClient client) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
int memSize = activityManager.getMemoryClass() * 1024 * 1024;
mCache = new ImageLruCache(memSize);
mHVClient = client;
mContext = context;
}
public void load(String id, ImageView imageView, int defaultResource) {
imageView.setImageResource(defaultResource);
Bitmap image = mCache.get(id);
if (image != null) {
imageView.setImageBitmap(image);
} else {
List<Record> records = HealthVaultApp.getInstance().getRecordList();
Record record = null;
for(Record rcd : records) {
if(Objects.equals(id, rcd.getId())) {
record = rcd;
break;
}
}
mHVClient.asyncRequest(getImageAsync(record), new PersonalImageCallback(id, imageView));
}
}
private Callable<Bitmap> getImageAsync(final Record record) {
return new Callable<Bitmap>() {
public Bitmap call() throws URISyntaxException, IOException {
// check if it exist in file
File cacheDir = mContext.getCacheDir();
if(!cacheDir.exists()) {
cacheDir.mkdirs();
}
File file = new File(cacheDir, "personalimage" + record.getId());
if(file.exists()) {
try(FileInputStream in = new FileInputStream(file)) {
return BitmapFactory.decodeStream(in);
}
}
// try to get from web
ThingResponseGroup2 response = record.getThings(ThingRequestGroup2.thingTypeQuery(PersonalImage.ThingType));
List<Thing2> things = response.getThing();
if(things != null && !things.isEmpty()) {
Thing2 thing = things.get(0);
PersonalImage image = (PersonalImage)thing.getData();
FileOutputStream destination = null;
FileInputStream inputStream = null;
Bitmap bitmap;
try {
destination = new FileOutputStream(file);
image.download(record, destination);
inputStream = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (destination != null) {
destination.close();
}
if (inputStream != null) {
inputStream.close();
}
}
}
return null;
}
};
}
@Override
public void onConfigurationChanged(Configuration arg0) {
// TODO Auto-generated method stub
}
@Override
public void onLowMemory() {
// TODO Auto-generated method stub
}
@Override
public void onTrimMemory(int level) {
if (level >= TRIM_MEMORY_MODERATE) {
mCache.evictAll();
} else if (level >= TRIM_MEMORY_BACKGROUND) {
mCache.trimToSize(mCache.size() / 2);
}
}
private class ImageLruCache extends LruCache<String, Bitmap> {
public ImageLruCache(int maxSize) {
super(maxSize);
}
}
private class PersonalImageCallback implements RequestCallback<Bitmap> {
private ImageView mImageView;
private String mId;
public PersonalImageCallback(String id, ImageView imageView) {
mId = id;
mImageView = imageView;
}
@Override
public void onError(HVException exception) {
Toast.makeText(
mContext, "An error occurred. " + exception.getMessage(), Toast.LENGTH_LONG).show();
}
@Override
public void onSuccess(Bitmap image) {
if(image != null) {
mCache.put(mId, image);
mImageView.setImageBitmap(image);
}
}
}
}
|
class A {
public static void main(String[] a){
String[]m={"一","二","三","四","五","六","七","八","九","十"};
for(int i=-1;i++<9;System.out.println("高橋"+m[i]+"郎"));}}
|
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.LinkedList;
import javax.swing.JTextField;
public class Board {
private Square[][] table;
private Row[] rows;
private Column[] cols;
private Box[][] boxes;
private Square nextSquare;
private int dimension, boxH, boxW;
private SudokuContainer sudokucont;
public SudokuGUI gui;
public Board(int dimension, int boxH, int boxW, boolean showGUI) throws Exception{
if((dimension % boxW) != 0 || (dimension % boxH) != 0 || boxW >= dimension || boxH >= dimension || (boxH * boxW) != dimension){
throw new Exception();
}
this.dimension = dimension;
this.boxH = boxH;
this.boxW = boxW;
this.nextSquare = null;
sudokucont = new SudokuContainer();
rows = new Row[dimension];
cols = new Column[dimension];
boxes = new Box[boxW][boxH];
table = new Square[dimension][dimension];
for(int i = 0; i < dimension; i++){
for(int j = 0; j < dimension; j++){
rows[i] = new Row(dimension);
rows[i].index = i;
cols[j] = new Column(dimension);
cols[j].index = j;
boxes[i/boxH][j/boxW] = new Box(dimension, boxH, boxW);
boxes[i/boxH][j/boxW].indexX = i/boxH;
boxes[i/boxH][j/boxW].indexY = j/boxW;
}
}
}
public Square[][] getTable(){
return table;
}
public void setTable(Square [][] s){
table = s;
}
public Square getFirst(){
return table[0][0];
}
public SudokuContainer getContainer(){
return sudokucont;
}
public int getBoxW(){
return boxW;
}
public int getBoxH(){
return boxH;
}
public int getDimension(){
return dimension;
}
public Row[] getRows() {
return rows;
}
public void setRows(Row[] rows) {
this.rows = rows;
}
public Column[] getCols() {
return cols;
}
public void setCols(Column[] cols) {
this.cols = cols;
}
public Box[][] getBoxes() {
return boxes;
}
public void setBoxes(Box[][] boxes) {
this.boxes = boxes;
}
public void saveSolution() {
int[][] savesol = new int[dimension][dimension];
for(int i = 0; i < dimension; i++){
for(int j = 0; j < dimension; j++){
savesol[i][j] = table[i][j].getValue();
}
}
sudokucont.addSolution(savesol);
}
public Square nextSquare(Square currentSquare) {
for(int i = 0; i < table.length; i++){
for(int j = 0; j < table.length; j++){
Square sq = table[i][j];
if(sq == currentSquare){
if(i < table.length - 1 && j == table.length - 1){
nextSquare = table[i+1][0];
}
else if(i == table.length - 1 && j == table.length - 1){
nextSquare = null;
}
else{
nextSquare = table[i][j+1];
}
}
}
}
return nextSquare;
}
public void writeSolutionToFile(File file){
int counter = 1;
LinkedList<int[][]> save = sudokucont.getSolutions();
Iterator<int[][]> it = save.iterator();
try{
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
while(it.hasNext() && counter < 501){
int[][] sol = it.next();
bw.write("Solution NO. " +counter + ": ");
for(int i = 0; i < sol.length; i++){
for(int j = 0; j < sol.length; j++){
bw.write(sol[i][j]);
if(j == sol.length-1){
bw.write("// ");
}
}
}
bw.newLine();
counter++;
}
bw.close();
}
catch(Exception e){
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Wrapper;
import Master.*;
import java.io.IOException;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import javax.jws.WebService;
import javax.jws.WebMethod;
/**
*
* @author Admin
*/
@WebService(serviceName = "Wrapper")
public class Wrapper {
private static int usersNumber = 4;
private Master master = Master.getInstance();
private PassFileOpener passFileOpener = PassFileOpener.getInstance();
private static final Logger logger = Logger.getLogger("DPCLogger");
private static int timesCalled = 0;
/**
* Sends parts of the dictionary to clients.
*
* @throws IOException
*/
@WebMethod(operationName = "getDictionaryPart")
public List<String> getDictionaryPart() throws IOException {
return master.getDictionary(usersNumber);
}
/**
* Sends the password file to clients.
*
* @throws IOException
*/
@WebMethod(operationName = "getPasswordFile")
public List<String> getPasswordFile() throws IOException {
return passFileOpener.getPassFile();
}
/**
* Logs the cracked passwords.
*
* @param list A list of cracked passwords sent from the clients
* @throws IOException
*/
@WebMethod(operationName = "sendCracked")
public void sendCracked(List<String> list) throws IOException {
timesCalled++;
if (timesCalled == 1) {
setLogger();
}
for (int i = 0; i < list.size(); i++) {
logger.info(list.get(i));
}
}
private void setLogger() throws IOException {
FileHandler handler = new FileHandler("C:\\DPC_Log.txt");
handler.setFormatter(new MyFormatter());
logger.addHandler(handler);
}
}
|
package com.roundarch.entity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.validation.constraints.NotNull;
import org.springframework.data.annotation.Transient;
import com.annconia.api.entity.AbstractEntity;
import com.annconia.api.entity.DeleteArchive;
public class RecruitEntity extends AbstractEntity implements DeleteArchive {
@NotNull
private String firstName;
@NotNull
private String lastName;
private String email;
private String mobileNumber;
private String homeNumber;
private Address currentAddress = new Address();
private Address hometown;
private double bucketScore;
private String favoriteBook;
private String favoriteMovie;
private String favoriteBlog;
private String favoriteWebsite;
private String favoritePublication;
private String favoriteTravelDestination;
private String socialOrganization;
private String foreignLanguage;
private String musicalInstrument;
@NotNull
private RecruitStage stage = RecruitStage.NOT_STAGED;
private Date stageDate;
private List<String> foreignLanguages;
private ArrayList<SchoolDetail> education = new ArrayList<SchoolDetail>();
private ArrayList<WorkDetail> work = new ArrayList<WorkDetail>();
@Transient
private List<DocumentMetadataEntity> documents;
@Transient
private List<ReviewEntity> reviews;
@Transient
private List<ActivityEntity> activities;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getHomeNumber() {
return homeNumber;
}
public void setHomeNumber(String homeNumber) {
this.homeNumber = homeNumber;
}
public Address getCurrentAddress() {
return currentAddress;
}
public void setCurrentAddress(Address currentAddress) {
this.currentAddress = currentAddress;
}
public Address getHometown() {
return hometown;
}
public void setHometown(Address hometown) {
this.hometown = hometown;
}
public double getBucketScore() {
return bucketScore;
}
public void setBucketScore(double bucketScore) {
this.bucketScore = bucketScore;
}
public List<String> getForeignLanguages() {
return foreignLanguages;
}
public void setForeignLanguages(List<String> foreignLanguages) {
this.foreignLanguages = foreignLanguages;
}
public RecruitStage getStage() {
return stage;
}
public void setStage(RecruitStage stage) {
if (stage != null) {
this.stage = stage;
}
}
public ArrayList<SchoolDetail> getEducation() {
return education;
}
public void setEducation(ArrayList<SchoolDetail> education) {
this.education = education;
}
public ArrayList<WorkDetail> getWork() {
return work;
}
public void setWork(ArrayList<WorkDetail> work) {
this.work = work;
}
public String getFavoriteBook() {
return favoriteBook;
}
public void setFavoriteBook(String favoriteBook) {
this.favoriteBook = favoriteBook;
}
public String getFavoriteMovie() {
return favoriteMovie;
}
public void setFavoriteMovie(String favoriteMovie) {
this.favoriteMovie = favoriteMovie;
}
public String getFavoriteBlog() {
return favoriteBlog;
}
public void setFavoriteBlog(String favoriteBlog) {
this.favoriteBlog = favoriteBlog;
}
public String getFavoriteWebsite() {
return favoriteWebsite;
}
public void setFavoriteWebsite(String favoriteWebsite) {
this.favoriteWebsite = favoriteWebsite;
}
public String getFavoritePublication() {
return favoritePublication;
}
public void setFavoritePublication(String favoritePublication) {
this.favoritePublication = favoritePublication;
}
public String getFavoriteTravelDestination() {
return favoriteTravelDestination;
}
public void setFavoriteTravelDestination(String favoriteTravelDestination) {
this.favoriteTravelDestination = favoriteTravelDestination;
}
public String getSocialOrganization() {
return socialOrganization;
}
public void setSocialOrganization(String socialOrganization) {
this.socialOrganization = socialOrganization;
}
public String getForeignLanguage() {
return foreignLanguage;
}
public void setForeignLanguage(String foreignLanguage) {
this.foreignLanguage = foreignLanguage;
}
public String getMusicalInstrument() {
return musicalInstrument;
}
public void setMusicalInstrument(String musicalInstrument) {
this.musicalInstrument = musicalInstrument;
}
public List<DocumentMetadataEntity> getDocuments() {
return documents;
}
public void setDocuments(List<DocumentMetadataEntity> documents) {
this.documents = documents;
}
public List<ReviewEntity> getReviews() {
return reviews;
}
public void setReviews(List<ReviewEntity> reviews) {
this.reviews = reviews;
}
public List<ActivityEntity> getActivities() {
return activities;
}
public void setActivities(List<ActivityEntity> activities) {
this.activities = activities;
}
@Override
public void storePreviousValues() {
addPreviousValue("education", getEducation());
addPreviousValue("work", getWork());
addPreviousValue("stage", getStage().name());
}
}
|
package com.meetingapp.android.rest.api;
import com.meetingapp.android.model.CountryCodeWithIP;
import io.reactivex.Observable;
import retrofit2.Call;
import retrofit2.http.GET;
/**
* This class used to define the web operations
*/
public interface ApiInterface {
@GET("/json")
Observable<CountryCodeWithIP> getCountryCodeWithIP();
}
|
package com.intentsg.service.user.repository;
import com.intentsg.service.user.model.User;
import com.intentsg.service.user.service.UserService;
import org.junit.After;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.transaction.annotation.Transactional;
import static org.junit.jupiter.api.Assertions.*;
@DataJpaTest
@Transactional
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class UserRepositoryTest {
@Autowired
private UserRepository subject;
@Test
public void changeUserBalanceDBTest() throws Exception {
User peter = new User("bodya", "111", "41", 1000);
subject.save(peter);
subject.changeUserBalanceDB("41", 100);
User changedPeter = subject.getOne("41");
assertEquals(changedPeter.getBalance(), 100);
}
}
|
package fr.unice.polytech.isa.polyevent;
import fr.unice.polytech.isa.polyevent.entities.Organisateur;
import fr.unice.polytech.isa.polyevent.entities.outils.Signal;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import java.io.Serializable;
import java.util.Optional;
@ManagedBean
@SessionScoped
public class OrganisateurBean implements Serializable {
private String mail;
private Organisateur organisateur;
@EJB
private transient TrouverOrganisateur trouverOrganisateur;
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public Organisateur getOrganisateur() {
return organisateur;
}
public void setOrganisateur(Organisateur organisateur) {
this.organisateur = organisateur;
}
// Invoked when the "Select" button is pushed
public String select() {
Optional<Organisateur> optional = trouverOrganisateur.connexion(mail);
if (optional.isPresent()) {
organisateur = optional.get();
return Signal.SELECTIONNE;
} else {
FacesContext.getCurrentInstance()
.addMessage("form-error", new FacesMessage("Client inconnu: " + getMail()));
return Signal.INCONNU;
}
}
}
|
package com.containers.repository;
import com.containers.model.Report;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Set;
public interface ReportRepository extends JpaRepository<Report, Long> {
// @Query("SELECT cr FROM Report cr WHERE cr.container.containerIdNumber = :containerIdNumber")
// Set<Report> fetchContainerReportsByContainerId(@Param("containerIdNumber") String containerIdNumber);
Set<Report> findByContainer_ContainerIdNumber(String containerIdNumber);
}
|
package dao;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import entities.Flight;
public class FlightDAO extends GenericDAO<Flight>{
public FlightDAO () {
super(Flight.class);
}
public List<Flight> findAll () {
List<Flight> flights = new ArrayList<>();
EntityManager em = DatabaseHelper.createEntityManager();
DatabaseHelper.beginTx(em);
TypedQuery<Flight> query = em.createQuery(
"select f "
+ "from Flight f "
+ "left join fetch f.bookings bookings", Flight.class);
flights = query.getResultList();
DatabaseHelper.commitTxAndClose(em);
return flights;
}
public List<Flight> findByCities (String takeoffCity, String landingCity) {
List<Flight> flights = new ArrayList<>();
EntityManager em = DatabaseHelper.createEntityManager();
DatabaseHelper.beginTx(em);
TypedQuery<Flight> query = em.createQuery(
"select f "
+ "from Flight f "
+ "left join fetch f.bookings b "
+ "where takeoffCity = :tc and landingCity = :lc", Flight.class);
query.setParameter("tc", takeoffCity);
query.setParameter("lc", landingCity);
flights = query.getResultList();
DatabaseHelper.commitTxAndClose(em);
return flights;
}
public Flight findByFlightNumber (String flightNumber) {
Flight flight;
EntityManager em = DatabaseHelper.createEntityManager();
DatabaseHelper.beginTx(em);
TypedQuery<Flight> query = em.createQuery(
"select f "
+ "from Flight f "
+ "left join fetch f.bookings b "
+ "where f.flightNumber = :fn", Flight.class);
query.setParameter("fn", flightNumber);
flight = query.getSingleResult();
DatabaseHelper.commitTxAndClose(em);
return flight;
}
}
|
package com.wdl.service.impl.rbac;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.wdl.base.service.impl.BaseServiceImpl;
import com.wdl.util.EncoderHandler;
import com.wdl.dao.rbac.RoleDao;
import com.wdl.dao.rbac.UserDao;
import com.wdl.dao.rbac.UserRoleDao;
import com.wdl.entity.rbac.RoleEntity;
import com.wdl.entity.rbac.UserEntity;
import com.wdl.entity.rbac.UserRoleEntity;
import com.wdl.service.rbac.UserService;
@Service("userService")
public class UserServiceImpl extends BaseServiceImpl implements UserService {
@Resource
private UserDao userDao;
@Resource
private RoleDao roleDao;
@Resource
private UserRoleDao userRoleDao;
@SuppressWarnings("rawtypes")
@Override
public Set<String> getRoleNameSetByUserId(Long userId) {
String hql = "select r.name as roleName from RoleEntity r, UserRoleEntity ur where r.id=ur.roleId and ur.userId ="
+ userId;
List<Map> list = userRoleDao.findMap(hql);
Set<String> roleNames = new HashSet<String>();
for (Map map : list) {
roleNames.add((String) map.get("roleName"));
}
return roleNames;
}
public List<RoleEntity> findUserRoleChacks(Long userId) {
List<RoleEntity> rlist = new ArrayList<RoleEntity>();
rlist = roleDao.findRoleIsDel();
List<UserRoleEntity> uList = new ArrayList<UserRoleEntity>();
uList = userRoleDao.findUserRoleByUserId(userId);
for (UserRoleEntity userRoleEntity : uList) {
for (RoleEntity roleEntity : rlist) {
if (userRoleEntity.getRoleId().equals(roleEntity.getId())) {
roleEntity.setIsChack(1); // 选中
} else {
if (roleEntity.getIsChack() != 1) {
roleEntity.setIsChack(0); // 未选中
}
}
}
}
return rlist;
}
public String saveOrUpdateUser(UserEntity userEntity) {
if (!checkExist(userEntity.getId(), userEntity.getLoginName())) {
UserEntity entity = null;
if (userEntity.getId() != null) {
entity = userDao.get(UserEntity.class, userEntity.getId());
} else {
entity = new UserEntity();
entity.setCountMistake(0);
entity.setPassWord(EncoderHandler.encode("SHA1", "Experian123."));
}
BeanUtils.copyProperties(userEntity, entity, new String[] { "version", "createDateTime", "countMistake",
"countMistakeTime", "validataCode", "outDate", "passWord" });
entity.setUpdateDateTime(new Date());
saveOrUpdate(entity);
return "01";
} else {
return "02";// 用户重复
}
}
private boolean checkExist(Long id, String loginName) {
Map<String, Object> param = new HashMap<String, Object>();
StringBuffer hql = new StringBuffer("select count(1) from UserEntity u where 1=1 ");
if (loginName != null) {
hql.append(" and u.loginName=:loginName");
param.put("loginName", loginName);
}
if (id != null) {
hql.append(" and u.id!=:id");
param.put("id", id);
}
Long count = count(hql.toString(), param);
if (count != null && count > 0) {
return true;
}
return false;
}
@Override
public UserEntity findUserByloginName(String loginName) {
return userDao.findUserByloginName(loginName);
}
@Override
public UserEntity chackEmain(String validataCode, String id) {
return userDao.chackEmain(validataCode, id);
}
@Override
public List<UserEntity> findByIsDel(Integer del) {
return userDao.findByIsDel(del);
}
@Override
public UserEntity findUserLoginAndPasword(String LoginName, String password) {
return userDao.findUserLoginAndPasword(LoginName, password);
}
}
|
package ar.edu.unlam.pb1.tp06.dominio;
/* 4. Desarrolla la clase PruebaEstadisticasDePersonas, cuyo objetivo es ingresar una muestra
de 50 personas y se calcule el:
a. El peso promedio
b. Cantidad de personas con bajo peso
c. Cantidad de personas con peso normal
d. Cantidad de personas con sobre peso
e. Promedio de edad de las personas con bajo peso
f. Promedio de edad de las personas con sobre peso
Tené en cuenta que este programa de prueba, luego deberá reutilizarse para ingresar
valores reales. Desarrollá los métodos de forma tal que te permita reutilizarlo.
*/
public class Estadistica {
/* Atributos propios de la clase que reflejan el estado de la clase Persona */
private int cantidadPersonas = 0;
private double peso;
private int edad;
private double pesoPromedio;
private double edadPromedioBajoPeso;
private double edadPromedioSobrePeso;
/*Constructor: * En el constructor le asignamos valores a los atributos de ese objeto y los inicializamos */
public Estadistica(int cantidadPersonas) {
this.cantidadPersonas = cantidadPersonas;
this.peso = 0.0;
this.edad = 0;
this.pesoPromedio = 0.0;
this.edadPromedioBajoPeso = 0.0;
this.edadPromedioSobrePeso = 0.0;
} // end constructor
/* Métodos */
public double calcularPesoPromedio(double pesoPromedio) {
this.peso = pesoPromedio;
pesoPromedio = peso / cantidadPersonas;
return pesoPromedio;
} // end calcularPesoPromedio
public double calcularPromedioPersonasEdadBajoPeso(int edadPersonasBajoPeso, int cantidadPersonasBajoPeso) {
edadPromedioBajoPeso = edadPersonasBajoPeso / cantidadPersonasBajoPeso;
return edadPromedioBajoPeso;
} // end calcularPromedioPersonasEdadBajoPeso
public double calcularPromedioPersonasEdadSobrePeso(int edadPersonasSobrePeso, int cantidadPersonasSobrePeso) {
edadPromedioSobrePeso = edadPersonasSobrePeso / cantidadPersonasSobrePeso;
return edadPromedioSobrePeso;
} // end calcularPromedioPersonasEdadSobrePeso
} // end Estadistica
|
package com.sdz.animal;
public class Chien extends Canin implements Rintintin // class fille de Canin
{
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// CONSTRUCTEURS
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
public Chien()
{
super();
}
public Chien(String couleur, int poids)
{
super(couleur, poids);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// METHODES ABSTRAITE
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@Override
public void crier()
{
System.out.println("J'aboie sans raison !");
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// METHODES INTERFACE
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@Override
public void faireLechouille()
{
System.out.println("Je fais de GROSSE LECHOUILLE");
}
@Override
public void faireCalin()
{
System.out.println("Je fais un GROS CALIN");
}
@Override
public void faireLeBeau()
{
System.out.println("Je fais le beau");
}
}
|
package uk.ac.ebi.intact.view.webapp.controller.search.facet;
import org.apache.solr.client.solrj.response.FacetField;
/**
* Count negative interactions
*
* @author Marine Dumousseau (marine@ebi.ac.uk)
* @version $Id$
* @since <pre>18/09/12</pre>
*/
public class NegativeCount extends AbstractCount {
public NegativeCount(FacetField facetField) {
super(facetField);
}
public long getNegativeCount() {
return getCount("true");
}
public long getPhysicalCount() {
return getCount("false");
}
}
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.utils.staterestapi.requests;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.errors.InvalidContentException;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitState;
import java.util.Map;
public interface SetUnitStateRequest extends UnitRequest {
Map<String, UnitState> getNewState();
enum Condition {
FORCE(1), // Don't check for any condition before setting unit state
SAFE(2); // Only set condition if it is deemed safe (e.g. redundancy is still ok during upgrade)
public final int value;
private Condition(int value) {
this.value = value;
}
public static Condition fromString(String value) throws InvalidContentException {
try {
return Condition.valueOf(value.toUpperCase());
} catch (IllegalArgumentException e) {
throw new InvalidContentException("Invalid value for my enum Condition: " + value);
}
}
}
Condition getCondition();
}
|
package com.xxx.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
@Controller
public class ThymeleafController {
/**
* 注意 这里不能用restcontroller,因为加了ResponseBody会导致
* 返回的字符串写入Response中,所以返回的不是界面了
* @return
*/
@RequestMapping("/themeleaf")
public String success(HashMap<String, Object> map) {
map.put("Hello", "nihao");
return "success";
}
}
|
public class TaroFillingAStringDiv2 {
private boolean[][] seen;
private int[][] results;
private String S;
public int getNumber(String S) {
this.S = S;
seen = new boolean[S.length()][3];
results = new int[S.length()][3];
return solve(0, 2);
}
private int solve(int index, int prev) {
if(index == S.length()) {
return 0;
}
if(seen[index][prev]) {
return results[index][prev];
}
int current = S.charAt(index) - 'A';
int result;
if(current < 0 || 1 < current) {
result = Integer.MAX_VALUE;
for(int i = 0; i < 2; ++i) {
if(i == prev) {
result = Math.min(result, 1 + solve(index + 1, i));
} else {
result = Math.min(result, solve(index + 1, i));
}
}
} else {
result = 0;
if(prev == current) {
++result;
}
result += solve(index + 1, current);
}
seen[index][prev] = true;
results[index][prev] = result;
return result;
}
}
|
package com.jixin;
public class Current {
public void use220V() {
System.out.println("使用220V电压");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.