text
stringlengths
10
2.72M
package github.tornaco.android.thanos.main; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.PopupMenu; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.GridLayoutManager; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import java.util.Objects; import github.tornaco.android.thanos.R; import github.tornaco.android.thanos.ThanosApp; import github.tornaco.android.thanos.app.donate.DonateIntroDialogKt; import github.tornaco.android.thanos.app.donate.DonateSettings; import github.tornaco.android.thanos.core.T; import github.tornaco.android.thanos.core.util.ClipboardUtils; import github.tornaco.android.thanos.dashboard.DashboardCardAdapter; import github.tornaco.android.thanos.dashboard.OnHeaderClickListener; import github.tornaco.android.thanos.dashboard.OnTileClickListener; import github.tornaco.android.thanos.dashboard.OnTileLongClickListener; import github.tornaco.android.thanos.dashboard.Tile; import github.tornaco.android.thanos.dashboard.ViewType; import github.tornaco.android.thanos.databinding.FragmentPrebuiltFeaturesBinding; import github.tornaco.android.thanos.onboarding.OnBoardingActivity; import github.tornaco.android.thanos.process.v2.ProcessManageActivityV2; public class PrebuiltFeatureFragment extends NavFragment implements OnTileClickListener, OnTileLongClickListener, OnHeaderClickListener { private FragmentPrebuiltFeaturesBinding prebuiltFeaturesBinding; private NavViewModel navViewModel; private Handler uiHandler; private PrebuiltFeatureLauncher featureLauncher; @Override public void onAttach(Context context) { super.onAttach(context); this.uiHandler = new Handler(Looper.getMainLooper()); } @Nullable @Override public View onCreateView( @NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { prebuiltFeaturesBinding = FragmentPrebuiltFeaturesBinding.inflate(inflater, container, false); setupView(); setupViewModel(); return prebuiltFeaturesBinding.getRoot(); } private void setupView() { prebuiltFeaturesBinding.features.getRecycledViewPool().setMaxRecycledViews(ViewType.HEADER, 0); prebuiltFeaturesBinding.features.getRecycledViewPool().setMaxRecycledViews(ViewType.ITEM, 0); prebuiltFeaturesBinding.features.getRecycledViewPool().setMaxRecycledViews(ViewType.FOOTER, 0); prebuiltFeaturesBinding.features.setLayoutManager(new GridLayoutManager(getContext(), 1)); prebuiltFeaturesBinding.features.setAdapter(new DashboardCardAdapter(this, this, this)); prebuiltFeaturesBinding.swipe.setColorSchemeColors(getResources().getIntArray( github.tornaco.android.thanos.module.common.R.array.common_swipe_refresh_colors)); prebuiltFeaturesBinding.swipe.setOnRefreshListener(() -> navViewModel.start()); } private void setupViewModel() { navViewModel = obtainViewModel(requireActivity()); prebuiltFeaturesBinding.setViewmodel(navViewModel); prebuiltFeaturesBinding.executePendingBindings(); this.featureLauncher = new PrebuiltFeatureLauncher(requireActivity(), navViewModel, uiHandler); } private static NavViewModel obtainViewModel(FragmentActivity activity) { ViewModelProvider.AndroidViewModelFactory factory = ViewModelProvider.AndroidViewModelFactory.getInstance(activity.getApplication()); return ViewModelProviders.of(activity, factory).get(NavViewModel.class); } @Override public void onClick(@NonNull Tile tile) { featureLauncher.launch(tile.getId()); } @Override public void onLongClick(@NonNull Tile tile, @NonNull View view) { if (tile.getId() == PrebuiltFeatureIds.ID_ONE_KEY_CLEAR) { showOneKeyBoostPopMenu(view); } else if (tile.getId() == PrebuiltFeatureIds.ID_GUIDE) { OnBoardingActivity.Starter.INSTANCE.start(requireActivity()); } else { showCommonTilePopMenu(view, tile); } } private void showOneKeyBoostPopMenu(@NonNull View view) { PopupMenu popupMenu = new PopupMenu(Objects.requireNonNull(requireActivity()), view); popupMenu.inflate(R.menu.one_key_boost_pop_menu); popupMenu.setOnMenuItemClickListener( item -> { if (item.getItemId() == R.id.create_shortcut) { OneKeyBoostShortcutActivity.ShortcutHelper.addShortcut(requireActivity()); return true; } if (item.getItemId() == R.id.broadcast_intent_shortcut) { new MaterialAlertDialogBuilder(Objects.requireNonNull(requireActivity())) .setTitle(getString(R.string.menu_title_broadcast_intent_shortcut)) .setMessage(T.Actions.ACTION_RUNNING_PROCESS_CLEAR) .setPositiveButton( R.string.menu_title_copy, (dialog, which) -> { ClipboardUtils.copyToClipboard( requireContext(), "one-ley-boost-intent", T.Actions.ACTION_RUNNING_PROCESS_CLEAR); Toast.makeText( requireActivity(), R.string.common_toast_copied_to_clipboard, Toast.LENGTH_SHORT) .show(); }) .setCancelable(true) .show(); return true; } return false; }); popupMenu.show(); } private void showCommonTilePopMenu(@NonNull View view, @NonNull Tile tile) { PopupMenu popupMenu = new PopupMenu(Objects.requireNonNull(requireActivity()), view); popupMenu.inflate(R.menu.nav_common_feature_pop_up_menu); popupMenu.setOnMenuItemClickListener( item -> { if (item.getItemId() == R.id.create_shortcut) { PrebuiltFeatureShortcutActivity.ShortcutHelper.addShortcut(requireActivity(), tile); return true; } return false; }); popupMenu.show(); } @Override public void onHeaderClick() { if (ThanosApp.isPrc() && !DonateSettings.isActivated(requireActivity())) { DonateIntroDialogKt.showDonateIntroDialog(requireActivity()); return; } ProcessManageActivityV2.Starter.INSTANCE.start(requireActivity()); } }
package com.solo.data.api; import com.solo.data.Constants; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class RecipesApi { private static RecipesService recipesService; private static final Object LOCK = new Object(); public synchronized static RecipesService getInstance() { if (recipesService == null) { synchronized (LOCK) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constants.BAKING_RECIPES_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); recipesService = retrofit.create(RecipesService.class); } } return recipesService; } }
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.util.bean.opteditor; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.awt.Component; import java.awt.Container; import java.text.SimpleDateFormat; import java.util.*; import javax.swing.*; import javax.swing.tree.TreePath; import org.junit.*; import com.toedter.calendar.JCalendar; import docking.action.DockingActionIf; import docking.options.editor.*; import docking.widgets.tree.GTree; import docking.widgets.tree.GTreeNode; import ghidra.app.plugin.core.codebrowser.CodeBrowserPlugin; import ghidra.framework.options.Options; import ghidra.framework.plugintool.PluginTool; import ghidra.program.database.ProgramBuilder; import ghidra.program.model.listing.Program; import ghidra.test.AbstractGhidraHeadedIntegrationTest; import ghidra.test.TestEnv; public class DateEditorTest extends AbstractGhidraHeadedIntegrationTest { private static final String TEST_CATEGORY_NAME = "Test Editor"; private static final String TEST_DATE_OPTION_NAME = "Time Option Name"; private TestEnv env; private PluginTool tool; private Program program; private CodeBrowserPlugin plugin; @Before public void setUp() throws Exception { program = buildProgram(); env = new TestEnv(); tool = env.showTool(program); tool.addPlugin(CodeBrowserPlugin.class.getName()); plugin = env.getPlugin(CodeBrowserPlugin.class); } private Program buildProgram() throws Exception { ProgramBuilder builder = new ProgramBuilder("notepad", ProgramBuilder._TOY); builder.createMemory("test1", Long.toHexString(0x1001000), 0x2000); return builder.getProgram(); } @After public void tearDown() throws Exception { env.dispose(); } @Test public void testEditor() throws Exception { Date initialDate = new Date(System.currentTimeMillis()); DateEditor dateEditor = addDateProperty(initialDate); showProgramOptions(); OptionsDialog optionsDialog = waitForDialogComponent(OptionsDialog.class); ScrollableOptionsEditor optionsEditor = selectionDateOptionCategory(optionsDialog); Component c = findPairedComponent(optionsEditor, TEST_DATE_OPTION_NAME); assertNotNull(c); JTextField optionTextField = findComponent((Container) c, JTextField.class); assertNotNull(optionTextField); String testDateString = dateEditor.format(initialDate); assertEquals(testDateString, getText(optionTextField)); JDialog dateDialog = lauchDateEditorDialog(c); JCalendar calendar = findComponent(dateDialog, JCalendar.class); assertNotNull("Could not find JCalendar", calendar); Calendar cal = calendar.getCalendar(); int hours = runSwing(() -> cal.get(Calendar.HOUR_OF_DAY)); int minutes = runSwing(() -> cal.get(Calendar.MINUTE)); int seconds = runSwing(() -> cal.get(Calendar.SECOND)); JTextField hoursField = getTextField(dateDialog, "Hours"); JTextField minutesField = getTextField(dateDialog, "Minutes"); JTextField secondsField = getTextField(dateDialog, "Seconds"); assertEquals(hours, Integer.parseInt(getText(hoursField))); assertEquals(minutes, Integer.parseInt(getText(minutesField))); assertEquals(seconds, Integer.parseInt(getText(secondsField))); JCalendar cd = calendar; Date currentDate = runSwing(() -> cd.getCalendar().getTime()); assertDateLabelValue(dateDialog, currentDate); // change the time setText(hoursField, "01"); setText(minutesField, "21"); setText(secondsField, "59"); Calendar c2 = (Calendar) cal.clone(); runSwing(() -> { c2.set(Calendar.HOUR_OF_DAY, 1); c2.set(Calendar.MINUTE, 21); c2.set(Calendar.SECOND, 59); cd.setCalendar(c2); }); Date newDate = runSwing(() -> c2.getTime()); pressOk(dateDialog); // make sure the text field was updated testDateString = dateEditor.format(newDate); assertEquals(testDateString, getText(optionTextField)); pressApply(optionsDialog); // make sure the property changed Options plist = program.getOptions(TEST_CATEGORY_NAME); Date actualDate = plist.getDate(TEST_DATE_OPTION_NAME, (Date) null); assertEquals(newDate, actualDate); closeAllWindowsAndFrames(); } private void assertDateLabelValue(Container c, Date date) { JLabel dateLabel = (JLabel) findComponentByName(c, "DateString"); assertNotNull(dateLabel); SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy "); assertEquals(formatter.format(date), runSwing(() -> dateLabel.getText())); } private JTextField getTextField(Container c, String name) { JTextField tf = (JTextField) findComponentByName(c, name); assertNotNull(tf); return tf; } private ScrollableOptionsEditor selectionDateOptionCategory(OptionsDialog optionsDialog) throws Exception { OptionsPanel optionsPanel = (OptionsPanel) getInstanceField("panel", optionsDialog); Container pane = optionsDialog.getComponent(); GTree tree = findComponent(pane, GTree.class); waitForTree(tree); GTreeNode testNode = getGTreeNode(tree.getRootNode(), TEST_CATEGORY_NAME); selectNode(testNode); ScrollableOptionsEditor p = (ScrollableOptionsEditor) getEditorPanel(optionsPanel, testNode); assertNotNull(p); return p; } private void pressApply(OptionsDialog optionsDialog) { JButton applyButton = findButtonByText(optionsDialog.getComponent(), "Apply"); pressButton(applyButton); waitForSwing(); } private void pressOk(JDialog dateDialog) { JButton okButton = findButtonByText(dateDialog.getContentPane(), "OK"); assertNotNull(okButton); pressButton(okButton); waitForSwing(); } private JDialog lauchDateEditorDialog(Component c) { JButton button = findButtonByIcon((Container) c, ButtonPanelFactory.BROWSE_ICON); assertNotNull(button); pressButton(button, false); waitForSwing(); JDialog dateDialog = waitForJDialog("Edit Date"); assertNotNull(dateDialog); return dateDialog; } private void showProgramOptions() { List<DockingActionIf> list = tool.getAllActions(); for (int i = 0; i < list.size(); i++) { DockingActionIf action = list.get(i); if (action.getName().equals("Program Options")) { performAction(action, plugin.getProvider(), false); break; } } waitForSwing(); } private Object getEditorPanel(OptionsPanel optionsPanel, Object testNode) { Map<?, ?> map = (Map<?, ?>) getInstanceField("editorMap", optionsPanel); return map.get(testNode); } private void selectNode(GTreeNode node) throws Exception { TreePath path = node.getTreePath(); GTree tree = node.getTree(); tree.setSelectionPath(path); waitForTree(tree); } private GTreeNode getGTreeNode(GTreeNode parent, String nodeName) throws Exception { for (int i = 0; i < parent.getChildCount(); i++) { GTreeNode node = parent.getChild(i); if (node.getName().equals(nodeName)) { return node; } GTreeNode foundNode = getGTreeNode(node, nodeName); if (foundNode != null) { return foundNode; } } return null; } private DateEditor addDateProperty(Date date) { Options list = program.getOptions(TEST_CATEGORY_NAME); list.registerOption(TEST_DATE_OPTION_NAME, new Date(0), null, "Test for the DateEditor"); int transactionID = program.startTransaction("My Test"); try { list.setDate(TEST_DATE_OPTION_NAME, date); } finally { program.endTransaction(transactionID, true); } return (DateEditor) runSwing(() -> list.getPropertyEditor(TEST_DATE_OPTION_NAME)); } private Component findPairedComponent(Container container, String labelText) { Component[] c = container.getComponents(); for (int i = 0; i < c.length; i++) { if (c[i] instanceof JLabel) { if (((JLabel) c[i]).getText().equals(labelText)) { return c[i + 1]; } } if (c[i] instanceof Container) { Component comp = findPairedComponent((Container) c[i], labelText); if (comp != null) { return comp; } } } return null; } }
class Arrays { public Arrays() { System.out.println("demo"); } } public class OnedArray2 { public static void main(String[] args) { Arrays a1 = new Arrays(); Arrays a2 = new Arrays(); Arrays a3 = new Arrays(); Arrays a4 = new Arrays(); Arrays a5 = new Arrays(); Arrays a[] = new Arrays[5]; Arrays b[] = {a1, a2, a3, a4, a5}; } }
package at.fhv.itm14.fhvgis.webservice.app.converters; import at.fhv.itm14.fhvgis.domain.DomainEntity; import org.json.JSONObject; /** * Author: Philip Heimböck * Date: 13.11.15. * <p/> * These converters are needed because I cannot just serialize the classes * because of inconsistencies between app classes and server classes * Custom mapping is therefore required */ public abstract class JsonConverter<T extends DomainEntity> { public abstract T toDomain(JSONObject json); public abstract JSONObject toJson(T entity); }
package com.wencheng.service; import javax.servlet.http.HttpServletRequest; import com.wencheng.domain.MiddleReport; public interface MiddleService { public boolean create(HttpServletRequest request); public MiddleReport find(HttpServletRequest request); public MiddleReport findother(HttpServletRequest request); }
package com.myxh.developernews.ui.widget; import android.graphics.Rect; import android.support.v7.widget.RecyclerView; import android.view.View; /** * Created by asus on 2016/10/5. */ public class ImageItemDecorator extends RecyclerView.ItemDecoration { //图片间隙 private int space; public ImageItemDecorator(int space) { this.space = space; } /** * 设置左右上下间隙 * @param outRect * @param view * @param parent * @param state */ @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { // super.getItemOffsets(outRect, view, parent, state); outRect.bottom = space; outRect.left = space; outRect.right = space; //第一行不设置top间隙 if (parent.getChildLayoutPosition(view) != 0) { outRect.top = space; } } }
package orm.integ.eao.model; public class FieldMapping { String foreignKeyField; String masterField; public String getForeignKeyField() { return foreignKeyField; } public String getMasterField() { return masterField; } }
package com.zantong.mobilecttx.presenter; import android.text.TextUtils; import android.view.View; 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.PublicData; import com.zantong.mobilecttx.model.IllegalQueryModelImp; import com.zantong.mobilecttx.presenter.presenterinterface.SimplePresenter; import com.zantong.mobilecttx.utils.DialogUtils; import com.zantong.mobilecttx.utils.SPUtils; import cn.qqtheme.framework.util.ToastUtils; import com.zantong.mobilecttx.utils.Tools; import com.zantong.mobilecttx.utils.rsa.RSAUtils; import com.zantong.mobilecttx.weizhang.bean.AddVehicleBean; import com.zantong.mobilecttx.weizhang.fragment.QueryFragment; 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 IllegalQueryPresenter extends BasePresenter<IBaseView> implements SimplePresenter, OnLoadServiceBackUI { QueryFragment mQueryFragment; IllegalQueryModelImp mIllegalQueryModelImp; private String msg = ""; private HashMap<String, Object> oMap = new HashMap<>(); private JSONObject masp = null; public IllegalQueryPresenter(QueryFragment mQueryFragment) { this.mQueryFragment = mQueryFragment; mIllegalQueryModelImp = new IllegalQueryModelImp(); } @Override public void loadView(final int index) { if (SPUtils.getInstance().getXinnengyuanFlag() && mQueryFragment.mapData().get("carnum").length() >= 8 && (!mQueryFragment.mapData().get("carnumtype").equals("51") || !mQueryFragment.mapData().get("carnumtype").equals("52"))){ SPUtils.getInstance().setXinnengyuanFlag(false); DialogUtils.createDialog(mQueryFragment.getActivity(), "温馨提示", "如果您的汽车为新能源汽车,车牌类型请选择新能源汽车", "取消", "继续查询", new View.OnClickListener() { @Override public void onClick(View v) { } }, new View.OnClickListener() { @Override public void onClick(View v) { mQueryFragment.showProgress(); switch (index) { case 1: MessageFormat.getInstance().setTransServiceCode("cip.cfc.v002.01"); masp = new JSONObject(); try { if (mQueryFragment.mapData().get("carnum").length() <= 6) { ToastUtils.showShort(mQueryFragment.getActivity(), "请输入车牌号"); mQueryFragment.hideProgress(); return; } if (Tools.isStrEmpty(mQueryFragment.mapData().get("enginenum"))) { ToastUtils.showShort(mQueryFragment.getActivity(), "请输入发动机号"); mQueryFragment.hideProgress(); return; } if (mQueryFragment.mapData().get("enginenum").length() != 5) { ToastUtils.showShort(mQueryFragment.getActivity(), "发动机号格式不正确"); mQueryFragment.hideProgress(); return; } if (TextUtils.isEmpty(PublicData.getInstance().imei)) { masp.put("token", RSAUtils.strByEncryption("00000000", true)); } else { masp.put("token", RSAUtils.strByEncryption(PublicData.getInstance().imei, true)); } LogUtils.i(masp.get("token").toString()); masp.put("carnumtype", mQueryFragment.mapData().get("carnumtype")); masp.put("carnum", RSAUtils.strByEncryption(mQueryFragment.mapData().get("carnum"), true)); masp.put("enginenum", RSAUtils.strByEncryption(mQueryFragment.mapData().get("enginenum"), true)); MessageFormat.getInstance().setMessageJSONObject(masp); msg = MessageFormat.getInstance().getMessageFormat(); mIllegalQueryModelImp.loadUpdate(IllegalQueryPresenter.this, msg, index); }catch (JSONException e){ } break; } } }); }else { mQueryFragment.showProgress(); switch (index) { case 1: MessageFormat.getInstance().setTransServiceCode("cip.cfc.v002.01"); masp = new JSONObject(); try { if (mQueryFragment.mapData().get("carnum").length() <= 6) { ToastUtils.showShort(mQueryFragment.getActivity(), "请输入车牌号"); mQueryFragment.hideProgress(); return; } if (Tools.isStrEmpty(mQueryFragment.mapData().get("enginenum"))) { ToastUtils.showShort(mQueryFragment.getActivity(), "请输入发动机号"); mQueryFragment.hideProgress(); return; } if (mQueryFragment.mapData().get("enginenum").length() != 5) { ToastUtils.showShort(mQueryFragment.getActivity(), "发动机号格式不正确"); mQueryFragment.hideProgress(); return; } if (TextUtils.isEmpty(PublicData.getInstance().imei)) { masp.put("token", RSAUtils.strByEncryption("00000000", true)); } else { masp.put("token", RSAUtils.strByEncryption(PublicData.getInstance().imei, true)); } LogUtils.i(masp.get("token").toString()); masp.put("carnumtype", mQueryFragment.mapData().get("carnumtype")); masp.put("carnum", RSAUtils.strByEncryption(mQueryFragment.mapData().get("carnum"), true)); masp.put("enginenum", RSAUtils.strByEncryption(mQueryFragment.mapData().get("enginenum"), true)); MessageFormat.getInstance().setMessageJSONObject(masp); msg = MessageFormat.getInstance().getMessageFormat(); mIllegalQueryModelImp.loadUpdate(IllegalQueryPresenter.this, msg, index); }catch (JSONException e){ } break; } } } @Override public void onSuccess(Object clazz, int index) { mQueryFragment.hideProgress(); switch (index){ case 1: AddVehicleBean mAddVehicleBean = (AddVehicleBean) clazz; if(PublicData.getInstance().success.equals(mAddVehicleBean.getSYS_HEAD().getReturnCode())){ LogUtils.i("1"); mQueryFragment.updateView(clazz, index); }else{ LogUtils.i("2"); ToastUtils.showShort(mQueryFragment.getActivity(), mAddVehicleBean.getSYS_HEAD().getReturnMessage()); } break; } } @Override public void onFailed() { mQueryFragment.hideProgress(); LogUtils.i("3"); // ToastUtils.showShort(mQueryFragment.getActivity(), Config.getErrMsg("1")); } }
package TEST; class Pairs<K, V> { private K key; private V value; public Pairs(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public void setKey(K key) { this.key = key; } public V getValue() { return value; } public void setValue(V value) { this.value = value; } } class Utils { public static <K, V> boolean compare(Pairs<K, V> p1, Pairs<K, V> p2) { boolean b1 = p1.getKey().equals(p2.getKey()); boolean b2 = p1.getValue().equals(p2.getValue()); return b1 && b2; } public static <T extends Number> int compare (T t1, T t2) { double v1 = t1.doubleValue(); double v2 = t2.doubleValue(); return Double.compare(v1, v2); // v1, v2 비교 해서 작을때-1, 같을때 0, 클때1 } } public class BoxM { public static void main(String[] args) { double result = Utils.compare(10.0, 10.0); System.out.println((int)result); // Pairs<Integer, String> p1 = new Pairs<Integer, String>(1, "aa"); // Pairs<Integer, String> p2 = new Pairs<Integer, String>(1, "aa"); // // boolean result = Utils.compare(p1, p2); // // if (result) // System.out.println("동일객체"); // else // System.out.println("동일객체아님"); } }
package com.wangtao; import com.github.tobato.fastdfs.domain.fdfs.MetaData; import com.github.tobato.fastdfs.domain.fdfs.StorePath; import com.github.tobato.fastdfs.service.FastFileStorageClient; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import org.activiti.engine.ProcessEngine; import org.activiti.engine.ProcessEngineConfiguration; import org.activiti.spring.SpringProcessEngineConfiguration; import org.assertj.core.util.Sets; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.sql.DataSource; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Random; import java.util.Set; /** * @author : want * @Team Home * @date : 2019-3-4 14:01 星期一 */ @RunWith(SpringRunner.class) @SpringBootTest public class ActivitiDemoApplicationTests { @Resource(name = "myDataSource") private DataSource myDataSource; @Test public void init() { ProcessEngineConfiguration configuration = SpringProcessEngineConfiguration.createProcessEngineConfigurationFromResourceDefault(); configuration.setDataSource(myDataSource); ProcessEngine processEngine = configuration.buildProcessEngine(); String name = processEngine.getName(); System.out.println("name = " + name); } @Test public void qrCode() throws WriterException, IOException { String qrcodeFilePath = ""; int qrcodeWidth = 300; int qrcodeHeight = 300; String qrcodeFormat = "png"; HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = new MultiFormatWriter().encode("http://www.cnblogs.com/java-class/", BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeHeight, hints); BufferedImage image = new BufferedImage(qrcodeWidth, qrcodeHeight, BufferedImage.TYPE_INT_RGB); Random random = new Random(); File QrcodeFile = new File("C:\\Users\\want\\Desktop\\test\\" + random.nextInt() + "." + qrcodeFormat); ImageIO.write(image, qrcodeFormat, QrcodeFile); MatrixToImageWriter.writeToFile(bitMatrix, qrcodeFormat, QrcodeFile); qrcodeFilePath = QrcodeFile.getAbsolutePath(); } @Autowired private FastFileStorageClient fastFileStorageClient; @Test public void testFastDfsUpload() throws FileNotFoundException { // File file = new File("C:\\Users\\want\\Desktop\\images\\home.png"); FileInputStream fileInputStream = new FileInputStream(file); //StorePath uploadFile(InputStream inputStream, long fileSize, String fileExtName, Set<MetaData> metaDataSet); Set<MetaData> metaDataSet = Sets.newHashSet(); MetaData name = new MetaData("name", file.getName()); MetaData size = new MetaData("size", String.valueOf(file.length())); metaDataSet.add(name); metaDataSet.add(size); StorePath storePath = fastFileStorageClient.uploadFile(fileInputStream, file.length(), "png", metaDataSet); String fullPath = storePath.getFullPath(); System.out.println("fullPath = " + fullPath); String path = storePath.getPath(); System.out.println("path = " + path); String group = storePath.getGroup(); System.out.println("group = " + group); } }
package yo.one.creation.singleton; //内部类实现的单例模式 public class InnerClassSingleton { private InnerClassSingleton() { } private static class InnerClassSingletonHolder{ private static InnerClassSingleton instance = new InnerClassSingleton(); } public static InnerClassSingleton getInstance(){ return InnerClassSingletonHolder.instance; } }
package ru.atc.wordsTrainer.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * Created by VTestova on 03.12.2015. */ @Controller @RequestMapping("/") public class MainController { @RequestMapping("/") public String main(){ return "index"; } }
package com.openfarmanager.android.googledrive.model; import com.openfarmanager.android.googledrive.api.Fields; import org.json.JSONException; import org.json.JSONObject; /** * author: Vlad Namashko */ public class Token { private String mAccessToken; private String mRefreshToken; public Token(String jsonData) throws JSONException { JSONObject object = new JSONObject(jsonData); mAccessToken = object.getString(Fields.ACCESS_TOKEN); mRefreshToken = object.getString(Fields.REFRESH_TOKEN); } public Token(String jsonData, String refreshToken) throws JSONException { JSONObject object = new JSONObject(jsonData); mAccessToken = object.getString(Fields.ACCESS_TOKEN); mRefreshToken = refreshToken; } public static Token fromLocalData(String accessToken, String refreshToken) { Token token = new Token(); token.mAccessToken = accessToken; token.mRefreshToken = refreshToken; return token; } public Token() { } public String getAccessToken() { return mAccessToken; } public String getRefreshToken() { return mRefreshToken; } }
package utilidades.interfaces; import java.util.HashMap; import org.json.simple.JSONArray; public interface ABM<T> { interface HashMapFunction<T> { void setJson(T t, Object value); } public static final String METHOD_NAME_insertOrUpdateValuesFromJSONArray = "insertOrUpdateValuesFromJSONArray"; public static final String METHOD_NAME_setHashMapFunction = "setHashMapFunction"; T insertOrUpdateValuesFromJSONArray(JSONArray jsonArray, String accion); void setHashMapFunction(HashMap<String, HashMapFunction<T>> map); }
package com.proyectofinal.game.objects.towers.attack; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.scenes.scene2d.Actor; import com.proyectofinal.game.helpers.AssetManager; /** * Created by ALUMNEDAM on 22/05/2017. */ public class Fuego extends Actor { //Atributos private float x, y; public float tiempoDeEstado = 0; private boolean visible; private float radio; private float curva; /** * Constructor de clase fuego, inicialitza atributos. * * @param x * @param y * @param radio */ public Fuego(float x, float y, int radio) { this.x = x - 100; this.y = y - 100; this.radio = radio - (radio / 3); curva = this.radio - (this.radio / 3); visible = false; } /** * Methodo override de draw. Por parametros le pasamos el batch y parentAlpha * * @param batch * @param parentAlpha */ @Override public void draw(Batch batch, float parentAlpha) { super.draw(batch, parentAlpha); //llama a clase padre, y por parametros le pasamos el batch y parentAlpha //si el booleano de visible es true, dibuja fuego de torre. if (visible) { batch.draw(AssetManager.fuegoTorre.getKeyFrame(getTiempoDeEstado()), x, y + radio, 0, 0, 300, 300, 1f, 1f, 0); batch.draw(AssetManager.fuegoTorre.getKeyFrame(getTiempoDeEstado()), x + radio, y, 0, 0, 300, 300, 1f, 1f, 0); batch.draw(AssetManager.fuegoTorre.getKeyFrame(getTiempoDeEstado()), x, y - radio, 0, 0, 300, 300, 1f, 1f, 0); batch.draw(AssetManager.fuegoTorre.getKeyFrame(getTiempoDeEstado()), x - radio, y, 0, 0, 300, 300, 1f, 1f, 0); batch.draw(AssetManager.fuegoTorre.getKeyFrame(getTiempoDeEstado()), x + curva, y + curva, 0, 0, 300, 300, 1f, 1f, 0); batch.draw(AssetManager.fuegoTorre.getKeyFrame(getTiempoDeEstado()), x + curva, y - curva, 0, 0, 300, 300, 1f, 1f, 0); batch.draw(AssetManager.fuegoTorre.getKeyFrame(getTiempoDeEstado()), x - curva, y + curva, 0, 0, 300, 300, 1f, 1f, 0); batch.draw(AssetManager.fuegoTorre.getKeyFrame(getTiempoDeEstado()), x - curva, y - curva, 0, 0, 300, 300, 1f, 1f, 0); } } /** * Methodo que devuelve el tirmpo de estado * * @return */ public float getTiempoDeEstado() { return tiempoDeEstado; } /** * Methodo set para poner el tiempo de estado. * * @param tiempoDeEstado */ public void setTiempoDeEstado(float tiempoDeEstado) { this.tiempoDeEstado = tiempoDeEstado; } //Methodos overrides @Override public float getX() { return x; } @Override public void setX(float x) { this.x = x; } @Override public float getY() { return y; } @Override public void setY(float y) { this.y = y; } @Override public boolean isVisible() { return visible; } @Override public void setVisible(boolean visible) { this.visible = visible; } }
package hu.mentlerd.hybrid.asm; import hu.mentlerd.hybrid.CallFrame; import hu.mentlerd.hybrid.LuaTable; import hu.mentlerd.hybrid.asm.OverloadResolver.OverloadRule; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import org.objectweb.asm.commons.GeneratorAdapter; import static org.objectweb.asm.Opcodes.*; import static org.objectweb.asm.Type.*; public class CoercionAdapter extends GeneratorAdapter{ protected static final String TABLE = AsmHelper.getAsmName( LuaTable.class ); protected static final String FRAME = AsmHelper.getAsmName( CallFrame.class ); protected static final Type OBJ_BOOLEAN = Type.getType( Boolean.class ); protected static final Type OBJ_DOUBLE = Type.getType( Double.class ); protected static final Type OBJ_TABLE = Type.getType( LuaTable.class ); protected static final Type OBJ_OBJECT = Type.getType( Object.class ); protected static final Type EXCEPTION = Type.getType( IllegalArgumentException.class ); protected static Map<String, Type> numberCoercionMap = new HashMap<String, Type>(); static{ numberCoercionMap.put("java/lang/Byte", BYTE_TYPE); numberCoercionMap.put("java/lang/Short", SHORT_TYPE); numberCoercionMap.put("java/lang/Integer", INT_TYPE); numberCoercionMap.put("java/lang/Float", FLOAT_TYPE); numberCoercionMap.put("java/lang/Long", LONG_TYPE); } //This method is here for nested tables: [[I -> [I private static Type getEntryType( Type array ){ return Type.getType( array.getInternalName().substring(1) ); } /** * Tells if a null value can be coerced into the target class * * (Only returns true on non boxed objects, apart from Boolean, * that is evaluated like the Lua standard) * * @param into The target class * @return Whether it is possible to coerce a null value to the target class */ public static boolean canCoerceNull( Type into ){ if ( into.getSort() == Type.OBJECT ){ String clazz = into.getInternalName(); if ( numberCoercionMap.containsKey(clazz) ) return false; if ( clazz.equals(CHAR) ) return false; return true; } return false; } /** * Returns the type required to be on the stack to coerce it into the target type. * * @param type The target type * @return The type required on the stack */ public static Type getCoercedType( Type type ){ switch( type.getSort() ){ //Primitives case Type.BOOLEAN: return OBJ_BOOLEAN; //Java numbers are coerced from Double objects case Type.BYTE: case Type.CHAR: case Type.SHORT: case Type.INT: case Type.FLOAT: case Type.LONG: case Type.DOUBLE: return OBJ_DOUBLE; case Type.OBJECT: String clazzName = type.getInternalName(); //Non primitive numbers object are coerced from Double objects if ( numberCoercionMap.containsKey(clazzName) ) return OBJ_DOUBLE; return type; //Arrays are coerced from LuaTables case Type.ARRAY: return OBJ_TABLE; default: throw new IllegalArgumentException(); } } /** * Tells whether the method passes is a valid @LuaMethod * * (Its return type is int, and only the last parameter is a CallFrame) * @param method * @return */ public static final boolean isMethodSpecial( Method method ){ if ( !method.isAnnotationPresent( LuaMethod.class ) || method.isVarArgs() ) return false; Type[] rTypes = Type.getArgumentTypes(method); Type rType = Type.getReturnType(method); //Check for integer return type if ( rType != Type.INT_TYPE ) return false; //Check for CallFrame parameter int params = rTypes.length; if ( params == 0 ) return false; Type last = rTypes[params -1]; if ( last.getSort() != Type.OBJECT || !last.getInternalName().equals(FRAME) ) return false; return true; } //Instance protected int frameArgIndex = -1; public CoercionAdapter(MethodVisitor mv, int access, String name, String desc) { super(mv, access, name, desc); } public CoercionAdapter(ClassVisitor cw, int access, String name, String desc){ super(cw.visitMethod(access, name, desc, null, null), access, name, desc); } //Utility public void push0(){ visitInsn(ICONST_0); } public void push1(){ visitInsn(ICONST_1); } private void visitIfValid(Label label) { if ( label != null ) visitLabel(label); } //Java calls public void callJava( Type clazz, Method method ){ boolean isStatic = AsmHelper.isStatic(method); boolean isSpecial = isMethodSpecial(method); boolean isVararg = method.isVarArgs(); int callType = INVOKESTATIC; String owner = clazz.getInternalName(); Type pTypes[] = Type.getArgumentTypes(method); //Non static calls require an instance, and INVOKEVIRTUAL if ( !isStatic ){ pushSelfArg(clazz); callType = INVOKEVIRTUAL; if ( AsmHelper.isInterfaceMethod(method) ) callType = INVOKEINTERFACE; } //Extract parameters to the stack int params = pTypes.length; int off = 1; if ( isVararg || isSpecial ) //Last parameter is handled differently params -= 1; if ( isStatic ) //No instance required for static methods off -= 1; //Extract parameters for ( int index = 0; index < params; index++ ) coerceFrameArg(index + off, pTypes[index]); //Extract varargs if ( isVararg ) coerceFrameVarargs(params, pTypes[params]); //Push the callframe if ( isSpecial ) loadArg(frameArgIndex); //Call visitMethodInsn(callType, owner, method.getName(), Type.getMethodDescriptor(method)); if ( isSpecial ) //Special methods manage returning themselves return; //Check if there are arguments to return Type rType = Type.getReturnType(method); if ( rType != Type.VOID_TYPE ) { varToLua(rType); //Coerce return, and push on CallFrame popToFrame(); push1(); } else { push0(); } } public void callOverload( Type clazz, List<Method> methods ){ List<OverloadRule> rules = OverloadResolver.resolve(methods); OverloadRule lastRule = rules.get( rules.size() -1 ); boolean isStatic = AsmHelper.isStatic( lastRule.method ); //Start processing rules, and storing variables int lastParamCount = -1; Label nextArgBranch = null; Label nextValueBranch = null; Label finish = new Label(); //Extract parameter count int argCount = newLocal(Type.INT_TYPE); //Extract frame.getArgCount pushFrameArgCount(); if ( !isStatic ){ push1(); math(SUB, INT_TYPE); } storeLocal(argCount); //Create branches based off rules for ( OverloadRule rule : rules ){ int paramCount = rule.paramCount; if ( lastParamCount != paramCount ){ //Argument count mismatch, new branch visitIfValid(nextArgBranch); nextArgBranch = new Label(); //Check argument count, on failure jump to next count check push(paramCount); loadLocal(argCount); ifICmp(LT, nextArgBranch); } if ( rule.paramType != null ){ //Check argument class visitIfValid(nextValueBranch); nextValueBranch = new Label(); pushFrameArg(rule.paramIndex + (isStatic ? 0 : 1), OBJ_OBJECT, true); //Check instance, if invalid jump to next type check instanceOf(getCoercedType(rule.paramType)); ifZCmp(IFEQ, nextValueBranch); } //Everything passed. Extract parameters from locals, and the frame callJava(clazz, rule.method); goTo(finish); //Prepare next rule lastParamCount = paramCount; } //Fail branch visitIfValid(nextArgBranch); visitIfValid(nextValueBranch); throwException(EXCEPTION, "Unable to resolve overloaded call"); //Finish visitLabel(finish); } //Frame access public void pushSelfArg( Type clazz ){ loadArg(frameArgIndex); push0(); //Fancy error messages push(clazz); push("self"); visitMethodInsn(INVOKEVIRTUAL, FRAME, "getNamedArg", "(ILjava/lang/Class;Ljava/lang/String;)Ljava/lang/Object;"); checkCast(clazz); } public void pushFrameArg( int index, Type type, boolean allowNull ){ loadArg(frameArgIndex); push(index); pushFrameArg(type, allowNull); } public void pushFrameArgCount(){ loadArg(frameArgIndex); visitMethodInsn(INVOKEVIRTUAL, FRAME, "getArgCount", "()I"); } public void popToFrame(){ loadArg(frameArgIndex); swap(); visitMethodInsn(INVOKEVIRTUAL, FRAME, "push", "(Ljava/lang/Object;)V"); } //Internals private void pushFrameArg( Type type, boolean allowNull ){ push(type); String method = allowNull ? "getArgNull" : "getArg"; visitMethodInsn(INVOKEVIRTUAL, FRAME, method, "(ILjava/lang/Class;)Ljava/lang/Object;"); } //Frame utils public void coerceFrameArg( int index, Type type ){ Type coerced = getCoercedType(type); //Pull the parameter on the stack pushFrameArg(index, coerced, canCoerceNull(type)); luaToVar(type); } public void coerceFrameVarargs( int from, Type arrayType ){ Type entry = getEntryType(arrayType); int array = newLocal(arrayType); int limit = newLocal(Type.INT_TYPE); int counter = newLocal(Type.INT_TYPE); /* * in frame * * limit = frame.getArgCount() - params * array = new array[limit] * * for ( int i = 0; i < limit; i++ ) * array[i] = coerceFrameArg( i + params, clazz ) * * push array */ Label loopBody = new Label(); Label loopEnd = new Label(); //Loop init pushFrameArgCount(); push(from); math(SUB, INT_TYPE); dup(); //frame.getArgCount() - params storeLocal(limit); newArray(entry); //new array[limit] storeLocal(array); push0(); storeLocal(counter); goTo(loopEnd); //Loop body visitLabel(loopBody); //Prepare array loadLocal(array); loadLocal(counter); //Pull argument from the stack loadArg(frameArgIndex); loadLocal(counter); push(from); math(ADD, INT_TYPE); pushFrameArg(getCoercedType(entry), canCoerceNull(entry)); //Store arrayStore(entry); iinc(counter, 1); //Loop end visitLabel(loopEnd); loadLocal(counter); loadLocal(limit); ifICmp(LT, loopBody); //'Return' loadLocal(array); } //Coercion public void luaToVar( Type type ){ switch( type.getSort() ){ case Type.BOOLEAN: case Type.DOUBLE: unbox(type); break; case Type.BYTE: case Type.SHORT: case Type.INT: unbox(INT_TYPE); cast(INT_TYPE, type); break; case Type.FLOAT: case Type.LONG: unbox(type); break; case Type.CHAR: unbox(INT_TYPE); //Double.intValue cast(INT_TYPE, CHAR_TYPE); //int -> char break; case Type.OBJECT: String clazz = type.getInternalName(); Type primitive = numberCoercionMap.get(clazz); if ( primitive != null ){ unbox(primitive); //Number.[int|double|float]Value valueOf(primitive); //[Int|Double|Float|...].valueOf } else if ( clazz.equals(CHAR) ){ unbox(INT_TYPE); cast(INT_TYPE, CHAR_TYPE); valueOf(CHAR_TYPE); } else { checkCast(type); } break; case Type.ARRAY: tableToArray(type); break; } } public void varToLua( Type type ){ switch( type.getSort() ){ case Type.BOOLEAN: case Type.DOUBLE: valueOf(type); break; case Type.BYTE: case Type.CHAR: case Type.SHORT: case Type.INT: case Type.FLOAT: case Type.LONG: cast(type, DOUBLE_TYPE); valueOf(DOUBLE_TYPE); break; case Type.OBJECT: String clazz = type.getInternalName(); if ( numberCoercionMap.containsKey(clazz) ){ unbox(DOUBLE_TYPE); //Number.doubleValue valueOf(DOUBLE_TYPE); //Double.valueOf } if ( clazz.equals(CHAR) ){ unbox(CHAR_TYPE); //Character -> char varToLua(CHAR_TYPE); //char -> Double } break; case Type.ARRAY: arrayToTable(type); break; } } public void tableToArray( Type type ){ checkCast(OBJ_TABLE); int array = newLocal(type); int table = newLocal(OBJ_TABLE); int limit = newLocal(INT_TYPE); int counter = newLocal(INT_TYPE); Type entry = getEntryType(type); Type cast = getCoercedType(entry); if ( type.getDimensions() > 1 ) cast = OBJ_TABLE; //Nested arrays require a LuaTable to get coerced /* * in table * * limit = table.maxN() * array = array[limit] * * for ( int i = 0; i < limit; i++ ) * array[i] = luaToVar( table.rawget( i +1 ) ) * * return array */ Label loopBody = new Label(); Label loopEnd = new Label(); Label valid = new Label(); //Loop init dup(); storeLocal(table); visitMethodInsn(INVOKEVIRTUAL, TABLE, "maxN", "()I"); dup(); storeLocal(limit); newArray(entry); // new array[maxN()] storeLocal(array); push0(); storeLocal(counter); goTo(loopEnd); //Loop body visitLabel(loopBody); // array[i] = luaToVar( table.rawget( i +1 ) ) loadLocal(array); loadLocal(counter); loadLocal(table); loadLocal(counter); push(1); math(ADD, INT_TYPE); visitMethodInsn(INVOKEVIRTUAL, TABLE, "rawget", "(I)Ljava/lang/Object;"); //Check validity dup(); instanceOf(cast); ifZCmp(IFNE, valid); throwException(EXCEPTION, "Unable to coerce to array. Value could not be coerced to descriptor: " + entry ); visitLabel(valid); //Coerce, store luaToVar(entry); arrayStore(entry); iinc(counter, 1); //Loop end visitLabel(loopEnd); loadLocal(counter); loadLocal(limit); ifICmp(LT, loopBody); //'Return' loadLocal(array); } public void arrayToTable( Type type ){ int array = newLocal(type); int table = newLocal(OBJ_TABLE); int limit = newLocal(INT_TYPE); int counter = newLocal(INT_TYPE); Type entry = getEntryType(type); /* * in array * * table = new table * for ( int i = 0; i < array.length; i++ ) * table.rawset( i +1, varToLua( array[i] ) ) * * return table */ Label loopBody = new Label(); Label loopEnd = new Label(); //Loop init dup(); storeLocal(array); arrayLength(); storeLocal(limit); push0(); storeLocal(counter); newInstance(OBJ_TABLE); dup(); visitMethodInsn(INVOKESPECIAL, TABLE, "<init>", "()V"); storeLocal(table); goTo(loopEnd); //Loop body visitLabel(loopBody); // table.rawset( counter +1, varToLua( array[counter] ) ) loadLocal(table); loadLocal(counter); push1(); math(ADD, INT_TYPE); loadLocal(array); loadLocal(counter); arrayLoad(entry); varToLua(entry); visitMethodInsn(INVOKEVIRTUAL, TABLE, "rawset", "(ILjava/lang/Object;)V"); iinc(counter, 1); //Loop end visitLabel(loopEnd); loadLocal(counter); loadLocal(array); arrayLength(); ifICmp(LT, loopBody); //'Return' loadLocal(table); } }
package codeWars; import java.util.Arrays; public class WeightSort { public static String orderWeight(String strng) { if("".equals(strng.trim())) return ""; StringBuilder result = new StringBuilder(); String[] numstr = strng.split(" "); int len = numstr.length; long[] nums = new long[len]; long[] weights = new long[len]; for(int i = 0 ; i<numstr.length ; i++){ nums[i] = Long.valueOf(numstr[i]); weights[i] = getWeight(nums[i]); } long tmp; String tmps; for(int i = 0 ; i<len ; i++){ for(int j = 0 ; j<len -1; j++){ if(weights[j]>weights[j+1]){ tmp = weights[j]; weights[j] = weights[j+1]; weights[j+1] = tmp; tmp = nums[j]; nums[j] = nums[j+1]; nums[j+1] = tmp; tmps = numstr[j]; numstr[j] = numstr[j+1]; numstr[j+1] = tmps; }else if(weights[j]==weights[j+1] && numstr[j].compareTo(numstr[j+1])>0){ tmp = weights[j]; weights[j] = weights[j+1]; weights[j+1] = tmp; tmp = nums[j]; nums[j] = nums[j+1]; nums[j+1] = tmp; tmps = numstr[j]; numstr[j] = numstr[j+1]; numstr[j+1] = tmps; } } } for(Long i : nums){ result.append(i); result.append(" "); } return result.toString().trim(); } private static int getWeight(long num){ int weight = 0; while (num>0){ weight+=num%10; num = num/10; } return weight; } }
package io.core9.plugin.widgets.widget; import io.core9.core.boot.BootStrategy; import io.core9.core.plugin.Core9Plugin; import io.core9.plugin.admin.AdminPlugin; import io.core9.plugin.server.VirtualHost; public interface WidgetAdminPlugin extends Core9Plugin, AdminPlugin, BootStrategy { void addVirtualHost(VirtualHost vhost); void removeVirtualHost(VirtualHost vhost); }
package skeleton; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(plugin= {"pretty","html:src/cucumber-reports","json:src/cucumber-reports/report1.json"},monochrome=true, dryRun=false, features= {"src/test/resources/skeleton/cucumberexpressiondemo.feature","src/test/resources/skeleton/login.feature"}) public class CucumberRunner { }
package lotro.my.xml; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import utils.Utils; public abstract class LogScraper { protected static final String LOREBOOK_URL = "http://lorebook.lotro.com/wiki/Special:LotroResource"; protected static final SimpleDateFormat HTML_DATE = new SimpleDateFormat ("MM/dd/yyyy h:mm a"); protected static final SimpleDateFormat USER_DATE = new SimpleDateFormat ("MMM dd yyyy"); // <td class="paginate_back"><< Back</td><td class="paginate_info"> Page: 1 of 187</td> private static final Pattern PAGES = Pattern.compile ("> Page: [0-9]+ of ([0-9]+)<"); // filter values: overview, level%20up, quest, deed, pvmp public void scrape (final String filter, final String charID) throws Exception { String page1 = scrape (filter, charID, 1); int pages = 1; Matcher m = PAGES.matcher (page1); if (m.find()) pages = Integer.parseInt (m.group (1)); int page = 2; while (page <= pages) { System.out.println ("Scraping " + page + " of " + pages + "..."); // TBD scrape (filter, charID, page++); } } protected abstract void parse (final String response); private String scrape (final String filter, final String charID, final int page) { Utils.sleep (Math.round (Math.random() * 8000)); // be nice HttpClient client = new HttpClient(); client.getHostConfiguration().setHost ("my.lotro.com", 80, "http"); PostMethod post = new PostMethod ("/wp-includes/widgets/ajax.php"); List<NameValuePair> args = new ArrayList<NameValuePair>(); args.add (new NameValuePair ("widget", "CharacterLog")); args.add (new NameValuePair ("CharacterLog_filter", filter)); args.add (new NameValuePair ("char_id", charID)); args.add (new NameValuePair ("world_id", "5")); // Landroval args.add (new NameValuePair ("page", page + "")); post.setRequestBody (args.toArray (new NameValuePair [args.size()])); String response = execute (client, post); parse (response); return response; } private static String execute (final HttpClient client, final HttpMethod method) { String response = null; try { method.setDoAuthentication (true); // method.setFollowRedirects (true); int statusCode = client.executeMethod (method); if (statusCode != HttpStatus.SC_OK) System.err.println ("Method failed: " + method.getStatusLine()); // Read the response body. Use caution: ensure correct character // encoding and is not binary data. response = method.getResponseBodyAsString(); } catch (HttpException x) { System.err.println ("Fatal protocol violation: " + x.getMessage()); x.printStackTrace(); } catch (IOException x) { System.err.println ("Fatal transport error: " + x.getMessage()); x.printStackTrace(); } finally { method.releaseConnection(); } return response; } }
package com.esum.as2; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.as2.msh.Configure; import com.esum.as2.msh.MessageListener; import com.esum.as2.msh.RetryProcessorFactory; import com.esum.as2.storage.RoutingInfoRecord; import com.esum.as2.storage.RoutingManager; import com.esum.as2.transaction.TransactionEvent; import com.esum.as2.transaction.TransactionProcessorFactory; import com.esum.framework.core.component.ComponentException; import com.esum.framework.core.component.ComponentManagerFactory; import com.esum.framework.core.exception.FrameworkException; import com.esum.framework.core.exception.SystemException; import com.esum.framework.http.HttpClientTemplateFactory; import com.esum.framework.net.http.server.tomcat.Tomcat70; /** * AS2 Processor 메인 클래스 * * Copyright(c) eSum Technologies, Inc. All rights reserved. */ public class AS2Processor { private Logger log = LoggerFactory.getLogger(AS2Processor.class); private Tomcat70 tomcatInstance = null; private RetryProcessorFactory retryProcessorFactory; /** * AS2를 시작하고, HTTP모듈을 동작시킨다. http context는 /as2/msh이다. * max.retry.count > 0이면 Retry Processor를 구동시킨다. */ public void startup(String home) throws SystemException, AS2Exception{ log.info("Starting AS2 Processor..."); log.info(Configure.TITLE); log.info("Initializing AS2 Processor..."); Configure.AS2_HOME = System.getProperty("as2.home", home); if(Configure.AS2_HOME == null || Configure.AS2_HOME.equals("")) throw new FrameworkException("init()", "System variable <as2.home> is null. Please set the system variable."); String configPath = Configure.AS2_HOME + File.separator + "conf" + File.separator; String defaultConfigFile = configPath + "config.properties"; Configure.init(defaultConfigFile); log.info("Initialized AS2 Processor."); RoutingManager.getInstance().init(); initTransactionHandler(); initHttp(configPath); if(Configure.RETRY_MAX_COUNT > 0){ log.info("Starting Message/MDN Retry Processor... Interval: " + Configure.RETRY_TIME_INTERVAL+", Max Count: " + Configure.RETRY_MAX_COUNT); retryProcessorFactory = new RetryProcessorFactory(); retryProcessorFactory.startup(); } log.info("Started AS2 Processor."); } private void initTransactionHandler() throws AS2Exception { log.debug("Initializing Transaction Processors."); Hashtable<String, RoutingInfoRecord> routingInfos = RoutingManager.getInstance().getAllRoutingInfo(); // start outbound transaction handler log.info("Creating Outbound Transaction Processors. Total {} routing.", routingInfos.size()); Iterator<String> i = routingInfos.keySet().iterator(); while(i.hasNext()){ String routingId = i.next(); RoutingInfoRecord rinfo = routingInfos.get(routingId); log.info("["+routingId+"] Outbound Transaction use a '"+rinfo.getMaxThreadCnt()+"' listeners."); TransactionProcessorFactory.getInstance().createTransactionProcessor( TransactionEvent.OUTBOUND_TRANSACTION, routingId, rinfo.getMaxThreadCnt()); } // start inbound transaction handler. log.info("Creating Inbound Transaction Processors. use a {} listeners.", Configure.INBOUND_TRANSACTION_THREAD_COUNT); TransactionProcessorFactory.getInstance().createTransactionProcessor( TransactionEvent.INBOUND_TRANSACTION, "", Configure.INBOUND_TRANSACTION_THREAD_COUNT); } /** * xTrus 와 함께 구동시 Shared Tomcat 을 공유하기 위해 추가 * xTrus 에서 구동하는 EmbeddedTomcat 의 Context 로 등록 되어 사용 가능 * ContextPath는 Default 로 /as2 를 사용 하고, * http.properties 와 ssl.properties 는 xTrus 의 설정 파일을 공유한다. * HttpClient 의 초기화도 수행 */ private void initHttp(String configPath) throws FrameworkException { log.info("Initializing HTTP/HTTPS configurations and Starting Embedded Tomcat"); Map<String, String> params = new HashMap<String, String>(); params.put("useAuth", Boolean.toString(Configure.USE_HTTP_AUTH)); params.put("componentId", "AS2"); try { params.put("nodeId", ComponentManagerFactory.currentComponentManager().getNodeId()); } catch (ComponentException e) { } try { tomcatInstance = Tomcat70.getInstance(); if (tomcatInstance == null) { tomcatInstance = Tomcat70.newInstance(); } tomcatInstance.createContext(Configure.CONTEXT_PATH, Configure.AS2_HOME, "msh", params, new MessageListener()); } catch (Exception e) { throw new FrameworkException("initHttp()", "Embedded Tomcat initialize error. "+e.getMessage(), e); } log.info("Initialiized HTTP/HTTPS configurations and Started Embedded Tomcat successfully."); } /** * AS2 Engine을 종료한다. */ public void shutdown() throws AS2Exception,FrameworkException{ log.info("Shutdowning AS2 Processor..."); TransactionProcessorFactory.getInstance().closeAll(); if(retryProcessorFactory != null) { retryProcessorFactory.close(); } if (tomcatInstance != null) { tomcatInstance.removeContext(Configure.CONTEXT_PATH); tomcatInstance = null; } List<String> usedNames = new ArrayList<String>(); Iterator<String> i = HttpClientTemplateFactory.getInstance().resuableIterator(); while(i.hasNext()) { String name = i.next(); if(name.startsWith("AS2")) usedNames.add(name); } for(String name : usedNames) { HttpClientTemplateFactory.getInstance().removeHttpClientTemplate(name); } log.info("Shutdowned AS2 Processor."); } }
package view.insuranceSystemView.rewardView.payJudger; import java.awt.Color; import java.awt.event.ActionListener; import view.aConstant.InsuranceSystemViewConstant; import view.component.BasicLabel; import view.component.SeparateLine; import view.component.button.ActionButton; import view.component.button.LinkButton; import view.component.group.StaticGroup; import view.component.textArea.InputTextArea; import view.insuranceSystemView.absInsuranceSystemView.InsuranceSystemView; @SuppressWarnings("serial") public class WritePayJudgeReportView extends InsuranceSystemView{ // Static public enum EActionCommands {WritePayJudgeReport, SavePayJudgeData} // Attribute private InputTextArea payJudgeTTA, judgementEvidenceTTA, relatedLawTTA; public WritePayJudgeReportView(ActionListener actionListener) { this.addComponent(new BasicLabel("면/부책 결과 입력")); this.addComponent(new SeparateLine(Color.black)); this.payJudgeTTA = new InputTextArea("결과", "부책(보험사가 보험금을 부담합니다)", 3, 100); this.judgementEvidenceTTA = new InputTextArea("근거", "조사 결과 음주, 무면허 사고에 해당하지 아니하고 일반적인 사고에 해당하기 때문임", 10, 100); this.relatedLawTTA = new InputTextArea("관련 법률", "면탈 행위(고지 의무 위반), 고의 사고인 경우 전부 면책에 해당하나 피고는 해당하지 않으므로 부책에 해당한다.", 10, 100); StaticGroup selectBtnGroup = new StaticGroup(new int[] {1, 1, 1}); selectBtnGroup.addGroupComponent(this.payJudgeTTA, this.judgementEvidenceTTA, this.relatedLawTTA); this.addComponent(selectBtnGroup); this.addComponent(new ActionButton("저장", EActionCommands.SavePayJudgeData.name(), actionListener)); this.addToLinkPanel( new LinkButton(InsuranceSystemViewConstant.SomeThingLookGreat, "", null), new LinkButton(InsuranceSystemViewConstant.SomeThingLookNide, "", null) ); } // Getter & Setter public String getPayJudgeTTA() {return payJudgeTTA.getContent();} public String getJudgementEvidenceTTA() {return judgementEvidenceTTA.getContent();} public String getRelatedLawTTA() {return relatedLawTTA.getContent();} }
package com.example.nnotnut.taximeters; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.renderscript.Double2; public class MyDbHelper extends SQLiteOpenHelper { private static final String DB_NAME = "Rate1.db"; private static final int DB_VERSION = 1; public static final String TABLE_NAME = "Rate"; public static final String SHORTWAY = "SHORTWAY"; public static final String LONGWAY = "LONGWAY" ; public static final String RATE_SER = "RATE_SER" ; public MyDbHelper(Context context){ super(context,DB_NAME,null,DB_VERSION); // SQLiteDatabase db = this.getWritableDatabase(); } @Override public void onCreate(SQLiteDatabase db) { // db = this.getWritableDatabase(); db.execSQL("CREATE TABLE "+TABLE_NAME +"(_id INTEGER PRIMARY KEY AUTOINCREMENT,"+SHORTWAY +" TEXT," +LONGWAY+" TEXT, "+RATE_SER+" TEXT); "); // insert("1","10","5.5"); // db.execSQL("CREATE TABLE "+TABLE_NAME +"("+SHORTWAY +"TEXT," +LONGWAY+"TEXT, "+RATE_SER+"TEXT) "); // ContentValues ct = new ContentValues(); // ct.put(SHORTWAY,"1"); // ct.put(LONGWAY,"10"); // ct.put(RATE_SER,"5.5"); // db.insert(TABLE_NAME, null,ct); db.execSQL("INSERT INTO "+TABLE_NAME+"("+SHORTWAY+","+LONGWAY+","+RATE_SER+") VALUES('0','1','35');"); db.execSQL("INSERT INTO "+TABLE_NAME+"("+SHORTWAY+","+LONGWAY+","+RATE_SER+") VALUES('0','10','5.5');"); db.execSQL("INSERT INTO "+TABLE_NAME+"("+SHORTWAY+","+LONGWAY+","+RATE_SER+") VALUES('10','20','6.5');"); db.execSQL("INSERT INTO "+TABLE_NAME+"("+SHORTWAY+","+LONGWAY+","+RATE_SER+") VALUES('20','40','7.5');"); db.execSQL("INSERT INTO "+TABLE_NAME+"("+SHORTWAY+","+LONGWAY+","+RATE_SER+") VALUES('40','60','8');"); db.execSQL("INSERT INTO "+TABLE_NAME+"("+SHORTWAY+","+LONGWAY+","+RATE_SER+") VALUES('60','80','9');"); db.execSQL("INSERT INTO "+TABLE_NAME+"("+SHORTWAY+","+LONGWAY+","+RATE_SER+") VALUES('80','10000','10.5');"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } // public void insert(String shortway , String longway , String rate){ // SQLiteDatabase db = this.getWritableDatabase(); // ContentValues ct = new ContentValues(); // ct.put(SHORTWAY,shortway); // ct.put(LONGWAY,longway); // ct.put(RATE_SER,rate); // long result = db.insert(TABLE_NAME,null,ct); // if(result == -1) { // return false; // } // else{ // return true; // } // } // public boolean insertData(String shortway,String longway,String rate_ser) { // SQLiteDatabase db = this.getWritableDatabase(); // ContentValues contentValues = new ContentValues(); // contentValues.put(SHORTWAY,shortway); // contentValues.put(LONGWAY,longway); // contentValues.put(RATE_SER,rate_ser); // long result = db.insert(TABLE_NAME,null ,contentValues); // if(result == -1) // return false; // else // return true; // } // // public Cursor getAllData() { // SQLiteDatabase db = this.getWritableDatabase(); // Cursor res = db.rawQuery("select * from "+TABLE_NAME,null); // return res; // } // // public boolean updateData(String id,String shortway,String longway,String rate_ser) { // SQLiteDatabase db = this.getWritableDatabase(); // ContentValues contentValues = new ContentValues(); //// contentValues.put(COL_1,id); // contentValues.put(SHORTWAY,shortway); // contentValues.put(LONGWAY,longway); // contentValues.put(RATE_SER,rate_ser); // db.update(TABLE_NAME, contentValues, "ID = ?",new String[] { id }); // return true; // } // // public Integer deleteData (String id) { // SQLiteDatabase db = this.getWritableDatabase(); // return db.delete(TABLE_NAME, "ID = ?",new String[] {id}); // } //public double getservice(int id,String shortway,String longway){ // // mDb = mHelper.getReadableDatabase(); // // cursor = mDb.query(mHelper.TABLE_NAME, // a. table // COLUMNS, // b. column names // " id = ?", // c. selections // new String[] { String.valueOf(id) }, // d. selections args // null, // e. group by // null, // f. having // null, // g. order by // null); // h. limit // if (cursor != null) // cursor.moveToFirst(); // //// result = Double.valueOf(cursor.getString(3)); // // // // // return result; //} public Cursor getAllData() { SQLiteDatabase db = this.getWritableDatabase(); Cursor res = db.rawQuery("select * from "+TABLE_NAME,null); return res; } }
package sch.frog.calculator.compile.semantic.exec.exception; import sch.frog.calculator.exception.CalculatorException; public class ExecuteException extends CalculatorException{ private static final long serialVersionUID = 1L; public ExecuteException(String msg){ super(msg); } }
package se.ade.autoproxywrapper.events; import se.ade.autoproxywrapper.ProxyMode; /** * Created by adrnil on 17/12/14. */ public class SetEnabledEvent { public boolean enabled; public SetEnabledEvent(boolean enabled) { this.enabled = enabled; } }
package com.lgbear.weixinplatform.base.typeeditor; import java.beans.PropertyEditorSupport; import org.apache.commons.lang3.StringUtils; public class DoubleTypeEditor extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { if (StringUtils.isEmpty(text)) text = "0"; setValue(Double.valueOf(text)); } }
package com.nisira.core.entity; import com.nisira.annotation.ClavePrimaria; import com.nisira.annotation.Columna; import com.nisira.annotation.Tabla; import com.google.gson.annotations.SerializedName; import com.thoughtworks.xstream.annotations.XStreamAlias; import java.io.Serializable; import java.util.ArrayList; @Tabla(nombre = "CONFIGSMTP") @XStreamAlias("CONFIGSMTP") public class Configsmtp implements Serializable { @ClavePrimaria @Columna @SerializedName("id") @XStreamAlias("ID") private String id = "" ; @Columna @SerializedName("mail_smtp_host") @XStreamAlias("MAIL_SMTP_HOST") private String mail_smtp_host = "" ; @Columna @SerializedName("mail_smtp_starttls_enable") @XStreamAlias("MAIL_SMTP_STARTTLS_ENABLE") private String mail_smtp_starttls_enable = "" ; @Columna @SerializedName("mail_smtp_port") @XStreamAlias("MAIL_SMTP_PORT") private String mail_smtp_port = "" ; @Columna @SerializedName("mail_smtp_mail_sender") @XStreamAlias("MAIL_SMTP_MAIL_SENDER") private String mail_smtp_mail_sender = "" ; @Columna @SerializedName("mail_smtp_user") @XStreamAlias("MAIL_SMTP_USER") private String mail_smtp_user = "" ; @Columna @SerializedName("mail_smtp_auth") @XStreamAlias("MAIL_SMTP_AUTH") private String mail_smtp_auth = "" ; @Columna @SerializedName("mail_smtp_password") @XStreamAlias("MAIL_SMTP_PASSWORD") private String mail_smtp_password = "" ; @Columna @SerializedName("asunto") @XStreamAlias("ASUNTO") private String asunto = "" ; @Columna @SerializedName("mensaje") @XStreamAlias("MENSAJE") private String mensaje = "" ; /* Sets & Gets */ public void setId(String id) { this.id = id; } public String getId() { return this.id; } public void setMail_smtp_host(String mail_smtp_host) { this.mail_smtp_host = mail_smtp_host; } public String getMail_smtp_host() { return this.mail_smtp_host; } public void setMail_smtp_starttls_enable(String mail_smtp_starttls_enable) { this.mail_smtp_starttls_enable = mail_smtp_starttls_enable; } public String getMail_smtp_starttls_enable() { return this.mail_smtp_starttls_enable; } public void setMail_smtp_port(String mail_smtp_port) { this.mail_smtp_port = mail_smtp_port; } public String getMail_smtp_port() { return this.mail_smtp_port; } public void setMail_smtp_mail_sender(String mail_smtp_mail_sender) { this.mail_smtp_mail_sender = mail_smtp_mail_sender; } public String getMail_smtp_mail_sender() { return this.mail_smtp_mail_sender; } public void setMail_smtp_user(String mail_smtp_user) { this.mail_smtp_user = mail_smtp_user; } public String getMail_smtp_user() { return this.mail_smtp_user; } public void setMail_smtp_auth(String mail_smtp_auth) { this.mail_smtp_auth = mail_smtp_auth; } public String getMail_smtp_auth() { return this.mail_smtp_auth; } public void setMail_smtp_password(String mail_smtp_password) { this.mail_smtp_password = mail_smtp_password; } public String getMail_smtp_password() { return this.mail_smtp_password; } public void setAsunto(String asunto) { this.asunto = asunto; } public String getAsunto() { return this.asunto; } public void setMensaje(String mensaje) { this.mensaje = mensaje; } public String getMensaje() { return this.mensaje; } /* Sets & Gets FK*/ }
package com.sapl.retailerorderingmsdpharma.adapter; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Build; import android.support.v4.graphics.drawable.RoundedBitmapDrawable; import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Base64; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.BitmapImageViewTarget; import com.sapl.retailerorderingmsdpharma.MyDatabase.TABLE_ORDER_DETAILS; import com.sapl.retailerorderingmsdpharma.MyDatabase.TABLE_TEMP_ORDER_DETAILS; import com.sapl.retailerorderingmsdpharma.R; import com.sapl.retailerorderingmsdpharma.activities.ActivityPreviewOrder; import com.sapl.retailerorderingmsdpharma.activities.ActivitySelection; import com.sapl.retailerorderingmsdpharma.activities.MyApplication; import com.sapl.retailerorderingmsdpharma.customView.CustomButtonRegular; import com.sapl.retailerorderingmsdpharma.customView.CustomEditTextMedium; import com.sapl.retailerorderingmsdpharma.customView.CustomTextViewMedium; import com.sapl.retailerorderingmsdpharma.models.OrderReviewModel; import java.util.List; import static android.content.Context.LAYOUT_INFLATER_SERVICE; /** * Created by MRUNAL on 07-Feb-18. */ public class ItemListAdapter extends RecyclerView.Adapter<ItemListAdapter.MyViewHolder> { private List<OrderReviewModel> orderReviewList; Context context; private static final String LOG_TAG = "ItemListAdapter"; String location = ""; public ItemListAdapter(Context context, List<OrderReviewModel> orderReviewList) { this.orderReviewList = orderReviewList; this.context = context; } public class MyViewHolder extends RecyclerView.ViewHolder { public CustomTextViewMedium txt_product_name, txt_price_of_product, txt_case_no, txt_bottle_no, txt_free_case_no, txt_free_bottle_no; public CustomTextViewMedium txt_case_label, txt_bottle_label, txt_free_case_label, txt_free_bottle_label; public ImageView img_product, img_edt, img_delete; public MyViewHolder(View view) { super(view); txt_product_name = view.findViewById(R.id.txt_product_name); txt_price_of_product = view.findViewById(R.id.txt_price_of_product); txt_case_no = view.findViewById(R.id.txt_case_no); txt_bottle_no = view.findViewById(R.id.txt_bottle_no); txt_free_case_no = view.findViewById(R.id.txt_free_case_no); txt_free_bottle_no = view.findViewById(R.id.txt_free_bottle_no); img_product = (ImageView) view.findViewById(R.id.img_product); img_edt = (ImageView) view.findViewById(R.id.img_edt); img_delete = (ImageView) view.findViewById(R.id.img_delete); txt_product_name.setTextColor(context.getResources().getColor(R.color.heading_background)); txt_case_no.setTextColor(context.getResources().getColor(R.color.heading_background)); txt_free_case_no.setTextColor(context.getResources().getColor(R.color.heading_background)); txt_bottle_no.setTextColor(context.getResources().getColor(R.color.heading_background)); txt_free_bottle_no.setTextColor(context.getResources().getColor(R.color.heading_background)); txt_price_of_product.setTextColor(context.getResources().getColor(R.color.heading_background)); txt_case_label = view.findViewById(R.id.txt_case_label); txt_bottle_label = view.findViewById(R.id.txt_bottle_label); txt_free_case_label = view.findViewById(R.id.txt_free_case_label); txt_free_bottle_label = view.findViewById(R.id.txt_free_bottle_label); txt_case_label.setTextColor(context.getResources().getColor(R.color.heading_background)); txt_bottle_label.setTextColor(context.getResources().getColor(R.color.heading_background)); txt_free_case_label.setTextColor(context.getResources().getColor(R.color.heading_background)); txt_free_bottle_label.setTextColor(context.getResources().getColor(R.color.heading_background)); img_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final int pos = getAdapterPosition(); if (pos != RecyclerView.NO_POSITION) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Confirm Delete") .setMessage("Do you want to delete order?") .setIcon(android.R.drawable.ic_delete) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { OrderReviewModel model = orderReviewList.get(pos); // long ret = TABLE_TEMP_ORDER_DETAILS.deletePreviewOrder(model.getItem_id(), MyApplication.get_session(MyApplication.SESSION_ORDER_ID)); MyApplication.logi(LOG_TAG, "in delete-->" + pos); orderReviewList.remove(pos); ItemListAdapter.this.notifyItemRemoved(pos); MyApplication.displayMessage(context, "Order deleted successfully."); } }).setNegativeButton("Cancel", null) // Do nothing on no .show(); } } }); img_edt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int pos = getAdapterPosition(); if (pos != RecyclerView.NO_POSITION) { OrderReviewModel model = orderReviewList.get(pos); // editOrder(model.getCase_no(), model.getFree_case_no(), // model.getBoittle_no(), model.getFree_bottle_no(), model.getPrice_of_product()); MyApplication.logi(LOG_TAG, "modellll->>" + model.toString()); editOrder(model, pos); } } }); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // get position int pos = getAdapterPosition(); if (pos != RecyclerView.NO_POSITION) { OrderReviewModel model = orderReviewList.get(pos); // ActivitySelection.txt_title_with_header.setText(MyApplication.get_session("item")); } } }); } } @Override public ItemListAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.adapter_item_list, parent, false); return new ItemListAdapter.MyViewHolder(itemView); } @Override public void onBindViewHolder(final ItemListAdapter.MyViewHolder holder, final int position) { final OrderReviewModel model = orderReviewList.get(position); MyApplication.logi(LOG_TAG, "model--->" + model); // MyApplication.set_session("model_item_id",model.getItem_id()); holder.img_delete.setTag(position); holder.img_product.clearAnimation(); holder.img_product.clearFocus(); holder.img_product.clearColorFilter(); // MyApplication.log("NAME: ----------> "+model.getName()+" ****************"); holder.txt_bottle_no.setText(model.getBoittle_no()); MyApplication.logi(LOG_TAG, "id ----->" + model.getItem_id()); MyApplication.logi(LOG_TAG, "getBoittle_no ----->" + model.getBoittle_no()); holder.txt_case_no.setText(model.getCase_no()); MyApplication.logi(LOG_TAG, "getBoittle_no ----->" + model.getCase_no()); holder.txt_free_case_no.setText(model.getFree_case_no()); holder.txt_free_bottle_no.setText(model.getFree_bottle_no()); MyApplication.logi(LOG_TAG, "PRODUCT NAME ----->" + model.getProduct_name()); holder.txt_product_name.setText(model.getProduct_name()); holder.txt_case_label.setText(MyApplication.get_session(MyApplication.SESSION_UOM_VALUE_FIRST)); holder.txt_bottle_label.setText(MyApplication.get_session(MyApplication.SESSION_UOM_VALUE_SECOND)); holder.txt_free_case_label.setText("Free " + MyApplication.get_session(MyApplication.SESSION_UOM_VALUE_FIRST)); holder.txt_free_bottle_label.setText("Free " + MyApplication.get_session(MyApplication.SESSION_UOM_VALUE_SECOND)); holder.txt_price_of_product.setText("₹ " + model.getPrice_of_product()); if (model.getProduct_img_path() == null) { Glide.with(context) .load(R.mipmap.msd_logo_1) .asBitmap() .error(R.mipmap.msd_logo_1) .placeholder(R.mipmap.msd_logo_1) .into(holder.img_product); } else { byte[] decodeString = Base64.decode(model.getProduct_img_path(), Base64.DEFAULT); Bitmap decodebitmap = BitmapFactory.decodeByteArray(decodeString, 0, decodeString.length); Glide.with(context) .load(decodeString) .asBitmap() .placeholder(R.drawable.arvind1) .into(holder.img_product); } /* Glide.with(context).load(context.getResources().getIdentifier(model.getProduct_img_path(), "drawable", context.getPackageName())) .asBitmap().centerCrop().into(new BitmapImageViewTarget(holder.img_product) { @Override protected void setResource(Bitmap resource) { RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), resource); circularBitmapDrawable.setCircular(true); holder.img_product.setImageDrawable(circularBitmapDrawable); } });*/ /*Glide.with(context) .load(context.getResources().getIdentifier(model.getDistImagePath(), "drawable", context.getPackageName())) .fitCenter() .into(holder.img_name);*/ // if (f.exists() && f.isFile()) { /* Glide.with(context).load(context.getResources().getIdentifier(model.getDistImagePath(), "drawable", context.getPackageName())) // .placeholder(R.drawable.ic_action_name) //.error(R.drawable.ic_action_name) .transform(new RoundedTransformation(70, 0, context.getResources().getIdentifier(model.getDistImagePath(), "drawable", context.getPackageName())) .resizeDimen(R.dimen.dp60, R.dimen.dp60) .centerCrop() .into(holder.img_name));*/ //} /* public int getImage(String imageName) { int drawableResourceId = this.getResources().getIdentifier(imageName, "drawable", this.getPackageName()); return drawableResourceId; }*/ } @Override public int getItemCount() { return orderReviewList == null ? 0 : orderReviewList.size(); } public void editOrder(final OrderReviewModel model, final int pos /*String caseNo, String freeCase, String bottleNo, String freeBottleNo, String price*/) { MyApplication.logi(LOG_TAG, "IN EDIT ORDER"); // LayoutInflater layoutInflater =LayoutInflater.from(context); LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); //(LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE); final View popupView = layoutInflater.inflate(R.layout.dialog_edit_order, null); final PopupWindow popupWindow = new PopupWindow(popupView, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT, true); popupWindow.setTouchable(true); popupWindow.setFocusable(true); popupWindow.setOutsideTouchable(false); popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0); final CustomEditTextMedium edt_case_no, edt_bottle_no, txt_free_case_no, txt_free_bottle_no; final CustomTextViewMedium txt_title, txt_product_name, txt_case_lable, txt_free_case_lable; final CustomTextViewMedium txt_bottle_lable, txt_free_bottle_lable; edt_case_no = popupView.findViewById(R.id.edt_case_no); edt_bottle_no = popupView.findViewById(R.id.edt_bottle_no); txt_title = popupView.findViewById(R.id.txt_title); txt_product_name = popupView.findViewById(R.id.txt_product_name); txt_case_lable = popupView.findViewById(R.id.txt_case_lable); txt_free_case_lable = popupView.findViewById(R.id.txt_free_case_lable); txt_free_case_no = popupView.findViewById(R.id.txt_free_case_no); txt_bottle_lable = popupView.findViewById(R.id.txt_bottle_lable); txt_free_bottle_lable = popupView.findViewById(R.id.txt_free_bottle_lable); txt_free_bottle_no = popupView.findViewById(R.id.txt_free_bottle_no); edt_case_no.setText(model.getCase_no()); edt_bottle_no.setText(model.getBoittle_no()); txt_free_case_no.setText(model.getFree_case_no()); txt_free_bottle_no.setText(model.getFree_bottle_no()); txt_product_name.setText(model.getProduct_name()); txt_case_lable.setTextColor(context.getResources().getColor(R.color.heading_background)); txt_bottle_lable.setTextColor(context.getResources().getColor(R.color.heading_background)); txt_free_bottle_lable.setTextColor(context.getResources().getColor(R.color.heading_background)); txt_free_bottle_no.setTextColor(context.getResources().getColor(R.color.heading_background)); txt_free_case_no.setTextColor(context.getResources().getColor(R.color.heading_background)); txt_free_case_lable.setTextColor(context.getResources().getColor(R.color.heading_background)); ImageView img_back = (ImageView) popupView.findViewById(R.id.img_back); img_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { popupWindow.dismiss(); } }); CustomButtonRegular btn_update = popupView.findViewById(R.id.btn_update); // if button is clicked, close the custom dialog btn_update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { model.setBoittle_no("" + edt_bottle_no.getText().toString().trim()); model.setCase_no("" + edt_case_no.getText().toString().trim()); model.setFree_bottle_no("" + txt_free_bottle_no.getText().toString().trim()); model.setFree_case_no("" + txt_free_case_no.getText().toString().trim()); double single_case_value_after_discount = model.getDiscounted_single_case_rate(); double single_btl_value_after_discount = model.getSingle_btl_price(); int edited_case_value = 0, edited_btl_value = 0; if (!edt_case_no.getText().toString().trim().equalsIgnoreCase("")) { edited_case_value = Integer.parseInt(edt_case_no.getText().toString().trim()); model.setCase_no(edited_case_value + ""); } if (!edt_bottle_no.getText().toString().trim().equalsIgnoreCase("")) { edited_btl_value = Integer.parseInt(edt_bottle_no.getText().toString().trim()); model.setBoittle_no(edited_btl_value + ""); } double final_case_val = single_case_value_after_discount * edited_case_value; double final_btl_val = single_btl_value_after_discount * edited_btl_value; MyApplication.logi(LOG_TAG, "final_case_val" + final_case_val); MyApplication.logi(LOG_TAG, "final_btl_val" + final_btl_val); double total_price_of_product = Double.parseDouble(String.valueOf(final_btl_val + final_case_val)); MyApplication.logi(LOG_TAG, "total_price_of_product--------" + total_price_of_product); String amt1 = String.format("%.2f", total_price_of_product); MyApplication.logi(LOG_TAG, "amt1 total_price_of_product--------" + amt1); model.setPrice_of_product(amt1); //model.setPrice_of_product(String.valueOf(final_btl_val + final_case_val)); long ret1 = TABLE_TEMP_ORDER_DETAILS.insertOrderDetails(MyApplication.get_session(MyApplication.SESSION_ORDER_ID), model.getItem_id(), model.getProduct_name(), String.valueOf(edited_case_value), String.valueOf(edited_btl_value), String.valueOf(single_btl_value_after_discount), String.valueOf(single_case_value_after_discount), Float.parseFloat(model.getPrice_of_product()), "0", "0", "update_data"); if (ret1 == 0) { MyApplication.logi(LOG_TAG, "TABLE_TEMP_ORDER_DETAILS successfully inserted " + ret1); Toast.makeText(context, "Updated data successfully...", Toast.LENGTH_SHORT).show(); } else { MyApplication.logi(LOG_TAG, "TABLE_TEMP_ORDER_DETAILS not successfully inserted " + ret1); } orderReviewList.remove(pos); ItemListAdapter.this.notifyItemRemoved(pos); orderReviewList.add(pos, model); ItemListAdapter.this.notifyDataSetChanged(); ItemListAdapter.this.notifyItemInserted(pos); popupWindow.dismiss(); MyApplication.displayMessage(context, "Order is successfully updated."); String sum = TABLE_TEMP_ORDER_DETAILS.getSumOfAllItems(MyApplication.get_session(MyApplication.SESSION_ORDER_ID)); ActivityPreviewOrder.txt_total_price.setText("₹" + sum); } }); edt_case_no.setMinWidth(20); edt_bottle_no.setMinWidth(20); txt_free_case_no.setMinWidth(20); txt_free_bottle_no.setMinWidth(20); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { edt_case_no.setBackground(context.getResources().getDrawable(R.drawable.border_background)); edt_bottle_no.setBackground(context.getResources().getDrawable(R.drawable.border_background)); txt_free_case_no.setBackground(context.getResources().getDrawable(R.drawable.border_background)); txt_free_bottle_no.setBackground(context.getResources().getDrawable(R.drawable.border_background)); } else { txt_free_case_no.setBackgroundResource(R.drawable.border_background); txt_free_bottle_no.setBackgroundResource(R.drawable.border_background); } } }
package org.esiea.boban_vilo.myapplication.model; import android.support.v7.app.AppCompatActivity; public class StatsModel extends AppCompatActivity { private String rank; private String player; private String games; private String fieldgoalpercentage; private String threeptpercentage; private String points; private String rebounds; private String assists; public StatsModel() { } public StatsModel(String rank, String player, String games, String fieldgoalpercentage, String threeptpercentage, String points, String rebounds, String assists) { this.rank = rank; this.player = player; this.games = games; this.fieldgoalpercentage = fieldgoalpercentage; this.threeptpercentage = threeptpercentage; this.points = points; this.rebounds = rebounds; this.assists = assists; } public String getRank() { return rank; } public void setRank(String rank) { this.rank = rank; } public String getPlayer() { return player; } public void setPlayer(String player) { this.player = player; } public String getGames() { return games; } public void setGames(String games) { this.games = games; } public String getFieldgoalpercentage() { return fieldgoalpercentage; } public void setFieldgoalpercentage(String fieldgoalpercentage) { this.fieldgoalpercentage = fieldgoalpercentage; } public String getThreeptpercentage() { return threeptpercentage; } public void setThreeptpercentage(String threeptpercentage) { this.threeptpercentage = threeptpercentage; } public String getPoints() { return points; } public void setPoints(String points) { this.points = points; } public String getRebounds() { return rebounds; } public void setRebounds(String rebounds) { this.rebounds = rebounds; } public String getAssists() { return assists; } public void setAssists(String assists) { this.assists = assists; } }
/* * 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 bookstore.GUI; import bookstore.BLL.NguoiDungBLL; import bookstore.Entity.NguoiDung; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JOptionPane; /** * * @author HieuNguyen */ public class jdDoiMatKhau extends javax.swing.JDialog { NguoiDungBLL obj = new NguoiDungBLL(); ArrayList<NguoiDung> lst = new ArrayList<>(); /** * Creates new form jdDoiMatKhau */ public jdDoiMatKhau(java.awt.Frame parent, boolean modal) { super(parent, modal); setIconImage(new ImageIcon(getClass().getResource("imgs/library.png")).getImage()); initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); btnHuy = new javax.swing.JButton(); btnDoiMatKhau = new javax.swing.JButton(); pw3 = new javax.swing.JPasswordField(); pw1 = new javax.swing.JPasswordField(); pw2 = new javax.swing.JPasswordField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Đổi Mật Khẩu"); jLabel1.setText("Mật Khẩu Hiện Tại:"); jLabel2.setText("Mật Khẩu Mới:"); jLabel3.setText("Nhập Lại Mật Khẩu Mới:"); btnHuy.setText("Hủy Bỏ"); btnHuy.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnHuyActionPerformed(evt); } }); btnDoiMatKhau.setText("Đổi Mật Khẩu"); btnDoiMatKhau.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDoiMatKhauActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(41, 41, 41) .addComponent(btnDoiMatKhau) .addGap(50, 50, 50) .addComponent(btnHuy, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(pw1) .addComponent(pw2) .addComponent(pw3, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(25, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(34, 34, 34) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(pw1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(pw2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(pw3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(34, 34, 34) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnHuy, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnDoiMatKhau, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(34, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnHuyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHuyActionPerformed // TODO add your handling code here: this.setVisible(false); }//GEN-LAST:event_btnHuyActionPerformed private void btnDoiMatKhauActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDoiMatKhauActionPerformed // TODO add your handling code here: try { String w = "taiKhoan = '" + frmDangNhap.taiKhoan + "' and matKhau = '" + pw1.getText()+ "'"; if (obj.getAll("", w, "").isEmpty()) { JOptionPane.showMessageDialog(this, "Sai mật khẩu hiện tại!"); pw1.setText(""); pw2.setText(""); pw3.setText(""); pw1.requestFocus(); } else if (pw2.getText().isEmpty() || pw3.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "Vui lòng nhập mật khẩu mới!"); pw2.setText(""); pw3.setText(""); pw2.requestFocus(); return; } else if (!pw2.getText().equals(pw3.getText())) { // System.out.println(pw2.getText()); // System.out.println(pw3.getText()); JOptionPane.showMessageDialog(this, "Mật khẩu mới không khớp"); pw2.setText(""); pw3.setText(""); pw2.requestFocus(); return; }else{ NguoiDung data = new NguoiDung(); data.setTaiKhoan(frmDangNhap.taiKhoan); data.setMatKhau(pw2.getText()); if(obj.updateData(data)){ JOptionPane.showMessageDialog(this, "Đổi mật khẩu thành công!"); obj.updateDataSave(data); }else{ JOptionPane.showMessageDialog(this, "Đổi mật khẩu thất bại!"); } } } catch (Exception e) { } this.setVisible(false); }//GEN-LAST:event_btnDoiMatKhauActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(jdDoiMatKhau.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(jdDoiMatKhau.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(jdDoiMatKhau.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(jdDoiMatKhau.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { jdDoiMatKhau dialog = new jdDoiMatKhau(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnDoiMatKhau; private javax.swing.JButton btnHuy; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPasswordField pw1; private javax.swing.JPasswordField pw2; private javax.swing.JPasswordField pw3; // End of variables declaration//GEN-END:variables }
/******************************************************************************* * Copyright 2014 See AUTHORS file. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 dk.sidereal.lumm.components.particlesystem; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.math.Vector2; import java.util.ArrayList; import dk.sidereal.lumm.architecture.Lumm; import dk.sidereal.lumm.architecture.LummObject; import dk.sidereal.lumm.architecture.core.AppData; /** * Emmits particles with a specific lifetime, being able to change multiple * particle logic behind individual particles. * * @author Claudiu */ public class ParticleEmitter { // region fields public boolean mustRemove = false; public boolean renderFirst; public float gravity; public float gravityRandomRange; public float timeBetweenParticles; public float timeBetweenParticlesRemaining; public float particleTime; public float particleTimeRandomRange; public Vector2 trajectory; public Vector2 trajectoryRandomRange; public Vector2 offsetPositionRandomRange; public Vector2 offsetPosition; public float speed; public float speedRandomRange; public float timeAlive; public float defaultTimeAlive; public float particlesPerSecond; public ArrayList<ParticleSpriteLayout> particleSources; public LummObject owner; public boolean enabled; // endregion fields // region constructors public ParticleEmitter(ArrayList<ParticleSpriteLayout> spriteSources, LummObject object) { this.renderFirst = true; this.enabled = true; if (object != null) { this.owner = object; } this.offsetPosition = new Vector2(); this.offsetPositionRandomRange = new Vector2(); this.particleSources = spriteSources; for (int i = 0; i < spriteSources.size(); i++) { String sprite = spriteSources.get(i).sprite; Lumm.assets.load(sprite, Texture.class); } speed = 10; speedRandomRange = 0; gravity = 0; gravityRandomRange = 0; particleTime = 2; particleTimeRandomRange = 0; timeAlive = 10; trajectory = new Vector2(); trajectoryRandomRange = new Vector2(2, 2); timeBetweenParticles = 0.5f; timeBetweenParticlesRemaining = 0; } public ParticleEmitter(ParticleEmitter emitter, LummObject obj) { this.mustRemove = emitter.mustRemove; this.renderFirst = emitter.renderFirst; this.gravity = emitter.gravity; this.gravityRandomRange = emitter.gravityRandomRange; this.timeBetweenParticles = emitter.timeBetweenParticles; this.timeBetweenParticlesRemaining = emitter.timeBetweenParticlesRemaining; this.trajectory = new Vector2(emitter.trajectory); this.trajectoryRandomRange = new Vector2(emitter.trajectoryRandomRange); this.offsetPositionRandomRange = new Vector2(emitter.offsetPositionRandomRange); this.offsetPosition = new Vector2(emitter.offsetPosition); // this.position = new Vector3(emitter.o); this.speed = emitter.speed; this.speedRandomRange = emitter.speedRandomRange; this.timeAlive = emitter.timeAlive; this.defaultTimeAlive = emitter.defaultTimeAlive; this.particleSources = new ArrayList<ParticleSpriteLayout>(emitter.particleSources); setOwner(obj); this.enabled = emitter.enabled; } // endregion constructors // region methods public void setTimeAlive(float timeAlive) { this.defaultTimeAlive = timeAlive; this.timeAlive = timeAlive; } public void restart() { this.timeAlive = this.defaultTimeAlive; } public void setOwner(LummObject object) { if (object != null) { this.owner = object; } } ParticleSpriteObject tempObject; public void run() { int particleSettings = ((Integer) Lumm.data.getSettings(AppData.Settings.PARTICLE_SETTINGS)); if (AppData.ParticleSettings.toString(particleSettings).equals(AppData.Settings.PARTICLE_SETTINGS_NONE)) return; if (timeAlive > 0) { timeAlive -= Lumm.time.getDeltaTime(); } if ((timeAlive != -1 && timeAlive <= 0) || !enabled) { return; } timeBetweenParticlesRemaining -= Lumm.time.getDeltaTime(); while (timeBetweenParticlesRemaining <= 0) { if (AppData.ParticleSettings.toString(particleSettings).equals(AppData.Settings.PARTICLE_SETTINGS_LOW)) { timeBetweenParticlesRemaining += timeBetweenParticles * 5; } else if (AppData.ParticleSettings.toString(particleSettings).equals(AppData.Settings.PARTICLE_SETTINGS_MEDIUM)) { timeBetweenParticlesRemaining += timeBetweenParticles * 2.5f; } else if (AppData.ParticleSettings.toString(particleSettings).equals(AppData.Settings.PARTICLE_SETTINGS_HIGH)) { timeBetweenParticlesRemaining += timeBetweenParticles * 1.8f; } else if (AppData.ParticleSettings.toString(particleSettings).equals(AppData.Settings.PARTICLE_SETTINGS_MAX)) { timeBetweenParticlesRemaining += timeBetweenParticles; } tempObject = new ParticleSpriteObject(owner.getScene(), this); tempObject.position.setRelative(0, 0, 30); } } // endregion methods }
package com.exam.zzz_other_menu_mysql; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.util.*; public class MySQLiteOpenHelper extends SQLiteOpenHelper { public MySQLiteOpenHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { Log.d("db_test", "oncreate"); String sql = "create table select_item ( " + "_id integer primary key autoincrement ," + " mart_name text , name text , price integer , amount integer , x double , y double , state integer , lat double , lon double)"; db.execSQL(sql); /* String sql2 = "create table small_item_info ( " + "_id integer primary key autoincrement ," + " name text , price integer)"; db.execSQL(sql2);*/ String sql3 = "create table large_item_info ( " + "_id integer primary key autoincrement ," + " name text)"; db.execSQL(sql3); String sql4 = "create table nfc_tag_item ( " + "_id integer primary key autoincrement ," + " name text , price integer , amount integer , x double , y double , state integer)"; db.execSQL(sql4); String sql5 = "create table small_mart_info ( " + "_id integer primary key autoincrement ," + " mart_name text , name text , price integer , amount integer , x double , y double , state integer , lat integer , lon integer)"; db.execSQL(sql5); String sql6 = "create table large_mart_info ( " + "_id integer primary key autoincrement ," + " name text)"; db.execSQL(sql6); String sql7 = "create table small_mart_info2 ( " + "_id integer primary key autoincrement ," + " name text , bookmarker integer)"; db.execSQL(sql7); String sql8 = "create table info_length ( " + "_id integer primary key autoincrement ," + " length integer , item_length integer)"; db.execSQL(sql8); /* String sql9 = "create table date_data ( " + "_id integer primary key autoincrement ," + " year text , month text , date text)"; db.execSQL(sql9); */ String sql9 = "create table date_data ( " + "_id integer primary key autoincrement ," + " year integer , month integer , date integer , hour integer , minute integer , second integer)"; db.execSQL(sql9); String sql10 = "create table intent_mart_name ( " + "_id integer primary key autoincrement ," + " name text)"; db.execSQL(sql10); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String sql = "drop table if exists select_mart"; db.execSQL(sql); /* String sql2 = "drop table if exists small_item_info"; db.execSQL(sql2);*/ String sql3 = "drop table if exists large_item_info"; db.execSQL(sql3); String sql4 = "drop table if exists nfc_tag_item"; db.execSQL(sql4); String sql5 = "drop table if exists small_mart_info"; db.execSQL(sql5); String sql6 = "drop table if exists large_mart_info"; db.execSQL(sql6); String sql7 = "drop table if exists small_mart_info2"; db.execSQL(sql7); String sql8 = "drop table if exists info_length"; db.execSQL(sql8); String sql9 = "drop table if exists date_data"; db.execSQL(sql9); String sql10 = "drop table if exists date_data"; db.execSQL(sql10); onCreate(db); } }
package course.chapter9.objects3; public class Customer { // fields private String firstName; private String lastName; private Account acc; // constructors public Customer(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public Customer() { this("John", "Doe"); } // methods void addAccount() { this.addAccount(0); } void addAccount(double initialBalance) { acc = new Account(); acc.accountId = Account.getNextId(); acc.balance = initialBalance; System.out.println(firstName + "'s" + " account has been created"); acc.display(); } public Account getAcc() { return acc; } public String Name() { return firstName + " " + lastName; } }
package br.com.youse.redditfeed.models; import java.io.Serializable; public class Posts implements Serializable { private long orderList; private String id; private String image; private String title; private String url; private int score; public long getOrderList() { return orderList; } public void setOrderList(long orderList) { this.orderList = orderList; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } }
package com.minhvu.proandroid.sqlite.database.main.presenter.view; import android.view.View; import com.minhvu.proandroid.sqlite.database.main.model.view.IMainModel; import com.minhvu.proandroid.sqlite.database.main.view.Adapter.NoteAdapter; import com.minhvu.proandroid.sqlite.database.main.view.Fragment.view.IMainView; /** * Created by vomin on 10/7/2017. */ public interface IMainPresenter { void onDestroy(boolean isChangingConfiguration); void loadData(); void onBindViewHolder(NoteAdapter.NoteViewHolder viewHolder, int position); void setModel(IMainModel model); void bindView(IMainView.View view); void AdapterOnClick(int position); void AdapterLongClick(View view, int position); int getDataCount(); void updateView(int requestCode); void updateAdapter(); void colorSort(int colorPos); void alphaSort(); void colorOrderSort(); void sortByModifiedTime(); void sortByImportant(); void userSignOutUpdate(); void userSignInUpdate(); }
// Lab 2 // // Released: 1/20/20 // // @Author Aaron Lack and alack // Last Edited: // // // Directions: Implement the following methods // // ////////////////////////////////////////////////////////////////////////////////// // Note: Do not need to explicitly import classes from java.lang but wanted to make it explicit // Goal - understand using Static classes - i.e. the Math class was not designed to be Instantiated (make objects) // It is a class that provides functionality and will be used to complete one of the methods import java.lang.Math; import java.util.Scanner; public class Lab2Exercises { // computes area of a square when given its side length public static int areaOfSquare(double sideLength) { double areaOfSquare = Math.pow(sideLength, 2); return (int) areaOfSquare; } // computes perimeter of a square when given its side length public static int perimeterOfSquare(double sideLength) { double perimeterOfSquare = sideLength * 4; return (int) sideLength; } // computes volume of a cubic when given its side length public static double volumeOfCube(double sideLength) { double volumeOfCube = Math.pow(sideLength, 3); return volumeOfCube; } // returns a String with two lines in the following format: // On Line1: "Length of one Side of Square is: * // On Line2: "Area: *, Perimeter: **, Volume: **** " where * refers to area, ** refers to // perimeter of square and *** refers to volume of the cube respectively. public static String printMeasurements(int value) { String meausrement = "Length of square: "+value+"\nArea: "+areaOfSquare(value) + " Perimeter: " + perimeterOfSquare(value) + " Volume: " + volumeOfCube(value); return meausrement; // Please reuse any of the functions defined above. } // given two points (x1,y1) and (x2,y2) return y intercept of the line public static int lineFunction(double x1, double y1, double x2, double y2) { double slope = (y2-y1) / (x2-x1); double yIntercept = y1 - (slope*x1); return (int) yIntercept; } // reads a number between 1000 and 1 Billion and prints it with commas (,) separating // every three digits. for example: 12317910 will be printed as $12,317,910 // hint use modulus (%) to save part of the number, then concatenate back together as a String public static String addCommas(int num) { // Take the quotient first, then the remander of a number. Then put a comma inbetween q and r. // return qutoint + , + remainder //I want the user to input a number //Convert input into a string //Use substring function (length) if (num >= 1000 && num <= 999999) { int quotientThousand = num/1000; int modThousand = num%1000; String thousandCombine = quotientThousand + "," + modThousand; return thousandCombine; } if (num >= 1000000 && num <= 999999999) { int quotientMillion1 = num/1000000; int modMillion1 = num%1000000; int quotientMillion2 = modMillion1/1000; //Breaks number up again so I can add commas int modMillion2 = modMillion1%1000; String millionCombine = quotientMillion1 + "," + quotientMillion2 + "," + modMillion2; return millionCombine; //I need to go back to the thousand if statement to add another comma for the remainder } if (num == 1000000000) { String billionCombine = "1,000,000,000"; return billionCombine; } return ""; //This is for a if condition is not satisfied. This will not crash the program. //Use scanner class again to } // test client // Use Scanner to read inputs from user. Don't use Scanner in above functions! // This is where we test our code. Call the functions public static void main(String[] args) { System.out.println(areaOfSquare(5.0)); System.out.println(perimeterOfSquare(5.0)); System.out.println(volumeOfCube(5.0)); Scanner sc = new Scanner(System.in); System.out.print("Please enter a measurement: "); System.out.println(printMeasurements(sc.nextInt())); System.out.println(lineFunction(0,5,4,9)); //int num = sc.nextInt(); System.out.print("Please enter a number: "); String res = addCommas(sc.nextInt()); System.out.println(res); //Questions int myInt = 7; double myDouble = 2.0; char myChar = 'a'; System.out.println(myInt*myChar); //1 System.out.println(myDouble*myChar); //2 System.out.println(Math.pow(myChar, 2)); //3 //Test cases work when I enter numbers such as 123,456,789; //Test cases do not work when I enter 100000. Ex: 1,0,0 is my outupt. How do I fix this? //Same with the billion conditional, why does it get mad at me? // int i = 10; // n = ++(i++); // System.out.println(++(i++) % 5); } } //Ask about question formatting. /////////////////////////////////// // // // ANSER THE FOLLOWING QUESTIONS // // // /////////////////////////////////// /* * Questions 1-3 are on explicit and implicit casting of some numerical types * * 1. What happens if you multiply an int with a char? * * Character 'a' has an ASCII value of 97, so when you multiply an integer with a char you get char, you get the integer product. In my test case, I got 679. * * * 2. What happens if you multiply a double with a char? * Again, the numeric values get multiplied and 'a'*2.0 returns 194.0, with the product being a double. * * 3. What happens if you square a char? * Squaring 'a' is the same as 97 squared so I got a value of 9409.0, with the product also being a double. * * 4. What happens if a method has a parameter of type int, but you pass it a char? * * (Just an example) public static String addCommas(int num) * String is the return type, num is the parameter. * You need to pass in a character because an error message will get thrown if you pass in an integer. * * 5. What happens if a method has a parameter of type char, but you pass it an int? * * You need to pass in an integer, you should pass whatever the data type for the parameter is asking. For example, if you pass in a character, an error message will return because of the mixing data types. If you pass in an integer, the program should compile because of matching data types. * * 6. What is the difference between two floating point primitive data types in the Java?\ * * There are two floating point primitive data types in Java. The first is float, and the other one is double. The main difference between them is a float the the size of the data types. A float has a range of +/- 10E38 with a 7 decimal place precision and has a size of 4 bytes. A double has a range of +/- 10E308 with a 15 decimal place precision and has a size of 8 bytes. * * 7. Consider the following code snippet. * int i = 10; * n = ++(i++); * System.out.println(++(i++) % 5); * * Without Compiling the Program: * What {do you think} are the values of i and n if the code is executed? * * I think the value is going to be 11 because the ++ operator increments the integer value by 1. * * What are the final value printed? * Now Compile and Run the Program to check your answers. If they are different, explain why * and provide updated code! * * Turns out I was wrong. The final answer was an error: Unresolved compilation problems, n cannot be resolved to a variable. Invalid argument to operation ++/--. */
package com.tech.interview.siply.redbus.entity.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.tech.interview.siply.redbus.constant.FuelType; import com.tech.interview.siply.redbus.constant.Status; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.util.Date; import java.util.UUID; @JsonIgnoreProperties(ignoreUnknown = true) @AllArgsConstructor @NoArgsConstructor @Getter @Setter public class BusDTO { private String name; private Status status; private String ownerName; private UUID ownerId; private Integer capacity; private String model; private String make; private Integer year; private Date registeredOn; private FuelType fuelType; private String registrationNo; private Boolean isPUCValid; }
/* * @(#) IComponentChannelInfoDAO.java * Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved. */ package com.esum.wp.ims.componentchannelinfo.dao; import java.util.List; import org.springframework.dao.DataAccessException; import com.esum.appframework.dao.IBaseDAO; import com.esum.appframework.exception.ApplicationException; /** * * @author heowon@esumtech.com * @version $Revision: $ $Date: $ */ public interface IComponentChannelInfoDAO extends IBaseDAO { List selectPageList(Object object) throws ApplicationException; }
package WebShop.model; import java.io.Serializable; import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; @Entity public class Client implements Serializable { private static final long serialVersionUID = 1L; public static final String USER_ROLE = "USER"; public static final String ADMIN_ROLE = "ADMIN"; @Id private String name; private String password; private String address; @ElementCollection(fetch = FetchType.EAGER) private Set<String> roles = new HashSet<>(); public Client() { roles.add(USER_ROLE); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Set<String> getRoles() { return Collections.unmodifiableSet(roles); } public void setRoles(Set<String> roles) { this.roles = roles; } public boolean isAdmin() { return roles.contains(ADMIN_ROLE); } public void setAdmin(boolean val) { if (val) roles.add(ADMIN_ROLE); else roles.remove(ADMIN_ROLE); } public boolean hasRole(String role) { return roles.contains(role); } public void addRole(String role) { roles.add(role); } public void removeRole(String role) { roles.remove(role); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Client other = (Client) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
package com.beike.service.merchant; import java.util.List; import com.beike.entity.goods.Goods; import com.beike.form.CashCouponForm; import com.beike.form.CouponForm; import com.beike.form.MerchantForm; import com.beike.page.Pager; /** * project:beiker * Title: * Description:商铺宝Service * Copyright:Copyright (c) 2011 * Company:Sinobo * @author qiaowb * @date Oct 31, 2011 5:31:48 PM * @version 1.0 */ public interface ShopsBaoService { /** * 通过商家ID查询商家详细信息 * @param merchantId * @return */ public MerchantForm getMerchantDetailById(Long merchantId); /** * 通过商家ID查询商家详细信息,商铺宝使用 * @param merchantId * @return */ public MerchantForm getShangpubaoDetailById(Long merchantId); /** * 根据品牌id获取优惠券数量 * @param merchantId * @return */ public int getCouponCount(Long merchantId); /** * 根据品牌id获取优惠券ID集合 * @param merchantId * @param pager * @return */ public List<Long> getCouponCountIds(Long merchantId, Pager pager); /** * 查询现金券 * @Title: getCashCoupon * @Description: TODO * @param @param merchantid 品牌ID * @param @param money 金额:100、50、20 * @param @return * @return List<MerchantForm> * @throws */ public CashCouponForm getCashCoupon(Long merchantid,Long money); /** * 查询该品牌的所有分店商品 * @Title: getChildMerchnatById * @Description: TODO * @param @param merchantId * @param @return * @return List<MerchantForm> * @throws */ public List<MerchantForm> getChildMerchnatById(Long merchantId); /** * 查询某品牌旗下的所有商品 带分页 * @Title: getGoodsCountIds * @Description: TODO * @param @param idsCourse * @param @param pager * @param @return * @return List<Long> * @throws */ public List<Long> getGoodsCountIds(String idsCourse, Pager pager); /** * 查询优惠券 * @Title: getCouponListByMerchantId * @Description: TODO * @param @param merchantId * @param @param top * @param @return * @return List<CouponForm> * @throws */ public List<CouponForm> getCouponListByMerchantId(Long merchantId, int top); /** * 查询该品牌下的置顶商品 * @Title: getGoodsByBrandId * @Description: TODO * @param @param merchantId * @param @return * @return Goods * @throws */ public Goods getGoodsByBrandId(Long merchantId); /** * 通过商品ID查询商家详细信息 * @param merchantId * @return * @author qiaowb 2011-11-12 */ public MerchantForm getMerchantDetailByGoodsId(Long goodsId); /** * @description:通过商品Id和交易Id查询商家信息 * @param goodsId * @param trx_order_id * @return MerchantForm * @throws */ public MerchantForm getCommMerchantDetail(String goodsId,String trx_order_id); /** * * @Title: getGoodsIdTotalCount * @Description: 查询热销商品总个数 * @param * @return int * @author wenjie.mai */ public int getGoodsIdTotalCount(String idsCourse); }
import java.util.Scanner; public class Main { private static Scanner terminal; public static void main(String[] args) { int number = -3; while(number < 1 || number > 3) { terminal = new Scanner(System.in); System.out.println("\n\n\t\t\tWelcome to American Airline Flight Reservation Center"); System.out.println("\n\tMenu: "); System.out.println("\tOption 1: Schedule Reservation"); System.out.println("\tOption 2: View Reservation"); System.out.println("\tOption 3: Exit System"); System.out.print("\n\tPlease enter option (integer): "); number = terminal.nextInt(); } switch(number) { case 1: Airline.populatefindFlights(); terminal = new Scanner(System.in); int num = 3; while(num != 0) { Airline.SearchFlight test = new Airline.SearchFlight(); test.getSearchData(); boolean found = test.getSearchResults(); if(found) { System.out.println("\n\t\t\tSEARCH RESULTS\n"); test.displayResults(); System.out.print("Enter the number of Flight you wish to book (1-" + (test.getList().size())+ "): "); int index = terminal.nextInt()-1; if(index >= 0 && index < test.getList().size()) { Flight reservedFlight = test.getList().get(index); if(reservedFlight.getAvailableSeats() <= 0){ System.out.println("Sorry! Not enough seats."); System.out.print("\nDo you want to search again?? (Enter 1 to try again): "); num = terminal.nextInt(); } else { System.out.print("\nSELECTED Flight: "+(index+1)+". "); reservedFlight.display(); System.out.println("\n\t\t\tENTER PASSENGER INFORMATION"); new Passenger.Person(reservedFlight); num = 0; } } else { System.out.print("ERROR: invalid"); System.out.print("\nDo you want to search again?? (Enter 1 to try again): "); num = terminal.nextInt(); } } else { System.out.print("Sorry! There are no Flights flying from " + test.getFrom() + " to " + test.getTo() + " on "); System.out.printf("%tD%n", test.getDepartureDate()); System.out.print("\nDo you want to search again?? (Enter 1 to try again): "); num = terminal.nextInt(); } } System.exit(0); case 2: int n = 1; Ticket.read(); System.out.print("\nWould you like to cancel your reservation? Press 1 for Yes or 2 for No: "); int delete = terminal.nextInt(); if(delete == n) { Ticket.cancelFlights(); } else Ticket.back(); System.exit(0); case 3: System.out.print("\n\tThank you for using our system!"); System.out.print("\n\tYou have exited the program.\n\n\n"); System.exit(0); } } }
package xyz.pozhu.lightvideo.bean; import android.os.Parcel; import android.os.Parcelable; public class Video implements Parcelable { private String title; private String path; public Video(){ } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(title); dest.writeString(path); } public Video(Parcel in) { this.title = in.readString(); this.path = in.readString(); } public static final Parcelable.Creator<Video> CREATOR = new Creator<Video>() { @Override public Video createFromParcel(Parcel source) { return new Video(source); } @Override public Video[] newArray(int size) { return new Video[size]; } }; }
// Session.java // Fait par : Simon Bouchard et Isabelle Angrignon // Fait le 2014-03-17 // Gestion des sessions des utilisateurs du serveur echoes package serveurweb; import java.net.*; import java.io.*; import java.text.*; import java.util.*; public class Session implements Runnable { BufferedReader reader; // Flux de texte PrintWriter writer; // Flux de texte Socket client; // Le client passé par le serveur int NumSession = 0; // Pour fin de suivi des connections Configuration maConf; // contient racine, index, listage final String NOMSERVEUR = "ServeurWeb IA & SB"; final String PROTOCOLE = "HTTP/1.0"; //Messages validation de fichiers: final String FICHIERTROUVE = "200 Okay"; final String ERREURREQUETE = "400 Requete erronee"; //|--------------------|// final String INTERDIT = "403 Interdit"; //| Message d'erreurs |// final String FICHIERNONTROUVE = "404 Non trouve"; //| |// final String PASIMPLEMENTE = "501 Non implemente"; //|--------------------|// // Constructeur public Session(Socket client , int NumeroSession , Configuration maConf) { this.maConf = maConf; // Le path est bon on le sait puisque le serveur l'a vérifié try { this.client = client; //////////////////////////////////////////////// reader = new BufferedReader( // On établie la connexion entre la session new InputStreamReader( client.getInputStream() ) ); // et le client , on établi aussi les writer = new PrintWriter( // flux de texte. les flux binaires new OutputStreamWriter( client.getOutputStream() ),true ); // seront instauré plus tard this.NumSession = NumeroSession; //////////////////////////////////////////////// } catch(IOException ioe) { System.out.println("On est dans marde"); } } // Affiche la liste de fichier a télécharger private void afficherListe(String rep) { File repertoire = new File(rep); String[] fichiers = repertoire.list(); writer.println("Contenu du repertoire " + rep); /////////////////////////////////////////////// if (fichiers != null) // Pour chaque fichier dans le { // path on appel la méthode afficher for (String fichier:fichiers) // info qui affichera de facon structurer { // le fichier afficherInfos(rep, fichier); // } // writer.println(fichiers.length + " fichier(s) disponible(s)"); //////////////////////////////////////////////// } } // Affiche la liste de fichier a télécharger private void afficherPageRepertoire(String rep) { String nomRep = rep;//nomRep est utilisé pour l'affichage sur une page web seulement if (rep.equals("/")) { nomRep = ""; } writer.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"); writer.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); writer.println("<head>"); writer.println("<meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\" />"); writer.println("<title>Path Index</title>"); writer.println(" </head>"); writer.println("<body>"); writer.println("<h1>Contenu du repertoire " +maConf.getRacine()+nomRep + "</h1>"); writer.println("<pre>"); File repertoire = new File(maConf.getRacine()+rep); String[] fichiers = repertoire.list(); if (fichiers != null) { for (String fichier:fichiers) /////////////////////////////////////////////// { // Pour chaque fichier dans le // path on appel la méthode afficher afficherInfos(rep, fichier); // info qui affichera de facon structurer // le fichier // } ////////////////////////////////////////////// writer.println(fichiers.length + " fichier(s) disponible(s)"); } writer.println("</pre>"); writer.println("</body>"); writer.println("</html>"); } // Sert a structurer la facon d'afficher les informations relier sur le fichier private void afficherInfos(String path, String fichier) { File f = new File(maConf.getRacine() + "\\" +path + "\\" + fichier); Date date = new Date(f.lastModified()); if(!path.equalsIgnoreCase("/") && !path.equalsIgnoreCase("\\") ) { path += "/"; } writer.println("<a href=\""+ path + f.getName() +"\">"); if (!f.isDirectory()) { writer.print(" "); writer.print(" "); writer.print(fichier + "</a> "+ f.length() + " " + getDateRfc822(date)); // Utilise printf vielle méthode du c writer.println(); } else { writer.printf("%-41s %tD %n", " [ ]" + fichier+"</a> " , f.lastModified()); // Utilise printf vielle méthode du c } } public void run () { boolean fini = false; try { // recevoir requete String maLigne; String ligne = maLigne = reader.readLine(); //Consommer l'entête du browser while (!ligne.equals("")) { ligne = reader.readLine(); } //envoi page TraitementRequete(maLigne); } catch(IOException ioe) { //Rien a faire } finally { ServeurWeb.NbrConnexion--; System.out.println("Fermeture de session " + NumSession); try { reader.close(); client.close(); } catch(IOException ioe) { } } } private void afficherPageErreur(String erreur) { File fichierErreur; switch (erreur) { case "ERREURREQUETE"://400 fichierErreur = new File("FichierServeur/400_Serveur_web.html"); break; case "INTERDIT"://403 fichierErreur = new File("FichierServeur/403_Serveur_web.html"); break; case "FICHIERNONTROUVE"://404 fichierErreur = new File("FichierServeur/404_Serveur_web.html"); break; case "PASIMPLEMENTE"://501 fichierErreur = new File("FichierServeur/501_Serveur_web.html"); break; default: fichierErreur = new File("FichierServeur/404_Serveur_web.html"); break; } writer.println(PROTOCOLE + " " + erreur); genererEntete(fichierErreur); traiterFichier(fichierErreur); } private void TraitementRequete (String ligne) { String[] laCommande = ligne.trim().split("\\s+"); if ( laCommande.length > 0 ) { switch (laCommande[0].toUpperCase()) { case "GET": if (laCommande.length == 3 ) { traiterRequeteGet(laCommande[1]); } else { afficherPageErreur(ERREURREQUETE); } try { client.close(); }catch(IOException ioe) { } break; case "HEAD": if (laCommande.length == 3 ) { traiterRequeteHead(laCommande[1]); } else { writer.println(PROTOCOLE + " " + ERREURREQUETE); } try { client.close(); }catch(IOException ioe) { } break; default: afficherPageErreur(PASIMPLEMENTE); try { client.close(); }catch(IOException ioe) { } } } else { afficherPageErreur(ERREURREQUETE); try { client.close(); }catch(IOException ioe) { } } } private void traiterRequeteGet(String nomFichier) { String path = maConf.getRacine() + nomFichier; if(validerFichier(path)) { File fichier = new File(path); if ( !fichier.isDirectory()) { genererEntete(fichier);//ajouter un head traiterFichier(fichier); } else { //generer entete est géré par traiter dossier traiterDossier(nomFichier); } } else { afficherPageErreur(FICHIERNONTROUVE); } } private void traiterRequeteHead(String nomFichier) { String path = maConf.getRacine() + "\\"+nomFichier; if(validerFichier(path)) { File fichier = new File(path); genererEntete(fichier);//ajouter un head } else { writer.println(PROTOCOLE + " " + FICHIERNONTROUVE); } } //cadeau du prof.... private String getDateRfc822(Date date) { SimpleDateFormat formatRfc822 = new SimpleDateFormat( "EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z", Locale.US ); return formatRfc822.format( date ); } private String getType(String extension) { switch(extension) { case "gif": return "image/gif"; case "html": return "text/html"; case "jpeg": return "image/jpeg"; case "jpg": return "image/jpeg"; case "png": return "image/png"; case "txt": return "text/plain"; default: return ""; } } private void genererEntete(File fichier) { String type =""; //PROTOCOLE + message réussite AFFICHÉ PLUS HAUT Date dateM = new Date(fichier.lastModified()); if(fichier.isFile()) { String extension = (fichier.getName().split("\\."))[1]; type = getType(extension); } Date dateJ = new Date(); writer.println("Server: " + NOMSERVEUR); writer.println("Date: "+ getDateRfc822(dateJ)); //Si le type n'est pas géré, la ligne sera omise... if (type.equals("")) { //il s'agit d'un dossier writer.println("Content-Type: " + "text/HTML"); } else { writer.println("Content-Type: " + type); } writer.println("Last-Modified: " + getDateRfc822(dateM)); if(fichier.length() != 0 ) { writer.println("Content-Length: " + fichier.length()); } writer.println(); } private void traiterFichier (File fichier) { int b = -1; boolean pasFini = true; try { //transfert en binaire BufferedInputStream in = new BufferedInputStream(new FileInputStream(fichier)); BufferedOutputStream out = new BufferedOutputStream(client.getOutputStream()); while (pasFini) { b = in.read(); if(b != -1) { out.write(b); } else { pasFini = false; } } in.close(); out.close(); } catch(IOException e) { e.printStackTrace(); } } private void traiterDossier(String rep) { File index = new File(maConf.getRacine() +"\\" + rep + "\\" + maConf.getNomIndex()); //serie de checks //si index.html existe if ((index.isFile())) { //afficher index.html genererEntete(index); traiterFichier(index); } else { //sinon si listage = false, if (!maConf.getListage()) { //afficher page 403 //générerEntete est géré par afficher page d'erreur afficherPageErreur(INTERDIT); } else { //sinon générer liste. genererEntete(index); afficherPageRepertoire(rep); } } } private boolean validerFichier(String nom) { File fichier = new File(nom); boolean existe = false; if (fichier.exists()) { writer.println(PROTOCOLE + " " + FICHIERTROUVE); existe = true; } return existe; } }
package com.chillcode.warOfFlags.util; import com.chillcode.warOfFlags.actors.Actor; public class GameUtils { /** * Returns a character representing given actor * Throws an IllegalArgumentException when given invalid input * * @param actor * @return */ public static char getChar(Actor actor) { throw new RuntimeException("Method not implemented!"); } /** * Returns a vector representing given direction * Throws an IllegalArgumentException when given invalid input * * @param dir * @return */ public static Vector toVector(Direction dir) { throw new RuntimeException("Method not implemented!"); } /** * Returns a direction converted from given vector * Throws an IllegalArgumentException when given invalid input * * @param vector * @return */ public static Direction toDirection(Vector vector) { if (vector.getX() == 0 && vector.getY() == -1) return Direction.UP; if (vector.getX() == 0 && vector.getY() == 1) return Direction.DOWN; if (vector.getX() == -1 && vector.getY() == 0) return Direction.LEFT; if (vector.getX() == 1 && vector.getY() == 0) return Direction.RIGHT; throw new IllegalArgumentException(); } /** * Returns a direction that is opposite to given direction * Throws an IllegalArgumentException when given invalid input * * @param dir * @return */ public static Direction inverted(Direction dir) { throw new RuntimeException("Method not implemented!"); } /** * Returns the amount of steps a player has to make in order to get from pos1 to pos2 * * @param pos1 * @param pos2 * @return */ public static int getDistance(Vector pos1, Vector pos2) { throw new RuntimeException("Method not implemented!"); } }
package org.point85.domain.plant; import java.util.HashSet; import java.util.Objects; import java.util.Set; import javax.persistence.AttributeOverride; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import org.point85.domain.dto.ReasonDto; import org.point85.domain.oee.TimeLoss; import org.point85.domain.persistence.TimeLossConverter; /** * The Reason class is the reason for an OEE time loss. * * @author Kent Randall * */ @Entity @Table(name = "REASON") @AttributeOverride(name = "primaryKey", column = @Column(name = "REASON_KEY")) public class Reason extends NamedObject { // the one and only root reason in the hierarchy public static final String ROOT_REASON_NAME = "All Reasons"; // parent reason @ManyToOne @JoinColumn(name = "PARENT_KEY") private Reason parent; // child reasons @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true) private final Set<Reason> children = new HashSet<>(); // loss category @Column(name = "LOSS") @Convert(converter = TimeLossConverter.class) private TimeLoss timeLoss; public Reason() { super(); } public Reason(String name, String description) { super(name, description); } public Reason(ReasonDto dto) { super(dto.getName(), dto.getDescription()); this.timeLoss = dto.getLossCategory() != null ? TimeLoss.valueOf(dto.getLossCategory()) : null; } public Reason getParent() { return this.parent; } public void setParent(Reason parent) { this.parent = parent; } public Set<Reason> getChildren() { return this.children; } public void addChild(Reason child) { if (!children.contains(child)) { children.add(child); child.setParent(this); } } public void removeChild(Reason child) { if (children.contains(child)) { children.remove(child); child.setParent(null); } } public TimeLoss getLossCategory() { return this.timeLoss; } public void setLossCategory(TimeLoss loss) { this.timeLoss = loss; } @Override public boolean equals(Object obj) { if (obj instanceof Reason) { return super.equals(obj); } return false; } @Override public int hashCode() { return Objects.hash(getName(), getLossCategory()); } @Override public String toString() { return super.toString() + ", Loss: " + getLossCategory(); } }
package br.com.saltypub.web.beer.hue; import org.springframework.data.repository.CrudRepository; public interface BeerHueRepository extends CrudRepository<BeerHue, Long> { }
package frc; import edu.wpi.first.wpilibj2.command.CommandBase; import edu.wpi.first.wpilibj2.command.Subsystem; /** * A {@link Command} that requires the subsystems passed to it, and does nothing * else. * * It never finishes on its own; be sure to cancel it once you want the * subsystems back. */ public class HoldSubsystems extends CommandBase { public HoldSubsystems(Subsystem... subsystems) { addRequirements(subsystems); } }
package com.alex.pets; public class Raccoon extends Pet implements Alive { public String name; public String breed; public Raccoon(String someName, String breed) { super(); this.name = someName; this.breed = breed; } public void rinsing() { if (isAlive) { System.out.println("Raccoon " + name + " is rinsing sock"); } else { System.out.println(":("); } } public void steal() { if (isAlive) { System.out.println("Raccoon " + name + " is steal food"); } else { System.out.println(":("); } } public void play() { if (isAlive) { System.out.println("Raccoon " + name + " is playing"); } else { System.out.println(":("); } } public String getName() { return name; } public String getBreed() { return breed; } public String toString() { return "Raccoon " + name; } }
package be.mxs.common.model.vo.healthrecord; import be.dpms.medwan.common.model.vo.administration.PersonVO; import be.dpms.medwan.common.model.vo.occupationalmedicine.ExaminationVO; import be.dpms.medwan.common.model.vo.occupationalmedicine.VerifiedExaminationVO; import be.dpms.medwan.webapp.wo.common.system.SessionContainerWO; import be.mxs.common.model.vo.IIdentifiable; import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.Vector; public class HealthRecordVO implements Serializable, IIdentifiable { private final PersonVO person; private final Collection transactions; private final Integer healthRecordId; private final Date dateBegin; private final Date dateEnd; private boolean updated=false; private String sortOrder; private Vector verifiedExaminations=null,otherverifiedExaminations=null; public Vector getVerifiedExaminations(SessionContainerWO sessionContainerWO,Vector myExaminations){ if(verifiedExaminations==null || updated){ verifiedExaminations=new Vector(); for(int n=0;n<myExaminations.size();n++){ ExaminationVO examinationVO = (ExaminationVO)myExaminations.elementAt(n); verifiedExaminations.add(new VerifiedExaminationVO(examinationVO.id.intValue(),healthRecordId+"",examinationVO.getMessageKey(),examinationVO.getTransactionType(),sessionContainerWO)); } } return verifiedExaminations; } public Vector getOtherVerifiedExaminations(SessionContainerWO sessionContainerWO,Vector myExaminations){ if(otherverifiedExaminations==null || updated){ otherverifiedExaminations=new Vector(); for(int n=0;n<myExaminations.size();n++){ ExaminationVO examinationVO = (ExaminationVO)myExaminations.elementAt(n); otherverifiedExaminations.add(new VerifiedExaminationVO(examinationVO.id.intValue(),healthRecordId+"",examinationVO.getMessageKey(),examinationVO.getTransactionType(),sessionContainerWO)); } } return otherverifiedExaminations; } public String getSortOrder(){ return sortOrder; } public void setSortOrder(String sortOrder){ this.sortOrder=sortOrder; } public boolean getUpdated(){ return updated; } public void setUpdated(boolean updated){ this.updated=updated; } public HealthRecordVO(PersonVO person, Collection transactionsVO, Integer healthRecordId, Date dateBegin, Date dateEnd) { this.person = person; this.transactions = transactionsVO; this.healthRecordId = healthRecordId; this.dateBegin = dateBegin; this.dateEnd = dateEnd; } public PersonVO getPerson() { return person; } public Collection getTransactions() { return transactions; } public Integer getHealthRecordId() { return healthRecordId; } public Date getDateBegin() { return dateBegin; } public Date getDateEnd() { return dateEnd; } public int hashCode() { if (healthRecordId != null){ return healthRecordId.hashCode(); } return 0; } }
package com.karya.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="uploadtemplate001mb") public class UploadTemplate001MB { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "id") private int id; @Column(name="content") private byte[] content; @Column(name="filename") private String filename; public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public int getId() { return id; } public void setId(int id) { this.id = id; } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } }
package com.example.test_2; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.security.acl.Group; import java.util.List; public class SelectedListTimetables extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.selected_timetables); init(); } public static Context Timetables; static com.airbnb.lottie.LottieAnimationView ProgressBarTimaTable; static Spinner spinner, spinner1, spinner2; Button btnListTable; Runnable run; Thread thread; TextView text; static TextView progresstext; public String Group; private DatabaseReference databaseReference; private void init() { ProgressBarTimaTable = findViewById(R.id.ProgresBarLoad); Timetables = SelectedListTimetables.this; spinner = findViewById(R.id.spinnerSelectedData); spinner1 = findViewById(R.id.spinnerSelectedData2); spinner2 = findViewById(R.id.spinnerSelectedData3); btnListTable = findViewById(R.id.BtnNext); text = findViewById(R.id.faculty); progresstext =findViewById(R.id.ProgressText); ParsingSelectSpinner parsingSelectSpinner = new ParsingSelectSpinner(); ButtonNext(); GetDataThread(); } private void GetDataThread() { final ParsingSelectSpinner parsingSelectSpinner = new ParsingSelectSpinner(); run = new Runnable() { @Override public void run() { parsingSelectSpinner.GetDataSpinner(); } }; thread = new Thread(run); thread.start(); new Thread(new Runnable() { @Override public void run() { while (thread.isAlive()) { try { Thread.sleep(1000); } catch (Exception e) { e.getMessage(); } Log.d("MyLog", "init: " + thread.isAlive()); } } }).start(); ProgressBarTimaTable.setVisibility(View.VISIBLE); } public void ButtonNext() { btnListTable.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("MyLog", "Start:\n" + LoginMain.table.getString("ValueFac", "Error") + "\n" + LoginMain.table.getString("ValueSpec", "Error") + "\n" + LoginMain.table.getString("ValueGroup", "Error")); if(spinner2.getSelectedItem()!=null){ setTimetablesFireBase(); }else { Toast.makeText(SelectedListTimetables.this,"Не выбран элемент",Toast.LENGTH_LONG).show(); } } }); } public void setTimetablesFireBase() { Group =spinner2.getSelectedItem().toString(); BaseGroup group = new BaseGroup(Group); databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()); databaseReference.child("GroupList").setValue(group).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ Intent next = new Intent(SelectedListTimetables.this, MainActivity.class); next.putExtra("ValueFac", LoginMain.table.getString("ValueFac", "404")); next.putExtra("ValueSpec", LoginMain.table.getString("ValueSpec", "404")); next.putExtra("ValueGroup", LoginMain.table.getString("ValueGroup", "404")); startActivity(next); finish(); } } }); } }
package org.squonk.camel.processor; import org.squonk.dataset.Dataset; import org.squonk.dataset.DatasetMetadata; import org.squonk.dataset.MoleculeObjectDataset; import org.squonk.http.RequestInfo; import org.squonk.types.MoleculeObject; import org.squonk.types.TypeResolver; import java.io.IOException; import java.util.Collections; import java.util.logging.Logger; import java.util.stream.Stream; /** * * <p> * Created by timbo on 26/03/2016. */ public abstract class AbstractMoleculeObjectRouteHttpProcessor extends AbstractMoleculeObjectHttpProcessor { private static final Logger LOG = Logger.getLogger(AbstractMoleculeObjectRouteHttpProcessor.class.getName()); protected final String routeUri; public AbstractMoleculeObjectRouteHttpProcessor( String routeUri, TypeResolver resolver, String[] inputMimeTypes, String[] outputMimeTypes, String statsRouteUri) { super(resolver, inputMimeTypes, outputMimeTypes, statsRouteUri); this.routeUri = routeUri; } protected abstract boolean isThin(RequestInfo requestInfo); protected MoleculeObjectDataset prepareDataset(MoleculeObjectDataset mods, boolean isThin) throws IOException { if (isThin) { // thin service so strip out everything except the molecule Dataset<MoleculeObject> dataset = mods.getDataset(); Stream<MoleculeObject> mols = dataset.getStream().map((mo) -> new MoleculeObject(mo.getUUID(), mo.getSource(), mo.getFormat())); DatasetMetadata oldMeta = dataset.getMetadata(); DatasetMetadata newMeta = new DatasetMetadata(MoleculeObject.class, Collections.emptyMap(), oldMeta == null ? 0 : oldMeta.getSize(), oldMeta == null ? Collections.emptyMap() : oldMeta.getProperties()); return new MoleculeObjectDataset(new Dataset<>(MoleculeObject.class, mols, newMeta)); } else { return mods; } } }
package io.projekat.pretraga; import java.util.Date; import java.util.List; import io.projekat.CitljivTerminIntervalInterfaceString; import io.projekat.sala.Sala; public class PretragaUpit implements CitljivTerminIntervalInterfaceString { private int response; private String datum; private Date datumF; private String pocetnoVreme; private Date pocetnoVremeF; private String vremeZavrsetka; private Date vremeZavrsetkaF; private List<String> objekat; private boolean sadrziProjektor; private boolean salaSaRacunarima; private int brojRacunara; private int brojMesta; private List<Sala> dostupneSale; public int getResponse() { return response; } public void setResponse(int response) { this.response = response; } public List<String> getObjekat() { return objekat; } public void setObjekat(List<String> objekat) { this.objekat = objekat; } public boolean isSadrziProjektor() { return sadrziProjektor; } public void setSadrziProjektor(boolean sadrziProjektor) { this.sadrziProjektor = sadrziProjektor; } public boolean isSalaSaRacunarima() { return salaSaRacunarima; } public void setSalaSaRacunarima(boolean salaSaRacunarima) { this.salaSaRacunarima = salaSaRacunarima; } public int getBrojRacunara() { return brojRacunara; } public void setBrojRacunara(int brojRacunara) { this.brojRacunara = brojRacunara; } public int getBrojMesta() { return brojMesta; } public void setBrojMesta(int brojMesta) { this.brojMesta = brojMesta; } public List<Sala> getDostupneSale() { return dostupneSale; } public void setDostupneSale(List<Sala> dostupneSale) { this.dostupneSale = dostupneSale; } public String getDatum() { return datum; } public void setDatum(String datum) { this.datum = datum; } public Date getDatumF() { return datumF; } public void setDatumF(Date datumF) { this.datumF = datumF; } public String getPocetnoVreme() { return pocetnoVreme; } public void setPocetnoVreme(String pocetnoVreme) { this.pocetnoVreme = pocetnoVreme; } public Date getPocetnoVremeF() { return pocetnoVremeF; } public void setPocetnoVremeF(Date pocetnoVremeF) { this.pocetnoVremeF = pocetnoVremeF; } public String getVremeZavrsetka() { return vremeZavrsetka; } public void setVremeZavrsetka(String vremeZavrsetka) { this.vremeZavrsetka = vremeZavrsetka; } public Date getVremeZavrsetkaF() { return vremeZavrsetkaF; } public void setVremeZavrsetkaF(Date vremeZavrsetkaF) { this.vremeZavrsetkaF = vremeZavrsetkaF; } @Override public String getKrajnjeVreme() { return getVremeZavrsetka(); } }
package com.example.root.proyecto_mapa.clases; import android.view.View; import android.widget.Toast; import java.util.ArrayList; public class DataParqueaderos { private ArrayList<Parqueadero> parqueaderos = null; private static DataParqueaderos data = null; private DataParqueaderos() { parqueaderos = new ArrayList<>(); Parqueadero park = new Parqueadero("PARQUEADERO DE DAVP","a 23-133, Cra 2 #23-39"); park.setPos(11.2314439, -74.2131814); Parqueadero park2 = new Parqueadero("Parqueadero de Motos Colonial","Cl. 19 #4 - 44"); park2.setPos(11.2414655,-74.2126184); Parqueadero park3 = new Parqueadero("Parqueadero central la 14","Cl. 14 Santa Marta, Magdalena"); park3.setPos(11.2443837,-74.2100939); Parqueadero park4 = new Parqueadero("Parqueadero de bicicletas", "Cl. 16 #16-30"); park4.setPos(11.2437862,-74.2115373); Parqueadero park5 = new Parqueadero("Parqueadero CC Buenavista", "Calle 29A"); park5.setPos(11.2312596,-74.1864803); parqueaderos.add(park); parqueaderos.add(park2); parqueaderos.add(park3); parqueaderos.add(park4); parqueaderos.add(park5); } public static ArrayList<Parqueadero> getParqueaderos() { if (data == null) { data = new DataParqueaderos(); } return data.parqueaderos; } public static Parqueadero BuscarParqueadero(String tag) { for (Parqueadero park: getParqueaderos()) { if ( park.getTag().equals(tag)) return park; } return null; } }
/* * 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 javaapplication2; /** * * @author matheusrangel */ public class Pizza extends ProdutoNaoDuravel{ private String tamanho; public String getTamanho() { return tamanho; } public void setTamanho(String tamanho) { this.tamanho = tamanho; } }
package it.raffo.codewars; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; public class test { private boolean[] operands; private char[] operators; private BigInteger[][] cacheT; private BigInteger[][] cacheF; public void BooleanOrder(final String operands, final String operators) { this.operands = new boolean[operands.length()]; this.operators = new char[operators.length()]; this.cacheT = new BigInteger[operands.length()][operands.length()]; this.cacheF = new BigInteger[operands.length()][operands.length()]; for (int i = 0; i < operands.length(); ++i) { this.operands[i] = operands.charAt(i) == 't'; if (i < operators.length()) { this.operators[i] = operators.charAt(i); } } } public BigInteger solve() { int n = this.operands.length - 1; for (int s = 0; s <= n; ++s) { for (int i = 0; i <= (n - s); ++i) { int j = s + i; BigInteger[] tf = this.calcTF(i, j); this.cacheT[i][j] = tf[0]; this.cacheF[i][j] = tf[1]; } } return this.cacheT[0][n]; } private BigInteger[] calcTF(int i, int j) { BigInteger[] res = new BigInteger[2]; if (i == j) { res[0] = this.operands[i] ? BigInteger.ONE : BigInteger.ZERO; res[1] = this.operands[i] ? BigInteger.ZERO : BigInteger.ONE; return res; } res[0] = res[1] = BigInteger.ZERO; for (int k = i; k < j; ++k) { int leftI = i; int leftJ = k; int rightI = k + 1; int rightJ = j; BigInteger leftT = this.cacheT[leftI][leftJ]; BigInteger leftF = this.cacheF[leftI][leftJ]; BigInteger rightT = this.cacheT[rightI][rightJ]; BigInteger rightF = this.cacheF[rightI][rightJ]; char op = this.operators[k]; switch (op) { case '&': { res[0] = res[0].add(leftT.multiply(rightT)); res[1] = res[1].add(leftF.multiply(rightF).add(leftF.multiply(rightT)).add(leftT.multiply(rightF))); break; } case '|': { res[0] = res[0].add(leftT.multiply(rightT).add(leftF.multiply(rightT)).add(leftT.multiply(rightF))); res[1] = res[1].add(leftF.multiply(rightF)); break; } case '^': { res[0] = res[0].add(leftT.multiply(rightF).add(leftF.multiply(rightT))); res[1] = res[1].add(leftT.multiply(rightT).add(leftF.multiply(rightF))); break; } default: throw new RuntimeException("errore: " + op); } } return res; } static String lcs(String a, String b) { int m = a.length(); int n = b.length(); return lcs(a, b, m, n); } static String lcs(String a, String b, int max, int min) { int[][] l = new int[max + 1][min + 1]; for (int i = 0; i <= max; i++) { for (int j = 0; j <= min; j++) { if ((i == 0) || (j == 0)) { l[i][j] = 0; } else if (a.charAt(i - 1) == b.charAt(j - 1)) { l[i][j] = l[i - 1][j - 1] + 1; } else { l[i][j] = Math.max(l[i - 1][j], l[i][j - 1]); } } } int idx = l[max][min]; int temp = idx; char[] lcs = new char[idx + 1]; lcs[idx] = '\0'; int i = max; int j = min; while ((i > 0) && (j > 0)) { if (a.charAt(i - 1) == b.charAt(j - 1)) { lcs[idx - 1] = a.charAt(i - 1); i--; j--; idx--; } else if (l[i - 1][j] > l[i][j - 1]) { i--; } else { j--; } } return getString(temp, lcs); } private static String getString(int temp, char[] lcs) { StringBuilder sb = new StringBuilder(); for (int k = 0; k <= temp; k++) { sb.append(lcs[k]); } return sb.deleteCharAt(temp).toString(); } public double evaluate(String expr) { if (expr.isEmpty()) { return 0d; } Deque<String> stack = new ArrayDeque<>(); String[] strArray = expr.split(" "); for (int i = 0; i < strArray.length; i++) { String c = strArray[i]; if (c.matches("\\+")) { String b = stack.pop(); String a = stack.pop(); int s = Integer.valueOf(a) + Integer.valueOf(b); stack.push(String.valueOf(s)); } else if (c.matches("\\-")) { String b = stack.pop(); String a = stack.pop(); int s = Integer.valueOf(a) - Integer.valueOf(b); stack.push(String.valueOf(s)); } else if (c.matches("\\*")) { String b = stack.pop(); String a = stack.pop(); int s = Integer.valueOf(a) * Integer.valueOf(b); stack.push(String.valueOf(s)); } else if (c.matches("\\/")) { String b = stack.pop(); String a = stack.pop(); int s = Integer.valueOf(a) / Integer.valueOf(b); stack.push(String.valueOf(s)); } else { stack.push(c); } } return Double.valueOf(stack.pop()); } public static boolean scramble(String str1, String str2) { HashMap<Character, Integer> mappa = new HashMap<>(); for (char c : str1.toCharArray()) { mappa.put(c, 1 + mappa.getOrDefault(c, 0)); } for (char c : str2.toCharArray()) { Integer contatore = mappa.getOrDefault(c, 0); if (contatore == 0) { return false; } mappa.put(c, --contatore); } return true; } public static double going(int n) { BigDecimal fattore = BigDecimal.ONE.setScale(6, BigDecimal.ROUND_UNNECESSARY); BigDecimal somma = BigDecimal.ZERO.setScale(6, BigDecimal.ROUND_UNNECESSARY); for (int i = 1; i <= n; i++) { fattore = fattore.multiply(BigDecimal.valueOf(i)); somma = somma.add(fattore); } BigDecimal graneNumero = somma.divide(fattore, BigDecimal.ROUND_FLOOR); return graneNumero.doubleValue(); } public static String rangeExtraction(int[] arr) { List<String> listaArr = new ArrayList<>(); int consecutivi = 0; for (int i = 0; i < arr.length;) { consecutivi = 0; String start = String.valueOf(arr[i]); while ((i != (arr.length - 1)) && ((arr[i + 1] - arr[i]) == 1)) { consecutivi++; i++; } if (consecutivi > 0) { if (consecutivi > 1) { start += "-" + (Integer.parseInt(start) + consecutivi); } else { i--; } } listaArr.add(start); i++; } return String.join(",", listaArr); } public static int calcolaOccorrenze(List<Integer> listaElements, int val) { int occ = 0; for (Integer e : listaElements) { if (e.intValue() == val) { occ++; } } return occ; } public static int[] deleteNth(int[] elements, int maxOccurrences) { List<Integer> listaElements = new ArrayList<>(); int arr[] = null; for (int e : elements) { if (calcolaOccorrenze(listaElements, e) < maxOccurrences) { listaElements.add(e); } } arr = listaElements.stream().mapToInt(e -> e).toArray(); return arr; } public static int[][] twosDifference(int[] array) { List<int[]> aRet = new ArrayList<int[]>(); List<Integer> lista = Arrays.stream(array).boxed().collect(Collectors.toList()); Collections.sort(lista); int[] arrayOredr = lista.stream().mapToInt(i -> i).toArray(); for (int i = 0; i < arrayOredr.length; i++) { for (int j = 0; j < arrayOredr.length; j++) { if ((arrayOredr[j] - arrayOredr[i]) == 2) { int arr[] = new int[2]; arr[0] = arrayOredr[i]; arr[1] = arrayOredr[j]; aRet.add(arr); } } } // aRet.stream().forEach(a -> System.out.println(a[0] + "," + a[1])); int a[][] = new int[aRet.size()][2]; for (int x = 0; x < aRet.size(); x++) { a[x] = new int[] { aRet.get(x)[0], aRet.get(x)[1] }; System.out.println(a[x][0] + "," + a[x][1]); } return a; } public static String recoverSecret(char[][] triplets) { List<Character> chiave_segreta = new ArrayList<>(); for (int i = 0; i < triplets.length; i++) { char[] tripletta = triplets[i]; handleTriplet(chiave_segreta, tripletta); } for (int i = triplets.length - 1; i >= 0; i--) { char[] tripletta = triplets[i]; handleTriplet(chiave_segreta, tripletta); } return chiave_segreta.stream().map(String::valueOf).collect(Collectors.joining()); } private static void handleTriplet(List<Character> chiave_segreta, char[] tripletta) { Boolean pulita = true; for (char ch : tripletta) { if (chiave_segreta.contains(ch)) { pulita = false; } } if (pulita) { gestisciTriplettaPulita(chiave_segreta, tripletta); } else { gestisciTriplettaSporca(chiave_segreta, tripletta); } } private static void gestisciTriplettaPulita(List<Character> chiave_segreta, char[] tripletta) { for (char ch : tripletta) { chiave_segreta.add(ch); } } private static void gestisciTriplettaSporca(List<Character> chiave_segreta, char[] triplet) { for (int i = 0; i < triplet.length; i++) { if (chiave_segreta.contains(triplet[i]) && (i < (triplet.length - 1))) { if (!chiave_segreta.contains(triplet[i + 1])) { chiave_segreta.add(chiave_segreta.indexOf(triplet[i]), triplet[i + 1]); } else if (chiave_segreta.indexOf(triplet[i]) > chiave_segreta.indexOf(triplet[i + 1])) { chiave_segreta.remove(chiave_segreta.indexOf(triplet[i])); chiave_segreta.add(chiave_segreta.indexOf(triplet[i + 1]), triplet[i]); } } if (chiave_segreta.contains(triplet[i]) && (i > 0)) { if (!chiave_segreta.contains(triplet[i - 1])) { chiave_segreta.add(chiave_segreta.indexOf(triplet[i]), triplet[i - 1]); } else if (chiave_segreta.indexOf(triplet[i]) < chiave_segreta.indexOf(triplet[i - 1])) { chiave_segreta.remove(chiave_segreta.indexOf(triplet[i])); chiave_segreta.add(chiave_segreta.indexOf(triplet[i - 1]) + 1, triplet[i]); } } } } public static String encryptThis(String text) { if ((text == null) || text.isEmpty()) { return ""; } String str = ""; List<String> listStr = Arrays.asList(text.split("\\s+")); for (String s : listStr) { String appo = s; if (s.length() >= 2) { char[] aAppo = s.toCharArray(); char temp = aAppo[1]; aAppo[1] = aAppo[s.length() - 1]; aAppo[s.length() - 1] = temp; appo = new String(aAppo); } appo = (int) s.charAt(0) + appo.substring(1); System.out.println("STR: " + appo); } return str; } public static String[] solution(String s) { s = s.replaceAll("\\s", "."); List<String> lStr = new ArrayList<>(); int a = 0, b = 0; for (int i = 0; i <= (s.length() / 2); i++) { a = i * 2; b = (a + 2) > s.length() ? s.length() : a + 2; String tmp = s.substring(a, b); if (!tmp.isEmpty()) { tmp = String.format("%-2s", tmp); tmp = tmp.replaceAll("\\s", "_"); tmp = tmp.replaceAll("\\.", " "); lStr.add(tmp); } } lStr.stream().forEach(e -> System.out.println(e)); return lStr.stream().toArray(String[]::new); } public static int findMissingNumber(int[] numbers) { int num = numbers.length + 1; for (int i = 0; i < numbers.length; i++) { num += (1 + i) - numbers[i]; } return num; } public static String capitalize(String str) { if ((str == null) || str.isEmpty()) { return str; } return str.substring(0, 1).toUpperCase() + str.substring(1); } public static String greet(String name) { System.out.println(name); return "Hello " + capitalize(name.toLowerCase()); } public static void main(String[] args) { // TODO Auto-generated method stub // int[] array = new int[] { -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, // 15, 17, 18, 19, 20 }; // System.out.println(rangeExtraction(array)); // int a[] = deleteNth(new int[] {}, 2); // // Arrays.stream(a).boxed().collect(Collectors.toList()).stream().forEach(i -> // System.out.print(i + ",")); int[] arr = new int[] { 1, 23, 3, 4, 7 }; twosDifference(arr); char[][] triplette = { { 't', 'u', 'p' }, { 'w', 'h', 'i' }, { 't', 's', 'u' }, { 'a', 't', 's' }, { 'h', 'a', 'p' }, { 't', 'i', 's' }, { 'w', 'h', 's' } }; System.out.println(recoverSecret(triplette)); System.out.println(encryptThis("lived")); solution(" bcde"); System.out.println(findMissingNumber(new int[] { 1, 2, 3, 4 })); System.out.println(greet("ciao")); } }
package spring.boot.com.isTwo; import spring.boot.com.entity.User; import java.util.*; /** * @author: yiqq * @date: 2019/4/23 * @description: */ public class Demo02Comparator { //定义一个方法,方法的返回值类型使用函数式接口Comparator // public static Comparator<String> getComparator(){ // //继续优化Lambda表达式 // return (o1, o2)->o2.length()-o1.length(); // } public static void main(String[] args) { // //创建一个字符串数组 // String[] arr = {"aaa","b","cccccc","dddddddddddd"}; // //输出排序前的数组 // System.out.println(Arrays.toString(arr));//[aaa, b, cccccc, dddddddddddd] // //调用Arrays中的sort方法,对字符串数组进行排序 // Arrays.sort(arr,getComparator()); // //输出排序后的数组 // System.out.println(Arrays.toString(arr));//[dddddddddddd, cccccc, aaa, b] /* String[] arr = {"aaa","bbb","ccc","ddd","fff","ggg"}; Arrays.sort(arr, (String s1, String s2) -> (s1.compareTo(s2)));//Lambdas排序集合 System.out.println(Arrays.toString(arr));*/ List<User> list = new ArrayList<>(); User user = new User(); user.setName("yiqq"); user.setEmail("111111"); list.add(user); User user1 = new User(); user1.setName("yqq"); user1.setEmail("222222"); list.add(user1); get(list); for (int i=0;i<list.size();i++) { System.out.println(list.get(i)); } System.out.println("--------------"); } public static void get(List<User> list){ for(int i=0;i<list.size();i++) { User user = list.get(i); int a = new Random().nextInt(10); user.setAge(a); } } }
public class Main { public static void main(int[] num) { int [] num; num = new int[]{}; for (int num)int }
// https://leetcode.com/problems/minimum-cost-to-connect-sticks/solution/ class Solution { public int connectSticks(int[] sticks) { int totalCost = 0; PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int stick : sticks) pq.add(stick); while (pq.size() > 1) { int stick1 = pq.remove(); int stick2 = pq.remove(); int cost = stick1 + stick2; totalCost += cost; pq.add(stick1 + stick2); } return totalCost; } }
/* * Copyright (C) 2018 Instituto Nacional de Telecomunicações * * All rights are reserved. Reproduction in whole or part is * prohibited without the written consent of the copyright owner. * */ package inatel.br.nfccontrol.di.qualifier; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import javax.inject.Qualifier; /** * Interface used to keep the Shared preference test. * * @author Daniela Mara Silva <danielamara@inatel.br> * @since 30/01/2018. */ @Qualifier @Documented @Retention(RUNTIME) public @interface IsAuthenticatedPreference { }
package DAO; import DataSets.GroupsDataSet; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.query.Query; import javax.persistence.NoResultException; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; public class GroupsDAO { private Session session; public GroupsDAO(Session session) { this.session = session; } public GroupsDataSet get(long id) throws HibernateException { return (GroupsDataSet) session.get(GroupsDataSet.class, id); } public List<GroupsDataSet> getGroupsByName(String name) throws HibernateException { CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<GroupsDataSet> cq = cb.createQuery(GroupsDataSet.class); Root<GroupsDataSet> root = cq.from(GroupsDataSet.class); cq.select(root); cq.where(cb.equal(root.get("name"), name)); List<GroupsDataSet> groups; Query<GroupsDataSet> query = session.createQuery(cq); try{ groups = query.getResultList(); }catch (NoResultException ex){ System.out.println("Групп с таким названием не найдено"); return null; } return groups; } public List<GroupsDataSet> getGroupsByTeacher(long teacher_id) throws HibernateException { CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<GroupsDataSet> cq = cb.createQuery(GroupsDataSet.class); Root<GroupsDataSet> root = cq.from(GroupsDataSet.class); cq.select(root); cq.where(cb.equal(root.get("teacher_id"), teacher_id)); List<GroupsDataSet> groups = new ArrayList<GroupsDataSet>(); Query<GroupsDataSet> query = session.createQuery(cq); try{ groups = query.getResultList(); }catch (NoResultException ex){ System.out.println("Групп созданнs[ этим преподавателем не существует"); return null; } return groups; } public void insertGroup(String name) throws HibernateException { session.save(new GroupsDataSet(name)); } }
package com.cxc.asimplecachedemo.ui; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.cxc.asimplecachedemo.R; import com.cxc.asimplecachedemo.cache.ACache; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button btn_save; private Button btn_read; private EditText et_h; private ACache aCache; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); aCache = ACache.get(this); } private void initView(){ btn_read = (Button)findViewById(R.id.btn_read); btn_read.setOnClickListener(this); btn_save = (Button)findViewById(R.id.btn_save); btn_save.setOnClickListener(this); et_h = (EditText)findViewById(R.id.et_h); } private void readCache(){ String str = aCache.getAsString("et_str"); if(str == null){ et_h.setText("cache is empty"); return; } et_h.setText(str); } /** * 保存缓存 * @param saveTime:过期时间,单位:秒 * @return */ private void saveCache(int saveTime){ aCache.put("et_str",et_h.getText().toString(),saveTime); et_h.setText(""); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btn_read: Toast.makeText(this,"read",Toast.LENGTH_SHORT).show(); readCache(); break; case R.id.btn_save: Toast.makeText(this,"save",Toast.LENGTH_SHORT).show(); saveCache(30); break; default: break; } } }
package com.letmesee.service.filtros; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.letmesee.entity.Imagem; import com.letmesee.service.FiltrosUtils; import com.letmesee.service.FiltrosUtils.Pixel; public class ExtrairCanalFacade { private static ExtrairCanalFacade instancia; private static FiltrosUtils filtrosUtils; private ExtrairCanalFacade() {} private static ObjectMapper mapper; private JsonNode parametros; public static synchronized ExtrairCanalFacade getInstancia() { if(instancia == null) { instancia = new ExtrairCanalFacade(); filtrosUtils = FiltrosUtils.getInstancia(); mapper = new ObjectMapper(); } return instancia; } public Imagem Processar(Imagem img, String parametros) { try { this.parametros = mapper.readTree(parametros); } catch (IOException e) { e.printStackTrace(); } boolean extrairR = this.parametros.get("R").asBoolean(); boolean extrairG = this.parametros.get("G").asBoolean(); boolean extrairB = this.parametros.get("B").asBoolean(); String formato = img.getTipo(); String novoConteudoBase64 = ""; if(formato.equals("jpg") || formato.equals("png") || formato.equals("bmp")) { BufferedImage imagem = filtrosUtils.base64toBufferedImage(img.getConteudoBase64()); imagem = ExtrairCanal(imagem, formato,extrairR, extrairG, extrairB); novoConteudoBase64 = filtrosUtils.BufferedImageToBase64(imagem,formato); imagem = null; } else if(formato.equals("gif")) { ArrayList<Integer> delays = new ArrayList<Integer>(); ArrayList<BufferedImage> frames = filtrosUtils.getGifFrames(img.getConteudoBase64(),delays); ArrayList<BufferedImage> framesProcessados = new ArrayList<BufferedImage>(); for(BufferedImage f : frames) { f = ExtrairCanal(f, formato, extrairR, extrairG, extrairB); framesProcessados.add(f); } novoConteudoBase64 = filtrosUtils.gerarBase64GIF(framesProcessados,delays); frames = null; framesProcessados = null; } Imagem saida = new Imagem(img.getLargura(),img.getAltura(),formato,img.getNome().concat("+Extração_Canal") .concat(extrairR || extrairG || extrairB ? "(" : "" ) .concat(extrairR? "R" : "") .concat(extrairG? "G" : "") .concat(extrairB? "B" : "").concat(")"),novoConteudoBase64); return saida; } public BufferedImage ExtrairCanal(BufferedImage img, String formato, boolean extrair_r, boolean extrair_g, boolean extrair_b) { int i,j,r,g,b; Pixel p; for(i = 0; i < img.getHeight(); i++) { for(j = 0; j < img.getWidth(); j++) { p = filtrosUtils.getPixel(img, i, j, formato); r = 0; g = 0; b = 0; if(extrair_r)r = p.getR(); if(extrair_g)g = p.getG(); if(extrair_b)b = p.getB(); p.setRGB(r, g, b); filtrosUtils.setPixel(img, i, j, p, formato); } } return img; } }
package com.company.daniel.lind.karlberg; import java.util.logging.Logger; /** * Created by daniellindkarlberg on 2016-11-30. */ public class UserInputHandler { private ContactManager contactManager; private static final Logger log = Logger.getLogger(ContactManager.class.getName()); public UserInputHandler(ContactManager contactManager) { this.contactManager = contactManager; } public void handle(UserInput userInput) { try { switch (userInput.getCommand()) { case "add": if (userInput.getParameterCount() > 3 || userInput.getParameterCount() < 3) { log.fine("Invalid parameters from user" + userInput.getInputData()); System.out.println("Invalid parameters: " + userInput.getInputData() + " please enter firstname lastname email"); log.fine("User command: add"); } else { contactManager.addNewContact(userInput.getParameters(0), userInput.getParameters(1), userInput.getParameters(2)); } break; case "delete": log.fine("User command: delete"); if (userInput.getParameterCount() > 1 || userInput.getParameterCount() < 1) { log.fine("Invalid parameters from user" + userInput.getInputData()); System.out.println("Invalid parameters: " + userInput.getInputData() + " please enter a contact id"); } else { contactManager.deleteContact(userInput.getParameters(0)); } break; case "list": log.fine("User command: list"); if (!(userInput.getParameterCount() > 0)) { contactManager.listContacts(); } else { log.fine("Invalid parameters from user" + userInput.getInputData()); System.out.println("Invalid parameters: " + userInput.getInputData() + " list should not contain any parameters"); } break; case "search": log.fine("User command: search" + ", searched for: " + userInput.getParameters(0)); contactManager.searchContacts(userInput.getParameters(0)); break; case "help": log.fine("User command: help"); if (!(userInput.getParameterCount() > 0)) { helpMenu(); } else { log.fine("Invalid parameters from user" + userInput.getInputData()); System.out.println("Invalid parameters: " + userInput.getInputData() + " help should not contain any parameters"); } break; case "quit": log.fine("User command: quit"); if (!(userInput.getParameterCount() > 0)) { contactManager.saveContactsToFile(); System.out.println("Contacts saved to file"); System.exit(0); } else { log.fine("Invalid parameters from user" + userInput.getInputData()); System.out.println("Invalid parameters: " + userInput.getInputData() + " quit should not contain any parameters "); } break; default: log.fine("Invalid command" + userInput.getInputData()); System.out.println("Invalid command: " + userInput.getInputData() + " type help for instructions"); } } catch (Exception e) { log.fine("Invalid parameters:" + userInput.getInputData()); System.out.println("Invalid parameters: " + userInput.getInputData() + " this command needs parameters"); } } private void helpMenu() { System.out.println(); System.out.println("Type your command followed by space and parameter(s) and hit Enter"); System.out.println("------------------------------------------------------------------------------"); System.out.println("Command Input parameters"); System.out.println("------------------------------------------------------------------------------"); System.out.println("add firstname lastname email \n" + "delete Id (tip, list contacts and copy/paste the id)\n" + "search first or last name( tip, you only need to enter the first letter(s)) \n" + "list no parameters, lists existing contacts\n" + "quit no parameters, exits application"); } }
package negocio.basica; // Generated 24/09/2012 21:42:03 by Hibernate Tools 3.2.0.CR1 import java.util.List; import javax.naming.InitialContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.LockMode; import org.hibernate.SessionFactory; import org.hibernate.criterion.Example; /** * Home object for domain model class Privilegio. * @see negocio.basica.Privilegio * @author Hibernate Tools */ public class PrivilegioHome { private static final Log log = LogFactory.getLog(PrivilegioHome.class); private final SessionFactory sessionFactory = getSessionFactory(); protected SessionFactory getSessionFactory() { try { return (SessionFactory) new InitialContext().lookup("SessionFactory"); } catch (Exception e) { log.error("Could not locate SessionFactory in JNDI", e); throw new IllegalStateException("Could not locate SessionFactory in JNDI"); } } public void persist(Privilegio transientInstance) { log.debug("persisting Privilegio instance"); try { sessionFactory.getCurrentSession().persist(transientInstance); log.debug("persist successful"); } catch (RuntimeException re) { log.error("persist failed", re); throw re; } } public void attachDirty(Privilegio instance) { log.debug("attaching dirty Privilegio instance"); try { sessionFactory.getCurrentSession().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(Privilegio instance) { log.debug("attaching clean Privilegio instance"); try { sessionFactory.getCurrentSession().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void delete(Privilegio persistentInstance) { log.debug("deleting Privilegio instance"); try { sessionFactory.getCurrentSession().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public Privilegio merge(Privilegio detachedInstance) { log.debug("merging Privilegio instance"); try { Privilegio result = (Privilegio) sessionFactory.getCurrentSession() .merge(detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public Privilegio findById( int id) { log.debug("getting Privilegio instance with id: " + id); try { Privilegio instance = (Privilegio) sessionFactory.getCurrentSession() .get("negocio.basica.Privilegio", id); if (instance==null) { log.debug("get successful, no instance found"); } else { log.debug("get successful, instance found"); } return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(Privilegio instance) { log.debug("finding Privilegio instance by example"); try { List results = sessionFactory.getCurrentSession() .createCriteria("negocio.basica.Privilegio") .add(Example.create(instance)) .list(); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } }
package com.GestiondesClub.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.GestiondesClub.dto.ClubMembreDto; import com.GestiondesClub.dto.DemEventDto; import com.GestiondesClub.dto.LesMatARes; import com.GestiondesClub.dto.LesSalleAReserve; import com.GestiondesClub.dto.NotifOnly; import com.GestiondesClub.entities.Club; import com.GestiondesClub.entities.DemandeCreationClub; import com.GestiondesClub.entities.DemandeEvenement; import com.GestiondesClub.entities.DemandeMaterielFac; import com.GestiondesClub.entities.DemmandeSalle; import com.GestiondesClub.entities.Lieu; import com.GestiondesClub.entities.MaterielFaculter; import com.GestiondesClub.entities.Planification; import com.GestiondesClub.entities.Salle; import com.GestiondesClub.services.ClubService; import com.GestiondesClub.services.DemEventServices; import com.GestiondesClub.services.DemandeMatFacService; import com.GestiondesClub.services.DemandeSalleService; import com.GestiondesClub.services.LieuEventService; import com.GestiondesClub.services.MaterialService; import com.GestiondesClub.services.PlanificationService; import com.GestiondesClub.services.VilleService; @RestController @RequestMapping("/api") @CrossOrigin(origins = "http://localhost:8000") public class DemandeEventController { @Autowired private DemEventServices demandeEvServ; @Autowired private LieuEventService LieuEvService; @Autowired private VilleService villeService; @Autowired private DemandeSalleService demandeSalleServ; @Autowired private PlanificationService PlanifcationServ; @Autowired private DemandeMatFacService demandeMatFacServ; @Autowired private ClubService clubService ; @Autowired private MaterialService materiaLServ; private List<Salle> salles; @RequestMapping("/DemandeEvent/list") public List<DemEventDto> GetAllDemande() { return demandeEvServ.GetAllDemande(); } @RequestMapping("/DemandeEvent/{id}") public Optional<DemandeEvenement> getDemandeEvent(@PathVariable Long id) { return demandeEvServ.getDemandeEvent(id); } @RequestMapping("/demandecreationclub/listbyClub/{id}") public List<DemEventDto> getAllByclub(@PathVariable String id) { ClubMembreDto c = clubService.getByName(id); Club leclub = new Club(); leclub.setId(c.getId()); leclub.setNomClub(c.getNomClub()); return demandeEvServ.getAllByclub(leclub); } @PutMapping("/DemandeEvent/create") public DemandeEvenement createDemandeEvent(@RequestBody DemandeEvenement demande){ Lieu l = new Lieu(); salles = null; if(!demande.isExterne()) { l.setId((long) 1); l.setSite("faculte de science economique et gestion sfax"); l.setAdresse("Route de l’Aéroport Km 4 Sfax Tunisie"); l.setCodePostal(3018); l.setEmailContact("contact@fsegs.rnu.tn"); l.setTel(74278777); l.setFax(74279139); l.setVille(villeService.findByVille("sfax")); LieuEvService.ajoutLieu(l); demande.getLeslieu().add(l); } else { if(demande.getLeslieu().size()>0 || demande.getLeslieu()!=null) { //List<Lieu> checkLieu =LieuEvService.getAllLieu(); for(Lieu site : demande.getLeslieu()) { LieuEvService.ajoutLieu(site); } } } DemandeEvenement de = new DemandeEvenement(); de=demandeEvServ.createDemandeEvent(demande); if(demande.getLesSalles().size()>0 || demande.getLesSalles() !=null) { for(DemmandeSalle d : demande.getLesSalles()) { for( Planification p : d.getLesplanification()) { PlanifcationServ.addplanifications(p,d); } d.setDemEvent(de); demandeSalleServ.affecter(d); } } if(demande.getLesMaterielAffecter().size()>0 || demande.getLesMaterielAffecter() !=null) { for(DemandeMaterielFac d : demande.getLesMaterielAffecter()) { for( Planification p : d.getLesplanificationMateriel()) { PlanifcationServ.addplanificationsMat(p,d); } d.setDemEventMat(de); demandeMatFacServ.affecter(d); } } return de; } @PutMapping("/DemandeEvent/update") public DemandeEvenement updateDemandeEvent(@RequestBody DemandeEvenement demande){ return demandeEvServ.updateDemandeEvent(demande); } @RequestMapping("/DemandeEvent/nonconfirmer") public List<NotifOnly> getNonConfirmed() { return demandeEvServ.getNonConfirmed(); } @RequestMapping("/DemandeEvent/lessalles") public List<LesSalleAReserve> getDemSalle() { return demandeEvServ.getDemSalle(); } @RequestMapping("/DemandeEvent/leMateriel") public List<LesMatARes> getDemMat() { return demandeEvServ.getDemMat(); } @PutMapping("/DemandeEvent/Materiel/affectMat/{id}") public Planification affecterQteMateriel(@RequestBody Planification planif,@PathVariable Long id){ Optional<DemandeMaterielFac> d = demandeMatFacServ.findDemandeMat(id); planif.setDemandeMatFac(d.get()); return PlanifcationServ.affecterQteMateriel(planif); } @PutMapping("/DemandeEvent/Salle/affectSalle/{id}") public Planification affecterSalle(@RequestBody Planification planif,@PathVariable Long id){ Optional<DemmandeSalle> d = demandeSalleServ.findbyid(id); planif.setDemandeSalle(d.get()); return PlanifcationServ.affecterQteMateriel(planif); } /* /*ListIterator matAffectIt = demande.getLesMaterielAffecter().listIterator(); while(matAffectIt.hasNext()) { DemandeMaterielFac demandeMatFac = (DemandeMaterielFac) matAffectIt.next(); ListIterator planifMat = demandeMatFac.getLesplanificationMateriel().listIterator(); while(planifMat.hasNext()) { Planification p = (Planification) planifMat.next(); p.setDemandeMatFac(demandeMatFac); PlanifcationServ.addplanificationsMat(p); } DemandeEvenement lademandeEv = new DemandeEvenement(); lademandeEv.setId((long)6); demandeMatFac.setDemEventMat(lademandeEv); demandeMatFacServ.affecter(demandeMatFac); }*/ }
package com.jd.jarvisdemonim.ui.testfragment; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.jd.jarvisdemonim.R; import com.jd.jarvisdemonim.ui.NimActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestTabReminderActivity; import com.jd.jdkit.elementkit.fragment.DBaseFragment; import com.jd.jdkit.reminder.ReminderManager; import com.netease.nim.uikit.common.util.log.LogUtil; /** * Auther: Jarvis Dong * Time: on 2016/12/30 0030 * Name: * OverView: * Usage: */ public class HomeFragment extends DBaseFragment { TextView txtOne; Button btnOne; Button btnTwosend; Button btnTwostop; int i = 0; private Handler mHandler = new Handler(); private Runnable runnable = new Runnable() { @Override public void run() { i++; ReminderManager.getInstance().upDateUnReadNum(i, true, Integer.parseInt(getArguments().getString(KEY))); mHandler.postDelayed(runnable, 1000); } }; private static String KEY = "key"; public static HomeFragment newInstance(String key) { HomeFragment fragment = new HomeFragment(); Bundle bun = new Bundle(); bun.putString(KEY, key); fragment.setArguments(bun); return fragment; } @Override protected View initXml(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_one, container, false); } @Override protected void initView(View view, @Nullable Bundle savedInstanceState) { txtOne = (TextView) view.findViewById(R.id.txtOne); btnOne = (Button) view.findViewById(R.id.btnOne); btnTwosend = (Button) view.findViewById(R.id.btnTwo); btnTwostop = (Button) view.findViewById(R.id.btnTwo2); } @Override protected void processLogic(Bundle savedInstanceState) { String string = getArguments().getString(KEY); txtOne.setText(string); btnOne.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mActivity instanceof NimActivity) { // ((NimActivity) mActivity).setCurrentMsg(Integer.parseInt(getArguments().getString(KEY))); } else if (mActivity instanceof NormalTestTabReminderActivity) { ((NormalTestTabReminderActivity) mActivity).setCurrentMsg(Integer.parseInt(getArguments().getString(KEY))); } } }); btnTwosend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LogUtil.i("jarvisclick", "发送"); mHandler.postDelayed(runnable, 1000); } }); btnTwostop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LogUtil.i("jarvisclick", "停止"); i = Integer.parseInt(getArguments().getString(KEY)); mHandler.removeCallbacks(runnable); ReminderManager.getInstance().upDateUnReadNum(0, true, Integer.parseInt(getArguments().getString(KEY))); } }); } @Override protected void initListener() { } @Override public void onDestroyView() { super.onDestroyView(); mHandler.removeCallbacks(runnable); } }
package com.wxt.designpattern.adapter.classadapter; /********************************* * @author weixiaotao1992@163.com * @date 2018/10/21 11:43 * QQ:1021061446 * *********************************/ import java.util.List; /** * 类适配器对象 */ public class ClassAdapter extends LogFileOptImpl implements ILogDbOpt{ public ClassAdapter(String logFilePathName) { super(logFilePathName); } public void createLog(LogEntity lm) { //1:先读取文件的内容 List<LogEntity> list = this.readLogFile(); //2:加入新的日志对象 list.add(lm); //3:重新写入文件 this.writeLogFile(list); } public List<LogEntity> getAllLog() { return this.readLogFile(); } public void removeLog(LogEntity lm) { //1:先读取文件的内容 List<LogEntity> list = this.readLogFile(); //2:删除相应的日志对象 list.remove(lm); //3:重新写入文件 this.writeLogFile(list); } public void updateLog(LogEntity lm) { //1:先读取文件的内容 List<LogEntity> list = this.readLogFile(); //2:修改相应的日志对象 for(int i=0;i<list.size();i++){ if(list.get(i).getLogId().equals(lm.getLogId())){ list.set(i, lm); break; } } //3:重新写入文件 this.writeLogFile(list); } }
<<<<<<< HEAD package in.vamsoft.excersise1; public enum Coin { HEADS, TAILS; /** * creating Coin flip method. * @return it returns heads or tails. */ public static Coin flip() { if (Math.random() < 0.5) { return (HEADS); } else { return (TAILS); } } } ======= package in.vamsoft.excersise1; /* * @author vignesh */ public enum Coin { HEADS, TAILS; public static Coin flip() { if (Math.random() < 0.5) { return(HEADS); } else { return(TAILS); } } } >>>>>>> 35b1b732e68ed3b6596b2e23d9ec90c62220f54e
package com.eappcat.base.code; /** * Created by yuebo on 2018/6/21. */ public interface NameStrategy { String type(String type); String table(String table); String column(String column); String entity(String table); String trimPackage(String fullName); }
import java.net.*; import java.util.*; public class GUID { private int time =0; // 32 bits of time. private int node =0; // 32 bits of randomness private Random rand =null; private String sysid=null; private int iHash =0; private int addr =0; public GUID() { StringBuffer tmp= new StringBuffer(); // sort out random seed :-) rand = new Random(); // get InetAddress try { InetAddress inet = InetAddress.getLocalHost(); byte[] bytes=inet.getAddress(); addr = bytes[0] << 24; addr+= bytes[1] << 16; addr+= bytes[2] << 8; addr+= bytes[3]; } catch(Exception e) { // we couldn't determine ip address // so we fake one :P addr = (rand.nextInt() & 0xFF) << 24; addr+= (rand.nextInt() & 0xFF) << 16; addr+= (rand.nextInt() & 0xFF) << 8; addr+= (rand.nextInt() & 0xFF) ; } String hexIp = toHex(addr); //get hashcode skew it a little just in case of multiple jvms iHash=System.identityHashCode(this) ^ rand.nextInt(); String sHash = toHex(iHash); //tmp.append(hexIp); //tmp.append('.'); //tmp.append(sHash);// IPad //tmp.append('.'); //sysid=tmp.toString(); node = rand.nextInt(); } public String getNextId() { //StringBuffer tmp=new StringBuffer(sysid); StringBuffer tmp=new StringBuffer(); time = (int) (System.currentTimeMillis() & 0xFFFFFFFF); node = rand.nextInt(); //tmp.append(toHex(time)); //tmp.append('.'); //tmp.append(toHex(node)); byte[] string = new byte[16]; // 4 ints = 16 bytes string[ 0] =(byte) ((addr >> 24) & 0xFF); string[ 1] =(byte) ((addr >> 16) & 0xFF); string[ 2] =(byte) ((addr >> 8) & 0xFF); string[ 3] =(byte) ((addr ) & 0xFF); string[ 4] =(byte) ((iHash>> 24) & 0xFF); string[ 5] =(byte) ((iHash>> 16) & 0xFF); string[ 6] =(byte) ((iHash>> 8) & 0xFF); string[ 7] =(byte) ((iHash ) & 0xFF); string[ 8] =(byte) ((time >> 24) & 0xFF); string[ 9] =(byte) ((time >> 16) & 0xFF); string[10] =(byte) ((time >> 8) & 0xFF); string[11] =(byte) ((time ) & 0xFF); string[12] =(byte) ((node >> 24) & 0xFF); string[13] =(byte) ((node >> 16) & 0xFF); string[14] =(byte) ((node >> 8) & 0xFF); string[15] =(byte) ((node ) & 0xFF); tmp.append(Base64.encode(string)); return tmp.toString().substring(0,22); } public String toHex(int integer) { return toHex(integer,8); } public String toHex(int integer, int size) { String str = Integer.toHexString(integer); if (str.length()<size) { StringBuffer sb= new StringBuffer(); for(int i = 0; i < (size-str.length()); i++) sb.append('0'); sb.append(str); return sb.toString(); } else { return str; } } public static void main(String args[]) { GUID uid = new GUID(); for(int i=0;i<16;i++) { System.out.println(uid.getNextId()); } } }//end class
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.ow2.proactive.scheduler.job; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlTransient; import org.hibernate.annotations.AccessType; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; import org.hibernate.annotations.Proxy; import org.objectweb.proactive.api.PAFuture; import org.ow2.proactive.scheduler.common.exception.UnknownTaskException; import org.ow2.proactive.scheduler.common.job.JobId; import org.ow2.proactive.scheduler.common.job.JobInfo; import org.ow2.proactive.scheduler.common.job.JobResult; import org.ow2.proactive.scheduler.common.task.TaskResult; import org.ow2.proactive.scheduler.task.TaskResultImpl; import org.ow2.proactive.scheduler.task.internal.InternalTask; /** * Class representing a job result. A job result is a map of task result. The * key of the map is the name of the task on which to get the result. To * identify the job result, it provides the id of the job in the scheduler and * the job name. * * @author The ProActive Team * @since ProActive Scheduling 0.9 */ @Entity @Table(name = "JOB_RESULT_IMPL") @AccessType("field") @Proxy(lazy = false) @XmlAccessorType(XmlAccessType.FIELD) public class JobResultImpl implements JobResult { /** */ private static final long serialVersionUID = 31L; @Id @GeneratedValue @SuppressWarnings("unused") @XmlTransient private long hId; /** Referenced JobId */ @Cascade(CascadeType.ALL) @OneToOne(fetch = FetchType.EAGER, targetEntity = JobIdImpl.class) private JobId id = null; /** Temporary used to store proActive future result. */ @Transient private Map<String, TaskResult> futurResults = new HashMap<String, TaskResult>(); /** List of every result */ @OneToMany(cascade = javax.persistence.CascadeType.ALL, targetEntity = TaskResultImpl.class) @Cascade(CascadeType.ALL) @LazyCollection(value = LazyCollectionOption.FALSE) @JoinColumn(name = "ALL_RESULTS") private Map<String, TaskResult> allResults = null; /** List of precious results */ @OneToMany(cascade = javax.persistence.CascadeType.ALL, targetEntity = TaskResultImpl.class) @Cascade(CascadeType.ALL) @LazyCollection(value = LazyCollectionOption.FALSE) @JoinColumn(name = "PRECIOUS_RESULTS") private Map<String, TaskResult> preciousResults = null; /** Info of the job at the end */ @Transient private JobInfo jobInfo; /** * ProActive empty constructor */ public JobResultImpl() { } /** * Instantiate a new JobResult with a jobId and a result * * @param id the jobId associated with this result */ public JobResultImpl(InternalJob job) { this.id = job.getId(); this.allResults = new HashMap<String, TaskResult>(job.getTasks().size()); this.preciousResults = new HashMap<String, TaskResult>(); for (InternalTask it : job.getIHMTasks().values()) { this.allResults.put(it.getName(), null); } } /** * @see org.ow2.proactive.scheduler.common.job.JobResult#getJobId() */ public JobId getJobId() { return id; } /** * @see org.ow2.proactive.scheduler.common.job.JobResult#getName() */ public String getName() { return getJobId().getReadableName(); } /** * @see org.ow2.proactive.scheduler.common.job.JobResult#getJobInfo() */ public JobInfo getJobInfo() { return jobInfo; } /** * Set the job info for this result * * @param jobInfo the current job info to set */ public void setJobInfo(JobInfo jobInfo) { this.jobInfo = jobInfo; } /** * Used to store the futur result. * It must be temporary in a Hibernate transient map to avoid empty ID Object. * * @param taskName user define name (in XML) of the task. * @param taskResult the corresponding result of the task. */ public void storeFuturResult(String taskName, TaskResult taskResult) { futurResults.put(taskName, taskResult); } /** * <font color="red">-- For internal use only --</font> * Add a new task result to this job result.<br> * Used by the scheduler to fill your job result. * * @param taskName user define name (in XML) of the task. * @param taskResult the corresponding result of the task. * @param isPrecious true if this taskResult is a precious one. It will figure out in the precious result list. */ public void addTaskResult(String taskName, TaskResult taskResult, boolean isPrecious) { //remove futur Result futurResults.remove(taskName); //add to all Results allResults.put(taskName, taskResult); //add to precious results if needed if (isPrecious) { preciousResults.put(taskName, taskResult); } } /** * Add this new (from replication) task result to the list of known tasks. * * @param taskName the name of the new task to add */ public void addToAllResults(String taskName) { allResults.put(taskName, null); } /** * @see org.ow2.proactive.scheduler.common.job.JobResult#getAllResults() */ public Map<String, TaskResult> getAllResults() { return filterNullResults(allResults); } /** * Remove every key that have null value * * @param trs the map to filter * @return a new filtered map */ private Map<String, TaskResult> filterNullResults(Map<String, TaskResult> trs) { Map<String, TaskResult> tmp = new HashMap<String, TaskResult>(); for (Entry<String, TaskResult> e : trs.entrySet()) { if (e.getValue() != null) { tmp.put(e.getKey(), e.getValue()); } } return tmp; } /** * @see org.ow2.proactive.scheduler.common.job.JobResult#getExceptionResults() */ public Map<String, TaskResult> getExceptionResults() { Map<String, TaskResult> exceptions = new HashMap<String, TaskResult>(); for (Entry<String, TaskResult> e : allResults.entrySet()) { if (e.getValue() != null && e.getValue().hadException()) { exceptions.put(e.getKey(), e.getValue()); } } return exceptions; } /** * @see org.ow2.proactive.scheduler.common.job.JobResult#getPreciousResults() */ public Map<String, TaskResult> getPreciousResults() { return preciousResults; } /** * @see org.ow2.proactive.scheduler.common.job.JobResult#getResult(java.lang.String) */ public TaskResult getResult(String taskName) throws UnknownTaskException { if (!allResults.containsKey(taskName)) { throw new UnknownTaskException(taskName + " does not exist in this job (jobId=" + id + ")"); } TaskResult tr = futurResults.get(taskName); if (tr == null) { return allResults.get(taskName); } else if (!PAFuture.isAwaited(tr)) { return tr; } else { return null; } } /** * Return any result even if it is awaited futur. * Null is returned only if the given taskName is unknown * <u>For internal Use.</u> * * @param taskName the task name of the result to get. * @return the result if it exists, null if not. */ public TaskResult getAnyResult(String taskName) throws UnknownTaskException { TaskResult tr = futurResults.get(taskName); if (tr == null) { return allResults.get(taskName); } else { return tr; } } /** * @see org.ow2.proactive.scheduler.common.job.JobResult#hadException() */ public boolean hadException() { return getExceptionResults().size() > 0; } /** * @see org.ow2.proactive.scheduler.common.job.JobResult#removeResult(java.lang.String) */ public void removeResult(String taskName) throws UnknownTaskException { if (!allResults.containsKey(taskName)) { throw new UnknownTaskException(taskName + " does not exist in this job (jobId=" + id + ")"); } allResults.put(taskName, null); preciousResults.remove(taskName); } /** * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder toReturn = new StringBuilder("\n"); boolean hasResult = false; for (TaskResult res : allResults.values()) { if (res != null) { hasResult = true; toReturn.append("\t" + res.getTaskId().getReadableName() + " : "); try { toReturn.append(res.value() + "\n"); } catch (Throwable e) { toReturn.append(res.getException().getMessage() + "\n"); } } } if (!hasResult) { return "No result available in this job !"; } else { return toReturn.toString(); } } }
package org.bots.model.datebase; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import java.util.List; import java.util.Map; @Data public class MessageState { @Id private Long id; @Indexed private Long chatId; @Indexed private Integer messageId; private LinkType linkType = LinkType.URL; private Map<Integer, MovieFileHierarchy> movieFileHierarchies; private List<String> hierarchyPath; public enum LinkType{ URL, VLC } }
package com.example.ask3; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.JsonRequest; import com.android.volley.toolbox.Volley; import com.example.Class.Person; import com.example.firstprogram.R; import com.example.firstprogram.TopBar; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; public class QuestionActivity1 extends Activity { private EditText edt1 ; private EditText edt2; private static final String[] str={"1km","2km","3km","其他"}; private ArrayAdapter<String> arrayAdapter; private Spinner spinner; private TopBar topbar; private RequestQueue requestQueue; private JSONObject return_json1; private String url; private Person person; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.question_activity1); person = (Person) getApplication(); spinner = (Spinner) findViewById(R.id.spinner1); edt1 = (EditText)findViewById(R.id.questionTitle); edt2 = (EditText)findViewById(R.id.questionContent); arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, str); arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(arrayAdapter); url = "http://120.24.208.130:1503/event/add"; //topbar topbar = (TopBar) findViewById(R.id.topBar_in_questionactivity1); topbar.setOnTopbarClickListener(new TopBar.topbarClickListener() { @Override public void leftClick() { finish(); } @Override public void rightClick() throws UnsupportedEncodingException { final String title = edt1.getText().toString(); final String content = edt2.getText().toString(); if (title.equals("")) { Toast t = Toast.makeText(QuestionActivity1.this, "请输入标题", Toast.LENGTH_SHORT); t.show(); return; } if (content.equals("")) { Toast t = Toast.makeText(QuestionActivity1.this, "请输入内容", Toast.LENGTH_SHORT); t.show(); return; } requestQueue = new Volley().newRequestQueue(QuestionActivity1.this); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("content", edt1.getText().toString() +"\n" + edt2.getText().toString()); jsonObject.put("id", person.getId()); jsonObject.put("type",0); } catch (JSONException e) { e.printStackTrace(); } JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject jsonObject) { Log.d("TAG", jsonObject.toString()); try { if (jsonObject.getInt("status") == 200) { Toast.makeText(QuestionActivity1.this, "提交成功", Toast.LENGTH_SHORT).show(); finish(); }else if (jsonObject.getInt("status") == 500) { Toast.makeText(QuestionActivity1.this, "提交失败", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); requestQueue.add(jsonRequest); } }); } }
package com.example.trialattemptone.Creators; import android.content.ContentValues; import com.example.trialattemptone.database.StatusTable; public class CourseStatus { private String courseStatus; private int courseStatusID; public CourseStatus() { } public CourseStatus(String statusTitle) { this.courseStatus = statusTitle; } public int getCourseStatusID() { return this.courseStatusID; } public void setCourseStatusID(int csID) { this.courseStatusID = csID; } public void setCourseStatus(String cStatus) { this.courseStatus = cStatus; } public String getCourseStatus() { return this.courseStatus; } public ContentValues toValues() { ContentValues values = new ContentValues(1); values.put(StatusTable.COLUMN_NAME, courseStatus); return values; } }
package br.unb.cic.poo.mh; import org.junit.Assert; import org.junit.Test; import br.unb.poo.mh.Expressao; import br.unb.poo.mh.Igual; import br.unb.poo.mh.PrettyPrinter; import br.unb.poo.mh.TamanhoDasExpressoes; import br.unb.poo.mh.ValorBooleano; import br.unb.poo.mh.ValorInteiro; import br.unb.poo.mh.Tipo; public class TesteExpressaoIgual { private ValorBooleano v_verdadeiro = new ValorBooleano(true); private ValorBooleano v_falso = new ValorBooleano(false); @Test public void testIgualdadeBooleano() { ValorBooleano v1 = new ValorBooleano(true); ValorBooleano v2 = new ValorBooleano(false); ValorBooleano v3 = new ValorBooleano(false); Expressao igualdade = new Igual(v1,v2); Assert.assertEquals(v_falso, igualdade.avaliar()); Assert.assertEquals(v_verdadeiro, new Igual(v2,v3).avaliar()); } @Test public void testIgualdadeInteiro(){ ValorInteiro v1 = new ValorInteiro(10); ValorInteiro v2 = new ValorInteiro(10); ValorInteiro v3 = new ValorInteiro(20); Assert.assertEquals(v_falso, new Igual(v3,v1).avaliar()); Assert.assertEquals(v_verdadeiro, new Igual(v1,v2).avaliar()); } @Test public void testIgualdadeTipoBooleanoOk() { ValorBooleano v1 = new ValorBooleano(true); ValorBooleano v2 = new ValorBooleano(false); Expressao igualdade = new Igual(v1,v2); Assert.assertEquals(Tipo.Booleano, igualdade.tipo()); } @Test public void testIgualdadeTipoInteiroOk(){ ValorInteiro v1 = new ValorInteiro(10); ValorInteiro v2 = new ValorInteiro(10); Assert.assertEquals(Tipo.Booleano, new Igual(v1,v2).tipo()); } @Test public void testIgualdadeTipoNok(){ ValorInteiro v1 = new ValorInteiro(10); ValorBooleano v2 = new ValorBooleano(false); Assert.assertEquals(Tipo.Error, new Igual(v1,v2).tipo()); } @Test public void testeIgualPrint(){ ValorBooleano v2 = new ValorBooleano(false); ValorBooleano v3 = new ValorBooleano(true); Igual equals = new Igual(v2,v3); PrettyPrinter pp = new PrettyPrinter(); equals.aceitar(pp); } @Test public void testeIgualTamanho(){ ValorBooleano v2 = new ValorBooleano(false); ValorBooleano v3 = new ValorBooleano(true); Expressao igual = new Igual(v2,v3); TamanhoDasExpressoes t = new TamanhoDasExpressoes(); igual.aceitar(t); Assert.assertEquals( 3 ,t.getTamanho()); } }
package com.example.blog; import com.example.blog.model.Post; import com.example.blog.model.User; import com.vaadin.data.util.BeanItem; import com.vaadin.navigator.Navigator; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.FormLayout; import com.vaadin.ui.RichTextArea; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; public class AddPostView extends VerticalLayout implements View { public final static String ADD_POST_VIEW = "ADD_POST"; private final FormLayout postForm; private Post post = new Post("", ""); private BeanItem<Post> item = new BeanItem<Post>(post); private final TextField titleField; private final RichTextArea textField; private final Button submit; private final Navigator navigator; public AddPostView(BlogUI root) { this.navigator = root.getNavigator(); this.postForm = new FormLayout(); this.titleField = new TextField("Title: ", item.getItemProperty("title")); this.textField = new RichTextArea("Text:", item.getItemProperty("text")); submit = new Button("Add post", new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { String userName = (String) getSession().getCurrent() .getAttribute("userName"); for (User user : root.getUsers()) { if (user.getName().equals(userName)) { user.getPosts().add(new Post(post.getTitle(), post.getText())); Broadcaster.addPost(new Post(post.getTitle(), post.getText()), user); } } navigator.navigateTo(PostsView.POSTS_VIEW); } }); this.postForm.addComponent(titleField); this.postForm.addComponent(textField); this.postForm.addComponent(submit); this.setSizeFull(); this.addComponent(postForm); this.setComponentAlignment(postForm, Alignment.MIDDLE_CENTER); } @Override public void enter(ViewChangeEvent event) { post.setText(""); post.setTitle(""); // TODO Auto-generated method stub if (getSession().getCurrent().getAttribute("userName") == null) navigator.navigateTo(LoginView.LOGIN_VIEW); } }
/** * Created by Aljaz on 25/10/2017. */ public class Profile { }
package com.egame.app.adapters; import java.io.File; import java.util.List; import java.util.Map; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.os.Environment; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.egame.R; import com.egame.app.EgameApplication; import com.egame.app.services.DBService; import com.egame.app.services.DownloadService; import com.egame.app.uis.GamesDetailActivity; import com.egame.beans.DownloadListBean; import com.egame.config.Const; import com.egame.utils.common.CommonUtil; import com.egame.utils.common.SourceUtils; import com.egame.utils.sys.ApnUtils; import com.egame.utils.ui.ToastUtil; /** * @desc 下载任务适配器 * * @Copyright lenovo * * @Project Egame4th * * @Author yaopp@gzylxx.com * * @timer 2011-01-05 * * @Version 1.0.0 * * @JDK version used 6.0 * * @Modification history none * * @Modified by none */ public class GameDownloadUpdateAdapter extends BaseAdapter { int expendIndex = -999; protected List<DownloadListBean> list; protected Map<String, Bitmap> iconMap; protected Activity context; EgameApplication application; @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } public int getExpendIndex() { return expendIndex; } public void setExpendIndex(int expendIndex) { this.expendIndex = expendIndex; } public GameDownloadUpdateAdapter(List<DownloadListBean> list, Map<String, Bitmap> iconMap, Activity context) { this.list = list; this.context = context; this.application = (EgameApplication) context.getApplication(); steup = context.getResources().getString(R.string.egame_manager_setup); continueStr = context.getResources().getString(R.string.egame_manager_continue); downloadError = "升级出错,请重试";//context.getResources().getString(R.string.egame_manager_download_error); // installed = context.getResources().getString(R.string.egame_manager_installed); pause = context.getResources().getString(R.string.egame_manager_pause); this.iconMap = iconMap; } private String steup; private String continueStr; private String downloadError; // private String installed; private String pause; @Override public View getView(int position, View convertView, ViewGroup parent) { final DownloadListBean bean = list.get(position); final LinearLayout item = (LinearLayout) View.inflate(context, R.layout.egame_game_downloadmission_item, null); if (position == expendIndex) { item.findViewById(R.id.rlGameManagerAction).setVisibility(View.VISIBLE); } TextView name = (TextView) item.findViewById(R.id.name); TextView size = (TextView) item.findViewById(R.id.size); ImageView icon = (ImageView) item.findViewById(R.id.icon); // 按钮 final ImageButton ibDownload = (ImageButton) item.findViewById(R.id.downloadBtn); // 标示的图片暂停、重新下载。。 final ImageView ivMarkpic = (ImageView) item.findViewById(R.id.markpic); // 下载按钮文字 final TextView tvdownText = (TextView) item.findViewById(R.id.downText); // 进度条 ProgressBar progressBar = (ProgressBar) item.findViewById(R.id.progressBar); // 下载按钮下方提示 final TextView tvdownload = (TextView) item.findViewById(R.id.downloading); BitmapDrawable bd = new BitmapDrawable(iconMap.get(bean.getServiceid())); if (null != bd) { icon.setBackgroundDrawable(bd); } name.setText(bean.getName()); if(TextUtils.isEmpty(bean.getSortName())){ size.setText(bean.getGameSizeM()); }else{ size.setText(bean.getSortName()+"类 " + bean.getGameSizeM()); } if (bean.isDownFinishAndNotInstall()) {// 已完成 progressBar.setVisibility(View.GONE); tvdownload.setVisibility(View.GONE); tvdownText.setText(steup); tvdownText.setTextColor(context.getResources().getColor(R.color.egame_text_green)); ivMarkpic.setBackgroundResource(R.drawable.egame_anzhuang); ibDownload.setBackgroundResource(R.drawable.egame_btn_green_selector); } else if (bean.isDownloading()) {// 下载中 tvdownText.setTextColor(context.getResources().getColor(R.color.egame_white)); tvdownText.setText("升级"); ibDownload.setBackgroundResource(R.drawable.egame_huisebutton); ivMarkpic.setBackgroundResource(R.drawable.egame_shengjijingyongicon); tvdownload.setText(context.getString(R.string.egame_manager_updating, "" + bean.getPercentage() + "%...")); } else if (bean.isDownError()) {// 中断 tvdownText.setText(continueStr); tvdownText.setTextColor(context.getResources().getColor(R.color.egame_text_green)); ivMarkpic.setBackgroundResource(R.drawable.egame_chongshiicon); tvdownload.setText(downloadError); ibDownload.setBackgroundResource(R.drawable.egame_btn_green_selector); } else if (bean.isInstalled()) {// 可升級 tvdownText.setText("升级"); tvdownload.setVisibility(View.GONE); tvdownText.setTextColor(context.getResources().getColor(R.color.egame_text_dark_yellow)); ivMarkpic.setBackgroundResource(R.drawable.egame_shengjiicon); progressBar.setVisibility(View.GONE); ibDownload.setBackgroundResource(R.drawable.egame_btn_yellow_selector); } else if (bean.isPause()) { // 已暂停 tvdownText.setText(continueStr); tvdownText.setTextColor(context.getResources().getColor(R.color.egame_text_green)); ivMarkpic.setBackgroundResource(R.drawable.egame_jixu); tvdownload.setText(pause); ibDownload.setBackgroundResource(R.drawable.egame_btn_green_selector); } // // 下载异常 // else if (downloadState == 999999) { // tvdownText.setText("重试"); // tvdownText.setTextColor(R.color.egame_text_green); // ivMarkpic.setBackgroundResource(R.drawable.egame_chongshiicon); // tvdownload.setText("下载出错,请重试..."); // ibDownload.setBackgroundResource(R.drawable.egame_greenbuttonon); // } // 设置进度条 progressBar.setProgress(bean.getPercentage()); ibDownload.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (bean.isDownFinishAndNotInstall()) { // 点击安装 CommonUtil.installGames(bean.getServiceid(), context); } else if (bean.isDownError() || bean.isPause()) { // 点击继续 // L.d("down2", "totalsize:" + bean.getTotalsize()); Bundle bundle = DownloadService.getBundle(context, Integer.parseInt(bean.getServiceid()), (int)(bean.getTotalsize() / 1024), application.getPhoneNum(), bean.getCpid(), bean.getCpcode(), bean.getServiceCode(), bean.getName(), bean.getChannelid(), bean.getIconurl(), application.getUA(), CommonUtil.getUserId(context), SourceUtils.DEFAULT,bean.getSortName()); Intent intent = new Intent(context, DownloadService.class); intent.putExtras(bundle); context.startService(intent); } else if (bean.isDownloading()) { // Intent intent = new Intent("com.egame.app.services.DownloadService"); // intent.putExtra("msg", "pause"); // intent.putExtra("gameid", bean.getServiceid()); // context.sendBroadcast(intent); } else if (bean.isInstalled()) { if (ApnUtils.checkNetWorkStatus(context)) { if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) { ToastUtil.show(context, R.string.egame_addUpdate_hint); Bundle bundle = DownloadService.getBundle(context, Integer.parseInt(bean.getServiceid()), (int)(bean.getTotalsize() / 1024), application.getPhoneNum(), bean.getCpid(), bean.getCpcode(), bean.getServiceCode(), bean.getName(), bean.getChannelid(), bean.getIconurl(), application.getUA(), CommonUtil.getUserId(context), SourceUtils.DEFAULT,bean.getSortName()); Intent intent = new Intent(context, DownloadService.class); intent.putExtras(bundle); context.startService(intent); } else { ToastUtil.show(context, "未找到SD卡,请插入"); } } else { ToastUtil.show(context, "无法连接到网络,请检查网络配置"); } } } }); View ib_ycgl = item.findViewById(R.id.ib_ycgl); // 隐藏管理 ib_ycgl.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { expendIndex = -999; item.findViewById(R.id.rlGameManagerAction).setVisibility(View.GONE); } }); TextView ib_scxz = (TextView) item.findViewById(R.id.ib_scxz); ib_scxz.setText("取消升级"); // 删除下载 ib_scxz.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // item.findViewById(R.id.rlGameManagerAction).setVisibility(View.GONE); try { if (bean.isDownloading()) { Intent intent = new Intent("com.egame.app.services.DownloadService"); intent.putExtra("msg", "cancel"); intent.putExtra("gameid", bean.getServiceid()); context.sendBroadcast(intent); } else if (bean.isDownError() || bean.isDownFinishAndNotInstall() || bean.isPause() || bean.isInstalled()) { new File(Const.DIRECTORY + "/" + bean.getServiceid() + ".apk").delete(); new File(Const.DIRECTORY + "/" + bean.getServiceid() + ".apk" + DownloadService.TEMP_FILE_FIX).delete(); DBService dbservice = new DBService(context); dbservice.open(); // dbservice.delGameByServiceId(Integer.parseInt(bean.getServiceid())); dbservice.updateData(bean.getServiceid(), DBService.KEY_STATE, DBService.DOWNSTATE_INSTALLED); dbservice.updateData(bean.getServiceid(), DBService.KEY_CANCEL_UPDATE_TIME, System.currentTimeMillis() + ""); dbservice.close(); CommonUtil.sendChangeBroadCast(context); } expendIndex = -999; notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); } } }); View ib_ckxq = item.findViewById(R.id.ib_ckxq); // 查看详情 ib_ckxq.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { Bundle bundle = GamesDetailActivity.makeIntentData(Integer.parseInt(bean.getServiceid()), SourceUtils.DEFAULT); Intent intent = new Intent(context, GamesDetailActivity.class); intent.putExtras(bundle); context.startActivity(intent); } catch (Exception e) { e.printStackTrace(); } } }); return item; } }
import java.util.*; // package 14Lab; /** * Key.java * @author Victor Lourng, Dan Burger, Eric Hart, Jacob Davis * @version 2016 */ public class KeyRoom extends Room { private boolean hasKey = true; public KeyRoom(){ super(); } public void grabKey(boolean hasKey){ if(hasKey == true) else if (hasKey == false){ System.out.println("You ") } } }
package com.intelligt.modbus.jlibmodbus.serial; import java.util.List; /* * Copyright (C) 2016 "Invertor" Factory", JSC * [http://www.sbp-invertor.ru] * * This file is part of JLibModbus. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Authors: Vladislav Y. Kochedykov, software engineer. * email: vladislav.kochedykov@gmail.com */ public class SerialUtils { static private SerialPortAbstractFactory factory; final static private SerialPortFactoryJSSC FACTORY_JSSC = new SerialPortFactoryJSSC(); final static private SerialPortFactoryRXTX FACTORY_RXTX = new SerialPortFactoryRXTX(); final static private SerialPortFactoryJSerialComm FACTORY_JSERIAL_COMM = new SerialPortFactoryJSerialComm(); final static private SerialPortFactoryPJC FACTORY_PJC = new SerialPortFactoryPJC(); final static private SerialPortFactoryAT FACTORY_AT = new SerialPortFactoryAT(); @Deprecated final static private SerialPortFactoryJavaComm FACTORY_JAVA_COMM = new SerialPortFactoryJavaComm(); final static private SerialPortAbstractFactory[] SERIAL_FACTORIES = new SerialPortAbstractFactory[] { FACTORY_JSERIAL_COMM, FACTORY_JSSC, FACTORY_RXTX, FACTORY_PJC, FACTORY_AT, FACTORY_JAVA_COMM}; /* static public boolean isThingsDevice(Context context) { final PackageManager pm = context.getPackageManager(); return pm.hasSystemFeature(PackageManager.FEATURE_EMBEDDED); } */ static { for (SerialPortAbstractFactory f : SERIAL_FACTORIES) { if (f.available()) { setSerialPortFactory(f); break; } } } static public void setSerialPortFactoryJSSC() { setSerialPortFactory(FACTORY_JSSC); } static public void setSerialPortFactoryRXTX() { setSerialPortFactory(FACTORY_RXTX); } static public void setSerialPortFactoryJSerialComm() { setSerialPortFactory(FACTORY_JSERIAL_COMM); } static public void setSerialPortFactoryPureJavaComm() { setSerialPortFactory(FACTORY_PJC); } static public void setSerialPortFactoryAndroidThings() { setSerialPortFactory(FACTORY_AT); } @Deprecated static public void setSerialPortFactoryJavaComm() { SerialUtils.factory = FACTORY_JAVA_COMM; } static public SerialPort createSerial(SerialParameters sp) throws SerialPortException { return getSerialPortFactory().createSerial(sp); } static public List<String> getPortIdentifiers() throws SerialPortException { return getSerialPortFactory().getPortIdentifiers(); } static public String getConnectorVersion() { return getSerialPortFactory().getVersion(); } /** * @param factory - a concrete serial port factory instance * @since 1.2.1 */ static public void setSerialPortFactory(SerialPortAbstractFactory factory) { SerialUtils.factory = factory; } static public SerialPortAbstractFactory getSerialPortFactory() { return SerialUtils.factory; } }
package com.xp.springboot.services; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.xp.springboot.entities.Employee; import com.xp.springboot.exception.EmployeeNotFoundException; import com.xp.springboot.repository.EmployeeRepository; /** * Represents Employee service layer to interact with Employee Repository and provide * services to Employee Controller. * * @author Swapnil Ahirrao * */ @Service public class EmployeeService { @Autowired EmployeeRepository empRepository; /** * Method to get all the employee present in DB * * @return List<Employee> */ public List<Employee> getAllEmployee(){ return empRepository.findAll(); } /** * Method to return employee with passed employee id * * @param empId * @return Employee */ public Employee getEmployee(int empId) { Optional<Employee> emp=empRepository.findById(empId); if(emp.isPresent()) return emp.get(); else throw new EmployeeNotFoundException(empId); } /** * Method to create or update employee if already exists with provided employee object * * @param employee * @return Employee */ public Employee createOrUpdateEmployee(Employee employee) { Optional<Employee> emp=empRepository.findById(employee.getEmpId()); if(emp.isPresent()) { Employee empEntity=emp.get(); empEntity.setAge(employee.getAge()); empEntity.setEmpName(employee.getEmpName()); empEntity.setEmpSalary(employee.getEmpSalary()); empEntity=empRepository.save(empEntity); return empEntity; }else { employee=empRepository.save(employee); return employee; } } /** * Method to delete employee from database if already exists * * @param empId * @return Boolean */ public boolean deleteEmployee(int empId) { Optional<Employee> emp=empRepository.findById(empId); if(emp.isPresent()) { empRepository.deleteById(empId); } else { throw new EmployeeNotFoundException(empId); } return true; } }
package com.ytdsuda.management.VO; import com.sun.org.apache.xpath.internal.operations.Bool; import lombok.Data; /* http最外层对象 * */ @Data public class ResultVO<T> { // 错误码 private Boolean success = true; // 提示信息 private String errorMsg = null; private Boolean login = true; /*data,返回的具体内容 data是一个对象, 可以定义一个范型*/ private T data = null; }
package com.karzaassignment; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import static android.Manifest.permission.ACCESS_FINE_LOCATION; import static android.Manifest.permission.CAMERA; import static android.Manifest.permission.READ_EXTERNAL_STORAGE; import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; public class BaseActivity extends AppCompatActivity { public String[] neededPermissions = new String[]{CAMERA, WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE, ACCESS_FINE_LOCATION}; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public void showSettingsDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this); builder.setTitle("Need Permissions"); builder.setMessage("This app needs permission to use this feature. You can grant them in app settings."); builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); openSettings(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } // navigating user to app settings private void openSettings() { Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", getPackageName(), null); intent.setData(uri); startActivityForResult(intent, 101); } public void showProgress() { progressDialog = new ProgressDialog(this); progressDialog.setMessage("Please wait..."); progressDialog.show(); } public void hideProgress() { progressDialog.hide(); } }
package gov.nist.hit.core.service.impl; import gov.nist.healthcare.unified.exceptions.ConversionException; import gov.nist.healthcare.unified.exceptions.NotFoundException; import gov.nist.healthcare.unified.model.*; import gov.nist.hit.core.domain.TestContext; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * This software was developed at the National Institute of Standards and Technology by employees of * the Federal Government in the course of their official duties. Pursuant to title 17 Section 105 * of the United States Code this software is not subject to copyright protection and is in the * public domain. This is an experimental system. NIST assumes no responsibility whatsoever for its * use by other parties, and makes no guarantees, expressed or implied, about its quality, * reliability, or any other characteristic. We would appreciate acknowledgement if the software is * used. This software can be redistributed and/or modified freely provided that any derivative * works bear some notice that they are derived from it, and any modified versions bear some notice * that they have been modified. * * Created by mcl1 on 10/21/16. * * The ValidationLogReport is a minimalist version of the EnhancedReport that contains * only the information we need to display the validation logs. * */ public class ValidationLogReport { private String messageId; private String format; private String testingStage; private int errorCount = 0; private int warningCount = 0; private Date date; private Map<String, Integer> errorCountInSegment; private boolean validationResult = true; /* * This constructor parses the EnhancedReport to take only the information we need from it. */ public ValidationLogReport(TestContext testContext, EnhancedReport report) { this.date = new Date(); this.errorCountInSegment = new HashMap<>(); Detections detections = report.getDetections(); //Loop on the classifications (Affirmative, Warning or Error) for (Classification classification : detections.classes()) { if (classification.getName().equals("Affirmative")) { //No need to display any log here } else if (classification.getName().equals("Warning")) { //Get the warning count this.warningCount = classification.keys().size(); } else if (classification.getName().equals("Error")) { //Get the error count this.errorCount = classification.keys().size(); if (this.errorCount > 0) { //If there is more than 0 errors, then the validation failed this.validationResult = false; //Loop on the errors for (String key : classification.keys()) { Collection collection = null; try { collection = classification.getArray(key); if(collection!=null && collection.size()>0) { for (int i = 0; i < collection.size(); i++) { Section section = collection.getObject(i); //Identify the path of the error String path = section.getString("path"); if (path != null && !"".equals(path)) { path = path.split("\\[")[0]; int segmentErrorCount = 1; //If there was already at least 1 error for this segment, then increment its error count. if (this.errorCountInSegment.containsKey(path)) { segmentErrorCount = this.errorCountInSegment.get(path) + 1; } //Add or update the segment's error count this.errorCountInSegment.put(path, segmentErrorCount); } } } } catch (NotFoundException e) { e.printStackTrace(); } catch (ConversionException e) { e.printStackTrace(); } } } } } //Parse the test context if(testContext != null){ this.format = (testContext.getFormat()!=null?testContext.getFormat():""); this.messageId = (testContext.getType()!=null?testContext.getType():""); this.testingStage = (testContext.getStage().name()!=null?testContext.getStage().name():""); } } public String getMessageId() { return messageId; } public void setMessageId(String messageId) { this.messageId = messageId; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public int getErrorCount() { return errorCount; } public void setErrorCount(int errorCount) { this.errorCount = errorCount; } public int getWarningCount() { return warningCount; } public void setWarningCount(int warningCount) { this.warningCount = warningCount; } public String getDate(String format) { //Format the date as specified SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); if(this.date==null){ this.date = new Date(); } return simpleDateFormat.format(this.date); } public void setDate(Date date) { this.date = date; } public Map<String, Integer> getErrorCountInSegment() { return errorCountInSegment; } public void setErrorCountInSegment(Map<String, Integer> errorCountInSegment) { this.errorCountInSegment = errorCountInSegment; } public boolean isValidationResult() { return validationResult; } public void setValidationResult(boolean validationResult) { this.validationResult = validationResult; } public String getTestingStage() { return testingStage; } public void setTestingStage(String testingStage) { this.testingStage = testingStage; } }
package com.theshoes.jsp.board.model.service; import static com.theshoes.jsp.common.mybatis.Template.getSqlSession; import java.util.List; import org.apache.ibatis.session.SqlSession; import com.theshoes.jsp.board.model.dao.BoardDAO; import com.theshoes.jsp.board.model.dao.ResellListDAO; import com.theshoes.jsp.board.model.dto.CommentsDTO; import com.theshoes.jsp.board.model.dto.ResellDetailDTO; import com.theshoes.jsp.board.model.dto.ResellListDTO; import com.theshoes.jsp.board.model.dto.ResellThumbDTO; import com.theshoes.jsp.common.paging.SelectCriteria; public class ResellListService { private final ResellListDAO resellListDAO; public ResellListService() { resellListDAO = new ResellListDAO(); } public List<ResellDetailDTO> selectResellList(SelectCriteria selectCriteria) { SqlSession session = getSqlSession(); List<ResellDetailDTO> resellList = resellListDAO.selectResellList(session, selectCriteria); System.out.println("resellList" + resellList); session.close(); return resellList; } /* 리셀 디테일 */ public ResellDetailDTO selectOneResellList(int no) { SqlSession session = getSqlSession(); ResellDetailDTO resellDetail = null; /* 게시글 조회수 */ int result = resellListDAO.incrementResellCount(session, no); if(result > 0) { resellDetail = resellListDAO.selectOneResellList(session, no); System.out.println(resellDetail); if(resellDetail != null) { session.commit(); } else { session.rollback(); } } else { session.rollback(); } return resellDetail; } public int insertResellShoes(ResellListDTO resell) { SqlSession session = getSqlSession(); System.out.println("test"); int result = 0; int resellResult = resellListDAO.insertResellShoes(session, resell); System.out.println("board Insert Test"); List<ResellThumbDTO> fileList = resell.getResellThumb(); int resellShoesThumbResult = 0; for(int i = 0; i < fileList.size(); i++) { fileList.get(i).setResellThumbNo(i + 1); resellShoesThumbResult += resellListDAO.insertResellThumb(session, fileList.get(i)); } if(resellResult > 0 && resellShoesThumbResult == fileList.size()) { session.commit(); result = 1; } else { session.rollback(); } session.close(); return result; } public int selectResellTotalCount() { SqlSession session = getSqlSession(); int totalCount = resellListDAO.selectResellTotalCount(session); session.close(); return totalCount; } public int comments(CommentsDTO commentsDTO) { SqlSession session = getSqlSession(); int result = resellListDAO.comments(session, commentsDTO); if(result > 0) { session.commit(); } else { session.rollback(); } session.close(); return result; } public int deleteComment(int no) { SqlSession session = getSqlSession(); int result = resellListDAO.deleteComment(session, no); if(result > 0) { session.commit(); } else { session.rollback(); } session.close(); return result; } }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): ActiveEon Team - http://www.activeeon.com * * ################################################################ * $$ACTIVEEON_CONTRIBUTOR$$ */ package functionaltests.nonblockingcore; import static junit.framework.Assert.assertTrue; import java.io.File; import java.net.URL; import javax.security.auth.login.LoginException; import org.junit.Assert; import org.objectweb.proactive.api.PAFuture; import org.objectweb.proactive.core.util.ProActiveInet; import org.ow2.proactive.authentication.crypto.CredData; import org.ow2.proactive.authentication.crypto.Credentials; import org.ow2.proactive.resourcemanager.authentication.RMAuthentication; import org.ow2.proactive.resourcemanager.common.event.RMEventType; import org.ow2.proactive.resourcemanager.core.properties.PAResourceManagerProperties; import org.ow2.proactive.resourcemanager.frontend.RMConnection; import org.ow2.proactive.resourcemanager.frontend.ResourceManager; import org.ow2.proactive.resourcemanager.nodesource.NodeSource; import org.ow2.proactive.scripting.SelectionScript; import org.ow2.proactive.utils.NodeSet; import org.ow2.tests.FunctionalTest; import functionaltests.RMTHelper; import functionaltests.selectionscript.SelectionScriptTimeOutTest; /** * Test starts node selection using timeout script. At the same time adds and removes node source and nodes to the RM. * Checks that blocking in the node selection mechanism does not prevent usage of RMAdmin interface. * * @author ProActice team * */ public class NonBlockingCoreTest extends FunctionalTest { private URL selectionScriptWithtimeOutPath = SelectionScriptTimeOutTest.class .getResource("selectionScriptWithtimeOut.js"); private NodeSet nodes; /** Actions to be Perform by this test. * The method is called automatically by Junit framework. * @throws Exception If the test fails. */ @org.junit.Test public void action() throws Exception { ResourceManager resourceManager = RMTHelper.getResourceManager(); RMTHelper.log("Deployment"); RMTHelper.createDefaultNodeSource(); RMTHelper.waitForNodeSourceEvent(RMEventType.NODESOURCE_CREATED, NodeSource.DEFAULT); for (int i = 0; i < RMTHelper.defaultNodesNumber; i++) { RMTHelper.waitForAnyNodeEvent(RMEventType.NODE_ADDED); //waiting for node to be in free state RMTHelper.waitForAnyNodeEvent(RMEventType.NODE_STATE_CHANGED); } int coreScriptExecutionTimeout = PAResourceManagerProperties.RM_SELECT_SCRIPT_TIMEOUT.getValueAsInt(); int scriptSleepingTime = coreScriptExecutionTimeout * 2; RMTHelper.log("Selecting node with timeout script"); //create the static selection script object final SelectionScript sScript = new SelectionScript(new File(selectionScriptWithtimeOutPath.toURI()), new String[] { Integer.toString(scriptSleepingTime) }, false); //mandatory to use RMUser AO, otherwise, getAtMostNode we be send in RMAdmin request queue final RMAuthentication auth = RMConnection.waitAndJoin(null); final Credentials cred = Credentials.createCredentials(new CredData(RMTHelper.username, RMTHelper.password), auth.getPublicKey()); // cannot connect twice from the same active object // so creating another thread Thread t = new Thread() { public void run() { ResourceManager rm2; try { rm2 = auth.login(cred); nodes = rm2.getAtMostNodes(2, sScript); } catch (LoginException e) { } } }; t.start(); String hostName = ProActiveInet.getInstance().getHostname(); String node1Name = "node1"; String node1URL = "//" + hostName + "/" + node1Name; RMTHelper.createNode(node1Name); RMTHelper.log("Adding node " + node1URL); resourceManager.addNode(node1URL); RMTHelper.waitForNodeEvent(RMEventType.NODE_ADDED, node1URL); //waiting for node to be in free state, it is in configuring state when added... RMTHelper.waitForAnyNodeEvent(RMEventType.NODE_STATE_CHANGED); assertTrue(resourceManager.getState().getTotalNodesNumber() == RMTHelper.defaultNodesNumber + 1); assertTrue(resourceManager.getState().getFreeNodesNumber() == RMTHelper.defaultNodesNumber + 1); //preemptive removal is useless for this case, because node is free RMTHelper.log("Removing node " + node1URL); resourceManager.removeNode(node1URL, false); RMTHelper.waitForNodeEvent(RMEventType.NODE_REMOVED, node1URL); assertTrue(resourceManager.getState().getTotalNodesNumber() == RMTHelper.defaultNodesNumber); assertTrue(resourceManager.getState().getFreeNodesNumber() == RMTHelper.defaultNodesNumber); RMTHelper.log("Creating Local node source " + NodeSource.LOCAL_INFRASTRUCTURE_NAME); RMTHelper.createLocalNodeSource(); //wait for creation of GCM Node Source event, and deployment of its nodes RMTHelper .waitForNodeSourceEvent(RMEventType.NODESOURCE_CREATED, NodeSource.LOCAL_INFRASTRUCTURE_NAME); for (int i = 0; i < RMTHelper.defaultNodesNumber; i++) { RMTHelper.waitForAnyNodeEvent(RMEventType.NODE_ADDED); RMTHelper.waitForAnyNodeEvent(RMEventType.NODE_REMOVED); //waiting for the node to be in free state RMTHelper.waitForAnyNodeEvent(RMEventType.NODE_ADDED); RMTHelper.waitForAnyNodeEvent(RMEventType.NODE_STATE_CHANGED); } assertTrue(resourceManager.getState().getTotalNodesNumber() == RMTHelper.defaultNodesNumber * 2); assertTrue(resourceManager.getState().getFreeNodesNumber() == RMTHelper.defaultNodesNumber * 2); RMTHelper.log("Removing node source " + NodeSource.LOCAL_INFRASTRUCTURE_NAME); resourceManager.removeNodeSource(NodeSource.LOCAL_INFRASTRUCTURE_NAME, true); boolean selectionInProgress = PAFuture.isAwaited(nodes); if (!selectionInProgress) { // normally we are looking for 2 nodes with timeout script, // so the selection procedure has to finish not earlier than // coreScriptExecutionTimeout * RMTHelper.defaultNodesNumber // it should be sufficient to perform all admin operations concurrently // // if the core is blocked admin operations will be performed after selection Assert.assertTrue("Blocked inside RMCore", false); } else { RMTHelper.log("No blocking inside RMCore"); } } }
package burst; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.PoisonPill; import akka.event.Logging; import akka.event.LoggingAdapter; import burst.messages.CalculationRequest; import burst.messages.CalculationResult; import burst.messages.CompilationRequest; import burst.messages.CompilationResult; import burst.messages.Task; import burst.spring.SpringExtension; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; import java.util.Random; import java.util.concurrent.TimeUnit; import scala.concurrent.duration.Duration; import akka.japi.Function; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.Executors; import static akka.dispatch.Futures.future; import static java.util.concurrent.TimeUnit.SECONDS; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import scala.concurrent.Await; import scala.concurrent.ExecutionContext; import scala.concurrent.Future; import akka.actor.Props; import akka.dispatch.Futures; import akka.dispatch.OnComplete; import akka.dispatch.OnFailure; import akka.dispatch.OnSuccess; import akka.pattern.Patterns; import akka.util.Timeout; import static akka.dispatch.Futures.traverse; /** * Tool to trigger messages passed to actors. */ @Configuration @EnableAutoConfiguration @ComponentScan("burst.configuration") public class App { public static void main(String[] args) throws Exception { ApplicationContext context = SpringApplication.run(App.class, args); ActorSystem system = context.getBean(ActorSystem.class); final LoggingAdapter log = Logging.getLogger(system, App.class.getSimpleName()); log.info("Starting up"); SpringExtension ext = context.getBean(SpringExtension.class); // Use the Spring Extension to create props for a named actor bean ActorRef calculator = system.actorOf(ext.props("calculator").withMailbox("akka.priority-mailbox")); /* * Create a completion service instance to await all futures */ final ExecutionContext ec = system.dispatcher(); Timeout timeout = new Timeout(120, TimeUnit.SECONDS); List<Long> ids = new ArrayList<>(); ArrayList<Future<Object>> futures = new ArrayList<Future<Object>>(); for (int i = 1; i <= 10; i++) { Future<Object> future = Patterns.ask(calculator, new CompilationRequest(i + " + 5"), timeout); future.onSuccess(new OnSuccess<Object>() { public void onSuccess(Object result) { if(result instanceof CompilationResult) { synchronized(ids) { log.debug("Compilation result {} ", result.toString()); ids.add(((CompilationResult)result).getExpressionId()); } } else { log.info("Compilation result is unknown type {} ", result.toString()); } } }, ec); futures.add(future); } Future<Iterable<Object>> seq = Futures.sequence(futures, ec); Await.result(seq, Duration.create(30, SECONDS)); log.info("======================================================"); log.info("Done waiting for compilations...{} ids", ids.size()); log.info("======================================================"); futures.clear(); long start = System.nanoTime(); List<Double> results = new ArrayList<>(); Long count = 1_000_000L; for (long i = 1; i <= count; i++) { Future<Object> future = Patterns.ask(calculator, new CalculationRequest(i, ids.get((int)(i % ids.size())), null), timeout); future.onSuccess(new OnSuccess<Object>() { public void onSuccess(Object result) { if (result instanceof CalculationResult) { log.debug("Calculation result {} ", result.toString()); // synchronized(results) // { // results.add((Double) ((CalculationResult) result).getValue()); // } } else { log.info("Calculation result is unknown type {} ", result.toString()); } } }, ec); futures.add(future); } seq = Futures.sequence(futures, ec); Await.result(seq, Duration.create(600, SECONDS)); calculator.tell(PoisonPill.getInstance(), null); while (!calculator.isTerminated()) { Thread.sleep(100); } long end = System.nanoTime(); // //int count = context.getBean(JdbcTemplate.class).queryForObject("SELECT COUNT(*) FROM tasks", Integer.class); Long elapsed = TimeUnit.MILLISECONDS.convert((end - start), TimeUnit.NANOSECONDS); Double tps = count.doubleValue()/(elapsed.doubleValue()/Double.parseDouble("1000")); log.info("{} calculations in {}ms {}tps", count, elapsed, tps); log.info("Shutting down ------------------------------> {}", results.size()); Thread.sleep(10000); system.shutdown(); system.awaitTermination(); } }
package client; import common.Constant; import common.ReadAndWriteElement; import common.WorkWithPacket; import common.WorkWithString; import javax.swing.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.List; class Control { private Socket socket; private ObjectOutputStream out; private File pathAbsoluteElementSave; private boolean isAuthorized = false; private Client client; private WorkWithPacket workWithPacket; private ReadAndWriteElement readAndWriteElement; private boolean isConnect = true; public Control(Client client) { this.client = client; start(); workWithPacket = new WorkWithPacket(out); readAndWriteElement = new ReadAndWriteElement(); //для debug // String[] strings = {"leo", "1111"}; // workWithPacket.sendPacket(Constant.SIGNIN, strings); listenerSignIn(); listenerSignUp(); listenerDownload(); listenerUpload(); listenerReload(); listenerDelete(); listenerMakeDir(); listenerRename(); listenerCreateNewFile(); listenerEnd(); listenerExit(); setAuthorized(false); } public void start() { try { socket = new Socket(Constant.SERVER_IP, Constant.PORT); out = new ObjectOutputStream(socket.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } new Thread(() -> { try (ObjectInputStream in = new ObjectInputStream(socket.getInputStream())) { while (isConnect) { takePacket(in.readObject()); } System.out.println(isConnect); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }).start(); } public void move(String str) { workWithPacket.sendPacket(Constant.MOVE, str); } public void listenerEnd() { client.addWindowListener(new WindowAdapter() { //отвечает за закрытие соединения при закрытии окна через крестик @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); isConnect = false; workWithPacket.sendPacket(Constant.END, null); } }); } public void listenerExit() { client.jbExit.addActionListener(e -> { workWithPacket.sendPacket(Constant.EXIT, null); setAuthorized(false); client.defaultListModel.clear(); }); } private void listenerCreateNewFile() { client.jbCreateNewFile.addActionListener(e -> { String nameNewFile = (String) JOptionPane.showInputDialog(client, Constant.ENTER_NAME_NEW_FILE , Constant.CREATE_NEW_FILE, JOptionPane.QUESTION_MESSAGE, null, null, Constant.DEFAULT_NAME_NEW_FILE); if (nameNewFile != null) { workWithPacket.sendPacket(Constant.NEW_FILE, nameNewFile); } }); } private void listenerRename() {//переименование client.jbRename.addActionListener(e -> { Object selectedElement; if ((selectedElement = client.list.getSelectedValue()) != null) { String nameOld = selectedElement.toString(); nameOld = WorkWithString.withoutBrackets(nameOld); String nameNew = (String) JOptionPane.showInputDialog(client, Constant.ENTER_NEW_NAME, Constant.TITLE_RENAME, JOptionPane.QUESTION_MESSAGE, null, null, nameOld); System.out.println(nameNew); if (nameNew != null) { String[] body = {nameOld, nameNew}; workWithPacket.sendPacket(Constant.RENAME, body); } } }); } private void listenerMakeDir() {//создание каталога client.jbCreateNewDir.addActionListener(e -> { String str = JOptionPane.showInputDialog(client, new String[]{Constant.ENTER_NAME_NEW_DIR}, Constant.CREATE_NEW_DIR, JOptionPane.WARNING_MESSAGE); if (str != null) { workWithPacket.sendPacket(Constant.MAKE_DIR, str); } }); } public void listenerDownload() {//скачать файл с сервера client.jbDownload.addActionListener(e -> { Object elementSelected; if ((elementSelected = client.list.getSelectedValue()) != null) {//выделенный элемент в листе File defaultPath = new File(Constant.DEFAULT_DOWNLOAD_DIR);//путь по умолчанию JFileChooser jFileChooser = new JFileChooser(defaultPath); String elementSelectedString = elementSelected.toString();//наименование файла по умолчанию elementSelectedString = WorkWithString.withoutBrackets(elementSelectedString);//наименование файла по умолчанию jFileChooser.setSelectedFile(new File(elementSelectedString)); jFileChooser.setDialogTitle(Constant.TITLE_SAVE_FILE); int result = jFileChooser.showSaveDialog(null); if (result == JFileChooser.APPROVE_OPTION) { pathAbsoluteElementSave = jFileChooser.getSelectedFile();//куда сохранять workWithPacket.sendPacket(Constant.DOWNLOAD, elementSelectedString);//какой файл выбрали в списке } } }); } public void listenerUpload() {//закачать файл на сервер client.jbUpload.addActionListener(e -> { File defaultPath = new File(Constant.DEFAULT_DOWNLOAD_DIR);//путь по умолчанию JFileChooser jFileChooser = new JFileChooser(defaultPath); jFileChooser.setDialogTitle(Constant.TITLE_OPEN_FILE); jFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); int result = jFileChooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { File selectedFile = jFileChooser.getSelectedFile();//выделенный файл Object object = readAndWriteElement.readElement(selectedFile); Object[] body = {selectedFile.getName(), object}; workWithPacket.sendPacket(Constant.UPLOAD, body); } }); } public void listenerReload() {//обновить список файлов client.jbReload.addActionListener(e -> workWithPacket.sendPacket(Constant.RELOAD, null)); } public void listenerSignIn() {//авторизоваться client.jbSignIn.addActionListener(e -> { if (socket == null || socket.isClosed()) start(); Object[] objects = {client.jtfLogin.getText(), client.jtfPassword.getText()}; workWithPacket.sendPacket(Constant.SIGNIN, objects); client.jtfLogin.setText(""); client.jtfPassword.setText(""); }); } public void listenerSignUp() {//зарегистрироваться client.jbSignUp.addActionListener(e -> { if (socket == null || socket.isClosed()) start(); Object[] objects = {client.jtfLogin.getText(), client.jtfPassword.getText()}; workWithPacket.sendPacket(Constant.SIGNUP, objects); client.jtfLogin.setText(""); client.jtfPassword.setText(""); }); } private void listenerDelete() {//удаление файла client.jbDelete.addActionListener(e -> { List elementSelectedList; if ((elementSelectedList = client.list.getSelectedValuesList()) != null) { int result = JOptionPane.showConfirmDialog(client, Constant.ARE_YOU_SURE, Constant.TITLE_CONFIRMATION_WINDOW, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (result == 0) { for (Object elementSelected : elementSelectedList) { workWithPacket.sendPacket(Constant.DELETE, elementSelected.toString()); } } } }); } public void setAuthorized(boolean authorized) { //скрываем панели для авторизованых и неавторизованых пользователей isAuthorized = authorized; client.topPanel.setVisible(!isAuthorized); client.rightPanel.setVisible(isAuthorized); } public void takePacket(Object answer) {//принять сообщение в виде массива Object if (answer instanceof Object[]) { Object[] packet = (Object[]) answer; String head = (String) packet[0]; Object body = packet[1]; checkHead(head, body); } } public void checkHead(String head, Object body) {//в зависимости от head, сделать с body switch (head) { case Constant.AUTHOK: setAuthorized(true); break; case Constant.TEXT_MESSAGE: showMessageDialog((String) body); break; case Constant.FILE_LIST: showFileList(body); break; case Constant.DOWNLOAD: downloadFile(body); break; } } private void showFileList(Object body) { client.defaultListModel.clear(); String[] fileList = (String[]) body; for (String fileName : fileList) { client.defaultListModel.addElement(fileName); } } public void showMessageDialog(String msg) {//показать у клиента диалоговое окно с сообщением JOptionPane.showMessageDialog(null, msg); } public void downloadFile(Object body) { readAndWriteElement.writeElement(body, pathAbsoluteElementSave); } }
package com.aisino.invoice.xtjk.po; import java.util.List; /** * @ClassName: FwkpUserFpzlEX * @Description: * @Copyright 2017 航天信息股份有限公司-版权所有 */ public class FwkpUserFpzl { private String xfsh; private Integer kpjh; private String qymc; private List<String> zdhmList; private List<Integer> fpzList; public String getXfsh() { return xfsh; } public void setXfsh(String xfsh) { this.xfsh = xfsh; } public Integer getKpjh() { return kpjh; } public void setKpjh(Integer kpjh) { this.kpjh = kpjh; } public String getQymc() { return qymc; } public void setQymc(String qymc) { this.qymc = qymc; } public List<String> getZdhmList() { return zdhmList; } public void setZdhmList(List<String> zdhmList) { this.zdhmList = zdhmList; } public List<Integer> getFpzList() { return fpzList; } public void setFpzList(List<Integer> fpzList) { this.fpzList = fpzList; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Controller.Admin; import Business.RoomBookingBAL; import Entity.Booking; import Entity.RoomBooking; import java.util.List; import java.util.TimeZone; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; /** * * @author TUNT */ @ManagedBean @RequestScoped public class RoomBookingList { /** Creates a new instance of RoomBookingList */ public RoomBookingList() { } private String redirect = "?faces-redirect=true"; private static int choice = 0; private static String bookingChoice = "Room bookings"; private static String bookedChoice = "Room bookeds"; private static Booking booking; private String errorMessage = "none"; private TimeZone timeZone = TimeZone.getDefault(); public TimeZone getTimeZone() { return timeZone; } public void setTimeZone(TimeZone timeZone) { this.timeZone = timeZone; } public int getChoice() { return choice; } public void setChoice(int choice) { RoomBookingList.choice = choice; } public String getBookingChoice() { return bookingChoice; } public String getBookedChoice() { return bookedChoice; } public Booking getBooking() { return booking; } public void setBooking(Booking booking) { RoomBookingList.booking = booking; } public String getErrorMessage() { return errorMessage; } public String getAction() { if(choice == 0) { return "block"; } else { return "none"; } } public String choice() { if (choice == 0) { choice = 1; bookingChoice = "Room bookeds"; bookedChoice = "Room bookings"; } else { choice = 0; bookingChoice = "Room bookings"; bookedChoice = "Room bookeds"; } return "RoomBookingList" + redirect; } private List<RoomBooking> roomBookingList; public List<RoomBooking> getRoomBookingList() { if (choice == 0) { roomBookingList = RoomBookingBAL.getInstance().getTableBookingList(); } else { roomBookingList = RoomBookingBAL.getInstance().getTableBookedList(); } return roomBookingList; } public String viewRoomBooking() { return "RoomBookingDetails" + redirect; } public String updateRoomBooking() { if(RoomBookingBAL.getInstance().updateRoomBooking(booking)) { return "RoomBookingList" + redirect; } errorMessage = "block"; return "RoomBookingDetails" + redirect; } }
/* * 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 jframeproject; import javax.swing.*; import java.awt.*; import javax.swing.border.*; public class JFrameProject { public static JFrame window = new JFrame("My window"); public static void main(String[] args) { Toolkit tkit = window.getToolkit(); Dimension d = tkit.getScreenSize(); Color thiscolor = Color.GRAY; System.out.println("Screen Resolution is "+tkit.getScreenResolution()); window.getContentPane().setBackground(thiscolor.darker()); JMenuBar b = new JMenuBar(); JMenu m = new JMenu("Names"); b.add(m); JMenuItem item = new JMenuItem("imtiaz"); m.add(item); JButton button; window.add(b); b.setSize(20, 40); window.setBounds(d.width/4, d.height/4, d.width/2, d.height/2); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); FlowLayout layout = new FlowLayout( FlowLayout.LEFT,20,10 ); window.setLayout( layout ); Font[] f = {new Font("Arial",Font.BOLD,10),new Font("Playbill",Font.PLAIN,10)}; EtchedBorder x = new EtchedBorder( EtchedBorder.LOWERED ); for( int i = 1; i<5; i++ ) { window.getContentPane().add(button = new JButton("Button "+i)); button.setBorder(x); } layout.setVgap(5); layout.setHgap(10); GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment(); // String[] f = e.getAvailableFontFamilyNames(); // // for( String c : f ) // { // System.out.println(c); // } } }
package gilded.rose; public class GildedRose { private String name; private int quality; private int daysRemaining; public GildedRose(String name) { this.name = name; } public void initialize(int quality, int daysRemaining) { this.quality = quality; this.daysRemaining = daysRemaining; } public int getQuality() { return quality; } public int getDaysRemaining() { return daysRemaining; } public void tick() { if (!name.equals("Aged Brie") && !name.equals("Backstage passes to a TAFKAL80ETC concert")) { if (quality > 0) { if (!name.equals("Sulfuras, Hand of Ragnaros")) { quality = quality - 1; } } } else { if (quality < 50) { quality = quality + 1; if (name.equals("Backstage passes to a TAFKAL80ETC concert")) { if (daysRemaining < 11) { if (quality < 50) { quality = quality + 1; } } if (daysRemaining < 6) { if (quality < 50) { quality = quality + 1; } } } } } if (!name.equals("Sulfuras, Hand of Ragnaros")) { daysRemaining = daysRemaining - 1; } if (daysRemaining < 0) { if (!name.equals("Aged Brie")) { if (!name.equals("Backstage passes to a TAFKAL80ETC concert")) { if (quality > 0) { if (!name.equals("Sulfuras, Hand of Ragnaros")) { quality = quality - 1; } } } else { quality = quality - quality; } } else { if (quality < 50) { quality = quality + 1; } } } } }
package apartment; import java.sql.Connection; public class Apartment { Connection conn = MyConnect.connect(); public static void main(String[] args) { System.out.println("OK"); JFrameApartment fm = new JFrameApartment(); fm.setVisible(true); } }
package com.minhvu.proandroid.sqlite.database.main.model.view; import android.content.ContentValues; import android.net.Uri; import com.minhvu.proandroid.sqlite.database.main.presenter.view.IDetailPresenter; /** * Created by vomin on 8/26/2017. */ public interface IDetailModel { void setPresenter(IDetailPresenter presenter); void onDestroy(boolean isChangingConfiguration); void setDataSharePreference(String key, String content); String getDataSharePreference(String key); Uri insertData(Uri uri, ContentValues cv); boolean update(Uri uri, ContentValues cv, String where, String[] selectionArgs); boolean delete(Uri uri, String where, String[] selectionArgs); }
package com.fz.web; import com.fz.VO.ResultVO; import com.fz.converter.OrderForm2OrderDTOConverter; import com.fz.dto.OrderDTO; import com.fz.enums.ResultEnum; import com.fz.exception.SellException; import com.fz.form.OrderForm; import com.fz.service.OrderService; import com.fz.utils.ResultVOUtil; import lombok.extern.slf4j.Slf4j; import org.hibernate.criterion.Order; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.CollectionUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * @author: FZ * @date: 2021/4/17 20:07 * @description: */ @Slf4j @RestController @RequestMapping("/buyer/order") public class BuyerOrderWeb { @Autowired private OrderService orderService; //创建订单 @PostMapping("/create") public ResultVO<Map<String,String>> create(@Valid OrderForm orderForm ,BindingResult bindingResult){ if(bindingResult.hasErrors()){ log.error("【创建订单】参数不正确,orderForm={}",orderForm); throw new SellException(ResultEnum.PARAM_ERROR.getCode() ,bindingResult.getFieldError().getDefaultMessage()); } OrderDTO orderDTO = OrderForm2OrderDTOConverter.converter(orderForm); if(CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){ log.error("【创建订单】购物车不能为空"); throw new SellException(ResultEnum.CART_EMPTY); } OrderDTO result = orderService.create(orderDTO); Map<String,String> map =new HashMap<String,String>(); map.put("orderId",result.getOrderId()); return ResultVOUtil.success( map ); } //订单列表 //订单详情 //取消订单 }
package com.mhframework.gameplay.actor; import com.mhframework.core.math.MHVector; import com.mhframework.gameplay.tilemap.MHITileMapContent; import com.mhframework.gameplay.tilemap.view.MHCamera2D; import com.mhframework.gameplay.tilemap.view.MHIsoMouseMap; import com.mhframework.platform.graphics.MHBitmapImage; import com.mhframework.platform.graphics.MHGraphicsCanvas; public class MHTileMapActor extends MHActor implements MHITileMapContent { private int tileID; @Override public int getTileID() { return tileID; } @Override public MHBitmapImage getImage() { return super.getImage(); } public void setTileID(int id) { tileID = id; } @Override public void render(MHGraphicsCanvas g, MHCamera2D camera) { MHVector v = camera.worldToScreen(getPosition().clone()); v = camera.screenToLocal(v); int rx = (int)(v.x-(getWidth()/2)); int ry = (int)(v.y-(getHeight()-MHIsoMouseMap.getInstance().getHeight()/2)); g.drawImage(getImage(), rx, ry); } // public MHVector getRenderAnchor() // { // MHVector p = getPosition().clone(); // p.x += getWidth()/2; // p.y += getHeight() - 16; // TODO: get this from the tile map system. // return p; // } }
class Solution { HashMap<Character, Task> map = new HashMap<>(); public int leastInterval(char[] tasks, int n) { for(char c: tasks){ if(map.containsKey(c)){ Task t = map.get(c); t.count++; } else{ map.put(c, new Task(c)); } } PriorityQueue<Task> q = new PriorityQueue<>(); q.addAll(map.values()); int time = 0; List<Task> taskss; while(!q.isEmpty()){ taskss = new ArrayList<>(); while(!q.isEmpty()){ Task t = q.poll(); if(t.earliest <= time){ t.count--; t.earliest = time + n + 1; if(t.count>0)taskss.add(t); break; }if(t.count>0)taskss.add(t);} time++; q.addAll(taskss); //if(t.count>0)q.add(t); } return time; } } class Task implements Comparable{ int count = 0; char v; int earliest = 0; public int compareTo(Object o){ Task t = (Task) o; if(t.count==this.count && this.earliest==t.earliest)return 0; //if(t.earliest>this.earliest || t.earliest==this.earliest && t.count<this.count) return -1; if(t.count<this.count || t.earliest>this.earliest && t.count==this.count) return -1; return 1; } public Task(char c){ v =c; count = 1; } }
package com.cn.ouyjs.jdk; /** * @author ouyjs * @date 2019/7/26 9:38 */ public class LookBookTest { public static void main(String[] args) { LookBooK lookBooK = new LookBookImpl(); LookBookHande lookBookHande = new LookBookHande(lookBooK); lookBookHande.look(); } }