text
stringlengths
10
2.72M
package com.wq.newcommunitygovern.app.custom; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.RelativeLayout; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.blankj.utilcode.util.ObjectUtils; import com.chad.library.adapter.base.provider.BaseItemProvider; import com.weique.commonres.adapter.ProviderMultiAdapter; import com.weique.commonres.adapter.provider.ProviderFactory; import com.weique.commonres.adapter.provider.ProviderStore; import com.weique.commonres.base.commonbean.RecordsBean; import com.wq.newcommunitygovern.R; import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration; import java.util.ArrayList; import java.util.List; /** * @author GK * @description: * @date :2020/9/12 13:49 */ public class SuperRecyclerMultiAdapterView extends RelativeLayout { private RecyclerView recyclerView; private ProviderMultiAdapter adapter; public SuperRecyclerMultiAdapterView(Context context) { this(context, null); } public SuperRecyclerMultiAdapterView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SuperRecyclerMultiAdapterView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initAttrs(context, attrs); initView(context); } public ProviderMultiAdapter getAdapter() { return adapter; } /** * 初始化属性信息 * * @param context context * @param attrs attrs */ private void initAttrs(Context context, AttributeSet attrs) { } private void initView(Context context) { try { View view = LayoutInflater.from(context).inflate(R.layout.app_super_recycler_multi_adapter_view, this, false); addView(view); recyclerView = findViewById(R.id.recycler_view); adapter = new ProviderMultiAdapter(); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getContext()) .colorResId(R.color.app_colorPrimary) .sizeResId(R.dimen.dp_4) .build()); recyclerView.setAdapter(adapter); } catch (Exception e) { e.printStackTrace(); } } /** * 多布局 RecyclerView */ public void setMultiRecyclerViewData(List<RecordsBean> data) { try { List<BaseItemProvider> lol = new ArrayList<>(); if (ObjectUtils.isNotEmpty(data) && data.size() > 0) { //供应者商店 ProviderStore providerStore = new ProviderStore(new ProviderFactory()); for (RecordsBean bean : data) { lol.add(providerStore.shipment(bean.getParamtype(),bean.getStyle())); } } adapter.addItemProvider(lol); adapter.setNewInstance(data); } catch (Exception e) { e.printStackTrace(); } } }
/* * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kitesdk.morphline.hadoop.core; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.Path; import org.kitesdk.morphline.api.Command; import org.kitesdk.morphline.api.CommandBuilder; import org.kitesdk.morphline.api.MorphlineCompilationException; import org.kitesdk.morphline.api.MorphlineContext; import org.kitesdk.morphline.base.AbstractCommand; import com.typesafe.config.Config; /** * Command for transferring HDFS files, for example to help with centralized configuration file * management. On startup, the command downloads zero or more files or directory trees from HDFS to * the local file system. */ public final class DownloadHdfsFileBuilder implements CommandBuilder { @Override public Collection<String> getNames() { return Collections.singletonList("downloadHdfsFile"); } @Override public Command build(Config config, Command parent, Command child, MorphlineContext context) { try { return new DownloadHdfsFile(this, config, parent, child, context); } catch (IOException e) { throw new MorphlineCompilationException("Cannot compile", config, e); } } /////////////////////////////////////////////////////////////////////////////// // Nested classes: /////////////////////////////////////////////////////////////////////////////// private static final class DownloadHdfsFile extends AbstractCommand { // global lock; contains successfully copied file paths private static final Set<String> DONE = new HashSet(); public DownloadHdfsFile(CommandBuilder builder, Config config, Command parent, Command child, MorphlineContext context) throws IOException { super(builder, config, parent, child, context); List<String> uris = getConfigs().getStringList(config, "inputFiles", Collections.EMPTY_LIST); File dstRootDir = new File(getConfigs().getString(config, "outputDir", ".")); Configuration conf = new Configuration(); String defaultFileSystemUri = getConfigs().getString(config, "fs", null); if (defaultFileSystemUri != null) { FileSystem.setDefaultUri(conf, defaultFileSystemUri); // see Hadoop's GenericOptionsParser } for (String value : getConfigs().getStringList(config, "conf", Collections.EMPTY_LIST)) { conf.addResource(new Path(value)); // see Hadoop's GenericOptionsParser } validateArguments(); download(uris, conf, dstRootDir); } /* * To prevent races, we lock out other commands that delete and write the same local files, * and we only once delete and write any given file. This ensures that local file reads only * occur after local file writes are completed. E.g. this handles N parallel SolrSinks clones * in the same VM. * * TODO: consider extending this scheme to add filesystem based locking (advisory) in order to * also lock out clones in other JVM processes on the same file system. */ private void download(List<String> uris, Configuration conf, File dstRootDir) throws IOException { synchronized (DONE) { for (String uri : uris) { Path path = new Path(uri); File dst = new File(dstRootDir, path.getName()).getCanonicalFile(); if (!DONE.contains(dst.getPath())) { if (dst.isDirectory()) { LOG.debug("Deleting dir {}", dst); FileUtils.deleteDirectory(dst); } FileSystem fs = path.getFileSystem(conf); if (fs.isFile(path)) { dst.getParentFile().mkdirs(); } LOG.debug("Downloading {} to {}", uri, dst); if (!FileUtil.copy(fs, path, dst, false, conf)) { throw new IOException("Cannot download URI " + uri + " to " + dst); } DONE.add(dst.getPath()); LOG.debug("Succeeded downloading {} to {}", uri, dst); } } } } } }
/* * 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. */ /* Интервейс, декларирующий методы обработки XML */ package weblistener; import java.net.Socket; /** * * @author icemen78 */ public interface WLSession { public boolean responseXML(Socket socket); }
/* * 文 件 名: StringUtil.java * 描 述: StringUtil.java * 时 间: 2013-6-27 */ package com.babyshow.util; /** * <一句话功能简述> * * @author ztc * @version [BABYSHOW V1R1C1, 2013-6-27] */ public class StringUtil { /** * * 将字符串首字母小写 * * @param s * @return */ public static String lowerCaseFirstLetter(String str) { return str.substring(0, 1).toLowerCase() + str.substring(1); } }
package com.banlv.road.support; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; import java.util.Date; /** * @author :Lambert Wang * @date :Created in 2021/6/29 18:09 * @description: * @modified By: * @version: 1.0.0 */ public class AdminClient implements Watcher { String hostPort; ZooKeeper zk; @Override public void process(WatchedEvent watchedEvent) { System.out.println(watchedEvent); } AdminClient(String hostPort) { this.hostPort = hostPort; } void start() throws Exception { zk = new ZooKeeper(hostPort, 15000, this); } public void listState() throws KeeperException, InterruptedException { try{ Stat stat = new Stat(); byte[] masterData = zk.getData("/master", false, stat); Date startDate = new Date(stat.getCtime()); System.out.println("Master: " + new String(masterData) + "since " + startDate); } catch (KeeperException.NoNodeException e) { System.out.println("No master"); } for(String w: zk.getChildren("/workers", false)) { byte[] workData = zk.getData("workers" + w, false, null); String state = new String(workData); System.out.println("worker: " + w + ", data:" +state); } } }
package br.edu.ifam.saf.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import com.codetroopers.betterpickers.hmspicker.HmsPickerBuilder; import com.codetroopers.betterpickers.hmspicker.HmsPickerDialogFragment; import java.util.Calendar; import br.edu.ifam.saf.R; import br.edu.ifam.saf.util.TimeFormatter; public class FieldView extends LinearLayout implements HmsPickerDialogFragment.HmsPickerDialogHandlerV2 { public static final int TYPE_TIME_PICKER = 0x10000000; private EditText editText; public FieldView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FieldView, 0, 0); String hintText = a.getString(R.styleable.FieldView_hint); int inputType = a.getInteger(R.styleable.FieldView_inputType, EditorInfo.TYPE_TEXT_VARIATION_NORMAL); Drawable iconDrawable = a.getDrawable(R.styleable.FieldView_icon); Boolean border = a.getBoolean(R.styleable.FieldView_border, true); boolean enabled = a.getBoolean(R.styleable.FieldView_enabled, true); a.recycle(); setOrientation(LinearLayout.HORIZONTAL); setGravity(Gravity.CENTER_VERTICAL); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.field_view, this, true); if (border) { setBackgroundResource(R.drawable.field_view_background); } int pad = context.getResources().getDimensionPixelSize(R.dimen.field_padding); setPadding(pad, pad, pad, pad); ImageView icon = (ImageView) getChildAt(0); icon.setImageDrawable(iconDrawable); editText = (EditText) getChildAt(1); int baseFormat; switch (inputType) { case EditorInfo.TYPE_DATETIME_VARIATION_DATE: baseFormat = EditorInfo.TYPE_CLASS_DATETIME; break; case EditorInfo.TYPE_NUMBER_VARIATION_NORMAL: baseFormat = EditorInfo.TYPE_CLASS_NUMBER; break; default: baseFormat = EditorInfo.TYPE_CLASS_TEXT; } if (inputType == TYPE_TIME_PICKER) { editText.setFocusable(false); editText.setFocusableInTouchMode(false); editText.setDuplicateParentStateEnabled(true); editText.setMovementMethod(null); editText.setKeyListener(null); this.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { HmsPickerBuilder hpb = new HmsPickerBuilder() .addHmsPickerDialogHandler(FieldView.this) .setFragmentManager(((AppCompatActivity) getContext()).getSupportFragmentManager()) .setStyleResId(R.style.BetterPickersDialogFragment); hpb.show(); } }); } else { editText.setInputType(baseFormat | inputType); } editText.setHint(hintText); editText.setEnabled(enabled); } public FieldView(Context context) { this(context, null); } public void addTextChangeListener(TextWatcherAdapter textWatcherAdapter) { editText.addTextChangedListener(textWatcherAdapter); } public String getText() { return editText.getText().toString(); } public void setText(String text) { editText.setText(text); } @Override public void onDialogHmsSet(int reference, boolean isNegative, int hours, int minutes, int seconds) { Calendar instance = Calendar.getInstance(); instance.set(Calendar.HOUR_OF_DAY, 8); editText.setText(TimeFormatter.format(hours, minutes)); } public static class TextWatcherAdapter implements 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) { } } }
package com.han.springbootmybatisplus2.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.han.springbootmybatisplus2.entity.Teacher; import com.han.springbootmybatisplus2.mapper.TeacherMapper; import com.han.springbootmybatisplus2.service.TeacherService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @ClassName TeacherServiceImpl * @Description TODO * @Author HanWL * @Since 2020/5/9 0009 14:36 */ @Service public class TeacherServiceImpl implements TeacherService { @Autowired TeacherMapper teacherMapper; @Override public int insert(Teacher teacher) { return teacherMapper.insert(teacher); } @Override public List<Teacher> findAll() { return teacherMapper.selectList(null); } @Override public int delete(Long id) { return teacherMapper.deleteById(id); } @Override public int update(Teacher teacher) { return teacherMapper.updateById(teacher); } public Teacher selectOne(Long id) { return teacherMapper.selectById(id); } @Override public Teacher selectOneByCondition(String name,Integer age) { QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("name",name).gt("age",age); return teacherMapper.selectOne(queryWrapper); } }
package com.simbircite.demo.repository; import org.springframework.data.repository.*; import com.simbircite.demo.model.*; public interface PayRepository extends PagingAndSortingRepository<Pay, Integer> { }
package JZOF; /** * Created by yangqiao on 19/6/17. */ public class Sort { public static void main(String[] args) { // int[] array = new int[]{1, 2, 3, 5, 2, 3, 1, 9, 4}; // QuikSort.quikSort(array); // for (int i : array) { // System.out.println(i); // } } } class QuikSort { /* private static int getPivot(int[] array, int start, int end) { int i = start; int key = array[start]; for (int j = i + 1; j <= end; j++) { if (array[j] < key) { int temp = array[j]; array[j] = array[i + 1]; array[i + 1] = temp; i++; } } array[start] = array[i]; array[i] = key; return i; } */ private static int getPivot(int[] array, int start, int end) { int i = start - 1; int key = array[end]; for (int j = start; j < end; j++) { if (array[j] < key) { i++; int temp = array[j]; array[j] = array[i]; array[i] = temp; } } int temp = array[end]; array[end] = array[i + 1]; array[i + 1] = temp; return i + 1; } private static void qsort(int[] array, int start, int end) { if (start < end) { int pivot = getPivot(array, start, end); qsort(array, 0, pivot - 1); qsort(array, pivot + 1, end); } } public static void quikSort(int[] array) { if (array != null) { qsort(array, 0, array.length - 1); } } }
package com.mihoyo.hk4e.wechat.dto; public class Result<T> { private int code; private String errMsg; private T data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getErrMsg() { return errMsg; } public void setErrMsg(String errMsg) { this.errMsg = errMsg; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
package com.tencent.mm.ui.widget.textview; import android.view.View; import android.view.View.OnClickListener; class a$4 implements OnClickListener { final /* synthetic */ a uPp; a$4(a aVar) { this.uPp = aVar; } public final void onClick(View view) { this.uPp.cBo(); this.uPp.cBn(); } }
package org.study.core.references; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; /** * WeakReference works similar to SoftReference however objects are eligible to be collected anyway if they have only weak references */ public class WeakRef { private static Object obj; private static void demoWeakRef() { System.out.println("-- demoWeakRef"); obj = new Object(); Reference<Object> ref = new WeakReference(obj); obj = null; System.out.println("Ref is " + ref.get()); try { Thread.sleep(1000); System.out.println("GC invocation"); System.gc(); } catch (InterruptedException e) { System.out.println("interrupted"); } System.out.println("Ref is " + ref.get()); } public static void main(String[] args) { demoWeakRef(); demoWeakRefWithQueue(); } private static void demoWeakRefWithQueue() { System.out.println("-- demoWeakRefWithQueue"); obj = new Object(); ReferenceQueue<Object> queue = new ReferenceQueue<>(); Reference<Object> ref = new WeakReference(obj, queue); obj = null; System.out.println("Ref is " + ref.get()); System.out.println("Queue pull is " + queue.poll()); try { Thread.sleep(1000); System.out.println("GC invocation"); System.gc(); } catch (InterruptedException e) { System.out.println("interrupted"); } System.out.println("Ref is " + ref.get()); System.out.println("Queue pull is required var? " + (queue.poll() == ref)); } }
package sample; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXTextField; import com.jfoenix.controls.JFXToggleButton; import javafx.animation.RotateTransition; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.WindowEvent; import javafx.util.Duration; public class settingsGUI { BorderPane borderPane = new BorderPane(); public static String blankScore = "0"; public static String flagScore = "5"; public static String bombkScore = "0"; public static String shieldsCount = "0"; public JFXToggleButton toggleTheme = new JFXToggleButton(); VBox settingsBox = new VBox(); ImageView topGearImg = new ImageView( new Image("./assests/topGear.png") ); ImageView secondGearImg = new ImageView( new Image("./assests/SecondGear.png") ); private static boolean darkOrLight = false; String themeLight ; String themeDark ; public boolean theme = false ; Stage window = new Stage(); private String themePath; public void openSettingsWindow(int blank , int flag , int bomb , int shields) { themeLight = getClass().getResource("../style.css").toExternalForm(); themeDark = getClass().getResource("../DarkStyle.css").toExternalForm(); if(darkOrLight){ themePath = themeDark; settingsBox.getStylesheets().add(themeDark); topGearImg.setImage( new Image("./assests/darkTopGear.png") ); secondGearImg.setImage( new Image("./assests/darkSecondGear.png") ); }else if(!darkOrLight){ themePath = themeLight; settingsBox.getStylesheets().add(themeLight); } HBox settingsBox = new HBox(); Label settingsWord = new Label("Settings :"); settingsWord.setAlignment(Pos.TOP_CENTER); settingsWord.getStyleClass().add("settingsLabel"); settingsWord.setId("settingsWord"); Label blankCell = new Label("Blank Cell Score"); blankCell.getStyleClass().add("settingsLabel"); JFXTextField blankScoreField = new JFXTextField(); blankScoreField.setLabelFloat(true); blankScoreField.setPromptText("Value"); blankScoreField.getStyleClass().add("settingsTextField"); HBox blankBlock = new HBox(); HBox.setMargin(blankCell , new Insets(10 , 30 , 50 , 40)); blankBlock.getChildren().addAll(blankCell , blankScoreField); //////////////////////// Label flagCell = new Label("Flag Cell Score"); flagCell.getStyleClass().add("settingsLabel"); JFXTextField flagScoreField = new JFXTextField(); flagScoreField.setLabelFloat(true); flagScoreField.setPromptText("Value"); flagScoreField.getStyleClass().add("settingsTextField"); HBox flagBlock = new HBox(); HBox.setMargin(flagCell , new Insets(10 , 30 , 50 , 40)); flagBlock.getChildren().addAll(flagCell , flagScoreField); //////////////////////// Label bombCell = new Label("Bomb Cell Score"); bombCell.getStyleClass().add("settingsLabel"); JFXTextField bombScoreField = new JFXTextField(); bombScoreField.setLabelFloat(true); bombScoreField.setPromptText("Value"); bombScoreField.getStyleClass().add("settingsTextField"); HBox bombBlock = new HBox(); HBox.setMargin(bombCell , new Insets(10 , 30 , 30 , 40)); bombBlock.getChildren().addAll(bombCell , bombScoreField); Label shieldsLabel = new Label(" Shields: "); shieldsLabel.getStyleClass().add("settingsLabel"); JFXTextField shieldsInput= new JFXTextField(); shieldsInput.setLabelFloat(true); shieldsInput.setPromptText("Value"); shieldsInput.getStyleClass().add("settingsTextField"); HBox shieldsBlock = new HBox(); HBox.setMargin(shieldsLabel , new Insets(10 , 30 , 30 , 40)); shieldsBlock.getChildren().addAll(shieldsLabel , shieldsInput); JFXButton settingsButton = new JFXButton("Save Settings"); settingsButton.getStyleClass().add("button-raised"); settingsButton.setOnAction(e -> { if (!blankScoreField.getText().trim().isEmpty()) this.blankScore = blankScoreField.getText(); if (!flagScoreField.getText().trim().isEmpty()) this.flagScore = flagScoreField.getText(); if (!bombScoreField.getText().trim().isEmpty()) this.bombkScore = bombScoreField.getText(); if (!shieldsInput.getText().trim().isEmpty()) this.shieldsCount = shieldsInput.getText(); window.close(); }); VBox.setMargin(settingsButton , new Insets(50 , 0 , 0, 0)); VBox allSettingsBlock = new VBox(); allSettingsBlock.getStylesheets().add(themePath); allSettingsBlock.setAlignment(Pos.CENTER); allSettingsBlock.setId("allSettingsBlock"); VBox.setMargin(settingsWord , new Insets(0 , 0 , 40 , 0)); allSettingsBlock.getChildren().addAll(settingsWord , blankBlock , flagBlock , bombBlock , shieldsBlock , settingsButton); Label blankDefault = new Label("Default: " + blank ); blankDefault.getStyleClass().add("defaultLabel"); Label flagDefault = new Label("Default: " + flag); flagDefault.getStyleClass().add("defaultLabel"); Label bombDefault = new Label("Default : " + bomb); bombDefault.getStyleClass().add("defaultLabel"); Label shieldsDefault = new Label("Default : " + shields); shieldsDefault.getStyleClass().add("defaultLabel"); VBox allSettingsDefaults = new VBox(); allSettingsDefaults.getStylesheets().add(themePath); allSettingsDefaults.setAlignment(Pos.CENTER); VBox.setMargin(blankDefault , new Insets(55 , 20 , 40 , 40)); VBox.setMargin(flagDefault , new Insets(40, 20 , 10, 40)); VBox.setMargin(bombDefault , new Insets(60 , 20 , 0 , 40)); VBox.setMargin(shieldsDefault , new Insets(60 , 20 , 0 , 40)); allSettingsDefaults.getChildren().addAll(blankDefault, flagDefault , bombDefault , shieldsDefault); HBox.setMargin(allSettingsDefaults , new Insets(0 , 20, 70,10 )); VBox pictureBox = new VBox(); topGearImg.getStyleClass().add("mapImage"); topGearImg.setPreserveRatio(true); topGearImg.setFitWidth(300); secondGearImg.getStyleClass().add("mapImage"); secondGearImg.setPreserveRatio(true); secondGearImg.setFitWidth(250); HBox movingGears = new HBox(); movingGears.setAlignment(Pos.CENTER); movingGears.getStyleClass().add("movingGearsBox"); movingGears.getChildren().addAll(topGearImg , secondGearImg); HBox.setMargin(secondGearImg , new Insets(120, 0, 0, 0 )); pictureBox.setAlignment(Pos.CENTER); pictureBox.setMinWidth(550); pictureBox.getChildren().add(movingGears); RotateTransition rt = new RotateTransition(Duration.seconds(5), topGearImg); rt.setByAngle(360); rt.setCycleCount(1000); rt.play(); RotateTransition rt1 = new RotateTransition(Duration.seconds(5), secondGearImg); rt1.setByAngle(-360); rt1.setCycleCount(1000); rt1.play(); toggleTheme.setOnAction(e -> { if (!toggleTheme.isSelected()) { toggleTheme.setSelected(false) ; this.theme = false ; darkOrLight = false ; settingsBox.getStylesheets().remove(themeDark); allSettingsBlock.getStylesheets().remove(themeDark); allSettingsDefaults.getStylesheets().remove(themeDark); System.out.println("scene stylesheets on button 1 click: " + settingsBox.getStylesheets()); if(!settingsBox.getStylesheets().contains(themeLight)){ settingsBox.getStylesheets().add(themeLight); allSettingsBlock.getStylesheets().add(themeLight); allSettingsDefaults.getStylesheets().add(themeLight); topGearImg.setImage( new Image("./assests/topGear.png") ); secondGearImg.setImage( new Image("./assests/SecondGear.png") ); } System.out.println("scene stylesheets on button 1 click: " + settingsBox.getStylesheets()); } else{ toggleTheme.setSelected(true); this.theme = true ; darkOrLight = true; settingsBox.getStylesheets().remove(themeLight); allSettingsBlock.getStylesheets().remove(themeLight); allSettingsDefaults.getStylesheets().remove(themeLight); System.out.println("scene stylesheets on button 1 click: " + settingsBox.getStylesheets()); if(!settingsBox.getStylesheets().contains(themeDark)){ settingsBox.getStylesheets().add(themeDark); allSettingsBlock.getStylesheets().add(themeDark); allSettingsDefaults.getStylesheets().add(themeDark); topGearImg.setImage( new Image("./assests/darkTopGear.png") ); secondGearImg.setImage( new Image("./assests/darkSecondGear.png") ); } System.out.println("scene stylesheets on button 1 click: " + settingsBox.getStylesheets()); } }); settingsBox.getChildren().addAll(allSettingsBlock , allSettingsDefaults , pictureBox , toggleTheme); Scene settings = new Scene( settingsBox, 1300 , 700 ); window.setScene(settings); window.show(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package classinfo; import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; /** * * @author Nathan */ public class ConstantPool { CPBase[] pool; public CPBase getEntry(int index) { if (index > 0 && index < pool.length) { return pool[index]; } return null; } public boolean read(DataInputStream dis) { try { int count = dis.readUnsignedShort(); pool = new CPBase[count]; for (int i = 1; i < count; i++) { pool[i] = CPBase.read(this, dis); if (pool[i] instanceof CPLong || pool[i] instanceof CPDouble) { i++; } } for (int i = 1; i < count; i++) { if (pool[i] != null && !pool[i].verify()) { return false; } } } catch (IOException ex) { } return true; } }
package com.dsc.dw.dao; import javax.naming.*; import javax.sql.*; public class ConnectionManager { private static DataSource dwDS = null; private static Context context = null; public static DataSource mtrcConn() throws Exception { if (dwDS != null){ return dwDS; } try{ if (context == null){ context = new InitialContext(); } dwDS = (DataSource) context.lookup("java:/comp/env/dwDS"); } catch( Exception e) { e.printStackTrace(); } return dwDS; } }
package com.aprendoz_test.data; /** * aprendoz_test.VPorcentajeCalificacion * 01/19/2015 07:58:52 * */ public class VPorcentajeCalificacion { private VPorcentajeCalificacionId id; public VPorcentajeCalificacionId getId() { return id; } public void setId(VPorcentajeCalificacionId id) { this.id = id; } }
/** * */ package com.wonders.schedule.aspect; import java.lang.reflect.Method; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; import com.wonders.schedule.common.util.SimpleLogger; import com.wonders.schedule.execute.IExecutable; import com.wonders.schedule.model.bo.TScheduleConfig; /** * @ClassName: ScheduleLog * @Description: TODO(日志记录) * @author zhoushun * @date 2012-12-5 上午11:27:15 * */ @Aspect @Component("logAspect") public class ScheduleLog { static SimpleLogger log = new SimpleLogger(ScheduleLog.class); @Before(value = "execution(* com.wonders.schedule.execute.IExecutable.*(..))") //也可使用 定义的切入点 //@Before("com.wonders.schedule.aspect.PointCutDef.beforeTaskExec()") public void beforeTask(JoinPoint joinPoint) { log.debug("sql prepare================================"); IExecutable target = (IExecutable) joinPoint.getTarget(); TScheduleConfig t = (TScheduleConfig) joinPoint.getArgs()[0]; executeMethod(t, target, "begin", ""); } // 总会执行 // @After(value="execution(* com.wonders.schedule.execute.IExecutable.*(..))") // public void afterTask(JoinPoint joinPoint){ // log.debug("sql end================================"); // IExecutable target = (IExecutable) joinPoint.getTarget(); // TScheduleConfig t = (TScheduleConfig)joinPoint.getArgs()[0]; // executeMethod(t,target,"end"); // afterMethod(t,target); // } // 可获取返回值 返回值后执行 @AfterReturning(value = "execution(* com.wonders.schedule.execute.IExecutable.*(..))",returning = "rtv") public void afterTask(JoinPoint joinPoint, Object rtv) { log.debug("sql end================================"); IExecutable target = (IExecutable) joinPoint.getTarget(); TScheduleConfig t = (TScheduleConfig) joinPoint.getArgs()[0]; executeMethod(t, target, "end", rtv==null ? "" : rtv.toString()); afterMethod(t, target); } // 可获取返回值 返回值后执行 切入点应放在执行的service 的接口上,这样能获得该service //内部方法及类的异常,若放在最外层,则只能获得外层service //即方法抛出只能获得当前这层service内的 异常 //若嵌套调用service 则需要将切入点放在最内层service 方能捕捉真正的内部 异常; //否则 异常停止在当前service层,不会深入内部 // 抛出后通知(After throwing advice) // @AfterThrowing(value = "execution(* com.wonders.task.sample.ITaskService.*(..))", throwing = "error") // public void afterThrowAdvice(JoinPoint joinPoint, Throwable error) { // String exceptionInfo = ""; // IExecutable target = (IExecutable) joinPoint.getTarget(); // TScheduleConfig t = (TScheduleConfig) joinPoint.getArgs()[0]; // exceptionInfo += "代理对象:" + joinPoint.getTarget().getClass().getName() // + "。 异常方法:" + joinPoint.getSignature() + "。异常详细信息:" // + error.toString() + "。" + "\n" + constructError(error); // log.debug("exceptionInfo log================================" // + exceptionInfo); // exceptionMethod(t, target, "exception", exceptionInfo); // } // 抛出后通知(After throwing advice) 应写为 itaskservice 即可捕捉异常及返回至 @AfterThrowing(value = "execution(* com.wonders.schedule.execute.IExecutable.*(..))", throwing = "error") public void afterThrowAdvice(JoinPoint joinPoint, Throwable error) { String exceptionInfo = ""; IExecutable target = (IExecutable) joinPoint.getTarget(); TScheduleConfig t = (TScheduleConfig) joinPoint.getArgs()[0]; exceptionInfo += "代理对象:" + joinPoint.getTarget().getClass().getName() + "。 异常方法:" + joinPoint.getSignature() + "。异常详细信息:" + error.toString() + "。" + "\n" + constructError(error); log.debug("exceptionInfo log================================" + exceptionInfo); exceptionMethod(t, target, "exception", exceptionInfo); } private void executeMethod(TScheduleConfig t, IExecutable target, String process, String rtv) { log.debug("sql log================================"+"TScheduleConfig:"+t.getName()+"rtv="+rtv); try { Method method = LogUtil.class.getMethod( "writeLog", new Class[] { TScheduleConfig.class, String.class, String.class }); method.invoke(null, new Object[] { t, process, rtv }); } catch (Exception e) { e.printStackTrace(); } } private void exceptionMethod(TScheduleConfig t, IExecutable target, String process, String error) { log.debug("sql log================================"); try { Method method = LogUtil.class.getMethod( "writeException", new Class[] { TScheduleConfig.class, String.class, String.class }); method.invoke(null, new Object[] { t, process, error }); } catch (Exception e) { e.printStackTrace(); } } private void afterMethod(TScheduleConfig t, IExecutable target) { try { Method method = LogUtil.class.getMethod("updateTime", new Class[] { TScheduleConfig.class }); method.invoke(null, new Object[] { t }); } catch (Exception e) { e.printStackTrace(); } } // 构建错误对象 private String constructError(Throwable e) { StringBuffer exInfo = new StringBuffer(); StackTraceElement[] messages = e.getStackTrace(); int length = messages.length; for (int i = 0; i < length; i++) { if (messages[i].getClassName().indexOf("com.wonders") > -1) { exInfo.append("ClassName:" + messages[i].getClassName() + "\n"); exInfo.append("getLineNumber:" + messages[i].getLineNumber() + "\n"); exInfo.append("getMethodName:" + messages[i].getMethodName() + "\n"); exInfo.append("toString:" + messages[i].toString() + "\n"); } } return exInfo.toString(); } }
package com.az.city7; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.webkit.WebView; import android.webkit.WebViewClient; import org.web3j.crypto.ECKeyPair; import org.web3j.crypto.Keys; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; public class CreateActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create); final String ERROR = "aaa"; // create new private/public key pair final ECKeyPair[] keyPair = {null}; try { keyPair[0] = Keys.createEcKeyPair(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); Log.e(ERROR,"No Such Algorithm Exception"); } catch (NoSuchProviderException e) { e.printStackTrace(); Log.e(ERROR,"No Such Provider Exception"); } WebView webView = (WebView) findViewById(R.id.webView); webView.loadUrl("http://www.google.com"); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient()); } }
package javaBasics; public class ArrayConcepts { public static void main(String[] args) { // int array int i[]=new int[4]; i[0]=10; i[1]=20; i[2]=30; i[3]=40; System.out.println(i[3]); System.out.println(i.length); //size of array //print all the values of array - use for loop for(int x=0; x<i.length; x++){ System.out.println(i[x]); } String name[] = new String[4]; name[0]="My"; name[1]="Name"; name[2]="is"; name[3]="Sri"; System.out.println(name[3]); for(int j=0; j<name.length; j++){ System.out.println(name[j]); } //Object Array - Object is a class----is used to store different data types values Object ob[] = new Object[6]; ob[0] = "Tom"; ob[1] = 25; ob[2] = 12.33; ob[3] = "1/1/1995"; ob[4] = 'M'; ob[5] = "London"; System.out.println(ob[5]); System.out.println(ob.length); for(int d=0; d<ob.length; d++){ System.out.println(ob[d]); } } }
/* * 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 com.hoc.service.interfaces; import com.hoc.model.AccessRole; import java.util.List; /** * * @author patience */ public interface AccessRoleService extends Service<AccessRole> { public AccessRole getAccessRoleByCode(long code); public List<AccessRole> getRoles(); }
package com.tencent.mm.plugin.appbrand.r; import com.tencent.mm.plugin.appbrand.jsapi.m; import com.tencent.mm.sdk.platformtools.aw.a; import com.tencent.mm.sdk.platformtools.x; class b$1 implements a { final /* synthetic */ b gBv; b$1(b bVar) { this.gBv = bVar; } public final void aou() { x.i("MicroMsg.AppBrandUserCaptureScreenMonitor", "onScreenShot callback"); m.tm(this.gBv.appId); } }
package no.fint.provider.fiks.exception; public class GetTilskuddFartoyNotFoundException extends RuntimeException { public GetTilskuddFartoyNotFoundException(String message) { super(message); } }
package com.utils.util; public class JVMUtils { /** * 返回虚拟机使用内存量的一个估计值,内容为"xxM" * @return */ public static String usedMemory() { Runtime runtime = Runtime.getRuntime(); return (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024 + "M"; } /** * 增加JVM停止时要做处理事件 */ public static void addShutdownHook( Runnable runnable ) { Runtime.getRuntime().addShutdownHook( new Thread( runnable ) ); } }
package com.lubarov.daniel.multiweb; import com.lubarov.daniel.alexresume.AlexResumeHandler; import com.lubarov.daniel.blog.BlogHandler; import com.lubarov.daniel.chat.ChatHandler; import com.lubarov.daniel.conniewedding.ConnieWeddingHandler; import com.lubarov.daniel.gw2.Gw2Handler; import com.lubarov.daniel.junkmail.JunkMailHandler; import com.lubarov.daniel.nagger.NaggerHandler; import com.lubarov.daniel.viewheaders.ViewHeadersHandler; import com.lubarov.daniel.web.http.HttpRequest; import com.lubarov.daniel.web.http.HttpResponse; import com.lubarov.daniel.web.http.server.Handler; import com.lubarov.daniel.web.http.server.util.HostBasedHandler; import com.lubarov.daniel.wedding.WeddingHandler; final class MultiwebHandler implements Handler { public static final MultiwebHandler singleton = new MultiwebHandler(); private static final Handler hostBasedHandler = new HostBasedHandler.Builder() .addHandlerForHost(".*nagger\\.daniel\\.lubarov\\.com.*", NaggerHandler.getHandler()) .addHandlerForHost(".*danielvi\\.com.*", WeddingHandler.getHandler()) .addHandlerForHost(".*leoconnie\\.com.*", ConnieWeddingHandler.getHandler()) .addHandlerForHost(".*daniel\\.lubarov\\.com.*", BlogHandler.getHandler()) .addHandlerForHost(".*alex\\.lubarov\\.com.*", AlexResumeHandler.getHandler()) .addHandlerForHost(".*viewheaders\\.com.*", ViewHeadersHandler.getHandler()) .addHandlerForHost(".*jabberings\\.net.*", ChatHandler.getHandler()) .addHandlerForHost(".*gw2tools\\.net.*", Gw2Handler.getHandler()) .addHandlerForHost(".*baggageman\\.com.*", JunkMailHandler.getHandler()) .build(); private MultiwebHandler() {} @Override public HttpResponse handle(HttpRequest request) { if (request.getResource().equals("/_version")) return VersionHandler.singleton.handle(request); if (request.getResource().equals("/_update")) return UpdateHandler.singlgeton.handle(request); return hostBasedHandler.handle(request); } }
package com.tencent.mm.plugin.webwx.a; import com.tencent.mm.ab.d; import com.tencent.mm.g.a.or; import com.tencent.mm.model.bv.a; import com.tencent.mm.platformtools.ab; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.bl; import com.tencent.mm.sdk.platformtools.x; class g$1 implements a { final /* synthetic */ g qmg; g$1(g gVar) { this.qmg = gVar; } public final void a(d.a aVar) { String str = (String) bl.z(ab.a(aVar.dIN.rcl), "sysmsg").get(".sysmsg.pushloginurl.url"); if (bi.oW(str)) { x.e("MicroMsg.SubCoreWebWX.pushloginurl", "pushloginurl is null"); } or orVar = new or(); orVar.bZC.bZD = str; orVar.bZC.type = 1; com.tencent.mm.sdk.b.a.sFg.m(orVar); aVar.dIN.rcp = null; } }
package com.toggleable.morgan.jeremyslist.ui; /** * Created by morgaface on 11/17/15. */ public class NewListActivity { }
package com.javanme.java8; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.OptionalInt; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; /** * Clase con ejercicios nivel intermedio * Created by aalopez on 18/08/15. */ public class Intermedio { static final String REGEXP = "[- .:,]+"; // separa cadenas de texto en palabras /** * Contar el número de líneas no vacías que tiene el archivo pasado por parámetro. * Usar nuevos métodos encontrados en la clase java.nio.file.Files en Java 8 para obtener un Stream de * las líneas de texto un archivo. * * @param archivo Ruta al archivo que se desea evaluar * @return Cantidad de líneas en el archivo * @see java.nio.file.Files * @see java.util.stream.Stream */ public long ejercicio1(Path archivo) { long numberLines = -1; try { numberLines = Files.lines(archivo) //.filter(Predicate.not(String::isEmpty)) .filter(l -> !l.isEmpty()) .count(); } catch (IOException e) { e.printStackTrace(); } return numberLines; } /** * Encuentra el número de caracteres que tiene la línea más larga del archivo. * Usar nuevos métodos encontrados en la clase java.nio.file.Files en Java 8 para obtener un Stream de * las líneas de texto de un archivo. * Para poder obtener un OptionalInt como resultado, debes convertir el Stream a uno primitivo. * * @param archivo Ruta al archivo que se desea evaluar * @return Cantidad de caracteres que tiene la línea más larga del archivo * @see java.nio.file.Files * @see java.util.stream.Stream * @see java.util.stream.IntStream */ public OptionalInt ejercicio2(Path archivo) { OptionalInt optional = null; try { optional = Files.lines(archivo) .mapToInt(String::length) .max(); } catch (IOException e) { e.printStackTrace(); } return optional; } /** * De las palabras que se encuentran en el archivo pasado por parámetro, conviertelas a minúsculas, * sin duplicados, ordenadas primero por tamaño y luego alfabeticamente. * * Une todas las palabras en una cadena de texto separando cada palabra por un espacio (" ") * * Usa la constante REGEXP proveida al inicio de esta clase para hacer la separación de cadenas de texto a palabras. * Es posible que esta expresión retorne palabras vacías por lo que tendrás que adicionar un filtro que las remueva. * * @param archivo Ruta al archivo que se desea evaluar * @return Cadena de texto que contiene las palabras en minúsculas, sin duplicados, ordenadas por tamaño, luego alfabeticamente * y cada palabra está separada por un espacio * @see java.nio.file.Files * @see java.util.stream.Stream * @see java.lang.String * @see java.util.stream.Collectors */ public String ejercicio3(Path archivo) { String cadena = ""; try { cadena = Files.lines(archivo) .map(l -> l.split(REGEXP)) .map(Arrays::stream) .flatMap(Function.identity()) .filter(w -> !w.isEmpty()) .map(String::toLowerCase) .distinct() .sorted(Comparator .comparingInt(String::length) .thenComparing(Comparator.naturalOrder())) .collect(Collectors.joining(" ")); } catch (IOException e) { e.printStackTrace(); } return cadena; } /** * Categorizar TODAS las palabras de las primeras 10 líneas del archivo pasado por parámetro en un Map cuya llave es el * número de caracteres y el valor es el listado de palabras que tienen esa cantidad de caracteres * * Usa la constante REGEXP proveida al inicio de esta clase para hacer la separación de cadenas de texto a palabras. Es posible * que esta expresión retorne palabras vacías por lo que tendrás que adicionar un filtro que las remueva. * * @param archivo Ruta al archivo que se desea evaluar * @return Map cuya llave es la cantidad de caracteres y valor es el listado de palabras que tienen esa cantidad de * caracteres en las primeras 10 líneas del archivo * @see java.nio.file.Files * @see java.util.stream.Stream * @see java.lang.String * @see java.util.stream.Collectors */ public Map<Integer, List<String>> ejercicio4(Path archivo) { Map<Integer, List<String>> groupData = null; try { groupData = Files.lines(archivo) .limit(10) .map(l -> l.split(REGEXP)) .map(Arrays::stream) .flatMap(Function.identity()) .filter(w -> !w.isEmpty()) .collect(Collectors.groupingBy(String::length)); } catch (IOException e) { e.printStackTrace(); } return groupData; } /** * Categorizar TODAS las palabras de las primeras 100 líneas del archivo pasado por parámetro en un Map cuya llave es la * palabra y el valor es la cantidad de veces que se repite la palabra * <p/> * Usa la constante REGEXP proveida al inicio de esta clase para hacer la separación de cadenas de texto a palabras. Es posible * que esta expresión retorne palabras vacías por lo que tendrás que adicionar un filtro que las remueva. * * @param archivo Ruta al archivo que se desea evaluar * @return Map cuya llave son las palabras de las primeras 100 líneas del archivo y su valor es la cantidad de veces que se repite * dicha palabra en las primeras 100 líneas del archivo * @see java.nio.file.Files * @see java.util.stream.Stream * @see java.lang.String * @see java.util.stream.Collectors */ public Map<String, Long> ejercicio5(Path archivo) { Map<String, Long> groupData = null; try { groupData = Files.lines(archivo) .limit(100) .map(l -> l.split(REGEXP)) .flatMap(Arrays::stream) .filter(w -> !w.isEmpty()) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); }catch(Exception e) { e.printStackTrace(); } return groupData; } /** * Crear una doble agrupación de palabras únicas del archivo pasado por parámetro. Hacer la agrupación * en dos Maps. El Map externo tiene como llave la primera letra de la palabra en mayúsculas y como valor otro Map (el interno). * El Map interno debe tener como llave la cantidad de letras y como valor un listado de palabras que tienen esa cantidad * de letras. * <p/> * Por ejemplo, dadas las palabras "ermita sebastian sanisidro sancipriano cristorey chipichape" * El Map externo tendrá las llaves "E", "C", "S" * El valor para la llave "S" debe ser un Map con dos llaves: llave 9 y valor [sebastian sanisidro] (una lista de dos palabras) * y otra llave 11 con el valor [sancipriano] (una lista de un solo item) * <p/> * Usa la constante REGEXP proveida al inicio de esta clase para hacer la separación de cadenas de texto a palabras. Es posible * que esta expresión retorne palabras vacías por lo que tendrás que adicionar un filtro que las remueva. * Pista: Pasa las palabras a minúsculas para que el méotodo distinct las pueda filtrar correctamente * * @param archivo Ruta al archivo que se desea evaluar * @return Map cuya llave es la primera letra en mayúsculas de las palabras del archivo y su valor es otro Map cuya llave es la * cantidad de letras y su valor es el listado de palabras que tienen esa cantidad de letras * @see java.nio.file.Files * @see java.util.stream.Stream * @see java.lang.String * @see java.util.stream.Collectors */ public Map<String, Map<Integer, List<String>>> ejercicio6(Path archivo) { Map<String, Map<Integer, List<String>>> groupData = null; try { groupData = Files.lines(archivo) .limit(100) .map(l -> l.split(REGEXP)) .flatMap(Arrays::stream) .filter(w -> !w.isEmpty()) .distinct() .map(String::toLowerCase) .peek(System.out::println) .collect(Collectors.groupingBy(groupByInitialWordMayus, Collectors.groupingBy(String::length ))); }catch(Exception e) { e.printStackTrace(); } return groupData; } Function<String, String> groupByInitialWordMayus = x -> x.substring(0, 1).toUpperCase(); }
/* * 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 soruIslemleri; import javax.swing.JOptionPane; import java.sql.*; /** * * @author Murat */ public class SoruDuzenlemeEkrani extends javax.swing.JFrame { /** * Creates new form SoruDuzenleme */ public SoruDuzenlemeEkrani() { initComponents(); tabloGuncelle(); } public void soruSil(String ID){ try { veritabani.VeriTabani vb = new veritabani.VeriTabani(); Statement s = vb.baglantiAc(); String sql ="DELETE FROM \"SYSTEM\".\"SORULAR\" WHERE SORULAR_ID ="+ID; s.executeUpdate(sql); vb.baglantiKapa(); tabloGuncelle(); temizle(); } catch (Exception e) { } } public void tabloGuncelle(){ try { veritabani.VeriTabani vb = new veritabani.VeriTabani(); Statement s = vb.baglantiAc(); String sql ="SELECT * FROM \"SYSTEM\".\"SORULAR\""; ResultSet rs = s.executeQuery(sql); SorularTabloModeli model = new SorularTabloModeli(rs); tablo.setModel(model); vb.baglantiKapa(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } } public void temizle(){ dersAdiCb.setSelectedIndex(0); soruTipiCb.setSelectedIndex(0); soruTxA.setText(""); cevapTxA.setText(""); soruPuaniTf.setText(""); zorlukCb.setSelectedIndex(0); } public void guncelle(String dersAdi, String soruTipi, String soru, String dogruCevap, String puan, String zorluk, String soruID){ try { String sql ="UPDATE \"SYSTEM\".\"SORULAR\" SET " + "DERS_ADI = '"+dersAdi+"', " + "SORU_TIPI = '"+soruTipi+"', " + "SORU = '"+soru+"', " + "DOGRU_CEVAP = '"+dogruCevap+"', " + "PUAN = "+puan+", " + "ZORLUK = '"+zorluk+"' WHERE SORULAR_ID = "+soruID; veritabani.VeriTabani vb = new veritabani.VeriTabani(); Statement s = vb.baglantiAc(); ResultSet rs = s.executeQuery(sql); vb.baglantiKapa(); tabloGuncelle(); temizle(); JOptionPane.showMessageDialog(null, "Güncelleme Başarılı!"); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Güncelleme Hatası\n"+e); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); tablo = new javax.swing.JTable(); cikisBt = new javax.swing.JButton(); geriDonBt = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); zorlukCb = new javax.swing.JComboBox<>(); dersAdiCb = new javax.swing.JComboBox<>(); soruTipiCb = new javax.swing.JComboBox<>(); soruPuaniTf = new javax.swing.JTextField(); jSeparator2 = new javax.swing.JSeparator(); jLabel1 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); soruTxA = new javax.swing.JTextArea(); jLabel2 = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); cevapTxA = new javax.swing.JTextArea(); güncelleBt = new javax.swing.JButton(); temizleBt = new javax.swing.JButton(); ekleBt = new javax.swing.JButton(); silBt = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); tablo.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {}, {}, {}, {} }, new String [] { } )); tablo.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { tabloMousePressed(evt); } }); jScrollPane1.setViewportView(tablo); cikisBt.setText("Çıkış"); cikisBt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cikisBtActionPerformed(evt); } }); geriDonBt.setText("Geri Dön"); geriDonBt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { geriDonBtActionPerformed(evt); } }); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Soru Düzenleme"))); jLabel6.setText("Ders Adı :"); jLabel8.setText("Soru Tipi :"); jLabel9.setText("Zorluk Derecesi :"); jLabel10.setText("Soru Puanı :"); zorlukCb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "--Zorluk Derecesi Seçiniz--", "Kolay", "Orta", "Zor" })); dersAdiCb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "--Ders Seçiniz--", "Tasarım Desenleri", "Hesaplama Kuramı", "İşletim Sistemleri", "Veri Yapıları", "Bilgisayar Mimarisi", "İnternet Programlama", "Grafik Tasarım" })); soruTipiCb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "--Soru Tipi Seçiniz--", "Çoktan Seçmeli (A B C D E)", "Doğru Yanlış (D/Y)", "Klasik" })); jLabel1.setText("Soru :"); soruTxA.setColumns(20); soruTxA.setRows(5); jScrollPane2.setViewportView(soruTxA); jLabel2.setText("Cevap :"); cevapTxA.setColumns(20); cevapTxA.setRows(5); jScrollPane3.setViewportView(cevapTxA); güncelleBt.setText("Güncelle"); güncelleBt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { güncelleBtActionPerformed(evt); } }); temizleBt.setText("Temizle"); temizleBt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { temizleBtActionPerformed(evt); } }); ekleBt.setText("Ekle"); ekleBt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ekleBtActionPerformed(evt); } }); silBt.setText("Sil"); silBt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { silBtActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator2) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel6) .addGap(72, 72, 72) .addComponent(dersAdiCb, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel8) .addGap(70, 70, 70)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jLabel9) .addGap(32, 32, 32))) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(zorlukCb, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(soruTipiCb, 0, 200, Short.MAX_VALUE) .addComponent(soruPuaniTf)))) .addComponent(jLabel10)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(silBt, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(ekleBt, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(güncelleBt, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(48, 48, 48) .addComponent(temizleBt, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE)))) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(dersAdiCb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(soruTipiCb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(zorlukCb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(soruPuaniTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(19, 19, 19) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(güncelleBt) .addComponent(temizleBt)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(silBt) .addComponent(ekleBt)) .addGap(32, 32, 32)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(geriDonBt, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cikisBt, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 561, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cikisBt, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(geriDonBt, javax.swing.GroupLayout.Alignment.TRAILING)) .addContainerGap()) ); setSize(new java.awt.Dimension(989, 656)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void geriDonBtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_geriDonBtActionPerformed this.dispose(); new GUI.AnaEkran().setVisible(true); }//GEN-LAST:event_geriDonBtActionPerformed private void cikisBtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cikisBtActionPerformed System.exit(0); }//GEN-LAST:event_cikisBtActionPerformed private void ekleBtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ekleBtActionPerformed veritabani.SoruEkle se = new veritabani.SoruEkle(dersAdiCb.getSelectedItem().toString(), soruTipiCb.getSelectedItem().toString(), soruTxA.getText(), cevapTxA.getText(), soruPuaniTf.getText(), zorlukCb.getSelectedItem().toString()); try { se.soruEkleme(se); tabloGuncelle(); temizle(); JOptionPane.showMessageDialog(null, "Soru Eklendi.."); } catch (Exception e) { JOptionPane.showMessageDialog(null, "HATA"+e); } }//GEN-LAST:event_ekleBtActionPerformed private void silBtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_silBtActionPerformed // Object valueAt = tablo.getValueAt(tablo.getSelectedRow(), 6); soruSil(tablo.getValueAt(tablo.getSelectedRow(), 6).toString()); }//GEN-LAST:event_silBtActionPerformed private void güncelleBtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_güncelleBtActionPerformed Object valueAt = tablo.getValueAt(tablo.getSelectedRow(), 6); guncelle(dersAdiCb.getSelectedItem().toString(), soruTipiCb.getSelectedItem().toString(), soruTxA.getText(), cevapTxA.getText(), soruPuaniTf.getText(), zorlukCb.getSelectedItem().toString(), tablo.getValueAt(tablo.getSelectedRow(), 6).toString()); }//GEN-LAST:event_güncelleBtActionPerformed private void temizleBtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_temizleBtActionPerformed temizle(); }//GEN-LAST:event_temizleBtActionPerformed private void tabloMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabloMousePressed dersAdiCb.setSelectedItem(tablo.getValueAt(tablo.getSelectedRow(), 0)); soruTipiCb.setSelectedItem(tablo.getValueAt(tablo.getSelectedRow(), 1)); zorlukCb.setSelectedItem(tablo.getValueAt(tablo.getSelectedRow(), 5)); soruPuaniTf.setText(tablo.getValueAt(tablo.getSelectedRow(), 4).toString()); soruTxA.setText(tablo.getValueAt(tablo.getSelectedRow(), 2).toString()); cevapTxA.setText(tablo.getValueAt(tablo.getSelectedRow(), 3).toString()); }//GEN-LAST:event_tabloMousePressed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(SoruDuzenlemeEkrani.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(SoruDuzenlemeEkrani.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(SoruDuzenlemeEkrani.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(SoruDuzenlemeEkrani.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new SoruDuzenlemeEkrani().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextArea cevapTxA; private javax.swing.JButton cikisBt; private javax.swing.JComboBox<String> dersAdiCb; private javax.swing.JButton ekleBt; private javax.swing.JButton geriDonBt; private javax.swing.JButton güncelleBt; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JSeparator jSeparator2; private javax.swing.JButton silBt; private javax.swing.JTextField soruPuaniTf; private javax.swing.JComboBox<String> soruTipiCb; private javax.swing.JTextArea soruTxA; private javax.swing.JTable tablo; private javax.swing.JButton temizleBt; private javax.swing.JComboBox<String> zorlukCb; // End of variables declaration//GEN-END:variables }
package buffered; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.channels.SeekableByteChannel; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Iterator; import org.junit.Test; public class TestClass { // Files工具类的使用:操作文件或目录的工具类 public class FilesTest { @Test public void test1() throws IOException { Path path1 = Paths.get("d:\\nio", "hello.txt"); Path path2 = Paths.get("atguigu.txt"); // Path copy(Path src, Path dest, CopyOption … how) : 文件的复制 // 要想复制成功,要求path1对应的物理上的文件存在。path1对应的文件没有要求。 // Files.copy(path1, path2, StandardCopyOption.REPLACE_EXISTING); // Path createDirectory(Path path, FileAttribute<?> … attr) : 创建一个目录 // 要想执行成功,要求path对应的物理上的文件目录不存在。一旦存在,抛出异常。 Path path3 = Paths.get("d:\\nio\\nio1"); // Files.createDirectory(path3); // Path createFile(Path path, FileAttribute<?> … arr) : 创建一个文件 // 要想执行成功,要求path对应的物理上的文件不存在。一旦存在,抛出异常。 Path path4 = Paths.get("d:\\nio\\hi.txt"); // Files.createFile(path4); // void delete(Path path) : 删除一个文件/目录,如果不存在,执行报错 // Files.delete(path4); // void deleteIfExists(Path path) : // Path对应的文件/目录如果存在,执行删除.如果不存在,正常执行结束 Files.deleteIfExists(path3); // Path move(Path src, Path dest, CopyOption…how) : 将 src 移动到 dest // 位置 // 要想执行成功,src对应的物理上的文件需要存在,dest对应的文件没有要求。 // Files.move(path1, path2, StandardCopyOption.ATOMIC_MOVE); // long size(Path path) : 返回 path 指定文件的大小 long size = Files.size(path2); System.out.println(size); } @Test public void test2() throws IOException { Path path1 = Paths.get("d:\\nio", "hello.txt"); Path path2 = Paths.get("atguigu.txt"); // boolean exists(Path path, LinkOption … opts) : 判断文件是否存在 System.out.println(Files.exists(path2, LinkOption.NOFOLLOW_LINKS)); // boolean isDirectory(Path path, LinkOption … opts) : 判断是否是目录 // 不要求此path对应的物理文件存在。 System.out.println(Files.isDirectory(path1, LinkOption.NOFOLLOW_LINKS)); // boolean isRegularFile(Path path, LinkOption … opts) : 判断是否是文件 // boolean isHidden(Path path) : 判断是否是隐藏文件 // 要求此path对应的物理上的文件需要存在。才可判断是否隐藏。否则,抛异常。 // System.out.println(Files.isHidden(path1)); // boolean isReadable(Path path) : 判断文件是否可读 System.out.println(Files.isReadable(path1)); // boolean isWritable(Path path) : 判断文件是否可写 System.out.println(Files.isWritable(path1)); // boolean notExists(Path path, LinkOption … opts) : 判断文件是否不存在 System.out.println(Files.notExists(path1, LinkOption.NOFOLLOW_LINKS)); } /* * StandardOpenOption.READ:表示对应的Channel是可读的。 * StandardOpenOption.WRITE:表示对应的Channel是可写的。 * StandardOpenOption.CREATE:如果要写出的文件不存在,则创建。如果存在,忽略 * StandardOpenOption.CREATE_NEW:如果要写出的文件不存在,则创建。如果存在,抛异常 */ @Test public void test3() throws IOException { Path path1 = Paths.get("d:\\nio", "hello.txt"); // InputStream newInputStream(Path path, OpenOption…how):获取 // InputStream 对象 InputStream inputStream = Files.newInputStream(path1, StandardOpenOption.READ); // OutputStream newOutputStream(Path path, OpenOption…how) : 获取 // OutputStream 对象 OutputStream outputStream = Files.newOutputStream(path1, StandardOpenOption.WRITE, StandardOpenOption.CREATE); // SeekableByteChannel newByteChannel(Path path, OpenOption…how) : // 获取与指定文件的连接,how 指定打开方式。 SeekableByteChannel channel = Files.newByteChannel(path1, StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); // DirectoryStream<Path> newDirectoryStream(Path path) : 打开 path // 指定的目录 Path path2 = Paths.get("e:\\teach"); DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path2); Iterator<Path> iterator = directoryStream.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } } } /* * 1. jdk 7.0 时,引入了 Path、Paths、Files三个类。 * 2.此三个类声明在:java.nio.file包下。 * 3.Path可以看做是java.io.File类的升级版本。也可以表示文件或文件目录,与平台无关 * 4.如何实例化Path:使用Paths. static Path get(String first, String … more) : * 用于将多个字符串串连成路径 static Path get(URI uri): 返回指定uri对应的Path路径 */ class PathTest { // 如何使用Paths实例化Path @Test public void test1() { Path path1 = Paths.get("d:\\nio\\hello.txt");// new File(String // filepath) Path path2 = Paths.get("d:\\", "nio\\hello.txt");// new File(String // parent,String // filename); System.out.println(path1); System.out.println(path2); Path path3 = Paths.get("d:\\", "nio"); System.out.println(path3); } // Path中的常用方法 @Test public void test2() { Path path1 = Paths.get("d:\\", "nio\\nio1\\nio2\\hello.txt"); Path path2 = Paths.get("hello.txt"); // String toString() : 返回调用 Path 对象的字符串表示形式 System.out.println(path1); // boolean startsWith(String path) : 判断是否以 path 路径开始 System.out.println(path1.startsWith("d:\\nio")); // boolean endsWith(String path) : 判断是否以 path 路径结束 System.out.println(path1.endsWith("hello.txt")); // boolean isAbsolute() : 判断是否是绝对路径 System.out.println(path1.isAbsolute() + "~"); System.out.println(path2.isAbsolute() + "~"); // Path getParent() :返回Path对象包含整个路径,不包含 Path 对象指定的文件路径 System.out.println(path1.getParent()); System.out.println(path2.getParent()); // Path getRoot() :返回调用 Path 对象的根路径 System.out.println(path1.getRoot()); System.out.println(path2.getRoot()); // Path getFileName() : 返回与调用 Path 对象关联的文件名 System.out.println(path1.getFileName() + "~"); System.out.println(path2.getFileName() + "~"); // int getNameCount() : 返回Path 根目录后面元素的数量 // Path getName(int idx) : 返回指定索引位置 idx 的路径名称 for (int i = 0; i < path1.getNameCount(); i++) { System.out.println(path1.getName(i) + "*****"); } // Path toAbsolutePath() : 作为绝对路径返回调用 Path 对象 System.out.println(path1.toAbsolutePath()); System.out.println(path2.toAbsolutePath()); // Path resolve(Path p) :合并两个路径,返回合并后的路径对应的Path对象 Path path3 = Paths.get("d:\\", "nio"); Path path4 = Paths.get("nioo\\hi.txt"); path3 = path3.resolve(path4); System.out.println(path3); // File toFile(): 将Path转化为File类的对象 File file = path1.toFile();// Path--->File的转换 Path newPath = file.toPath();// File--->Path的转换 } }
package javax.vecmath; class VecMathUtil { static final long hashLongBits(long hash, long l) { hash *= 31L; return hash + l; } static final long hashFloatBits(long hash, float f) { hash *= 31L; if (f == 0.0F) return hash; return hash + Float.floatToIntBits(f); } static final long hashDoubleBits(long hash, double d) { hash *= 31L; if (d == 0.0D) return hash; return hash + Double.doubleToLongBits(d); } static final int hashFinish(long hash) { return (int)(hash ^ hash >> 32L); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\javax\vecmath\VecMathUtil.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package main.serv; import main.EntityNotFoundException; import main.models.Todo; import java.util.List; public interface TaskService { long addTodo(Todo todo); Todo getTodo(long todoId) throws EntityNotFoundException; String deleteTodo(long todoId) throws EntityNotFoundException; String updateTodo(long todoId, Todo todo) throws EntityNotFoundException; String deleteAllTodo(); List<Todo> getListOfItems(); }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final import java.util.Date; /** * TChangeDetail generated by hbm2java */ public class TChangeDetail implements java.io.Serializable { private TChangeDetailId id; private TChangeHeader TChangeHeader; private String creator; private Date createtime; private String notes; private Date newlatefinish; private Long newdueqty; private String taskuid; private String changereason; public TChangeDetail() { } public TChangeDetail(TChangeDetailId id, TChangeHeader TChangeHeader) { this.id = id; this.TChangeHeader = TChangeHeader; } public TChangeDetail(TChangeDetailId id, TChangeHeader TChangeHeader, String creator, Date createtime, String notes, Date newlatefinish, Long newdueqty, String taskuid, String changereason) { this.id = id; this.TChangeHeader = TChangeHeader; this.creator = creator; this.createtime = createtime; this.notes = notes; this.newlatefinish = newlatefinish; this.newdueqty = newdueqty; this.taskuid = taskuid; this.changereason = changereason; } public TChangeDetailId getId() { return this.id; } public void setId(TChangeDetailId id) { this.id = id; } public TChangeHeader getTChangeHeader() { return this.TChangeHeader; } public void setTChangeHeader(TChangeHeader TChangeHeader) { this.TChangeHeader = TChangeHeader; } public String getCreator() { return this.creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreatetime() { return this.createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } public String getNotes() { return this.notes; } public void setNotes(String notes) { this.notes = notes; } public Date getNewlatefinish() { return this.newlatefinish; } public void setNewlatefinish(Date newlatefinish) { this.newlatefinish = newlatefinish; } public Long getNewdueqty() { return this.newdueqty; } public void setNewdueqty(Long newdueqty) { this.newdueqty = newdueqty; } public String getTaskuid() { return this.taskuid; } public void setTaskuid(String taskuid) { this.taskuid = taskuid; } public String getChangereason() { return this.changereason; } public void setChangereason(String changereason) { this.changereason = changereason; } }
import java.awt.*; import java.util.ArrayList; import java.util.Optional; /** * Class that handles drawing of the ultimate tic-tac-toe board * @author Andy Burris and Kevin Harris * @version 4 May 2020 */ public class BoardDrawer { private static int LINE_WIDTH = 10; public Board board; private int size; private ArrayList<SubBoardDrawer> subBoardDrawers = new ArrayList<>(); public BoardDrawer(Board board, int size) { this.board = board; this.size = size; for (int row = 0; row < board.spaces.length; row++) { for (int col = 0; col < board.spaces[row].length; col++) { SubBoard subBoard = board.spaces[row][col]; int x = row * (size / 3); int y = col * (size / 3); SubBoardDrawer drawer = new SubBoardDrawer(subBoard, x, y, size / 3); System.out.println("creating drawer at x = " + x + ", y = " + y); subBoardDrawers.add(drawer); } } } /** * Method to handle click on the board, delegate it to the click handler in the correct SubBoardDrawer * @param x absolute x position of mouse click * @param y absolute y position of mouse click * @param symbol char representing player who clicked (either 'x' or 'o') * @return true if click was successfully handled, false otherwise(e.g. if click was on an already filled square or board) */ public boolean handleClick(int x, int y, char symbol) { if(board.isWon() != ' '){ return false; } Optional<SubBoardDrawer> handler = subBoardDrawers.stream() .filter(d -> !d.subBoard.isWon().hasWinner() && d.canHandleClick(x, y)) .findFirst(); if(!handler.isPresent()){ return false; } else { return handler.get().handleClick(x, y, symbol); } } /** * Method that handles drawing of board, and draws all subboards through their respective drawers. * @param g Graphics2D context to draw on */ public void draw(Graphics2D g) { drawBoard(g); subBoardDrawers.forEach(d -> d.draw(g)); } /** * Method that draws lines of ultimate tic-tac-toe board * @param g Graphics2D context to draw on */ private void drawBoard(Graphics2D g) { g.setColor(Color.GRAY); int lineOffset = (LINE_WIDTH * 2 / 3); int oneThirdPosition = (size / 3) - lineOffset; int twoThirdsPosition = (size * 2 / 3) - lineOffset; g.fillRect(oneThirdPosition, 0, LINE_WIDTH, size); g.fillRect(twoThirdsPosition, 0, LINE_WIDTH, size); g.fillRect(0, oneThirdPosition, size, LINE_WIDTH); g.fillRect(0, twoThirdsPosition, size, LINE_WIDTH); } }
package com.example.newbies.desktopappweight; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; /** * * @author NewBies * @date 2018/fourth/seventh */ public class ConfigActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); } }
package com.fleet.xml.entity; import java.io.Serializable; import java.util.List; public class Protocol implements Serializable { private static final long serialVersionUID = 1L; /** * 数据名称 */ private String name; /** * 数据标识 */ private String identifier; /** * 数据单位 */ private String unit; /** * 数据类型(1:字符,2:数值,3:浮点) */ private Integer type; /** * 数据长度 */ private Integer length; /** * 保留字(0:否,1:是) */ private Integer reservedWord; /** * 备注 */ private String remark; /** * 属性值 */ private List<Property> propertyList; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getLength() { return length; } public void setLength(Integer length) { this.length = length; } public Integer getReservedWord() { return reservedWord; } public void setReservedWord(Integer reservedWord) { this.reservedWord = reservedWord; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public List<Property> getPropertyList() { return propertyList; } public void setPropertyList(List<Property> propertyList) { this.propertyList = propertyList; } }
package io.rudin.electricity.tariff.swiss.data.holiday; public class Holiday { private int year, month, day; private HolidayType type; public enum HolidayType { SATURDAY, SUNDAY } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } public HolidayType getType() { return type; } public void setType(HolidayType type) { this.type = type; } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.commerceservices.order.dao.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import de.hybris.bootstrap.annotations.IntegrationTest; import de.hybris.platform.basecommerce.util.BaseCommerceBaseTest; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.order.QuoteService; import de.hybris.platform.servicelayer.user.UserService; import javax.annotation.Resource; import org.junit.Before; import org.junit.Test; /** * JUnit test suite for {@link DefaultCommerceOrderDao} */ @IntegrationTest public class DefaultCommerceOrderDaoTest extends BaseCommerceBaseTest { private static final String TEST_QUOTE_CODE_1 = "testQuote1"; private static final String TEST_QUOTE_CODE_2 = "testQuote2"; private static final String TEST_QUOTE_CODE_3 = "testQuote3"; @Resource private DefaultCommerceOrderDao defaultCommerceOrderDao; @Resource private UserService userService; @Resource private QuoteService quoteService; @Before public void setUp() throws Exception { createCoreData(); createDefaultCatalog(); // importing test csv importCsv("/commerceservices/test/testQuoteOrders.impex", "utf-8"); userService.setCurrentUser(userService.getUserForUID("orderhistoryuser@test.com")); } @Test public void shouldFindOrderForQuote() { final OrderModel order = defaultCommerceOrderDao.findOrderByQuote(quoteService.getCurrentQuoteForCode(TEST_QUOTE_CODE_1)); assertNotNull("order should not be null", order); assertNotNull("quote reference for order should not be null", order.getQuoteReference()); assertEquals("quote code doesnt match for passed quote & order.quoteReference", TEST_QUOTE_CODE_1, order.getQuoteReference().getCode()); } @Test public void shouldNotFindOrderWhenSameQuoteHasReferenceToMultipleOrders() { final OrderModel order = defaultCommerceOrderDao.findOrderByQuote(quoteService.getCurrentQuoteForCode(TEST_QUOTE_CODE_2)); assertNull("order should be null", order); } @Test public void shouldNotFindOrderForQuoteWithNoQuoteReference() { final OrderModel order = defaultCommerceOrderDao.findOrderByQuote(quoteService.getCurrentQuoteForCode(TEST_QUOTE_CODE_3)); assertNull("order should be null", order); } }
package au.com.autogeneral.testAPI.controller; import au.com.autogeneral.testAPI.domain.ToDo; import au.com.autogeneral.testAPI.model.*; import au.com.autogeneral.testAPI.service.ToDoService; import io.swagger.annotations.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.MimeTypeUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; @RestController @Api(value = "todo", description = "the todo API") @Validated public class TodoApiController { private ToDoService toDoService; @Autowired public TodoApiController(ToDoService toDoService) { this.toDoService = toDoService; } @ApiOperation(value = "Retrieve a specific item by id", nickname = "todoIdGet", notes = "", response = ToDoItem.class, tags = {"todo",}) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = ToDoItem.class), @ApiResponse(code = 400, message = "Validation error", response = ToDoItemValidationError.class), @ApiResponse(code = 404, message = "Not Found Error", response = ToDoItemNotFoundError.class)}) @RequestMapping(value = "/todo/{id}", produces = {MimeTypeUtils.APPLICATION_JSON_VALUE}, method = RequestMethod.GET) public ResponseEntity todoIdGet( HttpServletRequest request, @ApiParam(value = "id", required = true) @PathVariable("id") Long id) { String accept = request.getHeader(HttpHeaders.ACCEPT); if (accept != null && accept.contains(MimeTypeUtils.APPLICATION_JSON_VALUE)) { return toDoService.findToDo(id).map(this::toDo2Item).<ResponseEntity>map(ResponseEntity::ok) .orElse(ResponseEntity.status(HttpStatus.NOT_FOUND).body(getNotFoundError(id))); } return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } private ToDoItemNotFoundError getNotFoundError(Long id) { return new ToDoItemNotFoundError() .name("NotFoundError") .addDetailsItem(new ToDoItemNotFoundErrorDetails().message("Item with id " + id + " not found")); } @ApiOperation(value = "Modify an item", nickname = "todoIdPatch", notes = "", response = ToDoItem.class, tags = {"todo",}) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = ToDoItem.class), @ApiResponse(code = 400, message = "Validation error", response = ToDoItemValidationError.class), @ApiResponse(code = 404, message = "Not Found Error", response = ToDoItemNotFoundError.class)}) @RequestMapping(value = "/todo/{id}", produces = {MimeTypeUtils.APPLICATION_JSON_VALUE}, consumes = {MimeTypeUtils.APPLICATION_JSON_VALUE}, method = RequestMethod.PATCH) public ResponseEntity todoIdPatch( HttpServletRequest request, @ApiParam(value = "id", required = true) @PathVariable("id") Long id, @ApiParam(value = "", required = true) @Valid @RequestBody ToDoItemUpdateRequest body) { String accept = request.getHeader(HttpHeaders.ACCEPT); if (accept != null && accept.contains(MimeTypeUtils.APPLICATION_JSON_VALUE)) { return toDoService.updateToDo(id, body.getText(), body.isIsCompleted()) .map(this::toDo2Item).<ResponseEntity>map(ResponseEntity::ok) .orElse(ResponseEntity.status(HttpStatus.NOT_FOUND).body(getNotFoundError(id))); } return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @ApiOperation(value = "Create a to do item", nickname = "todoPost", notes = "", response = ToDoItem.class, tags = {"todo",}) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = ToDoItem.class), @ApiResponse(code = 400, message = "Validation error", response = ToDoItemValidationError.class)}) @RequestMapping(value = "/todo", produces = {MimeTypeUtils.APPLICATION_JSON_VALUE}, consumes = {MimeTypeUtils.APPLICATION_JSON_VALUE}, method = RequestMethod.POST) public ResponseEntity<ToDoItem> todoPost( HttpServletRequest request, @ApiParam(value = "", required = true) @Valid @RequestBody ToDoItemAddRequest body) { String accept = request.getHeader(HttpHeaders.ACCEPT); if (accept != null && accept.contains(MimeTypeUtils.APPLICATION_JSON_VALUE)) { ToDo toDo = toDoService.createToDo(body.getText()); return ResponseEntity.ok(toDo2Item(toDo)); } return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * Copy domain object values to a model object. * For this reason model and domain entities could have been the same classes. But they are not. * * @param toDo * @return */ private ToDoItem toDo2Item(ToDo toDo) { return new ToDoItem() .id(toDo.getId()) .createdAt(toDo.getCreatedAt()) .text(toDo.getText()) .isCompleted(toDo.isCompleted()); } }
package com.zznode.opentnms.isearch.otnRouteService.api.model; import javax.xml.bind.annotation.XmlType; @XmlType( propOrder = {"objectid","portname"}) public class CardUsedPtpInfo { private String objectid; private String portname; public String getObjectid() { return objectid; } public void setObjectid(String objectid) { this.objectid = objectid; } public String getPortname() { return portname; } public void setPortname(String portname) { this.portname = portname; } }
package jp.smartcompany.job.modules.quartz.manager.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import jp.smartcompany.job.modules.quartz.JobBean; import jp.smartcompany.job.modules.quartz.dao.ScheduleJobLogDao; import jp.smartcompany.job.modules.quartz.manager.ScheduleJobLogManager; import jp.smartcompany.job.modules.quartz.pojo.entity.ScheduleJobLogDO; import org.springframework.stereotype.Repository; /** * @author Xiao Wenpeng */ @Repository(JobBean.Manager.SCHEDULE_JOB_LOG) public class ScheduleJobLogManagerImpl extends ServiceImpl<ScheduleJobLogDao, ScheduleJobLogDO> implements ScheduleJobLogManager { }
public class ResourceManager { // ResourceManager Singleton instance private static ResourceManager INSTANCE; /* The variables listed should be kept public, allowing us easy access to them when creating new Sprites, Text objects and to play sound files */ public ITextureRegion mGameBackgroundTextureRegion; public ITextureRegion mMenuBackgroundTextureRegion; public Sound mSound; public Font mFont; ResourceManager(){ // The constructor is of no use to us } public synchronized static ResourceManager getInstance(){ if(INSTANCE == null){ INSTANCE = new ResourceManager(); } return INSTANCE; } /* Each scene within a game should have a loadTextures method as well * as an accompanying unloadTextures method. This way, we can display * a loading image during scene swapping, unload the first scene's textures * then load the next scenes textures. */ public synchronized void loadGameTextures(Engine pEngine, Context pContext){ // Set our game assets folder in "assets/gfx/game/" BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/game/"); BuildableBitmapTextureAtlas mBitmapTextureAtlas = new BuildableBitmapTextureAtlas(pEngine.getTextureManager(), 800, 480); mGameBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapTextureAtlas, pContext, "game_background.png"); try { mBitmapTextureAtlas.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 1, 1)); mBitmapTextureAtlas.load(); } catch (TextureAtlasBuilderException e) { Debug.e(e); } } /* All textures should have a method call for unloading once * they're no longer needed; ie. a level transition. */ public synchronized void unloadGameTextures(){ // call unload to remove the corresponding texture atlas from memory BuildableBitmapTextureAtlas mBitmapTextureAtlas = (BuildableBitmapTextureAtlas) mGameBackgroundTextureRegion.getTexture(); mBitmapTextureAtlas.unload(); // ... Continue to unload all textures related to the 'Game' scene // Once all textures have been unloaded, attempt to invoke the Garbage Collector System.gc(); } /* Similar to the loadGameTextures(...) method, except this method will be * used to load a different scene's textures */ public synchronized void loadMenuTextures(Engine pEngine, Context pContext){ // Set our menu assets folder in "assets/gfx/menu/" BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/menu/"); BuildableBitmapTextureAtlas mBitmapTextureAtlas = new BuildableBitmapTextureAtlas(pEngine.getTextureManager() ,800 , 480); mMenuBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapTextureAtlas, pContext, "menu_background.png"); try { mBitmapTextureAtlas.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 1, 1)); mBitmapTextureAtlas.load(); } catch (TextureAtlasBuilderException e) { Debug.e(e); } } // Once again, this method is similar to the 'Game' scene's for unloading public synchronized void unloadMenuTextures(){ // call unload to remove the corresponding texture atlas from memory BuildableBitmapTextureAtlas mBitmapTextureAtlas = (BuildableBitmapTextureAtlas) mMenuBackgroundTextureRegion.getTexture(); mBitmapTextureAtlas.unload(); // ... Continue to unload all textures related to the 'Game' scene // Once all textures have been unloaded, attempt to invoke the Garbage Collector System.gc(); } /* As with textures, we can create methods to load sound/music objects * for different scene's within our games. */ public synchronized void loadSounds(Engine pEngine, Context pContext){ // Set the SoundFactory's base path SoundFactory.setAssetBasePath("sounds/"); try { // Create mSound object via SoundFactory class mSound = SoundFactory.createSoundFromAsset(pEngine.getSoundManager(), pContext, "sound.mp3"); } catch (final IOException e) { Log.v("Sounds Load","Exception:" + e.getMessage()); } } /* In some cases, we may only load one set of sounds throughout * our entire game's life-cycle. If that's the case, we may not * need to include an unloadSounds() method. Of course, this all * depends on how much variance we have in terms of sound */ public synchronized void unloadSounds(){ // we call the release() method on sounds to remove them from memory if(!mSound.isReleased())mSound.release(); } /* Lastly, we've got the loadFonts method which, once again, * tends to only need to be loaded once as Font's are generally * used across an entire game, from menu to shop to game-play. */ public synchronized void loadFonts(Engine pEngine){ FontFactory.setAssetBasePath("fonts/"); // Create mFont object via FontFactory class mFont = FontFactory.create(pEngine.getFontManager(), pEngine.getTextureManager(), 256, 256, Typeface.create(Typeface.DEFAULT, Typeface.NORMAL), 32f, true, org.andengine.util.adt.color.Color.WHITE_ABGR_PACKED_INT); mFont.load(); } /* If an unloadFonts() method is necessary, we can provide one */ public synchronized void unloadFonts(){ // Similar to textures, we can call unload() to destroy font resources mFont.unload(); } }
package services; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import javax.sql.rowset.CachedRowSet; import model.Report; import model.ReportFilter; import org.hibernate.HibernateException; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.transform.AliasToEntityMapResultTransformer; import util.ConnectionUtil; import util.DateUtil; import com.sun.rowset.CachedRowSetImpl; import db.HibernateUtil; public class ReportService { public static List<Map<String, String>> getReportParm(Boolean isAll, String docType) { List<Map<String,String>> result = null; Session s = HibernateUtil.getSessionFactory().openSession(); SQLQuery q = s.createSQLQuery("exec SPE_ReportParm " + "@Isall= :isAll, " + "@Doctype= :docType"); q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE); q.setBoolean("isAll", isAll); q.setString("docType", docType); try { result = new ArrayList<Map<String,String>>(); result = q.list(); } catch (HibernateException e) { e.printStackTrace(); } finally { s.close(); } return result; } public static List<Map<String, String>> getReportParmDet(String reportId) { List<Map<String,String>> result = null; Session s = HibernateUtil.getSessionFactory().openSession(); SQLQuery q = s.createSQLQuery("exec SPE_ReportParmDet " + "@ReportId= :reportId "); q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE); q.setString("reportId", reportId); try { result = new ArrayList<Map<String,String>>(); result = q.list(); } catch (HibernateException e) { e.printStackTrace(); } finally { s.close(); } return result; } public static String getEmpForReportFilter(String query, String empNo) { Session s = HibernateUtil.getSessionFactory().openSession(); String result = ""; query += " where Empno= '"+ empNo +"'"; SQLQuery q = s.createSQLQuery(query); q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE); try{ Map<String, String> map = (Map<String, String>) q.list().get(0); result = map.get("Empno"); } catch (Exception e){ e.printStackTrace(); } finally{ s.close(); } return result; } public static List<Object[]> getReportQueryResult(String query) { List<Object[]> result = null; Session s = HibernateUtil.getSessionFactory().openSession(); SQLQuery q = s.createSQLQuery(query); try { result = new ArrayList<Object[]>(); result = q.list(); } catch (HibernateException e) { e.printStackTrace(); } finally { s.close(); } return result; } public static List<CachedRowSet> getCachedRowSetForReportData(Report r){ List<CachedRowSet> listCr = new ArrayList<CachedRowSet>(); CachedRowSet cr = null; Connection con = null; int i = 1; try { String query = ""; con = ConnectionUtil.createConnection(); Statement s = con.createStatement(); ResultSet rsForQuery = s.executeQuery("select SQLQuery from G_ReportParm where ReportId='"+ r.reportId +"'"); // system.out.println("Executing Query: select SQLQuery from G_ReportParm where ReportId=?"); if(rsForQuery.next()){ query = rsForQuery.getString("SQLQuery"); } CallableStatement cs = con.prepareCall(query); int n = 0; for(ReportFilter rf: r.filters){ if(rf.from instanceof String){ // if(rf.type.equalsIgnoreCase("employee")){ // cs.setString(i++, (String) rf.from); // } // else{ // system.out.println("parm string " +i+ " from: " + rf.from); cs.setString(i++, (String) rf.from); // system.out.println("parm string " +i+ " to: " + rf.to); cs.setString(i++, (String) rf.to); // } } else if(rf.from instanceof Date){ // system.out.println("parm date " +n+ " from: " + rf.from); // system.out.println("parm date " +n+ " to: " + rf.to); cs.setDate(i++, DateUtil.getJavaSqlDateFromObject(rf.from)); cs.setDate(i++, DateUtil.getJavaSqlDateFromObject(rf.to)); } else if(rf.from instanceof Integer){ // system.out.println("parm Integer " +n+ " from: " + rf.from); // system.out.println("parm Integer " +n+ " to: " + rf.to); cs.setInt(i++, (Integer) rf.from); cs.setInt(i++, (Integer) rf.to); } n++; } // system.out.println("Executing query: " + query); Boolean result = cs.execute(); // system.out.println("Executing query: " + query + " result is: " + result); while (result){ cr = new CachedRowSetImpl(); ResultSet rs = cs.getResultSet(); cr.populate(rs); listCr.add(cr); rs.close(); result = cs.getMoreResults(); } } catch (SQLException e) { e.printStackTrace(); } finally{ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return listCr; } public static List<String> getTableNames(String reportId) { // TODO Auto-generated method stub List<String> result = new ArrayList<String>(); String tmp = ""; Connection con = null; try { con = ConnectionUtil.createConnection(); Statement s = con.createStatement(); ResultSet rs = s.executeQuery("select TableName from G_ReportParm where ReportId='"+ reportId +"'"); if(rs.next()){ tmp = rs.getString("TableName"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { con.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } String[] tmpArray = tmp.split(";"); for(String s: tmpArray){ result.add(s); } return result; } public static String getRptName(String reportId) { // TODO Auto-generated method stub List<String> result = new ArrayList<String>(); String tmp = ""; Connection con = null; try { con = ConnectionUtil.createConnection(); Statement s = con.createStatement(); ResultSet rs = s.executeQuery("select FileName from G_ReportParm where ReportId='"+ reportId +"'"); if(rs.next()){ tmp = rs.getString("FileName"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { con.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return tmp; } public static boolean getValidPrintReport(Report report) { List<CachedRowSet> tmp = getCachedRowSetForReportData(report); if(tmp == null || tmp.size() == 0){ return false; } ResultSet rs = null; try { rs = tmp.get(0).getOriginal(); if(!rs.next()){ return false; } } catch (Exception e) { e.printStackTrace(); return false; } finally{ try { rs.close(); } catch (Exception e) { // e.printStackTrace(); } } return true; } }
package src.br.com.alura.loja; import java.math.BigDecimal; import src.br.com.alura.loja.imposto.CalculadoraDeImpostos; import src.br.com.alura.loja.imposto.ISS; import src.br.com.alura.loja.orcamento.ItemOrcamento; import src.br.com.alura.loja.orcamento.Orcamento; public class TestesImposto { public static void main(String[] args) { Orcamento orcamento = new Orcamento(); orcamento.adicionarItem(new ItemOrcamento(new BigDecimal("100"))); CalculadoraDeImpostos calculadora = new CalculadoraDeImpostos(); System.out.println(calculadora.calcular(orcamento, new ISS(null))); } }
package edu.upenn.cit594.data; public class ZipCode { private int zipcode; private double population; private double totalParkingFinesAmount; private double totalParkingFinesAmount2; private double quantityOfParkingFines; private double averageParkingTicketCost; private double averageHouseMarketValue; public double getTotalMarketValueAmount() { return totalMarketValueAmount; } public void setTotalMarketValueAmount(double totalMarketValueAmount) { this.totalMarketValueAmount = totalMarketValueAmount; } private double totalMarketValueAmount; public double getFinesPerCapita() { return finesPerCapita; } public void setFinesPerCapita(double finesPerCapita) { this.finesPerCapita = finesPerCapita; } private double finesPerCapita; public double getMarketValuePerCapita() { return marketValuePerCapita; } public void setMarketValuePerCapita(double marketValuePerCapita) { this.marketValuePerCapita = marketValuePerCapita; } private double marketValuePerCapita; public ZipCode(int zipcode, double population) { this.population = population; this.zipcode = zipcode; } public int getZipcode() { return zipcode; } public double getPopulation() { return population; } public void setTotalParkingFinesAmount(double totalParkingFinesAmount) { this.totalParkingFinesAmount = totalParkingFinesAmount; } public double getTotalParkingFinesAmount() { return totalParkingFinesAmount; } public double getQuantityOfParkingFines() { return quantityOfParkingFines; } public void setQuantityOfParkingFines(double quantityOfParkingFines) { this.quantityOfParkingFines = quantityOfParkingFines; } public double getAverageParkingTicketCost() { return averageParkingTicketCost; } public void setAverageParkingTicketCost(double averageParkingTicketCost) { this.averageParkingTicketCost = averageParkingTicketCost; } public double getAverageHouseMarketValue() { return averageHouseMarketValue; } public void setAverageHouseMarketValue(double averageHouseMarketValue) { this.averageHouseMarketValue = averageHouseMarketValue; } public double getTotalParkingFinesAmount2() { return totalParkingFinesAmount2; } public void setTotalParkingFinesAmount2(double totalParkingFinesAmount2) { this.totalParkingFinesAmount2 = totalParkingFinesAmount2; } }
package uo.sdi.business.impl.task.command; import uo.sdi.business.exception.BusinessException; import uo.sdi.business.impl.util.CategoryCheck; import uo.sdi.infrastructure.Factories; import uo.sdi.model.Category; public class CreateCategoryCommand{ private Category category; public CreateCategoryCommand(Category category) { this.category = category; } public Category execute() throws BusinessException { CategoryCheck.nameIsNotNull(category); CategoryCheck.nameIsNotEmpty(category); CategoryCheck.userIsNotNull(category); CategoryCheck.isValidUser(category); CategoryCheck.isUniqueName(category); CategoryCheck.isNotForAdminUser(category); return Factories.persistence.getCategoryDao().save(category); } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.commercefacades.order; import de.hybris.platform.commercefacades.order.data.AbstractOrderData; import de.hybris.platform.core.enums.GroupType; import java.util.Collection; import java.util.List; import javax.annotation.Nonnull; /** * Manipulation with {@link EntryGroupData}. * * @see de.hybris.platform.order.EntryGroupService */ public interface CommerceEntryGroupUtils { /** * Flatten group tree and return it as a plain list of groups. * <p> * The method keeps item order unchanged: first goes root item, then its first child, then the children of that child * and so forth. * </p> * * @param root * node to start collecting from * @return list, that includes the node and all its descendants * @throws IllegalArgumentException * is root is null */ @Nonnull List<EntryGroupData> getNestedGroups(@Nonnull EntryGroupData root); /** * Returns all leaf nodes of group tree, preventing their natural order. * * @param root * root node of group tree * @return leaf nodes * @throws IllegalArgumentException * if {@code root} is null */ @Nonnull List<EntryGroupData> getLeaves(@Nonnull EntryGroupData root); /** * Returns {@link EntryGroupData} by groupNumber from given order * * @param groupNumber * number of the group to search for * @param order * order containing entry group trees * * @return {@link EntryGroupData} with given groupNumber from the order * @throws IllegalArgumentException * if no group with given groupNumber in the order * @throws IllegalArgumentException * if {@code order} is null * @throws IllegalArgumentException * if {@code order.rootGroups} is null * @throws IllegalArgumentException * if {@code groupNumber} is null */ @Nonnull EntryGroupData getGroup(@Nonnull AbstractOrderData order, @Nonnull Integer groupNumber); /** * Searches for entry group which is a type of {@code groupType} and which number belongs to the {@code groupNumbers}. * @param order * order what is expected to contain the desired group * @param groupNumbers * possible group numbers. Usually are taken from * {@link de.hybris.platform.commercefacades.order.data.OrderEntryData#getEntryGroupNumbers()} * @param groupType * desired group type * @return group * @throws IllegalArgumentException if group was not found or any of the args is invalid */ @Nonnull EntryGroupData getGroup(@Nonnull AbstractOrderData order, @Nonnull Collection<Integer> groupNumbers, @Nonnull GroupType groupType); /** * Returns max value of {@code EntryGroupData#groupNumber}. * * @param roots * root groups * @return maximum group number among the whole forest */ int findMaxGroupNumber(List<EntryGroupData> roots); }
package com.example.demo.entity.mail; import org.springframework.mail.javamail.MimeMessageHelper; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.persistence.Embeddable; import java.util.Properties; import java.util.regex.Pattern; @Embeddable public class SendMail { final String host = "smpt.gmail.com"; final String userSender = "0ozstarzo0@gmail.com"; final String password = "Foreverjo10061995"; private String msg = "<b>Gumi</b> say HELLO\""; private String receiverUserName = "tranbing88@gmail.com"; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getReceiverUserName() { return receiverUserName; } public void setReceiverUserName(String receiverUserName) { this.receiverUserName = receiverUserName; } public boolean isValidEmail(String email){ String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\." + "[a-zA-Z0-9_&*-]+)*@" + "(?:[a-zA-Z0-9-]+\\.)+[a-z" + "A-Z]{2,7}$"; Pattern pat = Pattern.compile(emailRegex); if (email == null){ return false; } return pat.matcher(email).matches(); } public void sendEmail() throws MessagingException { Properties proper = new Properties(); proper.put("mail.smtp.host",host); proper.put("mail.smtp.auth", "true"); proper.put("mail.smtp.starttls.enable", "true"); Session session = Session.getDefaultInstance(proper, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userSender,password); } }); MimeMessage message = new MimeMessage(session); MimeMessageHelper helper = new MimeMessageHelper(message); message.setFrom(new InternetAddress(userSender)); message.addRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress(receiverUserName)}); message.setSubject("Gumi"); message.setText(msg,"utf-8","html"); Transport.send(message); } }
package de.jmda.fx.cdi; import javax.enterprise.event.Event; import javax.enterprise.event.Observes; import javax.inject.Inject; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javafx.fxml.FXML; import javafx.scene.control.Button; //@Singleton public class FXViewSampleController implements FXViewSampleService { private final static Logger LOGGER = LogManager.getLogger(FXViewSampleController.class); @FXML private Button btn; @Inject private Event<FXViewSampleEventData> event; private FXViewSampleController() { LOGGER.debug("controller constructor: " + getClass().getName()); } @FXML private void initialize() { LOGGER.debug( "\nnull == btn : " + (null == btn) + "\nnull == event: " + (null == event)); btn.setOnAction ( e -> { LOGGER.debug("btn clicked action, firing event ..."); event.fire(new FXViewSampleEventData()); } ); } @SuppressWarnings("unused") private void eventReceiver(@Observes FXViewSampleEventData data) { LOGGER.debug( "received event data" + "\nnull == btn : " + (null == btn) + "\nnull == event: " + (null == event)); } @Override public void setButtonText(String text) { btn.setText(text); } }
package com.niit.dao; import java.util.List; import com.niit.model.Job; public interface JobDao { void addJob(Job job); List<Job>getAllJobs(); void deleteJob(int jid); }
package com.testarea; import java.sql.Time; import java.sql.Timestamp; import java.time.LocalDate; import java.time.LocalTime; import java.time.Month; import java.time.temporal.ChronoUnit; import java.util.Date; public class TimeStampTest { public static void main(String[] args) { LocalDate localDate = LocalDate.now(); System.out.println("LocalDate localDate = LocalDate.now(); = \t\t" + localDate); System.out.println("LocalDate.of(2015, 02, 20) = \t\t" + LocalDate.of(2015, 02, 20)); System.out.println("LocalDate.parse(\"2015-02-20\") = \t\t" + LocalDate.parse("2015-02-20")); LocalDate tomorrow = LocalDate.now().plusDays(1); System.out.println("Tomorrow ....LocalDate.now().plusDays(1) = \t\t" + tomorrow); ///////////////////////////// LocalTime System.out.println("\n####################\n\n"); // An instance of current LocalTime can be created from the system clock as below: LocalTime now = LocalTime.now(); System.out.println("Time now = \t\t" + now); // In the below code sample, we create a LocalTime representing 06:30 AM by parsing a string representation: LocalTime sixThirty = LocalTime.parse("06:30"); System.out.println(sixThirty); // The below example creates a LocalTime by parsing a string and adds an hour // to it by using the “plus” API. The result would be LocalTime representing 07:30 AM: LocalTime sevenThirty = LocalTime.parse("06:30").plus(1, ChronoUnit.HOURS); // Various getter methods are available which can be used to get specific units of time like hour, min and secs like below: int six = LocalTime.parse("06:30").getHour(); System.out.println(six); ///////////////////////////// Duration LocalTime initialTime = LocalTime.of(6, 30, 0); // LocalTime finalTime = initialTime.plus(Duration.osSeconds()) // no idea where i left this off on friday. } }
package ioccontainer.materials; import ioccontainer.CreateOnTheFly; public class CDependsA { @CreateOnTheFly private ADependsB dependency; public ADependsB getDependency() { return dependency; } public void setDependency(ADependsB dependency) { this.dependency = dependency; } }
package com.xwq520.faceobject.casting; /** * 向上转型对于可扩展性的好处,如果以后还有其他动物,只需要改一个方法 * @author xialiguo */ public class TestFun { public static void main(String[] args) { TestFun tf = new TestFun(); Animal a = new Animal("name"); Cat c = new Cat("catname", "blue"); Dog d = new Dog("dogname", "black"); tf.f(a); tf.f(c); tf.f(d); } public void f(Animal a) { System.out.println("name:" + a.name); if (a instanceof Cat) { Cat cat = (Cat) a; System.out.println(" " + cat.eyesColor + "eyes"); } else if (a instanceof Dog) { Dog dog = (Dog) a; System.out.println(" " + dog.furColor + "fur"); } } }
package member.desktop.pages.account; import global.Global; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import base.PageObject; import java.util.List; public class Member_AccEdit_PC_Page extends PageObject { public static String page_url = Global.getConfig().getString("member.url") + "/user/profile#/profile/edit"; @FindBy(css = ".mod-input-name input") private WebElement editName_txtField; @FindBy(className = "mod-input-close-icon") private WebElement clearOldName_btn; @FindBy(css = ".next-btn-large") private WebElement saveChanges_btn; @FindBy(css = "div > div:nth-child(2) > h3 > a") private WebElement changeEmail_btn; @FindBy(className = "buttons") private WebElement verifyEmail_btn; @FindBy(className = "mod-sendcode") private WebElement sendCode_btn; @FindBy(css = "span#month > span") private WebElement month_drpDownList; @FindBy (css = "span#day > span") private WebElement day_drpDownList; @FindBy (css = "span#year > span") private WebElement year_drpDownList; @FindBy(css = "span#gender > span") private WebElement gender_drpDownList; @FindBy(css = "ul > li.next-menu-item") private List <WebElement> Selector_listItem; @FindBy(css = "div#container div:nth-child(6) > div > div > input[type='text']") private WebElement editTaxId_txtField; @FindBy(css = ".mod-input-branchId input") private WebElement editBranchId_txtField; @FindBy(css = "div#container div:nth-child(6) > div > div > div") private WebElement clearTaxId_btn; @FindBy(css = "div#container div:nth-child(7) > div > div > div") private WebElement clearBrnachId_btn; private int random; private String day = ""; private int size = 0; private By Selector_listItem_by = By.cssSelector("ul > li.next-menu-item"); private By changeEmail_btn_by = By.cssSelector("div > div:nth-child(2) > h3 > a"); private By verifyEmail_btn_by = By.className("buttons"); private By sendCode_btn_by = By.className("mod-sendcode"); public void clearOldName() { waitUntilPageReady(); waitUntilVisible(clearOldName_btn); this.clearOldName_btn.click(); } public void editName(String newName) { waitUntilPageReady(); waitUntilVisible(editName_txtField); this.editName_txtField.sendKeys(newName); } public void saveChangesBtn() { waitUntilPageReady(); waitUntilVisible(saveChanges_btn); this.saveChanges_btn.click(); } public void sendCodeToInboxMail() { waitUntilPageReady(); waitUntilClickable(changeEmail_btn_by); this.changeEmail_btn.click(); waitUntilClickable(verifyEmail_btn_by); this.verifyEmail_btn.click(); waitUntilClickable(sendCode_btn_by); this.sendCode_btn.click(); } public void clearOldTaxId() // This method clears the already existed Tax code on edit profile page (if available) { if (page_url.contains(".th") || page_url.contains(".vn")) { waitUntilPageReady(); waitUntilVisible(editTaxId_txtField); if(!(editTaxId_txtField.getAttribute("value").equalsIgnoreCase(""))) { waitUntilVisible(clearTaxId_btn); this.clearTaxId_btn.click(); } } } public void clearBranchId() // This method clears the already existed branch id on edit profile page (if available) { if (page_url.contains(".th")) { waitUntilPageReady(); waitUntilVisible(editBranchId_txtField); if(!(editBranchId_txtField.getAttribute("value").equalsIgnoreCase(""))) { waitUntilVisible(clearBrnachId_btn); this.clearBrnachId_btn.click(); } } } public String changeTaxCode(String code) { // This method changes the branch id on edit profile page (if available) if (page_url.contains(".th") || page_url.contains(".vn")) { waitUntilPageReady(); waitUntilVisible(editTaxId_txtField); editTaxId_txtField.clear(); this.editTaxId_txtField.sendKeys(code); return code; } else { return ""; } } public String changeBranchId(String code) { // This method changes the branch id on edit profile page (if available) if (page_url.contains(".th")) { waitUntilPageReady(); waitUntilVisible(editBranchId_txtField); editBranchId_txtField.clear(); this.editBranchId_txtField.sendKeys(code); return code; } else return ""; } public String changeMonth() { // This method changes the month of date of birth on edit profile page waitUntilVisible(month_drpDownList); month_drpDownList.click(); size = Selector_listItem.size(); if (size > 12) {size = 12;} random = getRandom(size); waitUntilLocated(Selector_listItem_by); clickWithoutException(Selector_listItem.get(random)); return (Integer.toString((random+1))); } public String changeDay() { // This method changes the day of date of birth on edit profile page waitUntilVisible(day_drpDownList); day_drpDownList.click(); size = Selector_listItem.size(); if (size > 28) {size = 28;} random = getRandom(size); waitUntilLocated(Selector_listItem_by); Selector_listItem.get(random).click(); day = day_drpDownList.getText(); if (Integer.parseInt(day) < 10) {day = day.replace("0", "");} return day; } public String changeYear() { // This method changes the year of date of birth on edit profile page waitUntilVisible(year_drpDownList); year_drpDownList.click(); size = Selector_listItem.size(); if (size > 120) {size = 120;} waitUntilLocated(Selector_listItem_by); random = getRandom(size); clickWithoutException(Selector_listItem.get(random)); return year_drpDownList.getText(); } public String changeGender() { // This method changes the gender on edit profile page waitUntilPageReady(); waitUntilVisible(gender_drpDownList); if (gender_drpDownList.getText().equalsIgnoreCase("male") || gender_drpDownList.getText().equalsIgnoreCase("Male")) { gender_drpDownList.click(); Selector_listItem.get(1).click(); } else if (gender_drpDownList.getText().equalsIgnoreCase("female") || gender_drpDownList.getText().equalsIgnoreCase("Female")) { gender_drpDownList.click(); Selector_listItem.get(0).click(); } else { gender_drpDownList.click(); Selector_listItem.get(0).click(); } return this.gender_drpDownList.getText(); } }
package com.tencent.tinker.a.a; import com.tencent.tinker.a.a.a.a; import java.nio.ByteBuffer; public final class i$e extends a { private final String name; final /* synthetic */ i voZ; /* synthetic */ i$e(i iVar, String str, ByteBuffer byteBuffer, byte b) { this(iVar, str, byteBuffer); } private i$e(i iVar, String str, ByteBuffer byteBuffer) { this.voZ = iVar; super(byteBuffer); this.name = str; } public final s cGo() { a(i.a(this.voZ).vpx, false); return super.cGo(); } public final u cGp() { a(i.a(this.voZ).vps, false); return super.cGp(); } public final n cGq() { a(i.a(this.voZ).vpo, false); return super.cGq(); } public final p cGr() { a(i.a(this.voZ).vpp, false); return super.cGr(); } public final r cGs() { a(i.a(this.voZ).vpn, false); return super.cGs(); } public final f cGt() { a(i.a(this.voZ).vpq, false); return super.cGt(); } public final g cGu() { a(i.a(this.voZ).vpw, false); return super.cGu(); } public final h cGv() { a(i.a(this.voZ).vpy, false); return super.cGv(); } public final e cGw() { a(i.a(this.voZ).vpv, false); return super.cGw(); } public final a cGx() { a(i.a(this.voZ).vpz, false); return super.cGx(); } public final b cGy() { a(i.a(this.voZ).vpu, false); return super.cGy(); } public final c cGz() { a(i.a(this.voZ).vpt, false); return super.cGz(); } public final d cGA() { a(i.a(this.voZ).vpB, false); return super.cGA(); } public final k cGB() { a(i.a(this.voZ).vpA, false); return super.cGB(); } private void a(t.a aVar, boolean z) { if (!aVar.vpI) { return; } if (z) { super.Hy((((this.aig.position() + 3) & -4) - this.aig.position()) * 1); while ((this.aig.position() & 3) != 0) { this.aig.put((byte) 0); } if (this.aig.position() > this.vpO) { this.vpO = this.aig.position(); return; } return; } this.aig.position((this.aig.position() + 3) & -4); } public final int a(s sVar) { a(i.a(this.voZ).vpx, true); return super.a(sVar); } public final int a(u uVar) { a(i.a(this.voZ).vps, true); return super.a(uVar); } public final int a(n nVar) { a(i.a(this.voZ).vpo, true); return super.a(nVar); } public final int a(p pVar) { a(i.a(this.voZ).vpp, true); return super.a(pVar); } public final int a(r rVar) { a(i.a(this.voZ).vpn, true); return super.a(rVar); } public final int a(f fVar) { a(i.a(this.voZ).vpq, true); return super.a(fVar); } public final int a(g gVar) { a(i.a(this.voZ).vpw, true); return super.a(gVar); } public final int a(h hVar) { a(i.a(this.voZ).vpy, true); return super.a(hVar); } public final int a(e eVar) { a(i.a(this.voZ).vpv, true); return super.a(eVar); } public final int a(a aVar) { a(i.a(this.voZ).vpz, true); return super.a(aVar); } public final int a(b bVar) { a(i.a(this.voZ).vpu, true); return super.a(bVar); } public final int a(c cVar) { a(i.a(this.voZ).vpt, true); return super.a(cVar); } public final int a(d dVar) { a(i.a(this.voZ).vpB, true); return super.a(dVar); } public final int a(k kVar) { a(i.a(this.voZ).vpA, true); return super.a(kVar); } }
package app0510.gugudan; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; public class Gugudan extends JFrame{ JTextField t_input; JButton bt; JLabel la; public Gugudan() { //생성 la=new JLabel("몇단을 출력할까요?"); t_input=new JTextField(10); bt=new JButton("출력"); bt.addActionListener(new ActionControl(t_input)); //스타일 setLayout(new FlowLayout()); //조립 add(la); add(t_input); add(bt); //보여주기 setSize(300, 200); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args) { new Gugudan(); } }
package geometry.service; import geometry.entity.Figure; import geometry.entity.Square; /** * class SquareCreator. * * @author Ihor Zhytchenko (igor.zhytchenko@gmail.com) * @version $1$ * @since 18.08.2018 */ public class SquareCreator implements Creator { @Override public Figure createFigure() { return new Square(); } }
package jp.smartcompany.job.modules.base.pojo.entity; import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.Version; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * @author Xiao Wenpeng */ @Getter @Setter @ToString public abstract class AbstractLogicBean extends BaseBean{ @Version protected Long version; @TableLogic protected Integer delFlag; }
package com.tencent.mm.ui.chatting.g; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.tencent.mm.R; import com.tencent.mm.ui.chatting.a.b.a; class f$b extends a { TextView eCn; ImageView gmn; TextView jet; ImageView jez; final /* synthetic */ f tYA; public f$b(f fVar, View view) { this.tYA = fVar; super(view); this.gmn = (ImageView) view.findViewById(R.h.fav_icon); this.eCn = (TextView) view.findViewById(R.h.fav_desc); this.eCn.setVisibility(8); this.jet = (TextView) view.findViewById(R.h.fav_source); this.jez = (ImageView) view.findViewById(R.h.fav_icon_mask); this.jez.setImageResource(R.g.music_playicon); this.jez.setVisibility(0); } }
package com.example.healthmanage.ui.activity.temperature.adapter; import android.content.Context; import android.widget.TextView; import androidx.annotation.Nullable; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.example.healthmanage.R; import com.example.healthmanage.ui.activity.temperature.PopItem; import java.util.List; public class ItemPopAdapter extends BaseQuickAdapter<PopItem, BaseViewHolder> { Context mContext; public ItemPopAdapter(@Nullable List<PopItem> data,Context context) { super(R.layout.item_job, data); this.mContext = context; } @Override protected void convert(BaseViewHolder helper, PopItem item) { ((TextView)helper.getView(R.id.tv_content)).setText(item.getName()); helper.getView(R.id.ll_layout).setBackgroundResource(item.isSelect()?R.color.colorTxtBlue:R.color.white); helper.getView(R.id.ll_layout).getBackground().mutate().setAlpha(20); helper.setTextColor(R.id.tv_content,item.isSelect()?mContext.getResources().getColor(R.color.colorTxtBlue):mContext.getResources().getColor(R.color.colorTxtBlack)); } }
package model; //import java.io.Serializable; // //import javax.persistence.Entity; //import javax.persistence.Id; //import javax.persistence.JoinColumn; //import javax.persistence.ManyToOne; //import javax.persistence.Table; // // ///** // * The persistent class for the professor database table. // * // */ //@Entity //@Table(name="report") //public class Report implements Serializable { // private static final long serialVersionUID = 1L; // // @Id // private int id; // // private String full_report; // // private Professor professorId; // // // public void setProfessorId(Professor professor) { // this.professorId = professor; // } // // @ManyToOne // @JoinColumn(name="professorId", nullable=false) // public Professor getProfessorId() { // return this.professorId; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getFullReport() { // return full_report; // } // // public void setFullReport(String fullReport) { // this.full_report = fullReport; // } // // // // // //}
package com.facebook.react.common; import android.text.TextUtils; import com.facebook.common.e.a; import org.json.JSONException; import org.json.JSONObject; public class DebugServerException extends RuntimeException { public DebugServerException(String paramString) { super(paramString); } private DebugServerException(String paramString1, String paramString2, int paramInt1, int paramInt2) { super(stringBuilder.toString()); } public DebugServerException(String paramString, Throwable paramThrowable) { super(paramString, paramThrowable); } public static DebugServerException makeGeneric(String paramString1, String paramString2, Throwable paramThrowable) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(paramString1); stringBuilder.append("\n\nTry the following to fix the issue:\n• Ensure that the packager server is running\n• Ensure that your device/emulator is connected to your machine and has USB debugging enabled - run 'adb devices' to see a list of connected devices\n• Ensure Airplane Mode is disabled\n• If you're on a physical device connected to the same machine, run 'adb reverse tcp:8081 tcp:8081' to forward requests from your device\n• If your device is on the same Wi-Fi network, set 'Debug server host & port for device' in 'Dev settings' to your machine's IP address and the port of the local dev server - e.g. 10.0.1.1:8081\n\n"); stringBuilder.append(paramString2); return new DebugServerException(stringBuilder.toString(), paramThrowable); } public static DebugServerException makeGeneric(String paramString, Throwable paramThrowable) { return makeGeneric(paramString, "", paramThrowable); } public static DebugServerException parse(String paramString) { if (TextUtils.isEmpty(paramString)) return null; try { JSONObject jSONObject = new JSONObject(paramString); String str = jSONObject.getString("filename"); return new DebugServerException(jSONObject.getString("description"), shortenFileName(str), jSONObject.getInt("lineNumber"), jSONObject.getInt("column")); } catch (JSONException jSONException) { StringBuilder stringBuilder = new StringBuilder("Could not parse DebugServerException from: "); stringBuilder.append(paramString); a.b("ReactNative", stringBuilder.toString(), (Throwable)jSONException); return null; } } private static String shortenFileName(String paramString) { String[] arrayOfString = paramString.split("/"); return arrayOfString[arrayOfString.length - 1]; } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\common\DebugServerException.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
/* * 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 zip; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * * @author Ahmed */ public class Client extends Thread { public int unit = 0;//array length for one time public long recieve = 0; public long total = 0; String source; String destination; Progress frm; private Socket client; private DataInputStream in; private DataOutputStream out; public Client(String source, String destination, Progress frm) { this.source = source; this.destination = destination; this.frm = frm; this.setPriority(MAX_PRIORITY); } public void connect() { try { client = new Socket("localhost", 500); in = new DataInputStream(client.getInputStream()); out = new DataOutputStream(client.getOutputStream()); } catch (IOException ex) { System.out.println("cannot connect to the server +++" + ex.getMessage()); } } @Override public void run() { try { ZipFile(source, destination); } catch (IOException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } } public void ZipFile(String source, String destination) throws IOException { //format destination path destination = (destination.substring(0, destination.indexOf(".")) + ".zip"); FileOutputStream fileOutputStream = new FileOutputStream(destination); ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream); File f = new File(source); ZipEntry zipEntry = new ZipEntry(f.getName()); zipOutputStream.putNextEntry(zipEntry); try { //connect to server connect(); //send source file to server out.writeUTF(source); byte[] bytes = new byte[100 * 1024]; total = f.length(); //file total lenght frm.runprogress(this, frm);//open progress form //write zipped file while ((unit = in.read(bytes)) > 0) { recieve += unit; zipOutputStream.write(bytes, 0, unit); } out.writeBoolean(true); client.close(); } catch (IOException ex) { System.out.println("server disconected +++" + ex.getMessage()); } finally { zipOutputStream.closeEntry(); zipOutputStream.close(); fileOutputStream.close(); } } }
package com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.sdk.platformtools.x; class r$5 implements OnClickListener { final /* synthetic */ r nFh; r$5(r rVar) { this.nFh = rVar; } public final void onClick(View view) { x.i("MicroMsg.Sns.AdLandingPageNewStreamVideoComponent", "play btn onclick isPlaying[%b]", new Object[]{Boolean.valueOf(this.nFh.nEF.isPlaying())}); if (this.nFh.nEF.isPlaying()) { this.nFh.bAf(); this.nFh.nEW = 4; } else { if (this.nFh.nEO) { this.nFh.bzy(); } else { this.nFh.bzD(); this.nFh.bzC(); } r.a(this.nFh); this.nFh.nEW = 3; } if (this.nFh.nzR) { r rVar = this.nFh; rVar.nFa++; } } }
package codechef; import java.util.*; import org.junit.Test; import static org.junit.Assert.*; import codechef.Dijkstra.Road; public class DijkstraTest { @Test public void testDijkstra() { final var graph = new Dijkstra( new HashSet<>( Arrays.asList("Chicago", "Cleveland", "Peoria", "Lafayette", "Detroit", "Milwaukee") ) ); graph.addRoad("Chicago", "Cleveland", 300 ).addRoad("Chicago", "Milwaukee", 200 ).addRoad("Peoria", "Lafayette", 180 ).addRoad("Lafayette", "Cleveland", 200 ).addRoad("Cleveland", "Detroit", 200 ).addRoad("Milwaukee", "Detroit", 500 ); final List<Dijkstra.Road> expectedPeoriaToDetroit = Arrays.asList( new Road("Peoria", "Lafayette", 180), new Road("Lafayette", "Cleveland", 200), new Road("Cleveland", "Detroit", 200) ); final List<Road> peoriaToDetroit = graph.shortestPath("Peoria", "Detroit"); assertEquals("Peoria to Detroit", expectedPeoriaToDetroit, peoriaToDetroit); } }
/* * 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 tr.com.rah.fe; import java.awt.BorderLayout; import static java.awt.Dialog.DEFAULT_MODALITY_TYPE; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.text.SimpleDateFormat; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingUtilities; import static javax.swing.WindowConstants.HIDE_ON_CLOSE; import tr.com.rah.dal.MusteriDAL; import tr.com.rah.dal.PersonelDAL; import tr.com.rah.dal.SehirDAL; import tr.com.rah.dal.UrunlerDAL; import tr.com.rah.interfaces.FeInterfaces; import tr.com.rah.types.MusteriContract; import tr.com.rah.types.PersonelContract; import tr.com.rah.types.SehirContract; import tr.com.rah.types.UrunlerContract; /** * * @author rahimgng */ public class MüsteriDuzenleFE extends JDialog implements FeInterfaces { public MüsteriDuzenleFE() { initPencere(); } @Override public void initPencere() { JPanel panel = initPanel(); panel.setBorder(BorderFactory.createTitledBorder("Yetki Düzenleme Sayfası")); add(panel); setTitle("Yetki Düzenle"); pack(); setModalityType(DEFAULT_MODALITY_TYPE); setLocationRelativeTo(null); setVisible(true); setDefaultCloseOperation(HIDE_ON_CLOSE); } //id AdiSoyadi Telefon Adres SehirId @Override public JPanel initPanel() { JPanel panel = new JPanel(new BorderLayout()); JPanel ustPanel = new JPanel(new GridLayout(5, 2)); JPanel buttonPanel = new JPanel(new GridLayout(1, 2)); ustPanel.setBorder(BorderFactory.createTitledBorder("Müşteri Düzenle")); JLabel musteriLabel = new JLabel("Müşteri Bilgileri:", JLabel.RIGHT); ustPanel.add(musteriLabel); JComboBox musteriBox = new JComboBox(new MusteriDAL().GetAll().toArray()); ustPanel.add(musteriBox); JLabel sehirLabel = new JLabel("Şehir Bilgileri:", JLabel.RIGHT); ustPanel.add(sehirLabel); JComboBox sehirBox = new JComboBox(new SehirDAL().GetAll().toArray()); ustPanel.add(sehirBox); sehirBox.setSelectedIndex(musteriBox.getSelectedIndex()); JLabel adiLabel = new JLabel("Müşteri Adı Soyadı:", JLabel.RIGHT); ustPanel.add(adiLabel); JTextField adiField = new JTextField(10); ustPanel.add(adiField); JLabel telLabel = new JLabel("Müşteri Telefon:", JLabel.RIGHT); ustPanel.add(telLabel); JTextField telField = new JTextField(10); ustPanel.add(telField); JLabel adresLabel = new JLabel("Adres:", JLabel.RIGHT); ustPanel.add(adresLabel); JTextArea adresArea = new JTextArea(5, 1); JScrollPane pane = new JScrollPane(adresArea); pane.setBorder(BorderFactory.createTitledBorder("Adres Bilgisi")); JButton guncelleButton = new JButton("Güncelle"); buttonPanel.add(guncelleButton); JButton silButton = new JButton("Sil"); buttonPanel.add(silButton); //güncelle action guncelleButton.addActionListener((ActionEvent e) -> { SwingUtilities.invokeLater(() -> { MusteriContract contract = new MusteriContract(); SehirContract sContract = (SehirContract) sehirBox.getSelectedItem(); MusteriContract mContract = (MusteriContract) musteriBox.getSelectedItem(); contract.setId(mContract.getId()); contract.setAdiSoyadi(adiField.getText()); contract.setTelefon(telField.getText()); contract.setAdres(adresArea.getText()); contract.setSehirId(sContract.getId()); new MusteriDAL().Update(contract); JOptionPane.showMessageDialog(null, "müşteri güncellendi!"); }); }); //sil action silButton.addActionListener((ActionEvent e) -> { SwingUtilities.invokeLater(() -> { MusteriContract contract = new MusteriContract(); MusteriContract mContract = (MusteriContract) musteriBox.getSelectedItem(); contract.setId(mContract.getId()); new MusteriDAL().Delete(contract); JOptionPane.showMessageDialog(null, contract.getAdiSoyadi() + " adlı kişi silindi!"); }); }); panel.add(ustPanel, BorderLayout.NORTH); panel.add(pane, BorderLayout.CENTER); panel.add(buttonPanel, BorderLayout.SOUTH); return panel; } @Override public JMenuBar initBar() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public JTabbedPane initTabs() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
package mk.petrovski.weathergurumvp.injection.module; import android.content.Context; import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import dagger.Module; import dagger.Provides; import java.io.IOException; import mk.petrovski.weathergurumvp.data.remote.ApiConsts; import mk.petrovski.weathergurumvp.data.remote.ApiHelper; import mk.petrovski.weathergurumvp.data.remote.ApiInterface; import mk.petrovski.weathergurumvp.data.remote.AppApiHelper; import mk.petrovski.weathergurumvp.data.remote.helper.HeaderHelper; import mk.petrovski.weathergurumvp.data.remote.helper.error.ErrorHandlerHelper; import mk.petrovski.weathergurumvp.injection.qualifier.ApplicationContext; import mk.petrovski.weathergurumvp.injection.scope.WeatherGuruApplicationScope; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import timber.log.Timber; /** * Created by Nikola Petrovski on 2/13/2017. */ @Module(includes = { ContextModule.class, RxModule.class }) public class NetworkModule { @Provides @WeatherGuruApplicationScope public Interceptor httpInterceptor() { return new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { // Request customization: add request headers Request.Builder requestBuilder = chain.request() .newBuilder() .method(chain.request().method(), chain.request().body()) .headers(HeaderHelper.getAppHeaders()); return chain.proceed(requestBuilder.build()); } }; } @Provides @WeatherGuruApplicationScope public HttpLoggingInterceptor loggingInterceptor() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() { @Override public void log(String message) { Timber.i(message); } }); interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC); return interceptor; } @Provides @WeatherGuruApplicationScope public OkHttpClient okHttpClient(Interceptor interceptor) { return new OkHttpClient.Builder().addInterceptor(interceptor) .addInterceptor(loggingInterceptor()) .build(); } @Provides @WeatherGuruApplicationScope public Retrofit retrofit(OkHttpClient okHttpClient) { return new Retrofit.Builder().baseUrl(ApiConsts.BASE_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); } @Provides @WeatherGuruApplicationScope public ApiInterface apiServiceInterface(Retrofit retrofit) { return retrofit.create(ApiInterface.class); } @Provides @WeatherGuruApplicationScope public ErrorHandlerHelper errorHandlerHelper(@ApplicationContext Context context, Retrofit retrofit) { return new ErrorHandlerHelper(context, retrofit); } @Provides @WeatherGuruApplicationScope public ApiHelper apiHelper(ApiInterface apiInterface, ErrorHandlerHelper errorHandlerHelper) { return new AppApiHelper(apiInterface, errorHandlerHelper); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.trivee.fb2pdf; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Rectangle; import org.apache.commons.lang3.StringUtils; /** * * @author vzeltser */ public class HeaderSlotSettings { public boolean enabled; public String style = "header"; public String query; public int border = Rectangle.BOTTOM; private String borderColor; public HeaderSlotSettings() { } BaseColor getBorderColor() { return (StringUtils.isNotBlank(borderColor)) ? Utilities.getColor(borderColor) : null; } }
package codeforces.Round_292_Div2.C_Drazil_and_Factorial; import java.io.InputStream; import java.io.PrintStream; import java.util.*; public final class Solution { // 2 -> 2! // 3 -> 3! // 4 -> 3!2!2! // 5 -> 5! // 6 -> 5!3! // 7 -> 7! // 8 -> 7!2!2!2! // 9 -> 7!3!3!2! public static void main(String[] args) { parseSolveAndPrint(System.in, System.out); } private static final Map<Character, String> map = new HashMap<Character, String>(){{ put('0', ""); put('1', ""); put('2', "2"); put('3', "3"); put('4', "322"); put('5', "5"); put('6', "53"); put('7', "7"); put('8', "7222"); put('9', "7332"); }}; public static void parseSolveAndPrint(InputStream in, PrintStream out) { Scanner scanner = new Scanner(in); int n = scanner.nextInt(); String number = scanner.next(); ArrayList<Character> result = new ArrayList<>(); for (char ch : number.toCharArray()) { for (char chResult : map.get(ch).toCharArray()) { result.add(chResult); } } Collections.sort(result, (ch1, ch2) -> Character.compare(ch2, ch1)); StringBuilder output = new StringBuilder(); result.stream().forEach(output::append); out.println(output); } }
package com.xiaoysec.hrm.business.job.mapper; import java.util.List; import java.util.Map; import com.xiaoysec.hrm.business.job.entity.Job; public interface JobMapper { public Integer getJobCount(Map<String, Object> parm); // 分页查询 public List<Job> findJob(Map<String, Object> parm); public Job getJobById(Integer id); // 根据id删除 public void deleteJobById(Integer id); // 更新 public void updateJob(Job job); // 新增 public void addJob(Job job); }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * 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 2 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, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.servlet; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.openkm.bean.ConfigStoredFile; import com.openkm.core.Config; import com.openkm.util.SecureStore; import com.openkm.util.WebUtils; /** * Image Logo Servlet */ public class ImageLogoServlet extends HttpServlet { private static Logger log = LoggerFactory.getLogger(ImageLogoServlet.class); private static final long serialVersionUID = 1L; /** * */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String img = request.getPathInfo(); try { if (img != null && img.length() > 1) { ConfigStoredFile logo = getImage(img.substring(1)); if (logo != null) { byte[] content = SecureStore.b64Decode(logo.getContent()); ByteArrayInputStream bais = new ByteArrayInputStream(content); WebUtils.sendFile(request, response, logo.getName(), logo.getMime(), true, bais); } else { sendError(request, response); } } } catch (MalformedURLException e) { sendError(request, response); log.warn(e.getMessage(), e); } catch (IOException e) { sendError(request, response); log.error(e.getMessage(), e); } } /** * Send error image */ private void sendError(HttpServletRequest request, HttpServletResponse response) throws IOException { InputStream is = getServletContext().getResource("/img/error.png").openStream(); WebUtils.sendFile(request, response, "error.png", "image/png", true, is); is.close(); } /** * Get requested image input stream. */ private ConfigStoredFile getImage(String img) throws MalformedURLException, IOException { log.debug("getImage({})", img); ConfigStoredFile stFile = null; if ("tiny".equals(img)) { stFile = Config.LOGO_TINY; } else if ("login".equals(img)) { stFile = Config.LOGO_LOGIN; } else if ("report".equals(img)) { stFile = Config.LOGO_REPORT; } else if ("favicon".equals(img)) { stFile = Config.LOGO_FAVICON; } log.debug("getImage: {}", stFile); return stFile; } }
/* * 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 gal.teis.pgr.abstractos; /** * * @author Esther Ferreiro */ public class FiguraGeometricaUtils { public static double areaPromedio(FiguraGeometrica[] arr) { double areaTotal = 0; for (int i = 0; i < arr.length; i++) { areaTotal += arr[i].area(); } return areaTotal / arr.length; } }
package com.bashpole.updentity.dao; import java.io.IOException; import java.net.HttpRetryException; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import com.bashpole.updentity.utility.UpdentityConstants; import com.bashpole.updentity.webresources.CouchConnect; /* * Data access object for Constant Contact */ public class ConstantContactDao { private String username; private String ctctListId; private String password; public ConstantContactDao(String username, String password, String ctctListId) { this.username = username; this.password = password; this.ctctListId = ctctListId; } /** * Returns true if the username and password are valid on Constant Contact. * @throws IOException * * I think there are better ways to do this: I.E. write a java library for interfacing with CC * */ public static boolean isAuthentic(String username, String password) throws IOException { String URL = UpdentityConstants.REST_URL + "?action=authenticate_constantContact&uname=" + username + "&pname=" + password; try { CouchConnect request = new CouchConnect(URL); JSONArray ccResult = JSONArray.fromObject(request.get()); if(ccResult.size() != 0) return true; else return false; } catch(HttpRetryException e) { return false; } } /** * * @param limit * @param offset * @return * @throws HttpRetryException * @throws IOException * * http://[host]/updentity_rest_php/updentity-rest/rest.php?action=constantContact_list_contacts&limit=1&offset=1&uname=[username]&pname=[password] */ public JSONObject listContacts(int limit, int offset) throws HttpRetryException, IOException { String URL = UpdentityConstants.REST_URL + "?action=constantContact_list_contacts&" + "limit=" + limit + "&offset=" + offset + "&listid=" + this.ctctListId + "&uname=" + this.username + "&pname=" + this.password; CouchConnect request = new CouchConnect(URL); // System.out.println("TheRequest: " + request); JSONObject contacts = JSONObject.fromObject(request.get()); return contacts; } /** * * @return count * @throws HttpRetryException * @throws IOException */ public int getContactCount() throws HttpRetryException, IOException { int count; String URL = UpdentityConstants.REST_URL + "?action=constantContact_count_contacts&uname=" + this.username + "&pname=" + this.password + "&listid=" + this.ctctListId; CouchConnect request = new CouchConnect(URL); // System.out.println("\n User: " + this.username); JSONObject subscriberCountObj = JSONObject.fromObject(request.get()); //System.out.println("\n CountObj: " + subscriberCountObj.toString()); count = subscriberCountObj.getInt("subscibers"); //System.out.println("\ncontact count: " + count); return count; } }
package Pojos; // Generated Sep 19, 2015 12:30:29 PM by Hibernate Tools 4.3.1 import java.math.BigDecimal; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * Cargo generated by hbm2java */ public class Cargo implements java.io.Serializable { private Integer idCargo; private Date fechaCreacion; private String nombreCargo; private BigDecimal salarioMin; private Set medicos = new HashSet(0); private Set cajeros = new HashSet(0); private Set enfermeras = new HashSet(0); private Set empleadoLaboratorios = new HashSet(0); public Cargo() { } public Cargo(Date fechaCreacion, String nombreCargo, BigDecimal salarioMin) { this.fechaCreacion = fechaCreacion; this.nombreCargo = nombreCargo; this.salarioMin = salarioMin; } public Cargo(Date fechaCreacion, String nombreCargo, BigDecimal salarioMin, Set medicos, Set cajeros, Set enfermeras, Set empleadoLaboratorios) { this.fechaCreacion = fechaCreacion; this.nombreCargo = nombreCargo; this.salarioMin = salarioMin; this.medicos = medicos; this.cajeros = cajeros; this.enfermeras = enfermeras; this.empleadoLaboratorios = empleadoLaboratorios; } public Integer getIdCargo() { return this.idCargo; } public void setIdCargo(Integer idCargo) { this.idCargo = idCargo; } public Date getFechaCreacion() { return this.fechaCreacion; } public void setFechaCreacion(Date fechaCreacion) { this.fechaCreacion = fechaCreacion; } public String getNombreCargo() { return this.nombreCargo; } public void setNombreCargo(String nombreCargo) { this.nombreCargo = nombreCargo; } public BigDecimal getSalarioMin() { return this.salarioMin; } public void setSalarioMin(BigDecimal salarioMin) { this.salarioMin = salarioMin; } public Set getMedicos() { return this.medicos; } public void setMedicos(Set medicos) { this.medicos = medicos; } public Set getCajeros() { return this.cajeros; } public void setCajeros(Set cajeros) { this.cajeros = cajeros; } public Set getEnfermeras() { return this.enfermeras; } public void setEnfermeras(Set enfermeras) { this.enfermeras = enfermeras; } public Set getEmpleadoLaboratorios() { return this.empleadoLaboratorios; } public void setEmpleadoLaboratorios(Set empleadoLaboratorios) { this.empleadoLaboratorios = empleadoLaboratorios; } }
package app.integro.sjbhs.adapters; import android.content.Context; import androidx.core.content.ContextCompat; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.text.SpannableString; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import app.integro.sjbhs.R; import app.integro.sjbhs.WebActivity; import app.integro.sjbhs.models.Notification; public class NotificationAdapter extends RecyclerView.Adapter<NotificationAdapter.MyViewHolder> { private final Context context; private final ArrayList<Notification> notificationArrayList; public NotificationAdapter(Context context, ArrayList<Notification> notificationsArrayList) { this.context = context; this.notificationArrayList = notificationsArrayList; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.card_notification, parent, false); return new MyViewHolder(view); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { final Notification notificationItem = notificationArrayList.get(position); holder.tvN_Title.setText(notificationItem.getTitle()); holder.tvN_date.setText(notificationItem.getDate()); holder.tvN_Description.setText(notificationItem.getDescription()); holder.tvWeblink.setText(notificationItem.getWeblink()); holder.tvWeblink.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, WebActivity.class); intent.putExtra("URL", notificationItem.getWeblink()); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } }); } @Override public int getItemCount() { return notificationArrayList.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { private final TextView tvN_Title; private final TextView tvN_date; private final TextView tvN_Description; private final TextView tvWeblink; public MyViewHolder(View itemView) { super(itemView); tvN_date = (TextView) itemView.findViewById(R.id.tvDate); tvN_Title = (TextView) itemView.findViewById(R.id.tvTitle); tvN_Description = (TextView) itemView.findViewById(R.id.tvDescription); tvWeblink = (TextView) itemView.findViewById(R.id.tvWeblink); } } }
/* * Created on Sep 17, 2004 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package com.ibm.ive.tools.commandLine; import java.util.ArrayList; /** * @author sfoley * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public abstract class ArgumentOption extends Option { ArrayList parametrizedDescriptions = new ArrayList(); /** * * @author sfoley * * represents a special format that this option may take. * For example, an option may take on a selection of three ParametrizedDescriptions: * -debugLevel 0 * -debugLevel 1 * -debugLevel 2 * or the argument may make for a series of parametrized descriptions: * -person name=xxx * -person gender=xxx * * For each such argument format, a specialized description string is provided. * * This is mainly for use in writing usage and/or help strings. */ public class ParametrizedDescription { String defaultArgs[]; String description; private ParametrizedDescription(String defaultArgs[], String description) { this.defaultArgs = defaultArgs; this.description = description; } public String toString() { return ArgumentOption.this.toString(defaultArgs); } public String getDescription() { return description; } } public ArgumentOption(String name, String description, int argCount, char switchCharacters[]) { super(name, description, argCount, switchCharacters); } public ArgumentOption(String name, String description, int argCount, char switchCharacter) { super(name, description, argCount, switchCharacter); } public ArgumentOption(String name, String description, int argCount) { super(name, description, argCount); } public ArgumentOption(String name, int argCount) { super(name, argCount); } public ParametrizedDescription getDescription(int index) { return (ParametrizedDescription) parametrizedDescriptions.get(index); } public void addParametrizedDescription(String defaultArgs[], String description) { parametrizedDescriptions.add(new ParametrizedDescription(defaultArgs, description)); } }
package ru.otus.l151.front; import ru.otus.l151.app.MessageSystemContext; import ru.otus.l151.app.MsgChat; import ru.otus.l151.dataset.UserDataSet; import ru.otus.l151.db.MsgGetUserDataSet; import ru.otus.l151.db.MsgNewUserDataSet; import ru.otus.l151.messageSystem.Address; import ru.otus.l151.messageSystem.ControlBlock; import ru.otus.l151.messageSystem.Message; import ru.otus.l151.messageSystem.MessageSystem; import javax.websocket.Endpoint; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Created by tully. */ public abstract class FrontendEndpoint extends Endpoint implements FrontendService { private Address address; private MessageSystemContext context; private final Map<String, Long> users = new ConcurrentHashMap<>(); private final Map<Long, String> passwords = new ConcurrentHashMap<>(); public void init() { context.getMessageSystem().addAddressee(this); } void setAddress(Address address) { this.address = address; } void setContext(MessageSystemContext context) { this.context = context; } @Override public Address getAddress() { return address; } @Override public void handleRequest(Message message) { context.getMessageSystem().sendMessage(message); } @Override public MessageSystem getMS() { return context.getMessageSystem(); } @Override public void deliverString(ControlBlock control, String text) { /* none */ } @Override public void deliverUserDataSet(ControlBlock control, UserDataSet user) { if (null != user && user.getId() > -1) { users.put(user.getName(), user.getId()); passwords.put(user.getId(), user.getPassword()); } } public Message msgGetUserDataSet(ControlBlock control, String login) { return new MsgGetUserDataSet(getAddress(), context.getDbAddress(), control, login); } public Message msgNewUserDataSet(ControlBlock control, UserDataSet user) { return new MsgNewUserDataSet(getAddress(), context.getDbAddress(), control, user); } public Message msgChatUserDataSet(ControlBlock control, String login) { Address chatAddress = new Address("Frontend service chat"); return new MsgGetUserDataSet(chatAddress, context.getDbAddress(), control, login); } public Message msgChat(ControlBlock control, String text) { Address chatAddress = new Address("Frontend service chat"); return new MsgChat(chatAddress, chatAddress, control, text); } public long lookup(String username) { return users.getOrDefault(username, (long) -1); } public boolean isUserExists(String username) { return lookup(username) > -1; } public boolean auth(String username, String password) { long id = users.getOrDefault(username, (long) -1); if (id < 0) { return false; } String pwd = passwords.getOrDefault(id, null); return pwd != null && password.equals(pwd); } } /* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et */ //EOF
package com.takshine.wxcrm.service; import com.takshine.wxcrm.base.services.EntityService; import com.takshine.wxcrm.domain.Schedule; import com.takshine.wxcrm.message.error.CrmError; import com.takshine.wxcrm.message.sugar.ScheduleResp; /** * 日程任务 业务处理接口 * * @author liulin */ public interface Schedule2SugarService extends EntityService { /** * 查询 日程数据列表 * @return */ public ScheduleResp getScheduleList(Schedule sche,String source)throws Exception; /** * 查询单个日程数据 * @param rowId * @param crmId * @return */ public ScheduleResp getScheduleSingle(String rowId, String crmId,String schetype)throws Exception; /** * 保存日程信息 * @param obj * @return */ public CrmError addSchedule(Schedule obj); /** * 日程的完成操作 * @param rowId * @param crmId * @return */ public CrmError updateScheduleComplete(Schedule sche, String crmId); /** * * @param sche * @return */ public CrmError updateScheduleParent(Schedule sche); /** * 删除 * @param obj * @return */ public CrmError deleteSchedule(String rowid); }
package com.jim.multipos.ui.admin_main_page.fragments.dashboard.di; import android.support.v4.app.Fragment; import com.jim.multipos.config.scope.PerFragment; import com.jim.multipos.ui.admin_main_page.fragments.dashboard.OrdersFragment; import dagger.Binds; import dagger.Module; @Module public abstract class OrderModule { @Binds @PerFragment abstract Fragment provideFragment(OrdersFragment fragment); }
package thsst.calvis.configuration.model.exceptions; /** * Created by Goodwin Chua on 2/4/2016. */ public class ValueExceedException extends Exception { public ValueExceedException(String registerName) { super("Value of " + registerName + " exceeded. Values can only be between 2^-64 and 2^64."); } }
package com.dral.Chatter.permissions; import com.dral.Chatter.Chatter; import org.bukkit.entity.Player; import static com.dral.Chatter.Chatter.perms; import static com.dral.Chatter.Chatter.chatinfo; public class ChatterPermissionsHandler { Chatter plugin; public ChatterPermissionsHandler(Chatter plugin) { this.plugin = plugin; } /* * Info :D */ public String getInfo(Player player, String info) { String name = player.getName(); String world = player.getWorld().getName(); String group = perms.getPrimaryGroup(world, name); String groupstring = chatinfo.getGroupInfoString(world, group, info, null); String userstring = chatinfo.getPlayerInfoString(world, name, info, null); if (userstring != null && !userstring.isEmpty()) { return userstring; } if (group == null) { return ""; } if (groupstring == null) { return ""; } return groupstring; } public String getGroup(Player player) { String name = player.getName(); String world = player.getWorld().getName(); String group = plugin.perms.getPrimaryGroup(world, name); if (group == null) { return ""; } return group; } public Boolean checkPermissions(Player player, String node) { return checkPermissions(player, node, true); } public Boolean checkPermissions(Player player, String node, Boolean useOp) { if (plugin.perms.has(player, node)) { return true; } if (useOp) { return player.isOp(); } return player.hasPermission(node); } }
package com.smxknife.java2.io.reader; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; /** * @author smxknife * 2018/11/19 */ public class InputStreamReaderDemo { public static void main(String[] args) throws IOException { InputStreamReader inputStreamReader = new InputStreamReader(new ByteArrayInputStream("你好,hello".getBytes())); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); System.out.println(bufferedReader.readLine()); } }
package bartender.bardatabase; import java.io.FileReader; import java.util.HashMap; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import bartender.database.DatabaseSingelton; import bartender.mics.ProtocolCallback; import bartender.mics.ServiceCreator; import bartender.protocol.EchoProtocol; import bartender.services.*; public class Bar { public String name=""; public MessageBusImpl MessageBusImpl=new MessageBusImpl(); public BarStorage BarStorage=new BarStorage(); private HashMap<String, EchoProtocol> Users_=new HashMap<String, EchoProtocol>(); private HashMap<String, Table> Tables_=new HashMap<String, Table>(); public Bar(String name){ this.name=name; load(); } public void load (){ JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(name+".json")); JSONObject jsonObject = (JSONObject) obj; JSONArray companyList = (JSONArray) jsonObject.get("initialStorage"); BarStorageInfo [] items = new BarStorageInfo[companyList.size()]; //getting shoes and loading them to the store for (int i = 0 ; i<companyList.size() ; i++ ){ String curr = companyList.get(i).toString(); int start_amount = curr.indexOf("amount")+8; int finish_amount = curr.indexOf("shoeType")-2; String amount = curr.substring(start_amount, finish_amount); int start_shoeType = curr.indexOf("shoeType")+11; int finish_shoeType = curr.indexOf("}")-1; String type = curr.substring(start_shoeType, finish_shoeType); items[i]= new BarStorageInfo(type, Integer.parseInt(amount), 0); } BarStorage.load(items); JSONObject services = (JSONObject) jsonObject.get("services"); @SuppressWarnings("unchecked") Iterator<Object> iterator = services.entrySet().iterator(); //scanning the services while (iterator.hasNext()) { String curr = iterator.next().toString(); if (curr.contains("tables")){ for (int i=0; i<Integer.parseInt(curr.substring(7)); i++){ String istring = Integer.toString(i+1); Tables_.put(istring, new Table(istring)); } } } } catch (Exception e) { e.printStackTrace(); } } public void Buy(String item, String ammount, String myTable, ProtocolCallback<String> callback){ String [] args = {"request", item, myTable, ammount}; ServiceCreator creator = DatabaseSingelton.getInstance().serviceCreators.get("sender"); if (creator == null) { throw new IllegalArgumentException("unknown service type, supported types: " + DatabaseSingelton.getInstance().serviceCreators.keySet()); } new Thread(creator.create(callback, MessageBusImpl, BarStorage, args)).start(); } public void ListenToDiscount(ProtocolCallback<String> callback){ String [] args = {"5"}; ServiceCreator creator = DatabaseSingelton.getInstance().serviceCreators.get("brod-listener"); if (creator == null) { throw new IllegalArgumentException("unknown service type, supported types: " + DatabaseSingelton.getInstance().serviceCreators.keySet()); } new Thread(creator.create(callback, MessageBusImpl, BarStorage, args)).start(); } public void join (EchoProtocol incoming){ Users_.put(incoming.myName, incoming); } public BartenderService activateBartender (ProtocolCallback<String> callback){ BartenderService managerService = new BartenderService(callback, MessageBusImpl, BarStorage); new Thread(managerService).start(); return managerService; } public void sendDiscount (String item, String ammount,ProtocolCallback<String> callback){ String [] args = {"broadcast", item, ammount}; ServiceCreator creator = DatabaseSingelton.getInstance().serviceCreators.get("sender"); if (creator == null) { throw new IllegalArgumentException("unknown service type, supported types: " + DatabaseSingelton.getInstance().serviceCreators.keySet()); } new Thread(creator.create(callback, MessageBusImpl, BarStorage, args)).start(); } public HashMap<String, Table> getTables (){ return Tables_; } }
package com.example.cc.opencvtest; /** * Created by cc on 7/17/2015. */ public class EnumType { public enum Type{ } }
package com.designPattern.com.imooc.strategy; import com.designPattern.com.imooc.strategy.impl.FlyNoWay; /** * @Author : Admin * @Description : * @Date : 2018/6/28 10:55 */ public class BigYellow extends Duck{ public BigYellow() { super(); super.setFlyingStragety(new FlyNoWay()); } @Override public void display() { System.out.println("我身体很大,全身黄黄"); } }
package com.arkinem.libraryfeedbackservice.model; import java.util.UUID; import javax.validation.constraints.NotBlank; import com.fasterxml.jackson.annotation.JsonProperty; public class Vote { private final UUID id; @NotBlank private final Long timestamp; @NotBlank private final UUID questionId; private final UUID answerId; public Vote(@JsonProperty("id") UUID id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("questionId") UUID questionId, @JsonProperty("answerId") UUID answerId) { this.id = id; this.timestamp = timestamp; this.questionId = questionId; this.answerId = answerId; } public UUID getId( ) { return id; } public Long getTimestamp() { return timestamp; } public UUID getQuestionId() { return questionId; } public UUID getAnswerId() { return answerId; } }
package edu.jspiders.constructorinjection.beans; import java.io.Serializable; public class Mobile implements Serializable { private String serialNumber; private String brand; private String name; private double price; public Mobile() { System.out.println(this.getClass().getSimpleName()+" Object Created"); } public Mobile(String serialNumber, String brand, String name, double price) { System.out.println(this.getClass().getSimpleName()+" Object Created using arg-constructor(SN,Br,N,P)"); this.serialNumber = serialNumber; this.brand = brand; this.name = name; this.price = price; } public Mobile(String serialNumber,double price, String brand, String name) { System.out.println(this.getClass().getSimpleName()+" Object Created using arg-constructor(SN,P,Br,N)"); this.serialNumber = serialNumber; this.brand = brand; this.name = name; this.price = price; } public Mobile(double price,String serialNumber, String brand, String name) { System.out.println(this.getClass().getSimpleName()+" Object Created using arg-constructor(P,SN,Br,N)"); this.serialNumber = serialNumber; this.brand = brand; this.name = name; this.price = price; } public String getSerialNumber() { return serialNumber; } public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Mobile [serialNumber=" + serialNumber + ", brand=" + brand + ", name=" + name + ", price=" + price + "]"; } }
package c; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JOptionPane; import m.People; import m.Task; import v.Panel3; import m.SomeDataClass; /** * Class listening for action events from the button named 'save', inside the add people tab * * @author Samuel, Henry * */ public class ButtonListener3 implements ActionListener { private Panel3 panel3; private MainGUI mainGui; private People people; private SomeDataClass someData; /** * Constructor for ButtonListener3 * @param Panel3 panel3 * @param MainGUI mainGui * @param People people * @param SomeDataClass someData */ public ButtonListener3(Panel3 panel3, MainGUI mainGui , People people , SomeDataClass someData){ this.panel3=panel3; this.mainGui=mainGui; this.people=people; this.someData = someData; } /** * Method for the action of the button clicked *creates a new person and adds it to the arrayList of People *It sets back the values of the panel to its origin * @param ActionEvent e */ @Override public void actionPerformed(ActionEvent e) { JButton button = (JButton) e.getSource(); if(button.getName().equals("save")){ People thePeople = new People(panel3.getFirst(), panel3.getSurname() , panel3.getNum() , panel3.getCapacity() , someData); people.add_People(thePeople); panel3.getFirstNameField().setText(""); panel3.getSurnameField().setText(""); panel3.getEmployeeNoField().setText(""); panel3.getSkillSlider().setValue(5); } } }
package pattern_test.adapter.class_adapter; /** * Description: * * @author Baltan * @date 2019-04-02 14:42 */ public class StandardVoltage implements Voltage { @Override public void standardOutput() { System.out.println("电压:220V"); } }
package com.example.java.reflect; import java.util.Map; import java.util.ServiceLoader; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.xml.xpath.XPathFactory; import org.junit.Assert; import org.junit.Test; public class ClassForNamePerformanceDemo { @Test public void name() throws Exception { int totalCount = 100000; long start = System.currentTimeMillis(); for (int i = 0; i < totalCount; i++) { ServiceLoader<XPathFactory> load = ServiceLoader.load(XPathFactory.class); load.forEach(el -> {}); } System.out.println("ServiceLoader:" + (System.currentTimeMillis() - start) + "ms"); start = System.currentTimeMillis(); for (int i = 0; i < totalCount; i++) { Class.forName("com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl"); } System.out.println("Class.forName-SingleThread:" + (System.currentTimeMillis() - start) + "ms"); ExecutorService executorService = Executors.newFixedThreadPool(100); start = System.currentTimeMillis(); for (int i = 0; i < totalCount; i++) { executorService.submit(() -> { try { Class.forName("com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl"); } catch (ClassNotFoundException e) { e.printStackTrace(); } }); } executorService.shutdown(); boolean termination = executorService.awaitTermination(30, TimeUnit.SECONDS); Assert.assertTrue(termination); System.out.println("Class.forName-100Thread:" + (System.currentTimeMillis() - start) + "ms"); executorService = Executors.newFixedThreadPool(100); start = System.currentTimeMillis(); for (int i = 0; i < totalCount; i++) { executorService.submit(() -> { try { getClass().getClassLoader() .loadClass("com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl"); } catch (ClassNotFoundException e) { e.printStackTrace(); } }); } executorService.shutdown(); termination = executorService.awaitTermination(30, TimeUnit.SECONDS); Assert.assertTrue(termination); System.out.println("ClassLoader-100Thread:" + (System.currentTimeMillis() - start) + "ms"); Map<String, Object> pool = new ConcurrentHashMap<>(); pool.put("a", Class.forName("com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl")); executorService = Executors.newFixedThreadPool(100); start = System.currentTimeMillis(); for (int i = 0; i < totalCount; i++) { executorService.submit(() -> { try { pool.get("a"); } catch (RuntimeException e) { e.printStackTrace(); } }); } executorService.shutdown(); termination = executorService.awaitTermination(30, TimeUnit.SECONDS); Assert.assertTrue(termination); System.out.println("ObjectPool-100Thread:" + (System.currentTimeMillis() - start) + "ms"); } }
package com.xujiangjun.archetype.constant; /** * 应用内共享变量 * 包名统一使用单数形式,类名如果有复数含义,类名可以使用复数形式 * * @author xujiangjun * @since 2018.05.20 */ public interface ConfigConsts { /** IP白名单配置项 **/ String IP_WHITE_LIST = "ip_white_list"; }
package com.victoriachan.algorithmn; /** * @program: algorithm * @description: * @author: VictoriaChan * @create: 2020/03/14 21:23 **/ public class RandomListNode { int label; RandomListNode next = null; RandomListNode random = null; RandomListNode(int label) { this.label = label; } }
package com.halilayyildiz.game; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID; import com.halilayyildiz.game.model.IPlayer; import lombok.Data; @Data public class BaseGame { protected String id; protected int capacity; protected Map<String, IPlayer> players = Collections.synchronizedMap(new LinkedHashMap<>()); public BaseGame() { this.id = UUID.randomUUID().toString(); } }
package org.inftel.scrum.activities; import java.lang.reflect.Type; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import org.apache.http.message.BasicNameValuePair; import org.inftel.scrum.R; import org.inftel.scrum.lists.TareasAdapter; import org.inftel.scrum.modelXML.Proyecto; import org.inftel.scrum.modelXML.Tarea; import org.inftel.scrum.server.ServerRequest; import org.inftel.scrum.utils.Constantes; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.actionbarsherlock.app.SherlockListFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class ProyectoFragment extends SherlockListFragment { TextView nombreProyecto; TextView descripcionProyecto; TextView fechaEntrega; ListView listaTareas; ProgressBar barra; private TareasAdapter adapter; private ArrayList<Tarea> tareas; Proyecto p; private String jSessionId; ProgressDialog d; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.proyecto, container, false); View view2 = inflater.inflate(R.layout.dialogtareas, container, false); nombreProyecto = (TextView) view.findViewById(R.id.nombreProyecto); descripcionProyecto = (TextView) view .findViewById(R.id.descripcionProyecto); fechaEntrega = (TextView) view.findViewById(R.id.fechaProyecto); barra = (ProgressBar) view.findViewById(R.id.ProgressBar1); try { Context context = getActivity().getApplicationContext(); SharedPreferences prefs = context.getSharedPreferences( "loginPreferences", Context.MODE_PRIVATE); this.jSessionId = prefs.getString("jSessionId", "default_value"); Log.i("ProyectFragment", "JSessionId=" + this.jSessionId); // d = ServerRequest.compruebaConexionServer(this.getActivity()); realizarPeticion(); pedirBackLog(); } catch (Exception e) { ProgressDialog.show(this.getActivity().getApplicationContext(), getResources().getString(R.string.Error), getResources() .getString(R.string.Error_Indeterminado), true, true); } return view; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { menu.add("actualizar").setIcon(R.drawable.ic_actualizar) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); if (item.getTitle().toString().compareTo("actualizar") == 0) { realizarPeticion(); pedirBackLog(); } return true; } public void pedirBackLog() { try { ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(); parameters.add(new BasicNameValuePair("accion", Constantes.VER_BACKLOG)); parameters.add(new BasicNameValuePair("NOMBRE_PROYECTO", p .getNombre())); d=ProgressDialog.show(this.getSherlockActivity(), getResources().getString(R.string.espere), "", true, true); String datos = ServerRequest.send(this.jSessionId, parameters, "VER_BACKLOG"); d.dismiss(); Type listOfTestObject = new TypeToken<List<Tarea>>() { }.getType(); ArrayList<Tarea> list = new Gson() .fromJson(datos, listOfTestObject); p.setTareaList(list); barra.setMax(p.getTareaList().size()); int done = calcularTareasDone(); barra.setProgress(done); tareas = (ArrayList<Tarea>) p.getTareaList(); adapter = new TareasAdapter(this.getSherlockActivity() .getBaseContext(), tareas); setListAdapter(adapter); } catch (Exception e) { ProgressDialog.show(this.getActivity().getBaseContext(), getResources().getString(R.string.Error), getResources() .getString(R.string.Error_sin_proyectos), true, true); } } private int calcularTareasDone() { int done = 0; for (Tarea t : p.getTareaList()) { if (t.getDone().equals('2')) done++; } return done; } private void realizarPeticion() { ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(); parameters .add(new BasicNameValuePair("accion", Constantes.VER_PROYECTO)); try { d=ProgressDialog.show(this.getSherlockActivity(), getResources().getString(R.string.espere), "", true, true); String datos = ServerRequest.send(this.jSessionId, parameters, "VER_PROYECTO"); d.dismiss(); if (datos.compareTo("null") != 0) { p = new Gson().fromJson(datos, Proyecto.class); nombreProyecto.setText(p.getNombre()); descripcionProyecto.setText(p.getDescripcion()); SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy"); fechaEntrega.setText(formato.format(p.getEntrega())); } else { ProgressDialog.show(getActivity(), getResources().getString(R.string.Error), getResources().getString(R.string.Error_sin_proyectos), true, true); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onListItemClick(ListView l, View v, int position, long id) { Tarea t = p.getTareaList().get(position); Dialog dialog = new Dialog(getSherlockActivity()); dialog.setTitle(t.getDescripcion()); dialog.setContentView(R.layout.dialogtareas); try { ((TextView) dialog.findViewById(R.id.textTareaDuracionEstimada)) .setText(t.getDuracionEstimado().toString()); } catch (Exception e) { ((TextView) dialog.findViewById(R.id.textTareaDuracionEstimada)) .setText("0"); } try { ((TextView) dialog.findViewById(R.id.textTareaDuracion)).setText(t .getDuracion().toString()); } catch (Exception e) { ((TextView) dialog.findViewById(R.id.textTareaDuracion)).setText("0"); } try { ((TextView) dialog.findViewById(R.id.textTareaDescripcion)).setText(t .getDescripcion()); } catch (Exception e) { ((TextView) dialog.findViewById(R.id.textTareaDescripcion)).setText(""); } try { ((TextView) dialog.findViewById(R.id.textTareaViewPrioridad)).setText(t .getPrioridad().toString()); } catch (Exception e) { ((TextView) dialog.findViewById(R.id.textTareaViewPrioridad)).setText("0"); } try { ((TextView) dialog.findViewById(R.id.textTareaDone)).setText(t .getDone().toString()); } catch (Exception e) { } try { ((TextView) dialog.findViewById(R.id.textTotalHoras)).setText(t .getTotalHoras().toString()); } catch (Exception e) { } try { ((TextView) dialog.findViewById(R.id.textFechaInicio)).setText(t .getInicio().toString()); } catch (Exception e) { ((TextView) dialog.findViewById(R.id.textFechaInicio)) .setText(getResources().getString( R.string.estado_no_iniciado)); } try { ((TextView) dialog.findViewById(R.id.textFechaFin)).setText(t .getInicio().toString()); } catch (Exception e) { ((TextView) dialog.findViewById(R.id.textFechaFin)) .setText(getResources().getString( R.string.estado_finalizado)); } dialog.show(); } public String[] obtenerArray(ArrayList<Tarea> tareas) { String[] array = new String[tareas.size()]; for (int i = 0; i < array.length; i++) { array[i] = tareas.get(i).getDescripcion(); } return array; } }
package com.example.spring05.controller; import javax.inject.Inject; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.example.spring05.model.ReplyVO; import com.example.spring05.service.ReplyService; @Controller @RequestMapping(value="/reply/*") public class ReplyController { private static final Logger logger = LoggerFactory.getLogger(ReplyController.class); @Inject private ReplyService replyService; @RequestMapping(value="/list", method=RequestMethod.GET) public ModelAndView replyList(@RequestParam("bno") int bno, ModelAndView mav) throws Exception { logger.info("get reply list"); mav.setViewName("board/replyList"); mav.addObject("replyList", replyService.replyList(bno)); return mav; } @ResponseBody @RequestMapping(value="/write", method=RequestMethod.POST) public String replyWrite(@RequestBody ReplyVO reWrtVO, HttpSession session, Model model) throws Exception { logger.info("post reply write"); replyService.replyWrite(reWrtVO); model.addAttribute("bno", reWrtVO.getBno()); return "redirect:/board/view"; } @RequestMapping(value="view", method=RequestMethod.GET) public ModelAndView replyModify(ReplyVO reViewVO, ModelAndView mav) throws Exception { logger.info("get reply view"); mav.setViewName("board/replyModify"); mav.addObject("replyView", replyService.replyView(reViewVO)); return mav; } @ResponseBody @RequestMapping(value="modify", method=RequestMethod.POST) public String replyModify(@RequestBody ReplyVO reModVO, Model model) throws Exception { logger.info("post reply modify"); replyService.replyModify(reModVO); model.addAttribute("bno", reModVO.getBno()); return "redirect:/board/view"; } @ResponseBody @RequestMapping(value="/delete", method=RequestMethod.POST) public String replyDelete(@RequestBody ReplyVO reDelVO, Model model) throws Exception { logger.info("post reply delete"); replyService.replyDelete(reDelVO); model.addAttribute("bno", reDelVO.getBno()); return "redirect:/board/view"; } }
package com.sudipatcp.twopointers; import java.util.ArrayList; public class RemoveDuplicates2 { public static int removeDuplicates(ArrayList<Integer> a) { int i =0, j=1; while(j<a.size()){ int count = 1; while(j < a.size() && a.get(i).equals(a.get(j))){ j++; count++; } if(count > 1){ int dup = a.get(i+1); a.set(i+1, a.get(j-1)); a.set(j-1, dup); i++; if(i+1 != a.size()){ int unq = a.get(i+1); if(j != a.size()){ a.set(i+1, a.get(j)); a.set(j, unq); i++; } } j++; }else { int unq = a.get(i+1); a.set(i+1, a.get(j)); a.set(j, unq); i++; j++; } } System.out.println(a.subList(0,i+1)); return a.subList(0,i+1).size(); } public static void main(String[] args) { int a[] = { 2, 3, 3 }; ArrayList<Integer> listA = new ArrayList<Integer>(); for(int i : a){ listA.add(i); } System.out.println(removeDuplicates(listA)); } }
package org.springframework.fom.support.service; import java.io.File; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeSet; import javax.annotation.PostConstruct; import javax.validation.constraints.NotBlank; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.fom.Result; import org.springframework.fom.ScheduleContext; import org.springframework.fom.ScheduleInfo; import org.springframework.fom.ScheduleStatistics; import org.springframework.fom.logging.LogLevel; import org.springframework.fom.logging.LoggerConfiguration; import org.springframework.fom.logging.LoggingSystem; import org.springframework.fom.logging.log4j.Log4jLoggingSystem; import org.springframework.fom.support.Response; import org.springframework.util.Assert; import org.springframework.validation.annotation.Validated; /** * * @author shanhm1991@163.com * */ @Validated public class FomServiceImpl implements FomService, ApplicationContextAware{ @Value("${spring.fom.config.cache.enable:true}") private boolean configCacheEnable; @Value("${spring.fom.config.cache.path:cache/schedule}") private String configCachePath; private ApplicationContext applicationContext; private final Map<String, ScheduleContext<?>> scheduleMap = new HashMap<>(); private static LoggingSystem loggingSystem; static{ try{ loggingSystem = LoggingSystem.get(FomServiceImpl.class.getClassLoader()); }catch(IllegalStateException e){ System.err.println(e.getMessage()); } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @PostConstruct private void init(){ String[] scheduleNames = applicationContext.getBeanNamesForType(ScheduleContext.class); for(String scheduleName : scheduleNames){ scheduleMap.put(scheduleName, (ScheduleContext<?>)applicationContext.getBean(scheduleName)); } } @Override public List<ScheduleInfo> list() { List<ScheduleInfo> list = new ArrayList<>(scheduleMap.size()); for(ScheduleContext<?> schedule : scheduleMap.values()){ ScheduleInfo scheduleInfo = schedule.getScheduleInfo(); scheduleInfo.setLoggerLevel(getLoggerLevel(schedule.getScheduleName())); list.add(scheduleInfo); } return list; } @Override public ScheduleInfo info(String scheduleName) { ScheduleContext<?> schedule = scheduleMap.get(scheduleName); Assert.notNull(schedule, "schedule names " + scheduleName + " not exist."); return schedule.getScheduleInfo(); } @Override public ScheduleInfo info(Class<?> clazz) { if(ScheduleContext.class.isAssignableFrom(clazz)){ ScheduleContext<?> scheduleContext = (ScheduleContext<?>)applicationContext.getBean(clazz); Assert.notNull(scheduleContext, "schedule of " + clazz + " not exist."); return scheduleContext.getScheduleInfo(); } String[] beanNames = applicationContext.getBeanNamesForType(clazz); Assert.isTrue(beanNames != null && beanNames.length == 1, "cannot determine schedule by class:" + clazz); String beanName = beanNames[0]; ScheduleContext<?> scheduleContext = (ScheduleContext<?>)applicationContext.getBean("$" + beanName); Assert.notNull(scheduleContext, "schedule of " + clazz + " not exist."); return scheduleContext.getScheduleInfo(); } @Override public String getLoggerLevel(String scheduleName) { Assert.notNull(loggingSystem, "No suitable logging system located"); ScheduleContext<?> schedule = scheduleMap.get(scheduleName); Assert.notNull(schedule, "schedule names " + scheduleName + " not exist."); String loggerName = schedule.getLogger().getName(); if(loggingSystem instanceof Log4jLoggingSystem){ Log4jLoggingSystem log4jLoggingSystem = (Log4jLoggingSystem)loggingSystem; return log4jLoggingSystem.getLogLevel(loggerName); } LoggerConfiguration loggerConfiguration = loggingSystem.getLoggerConfiguration(loggerName); if(loggerConfiguration != null){ LogLevel logLevel = loggerConfiguration.getConfiguredLevel(); if(logLevel == null){ logLevel = loggerConfiguration.getEffectiveLevel(); } if(logLevel != null){ return logLevel.name(); } return "NULL"; }else{ // 向上找一个最近的父Logger List<LoggerConfiguration> list =loggingSystem.getLoggerConfigurations(); for(LoggerConfiguration logger : list){ String name = logger.getName(); if(name.startsWith(loggerName)){ LogLevel logLevel = logger.getConfiguredLevel(); if(logLevel == null){ logLevel = logger.getEffectiveLevel(); } if(logLevel != null){ return logLevel.name(); } } } return "NULL"; } } @Override public void updateloggerLevel( @NotBlank(message = "scheduleName cannot be empty.") String scheduleName, @NotBlank(message = "levelName cannot be empty.") String levelName) { Assert.notNull(loggingSystem, "No suitable logging system located"); ScheduleContext<?> schedule = scheduleMap.get(scheduleName); Assert.notNull(schedule, "schedule names " + scheduleName + " not exist."); String loggerName = schedule.getLogger().getName(); if(loggingSystem instanceof Log4jLoggingSystem){ Log4jLoggingSystem log4jLoggingSystem = (Log4jLoggingSystem)loggingSystem; log4jLoggingSystem.setLogLevel(loggerName, levelName); return; } try{ LogLevel level = LogLevel.valueOf(levelName); loggingSystem.setLogLevel(loggerName, level); }catch(IllegalArgumentException e){ throw new UnsupportedOperationException(levelName + " is not a support LogLevel."); } } @Override public Response<Void> start(String scheduleName) { ScheduleContext<?> schedule = scheduleMap.get(scheduleName); Assert.notNull(schedule, "schedule names " + scheduleName + " not exist."); return schedule.scheduleStart(); } @Override public Response<Void> shutdown(String scheduleName){ ScheduleContext<?> schedule = scheduleMap.get(scheduleName); Assert.notNull(schedule, "schedule names " + scheduleName + " not exist."); return schedule.scheduleShutdown(); } @Override public Response<Void> exec(String scheduleName) { ScheduleContext<?> schedule = scheduleMap.get(scheduleName); Assert.notNull(schedule, "schedule names " + scheduleName + " not exist."); return schedule.scheduleExecNow(); } @Override public Map<String, String> getWaitingTasks(String scheduleName) { ScheduleContext<?> schedule = scheduleMap.get(scheduleName); Assert.notNull(schedule, "schedule names " + scheduleName + " not exist."); return schedule.getWaitingTasks(); } @Override public List<Map<String, String>> getActiveTasks(String scheduleName) { ScheduleContext<?> schedule = scheduleMap.get(scheduleName); Assert.notNull(schedule, "schedule names " + scheduleName + " not exist."); return schedule.getActiveTasks(); } @Override public Map<String, Object> getSuccessStat(String scheduleName, String statDay) throws ParseException { ScheduleContext<?> schedule = scheduleMap.get(scheduleName); Assert.notNull(schedule, "schedule names " + scheduleName + " not exist."); return schedule.getSuccessStat(statDay); } @Override public Map<String, Object> saveStatConf(String scheduleName, String statDay, String statLevel, int saveDay) throws ParseException { ScheduleContext<?> schedule = scheduleMap.get(scheduleName); Assert.notNull(schedule, "schedule names " + scheduleName + " not exist."); Map<String, Object> successStat = null; ScheduleStatistics scheduleStatistics = schedule.getScheduleStatistics(); if(scheduleStatistics.setLevel(statLevel.split(","))){ successStat = schedule.getSuccessStat(statDay); } scheduleStatistics.setSaveDay(saveDay); return successStat; } @Override public List<Map<String, String>> getFailedStat(String scheduleName){ ScheduleContext<?> schedule = scheduleMap.get(scheduleName); Assert.notNull(schedule, "schedule names " + scheduleName + " not exist."); return schedule.getFailedStat(); } @Override public void saveConfig(String scheduleName, HashMap<String, Object> map) throws Exception { ScheduleContext<?> schedule = scheduleMap.get(scheduleName); Assert.notNull(schedule, "schedule names " + scheduleName + " not exist."); schedule.saveConfig(map, true); if(configCacheEnable){ File dir = new File(configCachePath); if(!dir.exists() && !dir.mkdirs()){ return; } File cacheFile = new File(dir.getPath() + File.separator + scheduleName + ".cache"); if(cacheFile.exists()){ cacheFile.delete(); } Map<String, Object> configMap = schedule.getScheduleConfig().getConfMap(); try(FileOutputStream out = new FileOutputStream(cacheFile); ObjectOutputStream oos = new ObjectOutputStream(out)){ oos.writeObject(configMap); } } } @Override public String buildExport(@NotBlank(message = "scheduleName cannot be empty.") String scheduleName) { ScheduleContext<?> schedule = scheduleMap.get(scheduleName); Assert.notNull(schedule, "schedule names " + scheduleName + " not exist."); ScheduleStatistics scheduleStatistics = schedule.getScheduleStatistics(); Map<String, List<Result<?>>> success = scheduleStatistics.copySuccessMap(); Map<String, List<Result<?>>> faield = scheduleStatistics.copyFaieldMap(); TreeSet<String> daySet = new TreeSet<>(); daySet.addAll(success.keySet()); daySet.addAll(faield.keySet()); DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss SSS"); StringBuilder builder = new StringBuilder(); for(String day : daySet){ List<Result<?>> slist = success.get(day); if(slist != null){ builder.append(day).append(" success:").append("\n"); for(Result<?> result : slist){ builder.append(result.getTaskId()).append(", "); builder.append("submitTime=").append(dateFormat.format(result.getSubmitTime())).append(", "); builder.append("startTime=").append(dateFormat.format(result.getStartTime())).append(", "); builder.append("cost=").append(result.getCostTime()).append("ms, "); builder.append("result=").append(result.getContent()).append("\n"); } builder.append("\n"); } List<Result<?>> flist = faield.get(day); if(flist != null){ builder.append(day).append(" failed:").append("\n"); for(Result<?> result : flist){ builder.append(result.getTaskId()).append(", "); builder.append("submitTime=").append(dateFormat.format(result.getSubmitTime())).append(", "); builder.append("startTime=").append(dateFormat.format(result.getStartTime())).append(", "); builder.append("cost=").append(result.getCostTime()).append("ms, "); Throwable throwable = result.getThrowable(); if(throwable == null){ builder.append("cause=null").append("\n"); }else{ Throwable cause = throwable; while((cause = throwable.getCause()) != null){ throwable = cause; } builder.append("cause=").append(throwable.toString()).append("\n"); for(StackTraceElement stack : throwable.getStackTrace()){ builder.append(stack).append("\n"); } } } builder.append("\n"); } } return builder.toString(); } }
package com.epam.restaurant.controller.command.impl; import com.epam.restaurant.controller.name.JspPageName; import com.epam.restaurant.controller.command.exception.CommandException; import com.epam.restaurant.controller.command.Command; import com.epam.restaurant.entity.Category; import com.epam.restaurant.service.CategoryService; import com.epam.restaurant.service.exception.ServiceException; import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; import static com.epam.restaurant.controller.name.RequestParameterName.*; /** * Control menu output. */ public class MenuCommand implements Command { /** * Service provides work with database (category table) */ private static final CategoryService categoryService = CategoryService.getInstance(); /** * Set all categories to request. * If everything is fine, return menu page value. * * @return page to forward to * @throws CommandException if can't get all categories */ @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws CommandException { String page = JspPageName.MENU_JSP; try { List<Category> categoryList = categoryService.getAllCategories(); if (categoryList != null) { request.setAttribute(CATEGORIES, categoryList); } } catch (ServiceException e) { throw new CommandException("Cant't execute MenuCommand", e); } return page; } }
/** * <copyright> * </copyright> * * $Id$ */ package BPMN; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Event Eskalation Bold Invert</b></em>'. * <!-- end-user-doc --> * * * @see BPMN.BPMNPackage#getBPMNEventEskalationBoldInvert() * @model * @generated */ public interface BPMNEventEskalationBoldInvert extends BPMNModelElement { } // BPMNEventEskalationBoldInvert
package com.xiaoxiao.controller; import com.xiaoxiao.pojo.XiaoxiaoAdvertising; import com.xiaoxiao.service.backend.AdvertisingService; import com.xiaoxiao.utils.Result; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * _ooOoo_ * o8888888o * 88" . "88 * (| -_- |) * O\ = /O * ____/`---'\____ * .' \\| |// `. * / \\||| : |||// \ * / _||||| -:- |||||- \ * | | \\\ - /// | | * | \_| ''\---/'' | | * \ .-\__ `-` ___/-. / * ___`. .' /--.--\ `. . __ * ."" '< `.___\_<|>_/___.' >'"". * | | : `- \`.;`\ _ /`;.`/ - ` : | | * \ \ `-. \_ __\ /__ _/ .-` / / * ======`-.____`-.___\_____/___.-`____.-'====== * `=---=' * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * 佛祖保佑 永无BUG * 佛曰: * 写字楼里写字间,写字间里程序员; * 程序人员写程序,又拿程序换酒钱。 * 酒醒只在网上坐,酒醉还来网下眠; * 酒醉酒醒日复日,网上网下年复年。 * 但愿老死电脑间,不愿鞠躬老板前; * 奔驰宝马贵者趣,公交自行程序员。 * 别人笑我忒疯癫,我笑自己命太贱; * 不见满街漂亮妹,哪个归得程序员? * * @project_name:xiaoxiao_final_blogs * @date:2019/12/16:18:41 * @author:shinelon * @Describe: */ @RestController @RequestMapping(value = "/admin/backend_advertising") @CrossOrigin(origins = "*",maxAge = 3600) @Api(value = "广告管理") public class AdvertisingController { @Autowired private AdvertisingService advertisingService; /** *查询全部的广告数据 * @param page * @param rows * @return */ @PostMapping(value = "/findAllAdvertising") public Result findAllAdvertising(@RequestParam(name = "page",defaultValue = "1") Integer page, @RequestParam(name = "rows",defaultValue = "10") Integer rows){ return this.advertisingService.findAllAdvertising(page,rows); } /** * 删除广告数据 * @param advertisingId * @return */ @PostMapping(value = "/deleteAdvertising") public Result deleteAdvertising(@RequestParam(name = "advertisingId") String advertisingId){ return this.advertisingService.deleteAdvertising(advertisingId); } /** * 根据ID获取 * @param advertisingId * @return */ @PostMapping(value = "/findAdvertisingById") public Result findAdvertisingById(@RequestParam(name = "advertisingId") String advertisingId){ return this.advertisingService.findAdvertisingById(advertisingId); } /** * 插入 * @param advertising * @return */ @PostMapping(value = "/insert") public Result insert(@RequestBody XiaoxiaoAdvertising advertising){ return this.advertisingService.insert(advertising); } /** * 修改 * @param advertising * @return */ @PostMapping(value = "/update") public Result update(@RequestBody XiaoxiaoAdvertising advertising){ return this.advertisingService.update(advertising); } @ApiOperation(value = "获取首页的广告位值",response = Result.class,notes = "获取首页的广告位值") @PostMapping(value = "/onto") public Result onto(@RequestParam(name = "advertisingId") String advertisingId){ return this.advertisingService.onto(advertisingId); } }
package great_class07; /** * Created by likz on 2023/4/14 * 给定一个正数组成的数组,长度一定大于1,求数组中哪两个数与的结果最大 * * @author likz */ public class Class01_MaxAndValue { /** * 暴力方法 O(n^2) 时间复杂度 * @param arr 入参 * @return ans */ public static int maxAndValue(int[] arr){ int ans = arr[0] & arr[1]; for(int i = 0; i < arr.length; i++){ for (int j = i + 1; j < arr.length; j++){ ans = Math.max(ans, arr[i] & arr[j]); } } return ans; } private static int maxAndValue2(int[] arr) { int M = arr.length; int ans = 0; for (int bit = 30; bit >= 0; bit--){ int i = 0; int temp = M; // arr[0...M-1] while(i < M){ if (((arr[i] >> bit) & 1) == 0){ swap(arr, i, --M); } else { i++; } } // arr[0] & arr[1] if (M == 2){ return arr[0] & arr[1]; } if (M < 2){ M = temp; } else { ans |= (1 << bit); } } return ans; } public static void swap(int[] arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static int[] generateRomdomArray(int size, int maxValue){ int[] res = new int[size]; for (int i = 0; i < size; i++){ res[i] = (int) (Math.random() * (maxValue + 1)); } return res; } public static void main(String[] args) { int maxSize = 50; int maxValue = 100; int times = 100000; int[] arr; System.out.println("test begin!"); for (int i = 0; i < times; i++){ int size = 2 + (int)(Math.random() * maxSize); arr = generateRomdomArray(size, maxValue); if (maxAndValue(arr) != maxAndValue2(arr) ){ System.out.println("Oops!"); break; } } System.out.println("test finish!"); } }