text
stringlengths
10
2.72M
package com.meizu.scriptkeeper.services; import android.app.Service; import android.content.Intent; import android.os.IBinder; import com.meizu.scriptkeeper.preferences.SchedulePreference; import com.meizu.scriptkeeper.schedule.ScheduleControl; import com.meizu.scriptkeeper.schedule.monkey.MonkeyError; import com.meizu.scriptkeeper.services.scriptkeeper.LifeKeeperService; import com.meizu.scriptkeeper.utils.Log; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; /** * Author: liyong1 * Date: 2015/6/1 */ public class ApplicationLogService extends Service { private static final String TAG = "DropFrame"; private static final String BEGIN_DROP_FRAME = "DropFrame count begin"; public static String processId = ""; private SchedulePreference pref_schedule; private File logFile; Process p; int pid; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); this.pref_schedule = new SchedulePreference(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { String log_dir = pref_schedule.getLogPath(); logFile = new File(log_dir + "global.log"); try { if (!logFile.exists()) { logFile.createNewFile(); } new Thread(new Runnable() { @Override public void run() { logRecord(); } }).start(); } catch (IOException e) { e.printStackTrace(); } return super.onStartCommand(intent, flags, startId); } public void onDestroy() { super.onDestroy(); try { Log.i("Logcat pid (" + pid +") would be killed, check if you don't believe it."); if (pid != 0) { Runtime.getRuntime().exec("kill " + pid); } } catch (IOException e) { e.printStackTrace(); } } public void logRecord() { FileWriter fw = null; BufferedWriter bw = null; try { String packageName = getPackageName(pref_schedule.getModule()); String[] command = {"system/bin/sh", "-c", "logcat -v time"}; p = Runtime.getRuntime().exec(command); pid = Integer.parseInt(p.toString().split("=")[1].split("]")[0].trim()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; fw = new FileWriter(logFile, true); bw = new BufferedWriter(fw); while (pref_schedule.isLogging() && (line = bufferedReader.readLine()) != null) { if (((!"0".equals(processId)) && line.contains(processId)) || line.contains(TAG)) { try { bw.write(line); bw.newLine(); if(line.contains(BEGIN_DROP_FRAME) && line.contains(packageName)){ LifeKeeperService.scriptkeeper.addMonkeyError(MonkeyError.INT_LOSE_FRAME); } }catch (Exception e){ e.printStackTrace(); } } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (bw != null) { bw.close(); } if (fw != null) { fw.close(); } p.waitFor(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } public String getPackageName(String module){ ScheduleControl control = new ScheduleControl(this); return control.getStringFromModule("app_name", module); } }
package com.pattern.observe.p2pcase.asynbuild; import com.pattern.observe.p2pcase.UserService; import com.pattern.observe.p2pcase.rebuild.RegObserver; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; public class UserController { private UserService userService; private List<RegObserver> regObservers = new ArrayList<>(); private Executor executor; public UserController(Executor executor){ this.executor = executor; } //一次性设置好,之后也不可能动态的修改 public void setRegObservers(List<RegObserver> observers){ regObservers.addAll(observers); } public Long register(String telephone,String password){ //省略输入参数的校验代码 //省略userService.register()异常的try-catch代码 long userId = userService.register(telephone,password); for (RegObserver observer:regObservers) { executor.execute(new Runnable() { @Override public void run() { observer.handRegSuccess(userId); } }); } return userId; } }
// Generated code from Butter Knife. Do not modify! package com.zhicai.byteera.activity.message; import android.view.View; import butterknife.ButterKnife.Finder; import butterknife.ButterKnife.ViewBinder; public class SelectAddressActivity$$ViewBinder<T extends com.zhicai.byteera.activity.message.SelectAddressActivity> implements ViewBinder<T> { @Override public void bind(final Finder finder, final T target, Object source) { View view; view = finder.findRequiredView(source, 2131427460, "field 'mHeadView'"); target.mHeadView = finder.castView(view, 2131427460, "field 'mHeadView'"); view = finder.findRequiredView(source, 2131427573, "field 'mListView'"); target.mListView = finder.castView(view, 2131427573, "field 'mListView'"); view = finder.findRequiredView(source, 2131427623, "field 'mLoadingPage'"); target.mLoadingPage = finder.castView(view, 2131427623, "field 'mLoadingPage'"); view = finder.findRequiredView(source, 2131427477, "field 'rlBottom'"); target.rlBottom = finder.castView(view, 2131427477, "field 'rlBottom'"); view = finder.findRequiredView(source, 2131427723, "field 'mRightLetter'"); target.mRightLetter = finder.castView(view, 2131427723, "field 'mRightLetter'"); view = finder.findRequiredView(source, 2131427721, "field 'tvMidLetter'"); target.tvMidLetter = finder.castView(view, 2131427721, "field 'tvMidLetter'"); view = finder.findRequiredView(source, 2131427810, "method 'clickListener'"); view.setOnClickListener( new butterknife.internal.DebouncingOnClickListener() { @Override public void doClick( android.view.View p0 ) { target.clickListener(p0); } }); view = finder.findRequiredView(source, 2131427935, "method 'clickListener'"); view.setOnClickListener( new butterknife.internal.DebouncingOnClickListener() { @Override public void doClick( android.view.View p0 ) { target.clickListener(p0); } }); view = finder.findRequiredView(source, 2131428183, "method 'clickListener'"); view.setOnClickListener( new butterknife.internal.DebouncingOnClickListener() { @Override public void doClick( android.view.View p0 ) { target.clickListener(p0); } }); } @Override public void unbind(T target) { target.mHeadView = null; target.mListView = null; target.mLoadingPage = null; target.rlBottom = null; target.mRightLetter = null; target.tvMidLetter = null; } }
package com.enesmumu.nba.base; /** * @author 作者:BoXuelin * @date 创建时间:2017年10月18日 * @version 1.0 */ public class Constant { public static String SUCCESS = "SUCCESS";// 成功 public static String FAILED = "FAILED";// 失败 public static String ERROR = "ERROR";// 异常 }
package atcoder.arc026; import java.util.Arrays; import java.util.Comparator; public class ARC026C { public static void main(String[] args) { new ARC026C().solve(5, new Light[] { // new Light(0, 1, 1), // new Light(1, 2, 1), // new Light(2, 4, 3), // new Light(3, 5, 1), // new Light(2, 3, 2) // }); new ARC026C().solve(10, new Light[] { // new Light(0, 1, 1), // new Light(1, 2, 1), // new Light(2, 3, 1), // new Light(3, 4, 1), // new Light(4, 5, 1), // new Light(0, 5, 4), // new Light(5, 7, 2), // new Light(6, 8, 3), // new Light(8, 10, 1), // new Light(2, 9 ,3) // }); } public void solve(int length, Light[] lights) { //  蛍光灯の左端座標が小さい順にソートしておく Arrays.sort(lights, Comparator.comparing(Light::getLeft)); // 西から距離iまでの区間を照らすのに必要なコストの暫定最小値 int[] tmp = new int[length + 1]; for (Light light : lights) { // 1つめの蛍光灯の情報でtmpを初期化する if (tmp[1] == 0) { // 対象の蛍光灯の左端から右端までの情報を更新する for (int i = 1; i <= light.getRight(); i++) { tmp[i] = light.getCost(); } continue; } // (2つめの蛍光灯以降)tmpを更新する int elapsedMin = tmp[light.getLeft()]; // ここまでの経過コストの最小値 // 対象の蛍光灯の左端から右端までの情報を更新する for (int i = light.getLeft() == 0 ? 1 : light.getLeft(); i <= light.getRight(); i++) { if (tmp[i] == 0) { // 暫定コストが未計測な区間は経過コスト+蛍光灯のコストを暫定コストとしておく tmp[i] = elapsedMin + light.getCost(); } else { // 暫定コスト計測済みの区間はコストが小さくなる場合のみ更新する if (tmp[i] > elapsedMin + light.getCost()) { tmp[i] = elapsedMin + light.getCost(); } } } } // 東端座標における暫定コストの最小値を解答として出力する System.out.println(tmp[length]); } private static class Light { int left; int right; int cost; public Light(int left, int right, int cost) { super(); this.left = left; this.right = right; this.cost = cost; } public int getLeft() { return left; } public int getRight() { return right; } public int getCost() { return cost; } } }
package com.bozuko.bozuko.views; import com.bozuko.bozuko.R; import com.bozuko.bozuko.datamodel.User; import com.fuzz.android.ui.URLImageView; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.text.TextUtils.TruncateAt; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.ImageView.ScaleType; public class UserView extends RelativeLayout{ URLImageView _image; TextView _name; TextView _email; public UserView(Context context) { super(context); // TODO Auto-generated constructor stub createUI(context); } private void createUI(Context mContext){ LinearLayout image = new LinearLayout(mContext); image.setBackgroundResource(R.drawable.photoboarder); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int)(80*getResources().getDisplayMetrics().density),(int)(80*getResources().getDisplayMetrics().density)); params.addRule(RelativeLayout.CENTER_VERTICAL,1); params.setMargins(5, 0, 0, 0); image.setLayoutParams(params); image.setId(100); addView(image); _image = new URLImageView(mContext); _image.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); _image.setScaleType(ScaleType.CENTER_CROP); _image.setPlaceHolder(R.drawable.defaultphoto); image.addView(_image); _name = new TextView(mContext); _name.setTextColor(Color.BLACK); _name.setTypeface(Typeface.DEFAULT_BOLD); _name.setTextSize(16); _name.setSingleLine(true); _name.setEllipsize(TruncateAt.END); _name.setId(102); params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT); params.addRule(RelativeLayout.RIGHT_OF,100); params.addRule(RelativeLayout.ALIGN_TOP,100); params.setMargins(5, 0, 0, 0); _name.setLayoutParams(params); addView(_name); _email = new TextView(mContext); _email.setTextColor(Color.GRAY); _email.setTextSize(14); _email.setSingleLine(true); _email.setEllipsize(TruncateAt.END); _email.setId(103); params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT); params.addRule(RelativeLayout.RIGHT_OF,100); params.addRule(RelativeLayout.BELOW,102); params.setMargins(5, 0, 0, 0); _email.setLayoutParams(params); addView(_email); } public void display(User page){ _image.setURL(page.requestInfo("image")); _name.setText(page.requestInfo("name")); _email.setText(page.requestInfo("email")); } }
package com.unknowns.hibernate.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Workers { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) int id; int lvl; public Workers() { super(); } public Workers(int lvl) { super(); this.lvl = lvl; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getLvl() { return lvl; } public void setLvl(int lvl) { this.lvl = lvl; } }
package de.mq.phone.web.person; import java.util.Collection; import java.util.Locale; import java.util.Map; import org.springframework.validation.BindingResult; import de.mq.phone.domain.person.GeoCoordinates; interface PersonSearchController { void assignPersons(final PersonSearchModel model, final int pageSize); void assignGeoKoordinates(final PersonSearchModel model); BindingResult validate(final Map<String, Object> map); Collection<String> geoInfos(final GeoCoordinates geoCoordinates, final PersonSearchModel model, final Locale locale); void incPaging(final PersonSearchModel model); void endPaging(final PersonSearchModel model); void decPaging(final PersonSearchModel model) ; void beginPaging(final PersonSearchModel model); }
package org.cethos.tools.ninebatch.tests.tasks; import org.cethos.tools.ninebatch.tasks.BatchConversionTask; import org.cethos.tools.ninebatch.tasks.ConversionFailureException; import org.cethos.tools.ninebatch.tasks.ImageQueryTask; import org.cethos.tools.ninebatch.tasks.Task; import org.cethos.tools.ninebatch.tasks.TaskFactory; import org.cethos.tools.ninebatch.tests.testutil.CommandLineUtil; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.junit.Assert.assertTrue; public class TaskFactoryTest { private TaskFactory taskFactory; @Rule public final ExpectedException thrown = ExpectedException.none(); @Before public void setUp() { this.taskFactory = new TaskFactory(); } @Test public void testCreateFrom_withoutArgs() throws Exception { thrown.expect(ConversionFailureException.class); taskFactory.createFrom(new String[0]); } @Test public void testCreateFrom_withInvalidArgs() throws Exception { thrown.expect(ConversionFailureException.class); taskFactory.createFrom(CommandLineUtil.getArgsFrom("--doesnotexist")); } @Test public void testCreateFrom_withArgsForBatchProcessor() throws Exception { final String[] args = CommandLineUtil.getArgsFrom("testdirectory"); final Task processor = taskFactory.createFrom(args); assertTrue(processor instanceof BatchConversionTask); } @Test public void testCreateFrom_imageQueryArgs() throws Exception { final String[] args = CommandLineUtil.getArgsFrom("-q testdirectory"); final Task processor = taskFactory.createFrom(args); assertTrue(processor instanceof ImageQueryTask); } @Test public void testCreateFrom_imageQueryAndBatchProcessorArgs() throws Exception { final String[] args = CommandLineUtil.getArgsFrom("-q -o test testdirectory"); final Task processor = taskFactory.createFrom(args); assertTrue(processor instanceof ImageQueryTask); } }
package com.example.kuno.sharedpreferences; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; /** * Created by kuno on 2017-01-25. */ public class TwoActivity extends Activity { Button btnReadTwo; TextView tvViewTwo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_two); btnReadTwo = (Button) findViewById(R.id.btnReadTwo); tvViewTwo = (TextView) findViewById(R.id.tvViewTwo); btnReadTwo.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { SharedPreferences sharedPreferences = getSharedPreferences("PreferencesEx", MODE_PRIVATE); tvViewTwo.setText(sharedPreferences.getString("text", "")); } }); } }
package com.zc.pivas.printlabel.service.impl; import com.zc.base.orm.mybatis.paging.JqueryStylePaging; import com.zc.base.orm.mybatis.paging.JqueryStylePagingResults; import com.zc.base.sys.common.util.DefineCollectionUtil; import com.zc.pivas.printlabel.entity.PrinterIPBean; import com.zc.pivas.printlabel.repository.PrinterIPDao; import com.zc.pivas.printlabel.service.PrinterIPService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; /** * 打印机配置 接口实现类 * * @author kunkka * @version 1.0 */ @Service("printerIPService") public class PrinterIPServiceImpl implements PrinterIPService { private Logger logger = LoggerFactory.getLogger(PrinterIPServiceImpl.class); @Resource private PrinterIPDao printerIPDao; @Override public JqueryStylePagingResults<PrinterIPBean> queryPrinterIPList(PrinterIPBean bean, JqueryStylePaging jqueryStylePaging) throws Exception { String[] columns = new String[]{"gid", "compName", "ipAddr", "prinName"}; JqueryStylePagingResults<PrinterIPBean> pagingResults = new JqueryStylePagingResults<PrinterIPBean>(columns); List<PrinterIPBean> list = printerIPDao.queryPrinterIPList(bean, jqueryStylePaging); // 处理最后一页不是第一页且没有数据的问题 if (DefineCollectionUtil.isEmpty(list) && jqueryStylePaging.getPage() != 1) { jqueryStylePaging.setPage(jqueryStylePaging.getPage() - 1); list = printerIPDao.queryPrinterIPList(bean, jqueryStylePaging); } int total = getPrinterIPCounts(bean); pagingResults.setDataRows(list); pagingResults.setTotal(total); pagingResults.setPage(jqueryStylePaging.getPage()); return pagingResults; } @Override public PrinterIPBean queryPrinterIPById(String id) throws Exception { // TODO Auto-generated method stub return printerIPDao.queryPrinterIPById(id); } /** * 添加打印机配置项 * @param bean * @return * @throws Exception */ @Override public int addPrinterIP(PrinterIPBean bean) throws Exception { return printerIPDao.addPrinterIP(bean); } /** * 更新打印机配置项 * @param bean * @return * @throws Exception */ @Override public int updatePrinterIP(PrinterIPBean bean) throws Exception { return printerIPDao.updatePrinterIP(bean); } /** * 删除打印机配置项 * @param gids * @return * @throws Exception */ @Override public int delPrinterIP(String[] gids) throws Exception { return printerIPDao.delPrinterIP(gids); } /** * 查询打印机配置项总数 * @param bean * @return * @throws Exception */ @Override public int getPrinterIPCounts(PrinterIPBean bean) throws Exception { return printerIPDao.getPrinterIPCounts(bean); } /** * 判断主机名/ip/打印机名称是否存在 * @param bean 查询条件 * @return * @throws Exception */ @Override public List<PrinterIPBean> checkPrinterIP(PrinterIPBean bean) throws Exception { return printerIPDao.checkPrinterIP(bean); } }
package esi.atl.G39864.blokus.view.javaFx; import esi.atl.gg39864.blokus.model.Game; import javafx.event.ActionEvent; import javafx.event.EventHandler; /** * this method allows to make the action stop the game for the current player * where the button arreter is clicked * * @author chris home */ public class ArreterButtonHandler implements EventHandler<ActionEvent> { private final Game game; /** * this method allows to make the action stop when the button arreter is * clicked * * @param game is the parameter necessary for make the action stop */ public ArreterButtonHandler(Game game) { this.game = game; } /** * this method allows to make the action for blocked the player when he * click on the button arreter * * @param event is the event when the player click on the button arreter */ @Override public void handle(ActionEvent event) { System.out.println(game.getCurrentPlayer().isBlocked() + "" + game.getCurrentPlayer().getNumber()); game.setIsBlocked(); System.out.println(game.getCurrentPlayer().isBlocked() + "" + game.getCurrentPlayer().getNumber()); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.messaging.simp.config; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.context.event.SmartApplicationListener; import org.springframework.core.task.TaskExecutor; import org.springframework.lang.Nullable; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.converter.ByteArrayMessageConverter; import org.springframework.messaging.converter.CompositeMessageConverter; import org.springframework.messaging.converter.DefaultContentTypeResolver; import org.springframework.messaging.converter.GsonMessageConverter; import org.springframework.messaging.converter.JsonbMessageConverter; import org.springframework.messaging.converter.KotlinSerializationJsonMessageConverter; import org.springframework.messaging.converter.MappingJackson2MessageConverter; import org.springframework.messaging.converter.MessageConverter; import org.springframework.messaging.converter.StringMessageConverter; import org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolver; import org.springframework.messaging.handler.invocation.HandlerMethodReturnValueHandler; import org.springframework.messaging.simp.SimpLogging; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler; import org.springframework.messaging.simp.broker.AbstractBrokerMessageHandler; import org.springframework.messaging.simp.broker.SimpleBrokerMessageHandler; import org.springframework.messaging.simp.stomp.StompBrokerRelayMessageHandler; import org.springframework.messaging.simp.user.DefaultUserDestinationResolver; import org.springframework.messaging.simp.user.MultiServerUserRegistry; import org.springframework.messaging.simp.user.SimpUserRegistry; import org.springframework.messaging.simp.user.UserDestinationMessageHandler; import org.springframework.messaging.simp.user.UserDestinationResolver; import org.springframework.messaging.simp.user.UserRegistryMessageHandler; import org.springframework.messaging.support.AbstractSubscribableChannel; import org.springframework.messaging.support.ExecutorSubscribableChannel; import org.springframework.messaging.support.ImmutableMessageChannelInterceptor; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.MimeTypeUtils; import org.springframework.util.PathMatcher; import org.springframework.util.StringUtils; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean; /** * Provides essential configuration for handling messages with simple messaging * protocols such as STOMP. * * <p>{@link #clientInboundChannel} and {@link #clientOutboundChannel} deliver * messages to and from remote clients to several message handlers such as the * following. * <ul> * <li>{@link #simpAnnotationMethodMessageHandler}</li> * <li>{@link #simpleBrokerMessageHandler}</li> * <li>{@link #stompBrokerRelayMessageHandler}</li> * <li>{@link #userDestinationMessageHandler}</li> * </ul> * * <p>{@link #brokerChannel} delivers messages from within the application to the * respective message handlers. {@link #brokerMessagingTemplate} can be injected * into any application component to send messages. * * <p>Subclasses are responsible for the parts of the configuration that feed messages * to and from the client inbound/outbound channels (e.g. STOMP over WebSocket). * * @author Rossen Stoyanchev * @author Brian Clozel * @author Sebastien Deleuze * @since 4.0 */ public abstract class AbstractMessageBrokerConfiguration implements ApplicationContextAware { private static final String MVC_VALIDATOR_NAME = "mvcValidator"; private static final boolean jackson2Present; private static final boolean gsonPresent; private static final boolean jsonbPresent; private static final boolean kotlinSerializationJsonPresent; static { ClassLoader classLoader = AbstractMessageBrokerConfiguration.class.getClassLoader(); jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) && ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader); gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", classLoader); jsonbPresent = ClassUtils.isPresent("jakarta.json.bind.Jsonb", classLoader); kotlinSerializationJsonPresent = ClassUtils.isPresent("kotlinx.serialization.json.Json", classLoader); } @Nullable private ApplicationContext applicationContext; @Nullable private ChannelRegistration clientInboundChannelRegistration; @Nullable private ChannelRegistration clientOutboundChannelRegistration; @Nullable private MessageBrokerRegistry brokerRegistry; /** * Protected constructor. */ protected AbstractMessageBrokerConfiguration() { } @Override public void setApplicationContext(@Nullable ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Nullable public ApplicationContext getApplicationContext() { return this.applicationContext; } @Bean public AbstractSubscribableChannel clientInboundChannel( @Qualifier("clientInboundChannelExecutor") TaskExecutor executor) { ExecutorSubscribableChannel channel = new ExecutorSubscribableChannel(executor); channel.setLogger(SimpLogging.forLog(channel.getLogger())); ChannelRegistration reg = getClientInboundChannelRegistration(); if (reg.hasInterceptors()) { channel.setInterceptors(reg.getInterceptors()); } return channel; } @Bean public TaskExecutor clientInboundChannelExecutor() { TaskExecutorRegistration reg = getClientInboundChannelRegistration().taskExecutor(); ThreadPoolTaskExecutor executor = reg.getTaskExecutor(); executor.setThreadNamePrefix("clientInboundChannel-"); return executor; } protected final ChannelRegistration getClientInboundChannelRegistration() { if (this.clientInboundChannelRegistration == null) { ChannelRegistration registration = new ChannelRegistration(); configureClientInboundChannel(registration); registration.interceptors(new ImmutableMessageChannelInterceptor()); this.clientInboundChannelRegistration = registration; } return this.clientInboundChannelRegistration; } /** * A hook for subclasses to customize the message channel for inbound messages * from WebSocket clients. */ protected void configureClientInboundChannel(ChannelRegistration registration) { } @Bean public AbstractSubscribableChannel clientOutboundChannel( @Qualifier("clientOutboundChannelExecutor") TaskExecutor executor) { ExecutorSubscribableChannel channel = new ExecutorSubscribableChannel(executor); channel.setLogger(SimpLogging.forLog(channel.getLogger())); ChannelRegistration reg = getClientOutboundChannelRegistration(); if (reg.hasInterceptors()) { channel.setInterceptors(reg.getInterceptors()); } return channel; } @Bean public TaskExecutor clientOutboundChannelExecutor() { TaskExecutorRegistration reg = getClientOutboundChannelRegistration().taskExecutor(); ThreadPoolTaskExecutor executor = reg.getTaskExecutor(); executor.setThreadNamePrefix("clientOutboundChannel-"); return executor; } protected final ChannelRegistration getClientOutboundChannelRegistration() { if (this.clientOutboundChannelRegistration == null) { ChannelRegistration registration = new ChannelRegistration(); configureClientOutboundChannel(registration); registration.interceptors(new ImmutableMessageChannelInterceptor()); this.clientOutboundChannelRegistration = registration; } return this.clientOutboundChannelRegistration; } /** * A hook for subclasses to customize the message channel for messages from * the application or message broker to WebSocket clients. */ protected void configureClientOutboundChannel(ChannelRegistration registration) { } @Bean public AbstractSubscribableChannel brokerChannel( AbstractSubscribableChannel clientInboundChannel, AbstractSubscribableChannel clientOutboundChannel, @Qualifier("brokerChannelExecutor") TaskExecutor executor) { MessageBrokerRegistry registry = getBrokerRegistry(clientInboundChannel, clientOutboundChannel); ChannelRegistration registration = registry.getBrokerChannelRegistration(); ExecutorSubscribableChannel channel = (registration.hasTaskExecutor() ? new ExecutorSubscribableChannel(executor) : new ExecutorSubscribableChannel()); registration.interceptors(new ImmutableMessageChannelInterceptor()); channel.setLogger(SimpLogging.forLog(channel.getLogger())); channel.setInterceptors(registration.getInterceptors()); return channel; } @Bean public TaskExecutor brokerChannelExecutor( AbstractSubscribableChannel clientInboundChannel, AbstractSubscribableChannel clientOutboundChannel) { MessageBrokerRegistry registry = getBrokerRegistry(clientInboundChannel, clientOutboundChannel); ChannelRegistration registration = registry.getBrokerChannelRegistration(); ThreadPoolTaskExecutor executor; if (registration.hasTaskExecutor()) { executor = registration.taskExecutor().getTaskExecutor(); } else { // Should never be used executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(0); executor.setMaxPoolSize(1); executor.setQueueCapacity(0); } executor.setThreadNamePrefix("brokerChannel-"); return executor; } /** * An accessor for the {@link MessageBrokerRegistry} that ensures its one-time creation * and initialization through {@link #configureMessageBroker(MessageBrokerRegistry)}. */ protected final MessageBrokerRegistry getBrokerRegistry( AbstractSubscribableChannel clientInboundChannel, AbstractSubscribableChannel clientOutboundChannel) { if (this.brokerRegistry == null) { MessageBrokerRegistry registry = new MessageBrokerRegistry(clientInboundChannel, clientOutboundChannel); configureMessageBroker(registry); this.brokerRegistry = registry; } return this.brokerRegistry; } /** * A hook for subclasses to customize message broker configuration through the * provided {@link MessageBrokerRegistry} instance. */ protected void configureMessageBroker(MessageBrokerRegistry registry) { } /** * Provide access to the configured PatchMatcher for access from other * configuration classes. */ @Nullable public final PathMatcher getPathMatcher( AbstractSubscribableChannel clientInboundChannel, AbstractSubscribableChannel clientOutboundChannel) { return getBrokerRegistry(clientInboundChannel, clientOutboundChannel).getPathMatcher(); } @Bean public SimpAnnotationMethodMessageHandler simpAnnotationMethodMessageHandler( AbstractSubscribableChannel clientInboundChannel, AbstractSubscribableChannel clientOutboundChannel, SimpMessagingTemplate brokerMessagingTemplate, CompositeMessageConverter brokerMessageConverter) { SimpAnnotationMethodMessageHandler handler = createAnnotationMethodMessageHandler( clientInboundChannel, clientOutboundChannel, brokerMessagingTemplate); MessageBrokerRegistry brokerRegistry = getBrokerRegistry(clientInboundChannel, clientOutboundChannel); handler.setDestinationPrefixes(brokerRegistry.getApplicationDestinationPrefixes()); handler.setMessageConverter(brokerMessageConverter); handler.setValidator(simpValidator()); List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>(); addArgumentResolvers(argumentResolvers); handler.setCustomArgumentResolvers(argumentResolvers); List<HandlerMethodReturnValueHandler> returnValueHandlers = new ArrayList<>(); addReturnValueHandlers(returnValueHandlers); handler.setCustomReturnValueHandlers(returnValueHandlers); PathMatcher pathMatcher = brokerRegistry.getPathMatcher(); if (pathMatcher != null) { handler.setPathMatcher(pathMatcher); } return handler; } /** * Protected method for plugging in a custom subclass of * {@link org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler * SimpAnnotationMethodMessageHandler}. * @since 5.3.2 */ protected SimpAnnotationMethodMessageHandler createAnnotationMethodMessageHandler( AbstractSubscribableChannel clientInboundChannel, AbstractSubscribableChannel clientOutboundChannel, SimpMessagingTemplate brokerMessagingTemplate) { return new SimpAnnotationMethodMessageHandler( clientInboundChannel, clientOutboundChannel, brokerMessagingTemplate); } protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { } protected void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) { } @Bean @Nullable public AbstractBrokerMessageHandler simpleBrokerMessageHandler( AbstractSubscribableChannel clientInboundChannel, AbstractSubscribableChannel clientOutboundChannel, AbstractSubscribableChannel brokerChannel, UserDestinationResolver userDestinationResolver) { MessageBrokerRegistry registry = getBrokerRegistry(clientInboundChannel, clientOutboundChannel); SimpleBrokerMessageHandler handler = registry.getSimpleBroker(brokerChannel); if (handler == null) { return null; } updateUserDestinationResolver(handler, userDestinationResolver, registry.getUserDestinationPrefix()); return handler; } private void updateUserDestinationResolver( AbstractBrokerMessageHandler handler, UserDestinationResolver userDestinationResolver, @Nullable String userDestinationPrefix) { Collection<String> prefixes = handler.getDestinationPrefixes(); if (!prefixes.isEmpty() && !prefixes.iterator().next().startsWith("/")) { ((DefaultUserDestinationResolver) userDestinationResolver).setRemoveLeadingSlash(true); } if (StringUtils.hasText(userDestinationPrefix)) { handler.setUserDestinationPredicate(destination -> destination.startsWith(userDestinationPrefix)); } } @Bean @Nullable public AbstractBrokerMessageHandler stompBrokerRelayMessageHandler( AbstractSubscribableChannel clientInboundChannel, AbstractSubscribableChannel clientOutboundChannel, AbstractSubscribableChannel brokerChannel, UserDestinationMessageHandler userDestinationMessageHandler, @Nullable MessageHandler userRegistryMessageHandler, UserDestinationResolver userDestinationResolver) { MessageBrokerRegistry registry = getBrokerRegistry(clientInboundChannel, clientOutboundChannel); StompBrokerRelayMessageHandler handler = registry.getStompBrokerRelay(brokerChannel); if (handler == null) { return null; } Map<String, MessageHandler> subscriptions = new HashMap<>(4); String destination = registry.getUserDestinationBroadcast(); if (destination != null) { subscriptions.put(destination, userDestinationMessageHandler); } destination = registry.getUserRegistryBroadcast(); if (destination != null) { subscriptions.put(destination, userRegistryMessageHandler); } handler.setSystemSubscriptions(subscriptions); updateUserDestinationResolver(handler, userDestinationResolver, registry.getUserDestinationPrefix()); return handler; } @Bean public UserDestinationMessageHandler userDestinationMessageHandler( AbstractSubscribableChannel clientInboundChannel, AbstractSubscribableChannel clientOutboundChannel, AbstractSubscribableChannel brokerChannel, UserDestinationResolver userDestinationResolver) { UserDestinationMessageHandler handler = new UserDestinationMessageHandler(clientInboundChannel, brokerChannel, userDestinationResolver); MessageBrokerRegistry registry = getBrokerRegistry(clientInboundChannel, clientOutboundChannel); String destination = registry.getUserDestinationBroadcast(); if (destination != null) { handler.setBroadcastDestination(destination); } return handler; } @Bean @Nullable public MessageHandler userRegistryMessageHandler( AbstractSubscribableChannel clientInboundChannel, AbstractSubscribableChannel clientOutboundChannel, SimpUserRegistry userRegistry, SimpMessagingTemplate brokerMessagingTemplate, @Qualifier("messageBrokerTaskScheduler") TaskScheduler scheduler) { MessageBrokerRegistry brokerRegistry = getBrokerRegistry(clientInboundChannel, clientOutboundChannel); if (brokerRegistry.getUserRegistryBroadcast() == null) { return null; } Assert.isInstanceOf(MultiServerUserRegistry.class, userRegistry, "MultiServerUserRegistry required"); return new UserRegistryMessageHandler((MultiServerUserRegistry) userRegistry, brokerMessagingTemplate, brokerRegistry.getUserRegistryBroadcast(), scheduler); } // Expose alias for 4.1 compatibility @Bean(name = {"messageBrokerTaskScheduler", "messageBrokerSockJsTaskScheduler"}) public TaskScheduler messageBrokerTaskScheduler() { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setThreadNamePrefix("MessageBroker-"); scheduler.setPoolSize(Runtime.getRuntime().availableProcessors()); scheduler.setRemoveOnCancelPolicy(true); return scheduler; } @Bean public SimpMessagingTemplate brokerMessagingTemplate( AbstractSubscribableChannel brokerChannel, AbstractSubscribableChannel clientInboundChannel, AbstractSubscribableChannel clientOutboundChannel, CompositeMessageConverter brokerMessageConverter) { SimpMessagingTemplate template = new SimpMessagingTemplate(brokerChannel); MessageBrokerRegistry registry = getBrokerRegistry(clientInboundChannel, clientOutboundChannel); String prefix = registry.getUserDestinationPrefix(); if (prefix != null) { template.setUserDestinationPrefix(prefix); } template.setMessageConverter(brokerMessageConverter); return template; } @Bean public CompositeMessageConverter brokerMessageConverter() { List<MessageConverter> converters = new ArrayList<>(); boolean registerDefaults = configureMessageConverters(converters); if (registerDefaults) { converters.add(new StringMessageConverter()); converters.add(new ByteArrayMessageConverter()); if (kotlinSerializationJsonPresent) { converters.add(new KotlinSerializationJsonMessageConverter()); } if (jackson2Present) { converters.add(createJacksonConverter()); } else if (gsonPresent) { converters.add(new GsonMessageConverter()); } else if (jsonbPresent) { converters.add(new JsonbMessageConverter()); } } return new CompositeMessageConverter(converters); } protected MappingJackson2MessageConverter createJacksonConverter() { DefaultContentTypeResolver resolver = new DefaultContentTypeResolver(); resolver.setDefaultMimeType(MimeTypeUtils.APPLICATION_JSON); MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); converter.setContentTypeResolver(resolver); return converter; } /** * Override this method to add custom message converters. * @param messageConverters the list to add converters to, initially empty * @return {@code true} if default message converters should be added to list, * {@code false} if no more converters should be added */ protected boolean configureMessageConverters(List<MessageConverter> messageConverters) { return true; } @Bean public UserDestinationResolver userDestinationResolver( SimpUserRegistry userRegistry, AbstractSubscribableChannel clientInboundChannel, AbstractSubscribableChannel clientOutboundChannel) { DefaultUserDestinationResolver resolver = new DefaultUserDestinationResolver(userRegistry); MessageBrokerRegistry registry = getBrokerRegistry(clientInboundChannel, clientOutboundChannel); String prefix = registry.getUserDestinationPrefix(); if (prefix != null) { resolver.setUserDestinationPrefix(prefix); } return resolver; } @Bean public SimpUserRegistry userRegistry( AbstractSubscribableChannel clientInboundChannel, AbstractSubscribableChannel clientOutboundChannel) { MessageBrokerRegistry brokerRegistry = getBrokerRegistry(clientInboundChannel, clientOutboundChannel); SimpUserRegistry userRegistry = createLocalUserRegistry(brokerRegistry.getUserRegistryOrder()); boolean broadcast = brokerRegistry.getUserRegistryBroadcast() != null; return (broadcast ? new MultiServerUserRegistry(userRegistry) : userRegistry); } /** * Create the user registry that provides access to local users. * @param order the order to use as a {@link SmartApplicationListener}. * @since 5.1 */ protected abstract SimpUserRegistry createLocalUserRegistry(@Nullable Integer order); /** * Return an {@link org.springframework.validation.Validator} instance for * validating {@code @Payload} method arguments. * <p>In order, this method tries to get a Validator instance: * <ul> * <li>delegating to getValidator() first</li> * <li>if none returned, getting an existing instance with its well-known name "mvcValidator", * created by an MVC configuration</li> * <li>if none returned, checking the classpath for the presence of a JSR-303 implementation * before creating a {@code OptionalValidatorFactoryBean}</li> * <li>returning a no-op Validator instance</li> * </ul> */ protected Validator simpValidator() { Validator validator = getValidator(); if (validator == null) { if (this.applicationContext != null && this.applicationContext.containsBean(MVC_VALIDATOR_NAME)) { validator = this.applicationContext.getBean(MVC_VALIDATOR_NAME, Validator.class); } else if (ClassUtils.isPresent("jakarta.validation.Validator", getClass().getClassLoader())) { try { validator = new OptionalValidatorFactoryBean(); } catch (Throwable ex) { throw new BeanInitializationException("Failed to create default validator", ex); } } else { validator = new Validator() { @Override public boolean supports(Class<?> clazz) { return false; } @Override public void validate(@Nullable Object target, Errors errors) { } }; } } return validator; } /** * Override this method to provide a custom {@link Validator}. * @since 4.0.1 */ @Nullable public Validator getValidator() { return null; } }
package com.jd.myadapterlib.dinterface; import android.view.View; /** * Auther: Jarvis Dong * Time: on 2017/1/3 0003 * Name: * OverView: * Usage: */ public interface DOnItemChildLongClickListener { boolean onLongClick(View var1, int var2); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.lifespeedtechnologies.OpenTracker; import java.awt.Graphics; import org.OpenNI.*; import static com.lifespeedtechnologies.OpenTracker.Driver.drawSkeleton; /** * * @author dean */ public class IrDriver extends Driver { protected static IRGenerator irgen; protected IRMap irMap; protected java.awt.image.BufferedImage bimg; protected int width, height; protected byte[] irbites; private boolean drawColor = true; protected IRMetaData imd; protected java.nio.ByteBuffer buf; protected int BPP; public IrDriver ( Context c ) { super( c ); } @Override public void init () throws GeneralException { initIr(); } protected void initIr () throws GeneralException { irbites = new byte[width * height * 3]; irgen = IRGenerator.create( context ); imd = irgen.getMetaData(); width = imd.getFullXRes(); height = imd.getFullYRes(); irgen.startGenerating(); } public void updateImage () throws GeneralException { context.waitAndUpdateAll(); irMap = irgen.getIRMap(); java.nio.ByteBuffer b = irgen.createDataByteBuffer(); b = b.get( irbites ); repaint(); } @Override public void paint ( Graphics g ) { java.awt.image.DataBufferByte dbb = new java.awt.image.DataBufferByte( irbites, width * height * 3 ); java.awt.image.WritableRaster raster = java.awt.image.Raster. createInterleavedRaster( dbb, width, height, width * 3, 3, new int[] { 0, 1, 2 }, null ); java.awt.image.ColorModel colorModel = new java.awt.image.ComponentColorModel( java.awt.color.ColorSpace.getInstance( java.awt.color.ColorSpace.CS_sRGB ), new int[] { 8, 8, 8 }, false, false, java.awt.image.ComponentColorModel.OPAQUE, java.awt.image.DataBuffer.TYPE_BYTE ); bimg = new java.awt.image.BufferedImage( colorModel, raster, false, null ); g.drawImage( bimg, 0, 0, this ); try { int[] users = userGen.getUsers(); for ( int i = 0; i < users.length; ++i ) { java.awt.Color c = colors[users[i] % colors.length]; c = new java.awt.Color( 255 - c.getRed(), 255 - c.getGreen(), 255 - c. getBlue() ); g.setColor( c ); if ( drawSkeleton && skeletonCap.isSkeletonTracking( users[i] ) ) { VideoDriver.drawSkeleton( g, users[i] ); } } } catch ( StatusException e ) { e.printStackTrace(); } } }
import java.util.*; public class day3 { public static void main(String[] args){ // question2 Scanner inp=new Scanner(System.in); System.out.print("Give the number to be checked : "); int n=inp.nextInt(); String str=Integer.toString(n); char digit[]=str.toCharArray(); int repeat=0; int i,j; for(i=0;i<str.length();i++){ for(j=i+1;j<str.length();j++){ if(digit[i]==digit[j]){ repeat++;} } } if(repeat>0){ System.out.println(n+" is not an Unique Number");} else{ System.out.println(n+" is an Unique Number"); } } }
package jp.ac.kyushu_u.csce.modeltool.base.utility; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.lang.StringUtils; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; /** * 要求モデル検証ツール・ヘルパークラス * * @author KBK yoshimura */ public class PluginHelper { /** 空文字列 */ public static final String EMPTY = ""; //$NON-NLS-1$ /** * 配列の要素のインデックスを取得する<br> * 指定した要素が配列に存在しない場合は負の値を返す * @param array 配列 * @param element 要素 * @return インデックス */ public static int indexOf(Object[] array, Object element) { for (int i=0; i<array.length; i++) { if (array[i].equals(element)) { return i; } } return -1; } /** * 文字列がnull、空文字列、半角スペースのみの場合trueを返す * @param input * @return 空チェック結果 */ public static boolean isEmpty(String input) { return (input == null || input.replaceAll(" ", "").equals(EMPTY)); //$NON-NLS-1$ //$NON-NLS-2$ } /** * 文字列配列に指定の文字列が存在するかどうかをチェックする<br> * 入力文字列がnullの場合はfalseを返す * @param input 文字列 * @param strings 文字列 * @return true:存在する/false:存在しない */ public static boolean in(String input, String... strings) { return in(input, true, strings); } /** * 文字列配列に指定の文字列が存在するかどうかをチェックする<br> * 入力文字列がnullの場合はfalseを返す * @param input 文字列 * @param strings 文字列 * @param caseSensitive 大/小文字の区別 * @return true:存在する/false:存在しない */ public static boolean in(String input, boolean caseSensitive, String... strings) { return in(input, caseSensitive, new String[][] {strings}); } /** * 文字列配列に指定の文字列が存在するかどうかをチェックする<br> * 入力文字列がnullの場合はfalseを返す * @param input 文字列 * @param arrays 配列 * @return true:存在する/false:存在しない */ public static boolean in(String input, String[]... arrays) { return in(input, true, arrays); } /** * 文字列配列に指定の文字列が存在するかどうかをチェックする<br> * 入力文字列がnullの場合はfalseを返す * @param input 文字列 * @param arrays 配列 * @param caseSensitive 大/小文字の区別 * @return true:存在する/false:存在しない */ public static boolean in(String input, boolean caseSensitive, String[]... arrays) { if (input == null) { return false; } for (String[] array : arrays) { for (String string : array) { if ((caseSensitive && string.equals(input)) || // caseSensitive = trueの場合、大/小文字区別あり (!caseSensitive && string.equalsIgnoreCase(input))) { // falseの場合、大/小文字区別なし return true; } } } return false; } // /** // * 配列を結合する(配列1+配列2) // * @param cls 配列要素のクラス // * @param array1 配列1 // * @param array2 配列2 // * @return 結合後の配列 // */ // public static Object[] arrayConcat(Class<?> cls, Object[] array1, Object[] array2) { // // Object[] ret = (Object[])Array.newInstance(cls, array1.length + array2.length); // // System.arraycopy(array1, 0, ret, 0, array1.length); // System.arraycopy(array2, 0, ret, array1.length, array2.length); // // return ret; // } /** * 配列を結合する * @param arrays 配列 * @return 結合後の配列 */ public static Object[] arrayConcat(Class<?> cls, Object[]... arrays) { List<Object> list = new ArrayList<Object>(); for (Object[] array : arrays) { list.addAll(Arrays.asList(array)); } return list.toArray((Object[])Array.newInstance(cls, 0)); } /** * 指定したリソースのワークスペースからの相対パスを取得する。 * @param resource リソース * @return 相対パス文字列 */ public static String getRelativePath(IResource resource) { String path = resource.getFullPath().toString(); // if (path.charAt(0) == '/') { // path = path.substring(1); // } return path; } /** * 指定したりソースの絶対パスを取得する。 * @param resource リソース * @return 絶対パス文字列 */ public static String getAbsolutePath(IResource resource) { return resource.getLocation().toString(); } /** * 拡張子なしのファイル名を取得する。 * @param file ファイル * @return 拡張子なしのファイル名 */ public static String getFileNameWithoutExtension(IFile file) { // 拡張子付ファイル名、拡張子の取得 String name = file.getName(); String extension = file.getFileExtension(); // 拡張子がない場合 if (isEmpty(extension)) { return name; } // 拡張子を除去したファイル名を返す('.'を除去するため-1しています) return name.substring(0, name.length() - extension.length() - 1); } /** * 文字列中に改行を含むかチェックする * @param object * @return 改行を含む場合trueを返す */ public static boolean isMultiLine(String object) { boolean ret = false; if (object != null) { // ret = object.split("[\r\n|\r|\n]").length != 1; // ret = object.matches(".*[\r|\n].*"); // ret = object.length() != object.replaceFirst("\r\n|\r|\n", "").length(); ret = object.indexOf('\n') >= 0 || object.indexOf('\r') >= 0; } return ret; } /** * コンテナハンドル、ファイル名からファイルハンドルを取得する * @param container コンテナ * @param fileName ファイル名 * @return ファイル */ public static IFile getFile(IContainer container, String fileName) { IPath containerPath = container.getFullPath(); IPath newFilePath = containerPath.append(fileName); IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(newFilePath); return file; } /** * * @param path ルートからの相対パス * @return 指定パスのファイルハンドル */ public static IFile getFile(IPath path) { return ResourcesPlugin.getWorkspace().getRoot().getFile(path); } /** * 空、ホワイトスペース、nullの場合defaultStrを返す * @param str 変換前文字列 * @param defaultStr 変換後文字列 * @return 変換結果 */ public static String defaultIfBlank(String str, String defaultStr) { if (StringUtils.isBlank(str)) { return defaultStr; } else { return str; } } // /** // * // * @param location ローカルファイルシステム上の絶対パス // * @return // */ // public static IFile getFileForLocation(IPath location) { // return ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(location); // } // // /** // * // * @param location ローカルファイルシステム上の絶対パス // * @return // */ // public static IContainer getContainerForLocation(IPath location) { // return ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(location); // } /** * 文字列を改行コードで分割する * @param str 対象文字列 * @return 分割結果の配列 */ public static String[] splitByLine(String str) { if (StringUtils.isBlank(str)) return new String[]{}; return str.replaceAll("\r\n", "\r").split("\r|\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } /** * 数値がnullの場合0を返す * @param num 数値 * @return 結果 */ public static int nullToZero(Integer num) { if (num == null) return 0; return num.intValue(); } /** * フォルダの取得 * @param relativePath ルートからの相対パス * @return フォルダ。指定パスがフォルダ(またはプロジェクト)でない場合nullを返す。 */ public static IContainer getFolder(String relativePath) { // ワークスペースルートの取得 IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); // フォルダの取得 IContainer container = null; try { // 指定パスをフォルダとして取得 container = root.getFolder(new Path(relativePath)); } catch (Exception e) { // 指定パスがプロジェクトの場合、例外となるのでここでキャッチ try { // 指定パスをプロジェクトとして取得 container = root.getProject(relativePath); } catch (Exception e2) { // ignore } } // フォルダが存在しない場合、nullを返す if (container != null) { if (!container.getLocation().toFile().exists()) { container = null; } } return container; } }
package com.appspot.smartshop.ui.product; import java.net.URLEncoder; import java.util.LinkedList; import java.util.Set; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ListView; import com.appspot.smartshop.R; import com.appspot.smartshop.adapter.ProductAdapter; import com.appspot.smartshop.dom.ProductInfo; import com.appspot.smartshop.facebook.utils.FacebookUtils; import com.appspot.smartshop.map.SearchProductsOnMapActivity; import com.appspot.smartshop.ui.BaseUIActivity; import com.appspot.smartshop.utils.CategoriesDialog; import com.appspot.smartshop.utils.DataLoader; import com.appspot.smartshop.utils.Global; import com.appspot.smartshop.utils.JSONParser; import com.appspot.smartshop.utils.RestClient; import com.appspot.smartshop.utils.SimpleAsyncTask; import com.appspot.smartshop.utils.URLConstant; import com.appspot.smartshop.utils.CategoriesDialog.CategoriesDialogListener; import com.google.android.maps.MapActivity; public class ProductsListActivity extends MapActivity { public static final String TAG = "[ProductsListActivity]"; public static final int BEST_SELLER_PRODUCTS = 0; public static final int CHEAPEST_PRODUCTS = 1; public static final int NEWEST_PRODUCTS = 2; private static ProductsListActivity instance = null; private CheckBox chMostUpdate, chCheapest, chMostView; private ListView listView; private ProductAdapter productAdapter; private LinkedList<ProductInfo> products; private EditText txtSearch; //set up variable for facebook connection //end set up variable for facebook connection public static ProductsListActivity getInstance() { return instance; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.products_list); BaseUIActivity.initHeader(this); Log.d(TAG, "onCreate"); // mLoginButton.setVisibility(View.VISIBLE); // search field txtSearch = (EditText) findViewById(R.id.txtSearch); Button btnSearch = (Button) findViewById(R.id.btnSearch); btnSearch.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String query = txtSearch.getText().toString(); if (query == null || query.trim().equals("")) { loadProductsList(); } else { searchProductsByQuery(URLEncoder.encode(query)); } } }); Button btnSearchOnMap = (Button) findViewById(R.id.btnSearchOnMap); btnSearchOnMap.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ProductsListActivity.this, SearchProductsOnMapActivity.class); startActivity(intent); } }); // checkboxes chMostUpdate = (CheckBox) findViewById(R.id.chMostUpdate); chCheapest = (CheckBox) findViewById(R.id.chCheapest); chMostView = (CheckBox) findViewById(R.id.chMostView); // TODO: search products based on price range Button btnPriceRange = (Button) findViewById(R.id.btnPriceRange); btnPriceRange.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { searchProductsByPriceRange(); } }); // list view listView = (ListView) findViewById(R.id.listViewProductAfterSearch); productAdapter = new ProductAdapter(this, R.layout.product_list_item, new LinkedList<ProductInfo>(),new FacebookUtils(this) ); loadProductsList(); } protected void searchProductsByPriceRange() { LayoutInflater inflater = LayoutInflater.from(this); final View view = inflater.inflate(R.layout.product_price_range_dialog, null); Button btnSearch = (Button) view.findViewById(R.id.btnSearch); btnSearch.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { EditText txtFromPrice = (EditText) view.findViewById(R.id.txtFromPrice); EditText txtToPrice = (EditText) view.findViewById(R.id.txtToPrice); constructUrl(); String fromPrice = txtFromPrice.getText().toString(); String toPrice = txtToPrice.getText().toString(); url += "&pricerange" + fromPrice + "," + toPrice; loadData(); dialog.dismiss(); } }); Builder dialogBuilder = new AlertDialog.Builder(this); dialogBuilder.setView(view); dialog = dialogBuilder.create(); dialog.show(); } protected void searchProductsByQuery(String query) { constructUrl(); url += "&q=" + query; loadData(); } private SimpleAsyncTask task = null; private String url; protected void loadProductsList() { constructUrl(); loadData(); } private void constructUrl() { // determine what criteria is used to search products String criteria = ""; if (chMostUpdate.isChecked()) { criteria += "1,"; } if (chCheapest.isChecked()) { criteria += "2,"; } if (chMostView.isChecked()) { criteria += "4,"; } // construct url url = null; if (!criteria.equals("")) { criteria = criteria.substring(0, criteria.length() - 1); url = String.format(URLConstant.GET_PRODUCTS_BY_CRITERIA, criteria); } else { url = URLConstant.GET_PRODUCTS; } } public static final int MENU_SEARCH_BY_CATEGORIES = 0; public static final int MENU_COMPARE_TWO_PRODUCTS = 1; private AlertDialog dialog; @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_SEARCH_BY_CATEGORIES, 0, getString(R.string.search_by_categories)).setIcon(R.drawable.category); menu.add(0, MENU_COMPARE_TWO_PRODUCTS, 0, getString(R.string.compare)).setIcon(R.drawable.compare); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_SEARCH_BY_CATEGORIES: CategoriesDialog.showCategoriesDialog(this, new CategoriesDialogListener() { @Override public void onCategoriesDialogClose(Set<String> categories) { searchByCategories(categories); } }); break; case MENU_COMPARE_TWO_PRODUCTS: Intent intent = new Intent(ProductsListActivity.this, SelectTwoProductActivity.class); intent.putExtra(Global.PRODUCTS, products); startActivity(intent); break; } return super.onOptionsItemSelected(item); } public void searchByCategories(final Set<String> categories) { if (categories.size() == 0) { return; } constructUrl(); url += "&cat_keys="; for (String cat : categories) { url += cat + ","; } loadData(); } private void loadData() { task = new SimpleAsyncTask(this, new DataLoader() { @Override public void updateUI() { productAdapter = new ProductAdapter( ProductsListActivity.this, R.layout.product_list_item, products,new FacebookUtils(ProductsListActivity.this)); listView.setAdapter(productAdapter); } @Override public void loadData() { RestClient.getData(url, new JSONParser() { @Override public void onSuccess(JSONObject json) throws JSONException { JSONArray arr = json.getJSONArray("products"); products = Global.gsonWithHour.fromJson(arr.toString(), ProductInfo.getType()); Log.d(TAG, "load " + products.size() + " products"); } @Override public void onFailure(String message) { task.hasData = false; task.message = message; task.cancel(true); } }); } }); task.execute(); } @Override protected boolean isRouteDisplayed() { return false; } }
package com.knightly.dynamicproxy; /** * Created by knightly on 2018/2/13. */ public interface Moveable { void move(); }
package com.pelephone_mobile.mypelephone.ui.adapters; import android.content.Context; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import com.pelephone_mobile.R; import com.pelephone_mobile.mypelephone.network.rest.pojos.BranchItem; import com.pelephone_mobile.mypelephone.ui.components.ArialBoldTextView; import com.pelephone_mobile.mypelephone.ui.components.ArialTextView; import java.util.List; /** * Created by Gali.Issachar on 26/12/13. */ public class FindBranchesResultsListAdapter extends BaseAdapter { private Context context; private List<BranchItem> branchesList; public FindBranchesResultsListAdapter(Context context, List<BranchItem> branchesList){ this.context = context; this.branchesList = branchesList; } @Override public int getCount() { return branchesList.size(); } @Override public Object getItem(int position) { return branchesList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null){ convertView = LayoutInflater.from(context).inflate(R.layout.find_branches_list_result_item,null,false); } ArialBoldTextView tvBranchName = (ArialBoldTextView) convertView.findViewById(R.id.tvBranchName); ArialTextView tvBranchAddress = (ArialTextView) convertView.findViewById(R.id.tvBranchAddress); tvBranchName.setText(Html.fromHtml(branchesList.get(position).name)); tvBranchAddress.setText(Html.fromHtml(branchesList.get(position).address)); return convertView; } }
/* * This file is part of lambda, licensed under the MIT License. * * Copyright (c) 2018 KyoriPowered * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.kyori.lambda.exception; import org.checkerframework.checker.nullness.qual.NonNull; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.ExecutionException; /** * A collection of methods for working with exceptions. */ public interface Exceptions { /** * Re-throws an exception, sneakily. * * @param exception the exception * @param <E> the exception type * @return nothing * @throws E the exception */ @SuppressWarnings("unchecked") static <E extends Throwable> @NonNull RuntimeException rethrow(final @NonNull Throwable exception) throws E { throw (E) exception; } /** * Propagates {@code throwable} as-is if it is an instance of {@link RuntimeException} or * {@link Error}, otherwise wraps it in a {@code RuntimeException} and then * propagates. * * @param throwable the throwable * @return nothing */ static RuntimeException propagate(final @NonNull Throwable throwable) { throwIfUnchecked(throwable); throw new RuntimeException(throwable); } /** * Throws {@code throwable} if it is a {@link RuntimeException} or {@link Error}. * * @param throwable the throwable */ static void throwIfUnchecked(final @NonNull Throwable throwable) { if(throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } if(throwable instanceof Error) { throw (Error) throwable; } } /** * Unwraps a throwable. * * @param throwable the throwable * @return the unwrapped throwable, or the original throwable */ static @NonNull Throwable unwrap(final @NonNull Throwable throwable) { if(throwable instanceof ExecutionException || throwable instanceof InvocationTargetException) { final /* @Nullable */ Throwable cause = throwable.getCause(); if(cause != null) { return cause; } } return throwable; } }
package com.cybex.provider.websocket; import android.util.Log; import com.cybex.provider.exception.NetworkStatusException; import com.cybex.provider.graphene.chain.AccountObject; import com.cybex.provider.graphene.chain.Asset; import com.cybex.provider.graphene.chain.AssetObject; import com.cybex.provider.graphene.chain.Authority; import com.cybex.provider.graphene.chain.BlockHeader; import com.cybex.provider.graphene.chain.BucketObject; import com.cybex.provider.graphene.chain.DynamicGlobalPropertyObject; import com.cybex.provider.graphene.chain.FeeAmountObject; import com.cybex.provider.graphene.chain.FullAccountObjectReply; import com.cybex.provider.graphene.chain.LimitOrder; import com.cybex.provider.graphene.chain.LimitOrderObject; import com.cybex.provider.graphene.chain.LockAssetObject; import com.cybex.provider.graphene.chain.MemoData; import com.cybex.provider.graphene.chain.ObjectId; import com.cybex.provider.graphene.chain.AccountHistoryObject; import com.cybex.provider.graphene.chain.Operations; import com.cybex.provider.graphene.chain.PrivateKey; import com.cybex.provider.graphene.chain.PublicKey; import com.cybex.provider.graphene.chain.SignedTransaction; import com.cybex.provider.graphene.chain.Types; import com.cybex.provider.graphene.chain.MarketTicker; import java.io.File; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import io.enotes.sdk.core.CardManager; import io.enotes.sdk.repository.db.entity.Card; import io.reactivex.Flowable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; public class BitsharesWalletWraper { private static BitsharesWalletWraper bitsharesWalletWraper = new BitsharesWalletWraper(); private WalletApi mWalletApi = new WalletApi(); private Map<ObjectId<AccountObject>, AccountObject> mMapAccountId2Object = new ConcurrentHashMap<>(); private Map<ObjectId<AccountObject>, List<Asset>> mMapAccountId2Asset = new ConcurrentHashMap<>(); private Map<ObjectId<AssetObject>, AssetObject> mMapAssetId2Object = new ConcurrentHashMap<>(); private Map<String, Types.public_key_type > mMapAddress2PublicKey = new ConcurrentHashMap<>(); private String mstrWalletFilePath; private List<ObjectId<AssetObject>> mObjectList = new ArrayList<>(); private List<String> addressList = new ArrayList<>(); private List<String> addressListFromPublicKey = new ArrayList<>(); private String password; private Disposable lockWalletDisposable; private BitsharesWalletWraper() { //mstrWalletFilePath = BitsharesApplication.getInstance().getFilesDir().getPath(); mstrWalletFilePath += "/wallet.json"; } public static BitsharesWalletWraper getInstance() { return bitsharesWalletWraper; } public void reset() { mWalletApi.reset(); // mWalletApi = new WalletApi(); mMapAccountId2Object.clear(); mMapAccountId2Asset.clear(); mMapAssetId2Object.clear(); File file = new File(mstrWalletFilePath); file.delete(); } public AccountObject get_account() { List<AccountObject> listAccount = mWalletApi.list_my_accounts(); if (listAccount == null || listAccount.isEmpty()) { return null; } return listAccount.get(0); } public boolean is_new() { return mWalletApi.is_new(); } public boolean is_locked() { return password == null; } public int load_wallet_file() { return mWalletApi.load_wallet_file(mstrWalletFilePath); } private int save_wallet_file() { return mWalletApi.save_wallet_file(mstrWalletFilePath); } public void build_connect() { mWalletApi.initialize(); } public void disconnect() { mWalletApi.disconnect(); } public List<AccountObject> list_my_accounts() { return mWalletApi.list_my_accounts(); } // public int import_key(String strAccountNameOrId, // String strPassword, // String strPrivateKey) { // // mWalletApi.set_password(strPassword); // // try { // int nRet = mWalletApi.import_key(strAccountNameOrId, strPrivateKey); // if (nRet != 0) { // return nRet; // } // } catch (NetworkStatusException e) { // e.printStackTrace(); // return -1; // } // // save_wallet_file(); // // for (AccountObject accountObject : list_my_accounts()) { // mMapAccountId2Object.put(accountObject.id, accountObject); // } // // return 0; // } // public int import_keys(String strAccountNameOrId, // String strPassword, // String strPrivateKey1, // String strPrivateKey2) { // // mWalletApi.set_password(strPassword); // // try { // int nRet = mWalletApi.import_keys(strAccountNameOrId, strPrivateKey1, strPrivateKey2); // if (nRet != 0) { // return nRet; // } // } catch (NetworkStatusException e) { // e.printStackTrace(); // return -1; // } // // save_wallet_file(); // // for (AccountObject accountObject : list_my_accounts()) { // mMapAccountId2Object.put(accountObject.id, accountObject); // } // // return 0; // } // public int import_brain_key(String strAccountNameOrId, // String strPassword, // String strBrainKey) { // mWalletApi.set_password(strPassword); // try { // int nRet = mWalletApi.import_brain_key(strAccountNameOrId, strBrainKey); // if (nRet != 0) { // return nRet; // } // } catch (NetworkStatusException e) { // e.printStackTrace(); // return ErrorCode.ERROR_IMPORT_NETWORK_FAIL; // } // // save_wallet_file(); // // for (AccountObject accountObject : list_my_accounts()) { // mMapAccountId2Object.put(accountObject.id, accountObject); // } // // return 0; // } // public int import_file_bin(String strPassword, // String strFilePath) { // File file = new File(strFilePath); // if (file.exists() == false) { // return ErrorCode.ERROR_FILE_NOT_FOUND; // } // // int nSize = (int)file.length(); // // final byte[] byteContent = new byte[nSize]; // // FileInputStream fileInputStream; // try { // fileInputStream = new FileInputStream(file); // fileInputStream.read(byteContent, 0, byteContent.length); // } catch (FileNotFoundException e) { // e.printStackTrace(); // return ErrorCode.ERROR_FILE_NOT_FOUND; // } catch (IOException e) { // e.printStackTrace(); // return ErrorCode.ERROR_FILE_READ_FAIL; // } // // WalletBackup walletBackup = FileBin.deserializeWalletBackup(byteContent, strPassword); // if (walletBackup == null) { // return ErrorCode.ERROR_FILE_BIN_PASSWORD_INVALID; // } // // String strBrainKey = walletBackup.getWallet(0).decryptBrainKey(strPassword); // //LinkedAccount linkedAccount = walletBackup.getLinkedAccounts()[0]; // // int nRet = ErrorCode.ERROR_IMPORT_NOT_MATCH_PRIVATE_KEY; // for (LinkedAccount linkedAccount : walletBackup.getLinkedAccounts()) { // nRet = import_brain_key(linkedAccount.getName(), strPassword, strBrainKey); // if (nRet == 0) { // break; // } // } // // return nRet; // } public int import_account_password(AccountObject accountObject, String strAccountName, String strPassword) { mWalletApi.set_password(strPassword); int nRet = mWalletApi.import_account_password(accountObject, strAccountName, strPassword); if (nRet == 0) { for (AccountObject account : list_my_accounts()) { mMapAccountId2Object.put(account.id, account); } password = strPassword; startLockWalletTimer(); } return nRet; } public int unlock(String strPassword) { return mWalletApi.unlock(strPassword); } public int lock() { return mWalletApi.lock(); } public void startLockWalletTimer() { lockWalletDisposable = Flowable.intervalRange(0, 1, 1, 1, TimeUnit.MINUTES) .observeOn(AndroidSchedulers.mainThread()) .doOnNext(new Consumer<Long>() { @Override public void accept(Long aLong) throws Exception { password = null; } }) .doOnComplete(new Action() { @Override public void run() throws Exception { } }) .doOnCancel(new Action() { @Override public void run() throws Exception { password = null; } }) .subscribe(); } public void cancelLockWalletTime() { if (lockWalletDisposable != null && !lockWalletDisposable.isDisposed()) { lockWalletDisposable.dispose(); } } // public List<Asset> list_balances(boolean bRefresh) throws NetworkStatusException { // List<Asset> listAllAsset = new ArrayList<>(); // for (AccountObject accountObject : list_my_accounts()) { // List<Asset> listAsset = list_account_balance(accountObject.id, bRefresh); // // listAllAsset.addAll(listAsset); // } // // return listAllAsset; // } // public List<Asset> list_account_balance(ObjectId<AccountObject> accountObjectId, // boolean bRefresh) throws NetworkStatusException { // List<Asset> listAsset = mMapAccountId2Asset.get(accountObjectId); // if (bRefresh || listAsset == null) { // listAsset = mWalletApi.list_account_balance(accountObjectId); // mMapAccountId2Asset.put(accountObjectId, listAsset); // } // // return listAsset; // } // public List<AccountHistoryObject> get_history(boolean bRefresh) throws NetworkStatusException { // List<AccountHistoryObject> listAllHistoryObject = new ArrayList<>(); // for (AccountObject accountObject : list_my_accounts()) { // List<AccountHistoryObject> listHistoryObject = get_account_history( // accountObject.id, // 100, // bRefresh // ); // // listAllHistoryObject.addAll(listHistoryObject); // } // // return listAllHistoryObject; // } // public void get_account_history(ObjectId<AccountObject> accountObjectId, // int nLimit, // MessageCallback<Reply<List<AccountHistoryObject>>> callback) throws NetworkStatusException { // mWalletApi.get_account_history(accountObjectId, nLimit, callback); // } // public List<AssetObject> list_assets(String strLowerBound, int nLimit) throws NetworkStatusException { // return mWalletApi.list_assets(strLowerBound, nLimit); // } // public Map<ObjectId<AssetObject>, AssetObject> get_assets(List<ObjectId<AssetObject>> listAssetObjectId) throws NetworkStatusException { // Map<ObjectId<AssetObject>, AssetObject> mapId2Object = new HashMap<>(); // // List<ObjectId<AssetObject>> listRequestId = new ArrayList<>(); // for (ObjectId<AssetObject> objectId : listAssetObjectId) { // AssetObject assetObject = mMapAssetId2Object.get(objectId); // if (assetObject != null) { // mapId2Object.put(objectId, assetObject); // } else { // listRequestId.add(objectId); // } // } // // if (listRequestId.isEmpty() == false) { // List<AssetObject> listAssetObject = mWalletApi.get_assets(listRequestId); // for (AssetObject assetObject : listAssetObject) { // mapId2Object.put(assetObject.id, assetObject); // mMapAssetId2Object.put(assetObject.id, assetObject); // } // } // // return mapId2Object; // } public void lookup_asset_symbols(String strAssetSymbol, MessageCallback<Reply<List<AssetObject>>> callback) throws NetworkStatusException { mWalletApi.lookup_asset_symbols(strAssetSymbol, callback); } //get asset detail public void get_objects(String objectId, MessageCallback<Reply<List<AssetObject>>> callback) throws NetworkStatusException { mWalletApi.get_objects(objectId, callback); } public void get_objects(Set<String> objectIds, MessageCallback<Reply<List<AssetObject>>> callback) throws NetworkStatusException { mWalletApi.get_objects(objectIds, callback); } public void get_accounts(List<String> accountIds, MessageCallback<Reply<List<AccountObject>>> callback) throws NetworkStatusException { mWalletApi.get_accounts(accountIds, callback); } public void get_block(int callId, int blockNumber, MessageCallback<Reply<BlockHeader>> callback) throws NetworkStatusException { mWalletApi.get_block(callId, blockNumber, callback); } public void get_block_header(int blockNumber, MessageCallback<Reply<BlockHeader>> callback) throws NetworkStatusException { mWalletApi.get_block_header(blockNumber, callback); } public void get_recent_transaction_by_id(String transactionId, MessageCallback<Reply<Object>> callback) throws NetworkStatusException { mWalletApi.get_recent_transaction_by_id(transactionId, callback); } public Operations.transfer_operation getTransferOperation(ObjectId<AccountObject> from, ObjectId<AccountObject> to, ObjectId<AssetObject> transferAssetId, long feeAmount, ObjectId<AssetObject> feeAssetId, long transferAmount, String memo, Types.public_key_type fromMemoKey, Types.public_key_type toMemoKey) { return mWalletApi.getTransferOperation(from, to, transferAssetId, feeAmount, feeAssetId, transferAmount, memo, fromMemoKey, toMemoKey); } public Operations.transfer_operation getTransferOperationWithLockTime(ObjectId<AccountObject> from, ObjectId<AccountObject> to, ObjectId<AssetObject> transferAssetId, long feeAmount, ObjectId<AssetObject> feeAssetId, long transferAmount, String memo, Types.public_key_type fromMemoKey, Types.public_key_type toMemoKey, Types.public_key_type toActiveKey, long vesting_period, int type) { return mWalletApi.getTransferOperationWithLockTime(from, to, transferAssetId, feeAmount, feeAssetId, transferAmount, memo, fromMemoKey, toMemoKey, toActiveKey, vesting_period, type); } public Operations.limit_order_create_operation getLimitOrderCreateOperation(ObjectId<AccountObject> accountId, ObjectId<AssetObject> assetFeeId, ObjectId<AssetObject> assetSellId, ObjectId<AssetObject> assetReceiveId, long amountFee, long amountSell, long amountReceive) { return mWalletApi.getLimitOrderCreateOperation(accountId, assetFeeId, assetSellId, assetReceiveId, amountFee, amountSell, amountReceive); } public Operations.limit_order_cancel_operation getLimitOrderCancelOperation(ObjectId<AccountObject> accountId, ObjectId<AssetObject> assetFeeId, ObjectId<LimitOrder> limitOrderId, long amountFee) { return mWalletApi.getLimitOrderCancelOperation(accountId, assetFeeId, limitOrderId, amountFee); } public Operations.cancel_all_operation getLimitOrderCancelAllOperation(ObjectId<AssetObject> assetFeeId, long amountFee, ObjectId<AccountObject> sellerId, ObjectId<AssetObject> receiveAssetId, ObjectId<AssetObject> sellAssetId) { return mWalletApi.getLimitOrderCancelAllOperation(assetFeeId, amountFee, sellerId, receiveAssetId, sellAssetId); } public Operations.withdraw_deposit_history_operation getWithdrawDepositOperation(String accountName, int offset, int size, String fundType, String asset, Date expiration) { return mWalletApi.getWithdrawDepositOperation(accountName, offset, size, fundType, asset, expiration); } public Operations.balance_claim_operation getBalanceClaimOperation(long fee, ObjectId<AssetObject> feeAssetId, ObjectId<AccountObject> depositToAccount, ObjectId<LockAssetObject> balanceToClaim, Types.public_key_type balanceOwnerKey, long totalClaimedAmount, ObjectId<AssetObject> totalClaimedAmountId) { return mWalletApi.getBalanceClaimOperation(fee, feeAssetId, depositToAccount, balanceToClaim, balanceOwnerKey, totalClaimedAmount, totalClaimedAmountId); } public Operations.account_update_operation getAccountUpdateOperation(ObjectId<AssetObject> feeAssetId, long fee, ObjectId<AccountObject> accountId, Authority authority, Types.account_options account_options, Types.public_key_type public_key_type) { return mWalletApi.getAccountUpdateOperation(feeAssetId, fee, accountId, authority, account_options, public_key_type); } public SignedTransaction getSignedTransaction(AccountObject accountObject, Operations.base_operation operation, int operationId, DynamicGlobalPropertyObject dynamicGlobalPropertyObject) { return mWalletApi.getSignedTransaction(accountObject, operation, operationId, dynamicGlobalPropertyObject); } public SignedTransaction getSignedTransactinForTickets(AccountObject accountObject, Operations.base_operation operation, int operationId, BlockHeader blockHeader) throws ParseException { return mWalletApi.getSignedTransactionForTicket(accountObject, operation, operationId, blockHeader); } public SignedTransaction getSignedTransactionByENotesForTicket(CardManager cardManager, Card card, AccountObject accountObject, Operations.base_operation operation, int operationId, BlockHeader blockHeader ) throws ParseException { return mWalletApi.getSignedTransactionByENotesForTicket(cardManager, card, accountObject, operation, operationId, blockHeader); } public String getChatMessageSignature(AccountObject accountObject, String message){ return mWalletApi.getChatMessageSignature(accountObject, message); } public String getWithdrawDepositSignature(AccountObject accountObject, Operations.base_operation operation) { return mWalletApi.getWithdrawDepositSignature(accountObject, operation); } public SignedTransaction getSignedTransactionByENotes(CardManager cardManager, Card card, AccountObject accountObject, Operations.base_operation operation, int operationId, DynamicGlobalPropertyObject dynamicGlobalPropertyObject) { return mWalletApi.getSignedTransactionByENotes(cardManager, card, accountObject, operation, operationId, dynamicGlobalPropertyObject); } public String getMemoMessage(MemoData memoData) { return mWalletApi.getMemoMessage(memoData); } // public signed_transaction transfer(String strFrom, // String strTo, // String strAmount, // String strAssetSymbol, // String strMemo) throws NetworkStatusException { // signed_transaction signedTransaction = mWalletApi.transfer( // strFrom, // strTo, // strAmount, // strAssetSymbol, // strMemo // ); // return signedTransaction; // } // public BitshareData prepare_data_to_display(boolean bRefresh) { // try { // List<Asset> listBalances = BitsharesWalletWraper.getInstance().list_balances(bRefresh); // // List<AccountHistoryObject> operationHistoryObjectList = BitsharesWalletWraper.getInstance().get_history(bRefresh); // HashSet<ObjectId<AccountObject>> hashSetObjectId = new HashSet<ObjectId<AccountObject>>(); // HashSet<ObjectId<AssetObject>> hashSetAssetObject = new HashSet<ObjectId<AssetObject>>(); // // List<Pair<AccountHistoryObject, Date>> listHistoryObjectTime = new ArrayList<Pair<AccountHistoryObject, Date>>(); // for (AccountHistoryObject historyObject : operationHistoryObjectList) { // block_header blockHeader = BitsharesWalletWraper.getInstance().get_block_header(historyObject.block_num); // listHistoryObjectTime.add(new Pair<>(historyObject, blockHeader.timestamp)); // if (historyObject.op.nOperationType <= Operations.ID_CREATE_ACCOUNT_OPERATION) { // Operations.base_operation operation = (Operations.base_operation)historyObject.op.operationContent; // hashSetObjectId.addAll(operation.get_account_id_list()); // hashSetAssetObject.addAll(operation.get_asset_id_list()); // } // } // // // 保证默认数据一直存在 // hashSetAssetObject.add(new ObjectId<AssetObject>(0, AssetObject.class)); // // //// TODO: 06/09/2017 这里需要优化到一次调用 // // for (Asset assetBalances : listBalances) { // hashSetAssetObject.add(assetBalances.asset_id); // } // // List<ObjectId<AccountObject>> listAccountObjectId = new ArrayList<ObjectId<AccountObject>>(); // listAccountObjectId.addAll(hashSetObjectId); // Map<ObjectId<AccountObject>, AccountObject> mapId2AccountObject = // BitsharesWalletWraper.getInstance().get_accounts(listAccountObjectId); // // // List<ObjectId<AssetObject>> listAssetObjectId = new ArrayList<ObjectId<AssetObject>>(); // listAssetObjectId.addAll(hashSetAssetObject); // // // 生成id 2 asset_object映身 // Map<ObjectId<AssetObject>, AssetObject> mapId2AssetObject = // BitsharesWalletWraper.getInstance().get_assets(listAssetObjectId); // // SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(BitsharesApplication.getInstance()); // String strCurrencySetting = prefs.getString("currency_setting", "USD"); // // AssetObject currencyObject = mWalletApi.list_assets(strCurrencySetting, 1).get(0); // mapId2AssetObject.put(currencyObject.id, currencyObject); // // hashSetAssetObject.add(currencyObject.id); // // listAssetObjectId.clear(); // listAssetObjectId.addAll(hashSetAssetObject); // // Map<ObjectId<AssetObject>, BucketObject> mapAssetId2Bucket = get_market_histories_base(listAssetObjectId); // // mBitshareData = new BitshareData(); // mBitshareData.assetObjectCurrency = currencyObject; // mBitshareData.listBalances = listBalances; // mBitshareData.listHistoryObject = listHistoryObjectTime; // mBitshareData.mapId2AssetObject = mapId2AssetObject; // //mBitshareData.mapId2AccountObject = mapId2AccountObject; // mBitshareData.mapAssetId2Bucket = mapAssetId2Bucket; // // return mBitshareData; // // } catch (NetworkStatusException e) { // e.printStackTrace(); // } // // return null; // } // 获取对于基础货币的所有市场价格 // public Map<ObjectId<AssetObject>, BucketObject> get_market_histories_base(List<ObjectId<AssetObject>> listAssetObjectId) throws NetworkStatusException { // dynamic_global_property_object dynamicGlobalPropertyObject = mWalletApi.get_dynamic_global_properties(); // // Date dateObject = dynamicGlobalPropertyObject.time; // Calendar calendar = Calendar.getInstance(); // calendar.setTime(dateObject); // calendar.add(Calendar.HOUR, -12); // // Date dateObjectStart = calendar.getTime(); // // calendar.setTime(dateObject); // calendar.add(Calendar.SECOND, 30); // // Date dateObjectEnd = calendar.getTime(); // // Map<ObjectId<AssetObject>, BucketObject> mapId2BucketObject = new HashMap<>(); // // ObjectId<AssetObject> assetObjectBase = new ObjectId<AssetObject>(0, AssetObject.class); // for (ObjectId<AssetObject> objectId : listAssetObjectId) { // if (objectId.equals(assetObjectBase)) { // continue; // } // List<BucketObject> listBucketObject = mWalletApi.get_market_history( // objectId, // assetObjectBase, // 3600, // dateObjectStart, // dateObjectEnd // ); // // if (listBucketObject.isEmpty() == false) { // BucketObject bucketObject = listBucketObject.get(listBucketObject.size() - 1); // mapId2BucketObject.put(objectId, bucketObject); // } // } // // return mapId2BucketObject; // } public void get_market_history(ObjectId<AssetObject> baseAssetId, ObjectId<AssetObject> quoteAssetId, int nBucket, Date dateStart, Date dateEnd, MessageCallback<Reply<List<BucketObject>>> callback) throws NetworkStatusException { mWalletApi.get_market_history(baseAssetId, quoteAssetId, nBucket, dateStart, dateEnd, callback); } public void subscribe_to_market(String id, String base, String quote, MessageCallback<Reply<String>> callback) throws NetworkStatusException { mWalletApi.subscribe_to_market(id, base, quote, callback); } public AtomicInteger get_call_id() { return mWalletApi.getCallId(); } // public void set_subscribe_market(boolean filter) throws NetworkStatusException { // mWalletApi.set_subscribe_market(filter); // } // public void get_ticker(String base, String quote, MessageCallback<Reply<MarketTicker>> callback) throws NetworkStatusException { mWalletApi.get_ticker(base, quote, callback); } // public List<MarketTrade> get_trade_history(String base, String quote, Date start, Date end, int limit) // throws NetworkStatusException { // return mWalletApi.get_trade_history(base, quote, start, end, limit); // } public void get_fill_order_history(ObjectId<AssetObject> base, ObjectId<AssetObject> quote, int limit, MessageCallback<Reply<List<HashMap<String, Object>>>> callback) throws NetworkStatusException { mWalletApi.get_fill_order_history(base, quote, limit, callback); } public void get_limit_orders(ObjectId<AssetObject> base, ObjectId<AssetObject> quote, int limit, MessageCallback<Reply<List<LimitOrderObject>>> callback) throws NetworkStatusException { mWalletApi.get_limit_orders(base, quote, limit, callback); } public void get_balance_objects(List<String> addresses, MessageCallback<Reply<List<LockAssetObject>>> callback) throws NetworkStatusException { mWalletApi.get_balance_objects(addresses, callback); } // public signed_transaction sell_asset(String amountToSell, String symbolToSell, // String minToReceive, String symbolToReceive, // int timeoutSecs, boolean fillOrKill) // throws NetworkStatusException { // return mWalletApi.sell_asset(amountToSell, symbolToSell, minToReceive, symbolToReceive, // timeoutSecs, fillOrKill); // } // public Asset calculate_sell_fee(AssetObject assetToSell, AssetObject assetToReceive, // double rate, double amount, // global_property_object globalPropertyObject) { // return mWalletApi.calculate_sell_fee(assetToSell, assetToReceive, rate, amount, // globalPropertyObject); // } // public Asset calculate_buy_fee(AssetObject assetToReceive, AssetObject assetToSell, // double rate, double amount, // global_property_object globalPropertyObject) { // return mWalletApi.calculate_buy_fee(assetToReceive, assetToSell, rate, amount, // globalPropertyObject); // } // public signed_transaction sell(String base, String quote, double rate, double amount) // throws NetworkStatusException { // return mWalletApi.sell(base, quote, rate, amount); // } // // public signed_transaction sell(String base, String quote, double rate, double amount, // int timeoutSecs) throws NetworkStatusException { // return mWalletApi.sell(base, quote, rate, amount, timeoutSecs); // } // // public signed_transaction buy(String base, String quote, double rate, double amount) // throws NetworkStatusException { // return mWalletApi.buy(base, quote, rate, amount); // } // // public signed_transaction buy(String base, String quote, double rate, double amount, // int timeoutSecs) throws NetworkStatusException { // return mWalletApi.buy(base, quote, rate, amount, timeoutSecs); // } // public BitshareData getBitshareData() { // return mBitshareData; // } public void get_account_object(String strAccount, MessageCallback<Reply<AccountObject>> callback) throws NetworkStatusException { mWalletApi.get_account_by_name(strAccount, callback); } // public Asset transfer_calculate_fee(String strAmount, // String strAssetSymbol, // String strMemo) throws NetworkStatusException { // return mWalletApi.transfer_calculate_fee(strAmount, strAssetSymbol, strMemo); // } // public String get_plain_text_message(memo_data memoData) { // return mWalletApi.decrypt_memo_message(memoData); // } public void get_full_accounts(List<String> names, boolean subscribe, MessageCallback<Reply<List<FullAccountObjectReply>>> callback) throws NetworkStatusException { mWalletApi.get_full_accounts(names, subscribe, callback); } public void get_required_fees(String assetId, int operationId, Operations.base_operation operation, MessageCallback<Reply<List<FeeAmountObject>>> callback) throws NetworkStatusException { mWalletApi.get_required_fees(assetId, operationId, operation, callback); } public void broadcast_transaction_with_callback(SignedTransaction signedTransaction, MessageCallback<Reply<String>> callback) throws NetworkStatusException { mWalletApi.broadcast_transaction_with_callback(signedTransaction, callback); } //Todo: add asset_object_to_id_map // public List<ObjectId<AssetObject>> getObjectList() { // if (mObjectList.size() == 0) { // mFullAccountObjects.get(0).balances // } // return mObjectList; // } // public signed_transaction cancel_order(ObjectId<LimitOrderObject> id) // throws NetworkStatusException { // return mWalletApi.cancel_order(id); // } // public void get_dynamic_global_properties(MessageCallback<Reply<DynamicGlobalPropertyObject>> callback) throws NetworkStatusException { mWalletApi.get_dynamic_global_properties(callback); } private List<String> getAddressesForLockAsset(String strAccountName, String strPassword) { PrivateKey privateActiveKey = PrivateKey.from_seed(strAccountName + "active" + strPassword); PrivateKey privateOwnerKey = PrivateKey.from_seed(strAccountName + "owner" + strPassword); PrivateKey privateMemoKey = PrivateKey.from_seed(strAccountName + "memo" + strPassword); Types.public_key_type publicActiveKeyType = new Types.public_key_type(privateActiveKey.get_public_key(true), true); Types.public_key_type publicOwnerKeyType = new Types.public_key_type(privateOwnerKey.get_public_key(true), true); Types.public_key_type publicMemoKeyType = new Types.public_key_type(privateMemoKey.get_public_key(true), true); Types.public_key_type publicActiveKeyTypeUnCompressed = new Types.public_key_type(privateActiveKey.get_public_key(false), false); Types.public_key_type publicOwnerKeyTypeUnCompressed = new Types.public_key_type(privateOwnerKey.get_public_key(false), false); Types.public_key_type publicMemoKeyTypeUnCompressed = new Types.public_key_type(privateMemoKey.get_public_key(false), false); String address = publicActiveKeyType.getAddress(); addressList.add(address); mMapAddress2PublicKey.put(address, publicActiveKeyType); String ownerAddress = publicOwnerKeyType.getAddress(); addressList.add(ownerAddress); mMapAddress2PublicKey.put(ownerAddress, publicOwnerKeyType); String memoAddress = publicMemoKeyType.getAddress(); addressList.add(memoAddress); mMapAddress2PublicKey.put(memoAddress, publicMemoKeyType); String PTSAddress = publicActiveKeyType.getPTSAddress(publicActiveKeyType.key_data); addressList.add(PTSAddress); mMapAddress2PublicKey.put(PTSAddress, publicActiveKeyType); String ownerPtsAddress = publicOwnerKeyType.getPTSAddress(publicOwnerKeyType.key_data); addressList.add(ownerPtsAddress); mMapAddress2PublicKey.put(ownerPtsAddress, publicOwnerKeyType); String memoPtsAddress = publicMemoKeyType.getPTSAddress(publicMemoKeyType.key_data); addressList.add(memoPtsAddress); mMapAddress2PublicKey.put(memoPtsAddress, publicMemoKeyType); String unCompressedPts = publicActiveKeyTypeUnCompressed.getPTSAddress(publicActiveKeyTypeUnCompressed.key_data_uncompressed); addressList.add(unCompressedPts); mMapAddress2PublicKey.put(unCompressedPts, publicActiveKeyType); String unCompressedOwnerKey = publicOwnerKeyTypeUnCompressed.getPTSAddress(publicOwnerKeyTypeUnCompressed.key_data_uncompressed); addressList.add(unCompressedOwnerKey); mMapAddress2PublicKey.put(unCompressedOwnerKey, publicOwnerKeyType); String unCompressedMemo = publicMemoKeyTypeUnCompressed.getPTSAddress(publicMemoKeyTypeUnCompressed.key_data_uncompressed); addressList.add(unCompressedMemo); mMapAddress2PublicKey.put(unCompressedMemo, publicMemoKeyType); Log.e("Address", address); Log.e("OwnerAddress", ownerAddress); Log.e("ActivePTSAddress", PTSAddress); Log.e("OwnerPtsAddress", ownerPtsAddress); Log.e("MemoAddress", memoAddress); Log.e("MemoPTSAddress", memoPtsAddress); Log.e("uncompressedActive", unCompressedPts); Log.e("uncompressedOwner", unCompressedOwnerKey); Log.e("uncompressedMemo", unCompressedMemo); return addressList; } public List<String> getAddressListFromPublicKey(Card card) { if (addressListFromPublicKey.size() != 0) { return addressListFromPublicKey; } else { Types.public_key_type public_key_type_compress = new Types.public_key_type(new PublicKey(card.getBitCoinECKey().getPubKeyPoint().getEncoded(true), true), true); Types.public_key_type public_key_type_uncompress = new Types.public_key_type(new PublicKey(card.getBitCoinECKey().getPubKeyPoint().getEncoded(false), false), false); addressListFromPublicKey.add(public_key_type_compress.getAddress()); addressListFromPublicKey.add(public_key_type_uncompress.getAddress()); addressListFromPublicKey.add(public_key_type_compress.getPTSAddress(public_key_type_compress.key_data)); addressListFromPublicKey.add(public_key_type_uncompress.getPTSAddress(public_key_type_uncompress.key_data_uncompressed)); return addressListFromPublicKey; } } public List<String> getAddressList(String userName, String passWord) { if (addressList.size() != 0) { return addressList; } else { return getAddressesForLockAsset(userName, passWord); } } public Types.public_key_type getPublicKeyFromAddress(String address) { if (!mMapAddress2PublicKey.isEmpty()) { for (Map.Entry<String, Types.public_key_type> entry : mMapAddress2PublicKey.entrySet() ) { if (entry.getKey().equals(address)) { return entry.getValue(); } } } return null; } public String getPassword() { return password; } public void clearAddressesForLockAsset(){ addressList.clear(); } }
package compiler; import com.next.schema.table.Table; public class TableImpl extends Table { public boolean isKey(String colName) { return (super.getKey().indexOf(colName)!=-1); } }
/** * Reader * package provides complete set of tools for reading * @author michailremmele */ package it.sevenbits.codecorrector.reader;
package com.alibaba.druid.bvt.pool; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.concurrent.atomic.AtomicInteger; import javax.sql.ConnectionEvent; import javax.sql.ConnectionEventListener; import javax.sql.PooledConnection; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.druid.mock.MockDriver; import com.alibaba.druid.mock.MockStatementBase; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidPooledConnection; /** * 这个场景测试defaultAutoCommit * * @author wenshao [szujobs@hotmail.com] */ public class DruidDataSourceTest_getPooledConnection extends TestCase { private DruidDataSource dataSource; protected void setUp() throws Exception { dataSource = new DruidDataSource(); dataSource.setUrl("jdbc:mock:xxx"); dataSource.setTestOnBorrow(false); dataSource.setRemoveAbandoned(true); dataSource.setDriver(new MockDriver() { public ResultSet executeQuery(MockStatementBase stmt, String sql) throws SQLException { throw new SQLException(); } }); } protected void tearDown() throws Exception { dataSource.close(); } public void test_conn() throws Exception { PooledConnection conn = dataSource.getPooledConnection(); conn.close(); } public void test_conn_1() throws Exception { Exception error = null; try { dataSource.getPooledConnection(null, null); } catch (UnsupportedOperationException e) { error = e; } Assert.assertNotNull(error); } public void test_event_error() throws Exception { DruidPooledConnection conn = (DruidPooledConnection) dataSource.getPooledConnection(); final AtomicInteger errorCount = new AtomicInteger(); conn.addConnectionEventListener(new ConnectionEventListener() { @Override public void connectionErrorOccurred(ConnectionEvent event) { errorCount.incrementAndGet(); } @Override public void connectionClosed(ConnectionEvent event) { } }); PreparedStatement stmt = conn.prepareStatement("select ?"); try { stmt.executeQuery(); } catch (SQLException e) { } Assert.assertEquals(1, errorCount.get()); conn.close(); } }
package com.soldevelo.vmi.testutils.packets; import com.soldevelo.vmi.ex.VMIException; import com.soldevelo.vmi.packets.TestRequest; import com.soldevelo.vmi.packets.TestRequestPhase2; import com.soldevelo.vmi.utils.MacHelper; import java.net.InetAddress; import java.net.UnknownHostException; public class TestRequestBuilder { public static final String DEFAULT_ADDRESS = "192.168.1.3"; public static final int DEFAULT_DEST_PORT = 3300; public static final int DEFAULT_SOURCE_PORT = 59413; public static final String DEFAULT_MAC = "aa:b1:c3:11:a2"; private TestRequest testRequest; public TestRequestBuilder() { this(0); } public TestRequestBuilder(int ver) { if (ver == 1) { testRequest = new TestRequestPhase2(); } else { testRequest = new TestRequest(); } testRequest.setDTE(false); testRequest.setUTE(false); } public TestRequestBuilder withAddress(InetAddress address) { testRequest.setAddress(address); return this; } public TestRequestBuilder withSourcePort(int port) { testRequest.setSourcePort(port); return this; } public TestRequestBuilder withDestinationPort(int port) { testRequest.setDestinationPort(port); return this; } public TestRequestBuilder withMacAddress(String mac) { testRequest.setMacAddress(MacHelper.toBytes(mac)); return this; } public TestRequestBuilder withMacAddress(byte[] mac) { testRequest.setMacAddress(mac); return this; } public TestRequestBuilder withHttpDownload() { testRequest.setPT0(false); testRequest.setPT1(false); testRequest.setPT2(false); testRequest.setDTR(true); return this; } public TestRequestBuilder withHttpUpload() { testRequest.setPT0(false); testRequest.setPT1(false); testRequest.setPT2(false); testRequest.setUTR(true); return this; } public TestRequestBuilder withReserved(byte[] reserved) { testRequest.setReserved(reserved); return this; } public TestRequestBuilder defaultPakcet() { InetAddress inetAddress; try { inetAddress = InetAddress.getByName(DEFAULT_ADDRESS); } catch (UnknownHostException e) { throw new VMIException("Unable to get InetAdress by name " + DEFAULT_ADDRESS, e); } withAddress(inetAddress); withMacAddress(DEFAULT_MAC); withSourcePort(DEFAULT_SOURCE_PORT); withDestinationPort(DEFAULT_DEST_PORT); withHttpUpload(); withHttpDownload(); return this; } public TestRequest build() { return testRequest; } }
package org.springframework.roo.addon.layers.service.addon; import static org.springframework.roo.model.RooJavaType.ROO_SERVICE; import static org.springframework.roo.model.RooJavaType.ROO_SERVICE_IMPL; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Service; import org.osgi.service.component.ComponentContext; import org.springframework.roo.addon.finder.addon.FinderMetadata; import org.springframework.roo.addon.finder.addon.parser.FinderMethod; import org.springframework.roo.addon.layers.service.annotations.RooServiceImpl; import org.springframework.roo.classpath.PhysicalTypeIdentifier; import org.springframework.roo.classpath.PhysicalTypeMetadata; import org.springframework.roo.classpath.customdata.taggers.CustomDataKeyDecorator; import org.springframework.roo.classpath.customdata.taggers.CustomDataKeyDecoratorTracker; import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails; import org.springframework.roo.classpath.details.ItdTypeDetails; import org.springframework.roo.classpath.details.MemberHoldingTypeDetails; import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue; import org.springframework.roo.classpath.details.annotations.AnnotationMetadata; import org.springframework.roo.classpath.itd.AbstractMemberDiscoveringItdMetadataProvider; import org.springframework.roo.classpath.itd.ItdTypeDetailsProvidingMetadataItem; import org.springframework.roo.classpath.layers.LayerTypeMatcher; import org.springframework.roo.metadata.MetadataDependencyRegistry; import org.springframework.roo.metadata.MetadataIdentificationUtils; import org.springframework.roo.metadata.internal.MetadataDependencyRegistryTracker; import org.springframework.roo.model.JavaSymbolName; import org.springframework.roo.model.JavaType; import org.springframework.roo.model.RooJavaType; import org.springframework.roo.project.LogicalPath; import org.springframework.roo.support.logging.HandlerUtils; /** * Implementation of {@link ServiceImplMetadataProvider}. * * @author Juan Carlos García * @since 2.0 */ @Component @Service public class ServiceImplMetadataProviderImpl extends AbstractMemberDiscoveringItdMetadataProvider implements ServiceImplMetadataProvider { protected final static Logger LOGGER = HandlerUtils .getLogger(ServiceImplMetadataProviderImpl.class); private final Map<JavaType, String> domainTypeToServiceMidMap = new LinkedHashMap<JavaType, String>(); protected MetadataDependencyRegistryTracker registryTracker = null; protected CustomDataKeyDecoratorTracker keyDecoratorTracker = null; /** * This service is being activated so setup it: * <ul> * <li>Create and open the {@link MetadataDependencyRegistryTracker}.</li> * <li>Create and open the {@link CustomDataKeyDecoratorTracker}.</li> * <li>Registers {@link RooJavaType#ROO_SERVICE_IMPL} as additional * JavaType that will trigger metadata registration.</li> * <li>Set ensure the governor type details represent a class.</li> * </ul> */ @Override @SuppressWarnings("unchecked") protected void activate(final ComponentContext cContext) { context = cContext.getBundleContext(); super.setDependsOnGovernorBeingAClass(false); this.registryTracker = new MetadataDependencyRegistryTracker(context, this, PhysicalTypeIdentifier.getMetadataIdentiferType(), getProvidesType()); this.registryTracker.open(); addMetadataTrigger(ROO_SERVICE_IMPL); this.keyDecoratorTracker = new CustomDataKeyDecoratorTracker(context, getClass(), new LayerTypeMatcher( ROO_SERVICE_IMPL, new JavaSymbolName(RooServiceImpl.SERVICE_ATTRIBUTE))); this.keyDecoratorTracker.open(); } /** * This service is being deactivated so unregister upstream-downstream * dependencies, triggers, matchers and listeners. * * @param context */ protected void deactivate(final ComponentContext context) { MetadataDependencyRegistry registry = this.registryTracker.getService(); registry.removeNotificationListener(this); registry.deregisterDependency(PhysicalTypeIdentifier.getMetadataIdentiferType(), getProvidesType()); this.registryTracker.close(); removeMetadataTrigger(ROO_SERVICE_IMPL); CustomDataKeyDecorator keyDecorator = this.keyDecoratorTracker.getService(); keyDecorator.unregisterMatchers(getClass()); this.keyDecoratorTracker.close(); } @Override protected String createLocalIdentifier(final JavaType javaType, final LogicalPath path) { return ServiceImplMetadata.createIdentifier(javaType, path); } @Override protected String getGovernorPhysicalTypeIdentifier(final String metadataIdentificationString) { final JavaType javaType = ServiceImplMetadata.getJavaType(metadataIdentificationString); final LogicalPath path = ServiceImplMetadata.getPath(metadataIdentificationString); return PhysicalTypeIdentifier.createIdentifier(javaType, path); } public String getItdUniquenessFilenameSuffix() { return "Service_Impl"; } @Override protected String getLocalMidToRequest(final ItdTypeDetails itdTypeDetails) { // Determine the governor for this ITD, and whether any metadata is even // hoping to hear about changes to that JavaType and its ITDs final JavaType governor = itdTypeDetails.getName(); final String localMid = domainTypeToServiceMidMap.get(governor); if (localMid != null) { return localMid; } final MemberHoldingTypeDetails memberHoldingTypeDetails = getTypeLocationService().getTypeDetails(governor); if (memberHoldingTypeDetails != null) { for (final JavaType type : memberHoldingTypeDetails.getLayerEntities()) { final String localMidType = domainTypeToServiceMidMap.get(type); if (localMidType != null) { return localMidType; } } } return null; } @Override protected ItdTypeDetailsProvidingMetadataItem getMetadata( final String metadataIdentificationString, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final String itdFilename) { final ServiceImplAnnotationValues annotationValues = new ServiceImplAnnotationValues(governorPhysicalTypeMetadata); // Getting service interface JavaType serviceInterface = annotationValues.getService(); // Validate that contains service interface Validate.notNull(serviceInterface, "ERROR: You need to specify service interface to be implemented."); ClassOrInterfaceTypeDetails interfaceTypeDetails = getTypeLocationService().getTypeDetails(serviceInterface); // Getting related entity AnnotationMetadata serviceAnnotation = interfaceTypeDetails.getAnnotation(ROO_SERVICE); Validate.notNull(serviceAnnotation, "ERROR: Service interface should be annotated with @RooService"); AnnotationAttributeValue<JavaType> relatedEntity = serviceAnnotation.getAttribute("entity"); Validate.notNull(relatedEntity, "ERROR: @RooService annotation should has a reference to managed entity"); JavaType entity = relatedEntity.getValue(); ClassOrInterfaceTypeDetails entityDetails = getTypeLocationService().getTypeDetails(entity); AnnotationMetadata entityAnnotation = entityDetails.getAnnotation(RooJavaType.ROO_JPA_ENTITY); Validate.notNull(entityAnnotation, "ERROR: Related entity should be annotated with @RooJpaEntity"); // Getting entity identifier type final JavaType identifierType = getPersistenceMemberLocator().getIdentifierType(entity); Validate.notNull(identifierType, "ERROR: Related entity should define a field annotated with @Id"); // Check if related entity is readOnly or not AnnotationAttributeValue<Boolean> readOnlyAttribute = entityAnnotation.getAttribute("readOnly"); boolean readOnly = false; if (readOnlyAttribute != null && readOnlyAttribute.getValue()) { readOnly = true; } // Getting related repository to current entity Set<ClassOrInterfaceTypeDetails> repositories = getTypeLocationService().findClassesOrInterfaceDetailsWithAnnotation( RooJavaType.ROO_REPOSITORY_JPA); ClassOrInterfaceTypeDetails repositoryDetails = null; for (ClassOrInterfaceTypeDetails repository : repositories) { AnnotationAttributeValue<JavaType> entityAttr = repository.getAnnotation(RooJavaType.ROO_REPOSITORY_JPA).getAttribute("entity"); if (entityAttr != null && entityAttr.getValue().equals(entity)) { repositoryDetails = repository; break; } } // Check if we have a valid repository Validate .notNull( repositoryDetails, String .format( "ERROR: You must generate some @RooJpaRepository for entity '%s' to be able to generate services", entity.getSimpleTypeName())); // Getting finders to be included on current service List<FinderMethod> finders = new ArrayList<FinderMethod>(); final LogicalPath logicalPath = PhysicalTypeIdentifier.getPath(repositoryDetails.getDeclaredByMetadataId()); final String finderMetadataKey = FinderMetadata.createIdentifier(repositoryDetails.getType(), logicalPath); registerDependency(finderMetadataKey, metadataIdentificationString); final FinderMetadata finderMetadata = (FinderMetadata) getMetadataService().get(finderMetadataKey); if (finderMetadata != null) { finders = finderMetadata.getFinders(); } return new ServiceImplMetadata(metadataIdentificationString, aspectName, governorPhysicalTypeMetadata, serviceInterface, repositoryDetails, entity, identifierType, readOnly, finders); } private void registerDependency(final String upstreamDependency, final String downStreamDependency) { if (getMetadataDependencyRegistry() != null && StringUtils.isNotBlank(upstreamDependency) && StringUtils.isNotBlank(downStreamDependency) && !upstreamDependency.equals(downStreamDependency) && !MetadataIdentificationUtils.getMetadataClass(downStreamDependency).equals( MetadataIdentificationUtils.getMetadataClass(upstreamDependency))) { getMetadataDependencyRegistry().registerDependency(upstreamDependency, downStreamDependency); } } public String getProvidesType() { return ServiceImplMetadata.getMetadataIdentiferType(); } }
package ru.itmo.ctlab.sgmwcs.graph; public class Edge extends Unit { public Edge(Edge that) { super(that); } public Edge(int num) { super(num); } @Override public String toString() { return "E(" + String.valueOf(num) + ")"; } }
// ********************************************************** // 1. 제 목: // 2. 프로그램명: CourseScoreData.java // 3. 개 요: // 4. 환 경: JDK 1.3 // 5. 버 젼: 0.1 // 6. 작 성: Administrator 2003-09-19 // 7. 수 정: // // ********************************************************** package com.ziaan.complete; import java.util.Enumeration; import java.util.Hashtable; /** * @author Administrator * * To change the template for this generated type comment go to * Window > Preferences > Java > Code Generation > Code and Comments */ public class CourseScoreData { private String course ; private String cyear ; private String courseseq ; private String userid ; private int graduatedcnt ; private String isgraduated ; private double score ; private Hashtable SubjScoreDataList ; public CourseScoreData() { course = ""; cyear = ""; courseseq = ""; userid = ""; graduatedcnt = 0; isgraduated = ""; score = 0; SubjScoreDataList = new Hashtable(); } /** * @return */ public String getCourse() { return course; } /** * @return */ public String getCourseseq() { return courseseq; } /** * @return */ public String getCyear() { return cyear; } /** * @return */ public int getGraduatedcnt() { return graduatedcnt; } /** * @return */ public double getScore() { return score; } /** * @return */ public String getUserid() { return userid; } /** * @param string */ public void setCourse(String string) { course = string; } /** * @param string */ public void setCourseseq(String string) { courseseq = string; } /** * @param string */ public void setCyear(String string) { cyear = string; } /** * @param i */ public void setGraduatedcnt(int i) { graduatedcnt = i; } /** * @param d */ public void setScore(double d) { score = d; } /** * @param string */ public void setUserid(String string) { userid = string; } public SubjScoreData get(int index) { return (SubjScoreData)SubjScoreDataList.get(String.valueOf(index)); } public void add(SubjScoreData data) { SubjScoreDataList.put(String.valueOf(SubjScoreDataList.size() ), data); } public void remove(int index) { SubjScoreDataList.remove(String.valueOf(index)); } public void clear() { SubjScoreDataList.clear(); } public int size() { return SubjScoreDataList.size(); } public Enumeration elements() { return SubjScoreDataList.elements(); } /** * @return */ public String getIsgraduated() { return isgraduated; } /** * @param string */ public void setIsgraduated(String string) { isgraduated = string; } }
package com.next.infra.odata2; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.web.servlet.ServletComponentScan; import gen.table.BmoORDR; @SpringBootApplication @ServletComponentScan //@EnableJpaRepositories(basePackages = "your.repositories.pakage") @EntityScan(basePackageClasses = BmoORDR.class) public class AppOdata2Jpa { public static void main(String[] args) { SpringApplication.run(AppOdata2Jpa.class, args); } }
package com.hfjy.framework.logging; public enum LogTypes { TRACE, DEBUG, INFO, WARN, ERROR, SYSTEM, TRADE }
package com.lenovohit.hcp.base.web.rest; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.alibaba.druid.sql.dialect.odps.ast.OdpsAddStatisticStatement; import com.lenovohit.core.dao.Page; import com.lenovohit.core.exception.BaseException; import com.lenovohit.core.manager.GenericManager; import com.lenovohit.core.utils.JSONUtils; import com.lenovohit.core.utils.StringUtils; import com.lenovohit.core.web.MediaTypes; import com.lenovohit.core.web.utils.Result; import com.lenovohit.core.web.utils.ResultUtils; import com.lenovohit.hcp.base.model.Dictionary; import com.lenovohit.hcp.base.model.HcpUser; import com.lenovohit.hcp.base.model.Hospital; import com.lenovohit.hcp.base.utils.PinyinUtil; import com.lenovohit.hcp.base.utils.WubiUtil; /** * 医院基本信息管理 */ @RestController @RequestMapping("/hcp/base/hospital") public class HospitalRestController extends HcpBaseRestController { @Autowired private GenericManager<Hospital, String> hospitalManager; @Autowired private GenericManager<Dictionary, String> dictionaryManager; @RequestMapping(value = "/page/{start}/{limit}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forPage(@PathVariable("start") String start, @PathVariable("limit") String limit, @RequestParam(value = "data", defaultValue = "") String data) { Hospital query = JSONUtils.deserialize(data, Hospital.class); StringBuilder jql = new StringBuilder("from Hospital where 1=1 "); List<Object> values = new ArrayList<Object>(); if (!StringUtils.isEmpty(query.getHosName())) { jql.append("and hosName like ? "); values.add("%" + query.getHosName() + "%"); } if (!StringUtils.isEmpty(query.getSpellCode())) { jql.append("and spellCode like ? "); values.add("%" + query.getSpellCode() + "%"); } if (!StringUtils.isEmpty(query.getWbCode())) { jql.append("and wbCode like ? "); values.add("%" + query.getWbCode() + "%"); } if (!StringUtils.isEmpty(query.getParentId())) { jql.append("and parentId like ? "); values.add("%" + query.getParentId() + "%"); } if (!StringUtils.isEmpty(query.getHosArea())) { jql.append("and hosArea like ? "); values.add("%" + query.getHosArea() + "%"); } if (!StringUtils.isEmpty(query.getHosGrade())) { jql.append("and hosGrade like ? "); values.add("%" + query.getHosGrade() + "%"); } if (!StringUtils.isEmpty(query.getHosType())) { jql.append("and hosType like ? "); values.add("%" + query.getHosType() + "%"); } Page page = new Page(); page.setStart(start); page.setPageSize(limit); page.setQuery(jql.toString()); page.setValues(values.toArray()); hospitalManager.findPage(page); return ResultUtils.renderPageResult(page); } @RequestMapping(value = "/info/{id}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forInfo(@PathVariable("id") String id) { Hospital hospital = hospitalManager.get(id); return ResultUtils.renderPageResult(hospital); } @RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forList(@RequestParam(value = "data", defaultValue = "") String data) { List<Hospital> menus = hospitalManager.findAll(); return ResultUtils.renderSuccessResult(menus); } @RequestMapping(value = "/create", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8/* TEXT_PLAIN_UTF_8 */) public Result forCreateMenu(@RequestBody String data) { Hospital model = JSONUtils.deserialize(data, Hospital.class); Date now = new Date(); HcpUser user = this.getCurrentUser(); model.setCreateOper(user.getName()); model.setCreateTime(now); model.setUpdateOper(user.getName()); model.setUpdateTime(now); if (model.getSpellCode() == null) model.setSpellCode(PinyinUtil.getFirstSpell(model.getHosName())); if (model.getWbCode() == null) model.setWbCode(WubiUtil.getWBCode(model.getHosName())); // TODO 校验 Hospital saved = this.hospitalManager.save(model); return ResultUtils.renderSuccessResult(saved); } @RequestMapping(value = "/update", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8) public Result forUpdate(@RequestBody String data) { Hospital model = JSONUtils.deserialize(data, Hospital.class); if (model == null || StringUtils.isBlank(model.getId())) { return ResultUtils.renderFailureResult(); } Hospital old = hospitalManager.get(model.getId()); Date now = new Date(); HcpUser user = this.getCurrentUser(); model.setCreateTime(old.getCreateTime()); model.setCreateOper(old.getCreateOper()); model.setUpdateOper(user.getName()); model.setUpdateTime(now); this.hospitalManager.save(model); return ResultUtils.renderSuccessResult(); } @RequestMapping(value = "/remove/{id}", method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8) public Result forDeleteMenu(@PathVariable("id") String id) { try { this.hospitalManager.delete(id); } catch (Exception e) { throw new BaseException("删除失败"); } return ResultUtils.renderSuccessResult(); } @RequestMapping(value = "/removeAll", method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8) public Result forDeleteAll(@RequestBody String data) { @SuppressWarnings("rawtypes") List ids = JSONUtils.deserialize(data, List.class); StringBuilder idSql = new StringBuilder(); List<String> idvalues = new ArrayList<String>(); try { idSql.append("DELETE FROM B_HOSINFO WHERE ID IN ("); for (int i = 0; i < ids.size(); i++) { idSql.append("?"); idvalues.add(ids.get(i).toString()); if (i != ids.size() - 1) idSql.append(","); } idSql.append(")"); System.out.println(idSql.toString()); this.hospitalManager.executeSql(idSql.toString(), idvalues.toArray()); } catch (Exception e) { e.printStackTrace(); throw new BaseException("删除失败"); } return ResultUtils.renderSuccessResult(); } @RequestMapping(value = "/type/list", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forTypeList(@RequestParam(value = "data", defaultValue = "") String data) { String columnName; columnName = "PARENT_ID"; System.console(); List<Dictionary> models = dictionaryManager.find( " select distinct dict.columnDis as columnDis, dict.columnKey as columnKey, dict.columnVal as columnValue from Dictionary dict where 1 = 1 and dict.columnName = ? ", columnName); return ResultUtils.renderSuccessResult(models); } public String ObjectIsNull(Object obj) { if (obj == null) return ""; return obj.toString(); } @RequestMapping(value = "/listEdit", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forEdit(@RequestParam(value = "data", defaultValue = "") String data) { // List<Hospital> menus = hospitalManager.findAll(); // return ResultUtils.renderSuccessResult(menus); HcpUser user = this.getCurrentUser(); StringBuilder jql = new StringBuilder("from Hospital where 1=1 "); List<Object> values = new ArrayList<Object>(); if (!StringUtils.isEmpty(user.getHosId())) { jql.append("and hosId = ?"); values.add(user.getHosId()); } Page page = new Page(); page.setQuery(jql.toString()); page.setValues(values.toArray()); hospitalManager.findPage(page); return ResultUtils.renderSuccessResult(page); } }
package com.dpp.dao; import com.dpp.entity.Goods; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Map; @Repository public interface GoodsDao { /** * 查询所有商品 * @return */ @Select("<script>select * from goods where 1=1 " + "<if test=\"pr!=null and pr!=''\"> and price &gt;= #{startPrice} and price &lt;=#{endPrice}</if>" + "<if test=\"type!=null and type!=''\">and type=#{type}</if>" + "<if test=\"si!=null and si!=''\">and size=#{size}</if></script>") List<Goods> getAllGoods(Map map); }
package org.yxm.modules.gank; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import org.yxm.modules.base.mvp.BaseMvpFragment; import org.yxm.modules.gank.entity.GankTabEntity; import org.yxm.modules.gank.tab.GankTabFragment; public class GankFragment extends BaseMvpFragment<IGankView, GankPresenter> implements IGankView { private static final String TAG = "GankFragment"; private TabLayout mTablayout; private ViewPager mViewpager; private GankPagerAdapter mViewpagerAdapter; public static GankFragment newInstance() { return new GankFragment(); } @Override protected GankPresenter createPresenter() { return new GankPresenter(getContext()); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.main_fragment_layout, container, false); initViews(view); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mPresenter.loadData(); } private void initViews(View root) { mTablayout = root.findViewById(R.id.main_tablayout); mViewpager = root.findViewById(R.id.main_viewpager); } @Override public void initDataView(List<GankTabEntity> tabInfos) { List<String> titles = new ArrayList<>(); List<Fragment> fragments = new ArrayList<>(); for (GankTabEntity tabinfo : tabInfos) { titles.add(tabinfo.name); fragments.add(GankTabFragment.newInstance(tabinfo)); } // getChildFragmentManager():fragment下面的子fragment,child的fragmentmanager mViewpagerAdapter = new GankPagerAdapter(getChildFragmentManager(), titles, fragments); mTablayout.setTabsFromPagerAdapter(mViewpagerAdapter); mTablayout.setTabMode(TabLayout.MODE_SCROLLABLE); mTablayout.setupWithViewPager(mViewpager); mViewpager.setAdapter(mViewpagerAdapter); mViewpager.setOffscreenPageLimit(3); } }
package de.hdm.softwarepraktikum.server.db; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.*; import java.util.ArrayList; import java.util.Vector; import com.gargoylesoftware.htmlunit.javascript.host.Console; import de.hdm.softwarepraktikum.shared.bo.Group; import de.hdm.softwarepraktikum.shared.bo.Item; import de.hdm.softwarepraktikum.shared.bo.Person; import de.hdm.softwarepraktikum.shared.bo.Responsibility; import de.hdm.softwarepraktikum.shared.bo.ShoppingList; public class GroupMapper { /** * Die Klasse GroupMapper wird nur einmal instantiiert. Man spricht hierbei * von einem sogenannten <b>Singleton</b>. * <p> * Diese Variable ist durch den Bezeichner <code>static</code> nur einmal f�r * s�mtliche eventuellen Instanzen dieser Klasse vorhanden. Sie speichert die * einzige Instanz dieser Klasse. * * @author Bruno Herceg */ private static GroupMapper groupMapper = null; /** * Geschuetzter Konstruktor - verhindert die Moeglichkeit, mit <code>new</code> * neue Instanzen dieser Klasse zu erzeugen. */ protected GroupMapper() { } /* * Einhaltung der Singleton Eigenschaft des Mappers. */ public static GroupMapper groupMapper() { if(groupMapper == null) { groupMapper = new GroupMapper(); } return groupMapper; } /* * Einkaeufergruppe anhand ihrer Id suchen. */ public Group findById(int id) { //Herstellung einer Verbindung zur DB-Connection Connection con =DBConnection.connection(); try { //leeres SQL-Statement (JDBC) anlegen Statement stmt = con.createStatement(); //Statement ausfuellen und als Query an die DB schicken ResultSet rs = stmt.executeQuery("Select Group_ID, Title, user FROM Group" + "WHERE Group_ID= " + id); /* * Da id Primaerschluessel ist, kann max. nur ein Tupel zurueckgegeben * werden. Pruefe, ob ein Ergebnis vorliegt. */ if (rs.next()) { //Ergebnis-Tupel in Objekt umwandeln Group g = new Group(); g.setId(rs.getInt("Group_ID")); g.setTitle(rs.getString("Title")); g.setMember((ArrayList<Person>) rs.getArray("member")); return g; } }catch (SQLException e) { e.printStackTrace(); return null; } return null; } /** * Methode um ein <code>Group</code> Objekt in der Datenbank zu speichern * @param g * @return das neu gespiecherte Group-Objekt. */ public Group insert(Group g) { Connection con = DBConnection.connection(); try { Statement stmt = con.createStatement(); /* * Zunaechst schauen wir nach, welches der momentan hoechste * Primaerschluesselwert ist. */ ResultSet rs = stmt.executeQuery("SELECT MIN(Group_ID) AS minid " + "FROM `Group` "); // Wenn wir etwas zurueckerhalten, kann dies nur einzeilig sein if (rs.next()) { /* * i erhaelt den bisher maximalen, nun um 1 inkrementierten * Primaerschluessel. */ g.setId(rs.getInt("minid") - 1); PreparedStatement stmt2 = con.prepareStatement( "INSERT INTO `Group` (Group_ID, Title, Creationdate, Changedate) " + "VALUES (?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); stmt2.setInt(1, g.getId()); stmt2.setString(2, g.getTitle()); stmt2.setTimestamp(3, g.getCreationdate()); stmt2.setTimestamp(4, g.getChangedate()); System.out.println(stmt2); stmt2.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } /* * Rueckgabe, der evtl. korrigierten Group. */ return g; } /** * Wiederholtes Schreiben eines Objekts in die Datenbank. * * @param g * @return das als Parameter uebergebene Objekt */ public Group update(Group g) { Connection con = DBConnection.connection(); try { PreparedStatement st = con.prepareStatement("UPDATE `Group` SET Title = ?, Changedate = ? WHERE Group_ID= ?"); st.setString(1, g.getTitle()); st.setTimestamp(2, g.getChangedate()); st.setInt(3, g.getId()); st.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } // Um Analogie zu insert(Group g) zu wahren, wird g zurueckgegeben return g; } //Loeschung einer Gruppe public void delete(Group g) { Connection con = DBConnection.connection(); try { Statement stmt = con.createStatement(); stmt.executeUpdate("DELETE FROM `Group` " + "WHERE Group_ID=" + g.getId()); } catch(SQLException e) { e.printStackTrace(); } } /** * auslesen aller Kunden * @return Eine ArrayList mit Group-Objekten, die alle Gruppen im System darstellen. */ public ArrayList<Group> findAll() { Connection con = DBConnection.connection(); //Ergebnisvektor vorbereiten ArrayList<Group> result = new ArrayList<Group>(); try { Statement stmt = con.createStatement(); ResultSet rs = stmt .executeQuery("SELECT Group_ID, Title, member " + "FROM `Group` " + "ORDER BY Title"); // Fuer jeden Eintrag im Suchergebnis wird nun ein Group-Objekt erstellt. while(rs.next()) { Group g = new Group(); g.setId(rs.getInt("Group_ID")); g.setTitle(rs.getString("Title")); //Hinzufuegen des neuen Objekts zum Ergebnisvektor result.add(g); } } catch (SQLException e) { e.printStackTrace(); } //Ergebnis zurueckgeben return result; } /** * Auslesen aller Gruppen eines durch Fremdschluessel (id) gegebenen * Kunden. * @param memberID * @return Eine ArrayList mit <code>Group</code>-Objekten, in welchen ein Nutzer Mitglied ist. */ public ArrayList<Group> findByMember(int memberID) { Connection con = DBConnection.connection(); ArrayList<Group> result = new ArrayList<Group>(); try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM Participant" + " JOIN `Group` ON Participant.Group_Group_ID = Group_ID" + " WHERE Participant.Person_PersonID =" + memberID); // Fuer jeden Eintrag im Suchergebnis wird nun ein Group-Objekt erstellt. while (rs.next()) { Group g = new Group(); g.setId(rs.getInt("Group_ID")); g.setTitle(rs.getString("Title")); // Hinzufuegen des neuen Objekts zum Ergebnisvektor result.add(g); } } catch (SQLException e2) { e2.printStackTrace(); } // Ergebnisvektor zurueckgeben return result; } /** * Auslesen aller Gruppen einer Person (durch <code> Person</code>-Objekt * gegeben). * @param member Personobjekt, dessen Gruppen ausgelesen werden sollen. * @return alle Gruppen der Person */ public ArrayList<Group> findByMember(Person member) { /* * Wir lesen einfach die id (Primaerschluessel) des Person-Objekts * aus und delegieren die weitere Bearbeitung an findByMember(int memberID). */ return findByMember(member.getId()); } /** * Mitgliedschaft einer Person zu einer Gruppe hinzufuegen * @param p * @param g */ public void addMembership(Person p, Group g) { Connection con = DBConnection.connection(); try { Statement stmt = con.createStatement(); stmt.executeUpdate("INSERT INTO Participant (Group_Group_ID, Person_PersonID) " + "VALUES (" + g.getId() + "," + p.getId() +");"); } catch(SQLException e2) { e2.printStackTrace(); } } /** * Loeschen einer Mitgliedschaft zu einer Gruppe * @param p * @param g */ public void deleteMembership(Person p, Group g) { Connection con = DBConnection.connection(); try { Statement stmt = con.createStatement(); stmt.executeUpdate("DELETE FROM Participant WHERE Group_Group_ID=" + g.getId() + " AND Person_PersonID=" + p.getId()); System.out.println(stmt); } catch(SQLException e2) { e2.printStackTrace(); } } /** * Methode, um alle Einkaufslisten einer Gruppe auszulesen. * @param currentPerson * @return ShoppingLists */ public ArrayList<ShoppingList> getShoppingListsPerGroup(Group g) { ArrayList<ShoppingList> result = new ArrayList<ShoppingList>(); Connection con = DBConnection.connection(); try { Statement stmt = con.createStatement(); //Statement ausf�llen und als Query an die DB schicken ResultSet rs = stmt.executeQuery("SELECT * FROM ShoppingList WHERE Group_ID=" + g.getId()); while(rs.next()) { ShoppingList sl = new ShoppingList(); sl.setId(rs.getInt("ShoppingList_ID")); sl.setGroupID(rs.getInt("Group_ID")); //Hinzuf�gen des neuen Objekts zum Ergebnisvektor result.add(sl); } }catch (SQLException e) { e.printStackTrace(); return null; } return result; } }
package com.java.OOP.partTwo; public abstract class Animal { /** 1) Abstract method has no body. 2) Always end the declaration with a semicolon(;). 3) It must be overridden. An abstract class must be extended and in a same way abstract method must be overridden. 4) A class has to be declared abstract to have abstract methods. */ public abstract void sound(); public abstract void move(); public void getInfo() { System.out.println("This is not a abstarct method"); } }
package io.micronaut.rabbitmq.docs.rpc; import io.micronaut.context.ApplicationContext; import io.micronaut.rabbitmq.AbstractRabbitMQTest; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; public class RpcUppercaseSpec extends AbstractRabbitMQTest { @Test void testProductClientAndListener() { ApplicationContext applicationContext = startContext(); // tag::producer[] ProductClient productClient = applicationContext.getBean(ProductClient.class); assert productClient.send("rpc").equals("RPC"); assert Mono.from(productClient.sendReactive("hello")).block().equals("HELLO"); // end::producer[] applicationContext.close(); } }
package com.zhicai.byteera.activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import com.lidroid.xutils.DbUtils; import com.umeng.analytics.MobclickAgent; import com.zhicai.byteera.MyApp; import com.zhicai.byteera.activity.bean.ZCUser; import com.zhicai.byteera.activity.initialize.LoginActivity; import com.zhicai.byteera.commonutil.ActivityUtil; import com.zhicai.byteera.commonutil.Constants; import com.zhicai.byteera.commonutil.LoadingDialogShow; import com.zhicai.byteera.commonutil.PreferenceUtils; import com.zhicai.byteera.commonutil.UIUtils; /** Created by bing on 2015/5/23. */ @SuppressWarnings("unused") public abstract class BaseFragment extends Fragment { public boolean isConnectionNet; protected String userId; protected DbUtils db; protected LoadingDialogShow dialog; public ZCUser zcUser; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); isConnectionNet = UIUtils.checkNetworkState(); MobclickAgent.openActivityDurationTrack(false); db = DbUtils.create(getActivity(), Constants.BYTEERA_DB); dialog = new LoadingDialogShow(getActivity()); } public final boolean DetermineIsLogin(){ if (TextUtils.isEmpty(MyApp.getInstance().getUserId())) { ActivityUtil.startActivity(getActivity(), new Intent(getActivity(), LoginActivity.class)); return true; } return false; } @Override public void onResume() { super.onResume(); userId = PreferenceUtils.getInstance(getActivity()).getUserId(); MobclickAgent.onPageStart(this.getClass().getSimpleName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(this.getClass().getSimpleName()); } @Override public void onDestroy() { super.onDestroy(); dialog.dismiss(); } }
/* * File: Breakout.java * ------------------- * Name: * Section Leader: * * This file will eventually implement the game of Breakout. */ import acm.graphics.*; import acm.program.*; import acm.util.*; import java.applet.*; import java.awt.*; import java.awt.event.*; public class Breakout extends GraphicsProgram{ /** Width and height of application window in pixels */ public static final int APPLICATION_WIDTH = 400; public static final int APPLICATION_HEIGHT = 600; /** Dimensions of game board (usually the same) */ private static final int WIDTH = APPLICATION_WIDTH; private static final int HEIGHT = APPLICATION_HEIGHT; /** Dimensions of the paddle */ private static final int PADDLE_WIDTH = 60; private static final int PADDLE_HEIGHT = 10; /** Offset of the paddle up from the bottom */ private static final int PADDLE_Y_OFFSET = 30; /** Number of bricks per row */ private static final int NBRICKS_PER_ROW = 10; /** Number of rows of bricks */ private static final int NBRICK_ROWS = 10; /** Separation between bricks */ private static final int BRICK_SEP = 4; /** Width of a brick */ private static final int BRICK_WIDTH = (WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW; /** Height of a brick */ private static final int BRICK_HEIGHT = 8; /** Radius of the ball in pixels */ private static final int BALL_RADIUS = 10; /** Offset of the top brick row from the top */ private static final int BRICK_Y_OFFSET = 70; /** Number of turns */ private static final int NTURNS = 3; /* The amount of time to pause between frames (48fps). */ private static final double PAUSE_TIME = 1000.0 / 48; /*main*/ public void run() { setBricks(); //build bricks. makePaddle(); //add paddle. playGame(); // play game. } /*set bricks*/ private void setBricks(){ for (int i = NBRICK_ROWS;i > 0 ; i--){ double firstRow = 0; for (int j = 0; j < NBRICKS_PER_ROW ; j++){ double x = firstRow + j* BRICK_WIDTH + j*BRICK_SEP; double y = BRICK_Y_OFFSET + i*(BRICK_HEIGHT+BRICK_SEP); GRect brick = new GRect(x,y,BRICK_WIDTH,BRICK_HEIGHT); brick.setFilled(true); if (i==1|i==2){ brick.setColor(Color.RED); } if (i==3|i==4){ brick.setColor(Color.ORANGE); } if (i==5|i==6){ brick.setColor(Color.YELLOW); } if (i==7|i==8){ brick.setColor(Color.GREEN); } if (i==9|i==10){ brick.setColor(Color.CYAN); } add(brick); } } } /* make a paddle which can move as mouse moves*/ public void makePaddle(){ double x = (APPLICATION_WIDTH - PADDLE_WIDTH)/2; double y = APPLICATION_HEIGHT - PADDLE_Y_OFFSET; paddle = new GRect(x,y,PADDLE_WIDTH,PADDLE_HEIGHT); add(paddle); } public void mouseMoved(MouseEvent e){ paddle.setLocation(e.getX() - PADDLE_WIDTH/2, getHeight() - PADDLE_Y_OFFSET - PADDLE_HEIGHT); } private void playGame(){ for (int i=NTURNS ; i>0 ; i--){ waitForClick(); makeBall(); addMouseListeners(); moveBall(); if (BricksNum <= 0){ break; } } } /* make a ball located in the middle of the canvas*/ public void makeBall(){ int x = APPLICATION_WIDTH / 2 - BALL_RADIUS ; int y = APPLICATION_HEIGHT / 2 - BALL_RADIUS; ball = new GOval(x,y,BALL_RADIUS,BALL_RADIUS); add(ball); } /*set vx,vy to make ball move,considering several collision events*/ private void moveBall(){ vy = 3.0; RandomGenerator rgen = RandomGenerator.getInstance(); vx = rgen.nextDouble(1.0, 3.0); if (rgen.nextBoolean(0.5)){ vx = -vx; } while(true){ ball.move(vx, vy); pause(PAUSE_TIME); getCollidingObject(); /*break when bricks are cleared*/ if (BricksNum <= 0){ remove(ball); break; } /*bounce the ball when face the wall*/ if (ball.getY() <= 0){ vy = -vy; } if (ball.getX() + ball.getWidth() >= getWidth()){ vx = -vx; } if (ball.getX() <= 0){ vx = -vx; } /*bounce the ball when collider is the paddle*/ if (collider == paddle){ vy = -vy; collider = null; } /*bounce the ball when collider is bricks*/ if (collider != null && collider != paddle){ vy = -vy; remove(collider); BricksNum = BricksNum - 1; collider = null; } /*break when the ball fall below the bottom*/ if (ball.getY() + ball.getHeight() >= getHeight()){ remove(ball); break; } } } /*check if ball meets an object*/ private GObject getCollidingObject(){ if (getElementAt(ball.getX(),ball.getY())!= null){ collider = getElementAt(ball.getX(),ball.getY()); return collider; } else if (getElementAt(ball.getX()+ ball.getWidth(),ball.getY())!= null){ collider = getElementAt(ball.getX()+ ball.getWidth(),ball.getY()); return collider; } else if (getElementAt(ball.getX(),ball.getY()+ ball.getHeight())!= null){ collider = getElementAt(ball.getX(),ball.getY()+ ball.getHeight()); return collider; } else if (getElementAt(ball.getX()+ ball.getWidth(),ball.getY()+ ball.getHeight())!= null){ collider = getElementAt(ball.getX()+ ball.getWidth(),ball.getY()+ ball.getHeight()); return collider; } else{ return null; } } //add some instance variable. private GRect paddle; private GOval ball; private double vx,vy; private GObject collider; private int BricksNum = NBRICKS_PER_ROW*NBRICK_ROWS; }
package rs2.model.game.entity.character.player; import java.util.ArrayList; import java.util.List; import rs2.model.game.world.World; import rs2.util.NameUtil; /** * A {@link Player}'s contact list (friends and ignores) used in private messaging. * @author Jake Bellotti * @since 1.0 */ public class ContactList { public ContactList() { } public static final int MAX_FRIENDS = 200; public static final int MAX_IGNORES = 100; private final List<Long> friends = new ArrayList<>(MAX_FRIENDS); private final List<Long> ignores = new ArrayList<>(MAX_IGNORES); public void addFriend(Player player, Long friend) { if(friends.size() >= MAX_FRIENDS) { player.getActionSender().sendMessage("Your friend list is full."); return; } Player added = World.getPlayerByName(NameUtil.longToName(friend)); if(added != null) { player.getActionSender().sendFriendList(friend, 1); } friends.add(friend); } public void addIgnore(Player player, Long ignore) { if(ignores.size() >= MAX_IGNORES) { player.getActionSender().sendMessage("Your ignore list is full."); return; } ignores.add(ignore); } public void deleteFriend(Long friend) { friends.remove(friend); } public void deleteIgnore(Long ignore) { ignores.remove(ignore); } public List<Long> getFriends() { return friends; } public List<Long> getIgnores() { return ignores; } }
package com.example.vibrationcustom; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.VibrationEffect; import android.os.Vibrator; import android.support.wearable.activity.WearableActivity; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.NonNull; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.BlockingDeque; public class TrainActivity extends WearableActivity { private TextView tv_count; private TextView tv_subcount; private Button button; private TimerTask timerTask; private TimerTask timerTask2; private Timer timer; private int vibCounter = -1; private int subCounter = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_train); tv_count = (TextView) findViewById(R.id.tv_count); tv_subcount = (TextView) findViewById(R.id.tv_sub_count); button = (Button) findViewById(R.id.train_button); final Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); button.setOnClickListener(new View.OnClickListener() { @SuppressLint("SetTextI18n") @Override public void onClick(View v) { if(subCounter > 3) subCounter = 0; subCounter++; tv_count.setText(" " + subCounter + " / 4 SET"); // 2000ms sleep 후 시작 (no pilot) // chirp 시그널 3회 재생, 사이사이 1.6초씩 sleep // 한 세기당 40ms씩 재생. 세기 간격: 5 (80, 85, 90, 95, ...,255) 총 36steps 36 * 40 = 1440 1440 + 1660 = 3040 //원래는 200, 1600, 40, 0, 40, ..., 1600, ... 1600...임! //지금 일단 0, 1400, 40, 0, 40, ... , 100, ... 으로 바꿔둠. long[] vibPtrnTime = {0, 1400, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 1400, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 1600, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40}; int[] vibPtrnAmpl = { 0, 0, 80, 0, 85, 0, 90, 0, 95, 0, 100, 0, 105, 0, 110, 0, 115, 0, 120, 0, 125, 0, 130, 0, 135, 0, 140, 0, 145, 0, 150, 0, 155, 0, 160, 0, 165, 0, 170, 0, 175, 0, 180, 0, 185, 0, 190 , 0, 195, 0, 200, 0, 205, 0, 210, 0, 215, 0, 220, 0, 225, 0, 230, 0, 235, 0, 240, 0, 245, 0, 250, 0, 255, 0, 80, 0, 85, 0, 90, 0, 95, 0, 100, 0, 105, 0, 110, 0, 115, 0, 120, 0, 125, 0, 130, 0, 135, 0, 140, 0, 145, 0, 150, 0, 155, 0, 160, 0, 165, 0, 170, 0, 175, 0, 180, 0, 185, 0, 190 , 0, 195, 0, 200, 0, 205, 0, 210, 0, 215, 0, 220, 0, 225, 0, 230, 0, 235, 0, 240, 0, 245, 0, 250, 0, 255, 0, 80, 0, 85, 0, 90, 0, 95, 0, 100, 0, 105, 0, 110, 0, 115, 0, 120, 0, 125, 0, 130, 0, 135, 0, 140, 0, 145, 0, 150, 0, 155, 0, 160, 0, 165, 0, 170, 0, 175, 0, 180, 0, 185, 0, 190 , 0, 195, 0, 200, 0, 205, 0, 210, 0, 215, 0, 220, 0, 225, 0, 230, 0, 235, 0, 240, 0, 245, 0, 250, 0, 255}; if(Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){ //create vibEffect instance VibrationEffect vibEffect = VibrationEffect.createWaveform(vibPtrnTime, vibPtrnAmpl, -1); vibrator.cancel(); vibrator.vibrate(vibEffect); //initiate the vibration @SuppressLint("HandlerLeak") final Handler handler = new Handler(){ @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); String string = ""; if(vibCounter < 1) { string = ""; tv_subcount.setText(string); } else if(vibCounter >=3){ string = Character.toString("\u2192".toCharArray()[0]) + " 3"; tv_subcount.setText(string); } else { string = Character.toString("\u2192".toCharArray()[0]) + " " + vibCounter; tv_subcount.setText(string); } } }; @SuppressLint("HandlerLeak") final Handler handler2 = new Handler(){ @Override public void handleMessage(@NonNull Message msg) { //4 set 녹음 시 종료 if(subCounter == 4 ){ tv_subcount.setTextSize(20); tv_subcount.setText("Training 완료"); tv_subcount.setTypeface(tv_subcount.getTypeface(), Typeface.ITALIC); //Train 버튼 비활성화 button.setEnabled(false); button.setClickable(false); //Train 버튼 회색으로 button.setBackground(getResources().getDrawable(R.drawable.roundedbutton_false)); } else { tv_subcount.setText(""); } } }; timerTask = new TimerTask() { @Override public void run() { vibCounter++; Log.d("TAG", "run: Vibration counter ---> " + String.valueOf(vibCounter)); Message msg = handler.obtainMessage(); handler.sendMessage(msg); if(vibCounter >= 3){ Log.d("TAG", "CANCEL 전"); timerTask2 = new TimerTask() { @Override public void run() { Message msg2 = handler2.obtainMessage(); handler2.sendMessage(msg2); Log.d("TAG", "CANCEL 후"); vibCounter = -1; timerTask.cancel(); timerTask2.cancel(); } }; timer.schedule(timerTask2, 1500); // -> 3 이라는 표시는 1500ms 이후에 사라지게 } } }; timer = new Timer(); timer.schedule(timerTask, 0, 2840); // -> 한 진동당 2840ms } } }); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Enables Always-on setAmbientEnabled(); } }
package com.heihei.model; import org.json.JSONObject; import com.heihei.model.msg.bean.GiftMessage; public class AudienceGift { public Gift gift = new Gift();// 礼物id public User fromUser = new User(); public int amount = 1; public int startAmount = 1; public long time = 0l; public String gift_uuid = ""; public AudienceGift() {} public AudienceGift(JSONObject json) { } /** * 从giftMessage创建 * * @param msg * @return */ public static AudienceGift createFromGiftMessage(GiftMessage msg) { AudienceGift aGift = new AudienceGift(); aGift.gift.id = msg.giftId; aGift.amount = msg.amount; aGift.fromUser.nickname = msg.fromUserName; // aGift.fromUser.parseGender(msg.)//解析性别 return aGift; } @Override public boolean equals(Object o) { // return super.equals(o); if (o == null) { return false; } if (!(o instanceof AudienceGift)) { return false; } AudienceGift ag = (AudienceGift) o; if (ag.fromUser != null && this.fromUser != null && ag.fromUser.uid.equals(this.fromUser.uid) && ag.gift != null && this.gift != null && ag.gift.id==this.gift.id && this.gift_uuid.equals(ag.gift_uuid)) { return true; } return super.equals(o); } }
package listeners.game.server; import java.util.Set; import java.util.stream.Collectors; import core.player.PlayerCompleteServer; import core.player.PlayerSimple; import core.server.SyncController; public abstract class ServerInGamePlayerListener { protected final String name; protected final Set<String> otherNames; protected final SyncController controller; protected ServerInGamePlayerListener(String name, Set<String> allNames, SyncController controller) { this.name = name; this.controller = controller; this.otherNames = allNames.stream().filter(n -> !n.equals(name)).collect(Collectors.toSet()); } /** * Send commands to refresh for oneself * * @param self * @return */ public abstract void refreshSelf(PlayerCompleteServer self); /** * Send commands to refresh for another player * * @param other * @return */ public abstract void refreshOther(PlayerSimple other); }
package io.github.atomfrede.gradle.plugins.crowdincli.task.crowdin.git; import org.yaml.snakeyaml.Yaml; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; public class GitCommitTask { private final File configFile; private final String commitMessage; public GitCommitTask(final File configFile, final String commitMessage) { this.configFile = configFile; this.commitMessage = commitMessage; } public void commitTranslations() throws FileNotFoundException { Yaml yamlFile = new Yaml().load(new FileReader(configFile)); } // // /** // * Convenience function for staging a file-tree for git commit // */ // def stageFiles = { tree -> // // Determine modified and added files. // def unstaged = grgit.status().unstaged // def modified = unstaged.modified // def added = unstaged.added // // def projectDir = new File("$projectDir").toPath() // // grgit.add expects a list of strings representing relative pathes // def list = tree.getFiles().collect { return projectDir.relativize(it.toPath()).toString() } // // filter out files that did not change or were not added // def toStage = list.findAll { modified.contains(it) || added.contains(it) } // // if (toStage.empty) { // logger.lifecycle('Nothing staged.') // return false // } else { // toStage.each { file -> // def text = 'Staging: ' + file // logger.lifecycle(text) // } // grgit.add(patterns: toStage) // return true // } // } // ///** // * Convenience function for commiting all translated files from a crowdin config file. // */ // def commitTranslations = { config, message -> // def yamlCfg = new File(config) // def crowdinConfig = new Yaml().load(yamlCfg.newInputStream()) // // def commitNotEmpty = false // def fileSpecs = crowdinConfig.get('files') // def basePath = crowdinConfig.get('base_path') ?: '.' // // fileSpecs.each { spec -> // def transFile = spec.get('translation').replaceAll(/%.*%/, '*') // def files = fileTree(basePath).include(transFile) // commitNotEmpty = stageFiles(files) || commitNotEmpty // } // // if (commitNotEmpty) { // logger.lifecycle('Comitting staged translation files.'); // grgit.commit(message: message) // } else { // logger.lifecycle('Nothing to commit.') // } // } }
import org.junit.Test; import java.awt.event.ActionEvent; import java.awt.event.ItemEvent; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.JSlider; import javax.swing.JCheckBox; import javax.swing.event.ChangeEvent; import cs3500.animator.controller.HybridController; import cs3500.animator.controller.IHybridController; import cs3500.animator.model.IModel; import cs3500.animator.model.Model; import cs3500.animator.shape.IShape; import cs3500.animator.util.ButtonListener; import cs3500.animator.view.HybridView; import cs3500.animator.util.AnimationFileReader; import static org.junit.Assert.assertEquals; public class HybridTest { HybridView hybrid = new HybridView(); IModel model; IHybridController hybridController; ButtonListener buttonListener; IModel m = new Model(); @Test public void testSetFps() { AnimationFileReader reader = new AnimationFileReader(); try { model = reader.readFile("resources/smalldemo.txt", new Model.Builder()); hybridController = new HybridController(model, hybrid); } catch (FileNotFoundException e) { e.printStackTrace(); } hybridController.setFPS(20); assertEquals(20, hybridController.getFps()); } @Test(expected = IllegalArgumentException.class) public void testNullModel() { hybridController = new HybridController(model, hybrid); } // test needs to be written for getModel @Test public void testGetModel() { AnimationFileReader reader = new AnimationFileReader(); try { model = reader.readFile("resources/smalldemo.txt", new Model.Builder()); hybridController = new HybridController(model, hybrid); } catch (FileNotFoundException e) { e.printStackTrace(); } for (IShape s : model.getListOfShapes()) { m.addShapes(s); } List<IShape> expected = m.getListOfShapes(); List<IShape> actual = hybridController.getModel().getListOfShapes(); for (int i = 0; i < expected.size(); i++) { assertEquals(expected.get(i).generateLoop(), actual.get(i).generateLoop()); assertEquals(expected.get(i).getName(), actual.get(i).getName()); assertEquals(expected.get(i).getColor().getGreen(), actual.get(i).getColor().getGreen(), 0.001); assertEquals(expected.get(i).getColor().getRed(), actual.get(i).getColor().getRed(), 0.001); assertEquals(expected.get(i).getColor().getBlue(), actual.get(i).getColor().getBlue(), 0.001); } } @Test public void testGetFps() { AnimationFileReader reader = new AnimationFileReader(); try { model = reader.readFile("resources/smalldemo.txt", new Model.Builder()); hybridController = new HybridController(model, hybrid); } catch (FileNotFoundException e) { e.printStackTrace(); } assertEquals(0, hybridController.getFps()); } @Test public void testSetPause() { AnimationFileReader reader = new AnimationFileReader(); try { model = reader.readFile("resources/smalldemo.txt", new Model.Builder()); hybridController = new HybridController(model, hybrid); } catch (FileNotFoundException e) { e.printStackTrace(); } hybridController.loop(); assertEquals(true, hybridController.getIsPaused()); hybridController.setPause(); assertEquals(true, hybridController.getIsPaused()); hybridController.resume(); assertEquals(false, hybridController.getIsPaused()); hybridController.loop(); assertEquals(false, hybridController.getIsPaused()); } @Test public void testSetLoop() { AnimationFileReader reader = new AnimationFileReader(); try { model = reader.readFile("resources/smalldemo.txt", new Model.Builder()); hybridController = new HybridController(model, hybrid); } catch (FileNotFoundException e) { e.printStackTrace(); } assertEquals(false, hybridController.getHasLoop()); hybridController.setLoop(); assertEquals(true, hybridController.getHasLoop()); } // not sure if correcct @Test public void testRestart() { AnimationFileReader reader = new AnimationFileReader(); try { model = reader.readFile("resources/smalldemo.txt", new Model.Builder()); hybridController = new HybridController(model, hybrid); } catch (FileNotFoundException e) { e.printStackTrace(); } hybridController.restart(); assertEquals(1, hybridController.getFrameCount()); } @Test public void testRestartFps() { AnimationFileReader reader = new AnimationFileReader(); try { model = reader.readFile("resources/smalldemo.txt", new Model.Builder()); hybridController = new HybridController(model, hybrid); } catch (FileNotFoundException e) { e.printStackTrace(); } hybridController.timerRestart(10); hybridController.setAndRestart(100); assertEquals(100, hybridController.getFps()); } // ButtonListener tests @Test public void testActionPerformed() { AnimationFileReader reader = new AnimationFileReader(); try { model = reader.readFile("resources/smalldemo.txt", new Model.Builder()); hybridController = new HybridController(model, hybrid); } catch (FileNotFoundException e) { e.printStackTrace(); } buttonListener = new ButtonListener(hybridController); ActionEvent start = new ActionEvent(buttonListener, 10, "Start animation"); buttonListener.actionPerformed(start); assertEquals(false, hybridController.getIsPaused()); ActionEvent pause = new ActionEvent(buttonListener, 10, "Pause animation"); buttonListener.actionPerformed(pause); assertEquals(true, hybridController.getIsPaused()); ActionEvent resume = new ActionEvent(buttonListener, 10, "Resume animation"); buttonListener.actionPerformed(resume); assertEquals(false, hybridController.getIsPaused()); } @Test public void actionPerformedView() { AnimationFileReader reader = new AnimationFileReader(); try { model = reader.readFile("resources/smalldemo.txt", new Model.Builder()); hybridController = new HybridController(model, hybrid); } catch (FileNotFoundException e) { e.printStackTrace(); } assertEquals(hybrid.getActionText(), "Ready to start"); ActionEvent start = new ActionEvent(hybrid, 10, "Start animation"); hybrid.actionPerformed(start); assertEquals(hybrid.getActionText(), "Animation was started"); ActionEvent pause = new ActionEvent(hybrid, 10, "Pause animation"); hybrid.actionPerformed(pause); assertEquals(hybrid.getActionText(), "Animation was paused"); ActionEvent resume = new ActionEvent(hybrid, 10, "Resume animation"); hybrid.actionPerformed(resume); assertEquals(hybrid.getActionText(), "Animation was resumed"); hybrid.actionPerformed(pause); assertEquals(hybrid.getActionText(), "Animation was paused"); } @Test public void testChangeEvent() { AnimationFileReader reader = new AnimationFileReader(); try { model = reader.readFile("resources/smalldemo.txt", new Model.Builder()); hybridController = new HybridController(model, hybrid); } catch (FileNotFoundException e) { e.printStackTrace(); } hybridController.timerRestart(10); JSlider fpsControl = new JSlider(JSlider.HORIZONTAL, 1, 300, 20); fpsControl.addChangeListener(buttonListener); buttonListener = new ButtonListener(hybridController); ChangeEvent e = new ChangeEvent(fpsControl); buttonListener.stateChanged(e); assertEquals(20, hybridController.getFps()); } @Test public void testSliderView() { AnimationFileReader reader = new AnimationFileReader(); try { model = reader.readFile("resources/smalldemo.txt", new Model.Builder()); hybridController = new HybridController(model, hybrid); } catch (FileNotFoundException e) { e.printStackTrace(); } JSlider fpsControl = new JSlider(JSlider.HORIZONTAL, 1, 300, 20); fpsControl.addChangeListener(hybrid); ChangeEvent e = new ChangeEvent(fpsControl); hybrid.stateChanged(e); assertEquals(hybrid.getActionText(), "Speed changed to 20 fps."); fpsControl.setValue(30); hybrid.stateChanged(e); assertEquals(hybrid.getActionText(), "Speed changed to 30 fps."); } @Test public void testItemStateChanged() { AnimationFileReader reader = new AnimationFileReader(); try { model = reader.readFile("resources/smalldemo.txt", new Model.Builder()); hybridController = new HybridController(model, hybrid); } catch (FileNotFoundException e) { e.printStackTrace(); } buttonListener = new ButtonListener(hybridController); JCheckBox loopButton = new JCheckBox("Loop"); loopButton.setSelected(false); loopButton.setActionCommand("Loop animation"); loopButton.addItemListener(buttonListener); ItemEvent loop = new ItemEvent(loopButton, 1, buttonListener, 1); buttonListener.itemStateChanged(loop); assertEquals(true, hybridController.getHasLoop()); ItemEvent noLoop = new ItemEvent(loopButton, 1, buttonListener, 2); buttonListener.itemStateChanged(noLoop); assertEquals(false, hybridController.getHasLoop()); } @Test public void testViewStateChanged() { AnimationFileReader reader = new AnimationFileReader(); try { model = reader.readFile("resources/smalldemo.txt", new Model.Builder()); hybridController = new HybridController(model, hybrid); } catch (FileNotFoundException e) { e.printStackTrace(); } buttonListener = new ButtonListener(hybridController); JCheckBox loopButton = new JCheckBox("Loop"); loopButton.setSelected(false); loopButton.setActionCommand("Loop animation"); loopButton.addItemListener(hybrid); assertEquals(hybrid.getActionText(), "Ready to start"); ItemEvent loop = new ItemEvent(loopButton, 1, hybrid, 1); hybrid.itemStateChanged(loop); assertEquals(hybrid.getActionText(), "Looping..."); ItemEvent loopback = new ItemEvent(loopButton, 1, hybrid, 0); hybrid.itemStateChanged(loopback); assertEquals(hybrid.getActionText(), ""); hybrid.itemStateChanged(loop); assertEquals(hybrid.getActionText(), "Looping..."); hybrid.itemStateChanged(loopback); assertEquals(hybrid.getActionText(), ""); } @Test(expected = UnsupportedOperationException.class) public void UnsupportedMethods() { hybrid.setFps(10); ArrayList<IShape> temp = new ArrayList<>(); try { hybrid.drawForSVG(temp); } catch (IOException e) { e.printStackTrace(); } hybrid.drawString("wow"); hybrid.setFilePath("ojj.svg"); } }
package standalone; import com.github.louism33.axolotl.search.Engine; import com.github.louism33.chesscore.Chessboard; import com.github.louism33.chesscore.MoveParser; import java.io.IOException; import java.io.InputStreamReader; class StandAlone { private static int totalMoves = 1; private static final long timeLimit = 20000; public static void main(String[] args) throws IOException { InputStreamReader stdin; stdin = new InputStreamReader(System.in); Chessboard board = new Chessboard(); String command, prompt; int move; while(true) { while (true) { if (board.isWhiteTurn()){ prompt = "White"; } else { prompt = "Black"; } System.out.println("\nPosition ("+prompt+" to move):\n" + board); int[] moves = board.generateLegalMoves(); if (moves.length == 0) { if (board.inCheck(board.isWhiteTurn())){ System.out.println("Checkmate"); } else { System.out.println("Stalemate"); } break; } System.out.println("Moves:"); System.out.print(" "); final String[] niceMoves = MoveParser.toString(moves); for (int i = 0; i< niceMoves.length; i++) { if ((i % 10) == 0 && i>0) System.out.print("\n "); System.out.print(niceMoves[i]+", "); } System.out.println(); System.out.println(MoveParser.numberOfRealMoves(moves) + " moves in total."); System.out.println(); label: while (true) { System.out.print(prompt + " move (or \"go\" or \"quit\")> "); command = readCommand(stdin); System.out.println("This is move number " + totalMoves + "."); switch (command) { case "go": move = Engine.searchFixedTime(board, timeLimit, false); break label; case "quit": System.out.println("QUIT.\n"); System.exit(1); default: move = 0; for (int m : moves) { if (command.equals(MoveParser.toString(m))) { move = m; break; } } if (move != 0) break label; System.out.println("\"" + command + "\" is not a legal move"); break; } } board.makeMove(move); board.setWhiteTurn(!board.isWhiteTurn()); totalMoves++; System.out.println(prompt + " made move "+move); } while(true) { System.out.print("Play again? (y/n):"); command = readCommand(stdin); if (command.equals("n")) System.exit(1); if (command.equals("y")) { totalMoves = 0; break; } } } } private static String readCommand(InputStreamReader stdin) throws IOException { int MAX = 100; int len = 0; char[] cbuf = new char[MAX]; //len = stdin.read(cbuf, 0, MAX); for(int i=0; i<cbuf.length; i++){ cbuf[i] = (char)stdin.read(); len++; if(cbuf[i] == '\n') break; if(cbuf[i] == -1){ System.out.println("An error occurred reading input"); System.exit(1); } } /*if (len == -1){ System.out.println("An error occurred reading input"); System.exit(1); }*/ return new String(cbuf, 0, len).trim(); /* trim() removes \n in unix and \r\n in windows */ } }
package ru.mcfr.oxygen.framework.operations.table; import ro.sync.ecss.extensions.api.ArgumentDescriptor; import ro.sync.ecss.extensions.api.AuthorOperationException; import ro.sync.ecss.extensions.api.node.AuthorElement; import ro.sync.ecss.extensions.api.node.AuthorNode; import ru.mcfr.oxygen.framework.operations.McfrBaseAuthorOperation; import javax.swing.text.BadLocationException; import java.util.Vector; /** * Created by IntelliJ IDEA. * User: ws * Date: 23.06.11 * Time: 16:05 * To change this template use File | Settings | File Templates. */ public class CopyColumnWidthOperation extends McfrBaseAuthorOperation { { description = "Копирование ширины и колспана колонок в другие колонки"; argumentsNameArray = new String[]{"arg"}; argumentsTypesArray = new Object[]{ArgumentDescriptor.TYPE_STRING}; argumentsDescriptionsArray = new String[]{"arg"}; } private Vector<String> colspans = new Vector<String>(); @Override public void doMainOperation() { AuthorNode thisElement = selectedElement; while (!thisElement.getName().equalsIgnoreCase("строка")) thisElement = thisElement.getParent(); int i = 0; for (AuthorNode cell : ((AuthorElement) thisElement).getContentNodes()){ authorAccess.getWorkspaceAccess().showErrorMessage(thisElement.getName() + " => " + cell.getName());// for (AuthorNode node : ((AuthorElement) cell).getContentNodes()){ if (node.getType() == AuthorNode.NODE_TYPE_ELEMENT){ String text = "some text " + (++i); int offset = node.getStartOffset() + node.getDisplayName().length() + 2 + text.length() * (i - 1); // try { // AuthorDocumentFragment frag = controller.createNewDocumentTextFragment("some text " + (++i)); // controller.insertFragment(offset, frag); // } catch (AuthorOperationException e) { // e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. // } authorAccess.getWorkspaceAccess().showErrorMessage(thisElement.getDisplayName() + " => " + cell.getDisplayName() + " => " + node.getDisplayName()); controller.insertText(offset, text); break; } } } /* authorAccess.showErrorMessage(thisElement.getName()); if (thisElement != null){ if (argumentsValues.get(argumentsNameArray[0]).equalsIgnoreCase("copy")){ // copy parameters to bufer try{ AuthorElement[] cells = ((AuthorElement) thisElement).getElementsByLocalName("ячейка"); for (AuthorElement cell : cells) colspans.add(cell.getAttribute("colspan").getValue()); } catch (Exception e){ authorAccess.showErrorMessage(e.getMessage()); } } else if (argumentsValues.get(argumentsNameArray[1]).equalsIgnoreCase("apply")){ // apply parameters from bufer AuthorElement[] cells = ((AuthorElement) thisElement).getElementsByLocalName("ячейка"); if (colspans.size() != 0){ int diff = colspans.size() - cells.length; authorAccess.showErrorMessage("diff:" + diff); if (diff > 0){ AuthorNode lastCell = cells[cells.length]; try { AuthorDocumentFragment fragment = controller.createNewDocumentFragmentInContext("<ячейка/>", lastCell.getEndOffset()); for (int i = 0; i < diff; i++){ controller.insertFragment(lastCell.getEndOffset(), fragment); authorAccess.showErrorMessage("insert new fragment"); } } catch (AuthorOperationException e) { e.printStackTrace(); } } // if deiff < 0 not see here right now cells = ((AuthorElement) thisElement).getElementsByLocalName("ячейка"); authorAccess.showErrorMessage("cells count: " + cells.length); int o = 0; for (String colspan : colspans){ if (!colspan.isEmpty()){ controller.setAttribute("colspan", new AttrValue(colspan), (AuthorElement) cells[o]); authorAccess.showErrorMessage("set collspan for cell: " + o); } //((AuthorElement) cells.get(o)).setAttribute("colspan", new AttrValue(colspan)); o++; } } } } */ } @Override public void doOperationWithSelected() throws AuthorOperationException, BadLocationException { } @Override public void doOperationAtCaretPos() throws AuthorOperationException { } }
package com.second.practiceproject2.controller; import com.second.practiceproject2.aspect.LogAspect; import com.second.practiceproject2.model.User; import com.second.practiceproject2.service.AnswerService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.view.RedirectView; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; //@Controller public class IndexController { private static final Logger logger = LoggerFactory.getLogger(IndexController.class); @Autowired private AnswerService answerService; //初始页面 @RequestMapping(path = {"/","/index"}) @ResponseBody public String index(){ logger.info("Visit Home"); return answerService.getMessage(2)+"first page"; } /*这里注释掉是对应301/302页面跳转 public String index(HttpSession httpSession) { return "first page"+ httpSession.setAttribute("msg"); }*/ //练习路径 @RequestMapping(path = {"/profile/{userId}"},method = {RequestMethod.GET }) @ResponseBody public String profile(@PathVariable("userId") int userId, @RequestParam(value = "page",defaultValue = "1",required = true)int page) { return String.format("Profile Page of %d, p:%d",userId,page); } //thymeleaf模板 @RequestMapping(path = {"/thy"},method = {RequestMethod.GET }) public String template(Model model) { model.addAttribute("name", "hello world"); List<String> colors = Arrays.asList(new String[]{"RED","GREEN","BLUE"}); model.addAttribute("colors",colors); Map<String,String> map = new HashMap<String,String>(); for(int i = 0; i< 4; ++i) { map.put(String.valueOf(i),String.valueOf(i*i)); } model.addAttribute("map",map); model.addAttribute("user",new User("TIAN")); return "home"; } //response和request @RequestMapping(path = {"/request"},method = {RequestMethod.GET }) @ResponseBody public String request(Model model, HttpServletResponse response, HttpServletRequest request, HttpSession httpSession, @CookieValue("JSESSIONID") String sessionId) { StringBuilder sb = new StringBuilder(); sb.append("CookieValue:"+sessionId); sb.append(request.getMethod()+"<br>"); sb.append(request.getQueryString()+"<br>"); response.addHeader("oneId","learn"); response.addCookie(new Cookie("username","tld")); return sb.toString(); } //301/302页面跳转不知道哪里错了,先注释掉 /*@RequestMapping(path = {"/redirect/{code}"},method = {RequestMethod.GET }) public String RedirectView redirect(@PathVariable("code") int code, HttpServletRequest request, HttpSession httpSession) { httpSession.setAttribute("msg","jump from redirect"); RedirectView red = new RedirectView("/",true); if(code == 301) { red.setStatusCode(HttpStatus.MOVED_PERMANENTLY ); } return red; }*/ //异常捕获,自己定义的异常,这里是admin管理者参数输入错误异常 @RequestMapping(path = {"/admin"},method = {RequestMethod.GET }) @ResponseBody public String admin(@RequestParam("key") String key){ if("password".equals(key)){ return "I'm an admin"; } throw new IllegalArgumentException("参数错啦"); } @ExceptionHandler() @ResponseBody public String error(Exception e){ return "error:"+e.getMessage(); } }
/* * Created on 2004. 9. 6. */ package com.esum.framework.core.event.util; import com.esum.framework.common.util.MessageIDGenerator; import com.esum.framework.core.event.EventException; import com.esum.framework.core.event.message.Attachment; import com.esum.framework.core.event.message.ContentInfo; import com.esum.framework.core.event.message.DataInfo; import com.esum.framework.core.event.message.EventHeader; import com.esum.framework.core.event.message.FromParty; import com.esum.framework.core.event.message.Header; import com.esum.framework.core.event.message.Message; import com.esum.framework.core.event.message.MessageEvent; import com.esum.framework.core.event.message.Payload; import com.esum.framework.core.event.message.ToParty; public class MessageEventUtil { public static MessageEvent makeMessageEvent(int type, String fromId, String toId, String startComponentId, String sourceInterfaceId, String inMessageId, String messageName, String messageNumber) throws EventException { String messageCtrlId = MessageIDGenerator.generateMessageID(); MessageEvent msgEvent = makeMessageEvent(messageCtrlId, type, fromId, toId, startComponentId, sourceInterfaceId, inMessageId, messageName, messageNumber); return msgEvent; } public static MessageEvent makeMessageEvent(String messageCtrlId, int type, String fromId, String toId, String startComponentId, String sourceInterfaceId, String inMessageId, String messageName, String messageNumber) { MessageEvent msgEvent = new MessageEvent(); EventHeader eh = new EventHeader(); eh.setType(type); msgEvent.setEventHeader(eh); msgEvent.setMessageControlId(messageCtrlId); Message message = new Message(); Header messageHeader = new Header(); FromParty fp = new FromParty(fromId); messageHeader.setFromParty(fp); ToParty tp = new ToParty(toId); messageHeader.setToParty(tp); messageHeader.setStartComponentId(startComponentId); messageHeader.setSourceInterfaceId(sourceInterfaceId); messageHeader.setInMessageId(inMessageId); messageHeader.setMessageName(messageName); messageHeader.setMessageNumber(messageNumber); message.setHeader(messageHeader); msgEvent.setMessage(message); return msgEvent; } public static Payload addPayload(MessageEvent msgEvent, ContentInfo contentInfo, DataInfo dataInfo, byte[] data) { Payload p = new Payload(); p.setContentInfo(contentInfo); p.setDataInfo(dataInfo); p.setData(data); msgEvent.getMessage().setPayload(p); return p; } public static Attachment addAttachment(MessageEvent msgEvent, ContentInfo contentInfo, byte[] data) throws EventException{ Attachment attach = new Attachment(contentInfo, data); msgEvent.getMessage().addAttachment(attach); return attach; } }
package person.zhao.pattern; import person.zhao.pattern.bean.AmericanPerson; import person.zhao.pattern.bean.ChinesePerson; import person.zhao.pattern.bean.IPerson; import person.zhao.pattern.bean.JapanesePerson; /** * 简单工厂实例 * * PersonFactory 生产3个国家的人 * */ public class Factory { public void p(){ PersonFactory f = new PersonFactory(); IPerson p = f.create("ZH"); p.talk(); IPerson p2 = f.create("JP"); p2.talk(); } public static void main(String[] args){ new Factory().p(); } } class PersonFactory{ public IPerson create(String type){ if("JP".equals(type)){ return new JapanesePerson(); }else if("USA".equals(type)){ return new AmericanPerson(); }else if("ZH".equals(type)){ return new ChinesePerson(); }else { throw new RuntimeException("not support type"); } } }
package com.pm.customer.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; 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.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.pm.customer.service.CustomerService; import com.pm.rentapp.commons.model.Customer; @RestController @RequestMapping("/customers") public class CustomerController { @Autowired CustomerService customserService; @PostMapping("/customer") @PreAuthorize("hasAuthority('ADMIN')") public ResponseEntity<?> save(@RequestBody Customer customer) { Customer cust = customserService.save(customer); if (cust == null) return new ResponseEntity<>(HttpStatus.BAD_REQUEST); return new ResponseEntity<>(cust, HttpStatus.CREATED); } @GetMapping("/customer") @PreAuthorize("hasAuthority('USER')") public ResponseEntity<?> getCustomers(){ return new ResponseEntity<>(customserService.findAll(),HttpStatus.OK); } }
package com.example.counterclock.receivers; import android.app.admin.DeviceAdminReceiver; import android.content.Context; import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; public class AdminReceiver extends DeviceAdminReceiver { public static final String ACTION_DISABLED = "device_admin_action_disabled"; public static final String ACTION_ENABLED = "device_admin_action_enabled"; @Override public void onDisabled(Context context, Intent intent) { super.onDisabled(context, intent); LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(ACTION_DISABLED)); } @Override public void onEnabled(Context context, Intent intent) { super.onEnabled(context, intent); LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(ACTION_ENABLED)); } }
package main; import parser.jdom2.GenerateXMLDriver; import io.bytes.reader.ReadFileBytes; import io.bytes.writer.WriteFileBytes; import io.regex.RegExSearch; public class Main { public static void main(String[] args) { //PATH OF LOG String path = "log//server.log"; //READER ReadFileBytes reader = new ReadFileBytes(); reader.readFile(path); //WRITER WriteFileBytes writer = new WriteFileBytes(); writer.writeFileXML(GenerateXMLDriver.generateChannelXML(RegExSearch.getTimes(), RegExSearch.getUid(), "uid", "start")); //SUCCESS System.err.println("ENDED WITH SUCCESS!!"); } }
/** * GUIClient.java * * Created on January 19, 2007, 10:03 PM * Description: it creates the main GUI that launches * all the applications. Display URL's, file choosers * brings GUIDatabase and performs the statistics * USES GUIDatabase.java, htmlEditor.java. * It has two internal classes RightPanel.java, * LeftPanel.java that fill the left and hand * parts of the screen; * the bottom of the screen has a textarea. * * @author Elena Villalon */ package jclient; import jalgo.Student; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.Label; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; public class GUIClient extends JFrame{ static final long serialVersionUID = 7788L; private static final int DEFAULT_WIDTH= 600; private static final int DEFAULT_HEIGTH= 700; private float scale = 4; private JPanel statpanel; private final String [] vidf = {"file://elephant.mpg", "file://bailey.mpg"}; final JTextArea outputarea= new JTextArea("Video analysis", 100,20); private final VideoDescribe desc = new VideoDescribe(); private final JComboBox tags = new JComboBox(); final static int fsz =14; private static Executor exec; final static int NTHREADS = 7; String [] nameMenu; final JTextField videotxt; //videos selected for classification; index 0 is the video to test List<String> vidSelected; private static Logger mLog = Logger.getLogger(GUIClient.class.getName()); private boolean debug = false; public GUIClient(){ if(!debug) mLog.setLevel(Level.WARNING); exec = Executors.newFixedThreadPool(NTHREADS); setTitle("Video Analyzer"); setSize(DEFAULT_WIDTH,DEFAULT_HEIGTH); setLayout(new BorderLayout(1,2)); vidSelected = new ArrayList<String>(); Font f = new Font("menuF", Font.BOLD, fsz-1); videotxt= new JTextField(vidf[0], 20); JMenuBar menubar = new JMenuBar(); setJMenuBar(menubar); nameMenu = new String[7]; JMenu statdisp = new JMenu("File"); statdisp.setMnemonic(KeyEvent.VK_F); statdisp.setFont(f); MenuItemHandler handmenu = new MenuItemHandler(); nameMenu[0] = "Add Video"; JMenuItem vidItem = new JMenuItem(nameMenu[0], KeyEvent.VK_V); vidItem.setToolTipText("Enter video from directory into database."); vidItem.addActionListener(handmenu); vidItem.setFont(f); nameMenu[1] = "Add Label"; JMenuItem labelItem = new JMenuItem(nameMenu[1], KeyEvent.VK_L); labelItem.setToolTipText("Enter classification tags/labels."); labelItem.addActionListener(handmenu); labelItem.setFont(f); nameMenu[2]= "Test Videos"; JMenuItem testItem = new JMenuItem(nameMenu[2], KeyEvent.VK_T); testItem.setToolTipText("Text tile with video primary keys for classification."); testItem.addActionListener(handmenu); testItem.setFont(f); statdisp.add(vidItem); statdisp.add(labelItem); statdisp.add(testItem); menubar.add(statdisp); JMenu databasedisp = new JMenu("Database"); databasedisp.setMnemonic(KeyEvent.VK_D); databasedisp.setFont(f); nameMenu[3]= "Analyze/Show"; JMenuItem showItem = new JMenuItem(nameMenu[3],KeyEvent.VK_A); showItem.setToolTipText("Show table with database of videos."); showItem.addActionListener(handmenu); showItem.setFont(f); nameMenu[4] = "Mckoy/SQL Exit"; JMenuItem queryItem = new JMenuItem(nameMenu[4], KeyEvent.VK_M); queryItem.addActionListener(handmenu); queryItem.setFont(f); queryItem.setToolTipText("Show Mckoy SQL JDBC Query tool."); databasedisp.add(showItem); databasedisp.add(queryItem); databasedisp.addSeparator(); nameMenu[5] = "URL Remove"; JMenuItem vpkItem = new JMenuItem(nameMenu[5],KeyEvent.VK_U); vpkItem.setToolTipText("Eliminate video primary Key (URL) from database."); vpkItem.addActionListener(handmenu); vpkItem.setFont(f); databasedisp.add(vpkItem); menubar.add(databasedisp); JMenu studio = new JMenu("JMF"); studio.setMnemonic(KeyEvent.VK_J); studio.setFont(f); nameMenu[6] = "JMStudio"; JMenuItem studItem = new JMenuItem(nameMenu[6],KeyEvent.VK_S); studItem.setToolTipText("Show JMF Studio."); studItem.addActionListener(handmenu); studItem.setFont(f); studio.add(studItem); menubar.add(studio); ///////////////////////////////////////////////////////// RightPanel rght = new RightPanel(); JPanel congo = new JPanel(); congo.setLayout(new BorderLayout(0,0)); congo.add(rght.statpanel, BorderLayout.EAST); LeftPanel left = new LeftPanel(); congo.add(left.textpanel,BorderLayout.WEST ); add(congo, BorderLayout.NORTH); GUISelectVid vidlst = new GUISelectVid(vidSelected); vidSelected =vidlst.getSelectedVid(); add(vidlst,BorderLayout.CENTER); outputarea.setLineWrap(true); outputarea.setWrapStyleWord(true); Font font3 = new Font("Courier", Font.PLAIN,fsz); outputarea.setFont(font3); outputarea.setToolTipText("Send your message to a file, write in the text area select it "); outputarea.addCaretListener(new CaretListener() { public void caretUpdate(CaretEvent caretEvent) { mLog.info("dot:"+ caretEvent.getDot()); mLog.info("mark"+caretEvent.getMark()); mLog.info(outputarea.getSelectedText()); mLog.info(outputarea.getText()); if(outputarea.getSelectedText()!=null) new SendYourComments("emailFile.txt", outputarea); } }); JScrollPane scroller= new JScrollPane(outputarea); scroller.setPreferredSize(new Dimension(DEFAULT_WIDTH-10, DEFAULT_HEIGTH/3)); JPanel panel = new JPanel(); panel.add(scroller); add(panel, BorderLayout.SOUTH); } private class MenuItemHandler implements ActionListener{ public MenuItemHandler(){ super(); } public void actionPerformed(ActionEvent event) { String src = ((JMenuItem) event.getSource()).getText(); if(src.equals(nameMenu[0])){ //"Add Video" mLog.info(""+vidf[0]); String[] which = vidf[0].split("\\."); String ending = which[which.length-1].trim(); Runnable r = new DatabaseRunnable.VideoRunnable(vidf[0], "false"); new Thread(r).start(); return; } if(src.equals(nameMenu[1]) || src.equals(nameMenu[2])){ String[] which = vidf[0].split("\\."); String ending = which[which.length-1].trim(); if(!ending.equalsIgnoreCase("txt")) if(!ending.equalsIgnoreCase("text")) if(!ending.equalsIgnoreCase("tex")) return; } if(src.equals(nameMenu[1])){ //"Add Label" HashMap<String, Set<String>> usr= readFile(vidf[0], true); desc.setUserlabel(usr); Set<String> tagval= usr.keySet(); if(tagval.isEmpty()) return; for(String str:tagval) tags.addItem(str); return; } if(src.equals(nameMenu[2])){//"Test Videos" HashMap<String, Set<String>> usr= readFile(vidf[0], false); String key = "NOTAG"; Set<String> vid = usr.keySet(); if(vid.isEmpty()){ mLog.info("EMPTY"); return; } String [] argsf = vid.toArray(new String[vid.size()]); Runnable r = new DatabaseRunnable.StudentRunnable(argsf, outputarea); exec.execute(r); } if(src.equals(nameMenu[3])){ //"Show/Analyze"; Runnable r = new DatabaseRunnable.GUIDatabaseRunnable(); exec.execute(r); } if(src.equals(nameMenu[4])){//"Mckoy/SQL Exit"; Runnable r = new DatabaseRunnable.MckoiQueryRunnable(); exec.execute(r); } if(src.equals(nameMenu[5])){//"URL Remove" String []vdrm = {(videotxt.getText()).trim()}; Runnable r = new DatabaseRunnable.DropVideoRunnable(vdrm[0]); exec.execute(r); } if(src.equals(nameMenu[6])){//"JMStudio" Runnable r = new DatabaseRunnable.JMStudioRunnable(); exec.execute(r); } } } /** * Internal class that creates a panel for video classification * */ public class RightPanel extends JPanel{ JPanel statpanel; private JPanel textpanel; public RightPanel(){ textpanel = new JPanel(); statpanel = new JPanel() { public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getPreferredSize() { return new Dimension(300, super.getPreferredSize().height); } public Dimension getMaximumSize() { return getPreferredSize(); } }; desc.classifiedVideos(); statpanel.setLayout(new GridLayout(1, 1)); statpanel. setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Video Classifier"), BorderFactory.createEmptyBorder(0,0,0,0))); textpanel.setLayout(new BoxLayout(textpanel, BoxLayout.Y_AXIS)); textpanel.setAlignmentX(Component.LEFT_ALIGNMENT); final Box buttonpanel = Box.createVerticalBox(); final String [] nmbut = {"Student", "Rank", "SVD", "Anova"}; final ButtonGroup group = new ButtonGroup(); JRadioButton butmean = new JRadioButton("Paired Student Test",false); mLog.info("Student Test Button " + butmean.isSelected()); butmean.setActionCommand(nmbut[0]); group.add(butmean); buttonpanel.add(butmean); JRadioButton butmedian = new JRadioButton("Signed Rank Test"); butmedian.setSelected(false); butmedian.setActionCommand(nmbut[1]); group.add(butmedian); buttonpanel.add(butmedian); JRadioButton butAnova = new JRadioButton("ANOVA",false); butAnova.setActionCommand(nmbut[3]); group.add(butAnova); buttonpanel.add(butAnova); JRadioButton butSVD = new JRadioButton("SVD & PCA",false); butSVD.setActionCommand(nmbut[2]); group.add(butSVD); buttonpanel.add(butSVD); RadioButtonHandler buts = new RadioButtonHandler(nmbut); butmean.addActionListener(buts); butmedian.addActionListener(buts); butSVD.addActionListener(buts); butAnova.addActionListener(buts); statpanel.add(buttonpanel); statpanel.add(textpanel); } } private class RadioButtonHandler implements ActionListener{ String [] nmbut; public RadioButtonHandler(String[] b){ super(); nmbut=b; } public void actionPerformed(ActionEvent event) { String but = event.getActionCommand(); if(vidSelected.size()<= 0){ Student.prUsage("No videos selected"); return; } String url[] = vidSelected.toArray(new String[vidSelected.size()]); for(int n=0; n < url.length; ++n){ mLog.info(url[n]); url[n] = "'"+url[n]+"'"; mLog.info(url[n]); } mLog.info(but); if(but.equalsIgnoreCase(nmbut[0])){ Runnable r = new DatabaseRunnable.StudentRunnable(url, outputarea); exec.execute(r); return; } if(but.equalsIgnoreCase(nmbut[1])){ mLog.info(nmbut[1]); Runnable r = new DatabaseRunnable.SumRankTestRunnable(url, outputarea); exec.execute(r); return; } if(but.equalsIgnoreCase(nmbut[2])){ mLog.info(nmbut[2]); Runnable r = new DatabaseRunnable.SVDVideoTestRunnable(url, outputarea); Thread t = new Thread(r); t.start(); return; } if(but.equalsIgnoreCase(nmbut[3])){ mLog.info(nmbut[3]); Runnable r = new DatabaseRunnable.ANOVATestRunnable(url, outputarea); Thread t = new Thread(r); t.start(); return; } } } public void addRadioButton(String name, boolean selected, ButtonGroup group, JPanel panel){ JRadioButton button = new JRadioButton(name,selected); group.add(button); panel.add(button); } /** * Internal class that creates a panel for url display and * the video database. * */ public class LeftPanel extends JPanel { JPanel textpanel; public LeftPanel(){ textpanel = new JPanel() { public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getPreferredSize() { return new Dimension(300, super.getPreferredSize().height); } public Dimension getMaximumSize() { return getPreferredSize(); } }; textpanel.setLayout(new BoxLayout(textpanel, BoxLayout.PAGE_AXIS)); //create a sub-panel to add to text-panel final JPanel textpanel1 = new JPanel(); textpanel1. setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("URL's and Files"), BorderFactory.createEmptyBorder(5,5,5,5))); textpanel1.setLayout(new BoxLayout(textpanel1, BoxLayout.Y_AXIS)); textpanel1.setAlignmentX(Component.LEFT_ALIGNMENT); final JTextField urltxt = new JTextField("http://www.youtube.com", 15); urltxt.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent event){ new htmlEditor(urltxt.getText()); } }); urltxt.setMaximumSize(urltxt.getPreferredSize()); JButton submit = new JButton("Submit"); submit.setMnemonic(KeyEvent.VK_S); submit.setToolTipText("Display website."); submit.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent event){ new htmlEditor(urltxt.getText()); } }); addRow("URL:", urltxt, submit, textpanel1); videotxt.setMaximumSize(urltxt.getPreferredSize()); JButton browse = new JButton("Browse"); browse.setToolTipText("Select file or video from directories."); browse.setMnemonic(KeyEvent.VK_B); addRow("File: ", videotxt, browse, textpanel1); final JFileChooser fc = new JFileChooser(); browse.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent event){ int retVal= fc.showOpenDialog(textpanel1); if (retVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String fstr = file.toString(); StringTokenizer tok = new StringTokenizer(fstr, "\\"); int n = tok.countTokens(); String disp = fstr; while(tok.hasMoreTokens()) disp = tok.nextToken().toString(); String []which = disp.split("."); int ln = which.length; videotxt.setText("file://".concat(disp)); vidf[0] = "file://".concat(fstr); mLog.info(vidf[0]); } } }); textpanel.add(textpanel1); //done with the upper part JPanel metapanel = new JPanel(); metapanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Metadata"), BorderFactory.createEmptyBorder(5,5,5,5))); metapanel.setLayout(new BoxLayout(metapanel, BoxLayout.X_AXIS)); metapanel.setAlignmentX(Component.LEFT_ALIGNMENT); ArrayList<String> choices = desc.getLabels(); JLabel lab = new JLabel("Labels: "); for(int n=0; n <choices.size(); ++n) tags.addItem(choices.get(n)); tags.setEditable(true); tags.setMaximumSize(tags.getPreferredSize()); tags.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event){ String strselect = (String) tags.getSelectedItem(); strselect.trim(); String sum = "Label selected: " + strselect; HashMap<String, String> tmp = desc.getTag(strselect); if(tmp==null){ Set<String> usrlb = desc.getUserLabel(strselect); if(usrlb.isEmpty()) { sum = sum + "\n" + "No videos exist"; outputarea.setText(sum); return; } for(String lab:usrlb) sum = sum +"\n" + lab; outputarea.setText(sum); return; } String allvid = tmp.toString(); String res [] = allvid.split("file"); for(int n=0; n < res.length; ++n){ if(n > 0) res[n] ="file".concat(res[n]); sum = sum + "\n" + res[n]; mLog.info(res[n]); } outputarea.setText(sum); } }); metapanel.add(lab); metapanel.add(tags); textpanel.add(metapanel); } } /** Takes a file name and reads line by line * Each line has the label and all videos * classified under the label; the separation is tab * Creates a HashMap with labels and videos. */ public HashMap<String, Set<String>> readFile(String ff, boolean tg){ ff = ff.split("://",2)[1]; mLog.info(ff); BufferedReader inputStream = null; HashMap<String, Set<String>> tags = new HashMap<String, Set<String>>(); String l; String tag=""; try { inputStream = new BufferedReader(new FileReader(ff)); while ((l = inputStream.readLine()) != null) { String [] res= l.split("[\t|\n|\f|\r]+"); int st=0; tag= new String(res[0].trim()); if(tg) st =1; Set<String> vf = new HashSet<String>(); for(int n=st; n < res.length; ++n) vf.add(res[n].trim()); tags.put(tag, vf); } }catch(FileNotFoundException ef){ ef.printStackTrace(); }catch(IOException eio){ eio.printStackTrace(); } finally { if (inputStream != null) try{ inputStream.close(); }catch(IOException cio){ cio.printStackTrace(); } } return tags; } public void addRow(String label, final JTextField field, final JButton but, JPanel textpanel){ Box h1= Box.createHorizontalBox();; if(label.startsWith("V")){ h1.add(Box.createRigidArea(new Dimension(0,15))); } textpanel.add(h1); String filler = " "; h1.add(new JLabel(label+ filler)); if(field!=null) h1.add(field); if(but!=null) h1.add(but); else h1.add(new Label("Compare to")); textpanel.add(h1); } public Box ButtonRow(String label1, final JButton but1,String label2, final JButton but2, final JPanel textpanel, int ord){ Box h1 =Box.createVerticalBox(); final int sep = 10; String filler = " "; h1.add(new JLabel(label1)); h1.add(but1); h1.add(Box.createVerticalStrut(sep)); h1.add(new JLabel(label2)); h1.add(but2); return(h1); } public static void main(String[] args) { // TODO Auto-generated method stub javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { GUIClient client = new GUIClient(); client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); client.setVisible(true); } }); } }
package com.bitcamp.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.bitcamp.DTO.Product.ListDTO; import com.bitcamp.DTO.customerqaboard.CustomerQABoardDTO; import com.bitcamp.DTO.member.MemberDTO; import com.bitcamp.DTO.order.OrderDTO; import com.bitcamp.DTO.productdetail.BuyReviewDTO; import com.bitcamp.DTO.productdetail.QABoardDTO; import com.bitcamp.mapper.MyPageMapper; @Service("myPageService") public class MyPageService { @Autowired MyPageMapper mapper; public void updateUserInfo(MemberDTO memberDTO) { // TODO Auto-generated method stub mapper.updateUserInfo(memberDTO); } public void updateUserPassword(int member_no, String newPwd) { // TODO Auto-generated method stub Map<String, Object> parameters = new HashMap<>(); parameters.put("member_no", member_no); parameters.put("newPwd", newPwd); mapper.updateUserPassword(parameters); } public void insertCQA(int member_no, String question_type, String question_title, String question_content) { // TODO Auto-generated method stub Map<String, Object> parameters = new HashMap<>(); parameters.put("member_no", member_no); parameters.put("question_type", question_type); parameters.put("question_title", question_title); parameters.put("question_content", question_content); mapper.insertCQA(parameters); } public void withdraw(String user_id) { // TODO Auto-generated method stub mapper.withdraw(user_id); } public List<OrderDTO> buyList(int member_no) { // TODO Auto-generated method stub List<OrderDTO> buyList = mapper.buyList(member_no); for (int i = 0; i < buyList.size(); i++) { String list_title = mapper.findList_title(buyList.get(i).getList_no()); buyList.get(i).setList_title(list_title); Map<String, Object> results = mapper.findOption(buyList.get(i).getOrder_no()); String order_add_option = (String) results.get("ORDER_ADD_OPTION"); String order_amount = (String) results.get("ORDER_AMOUNT"); String ordermade_no = (String) results.get("ORDERMADE_NO"); List<Integer> order_add_option_list = new ArrayList<>(); List<Integer> order_amount_list = new ArrayList<>(); List<Integer> ordermade_no_list = new ArrayList<>(); List<String> option_name_list = new ArrayList<>(); if (order_add_option.contains("/")) { String[] order_add_option_array = order_add_option.split("/"); String[] order_amount_array = order_amount.split("/"); System.out.println("---1---"); for (int j = 0; j < order_add_option_array.length; j++) { System.out.println(order_add_option_array[j]); System.out.println(order_amount_array[j]); order_add_option_list.add(Integer.parseInt(order_add_option_array[j])); order_amount_list.add(Integer.parseInt(order_amount_array[j])); } System.out.println("---2---"); System.out.println(order_add_option_list); System.out.println(order_amount_list); System.out.println("---3---"); buyList.get(i).setOrder_add_option(order_add_option_list); buyList.get(i).setOrder_amount(order_amount_list); } if (ordermade_no != null) { if (ordermade_no.contains("/")) { String[] ordermade_no_array = ordermade_no.split("/"); for (int j = 0; j < ordermade_no_array.length; j++) { ordermade_no_list.add(Integer.parseInt(ordermade_no_array[j])); } buyList.get(i).setOrdermade_no(ordermade_no_list); } } for (int j = 0; j < order_add_option_list.size(); j++) { String option_name = mapper.findOption_name(order_add_option_list.get(j)); option_name_list.add(option_name); } buyList.get(i).setOption_name(option_name_list); } return buyList; } public List<CustomerQABoardDTO> cQAList(int member_no) { // TODO Auto-generated method stub return mapper.cQAList(member_no); } public Map<String, Object> buyerPQList(int member_no) { // TODO Auto-generated method stub Map<String, Object> parameters = new HashMap<>(); List<QABoardDTO> buyerPQList = mapper.buyerPQList(member_no); List<String> list_title_list = new ArrayList<>(); for (int i = 0; i < buyerPQList.size(); i++) { String list_title = mapper.findList_title(buyerPQList.get(i).getList_no()); list_title_list.add(list_title); } parameters.put("buyerPQList", buyerPQList); parameters.put("list_title_list", list_title_list); return parameters; } public Map<String, Object> buyerReviewList(int member_no) { // TODO Auto-generated method stub Map<String, Object> parameters = new HashMap<>(); List<BuyReviewDTO> buyerReviewList = mapper.buyerReviewList(member_no); List<String> list_title_list = new ArrayList<>(); for (int i = 0; i < buyerReviewList.size(); i++) { String list_title = mapper.findList_title(buyerReviewList.get(i).getList_no()); list_title_list.add(list_title); } parameters.put("buyerReviewList", buyerReviewList); parameters.put("list_title_list", list_title_list); return parameters; } public Map<String, Object> sellList(String user_id) { // TODO Auto-generated method stub Map<String, Object> parameters = new HashMap<>(); List<OrderDTO> sellList = mapper.sellList(user_id); List<MemberDTO> buyerList = new ArrayList<>(); System.out.println("---sellList---"); System.out.println(sellList); System.out.println("------"); for (int i = 0; i < sellList.size(); i++) { MemberDTO buyer = mapper.findBuyer(sellList.get(i).getMember_no()); buyerList.add(buyer); Map<String, Object> results = mapper.findOption(sellList.get(i).getOrder_no()); String order_add_option = (String) results.get("ORDER_ADD_OPTION"); String order_amount = (String) results.get("ORDER_AMOUNT"); String ordermade_no = (String) results.get("ORDERMADE_NO"); List<Integer> order_add_option_list = new ArrayList<>(); List<Integer> order_amount_list = new ArrayList<>(); List<Integer> ordermade_no_list = new ArrayList<>(); List<String> option_name_list = new ArrayList<>(); if (order_add_option.contains("/")) { String[] order_add_option_array = order_add_option.split("/"); String[] order_amount_array = order_amount.split("/"); for (int j = 0; j < order_add_option_array.length; j++) { order_add_option_list.add(Integer.parseInt(order_add_option_array[j])); order_amount_list.add(Integer.parseInt(order_amount_array[j])); } sellList.get(i).setOrder_add_option(order_add_option_list); sellList.get(i).setOrder_amount(order_amount_list); } if (ordermade_no != null) { if (ordermade_no.contains("/")) { String[] ordermade_no_array = ordermade_no.split("/"); for (int j = 0; j < ordermade_no_array.length; j++) { ordermade_no_list.add(Integer.parseInt(ordermade_no_array[j])); } sellList.get(i).setOrdermade_no(ordermade_no_list); } } for (int j = 0; j < order_add_option_list.size(); j++) { String option_name = mapper.findOption_name(order_add_option_list.get(j)); option_name_list.add(option_name); } sellList.get(i).setOption_name(option_name_list); } parameters.put("sellList", sellList); parameters.put("buyerList", buyerList); return parameters; } public Map<String, Object> sellerPQAList(String user_id) { // TODO Auto-generated method stub Map<String, Object> parameters = new HashMap<>(); List<QABoardDTO> sellerPQAList = mapper.sellerPQAList(user_id); List<String> list_title_list = new ArrayList<>(); for (int i = 0; i < sellerPQAList.size(); i++) { String list_title = mapper.findList_title(sellerPQAList.get(i).getList_no()); list_title_list.add(list_title); } parameters.put("sellerPQAList", sellerPQAList); parameters.put("list_title_list", list_title_list); return parameters; } public Map<String, Object> sellerReviewList(String user_id) { // TODO Auto-generated method stub Map<String, Object> parameters = new HashMap<>(); List<BuyReviewDTO> sellerReviewList = mapper.sellerReviewList(user_id); List<String> list_title_list = new ArrayList<>(); for (int i = 0; i < sellerReviewList.size(); i++) { String list_title = mapper.findList_title(sellerReviewList.get(i).getList_no()); list_title_list.add(list_title); } parameters.put("sellerReviewList", sellerReviewList); parameters.put("list_title_list", list_title_list); return parameters; } public MemberDTO findBuyer(int member_no) { return mapper.findBuyer(member_no); } public List<ListDTO> registerList(String user_id) { // TODO Auto-generated method stub return mapper.registerList(user_id); } public void cor(int order_no) { // TODO Auto-generated method stub mapper.cor(order_no); } }
import java.util.*; // general n sum code. public class ThreeSum { public static List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); return threeSum(nums, 0, 3, 0); } public static List<List<Integer>> threeSum(int[] nums, int begin, int k, int target) { List<List<Integer>> result = new ArrayList<>(); Set<Integer> visited = new HashSet<>(); if (k == 2) { int i = begin, j = nums.length - 1; while (i < j) { int sum = nums[i] + nums[j]; if (sum == target && !visited.contains(nums[i])) { visited.add(nums[i]); List<Integer> branch = new ArrayList<>(); branch.add(nums[i]); branch.add(nums[j]); result.add(branch); i++; j--; } else if (sum < target) { i++; } else { //sum > target j--; } } return result; } for (int i = begin; i < nums.length; i++) { if (visited.contains(nums[i])) continue; visited.add(nums[i]); List<List<Integer>> list1 = threeSum(nums, i + 1, k - 1, target - nums[i]); if (list1.size() == 0) continue; for (List<Integer> list : list1) list.add(nums[i]); result.addAll(list1); } return result; } public static void main(String args[]) { int[] nums = {-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6}; List<List<Integer>> lists = threeSum(nums); for (List<Integer> list : lists) { for (int e : list) { System.out.print(e + " "); } System.out.println(); } } }
package com.pmm.sdgc.model; import java.io.Serializable; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * * @author dreges */ @Entity @Table(name="cursos") public class Curso implements Serializable { //VAR private static final long serialVersionUID = 1L; @Id @Column(name="id_curso") private String id; @Column(name="nome_curso") private String nome; @Column(name="controle") private String controle; //JOIN @ManyToOne @JoinColumn(name = "id_curso_grau_curso", referencedColumnName = "id_curso_grau") private CursoGrau grau; //GET SET public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public CursoGrau getGrau() { return grau; } public void setGrau(CursoGrau grau) { this.grau = grau; } public String getControle() { return controle; } public void setControle(String controle) { this.controle = controle; } @Override public int hashCode() { int hash = 5; return hash; } //COMPARACAO @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Curso other = (Curso) obj; if (!Objects.equals(this.id, other.id)) { return false; } return true; } }
package com.example.hyunyoungpark.addressbookdemo.Data; //extend with ContentProvider import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.example.hyunyoungpark.addressbookdemo.R; public class AddressBookContentProvider extends ContentProvider{ //1 Create instance of your database private AddressBookDatabaseHelper dbHelper; //2. URI Matcher that helps ContentProvider to determine // the operation to perform // we have two uris 1) that gives you all rows of contact // 2) That gives you only one row of contact based on ID private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); //Constant values that are used with URIMATCHER to // determine the operations to performed private static final int CONTACTS = 2; private static final int ONE_CONTACT = 1; // //static block to configure this URIMATCHER static{ //URI for contact table that will return all rows uriMatcher.addURI(DatabaseDescription.AUTHORITY, DatabaseDescription.Contact.TABLE_NAME,CONTACTS); //uri for contact table with specific #id value uriMatcher.addURI(DatabaseDescription.AUTHORITY, DatabaseDescription.Contact.TABLE_NAME + "/#" ,ONE_CONTACT); } @Override public boolean onCreate() { //create the database dbHelper = new AddressBookDatabaseHelper(getContext()); return true; } // select the data or query the database // (this one is method similar to SELECT * FROM CONTACT; // or SELECT * FROM CONTACT where CONTACT_ID = #value; @Nullable @Override public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) { //create a sqllitebuilder for querying contact table SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); //you want to query to which table //that is specified by setTable() queryBuilder.setTables(DatabaseDescription.Contact.TABLE_NAME); switch(uriMatcher.match(uri)) { case ONE_CONTACT : //contact with specific ID will be selcetd here // add the ID value from URI to the QueryBuilder queryBuilder.appendWhere ((DatabaseDescription.Contact._ID + " = " + uri.getLastPathSegment())); break; case CONTACTS : //all contacts will be selected //this is for all rows break; default: throw new UnsupportedOperationException( getContext().getString(R.string.invalid_query_uri) + uri ); } //we just finished creating the query //exceution is remianed Cursor cursor = queryBuilder.query(dbHelper.getReadableDatabase(), projection, selection, selectionArgs, // Columns & rows null, null, sortOrder) ; // GroupBY and Having //configure tthe cursor that whenever data is changed // cursor should get updated //this method needs a Content provider obj // & URI to invoke it cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; } //MIME type @Nullable @Override public String getType(@NonNull Uri uri) { return null; } //insert a new Contact to the database @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) { //uri it represents table in which data will be added //ContentValues it represents the object containg //key-value pair Uri newContact = null; //Check whether uri is for contact table //If URI is a match for insert //then get the writable database, use the insert() switch(uriMatcher.match(uri)) { //add the new data to the end of table // not on specific ID value . // CONTACTS give you a full table case CONTACTS : //insert the new contact-- success it should //return the id value ( a value 0r -1) //get the database instance long rowID = dbHelper.getWritableDatabase().insert( DatabaseDescription.Contact.TABLE_NAME, null, //nullcolumnHack values ); //nullColumnHack : SQLite doesn't support inserting //empty row in table , Instead making it illegal to pass // empty contentvalues it identifies a columns that // accept a NULL value. //check for success if yes create a uri for new contact if(rowID>0) { newContact = DatabaseDescription.Contact.buildContactUri(rowID); //notify the cursor for newly added data getContext().getContentResolver().notifyChange(uri,null); } else { //database operation gets fail throw insert failed exception throw new SQLException( getContext().getString(R.string.insert_failed)); } break; default: throw new SQLException( getContext().getString(R.string.insert_failed)); } return newContact; } // delete an existing contact // URi means row to delete // Where clause specifyinf a row to delete //String[] having value for where caluse @Override public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) { int noofRowsDeleted; //check the uri for one contact switch(uriMatcher.match(uri)) { case ONE_CONTACT: //get from the uri the id of contact for delete String id = uri.getLastPathSegment(); //delete() // 1. Table name // 2. Where Clause // 3. Array of string subtitute into Where Cluase noofRowsDeleted = dbHelper.getWritableDatabase().delete( DatabaseDescription.Contact.TABLE_NAME, DatabaseDescription.Contact._ID + " = " + id , selectionArgs ); break; default: throw new SQLException( getContext().getString(R.string.invalid_delete_uri) ); } //if delete is successful notify the cursor about // database change if(noofRowsDeleted >0) { getContext().getContentResolver().notifyChange(uri,null); } return noofRowsDeleted; } //change the existing value of contact @Override //uri : row // ContentValues : key-value pair // Selection: where clause // SelectionArgs : a string array for Where clause public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) { int noOfRowsUpdated; //we need uri matcher for one contact switch ((uriMatcher.match(uri))) { case ONE_CONTACT: //get the id from uri using getlastpathsegmemt String id = uri.getLastPathSegment(); //update the data // 1. tablename // 2. contentvalue // 3. where clause // 4. values noOfRowsUpdated = dbHelper.getWritableDatabase().update( DatabaseDescription.Contact.TABLE_NAME, values, DatabaseDescription.Contact._ID + " = " + id , // e.g. where id = 50 selectionArgs ); break; default: throw new SQLException( getContext().getString(R.string.invalid_update_uri) ); } //if changes are succcessful notify the // changes in cursor if(noOfRowsUpdated > 0) { getContext().getContentResolver().notifyChange(uri,null); } return noOfRowsUpdated; } }
package com.github.riyaz.bakingapp.model; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; /** * POJO representing a single step in the recipe * * @author Riyaz */ @SuppressWarnings("WeakerAccess") public final class Step implements Parcelable { /** * Id of the this step. This is also the order number for the steps */ @SerializedName("id") private int id; /** * A short readable description of the recipe */ @SerializedName("shortDescription") private String shortDescription; /** * A more detailed description of this step */ @SerializedName("description") private String description; /** * URL to an associated video to this step, if any */ @SerializedName("videoURL") private String video; /** * Url to the thumbnail of this step, if any */ @SerializedName("thumbnailURL") private String thumbnail; //================================================================================// //================================ AUTO GENERATED ================================// //================================================================================// public int getId() { return id; } public String getShortDescription() { return shortDescription; } public String getDescription() { return description; } public String getVideo() { return video; } public String getThumbnail() { return thumbnail; } @Override public String toString() { return "Step{" + "id=" + id + ", shortDescription='" + shortDescription + '\'' + ", description='" + description + '\'' + ", video='" + video + '\'' + ", thumbnail='" + thumbnail + '\'' + '}'; } //================================================================================// //================================== PARCELABLE ==================================// //================================================================================// private Step(Parcel in){ this.id = in.readInt(); this.shortDescription = in.readString(); this.description = in.readString(); this.video = in.readString(); this.thumbnail = in.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(id); dest.writeString(shortDescription); dest.writeString(description); dest.writeString(video); dest.writeString(thumbnail); } public static final Creator<Step> CREATOR = new Creator<Step>() { @Override public Step createFromParcel(Parcel source) { return new Step(source); } @Override public Step[] newArray(int size) { return new Step[size]; } }; }
package com.mhg.weixin.config.shiro; import at.pollux.thymeleaf.shiro.dialect.ShiroDialect; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.apache.shiro.mgt.SecurityManager; import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; /** * @Classname ShiroConfig * @Description TODO * @Date 2020/2/1 14:01 * @Created by pwt */ @Configuration public class ShiroConfig { @Bean public CustomRealm customRealm() { CustomRealm customRealm = new CustomRealm(); customRealm.setCredentialsMatcher(hashedCredentialsMatcher()); return customRealm; } @Bean public SecurityManager securityManager(){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(customRealm()); return securityManager; } @Bean public HashedCredentialsMatcher hashedCredentialsMatcher() { HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); hashedCredentialsMatcher.setHashAlgorithmName("MD5");// 散列算法:这里使用MD5算法; hashedCredentialsMatcher.setHashIterations(2);// 散列的次数,比如散列两次,相当于 md5(md5("")); return hashedCredentialsMatcher; } /** * 配置Shiro的Web过滤器,拦截浏览器请求并交给SecurityManager处理 * @return */ @Bean public ShiroFilterFactoryBean webFilter(){ ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); //设置securityManager shiroFilterFactoryBean.setSecurityManager(securityManager()); //配置拦截链 使用LinkedHashMap,因为LinkedHashMap是有序的,shiro会根据添加的顺序进行拦截 // Map<K,V> K指的是拦截的url V值的是该url是否拦截 Map<String,String> filterChainMap = new LinkedHashMap<String,String>(16); //配置退出过滤器logout,由shiro实现 filterChainMap.put("/logout","logout"); //authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问,先配置anon再配置authc。 filterChainMap.put("/login","anon"); filterChainMap.put("/css/**.css","anon"); filterChainMap.put("/font/**","anon"); filterChainMap.put("/**.js","anon"); filterChainMap.put("/lib/**","anon"); filterChainMap.put("/modules/**","anon"); filterChainMap.put("/lay/**","anon"); filterChainMap.put("/**", "authc"); //设置默认登录的URL. shiroFilterFactoryBean.setLoginUrl("/login"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainMap); return shiroFilterFactoryBean; } /** * 开启aop注解支持 * 即在controller中使用 @RequiresPermissions("user/userList") */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){ AuthorizationAttributeSourceAdvisor attributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); //设置安全管理器 attributeSourceAdvisor.setSecurityManager(securityManager); return attributeSourceAdvisor; } @Bean @ConditionalOnMissingBean public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator(); defaultAAP.setProxyTargetClass(true); return defaultAAP; } /** * 处理未授权的异常,返回自定义的错误页面(403) * @return */ @Bean public SimpleMappingExceptionResolver simpleMappingExceptionResolver() { SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver(); Properties properties = new Properties(); /*未授权处理页*/ properties.setProperty("UnauthorizedException", "403.html"); resolver.setExceptionMappings(properties); return resolver; } /** * 用于thymeleaf模板使用shiro标签 * @return */ @Bean public ShiroDialect shiroDialect() { return new ShiroDialect(); } }
/** * Server-side support classes including container-specific strategies * for upgrading a request. */ @NonNullApi @NonNullFields package org.springframework.web.socket.server.support; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
import java.applet.Applet; import java.awt.*; import com.sun.j3d.utils.applet.MainFrame; import com.sun.j3d.utils.geometry.*; import com.sun.j3d.utils.universe.*; import javax.media.j3d.*; import javax.vecmath.*; import com.sun.j3d.utils.behaviors.mouse.*; public class BSurfaceMerging extends Applet {public BranchGroup createBranchGroupSceneGraph() {BranchGroup BranchGroupRoot =new BranchGroup(); BoundingSphere bounds=new BoundingSphere(new Point3d(0.0,0.0,0.0),100.0); Color3f bgColor=new Color3f(1.0f,1.0f,1.0f); Background bg=new Background(bgColor); bg.setApplicationBounds(bounds); BranchGroupRoot.addChild(bg); Color3f directionalColor=new Color3f(1.f,1.f,1.f); Vector3f vec=new Vector3f(0.f,0.f,-1.0f); DirectionalLight directionalLight=new DirectionalLight(directionalColor,vec); directionalLight.setInfluencingBounds(bounds); BranchGroupRoot.addChild(directionalLight); Transform3D tr=new Transform3D(); tr.setScale(0.85); TransformGroup transformgroup=new TransformGroup(tr); transformgroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); transformgroup.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); BranchGroupRoot.addChild(transformgroup); MouseRotate mouserotate = new MouseRotate(); mouserotate.setTransformGroup(transformgroup); BranchGroupRoot.addChild(mouserotate); mouserotate.setSchedulingBounds(bounds); MouseZoom mousezoom = new MouseZoom(); mousezoom.setTransformGroup(transformgroup); BranchGroupRoot.addChild(mousezoom); mousezoom.setSchedulingBounds(bounds); MouseTranslate mousetranslate = new MouseTranslate(); mousetranslate.setTransformGroup(transformgroup); BranchGroupRoot.addChild(mousetranslate); mousetranslate.setSchedulingBounds(bounds); //定义第一个双三次B样条曲面的16个控制顶点 float[][][] P1={{{-0.8f,0.9f,-0.4f,1.f}, {-0.2f,0.8f,-0.5f,1.f}, {0.2f,0.9f,-0.4f,1.f}, {0.8f,0.8f,-0.5f,1.f} }, {{-0.8f,0.7f,-0.4f,1.f}, {-0.2f,0.6f,0.9f,1.f}, {0.2f,0.7f,0.8f,1.f}, {0.8f,0.6f,-0.4f,1.f} }, {{-0.8f,0.4f,-0.4f,1.f}, {-0.2f,0.5f,0.8f,1.f}, {0.2f,0.3f,0.7f,1.f}, {0.8f,0.4f,-0.5f,1.f} }, {{-0.8f,0.f,-0.8f,1.f}, {-0.2f,0.1f,0.9f,1.f}, {0.2f,0.f,-0.8f,1.f}, {0.8f,0.1f,0.9f,1.f} } }; //定义第一个双三次B样条曲面的外观属性 Appearance app1 = new Appearance(); PolygonAttributes polygona1=new PolygonAttributes(); polygona1.setBackFaceNormalFlip(true); polygona1.setCullFace(PolygonAttributes.CULL_NONE); //polygona1.setPolygonMode(PolygonAttributes.POLYGON_LINE); app1.setPolygonAttributes(polygona1); Color3f color11=new Color3f(1.f,0.f,0.f); Material material1 = new Material(); material1.setAmbientColor(color11); material1.setSpecularColor(color11); material1.setDiffuseColor(color11); //material.setEmissiveColor(red); material1.setShininess(128.f); app1.setMaterial(material1); //定义第一个双三次B样条曲面控制顶点网格的外观属性 Appearance app10 = new Appearance(); PolygonAttributes polygona10=new PolygonAttributes(); polygona10.setBackFaceNormalFlip(true); polygona10.setCullFace(PolygonAttributes.CULL_NONE); polygona10.setPolygonMode(PolygonAttributes.POLYGON_LINE); app10.setPolygonAttributes(polygona10); Color3f color110=new Color3f(0.f,1.f,0.f); Material material10 = new Material(); material10.setAmbientColor(color110); material10.setSpecularColor(color110); material10.setDiffuseColor(color110); //material10.setEmissiveColor(red); material10.setShininess(128.f); app10.setMaterial(material10); //定义第二个双三次B样条曲面的16个控制顶点, //其中的三行控制顶点与前一个曲面相同,这样才能保证两个曲面拼接在一起。 float[][][] P2={{{-0.8f,0.7f,-0.4f,1.f}, {-0.2f,0.6f,0.9f,1.f}, {0.2f,0.7f,0.8f,1.f}, {0.8f,0.6f,-0.4f,1.f} }, {{-0.8f,0.4f,-0.4f,1.f}, {-0.2f,0.5f,0.8f,1.f}, {0.2f,0.3f,0.7f,1.f}, {0.8f,0.4f,-0.5f,1.f} }, {{-0.8f,0.f,-0.8f,1.f}, {-0.2f,0.1f,0.9f,1.f}, {0.2f,0.f,-0.8f,1.f}, {0.8f,0.1f,0.9f,1.f} }, {{-0.8f,-0.9f,0.4f,1.f}, {-0.2f,-0.9f,0.6f,1.f}, {0.2f,-0.8f,0.4f,1.f}, {0.8f,-0.9f,0.6f,1.f} } }; //定义第二个双三次B样条曲面的外观属性 Appearance app2 = new Appearance(); PolygonAttributes polygona2=new PolygonAttributes(); polygona2.setBackFaceNormalFlip(true); polygona2.setCullFace(PolygonAttributes.CULL_NONE); //polygona2.setPolygonMode(PolygonAttributes.POLYGON_LINE); app2.setPolygonAttributes(polygona2); Color3f color22=new Color3f(0.f,1.f,0.f); Material material2 = new Material(); material2.setAmbientColor(color22); material2.setSpecularColor(color22); material2.setDiffuseColor(color22); //material.setEmissiveColor(red); material2.setShininess(128.f); app2.setMaterial(material2); //定义第二个双三次B样条曲面控制顶点网格的外观属性 Appearance app20 = new Appearance(); PolygonAttributes polygona20=new PolygonAttributes(); polygona20.setBackFaceNormalFlip(true); polygona20.setCullFace(PolygonAttributes.CULL_NONE); polygona20.setPolygonMode(PolygonAttributes.POLYGON_LINE); app20.setPolygonAttributes(polygona20); Color3f color220=new Color3f(0.f,1.f,0.f); Material material20 = new Material(); material20.setAmbientColor(color220); material20.setSpecularColor(color220); material20.setDiffuseColor(color220); //material20.setEmissiveColor(red); material20.setShininess(128.f); app20.setMaterial(material20); Shape3D BSurfaceface1=new BThreeOrderSurfaceface(P1,app1); transformgroup.addChild(BSurfaceface1); Shape3D BSurfaceface2=new BThreeOrderSurfaceface(P2,app2); transformgroup.addChild(BSurfaceface2); Shape3D BControlPoints1=new BSurfaceControlPoints(P1,app10); transformgroup.addChild(BControlPoints1); Shape3D BControlPoints2=new BSurfaceControlPoints(P2,app20); transformgroup.addChild(BControlPoints2); BranchGroupRoot.compile(); return BranchGroupRoot; } public BSurfaceMerging() {setLayout(new BorderLayout()); GraphicsConfiguration gc = SimpleUniverse.getPreferredConfiguration(); Canvas3D c=new Canvas3D(gc); add("Center",c); BranchGroup BranchGroupScene=createBranchGroupSceneGraph(); SimpleUniverse u=new SimpleUniverse(c); u.getViewingPlatform().setNominalViewingTransform(); u.addBranchGraph(BranchGroupScene); } public static void main(String[] args) {new MainFrame(new BSurfaceMerging(),400,400);}}
package slimeknights.tconstruct.library.modifiers; import com.google.common.collect.ImmutableList; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import java.util.List; import slimeknights.mantle.util.RecipeMatch; import slimeknights.tconstruct.library.TinkerRegistry; import slimeknights.tconstruct.library.traits.AbstractTrait; import slimeknights.tconstruct.library.utils.TinkerUtil; /** * Represents a modifier that has trait-logic * Modifier can have multiple levels. * Since this is intended for modifiers it uses a modifier */ public class ModifierTrait extends AbstractTrait implements IModifierDisplay { protected final int maxLevel; public ModifierTrait(String identifier, int color) { this(identifier, color, 0, 0); } public ModifierTrait(String identifier, int color, int maxLevel, int countPerLevel) { super(identifier, color); // register the modifier trait TinkerRegistry.addTrait(this); this.maxLevel = maxLevel; this.aspects.clear(); if(maxLevel > 0 && countPerLevel > 0) { addAspects(new ModifierAspect.MultiAspect(this, color, maxLevel, countPerLevel, 1)); } else { if(maxLevel > 0) { addAspects(new ModifierAspect.LevelAspect(this, maxLevel)); } addAspects(new ModifierAspect.DataAspect(this, color), ModifierAspect.freeModifier); } } @Override public boolean canApplyCustom(ItemStack stack) { // not present yet, ok if(super.canApplyCustom(stack)) { return true; } // no max level else if(maxLevel == 0) { return false; } // already present, limit by level NBTTagCompound tag = TinkerUtil.getModifierTag(stack, identifier); return ModifierNBT.readTag(tag).level <= maxLevel; } @Override public String getTooltip(NBTTagCompound modifierTag, boolean detailed) { if(maxLevel > 0) { return getLeveledTooltip(modifierTag, detailed); } return super.getTooltip(modifierTag, detailed); } @Override public int getColor() { return color; } @Override public List<List<ItemStack>> getItems() { ImmutableList.Builder<List<ItemStack>> builder = ImmutableList.builder(); for(RecipeMatch rm : items) { List<ItemStack> in = rm.getInputs(); if(!in.isEmpty()) { builder.add(in); } } return builder.build(); } public ModifierNBT.IntegerNBT getData(ItemStack tool) { NBTTagCompound tag = TinkerUtil.getModifierTag(tool, getModifierIdentifier()); return ModifierNBT.readInteger(tag); } }
public class RotatedBinarySearch { static int binarySearch(int[] arr, int x, int low, int high) { if(low > high) return -1; int mid = (high + low) / 2; boolean rotatedAtLeft = arr[mid] < arr[low]; boolean rotatedAtRight = arr[mid] > arr[high]; if((!rotatedAtLeft && arr[mid] > x) || (rotatedAtLeft && !isIn(arr[low], arr[mid], x))) return binarySearch(arr, x, low, mid - 1); else if((!rotatedAtRight && arr[mid] < x) || (rotatedAtRight && !isIn(arr[mid], arr[high], x))) return binarySearch(arr, x, mid + 1, high); else return mid; } static boolean isIn(int a, int b, int x) { if(a > b) { int tmp = a; a = b; b = tmp; } return x >= a && x <= b; } public static void main(String[] args) { int[] arr = {13, 20, 25, 1, 2, 5, 8, 9}; System.out.println("search(5) : " + binarySearch(arr, 5, 0, arr.length - 1)); System.out.println("search(21) : " + binarySearch(arr, 21, 0, arr.length - 1)); } }
package com.ideal.cash.register.models; /** * 店员 * @author Ideal */ public class Clerk { /** * 设定优惠活动是否开启 * @param onSale 要设定的活动 * @param active 是否开启 */ public void setOnSaleActivation(OnSale onSale, boolean active) { onSale.setActive(active); } /** * 添加商品信息到指定优惠 * @param onSale 要设定的活动 * @param barcode 条形码 */ public void addOnSaleGoods(OnSale onSale, String barcode) { onSale.addOnSaleGoods(barcode); } /** * 从指定优惠中移除指定商品 * @param onSale 要设定的活动 * @param barcode 条形码 */ public void removeOnSaleGoods(OnSale onSale, String barcode) { onSale.removeOnSaleGoods(barcode); } /** * 清空指定优惠中的参与商品 * @param onSale 要设定的活动 */ public void clearOnSaleGoods(OnSale onSale) { onSale.getOnSaleGoods().clear(); } /** * 设置优惠方案冲突时首选优惠方案 * @param onSale */ public void setFirstOnSale(OnSale onSale) { RegisterInfos.setFirstOnSale(onSale); } /** * 设定是否在小票中列出指定优惠明细 * @param onSale 要设定的活动 * @param showDiscount 是否显示 */ public void setShowDiscount(OnSale onSale, boolean showDiscount) { onSale.setShowDiscount(showDiscount); } /** * 添加商品信息 * @param goods 商品信息 */ public void addGoods(Goods goods) { RegisterInfos.GOODS_INFO.put(goods.getBarcode(), goods); } /** * 删除商品信息,同时删除该商品优惠信息 * @param barcode 条形码 */ public void removeGoods(String barcode) { RegisterInfos.GOODS_INFO.remove(barcode); // 所有优惠信息 OnSale[] onSaleInfos = OnSale.values(); for (OnSale onSale : onSaleInfos) { removeOnSaleGoods(onSale, barcode); } } }
package RestAssured; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import googleApis.payLoad; import googleApis.resources; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import io.restassured.RestAssured; import io.restassured.http.ContentType; public class basic2 { Properties prop = new Properties(); @BeforeTest public void getData() throws IOException { FileInputStream fis = new FileInputStream(System.getProperty("user.dir")+"//env.properties"); prop.load(fis); } @Test public void test() { RestAssured.baseURI = prop.getProperty("HOST"); given() .queryParam("key", prop.getProperty("KEY")).body(payLoad.getPostData()) .when() .post(resources.placePostData()) .then() .assertThat().statusCode(200).and() .contentType(ContentType.JSON).and().body("status", equalTo("OK")); // Grab the place-Id and use the same in delete place API } }
/* * Merge HRIS API * The unified API for building rich integrations with multiple HR Information System platforms. * * The version of the OpenAPI document: 1.0 * Contact: hello@merge.dev * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package merge_hris_client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.annotations.SerializedName; import java.io.IOException; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; /** * Gets or Sets EmploymentStatusEnum */ @JsonAdapter(EmploymentStatusEnum.Adapter.class) public enum EmploymentStatusEnum { ACTIVE("ACTIVE"), PENDING("PENDING"), INACTIVE("INACTIVE"); private String value; EmploymentStatusEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static EmploymentStatusEnum fromValue(String value) { for (EmploymentStatusEnum b : EmploymentStatusEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } public static class Adapter extends TypeAdapter<EmploymentStatusEnum> { @Override public void write(final JsonWriter jsonWriter, final EmploymentStatusEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public EmploymentStatusEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return EmploymentStatusEnum.fromValue(value); } } }
package com.openfarmanager.android.utils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.openfarmanager.android.App; import java.text.ParseException; import java.util.StringTokenizer; /** * A set of static methods for IPv4 addreses processing, conversion and validation. * * @author nvv && bav */ public class NetworkCalculator { private static final String TAG = "NetworkUtils"; public static final String[] tunnelSubnets = {"192.168.0.0/16", "172.16.0.0/12", "10.0.0.0/8"}; public static final String ipPattern = "(\\d{1,3}\\.){3}\\d{1,3}"; /** * Converts IP address from <code>int</code> to <code>String</code> * representation. * * @param address given IP address * @return IP address as string like "x.x.x.x" */ public static String ipIntToStringRevert(int address) { return String.format("%d.%d.%d.%d", address & 0xff, address >> 8 & 0xff, address >> 16 & 0xff, address >> 24 & 0xff); } public static byte[] ipIntToBytesReverted(int address) { byte[] ip = new byte[4]; ip[0] = (byte) (address & 0xff); ip[1] = (byte) (address >> 8 & 0xff); ip[2] = (byte) (address >> 16 & 0xff); ip[3] = (byte) (address >> 24 & 0xff); return ip; } public static String ipIntToString(int address) { StringBuilder sb = new StringBuilder(15); sb.append((address >>> 24) & 0xFF).append('.') .append((address >>> 16) & 0xFF).append('.') .append((address >>> 8) & 0xFF).append('.') .append((address) & 0xFF); return sb.toString(); } public static String revertIpAddress(String ipAddress) throws ParseException { if (null == ipAddress) { throw new ParseException("Can't parse internet address", 0); } String[] octets = ipAddress.split("[.]"); if (4 != octets.length) { throw new ParseException("Can't parse internet address", 0); } String revertedIp = ""; for (int i = 3; i >= 0; i--) { revertedIp += octets[i]; if (i > 0) { revertedIp += "."; } } return revertedIp; } public static byte[] ipIntToByteArray(int value) { return new byte[]{ (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value}; } /** * Converts IP address from <code>byte[]</code> to <code>String</code> * representation. * * @param address given IP address * @return IP address as string like "x.x.x.x" */ public static String ipBytesToString(byte[] address) { return ((((int) address[0]) & 0xFF) + "." + (((int) address[1]) & 0xFF) + "." + (((int) address[2]) & 0xFF) + "." + (((int) address[3]) & 0xFF)); } /** * Converts IP address from <code>byte</code> array to <code>int</code> * representation. * * @param _addr given IP address * @return IP address as int value */ public static int ipBytesToInt(byte[] _addr) { int address; address = _addr[3] & 0xFF; address |= ((_addr[2] << 8) & 0xFF00); address |= ((_addr[1] << 16) & 0xFF0000); address |= ((_addr[0] << 24) & 0xFF000000); return address; } /** * Converts IP address from <code>String</code> to <code>byte</code> array * representation. * * @param address given IP address as string like "x.x.x.x" * @return IP address as four bytes */ public static byte[] ipStringToBytes(String address) { StringTokenizer st = new StringTokenizer(address, "."); int i = 0; byte[] ip = new byte[4]; while (st.hasMoreTokens()) { int a = Integer.parseInt(st.nextToken()); ip[i++] = (byte) a; } return ip; } /** * Converts IP address from <code>String</code> to <code>int</code> * representation. * * @param address given IP address as string like "x.x.x.x" * @return IP address as int value * @throws java.text.ParseException is string cannot be parsed */ public static int ipStringToInt(String address) { return ipBytesToInt(ipStringToBytes(address)); } /** * Splits string representation of IPv4 address it array of integer numbers. * * @param ip IP address as string * @return array of integers numbers * @throws java.text.ParseException if string cannot be parsed */ public static int[] ipStringToIntArray(String ip) throws ParseException { String[] values = ip.split("[.]"); int[] intValues = new int[4]; int i = 0; try { for (String str : values) { intValues[i++] = Integer.parseInt(str, 10); } } catch (Exception e) { throw new ParseException("Can't parse internet address", 0); } if (i < 4) // To short internet address throw new ParseException("Invalid internet address", 0); return intValues; } /** * Corrects string representation of IP address if necessary, removing redundant leading zeros in each number and * checking each number to be between 0 and 255 * * @param ip address as string * @return corrected IP address as string */ public static String checkIp(String ip) { StringTokenizer st = new StringTokenizer(ip, "."); boolean first = true; String newIp = ""; try { while (st.hasMoreTokens()) { int value = Integer.parseInt(st.nextToken(), 10); if (value < 0 || value > 255) { return null; } if (first) { newIp += Integer.toString(value); first = false; } else { newIp += '.' + Integer.toString(value); } } } catch (Exception e) { return null; } return newIp; } /** * Corrects string representation of IP address if necessary, removing redundant leading zeros in each number. * Also checks equality of ip address and some reserved ip addresses. * * @param ip IP address as string * @return corrected IP address as string */ public static String correctIp(String ip) { ip = ip.trim(); String newIp = checkIp(ip); if (newIp == null || newIp.equals("0.0.0.0") || newIp.equals("255.255.255.255") || !newIp.matches(ipPattern)) { return null; } return newIp; } /** * Checks the correctness of IP address mask for local subnet. * * @param mask IP mask to check * @return true if IP mask is corect */ public static boolean isCorrectMask(String mask) { try { ipStringToIntArray(mask); } catch (ParseException e) { return false; } String[] masks = {"0.0.0.0", "128.0.0.0", "192.0.0.0", "224.0.0.0", "240.0.0.0", "248.0.0.0", "252.0.0.0", "254.0.0.0", "255.0.0.0", "255.128.0.0", "255.192.0.0", "255.224.0.0", "255.240.0.0", "255.248.0.0", "255.252.0.0", "255.254.0.0", "255.255.0.0", "255.255.128.0", "255.255.192.0", "255.255.224.0", "255.255.240.0", "255.255.248.0", "255.255.252.0", "255.255.254.0", "255.255.255.0", "255.255.255.128", "255.255.255.192", "255.255.255.224", "255.255.255.240", "255.255.255.248", "255.255.255.252", "255.255.255.254", "255.255.255.255" }; try { for (String mask1 : masks) { if (correctIp(mask).equals(mask1)) { return true; } } } catch (NullPointerException e) { return false; } return false; } public static boolean isValidIp(String address) { int[] intValues; try { intValues = ipStringToIntArray(address); } catch (ParseException e) { return false; } for (int quad : intValues) { if (quad < 0 || quad > 255) { return false; } } return true; } /** * Checks the correctness of IP address depending of local subnetnet class which is determining by first one ore two * numbers of IP address. * * @param ip IP to check * @return true if IP is correct */ public static boolean isCorrectIp(String ip) { int[] intValues; try { intValues = ipStringToIntArray(ip); } catch (ParseException e) { return false; } if ((intValues[0] == 10) && (intValues[1] >= 0 && intValues[1] <= 255) && (intValues[2] >= 0 && intValues[2] <= 255) && (intValues[3] >= 0 && intValues[3] <= 255)) { return true; } else if ((intValues[0] == 172) && (intValues[1] >= 16 && intValues[1] <= 31) && (intValues[2] >= 0 && intValues[2] <= 255) && (intValues[3] >= 0 && intValues[3] <= 255)) { return true; } else if ((intValues[0] == 192) && (intValues[1] == 168) && (intValues[2] >= 0 && intValues[2] <= 255) && (intValues[3] >= 0 && intValues[3] <= 255)) { return true; } return false; } public static String getTunnelSubnet(String ip) { if (!isCorrectIp(ip)) { throw new IllegalArgumentException("String [" + ip + "] is not correct virtual subnet IP address"); } if (ip.startsWith("192")) { return tunnelSubnets[0]; } else if (ip.startsWith("172")) { return tunnelSubnets[1]; } else { return tunnelSubnets[2]; } } /** * Convert CIDR subnet mask to quad form in network byte order * * @param maskLen CIDR subnet mask * @return subnet mask in network byte order */ public static byte[] cidrToQuad(int maskLen) { if (maskLen < 0 || maskLen > 32) { throw new IllegalArgumentException("CIDR mask should be in range 0-32."); } byte[] addr = new byte[4]; int mask = (0xFFFFFFFF << (32 - maskLen)); addr[0] = (byte) ((mask >>> 24) & 0xFF); addr[1] = (byte) ((mask >>> 16) & 0xFF); addr[2] = (byte) ((mask >>> 8) & 0xFF); addr[3] = (byte) (mask & 0xFF); return addr; } /** * Convert network mask in a quad form to a CIDR mask length * * @param mask network mask in a quad form * @return CIDR mask length */ public static int quadToCidr(byte mask[]) { if (mask.length != 4) { throw new IllegalArgumentException("Mask should be 4 bytes long."); } int maskLen = 0; int intMask = NetworkCalculator.ipBytesToInt(mask); // check either provided mask is contiguous // and calculate mask length for (int j = 0; j < 32 && intMask < 0; j++) { maskLen++; intMask <<= 1; } if (intMask > 0) { throw new IllegalArgumentException("The subnet mask has to be contiguous."); } return maskLen; } public static byte[] networkStartIp(byte[] ipAddress, byte[] mask) { return AND(ipAddress, mask); } public static byte[] networkStartIp(String ipAddress, String mask) throws ParseException { return networkStartIp(NetworkCalculator.ipStringToBytes(ipAddress), NetworkCalculator.ipStringToBytes(mask)); } public static int numberOfAddressesInMask(String mask) throws ParseException { int len = NetworkCalculator.quadToCidr(NetworkCalculator.ipStringToBytes(mask)); return (int) Math.pow(2, 32 - len); } public static int numberOfAddressesInMask(byte mask[]) { int len = NetworkCalculator.quadToCidr(mask); return (int) Math.pow(2, 32 - len); } public static byte[][] allAddressesInSubnet(byte[] startIp, int numberOfAddressesInMask) throws ParseException { byte[][] addresses = new byte[numberOfAddressesInMask][]; int start = ipBytesToInt(startIp); for (int i = 0; i < numberOfAddressesInMask; i++) { addresses[i] = ipStringToBytes(ipIntToString(start++)); } return addresses; } public static String[] allStringAddressesInSubnet(byte[] startIp, int numberOfAddressesInMask) throws ParseException { String[] addresses = new String[numberOfAddressesInMask]; int start = ipBytesToInt(startIp); for (int i = 0; i < numberOfAddressesInMask; i++) { addresses[i] = ipIntToString(start++); } return addresses; } public static byte[][] allAddressesInSubnet(String ipAddress, String mask) throws ParseException { byte[] startIp = networkStartIp(ipAddress, mask); int numberOfAddressesInMask = numberOfAddressesInMask(mask); return allAddressesInSubnet(startIp, numberOfAddressesInMask); } public static byte[][] allAddressesInSubnet(int ipAddress, int mask) throws ParseException { return allAddressesInSubnet(ipIntToString(ipAddress), ipIntToString(mask)); } public static String[] allStringAddressesInSubnet(String ipAddress, String mask) throws ParseException { byte[] startIp = networkStartIp(ipAddress, mask); int numberOfAddressesInMask = numberOfAddressesInMask(mask); return allStringAddressesInSubnet(startIp, numberOfAddressesInMask); } public static String[] allStringAddressesInSubnet(int ipAddress, int mask) throws ParseException { return allStringAddressesInSubnet(ipIntToString(ipAddress), ipIntToString(mask)); } public static String[] allStringAddressesInSubnet(byte[] ipAddress, byte[] mask) throws ParseException { return allStringAddressesInSubnet(ipBytesToString(ipAddress), ipBytesToString(mask)); } public static byte[] AND(byte[] a1, byte[] a2) { byte[] r = new byte[a1.length]; for (int i = 0; i < a1.length; i++) { r[i] = new Integer(a1[i] & a2[i]).byteValue(); } return r; } public static byte[] XOR(byte[] a1, byte[] a2) { byte[] r = new byte[a1.length]; for (int i = 0; i < a1.length; i++) { r[i] = new Integer(a1[i] ^ a2[i]).byteValue(); } return r; } public static byte[] NOT(byte[] a) { byte[] r = new byte[a.length]; for (int i = 0; i < a.length; i++) { r[i] = new Integer(~a[i]).byteValue(); } return r; } public static boolean isNetworkAvailable() { return NetworkInfo.State.CONNECTED == getState(); } public static NetworkInfo.State getState() { ConnectivityManager mgr = (ConnectivityManager) App.sInstance.getSystemService(Context.CONNECTIVITY_SERVICE); if (mgr != null) { try { NetworkInfo info = mgr.getActiveNetworkInfo(); if (info != null) { return info.getState(); } } catch (SecurityException ignored) { } } return null; } }
package demo.domain; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface ItemRepository extends JpaRepository<Item, Long> { List<Item> findByRestaurantId(String restaurantId); List<Item> findByOrderInfo(OrderInfo orderInfo); }
package com.hotel.master.category; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.hotel.mapper.MapperClz; @Service public class CategoryServiceImpl implements ICategoryService { @Autowired ICategoryRepo categoryRepo; @Autowired MapperClz mapperClz; @Override public List<CategoryDTO> findAll() { return mapperClz.convertToDto(categoryRepo.findAll()); } }
package com.reagan.graphingcalc; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.Timer; @SuppressWarnings("serial") public class CartesianPlane extends JPanel { //private Function f; private final double domainRadius; private Color graphColor; private int thickness; private ArrayList<Function> functions = new ArrayList<Function>(); public CartesianPlane(/*Function f,*/ double domainRadius, Color bkgrnd, Color graphColor, int thickness) { this.thickness = thickness; this.graphColor = graphColor; //this.f = f; this.domainRadius = domainRadius; setBorder(BorderFactory.createLineBorder(Color.BLACK)); this.setOpaque(true); this.setBackground(bkgrnd); } @Override public Dimension getPreferredSize() { return new Dimension(500,500); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); drawAxis(g); for (int i = 0; i < functions.size(); i++) graphMethod2(g, functions.get(i)); } public void addFunction(Function f) { functions.add(f); } private void drawAxis(Graphics g) { g.setColor(Color.DARK_GRAY); g.fillRect(getWidth()/2 - thickness/2, 0, thickness, getHeight()); g.fillRect(0, getHeight()/2 - thickness/2, getWidth(), thickness); } private void graphMethod2(Graphics g, Function f) { int m = 100; int totalPoints = m*getWidth(); CartesianPoint rawPoint = new CartesianPoint(0,0); CartesianPoint centered = new CartesianPoint(0,0);; CartesianPoint accurateToScale = new CartesianPoint(0,0); CartesianPoint subPixelPoint = new CartesianPoint(0,0); for(int x = 0; x <= totalPoints; x++) { subPixelPoint.x = x; rawPoint.x = subPixelPoint.x/m; centered = rawToCentered(rawPoint); accurateToScale = scaleToDomainRadius(centered, domainRadius); accurateToScale.y = f.f(accurateToScale.x); double xp = accurateToScale.x; g.setColor(new Color((float)(0.49*Math.sin(xp)+0.5),(float)(0.49*Math.sin(xp + 2)+0.5),(float)(0.49*Math.sin(xp + 4)+0.5))); g.fillRect(x/m-thickness/2, reverse(accurateToScale.y)-thickness/2, thickness, thickness); } } private void graph(Graphics g, Function f) { g.setColor(graphColor); CartesianPoint rawPoint = new CartesianPoint(0,0); CartesianPoint centered = new CartesianPoint(0,0);; CartesianPoint accurateToScale = new CartesianPoint(0,0); for(int y = 0; y < getHeight(); y++) { for(int x = 0; x < getWidth(); x++) { rawPoint.x = x; rawPoint.y = y; centered = rawToCentered(rawPoint); accurateToScale = scaleToDomainRadius(centered, domainRadius); double xp = accurateToScale.x; if (reverse(f.f(accurateToScale.x)) == y) { g.setColor(new Color((float)(0.49*Math.sin(xp)+0.5),(float)(0.49*Math.sin(xp + 2)+0.5),(float)(0.49*Math.sin(xp + 4)+0.5))); g.fillRect(x-thickness/2, y-thickness/2, thickness, thickness); } } } } private int reverse(double y) { return (int)((getHeight()/2) - (getWidth()*y)/(2*domainRadius)); } private CartesianPoint scaleToDomainRadius(CartesianPoint p, double domainRadius) { return new CartesianPoint((2*p.x*domainRadius/getWidth()),(2*p.y*domainRadius/getWidth())); } private CartesianPoint rawToCentered(CartesianPoint raw) { return new CartesianPoint((-getWidth()/2) + raw.x, (getHeight()/2) - raw.y); } }
/** * */ package com.gcit.lms.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.stereotype.Component; import com.gcit.lms.entity.BookCopies; /** * @BookCopies ppradhan * */ @Component public class BookCopiesDAO extends BaseDAO<BookCopies> implements ResultSetExtractor<List<BookCopies>>{ public void createBookCopies(BookCopies bookCopies) throws ClassNotFoundException, SQLException { jdbcTemplate.update("insert into tbl_book_copies (bookId,branchId,noOfCopies) values (?,?,?)", new Object[] { bookCopies.getBookId(), bookCopies.getBranchId(), bookCopies.getNoOfCopies() }); } public void updateBookCopies(BookCopies bookCopies) throws ClassNotFoundException, SQLException { jdbcTemplate.update("UPDATE tbl_book_copies SET noOfCopies=? WHERE bookId=? AND branchId=?", new Object[] { bookCopies.getNoOfCopies(), bookCopies.getBookId(), bookCopies.getBranchId() }); } public void deleteBookCopies(BookCopies bookCopies) throws ClassNotFoundException, SQLException { jdbcTemplate.update("delete from tbl_book_copies where bookId = ? and branchId= ?", new Object[] { bookCopies.getBookId(), bookCopies.getBranchId() }); } public List<BookCopies> readBookCopies() throws ClassNotFoundException, SQLException { return jdbcTemplate.query("select * from tbl_book_copies", this); } public List<BookCopies> bookCopiesPerBranch(BookCopies bookCopies) throws ClassNotFoundException, SQLException { return jdbcTemplate.query("select noOfCopies from tbl_book_copies where bookId=? and branchId=?", new Object[] { bookCopies.getBookId(), bookCopies.getBranchId() },this); } public Integer countBookCopies( int branchId, int bookId) throws SQLException, ClassNotFoundException { List<BookCopies> bc = jdbcTemplate.query("SELECT * FROM tbl_book_copies WHERE branchId = ? AND bookId = ?", new Object[] { branchId, bookId },this); if (bc != null) { BookCopies bookCopy = bc.get(0); return bookCopy.getNoOfCopies(); } return null; } @Override public List<BookCopies> extractData(ResultSet rs) throws SQLException { List<BookCopies> bookCopies = new ArrayList<>(); while (rs.next()) { BookCopies bookCopie = new BookCopies(); bookCopie.setBookId(rs.getInt("bookId")); bookCopie.setBranchId(rs.getInt("branchId")); bookCopie.setNoOfCopies(rs.getInt("noOfCopies")); bookCopies.add(bookCopie); } return bookCopies; } public void checkOutBookCopies(BookCopies bookCopies) throws SQLException, ClassNotFoundException { jdbcTemplate.update("UPDATE tbl_book_copies SET noOfCopies = noOfCopies-1 WHERE bookId = ? and branchId = ?", new Object[] { bookCopies.getBookId(), bookCopies.getBranchId() }); } public void returnBookCopies(BookCopies bookCopies) throws SQLException, ClassNotFoundException { jdbcTemplate.update("UPDATE tbl_book_copies SET noOfCopies = noOfCopies+1 WHERE bookId = ? and branchId = ?", new Object[] { bookCopies.getBookId(), bookCopies.getBranchId() }); } }
package fine.project.oauth; public class Credentials { private String aplicationID; private String aplicationSecret; private String redirectUrl; private String scope; private String resourceRequestURL; public Credentials(String aplicationID, String aplicationSecret, String redirectUrl, String resourceRequestURL) { this.aplicationID = aplicationID; this.aplicationSecret = aplicationSecret; this.redirectUrl = redirectUrl; this.resourceRequestURL = resourceRequestURL; } public Credentials(String aplicationID, String aplicationSecret, String redirectUrl, String resourceRequestURL, String scope) { this.aplicationID = aplicationID; this.aplicationSecret = aplicationSecret; this.redirectUrl = redirectUrl; this.scope = scope; this.resourceRequestURL = resourceRequestURL; } public String getAplicationID() { return aplicationID; } public String getAplicationSecret() { return aplicationSecret; } public String getRedirectUrl() { return redirectUrl; } public String getResourceRequestURL() { return resourceRequestURL; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } }
/* * work_wx * wuhen 2020/2/4. * Copyright (c) 2020 jianfengwuhen@126.com All Rights Reserved. */ package com.work.wx.controller.modle.subChatItem; public class ChatModeRecordItem { private String type; // 每条聊天记录的具体消息类型:ChatRecordText/ ChatRecordFile/ ChatRecordImage/ ChatRecordVideo/ ChatRecordLink/ // ChatRecordLocation …. private Long msgtime; // 消息时间,utc时间,ms单位。 private String content; // 消息内容。Json串,内容为对应类型的json。String类型 private Boolean from_chatroom; // 是否来自群会话。Bool类型 public String getType() { return type; } public void setType(String type) { this.type = type; } public Long getMsgtime() { return msgtime; } public void setMsgtime(Long msgtime) { this.msgtime = msgtime; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Boolean getFrom_chatroom() { return from_chatroom; } public void setFrom_chatroom(Boolean from_chatroom) { this.from_chatroom = from_chatroom; } @Override public String toString() { return "ChatItem{" + "type='" + type + '\'' + ", msgtime=" + msgtime + ", content='" + content + '\'' + ", from_chatroom=" + from_chatroom + '}'; } }
package GUI; import file_operations.Record; import object_type.Animal; import object_type.Point; import java.awt.event.*; import java.awt.*; import java.util.*; import javax.swing.*; import java.io.*; import java.net.*; import java.applet.*; /* 计时功能 */ public class HandleMouse extends JPanel implements MouseListener, ActionListener { object_type.Point[] point; ArrayList<Integer> step; int spendTime = 0; javax.swing.Timer recordTime; boolean countTime = false; JTextField showTime; File musicFile; AudioClip clip; File gradeFile; Record record; HandleMouse() { try { step = new ArrayList<Integer>(); recordTime = new javax.swing.Timer(1000, this); record = new Record(); musicFile = new File("resource/qwe.wav");//todo 音乐文件在这里 URI uri = musicFile.toURI(); URL url = uri.toURL(); showTime = new JTextField(26); showTime.setEditable(false); showTime.setHorizontalAlignment(JTextField.CENTER); showTime.setFont(new Font("UTF8", Font.BOLD, 18)); this.add(new JLabel("点击动物图片开始游戏并计时:", JLabel.CENTER)); this.add(showTime); this.setBackground(Color.pink); clip = Applet.newAudioClip(url); } catch (Exception e) { e.printStackTrace(); } } public void setPoint(object_type.Point[] point) { this.point = point; } public void initStep() { this.step.clear(); } public void initSpendTime() { this.spendTime = 0; this.showTime.setText(null); this.recordTime.stop(); } public ArrayList<Integer> getStep() { return step; } public void setCountTime(boolean b) { this.countTime = b; } public void mousePressed(MouseEvent e) { if (countTime) { this.recordTime.start(); this.clip.play(); } else { this.showTime.setText("计时取消"); } Animal animal; animal = (Animal) e.getSource(); int w = animal.getBounds().width; int h = animal.getBounds().height; int m = -1; Point startPoint = animal.getAtPoint(); for (int i = 0; i < point.length; i++) { if (point[i].equals(startPoint)) { m = i; break; } } if (animal.getIsLeft() && m <= point.length - 2) { if (!point[m + 1].isHaveAnimal()) { animal.setLocation(point[m + 1].getX() - w / 2, point[m + 1].getY() - h); animal.setAtPoint(point[m + 1]); point[m + 1].setThisAnimal(animal); point[m + 1].setIsHaveAnimal(true); startPoint.setIsHaveAnimal(false); step.add(m); step.add(m + 1); } else if (m + 1 <= point.length - 2 && point[m + 2].isHaveAnimal() == false) { animal.setLocation(point[m + 2].getX() - w / 2, point[m + 2].getY() - h); animal.setAtPoint(point[m + 2]); point[m + 2].setThisAnimal(animal); point[m + 2].setIsHaveAnimal(true); startPoint.setIsHaveAnimal(false); step.add(m); step.add(m + 2); } } else if (!animal.getIsLeft() && m >= 1) { if (!point[m - 1].isHaveAnimal()) { animal.setLocation(point[m - 1].getX() - w / 2, point[m - 1].getY() - h); animal.setAtPoint(point[m - 1]); point[m - 1].setThisAnimal(animal); point[m - 1].setIsHaveAnimal(true); startPoint.setIsHaveAnimal(false); step.add(m); step.add(m - 1); } else if (m - 1 >= 1 && !point[m - 2].isHaveAnimal()) { animal.setLocation(point[m - 2].getX() - w / 2, point[m - 2].getY() - h); animal.setAtPoint(point[m - 2]); point[m - 2].setThisAnimal(animal); point[m - 2].setIsHaveAnimal(true); startPoint.setIsHaveAnimal(false); step.add(m); step.add(m - 2); } } } public void actionPerformed(ActionEvent e) { spendTime++; showTime.setText("您的用时:" + spendTime + "秒"); } public boolean isSuccess() { boolean boo = true; int i = 0; for (i = 0; i < point.length / 2; i++) { if (point[i].getThisAnimal().getIsLeft() || !point[i + point.length / 2 + 1].getThisAnimal().getIsLeft()) { boo = false; break; } } return boo; } public void mouseReleased(MouseEvent e) { if (isSuccess()) { recordTime.stop(); record.setTime(spendTime); record.setGradeFile(gradeFile); record.setVisible(true); } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } }
package configuration; import com.alibaba.nacos.api.exception.NacosException; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 主备选举测试逻辑 * @author plusman * @since 2021/4/12 2:52 PM */ @Slf4j public class LeaderFollowerElectionConfiguration { public static void main(String[] args) { CompetitorConfiguration competitor1 = new CompetitorConfiguration("C1"); CompetitorConfiguration competitor2 = new CompetitorConfiguration("c2"); ExecutorService executorService = Executors.newFixedThreadPool(10); executorService.execute(() -> { try { competitor1.run(); } catch (NacosException | InterruptedException e) { e.printStackTrace(); } }); executorService.execute(() -> { try { competitor2.run(); } catch (NacosException | InterruptedException e) { e.printStackTrace(); } }); } }
/* * 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 CSC110_2016; /** * * @author JanithWanni */ public class SavingsAccount extends BankAccount{ private double annualInterestRate; public SavingsAccount(double annualInterestRate, String accountNumber, double balance, String nic) { super(accountNumber, balance, nic); this.annualInterestRate = annualInterestRate; } @Override public String toString() { return super.toString()+"SavingsAccount{" + "annualInterestRate=" + annualInterestRate + '}'; } }
import org.junit.Test; import static org.junit.Assert.assertEquals; import java.util.*; public class LoopoverTest { private Looper l; @Test public void FixedTest() { l=new Looper(); Loopover L; l.up(0); l.left(0); l.down(0); l.right(0); L=l.loopdyDoop(); List<String> a=L.solve(); System.out.println("Testing for:"); System.out.println(l.boardString()); assertEquals(true, l.valid(a, l.newBoard())); } @Test public void RandomTests() { Looper l=new Looper(); Loopover L; List<String> a; for(int i=0; i<100; i++) { l.scramble(); L=l.loopdyDoop(); a=L.solve(); System.out.println("Testing for:"); System.out.println(l.boardString()); assertEquals(true, l.valid(a, l.newBoard())); } } }
package com.example.demo.persistencia; import com.example.demo.dominio.Tabuleiro; import java.sql.*; import java.util.ArrayList; public class TabuleiroDAO { private final Conexao conex; private final String SELECTALL = "SELECT * FROM public.tabuleiro;"; private final String SELECT = "SELECT * FROM public.tabuleiro WHERE id = ?;"; private final String INSERT = "INSERT INTO public.tabuleiro(\n" + "\tnome, valor, quantidade, descricao, classificacao)\n" + "\tVALUES (?, ?, ?, ?, ?);"; private final String CREATE = "CREATE SEQUENCE public.tabuleiro_id_seq\n" + " INCREMENT 1\n" + " START 1\n" + " MINVALUE 1\n" + " MAXVALUE 32767\n" + " CACHE 1;" + "CREATE TABLE public.tabuleiro\n" + "(\n" + " id smallint NOT NULL DEFAULT nextval('tabuleiro_id_seq'::regclass),\n" + " nome text COLLATE pg_catalog.\"default\",\n" + " valor integer,\n" + " quantidade integer,\n" + " descricao text COLLATE pg_catalog.\"default\",\n" + " classificacao text COLLATE pg_catalog.\"default\",\n" + " CONSTRAINT tabuleiro_pkey PRIMARY KEY (id)\n" + ");"; private final String EXISTS = "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'tabuleiro');"; public TabuleiroDAO(){ conex = new Conexao(System.getenv("DATABASE_HOST"), System.getenv("DATABASE_PORT"), System.getenv("DATABASE_NAME"), System.getenv("DATABASE_USERNAME"), System.getenv("DATABASE_PASSWORD")); } public boolean exists(){ boolean existe = false; try{ conex.Conectar(); Statement st = conex.getCon().createStatement(); ResultSet rs = st.executeQuery(EXISTS); if(rs.next()){ existe = rs.getBoolean("exists"); } conex.Desconectar(); } catch(SQLException e){ System.out.println("Erro na criação da tabela: " + e.getMessage()); } return existe; } public Tabuleiro select(int id){ Tabuleiro t = null; try{ conex.Conectar(); PreparedStatement st = conex.getCon().prepareStatement(SELECT); st.setInt(1, id); ResultSet rs = st.executeQuery(); if(rs.next()){ t = new Tabuleiro(rs.getInt("id"), rs.getString("nome"), rs.getInt("valor"), rs.getInt("quantidade"), rs.getString("descricao"), rs.getString("classificacao")); } conex.Desconectar(); } catch (SQLException e){ System.out.println("Erro na busca:" + e.getMessage()); } return t; } public ArrayList<Tabuleiro> selectALL(){ ArrayList<Tabuleiro> tabuleiros = new ArrayList<>(); try{ conex.Conectar(); Statement st = conex.getCon().createStatement(); ResultSet rs = st.executeQuery(SELECTALL); while(rs.next()){ tabuleiros.add(new Tabuleiro(rs.getInt("id"), rs.getString("nome"), rs.getInt("valor"), rs.getInt("quantidade"), rs.getString("descricao"), rs.getString("classificacao"))); } } catch(SQLException e){ System.out.println("Erro no relatorio:" + e.getMessage()); } return tabuleiros; } public void create(){ try{ conex.Conectar(); Statement st = conex.getCon().createStatement(); st.execute(CREATE); conex.Desconectar(); } catch (SQLException e){ System.out.println("Erro na criação da tabela" + e.getMessage()); } } public void insert(Tabuleiro t){ try{ conex.Conectar(); PreparedStatement ps = conex.getCon().prepareStatement(INSERT); //ps.setInt(1, p.getId()); ps.setString(1, t.getNome()); ps.setInt(2, t.getValor()); ps.setInt(3, t.getQuantidade()); ps.setString(4, t.getDescricao()); ps.setString(5, t.getClassificacao()); ps.execute(); } catch (SQLException e){ System.out.println(""); } } }
package com.zantong.mobilecttx.presenter; import com.zantong.mobilecttx.api.OnLoadServiceBackUI; import com.zantong.mobilecttx.base.BasePresenter; import com.zantong.mobilecttx.base.MessageFormat; import com.zantong.mobilecttx.base.interf.IBaseView; import com.zantong.mobilecttx.common.Config; import com.zantong.mobilecttx.common.PublicData; import com.zantong.mobilecttx.model.QueryHistoryModelImp; import com.zantong.mobilecttx.presenter.presenterinterface.SimplePresenter; import cn.qqtheme.framework.util.ToastUtils; import com.zantong.mobilecttx.utils.rsa.RSAUtils; import com.zantong.mobilecttx.weizhang.bean.AddVehicleBean; import com.zantong.mobilecttx.weizhang.fragment.QueryHistory; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import cn.qqtheme.framework.util.log.LogUtils; /** * Created by 王海洋 on 16/6/1. */ public class QueryHistoryPresenter extends BasePresenter<IBaseView> implements SimplePresenter, OnLoadServiceBackUI { QueryHistory mQueryHistory; QueryHistoryModelImp mQueryHistoryModelImp; private String msg = ""; private HashMap<String, Object> oMap = new HashMap<>(); private JSONObject masp = null; public QueryHistoryPresenter(QueryHistory mQueryHistory) { this.mQueryHistory = mQueryHistory; mQueryHistoryModelImp = new QueryHistoryModelImp(); } @Override public void loadView(int index) { mQueryHistory.showProgress(); switch (index){ case 1: MessageFormat.getInstance().setTransServiceCode("cip.cfc.v002.01"); masp = new JSONObject() ; // try { masp.put("token", RSAUtils.strByEncryption(PublicData.getInstance().imei, true)); masp.put("carnumtype", PublicData.getInstance().mHashMap.get("carnumtype")); masp.put("carnum", RSAUtils.strByEncryption(PublicData.getInstance().mHashMap.get("carnum").toString(),true)); masp.put("enginenum", RSAUtils.strByEncryption(PublicData.getInstance().mHashMap.get("enginenum").toString(),true)); LogUtils.i(masp.get("carnumtype").toString()+ masp.get("carnum")+masp.get("enginenum")); // masp.put("usrid","000160180 6199 2851"); MessageFormat.getInstance().setMessageJSONObject(masp); } catch (JSONException e) { e.printStackTrace(); } break; } msg = MessageFormat.getInstance().getMessageFormat(); // Log.e("why",msg); mQueryHistoryModelImp.loadUpdate(this, msg, index); } @Override public void onSuccess(Object clazz, int index) { mQueryHistory.hideProgress(); switch (index){ case 1: AddVehicleBean mAddVehicleBean = (AddVehicleBean) clazz; if(PublicData.getInstance().success.equals(mAddVehicleBean.getSYS_HEAD().getReturnCode())){ mQueryHistory.updateView(clazz, index); }else{ ToastUtils.showShort(mQueryHistory.getContext(), mAddVehicleBean.getSYS_HEAD().getReturnMessage()); } break; } } @Override public void onFailed() { mQueryHistory.hideProgress(); ToastUtils.showShort(mQueryHistory.getContext(), Config.getErrMsg("1")); } }
/** * */ package com.aof.component.prm.Bill; import java.util.Calendar; import java.util.Iterator; import java.util.List; import net.sf.hibernate.Transaction; import net.sf.hibernate.HibernateException; import net.sf.hibernate.Query; import com.aof.component.BaseServices; import com.aof.component.crm.customer.CustomerProfile; import com.aof.component.domain.party.UserLogin; import com.aof.component.prm.expense.ProjectCostMaster; import com.aof.component.prm.project.CurrencyType; import com.aof.core.persistence.jdbc.*; import com.aof.core.persistence.util.EntityUtil; import com.aof.core.persistence.*; /** * @author CN01511 * */ public class ReceiptService extends BaseServices{ public CurrencyType getCurrency(String currencyString) { session = this.getSession(); try{ String statement = "from CurrencyType as ct where ct.currId = ?"; Query q = session.createQuery(statement); q.setString(0,currencyString); List list = q.list(); Iterator i = list.iterator(); if(i.hasNext()){ session.flush(); return (CurrencyType)i.next(); } session.flush(); }catch(HibernateException e){ e.printStackTrace(); } return new CurrencyType(); } public UserLogin getCreateUser(String createUserString) { session = this.getSession(); try{ String statement = "from UserLogin as ul where ul.userLoginId = ?"; Query q = session.createQuery(statement); q.setString(0,createUserString); List list = q.list(); Iterator i = list.iterator(); if(i.hasNext()){ session.flush(); return (UserLogin)i.next(); } session.flush(); }catch(HibernateException e){ e.printStackTrace(); } return new UserLogin(); } public CustomerProfile getCustomer(String customerIdString) { session = this.getSession(); try{ String statement = "from CustomerProfile as cp where cp.partyId = ?"; Query q = session.createQuery(statement); q.setString(0,customerIdString); List list = q.list(); Iterator i = list.iterator(); if(i.hasNext()){ session.flush(); return (CustomerProfile)i.next(); } session.flush(); }catch(HibernateException e){ e.printStackTrace(); } return new CustomerProfile(); } public boolean checkReceiptNo(String receiptNo) { session = this.getSession(); try{ String statement = "from ProjectReceiptMaster as prm where prm.receiptNo = ?"; Query q = session.createQuery(statement); q.setString(0,receiptNo); List list = q.list(); Iterator i = list.iterator(); if(i.hasNext()){ session.flush(); return true; } session.flush(); }catch(HibernateException e){ e.printStackTrace(); } return false; } public void insert(ProjectReceiptMaster prm) { session = this.getSession(); Transaction transaction = null; try{ //transaction = session.beginTransaction(); session.save(prm); session.flush(); } catch (HibernateException e) { try { // TODO Auto-generated catch block transaction.rollback(); } catch (HibernateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } finally { try { //transaction.commit(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } public void update(ProjectReceiptMaster prm) { session = this.getSession(); Transaction transaction = null; try{ //transaction = session.beginTransaction(); session.saveOrUpdate(prm); session.flush(); } catch (HibernateException e) { try { // TODO Auto-generated catch block //transaction.rollback(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } finally { try { //transaction.commit(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } public void delete(ProjectReceiptMaster prm) { // TODO Auto-generated method stub session = this.getSession(); Transaction transaction = null; try{ transaction = session.beginTransaction(); ProjectReceiptMaster receipt = (ProjectReceiptMaster)session.load(ProjectReceiptMaster.class,prm.getReceiptNo()); session.delete(receipt); session.flush(); } catch (HibernateException e) { try { // TODO Auto-generated catch block transaction.rollback(); } catch (HibernateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } finally { try { transaction.commit(); } catch (HibernateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } public ProjectReceiptMaster getView(String dataId) { // TODO Auto-generated method stub session = this.getSession(); Transaction transaction = null; try{ transaction = session.beginTransaction(); if(dataId != null && !dataId.trim().equals("")){ ProjectReceiptMaster prm = (ProjectReceiptMaster)session.load(ProjectReceiptMaster.class,dataId); if(prm != null) return prm; } } catch (HibernateException e) { try { // TODO Auto-generated catch block transaction.rollback(); } catch (HibernateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } finally { try { transaction.commit(); } catch (HibernateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return null; } public Double getRemainAmount(ProjectReceiptMaster prm){ if(prm == null || prm.getReceiptAmount() == null) return new Double(0.0); double amount = prm.getReceiptAmount().doubleValue() * prm.getExchangeRate().doubleValue(); Iterator i = prm.getInvoices().iterator(); while(i.hasNext()){ ProjectReceipt pr = (ProjectReceipt)i.next(); double settledAmount = pr.getReceiveAmount().doubleValue(); //* pr.getCurrencyRate().doubleValue(); amount -= settledAmount; } if(amount < 1 && amount > -1) amount = 0; return new Double(amount); } /* public Double getRemainAmount(ProjectReceiptMaster prm){ SQLExecutor sqlExec = new SQLExecutor( Persistencer.getSQLExecutorConnection(EntityUtil.getConnectionByName("jdbc/aofdb"))); try{ StringBuffer sql = new StringBuffer(); sql.append(" select sum(receive_amount)"); sql.append(" from proj_receipt"); sql.append(" where receipt_no = '"+ prm.getReceiptNo()+"'"); sql.append(" group by receipt_no"); SQLResults result = sqlExec.runQueryCloseCon(sql.toString()); double settleAmount = (result.getRowCount()==0) ? 0.0 : result.getDouble(0,0); double totalAmount = prm.getReceiptAmount()==null?0.0:prm.getReceiptAmount().doubleValue(); return new Double(totalAmount-settleAmount); }catch(Exception e){ //e.printStackTrace(); if(sqlExec.getConnection() != null) sqlExec.closeConnection(); return new Double(0.0); } } */ public List getSettlement(ProjectReceiptMaster prm) { session = this.getSession(); String statement = "from ProjectReceipt as pr where pr.receiptNo = '"+prm.getReceiptNo()+"'"; List list = null; try{ Query q = session.createQuery(statement); list = q.list(); session.flush(); }catch(Exception e){ e.printStackTrace(); } return list; } public String generateNo() { // TODO Auto-generated method stub session = this.getSession(); Calendar calendar = Calendar.getInstance(); StringBuffer sb = new StringBuffer(); sb.append("R"); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH)+1; int day = calendar.get(Calendar.DATE); sb.append(year); sb.append(this.fillPreZero(month,2)); sb.append(this.fillPreZero(day,2)); String codePrefix = sb.toString(); SQLExecutor sqlExec = new SQLExecutor( Persistencer.getSQLExecutorConnection(EntityUtil.getConnectionByName("jdbc/aofdb"))); try { String statement = "select max(p.receipt_no) from proj_receipt_mstr as p where p.receipt_no like '"+codePrefix+"%'"; SQLResults result = sqlExec.runQueryCloseCon(statement); int count = 0; String GetResult = (String)result.getString(0,0); if (GetResult != null) count = (new Integer(GetResult.substring(codePrefix.length()))).intValue(); sb = new StringBuffer(); sb.append(codePrefix); sb.append(fillPreZero(count+1,3)); return sb.toString(); } catch (Exception e) { // TODO Auto-generated catch block //e.printStackTrace(); if(sqlExec.getConnection() != null) sqlExec.closeConnection(); return null; } } private String fillPreZero(int no,int len) { String s=String.valueOf(no); StringBuffer sb=new StringBuffer(); for(int i=0;i<len-s.length();i++) { sb.append('0'); } sb.append(s); return sb.toString(); } }
package xtrus.user.apps.site.samsung.parser; import java.util.StringTokenizer; public class PDFMSGParser extends SamsungParser { public PDFMSGParser(String pdfMessageNumber) throws Exception { StringTokenizer tok = new StringTokenizer(pdfMessageNumber, "_"); if (tok.hasMoreTokens()) { this.messageNumber = tok.nextToken(); } else { throw new Exception("PDF Message Number is not correct. ("+pdfMessageNumber+")"); } if (tok.hasMoreTokens()) { this.senderTpId = tok.nextToken(); } else { throw new Exception("PDF Message Number is not correct. ("+pdfMessageNumber+")"); } if (tok.hasMoreTokens()) { this.receiverTpId = tok.nextToken(); } else { throw new Exception("PDF Message Number is not correct. ("+pdfMessageNumber+")"); } if (tok.hasMoreTokens()) { this.documentNumber = tok.nextToken(); } else { throw new Exception("PDF Message Number is not correct. ("+pdfMessageNumber+")"); } this.documentName = "BLPDF"; this.documentVersion = "1.0"; this.conversationId = pdfMessageNumber; } }
package repositories; import models.SinhVien; import java.util.ArrayList; import java.util.List; public class SinhVienRepo { private List<SinhVien> sinhVienList = new ArrayList<>(); /** * Add a sinhVien object * @param sinhVien */ public void add(SinhVien sinhVien) { this.sinhVienList.add(sinhVien); } /** * Edit a exist sinhVien * Step 1: remove sinhVien at position which stored * Step 2: add sinhVien at position which removed * @param sinhVien * @param position */ public void edit(SinhVien sinhVien, int position) { this.sinhVienList.remove(position); this.sinhVienList.add(position, sinhVien); } /** * Delete a sinhVien * @param position */ public void delete(int position) { this.sinhVienList.remove(position); } /** * Get a sinhVien by maSinhVien * @param maSinhVien * @return a sinhVien which has maSinhVien map for parameter maSinhVien */ public SinhVien getByMaSinhVien(int maSinhVien) { return this.sinhVienList.stream().filter(item -> item.getMaSinhVien() == maSinhVien).findFirst().orElseThrow(); } /** * Get all sinhVien * @return list sinhVien */ public List<SinhVien> getAll() { return this.sinhVienList; } /** * Find a position's sinhVien is stored in array * @param maSinhVien maSinhVien * @return position is stored in array */ public int getPosition(int maSinhVien) { for (int i = 0; i < this.sinhVienList.size(); i++) { SinhVien sinhVien = this.sinhVienList.get(i); if (sinhVien.getMaSinhVien() == maSinhVien) { return i; } } return -1; // nếu không tìm thấy sinh viên nào thì trả về -1 } }
package co.company.spring.emp.service; import java.util.List; import java.util.Map; import co.company.spring.dao.Emp; import co.company.spring.dao.EmpSearch; public interface EmpService { public List<Emp> getEmpList(EmpSearch emp); //전체조회 public List<Map<String, Object>> getStatDept(); public Emp getEmp(Emp emp); //단건조회 public int insertEmp(Emp emp); //한건 삽입 public int updateEmp(Emp emp); //업데이트 public int deleteEmp(Emp emp); //단건삭제 }
package com.aisino.invoice.xtjk.po; import java.util.Date; /** * @ClassName: FwkpSbzt * @Description: * @Copyright 2017 航天信息股份有限公司-版权所有 */ public class FwkpSbzt extends FwkpQyxx{ private float lxljzpxe;//最大持票量 private String fpzl; private String zzlxsjstr;//最早离线时间字符串 private Date zzlxsj;//最早离线时间date private Integer dzfpxe; public Integer getDzfpxe() { return dzfpxe; } public void setDzfpxe(Integer dzfpxe) { this.dzfpxe = dzfpxe; } public float getLxljzpxe() { return lxljzpxe; } public void setLxljzpxe(float lxljzpxe) { this.lxljzpxe = lxljzpxe; } public String getFpzl() { return fpzl; } public void setFpzl(String fpzl) { this.fpzl = fpzl; } public String getZzlxsjstr() { return zzlxsjstr; } public void setZzlxsjstr(String zzlxsjstr) { this.zzlxsjstr = zzlxsjstr; } public Date getZzlxsj() { return zzlxsj; } public void setZzlxsj(Date zzlxsj) { this.zzlxsj = zzlxsj; } }
import java.io.*; import java.util.*; /** * Console UI class that interacts with and displays information * about the Meerkat Lane. * * @author Kody Dangtongdee * @version 2/24/2015 */ public class MeerkatLane { /** * Scaner to read user input */ private Scanner in; /** * Writer to display console output */ private PrintWriter out; /** * Constructor for a MeerkatLane * @param rdr the reader to be used for the user's input * @param wrt the writer to be used to display the * console output */ public MeerkatLane(Reader rdr, Writer wrt) { in = new Scanner(rdr); out = new PrintWriter(wrt); } /** * Method that handles most of the IO, and makes calls * to method to perform tasks based on the user input. */ public void run() { String command = ""; Lane lane = new Lane(); boolean quit = false; int commandCount = 0; out.println("Welcome to Meerkat Lane."); out.println(); //Perform operations based on user input, while the user //has not entered "Quit" do { out.println("Load, Add, Member, Remove, List, Map, Lookup, Clear, Quit"); out.println("Your Command? "); command = in.next().toUpperCase(); //switch statement to handle the user input switch(command) { //load a file of Meerkats case "LOAD": //Try to load the file the user entered try { lane.loadFile(in.next().trim()); } catch(FileNotFoundException e) { System.out.println("Error: File not found"); } break; //display the lane mappings, in their compressed form case "MAP": List<String> map = lane.getCompressed(); //for every location in the compressed map for (String line : map) { //print the map to the console out.println(line); } break; //add a meerkat to the lane case "ADD": addMeerkat(lane); break; //add a meerkat to another's family case "MEMBER": String name1 = in.next().trim(); String name2 = in.next().trim(); //if the meerkat has a valid name, add it to the family if (Meerkat.validName(name2)) { lane.addToFamily(name1, name2); out.println("OK"); } else { out.println("Error: " + name2 + " is not a valid name."); } break; //remove a meerkat case "REMOVE": String removeName = in.next().trim(); //If the lane does not contain the meerkat, if (!lane.contains(removeName)) { //print this error message out.println("Error: attempt to remove " + removeName + " failed."); } else { //otherwise, remove the meerkat lane.remove(removeName); out.println("OK"); } break; //display information about a meerkat's family case "LOOKUP": String lookupName = ""; //try to find the meerkat in the lane. try { lookupName = in.nextLine().trim(); //If the meerkat doesnt exist if (!lane.contains(lookupName)) { //print this error message out.println("Error: lookup couldn't find " + lookupName); break; } else { //othewerise lookup the name out.println(lane.lookup(lookupName) + " "); } } catch(NullPointerException e) { out.println("Error: lookup couldn't find " + lookupName); } break; //list all meerkats in the lane case "LIST": //get alphabetical list on members List<String> list = lane.listMembers(); //for every meerkat in the lane, print their information for (int index = 0; index < list.size(); index++) { out.println(list.get(index)); } break; //empty the lane case "CLEAR": lane.clear(); lane = new Lane(); out.println("OK"); break; //end the UI case "QUIT": quit = true; break; default: //out.println("Error: invalid command."); break; } out.println(); }while(!quit && in.hasNext()); in.close(); out.close(); } /** * Helper method to add a meerkat to the lane. * @param lane the Lane of meerkats and families * @return boolean true if the meerkat was added, * otherwise false */ private boolean addMeerkat(Lane lane) { String name = in.next(); int end = 0; int start = 0; //If the meerkat's name is invalid if (!Meerkat.validName(name)) { out.println("Error: " + name + " is not a valid name."); in.nextLine(); return false; } //Try to read the next input as an integer //catches exception thrown if the input was not an integer try { start = (Integer)in.nextInt(); end = (Integer)in.nextInt(); in.nextLine(); } catch(InputMismatchException e) { out.println("Error: Missing required parameter."); return false; } //Check if the meerkat already exists if (lane.contains(name)) { out.println("Error: " + name + " already exists."); return false; } lane.add(name, start, end); out.println("OK"); return true; } /** * Main method, gets called by the user to launch the application * @param args the command line arguments, file input and file output */ public static void main(String[] args) { FileReader reader; PrintWriter writer; //try to use/read the input file, //catch the IO exceptin if something goes wrong try { File input = new File(args[0]); File output = new File(args[1]); reader = new FileReader(input); writer = new PrintWriter(output); MeerkatLane lane = new MeerkatLane(reader, writer); lane.run(); } catch(IOException e) { System.out.println("Error: No file Found"); } } }
package com.corycharlton.bittrexapi.request; import android.support.annotation.NonNull; import com.corycharlton.bittrexapi.internal.constants.Url; import com.corycharlton.bittrexapi.response.GetOrderBookResponse; import static com.corycharlton.bittrexapi.internal.util.Ensure.isNotNullOrWhitespace; /** * Used to retrieve the latest trades that have occurred for a specific market. */ public class GetOrderBookRequest extends Request<GetOrderBookResponse> { /** * Used to retrieve the order book for a given market. * @param market A string literal for the market (ex: BTC-LTC) */ // TODO: Expose the 'type' parameter? public GetOrderBookRequest(@NonNull String market) { super(Url.GETORDERBOOK, false, GetOrderBookResponse.class); isNotNullOrWhitespace("market", market); addParameter("market", market); addParameter("type", "both"); } }
package com.rednovo.ace.widget.live; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.view.WindowManager; import android.widget.TextView; import com.facebook.drawee.generic.GenericDraweeHierarchy; import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.imagepipeline.request.ImageRequest; import com.rednovo.ace.R; import com.rednovo.ace.common.Globle; import com.rednovo.ace.common.LiveInfoUtils; import com.rednovo.ace.core.session.SendUtils; import com.rednovo.ace.data.UserInfoUtils; import com.rednovo.ace.net.api.ReqRelationApi; import com.rednovo.ace.net.api.ReqUserApi; import com.rednovo.ace.net.parser.BaseResult; import com.rednovo.ace.net.parser.UserInfoResult; import com.rednovo.ace.net.request.RequestCallback; import com.rednovo.ace.ui.activity.UserZoneActivity; import com.rednovo.libs.BaseApplication; import com.rednovo.libs.common.ShowUtils; import com.rednovo.libs.common.StringUtils; import com.rednovo.libs.net.fresco.FrescoEngine; import com.rednovo.libs.widget.dialog.BaseDialog; /** * 个人简单信息弹框 */ public class SimpleUserInfoDialog extends BaseDialog implements View.OnClickListener { // private static SimpleUserInfoDialog mInstance; private SimpleDraweeView ivAnchor; private TextView tvReport, tvHome, tvSubscribe, tvName, tvSignature, tvFans, tvPosition, tvID; private Context mContext; private UserInfoResult.UserEntity currentUser; private boolean isSubscribe; private int fansCnt; private OnNoLoginListener listener; public void setIsAnchor(boolean isAnchor) { this.isAnchor = isAnchor; if (isAnchor) { tvReport.setText(getContext().getString(R.string.tv_silent)); tvHome.setVisibility(View.GONE); } else { tvHome.setVisibility(View.VISIBLE); } } private boolean isAnchor; /*public static SimpleUserInfoDialog getSimpleUserInfoDialog(Context context, int resId) { if (mInstance == null) { mInstance = new SimpleUserInfoDialog(context, resId); } return mInstance; }*/ public SimpleUserInfoDialog(Context context, int resId) { super(context, R.layout.dialog_simple_userinfo, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, Gravity.CENTER); this.getWindow().setWindowAnimations(R.style.dialogCenterWindowAnim); ivAnchor = (SimpleDraweeView) findViewById(R.id.icon_anchor); tvReport = (TextView) findViewById(R.id.tv_report); tvHome = (TextView) findViewById(R.id.tv_home); tvSubscribe = (TextView) findViewById(R.id.tv_subscribe); tvName = (TextView) findViewById(R.id.tv_name); tvFans = (TextView) findViewById(R.id.tv_fans); tvID = (TextView) findViewById(R.id.tv_id); tvPosition = (TextView) findViewById(R.id.tv_position); tvSignature = (TextView) findViewById(R.id.tv_signature); tvReport.setOnClickListener(this); tvHome.setOnClickListener(this); tvSubscribe.setOnClickListener(this); // mInstance = this; mContext = context; } @Override public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.tv_report: if(!UserInfoUtils.isAlreadyLogin()){ if(listener != null) listener.loginNotice(); }else if(currentUser != null){ if (isAnchor) { // SendUtils.kickOut(UserInfoUtils.getUserInfo().getUserId(), currentUser.getUserId(), UserInfoUtils.getUserInfo().getUserId()); // SendUtils.shutup(UserInfoUtils.getUserInfo().getUserId(), currentUser.getUserId(), UserInfoUtils.getUserInfo().getUserId()); shutup(currentUser.getUserId()); } else { report(currentUser.getUserId()); } } break; case R.id.tv_home: if(!UserInfoUtils.isAlreadyLogin()){ if(listener != null) listener.loginNotice(); }else if (currentUser != null) { Intent intent = new Intent(mContext, UserZoneActivity.class); intent.putExtra(UserZoneActivity.USER, currentUser); intent.putExtra(Globle.KEY_SHOW_LIVEING_BTN, false); mContext.startActivity(intent); this.dismiss(); } break; case R.id.tv_subscribe: if(!UserInfoUtils.isAlreadyLogin()){ if(listener != null) listener.loginNotice(); }else if (currentUser != null) { if (isSubscribe) { //已订阅 cancelSub(currentUser.getUserId()); tvSubscribe.setText(mContext.getString(R.string.hall_subscribe_text)); tvSubscribe.setTextColor(mContext.getResources().getColor(R.color.color_19191a)); tvSubscribe.setBackgroundResource(R.drawable.tv_subscribe_bg); isSubscribe = false; fansCnt--; if (fansCnt < 0) fansCnt = 0; tvFans.setText(getContext().getString(R.string.tv_fans, fansCnt + "")); } else { subscribe(currentUser.getUserId()); tvSubscribe.setText(mContext.getString(R.string.subscribe_already)); tvSubscribe.setTextColor(mContext.getResources().getColor(R.color.color_868686)); tvSubscribe.setBackgroundResource(R.drawable.tv_subscribed_bg); isSubscribe = true; fansCnt++; tvFans.setText(getContext().getString(R.string.tv_fans, fansCnt + "")); if(listener != null && LiveInfoUtils.getStartId() != null && LiveInfoUtils.getStartId().equals(currentUser.getUserId())) listener.followNotice(); } } break; default: break; } } /** * 订阅 */ private void subscribe(String userId) { ReqRelationApi.reqSubscibe((Activity) mContext, UserInfoUtils.getUserInfo().getUserId(),userId, new RequestCallback<BaseResult>() { @Override public void onRequestSuccess(BaseResult object) { } @Override public void onRequestFailure(BaseResult error) { } }); } /** * 取消订阅 */ private void cancelSub(String userId) { ReqRelationApi.reqCancelSubscibe((Activity) mContext, UserInfoUtils.getUserInfo().getUserId(),userId, new RequestCallback<BaseResult>() { @Override public void onRequestSuccess(BaseResult object) { } @Override public void onRequestFailure(BaseResult error) { } }); } /** * 禁言 */ private void shutup(String userId) { ReqRelationApi.reqShutup((Activity) mContext, UserInfoUtils.getUserInfo().getUserId(),userId, new RequestCallback<BaseResult>() { @Override public void onRequestSuccess(BaseResult object) { ShowUtils.showToast(mContext.getString(R.string.tv_shutup_success)); } @Override public void onRequestFailure(BaseResult error) { } }); dismiss(); } /** * 举报 */ private void report(String userId) { ReqRelationApi.reqReport((Activity) mContext, UserInfoUtils.getUserInfo().getUserId(),userId, new RequestCallback<BaseResult>() { @Override public void onRequestSuccess(BaseResult object) { ShowUtils.showToast(mContext.getString(R.string.tv_reprot_success)); } @Override public void onRequestFailure(BaseResult error) { } }); dismiss(); } @Override public void dismiss() { super.dismiss(); // mInstance = null; } public void setUserId(String id) { String userId = ""; if (UserInfoUtils.isAlreadyLogin()) { userId = UserInfoUtils.getUserInfo().getUserId(); } tvID.setText(getContext().getString(R.string.ID, id)); ReqUserApi.requestUserInfo((Activity) mContext, id, userId, new RequestCallback<UserInfoResult>() { @Override public void onRequestSuccess(UserInfoResult object) { if (object != null) { setData(object.getUser()); currentUser = object.getUser(); } } @Override public void onRequestFailure(UserInfoResult error) { } }); } private void setData(UserInfoResult.UserEntity user) { if (user != null) { Context cxt = BaseApplication.getApplication().getApplicationContext(); ((GenericDraweeHierarchy) ivAnchor.getHierarchy()).setPlaceholderImage(R.drawable.head_online); ((GenericDraweeHierarchy) ivAnchor.getHierarchy()).setFailureImage(cxt.getResources().getDrawable(R.drawable.head_offline)); FrescoEngine.setSimpleDraweeView(ivAnchor, user.getProfile(), ImageRequest.ImageType.SMALL); tvName.setText(user.getNickName() == null ? "" : user.getNickName()); String signature = ""; if (user.getSignature() != null) signature = user.getSignature(); if (signature.length() > 10) { String substring = signature.substring(0, 10); String substring1 = signature.substring(10, signature.length()); signature = substring + "\n" + substring1; } if(StringUtils.isEmpty(signature)) { signature = mContext.getString(R.string.signature_default_text); } tvSignature.setText(signature); String fans = user.getExtendData().getFansCnt(); if (TextUtils.isEmpty(fans)) { fansCnt = 0; } else { fansCnt = Integer.parseInt(fans); } tvFans.setText(getContext().getString(R.string.tv_fans, fansCnt + "")); String position = ""; if(StringUtils.isEmpty(user.getExtendData().getPostion())) { position = mContext.getString(R.string.position_default_text); } else { position = user.getExtendData().getPostion(); } tvPosition.setText(position); if (UserInfoUtils.isAlreadyLogin() && UserInfoUtils.getUserInfo().getUserId().equals(user.getUserId())) { //自己 tvReport.setVisibility(View.GONE); tvSubscribe.setText(mContext.getString(R.string.hall_subscribe_text)); tvSubscribe.setTextColor(mContext.getResources().getColor(R.color.color_19191a)); tvSubscribe.setBackgroundResource(R.drawable.tv_subscribe_bg); tvSubscribe.setEnabled(false); } else { tvReport.setVisibility(View.VISIBLE); tvSubscribe.setEnabled(true); if (user.getExtendData().getRelatoin() != null) { tvSubscribe.setTextColor(mContext.getResources().getColor(user.getExtendData().getRelatoin().equals("1") ? R.color.color_868686 : R.color.color_19191a)); tvSubscribe.setBackgroundResource(user.getExtendData().getRelatoin().equals("1") ? R.drawable.tv_subscribed_bg : R.drawable.tv_subscribe_bg); tvSubscribe.setText(user.getExtendData().getRelatoin().equals("1") ? mContext.getString(R.string.subscribe_already) : mContext.getString(R.string.hall_subscribe_text)); isSubscribe = user.getExtendData().getRelatoin().equals("1"); } else { tvSubscribe.setText(mContext.getString(R.string.hall_subscribe_text)); tvSubscribe.setTextColor(mContext.getResources().getColor(R.color.color_19191a)); tvSubscribe.setBackgroundResource(R.drawable.tv_subscribe_bg); } } } } public interface OnNoLoginListener { /** * 登陆提醒 */ void loginNotice(); /** * 关注监听 */ void followNotice(); } public void setOnNoLoginListener(OnNoLoginListener listener) { this.listener = listener; } }
package Telas; import Controle.ControleLogin; import Supermercado.BD; import Supermercado.Caixa; import Supermercado.Estoque; import Supermercado.Venda; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; public class TelaLogin { private JFrame frame; private JPanel painelLogin; private JPasswordField senha; private JTextField login; public void montarTelaLogin(BD bd, Estoque estoque, Caixa caixa) { frame = new JFrame("Sistema Supermercado Caixa " + caixa.getIdCaixa()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); painelLogin = new JPanel(new GridLayout(3, 2)); frame.add(painelLogin); JLabel labelLogin = new JLabel("Login:"); login = new JTextField(); painelLogin.add(labelLogin); painelLogin.add(login); JLabel labelSenha = new JLabel("Senha:"); senha = new JPasswordField(); painelLogin.add(labelSenha); painelLogin.add(senha); JButton confirma = new JButton("Confirma"); JButton sair = new JButton("Sair"); painelLogin.add(confirma); painelLogin.add(sair); confirma.addActionListener(new ControleLogin(login, senha, bd, estoque, caixa,frame)); confirma.addKeyListener(new ControleLogin(login, senha, bd, estoque, caixa,frame)); sair.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); frame.pack(); frame.setLocationRelativeTo(null); frame.setSize(200, 120); frame.setVisible(true); } }
package ru.job4j.nonblocking; import java.util.Comparator; import java.util.ArrayList; import java.util.Objects; /** * Класс Task реализует сущность "Задача". * * @author Gureyev Ilya (mailto:ill-jah@yandex.ru) * @version 1 * @since 2017-08-04 */ class Task { /** * Счётчик объектов. */ private static int counter = 1; /** * Описание задачи. */ private String description; /** * Идентификатор задачи. */ private int id; /** * Имя задачи. */ private String name; /** * Версия. */ private int version; /** * Список ревизий. */ private ArrayList<String> revisions; /** * Объект блокировки. */ private Object lock; /** * Конструктор. * @param name имя задачи. * @param description описание задачи. */ Task(String name, String description) { this.lock = this; this.id = counter++; this.name = name; this.description = description; this.version = 1; this.revisions = new ArrayList<>(); this.revisions.add(this.toString()); } /** * Копирующий конструктор. * @param task объект задачи. */ Task(Task task) { this.lock = this; this.id = task.id; this.name = task.name; this.description = task.description; this.version = task.version; this.revisions = new ArrayList<>(task.revisions); } /** * Переопределяет метод equals(). * @return true если объекты равны. Иначе false. */ @Override public boolean equals(Object obj) { synchronized (this.lock) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } Task task = (Task) obj; if (!this.name.equals(task.getName()) || !this.description.equals(task.getDescription()) || this.version != task.getVersion()) { return false; } return true; } } /** * Возвращает хэш-код объекта задачи. * @return хэш-код объекта задачи. */ @Override public int hashCode() { synchronized (this.lock) { return Objects.hash(this.name, this.description, this.version); } } /** * Получает описание задачи. * @return описание задачи. */ public String getDescription() { return this.description; } /** * Получает идентификатор задачи. * @return идентификатор задачи. */ public int getId() { return this.id; } /** * Получает имя задачи. * @return имя задачи. */ public String getName() { return this.name; } /** * Устанавливает описание задачи. * @param description описание задачи. */ public void setDescription(String description) { synchronized (this.lock) { if (!this.description.equals(description)) { this.description = description; int version = this.version++; if (version == this.revisions.size()) { this.revisions.add(this.toString()); } else { this.revisions.set(version, this.toString()); } } } } /** * Получает список ревизий задачи. * @return список ревизий задачи. */ public String[] getRevisions() { synchronized (this.lock) { this.revisions.sort(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareTo(o2); } }); return this.revisions.toArray(new String[this.revisions.size()]); } } /** * Получает версию задачи. * @return версию задачи. */ public int getVersion() { synchronized (this.lock) { return this.version; } } /** * Устанавливает имя задачи. * @param name имя задачи. */ public void setName(String name) { synchronized (this.lock) { if (!this.name.equals(name)) { this.name = name; } } } /** * Возвращает строковое представление задачи. * @return строковое представление задачи. */ @Override public String toString() { synchronized (this.lock) { return String.format("Task{description: %s}", this.description); } } }
package kxg.searchaf.url.ralphlauren; import java.util.ArrayList; import java.util.List; public class RalphlaurenPage { public String Category; public String type; // clearance or sale public String url; public RalphlaurenPage() { } public static List<RalphlaurenPage> getBoysInstance() { ArrayList<RalphlaurenPage> urllist = new ArrayList<RalphlaurenPage>(); String type = "sale"; // Boy String category = "Boy 8-20"; String url = "http://www.ralphlauren.com/family/index.jsp?view=399&categoryId=12480297&s=A-StorePrice-POLO&pg=1"; RalphlaurenPage page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Boy 2-7"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=399&pg=1&categoryId=12480295"; page = new RalphlaurenPage(type, category, url); urllist.add(page); // Baby category = "Infant Boy"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=399&pg=1&categoryId=12480336"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Layette Boy"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=399&pg=1&categoryId=12480336"; page = new RalphlaurenPage(type, category, url); urllist.add(page); return urllist; } public static List<RalphlaurenPage> getGirlsInstance() { ArrayList<RalphlaurenPage> urllist = new ArrayList<RalphlaurenPage>(); String type = "sale"; // Baby String category = "Infant Baby Girl"; String url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=399&pg=1&categoryId=12480374"; RalphlaurenPage page = new RalphlaurenPage(type, category, url); urllist.add(page); // KID category = "Girl 2-6x"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=399&pg=1&categoryId=12480298"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Girl 7-16"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=399&pg=1&categoryId=12480299"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Layette Girl"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=399&pg=1&categoryId=12480372"; page = new RalphlaurenPage(type, category, url); urllist.add(page); return urllist; } public static List<RalphlaurenPage> getMenSaleByBrand() { ArrayList<RalphlaurenPage> urllist = new ArrayList<RalphlaurenPage>(); String type = "sale"; String category = "polo ralph lauren"; String url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=399&categoryId=3607674&pg=1"; RalphlaurenPage page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Denim"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=399&categoryId=12253832&pg=1"; page = new RalphlaurenPage(type, category, url); urllist.add(page); return urllist; } public static List<RalphlaurenPage> getWomenSaleByBrand() { ArrayList<RalphlaurenPage> urllist = new ArrayList<RalphlaurenPage>(); String type = "sale"; String category = "lauren"; String url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=399&categoryId=11084907&pg=1"; RalphlaurenPage page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Lauren Petite"; url = "http://www.ralphlauren.com/family/index.jsp?categoryId=10931539&view=399&cp=2943768&ab=ln_nodivision_cs10_laurenpetite(sizes2%9614)"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Lauren Woman"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=399&categoryId=10931540&pg=1"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Denim"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=399&categoryId=12254000&pg=1"; page = new RalphlaurenPage(type, category, url); urllist.add(page); return urllist; } public static List<RalphlaurenPage> getMenSale() { ArrayList<RalphlaurenPage> urllist = new ArrayList<RalphlaurenPage>(); String type = "sale"; String category = "POLO"; String url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=12618507"; RalphlaurenPage page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "POLO"; // page 2 url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=2&categoryId=12618507"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Sport Shirt"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=12618509"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Sport Shirt"; // page 2 url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=2&categoryId=12618509"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Dress Shirt"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=12997217"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Jacket & Outwear"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=4216762"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Sweaters"; // 1766320 url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=1766320"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Sweaters"; // page 2 url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=2&categoryId=1766320"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Sweatshirts & T-shirts"; // 13183412 url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=13183412"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Rugbys"; // 2551783 url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=2551783"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Pants"; // 1766319 url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=1766319"; page = new RalphlaurenPage(type, category, url); // urllist.add(page); category = "Chinos"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=3599821"; page = new RalphlaurenPage(type, category, url); // urllist.add(page); category = "Jeans"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=2061050"; page = new RalphlaurenPage(type, category, url); // urllist.add(page); category = "Shorts"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=1785464"; page = new RalphlaurenPage(type, category, url); // urllist.add(page); category = "Swim"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=1803513"; page = new RalphlaurenPage(type, category, url); // urllist.add(page); category = "Sport Coat"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=12993134"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Suits"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=13080553"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "underwear"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=1785475"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Sleepwear & Robes"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=15474366"; page = new RalphlaurenPage(type, category, url); urllist.add(page); // Shoes And Accessories category = "Shoes"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=2018030"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Hats"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=11618129"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Bags"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=11757767"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Small leather thing"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=12342421"; page = new RalphlaurenPage(type, category, url); urllist.add(page); category = "Belts"; url = "http://www.ralphlauren.com/family/index.jsp?s=A-StorePrice-POLO&view=all&pg=1&categoryId=11618127"; page = new RalphlaurenPage(type, category, url); urllist.add(page); return urllist; } public RalphlaurenPage(String type, String Category, String url) { this.type = type; this.Category = Category; this.url = url; } }
/* +--------------------------------------------------------------------------------------+ |Federal University Of Juiz de Fora - UFJF - Minas Gerais - Brazil | |Institute of Hard Sciences - ICE | |Computer Science Departament - DCC | |Project.........: qodra - video search | |Created in......:12/12/2013 | |--------------------------------------------------------------------------------------+ */ package br.ufjf.video; import br.ufjf.io.FileManager; import br.ufjf.io.XMLManager; import br.ufjf.ontology.QodraOntology; import org.apache.commons.lang.StringEscapeUtils; public class Video { public static void main(String args[]){ StringBuilder sb = new StringBuilder(); XMLManager.loadXMLFile("../files/ead_fonseca_05_sd.xml"); sb.append(getTriple(XMLManager.getValue("entry"),QodraOntology.TITLE,StringEscapeUtils.escapeJava(XMLManager.getValue("title")))); sb.append("\n"); sb.append(getTriple(XMLManager.getValue("entry"),QodraOntology.ABSTRACT,StringEscapeUtils.escapeJava(XMLManager.getValue("course")))); sb.append("\n"); sb.append(getTriple(XMLManager.getValue("entry"),QodraOntology.DATE,XMLManager.getValue("date"))); sb.append("\n"); //sb.append(getTriple(XMLManager.getValue("entry"),QodraOntology.REFERENCES,XMLManager.getValue("title"))); //sb.append("\n"); //sb.append(getTriple(XMLManager.getValue("entry"),QodraOntology.DESCRIPTION,XMLManager.getValue("title"))); //sb.append("\n"); sb.append(getTriple(XMLManager.getValue("entry"),QodraOntology.PUBLISHER,StringEscapeUtils.escapeJava(XMLManager.getValue("name")))); sb.append("\n"); sb.append(getTriple(XMLManager.getValue("entry"),QodraOntology.CREATOR,StringEscapeUtils.escapeJava(XMLManager.getValue("entity")))); sb.append("\n"); //sb.append(getTriple(XMLManager.getValue("entry"),QodraOntology.LICENSE,XMLManager.getValue("title"))); //sb.append("\n"); sb.append(getTriple(XMLManager.getValue("entry"),QodraOntology.LANGUAGE,XMLManager.getValue("language"))); sb.append("\n"); //sb.append(getTriple(XMLManager.getValue("entry"),QodraOntology.EDUCATIONLEVEL,XMLManager.getValue("title"))); //sb.append("\n"); FileManager.writeFile("../files/allegro.graph.nt",sb.toString() ); System.out.println(sb.toString()); } public static String getTriple(String subject, String predicate, String object){ return String.format(QodraOntology.N_TRIPLE_FORMAT,subject,predicate,object); } }
/* * Copyright (c) 2015 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.server.translation.in.action; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import pl.edu.icm.unity.exceptions.EngineException; import pl.edu.icm.unity.server.authn.remote.RemotelyAuthenticatedInput; import pl.edu.icm.unity.server.translation.in.InputTranslationAction; import pl.edu.icm.unity.server.translation.in.MappingResult; import pl.edu.icm.unity.server.utils.Log; import pl.edu.icm.unity.types.translation.TranslationActionType; /** * Maps multiple attributes only by providing new names, values are unchanged. * @author K. Benedyczak */ @Component public class RemoveStaleDataActionFactory extends AbstractInputTranslationActionFactory { public static final String NAME = "removeStaleData"; public RemoveStaleDataActionFactory() { super(NAME); } @Override public InputTranslationAction getInstance(String... parameters) { return new RemoveStaleDataAction(getActionType(), parameters); } public static class RemoveStaleDataAction extends InputTranslationAction { private static final Logger log = Log.getLogger(Log.U_SERVER_TRANSLATION, RemoveStaleDataAction.class); public RemoveStaleDataAction(TranslationActionType description, String[] params) { super(description, params); setParameters(params); } @Override protected MappingResult invokeWrapped(RemotelyAuthenticatedInput input, Object mvelCtx, String currentProfile) throws EngineException { MappingResult ret = new MappingResult(); log.debug("Ordering removal of the stale data"); ret.setCleanStaleAttributes(true); ret.setCleanStaleGroups(true); ret.setCleanStaleIdentities(true); return ret; } private void setParameters(String[] parameters) { if (parameters.length != 0) throw new IllegalArgumentException("Action requires no parameters"); } } }
package com.stk123.task.config; import com.stk123.common.CommonUtils; import lombok.extern.apachecommons.CommonsLog; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; @CommonsLog public class TaskCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return CommonUtils.isDevelopment(); } }
package be.mxs.common.util.date; import java.util.GregorianCalendar; import java.util.Date; public class MedwanCalendar extends GregorianCalendar { public static Date getNewDate(Date originalDate,long timeInMilliSeconds){ try{ MedwanCalendar cal = new MedwanCalendar(); cal.setTime(originalDate); cal.setTimeInMillis(cal.getTimeInMillis()+timeInMilliSeconds); return cal.getTime(); } catch (Exception e){ return new Date(); } } public static Date asDate(String sDate){ Date date = null; if (sDate.length()>0){ MedwanCalendar cal = new MedwanCalendar(); sDate.replace('.','/'); sDate.replace('-','/'); sDate.replace('_','/'); sDate.replace(' ','/'); sDate.replace('\\','/'); int nDay=0; int nMonth=0; int nYear=0; int nDelimiterPos=sDate.indexOf('/'); if (nDelimiterPos>-1){ nDay = Integer.parseInt(sDate.substring(0,nDelimiterPos)); sDate = sDate.substring(nDelimiterPos+1); nDelimiterPos=sDate.indexOf('/'); if (nDelimiterPos>-1){ nMonth = Integer.parseInt(sDate.substring(0,nDelimiterPos)); sDate = sDate.substring(nDelimiterPos+1); nDelimiterPos=sDate.indexOf('/'); if (nDelimiterPos>-1){ nYear = Integer.parseInt(sDate.substring(0,nDelimiterPos)); } else { nYear = Integer.parseInt(sDate); } try { cal.set(nYear, nMonth-1, nDay); date = cal.getTime(); } catch (Exception e){ // } } } } return date; } }
package com.medic.medicapp; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.ValueEventListener; import com.medic.medicapp.data.MedicContract; import static com.medic.medicapp.MainActivity.id; import static com.medic.medicapp.MainActivity.mAdminsReference; import static com.medic.medicapp.MainActivity.mDb; import static com.medic.medicapp.MainActivity.mFirebaseAuth; import static com.medic.medicapp.MainActivity.mUsersReference; public class RegisterActivity extends AppCompatActivity { private EditText mNewUserEditText; private EditText mNewPasswordEditText; private EditText mEmailEditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); mNewUserEditText = (EditText) findViewById(R.id.et_user_name); mNewPasswordEditText = (EditText) findViewById(R.id.et_user_password); mEmailEditText = (EditText) findViewById(R.id.et_email); } //Este es el método que se llama al pulsar el botón de REGISTRARSE public void addUser(View view) { if(mNewUserEditText.getText().length()==0 ||mNewPasswordEditText.getText().length()==0 || mEmailEditText.getText().length()==0){ }else if(mNewPasswordEditText.getText().length() < 6){ Toast.makeText(getBaseContext(), R.string.password6Caracteres, Toast.LENGTH_LONG).show(); mNewPasswordEditText.getText().clear(); }else{ addUserIfUsernameAvailable(mNewUserEditText.getText().toString()); } } private void addUserIfUsernameAvailable(final String username) { mUsersReference.child(username).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ // username already exists. Not available mNewUserEditText.getText().clear(); Toast.makeText(getBaseContext(), R.string.register_error, Toast.LENGTH_LONG).show(); } else { // username does not exist. Available checkIfAvailableInAdminsNode(username); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void checkIfAvailableInAdminsNode(String username) { mAdminsReference.child(username).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ // username already exists. Not available mNewUserEditText.getText().clear(); Toast.makeText(getBaseContext(), R.string.register_error, Toast.LENGTH_LONG).show(); } else { // username does not exist. Available createAccount( mEmailEditText.getText().toString(), mNewUserEditText.getText().toString(), mNewPasswordEditText.getText().toString()); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void createAccount(String email, final String userName, final String password) { mFirebaseAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>(){ @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { createNewUser(task.getResult().getUser(), userName, password); Toast.makeText(RegisterActivity.this, "User registered correctly", Toast.LENGTH_SHORT).show(); Toast.makeText(getBaseContext(), R.string.register_ok, Toast.LENGTH_LONG).show(); //Como se ha registrado correctamente puede acceder a su nueva cuenta Intent intent = new Intent(RegisterActivity.this, PatientActivity.class); intent.putExtra(Intent.EXTRA_TEXT, mNewUserEditText.getText().toString()); startActivity(intent); } else { Toast.makeText(RegisterActivity.this, "An error occurred: " + task.getResult().toString(), Toast.LENGTH_SHORT).show(); } } } ); } private void createNewUser(FirebaseUser userFromRegistration, String userName, String password) { // String email = userFromRegistration.getEmail(); // String userId = userFromRegistration.getUid(); // // User user = new User(userName, email, password); // // user.insertUser(userId); } @Override public boolean onCreateOptionsMenu(Menu menu) { /* Use AppCompatActivity's method getMenuInflater to get a handle on the menu inflater */ MenuInflater inflater = getMenuInflater(); /* Use the inflater's inflate method to inflate our menu layout to this menu */ /////////////////inflater.inflate(R.menu.menu_help, menu); /* Return true so that the menu is displayed in the Toolbar */ return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id){ /////////////////case R.id.action_help: ////////////// startActivity(new Intent(this, RegisterHelpActivity.class)); ///////////////// return true; } return super.onOptionsItemSelected(item); } }
package com.lotus.controller; import java.util.LinkedList; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import com.lotus.model.TweetDetails; class OperationsTest { private Operations op = new Operations(); @Test void test() { TweetDetails tweet1 = new TweetDetails(); tweet1.setUsername("vaibhav"); tweet1.setLocation("hyderabad"); tweet1.setHashtag("#swym"); tweet1.setText("hi"); op.parseTweet(tweet1); TweetDetails tweet2 = new TweetDetails(); tweet2.setUsername("anuj"); tweet2.setLocation("pune"); tweet2.setHashtag("#awesome"); tweet2.setText("hello"); op.parseTweet(tweet2); TweetDetails tweet3 = new TweetDetails(); tweet3.setUsername("vaibhav"); tweet3.setLocation("london"); tweet3.setHashtag("#swym"); tweet3.setText("how are u?"); op.parseTweet(tweet3); assert(Controller.hashtagCountMap.size() == 2); assert(Controller.locationTweetCountMap.size() == 3); assert(Controller.top100hashtags.size() ==3); LinkedList<TweetDetails> ll = Controller.userToTweet.get("vaibhav"); assert(ll.size() == 2); LinkedList<TweetDetails> ll1 = Controller.userToTweet.get("anuj"); assert(ll1.size() == 1); } }
package cz.jpetrla.springdemo.mvc; import java.util.Map; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/student") public class StudentController { @Value("#{countryOptions}") private Map<String, String> countryOptions; @Value("#{programmingLanguageOptions}") private Map<String, String> programmingLanguageOptions; @Value("#{operationSystemOptions}") private Map<String, String> operationSystemOptions; @RequestMapping("/showForm") public String showForm(Model model) { // create student object Student student = new Student(); // add student object to model model.addAttribute("student", student); // add country options to model model.addAttribute("countryOptions", countryOptions); // add programming language options to model model.addAttribute("programmingLanguageOptions", programmingLanguageOptions); // add operation system options to model model.addAttribute("operationSystemOptions", operationSystemOptions); return "student-form"; } @RequestMapping("/processForm") public String processForm(@ModelAttribute("student") Student student) { // log input data return "student-confirmation"; } }
package com.example.android.moneytran.currency; import com.example.android.moneytran.R; public class JapaneseYen extends Currency { private int name = R.string.jpy_name; private int balance = R.string.jpy_balance; private int flag = R.drawable.flag_japan; private char symbol = '\u00A5'; @Override public int getName() { return name; } @Override public int getBalance() { return balance; } @Override public int getFlag() { return flag; } @Override public char getSymbol() { return symbol; } }
package domain; import lombok.Data; import java.io.Serializable; /** * 要找到类的实例只需要知道此类的名字就行,找到了类的实例,那么如何找到方法呢?在反射中通过反射能够根据方法名和参数 * 类型从而找到这个方法。那么此时第一类的信息我们就明了了,那么就建立相应的是实体类存储这些信息。 */ @Data public class Request implements Serializable { private static final long serialVersionUID = 3933918042687238629L; private String className; //类名 private String methodName; //方法名 private Class<?>[] parameTypes; //参数类型 private Object[] parameters; //参数 }