text
stringlengths
10
2.72M
package shulei.july26; // 自定义日期类 /** * 日期类型 * @author helloWorld * */ class MyDate { public int iYear; public int iMonth; public int iDay; private static int checkYear(int iYear) { if ((iYear > 1901) && (iYear < 2050)) return iYear; else { System.out.println("The Year out of range, I think you want 1981"); return 1981; } } public MyDate(int iYear, int iMonth, int iDay) { this.iYear = checkYear(iYear); this.iMonth = iMonth; this.iDay = iDay; } public MyDate(int iYear, int iMonth) { this.iYear = checkYear(iYear); this.iMonth = iMonth; this.iDay = 1; } public MyDate(int iYear) { this.iYear = checkYear(iYear); this.iMonth = 1; this.iDay = 1; } public MyDate() { this.iYear = 1981; this.iMonth = 1; this.iDay = 1; } /** * @param date 格式如19900126 */ public MyDate(String date) { byte[] bytes=date.getBytes(); this.iYear=Integer.parseInt(new String(bytes,0,4)); this.iMonth=Integer.parseInt(new String(bytes,4,2)); this.iDay=Integer.parseInt(new String(bytes,6,2)); } public String toString() { return "" + this.iYear + (this.iMonth > 9 ? "" + this.iMonth : "0" + this.iMonth) + (this.iDay > 9 ? "" + this.iDay : "0" + this.iDay); } public boolean equals(MyDate md) { return ((md.iDay == this.iDay) && (md.iMonth == this.iMonth) && (md.iYear == this.iYear)); } }
package com.example.framgiaphamducnam.demomodel3d.screens.vietskin; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.RelativeLayout; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.example.framgiaphamducnam.demomodel3d.MainActivity; import com.example.framgiaphamducnam.demomodel3d.R; import com.example.framgiaphamducnam.demomodel3d.utils.DialogUtils; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import static com.example.framgiaphamducnam.demomodel3d.MainActivity.mUnityPlayer; /** * Created by FRAMGIA\pham.duc.nam on 18/04/2018. */ public class VietSkinFragment extends Fragment { protected View mView; @BindView(R.id.rlLoading) RelativeLayout rlLoading; @BindView(R.id.btnNext) Button btnNext; @BindView(R.id.fl_forUnity) FrameLayout fl_forUnity; private int[] resultData; private String mData; private MainActivity mActivity; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (mView == null) { mView = inflater.inflate(R.layout.fragment_viet_skin, container, false); ButterKnife.bind(this, mView); mActivity = (MainActivity) getActivity(); initData(); } return mView; } private void initData() { rlLoading.setVisibility(View.VISIBLE); btnNext.setVisibility(View.GONE); new Handler().postDelayed(new Runnable() { public void run() { rlLoading.setVisibility(View.GONE); btnNext.setVisibility(View.VISIBLE); } }, 5000); fl_forUnity.addView(mUnityPlayer.getView(), FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); mUnityPlayer.requestFocus(); } @OnClick(R.id.btnNext) public void onNext() { mUnityPlayer.UnitySendMessage("GameManager", "GetListChecked", ""); new Handler().postDelayed(new Runnable() { @Override public void run() { receiveData(); } }, 1000); } private void receiveData() { if (TextUtils.isEmpty(mActivity.sendData())) return; Type type = new TypeToken<int[]>() { }.getType(); resultData = new Gson().fromJson(mActivity.sendData(), type); if (resultData.length == 0) { DialogUtils.showDialogAlert(mActivity); } else { toQuestion1(); } } private void toQuestion1() { mActivity.pushFragmentQ1(new Question1Fragment()); } }
package Matrix2; import ConcurrentCache.ConcurrentCache; import java.util.Random; public class Matrix2 { private int dim; private int[] arr; private ConcurrentCache cache; public Matrix2(int dim) { this.dim = dim; arr = new int[dim * dim]; cache = new ConcurrentCache(dim); } public void randomFill(int bound) { Random random = new Random(); for (int i = 0; i < arr.length; i++) { // arr[i] = random.nextInt(bound); arr[i] = i; } } public int getEle(int i, int j) { // try { // Thread.sleep(1); // } catch(InterruptedException e) { // e.printStackTrace(); // } return arr[i * dim + j]; } public int getCacheEle(int i, int j) { int key = i * dim + j; int value = cache.get(key); if (value < 0) { value = getEle(i, j); cache.put(key, value); } return value; } public void setEle(int i, int j, int e) { arr[i * dim + j] = e; } }
package view.prof_frame; import control.erros.ErroNome; import javax.swing.*; import java.io.IOException; import static control.ExibirListas.exibirListaTurmasDumProf; class ListaTurmas { JPanel listaTurmas; private JLabel listaTurmasLabel; public ListaTurmas(){ try { listaTurmasLabel.setText("<html>" + exibirListaTurmasDumProf() + "</html>"); } catch (IOException | ErroNome e) { e.printStackTrace(); } } }
package cn.quartz; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; /** * @author Created by xiaoni on 2018/10/17. */ @Configuration @EnableScheduling //启用定时任务 @Slf4j public class QuartzTest { private int i = 0; /** * 基本配置定时任务时间的格式就是“秒 分 时 月 日 星期几 年”,不想设置的字段就? 。 * 附录: * cronExpression的配置说明,具体使用以及参数请百度google * 字段 允许值 允许的特殊字符 * 秒 0-59 , - * / * 分 0-59 , - * / * 小时 0-23 , - * / * 日期 1-31 , - * ? / L W C * 月份 1-12 或者 JAN-DEC , - * / * 星期 1-7 或者 SUN-SAT , - * ? / L C # * 年(可选) 留空, 1970-2099 , - * / * - 区间 * 通配符 * ? 你不想设置那个字段 * 下面只例出几个式子 * <p> * CRON表达式 含义 * "0 0 12 * * ?" 每天中午十二点触发 * "0 15 10 ? * *" 每天早上10:15触发 * "0 15 10 * * ?" 每天早上10:15触发 * "0 15 10 * * ? *" 每天早上10:15触发 * "0 15 10 * * ? 2005" 2005年的每天早上10:15触发 * "0 * 14 * * ?" 每天从下午2点开始到2点59分每分钟一次触发 * "0 0/5 14 * * ?" 每天从下午2点开始到2:55分结束每5分钟一次触发 * "0 0/5 14,18 * * ?" 每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发 * "0 0-5 14 * * ?" 每天14:00至14:05每分钟一次触发 * "0 10,44 14 ? 3 WED" 三月的每周三的14:10和14:44触发 * "0 15 10 ? * MON-FRI" 每个周一、周二、周三、周四、周五的10:15触发 * 0 0 *(去掉这个)/1 * * ? 每天隔一小时 * 0 0 1-8/1 * * ? 从凌晨一点到早上八点每隔一小时 */ @Scheduled(cron = "*/1 * * * * ?") public void test1() { // if (i < 10) { log.info("我是test1"); i ++; // } } // public static void main(String[] args) { // new QuartzTest().test1(); // } }
package com.android.cvbsdemo; public class CommonUtils { public static boolean is7Inch() { return false; } }
package xcelite.model; import compat.com.ebay.xcelite_104.annotations.Compat_Column; public class AbstractWriterTestsBean { @Compat_Column(name = "booleanSimpleType") boolean booleanSimpleType = true; @Compat_Column(name = "booleanObjectType") Boolean booleanObjectType = true; @Compat_Column(name = "stringType") String stringType = "abcde"; public boolean isBooleanSimpleType() { return booleanSimpleType; } public void setBooleanSimpleType(boolean booleanSimpleType) { this.booleanSimpleType = booleanSimpleType; } public Boolean getBooleanObjectType() { return booleanObjectType; } public void setBooleanObjectType(Boolean booleanObjectType) { this.booleanObjectType = booleanObjectType; } public String getStringType() { return stringType; } public void setStringType(String stringType) { this.stringType = stringType; } }
/* * Created by Angel Leon (@gubatron), Alden Torres (aldenml) * Copyright (c) 2011-2014, FrostWire(R). All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.frostwire.gui.bittorrent; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.RowFilter; import javax.swing.SwingConstants; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableRowSorter; import org.gudy.azureus2.core3.torrent.TOTorrent; import org.gudy.azureus2.core3.torrent.TOTorrentException; import org.gudy.azureus2.core3.util.TorrentUtils; import org.limewire.util.FilenameUtils; import org.limewire.util.StringUtils; import com.limegroup.gnutella.gui.GUIMediator; import com.limegroup.gnutella.gui.GUIUtils; import com.limegroup.gnutella.gui.I18n; import com.limegroup.gnutella.gui.IconManager; import com.limegroup.gnutella.gui.LabeledTextField; import com.limegroup.gnutella.gui.search.NamedMediaType; import com.limegroup.gnutella.gui.tables.SizeHolder; /** * * @author gubatron * @author aldenml * */ public class PartialFilesDialog extends JDialog { private static final long serialVersionUID = 4312306965758592618L; private LabeledTextField _filter; private RowFilter<Object, Object> textBasedFilter; private JPanel panel; private JLabel labelTitle; private JTable _table; private JScrollPane _scrollPane; private JButton _buttonOK; private JButton _buttonCancel; private final TOTorrent _torrent; private final String _name; private final TorrentTableModel _model; private boolean[] _filesSelection; private JCheckBox _checkBoxToggleAll; /** Has the table been painted at least once? */ protected boolean tablePainted; public PartialFilesDialog(JFrame frame, File torrentFile) throws TOTorrentException { super(frame, I18n.tr("Select files to download")); _torrent = TorrentUtils.readFromFile(torrentFile, false); _name = torrentFile.getName(); _model = new TorrentTableModel(_torrent); addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { GUIMediator.instance().setRemoteDownloadsAllowed(false); } @Override public void windowClosing(WindowEvent e) { GUIMediator.instance().setRemoteDownloadsAllowed(true); } }); setupUI(); setLocationRelativeTo(frame); } protected void setupUI() { setResizable(true); setMinimumSize(new Dimension(400, 300)); panel = new JPanel(new GridBagLayout()); // title setupTitle(); // filter setupTextFilter(); setupToggleAllSelectionCheckbox(); // table setupTable(); // ok button setupOkButton(); // cancel button setupCancelButton(); getContentPane().add(panel); pack(); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setModalityType(ModalityType.APPLICATION_MODAL); getRootPane().setDefaultButton(_buttonOK); GUIUtils.addHideAction((JComponent) getContentPane()); } private void setupCancelButton() { GridBagConstraints c; _buttonCancel = new JButton(I18n.tr("Cancel")); _buttonCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buttonCancel_actionPerformed(e); } }); c = new GridBagConstraints(); c.insets = new Insets(4, 0, 8, 6); c.gridwidth = GridBagConstraints.REMAINDER; c.anchor = GridBagConstraints.EAST; c.ipadx = 18; c.gridy = 4; panel.add(_buttonCancel, c); } private void setupOkButton() { GridBagConstraints c; _buttonOK = new JButton(I18n.tr("Download Selected Files Only")); _buttonOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buttonOK_actionPerformed(e); } }); c = new GridBagConstraints(); c.insets = new Insets(4, 100, 8, 4); c.fill = GridBagConstraints.NONE; c.gridwidth = GridBagConstraints.RELATIVE; c.anchor = GridBagConstraints.EAST; c.ipadx = 20; c.weightx = 1.0; c.gridy = 4; panel.add(_buttonOK, c); } private void setupTable() { GridBagConstraints c; _table = new JTable() { private static final long serialVersionUID = -4266029708016964901L; public void paint(java.awt.Graphics g) { super.paint(g); try { if (tablePainted) { return; } tablePainted = true; GUIUtils.adjustColumnWidth(_model, 2, 620, 10, this); GUIUtils.adjustColumnWidth(_model, 3, 150, 10, this); } catch (Exception e) { tablePainted = false; } }; }; _table.setPreferredScrollableViewportSize(new Dimension(600, 300)); _table.setRowSelectionAllowed(false); _table.setModel(_model); _table.getColumnModel().getColumn(0).setHeaderValue(""); //checkbox _table.getColumnModel().getColumn(1).setHeaderValue(""); //icon _table.getColumnModel().getColumn(2).setHeaderValue(I18n.tr("File")); _table.getColumnModel().getColumn(3).setHeaderValue(I18n.tr("Type")); _table.getColumnModel().getColumn(4).setHeaderValue(I18n.tr("Extension")); _table.getColumnModel().getColumn(5).setHeaderValue(I18n.tr("Size")); _table.getColumnModel().getColumn(0).setPreferredWidth(30);//checkbox _table.getColumnModel().getColumn(1).setPreferredWidth(30);//icon _table.getColumnModel().getColumn(2).setPreferredWidth(620); _table.getColumnModel().getColumn(3).setPreferredWidth(150); _table.getColumnModel().getColumn(4).setPreferredWidth(60); _table.getColumnModel().getColumn(5).setPreferredWidth(60); _scrollPane = new JScrollPane(_table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); _table.setFillsViewportHeight(true); _table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); c = new GridBagConstraints(); c.insets = new Insets(5, 5, 5, 5); c.gridx = 0; c.gridy = 3; c.gridwidth = 2; c.gridheight = 1; c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; panel.add(_scrollPane, c); } private void setupToggleAllSelectionCheckbox() { GridBagConstraints c; _checkBoxToggleAll = new JCheckBox(I18n.tr("Select/Unselect all files"), true); _checkBoxToggleAll.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { onCheckBoxToggleAll(e); } }); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 2; c.gridwidth = 1; c.gridheight = 1; c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.insets = new Insets(5, 5, 5, 5); panel.add(_checkBoxToggleAll, c); } private void setupTextFilter() { GridBagConstraints c; _filter = new LabeledTextField("Filter files", 30); _filter.setMinimumSize(_filter.getPreferredSize()); // fix odd behavior textBasedFilter = new RowFilterExtension(_filter, 2); _filter.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (_filter.getText() == null || _filter.getText().equals("")) { _table.setRowSorter(null); return; } _checkBoxToggleAll.setSelected(false); TableRowSorter<TorrentTableModel> sorter = new TableRowSorter<TorrentTableModel>(_model); sorter.setRowFilter(textBasedFilter); _table.setRowSorter(sorter); } }); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 1; c.gridwidth = 2; c.gridheight = 1; c.anchor = GridBagConstraints.WEST; c.weightx = 1.0; c.insets = new Insets(5, 5, 5, 5); panel.add(_filter, c); } private void setupTitle() { GridBagConstraints c; String title = _torrent.getUTF8Name(); if (title == null) { if (_torrent.getName() != null) { title = StringUtils.getUTF8String(_torrent.getName()); } else { title = _name.replace("_", " ").replace(".torrent", "").replace("&quot;", "\""); } } labelTitle = new JLabel(title); labelTitle.setFont(new Font("Dialog", Font.BOLD, 18)); labelTitle.setHorizontalAlignment(SwingConstants.LEFT); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.gridwidth = 2; c.gridheight = 1; c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.insets = new Insets(5, 5, 5, 5); panel.add(labelTitle, c); } protected void onCheckBoxToggleAll(ItemEvent e) { _model.setAllSelected(_checkBoxToggleAll.isSelected()); _buttonOK.setEnabled(_checkBoxToggleAll.isSelected()); } /** * Change the value of the checkbox but don't trigger any events. * (We probably need something generic for this, this pattern keeps appearing all over) * @param allSelected */ public void checkboxToggleAllSetSelectedNoTrigger(boolean allSelected) { ItemListener[] itemListeners = _checkBoxToggleAll.getItemListeners(); for (ItemListener l : itemListeners) { _checkBoxToggleAll.removeItemListener(l); } _checkBoxToggleAll.setSelected(allSelected); for (ItemListener l : itemListeners) { _checkBoxToggleAll.addItemListener(l); } } protected void buttonOK_actionPerformed(ActionEvent e) { TorrentFileInfo[] fileInfos = _model.getFileInfos(); _filesSelection = new boolean[fileInfos.length]; for (int i = 0; i < _filesSelection.length; i++) { _filesSelection[i] = fileInfos[i].selected; } GUIUtils.getDisposeAction().actionPerformed(e); } protected void buttonCancel_actionPerformed(ActionEvent e) { GUIUtils.getDisposeAction().actionPerformed(e); } public boolean[] getFilesSelection() { return _filesSelection; } static final class RowFilterExtension extends RowFilter<Object, Object> { private final LabeledTextField labelFilter; private final int columnIndex; public RowFilterExtension(LabeledTextField labelFilter, int columnIndex) { this.labelFilter = labelFilter; this.columnIndex = columnIndex; } @Override public boolean include(RowFilter.Entry<? extends Object, ? extends Object> entry) { Object value = entry.getValue(columnIndex); String fileName = value != null && value instanceof String ? (String) value : ""; String[] tokens = labelFilter.getText().split(" "); for (String t : tokens) { if (!fileName.toLowerCase().contains(t.toLowerCase())) { return false; } } return true; } } private final class TorrentTableModel extends AbstractTableModel { private static final long serialVersionUID = -8689494570949104116L; private final TOTorrent _torrent; private final TorrentFileInfo[] _fileInfos; public TorrentTableModel(TOTorrent torrent) { _torrent = torrent; _fileInfos = new TorrentFileInfo[torrent.getFiles().length]; for (int i = 0; i < _fileInfos.length; i++) { _fileInfos[i] = new TorrentFileInfo(torrent.getFiles()[i], true); } } @Override public int getRowCount() { return _torrent.getFiles().length; } @Override public int getColumnCount() { return 6; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex == 0; } @Override public Class<?> getColumnClass(int columnIndex) { switch (columnIndex) { case 0: return Boolean.class; case 1: return Icon.class; case 2: return String.class; case 3: return String.class; case 4: return String.class; case 5: return SizeHolder.class; default: return null; } } @Override public Object getValueAt(int rowIndex, int columnIndex) { String filePath = _fileInfos[rowIndex].torrentFile.getRelativePath(); String extension = FilenameUtils.getExtension(filePath); switch (columnIndex) { case 0: //checkbox return _fileInfos[rowIndex].selected; case 1: //icon return IconManager.instance().getIconForExtension(extension); case 2: //path return filePath; case 3: //human type return guessHumanType(extension); case 4: //extension return extension; case 5: //file size return new SizeHolder(_fileInfos[rowIndex].torrentFile.getLength()); default: return null; } } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if (columnIndex == 0) { _fileInfos[rowIndex].selected = (Boolean) aValue; fireTableDataChanged(); } checkboxToggleAllSetSelectedNoTrigger(isAllSelected()); _buttonOK.setEnabled(!isNoneSelected()); } public void setAllSelected(boolean selected) { for (int i = 0; i < _fileInfos.length; i++) { _fileInfos[i].selected = selected; } fireTableDataChanged(); } public boolean isAllSelected() { for (int i = 0; i < _fileInfos.length; i++) { if (!_fileInfos[i].selected) { return false; } } return true; } public boolean isNoneSelected() { for (int i = 0; i < _fileInfos.length; i++) { if (_fileInfos[i].selected) { return false; } } return true; } public TorrentFileInfo[] getFileInfos() { return _fileInfos; } private String guessHumanType(String extension) { try { return NamedMediaType.getFromExtension(extension).getMediaType().getDescriptionKey(); } catch (Throwable t) { return I18n.tr("Unknown"); } } } }
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cache.support; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.springframework.beans.factory.InitializingBean; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.lang.Nullable; /** * Abstract base class implementing the common {@link CacheManager} methods. * Useful for 'static' environments where the backing caches do not change. * * @author Costin Leau * @author Juergen Hoeller * @author Stephane Nicoll * @since 3.1 */ public abstract class AbstractCacheManager implements CacheManager, InitializingBean { private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<>(16); private volatile Set<String> cacheNames = Collections.emptySet(); // Early cache initialization on startup @Override public void afterPropertiesSet() { initializeCaches(); } /** * Initialize the static configuration of caches. * <p>Triggered on startup through {@link #afterPropertiesSet()}; * can also be called to re-initialize at runtime. * @since 4.2.2 * @see #loadCaches() */ public void initializeCaches() { Collection<? extends Cache> caches = loadCaches(); synchronized (this.cacheMap) { this.cacheNames = Collections.emptySet(); this.cacheMap.clear(); Set<String> cacheNames = new LinkedHashSet<>(caches.size()); for (Cache cache : caches) { String name = cache.getName(); this.cacheMap.put(name, decorateCache(cache)); cacheNames.add(name); } this.cacheNames = Collections.unmodifiableSet(cacheNames); } } /** * Load the initial caches for this cache manager. * <p>Called by {@link #afterPropertiesSet()} on startup. * The returned collection may be empty but must not be {@code null}. */ protected abstract Collection<? extends Cache> loadCaches(); // Lazy cache initialization on access @Override @Nullable public Cache getCache(String name) { // Quick check for existing cache... Cache cache = this.cacheMap.get(name); if (cache != null) { return cache; } // The provider may support on-demand cache creation... Cache missingCache = getMissingCache(name); if (missingCache != null) { // Fully synchronize now for missing cache registration synchronized (this.cacheMap) { cache = this.cacheMap.get(name); if (cache == null) { cache = decorateCache(missingCache); this.cacheMap.put(name, cache); updateCacheNames(name); } } } return cache; } @Override public Collection<String> getCacheNames() { return this.cacheNames; } // Common cache initialization delegates for subclasses /** * Check for a registered cache of the given name. * In contrast to {@link #getCache(String)}, this method does not trigger * the lazy creation of missing caches via {@link #getMissingCache(String)}. * @param name the cache identifier (must not be {@code null}) * @return the associated Cache instance, or {@code null} if none found * @since 4.1 * @see #getCache(String) * @see #getMissingCache(String) */ @Nullable protected final Cache lookupCache(String name) { return this.cacheMap.get(name); } /** * Update the exposed {@link #cacheNames} set with the given name. * <p>This will always be called within a full {@link #cacheMap} lock * and effectively behaves like a {@code CopyOnWriteArraySet} with * preserved order but exposed as an unmodifiable reference. * @param name the name of the cache to be added */ private void updateCacheNames(String name) { Set<String> cacheNames = new LinkedHashSet<>(this.cacheNames); cacheNames.add(name); this.cacheNames = Collections.unmodifiableSet(cacheNames); } // Overridable template methods for cache initialization /** * Decorate the given Cache object if necessary. * @param cache the Cache object to be added to this CacheManager * @return the decorated Cache object to be used instead, * or simply the passed-in Cache object by default */ protected Cache decorateCache(Cache cache) { return cache; } /** * Return a missing cache with the specified {@code name}, or {@code null} if * such a cache does not exist or could not be created on demand. * <p>Caches may be lazily created at runtime if the native provider supports it. * If a lookup by name does not yield any result, an {@code AbstractCacheManager} * subclass gets a chance to register such a cache at runtime. The returned cache * will be automatically added to this cache manager. * @param name the name of the cache to retrieve * @return the missing cache, or {@code null} if no such cache exists or could be * created on demand * @since 4.1 * @see #getCache(String) */ @Nullable protected Cache getMissingCache(String name) { return null; } }
package ch11; import java.util.*; public class HashSetEx5 { public static void main(String[] args) { HashSet setA = new HashSet(); HashSet setB = new HashSet(); HashSet setHab = new HashSet(); HashSet setKyo = new HashSet(); HashSet setCha = new HashSet(); setA.add("1"); setA.add("2"); setA.add("3"); setA.add("4"); setA.add("5"); System.out.println("A = "+setA); setB.add("4"); setB.add("5"); setB.add("6"); setB.add("7"); setB.add("8"); System.out.println("B = "+setB); /*//교집합 Iterator it = setB.iterator(); while(it.hasNext()) { Object tmp = it.next(); if(setA.contains(tmp)) setKyo.add(tmp); } //차집합 it = setA.iterator(); while(it.hasNext()) { Object tmp = it.next(); if(!setB.contains(tmp)) //setB에 없는 것만 setCha에 저장 setCha.add(tmp); } //합집합 it = setA.iterator(); while(it.hasNext()) { setHab.add(it.next()); } it = setB.iterator(); while(it.hasNext()) { setHab.add(it.next()); } System.out.println("A ∩ B = "+setKyo); System.out.println("A ∪ B = "+setHab); System.out.println("A - B = "+setCha); */ // setA.retainAll(setB); // 교집합. 공통된 요소만 남기고 삭제 // setA.addAll(setB); // 합집합. setB의 모든 요소를 추가(중복 제외) // setA.removeAll(setB); // 차집합. setB와 공통 요소를 제거 System.out.println(setA); } }
package com.example.atpc.cms; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.Button; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { public void switchtosettings(){ Intent i = new Intent(this, Main2Activity.class); startActivity(i); } public void switchtohelp(){ Intent i = new Intent(this, Main3Activity.class); startActivity(i); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ToggleButton switchService = (ToggleButton) findViewById(R.id.toggleButton); final Intent startBackgroundService = new Intent(getApplicationContext(), BackgroundService.class); switchService.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { //BackgroundService.shouldContinue = true; GPSTracker gps = new GPSTracker(getApplicationContext()); startService(startBackgroundService); if(gps.canGetLocation()) { } } else { /*ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> runningAppProcess = am.getRunningAppProcesses(); Iterator<ActivityManager.RunningAppProcessInfo> iter = runningAppProcess.iterator(); while (iter.hasNext()) { ActivityManager.RunningAppProcessInfo next = iter.next(); String pricessName = getPackageName() + ":service"; if (next.processName.equals(pricessName)) { Process.killProcess(next.pid); break; } }*/ Intent stopIntent = new Intent(getApplicationContext(), RingtonePlayer.class); getApplicationContext().stopService(stopIntent); stopService(startBackgroundService); } } }); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_settings) { // Handle the camera action switchtosettings(); } else if (id == R.id.nav_help) { switchtohelp(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
package mlAlg; import java.awt.Canvas; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.imageio.ImageIO; public class myCanvas extends Canvas { /** * */ private static final long serialVersionUID = 1L; private int[][] points; private int width; private int height; public myCanvas(int[][] points, int width, int height) { setSize(width, height); this.points = points; this.width = width; this.height = height; } public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g; kNNalg(g2d, 0); g2d.dispose(); } private void kNNalg(Graphics2D g2d, int n) { List<Color> gradient = new ArrayList<Color>(); float colorCount = 300; for (float i = 0; i < 1; i += 1 / colorCount) { gradient.add(new Color(0, i, i, 1f)); } int[] point2 = new int[2]; // g2d.scale(5, 5); // for every x in canvas for (int x = 0; x < width; x++) { // for every y in canvas for (int y = 0; y < height; y++) { // point1 represents those points int[] point1 = { x, y }; // array of distances from the array of points to every point in the canvas List<Integer> distances = new ArrayList<Integer>(); // for every point in points array for (int i = 0; i < points.length; i++) { point2[0] = points[i][0]; point2[1] = points[i][1]; distances.add(distance(point1, point2)); } Collections.sort(distances); int noise = distances.get(n); if (noise >= gradient.size()) { g2d.setColor(Color.white); } else { g2d.setPaint(gradient.get(noise % gradient.size())); } g2d.drawLine(x, y, x, y); } } } private int distance(int[] point1, int[] point2) { return (int) Math.sqrt( (point2[1] - point1[1]) * (point2[1] - point1[1]) + (point2[0] - point1[0]) * (point2[0] - point1[0])); } public void toJPG() throws IOException { BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bImage.createGraphics(); kNNalg(g2d, 1 ); g2d.dispose(); File file = new File("Image.jpg"); ImageIO.write(bImage, "jpg", file); } }
package com.seatgeek.placesautocomplete; import java.util.HashSet; import java.util.Set; /** * Object for passing filters around. */ public class Filters { private final Set<String> countries = new HashSet<>(); public Filters() { } public static Filters getDefault() { return new Filters(); } public boolean hasCountry() { return !(countries.size() == 0); } public Set<String> getCountries() { return countries; } public void setCountry(String country) { if(country != null) { this.countries.add(country); }else{ this.countries.clear(); } } public void removeCountry(String title) { this.countries.remove(title); } }
class Solution { public int widthOfBinaryTree(TreeNode root) { if (root == null) return 0; int max = 0; Queue<Pair<TreeNode, Integer>> q = new LinkedList<>(); q.offer(new Pair<>(root, 1)); int firstIndex = 0; int lastIndex = 0; while (!q.isEmpty()) { int qlen = q.size(); firstIndex = q.peek().getValue(); while(qlen-- > 0) { Pair<TreeNode, Integer> pair = q.poll(); TreeNode node = pair.getKey(); lastIndex = pair.getValue(); if (node.left != null) q.offer(new Pair<>(node.left, 2 * lastIndex)); if (node.right != null) q.offer(new Pair<>(node.right, 2 * lastIndex + 1)); } max = Math.max(max, lastIndex - firstIndex + 1); } return max; } }
/* * Copyright Verizon Media, Licensed under the terms of the Apache License, Version 2.0. See LICENSE file in project root for terms. */ package com.yahoo.cubed.dao; import com.yahoo.cubed.model.PipelineProjectionVM; import org.hibernate.Session; /** * Pipeline projection value mapping data access object implementation. */ public class PipelineProjectionVMDAOImpl extends AbstractAssociationDAOImpl<PipelineProjectionVM> implements PipelineProjectionVMDAO { /** * Get the entity class: PipelineProjectionVM. */ @Override public Class<PipelineProjectionVM> getEntityClass() { return PipelineProjectionVM.class; } /** * Unsupported method. */ @Override public PipelineProjectionVM fetchByName(Session session, String name) { throw new UnsupportedOperationException(); } }
package di.homework.CalXml; public class MyCalculator { private int firstNum; private int secondNum; public MyCalculator(int first, int second) { this.firstNum = first; this.secondNum = second; System.out.println("MyCalculator(fir,sec)..."); } public int getAdd() { return this.firstNum + this.secondNum; } public int getMin() { return this.firstNum - this.secondNum; } public int getMul() { return this.firstNum * this.secondNum; } public int getDiv() { return this.firstNum / this.secondNum; } public void getResult() { System.out.println(this.firstNum + "+" + this.secondNum + "=" + getAdd()); System.out.println(this.firstNum + "-" + this.secondNum + "=" + getMin()); System.out.println(this.firstNum + "*" + this.secondNum + "=" + getMul()); System.out.println(this.firstNum + "/" + this.secondNum + "=" + getDiv()); } }
package common; import java.awt.FlowLayout; import java.awt.GridLayout; import java.util.Collection; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextField; /** * @author Steve Riley */ public class TaskPullPanel extends JPanel { /** * WTF is this for? No idea */ private static final long serialVersionUID = -6261407565958923776L; private static boolean doTaskCompletion() { return PMMainController.markSelectedTaskAsComplete(); } private final MainModel m_model; private final JSlider m_prioritySensitivitySlider; private final ScheduledExecutorService m_snoozeThreadPool; private final MainView m_view; /** * */ public TaskPullPanel(final MainModel p_model, final MainView p_view) { super(new GridLayout(2, 1)); m_snoozeThreadPool = Executors.newScheduledThreadPool(1); m_model = p_model; m_view = p_view; final JPanel panel1 = new JPanel(); final JPanel subPanel1 = new JPanel(); m_prioritySensitivitySlider = new JSlider(0, Constants.MAX_PRIORITY_SENSITIVITY, Constants.DEFAULT_PRIORITY_SENSITIVITY); final JButton pullButton = new JButton(Messages.getString("TaskPullPanel.0")); //$NON-NLS-1$ pullButton.addActionListener(p_arg0 -> { pullTasks(); }); subPanel1.add(pullButton); final JButton renormalizeButton = new JButton(Messages.getString("TaskPullPanel.1")); //$NON-NLS-1$ renormalizeButton.addActionListener(p_arg0 -> { PMMainController.renormalizePriorities(); JOptionPane .showMessageDialog( this, Messages.getString("TaskPullPanel.2") //$NON-NLS-1$ + Constants.TASK_TARGET_PRIORITY_MEAN + Messages.getString("TaskPullPanel.3") //$NON-NLS-1$ + Constants.TASK_TARGET_PRIORITY_SD); }); subPanel1.add(renormalizeButton); panel1.add(subPanel1); add(panel1); final JPanel panel2 = new JPanel(); final JPanel subPanel2 = new JPanel(new FlowLayout()); subPanel2.add(new JLabel(Messages.getString("TaskPullPanel.4"))); //$NON-NLS-1$ final JTextField textField = new JTextField(3); textField.setText(String.valueOf(m_prioritySensitivitySlider.getValue())); textField.setEditable(false); m_prioritySensitivitySlider.addChangeListener(p_arg0 -> { textField.setText(String.valueOf(m_prioritySensitivitySlider.getValue())); }); subPanel2.add(m_prioritySensitivitySlider); subPanel2.add(textField); panel2.add(subPanel2); add(panel2); } private boolean displayTask(final Task p_task) { m_view.getTaskManagementPanel().getTaskTree().setSelectedTask(p_task); final ResponseOption[] options = ResponseOption.values(); String desc = p_task.getDescription(); if (p_task.hasDueDate() && p_task.isRepeatingTask()) { desc += Messages.getString("TaskPullPanel.5"); //$NON-NLS-1$ if (p_task.getRepeatRestartType() == RepeatRestartType.ON_DUE_DATE) { desc += Messages.getString("TaskPullPanel.6") //$NON-NLS-1$ + p_task.getDueLocalDate() + Messages.getString("TaskPullPanel.7"); //$NON-NLS-1$ } desc += Messages.getString("TaskPullPanel.8") //$NON-NLS-1$ + p_task.getRepeatPeriodCount() + Messages.getString("TaskPullPanel.9") //$NON-NLS-1$ + p_task.getRepeatPeriodType() + Messages.getString("TaskPullPanel.10"); //$NON-NLS-1$ } final int response = JOptionPane .showOptionDialog( this, desc, Messages.getString("TaskPullPanel.11"), //$NON-NLS-1$ JOptionPane.DEFAULT_OPTION,JOptionPane.QUESTION_MESSAGE, null, ResponseOption.values(), null); if (response == JOptionPane.CLOSED_OPTION) { return false; } boolean ret = false; switch (options[response]) { case COMPLETE: ret = doTaskCompletion(); break; case SNOOZE: ret = doSnoozing(p_task); break; default: throw new RuntimeException(); } return ret; } private boolean doSnoozing(final Task p_task) { m_snoozeThreadPool.schedule(() -> { p_task.setSnoozing(false); }, Constants.DEFAULT_SNOOZE_MINUTES * 60, TimeUnit.SECONDS); p_task.setSnoozing(true); return true; } private void pullTasks() { boolean breakLoop = false; while (!breakLoop) { final Collection<Task> tasks = m_model.getTasks().values(); final int sensitivity = m_prioritySensitivitySlider.getValue(); final int maxSensitivity = m_prioritySensitivitySlider.getMaximum(); final Task task = PMMainController.pullTask(tasks, sensitivity, maxSensitivity); if (task == null) { JOptionPane.showMessageDialog(this, Messages.getString("TaskPullPanel.12")); //$NON-NLS-1$ breakLoop = true; } else { breakLoop = !displayTask(task); } } } }
package gr.uoa.di.dbm.webapp.entity; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the trim_trees database table. * */ @Entity @Table(name="trim_trees") public class TrimTree extends ServiceRequest implements Serializable { private static final long serialVersionUID = 1L; @Column(name="trees_location") private String treesLocation; public TrimTree() { } public String getTreesLocation() { return this.treesLocation; } public void setTreesLocation(String treesLocation) { this.treesLocation = treesLocation; } }
package com.cxxt.mickys.playwithme.model.register; import android.content.Context; import com.cxxt.mickys.playwithme.presenter.register.OnAuthCodeListener; import com.cxxt.mickys.playwithme.presenter.register.OnRegisterFinishedListener; /** * RegisterModel * 注册 model 层接口 * * @author huangyz0918 */ public interface RegisterModel { void register(String authCode, Context context, String phoneNumber, OnRegisterFinishedListener listener); void getAuthCode(String phoneNumber, Context context, OnAuthCodeListener listener); }
package functionalTesting.logoutPage.independently; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import pageObject.Login; public class LogoutTest { static { System.setProperty("webdriver.gecko.driver","C:\\SeleniumGecko\\geckodriver.exe"); } private final static Log log = LogFactory.getLog(LogoutTest.class); WebDriverWait wait = new WebDriverWait(Login.driver, 3); @Test public void logout(){ Login.login("http://10.102.0.222:8070/web/user/login"); if(null != getLogout()){ getLogout().click(); } String loginText = "登陆"; String loginButton = Login.getLoginButton().getText(); Assert.assertEquals(loginText, loginButton); // Login.driver.quit(); } /** * Get logout element. * @return the WebElement. */ public WebElement getLogout(){ //this driver has to be Login's driver, otherwise it will trigger another browser window. //do not use vpn here WebElement logoutElement = wait.until( ExpectedConditions.presenceOfElementLocated(By.cssSelector(".notifications-wrapper > ul > li:nth-child(2) > a"))); return logoutElement; } }
/* Link.java Purpose: Description: History: Tue Dec 13 15:22:15 2005, Created by tomyeh Copyright (C) 2005 Potix Corporation. All Rights Reserved. {{IS_RIGHT This program is distributed under LGPL Version 2.1 in the hope that it will be useful, but WITHOUT ANY WARRANTY. }}IS_RIGHT */ package org.zkoss.zhtml; import org.zkoss.zhtml.impl.AbstractTag; import org.zkoss.zhtml.impl.PageRenderer; /** * The LINK tag. * * @author tomyeh */ public class Link extends AbstractTag { public Link() { super("link"); } }
package com.ljm.server.impl; import com.ljm.domain.DemoInfo; import com.ljm.repository.DemoInfoRepository; import com.ljm.server.DemoInfoService; import javassist.NotFoundException; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service; import javax.annotation.Resource; /** * @Project MyWebProject * @ClassName DemoInfoServiceImpl * @Description DemoInfo数据处理类 * @Author random * @Date Create in 2018/4/8 16:23 * @Version 1.0 **/ @Service public class DemoInfoServiceImpl implements DemoInfoService { @Resource private DemoInfoRepository demoInfoRepository; @Resource private RedisTemplate<String,String> redisTemplate; @Override public void test(){ ValueOperations<String,String> valueOperations =redisTemplate.opsForValue(); valueOperations.set("mykey4", "random1="+Math.random()); System.out.println(valueOperations.get("mykey4")); } // 查询数据 @Cacheable(value = DEMO_CACHE_NAME, key = "'demoInfo_'+#id") @Override public DemoInfo findById2(Long id) { System.out.println("没有走缓存!" + id); return demoInfoRepository.findOne(id); } //keyGenerator="myKeyGenerator" @Cacheable(value="demoInfo") //缓存,这里没有指定key. @Override public DemoInfo findById(Long id) { System.err.println("DemoInfoServiceImpl.findById()=========从数据库中进行获取的....id="+id); return demoInfoRepository.findOne(id); } @CacheEvict(value="demoInfo") @Override public void deleteFromCache(Long id) { System.out.println("DemoInfoServiceImpl.delete().从缓存中删除."); } // 这里的单引号不能少,否则会报错,被识别是一个对象 public static final String CACHE_KEY = "'demoInfo'"; // value属性表示使用那个缓存策略,缓存策略在ehcache.xml public static final String DEMO_CACHE_NAME = "demo"; // 删除数据 @CacheEvict(value = DEMO_CACHE_NAME, key = "'demoInfo_'+#id") // 这是清除缓存 @Override public void delete(Long id) { demoInfoRepository.delete(id); } // 修改数据 /** 在支持Spring Cache的环境下,对于使用@Cacheable标注的方法,Spring在每次执行前都会检查Cache中是否存在相同key的缓存元素, * 如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则才会执行并将返回结果存入指定的缓存中。 * @CachePut也可以声明一个方法支持缓存功能。与@Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果, * 而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。 * @CachePut也可以标注在类上和方法上。使用@CachePut时我们可以指定的属性跟@Cacheable是一样的。 */ @CachePut(value = DEMO_CACHE_NAME, key = "'demoInfo_'+#update.getId()") // @CacheEvict(value = DEMO_CACHE_NAME, key = "'demoInfo_'+#update.getId()") // 这是缓存清除 @Override public DemoInfo update(DemoInfo update) throws NotFoundException { DemoInfo demoInfo = demoInfoRepository.findOne(update.getId()); if (demoInfo == null) { throw new NotFoundException("No find"); } demoInfo.setName(update.getName()); demoInfo.setPwd(update.getPwd()); return demoInfo; } // 保存数据 @CacheEvict(value = DEMO_CACHE_NAME, key = CACHE_KEY) @Override public DemoInfo save(DemoInfo demoInfo) { return demoInfoRepository.save(demoInfo); } }
package repository; import java.time.LocalDate; import java.util.HashMap; import java.util.Map; import data.Prod_Id; public class ProductOrder { public ProductOrder(){ } static Map<Integer, Prod_Id> prod = new HashMap<>(); static{ prod.put(101, new Prod_Id(101,"Hyderabad",LocalDate.of(2019, 01, 15), "Packaging")); prod.put(102, new Prod_Id(102, "Gurugram",LocalDate.of(2018, 05, 24), "Dispatched")); prod.put(103, new Prod_Id(103, "Bangalore",LocalDate.of(2019, 05, 26), "Dispatched")); prod.put(104, new Prod_Id(104, "Pune",LocalDate.of(2020, 01, 19), "Not delivered")); } static public Map<Integer, Prod_Id> get(){ return prod; } }
package com.example.bob.health_helper.Community.activity; import android.graphics.Color; import android.os.Bundle; import android.support.design.internal.FlowLayout; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.util.TypedValue; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.example.bob.health_helper.Base.BaseActivity; import com.example.bob.health_helper.Community.adapter.SearchHistoryAdapter; import com.example.bob.health_helper.Community.fragment.SearchResultFragment; import com.example.bob.health_helper.Local.LocalBean.SearchHistory; import com.example.bob.health_helper.Local.Dao.SearchHistoryDao; import com.example.bob.health_helper.R; import com.example.bob.health_helper.Util.JsonParser; import com.example.bob.health_helper.Util.RandomColorUtil; import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.InitListener; import com.iflytek.cloud.RecognizerResult; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechError; import com.iflytek.cloud.ui.RecognizerDialog; import com.iflytek.cloud.ui.RecognizerDialogListener; import com.orhanobut.logger.Logger; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Random;; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class SearchActivity extends BaseActivity { @BindView(R.id.search_view) SearchView searchView; @BindView(R.id.search) LinearLayout search; @BindView(R.id.flow_layout) FlowLayout flowLayout; @BindView(R.id.search_history) RecyclerView searchHistoryView; private List<String> hotKeyList=new ArrayList<>(Arrays.asList("饮食","健身","慢性病","预防","药品", "高血压防治","检查","危险因素")); private SearchHistoryDao searchHistoryDao; private List<SearchHistory> searchHistoryList; private SearchHistoryAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); ButterKnife.bind(this); searchHistoryDao=new SearchHistoryDao(this); //搜索框背景无下划线 try{ Class<?> argClass=searchView.getClass(); Field ownField=argClass.getDeclaredField("mSearchPlate"); ownField.setAccessible(true); View view=(View)ownField.get(searchView); view.setBackgroundResource(R.drawable.searchview_line);//设置背景,去掉下划线 } catch (Exception e) { e.printStackTrace(); } TextView tv=searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text); tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,15); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override //当点击搜索按钮时触发 public boolean onQueryTextSubmit(String query) { if(query.length()>0){ Logger.e("search"); SearchHistory history=new SearchHistory(query); searchHistoryDao.addHistory(history); searchHistoryList.add(history); adapter.notifyDataSetChanged(); //带参数创建碎片 SearchResultFragment fragment=new SearchResultFragment(); Bundle bundle=new Bundle(); bundle.putString("search_question",query); fragment.setArguments(bundle); getSupportFragmentManager().beginTransaction().replace(R.id.search_result,fragment).commit(); search.setVisibility(View.GONE); searchView.setIconified(true);//防止数据两次加载 } return true; } @Override public boolean onQueryTextChange(String s) { Logger.e("text change"); return false; } }); //热搜词添加 Random random=new Random(); for(int i=0;i<hotKeyList.size();i++){ View child=View.inflate(this,R.layout.item_hotkey,null); TextView textView=child.findViewById(R.id.tag); textView.setText(hotKeyList.get(i)); textView.setTextColor(RandomColorUtil.getRandomColor(random)); child.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { searchView.setQuery(textView.getText(),false); } }); flowLayout.addView(child); } //搜索历史列表设置 searchHistoryList=searchHistoryDao.queryAllSearchHistory(); adapter=new SearchHistoryAdapter(searchHistoryList); adapter.setOnDeleteClickListener(new SearchHistoryAdapter.OnDeleteClickListener() { @Override public void onClick(int position) { searchHistoryDao.deleteHistoryById(searchHistoryList.get(position)); searchHistoryList.remove(position); adapter.notifyDataSetChanged(); } }); searchHistoryView.setLayoutManager(new LinearLayoutManager(this)); searchHistoryView.setAdapter(adapter); searchHistoryView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); } //语音听写UI private RecognizerDialog recognizerDialog; //听写结果 private HashMap<String,String> recognizeResults=new LinkedHashMap<>(); @OnClick(R.id.recorder) public void onClicked(){ recognizeResults.clear(); recognizerDialog=new RecognizerDialog(this,initListener); initParams(); recognizerDialog.setListener(recognizerDialogListener); recognizerDialog.show(); } private void initParams(){ //语音输入语言 recognizerDialog.setParameter(SpeechConstant.LANGUAGE,"zh_cn"); //结果返回语言 recognizerDialog.setParameter(SpeechConstant.ACCENT,"mandarin"); //返回结果无标点 recognizerDialog.setParameter(SpeechConstant.ASR_PTT,"0"); //设置语音前端点:静音超时时间,10s,即用户多长时间不说话则当做超时处理 recognizerDialog.setParameter(SpeechConstant.VAD_BOS, "10000"); //设置语音后端点:后端点静音检测时间,自动停止录音,1s,即用户停止说话多长时间内即认为不再输入 recognizerDialog.setParameter(SpeechConstant.VAD_EOS, "1000"); } //初始化监听器 private InitListener initListener=new InitListener() { @Override public void onInit(int code) { if (code != ErrorCode.SUCCESS) { showTips("初始化失败,错误码:" + code); } } }; //听写UI监听器 private RecognizerDialogListener recognizerDialogListener=new RecognizerDialogListener() { @Override public void onResult(RecognizerResult recognizerResult, boolean b) { handleResult(recognizerResult); } @Override public void onError(SpeechError speechError) { showTips(speechError.getPlainDescription(true)); } }; //解析结果 private void handleResult(RecognizerResult recognizerResult) { String text= JsonParser.parseIatResult(recognizerResult.getResultString()); String sn=null; //读取json结果中的sn字段 try{ JSONObject resultJson=new JSONObject(recognizerResult.getResultString()); sn=resultJson.optString("sn"); }catch (JSONException e){ e.printStackTrace(); } recognizeResults.put(sn,text); StringBuilder resultBuffer=new StringBuilder(); for(String key:recognizeResults.keySet()) resultBuffer.append(recognizeResults.get(key)); searchView.setQuery(resultBuffer,false); } }
package com.example.displayinfo; import android.app.Activity; import android.content.res.Configuration; import android.graphics.Point; import android.os.Build; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.Display; import android.widget.TextView; public class MainActivity extends Activity { TextView tView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tView = (TextView) findViewById(R.id.logTextView); showInfo(); // initial display } /** Update the info if the screen is rotated, etc. */ @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); showInfo(); } /** Compute the current info, and add it to the textarea. */ void showInfo() { tView.append("AboutInfo v 0.0" + "\n"); // Get Android information String manufacturer = Build.MANUFACTURER; String deviceCode = Build.BOARD; String device = Build.DEVICE; String version = Build.DISPLAY; String codename = Build.VERSION.CODENAME; String release = Build.VERSION.RELEASE; int sdk = Build.VERSION.SDK_INT; tView.append("Make: " + manufacturer + "; Code " + deviceCode + "; Device " + device + "\n"); tView.append("Android: " + codename + " " + release + " API " + sdk + " Load " + version + "\n"); // Get view information tView.append("\n"); tView.append("Display info:" + "\n"); final Display display = getWindowManager().getDefaultDisplay(); int width, height; // This method added in API level 13. Point point = new Point(); display.getSize(point); // READ DISCLAIMER ON METHOD DOCUMENT!! width = point.x; height = point.y; dump("display.getSize()", width, height); width = display.getWidth(); height = display.getHeight(); dump("display.getWidth(),getHeight", width, height); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); width = metrics.widthPixels; height = metrics.heightPixels; dump("metrics.fields", width, height); } private void dump(String m, int w, int h) { tView.append(String.format("Via %s: Width %d, Height %d%n", m, w, h)); } }
package org.vanilladb.comm.protocols.tob; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.vanilladb.comm.process.ProcessList; import org.vanilladb.comm.process.ProcessState; import org.vanilladb.comm.protocols.events.ProcessListInit; import org.vanilladb.comm.protocols.floodingcons.ConsensusRequest; import org.vanilladb.comm.protocols.floodingcons.ConsensusResult; import org.vanilladb.comm.protocols.rb.MessageId; import org.vanilladb.comm.protocols.tcpfd.FailureDetected; import org.vanilladb.comm.protocols.tcpfd.ProcessConnected; import net.sf.appia.core.AppiaEventException; import net.sf.appia.core.Channel; import net.sf.appia.core.Direction; import net.sf.appia.core.Event; import net.sf.appia.core.Layer; import net.sf.appia.core.Session; public class TotalOrderBroadcastSession extends Session { private static Logger logger = Logger.getLogger(TotalOrderBroadcastSession.class.getName()); private ProcessList processList; private int sequenceNumber = 1; private Set<MessageId> delivered = new HashSet<MessageId>(); // <Message Id> -> <message> private Map<MessageId, TotalOrderBroadcast> unordered = new HashMap<MessageId, TotalOrderBroadcast>(); private List<MessageId> waitForDeliverIds = new ArrayList<MessageId>(); private Map<MessageId, TotalOrderBroadcast> waitForDeliverMessages = new HashMap<MessageId, TotalOrderBroadcast>(); private boolean wait = false; TotalOrderBroadcastSession(Layer layer) { super(layer); } @Override public void handle(Event event) { if (event instanceof ProcessListInit) handleProcessListInit((ProcessListInit) event); else if (event instanceof ProcessConnected) handleProcessConnected((ProcessConnected) event); else if (event instanceof FailureDetected) handleFailureDetected((FailureDetected) event); else if (event instanceof TotalOrderBroadcast) { if (event.getDir() == Direction.DOWN) { handleBroadcastRequest((TotalOrderBroadcast) event); } else { handleBroadcastDeliver((TotalOrderBroadcast) event); } } else if (event instanceof ConsensusResult) handleConsensusResult((ConsensusResult) event); } private void handleProcessListInit(ProcessListInit event) { if (logger.isLoggable(Level.FINE)) logger.fine("Received ProcessListInit"); // Save the list this.processList = event.copyProcessList(); // Let the event continue try { event.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } private void handleProcessConnected(ProcessConnected event) { if (logger.isLoggable(Level.FINE)) logger.fine("Received ProcessConnected"); // Let the event continue try { event.go(); } catch (AppiaEventException e) { e.printStackTrace(); } // Set the connected process ready processList.getProcess(event.getConnectedProcessId()) .setState(ProcessState.CORRECT); } private void handleFailureDetected(FailureDetected event) { if (logger.isLoggable(Level.FINE)) logger.fine("Received FailureDetected (failed id = " + event.getFailedProcessId() + ")"); processList.getProcess(event.getFailedProcessId()).setState(ProcessState.FAILED); // Let the event continue try { event.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } private void handleBroadcastRequest(TotalOrderBroadcast event) { if (logger.isLoggable(Level.FINE)) logger.fine("Received a TotalOrderBroadcast request"); // Append a sequence number MessageId id = new MessageId(processList.getSelfId(), sequenceNumber); sequenceNumber++; event.getMessage().pushObject(id); // Let the event continue. // ReliableBroadcast layer will handle it. try { event.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } private void handleBroadcastDeliver(TotalOrderBroadcast event) { if (logger.isLoggable(Level.FINE)) logger.fine("Received a delivered Broadcast message"); // Take out the message id MessageId id = (MessageId) event.getMessage().popObject(); // Check if it is delivered if (!delivered.contains(id)) { if (waitForDeliverIds.contains(id)) { waitForDeliverMessages.put(id, event); tryDeliver(event.getChannel()); } else { // Cache the message unordered.put(id, event); tryOrder(event.getChannel()); } } } private void handleConsensusResult(ConsensusResult event) { OrderProposal decision = (OrderProposal) event.getDecision(); // Sort the ids List<MessageId> orderedIds = new ArrayList<MessageId>(decision.getMessageIds()); Collections.sort(orderedIds); // Put the decided ids and corresponding messages to the deliver queue for (MessageId id : orderedIds) { TotalOrderBroadcast message = unordered.remove(id); waitForDeliverIds.add(id); if (message != null) waitForDeliverMessages.put(id, message); } tryDeliver(event.getChannel()); // Ready for the next consensus wait = false; tryOrder(event.getChannel()); } private void tryOrder(Channel channel) { if (!wait && !unordered.isEmpty()) { wait = true; // Create a order proposal OrderProposal proposal = new OrderProposal(unordered.keySet()); // Send a consensus request try { ConsensusRequest request = new ConsensusRequest(channel, this, proposal); request.init(); request.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } } private void tryDeliver(Channel channel) { Set<MessageId> delivered = new HashSet<MessageId>(); for (MessageId id : waitForDeliverIds) { TotalOrderBroadcast message = waitForDeliverMessages.remove(id); if (message != null) { delivered.add(id); try { message.setSourceSession(this); message.setDir(Direction.UP); message.init(); message.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } } // Remove the delivered ids form the queue waitForDeliverIds.removeAll(delivered); this.delivered.addAll(delivered); } }
package com.user.profileapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.Toast; import com.raizlabs.android.dbflow.sql.language.Select; import java.util.ArrayList; import java.util.List; public class FriendsActivity extends AppCompatActivity { List<Friend> listFriend = new ArrayList<>(); Friend deletedFriend = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_friends); final RelativeLayout boxPopUp = findViewById(R.id.box_popup); Button btnYa = findViewById(R.id.btn_ya); Button btnTidak = findViewById(R.id.btn_tidak); btnTidak.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boxPopUp.setVisibility(View.GONE); } }); RecyclerView rvFriends = findViewById(R.id.rv_friends); rvFriends.setHasFixedSize(true); LinearLayoutManager llm = new LinearLayoutManager(getApplicationContext()); rvFriends.setLayoutManager(llm); final FriendsAdapter adapter = new FriendsAdapter(listFriend, new FriendListener() { @Override public void onFriendClicked(Friend friend) { Toast.makeText(getApplicationContext(), friend.getNama() + " Clicked", Toast.LENGTH_SHORT).show(); boxPopUp.setVisibility(View.VISIBLE); deletedFriend = friend; } }); rvFriends.setAdapter(adapter); btnYa.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // refresh list listFriend.remove(deletedFriend); adapter.refreshData(listFriend); // delete dari dbnya deletedFriend.delete(); } }); listFriend = new Select() .from(Friend.class) .queryList(); adapter.refreshData(listFriend); } }
package com.example.administrator.listview_callback.Test2; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import com.example.administrator.listview_callback.Myadapter; import com.example.administrator.listview_callback.R; import java.util.List; /** * Created by Administrator on 2018/1/26 0026. */ public class Myadapter2 extends BaseAdapter { String myData=""; private List<String> data; private ICallBack2 callBack2; private Main2Activity context; public Myadapter2(ICallBack2 callBack2, List<String>data , Main2Activity main2Activity){ this.callBack2=callBack2; this.data=data; this.context=main2Activity; } @Override public int getCount() { return data.size(); } @Override public Object getItem(int i) { return data.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int position, View view, ViewGroup viewGroup) { MyViewHodler myViewHodler; if (view==null){ view= LayoutInflater.from(context).inflate(R.layout.item,null); myViewHodler=new MyViewHodler(view); view.setTag(myViewHodler); }else { myViewHodler= (MyViewHodler) view.getTag(); } myViewHodler.button.setText(data.get(position)); myData = data.get(position); myViewHodler.button.setOnClickListener(new MyListener(position)); return view; } class MyViewHodler{ Button button; public MyViewHodler(View view){ button=view.findViewById(R.id.bt); } } class MyListener implements View.OnClickListener{ int position; public MyListener(int position){ this.position=position; } @Override public void onClick(View view) { callBack2.show(); callBack2.showData(position); } } public interface ICallBack2{ void show(); void showData(int data); } }
package com.daydvr.store.view.login; import android.view.View; import android.widget.ImageView; import com.daydvr.store.base.BaseActivity; /** * @author LoSyc * @version Created on 2018/1/6. 0:25 */ public class BaseForLoginActivity extends BaseActivity { protected void initBackButton(ImageView back) { back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
package com.restaurent; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.ClientContext; import org.apache.http.impl.client.AbstractHttpClient; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.json.JSONArray; import org.json.JSONObject; import android.os.Bundle; import android.os.StrictMode; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckedTextView; import android.widget.ListView; import android.widget.Spinner; import android.widget.Toast; public class MainActivity extends ListActivity { //String[] city= {}; String[] sbu; String[] item; String[] price; Context context=this; //String[] x; int xx; int[] quantity; JSONArray jArray; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); Button order=(Button)findViewById(R.id.order); order.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub int count=0; Intent it=new Intent(MainActivity.this,ReviewActivity.class); for(int i=0;i<jArray.length();i++) { if(quantity[i]!=0) { count++; it.putExtra("item"+i, item[i]); it.putExtra("price"+i, price[i]); it.putExtra("quantity"+i,""+quantity[i]); } else continue; } it.putExtra("noOfItems",""+jArray.length()); it.putExtra("noOfItems2",""+count); for(int a=0;a<quantity.length;a++) Log.e("A Loop",""+quantity[a]); startActivity(it); } }); ListView listview= getListView(); // listview.setChoiceMode(listview.CHOICE_MODE_NON E); // listview.setChoiceMode(listview.CHOICE_MODE_SINGLE); //listview.setAdapter(getListAdapter()); listview.setChoiceMode(listview.CHOICE_MODE_MULTIPLE); //-- text filtering InputStream is2 = null; // TODO Auto-generated method stub try { HttpClient httpclient = new DefaultHttpClient(); /* httpclient.getParams().setParameter( HttpMethodParams.USER_AGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2" ); ((AbstractHttpClient) httpclient).setCookieStore(new BasicCookieStore()); httpclient.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY); */ HttpPost httppost = new HttpPost("http://vamsidhar.esy.es/search.php"); // CookieStore cookieStore = new BasicCookieStore(); // Create local HTTP context // HttpContext localContext = new BasicHttpContext(); // Bind custom cookie store to the local context // localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); //httppost.setEntity(new UrlEncodedFormEntity(a1)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is2 = entity.getContent(); // Toast.makeText(getApplicationContext(), "Connection Success Inserted",Toast.LENGTH_SHORT).show(); //Log.e("log_tag", " in doinbackground connection success"); // Toast.makeText(getApplicationContext(), “pass”,Toast.LENGTH_SHORT).show(); } catch (Exception e) { // x="false"; Log.e("log_tag", "Error in http connection" + e.toString()); } //convert response to string try { Log.e("log_tag", "TWO"); BufferedReader reader = new BufferedReader(new InputStreamReader(is2,"iso-8859-1")); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); // Toast.makeText(getApplicationContext(), “Input Reading pass”, Toast.LENGTH_SHORT).show(); } is2.close(); Log.e("log_tag", "THREE"); String result = sb.toString(); Log.e("log_tag", " JSON"+result); /* boolean x=result!=null; Log.e("log_tag", "444"); if(!x||result.equals("")||result.equals(null)||result==""||result==null) { Log.e("log_tag", "2222"); Toast.makeText(getApplicationContext(),"No ResultsFound",Toast.LENGTH_SHORT); }*/ Log.e("log_tag", "1111"); jArray=new JSONArray(result); Log.e("log_tag", "FOUR"); //JSONArray ar=new JSONArray(ob); item=new String[jArray.length()]; price=new String[jArray.length()]; quantity=new int[jArray.length()]; //String[] location=new String[jArray.length()]; //String[] phone=new String[jArray.length()]; sbu=new String[jArray.length()]; for(int i=0;i<jArray.length();i++) { Log.e("FOR", ""+i); JSONObject json_data = jArray.getJSONObject(i); item[i]=json_data.getString("item"); price[i]=json_data.getString("price"); Log.e("fff",item[i]+" Rs"+price[i]); int x=item[i].length()+5; sbu[i]=item[i]; for(int j=45;j>x;j--) sbu[i]+=" "; sbu[i]=sbu[i]+"Rs."+price[i]; Log.e("log_tag", "LOOP Item: "+item[i].toString()+" Price : "+price[i].toString()); } /* if(jArray.length()==0) { Toast.makeText(getApplicationContext(), "No ResultsFound",Toast.LENGTH_SHORT); } else { reader.close(); Intent it=new Intent(MainActivity.this,ReviewActivity.class); for(int i=0;i<jArray.length();i++) { it.putExtra("name"+i, name[i]); it.putExtra("bgroup"+i, bgr[i]); it.putExtra("location"+i, location[i]); it.putExtra("phone"+i, phone[i]); } it.putExtra("noOfPeople",""+jArray.length()); startActivity(it); } */ //tv.setText(result); } catch (Exception e) { Log.e("log_tag", " Error converting result" + e.toString()); } /* x=new String[sbu.length]; for(int i=0;i<sbu.length;i++) { x[i]=sbu[i].toString(); } */ listview.setTextFilterEnabled(true); // listview.scrollBy(0, 20); setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_checked,sbu)); Log.e("WHOLE",""+sbu); } public void onListItemClick(ListView parent, View v,final int position,long id){ xx=position; final CheckedTextView item = (CheckedTextView) v; //Toast.makeText(this, sbu[position] +item.isChecked(), Toast.LENGTH_SHORT).show(); if(item.isChecked()) { LayoutInflater li = LayoutInflater.from(context); View promptsView = li.inflate(R.layout.list_view_adapter, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); // set prompts.xml to alertdialog builder alertDialogBuilder.setView(promptsView); final Spinner userInput = (Spinner) promptsView .findViewById(R.id.spinner1); // set dialog message alertDialogBuilder .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // get user input and set it to result // edit text quantity[xx]=Integer.parseInt(userInput.getSelectedItem().toString()); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { item.setChecked(false); dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } else { quantity[position]=0; } for(int a=0;a<quantity.length;a++) Log.e("A Loop",""+quantity[a]); } }
package ru.shikhovtsev.factorymethod; import ru.shikhovtsev.factorymethod.button.Button; import ru.shikhovtsev.factorymethod.button.WindowsButton; public class WindowsDialog extends Dialog { @Override public Button createButton() { return new WindowsButton(); } }
package Object; import Object.Enum.CategoriaEnum; import Object.Enum.IntensitaEnum; import Object.Enum.UnitaMisuraEnum; /** * La classe EsercizioObject mappa la tabella "esercizio" del database */ public class EsercizioObject { private String tipologia; private CategoriaEnum categoria; private IntensitaEnum intensita; private UnitaMisuraEnum unita_misura; private int consumo_calorico; public EsercizioObject() { tipologia=null; consumo_calorico=0; categoria=null; intensita=null; unita_misura=null; } public String getTipologia() { return tipologia; } public void setTipologia(String tipologia) { this.tipologia = tipologia; } public int getConsumo_calorico() { return consumo_calorico; } public void setConsumo_calorico(int consumo_calorico) { this.consumo_calorico = consumo_calorico; } public CategoriaEnum getCategoria() { return categoria; } public void setCategoria(CategoriaEnum categoria) { this.categoria = categoria; } public IntensitaEnum getIntensita() { return intensita; } public void setIntensita(IntensitaEnum intensita) { this.intensita = intensita; } public UnitaMisuraEnum getUnita_misura() { return unita_misura; } public void setUnita_misura(UnitaMisuraEnum unita_misura) { this.unita_misura = unita_misura; } }
package no.nav.vedtak.felles.integrasjon.person; public record PDLExceptionDetails(String type, String cause, String policy) { }
package hw10003; public class Sample9 { public static void main(String[]args) { int num1,num2; num1=3; System.out.println("變數num1的值是:"+num1); num2=num1; System.out.println("將變數num1指定到變數num2之中"); System.out.println("變數num2的值是:"+num2); } }
package com.cbs.edu.jdbc.examples; import java.sql.*; import java.util.ArrayList; import java.util.List; public class PreparedStatementExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "org.postgresql.Driver"; static final String DB_URL = "impl:postgresql://ec2-54-228-251-254.eu-west-1.compute.amazonaws.com:5432/d3kqlpsdudhcij?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory"; // Database credentials static final String USER = "nykgmqvvdcegwm"; static final String PASS = "bf201d90be9b4ae104d4aaa76ac8f63c8482ad8ff94f4d010f25f861066f8690"; public static void main(String[] args) { Connection conn = null; PreparedStatement stmt = null; try { //STEP 2: Register JDBC driver Class.forName(JDBC_DRIVER); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.prepareStatement("INSERT INTO employees(first_name, last_name, age, email, gender, salary, id) VALUES(?, ?, ?, ?, ?, ?, ?)"); stmt.setString(1, "Tom"); stmt.setString(2, "Tomson"); stmt.setInt(3, 22); stmt.setString(4, "Tom21@gmail.com"); stmt.setString(5, "Male"); stmt.setInt(6, 22000); stmt.setInt(7, 51); stmt.execute(); //STEP 6: Clean-up environment stmt.close(); conn.close(); } catch (SQLException se) { //Handle errors for JDBC se.printStackTrace(); } catch (Exception e) { //Handle errors for Class.forName e.printStackTrace(); } finally { //finally block used to close resources try { if (stmt != null) stmt.close(); } catch (SQLException se2) { }// nothing we can do try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end FirstExample
package spms.vo; import java.util.Date; public class Application { protected int ano; protected int rno; protected String title; protected String email; protected String company; protected String job; protected String question1; protected String answer1; protected String question2; protected String answer2; protected String question3; protected String answer3; protected String question4; protected String answer4; protected String question5; protected String answer5; protected String question6; protected String answer6; protected Date createdDate; public int getAno() { return ano; } public Application setAno(int ano) { this.ano = ano; return this; } public int getRno() { return rno; } public Application setRno(int rno) { this.rno = rno; return this; } public String getTitle() { return title; } public Application setTitle(String title) { this.title = title; return this; } public String getEmail() { return email; } public Application setEmail(String email) { this.email = email; return this; } public String getCompany() { return company; } public Application setCompany(String company) { this.company = company; return this; } public String getJob() { return job; } public Application setJob(String job) { this.job = job; return this; } public String getQuestion1() { return question1; } public Application setQuestion1(String question1) { this.question1 = question1; return this; } public String getAnswer1() { return answer1; } public Application setAnswer1(String answer1) { this.answer1 = answer1; return this; } public String getQuestion2() { return question2; } public Application setQuestion2(String question2) { this.question2 = question2; return this; } public String getAnswer2() { return answer2; } public Application setAnswer2(String answer2) { this.answer2 = answer2; return this; } public String getQuestion3() { return question3; } public Application setQuestion3(String question3) { this.question3 = question3; return this; } public String getAnswer3() { return answer3; } public Application setAnswer3(String answer3) { this.answer3 = answer3; return this; } public String getQuestion4() { return question4; } public Application setQuestion4(String question4) { this.question4 = question4; return this; } public String getAnswer4() { return answer4; } public Application setAnswer4(String answer4) { this.answer4 = answer4; return this; } public String getQuestion5() { return question5; } public Application setQuestion5(String question5) { this.question5 = question5; return this; } public String getAnswer5() { return answer5; } public Application setAnswer5(String answer5) { this.answer5 = answer5; return this; } public String getQuestion6() { return question6; } public Application setQuestion6(String question6) { this.question6 = question6; return this; } public String getAnswer6() { return answer6; } public Application setAnswer6(String answer6) { this.answer6 = answer6; return this; } public Date getCreatedDate() { return createdDate; } public Application setCreatedDate(Date createdDate) { this.createdDate = createdDate; return this; } }
package algopro.algo; import algopro.util.MapScanner; import java.util.Random; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class JumpPointTest { JumpPoint j; char[][] chart; final double ref = 0.01; boolean check; Random random; @Before public void setUp() throws Exception { MapScanner reader = new MapScanner(this.getClass().getResource("/algopro/testFiles/test.map").getPath()); chart = reader.read(); check = true; j = new JumpPoint(); } @Test(timeout = 500) public void moveOneVertical() { assertTrue(Math.abs(j.run(9, 1, 9, 2, chart)) - 1 < ref); } @Test(timeout = 500) public void moveOneHorizontal() { assertTrue(Math.abs(j.run(9, 2, 10, 2, chart)) - 1 < ref); } @Test(timeout = 500) public void moveOneDiagonal() { assertTrue(Math.abs(j.run(9, 1, 10, 2, chart) - Math.sqrt(2)) < ref); } @Test(timeout = 500) public void moveLongerVertical() { assertTrue(Math.abs(j.run(9, 1, 9, 40, chart)) - 39 < ref); } @Test(timeout = 500) public void moveLongerHorizontal() { assertTrue(Math.abs(j.run(45, 12, 6, 12, chart)) - 39 < ref); } @Test(timeout = 500) public void noRouteExists() { assertTrue(j.run(45, 2, 19, 33, chart) + 1 < ref); } @Test(timeout = 500) public void startFromBlockedTile() { assertTrue(j.run(30, 15, 30, 1, chart) + 1 < ref); } @Test(timeout = 500) public void stopAtBlockedTile() { assertTrue(j.run(30, 16, 30, 0, chart) + 1 < ref); } @Test(timeout = 500) public void fixedRoute1() { assertTrue(Math.abs(j.run(45, 2, 27, 32, chart)) - 88.87 < ref); } @Test(timeout = 500) public void fixedRoute2() { assertTrue(j.run(30, 16, 30, 1, chart) - 82.11 < ref); } @Test(timeout = 500) public void random1() { random = new Random(42); for (int i = 0; i < 500; i++) { int x1 = random.nextInt(12) + 3; int y1 = random.nextInt(47) + 1; int x2 = random.nextInt(12) + 3; int y2 = random.nextInt(47) + 1; int shorter = Math.min(Math.abs(x1 - x2), Math.abs(y1 - y2)); int longer = Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)); double trueDistance = shorter * Math.sqrt(2) + longer - shorter; if (j.run(x1, y1, x2, y2, chart) - trueDistance > ref) { check = false; } } assertTrue(check); } @Test(timeout = 500) public void random2() { random = new Random(43); for (int i = 0; i < 500; i++) { int x1 = random.nextInt(12) + 3; int y1 = random.nextInt(47) + 1; int x2 = random.nextInt(12) + 3; int y2 = random.nextInt(47) + 1; int shorter = Math.min(Math.abs(x1 - x2), Math.abs(y1 - y2)); int longer = Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)); double trueDistance = shorter * Math.sqrt(2) + longer - shorter; if (j.run(x1, y1, x2, y2, chart) - trueDistance > ref) { check = false; } } assertTrue(check); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Random; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; /** * Benchmarks for {@link StringUtils}. * * @author Brian Clozel */ @BenchmarkMode(Mode.Throughput) public class StringUtilsBenchmark { @Benchmark public void collectionToDelimitedString(DelimitedStringState state, Blackhole bh) { bh.consume(StringUtils.collectionToCommaDelimitedString(state.elements)); } @State(Scope.Benchmark) public static class DelimitedStringState { @Param("10") int elementMinSize; @Param("20") int elementMaxSize; @Param("10") int elementCount; Collection<String> elements; @Setup(Level.Iteration) public void setup() { Random random = new Random(); this.elements = new ArrayList<>(this.elementCount); int bound = this.elementMaxSize - this.elementMinSize; for (int i = 0; i < this.elementCount; i++) { this.elements.add(String.format("%0" + (random.nextInt(bound) + this.elementMinSize) + "d", 1)); } } } @Benchmark public void cleanPath(CleanPathState state, Blackhole bh) { for (String path : state.paths) { bh.consume(StringUtils.cleanPath(path)); } } @State(Scope.Benchmark) public static class CleanPathState { private static final List<String> SEGMENTS = Arrays.asList("some", "path", ".", "..", "springspring"); @Param("10") int segmentCount; @Param("20") int pathsCount; Collection<String> paths; @Setup(Level.Iteration) public void setup() { this.paths = new ArrayList<>(this.pathsCount); Random random = new Random(); for (int i = 0; i < this.pathsCount; i++) { this.paths.add(createSamplePath(random)); } } private String createSamplePath(Random random) { String separator = (random.nextBoolean() ? "/" : "\\"); StringBuilder sb = new StringBuilder(); sb.append("jar:file:///c:"); for (int i = 0; i < this.segmentCount; i++) { sb.append(separator); sb.append(SEGMENTS.get(random.nextInt(SEGMENTS.size()))); } sb.append(separator); sb.append("the%20file.txt"); return sb.toString(); } } }
/* The MIT License (MIT) Copyright (c) 2014 Stephan Kesper Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package de.kesper.software.bootstrap.components.grid; import java.io.IOException; import javax.faces.component.FacesComponent; import javax.faces.component.UIOutput; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; /** * * @author kesper */ @FacesComponent(value = "de.kesper.software.bootstrap.components.grid.GridTag") public class GridTag extends UIOutput { @Override public String getFamily() { return "grid"; } @Override public void encodeBegin(FacesContext context) throws IOException { ResponseWriter writer = context.getResponseWriter(); writer.startElement("div", this); writer.writeAttribute("class", "grid", null); } @Override public void encodeEnd(FacesContext context) throws IOException { ResponseWriter writer = context.getResponseWriter(); writer.endElement("div"); } }
package ca.mcgill.ecse223.kingdomino.features; import static org.junit.Assert.assertEquals; import ca.mcgill.ecse223.kingdomino.KingdominoApplication; import ca.mcgill.ecse223.kingdomino.controller.*; import ca.mcgill.ecse223.kingdomino.model.*; import io.cucumber.java.After; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.List; /*** *As a player, I want the Kingdomino app to automatically check if my *current domino is placed to an adjacent territory. *@author Cecilia * ***/ public class VerifyNeighborAdjacencyStepDefinition { private Boolean isValid; private Square[] grid; @Given("the game is initialized for neighbor adjacency") public void initialize_the_game() { // Intialize empty game Kingdomino kingdomino = KingdominoApplication.getKingdomino(); Game game = new Game(48, kingdomino); game.setNumberOfPlayers(4); kingdomino.setCurrentGame(game); // Populate game addDefaultUsersAndPlayers(game); createAllDominoes(game); game.setNextPlayer(game.getPlayer(0)); KingdominoApplication.setKingdomino(kingdomino); String player0Name = (game.getPlayer(0).getUser().getName()); GameController.setGrid(player0Name, new Square[81]); GameController.setSet(player0Name, new DisjointSet(81)); Square[] grid = GameController.getGrid(player0Name); for(int i = 4; i >=-4; i-- ) for(int j = -4 ; j <= 4; j++) grid[Square.convertPositionToInt(i,j)] = new Square(i,j); } @When("check current preplaced domino adjacency is initiated") public void trigger_check_neighbor_adjacency() { Kingdomino kingdomino = KingdominoApplication.getKingdomino(); Game game = kingdomino.getCurrentGame(); Player player = game.getNextPlayer(); Castle castle = getCastle(player.getKingdom()); List<KingdomTerritory> list= player.getKingdom().getTerritories(); DominoInKingdom dominoInKingdom = (DominoInKingdom)list.get(list.size() - 1); String player0Name = (game.getPlayer(0).getUser().getName()); Square[] grid = GameController.getGrid(player0Name); if (castle != null && dominoInKingdom != null && grid !=null) isValid = VerificationController.verifyNeighborAdjacency(castle,grid,dominoInKingdom); } @Then("the current-domino\\/existing-domino adjacency is {string}") public void the_castle_domino_adjacency_is(String result) { Boolean expectedResult = (!result.equals("invalid")); assertEquals(expectedResult,isValid); } @After public void tearDown() { Kingdomino kingdomino = KingdominoApplication.getKingdomino(); kingdomino.delete(); GameController.clearGrids(); GameController.clearSets(); } /////////////////////////////////////// /// -----Private Helper Methods---- /// /////////////////////////////////////// private void addDefaultUsersAndPlayers(Game game) { String[] userNames = { "User1", "User2", "User3", "User4" }; for (int i = 0; i < userNames.length; i++) { User user = game.getKingdomino().addUser(userNames[i]); Player player = new Player(game); player.setUser(user); player.setColor(Player.PlayerColor.values()[i]); Kingdom kingdom = new Kingdom(player); new Castle(0, 0, kingdom, player); } } private Domino getdominoByID(int id) { Game game = KingdominoApplication.getKingdomino().getCurrentGame(); for (Domino domino : game.getAllDominos()) { if (domino.getId() == id) { return domino; } } throw new java.lang.IllegalArgumentException("Domino with ID " + id + " not found."); } private void createAllDominoes(Game game) { try { BufferedReader br = new BufferedReader(new FileReader("src/main/resources/alldominoes.dat")); String line = ""; String delimiters = "[:\\+()]"; while ((line = br.readLine()) != null) { String[] dominoString = line.split(delimiters); // {id, leftTerrain, rightTerrain, crowns} int dominoId = Integer.decode(dominoString[0]); TerrainType leftTerrain = getTerrainType(dominoString[1]); TerrainType rightTerrain = getTerrainType(dominoString[2]); int numCrown = 0; if (dominoString.length > 3) { numCrown = Integer.decode(dominoString[3]); } new Domino(dominoId, leftTerrain, rightTerrain, numCrown, game); } br.close(); } catch (IOException e) { e.printStackTrace(); throw new java.lang.IllegalArgumentException( "Error occured while trying to read alldominoes.dat: " + e.getMessage()); } } private TerrainType getTerrainType(String terrain) { switch (terrain) { case "W": return TerrainType.WheatField; case "F": return TerrainType.Forest; case "M": return TerrainType.Mountain; case "G": return TerrainType.Grass; case "S": return TerrainType.Swamp; case "L": return TerrainType.Lake; default: throw new java.lang.IllegalArgumentException("Invalid terrain type: " + terrain); } } private DominoInKingdom.DirectionKind getDirection(String dir) { switch (dir) { case "up": return DominoInKingdom.DirectionKind.Up; case "down": return DominoInKingdom.DirectionKind.Down; case "left": return DominoInKingdom.DirectionKind.Left; case "right": return DominoInKingdom.DirectionKind.Right; default: throw new java.lang.IllegalArgumentException("Invalid direction: " + dir); } } private Castle getCastle (Kingdom kingdom) { for(KingdomTerritory territory: kingdom.getTerritories()){ if(territory instanceof Castle ) return (Castle)territory; } 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 chapseven; import java.util.Scanner; /** * * @author Frebby */ public class ValidatePassword { public static void main(String[] args) { Scanner input = new Scanner(System.in); String str = input.nextLine(); boolean upperCase = false; boolean lowerCase= false; boolean digit = false; for(int x = 0; x < str.length(); ++x) { int ch = str.charAt(x); if(Character.isDigit(ch) && Character.isUpperCase(ch) && Character.isLowerCase(ch)) { digit = true; upperCase = true; lowerCase= true; System.out.println("access granted"); } if(!(Character.isDigit(ch) && Character.isUpperCase(ch) && Character.isLowerCase(ch))){ upperCase = false; lowerCase= false; digit = false; System.out.println("acces denied"); } } } }
/*Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].*/ public class Solution { public void moveZeroes(int[] nums) { if(nums.length==0) //if length of array is 0 return return; int i=0,j=1; while(j<nums.length) { if(nums[i]==0) //when we find 0 at a particular index search for an index with non-zero element { if(nums[j]!=0) { nums[i]=nums[j]; //swap them and increase the pointers nums[j]=0; i++; j++; } else j++; } else { i++; j++; } } } }
package org.lazywizard.localmp.controllers.joypad; import org.lwjgl.input.Controller; // Purpose of this class: LWJGL event system doesn't work with non-L axis, // so we need to calculate axis events manually if we want the R/LZ/RZ/dpad // TODO: Throw exception when acting on consumed events class JoypadAxisEvent extends BaseJoypadInputEvent { private final Controller controller; private final AxisType type; private final long nanoTime; private final boolean isDeadZoneEvent; private final float axisX, axisY, axisZ, dpadX, dpadY; private final boolean isValid; private boolean isConsumed = false; enum AxisType { LAXIS, RAXIS, LZAXIS, RZAXIS, DPAD } JoypadAxisEvent(Controller controller, AxisType axis) { this.controller = controller; this.nanoTime = System.nanoTime(); this.type = axis; switch (axis) { case LAXIS: isValid = controller.getAxisCount() >= 1; axisX = controller.getXAxisValue(); axisY = controller.getYAxisValue(); axisZ = 0f; isDeadZoneEvent = (Math.abs(axisX) <= controller.getXAxisDeadZone()) && (Math.abs(axisY) <= controller.getYAxisDeadZone()); dpadX = 0; dpadY = 0; break; case RAXIS: isValid = controller.getAxisCount() >= 3; axisX = controller.getRXAxisValue(); axisY = controller.getRYAxisValue(); axisZ = 0f; isDeadZoneEvent = (Math.abs(axisX) <= controller.getRXAxisDeadZone()) && (Math.abs(axisY) <= controller.getRYAxisDeadZone()); dpadX = 0; dpadY = 0; break; case LZAXIS: isValid = controller.getAxisCount() >= 4; axisX = 0f; axisY = 0f; axisZ = controller.getZAxisValue(); dpadX = 0f; dpadY = 0f; isDeadZoneEvent = (Math.abs(axisZ) <= controller.getZAxisDeadZone()); break; case RZAXIS: isValid = controller.getAxisCount() >= 5; axisX = 0f; axisY = 0f; axisZ = controller.getRZAxisValue(); dpadX = 0f; dpadY = 0f; isDeadZoneEvent = (Math.abs(axisZ) <= controller.getRZAxisDeadZone()); break; case DPAD: isValid = true; axisX = 0f; axisY = 0f; axisZ = 0f; dpadX = controller.getPovX(); dpadY = controller.getPovY(); isDeadZoneEvent = (dpadX == 0f) && (dpadY == 0f); break; default: isValid = false; axisX = 0f; axisY = 0f; axisZ = 0f; dpadX = 0f; dpadY = 0f; isDeadZoneEvent = true; } } @Override public Controller getController() { return controller; } @Override public long getEventNanoTime() { return nanoTime; } @Override public boolean isAxisEvent() { return !isDPadEvent(); } @Override public boolean isLAxisEvent() { return (type == AxisType.LAXIS); } @Override public boolean isRAxisEvent() { return (type == AxisType.RAXIS); } @Override public boolean isLZAxisEvent() { return (type == AxisType.LZAXIS); } @Override public boolean isRZAxisEvent() { return (type == AxisType.RZAXIS); } @Override public boolean isDeadZoneEvent() { return isDeadZoneEvent; } @Override public float getAxisX() { return axisX; } @Override public float getAxisY() { return axisY; } @Override public float getAxisZ() { return axisZ; } @Override public boolean isDPadEvent() { return (type == AxisType.DPAD); } @Override public float getDPadX() { return dpadX; } @Override public float getDPadY() { return dpadY; } @Override public boolean isButtonEvent() { return false; } @Override public boolean isButtonDownEvent() { return false; } @Override public boolean isButtonHeldEvent() { return false; } @Override public boolean isButtonUpEvent() { return false; } @Override public int getButton() { return -1; } @Override public void consume() { isConsumed = true; } @Override public boolean isConsumed() { return isConsumed; } @Override boolean isValidEvent() { return isValid; } }
package 小实例.学生管理系统; public class StudentFactory { private StudentFactory() { } public static IStudentService getInstance() { return new StudentService(); } }
package com.sherry.apistore; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController("/") public class ToDoApp { @GetMapping("/") private String hello() { return "Hello from API Store"; } }
package org.usfirst.frc.team548.robot.AutoModes; import org.usfirst.frc.team548.robot.Constants; public class OnlyShoot extends AutoMode { public OnlyShoot() { super("Only Shoot"); } @Override protected void run() { //shootAtSpeed(12, Constants.SHOOT_AUTON_SPEED); //Blue.... Make pos to do red wideTurn(.2, -.5, -.1); driveInTime(1, -.9); } }
package com.demo.web.tags; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; import com.demo.common.AppConfig; import com.demo.util.DESTool; public class EncryptionTag extends SimpleTagSupport { private String value; @Override public void doTag() throws JspException, IOException { this.getJspContext() .getOut() .print(DESTool.getInstance().encrypt(value, AppConfig.get("app.encryptparam"))); } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
package com.programapprentice.app; import com.programapprentice.util.Util; import org.junit.Test; import java.util.List; /** * User: program-apprentice * Date: 10/11/15 * Time: 11:15 AM */ public class DifferentWaysToAddParentheses_Test { DifferentWaysToAddParentheses_241 obj = new DifferentWaysToAddParentheses_241(); @Test public void test1() { String input = "2*3-4*5"; List<Integer> actual = obj.diffWaysToCompute(input); Util.printListInteger(actual); } @Test public void test2() { String input = "2*3-4*5"; List<String> tokens = obj.splitTokens(input); List<List<String>> afterParenteses = obj.insertParentheses(tokens); Util.printListOfListString(afterParenteses); // ( 2 * ( 3 - ( 4 * 5 ) ) ) // ( 2 * ( ( 3 - 4 ) * 5 ) ) // ( ( 2 * 3 ) - ( 4 * 5 ) ) // ( ( 2 * ( 3 - 4 ) ) * 5 ) // ( ( ( 2 * 3 ) - 4 ) * 5 ) } @Test public void test3() { String input = "( ( ( 2 * 3 ) - 4 ) * 5 )"; List<String> tokens = obj.splitTokens(input); List<String> result = obj.toRPN(tokens); Util.printListToken(result); } }
package br.com.welson.clinic.errors; import javax.ws.rs.core.Response; public class UsernameOrPasswordError extends ErrorDetails { public UsernameOrPasswordError() { super("Usuário ou senha invalidos!", Response.Status.FORBIDDEN); } }
/* * Copyright 2008-2018 shopxx.net. All rights reserved. * Support: localhost * License: localhost/license * FileId: zg8TvBOglxtNtu5NHOACaKzMkpvg5Isz */ package net.bdsc.service.impl; import org.springframework.stereotype.Service; import net.bdsc.entity.Specification; import net.bdsc.service.SpecificationService; /** * Service - 规格 * * @author 好源++ Team * @version 6.1 */ @Service public class SpecificationServiceImpl extends BaseServiceImpl<Specification, Long> implements SpecificationService { }
package com.dodoca.create_image.controller; import com.dodoca.create_image.exception.BaseResult; import com.dodoca.create_image.exception.ResultUtil; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @Author: TianGuangHui * @Date: 2019/6/19 11:29 * @Description: */ @RestController public class RootController { @RequestMapping("/") public BaseResult root() { return ResultUtil.success("create_image server"); } }
package com.nextLevel.hero.member.model.dto; import java.util.Collection; import java.util.List; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.User; public class UserImpl extends User { private int no; //회원번호 private int companyNo; //회사번호 private String id; //회원아이디 private String pwd; //회원비밀번호 private String tempPwdYn; //임시비밀번호여부 private String name; //회원이름 private java.sql.Date registDatetime; //회원가입일시 private java.sql.Date accSecessionDatetime; //계정탈퇴일시 private String accSecessionYn; //계정탈퇴여부 private List<MemberRoleDTO> memberRoleList; //회원별권한리스트 public UserImpl(int no, String username, String password, Collection<? extends GrantedAuthority> authorities) { super(username, password, authorities); } public void setDetails(MemberDTO member, int companyNo) { this.no = member.getNo(); this.companyNo = companyNo; this.id = member.getId(); this.pwd = member.getPwd(); this.tempPwdYn = member.getTempPwdYn(); this.name = member.getName(); this.registDatetime = member.getRegistDatetime(); this.accSecessionDatetime = member.getAccSecessionDatetime(); this.accSecessionYn = member.getAccSecessionYn(); this.memberRoleList = member.getMemberRoleList(); } public int getNo() { return no; } public int getCompanyNo() { return companyNo; } public String getId() { return id; } public String getPwd() { return pwd; } public String getTempPwdYn() { return tempPwdYn; } public String getName() { return name; } public java.sql.Date getRegistDatetime() { return registDatetime; } public java.sql.Date getAccSecessionDatetime() { return accSecessionDatetime; } public String getAccSecessionYn() { return accSecessionYn; } public List<MemberRoleDTO> getMemberRoleList() { return memberRoleList; } }
package com.test.logn; import com.test.base.Node; import com.test.base.Solution; /** * .并归排序 - 递归实现 * * 1,最好情况时间复杂度 * n*log(n) * * 2,最坏情况时间复杂度 * n*log(n) * * 3,平均情况时间复杂度 * n*log(n) * * 4,空间复杂度 * O(n) * * 5,稳定性 * .稳定 * * @author YLine * * 2019年2月20日 上午10:26:05 */ public class SolutionMergeB implements Solution { @Override public void sort(Node[] array) { // 在排序前,先建好一个长度等于原数组长度的临时数组,避免递归中频繁开辟空间 Node[] temp = new Node[array.length]; sort(array, 0, array.length - 1, temp); } private static void sort(Node[] array, int left, int right, Node[] temp) { if (left < right) { int mid = (left + right) / 2; sort(array, left, mid, temp);//左边归并排序,使得左子序列有序 sort(array, mid + 1, right, temp);//右边归并排序,使得右子序列有序 merge(array, left, mid, right, temp);//将两个有序子数组合并操作 } } private static void merge(Node[] arr, int left, int mid, int right, Node[] temp) { int i = left;//左序列指针 int j = mid + 1;//右序列指针 int t = 0;//临时数组指针 while (i <= mid && j <= right) { if (arr[i].value <= arr[j].value) { temp[t++] = arr[i++]; } else { temp[t++] = arr[j++]; } } //将左边剩余元素填充进temp中 while (i <= mid) { temp[t++] = arr[i++]; } //将右序列剩余元素填充进temp中 while (j <= right) { temp[t++] = arr[j++]; } t = 0; //将temp中的元素全部拷贝到原数组中 while (left <= right) { arr[left++] = temp[t++]; } } }
package com.example.demo.rpc; public interface Tinterface { String send(String msg); }
package com.chompchompfig.rockpaperscissors.infrastructure.rest; import com.chompchompfig.rockpaperscissors.domain.moves.ClassicMoves; import com.chompchompfig.rockpaperscissors.infrastructure.movestrategy.RemoteNextMoveResource; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.web.util.UriTemplate; import static org.junit.Assert.assertNotNull; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @WebMvcTest(RockPaperScissorsMoveStrategyController.class) @ContextConfiguration(classes=RestContextConfiguration.class) public class RockPaperScissorsMoveStrategyControllerTests { public static final String RANDOM_STRATEGY_RESOURCE_NAME = "random"; public static final String JSONPATH_RESPONSE_MOVE_PROPERTY_PATTERN = "$.move"; @Autowired private MockMvc mockMvc; @Test public void givenValidConfigurationWhenApiMoveStrategyRandomNextMoveThenReturn200kAndRandomMove() throws Exception{ UriTemplate template = new UriTemplate(RockPaperScissorsMoveStrategyController.API_MOVE_STRATEGY_NEXT_MOVE_URI); MvcResult result = this.mockMvc.perform(MockMvcRequestBuilders.get(template.expand(RANDOM_STRATEGY_RESOURCE_NAME))) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath(JSONPATH_RESPONSE_MOVE_PROPERTY_PATTERN).hasJsonPath()) .andExpect(jsonPath(JSONPATH_RESPONSE_MOVE_PROPERTY_PATTERN).isString()).andReturn(); assertResponseIsClassicMove(result.getResponse().getContentAsString()); } private void assertResponseIsClassicMove(String jsonResponse) throws java.io.IOException { ObjectMapper objectMapper = new ObjectMapper(); RemoteNextMoveResource response = objectMapper.readValue(jsonResponse, RemoteNextMoveResource.class); assertNotNull(ClassicMoves.from(response.getMove())); } }
package dfs_ch05; import java.util.*; public class Ch05_pb1 { public static void main(String[] args) { Scanner scn = new Scanner(System.in); System.out.println("행(N)과 열(M)의 수를 각각 입력하세요. "); int row = scn.nextInt(); int col = scn.nextInt(); int [][] arr = new int [row][col]; System.out.println("얼음틀을 입력하세요."); int row1 = scn.nextInt(); int row2 = scn.nextInt(); int row3 = scn.nextInt(); int row4 = scn.nextInt(); for(int i=0; i<arr.length; i++) { for(int j=0; j<arr[i].length; j++) { if(arr[i][j]==0) { //arr[i][j+1] } } } } }
package com.example.startup; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import com.example.startup.FragmentStudent.Assingments; import com.example.startup.FragmentStudent.Attendance; import com.example.startup.FragmentStudent.Fees; import com.example.startup.FragmentStudent.Home; import com.example.startup.FragmentStudent.Profile; import com.example.startup.FragmentStudent.Query; import com.example.startup.FragmentStudent.TimeTable; import com.example.startup.FragmentTeacher.ClassRoutine; import com.example.startup.FragmentTeacher.GiveAssignments; import com.example.startup.FragmentTeacher.StudentAttendance; import com.example.startup.FragmentTeacher.StudentQueries; import com.example.startup.FragmentTeacher.TeacherHome; import com.example.startup.FragmentTeacher.TeacherProfile; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import android.view.LayoutInflater; import android.view.View; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.core.view.GravityCompat; import androidx.appcompat.app.ActionBarDrawerToggle; import android.view.MenuItem; import com.google.android.material.navigation.NavigationView; import androidx.drawerlayout.widget.DrawerLayout; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import android.view.Menu; import android.widget.ImageButton; import android.widget.Toast; public class TeacherMainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private ImageButton notification; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_teacher_main); notification = findViewById(R.id.notification_click_teacher); notification.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(TeacherMainActivity.this); LayoutInflater layoutInflater = getLayoutInflater(); View dialoglayout = layoutInflater.inflate(R.layout.notification_activity, null); builder.setView(dialoglayout); builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(TeacherMainActivity.this, "", Toast.LENGTH_SHORT).show(); } }); builder.show(); } }); Toolbar toolbar = findViewById(R.id.toolbar_teacher); setSupportActionBar(toolbar); FloatingActionButton floatingActionButton = findViewById(R.id.fab_teacher); floatingActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); DrawerLayout drawer = findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = findViewById(R.id.nav_view_teacher); navigationView.setNavigationItemSelectedListener(this); navigationView.setItemIconTintList(null); displaySelectedScreen(R.id.nav_home); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { /* getMenuInflater().inflate(R.menu.main_menu, menu); MenuItem item1 = menu.findItem(R.id.actionbar_item); MenuItemCompat.setActionView(item1, R.layout.notification_update_count_layout); notificationCount1 = (RelativeLayout) MenuItemCompat.getActionView(item1); */ return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { /* if (item.getItemId() == R.id.actionbar_item) { AlertDialog.Builder builder = new AlertDialog.Builder(StudentMainActivity.this); LayoutInflater layoutInflater = getLayoutInflater(); View dialoglayout = layoutInflater.inflate(R.layout.notification_activity, null); builder.setView(dialoglayout); builder.show(); } */ return super.onOptionsItemSelected(item); } private void displaySelectedScreen(int itemId) { Fragment fragment = null; switch (itemId) { case R.id.nav_home: fragment = new TeacherHome(); break; case R.id.nav_class_routine: fragment = new ClassRoutine(); break; case R.id.nav_attendance: fragment = new StudentAttendance(); break; case R.id.nav_profile: fragment = new TeacherProfile(); break; case R.id.nav_query: fragment = new StudentQueries(); break; case R.id.nav_assignments: fragment = new GiveAssignments(); break; case R.id.nav_logout: //Intent a = new Intent(TeacherMainActivity.this,Login.class); //Toast.makeText(this, "Logout Successfully", Toast.LENGTH_SHORT).show(); //startActivity(a); SharedPreferences sp=getSharedPreferences("login",MODE_PRIVATE); SharedPreferences.Editor e=sp.edit(); e.clear(); e.apply(); startActivity(new Intent(TeacherMainActivity.this,Login.class)); finish(); //finish current activity break; } if (fragment != null) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content_frame_teacher, fragment); ft.commit(); } DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); } @Override public boolean onNavigationItemSelected(MenuItem item) { displaySelectedScreen(item.getItemId()); return true; } }
package cn.machine.secondarysort; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.Function; import org.apache.spark.api.java.function.PairFunction; import scala.Tuple2; import java.util.*; /** * Created by zhao on 2017-12-17. */ public class SecondarySort2 { public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Usage: secondarySort <file>"); } String inputPath = args[0]; String outputPath = args[1]; System.out.println("args[0] <file> = " + inputPath); SparkConf conf = new SparkConf().setAppName("Secondary Sort"); final JavaSparkContext ctx = new JavaSparkContext(conf); JavaRDD<String> lines = ctx.textFile(inputPath,1); // <name>,<time>,<value> JavaPairRDD<String, Tuple2<Integer, Integer>> pairs = lines.mapToPair( new PairFunction<String, String, Tuple2<Integer, Integer>>() { public Tuple2<String, Tuple2<Integer, Integer>> call(String s) throws Exception { String[] tokens = s.split(","); // System.out.println(tokens[0] + "," + tokens[1] + "," + tokens[2]); Integer time = new Integer(tokens[1]); Integer value = new Integer(tokens[2]); Tuple2<Integer, Integer> timeValue = new Tuple2<Integer, Integer>(time, value); return new Tuple2<String, Tuple2<Integer, Integer>>(tokens[0],timeValue); } } ); JavaPairRDD<String, Iterable<Tuple2<Integer, Integer>>> groups = pairs.groupByKey(); JavaPairRDD<String, Iterable<Tuple2<Integer, Integer>>> sorted = groups.mapValues(new Function<Iterable<Tuple2<Integer, Integer>>, Iterable<Tuple2<Integer, Integer>>>() { public Iterable<Tuple2<Integer, Integer>> call(Iterable<Tuple2<Integer, Integer>> tuple2s) throws Exception { List<Tuple2<Integer, Integer>> newList = new ArrayList<Tuple2<Integer, Integer>>((Collection<? extends Tuple2<Integer, Integer>>) tuple2s); Collections.sort(newList, new Comparator<Tuple2<Integer, Integer>>() { public int compare(Tuple2<Integer, Integer> o1, Tuple2<Integer, Integer> o2) { return o1._1().compareTo(o2._1()); } }); return newList; } }); // sorted.saveAsTextFile(outputPath); System.out.println("========debug========="); List<Tuple2<String, Iterable<Tuple2<Integer, Integer>>>> output = sorted.collect(); for (Tuple2<String, Iterable<Tuple2<Integer, Integer>>> t : output){ Iterable<Tuple2<Integer, Integer>> list = t._2(); System.out.println(t._1()); for (Tuple2<Integer, Integer> tp : list){ System.out.println(tp._1() + ", " + tp._2()); } System.out.println("==================="); } } }
package people; public class People { //属性(成员变量) 有什么 private double height; //身高 public double getHeight(){ return height; } public void setHeight(double newHeight){ height = newHeight; } private int age; //年龄 public int getAge() { return age; } public void setAge(int age) { this.age = age; } int sex; //性别,0为男性,非0为女性 // 构造方法 public People(){} //构造函数,初始化了所有属性 public People(double h, int a, int s){ height = h; age = a; sex = s; } //方法 干什么 void cry(){ System.out.println("我在哭!"); } protected void laugh(){ System.out.println("我在笑!"); } void printBaseMes(){ System.out.println("我的身高是"+height+"cm"); System.out.println("我的年龄是"+age+"岁"); if(this.sex==0) System.out.println("我是男性!"); else System.out.println("我是女性!"); } // 内部类 private String name = "Sam"; /*外部类的静态变量。 Java 中被 static 修饰的成员称为静态成员或类成员。它属于整个类所有,而不是某个对象所有, 即被类的所有对象所共享。静态成员可以使用类名直接访问,也可以使用对象名进行访问。 */ static String ID = "510xxx199X0724XXXX"; public class Student0 { String ID = "20151234"; //内部类的成员属性 //内部类的方法 public void stuInfo(){ System.out.println("访问外部类中的name:" + name); System.out.println("访问外部类中的ID:" + People.ID); System.out.println("访问内部类中的ID:" + ID); } } // static 修饰的内部类,可直接实例化 public static class Student { String ID = "20151234"; //内部类的成员属性 //内部类的方法 public void stuInfo(){ System.out.println("访问外部类中的name:" + (new People().name)); System.out.println("访问外部类中的ID:" + People.ID); System.out.println("访问内部类中的ID:" + ID); } } //定义在外部类中的方法内: public void peopleInfo() { final String sex = "man"; //外部类方法中的常量 class Student { String ID = "20151234"; //内部类中的常量 public void print() { System.out.println("访问外部类的方法中的常量sex:" + sex); System.out.println("访问内部类中的变量ID:" + ID); } } Student a = new Student(); //创建方法内部类的对象 a.print();//调用内部类的方法 } //定义在外部类中的作用域内 public void peopleInfo2(boolean b) { if(b){ final String sex = "man"; //外部类方法中的常量 class Student { String ID = "20151234"; //内部类中的常量 public void print() { System.out.println("访问外部类的方法中的常量sex:" + sex); System.out.println("访问内部类中的变量ID:" + ID); } } Student a = new Student(); //创建方法内部类的对象 a.print();//调用内部类的方法 } } //测试成员内部类 public static void main(String[] args) { People a = new People(); //创建外部类对象,对象名为a Student0 b = a.new Student0(); //使用外部类对象创建内部类对象,对象名为b // 或者为 People.Student b = a.new Student(); b.stuInfo(); //调用内部对象的suInfo方法 Student d = new Student(); //直接创建内部类对象,对象名为b d.stuInfo(); //调用内部对象的suInfo方法 People e = new People(); //创建外部类的对象 System.out.println("定义在方法内:==========="); e.peopleInfo(); //调用外部类的方法 System.out.println("定义在作用域内:==========="); e.peopleInfo2(true); } }
package morpion; public class BigMorpion { Morpion[] total; char gagnant; static final int nbMorpion = 9; public BigMorpion() { this.total = new Morpion[nbMorpion]; for (int i = 0; i < nbMorpion; i++) { total[i] = new Morpion(); } } public boolean isFini() { Morpion[] t = this.getTotal(); if (t[0].isFini() && t[0].getGagnant() == t[1].getGagnant() && t[2].getGagnant() == t[0].getGagnant()) { // horinzontale haut gagnant = t[0].getGagnant(); return true; } else if (t[0].isFini() && t[3].isFini() && t[6].isFini() && t[0].getGagnant() == t[3].getGagnant() && t[6].getGagnant() == t[0].getGagnant()) { // verticale gauche gagnant = t[0].getGagnant(); return true; } else if (t[1].isFini() && t[4].isFini() && t[7].isFini() && t[1].getGagnant() == t[4].getGagnant() && t[7].getGagnant() == t[1].getGagnant()) { // verticale milieu gagnant = t[1].getGagnant(); return true; } else if (t[2].isFini() && t[5].isFini() && t[8].isFini() && t[2].getGagnant() == t[5].getGagnant() && t[8].getGagnant() == t[2].getGagnant()) { // verticale droite gagnant = t[2].getGagnant(); return true; } else if (t[3].isFini() && t[4].isFini() && t[5].isFini() && t[3].getGagnant() == t[4].getGagnant() && t[5].getGagnant() == t[3].getGagnant()) { // horizon milieu gagnant = t[3].getGagnant(); return true; } else if (t[6].isFini() && t[7].isFini() && t[8].isFini() && t[6].getGagnant() == t[7].getGagnant() && t[8].getGagnant() == t[6].getGagnant()) { // horizon bas gagnant = t[6].getGagnant(); return true; } else if (t[0].isFini() && t[4].isFini() && t[8].isFini() && t[0].getGagnant() == t[4].getGagnant() && t[8].getGagnant() == t[0].getGagnant()) { // diago haut bas gagnant = t[0].getGagnant(); return true; } else if (t[2].isFini() && t[4].isFini() && t[6].isFini() && t[2].getGagnant() == t[4].getGagnant() && t[6].getGagnant() == t[2].getGagnant()) { // diago bas haut gagnant = t[2].getGagnant(); return true; } else if (isRempli()) { gagnant = 'N'; return true; } else return false; } public boolean isRempli() { Morpion[] t = this.getTotal(); for (int i = 0; i < nbMorpion; i++) { if (!t[i].isRempli()) { return false; } } return true; } public Morpion[] getTotal() { return total; } public void setTotal(Morpion[] total) { this.total = total; } public static int getNbmorpion() { return nbMorpion; } public char getWinner() { return gagnant; } public String afficherLigne(int big, int small) { String s = ""; Morpion[] t = this.getTotal(); if (small == 0) { s += "[ " + t[big].getChar(0) + "|" + t[big].getChar(1) + "|" + t[big].getChar(2) + " ][ " + t[big + 1].getChar(0) + "|" + t[big + 1].getChar(1) + "|" + t[big + 1].getChar(2) + " ][ " + t[big + 2].getChar(0) + "|" + t[big + 2].getChar(1) + "|" + t[big + 2].getChar(2) + " ]" + "\n[ --+-+-- ][ --+-+-- ][ --+-+-- ]"; } else if (small == 1) { s += "[ " + t[big].getChar(3) + "|" + t[big].getChar(4) + "|" + t[big].getChar(5) + " ][ " + t[big + 1].getChar(3) + "|" + t[big + 1].getChar(4) + "|" + t[big + 1].getChar(5) + " ][ " + t[big + 2].getChar(3) + "|" + t[big + 2].getChar(4) + "|" + t[big + 2].getChar(5) + " ]" + "\n[ --+-+-- ][ --+-+-- ][ --+-+-- ]"; } else if (small == 2) { s += "[ " + t[big].getChar(6) + "|" + t[big].getChar(7) + "|" + t[big].getChar(8) + " ][ " + t[big + 1].getChar(6) + "|" + t[big + 1].getChar(7) + "|" + t[big + 1].getChar(8) + " ][ " + t[big + 2].getChar(6) + "|" + t[big + 2].getChar(7) + "|" + t[big + 2].getChar(8) + " ]"; } return s; } public String toString() { String s = ""; for (int i = 0; i < 9; i = i+3) { s += "#====="+(i+1)+"========="+(i+2)+"=========="+(i+3)+"======#\n"; s += "[ ]\n"; for (int j = 0; j < 3; j++) { s += afficherLigne(i, j) + "\n"; } s += "[ ]\n"; } s += "#=================================#\n"; return s; } }
package net.maizegenetics.analysis.popgen; import net.maizegenetics.util.TableReport; import net.maizegenetics.util.AbstractTableReport; import java.io.Serializable; import java.util.Vector; import net.maizegenetics.dna.snp.GenotypeTable; /** *This class provides the distribution of polymorphisms * * @author Ed Buckler * @version 1.0 */ public class PolymorphismDistribution extends AbstractTableReport implements TableReport, Serializable { Vector polyDistResultsVector = new Vector(); int maxSeqCount = -1; public PolymorphismDistribution() { } //consider whether to output pooled minority alleles or everything public void addDistribution(String label, GenotypeTable theSP, boolean poolMinor) { maxSeqCount = theSP.numberOfTaxa() * 2; int[] pdist = new int[maxSeqCount]; for (int i = 0; i < theSP.numberOfSites(); i++) { if (theSP.isPolymorphic(i)) { int[][] alleleCounts = theSP.allelesSortedByFrequency(i); int numAlleles = alleleCounts[0].length; if ((poolMinor == false) || (numAlleles == 2)) { pdist[alleleCounts[1][1]]++; } else { int sum = 0; for (int a = 1; a < numAlleles; a++) { sum += alleleCounts[1][a]; } pdist[sum]++; } } else { pdist[0]++; } } PolymorphismDistributionResults pdr = new PolymorphismDistributionResults(label, pdist, poolMinor); polyDistResultsVector.add(pdr); } //Implementation of TableReport Interface public Object[] getTableColumnNames() { String[] basicLabels = new String[1 + polyDistResultsVector.size()]; basicLabels[0] = "Site_Freq"; PolymorphismDistributionResults pdr; for (int i = 0; i < polyDistResultsVector.size(); i++) { pdr = (PolymorphismDistributionResults) polyDistResultsVector.get(i); basicLabels[i + 1] = pdr.label; } return basicLabels; } public Object[][] getTableData() { Object[][] data; int basicCols = 1, labelOffset; PolymorphismDistributionResults pdr; data = new String[maxSeqCount + 1][basicCols + polyDistResultsVector.size()]; data[0][0] = "N"; //label along side for frequency for (int i = 0; i < maxSeqCount; i++) { data[i + 1][0] = "" + i; } for (int i = 0; i < polyDistResultsVector.size(); i++) { pdr = (PolymorphismDistributionResults) polyDistResultsVector.get(i); //label of taxa sample across the top data[0][i + 1] = "" + pdr.polyDist.length; for (int j = 0; j < pdr.polyDist.length; j++) { data[j + 1][i + 1] = "" + pdr.polyDist[j]; } } return data; } /** * Returns specified row. * * @param row row number * * @return row */ public Object[] getRow(int row) { throw new UnsupportedOperationException(); } public String getTableTitle() { return "Polymorphism Distribution"; } public String toString() { if (polyDistResultsVector.size() == 0) { return "Needs to be run"; } StringBuffer cs = new StringBuffer(); Object[] header = this.getTableColumnNames(); for (int i = 0; i < header.length; i++) { cs.append(header[i]); } cs.append("\n"); Object[][] data = this.getTableData(); for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) {//System.out.println("i="+i+" j="+j+" data="+(String)data[i][j]); cs.append(data[i][j]); } cs.append("\n"); } return cs.toString(); } public int getRowCount() { return maxSeqCount + 1; } public int getElementCount() { throw new UnsupportedOperationException(); } public int getColumnCount() { throw new UnsupportedOperationException(); } } class PolymorphismDistributionResults implements Serializable { protected int[] polyDist; protected String label; protected boolean poolMinor; private int index; public PolymorphismDistributionResults(String label, int[] dist, boolean poolMinor) { this.label = label; this.poolMinor = poolMinor; this.polyDist = dist; } public boolean equals(Object anObject) { PolymorphismDistributionResults x = (PolymorphismDistributionResults) anObject; if (x.index == this.index) { return true; } else { return false; } } public void setIndex(int theIndex) { this.index = theIndex; } public String toString() { String result = "Polymorphism Distribution for " + label + "\n"; result += "Pool Minor =" + poolMinor + "\n"; result += "Dist =" + polyDist.toString() + "\n"; return result; } }
package org.abrahamalarcon.datastream.util; public enum ErrorCode { GENERAL_ERROR(1000), ; long error; private ErrorCode(long error) { this.error = error; } public long getError() { return error; } public String toString() { return String.valueOf(error); } }
package String; public class ReverseString { public static String reverseString(String s) { if(s == null || s.length() ==0) return s; int left = 0; int right = s.length()-1; char[] str = s.toCharArray(); while(left < right) { char temp = str[left]; str[left] = str[right]; left++; str[right] = temp; right--; } return new String(str); } }
import java.awt.*; /** * Created with IntelliJ IDEA. * User: dogeyes * Date: 13-1-14 * Time: 上午10:17 * To change this template use File | Settings | File Templates. */ public class MyParticle { private double rx, ry; private double vx, vy; private double s; private double mass; private Color color; private int count; public MyParticle() { rx = StdRandom.random(); ry = StdRandom.random(); vx = (StdRandom.random() - 0.5) * 0.01; vy = (StdRandom.random() - 0.5) * 0.01; s = StdRandom.random() * 0.01; mass = StdRandom.random() * 0.1; color = Color.BLACK; } public MyParticle( double rx, double ry, double vx, double vy, double s, double mass, Color color ) { this.rx = rx; this.ry = ry; this.vx = vx; this.vy = vy; this.s = s; this.mass = mass; count = 0; this.color = color; } public void draw() { Color color1 = StdDraw.getPenColor(); StdDraw.setPenColor(color); StdDraw.filledCircle(rx, ry, s); StdDraw.setPenColor(color1); } public void move(double dt) { rx += vx * dt; ry += vy * dt; } public int count() { return count; } public double timeToHit(MyParticle b) { } public double timeToHitHorizontalWall() { } public double timetoHitVerticalWall() { } public void bounceOff(Particle b) { } public void bounceHorizontalWall() { vx = -vx; count++; } public void bounceVerticalWall() { vy = -vy; count++; } }
/* * 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 ifpb.dac.queue; import javax.annotation.Resource; import javax.ejb.LocalBean; import javax.ejb.Stateful; import javax.ejb.Stateless; import javax.inject.Inject; import javax.jms.JMSConnectionFactory; import javax.jms.JMSConsumer; import javax.jms.JMSContext; import javax.jms.JMSException; import javax.jms.Queue; /** * * @author Sergio Diniz */ @Stateless @LocalBean public class Consumidor { @Inject @JMSConnectionFactory("java:global/jms/demoConnectionFactory") private JMSContext context; @Resource(lookup = "java:global/jms/demoQueue") Queue canalDeComunicacao; public String recebeMessagem() throws JMSException { JMSConsumer consumer = context.createConsumer(canalDeComunicacao); String msg = consumer.receiveBody(String.class, 1000); // System.out.println("Message do Navegador: " + msg); String retorno = ""; if (msg != null) { if (msg.equals("1")) { retorno = ""; }else{ retorno = "Erro ao efetuar login"; } } return retorno; } }
package ru.carFactory.Details; public class Body implements Detail { private final int ID; private static int amount = 0; public Body() { ID = amount++; } @Override public int getID() { return ID; } }
package com.pack.dao; import com.pack.entity.Admin; import com.pack.entity.BatchAllocation; import com.pack.entity.Login; public interface AdminDao { public String loginAdmin(Login login); public void addBatch(BatchAllocation batchAllocation); public void addAdmin(Admin admin); }
package logic.bonus; import controller.Game; import logic.gameelements.bumper.Bumper; import logic.table.ConcreteTable; import logic.table.Table; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class DropTargetBonusTest { private Game game; private Table tab1; @Before public void setUp() throws Exception { game = new Game(); tab1 = new ConcreteTable(8008, "tab1", 10, 0.5, 0, 0); game.setTable(tab1); } @Test public void trigger() { assertEquals(0, game.getCurrentScore()); game.getDropTargetBonus().trigger(game); assertEquals(1000000, game.getCurrentScore()); for (Bumper bumper : game.getCurrentTable().getBumpers()) { assertTrue(bumper.isUpgraded()); } } }
package com.GestiondesClub.services; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.GestiondesClub.dao.DemandeEventRepository; 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.DemandeEvenement; @Service public class DemEventServices { @Autowired private DemandeEventRepository demandeEv; public List<DemEventDto> GetAllDemande() { return demandeEv.findDemEventBy(); } public Optional<DemandeEvenement> getDemandeEvent(Long id) { return demandeEv.findById(id); } public DemandeEvenement createDemandeEvent(DemandeEvenement demande) { return demandeEv.save(demande); } public DemandeEvenement updateDemandeEvent(DemandeEvenement demande) { return demandeEv.save(demande); } public List<NotifOnly> getNonConfirmed() { return demandeEv.findByConfirmerEventFalse(); } public List<DemEventDto> getAllByclub(Club c) { return demandeEv.findByLeClub(c); } public List<LesSalleAReserve> getDemSalle() { return demandeEv.findByAccepterEventTrue(); } public List<LesMatARes> getDemMat() { return demandeEv.findByMaterielDemander(); } }
package com.eurekacachet.clocling.data.remote; import com.eurekacachet.clocling.data.local.PreferencesHelper; import com.eurekacachet.clocling.data.model.AuthResponse; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.util.Map; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; import rx.Observable; public interface ClockingService { String ENDPOINT = "http://localhost/api/"; @FormUrlEncoded @POST("login") Observable<AuthResponse> login(@FieldMap Map<String, String> credentials); class Creator{ public static ClockingService newClockingService(final PreferencesHelper preferencesHelper){ Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .create(); Interceptor mInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("Authorization: Bearer ", preferencesHelper.apiToken()) .build(); return chain.proceed(request); } }; OkHttpClient client = new OkHttpClient(); client.interceptors().add(mInterceptor); Retrofit retrofit = new Retrofit.Builder() .baseUrl(ClockingService.ENDPOINT) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(client) .build(); return retrofit.create(ClockingService.class); } } }
package com.gaoshin.points.server.resource; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import org.apache.log4j.Logger; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.gaoshin.points.server.bean.Cashier; import com.gaoshin.points.server.bean.ExchangeHistory; import com.gaoshin.points.server.bean.Item; import com.gaoshin.points.server.bean.ItemList; import com.gaoshin.points.server.bean.User; import com.gaoshin.points.server.entity.UserType; import com.gaoshin.points.server.service.MerchantService; import com.sun.jersey.spi.inject.Inject; import common.util.web.BusinessException; import common.util.web.GenericResponse; import common.util.web.JerseyBaseResource; import common.util.web.ServiceError; @Path("/merchant") @Component @Scope("request") @Produces({ "text/html;charset=utf-8", "text/xml;charset=utf-8", "application/json" }) public class MerchantResource extends JerseyBaseResource { private static final Logger logger = Logger.getLogger(MerchantResource.class.getName()); @Inject private MerchantService merchantService; @POST @Path("/set-as-merchant/{userId}") public GenericResponse setAsMerchant(@PathParam("userId") String userId) { UserResource userResource = getResource(UserResource.class); User me = userResource.me(); if(!UserType.Super.equals(me.getUserType())) { throw new BusinessException(ServiceError.PermissionDenied); } merchantService.setAsMerchant(userId); return new GenericResponse(); } @Path("/create-item") @POST public Item createItem(Item item) { String userId = assertRequesterUserId(); return merchantService.createItem(userId, item); } @Path("/add-cashier") @POST public Cashier addCashier(Cashier cashier) { String userId = assertRequesterUserId(); return merchantService.addCashier(userId, cashier); } @Path("/item/{itemId}") @GET public Item getItemById(@PathParam("itemId") String itemId) { return merchantService.getItemById(itemId); } @Path("/item/list/{merchantId}") @GET public ItemList list(@PathParam("merchantId") String merchantId) { return merchantService.listVarieties(merchantId); } @Path("/adjust-points") @POST public ExchangeHistory adjustPoints(ExchangeHistory trade) { String cashierId = assertRequesterUserId(); return merchantService.adjustPoints(cashierId, trade); } @Path("/adjust-points-by-phone/{phone}") @POST public ExchangeHistory adjustPoints(@PathParam("phone") String phone, ExchangeHistory trade) { String cashierId = assertRequesterUserId(); return merchantService.adjustPointsByPhone(cashierId, phone, trade); } }
package org.dbdoclet.test.sample; /** * The class <code>Hint</code> is a sample documentation class, which * tries to use as many features of the javadoc world as possible. * * @author <a href="mailto:mfuchs@unico-consulting.com">Michael Fuchs</a> * @version 1.0 */ public class Hint implements Thinkable { /** * The method <code>giveOne</code>. * * @dreamer Perhaps you have an <code>Idea</code> ({@link Idea}). * @return a <code>Hint</code> value */ public Hint giveOne() { return new Hint(); } /** * Nothing returns ! * * Hint:before {@inheritDoc} Hint:after * * @see "DocBook Doclet Tutorial" * @param what <code>String</code> */ public void think(String what) { } }
public class ArrQ1 { public boolean iscandles(int n) { if(n>=5) return true; else return false; } public static void main(String[] args) { ArrQ1 ob=new ArrQ1(); int arr[]= {2,3,5,1,3}; for(int i=0;i<arr.length;i++) { int sum=3; if(arr[i]== 5) System.out.print("True"); else { sum+=arr[i]; boolean rest=ob.iscandles(sum); if(rest==true) System.out.print(" True "); else System.out.print(" False "); } } } }
/** * @author DengYouming * @since 2016-7-29 下午9:52:59 */ package org.hpin.webservice.util; import org.apache.commons.lang.StringUtils; import java.io.*; import java.nio.charset.Charset; import java.util.List; import java.util.Properties; /** * @author DengYouming * @since 2016-7-29 下午9:52:59 */ public class PropertiesUtils { private static Properties prop; /** * @description 加载配置文件 * @author YoumingDeng * @since: 2016/12/21 3:23 */ public static Properties loadProp(String propName){ List<File> fileList = Tools.findFile(propName); File propFile = null; if(fileList!=null&&fileList.size()>0){ propFile = fileList.get(0); try { InputStream is = new FileInputStream(propFile); if(is!=null) { BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8")); prop = new Properties(); prop.load(br); if(br!=null){ br.close(); } is.close(); } } catch (IOException e) { e.printStackTrace(); } } return prop; } /** * @description 获取配置文件中相关key的String值 * @param propName 配置文件名称,可以不包含后缀 * @param key * @author YoumingDeng * @since: 2016/12/21 3:23 */ public static String getString(String propName, String key){ String value = null; if(StringUtils.isNotEmpty(propName)&& StringUtils.isNotEmpty(key)){ if(!propName.contains(".properties")){ propName = propName+".properties"; } if(prop!=null){ value = prop.getProperty(key); if(StringUtils.isEmpty(value)){ loadProp(propName); } }else{ loadProp(propName); } if(StringUtils.isEmpty(value)) { value = prop.getProperty(key); } } return value; } /** * @description 获取配置文件中的值,并转换成对应的Integer值 * @author YoumingDeng * @since: 2016/12/21 3:25 */ public static Integer getInt(String propName, String key){ Integer value = null; String tempStr = getString(propName, key); if(StringUtils.isNotEmpty(tempStr)){ value = Integer.valueOf(tempStr); } return value; } }
package edu.nyu.cs9053.homework4.hierarchy; import java.util.Objects; public class Gulf extends BodyOfWater { private final int gulfParameter; public Gulf(String name, double volume, int gulfParameter) { super(name, volume); this.gulfParameter = gulfParameter; } public int getGulfParameter() { return gulfParameter; } @Override public String getDescription() { return String.format("a gulf with parameter %d", gulfParameter); } @Override public boolean equals(Object otherObject) { if (this == otherObject) return true; if (otherObject == null) return false; if (getClass() != otherObject.getClass()) return false; Gulf other = (Gulf) otherObject; return gulfParameter == other.gulfParameter && getName().equals(other.getName()) && getVolume() == other.getVolume(); } @Override public int hashCode() { return 7 * Objects.hashCode(getName()) + 11 * Integer.hashCode(gulfParameter) + 13 * Double.hashCode(getVolume()); } }
package baseclass; import mysqlcon.sqlconnect; import java.sql.*; public class authorinfo { private String bookindex; private String authorname;//此处名称应与jsp表单名一致 private String age; private String wherefrom; public String getbookindex() { return bookindex; } public void setbookindex(String bookindex) { this.bookindex = bookindex; } public String getauthorname() { return authorname; } public void setauthorname(String authorname) { this.authorname = authorname; } public String getage() { return age; } public void setage(String age) { this.age = age; } public String getwherefrom() { return wherefrom; } public void sewherefrom(String wherefrom) { this.wherefrom = wherefrom; } public authorinfo(String bookindex,String authorname,String age,String wherefrom ) { super(); this.bookindex = bookindex; this.authorname = authorname; this.age = age; this.wherefrom = wherefrom; } }
package com.tech.interview.siply.redbus.repository.contract.users; import com.tech.interview.siply.redbus.entity.dao.users.Customer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; import java.util.UUID; @Repository public interface CustomerRepository extends JpaRepository<Customer, UUID> { Optional<Customer> findByUserName(String userName); }
package edu.upenn.cis455.frontend; import static spark.Spark.*; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.text.SimpleDateFormat; import java.util.List; import java.util.TimeZone; import edu.upenn.cis455.crawler.info.URLInfo; import edu.upenn.cis455.storage.ChannelInfo; import edu.upenn.cis455.storage.DBWrapper; import edu.upenn.cis455.storage.DocInfo; import edu.upenn.cis455.storage.UserInfo; class XPathApp { public static void main(String args[]) { if (args.length != 1) { System.err.println("You need to provide the path to the BerkeleyDB data store!"); System.exit(1); } // Initiate the DB DBWrapper myDB; try { myDB = DBWrapper.getInstance(args[0]); } catch (Exception e) { e.printStackTrace(); return; } port(8080); /* Displays a login form if the user is not logged in yet (i.e., the "username" attribute in the session has not been set yet), and welcomes the user otherwise */ get("/", (request, response) -> { String username = (String) (request.session().attribute("user")); String firstName = (String) (request.session().attribute("firstname")); String lastName = (String) (request.session().attribute("lastname")); if (username == null) { return "<html><body>Please enter your username and password: <form action=\"/login\" method=\"POST\"><label for=\"uname\">Username:</label><br><input type=\"text\" id=\"uname\" name=\"username\"/><br><label for=\"pwd\">Password:</label><br><input type=\"text\" id=\"pwd\" name=\"password\"/><br><input type=\"submit\" value=\"Log in\"/></form><p><a href=\"/newaccount\">Create a New Account</a></body></html>"; } else { String res = "<html><body>Welcome, " + firstName + " " + lastName + "!<br>Crawled urls:<br>"; List<String> channels = myDB.getURLs(); UserInfo info = myDB.getUserInfo(username); for (String channel : channels) { if (info.ifSubscribed(channel)) { res += "<a href=\"/show?name=" + channel + "\">" + channel + "</a>"; DocInfo docInfo = myDB.getDocInfo(channel); // if (docInfo.getAuthor().equals(username)) { // res += "&#9<a href=\"/delete?name=" + channel + "\">delete</a><br>"; // } else { // res += "<br>"; // } res += "<br>"; } else { res += channel + "&#9<a href=\"/subscribe?name=" + channel + "\">subscribe</a><br>"; } } res += "<br><form action=\"/create\" method=\"GET\"><label for=\"name\">New Channel Name:</label><br><input type=\"text\" id=\"name\" name=\"name\"/><br><label for=\"path\">XPath pattern:</label><br><input type=\"text\" id=\"path\" name=\"xpath\"/><br><input type=\"submit\" value=\"Create New Channel\"/></form></body></html>"; return res; } }); /* Displays a register form and post the form to /register when submitted */ get("/newaccount", (request, response) -> { return "<html><body>Please fill in the info: <form action=\"/register\" method=\"POST\"><label for=\"uname\">Username:</label><br><input type=\"text\" id=\"uname\" name=\"username\"/><br><label for=\"fname\">First name:</label><br><input type=\"text\" id=\"fname\" name=\"firstname\"/><br><label for=\"lname\">Last name:</label><br><input type=\"text\" id=\"lname\" name=\"lastname\"/><br><label for=\"pwd\">Password:</label><br><input type=\"text\" id=\"pwd\" name=\"password\"/><br><input type=\"submit\" value=\"Register\"/></form></body></html>"; }); /* Receives the data from the login form, logs the user in, and redirects the user back to /. */ post("/login", (request, response) -> { String username = request.queryParams("username"); String rawPwd = request.queryParams("password"); if (username != null && rawPwd != null) { UserInfo info = null; try { info = myDB.getUserInfo(username); } catch (Exception e) { e.printStackTrace(); } if (info == null) { // Account not exist, send an error message return "<html><body>Username is not registered!<p><a href=\"/\">Try again</a></body></html>"; } MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] encodedPwd = md.digest(rawPwd.getBytes(StandardCharsets.UTF_8)); if (!info.checkPwdEqual(encodedPwd)) { // Wrong password return "<html><body>Password is incorrect!<p><a href=\"/\">Try again</a></body></html>"; } // Success match request.session().attribute("user", username); request.session().attribute("firstname", info.getFirstName()); request.session().attribute("lastname", info.getLastName()); response.redirect("/"); return null; } else { // Send an error page return "<html><body>Empty username or password!<p><a href=\"/\">Try again</a></body></html>"; } }); /* Receives the data from the register form and write the data into the BDB. */ post("/register", (request, response) -> { String username = request.queryParams("username"); String rawPwd = request.queryParams("password"); String firstName = request.queryParams("firstname"); String lastName = request.queryParams("lastname"); if (username != null && rawPwd != null && firstName != null && lastName != null) { UserInfo info = null; try { info = myDB.getUserInfo(username); } catch (Exception e) { e.printStackTrace(); } if (info != null) { // Already exist, send an error message return "<html><body>Username already in use!<p><a href=\"/newaccount\">Try again</a></body></html>"; } MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] encodedPwd = md.digest(rawPwd.getBytes(StandardCharsets.UTF_8)); info = new UserInfo(firstName, lastName, encodedPwd); try { myDB.addUserInfo(username, info); } catch (Exception e) { e.printStackTrace(); } // If success request.session().attribute("user", username); request.session().attribute("firstname", firstName); request.session().attribute("lastname", lastName); response.redirect("/"); return null; } else { // Send an error page return "<html><body>Please fill in all information!<p><a href=\"/newaccount\">Try again</a></body></html>"; } }); /* Logs the user out by deleting the "username" attribute from the session. You could also invalidate the session here to get rid of the JSESSIONID cookie entirely. */ get("/logout", (request, response) -> { request.session().invalidate(); response.redirect("/"); return null; }); /* Look up a document in store*/ get("/lookup", (request, response) -> { String URL = request.queryParams("url"); if (URL == null) { // Send an error page return "<html><body>Please include an URL!</body></html>"; } // Decode and normalize try { URL = URLDecoder.decode(URL, StandardCharsets.UTF_8.name()); } catch (Exception e) { // Do nothing } URL = new URLInfo(URL).normalize(); DocInfo info = null; try { info = myDB.getDocInfo(URL); } catch (Exception e) { e.printStackTrace(); } if (info != null) { if (info.getMimeType() != null) { response.type(info.getMimeType()); } return info.getContent(); } else { // Send 404 response.status(404); return null; } }); /* Create a channel */ get("/create", (request, response) -> { String user = (String) request.session().attribute("user"); String name = request.queryParams("name"); String pattern = request.queryParams("xpath"); // Check for log in if (user == null) { response.status(401); return "<html><body>Please log in first!</body></html>"; } // Check for channel name/pattern if (name == null || pattern == null) { response.status(409); return "<html><body>Please provide the name and/or the xpath pattern!</body></html>"; } // Check if exists ChannelInfo info = null; try { info = myDB.getChannelInfo(name); } catch (Exception e) { e.printStackTrace(); } if (info != null) { // Already exist, send an error message response.status(409); return "<html><body>Channel already exists!</body></html>"; } info = new ChannelInfo(user, pattern); try { myDB.addChannelInfo(name, info); } catch (Exception e) { e.printStackTrace(); } // Success return "<html><body>You have created channel " + name + "!<p><a href=\"/\">Back to Home Page</a></body></html>"; }); /* Delete a channel */ get("/delete", (request, response) -> { String user = (String) request.session().attribute("user"); String name = request.queryParams("name"); // Check for log in if (user == null) { response.status(401); return "<html><body>Please log in first!</body></html>"; } // Check for channel name if (name == null) { response.status(409); return "<html><body>Please provide the channel name!</body></html>"; } // Check if exists ChannelInfo info = null; try { info = myDB.getChannelInfo(name); } catch (Exception e) { e.printStackTrace(); } if (info == null) { // Missing response.status(404); return "<html><body>Channel is not found!</body></html>"; } if (!info.getAuthor().equals(user)) { response.status(403); return "<html><body>You are not the creator of the channel!</body></html>"; } try { myDB.deleteChannelInfo(name); } catch (Exception e) { e.printStackTrace(); } // Success return "<html><body>You have deleted channel " + name + "!<p><a href=\"/\">Back to Home Page</a></body></html>"; }); /* Subscribe a channel */ get("/subscribe", (request, response) -> { String user = (String) request.session().attribute("user"); String name = request.queryParams("name"); // Check for log in if (user == null) { response.status(401); return "<html><body>Please log in first!</body></html>"; } // Check for channel name if (name == null) { response.status(409); return "<html><body>Please provide the channel name!</body></html>"; } // Check if already subscribed UserInfo userInfo = null; try { userInfo = myDB.getUserInfo(user); } catch (Exception e) { e.printStackTrace(); } if (userInfo == null) { // This would be weird since logged in response.status(500); return null; } if (userInfo.ifSubscribed(name)) { response.status(409); return "<html><body>You already subscribed!</body></html>"; } // Check if exists ChannelInfo info = null; try { info = myDB.getChannelInfo(name); } catch (Exception e) { e.printStackTrace(); } if (info == null) { // Missing response.status(404); return "<html><body>Channel is not found!</body></html>"; } // Success. Add to list, and store to db userInfo.subscribe(name); try { myDB.addUserInfo(user, userInfo); } catch (Exception e) { e.printStackTrace(); } return "<html><body>You have subscribed channel " + name + "!<p><a href=\"/\">Back to Home Page</a></body></html>"; }); /* Unsubscribe a channel */ get("/unsubscribe", (request, response) -> { String user = (String) request.session().attribute("user"); String name = request.queryParams("name"); // Check for log in if (user == null) { response.status(401); return "<html><body>Please log in first!</body></html>"; } // Check for channel name if (name == null) { response.status(409); return "<html><body>Please provide the channel name!</body></html>"; } // Check if subscribed UserInfo userInfo = null; try { userInfo = myDB.getUserInfo(user); } catch (Exception e) { e.printStackTrace(); } if (userInfo == null) { // This would be weird since logged in response.status(500); return null; } if (!userInfo.ifSubscribed(name)) { response.status(404); return "<html><body>You didn't subscribe this channel!</body></html>"; } // Success. Add to list, and store to db userInfo.unsubscribe(name); try { myDB.addUserInfo(user, userInfo); } catch (Exception e) { e.printStackTrace(); } return "<html><body>You have unsubscribed channel " + name + "!<p><a href=\"/\">Back to Home Page</a></body></html>"; }); /* Show a channel */ get("/show", (request, response) -> { String user = (String) request.session().attribute("user"); String name = request.queryParams("name"); // Check for log in if (user == null) { response.status(401); return "<html><body>Please log in first!</body></html>"; } // Check for channel name if (name == null) { response.status(409); return "<html><body>Please provide the channel name!</body></html>"; } // Check if already subscribed UserInfo userInfo = null; try { userInfo = myDB.getUserInfo(user); } catch (Exception e) { e.printStackTrace(); } if (userInfo == null) { // This would be weird since logged in response.status(500); return null; } if (!userInfo.ifSubscribed(name)) { response.status(409); return "<html><body>You didn't subscribe this channel!</body></html>"; } // Check if exists ChannelInfo info = null; try { info = myDB.getChannelInfo(name); } catch (Exception e) { e.printStackTrace(); } if (info == null) { // Missing response.status(404); return "<html><body>Channel is not found!</body></html>"; } // Success. Show the list String res = "<!DOCTYPE html><html><body><div class=\"channelheader\">"; res += "Channel name: " + name + ", created by: " + userInfo.getFirstName() + " " + userInfo.getLastName() + "</div>"; SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD'T'hh:mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); for (String docLink : info.getDocList()) { DocInfo docInfo = null; try { docInfo = myDB.getDocInfo(docLink); } catch (Exception e) { e.printStackTrace(); } if (docInfo != null) { res += "<br>Crawled on " + dateFormat.format(docInfo.getLastModified()); res += "<br>Location: " + docInfo.getNormalizedLink(); res += "<div class=”document”><xmp>" + docInfo.getContent().toString() + "</xmp></div>"; } } res += "</body></html>"; return res; }); } }
package cn.diffpi.resource.asthma.user.model; import cn.diffpi.kit.DateUtil; import cn.dreampie.orm.Model; import cn.dreampie.orm.annotation.Table; import cn.dreampie.security.DefaultPasswordService; /** * Created by one__l on 2015年10月11日 */ @Table(name = "asthma_user", cached = true) public class AsthmaUser extends Model<AsthmaUser> { public final static AsthmaUser dao = new AsthmaUser(); /*** * 获取用户信息 * * @return */ public AsthmaPerson getPerson() { AsthmaPerson person; if (this.get("pserson") == null && this.get("id") != null) { person = AsthmaPerson.dao.findFirstBy(" user = ?", this.get("id")); if(person != null){ person.remove("user", "id"); } else { person = new AsthmaPerson(); } this.put("person", person); } else { return this.get("person"); } return person; } /*** * 登陆 * * @param loginName * @param pwd * @param platform * @param deviceId * @return */ public AsthmaUser login(String loginName, String pwd, String platform, String deviceId) { if (loginName == null || pwd == null || platform == null || deviceId == null) { return null; } try { String sql = "select * from asthma_user t where t.phonenum = ? and t.del = '0'"; AsthmaUser user = dao.findFirst(sql, loginName.toLowerCase()); if (user != null) { if (user.get("pwd") != null && DefaultPasswordService.instance().match(pwd, user.<String>get("pwd")) ) { if (user.get("state") != null && user.get("state").equals("0")) {// 用户状态正常 if (user.get("online").equals("1")) {// 用户已经在线 } String time = DateUtil.getCurrentDate(DateUtil.DATE_MIN); new AsthmaUserLoginLog() .set("ruid", user.get("id")) .set("platform", Integer.valueOf(platform)) .set("device_id", deviceId) .set("time", time) .save(); if (user.get("type").equals("0")) { user.set("online", 1); } user.set("last_time", time).set("online", 1).update(); user.filter(); return user; } else { // return ReturnData.getErrJson(40008); } } } } catch (Exception e) { e.printStackTrace(); // return ReturnData.getErrJson(2); } return null; } /*** * 用户注册 */ public void register(String phone , String pwd){ if(phone == null || pwd == null){ //return ReturnData.getErrJson(3); } AsthmaUser user = new AsthmaUser() .set("phonenum", phone) .set("pwd", DefaultPasswordService.instance().crypto(pwd)) .set("state", 0) .set("isvali", 0) .set("type", 0) .set("del", 0) .set("online", 0) .set("create_time", DateUtil.getCurrentDate(DateUtil.DATE_MIN)); user.save(); user.filter(); } /*** * 验证手机号码 * * @param phonenum * @return */ public void valiPhonenumRepeat(String phonenum) { if (phonenum == null || phonenum.equals("")) { //return ReturnData.getErrJson(3); } String sql = "select * from jms_user t where t.phonenum = '" + phonenum + "' and t.del = '0'"; if(dao.findFirst(sql) != null){ //return ReturnData.getErrJson(40007); } //return ReturnData.getSuccessCode(); } public void filter(){ this.remove(new String[] { "pwd", "del" }); } }
package org.valar.project.contactsApplication.exception; public class UserBlockedException extends RuntimeException{ /* * Create User object with out error description */ public UserBlockedException() {} /* * Created user object with error description */ public UserBlockedException(String errDesc) {} }
package com.manit.krungsri.realmmeapplication.activity; import android.content.Intent; import android.databinding.DataBindingUtil; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Toast; import com.manit.krungsri.realmmeapplication.R; import com.manit.krungsri.realmmeapplication.databinding.ActivityMainBinding; import com.manit.krungsri.realmmeapplication.model.Person; import com.manit.krungsri.realmmeapplication.model.Student; import java.util.ArrayList; import io.realm.Realm; import io.realm.RealmResults; public class MainActivity extends AppCompatActivity { Realm realm; ActivityMainBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { binding = DataBindingUtil.setContentView(this, R.layout.activity_main); super.onCreate(savedInstanceState); initinstance(); realm = Realm.getDefaultInstance(); // opens "myrealm.realm" // SaveDataAsynchronous("Pang", 23); // selectPersonAll(); // SaveDataSynchronous(); binding.btnGenerate.setOnClickListener(buttonClick); // updateStudent(); queryRealmTest(); } private void initinstance() { binding.btnRecyclerView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "123", Toast.LENGTH_SHORT).show(); Intent i = new Intent(MainActivity.this, RecycleViewActivity.class); startActivity(i); } }); } private void queryRealmTest() { // Or alternatively do the same all at once (the "Fluent interface"): // RealmResults<Student> result2 = realm.where(Student.class) // .equalTo("studentName", "John") // .or() // .equalTo("studentName", "Peter") // .findAll(); Log.d("student", "------------"); RealmResults<Student> result22 = realm.where(Student.class) .equalTo("studentName", "Raj Koothrappali") .findAll(); result22 = result22.sort("studentName"); for(Student s : result22){ Log.d("student", s.getStudentName() ); } Log.d("student", "------------"); //size Log.d("student", String.valueOf(result22.size())); Log.d("student", "------------"); RealmResults<Student> result3 = realm.where(Student.class) .findAll(); realm.beginTransaction(); for (int i = 0; i<result3.size(); i++) { Log.d("student", String.valueOf(result3.get(i).getStudentName())); } realm.commitTransaction(); Student result4 = realm.where(Student.class) .findFirst(); Log.d("student", String.valueOf(result4)); } private void generateStudent() { // clearStudent(); insertStudent(); } public ArrayList<Student> getSampleStudentData(int size) { String name[] = {"Raj Koothrappali", "Penny Hofstadter", "Leonard Hopstater", "Sheldon cooper", "Howard Wolowitz"}; ArrayList<Student> listStudent = new ArrayList<>(); for (int i = 1; i <= size; i++) { Student student = new Student(); student.setStudentId(i); student.setStudentName(name[i % name.length]); student.setStudentScore((int) (Math.random() * 100)); listStudent.add(student); } return listStudent; } private void insertStudent() { final ArrayList<Student> listStudentGenerate = getSampleStudentData(10); realm.executeTransactionAsync( new Realm.Transaction() { @Override public void execute(Realm realm) { String text = ""; for (final Student s : listStudentGenerate) { Student student = realm.createObject(Student.class, s.getStudentId()); // student.setStudentId(s.getStudentId()); student.setStudentName(s.getStudentName()); student.setStudentScore(s.getStudentScore()); // Log.d("student", "Add student id = " + s.getStudentId()); text += s.toString(); } } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { Toast.makeText(getApplicationContext(), "Generate student complete.", Toast.LENGTH_SHORT).show(); showStudent(); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { error.printStackTrace(); Toast.makeText(getApplicationContext(), "error"+error.getMessage(), Toast.LENGTH_SHORT).show(); Log.d("student", error.getMessage()); } }); } private void showStudent() { RealmResults<Student> listStudent = getAllStudent(); Log.d("student", "SIZE = " + listStudent.size()); String str = ""; for (Student student : listStudent) { str += "\nID = " + student.getStudentId()+ " , " + student.getStudentName() + " , (" + student.getStudentScore() + ")"; } Log.d("student", str); } private void updateStudent(){ final Student student = new Student(); student.setStudentId(10); student.setStudentName("123456789"); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.copyToRealmOrUpdate(student); } }); } private void clearStudent() { realm.beginTransaction(); realm.delete(Student.class); realm.commitTransaction(); } private void insertStudentxxx() { // realm.beginTransaction(); // // Student student = realm.createObject(Student.class); // student.setStudentId(2); // student.setStudentName("manit"); // student.setStudentScore(99); // // realm.commitTransaction(); } private RealmResults<Student> getAllStudent() { RealmResults<Student> result = realm.where(Student.class).findAll(); return result; } private void SaveDataSynchronous() { realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { } }); } private void selectPersonAll() { // read from DB show in textView_log StringBuilder output = new StringBuilder(); RealmResults<Person> personRealmResults = realm.where(Person.class).findAll(); for (Person person : personRealmResults) { output.append(person.toString()); } Log.d("database", output.toString()); binding.tvHello.setText(output.toString()); } private void SaveDataAsynchronous(final String name, final int age) { // realmasyncTask realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm bgRealm) { Person person = bgRealm.createObject(Person.class); person.setName(name); person.setAge(age); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { // Transaction was a success. Log.d("database", ">>> stored ok<<<"); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { // Transaction failed and was automatically canceled. Log.d("database", error.getMessage()); } }); } View.OnClickListener buttonClick = new View.OnClickListener() { @Override public void onClick(View view) { switch (view.getId()) { case R.id.btnGenerate: Toast.makeText(MainActivity.this, "click", Toast.LENGTH_SHORT).show(); generateStudent(); break; case R.id.btnRecyclerView: break; default: Toast.makeText(MainActivity.this, "Main", Toast.LENGTH_SHORT).show(); break; } } }; @Override protected void onStop() { super.onStop(); realm.close(); } @Override protected void onDestroy() { super.onDestroy(); realm.close(); } }
package com.bofsoft.laio.laiovehiclegps.DataClass; import com.bofsoft.laio.data.BaseData; import java.util.List; /** * 获取公共数据表更新时间信息,如果比本地新,就进行更新操作 * * @author admin * */ public class TableUpdateListData<T> extends BaseData { private int ConfType; private String UpdateTime; private List<T> info; public int getConfType() { return ConfType; } public void setConfType(int confType) { ConfType = confType; } public String getUpdateTime() { return UpdateTime; } public void setUpdateTime(String updateTime) { UpdateTime = updateTime; } public List<T> getInfo() { return info; } public void setInfo(List<T> info) { this.info = info; } }
package PACKAGE_NAME;public class StringInstrument { }
package f.star.iota.milk.ui.www52guzhuang.guzhuang; import android.os.Bundle; import f.star.iota.milk.base.MoreScrollImageFragment; public class GuZhuangFragment extends MoreScrollImageFragment<GuZhuangPresenter, GuZhuangAdapter> { public static GuZhuangFragment newInstance(String url) { GuZhuangFragment fragment = new GuZhuangFragment(); Bundle bundle = new Bundle(); bundle.putString("base_url", url); bundle.putString("page_suffix", ".html"); fragment.setArguments(bundle); return fragment; } @Override protected GuZhuangPresenter getPresenter() { return new GuZhuangPresenter(this); } @Override protected GuZhuangAdapter getAdapter() { return new GuZhuangAdapter(); } }
package com.cloud.test; import android.os.Binder; import android.os.Parcel; import android.os.RemoteException; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; public class CallBackProxy extends Binder { public static final String descriptor = "com.cloud.test.callback"; public static final int test = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1); @Override protected boolean onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply, int flags) throws RemoteException { Log.d("TestAc", "onTransact:::"+code); switch (code) { case test: data.enforceInterface(descriptor); Log.d("TestAc", "onTransact:::???"); break; } return super.onTransact(code, data, reply, flags); } }
package com.Ajinkya.wa_text.fragments; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.Ajinkya.wa_text.Activities.MainActivity; import com.Ajinkya.wa_text.Adapters.Category_Adapter; import com.Ajinkya.wa_text.Models.Category; import com.Ajinkya.wa_text.R; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList; import java.util.List; /** * A simple {@link Fragment} subclass. */ public class CategoryFragment extends Fragment { private RecyclerView recyclerView; List<Category> list; private Category_Adapter adapter; public CategoryFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_category, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ((MainActivity)getActivity()).settitle("Category"); recyclerView=view.findViewById(R.id.category_recycler_view); list=new ArrayList<>(); adapter=new Category_Adapter(getActivity(),list); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new GridLayoutManager(getContext(),3)); recyclerView.setAdapter(adapter); FirebaseFirestore db=FirebaseFirestore.getInstance(); db.collection("Categories").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot queryDocumentSnapshots) { for (QueryDocumentSnapshot doc : queryDocumentSnapshots){ if (doc.exists()){ Category category=new Category(); category.setTitle(doc.getString("name")); category.setThumbnail(doc.getString("thumbnail")); list.add(category); } } adapter.notifyDataSetChanged(); } }); } }
package com.dudhe.narayan.strecive; import android.speech.tts.TextToSpeech; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Locale; public class MainActivity extends AppCompatActivity { TextToSpeech t1; TextView textView; ListView ls; FirebaseDatabase firebaseDatabase; DatabaseReference databaseReference; ArrayList<String> list; ArrayAdapter<String> adapter; busi bussend; private String uid,x; int y=1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ls=(ListView)findViewById(R.id.card_listView); textView=(TextView)findViewById(R.id.aura); bussend=new busi(); firebaseDatabase=FirebaseDatabase.getInstance(); databaseReference=firebaseDatabase.getReference().child("Bus"); list=new ArrayList<>(); adapter=new ArrayAdapter<String>(this,R.layout.list_bus,R.id.line1,list); databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { list.clear(); for (DataSnapshot ds : dataSnapshot.getChildren()) { bussend = ds.getValue(busi.class); String res = bussend.getbNo() + " " + bussend.getbFrom() + " " + bussend.getbTo(); list.add(res); String toSpeak = "Bus Number " + bussend.getbNo() + " From " + bussend.getbFrom() + " to " + bussend.getbTo() + " is arriving in five minutes."; t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } ls.setAdapter(adapter); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(MainActivity.this,"hello error",Toast.LENGTH_SHORT).show(); } }); t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if(status != TextToSpeech.ERROR) { t1.setLanguage(Locale.UK); } } }); } public void onPause(){ if(t1 !=null){ t1.stop(); t1.shutdown(); } super.onPause(); } }
package nesto.daggertaste; import android.net.ConnectivityManager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import javax.inject.Inject; import nesto.base.util.LogUtil; public class MainActivity extends AppCompatActivity { EditText editText; @Inject ConnectivityManager manager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = (EditText) findViewById(R.id.hello); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { LogUtil.d("afterTextChanged: " + s); editText.setError(s); } }); ((App) getApplication()).getComponent().inject(this); } }
package com.logicbig.example; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttribute; import java.time.Duration; import java.time.LocalDateTime; @Controller public class ExampleController { @RequestMapping("/") @ResponseBody public String handle (@SessionAttribute(name = "sessionStartTime") LocalDateTime startDateTime) { Duration d = Duration.between(startDateTime, LocalDateTime.now()); return String.format("First Visit time: %s<br/> Visiting site for:" + " %s seconds", startDateTime, d.getSeconds()); } }
package com.gaoshin.onsalelocal.slocal.service.impl; import java.math.BigDecimal; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.gaoshin.onsalelocal.api.Offer; import com.gaoshin.onsalelocal.api.OfferDetails; import com.gaoshin.onsalelocal.api.OfferDetailsList; import com.gaoshin.onsalelocal.api.Store; import com.gaoshin.onsalelocal.slocal.dao.SlocalDao; import com.gaoshin.onsalelocal.slocal.service.SlocalService; import common.db.dao.GeoDao; import common.geo.GeoService; import common.geo.Geocode; import common.geo.Location; import common.geo.google.GoogleGeoService; import common.util.reflection.ReflectionUtil; @Service("slocalService") @Transactional(readOnly=true) public class SlocalServiceImpl extends ServiceBaseImpl implements SlocalService { @Autowired private SlocalDao slocalDao; @Autowired private GeoDao geoDao; private GeoService geoService = new GoogleGeoService(); @Override @Transactional(readOnly=false, rollbackFor=Throwable.class) public void updateTasks() { slocalDao.updateTasks(); } @Override @Transactional(readOnly=false, rollbackFor=Throwable.class) public void seedCityTasks() { int cnt = slocalDao.getNumberOfCityTasks(); if(cnt == 0) { slocalDao.seedCityTasks(); } } @Override public OfferDetailsList searchOffer(final float lat, final float lng, int radius, int offset, int size) { OfferDetailsList list = new OfferDetailsList(); List<Offer> offers = slocalDao.listOffersIn(lat, lng, radius, offset, size); for(Offer o : offers) { OfferDetails details = ReflectionUtil.copy(OfferDetails.class, o); details.setRootSource("Shoplocal"); list.getItems().add(details); float dis1 = Geocode.distance(o.getLatitude(), o.getLongitude(), lat, lng); details.setDistance(dis1); } Collections.sort(list.getItems(), new Comparator<OfferDetails>() { @Override public int compare(OfferDetails o1, OfferDetails o2) { return (int) ((o1.getDistance() - o2.getDistance()) * 1000); } }); return list; } @Override @Transactional(readOnly=false, rollbackFor=Throwable.class) public void geo() { List<Store> stores = slocalDao.getNoGeoStores(); for(Store store : stores) { String location = store.getAddress() + ", " + store.getCity() + ", " + store.getState(); try { Location loc = geoService.geo(location); store.setLatitude(new BigDecimal(loc.getGeocode().getLatitude())); store.setLongitude(new BigDecimal(loc.getGeocode().getLongitude())); } catch (Exception e) { e.printStackTrace(); store.setLatitude(new BigDecimal(0)); store.setLongitude(new BigDecimal(0)); } slocalDao.updateEntity(store, "latitude", "longitude"); } } @Override public int getPendingCityCategoryTaskCount() { return slocalDao.getPendingCityCategoryTaskCount(); } @Override public void ondemand(String cityId) { slocalDao.ondemand(cityId); } }
package com.zc.cris.mybatis.bean; import java.util.List; // 模拟oracle 的分页查询,将其定义为一个存储过程 procedure public class Page { private int start; private int end; private int totalCount; private List<Employee> emps; public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getEnd() { return end; } public void setEnd(int end) { this.end = end; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public List<Employee> getEmps() { return emps; } public void setEmps(List<Employee> emps) { this.emps = emps; } }
/** * Sencha GXT 3.0.1 - Sencha for GWT * Copyright(c) 2007-2012, Sencha, Inc. * licensing@sencha.com * * http://www.sencha.com/products/gxt/license/ */ package com.sencha.gxt.explorer.client.window; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.sencha.gxt.explorer.client.model.Example.Detail; import com.sencha.gxt.widget.core.client.Window; import com.sencha.gxt.widget.core.client.button.TextButton; import com.sencha.gxt.widget.core.client.event.HideEvent; import com.sencha.gxt.widget.core.client.event.SelectEvent; import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler; @Detail(name = "Hello World (UiBinder)", icon = "helloworld", category = "Windows", files = "HelloWindowUiBinderExample.ui.xml") public class HelloWindowUiBinderExample implements IsWidget, EntryPoint { interface MyUiBinder extends UiBinder<Widget, HelloWindowUiBinderExample> { } private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); @UiField Window window; public Widget asWidget() { uiBinder.createAndBindUi(this); TextButton btn = new TextButton("Hello World"); btn.addSelectHandler(new SelectHandler() { @Override public void onSelect(SelectEvent event) { window.show(); } }); window.setData("open", btn); VerticalPanel vp = new VerticalPanel(); vp.setSpacing(10); vp.add(btn); return vp; } public void onModuleLoad() { RootPanel.get().add(asWidget()); } @UiHandler("window") public void onHide(HideEvent event) { TextButton open = window.getData("open"); open.focus(); } @UiHandler("closeButton") public void onCloseButtonClicked(SelectEvent event) { window.hide(); } }
package br.com.mixfiscal.prodspedxnfe.util; public class Masc { public static boolean isCPF(String numDoc) { return Masc.isCPFOrCNPJ(numDoc, ETipoDoc.CPF); } public static boolean isCNPJ(String numDoc) { return Masc.isCPFOrCNPJ(numDoc, ETipoDoc.CNPJ); } public static String mascararCNPJ(String numDoc) { if (!isCNPJ(numDoc)) throw new IllegalArgumentException(String.format("numDoc: '%s' não é um CNPJ válido", numDoc)); String[] partes = new String[5]; partes[0] = numDoc.substring(0, 2); partes[1] = numDoc.substring(2, 5); partes[2] = numDoc.substring(5, 8); partes[3] = numDoc.substring(8, 12); partes[4] = numDoc.substring(12, 14); return String.format("%s.%s.%s/%s-%s", partes[0], partes[1], partes[2], partes[3], partes[4]); } public static String mascararCPF(String numDoc) { if (!isCPF(numDoc)) throw new IllegalArgumentException(String.format("numDoc: '%s' não é um CPF válido", numDoc)); String[] partes = new String[4]; partes[0] = numDoc.substring(0, 3); partes[1] = numDoc.substring(3, 6); partes[2] = numDoc.substring(6, 9); partes[3] = numDoc.substring(9, 11); return String.format("%s.%s.%s-%s", partes[0], partes[1], partes[2], partes[3]); } private static boolean isCPFOrCNPJ(String numDoc, ETipoDoc tpDoc) { if (numDoc == null || numDoc.isEmpty()) return false; byte qtdChars = (byte)(tpDoc == ETipoDoc.CNPJ ? 14 : 11); return numDoc.replace(".", "").replace("/", "").replace("-", "").length() == qtdChars; } private enum ETipoDoc { CPF, CNPJ } }
package kim; public class commtandpush1 { }
package com.java9whatsnew.language_improvements; import static java.util.stream.Collectors.filtering; import static java.util.stream.Collectors.flatMapping; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toSet; import java.util.Map; import java.util.Set; public class StreamsNewMethods { public static void main(String[] args) { // new filtering method on Stream api Map<Set<String>, Set<Book>> booksByAuthors = Book.getDiferentBooks() .collect( groupingBy(Book::getAuthors, filtering( book -> book.getPrice() > 10.0, toSet()) ) ); System.out.println(booksByAuthors); // new flatMapping method on Stream api Map<Double, Set<String>> authorsSellingForPrice = Book.getDiferentBooks() .collect( groupingBy(Book::getPrice, flatMapping(book -> book.getAuthors().stream(), toSet() ) ) ); System.out.println(authorsSellingForPrice); } }
package modifer.innerClass; import com.sun.org.apache.bcel.internal.classfile.InnerClass; import modifer.Address; import modifer.User; /** * 简述: * <p> * 内部类不加static属性时,只能先创建了外部类再创建内部类 * 加static修饰时,通过外部类名就可以创建内部类对象 * 内部类是一个相对独立的概念 * * @author WangLipeng 1243027794@qq.com * @version 1.0 * @since 2020/1/8 10:07 */ public class OutClass extends User { static class InnerClass extends Address implements InterfaceDemo { @Override public void print() { System.out.println("inner class print"); } } private InnerClass /*InterfaceDemo*/ returnObj() { return new InnerClass(); } /* * 匿名内部类,在一个方法中创建一个类实现一个接口或者继承一个类 * 方法内部类 * */ public void noNameInnerClass() { //实现一个接口 ((InterfaceDemo) () -> { int a = 1; System.out.println("implement print"); }).print(); //继承一个类 new Address() { { System.out.println("noNameInnerClass print"); } }.pirnt(); } public static void main(String[] args) { OutClass outClass = new OutClass(); { //加static修饰内部类时的创建方法 // InnerClass innerClass = new OutClass.InnerClass(); //内部类为不加static的创建方式 对象.对象的方式才能创建 // InnerClass out = new OutClass().new InnerClass(); } //返回一个实体类,不看代码不知道是什么类型,实现了很好的隐藏 InnerClass /*InterfaceDemo*/ interfaceDemo = outClass.returnObj(); interfaceDemo.print(); //内部类继承一个类,外部类继承一个类,先实现了多继承,但是不能隐藏内部类细节了,返回内部类类型才能访问内部类中继承的属性 //父类的引用指向子类的对象,调用的都是子类重写之后的方法,不能调用子类对象的属性 String address = interfaceDemo.address; String ph = outClass.phone; //继承一个类和实现一个接口时,发现他们的方法相同了,实现接口方法时是实现了方法还是重写了方法,无法确认,通过内部类可以解决这个问题 System.out.println("-------"); outClass.noNameInnerClass(); } }
package com.ece.ing4.ppe.smartpillbox.smartpillbox; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import android.app.ActionBar.LayoutParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; public class TreatmentActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { // User id private static String user_id; private static String user_name; private static String medical_staff; private TextView mytextName; private static Spinner spinnerTreatment, spinnerMedicine; private String user, temps, dose, expiration, nom; // Progress Dialog private ProgressDialog pDialog; private EditText t; int text_number, number; private boolean onChange = false; private String myTest, myTest2 = "1", myTest3, myTest4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_treatment); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); // getting product details from intent Intent i = getIntent(); if (i.hasExtra(MyGlobalVars.TAG_USER_ID)) { // getting user id from intent user_id = i.getStringExtra(MyGlobalVars.TAG_USER_ID); user_name = i.getStringExtra(MyGlobalVars.TAG_NAME); // getting medical from intent medical_staff = i.getStringExtra(MyGlobalVars.TAG_MEDICAL_STAFF); } else { // Log out startActivity(new Intent(this, LoginActivity.class)); } //t = (EditText) findViewById(R.id.opLevel); //mytextName = (TextView) findViewById(R.id.mytextName); spinnerTreatment = (Spinner) findViewById(R.id.spinnerTreatment); spinnerTreatment.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { // your code here //t.setText(myTest2); if (spinnerTreatment.getSelectedItem().toString() != myTest && onChange) { spinnerMedicine.setAdapter(null); initializeSpinner(spinnerMedicine); new GetMedicineDetails().execute(); } myTest = spinnerTreatment.getSelectedItem().toString(); myTest2 = "" + myTest.charAt(0); } @Override public void onNothingSelected(AdapterView<?> parentView) { // your code here //new GetMedicineDetails().execute(); } }); spinnerMedicine = (Spinner) findViewById(R.id.spinnerMedicine); spinnerMedicine.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { // your code here myTest3 = spinnerMedicine.getSelectedItem().toString(); myTest4 = "" + myTest3.charAt(0); //t.setText(myTest2); } @Override public void onNothingSelected(AdapterView<?> parentView) { // your code here } }); initializeSpinner(spinnerTreatment); initializeSpinner(spinnerMedicine); // Getting complete product details in background thread new GetTreatmentDetails().execute(); // Getting complete product details in backgroun"d thread //new GetMedicineDetails().execute(); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_home) { // Go to home page Intent i = new Intent(this, SmartPillboxMainActivity.class); i.putExtra(MyGlobalVars.TAG_USER_ID, user_id); i.putExtra(MyGlobalVars.TAG_NAME, user_name); i.putExtra(MyGlobalVars.TAG_MEDICAL_STAFF, medical_staff); startActivity(i); } else if (id == R.id.nav_profile) { // Go to profile page Intent i = new Intent(this, ProfileActivity.class); i.putExtra(MyGlobalVars.TAG_USER_ID, user_id); i.putExtra(MyGlobalVars.TAG_NAME, user_name); i.putExtra(MyGlobalVars.TAG_MEDICAL_STAFF, medical_staff); startActivity(i); } else if (id == R.id.nav_treatment) { // Go to treatment page Intent i = new Intent(this, TreatmentActivity.class); i.putExtra(MyGlobalVars.TAG_USER_ID, user_id); i.putExtra(MyGlobalVars.TAG_NAME, user_name); i.putExtra(MyGlobalVars.TAG_MEDICAL_STAFF, medical_staff); startActivity(i); } else if (id == R.id.nav_patient) { // Go to patient page Intent i = new Intent(this, PatientActivity.class); i.putExtra(MyGlobalVars.TAG_USER_ID, user_id); i.putExtra(MyGlobalVars.TAG_NAME, user_name); i.putExtra(MyGlobalVars.TAG_MEDICAL_STAFF, medical_staff); startActivity(i); } else if (id == R.id.nav_settings) { // Go to settings page Intent i = new Intent(this, SettingsActivity.class); i.putExtra(MyGlobalVars.TAG_USER_ID, user_id); i.putExtra(MyGlobalVars.TAG_NAME, user_name); i.putExtra(MyGlobalVars.TAG_MEDICAL_STAFF, medical_staff); startActivity(i); } else if (id == R.id.nav_logout) { // Log out Intent i = new Intent(this, LoginActivity.class); startActivity(i); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } public void initializeSpinner(Spinner mySpinner) { ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new String[]{}); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mySpinner.setAdapter(adapter); //TODO get contact list from database String[] data = new String[]{}; for (String s : data) { addItemOnSpinnerContact(s, mySpinner); } } public void addItemOnSpinnerContact(String addItem, Spinner mySpinner) { int length = mySpinner.getAdapter().getCount(); String arrN[] = new String[length + 1]; arrN[0] = addItem; for (int i = 0; i < length; i++) { arrN[i + 1] = (String) mySpinner.getAdapter().getItem(i); } ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrN); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mySpinner.setAdapter(adapter); } public void myTreatment(ArrayList<String> batch_number, ArrayList<String> name, ArrayList<String> expiration_date, ArrayList<String> dosage) { final LinearLayout lm = (LinearLayout) findViewById(R.id.medicineAddLayout); if (lm.getChildCount() > 0) { lm.removeAllViews(); } // create the layout params that will be used to define how your // button will be displayed LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); ArrayList<LinearLayout> myMedicine = new ArrayList<>(); //Create four text_number = batch_number.size(); for (int j = 0; j <= batch_number.size() - 1; j++) { // Create LinearLayout myMedicine.add(new LinearLayout(this)); //LinearLayout ll = new LinearLayout(this); myMedicine.get(j).setOrientation(LinearLayout.HORIZONTAL); // Create TextView TextView product = new TextView(this); product.setText(name.get(j) + " : "); myMedicine.get(j).addView(product); // Create TextView TextView doom = new TextView(this); doom.setText(batch_number.get(j)); doom.setVisibility(View.GONE); myMedicine.get(j).addView(doom); // Create TextView TextView doom1 = new TextView(this); doom1.setText(name.get(j)); doom1.setVisibility(View.GONE); myMedicine.get(j).addView(doom1); // Create TextView TextView doom2 = new TextView(this); doom2.setText(expiration_date.get(j) + " "); doom2.setVisibility(View.GONE); myMedicine.get(j).addView(doom2); // Create TextView TextView doom3 = new TextView(this); doom3.setText(dosage.get(j) + " "); myMedicine.get(j).addView(doom3); // Create Button final Button btn = new Button(this); // Give button an ID btn.setId(j + 1); btn.setText("Change"); // set the layoutParams on the button btn.setLayoutParams(params); final int index = j; // Set click listener for button btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.i("TAG", "index :" + index); number = index; test(index); Toast.makeText(getApplicationContext(), "Clicked Button Index :" + index, Toast.LENGTH_SHORT).show(); } }); //Add button to LinearLayout myMedicine.get(j).addView(btn); //Add button to LinearLayout defined in XML lm.addView(myMedicine.get(j)); } } private void addTreatmentsave() { new addTreatmentToUser().execute(); } /*mAuthTask = new TreatmentTask(email, password); mAuthTask.execute((Void) null);*/ class addTreatmentToUser extends AsyncTask<Void, Void, Void> { private String data = ""; private ArrayList<String> success = new ArrayList<>(); private String start_date, end_date, doctor; HttpURLConnection urlConnection; JSONObject jsonData; /** * Before starting background thread Show Progress Dialog */ @Override protected void onPreExecute() { super.onPreExecute(); number = 0; pDialog = new ProgressDialog(TreatmentActivity.this); pDialog.setMessage("Loading user details. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); start_date = user; end_date = nom; doctor = expiration; } @Override protected Void doInBackground(Void... voids) { try { data = updateJSON(MyGlobalVars.url_add_treatment); jsonData = new JSONObject(data); success.add(jsonData.getString(MyGlobalVars.TAG_SUCCESS)); } catch (JSONException e) { e.printStackTrace(); } return null; } // http://smartpillbox.byethost7.com/database/medicine/update_medicine_info.php?TREATMENT_ID=1&BATCH_NUMBER=bfjkng897hj82&NAME=granddieu&DOSAGE=soir%20et%20matin&EXPIRATION_DATE=2018-04-20%2000:00:00 // TREATMENT_ID=1&BATCH_NUMBER=bfjkng897hj82&NAME=granddieu&DOSAGE=soir%20et%20matin&EXPIRATION_DATE=2018-04-20%2000:00:00 public String updateJSON(String url) { HttpURLConnection connection = null; try { String update = "" + url + MyGlobalVars.TAG_USER_ID + "=" + user_id + "&" + MyGlobalVars.TAG_START_DATE + "=" + start_date + "&" + MyGlobalVars.TAG_END_DATE + "=" + end_date + "&" + MyGlobalVars.TAG_DOCTOR + "=" + doctor ; update = update.replaceAll(" ", "%20"); URL u = new URL(update); connection = (HttpURLConnection) u.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-length", "0"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setAllowUserInteraction(false); connection.setConnectTimeout(MyGlobalVars.TIMEOUT); connection.setReadTimeout(MyGlobalVars.TIMEOUT); connection.setRequestProperty("Cookie", MyGlobalVars.myCookie); connection.connect(); int status = connection.getResponseCode(); switch (status) { case 200: case 201: InputStream responseStream = new BufferedInputStream(connection.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(responseStream), 8); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); String response = sb.toString(); return response; } } catch (MalformedURLException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } finally { if (connection != null) { try { connection.disconnect(); } catch (Exception ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } } } return null; } /** * After completing background task Dismiss the progress dialog **/ protected void onPostExecute(Void file_url) { // dismiss the dialog once got all details //editContact.setText(data); for (String ok : success) { if (ok.contentEquals("0")) { Toast.makeText(getBaseContext(), "Failed to update", Toast.LENGTH_SHORT); } } if (pDialog.isShowing()) { pDialog.dismiss(); } spinnerTreatment.setAdapter(null); initializeSpinner(spinnerTreatment); new GetTreatmentDetails().execute(); } } private void addMedicinesave() { new addMecineToUser().execute(); } /*mAuthTask = new TreatmentTask(email, password); mAuthTask.execute((Void) null);*/ class addMecineToUser extends AsyncTask<Void, Void, Void> { private String data = ""; private ArrayList<String> success = new ArrayList<>(); private String dosage, name, expiration_date, batch_number, treatment_id = myTest2; HttpURLConnection urlConnection; JSONObject jsonData; /** * Before starting background thread Show Progress Dialog */ @Override protected void onPreExecute() { super.onPreExecute(); number = 0; pDialog = new ProgressDialog(TreatmentActivity.this); pDialog.setMessage("Loading user details. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); batch_number = user; name = nom; expiration_date = expiration; dosage = dose; } @Override protected Void doInBackground(Void... voids) { try { data = updateJSON(MyGlobalVars.url_add_medicine); jsonData = new JSONObject(data); success.add(jsonData.getString(MyGlobalVars.TAG_SUCCESS)); } catch (JSONException e) { e.printStackTrace(); } return null; } // http://smartpillbox.byethost7.com/database/medicine/update_medicine_info.php?TREATMENT_ID=1&BATCH_NUMBER=bfjkng897hj82&NAME=granddieu&DOSAGE=soir%20et%20matin&EXPIRATION_DATE=2018-04-20%2000:00:00 // TREATMENT_ID=1&BATCH_NUMBER=bfjkng897hj82&NAME=granddieu&DOSAGE=soir%20et%20matin&EXPIRATION_DATE=2018-04-20%2000:00:00 public String updateJSON(String url) { HttpURLConnection connection = null; try { String update = "" + url + MyGlobalVars.TAG_BATCH_NUMBER + "=" + batch_number + "&" + MyGlobalVars.TAG_TREATMENT_ID + "=" + treatment_id + "&" + MyGlobalVars.TAG_NAME + "=" + name + "&" + MyGlobalVars.TAG_EXPIRATION_DATE + "=" + expiration_date + "&" + MyGlobalVars.TAG_DOSAGE + "=" + dosage; update = update.replaceAll(" ", "%20"); URL u = new URL(update); connection = (HttpURLConnection) u.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-length", "0"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setAllowUserInteraction(false); connection.setConnectTimeout(MyGlobalVars.TIMEOUT); connection.setReadTimeout(MyGlobalVars.TIMEOUT); connection.setRequestProperty("Cookie", MyGlobalVars.myCookie); connection.connect(); int status = connection.getResponseCode(); switch (status) { case 200: case 201: InputStream responseStream = new BufferedInputStream(connection.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(responseStream), 8); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); String response = sb.toString(); return response; } } catch (MalformedURLException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } finally { if (connection != null) { try { connection.disconnect(); } catch (Exception ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } } } return null; } /** * After completing background task Dismiss the progress dialog **/ protected void onPostExecute(Void file_url) { // dismiss the dialog once got all details //editContact.setText(data); for (String ok : success) { if (ok.contentEquals("0")) { Toast.makeText(getBaseContext(), "Failed to update", Toast.LENGTH_SHORT); } } if (pDialog.isShowing()) { pDialog.dismiss(); } spinnerMedicine.setAdapter(null); initializeSpinner(spinnerMedicine); new GetMedicineDetails().execute(); } } public void saveTreatment(View view) { saveUpdateUser(); } private void saveUpdateUser() { new UpdateUserDetails().execute(); } /** * Represents an asynchronous login/registration task used to authenticate * the user. */ class UpdateUserDetails extends AsyncTask<Void, Void, Void> { private String data = ""; private ArrayList<String> success = new ArrayList<>(); private String dosage, name, expiration_date, batch_number, treatment_id = myTest2; HttpURLConnection urlConnection; JSONObject jsonData; /** * Before starting background thread Show Progress Dialog */ @Override protected void onPreExecute() { super.onPreExecute(); number = 0; pDialog = new ProgressDialog(TreatmentActivity.this); pDialog.setMessage("Loading user details. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected Void doInBackground(Void... voids) { while (number < text_number) { saves(); try { data = updateJSON(MyGlobalVars.url_update_medicine_info); jsonData = new JSONObject(data); success.add(jsonData.getString(MyGlobalVars.TAG_SUCCESS)); } catch (JSONException e) { e.printStackTrace(); } number++; } return null; } private void saves() { Button myButton = null; for (int i = 0; i < text_number; i++) { if (i == number) { myButton = (Button) findViewById(i + 1); } } LinearLayout test = (LinearLayout) myButton.getParent(); for (int j = 0; j < test.getChildCount(); j++) { View myView = test.getChildAt(j); if (j == 4) { dosage = (((TextView) myView).getText().toString()); } if (j == 3) { expiration_date = (((TextView) myView).getText().toString()); } if (j == 2) { name = (((TextView) myView).getText().toString()); } if (j == 1) { batch_number = (((TextView) myView).getText().toString()); } } System.out.println("dosage :" + dosage + " " + "expiration :" + expiration_date + " " + "name :" + name + " " + "batch :" + batch_number + " " + "treatment :" + treatment_id); } // http://smartpillbox.byethost7.com/database/medicine/update_medicine_info.php?TREATMENT_ID=1&BATCH_NUMBER=bfjkng897hj82&NAME=granddieu&DOSAGE=soir%20et%20matin&EXPIRATION_DATE=2018-04-20%2000:00:00 // TREATMENT_ID=1&BATCH_NUMBER=bfjkng897hj82&NAME=granddieu&DOSAGE=soir%20et%20matin&EXPIRATION_DATE=2018-04-20%2000:00:00 public String updateJSON(String url) { HttpURLConnection connection = null; try { String update = "" + url + MyGlobalVars.TAG_BATCH_NUMBER + "=" + batch_number + "&" + MyGlobalVars.TAG_TREATMENT_ID + "=" + treatment_id + "&" + MyGlobalVars.TAG_NAME + "=" + name + "&" + MyGlobalVars.TAG_EXPIRATION_DATE + "=" + expiration_date + "&" + MyGlobalVars.TAG_DOSAGE + "=" + dosage; update = update.replaceAll(" ", "%20"); URL u = new URL(update); connection = (HttpURLConnection) u.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-length", "0"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setAllowUserInteraction(false); connection.setConnectTimeout(MyGlobalVars.TIMEOUT); connection.setReadTimeout(MyGlobalVars.TIMEOUT); connection.setRequestProperty("Cookie", MyGlobalVars.myCookie); connection.connect(); int status = connection.getResponseCode(); switch (status) { case 200: case 201: InputStream responseStream = new BufferedInputStream(connection.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(responseStream), 8); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); String response = sb.toString(); return response; } } catch (MalformedURLException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } finally { if (connection != null) { try { connection.disconnect(); } catch (Exception ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } } } return null; } /** * After completing background task Dismiss the progress dialog **/ protected void onPostExecute(Void file_url) { // dismiss the dialog once got all details //editContact.setText(data); for (String ok : success) { if (ok.contentEquals("0")) { Toast.makeText(getBaseContext(), "Failed to update", Toast.LENGTH_SHORT); } } if (pDialog.isShowing()) { pDialog.dismiss(); } } } /** * Background Async Task to Get complete product details */ class GetTreatmentDetails extends AsyncTask<Void, Void, Void> { private String data = ""; private ArrayList<String> start_date = new ArrayList<>(); private ArrayList<String> end_date = new ArrayList<>(); private ArrayList<String> doctor = new ArrayList<>(); private ArrayList<String> treatmentID = new ArrayList<>(); HttpURLConnection urlConnection; JSONObject jsonData; /** * Before starting background thread Show Progress Dialog */ @Override protected void onPreExecute() { super.onPreExecute(); onChange = false; pDialog = new ProgressDialog(TreatmentActivity.this); pDialog.setMessage("Loading treatment details. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /** * Getting product details in background thread */ protected Void doInBackground(Void... voids) { try { data = getJSON(MyGlobalVars.url_get_all_treatments); jsonData = new JSONObject(data); JSONArray treatments = jsonData.getJSONArray(MyGlobalVars.TAG_TREATMENT_MIN); for (int i = 0; i < treatments.length(); i++) { JSONObject treatment = treatments.getJSONObject(i); treatmentID.add(treatment.getString(MyGlobalVars.TAG_TREATMENT_ID)); start_date.add(treatment.getString(MyGlobalVars.TAG_START_DATE)); end_date.add(treatment.getString(MyGlobalVars.TAG_END_DATE)); doctor.add(treatment.getString(MyGlobalVars.TAG_DOCTOR)); } } catch (JSONException e) { e.printStackTrace(); } return null; } public String getJSON(String url) { HttpURLConnection connection = null; try { URL u = new URL(url + user_id); connection = (HttpURLConnection) u.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-length", "0"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setAllowUserInteraction(false); connection.setConnectTimeout(MyGlobalVars.TIMEOUT); connection.setReadTimeout(MyGlobalVars.TIMEOUT); connection.setRequestProperty("Cookie", MyGlobalVars.myCookie); connection.connect(); int status = connection.getResponseCode(); switch (status) { case 200: case 201: InputStream responseStream = new BufferedInputStream(connection.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(responseStream), 8); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); String response = sb.toString(); return response; } } catch (MalformedURLException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } finally { if (connection != null) { try { connection.disconnect(); } catch (Exception ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } } } return null; } /** * After completing background task Dismiss the progress dialog **/ protected void onPostExecute(Void file_url) { // dismiss the dialog once got all details String s; for (int i = treatmentID.size() - 1; i >= 0; i--) { s = treatmentID.get(i) + ": " + start_date.get(i) + " " + end_date.get(i); addItemOnSpinnerContact(s, spinnerTreatment); } //myTreatment(); if (pDialog.isShowing()) { pDialog.dismiss(); } onChange = true; spinnerMedicine.setAdapter(null); initializeSpinner(spinnerMedicine); new GetMedicineDetails().execute(); } } /** * Background Async Task to Get complete product details */ class GetMedicineDetails extends AsyncTask<Void, Void, Void> { private String data = ""; private ArrayList<String> dosage = new ArrayList<>(); private ArrayList<String> expiration_date = new ArrayList<>(); private ArrayList<String> batch_number = new ArrayList<>(); private ArrayList<String> treatmentID = new ArrayList<>(); private ArrayList<String> name = new ArrayList<>(); HttpURLConnection urlConnection; JSONObject jsonData; /** * Before starting background thread Show Progress Dialog */ @Override protected void onPreExecute() { super.onPreExecute(); onChange = false; pDialog = new ProgressDialog(TreatmentActivity.this); pDialog.setMessage("Loading treatment details. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /** * Getting product details in background thread */ protected Void doInBackground(Void... voids) { try { data = getJSON(MyGlobalVars.url_get_all_medicine); jsonData = new JSONObject(data); JSONArray medicines = jsonData.getJSONArray(MyGlobalVars.TAG_MEDICINE); for (int i = 0; i < medicines.length(); i++) { JSONObject medicine = medicines.getJSONObject(i); batch_number.add(medicine.getString(MyGlobalVars.TAG_BATCH_NUMBER)); treatmentID.add(medicine.getString(MyGlobalVars.TAG_TREATMENT_ID)); name.add(medicine.getString(MyGlobalVars.TAG_NAME)); expiration_date.add(medicine.getString(MyGlobalVars.TAG_EXPIRATION_DATE)); dosage.add(medicine.getString(MyGlobalVars.TAG_DOSAGE)); } } catch (JSONException e) { e.printStackTrace(); } return null; } public String getJSON(String url) { HttpURLConnection connection = null; try { URL u = new URL(url + myTest2); connection = (HttpURLConnection) u.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-length", "0"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setAllowUserInteraction(false); connection.setConnectTimeout(MyGlobalVars.TIMEOUT); connection.setReadTimeout(MyGlobalVars.TIMEOUT); connection.setRequestProperty("Cookie", MyGlobalVars.myCookie); connection.connect(); int status = connection.getResponseCode(); switch (status) { case 200: case 201: InputStream responseStream = new BufferedInputStream(connection.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(responseStream), 8); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); String response = sb.toString(); return response; } } catch (MalformedURLException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } finally { if (connection != null) { try { connection.disconnect(); } catch (Exception ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } } } return null; } /** * After completing background task Dismiss the progress dialog **/ protected void onPostExecute(Void file_url) { // dismiss the dialog once got all details String s; for (int i = treatmentID.size() - 1; i >= 0; i--) { s = "Medicine " + i + " : " + dosage.get(i) + " " + expiration_date.get(i); addItemOnSpinnerContact(s, spinnerMedicine); } myTreatment(batch_number, name, expiration_date, dosage); if (pDialog.isShowing()) { pDialog.dismiss(); } onChange = true; } } public void test(int view) { LayoutInflater inflater = getLayoutInflater(); View alertLayout = inflater.inflate(R.layout.medicine_change_dialog, null); final EditText batch_number = (EditText) alertLayout.findViewById(R.id.batch_number); final EditText name = (EditText) alertLayout.findViewById(R.id.medicine_patient_name); final EditText expiration_date = (EditText) alertLayout.findViewById(R.id.expiration_date); final EditText dosage = (EditText) alertLayout.findViewById(R.id.dosage); final CheckBox show = (CheckBox) alertLayout.findViewById(R.id.show); Button myButton = null; for (int i = 0; i < text_number; i++) { if (i == view) { myButton = (Button) findViewById(i + 1); } } LinearLayout test = (LinearLayout) myButton.getParent(); for (int j = 0; j < test.getChildCount(); j++) { View myView = test.getChildAt(j); if (j == 4) { dosage.setText(((TextView) myView).getText().toString()); } if (j == 3) { expiration_date.setText(((TextView) myView).getText().toString()); } if (j == 2) { name.setText(((TextView) myView).getText().toString()); } if (j == 1) { batch_number.setText(((TextView) myView).getText().toString()); } } show.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { } }); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Medicine change"); // this is set the view from XML inside AlertDialog alert.setView(alertLayout); // disallow cancel of AlertDialog on click of back button and outside touch alert.setCancelable(false); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getBaseContext(), "Cancel clicked", Toast.LENGTH_SHORT).show(); } }); alert.setPositiveButton("Apply changes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Button myButton = null; for (int i = 0; i < text_number; i++) { if (i == number) { myButton = (Button) findViewById(i + 1); } } final LinearLayout test = (LinearLayout) myButton.getParent(); for (int j = 0; j < test.getChildCount(); j++) { View myView = test.getChildAt(j); if (j == 4) { ((TextView) myView).setText(dosage.getText().toString()); } if (j == 3) { ((TextView) myView).setText(expiration_date.getText().toString()); } if (j == 2 || j == 0) { ((TextView) myView).setText(name.getText().toString() + " : "); } if (j == 1) { ((TextView) myView).setText(batch_number.getText().toString()); } } user = batch_number.getText().toString(); nom = name.getText().toString(); expiration = expiration_date.getText().toString(); dose = dosage.getText().toString(); Toast.makeText(getBaseContext(), "Batch number: " + batch_number.getText().toString() + " " + number + " Time: " + name.getText().toString(), Toast.LENGTH_SHORT).show(); saveUpdateUser(); } }); AlertDialog dialog = alert.create(); dialog.show(); } public void add_medicine(View view) { LayoutInflater inflater = getLayoutInflater(); View alertLayout = inflater.inflate(R.layout.medicine_change_dialog, null); final EditText batch_number = (EditText) alertLayout.findViewById(R.id.batch_number); final EditText name = (EditText) alertLayout.findViewById(R.id.medicine_patient_name); final EditText expiration_date = (EditText) alertLayout.findViewById(R.id.expiration_date); final EditText dosage = (EditText) alertLayout.findViewById(R.id.dosage); final CheckBox show = (CheckBox) alertLayout.findViewById(R.id.show); show.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { } }); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Medicin change"); // this is set the view from XML inside AlertDialog alert.setView(alertLayout); // disallow cancel of AlertDialog on click of back button and outside touch alert.setCancelable(false); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getBaseContext(), "Cancel clicked", Toast.LENGTH_SHORT).show(); } }); alert.setPositiveButton("Apply changes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { user = batch_number.getText().toString(); nom = name.getText().toString(); expiration = expiration_date.getText().toString(); dose = dosage.getText().toString(); Toast.makeText(getBaseContext(), "Batch number: " + batch_number.getText().toString() + " " + number + " Time: " + name.getText().toString(), Toast.LENGTH_SHORT).show(); addMedicinesave(); } }); AlertDialog dialog = alert.create(); dialog.show(); } public void add_treatment(View view) { LayoutInflater inflater = getLayoutInflater(); View alertLayout = inflater.inflate(R.layout.treatment_change_dialog, null); final EditText start = (EditText) alertLayout.findViewById(R.id.start_date); final EditText end = (EditText) alertLayout.findViewById(R.id.end_date); final EditText doct = (EditText) alertLayout.findViewById(R.id.treatment_doctor); final CheckBox show = (CheckBox) alertLayout.findViewById(R.id.show); show.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { } }); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Treatment add"); // this is set the view from XML inside AlertDialog alert.setView(alertLayout); // disallow cancel of AlertDialog on click of back button and outside touch alert.setCancelable(false); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getBaseContext(), "Cancel clicked", Toast.LENGTH_SHORT).show(); } }); alert.setPositiveButton("Apply changes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { user = start.getText().toString(); nom = end.getText().toString(); expiration = doct.getText().toString(); Toast.makeText(getBaseContext(), "Batch number: " + start.getText().toString() + " " + number + " Time: " + end.getText().toString(), Toast.LENGTH_SHORT).show(); addTreatmentsave(); } }); AlertDialog dialog = alert.create(); dialog.show(); } }
/* * Copyright 2002-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jdbc.support.incrementer; import org.springframework.dao.DataAccessException; /** * Interface that defines contract of incrementing any data store field's * maximum value. Works much like a sequence number generator. * * <p>Typical implementations may use standard SQL, native RDBMS sequences * or Stored Procedures to do the job. * * @author Dmitriy Kopylenko * @author Jean-Pierre Pawlak * @author Juergen Hoeller */ public interface DataFieldMaxValueIncrementer { /** * Increment the data store field's max value as int. * @return int next data store value such as <b>max + 1</b> * @throws org.springframework.dao.DataAccessException in case of errors */ int nextIntValue() throws DataAccessException; /** * Increment the data store field's max value as long. * @return int next data store value such as <b>max + 1</b> * @throws org.springframework.dao.DataAccessException in case of errors */ long nextLongValue() throws DataAccessException; /** * Increment the data store field's max value as String. * @return next data store value such as <b>max + 1</b> * @throws org.springframework.dao.DataAccessException in case of errors */ String nextStringValue() throws DataAccessException; }
package com.kbi.qwertech.api.data; public class QTConfigs { public static boolean doMobScrapesDrop; public static boolean slingshotGlass; public static boolean slingshotExplode; public static boolean doMobsUseGear; public static boolean canScrapePlayers; public static boolean addCustomAI; public static boolean cowsOverheat; public static boolean announceFanfare; public static boolean addDungeonTools; public static boolean overwriteJourneyMap; public static boolean removeVanillaCrafting; public static boolean allHammers; public static boolean anyHammers; public static boolean add3DGregTools; public static boolean add3DQwerTools; public static boolean add3DPrefixes; public static boolean enableFrogs; public static boolean enableTurkeys; public static boolean enable3DCrafting; public static boolean enableTools; public static boolean enableArmor; public static boolean chemicalXRandom; }
package leetcode; import org.junit.Before; import org.junit.Test; import com.google.common.truth.Truth; public class NimGameTest { private NimGame nimGame; @Before public void setup(){ nimGame = new NimGame(); } @Test public void test1_Expect_True(){ Truth.assertThat(nimGame.canWinNim(1)).isTrue(); } @Test public void test2_Expect_True(){ Truth.assertThat(nimGame.canWinNim(2)).isTrue(); } @Test public void test3_Expect_True(){ Truth.assertThat(nimGame.canWinNim(3)).isTrue(); } @Test public void test4_Expect_False(){ Truth.assertThat(nimGame.canWinNim(4)).isFalse(); } @Test public void test8_Expect_False(){ Truth.assertThat(nimGame.canWinNim(8)).isFalse(); } }