text
stringlengths
10
2.72M
package com.example.user.kurswork; import android.app.AlarmManager; import android.app.DatePickerDialog; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Color; import android.graphics.Typeface; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.InputFilter; import android.util.DisplayMetrics; import android.view.Display; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.RelativeLayout; import java.util.Calendar; import java.util.GregorianCalendar; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private MyThread myThread; private MyEdittext []editTexts = new MyEdittext[5]; private EditTime []time = new EditTime[5]; DBHelper dbHelper; private Integer counter=1; private String currDate; private boolean setDate=false; private boolean SwipedRight=false; private boolean SwipedLeft=false; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); createGui(); } private void createGui(){ RelativeLayout relativeLayout = new RelativeLayout(this); dbHelper = new DBHelper(this); Button button = new Button(this); Display display = getWindowManager().getDefaultDisplay(); DisplayMetrics metricsB = new DisplayMetrics(); display.getMetrics(metricsB); GregorianCalendar gregorianCalendar = new GregorianCalendar(); if (!setDate){ currDate=String.valueOf(gregorianCalendar.get(Calendar.DATE))+ "." + String.valueOf(gregorianCalendar.get(Calendar.MONTH)+1)+"."+ String.valueOf(gregorianCalendar.get(Calendar.YEAR)); } button.setText(currDate); button.setVisibility(View.VISIBLE); Typeface typeface=Typeface.create(Typeface.SERIF, Typeface.ITALIC); button.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/cac-champagne.ttf")); button.setTextSize(50); button.setY(20); button.setX(metricsB.widthPixels/4); button.getBackground().setAlpha(0); Button buttonForward = new Button(this); if (counter==1){ buttonForward.setVisibility(View.VISIBLE); buttonForward.setEnabled(true); }else{ buttonForward.setVisibility(View.GONE); buttonForward.setEnabled(false); } buttonForward.setX(metricsB.widthPixels/1.3f); buttonForward.setY(40); buttonForward.setBackgroundResource(R.drawable.strelka); buttonForward.setId(Integer.parseInt("1")); buttonForward.setOnClickListener(this); Button buttonBack = new Button(this); if (counter==10) { buttonBack.setVisibility(View.VISIBLE); buttonBack.setEnabled(true); }else{ buttonBack.setVisibility(View.GONE); buttonBack.setEnabled(false); } buttonBack.setX(0); buttonBack.setY(40); buttonBack.setBackgroundResource(R.drawable.strelka1); buttonBack.setOnClickListener(this); buttonBack.setId(Integer.parseInt("2")); float p = metricsB.heightPixels/5f; for (int i=0; i<time.length; ++i){ EditTime text = new EditTime(this, i, counter, currDate, dbHelper) ; text.setEnabled(true); text.setTextColor(Color.BLACK); text.setTypeface(typeface); text.setTextSize(20); text.setText(""); text.setBackgroundColor(Color.TRANSPARENT); text.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); text.setHeight(170); text.setWidth(220); text.setHint("00:00"); text.setFilters(new InputFilter[] { new InputFilter.LengthFilter(5) }); text.setInputType(4); text.setVisibility(View.VISIBLE); text.setY(p); text.setX(metricsB.widthPixels/1.45f); text.setZ(10); time[i]=text; time[i].setOnFocusChangeListener(new MyTextWatcher(this, i, counter, currDate, dbHelper)); p = p+metricsB.heightPixels/8f; } myThread = new MyThread(time, dbHelper, counter, currDate); myThread.execute(); p = metricsB.heightPixels/5.5f; for (int i=0; i<editTexts.length; ++i){ MyEdittext textView = new MyEdittext(this, time[i], i, counter, currDate, dbHelper) ; textView.setEnabled(true); textView.setTextColor(Color.BLACK); textView.setTypeface(typeface); textView.setTextSize(20); textView.setBackgroundColor(Color.TRANSPARENT); textView.setFilters(new InputFilter[] { new InputFilter.LengthFilter(35) }); textView.setHeight(metricsB.heightPixels/10+30); textView.setWidth((int) ((int) metricsB.widthPixels/1.7f)); textView.setVisibility(View.VISIBLE); textView.setY(p); textView.setZ(10); editTexts[i]=textView; editTexts[i].setOnFocusChangeListener(new FocusChangerForMyEdittext(i, counter, currDate, dbHelper, time[i])); p = p+metricsB.heightPixels/8; } myThread = new MyThread(editTexts, dbHelper, counter, currDate); myThread.execute(); Typeface typeface1 = Typeface.createFromAsset(getAssets(), "fonts/cac-champagne.ttf"); Draw draw = new Draw(this, typeface1, counter, display); draw.setZ(1); button.setOnClickListener(this); for (int i=0; i<editTexts.length; ++i){ relativeLayout.addView(editTexts[i]); } for (int i=0; i<time.length; ++i){ relativeLayout.addView(time[i]); } relativeLayout.addView(button); relativeLayout.addView(buttonForward); relativeLayout.addView(buttonBack); draw.setBackgroundResource(R.drawable.back); relativeLayout.addView(draw); setContentView(relativeLayout); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); AlarmManager mgr=(AlarmManager)this.getSystemService(Context.ALARM_SERVICE); Intent i=new Intent(this, DateRecieve.class); PendingIntent pi=PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT); mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 2000, pi); } private void addToSQL(boolean flag, EditText[] editTexts, int count){ SQLiteDatabase database = dbHelper.getWritableDatabase(); for (int i=0; i<editTexts.length; ++i){ ContentValues cv = new ContentValues(); String task; String time; String t = editTexts[i].getText().toString(); String strDate = currDate; if (!( t.equals(""))) { if (flag) { task = editTexts[i].getText().toString(); cv.put("value", String.valueOf(i)); cv.put("task", task); cv.put("page", count); cv.put("date", strDate ); Cursor cursor = database.query("myDb", null, null, null, null, null, null); while (cursor.moveToNext()) { if ((cursor.getString(cursor.getColumnIndexOrThrow("value")).equals(String.valueOf(i))) && (cursor.getString(cursor.getColumnIndexOrThrow("page")).equals(String.valueOf(count)))&& (cursor.getString(cursor.getColumnIndexOrThrow("date")).equals(String.valueOf(strDate)))){ database.delete("myDb", "value=? AND page=? AND date=?", new String[] {String.valueOf(i),String.valueOf(count), strDate}); database.insert("myDb", null, cv); break; } } if (cursor.isAfterLast()) { database.insert("myDb", null, cv); } else { continue; } } else { time = editTexts[i].getText().toString(); cv.put("time", time); cv.put("page", count); cv.put("date", strDate ); Cursor cursor = database.query("myDb", null, null, null, null, null, null); while (cursor.moveToNext()) { if ((cursor.getString(cursor.getColumnIndexOrThrow("value")).equals(String.valueOf(i))) && (cursor.getString(cursor.getColumnIndexOrThrow("page")).equals(String.valueOf(count)))&& (cursor.getString(cursor.getColumnIndexOrThrow("date")).equals(String.valueOf(strDate)))){ database.update("myDb", cv, "value=? AND page=? AND date=?", new String[] {String.valueOf(i),String.valueOf(count), strDate}); break; } } } } else{ if (flag) { try { Cursor cursor = database.query("myDb", null, null, null, null, null, null); while (cursor.moveToNext()) { if ((cursor.getString(cursor.getColumnIndexOrThrow("value")).equals(String.valueOf(i))) && (cursor.getString(cursor.getColumnIndexOrThrow("page")).equals(String.valueOf(count)))&& (cursor.getString(cursor.getColumnIndexOrThrow("date")).equals(String.valueOf(strDate)))){ database.delete("myDb", "value=? AND page=? AND date=?", new String[] {String.valueOf(i),String.valueOf(count), strDate}); break; } } }catch (Exception e){ continue; } } } // dbHelper.close(); } } @Override protected void onDestroy() { if ((!SwipedRight)&&(!SwipedLeft)){ addToSQL(true, editTexts, 1); addToSQL(false, time, 1); }else if ((SwipedRight)&&(!SwipedLeft)) { addToSQL(true, editTexts, 10); addToSQL(false, time, 10); } else{} super.onDestroy(); } @Override protected void onStop() { addToSQL(true, editTexts, counter); addToSQL(false, time, counter); super.onStop(); } protected void onPause() { addToSQL(true, editTexts, counter); addToSQL(false, time, counter); super.onPause(); } @Override public void onClick(View v) { switch (v.getId()) { case 1:{ SwipeRight(); break; } case 2:{ SwipeLeft(); break; } default: { GregorianCalendar calendar = new GregorianCalendar(); int myYear = calendar.get(Calendar.YEAR); int myMonth = calendar.get(Calendar.MONTH); int myDay = calendar.get(Calendar.DATE); DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) { String year = String.valueOf(selectedYear); String month = String.valueOf(selectedMonth + 1); String day = String.valueOf(selectedDay); currDate = (day + "." + month + "." + year); setDate = true; createGui(); } }; DatePickerDialog datePicker = new DatePickerDialog(this, R.style.Theme_AppCompat_Light_Dialog_Alert, datePickerListener, myYear, myMonth, myDay); datePicker.setTitle("Select the date"); datePicker.show(); break; } } } private void SwipeLeft() { counter = counter / 10; if (counter == 1) { addToSQL(true, editTexts, 10); addToSQL(false, time, 10); SwipedLeft = true; SwipedRight = false; createGui(); } else { counter = 1; } } private void SwipeRight(){ counter = counter*10; if (counter>10){ counter=10; } else { addToSQL(true, editTexts, 1); addToSQL(false, time, 1); SwipedRight=true; SwipedLeft=false; createGui(); } } public void onBackPressed() { if ((!SwipedRight)&&(!SwipedLeft)){ addToSQL(true, editTexts, 1); addToSQL(false, time, 1); }else if ((SwipedRight)&&(!SwipedLeft)) { addToSQL(true, editTexts, 10); addToSQL(false, time, 10); } else{} moveTaskToBack(true); } }
import dataFactory.DataFactory; import dataFactory.HotelDataHelper; import dataFactory.impl.DataFactoryImpl; import dataServiceImpl.HotelDataServiceImpl; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import po.HotelInfoPO; import java.util.Map; /** * HotelDataServiceImpl Tester. * * @author <Authors name> * @since <pre>十一月 30, 2016</pre> * @version 1.0 */ public class HotelDataServiceImplTest { private Map<String, HotelInfoPO> hotelInfoPOMap; private static HotelDataServiceImpl hotelDao; private DataFactory dataFactory; private HotelDataHelper hotelDataHelper; @Before public void setUp() throws Exception { hotelDao = HotelDataServiceImpl.getInstance(); if(hotelInfoPOMap == null){ dataFactory = new DataFactoryImpl() ; hotelDataHelper = dataFactory.getHotelDataHelper(); hotelInfoPOMap = hotelDataHelper.getHotelInfoData(); } } @After public void after() throws Exception { } /** * 测试已通过 */ @Test @Ignore public void testFindHotelInfo() { /* HotelInfoPO hipo = hotelDao.findHotelInfo("如家酒店(仙林)"); assertEquals("如家酒店(仙林)", hipo.getHotelName()); assertEquals("南京", hipo.getCity()); assertEquals("仙林", hipo.getBusinessCircle()); assertEquals("仙林大道163号", hipo.getAddress()); assertEquals("交通方便", hipo.getIntroduction()); assertEquals("热水24小时供应", hipo.getFacility()); assertEquals(3, hipo.getStarLevel()); assertEquals("网易;阿里", hipo.getCooperCompany()); assertEquals(4.0, hipo.getScore()); */ } /** * 测试已通过 */ @Test @Ignore public void testUpdateHotelInfo() { /* HotelInfoPO hipo = new HotelInfoPO("如家酒店(新街口)", null, null, "南京市新街口123号", "娱乐设施完善", "空调、热水24小时供应", -1, "网易;腾讯", 4.2); boolean result = hotelDao.updateHotelInfo(hipo); if(result) { hipo = hotelDao.findHotelInfo("如家酒店(新街口)"); assertEquals("如家酒店(新街口)", hipo.getHotelName()); assertEquals("南京", hipo.getCity()); assertEquals("新街口", hipo.getBusinessCircle()); assertEquals("南京市新街口123号", hipo.getAddress()); assertEquals("娱乐设施完善", hipo.getIntroduction()); assertEquals("空调、热水24小时供应", hipo.getFacility()); assertEquals(4, hipo.getStarLevel()); assertEquals("网易;腾讯", hipo.getCooperCompany()); assertEquals(4.2, hipo.getScore()); }else { System.out.println("当前酒店不存在!"); } */ } /** * 测试已通过 */ @Test @Ignore public void testFindHotels() { /* ArrayList<HotelInfoPO> hotelList = new ArrayList<HotelInfoPO>(); Iterator<Map.Entry<String, HotelInfoPO>> iterator = hotelInfoPOMap.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry<String, HotelInfoPO> entry = iterator.next(); HotelInfoPO hotelInfoPO = entry.getValue(); hotelList.add(hotelInfoPO); } assertEquals(hotelList.get(0).getAddress(), hotelDao.findHotels().get(0).getAddress()); */ } /** * 测试已通过 */ @Test @Ignore public void testInsertHotel() { /* HotelInfoPO hipo = new HotelInfoPO("和东酒店(仙林)", "南京", "仙林", "南京市新街口123号", "娱乐设施完善", "空调、热水24小时供应", 5, "网易;腾讯", 4.0); boolean result = hotelDao.insertHotel(hipo); if(result) { hipo = hotelDao.findHotelInfo("和东酒店(仙林)"); assertEquals("和东酒店(仙林)", hipo.getHotelName()); assertEquals("南京", hipo.getCity()); assertEquals("仙林", hipo.getBusinessCircle()); assertEquals("南京市新街口123号", hipo.getAddress()); assertEquals("娱乐设施完善", hipo.getIntroduction()); assertEquals("空调、热水24小时供应", hipo.getFacility()); assertEquals(5, hipo.getStarLevel()); assertEquals("网易;腾讯", hipo.getCooperCompany()); assertEquals(4.0, hipo.getScore()); }else { System.out.println("酒店已存在!"); } */ } /** * 测试已通过 */ @Test @Ignore public void testUpdateHotelScore() { /* boolean result = hotelDao.updateHotelScore("如家酒店(新街口)", 2); if(result) { HotelInfoPO hipo = hotelDao.findHotelInfo("如家酒店(新街口)"); assertEquals(3.1, hipo.getScore()); }else { System.out.println("酒店不存在!"); } */ } }
package models; public class Utente { private String nome; private String cognome; private String email; private String pass; private int saldo; private String image; private boolean active; public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public Utente(String nome, String cognome,String email,String pass, int saldo,String image,boolean active) { this.nome=nome; this.cognome=cognome; this.email=email; this.pass=pass; this.saldo=saldo; this.image=image; this.active=active; } public int getSaldo() { return saldo; } public void setSaldo(int saldo) { this.saldo = saldo; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCognome() { return cognome; } public void setCognome(String cognome) { this.cognome = cognome; } }
package nobile.riccardo.harbour; public interface CalcolaIndiceP { int calcolaIndiceP(); }
package com.cdkj.util; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; /** * JFinal2.0文件上传重命名策略 * * @author L.cm * email: 596392912@qq.com * site:http://www.dreamlu.net * date 2015年7月10日下午11:23:25 */ public class UpFileRenamePolicy { public static String rename(String path, String name, boolean hasParents) { // 获取webRoot目录 // 用户设置的默认上传目录 String saveDir = path; //String saveDir = ""; SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy"); // 添加时间作为目录 SimpleDateFormat dateFormat = new SimpleDateFormat("MMdd"); String sYear = yearFormat.format(new Date()); String sDate = dateFormat.format(new Date()); String uuid = UUID.randomUUID().toString(); String ext = getFileExt(name); StringBuilder fileName = new StringBuilder(""); if (hasParents) { StringBuilder dirPath = new StringBuilder("") .append(saveDir == null ? "file" : saveDir) .append(File.separator) .append(sYear) .append(File.separator) .append(sDate); File dir = new File(dirPath.toString()); if (!dir.exists()) { dir.mkdirs(); } fileName.append(File.separator) .append(sYear) .append(File.separator) .append(sDate) .append(File.separator) .append(uuid) .append(ext); File dest = new File(fileName.toString()); // 创建上层目录 File dir1 = dest.getParentFile(); if (!dir1.exists()) { dir1.mkdirs(); } } else { fileName.append(uuid) .append(ext); } return fileName.toString(); } /** * 获取文件后缀 * * @param @param fileName * @param @return 设定文件 * @return String 返回类型 */ public static String getFileExt(String fileName) { return fileName.substring(fileName.lastIndexOf('.'), fileName.length()); } }
package com.radauer.mathrix.types; import com.radauer.mathrix.GroupKey; /** * Allows an API user to implement a Factory for GroupKeys based on its own group or column types */ public interface GroupKeyFactory<T> { GroupKey getGroupKey(T specificGroupKey); }
/* $Id$ */ package djudge.exceptions; public class DJudgeXmlCorruptedException extends DJudgeXmlException { private static final long serialVersionUID = 1L; }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.ow2.proactive.scheduler.resourcemanager.nodesource.policy; import java.util.Timer; import java.util.TimerTask; import org.objectweb.proactive.Body; import org.objectweb.proactive.InitActive; import org.objectweb.proactive.api.PAActiveObject; import org.objectweb.proactive.core.util.wrapper.BooleanWrapper; import org.objectweb.proactive.extensions.annotation.ActiveObject; import org.ow2.proactive.resourcemanager.nodesource.common.Configurable; import org.ow2.proactive.scheduler.common.NotificationData; import org.ow2.proactive.scheduler.common.SchedulerEvent; import org.ow2.proactive.scheduler.common.SchedulerEventListener; import org.ow2.proactive.scheduler.common.job.JobInfo; import org.ow2.proactive.scheduler.common.job.JobState; @ActiveObject public class ReleaseResourcesWhenSchedulerIdle extends SchedulerAwarePolicy implements InitActive, SchedulerEventListener { /** */ private static final long serialVersionUID = 31L; private transient Timer timer; private int activeJobs = 0; @Configurable(description = "ms") private long idleTime = 60 * 1000; // 1 min by default private boolean resourcesReleased = true; private ReleaseResourcesWhenSchedulerIdle thisStub; public ReleaseResourcesWhenSchedulerIdle() { } /** * Configure a policy with given parameters. * @param policyParameters parameters defined by user */ @Override public BooleanWrapper configure(Object... policyParameters) { super.configure(policyParameters); try { timer = new Timer(true); idleTime = Long.parseLong(policyParameters[4].toString()); } catch (RuntimeException e) { throw new IllegalArgumentException(e); } return new BooleanWrapper(true); } public void initActivity(Body body) { thisStub = (ReleaseResourcesWhenSchedulerIdle) PAActiveObject.getStubOnThis(); } @Override public BooleanWrapper activate() { BooleanWrapper activationStatus = super.activate(); if (!activationStatus.getBooleanValue()) { return activationStatus; } activeJobs = state.getPendingJobs().size() + state.getRunningJobs().size(); debug("Policy is activated. Current number of jobs is " + activeJobs); return new BooleanWrapper(true); } @Override protected SchedulerEvent[] getEventsList() { return new SchedulerEvent[] { SchedulerEvent.JOB_RUNNING_TO_FINISHED, SchedulerEvent.JOB_PENDING_TO_FINISHED, SchedulerEvent.JOB_SUBMITTED }; } @Override protected SchedulerEventListener getSchedulerListener() { return thisStub; } @Override public String getDescription() { return "Releases all resources when scheduler is idle for specified\ntime. Acquires them back on job submission."; } @Override public String toString() { return super.toString() + " [idle time: " + idleTime + " ms]"; } @Override public void jobSubmittedEvent(JobState jobState) { activeJobs++; debug("Job is submitted. Total number of jobs is " + activeJobs); timer.cancel(); if (activeJobs > 0 && resourcesReleased) { synchronized (timer) { acquireAllNodes(); resourcesReleased = false; } } } @Override public void jobStateUpdatedEvent(NotificationData<JobInfo> notification) { switch (notification.getEventType()) { case JOB_PENDING_TO_FINISHED: case JOB_RUNNING_TO_FINISHED: activeJobs--; debug("Job is finished. Total number of jobs is " + activeJobs); if (activeJobs == 0 && !resourcesReleased) { debug("Schedule task to release resources in " + idleTime); timer = new Timer(true); timer.schedule(new TimerTask() { @Override public void run() { synchronized (timer) { thisStub.removeAllNodes(false); resourcesReleased = true; } } }, idleTime); } break; } } }
/* * 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 scheduling; import java.awt.Dialog; import java.util.ArrayList; import javax.swing.JFrame; import static scheduling.AddGenerator.InfoGENCO; import static scheduling.AddGenerator.prov_address1; import static scheduling.AddGenerator.prov_address2; import static scheduling.AddGenerator.prov_email; import static scheduling.AddGenerator.prov_name; /** * * @author AfonsoMCardoso */ public class EnterGENCO extends javax.swing.JFrame { private static ErrorMessage errormess; private static AddGenerator addgen1; static String Name; public static ArrayList<String> personal_info = new ArrayList<>(); /** * Creates new form EnterGENCO */ public EnterGENCO(String name) { Name=name; initComponents(); this.setTitle("Genco Information"); this.setResizable(false); this.setAlwaysOnTop(true); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setModalExclusionType(Dialog.ModalExclusionType.NO_EXCLUDE); try{ Import_export.LoadGencoINFO(Name); personal_info.add(prov_name); prov_address1 = Address1.getText(); personal_info.add( prov_address1); prov_address2 = Address2.getText(); personal_info.add( prov_address2); prov_email = mail1.getText(); personal_info.add(prov_email); }catch(Exception e){ Name1.setText(""); Address1.setText(""); Address2.setText(""); mail1.setText(""); } } /** * 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() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); Name1 = new javax.swing.JTextField(); Address1 = new javax.swing.JTextField(); mail1 = new javax.swing.JTextField(); Address2 = new javax.swing.JTextField(); Save = new javax.swing.JButton(); Cancel = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "GenCo's Info", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 1, 12))); // NOI18N jLabel1.setText("Name:"); jLabel2.setText("Address:"); jLabel3.setText("E-mail:"); Name1.setEnabled(false); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel2) .addGap(6, 6, 6)) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)) .addComponent(jLabel1)) .addGap(5, 5, 5) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Name1, javax.swing.GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE) .addComponent(Address1, javax.swing.GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE) .addComponent(mail1) .addComponent(Address2)) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(Name1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(19, 19, 19) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Address1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Address2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(mail1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addContainerGap(25, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap())) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 225, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) ); Save.setText("Save"); Save.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SaveActionPerformed(evt); } }); Cancel.setText("Cancel"); Cancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CancelActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(267, Short.MAX_VALUE) .addComponent(Save) .addGap(18, 18, 18) .addComponent(Cancel) .addGap(18, 18, 18)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(27, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Cancel) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(Save) .addContainerGap()))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void SaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveActionPerformed int check = 0; for(int i = 0; i < AddGenerator.InfoGENCO.size(); i++){ if (Name1.getText() == AddGenerator.InfoGENCO.get(i).getName()){ check++; } } if (Name1.getText().isEmpty() || Address1.getText().isEmpty() ||mail1.getText().isEmpty()){ errormess = new ErrorMessage("No GENCO Added","Please Fill GENCO's Info"); errormess.setVisible(true); }else{ if(check!=0){ errormess = new ErrorMessage("GENCO Name Already Exists",""); errormess.setVisible(true); }else{ prov_name = Name1.getText(); personal_info.add(prov_name); prov_address1 = Address1.getText(); personal_info.add( prov_address1); prov_address2 = Address2.getText(); personal_info.add( prov_address2); prov_email = mail1.getText(); personal_info.add(prov_email); DataGENcos NP = new DataGENcos(prov_name,prov_address1,prov_address2,prov_email,false); AddGenerator.InfoGENCO.add(NP); addgen1 = new AddGenerator(); addgen1.setVisible(true); this.dispose(); } } }//GEN-LAST:event_SaveActionPerformed private void CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelActionPerformed this.dispose(); // TODO add your handling code here: }//GEN-LAST:event_CancelActionPerformed /** * @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(EnterGENCO.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EnterGENCO.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EnterGENCO.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EnterGENCO.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 EnterGENCO(Name).setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables public static javax.swing.JTextField Address1; public static javax.swing.JTextField Address2; private javax.swing.JButton Cancel; public static javax.swing.JTextField Name1; private javax.swing.JButton Save; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; public static javax.swing.JTextField mail1; // End of variables declaration//GEN-END:variables }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.account.suspension.notification.task.ldap; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.identity.account.suspension.notification.task.NotificationReceiversRetrieval; import org.wso2.carbon.identity.account.suspension.notification.task.exception.AccountSuspensionNotificationException; import org.wso2.carbon.identity.account.suspension.notification.task.internal.NotificationTaskDataHolder; import org.wso2.carbon.identity.account.suspension.notification.task.util.NotificationConstants; import org.wso2.carbon.identity.account.suspension.notification.task.util.NotificationReceiver; import org.wso2.carbon.identity.account.suspension.notification.task.util.NotificationReceiversRetrievalUtil; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.user.api.RealmConfiguration; import org.wso2.carbon.user.core.UserCoreConstants; import org.wso2.carbon.user.core.UserStoreConfigConstants; import org.wso2.carbon.user.core.UserStoreException; import org.wso2.carbon.user.core.claim.ClaimManager; import org.wso2.carbon.user.core.ldap.LDAPConnectionContext; import org.wso2.carbon.user.core.ldap.LDAPConstants; import org.wso2.carbon.user.core.service.RealmService; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; public class LDAPNotificationReceiversRetrieval implements NotificationReceiversRetrieval { private static final Log log = LogFactory.getLog(LDAPNotificationReceiversRetrieval.class); private RealmConfiguration realmConfiguration = null; @Override public void init(RealmConfiguration realmConfiguration) { this.realmConfiguration = realmConfiguration; } @Override public List<NotificationReceiver> getNotificationReceivers(long lookupMin, long lookupMax, long delayForSuspension, String tenantDomain) throws AccountSuspensionNotificationException { List<NotificationReceiver> users = new ArrayList<NotificationReceiver>(); if (realmConfiguration != null) { String ldapSearchBase = realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); RealmService realmService = NotificationTaskDataHolder.getInstance().getRealmService(); try { ClaimManager claimManager = (ClaimManager) realmService.getTenantUserRealm(IdentityTenantUtil. getTenantId(tenantDomain)).getClaimManager(); String userStoreDomain = realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig. PROPERTY_DOMAIN_NAME); if (StringUtils.isBlank(userStoreDomain)) { userStoreDomain = IdentityUtil.getPrimaryDomainName(); } String identityClaimForLastLoginTime = IdentityUtil. getProperty(NotificationConstants.USE_IDENTITY_CLAIM_FOR_LAST_LOGIN_TIME); boolean useIdentityClaimForLastLoginTime = StringUtils.isBlank(identityClaimForLastLoginTime) || Boolean.parseBoolean(identityClaimForLastLoginTime); if (useIdentityClaimForLastLoginTime) { if (log.isDebugEnabled()) { log.debug("Property " + NotificationConstants.USE_IDENTITY_CLAIM_FOR_LAST_LOGIN_TIME + " is enabled in identity.xml file. Hence treating last login time as identity claim."); } return NotificationReceiversRetrievalUtil.getNotificationReceiversFromIdentityClaim(lookupMin, lookupMax, delayForSuspension, realmService, tenantDomain, userStoreDomain); } String lastLoginClaim = NotificationConstants.LAST_LOGIN_TIME; String usernameMapAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.USERNAME_CLAIM); String firstNameMapAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.FIRST_NAME_CLAIM); String emailMapAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.EMAIL_CLAIM); String lastLoginTimeAttribute = claimManager.getAttributeName(userStoreDomain, lastLoginClaim); if (log.isDebugEnabled()) { log.debug("Retrieving ldap user list for lookupMin: " + lookupMin + " - lookupMax: " + lookupMax); } String[] returnedAttrs = {emailMapAttribute, usernameMapAttribute, firstNameMapAttribute, lastLoginTimeAttribute}; LDAPConnectionContext ldapConnectionContext = new LDAPConnectionContext(realmConfiguration); DirContext ctx = ldapConnectionContext.getContext(); //carLicense is the mapped LDAP attribute for LastLoginTime claim String searchFilter = getSearchFilter(lookupMin, lookupMax,lastLoginTimeAttribute); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(returnedAttrs); NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls); if (log.isDebugEnabled()) { log.debug("LDAP user list retrieved."); } while (results.hasMoreElements()) { SearchResult result = results.nextElement(); NotificationReceiver receiver = new NotificationReceiver(); receiver.setEmail((String) result.getAttributes().get(emailMapAttribute).get()); receiver.setUsername((String) result.getAttributes().get(usernameMapAttribute).get()); receiver.setFirstName((String) result.getAttributes().get(firstNameMapAttribute).get()); receiver.setUserStoreDomain(userStoreDomain); String lastLoginTimeValue = result.getAttributes().get(lastLoginTimeAttribute).get().toString(); long lastLoginTime = convertToWSO2DateFormat(lastLoginTimeValue); long expireDate = lastLoginTime + TimeUnit.DAYS.toMillis(delayForSuspension); receiver.setExpireDate(new SimpleDateFormat("dd-MM-yyyy").format(new Date(expireDate))); if (log.isDebugEnabled()) { log.debug("Expire date was set to: " + receiver.getExpireDate()); } users.add(receiver); } } catch (NamingException e) { throw new AccountSuspensionNotificationException("Failed to filter users from LDAP user store.", e); } catch (UserStoreException e) { throw new AccountSuspensionNotificationException("Failed to load LDAP connection context.", e); } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new AccountSuspensionNotificationException("Error occurred while getting tenant user realm for " + "tenant:" + tenantDomain, e); } } return users; } /** * Convert Active Directory date format (Generalized Time) to WSO2 format. * @param date Date formatted in Active Directory date format. * @return Date formatted in WSO2 date format. */ private long convertToWSO2DateFormat(String date) { // If the user-store uses a different timestamp than WSO2 format. String dateTimeFormat = realmConfiguration.getUserStoreProperty(UserStoreConfigConstants.dateAndTimePattern); if(StringUtils.isNotEmpty(dateTimeFormat)){ DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateTimeFormat); OffsetDateTime offsetDateTime = OffsetDateTime.parse(date, dateTimeFormatter); Instant instant = offsetDateTime.toInstant(); return instant.toEpochMilli(); } return Long.parseLong(date); } /** * Construct the search filter according to timestamps defined in the user-store configuration. * @param lookupMin Search start time. * @param lookupMax Search end time. * @param lastLoginTimeAttribute Last login time. * @return Constructed search filter. */ protected String getSearchFilter(long lookupMin, long lookupMax, String lastLoginTimeAttribute) { // The lastLoginTimeAttribute is the mapped LDAP attribute for LastLoginTime claim. String searchFilter = "(&(" + lastLoginTimeAttribute + ">=" + lookupMin + ")(|(!(" + lastLoginTimeAttribute + ">=" + lookupMax + "))(" + lastLoginTimeAttribute + "=" + lookupMax + ")))"; // If the user-store uses a different timestamp than WSO2 format. String timeStampFormat = realmConfiguration.getUserStoreProperty(UserStoreConfigConstants.dateAndTimePattern); if (StringUtils.isNotEmpty(timeStampFormat)) { String lookUpMinDate = new SimpleDateFormat(timeStampFormat).format(new Date(lookupMin)); String lookUpMaxDate = new SimpleDateFormat(timeStampFormat).format(new Date(lookupMax)); searchFilter = "(&(" + lastLoginTimeAttribute + ">=" + lookUpMinDate + ")(|(!(" + lastLoginTimeAttribute + ">=" + lookUpMaxDate + "))(" + lastLoginTimeAttribute + "=" + lookUpMaxDate + ")))"; } if (log.isDebugEnabled()) { log.debug("Retrieving LDAP user list for searchFilter: " + searchFilter); } return searchFilter; } }
package collection; import java.util.PriorityQueue; import java.util.Queue; public class QDemo { public static void main(String[] args) { Queue<Integer>q= new PriorityQueue<>(); for(int i =5;i>=0;i--) { q.add(i); } System.out.println(q); for(int i=0;i<=5;i++) { System.out.println(q.remove()); } // System.out.println(q); } }
package net.inveed.rest.jpa.typeutils; import com.fasterxml.jackson.annotation.JsonProperty; import net.inveed.commons.reflection.BeanPropertyDesc; import net.inveed.commons.reflection.ext.IBeanPropertyExtension; public class JsonPropertyExt implements IBeanPropertyExtension { private final BeanPropertyDesc beanProperty; private final JsonTypeExt<?> type; private int order = 1000; private String jsonName; public JsonPropertyExt(BeanPropertyDesc bpd, JsonTypeExt<?> type) { this.beanProperty = bpd; this.type = type; } public String getJSONName() { return this.jsonName; } public int getOrder() { return this.order; } public JsonTypeExt<?> getType() { return this.type; } public void initialize() { JsonProperty jp = this.beanProperty.getAnnotation(JsonProperty.class); if (jp != null) { this.order = jp.index(); this.jsonName = jp.value(); } else { this.order = 1000; this.jsonName = this.beanProperty.getName(); } } @Override public boolean canGet() { return true; } @Override public boolean canSet() { return true; } }
package com.fm.scheduling.service; import com.fm.scheduling.dao.*; import com.fm.scheduling.domain.*; import com.fm.scheduling.exception.SchedulingException; import java.sql.SQLException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; public class SchedulingService { public enum LocalesSupported{ en(new Locale("en")), es(new Locale("es")); LocalesSupported(Locale locale){ this.locale = locale; } private Locale locale; public Locale getLocale() { return locale; } public static LocalesSupported getLocaleSupported(Locale locale){ for(LocalesSupported localesSupported: LocalesSupported.values()){ if(localesSupported.name().equals(localesSupported.getLocale().getLanguage())) return localesSupported; } return LocalesSupported.en; } } private LocalesSupported locale = LocalesSupported.en; private Customer customerSelected; private Appointment appointmentSelected; private static SchedulingService instance; private User userLoggedIn; private ZoneId localZoneId; private ZoneId utcZoneId = ZoneId.of("UTC"); private AppointmentDao appointmentDao = new AppointmentDao(); private UserDao userDao = new UserDao(); private CustomerDao customerDao = new CustomerDao(); private AddressDao addressDao = new AddressDao(); private CityDao cityDao = new CityDao(); private CountryDao countryDao = new CountryDao(); private SchedulingService(){ } public boolean login(String userName, String password) throws SchedulingException { boolean loggedIn = false; User user = null; try { user = userDao.getByName(userName); } catch(Exception e){ e.printStackTrace(); throw new SchedulingException(SchedulingException.SchedulingExceptionTypeEnum.DB_CONNECTION_PROBLEM); } if(user != null && user.getPassword().equals(password)){ loggedIn = true; userLoggedIn = user; localZoneId = ZoneId.systemDefault(); } return loggedIn; } public LocalDateTime getUTCLocalDateTime(LocalDateTime localDateTime){ ZonedDateTime ldtZoned = localDateTime.atZone(localZoneId); ZonedDateTime utcZoned = ldtZoned.withZoneSameInstant(utcZoneId); return utcZoned.toLocalDateTime(); } public LocalDateTime getLocalDateTimeFromUTCTime(LocalDateTime localDateTime){ ZonedDateTime utcZoned = localDateTime.atZone(utcZoneId); ZonedDateTime ldtZoned = utcZoned.withZoneSameInstant(localZoneId); return ldtZoned.toLocalDateTime(); } public static synchronized SchedulingService getInstance(){ if(instance == null) instance = new SchedulingService(); return instance; } public User getUserLoggedIn() { return userLoggedIn; } public LocalesSupported getLocale() { return locale; } public void setLocale(LocalesSupported locale) { this.locale = locale; } public List<Country> getCountryList() throws SchedulingException{ List<Country> countryList; try{ countryList = countryDao.getList(); } catch (SQLException ex){ throw new SchedulingException(SchedulingException.SchedulingExceptionTypeEnum.DB_CONNECTION_PROBLEM); } return countryList; } public List<City> getCityListByCountry(int countryId) throws SchedulingException{ List<City> cityList; try{ cityList = cityDao.getListByCountryId(countryId); } catch (SQLException ex){ throw new SchedulingException(SchedulingException.SchedulingExceptionTypeEnum.DB_CONNECTION_PROBLEM); } return cityList; } public List<User> getUserList() throws SchedulingException{ List<User> userList; try{ userList = userDao.getList(); } catch (SQLException ex){ ex.printStackTrace(); throw new SchedulingException(SchedulingException.SchedulingExceptionTypeEnum.DB_CONNECTION_PROBLEM); } return userList; } public Map<String, String> getAppointmentsGroupedByDescriptionByMonth(LocalDate month) throws SchedulingException{ Map<String, String> mapAppointmentsByDescriptionString; if(month == null) return null; LocalDate startMonth = month.withDayOfMonth(1); LocalDate endMonth = month.withDayOfMonth(month.lengthOfMonth()); try{ mapAppointmentsByDescriptionString = appointmentDao.getAppointmentsGroupedByDescriptionByDateRange(startMonth, endMonth).entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> (e.getValue().toString()))); } catch (SQLException ex){ ex.printStackTrace(); throw new SchedulingException(SchedulingException.SchedulingExceptionTypeEnum.DB_CONNECTION_PROBLEM); } return mapAppointmentsByDescriptionString; } public List<Appointment> getAppointmentOnLocalDateTimeRange(LocalDateTime startDateTime, LocalDateTime endDateTime) throws SchedulingException{ if(startDateTime == null || endDateTime == null) return null; List<Appointment> appointmentList; appointmentList = getAppointmentList(); appointmentList = appointmentList.stream().filter(x -> x.getStart().isAfter(startDateTime) && x.getStart().isBefore(endDateTime)).collect(Collectors.toList()); return appointmentList; } public List<Appointment> getAppointmentList() throws SchedulingException{ List<Appointment> appointmentList; try{ appointmentList = appointmentDao.getList(); for(Appointment appointment: appointmentList){ appointment.setStart(getLocalDateTimeFromUTCTime(appointment.getStart())); appointment.setEnd(getLocalDateTimeFromUTCTime(appointment.getEnd())); appointment.setCustomer(getFullCustomer(appointment.getCustomerId())); } } catch (SQLException ex){ ex.printStackTrace(); throw new SchedulingException(SchedulingException.SchedulingExceptionTypeEnum.DB_CONNECTION_PROBLEM); } return appointmentList; } public List<Appointment> getAppointmentByConsultant(String consultant) throws SchedulingException{ if(consultant == null || consultant.equals("")) return null; List<Appointment> appointmentList; try{ appointmentList = appointmentDao.getByConsultant(consultant); for(Appointment appointment: appointmentList){ appointment.setStart(getLocalDateTimeFromUTCTime(appointment.getStart())); appointment.setEnd(getLocalDateTimeFromUTCTime(appointment.getEnd())); appointment.setCustomer(getFullCustomer(appointment.getCustomerId())); } } catch (SQLException ex){ ex.printStackTrace(); throw new SchedulingException(SchedulingException.SchedulingExceptionTypeEnum.DB_CONNECTION_PROBLEM); } return appointmentList; } public List<Appointment> getAppointmentByLocation(Appointment.LocationEnum location) throws SchedulingException{ if(location == null) return null; List<Appointment> appointmentList; try{ appointmentList = appointmentDao.getByLocation(location); for(Appointment appointment: appointmentList){ appointment.setStart(getLocalDateTimeFromUTCTime(appointment.getStart())); appointment.setEnd(getLocalDateTimeFromUTCTime(appointment.getEnd())); appointment.setCustomer(getFullCustomer(appointment.getCustomerId())); } } catch (SQLException ex){ ex.printStackTrace(); throw new SchedulingException(SchedulingException.SchedulingExceptionTypeEnum.DB_CONNECTION_PROBLEM); } return appointmentList; } public List<Customer> getCustomerList() throws SchedulingException { List<Customer> customerList; try{ customerList = customerDao.getList(); for(Customer customer: customerList){ customer.setAddress(getFullAddress(customer.getAddressId())); } } catch (SQLException ex){ ex.printStackTrace(); throw new SchedulingException(SchedulingException.SchedulingExceptionTypeEnum.DB_CONNECTION_PROBLEM); } return customerList; } public void deleteAppointment(Appointment appointment) throws SchedulingException{ try { appointmentDao.delete(appointment.getAppointmentId()); } catch (SQLException ex){ ex.printStackTrace(); throw new SchedulingException(SchedulingException.SchedulingExceptionTypeEnum.DB_CONNECTION_PROBLEM); } } public void deleteCustomer(Customer customer) throws SchedulingException { try { checkCustomerOnAppointment(customer); customerDao.delete(customer.getCustomerId()); } catch (SQLException ex){ ex.printStackTrace(); throw new SchedulingException(SchedulingException.SchedulingExceptionTypeEnum.DB_CONNECTION_PROBLEM); } } private void checkCustomerOnAppointment(Customer customer) throws SchedulingException, SQLException{ List<Appointment> appointmentList = appointmentDao.getByCustomer(customer.getCustomerId()); if(appointmentList != null && !appointmentList.isEmpty()) throw new SchedulingException(SchedulingException.SchedulingExceptionTypeEnum.CUSTOMER_ON_APPOINMENT); } public int storeAppointment(Appointment appointment) throws SchedulingException{ try { appointment.setStart(getUTCLocalDateTime(appointment.getStart())); appointment.setEnd(getUTCLocalDateTime(appointment.getEnd())); return appointmentDao.insert(appointment, userLoggedIn); } catch (SQLException ex){ ex.printStackTrace(); throw new SchedulingException(SchedulingException.SchedulingExceptionTypeEnum.DB_CONNECTION_PROBLEM); } } public void updateAppointment(Appointment appointment, Appointment originalAppointment) throws SchedulingException{ try { appointment.setStart(getUTCLocalDateTime(appointment.getStart())); appointment.setEnd(getUTCLocalDateTime(appointment.getEnd())); appointmentDao.update(appointment, userLoggedIn, originalAppointment.getAppointmentId()); } catch (SQLException ex) { ex.printStackTrace(); throw new SchedulingException(SchedulingException.SchedulingExceptionTypeEnum.DB_CONNECTION_PROBLEM); } } public void updateCustomer(Customer customer, Customer originalCustomer) throws SchedulingException { try { updateAddress(customer.getAddress(), originalCustomer.getAddress()); customer.setAddressId(originalCustomer.getAddressId()); customerDao.update(customer, userLoggedIn, originalCustomer.getCustomerId()); } catch (SQLException ex) { ex.printStackTrace(); throw new SchedulingException(SchedulingException.SchedulingExceptionTypeEnum.DB_CONNECTION_PROBLEM); } } private void updateAddress(Address address, Address originalAddress) throws SQLException{ addressDao.update(address, userLoggedIn, originalAddress.getAddressId()); } public int storeCustomer(Customer customer) throws SchedulingException{ try { customer.setAddressId(storeAddress(customer.getAddress())); return customerDao.insert(customer, userLoggedIn); } catch (SQLException ex) { ex.printStackTrace(); throw new SchedulingException(SchedulingException.SchedulingExceptionTypeEnum.DB_CONNECTION_PROBLEM); } } private int storeAddress(Address address) throws SQLException{ return addressDao.insert(address, userLoggedIn); } private Customer getFullCustomer(int customerId) throws SQLException{ Customer customer = customerDao.getById(customerId); customer.setAddress(getFullAddress(customer.getAddressId())); return customer; } private Address getFullAddress(int addressId)throws SQLException{ Address address = addressDao.getById(addressId); address.setCity(getFullCity(address.getCityId())); return address; } private City getFullCity(int cityId) throws SQLException{ City city = cityDao.getById(cityId); city.setCountry(getFullCountry(city.getCountryId())); return city; } private Country getFullCountry(int countryId) throws SQLException{ return countryDao.getById(countryId); } public Customer getCustomerSelected() { return customerSelected; } public void setCustomerSelected(Customer customerSelected) { this.customerSelected = customerSelected; } public void clearCustomerSelected(){ this.customerSelected = null; } public Appointment getAppointmentSelected() { return appointmentSelected; } public void setAppointmentSelected(Appointment appointmentSelected) { this.appointmentSelected = appointmentSelected; } public void clearAppointmentSelected(){ this.appointmentSelected = null; } }
package com.example.mathpractice; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class SubtractionActivity extends AppCompatActivity { private Button lvlOneBtn; private Button lvlTwoBtn; private Button lvlThreeBtn; private Button lvlFourBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_subtraction); lvlOneBtn = (Button) findViewById(R.id.lvl_1); lvlTwoBtn = (Button) findViewById(R.id.lvl_2); lvlThreeBtn = (Button) findViewById(R.id.lvl_3); lvlFourBtn = (Button) findViewById(R.id.lvl_4); lvlOneBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(SubtractionActivity.this, SubtractionLevelOneActivity.class)); } }); lvlTwoBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(SubtractionActivity.this, SubtractionLevelTwoActivity.class)); } }); lvlThreeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(SubtractionActivity.this, SubtractionLevelThreeActivity.class)); } }); lvlFourBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(SubtractionActivity.this, SubtractionLevelFourActivity.class)); } }); } }
public class PostfixExpressionCalculator implements Visitor { private GenericListBasedStack<Operand> glbs; public PostfixExpressionCalculator() { glbs = new GenericListBasedStack<>(); } @Override //Integers public void visit(Operand e) { glbs.push(e); } @Override //+,*,/,- public void visit(Operator e) { switch (e.getOp()) { case "+": glbs.push(new Operand(glbs.pop().getValue()+glbs.pop().getValue())); break; case "-": glbs.push(new Operand((glbs.pop().getValue()-glbs.pop().getValue())*(-1))); break; case "*": glbs.push(new Operand(glbs.pop().getValue()*glbs.pop().getValue())); break; case "/": int a = glbs.pop().getValue(); glbs.push(new Operand(glbs.pop().getValue()/a)); break; default: throw new IllegalArgumentException("Invalid Operator : " + e.getOp()); } } public Integer getToken() { return glbs.peek().getValue(); } }
package com.redsun.platf.dao; import com.redsun.platf.dao.base.IPagedDao; import com.redsun.platf.entity.account.AccountResources; import com.redsun.platf.entity.account.AccountRole; import com.redsun.platf.entity.account.Authority; import com.redsun.platf.entity.account.UserAccount; import com.redsun.platf.entity.sys.*; import com.redsun.platf.entity.tag.Attachment; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.io.Serializable; /** * <p>Title : com.webapp </p> * <p>Description : 所有DAO的集合 </p> * <p>Copyright : Copyright (c) 2011</p> * <p>Company : FreedomSoft </p> * */ /** * @author dick pan * @version 1.0 * @since 1.0 * <p> * <H3>Change history</H3> * </p> * <p> * 2011/1/25 : Created * </p> 2012/06/08 : add user resource ,user department * </p> */ @Component("dataAccessObjectFactory") // @Transactional //need't just in dao public class DataAccessObjectFactory implements Serializable { private static final long serialVersionUID = -5450000925993172262L; private static DataAccessObjectFactory instance; public static DataAccessObjectFactory getInstance() { if (instance == null) instance = new DataAccessObjectFactory(); return instance; } // authority @Resource(name = "systemLanguageDao") private IPagedDao<SystemLanguage, Long> systemLanguageDao; // authority @Resource(name = "systemThemeDao") private IPagedDao<SystemTheme, Long> systemThemeDao; // private SystemThemeDao systemThemeDao; @Resource(name = "systemValueDao") private IPagedDao<SystemValue, Long> systemValueDao; @Resource(name = "systemTxnDao") private IPagedDao<SystemTxn, Long> systemTxnDao; @Resource(name = "authorityDao") private IPagedDao<Authority, Long> authorityDao; // role @Resource(name = "roleDao") private IPagedDao<AccountRole, Long> roleDao; // private RoleDao roleDao; // user @Resource(name = "userDao") private IPagedDao<UserAccount, Long> userDao; // user resources // add by pyc.2012.6.8 @Resource(name = "accountResourcesDao") private IPagedDao<AccountResources, Long> accountResourcesDao; // department @Resource(name = "departmentDao") private IPagedDao<Department, Long> departmentDao; @Resource(name = "systemCompanyDao") private IPagedDao<SystemCompany, Long> systemCompanyDao; @Resource(name = "systemMailDao") private IPagedDao<SystemMail, Long> systemMailDao; @Resource(name = "attachmentDao") private IPagedDao<Attachment, Long> attachmentDao; public IPagedDao<SystemCompany, Long> getSystemCompanyDao() { return systemCompanyDao; } public IPagedDao<SystemLanguage, Long> getSystemLanguageDao() { return systemLanguageDao; } public IPagedDao<SystemTheme, Long> getSystemThemeDao() { // error // public SystemThemeDao getSystemThemeDao() { return systemThemeDao; } public IPagedDao<SystemValue, Long> getSystemValueDao() { return systemValueDao; } public IPagedDao<Authority, Long> getAuthorityDao() { return authorityDao; } public IPagedDao<AccountRole, Long> getRoleDao() { return roleDao; } public IPagedDao<UserAccount, Long> getUserDao() { return userDao; } public IPagedDao<SystemTxn, Long> getSystemTxnDao() { return systemTxnDao; } public IPagedDao<AccountResources, Long> getAccountResourcesDao() { return accountResourcesDao; } public IPagedDao<Department, Long> getDepartmentDao() { return departmentDao; } public IPagedDao<SystemMail, Long> getSystemMailDao() { return systemMailDao; } public IPagedDao<Attachment, Long> getAttachmentDao() { return attachmentDao; } }
import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.JButton; import javax.swing.JScrollPane; import javax.swing.JTextPane; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; public class ActionParserGUI extends JFrame { private JPanel contentPane; private JTextField textField; private JTextPane textPane ; static EG1 parser = null; static List<String> equi_textual= new ArrayList<String>(); /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ActionParserGUI frame = new ActionParserGUI(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public ActionParserGUI() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 537, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); textField = new JTextField(); textField.setBounds(97, 11, 324, 25); contentPane.add(textField); textField.setColumns(10); JLabel lblNewLabel = new JLabel("Enter Syntaxes:"); lblNewLabel.setBounds(10, 16, 84, 20); contentPane.add(lblNewLabel); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(10, 62, 414, 188); contentPane.add(scrollPane); textPane = new JTextPane(); scrollPane.setViewportView(textPane); JButton btnNewButton = new JButton("Check"); btnNewButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { String sentence = textField.getText(); // Put parens around sentence so that parser knows scope InputStream is = new ByteArrayInputStream(sentence.getBytes()); if(parser == null) parser = new EG1(is); else EG1.ReInit(is); try { switch (EG1.start()) { case 0 : textPane.setText("expression parsed ok."); break; default : break; } } catch (Exception e1) { textPane.setText("error in expression.\n"+ e1.getMessage()); } catch (Error e2) { textPane.setText("error in expression.\n"+ e2.getMessage()); } finally { } if (textPane.getText().equals("expression parsed ok.")) { equi_textual= EG1.getEqui(); textPane.setText("Expression Paresed ok. \nEquivalent is: \n"); for(String gi : equi_textual) { textPane.setText(textPane.getText()+gi+" "); } } } }); btnNewButton.setBounds(431, 11, 80, 25); contentPane.add(btnNewButton); } }
package pl.edu.uj.fais.amsi.gfx; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.Color; import pl.edu.uj.fais.amsi.bio.Bacteria; import pl.edu.uj.fais.amsi.bio.MapObject; import pl.edu.uj.fais.amsi.bio.Worm; import pl.edu.uj.fais.amsi.main.Game; /** * * @author Michal Szura & Bartosz Bereza */ public class HexOperations { //Constants public final static boolean orFLAT = true; public final static boolean orPOINT = false; public static boolean XYVertex = true; //true: x,y are the co-ords of the first vertex. //false: x,y are the co-ords of the top left rect. co-ord. private static int BORDERS = 50; //default number of pixels for the border. private static int s = 0; // length of one side private static int t = 0; // short side of 30o triangle outside of each hex private static int r = 0; // radius of inscribed circle (centre to middle of each side). r= h/2 private static int h = 0; // height. Distance between centres of two adjacent hexes. Distance between two opposite sides in a hex. public static void setXYasVertex(boolean b) { XYVertex = b; } public static void setBorders(int b) { BORDERS = b; } public static void setHeight(int height) { h = height; // h = basic dimension: height (distance between two adj centresr aka size) r = h / 2; // r = radius of inscribed circle s = (int) (h / 1.73205); // s = (h/2)/cos(30)= (h/2) / (sqrt(3)/2) = h / sqrt(3) t = (int) (r / 1.73205); // t = (h/2) tan30 = (h/2) 1/sqrt(3) = h / (2 sqrt(3)) = r / sqrt(3) } public static Polygon hex(int x0, int y0) { int y = y0 + BORDERS; int x = x0 + BORDERS; if (s == 0 || h == 0) { System.out.println("ERROR: size of hex has not been set"); return new Polygon(); } int[] cx, cy; if (XYVertex) { cx = new int[]{x, x + s, x + s + t, x + s, x, x - t}; } else { cx = new int[]{x + t, x + s + t, x + s + t + t, x + s + t, x + t, x}; } cy = new int[]{y, y, y + r, y + r + r, y + r + r, y + r}; return new Polygon(cx, cy, 6); } public static void drawHex(int i, int j, Graphics2D g2) { int x = i * (s + t); int y = j * h + (i % 2) * h / 2; Polygon poly = hex(x, y); g2.setColor(GameWindow.COLOURCELL); g2.fillPolygon(poly); g2.setColor(GameWindow.COLOURGRID); g2.drawPolygon(poly); } public static void fillHex(int i, int j, double wi, double hi, String n, int xWorm, int yWorm, Graphics2D g2) { int xFrom, yFrom; int xTo = (int) ((i * (s + t)) + s + BORDERS); int yTo = (int) ((j * h + (i % 2) * h / 2) + r + BORDERS); int x = i * (s + t); int y = j * h + (i % 2) * h / 2; MapObject temp = Game.getMapObject(xWorm, yWorm); if (temp instanceof Bacteria) { //Filling Hex g2.setColor(GameWindow.COLOURONE); g2.fillPolygon(hex(x, y)); //Painting Text g2.setColor(GameWindow.COLOURONETXT); g2.drawString(n, (int) (x + r + BORDERS - wi / 4), (int) (y + r + BORDERS + hi / 4)); } if (temp instanceof Worm) { //Filling Hex g2.setColor(GameWindow.COLOURTWO); g2.fillPolygon(hex(x, y)); //Painting Movement Arrow Worm worm = (Worm) temp; g2.setColor(GameWindow.COLOURDIRARROW); if (worm.getDirection().toString().equals("TL")) { xFrom = (int) (((i + 1) * (s + t)) + s + BORDERS); yFrom = (int) ((j * h + (i % 2) * h / 2) + r + h / 2 + BORDERS); g2.drawLine(xTo, yTo, xFrom, yFrom); g2.drawLine(xTo, yTo, xTo + 10, yTo + 18); g2.drawLine(xTo, yTo, xTo + 20, yTo); g2.fillOval(xFrom - 3, yFrom - 3, 6, 6); } else if (worm.getDirection().toString().equals("TR")) { xFrom = (int) (((i - 1) * (s + t)) + s + BORDERS); yFrom = (int) ((j * h + (i % 2) * h / 2) + r + h / 2 + BORDERS); g2.drawLine(xTo, yTo, xTo - 10, yTo + 18); g2.drawLine(xTo, yTo, xTo - 20, yTo); g2.drawLine(xTo, yTo, xFrom, yFrom); g2.fillOval(xFrom - 3, yFrom - 3, 6, 6); } else if (worm.getDirection().toString().equals("BL")) { xFrom = (int) (((i + 1) * (s + t)) + s + BORDERS); yFrom = (int) (((j - 1) * h + (i % 2) * h / 2) + r + h / 2 + BORDERS); g2.drawLine(xTo, yTo, xFrom, yFrom); g2.drawLine(xTo, yTo, xTo + 10, yTo - 18); g2.drawLine(xTo, yTo, xTo + 20, yTo); g2.fillOval(xFrom - 3, yFrom - 3, 6, 6); } else if (worm.getDirection().toString().equals("BR")) { xFrom = (int) (((i - 1) * (s + t)) + s + BORDERS); yFrom = (int) (((j - 1) * h + (i % 2) * h / 2) + r + h / 2 + BORDERS); g2.drawLine(xTo, yTo, xFrom, yFrom); g2.drawLine(xTo, yTo, xTo - 10, yTo - 18); g2.drawLine(xTo, yTo, xTo - 20, yTo); g2.fillOval(xFrom - 3, yFrom - 3, 6, 6); } else if (worm.getDirection().toString().equals("T")) { xFrom = (int) ((i * (s + t)) + s + BORDERS); yFrom = (int) (((j + 1) * h + (i % 2) * h / 2) + r + BORDERS); g2.drawLine(xTo, yTo, xFrom, yFrom); g2.drawLine(xTo, yTo, xTo + 10, yTo + 18); g2.drawLine(xTo, yTo, xTo - 10, yTo + 18); g2.fillOval(xFrom - 3, yFrom - 3, 6, 6); } else if (worm.getDirection().toString().equals("B")) { xFrom = (int) ((i * (s + t)) + s + BORDERS); yFrom = (int) (((j - 1) * h + (i % 2) * h / 2) + r + BORDERS); g2.drawLine(xTo, yTo, xFrom, yFrom); g2.drawLine(xTo, yTo, xTo + 10, yTo - 18); g2.drawLine(xTo, yTo, xTo - 10, yTo - 18); g2.fillOval(xFrom - 3, yFrom - 3, 6, 6); } //Painting Text g2.setColor(GameWindow.COLOURTWOTXT); g2.drawString(n, (int) (x + r + BORDERS - wi / 3), (int) (y + r + BORDERS + hi / 3)); } } }
package com.mahang.weather.ui.fragment; import com.mahang.weather.base.BaseFragment; public class AirFragment extends BaseFragment { @Override public void notifyDataSetChanged() { // TODO Auto-generated method stub } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.common.security.auth; import java.security.Principal; public class KafkaPrincipal implements Principal { public static final String SEPARATOR = ":"; public static final String USER_TYPE = "User"; public final static KafkaPrincipal ANONYMOUS = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "ANONYMOUS"); private String principalType; private String name; public KafkaPrincipal(String principalType, String name) { if (principalType == null || name == null) { throw new IllegalArgumentException("principalType and name can not be null"); } this.principalType = principalType; this.name = name; } public static KafkaPrincipal fromString(String str) { if (str == null || str.isEmpty()) { throw new IllegalArgumentException("expected a string in format principalType:principalName but got " + str); } String[] split = str.split(SEPARATOR, 2); if (split == null || split.length != 2) { throw new IllegalArgumentException("expected a string in format principalType:principalName but got " + str); } return new KafkaPrincipal(split[0], split[1]); } @Override public String toString() { return principalType + SEPARATOR + name; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof KafkaPrincipal)) return false; KafkaPrincipal that = (KafkaPrincipal) o; if (!principalType.equalsIgnoreCase(that.principalType)) return false; return name.equalsIgnoreCase(that.name); } @Override public int hashCode() { int result = principalType.hashCode(); result = 31 * result + name.hashCode(); return result; } @Override public String getName() { return name; } public String getPrincipalType() { return principalType; } }
/** */ package CFG; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Var</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link CFG.Var#getName <em>Name</em>}</li> * <li>{@link CFG.Var#getMethod <em>Method</em>}</li> * <li>{@link CFG.Var#getNodes <em>Nodes</em>}</li> * </ul> * </p> * * @see CFG.CFGPackage#getVar() * @model * @generated */ public interface Var extends EObject { /** * Returns the value of the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Name</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Name</em>' attribute. * @see #setName(String) * @see CFG.CFGPackage#getVar_Name() * @model * @generated */ String getName(); /** * Sets the value of the '{@link CFG.Var#getName <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Name</em>' attribute. * @see #getName() * @generated */ void setName(String value); /** * Returns the value of the '<em><b>Method</b></em>' container reference. * It is bidirectional and its opposite is '{@link CFG.MControlFlowGraph#getLocalVar <em>Local Var</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Method</em>' container reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Method</em>' container reference. * @see #setMethod(MControlFlowGraph) * @see CFG.CFGPackage#getVar_Method() * @see CFG.MControlFlowGraph#getLocalVar * @model opposite="localVar" transient="false" * @generated */ MControlFlowGraph getMethod(); /** * Sets the value of the '{@link CFG.Var#getMethod <em>Method</em>}' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Method</em>' container reference. * @see #getMethod() * @generated */ void setMethod(MControlFlowGraph value); /** * Returns the value of the '<em><b>Nodes</b></em>' container reference list. * The list contents are of type {@link CFG.AbstractNode}. * It is bidirectional and its opposite is '{@link CFG.AbstractNode#getVar <em>Var</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Nodes</em>' container reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Nodes</em>' container reference list. * @see CFG.CFGPackage#getVar_Nodes() * @see CFG.AbstractNode#getVar * @model opposite="var" transient="false" * @generated */ EList<AbstractNode> getNodes(); } // Var
/* * 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 ppro.modelo; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; /** * * @author casa */ @Entity @Table(name = "ppro_rel_perfil_menu") @XmlRootElement @NamedQueries({ @NamedQuery(name = "PproRelPerfilMenu.findAll", query = "SELECT p FROM PproRelPerfilMenu p"), @NamedQuery(name = "PproRelPerfilMenu.findByRpmId", query = "SELECT p FROM PproRelPerfilMenu p WHERE p.rpmId = :rpmId"), @NamedQuery(name = "PproRelPerfilMenu.findByRpmEstado", query = "SELECT p FROM PproRelPerfilMenu p WHERE p.rpmEstado = :rpmEstado")}) @ManagedBean @SessionScoped public class PproRelPerfilMenu implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "rpm_id") private Integer rpmId; @Column(name = "rpm_estado") private Integer rpmEstado; @JoinColumn(name = "rpm_perf_id", referencedColumnName = "perf_id") @ManyToOne private PproPerfil rpmPerfId; @JoinColumn(name = "rpm_men_id", referencedColumnName = "men_id") @ManyToOne private PproMenu rpmMenId; public PproRelPerfilMenu() { } public PproRelPerfilMenu(Integer rpmId) { this.rpmId = rpmId; } public Integer getRpmId() { return rpmId; } public void setRpmId(Integer rpmId) { this.rpmId = rpmId; } public Integer getRpmEstado() { return rpmEstado; } public void setRpmEstado(Integer rpmEstado) { this.rpmEstado = rpmEstado; } public PproPerfil getRpmPerfId() { return rpmPerfId; } public void setRpmPerfId(PproPerfil rpmPerfId) { this.rpmPerfId = rpmPerfId; } public PproMenu getRpmMenId() { return rpmMenId; } public void setRpmMenId(PproMenu rpmMenId) { this.rpmMenId = rpmMenId; } @Override public int hashCode() { int hash = 0; hash += (rpmId != null ? rpmId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof PproRelPerfilMenu)) { return false; } PproRelPerfilMenu other = (PproRelPerfilMenu) object; if ((this.rpmId == null && other.rpmId != null) || (this.rpmId != null && !this.rpmId.equals(other.rpmId))) { return false; } return true; } @Override public String toString() { return "ppro.modelo.PproRelPerfilMenu[ rpmId=" + rpmId + " ]"; } }
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.oxm.config; import java.util.List; import org.w3c.dom.Element; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; /** * Parser for the {@code <oxm:jaxb2-marshaller/>} element. * * @author Arjen Poutsma * @since 3.0 */ class Jaxb2MarshallerBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { @Override protected String getBeanClassName(Element element) { return "org.springframework.oxm.jaxb.Jaxb2Marshaller"; } @Override protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder beanDefinitionBuilder) { String contextPath = element.getAttribute("context-path"); if (StringUtils.hasText(contextPath)) { beanDefinitionBuilder.addPropertyValue("contextPath", contextPath); } List<Element> classes = DomUtils.getChildElementsByTagName(element, "class-to-be-bound"); if (!classes.isEmpty()) { ManagedList<String> classesToBeBound = new ManagedList<>(classes.size()); for (Element classToBeBound : classes) { String className = classToBeBound.getAttribute("name"); classesToBeBound.add(className); } beanDefinitionBuilder.addPropertyValue("classesToBeBound", classesToBeBound); } } }
package mvc.controller; import mvc.model.User; public class UserController { private User user; public UserController() { } public User getUser() { user = new User(); user.setName("user1"); user.setAge(5); return user; } }
package com.qx.wechat.comm.sdk.request.query; import com.qx.wechat.comm.sdk.request.msg.PassiveMsgType; public class RobotGroupMembersQuery extends BasicQuery{ /** * */ private static final long serialVersionUID = -5952023410986951767L; private String robot_wxid; // 是否刷新列表,0 从缓存获取 / 1 刷新并获取 private String is_refresh = "1"; // 群组微信id private String group_wxid; public RobotGroupMembersQuery() { super.setType(PassiveMsgType.ROBOT_GROUP_MEMBERS_MSG.getValue()); } public RobotGroupMembersQuery setRefresh(boolean refresh) { if(refresh) { is_refresh = "1"; }else { is_refresh = "0"; } return this; } public String getRobot_wxid() { return robot_wxid; } public RobotGroupMembersQuery setRobot_wxid(String robot_wxid) { this.robot_wxid = robot_wxid; return this; } public String getIs_refresh() { return is_refresh; } public String getGroup_wxid() { return group_wxid; } public RobotGroupMembersQuery setGroup_wxid(String group_wxid) { this.group_wxid = group_wxid; return this; } }
package com.eegeo.mapapi.buildings; import android.graphics.Point; import com.eegeo.mapapi.geometry.LatLng; /** * Options used to construct a BuildingHighlight object. */ @SuppressWarnings("WeakerAccess") public final class BuildingHighlightOptions { /** * @eegeo.internal */ enum SelectionMode { SelectAtLocation, SelectAtScreenPoint } private LatLng m_selectionLocation = new LatLng(0.0, 0.0); private Point m_selectionScreenPoint = new Point(0,0); private int m_colorARGB = 0xff000000; private SelectionMode m_selectionMode = SelectionMode.SelectAtLocation; private boolean m_shouldCreateView = true; private OnBuildingInformationReceivedListener m_onBuildingInformationReceivedListener = null; /** * Default constructor for building highlight creation parameters. */ public BuildingHighlightOptions() { } /** * Sets options to attempt to highlight any building present at the given latLng location. * * @param location The location * @return The BuildingHighlightOptions object on which the method was called */ @SuppressWarnings("JavaDoc") public BuildingHighlightOptions highlightBuildingAtLocation(LatLng location) { m_selectionLocation = location; m_selectionMode = SelectionMode.SelectAtLocation; return this; } /** * Sets options to attempt to highlight any building present at the given screen point for the * current map view. * * @param screenPoint The screen-space point * @return The BuildingHighlightOptions object on which the method was called */ @SuppressWarnings("JavaDoc") public BuildingHighlightOptions highlightBuildingAtScreenPoint(Point screenPoint) { m_selectionScreenPoint = screenPoint; m_selectionMode = SelectionMode.SelectAtScreenPoint; return this; } /** * Sets the color of the building highlight as a 32-bit ARGB color. The default value is opaque black (0xff000000). * * @param color The color to use. * @return The BuildingHighlightOptions object on which the method was called, with the new color set. */ @SuppressWarnings("JavaDoc") public BuildingHighlightOptions color(int color) { m_colorARGB = color; return this; } /** * Sets options such that, if a BuildingHighlight object is created with these options and added * to a map, it will not result in any visual highlight overlay being displayed. In this case, * the BuildingHighlight object is used only for the purpose of retrieving BuildingInformation. * * @return The BuildingHighlightOptions object on which the method was called, with the option set. */ public BuildingHighlightOptions informationOnly() { m_shouldCreateView = false; return this; } /** * BuildingInformation for a BuildingHighlight that is created and added to the map is fetched * asynchronously. This method sets a listener object to obtain notification when * BuildingInformation for a BuildingHighlight created with these options is received. * * @return The BuildingHighlightOptions object on which the method was called, with the option set. */ public BuildingHighlightOptions buildingInformationReceivedListener(OnBuildingInformationReceivedListener listener) { m_onBuildingInformationReceivedListener = listener; return this; } /** * @eegeo.internal */ public SelectionMode getSelectionMode() { return m_selectionMode; } /** * @eegeo.internal */ public LatLng getSelectionLocation() { return m_selectionLocation; } /** * @eegeo.internal */ public Point getSelectionScreenPoint() { return m_selectionScreenPoint; } /** * @eegeo.internal */ public int getColor() { return m_colorARGB; } /** * @eegeo.internal */ public boolean getShouldCreateView() { return m_shouldCreateView; } /** * @eegeo.internal */ public OnBuildingInformationReceivedListener getOnBuildingInformationReceivedListener() { return m_onBuildingInformationReceivedListener; } }
package exercicio05; import java.util.ArrayList; public interface Ferramentas { public ArrayList<Animal> filtraEspecie ( ArrayList<Animal> completo , String especieFiltrar ); public ArrayList<String> classificaEspecies ( ArrayList<Animal> completo ) ; }
package com.XJK.pojo; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Article { public Long id; public String title; public String putTime; public String introduct; public String img; public String content; public String imgPath = ""; public List<String> contentSrcPath; private Pattern pattern = Pattern.compile("src=\"[^\"]*\"?"); String sepa = java.io.File.separator; public Article() { } public Article(String title,String putTime, String introduct, String img, String content) { this.title = title; this.content = content; this.putTime = putTime; this.introduct = introduct; this.img = img; } public Article(ResultSet resultSet){ try { this.id = resultSet.getLong("id"); this.title = resultSet.getString("title"); this.content = resultSet.getString("content"); this.putTime = resultSet.getString("putTime"); this.introduct = resultSet.getString("introduct"); this.img = resultSet.getString("img"); setImgPath(this.img); //获取简介图片的路径 setContentSrcPath(this.content); //获取文中的资源路径 } catch (SQLException e) { e.printStackTrace(); } } public String getImgPath() { return imgPath; } public List<String> getContentSrcPath() { return contentSrcPath; } public void setContentSrcPath(String content) { this.contentSrcPath = new ArrayList<>(); String s = ""; Matcher m = pattern.matcher(content); while (m.find()) { s = content.substring(m.start(), m.end()); s = s.replaceAll("src=\"",""); s = s.replaceAll("\"",""); this.contentSrcPath.add(s); // src="/attached/image/20200322/20200322230634_975.jpg" alt="" /> } this.contentSrcPath.add(imgPath); } public void setImgPath(String img) { Matcher m = pattern.matcher(img); while (m.find()) { this.imgPath = img.substring(m.start(), m.end()); this.imgPath = this.imgPath.replaceAll("src=\"",""); this.imgPath = this.imgPath.replaceAll("\"",""); } } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getPutTime() { return putTime; } public void setPutTime(String putTime) { this.putTime = putTime; } public String getIntroduct() { return introduct; } public void setIntroduct(String introduct) { this.introduct = introduct; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public Object getparArr(){ return new Object[]{id,title,content}; } @Override public String toString() { return "Article{" + "id=" + id + ", title='" + title + '\'' + ", putTime='" + putTime + '\'' + ", introduct='" + introduct + '\'' + ", img='" + img + '\'' + ", content='" + content + '\'' + '}'; } }
package crux; import java.io.IOException; import crux.Token.Kind; public class Parser { private Scanner scanner; private Token current; private ErrorReport error; private SymbolTable symbolTable; public Parser(Scanner scanner) { this.scanner = scanner; this.error = new ErrorReport(); initSymbolTable(); } public void parse() { try { program(); } catch (QuitParseException e) { error.reportSyntaxError(); } } // program := declaration-list EOF private void program() { nextToken(); declarationList(); expect(Token.Kind.EOF); } // declaration-list := { declaration } private void declarationList() { while (have(NonTerminal.DECLARATION_LIST)) { declaration(); } } // declaration := variable-declaration | array-declaration | // function-definition private void declaration() { if (have(NonTerminal.VARIABLE_DECLARATION)) { variableDeclaration(); } else if (have(NonTerminal.FUNCTION_DEFINITION)) { functionDefinition(); } else if (have(NonTerminal.ARRAY_DECLARATION)) { arrayDeclaration(); } } // variable-declaration := "var" IDENTIFIER ":" type ";" private void variableDeclaration() { if (accept(NonTerminal.VARIABLE_DECLARATION)) { tryDeclareSymbol(current); expect(Token.Kind.IDENTIFIER); expect(Token.Kind.COLON); type(); expect(Token.Kind.SEMICOLON); } } // function-definition := "func" IDENTIFIER "(" parameter-list ")" ":" type // statement-block private void functionDefinition() { if (accept(NonTerminal.FUNCTION_DEFINITION)) { tryDeclareSymbol(current); expect(Token.Kind.IDENTIFIER); expect(Token.Kind.OPEN_PAREN); enterScope(); parameterList(); expect(Token.Kind.CLOSE_PAREN); expect(Token.Kind.COLON); type(); statementBlock(); exitScope(); } } // array-declaration := "array" IDENTIFIER ":" type "[" INTEGER "]" { "[" // INTEGER "]" } ";" private void arrayDeclaration() { if (accept(NonTerminal.ARRAY_DECLARATION)) { tryDeclareSymbol(current); expect(Token.Kind.IDENTIFIER); expect(Token.Kind.COLON); type(); expect(Token.Kind.OPEN_BRACKET); expect(Token.Kind.INTEGER); expect(Token.Kind.CLOSE_BRACKET); while (accept(Token.Kind.OPEN_BRACKET)) { expect(Token.Kind.INTEGER); expect(Token.Kind.CLOSE_BRACKET); } expect(Token.Kind.SEMICOLON); } } // statement-block := "{" statement-list "}" private void statementBlock() { expect(Token.Kind.OPEN_BRACE); statementList(); expect(Token.Kind.CLOSE_BRACE); } // statement-list := { statement } private void statementList() { while (have(NonTerminal.STATEMENT)) { statement(); } } // statement := variable-declaration | call-statement | assignment-statement // | if-statement | while-statement | return-statement private void statement() { if (have(NonTerminal.VARIABLE_DECLARATION)) { variableDeclaration(); } else if (have(NonTerminal.CALL_STATEMENT)) { callStatement(); } else if (have(NonTerminal.ASSIGNMENT_STATEMENT)) { assignmentStatement(); } else if (have(NonTerminal.IF_STATEMENT)) { ifStatement(); } else if (have(NonTerminal.WHILE_STATEMENT)) { whileStatement(); } else if (have(NonTerminal.RETURN_STATEMENT)) { returnStatement(); } } // call-statement := call-expression ";" private void callStatement() { callExpression(); expect(Token.Kind.SEMICOLON); } // call-expression := "::" IDENTIFIER "(" expression-list ")" private void callExpression() { if (accept(NonTerminal.CALL_EXPRESSION)) { tryResolveSymbol(current); expect(Token.Kind.IDENTIFIER); expect(Token.Kind.OPEN_PAREN); expressionList(); expect(Token.Kind.CLOSE_PAREN); } } // assignment-statement := "let" designator "=" expression0 ";" private void assignmentStatement() { if (accept(NonTerminal.ASSIGNMENT_STATEMENT)) { designator(); expect(Token.Kind.ASSIGN); expression0(); expect(Token.Kind.SEMICOLON); } } // designator := IDENTIFIER { "[" expression0 "]" } private void designator() { if (have(NonTerminal.DESIGNATOR)) { tryResolveSymbol(current); nextToken(); while (accept(Token.Kind.OPEN_BRACKET)) { expression0(); expect(Token.Kind.CLOSE_BRACKET); } } } // if-statement := "if" expression0 statement-block [ "else" statement-block // ] private boolean ifStatement() { if (accept(NonTerminal.IF_STATEMENT)) { enterScope(); expression0(); statementBlock(); if (accept(Token.Kind.ELSE)) { statementBlock(); } exitScope(); } return false; } // while-statement := "while" expression0 statement-block private void whileStatement() { if (accept(NonTerminal.WHILE_STATEMENT)) { enterScope(); expression0(); statementBlock(); exitScope(); } } // return-statement := "return" expression0 ";" private void returnStatement() { if (accept(NonTerminal.RETURN_STATEMENT)) { expression0(); expect(Token.Kind.SEMICOLON); } } // expression-list := [ expression0 { "," expression0 } ] private void expressionList() { if (have(NonTerminal.EXPRESSION0)) { do { expression0(); } while (accept(Token.Kind.COMMA)); } } // expression0 := expression1 [ op0 expression1 ] private void expression0() { expression1(); if (accept(NonTerminal.OP0)) { expression1(); } } // expression1 := expression2 { op1 expression2 } private void expression1() { expression2(); while (accept(NonTerminal.OP1)) { expression2(); } } // expression2 := expression3 { op2 expression3 } private void expression2() { expression3(); while (accept(NonTerminal.OP2)) { expression3(); } } // expression3 := "not" expression3 | "(" expression0 ")" | designator | // call-expression | literal private void expression3() { if (have(NonTerminal.EXPRESSION3)) { if (accept(Token.Kind.NOT)) { expression3(); } else if (accept(Token.Kind.OPEN_PAREN)) { expression0(); expect(Token.Kind.CLOSE_PAREN); } else if (have(NonTerminal.DESIGNATOR)) { designator(); } else if (have(NonTerminal.CALL_EXPRESSION)) { callExpression(); } else if (have(NonTerminal.LITERAL)) { literal(); } } } // literal := INTEGER | FLOAT | TRUE | FALSE private void literal() { if (accept(NonTerminal.LITERAL)) { } } // parameter-list := [ parameter { "," parameter } ] private void parameterList() { do { if (have(NonTerminal.PARAMETER)) { parameter(); } } while (accept(Token.Kind.COMMA)); } // parameter := IDENTIFIER ":" type private void parameter() { if (have(NonTerminal.PARAMETER)) { tryDeclareSymbol(current); nextToken(); expect(Token.Kind.COLON); type(); } } // type := IDENTIFIER private void type() { expect(Token.Kind.IDENTIFIER); } private boolean have(NonTerminal nonterminal) { return nonterminal.firstSet().contains(current.kind); } private boolean have(Kind kind) { return current.isToken(kind); } private boolean accept(NonTerminal nonterminal) { if (have(nonterminal)) { nextToken(); return true; } return false; } private boolean accept(Kind kind) { if (have(kind)) { nextToken(); return true; } return false; } private boolean expect(Kind kind) { if (accept(kind)) { return true; } String msg = error.reportSyntaxError(kind); throw new QuitParseException(msg); } private boolean expect(NonTerminal nonterminal) { if (accept(nonterminal)) { return true; } String msg = error.reportSyntaxError(nonterminal); throw new QuitParseException(msg); } private void nextToken() { try { current = scanner.next(); } catch (IOException e) { } } public boolean hasError() { return error.hasError(); } public String errorReport() { return error.toString(); } private void initSymbolTable() { symbolTable = new SymbolTable(); symbolTable.setParent(null); symbolTable.setDepth(0); symbolTable.insert("readInt"); symbolTable.insert("readFloat"); symbolTable.insert("printBool"); symbolTable.insert("printInt"); symbolTable.insert("printFloat"); symbolTable.insert("println"); } private void enterScope() { SymbolTable table = new SymbolTable(); table.setDepth(symbolTable.getDepth() + 1); table.setParent(symbolTable); symbolTable = table; } private void exitScope() { symbolTable = symbolTable.getParent(); } private Symbol tryResolveSymbol(Token ident) { assert (ident.isToken(Token.Kind.IDENTIFIER)); String name = ident.lexeme; try { return symbolTable.lookup(name); } catch (SymbolNotFoundError e) { String message = reportResolveSymbolError(name, ident.lineNumber, ident.charPosition); return new ErrorSymbol(message); } } private String reportResolveSymbolError(String name, int lineNum, int charPos) { return error.reportResolveSymbolError(lineNum, charPos, name); } private Symbol tryDeclareSymbol(Token ident) { assert (ident.isToken(Token.Kind.IDENTIFIER)); String name = ident.lexeme; try { return symbolTable.insert(name); } catch (RedeclarationError re) { String message = reportDeclareSymbolError(name, ident.lineNumber, ident.charPosition); return new ErrorSymbol(message); } } private String reportDeclareSymbolError(String name, int lineNum, int charPos) { return error.reportDeclareSymbolError(lineNum, charPos, name); } private class QuitParseException extends RuntimeException { private static final long serialVersionUID = 1L; public QuitParseException(String msg) { super(msg); } } private class ErrorReport { private StringBuffer buffer = new StringBuffer(); private final String expectedResponse = "SyntaxError(%d,%d)[Expected %s but got %s.]"; private final String tokenResponse = "SyntaxError(%d,%d)[Expected a token from %s but got %s.]"; private final String syntaxResponse = "SyntaxError(%d,%d)[Could not complete parsing.]"; public boolean hasError() { return buffer.length() != 0; } public String toString() { return buffer.toString(); } private void reportSyntaxError() { String message = String.format(syntaxResponse, current.lineNumber, current.charPosition); buffer.append(message); } private String reportSyntaxError(NonTerminal nonTerminal) { String message = String.format(tokenResponse, current.lineNumber, current.charPosition, nonTerminal.name(), current.kind); buffer.append(message + "\n"); return message; } private String reportSyntaxError(Token.Kind kind) { String message = String.format(expectedResponse, current.lineNumber, current.charPosition, kind, current.kind); buffer.append(message + "\n"); return message; } private String reportResolveSymbolError(int lineNumber, int charPosition, String name) { String message = "ResolveSymbolError(" + lineNumber + "," + charPosition + ")[Could not find " + name + ".]"; buffer.append(message + "\n"); buffer.append(symbolTable.toString() + "\n"); return message; } private String reportDeclareSymbolError(int lineNumber, int charPosition, String name) { String message = "DeclareSymbolError(" + lineNumber + "," + charPosition + ")[" + name + " already exists.]"; buffer.append(message + "\n"); buffer.append(symbolTable.toString() + "\n"); return message; } } }
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.recovery.handler; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.configuration.mgt.core.constant.ConfigurationConstants; import org.wso2.carbon.identity.configuration.mgt.core.exception.ConfigurationManagementClientException; import org.wso2.carbon.identity.configuration.mgt.core.exception.ConfigurationManagementException; import org.wso2.carbon.identity.configuration.mgt.core.model.Resource; import org.wso2.carbon.identity.recovery.IdentityRecoveryClientException; import org.wso2.carbon.identity.recovery.IdentityRecoveryConstants; import org.wso2.carbon.identity.recovery.handler.function.ResourceToProperties; import org.wso2.carbon.identity.recovery.internal.IdentityRecoveryServiceDataHolder; import org.wso2.carbon.identity.recovery.util.Utils; import java.util.HashMap; import java.util.Map; /** * Config store based property handler. */ public class ConfigStoreFunctionalityLockPropertyHandler { private static final Log log = LogFactory.getLog(ConfigStoreFunctionalityLockPropertyHandler.class); private static final boolean isDetailedErrorMessagesEnabled = Utils.isDetailedErrorResponseEnabled(); private static ConfigStoreFunctionalityLockPropertyHandler instance = new ConfigStoreFunctionalityLockPropertyHandler(); private ConfigStoreFunctionalityLockPropertyHandler() { } public static ConfigStoreFunctionalityLockPropertyHandler getInstance() { return instance; } public Map<String, String> getConfigStoreProperties(String tenantDomain, String functionalityIdentifier) throws IdentityRecoveryClientException { Map<String, String> properties; try { FrameworkUtils.startTenantFlow(tenantDomain); try { if (isFunctionalityLockResourceTypeExists()) { Resource resource = IdentityRecoveryServiceDataHolder.getInstance().getConfigurationManager() .getResource(IdentityRecoveryConstants.FUNCTIONALITY_LOCK_RESOURCE_TYPE, functionalityIdentifier); properties = new ResourceToProperties().apply(resource); } else { if (log.isDebugEnabled()) { log.debug("User Functionality properties are not configured. Resorting to default values."); } return getDefaultConfigurationPropertiesMap(); } } catch (ConfigurationManagementException e) { StringBuilder message = new StringBuilder( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_FAILED_TO_FETCH_RESOURCE_FROM_CONFIG_STORE .getMessage()); if (isDetailedErrorMessagesEnabled) { message.append("\nresource type: ") .append(IdentityRecoveryConstants.FUNCTIONALITY_LOCK_RESOURCE_TYPE); message.append("\nresource: ").append(functionalityIdentifier); } throw IdentityException.error(IdentityRecoveryClientException.class, IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_FAILED_TO_FETCH_RESOURCE_FROM_CONFIG_STORE .getCode(), message.toString()); } } finally { FrameworkUtils.endTenantFlow(); } return properties; } private Map<String, String> getDefaultConfigurationPropertiesMap() { Map<String, String> properties = new HashMap<>(); properties.put(IdentityRecoveryConstants.FUNCTION_MAX_ATTEMPTS_PROPERTY, IdentityRecoveryConstants.MAX_ATTEMPTS_DEFAULT); properties.put(IdentityRecoveryConstants.FUNCTION_LOCKOUT_TIME_PROPERTY, IdentityRecoveryConstants.LOCKOUT_TIME_DEFAULT); properties.put(IdentityRecoveryConstants.FUNCTION_LOGIN_FAIL_TIMEOUT_RATIO_PROPERTY, IdentityRecoveryConstants.LOGIN_FAIL_TIMEOUT_RATIO_DEFAULT); return properties; } /** * Returns true if the Functionality Lock type is already in the ConfigurationManager. * * @return {@code true} if the Functionality Lock resource type is already in the ConfigurationManager, * {@code false} otherwise. * @throws ConfigurationManagementException */ private boolean isFunctionalityLockResourceTypeExists() throws ConfigurationManagementException { try { IdentityRecoveryServiceDataHolder.getInstance().getConfigurationManager() .getResourceType(IdentityRecoveryConstants.FUNCTIONALITY_LOCK_RESOURCE_TYPE); } catch (ConfigurationManagementClientException e) { if (ConfigurationConstants.ErrorMessages.ERROR_CODE_RESOURCE_TYPE_DOES_NOT_EXISTS.getCode() .equals(e.getErrorCode())) { return false; } throw e; } return true; } }
package multipliersimulation; /** * @author Kiyeon * Kyle Del Castillo * CS 147 - Homework 2 * Multiplication Simulator */ public class MultiplierSimulation { public static void main(String[] args) throws Exception { //4-bit signed numbers are from -8 to +7 byte[] multiplierArray = { -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7 }; //4-bit signed numbers are from -8 to +7 byte[] multiplicandArray = { -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7 }; //String binary values for 4-bit multiplicands String binaryMultiplicand[] = { "1000", "1001", "1010", "1011", //-8, -7, -6, -5 "1100", "1101", "1110", "1111", //-4, -3, -2, -1 "0000", "0001", "0010", "0011", //0, 1, 2, 3 "0100", "0101", "0110", "0111", //4, 5, 6, 7 }; //String binary values for 4-bit multipliers String binaryMultiplier[] = { "1000", "1001", "1010", "1011", //-8, -7, -6, -5 "1100", "1101", "1110", "1111", //-4, -3, -2, -1 "0000", "0001", "0010", "0011", //0, 1, 2, 3 "0100", "0101", "0110", "0111", //4, 5, 6, 7 }; String twosExpected; //String for 2's complement of the expected result String twosResult; //String for 2's complement of the obtained result short[] expectedResult = new short[100]; //Array to store the expected result short[] result = new short[100]; //Array to store the obtained result //Double for loop for proper multiplication and printing //Simulate every possible 4-bit signed multiplication for(int i = 0; i < multiplicandArray.length; i++) //For every multiplier { for(int j = 0; j < multiplierArray.length; j++) //Multiply the multiplier to the multiplicand { expectedResult[i] = (short) (multiplicandArray[i] * multiplierArray[j]); result[i] = multiply(multiplicandArray[i], multiplierArray[j]); twosExpected = Integer.toBinaryString(expectedResult[i]); twosResult = Integer.toBinaryString(result[i]); //The following if/else statements are used to turn the corresponding binary into 8-bit format if(twosExpected.length() > 8) { twosExpected = twosExpected.substring(24, twosExpected.length()); //Cuts the string into 8-bit format } else { twosExpected = ("00000000" + twosExpected).substring(twosExpected.length()); //Formats the binary string into 8-bit format } if(twosResult.length() > 8) { twosResult = twosResult.substring(24, twosResult.length()); //Cuts the string into 8-bit format } else { twosResult = ("00000000" + twosResult).substring(twosResult.length()); //Formats the binary string into 8-bit format } //If the obtained result is not the same as expected result, print out the incorrect numbers. if(expectedResult[i] != result[i]) { System.out.printf("%10s%2s (%2s)%15s%2s (%2s)%20s%10s(%3s dec)%15s%10s(%3s)\n", "Multiplicand: ", binaryMultiplicand[i], multiplicandArray[i], "Multiplier: ", binaryMultiplier[j], multiplierArray[j],"Expected Result: ", twosExpected, expectedResult[i], "Obtained: ", twosResult,result[i]); } } } } //Hardware/Binary multiplication public static short multiply(byte multiplicand, byte multiplier) { short product = 0; //Initialize product for(int i = 0; i < 4; i++) //Condition to check if multiplier != 0 based on the hardware protocol { if ((multiplier & 1) != 0) //Logical AND { product = (short) (product + multiplicand); //Add previous product to multiplicand //Ends the infinite loop for trivial case of multiplier being always -1 after shifting //if(multiplier == -1) //{ // product = (short) (product * -1); //Corrects some output // break; //} } } return product; //Return product } }
class Solution { public boolean containsDuplicate(int[] nums) { Set set = new HashSet(); //重複確認用 for(int duplicateCheck : nums) { if(!set.add(duplicateCheck)) { //System.out.println(duplicateCheck); return true; } } return false; } }
package liu.java.nio.channels.classes; public class Test { }
package com.volvobuses.client.serviceImpl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.volvobuses.client.bean.GenTbBuseseventos; import com.volvobuses.client.dao.GenTbBuseseventosMapper; import com.volvobuses.client.service.GenTbBusesEventoService; import com.volvobuses.client.util.CriteriaManager; @Service public class GenTbBusesEventoServiceImpl implements GenTbBusesEventoService { @Autowired GenTbBuseseventosMapper genTbBuseseventoMapper; @Override public int save(GenTbBuseseventos bean) throws Exception { if (bean.getIdBusEvento() == null) return genTbBuseseventoMapper.insert(bean); else return genTbBuseseventoMapper.updateByPrimaryKeySelective(bean); } @Override public List<GenTbBuseseventos> select(CriteriaManager criteriaManager) throws Exception { return genTbBuseseventoMapper.selectByExample(criteriaManager); } @Override public GenTbBuseseventos selectByPrimaryKey(Integer primaryKey) throws Exception { return genTbBuseseventoMapper.selectByPrimaryKey(primaryKey); } }
package slimeknights.tconstruct.library.fluid; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.capability.FluidTankProperties; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidTankProperties; import net.minecraftforge.fluids.capability.templates.EmptyFluidHandler; import net.minecraftforge.fluids.capability.templates.FluidHandlerConcatenate; import java.lang.ref.WeakReference; public class FluidHandlerExtractOnlyWrapper extends FluidHandlerConcatenate { // we hold a weak reference as we don't want the drains when storing the wrapper to keep old smeltery TEs from being collected // if you need this functionality in another tank, implement it directly rather than using a wrapper private final WeakReference<IFluidHandler> parent; public FluidHandlerExtractOnlyWrapper(IFluidHandler parent) { super(parent); this.parent = new WeakReference<>(parent); } // checks if the parent is no longer available, for example the smeltery containing the tank was removed public boolean hasParent() { return parent.get() != null; } @Override public IFluidTankProperties[] getTankProperties() { if(hasParent()) { IFluidHandler iFluidHandler = parent.get(); assert iFluidHandler != null; IFluidTankProperties[] iFluidTankPropertiesArray = iFluidHandler.getTankProperties(); if(iFluidTankPropertiesArray.length > 0) { IFluidTankProperties fluidTankProperties = iFluidHandler.getTankProperties()[0]; return new IFluidTankProperties[]{new FluidTankProperties(fluidTankProperties.getContents(), fluidTankProperties.getCapacity(), true, false)}; } } return EmptyFluidHandler.EMPTY_TANK_PROPERTIES_ARRAY; } @Override public FluidStack drain(int maxDrain, boolean doDrain) { return null; } @Override public FluidStack drain(FluidStack resource, boolean doDrain) { return null; } }
package shop; import gui.GUIApplication; import shop.ShopGUI; public class ShopGUI extends GUIApplication { private ShopScreen shop; public static void main(String[] args) { ShopGUI s = new ShopGUI(960,540); Thread runner = new Thread(s); runner.start(); } public ShopGUI(int width, int height) { super(width, height); setVisible(true); } public void initScreen() { shop = new ShopScreen(getWidth(), getHeight()); setScreen(shop); } }
package com.drivetuningsh.constant; import lombok.Getter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Locale; @Getter public enum AppConstant { DEFAULT_LOCALE(Locale.ENGLISH), DEFAULT_ENCODING(StandardCharsets.UTF_8); private Locale locale; private Charset charset; AppConstant(Locale locale) { this.locale = locale; } AppConstant(Charset charset) { this.charset = charset; } }
package view; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import listener.DeleteListener; import listener.InputListener; import listener.MouseListener; import listener.OutputListener; import listener.ShowListener; import listener.UpdateListener; import model.JTable1; public class MainWindow { public boolean mouseflag;//值为false则排为降序,true则升序 public DefaultTableModel model; public JTable table; public JScrollPane jscp; public JMenuItem add; public JMenuItem edit; public JMenuItem search; public JButton btn1; public JButton btn3; public JButton btn5; public MainWindow() { JFrame frame=new JFrame("人事管理系统"); Container con=frame.getContentPane(); con.setLayout(new FlowLayout()); JMenuBar bar=new JMenuBar(); JMenu file=new JMenu("File"); JMenu help=new JMenu("Help"); add=new JMenuItem("增加"); ShowListener show=new ShowListener(this); add.addActionListener(show); DeleteListener dl=new DeleteListener(this); JMenuItem delete=new JMenuItem("删除"); delete.addActionListener(dl); edit=new JMenuItem("修改"); edit.addActionListener(show); JMenuItem update=new JMenuItem("更新"); search=new JMenuItem("查询"); search.addActionListener(show); JMenuItem input=new JMenuItem("导入"); InputListener il=new InputListener(this); input.addActionListener(il); JMenuItem output=new JMenuItem("导出"); OutputListener ol=new OutputListener(this); output.addActionListener(ol); file.add(add); file.add(delete); file.add(edit); file.add(update); file.add(search); file.add(input); file.add(output); bar.add(file); bar.add(help); bar.setPreferredSize(new Dimension(460,30)); frame.setJMenuBar(bar); JLabel label=new JLabel(" 人事管理系统"); Object[] obj={"编号","姓名","性别","部门","工资"}; model=new DefaultTableModel(obj,0); table=new JTable1(model); jscp=new JScrollPane(table); MouseListener ml=new MouseListener(this); table.addMouseListener(ml); JPanel p1=new JPanel(); p1.setLayout(new BorderLayout()); p1.add(label,BorderLayout.NORTH); p1.add(jscp,BorderLayout.CENTER); btn1=new JButton("增加"); btn1.addActionListener(show); JButton btn2=new JButton("删除"); btn2.addActionListener(dl); btn3=new JButton("修改"); btn3.addActionListener(show); JButton btn4=new JButton("更新"); UpdateListener ul=new UpdateListener(this); btn4.addActionListener(ul); btn5=new JButton("查询"); btn5.addActionListener(show); JPanel p2=new JPanel(); p2.add(btn1); p2.add(btn2); p2.add(btn3); p2.add(btn4); p2.add(btn5); con.add(p1); con.add(p2); frame.setSize(500, 560); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
package com.praktyki.log.web.message.models; import org.springframework.lang.Nullable; import java.time.LocalDate; import java.util.Objects; public class ScheduleCalculationEventModel { public int id; public double capital; public String installmentType; public int installmentAmount; public double interestRate; public LocalDate withdrawalDate; public double commissionRate; public Integer age; public boolean insurance; public double capitalInstallmentSum; public double interestInstallmentSum; public double loanPaidOutAmount; public double commissionAmount; public double insuranceTotalAmount; public double loanTotalCost; public double aprc; public LocalDate calculationDate; public ScheduleCalculationEventModel() { } public ScheduleCalculationEventModel( int id, double capital, String installmentType, int installmentAmount, double interestRate, LocalDate withdrawalDate, double commissionRate, Integer age, boolean insurance, double capitalInstallmentSum, double interestInstallmentSum, double loanPaidOutAmount, double commissionAmount, double insuranceTotalAmount, double loanTotalCost, double aprc, LocalDate calculationDate ) { this.id = id; this.capital = capital; this.installmentType = installmentType; this.installmentAmount = installmentAmount; this.interestRate = interestRate; this.withdrawalDate = withdrawalDate; this.commissionRate = commissionRate; this.age = age; this.insurance = insurance; this.capitalInstallmentSum = capitalInstallmentSum; this.interestInstallmentSum = interestInstallmentSum; this.loanPaidOutAmount = loanPaidOutAmount; this.commissionAmount = commissionAmount; this.insuranceTotalAmount = insuranceTotalAmount; this.loanTotalCost = loanTotalCost; this.aprc = aprc; this.calculationDate = calculationDate; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ScheduleCalculationEventModel that = (ScheduleCalculationEventModel) o; return id == that.id && Double.compare(that.capital, capital) == 0 && installmentAmount == that.installmentAmount && Double.compare(that.interestRate, interestRate) == 0 && Double.compare(that.commissionRate, commissionRate) == 0 && age.equals(that.age) && insurance == that.insurance && Double.compare(that.capitalInstallmentSum, capitalInstallmentSum) == 0 && Double.compare(that.interestInstallmentSum, interestInstallmentSum) == 0 && Double.compare(that.loanPaidOutAmount, loanPaidOutAmount) == 0 && Double.compare(that.commissionAmount, commissionAmount) == 0 && Double.compare(that.insuranceTotalAmount, insuranceTotalAmount) == 0 && Double.compare(that.loanTotalCost, loanTotalCost) == 0 && Double.compare(that.aprc, aprc) == 0 && installmentType.equals(that.installmentType) && withdrawalDate.equals(that.withdrawalDate) && calculationDate.equals(that.calculationDate); } @Override public int hashCode() { return Objects.hash( id, capital, installmentType, installmentAmount, interestRate, withdrawalDate, commissionRate, age, insurance, capitalInstallmentSum, interestInstallmentSum, loanPaidOutAmount, commissionAmount, insuranceTotalAmount, loanTotalCost, aprc, calculationDate ); } }
package com.jwebsite.dao; import java.util.List; import com.jwebsite.vo.Special; public interface SpecialDao { //添加专题 public void insertSpecial(Special special) throws Exception; //查询所有专题 public List<Special> quaryAllSpecial() throws Exception; //删除一条记录 public void delOneSpecial(int SpecialID) throws Exception; //查询一条 public Special quaryOneSpecial(int specialID) throws Exception; //更新专题 public void updateSpecial(Special special) throws Exception; //在下拉列表中显示专题 public String showSpecialInSel(String specialID) throws Exception; }
package net.b07z.sepia.server.mesh.server; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.b07z.sepia.server.core.data.Role; import net.b07z.sepia.server.core.tools.FilesAndStreams; import net.b07z.sepia.server.core.tools.Is; import net.b07z.sepia.server.core.tools.SandboxClassLoader; import net.b07z.sepia.server.core.users.AuthenticationAssistAPI; import net.b07z.sepia.server.mesh.endpoints.ExampleEndpoints; /** * Read, write and store Mesh-Node server configuration. * * @author Florian Quirin * */ public class ConfigNode { private static final Logger log = LoggerFactory.getLogger(ConfigNode.class); public static final String SERVERNAME = "SEPIA-Mesh-Node"; //public server name public static final String apiVersion = "v0.10.0"; //API version //Server settings (port, web-server, folders etc.) public static String settingsFolder = "Settings/"; //folder for settings public static String configFile = settingsFolder + "node.properties"; //external configuration file - note: this will be overwritten in "Setup" and "Start" public static String webServerFolder = "WebServer/"; //folder for web-server public static String pluginsFolder = "Plugins/"; //folder for plugins public static int serverPort = 20780; //**server port public static boolean enableCORS = true; //enable CORS (set access-control headers) public static boolean useSandboxPolicy = true; //enable security policy to restrict e.g. access to 'System.exit()' public static boolean hostFiles = false; //use web-server? public static String privacyPolicyLink = "http://localhost:20780/privacy-policy.html"; //link to privacy policy in case you host files public static String accessPin = "123456"; //**user defined access pin for non-critical access e.g. to statistics public static String localName = "sepia-mesh-node"; //**user defined local server name public static String localSecret = "123456"; //**user defined secret to validate local server public static String meshId = "MESHbyW3YLh8jTQPs5uzt2SzbmXZyphW"; //**one step of inter-API communication security - similar to clusterKey public static boolean allowInternalCalls = false; //**allow API-to-API authentication via cluster-key public static boolean allowGlobalDevRequests = false; //**restrict certain developer-specific requests to private network public static boolean usePlugins = false; //use code loading on run-time public static boolean pluginsRequireAuthentication = false; //does plugin execution require authentication? public static Role pluginsRequiredRole = Role.developer; //required role to execute a plugin (only used when auth. required) public static boolean pluginsRequireLocalhost = false; //only allow localhost plugin calls? (handy for client controls) public static boolean pluginsRequirePin = false; //ask for PIN when using a plugin? //Modules and APIs to know public static String assistEndpointUrl = "http://localhost:20721/"; //SEPIA Assist-API endpoint URL (e.g. for authentication) public static String authenticationModule = AuthenticationAssistAPI.class.getCanonicalName(); //----------- Sandbox Setup ------------- //to be used with SandboxClassLoader private static List<String> blackList = new ArrayList<>(); /** * Setup sandbox for {@link SandboxClassLoader}. */ public static void setupSandbox(){ blackList.add(ConfigNode.class.getPackage().getName()); //server.* blackList.add(ExampleEndpoints.class.getPackage().getName()); //endpoints.* } public static void addToSandboxBlackList(String classOrPackageName){ blackList.add(classOrPackageName); } public static List<String> getSandboxBlacklist(){ return blackList; } //----------- Modules ----------- public static void setupAuthModule(){ if (authenticationModule != null) { //TODO: setup module if required } } //---------- helpers ---------- /** * Load server settings from properties file. */ public static void loadSettings(String confFile){ if (confFile == null || confFile.isEmpty()) confFile = configFile; try{ Properties settings = FilesAndStreams.loadSettings(confFile); //server accessPin = settings.getProperty("server_access_pin"); localName = settings.getProperty("server_local_name"); localSecret = settings.getProperty("server_local_secret"); serverPort = Integer.valueOf(settings.getProperty("server_port")); meshId = settings.getProperty("mesh_id"); allowInternalCalls = Boolean.valueOf(settings.getProperty("allow_internal_calls")); allowGlobalDevRequests = Boolean.valueOf(settings.getProperty("allow_global_dev_requests")); enableCORS = Boolean.valueOf(settings.getProperty("enable_CORS")); //plugin stuff usePlugins = Boolean.valueOf(settings.getProperty("use_plugins")); pluginsRequireAuthentication = Boolean.valueOf(settings.getProperty("plugins_require_authentication")); String pluginsRequiredRoleString = settings.getProperty("plugins_required_user_role"); if (Is.notNullOrEmpty(pluginsRequiredRoleString)){ pluginsRequiredRole = Role.valueOf(pluginsRequiredRoleString); } pluginsRequireLocalhost = Boolean.valueOf(settings.getProperty("plugins_require_localhost", "false")); pluginsRequirePin = Boolean.valueOf(settings.getProperty("plugins_require_pin", "false")); //webserver hostFiles = Boolean.valueOf(settings.getProperty("host_files")); privacyPolicyLink = settings.getProperty("privacy_policy"); //security and policies useSandboxPolicy = Boolean.valueOf(settings.getProperty("use_sandbox_security_policy")); //connectors and modules assistEndpointUrl = settings.getProperty("assist_endpoint_url"); authenticationModule = settings.getProperty("module_authentication"); log.info("loading settings from " + confFile + "... done."); }catch (Exception e){ log.error("loading settings from " + confFile + "... failed!"); } } /** * Save server settings to file. Skip security relevant fields. */ public static void saveSettings(String confFile){ if (confFile == null || confFile.isEmpty()) confFile = configFile; //save all personal parameters Properties settings = new Properties(); //server settings.setProperty("server_access_pin", accessPin); settings.setProperty("server_local_name", localName); settings.setProperty("server_local_secret", localSecret); settings.setProperty("server_port", Integer.toString(serverPort)); settings.setProperty("mesh_id", meshId); settings.setProperty("allow_internal_calls", Boolean.toString(allowInternalCalls)); settings.setProperty("allow_global_dev_requests", Boolean.toString(allowGlobalDevRequests)); settings.setProperty("enable_CORS", Boolean.toString(enableCORS)); //plugins stuff settings.setProperty("use_plugins", Boolean.toString(usePlugins)); settings.setProperty("plugins_require_authentication", Boolean.toString(pluginsRequireAuthentication)); settings.setProperty("plugins_required_user_role", pluginsRequiredRole.name()); settings.setProperty("plugins_require_localhost", Boolean.toString(pluginsRequireLocalhost)); settings.setProperty("plugins_require_pin", Boolean.toString(pluginsRequirePin)); //webserver settings.setProperty("host_files", Boolean.toString(hostFiles)); settings.setProperty("privacy_policy", privacyPolicyLink); //security and policies settings.setProperty("use_sandbox_security_policy", Boolean.toString(useSandboxPolicy)); //connectors and modules settings.setProperty("assist_endpoint_url", assistEndpointUrl); settings.setProperty("module_authentication", authenticationModule); try{ FilesAndStreams.saveSettings(confFile, settings); log.info("saving settings to " + confFile + "... done."); }catch (Exception e){ log.error("saving settings to " + confFile + "... failed!"); } } }
package chapter_8; import static org.junit.jupiter.api.Assertions.*; import java.math.BigDecimal; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class SavingsAccountTest { SavingsAccount yourSavings; SavingsAccount mySavings; @BeforeEach void setUp() throws Exception { yourSavings = new SavingsAccount(BigDecimal.valueOf(2500.00), BigDecimal.valueOf(0.06)); mySavings = new SavingsAccount(BigDecimal.valueOf(3000.00), BigDecimal.valueOf(0.06)); } @AfterEach void tearDown() throws Exception { } @Test void constructorTest() { assertNotNull(mySavings); assertNotNull(yourSavings); } @Test void savingAccountCanChangeInterestRate() { yourSavings.modifyInterestRate(BigDecimal.valueOf(0.04)); assertEquals(BigDecimal.valueOf(0.04), mySavings.getAnnualInterestRate()); //assertEquals(BigDecimal.valueOf((3000 * 0.04)/12), mySavings.calculateMonthlyInterest()); SavingsAccount.modifyInterestRate(BigDecimal.valueOf(0.05)); //assertEquals(BigDecimal.valueOf(10.417), yourSavings.calculateMonthlyInterest()); } }
package fr.centralesupelec.sio.model; /** * Define the characteristics of a Person. */ public abstract class Person { // Only name was implemented in a first time, next step would have been to add an id. private String name; public String getName() { return name; } public void setName( String name ) { this.name = name; } }
package org.nistagram.campaignmicroservice.data.dto; import java.io.Serializable; public class FollowingStatusDto implements Serializable { private String following; private String notifications; private boolean muted; private boolean blocked; public FollowingStatusDto() { } public FollowingStatusDto(String following, String notifications, boolean muted, boolean blocked) { this.following = following; this.notifications = notifications; this.muted = muted; this.blocked = blocked; } public String getFollowing() { return following; } public void setFollowing(String following) { this.following = following; } public String getNotifications() { return notifications; } public void setNotifications(String notifications) { this.notifications = notifications; } public boolean isMuted() { return muted; } public void setMuted(boolean muted) { this.muted = muted; } public boolean isBlocked() { return blocked; } public void setBlocked(boolean blocked) { this.blocked = blocked; } @Override public String toString() { return "FollowingStatusDto{" + "following='" + following + '\'' + ", notifications='" + notifications + '\'' + ", muted=" + muted + ", blocked=" + blocked + '}'; } }
package com.wrathOfLoD.Models.Items; import com.wrathOfLoD.Models.Commands.EntityActionCommands.PickUpItemCommand; import com.wrathOfLoD.Models.Entity.Character.Character; import com.wrathOfLoD.Models.Entity.Entity; import com.wrathOfLoD.Observers.ModelObservers.DestroyableModelObserver; import com.wrathOfLoD.VisitorInterfaces.ItemVisitor; /** * Created by matthewdiaz on 4/7/16. */ public abstract class TakeableItem extends Item{ public TakeableItem(String name ){super(name);} @Override public void encounter(Entity entity){ PickUpItemCommand pickUpItemCommand = new PickUpItemCommand(entity, this); pickUpItemCommand.execute(); System.out.println("PICK UP CALLED?"); for(DestroyableModelObserver mio : getDestroyableModelObservers()){ mio.notifyDestroy(entity.getPosition()); } } public abstract void use(Character character); public void accept(ItemVisitor iv){ iv.visitTakeable(this); } }
package com.EvilNotch.silkspawners; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.EvilNotch.silkspawners.entity.MinecartMobSpawner; import com.EvilNotch.silkspawners.util.Util; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.BlockLiquid; import net.minecraft.client.Minecraft; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.IEntityLivingData; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemMonsterPlacer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.MobSpawnerBaseLogic; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityMobSpawner; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.ChatComponentText; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.Facing; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; public class forge_egg extends Item { public static String entityname0; public static String entityname1; public static List Listing; forge_egg(String name) { this.setUnlocalizedName(name); this.setTextureName("silkspawners:foge_egg"); this.setCreativeTab(CreativeTabs.tabMisc); this.setHasSubtypes(true); } @Override public String getItemStackDisplayName(ItemStack stack) { String overloaded = "1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcd"; String test = "nevermine.archvine.com.java.util/hi/mnm.Monster"; //String max_line = "nevermine.archvine" + " Blank Forge Egg"; int max_line = 34; if (stack.getTagCompound() == null || stack.getTagCompound().getString("EntityId") == "" || stack.getTagCompound().getString("EntityId") == null) { String a = ("" + StatCollector.translateToLocal(MainJava.forge_egg.getUnlocalizedName() + ".name")).trim(); return a; } return Util.getItemTranslation(SilkSpawners.getNBT(stack), stack, false); } /** * Callback for item usage. If the item does something special on right clicking, he will have one of those. Return * True if something happen and false if it don't. This is for ITEMS, not BLOCKS */ @Override public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int offset, float p_77648_8_, float p_77648_9_, float p_77648_10_) { if (world.isRemote) { return true; } if (!stack.hasTagCompound()) { return true; } else { Block block = world.getBlock(x, y, z); int x1 = x + Facing.offsetsXForSide[offset]; int y1 = y + Facing.offsetsYForSide[offset]; int z1 = z + Facing.offsetsZForSide[offset]; double d0 = 0.0D; if (offset == 1 && block.getRenderType() == 11) { d0 = 0.5D; } TileEntity tile = world.getTileEntity(x1, y1, z1); TileEntity tile1 = world.getTileEntity(x,y,z); NBTTagCompound nbt = stack.getTagCompound(); entityname1 = nbt.getString("EntityId"); if (world.getBlock(x1, y1, z1) instanceof BlockLiquid && tile instanceof TileEntityMobSpawner) { Entity entity1 = EntityList.createEntityByName(nbt.getString("EntityId"), world); if (entity1 == null) { return false; } SilkSpawners.setMountedSpawner(stack, tile, world, x1, y1, z1); //New Super Cool Optimization Method For Spawners if (!player.capabilities.isCreativeMode) { --stack.stackSize; } return true; } if (tile1 instanceof TileEntityMobSpawner) { Entity entity1 = EntityList.createEntityByName(nbt.getString("EntityId"), world); if (entity1 == null && !nbt.getString("EntityId").equals("Blank") || SilkSpawners.getTagList(stack, "Mounting", 10).tagCount() > 0 && nbt.getString("EntityId").equals("Blank")) { if(config.Debug) System.out.println("Returning:"); return false; } SilkSpawners.setMountedSpawner(stack, tile1, world, x, y, z); if (!player.capabilities.isCreativeMode) { --stack.stackSize; } return true; } entityname0 = nbt.getString("EntityId"); // Entity entity = spawnCreature(p_77648_3_, p_77648_1_.getItemDamage(), (double)p_77648_4_ + 0.5D, (double)p_77648_5_ + d0, (double)p_77648_6_ + 0.5D); Entity entity = SilkSpawners.spawnCreature(world, stack, (double)x1 + 0.5D, (double)y1 + d0, (double)z1 + 0.5D, true); if (entity != null) { if (entity instanceof EntityLivingBase && stack.hasDisplayName()) { if (!stack.getDisplayName().equals("")) { ((EntityLiving)entity).setCustomNameTag(stack.getDisplayName()); } } if (!player.capabilities.isCreativeMode) { --stack.stackSize; } } return true; } } /** * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer */ @Override public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { if (world.isRemote) { //System.out.println("movingobj"); return stack; } if (!stack.hasTagCompound()) { return stack; } if (stack.getTagCompound().getString("EntityId") == "") { //System.out.println("movingobj"); return stack; } else { MovingObjectPosition movingobjectposition = this.getMovingObjectPositionFromPlayer(world, player, true); if (movingobjectposition == null) { //System.out.println("movingobj"); return stack; } else { if (movingobjectposition.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { int i = movingobjectposition.blockX; int j = movingobjectposition.blockY; int k = movingobjectposition.blockZ; if (!world.canMineBlock(player, i, j, k)) { //System.out.println("mineing"); return stack; } if (!player.canPlayerEdit(i, j, k, movingobjectposition.sideHit, stack)) { //System.out.println("Edit"); return stack; } int x = i; int y = j; int z = k; //System.out.println(world.getBlock(i, j, k).getLocalizedName()); if (!(world.getBlock(i, j, k) instanceof BlockLiquid)) { if (movingobjectposition.sideHit == 0) { j -= 1; } if (movingobjectposition.sideHit == 1) { j += 1; } if (movingobjectposition.sideHit == 2) { k -= 1; } if (movingobjectposition.sideHit == 3) { k += 1; } if (movingobjectposition.sideHit == 4) { i -= 1; } if (movingobjectposition.sideHit == 5) { i += 1; } } //System.out.println("After:" + world.getBlock(i, j, k).getLocalizedName()); if (world.getBlock(i, j, k) instanceof BlockLiquid) { NBTTagCompound nbt = stack.getTagCompound(); entityname1 = nbt.getString("EntityId"); TileEntity tile = world.getTileEntity(i, j, k); Entity entity1 = EntityList.createEntityByName(nbt.getString("EntityId"), world); if (entity1 == null) { return stack; } if (tile instanceof TileEntityMobSpawner) { SilkSpawners.setMountedSpawner(stack, tile, world, x, y, z); if (!player.capabilities.isCreativeMode) { --stack.stackSize; } return stack; } Entity entity = SilkSpawners.spawnCreature(world, stack, (double)x + 0.5D, (double)y, (double)z + 0.5D, true); if (entity != null) { if (entity instanceof EntityLivingBase && stack.hasDisplayName()) { ((EntityLiving)entity).setCustomNameTag(stack.getDisplayName()); } if (!player.capabilities.isCreativeMode) { --stack.stackSize; } } } } return stack; } } } @Override @SideOnly(Side.CLIENT) public void getSubItems(Item p_150895_1_, CreativeTabs p_150895_2_, List p_150895_3_) { SilkSpawners.genHashMaps(); //Generates All HashMaps if they are not empty Iterator iterator = SilkSpawners.forge_eggs.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry pair2 = (Map.Entry)iterator.next(); String it = pair2.getKey().toString(); NBTTagCompound nbt = new NBTTagCompound(); NBTTagCompound local = new NBTTagCompound(); World world = DimensionManager.getWorld(0); Entity entity = EntityList.createEntityByName(it, world); if (entity != null) { String raw = EntityLookUp.getEntityMod(entity); String[] parts = raw.split("\u00A9"); String modname = parts[0]; nbt.setString("EntityId", it); nbt.setString("modid", modname); nbt.setString("CreativeTab","true"); ItemStack jk = new ItemStack(MainJava.forge_egg, 1, 0); jk.setTagCompound(nbt); int globalID = EntityList.getEntityID(entity); if (globalID > 0) { if (!EntityList.entityEggs.containsKey(globalID) || config.GlobalIdForgeEggs == true) { p_150895_3_.add(jk); } } else{ //for versions 1.8+ check if needs forge egg checker same for everything else... p_150895_3_.add(jk); } } } } @Override @SideOnly(Side.CLIENT) public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean b) { SilkSpawners.addEggToolTip(stack, list, b); } }
package com.encdata.corn.niblet.security; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Maps; import org.keycloak.adapters.HttpClientBuilder; import org.keycloak.adapters.KeycloakDeployment; import org.keycloak.adapters.authentication.ClientCredentialsProviderUtils; import org.keycloak.adapters.authorization.PolicyEnforcer; import org.keycloak.adapters.rotation.HardcodedPublicKeyLocator; import org.keycloak.adapters.rotation.JWKPublicKeyLocator; import org.keycloak.adapters.spi.HttpFacade; import org.keycloak.common.enums.SslRequired; import org.keycloak.common.util.PemUtils; import org.keycloak.enums.TokenStore; import org.keycloak.representations.adapters.config.AdapterConfig; import org.keycloak.representations.adapters.config.PolicyEnforcerConfig; import org.keycloak.util.SystemPropertiesJsonParserFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.IOException; import java.io.InputStream; import java.security.PublicKey; import java.util.Map; /** * Copyright (c) 2015-2017 Enc Group * * @Description keycloak配置处理类 * @Author Siwei Jin * @Date 2018/10/26 13:31 */ @Service public class KeycloakConfigResolverNew implements org.keycloak.adapters.KeycloakConfigResolver { private static final Logger LOG = LoggerFactory.getLogger(KeycloakConfigResolverNew.class); @Value(value = "${keycloak.realm}") private String realm; @Value(value = "${keycloak.auth-server-url}") private String authServerUrl; @Value(value = "${keycloak.ssl-required}") private String sslRequired; @Value(value = "${keycloak.resource}") private String resource; @Value(value = "${keycloak.credentials.secret}") private String credentialsSecret; @Value(value = "${keycloak.use-resource-role-mappings}") private Boolean useResourceRoleMappings; protected KeycloakDeployment deployment = new KeycloakDeployment(); private AdapterConfig adapterConfig; @Override public KeycloakDeployment resolve(HttpFacade.Request request) { adapterConfig = loadAdapterConfig(null); return internalBuild(adapterConfig); } protected AdapterConfig loadAdapterConfig(InputStream is) { AdapterConfig adapterConfig = new AdapterConfig(); ObjectMapper mapper = new ObjectMapper(new SystemPropertiesJsonParserFactory()); mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); try { if(null!=is){ adapterConfig = (AdapterConfig)mapper.readValue(is, AdapterConfig.class); } adapterConfig.setRealm(realm); adapterConfig.setAuthServerUrl(authServerUrl); adapterConfig.setSslRequired(sslRequired); adapterConfig.setResource(resource); Map<String, Object> credentials = Maps.newHashMap(); credentials.put("secret", credentialsSecret); adapterConfig.setCredentials(credentials); adapterConfig.setUseResourceRoleMappings(useResourceRoleMappings); return adapterConfig; } catch (IOException var4) { throw new RuntimeException(var4); } } protected KeycloakDeployment internalBuild(AdapterConfig adapterConfig) { if (adapterConfig.getRealm() == null) { throw new RuntimeException("Must set 'realm' in config"); } else { this.deployment.setRealm(adapterConfig.getRealm()); String resource = adapterConfig.getResource(); if (resource == null) { throw new RuntimeException("Must set 'resource' in config"); } else { this.deployment.setResourceName(resource); String realmKeyPem = adapterConfig.getRealmKey(); if (realmKeyPem != null) { try { PublicKey realmKey = PemUtils.decodePublicKey(realmKeyPem); HardcodedPublicKeyLocator pkLocator = new HardcodedPublicKeyLocator(realmKey); this.deployment.setPublicKeyLocator(pkLocator); } catch (Exception var6) { throw new RuntimeException(var6); } } else { JWKPublicKeyLocator pkLocator = new JWKPublicKeyLocator(); this.deployment.setPublicKeyLocator(pkLocator); } if (adapterConfig.getSslRequired() != null) { this.deployment.setSslRequired(SslRequired.valueOf(adapterConfig.getSslRequired().toUpperCase())); } else { this.deployment.setSslRequired(SslRequired.EXTERNAL); } if (adapterConfig.getTokenStore() != null) { this.deployment.setTokenStore(TokenStore.valueOf(adapterConfig.getTokenStore().toUpperCase())); } else { this.deployment.setTokenStore(TokenStore.SESSION); } if (adapterConfig.getPrincipalAttribute() != null) { this.deployment.setPrincipalAttribute(adapterConfig.getPrincipalAttribute()); } this.deployment.setResourceCredentials(adapterConfig.getCredentials()); this.deployment.setClientAuthenticator(ClientCredentialsProviderUtils.bootstrapClientAuthenticator(this.deployment)); this.deployment.setPublicClient(adapterConfig.isPublicClient()); this.deployment.setUseResourceRoleMappings(adapterConfig.isUseResourceRoleMappings()); this.deployment.setExposeToken(adapterConfig.isExposeToken()); if (adapterConfig.isCors()) { this.deployment.setCors(true); this.deployment.setCorsMaxAge(adapterConfig.getCorsMaxAge()); this.deployment.setCorsAllowedHeaders(adapterConfig.getCorsAllowedHeaders()); this.deployment.setCorsAllowedMethods(adapterConfig.getCorsAllowedMethods()); } this.deployment.setBearerOnly(adapterConfig.isBearerOnly()); this.deployment.setAutodetectBearerOnly(adapterConfig.isAutodetectBearerOnly()); this.deployment.setEnableBasicAuth(adapterConfig.isEnableBasicAuth()); this.deployment.setAlwaysRefreshToken(adapterConfig.isAlwaysRefreshToken()); this.deployment.setRegisterNodeAtStartup(adapterConfig.isRegisterNodeAtStartup()); this.deployment.setRegisterNodePeriod(adapterConfig.getRegisterNodePeriod()); this.deployment.setTokenMinimumTimeToLive(adapterConfig.getTokenMinimumTimeToLive()); this.deployment.setMinTimeBetweenJwksRequests(adapterConfig.getMinTimeBetweenJwksRequests()); this.deployment.setPublicKeyCacheTtl(adapterConfig.getPublicKeyCacheTtl()); if (realmKeyPem == null && adapterConfig.isBearerOnly() && adapterConfig.getAuthServerUrl() == null) { throw new IllegalArgumentException("For bearer auth, you must set the realm-public-key or auth-server-url"); } else { if (realmKeyPem == null || !this.deployment.isBearerOnly() || this.deployment.isEnableBasicAuth() || this.deployment.isRegisterNodeAtStartup() || this.deployment.getRegisterNodePeriod() != -1) { this.deployment.setClient((new HttpClientBuilder()).build(adapterConfig)); } if (adapterConfig.getAuthServerUrl() != null || this.deployment.isBearerOnly() && realmKeyPem != null) { this.deployment.setAuthServerBaseUrl(adapterConfig); if (adapterConfig.getTurnOffChangeSessionIdOnLogin() != null) { this.deployment.setTurnOffChangeSessionIdOnLogin(adapterConfig.getTurnOffChangeSessionIdOnLogin().booleanValue()); } PolicyEnforcerConfig policyEnforcerConfig = adapterConfig.getPolicyEnforcerConfig(); if (policyEnforcerConfig != null) { this.deployment.setPolicyEnforcer(new PolicyEnforcer(this.deployment, adapterConfig)); } LOG.debug("Use authServerUrl: " + this.deployment.getAuthServerBaseUrl() + ", tokenUrl: " + this.deployment.getTokenUrl() + ", relativeUrls: " + this.deployment.getRelativeUrls()); return this.deployment; } else { throw new RuntimeException("You must specify auth-server-url"); } } } } } }
package eu.test.dropwizard.dao; import com.codahale.metrics.annotation.Metered; import com.codahale.metrics.annotation.Timed; import com.google.common.base.Optional; import eu.test.dropwizard.model.Person; import io.dropwizard.hibernate.AbstractDAO; import org.hibernate.SessionFactory; import java.util.List; public class PersonDAO extends AbstractDAO<Person> { public PersonDAO(SessionFactory sessionFactory){ super(sessionFactory); } @Metered public Optional<Person> findById(Long id){ return Optional.fromNullable(get(id)); } @Metered public Person create(Person person){ return persist(person); } @Metered public List<Person> findAll(){ return list(namedQuery(Person.class.getName() +".findAll")); } }
package com.example.alex.allthewage; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; //FIREBASE AUTH import com.google.firebase.auth.FirebaseAuth; public class MainActivity extends Activity { Button rButton; //employer button Button eButton; //employee button @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_split); rButton = (Button) findViewById(R.id.employerButton); eButton = (Button) findViewById(R.id.employeeButton); rButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent split1 = new Intent(MainActivity.this, employer_login.class); startActivity(split1); } }); eButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //TRIED TO SWITCH System.out.println("TRIED TO SWITCH"); Intent split2 = new Intent(MainActivity.this, employee_login.class); startActivity(split2); } }); } }
import java.util.*; public class PermutationCounts { private long MOD = 1000000007; private int MN = 1000000; private long[] factorials; private long[] invFactorials; public int countPermutations(int N, int[] pos) { factorials = new long[N + 1]; factorials[0] = 1; for(int i = 1; i < factorials.length; ++i) { factorials[i] = i * factorials[i - 1]; factorials[i] %= MOD; } invFactorials = new long[MN + 1]; invFactorials[MN] = 397802501; for(int i = MN - 1; 0 <= i; --i) { invFactorials[i] = ((i + 1) * invFactorials[i+1]) % MOD; } ArrayList<Integer> posList = new ArrayList<Integer>(); posList.add(0); posList.add(N); for(int i = 0; i < pos.length; ++i) { posList.add(pos[i]); } Collections.sort(posList); long[] dp = new long[posList.size()]; dp[0] = 1; for(int i = 1; i < dp.length; ++i) { for(int j = 0; j < i; ++j) { long temp = (dp[j] * C(posList.get(i), posList.get(j))) % MOD; if((i + j)%2 == 0) { dp[i] = (dp[i] - temp + MOD)%MOD; } else { dp[i] += temp; dp[i] %= MOD; } } } return (int)dp[dp.length - 1]; } private long C(int N, int R) { return (((factorials[N] * invFactorials[R])%MOD)*invFactorials[N - R])%MOD; } }
//MJ Keegan 15170756 public class Course2 { private String courseName; private String[] students = new String[100]; private int numberOfStudents; public void Course(String courseName) { this.courseName = courseName; } /** Adds the name of the students to the array of students and increments the number of students present */ public void addStudent(String student) { if (numberOfStudents == students.length) { String [] temp = students; students = new String [students.length * 2]; System.arraycopy(temp, 0 , students, 0, numberOfStudents); } students[numberOfStudents] = student; numberOfStudents++; } /** Returns the array of student names */ public String[] getStudents() { String [] temp = new String[numberOfStudents]; System.arraycopy(students, 0 , temp, 0, numberOfStudents); return temp; } /** Returns the value of the amount of students present */ public int getNumberOfStudents() { return numberOfStudents; } /** Return sa String of the name of a course */ public String getCourseName() { return courseName; } /** Removes a student fom course */ public void dropStudent(String student) { int index = -1; for (int i = 0; i < numberOfStudents && index == -1; i++) { if (students[i].equals(student)) index = i; } if (index != -1) { System.arraycopy(students, index + 1, students, index, numberOfStudents - index - 1); numberOfStudents--; } } /** Removes all students */ public void clearStudents() { students = new String[100]; numberOfStudents = 0; } }
package com.thepoofy.website_searcher.csv.writer; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import com.fasterxml.jackson.dataformat.csv.CsvSchema.ColumnType; import com.thepoofy.website_searcher.models.MozResults; public class MozCsvWriter implements MozWriter { @Override public void toFile(String fileName, List<MozResults> mozData) throws IOException, FileNotFoundException { CsvSchema schema = CsvSchema.builder() .addColumn("rank", ColumnType.NUMBER) .addColumn("url", ColumnType.NUMBER) .addColumn("linkingRootDomains", ColumnType.NUMBER) .addColumn("externalLinks", ColumnType.NUMBER) .addColumn("mozRank", ColumnType.NUMBER) .addColumn("mozTrust", ColumnType.NUMBER) .addColumn("isSuccessful", ColumnType.BOOLEAN) .build(); CsvMapper mapper = new CsvMapper(); try (FileOutputStream fos = new FileOutputStream(fileName)) { ObjectWriter writer = mapper.writer(schema.withLineSeparator("\n")); writer.writeValues(fos).writeAll(mozData.toArray()); } } }
package models.converter;//package models.converter; // //import javax.persistence.AttributeConverter; //import javax.persistence.Converter; //import java.time.LocalDateTime; //import java.time.ZoneOffset; // //@Converter(autoApply = true) //public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Integer> { // @Override // public Integer convertToDatabaseColumn(LocalDateTime attribute) { // if (attribute == null) { // return null; // } else { // return (int)attribute.toEpochSecond(ZoneOffset.UTC); // } // } // // @Override // public LocalDateTime convertToEntityAttribute(Integer dbData) { // if (dbData == null) { // return null; // } else { // return LocalDateTime.ofEpochSecond(dbData.longValue(), 0, ZoneOffset.UTC); // } // } //}
package br.com.saulofarias.customerapi.repository; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertEquals; import java.text.ParseException; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.context.annotation.Lazy; import org.springframework.test.context.junit4.SpringRunner; import br.com.saulofarias.customerapi.model.City; import br.com.saulofarias.customerapi.model.Customer; import br.com.saulofarias.customerapi.util.DateUtil; @RunWith(SpringRunner.class) @DataJpaTest public class CustomerRepositoryTest { @Autowired public TestEntityManager entityManager; @Autowired @Lazy public CustomerRepository repository; @Autowired public CityRepository cityRepository; @Test public void shouldReturnCustomers() throws ParseException { City city = new City(null, "City", "PE"); entityManager.persist(city); Customer customer1 = new Customer(null, "Customer1", 'M', DateUtil.stringToDate("2010-09-09"), 12, city); List<Customer> customers = Arrays.asList(customer1); for (Customer customer : customers) { entityManager.persist(customer); entityManager.flush(); } assertEquals(1, repository.findAll().size()); } @Test public void shouldReturnCustomer() throws ParseException { City city = new City(null, "City", "PE"); entityManager.persist(city); Customer customer = new Customer(null, "Customer1", 'M', DateUtil.stringToDate("2010-09-09"), 12, city); entityManager.persist(customer); entityManager.flush(); Customer customerFound = repository.findById(customer.getId()).get(); assertEquals(customerFound.getId(), customer.getId()); } @Test public void shouldReturnCustomerCreatedWithSucess() throws ParseException { City city = new City(null, "City", "PE"); entityManager.persist(city); Customer customer = new Customer(null, "Customer1", 'M', DateUtil.stringToDate("2010-09-09"), 12, city); Customer newCustomer = this.repository.save(customer); assertNotNull(newCustomer); assertNotNull(newCustomer.getCity()); assertEquals(newCustomer.getId(), customer.getId()); assertEquals(newCustomer.getName(), customer.getName()); } @Test public void shouldPersistAndChangeDataWithSucess() throws ParseException { City city = new City(null, "City", "PE"); entityManager.persist(city); Customer customer = new Customer(null, "Customer1", 'M', DateUtil.stringToDate("2010-09-09"), 12, city); entityManager.persist(customer); entityManager.flush(); String name = "Customer1"; Customer customerFound = repository.findById(customer.getId()).get(); customerFound.setName(name); repository.save(customerFound); customerFound = repository.getOne(customer.getId()); assertNotNull(customerFound); assertNotNull(customerFound.getCity()); assertEquals(customerFound.getName(), name); } @Test public void deleteShouldRemoveData() throws ParseException { City city = new City(null, "City", "PE"); entityManager.persist(city); Customer customer = new Customer(null, "Customer1", 'M', DateUtil.stringToDate("2010-09-09"), 12, city); entityManager.persist(customer); entityManager.flush(); repository.deleteById(customer.getId()); assertFalse(repository.findById(customer.getId()).isPresent()); } }
package com.pointinside.android.app.widget; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Point; import android.graphics.Rect; import android.graphics.drawable.AnimationDrawable; import android.location.Location; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.MapView; //import com.google.android.maps.MyLocationOverlay; import com.google.android.gms.maps.Projection; public class MyGoogleLocation // extends MyLocationOverlay { private static final long ACCURACY_LIMIT = 12L; private final Paint mErrorCirclePaint; private final Rect mLocationBounds; private AnimationDrawable mLocationImage; private int mLocationImageCenterX; private int mLocationImageCenterY; private int mLocationImageHeight; private int mLocationImageWidth; public MyGoogleLocation(Context paramContext, MapView paramMapView) { // super(paramContext, paramMapView); this.mLocationImage = ((AnimationDrawable)paramContext.getResources().getDrawable(2130837681)); this.mErrorCirclePaint = new Paint(); this.mErrorCirclePaint.setARGB(0, 102, 153, 255); this.mErrorCirclePaint.setStrokeWidth(3.0F); this.mErrorCirclePaint.setDither(true); this.mErrorCirclePaint.setAntiAlias(true); int i = paramContext.getResources().getDimensionPixelSize(2131296264); this.mLocationImageWidth = i; this.mLocationImageHeight = i; this.mLocationImageCenterX = (this.mLocationImageWidth / 2); this.mLocationImageCenterY = (this.mLocationImageHeight / 2); int j = -this.mLocationImageCenterX; int k = j + this.mLocationImageWidth; int m = -this.mLocationImageCenterY; int n = m + this.mLocationImageHeight; this.mLocationImage.setBounds(j, m, k, n); this.mLocationBounds = this.mLocationImage.copyBounds(); this.mLocationImage.start(); } private void drawErrorRing(Canvas paramCanvas, Projection paramProjection, float paramFloat, int paramInt1, int paramInt2) { if (paramFloat > 12.0F) { paramCanvas.save(); //float f = paramProjection.metersToEquatorPixels(paramFloat); //float f = paramProjection.metersToEquatorPixels(paramFloat); float f = 12.0F; this.mErrorCirclePaint.setAlpha(50); this.mErrorCirclePaint.setStyle(Paint.Style.FILL); paramCanvas.drawCircle(paramInt1, paramInt2, f, this.mErrorCirclePaint); this.mErrorCirclePaint.setAlpha(150); this.mErrorCirclePaint.setStyle(Paint.Style.STROKE); paramCanvas.drawCircle(paramInt1, paramInt2, f, this.mErrorCirclePaint); paramCanvas.restore(); } } protected void drawMyLocation(Canvas paramCanvas, MapView paramMapView, Location paramLocation, LatLng paramGeoPoint, long paramLong) { //Projection localProjection = paramMapView.getProjection(); Projection localProjection = paramMapView.getMap().getProjection(); Point localPoint = localProjection.toScreenLocation(paramGeoPoint); if ((paramLocation != null) && (paramLocation.hasAccuracy())) { drawErrorRing(paramCanvas, localProjection, paramLocation.getAccuracy(), localPoint.x, localPoint.y); } paramCanvas.save(); AnimationDrawable localAnimationDrawable = this.mLocationImage; int i = localPoint.x + this.mLocationBounds.left; int j = i + this.mLocationImageWidth; int k = localPoint.y + this.mLocationBounds.top; localAnimationDrawable.setBounds(i, k, j, k + this.mLocationImageHeight); localAnimationDrawable.draw(paramCanvas); paramCanvas.restore(); } }
package Interface; /** * Created by YZQ on 2017-04-24. */ public class Login { public void lo(){ System.out.println("dfjdlkjfgkjglkfd"); System.out.println("dlkjfgdgjfkjgkfitutytytuyty"); System.out.println("sfjdkjfk"); } }
package com.es.core; import com.es.core.model.order.Order; import com.es.core.model.order.OrderItem; import com.es.core.model.phone.Phone; import com.es.core.model.phone.Stock; import org.junit.Assert; import java.util.Iterator; import static junit.framework.TestCase.assertEquals; public class TestUtils { public static void assertPhonesEquality( final Phone expected, final Phone actual ) { assertEquals(expected.getId(), actual.getId()); assertEquals(expected.getBrand(), actual.getBrand()); assertEquals(expected.getModel(), actual.getModel()); assertEquals(expected.getPrice(), actual.getPrice()); assertEquals(expected.getDisplaySizeInches(), actual.getDisplaySizeInches()); assertEquals(expected.getWeightGr(), actual.getWeightGr()); assertEquals(expected.getLengthMm(), actual.getLengthMm()); assertEquals(expected.getWidthMm(), actual.getWidthMm()); assertEquals(expected.getHeightMm(), actual.getHeightMm()); assertEquals(expected.getAnnounced(), actual.getAnnounced()); assertEquals(expected.getDeviceType(), actual.getDeviceType()); assertEquals(expected.getOs(), actual.getOs()); assertEquals(expected.getColors(), actual.getColors()); assertEquals(expected.getDisplayResolution(), actual.getDisplayResolution()); assertEquals(expected.getPixelDensity(), actual.getPixelDensity()); assertEquals(expected.getDisplayTechnology(), actual.getDisplayTechnology()); assertEquals(expected.getBackCameraMegapixels(), actual.getBackCameraMegapixels()); assertEquals(expected.getFrontCameraMegapixels(), actual.getFrontCameraMegapixels()); assertEquals(expected.getRamGb(), actual.getRamGb()); assertEquals(expected.getInternalStorageGb(), actual.getInternalStorageGb()); assertEquals(expected.getBatteryCapacityMah(), actual.getBatteryCapacityMah()); assertEquals(expected.getTalkTimeHours(), actual.getTalkTimeHours()); assertEquals(expected.getStandByTimeHours(), actual.getStandByTimeHours()); assertEquals(expected.getBluetooth(), actual.getBluetooth()); assertEquals(expected.getPositioning(), actual.getPositioning()); assertEquals(expected.getImageUrl(), actual.getImageUrl()); assertEquals(expected.getDescription(), actual.getDescription()); } public static void assertStocksEquality(final Stock expected, final Stock actual) { Assert.assertEquals(expected.getPhone().getId(), actual.getPhone().getId()); Assert.assertEquals(expected.getStock(), actual.getStock()); Assert.assertEquals(expected.getReserved(), actual.getReserved()); } public static void assertOrdersEquality(final Order expected, final Order actual) { assertEquals(expected.getId(), actual.getId()); assertEquals(expected.getSubtotal(), actual.getSubtotal()); assertEquals(expected.getDeliveryPrice(), actual.getDeliveryPrice()); assertEquals(expected.getTotalPrice(), actual.getTotalPrice()); assertEquals(expected.getFirstName(), actual.getFirstName()); assertEquals(expected.getLastName(), actual.getLastName()); assertEquals(expected.getDeliveryAddress(), actual.getDeliveryAddress()); assertEquals(expected.getContactPhoneNo(), actual.getContactPhoneNo()); assertEquals(expected.getStatus(), actual.getStatus()); assertEquals(expected.getOrderItems().size(), actual.getOrderItems().size()); Iterator<OrderItem> actualOrderItemsIterator = actual.getOrderItems().iterator(); for (OrderItem expectedOrderItem: expected.getOrderItems()) { OrderItem actualOrderItem = actualOrderItemsIterator.next(); assertPhonesEquality(expectedOrderItem.getPhone(), actualOrderItem.getPhone()); assertEquals(expectedOrderItem.getQuantity(), actualOrderItem.getQuantity()); } } }
package cn.mldn.util.factory; import cn.mldn.util.ResourceUtil; import cn.mldn.util.service.ServiceProxy; public class Factory { private static ResourceUtil DAO_RESOURCE = new ResourceUtil("cn.mldn.resource.dao") ; private static ResourceUtil SERVICE_RESOURCE = new ResourceUtil("cn.mldn.resource.service") ; private Factory() {} // 本类不需要构造方法 @SuppressWarnings("unchecked") public static <T> T getServiceInstance(String serviceKey) { Object proxy = null ; try { Object realObject = Class.forName(SERVICE_RESOURCE.get(serviceKey)).newInstance() ; proxy = new ServiceProxy().bind(realObject) ; } catch (Exception e) { e.printStackTrace(); } return (T) proxy ; } @SuppressWarnings("unchecked") public static <T> T getDAOInstance(String daoKey) { try { return (T) Class.forName(DAO_RESOURCE.get(daoKey)).newInstance() ; } catch (Exception e) { e.printStackTrace(); return null ; } } }
// Team Name: Charity (Kimberly Atienza, Joesph Bingham, Keith Horace, Darren Johnson, Ryan Parker, Alexander Partain, Emiley Smith, Kenton Wilhelm) // Date: 4/25/18 // Assignment: TIMELOCK // compile in linux: "javac TimelockFinal.java" // run in linux: "java TimelockFinal < epoch.txt" // where epoch.txt has the epoch date in it import java.util.*; import java.text.*; import java.security.*; import javax.xml.bind.DatatypeConverter; import java.math.*; import java.io.*; import java.time.*; class TimelockFinal { public static void main(String [] args) { //get the epoch time from txt file Scanner sc = new Scanner(System.in); String line = sc.nextLine(); //initialize date format and different times to keep track of TimeZone.setDefault(TimeZone.getTimeZone("UTC")); SimpleDateFormat dateParser = new SimpleDateFormat("yyyy MM dd HH mm ss"); Calendar systemTime = Calendar.getInstance(); Calendar epochTime = Calendar.getInstance(); //set the epoch time, the system time was automatically set when creating the Calendar objects above try{ dateParser.setTimeZone(TimeZone.getTimeZone("UTC")); epochTime.setTime(dateParser.parse(line)); }catch(ParseException e){ System.out.println("error parsing"); } //set the system seconds to line up with the epoch seconds //zero out the system milliseconds, we don't need them systemTime.set(systemTime.MILLISECOND,0); //getTimeCode takes the two times, finds the difference in seconds, and then spits out the timeCode getTimeCode(systemTime, epochTime); } //hashing function public static String md5Hash(String hash){ try{ MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(hash.getBytes("UTF-8")); return String.format("%032x", new BigInteger(1, md5.digest())); } catch(NoSuchAlgorithmException e){ } catch(UnsupportedEncodingException e){ } return ""; } //grabs and returns the letters from a given hash public static String letterCode(String hash){ int j = 0; String timeCode = ""; for(int i = 0; i < hash.length()-1; i++ ){ if(Character.isAlphabetic(hash.charAt(i))){ timeCode += hash.charAt(i); j++; } if(j == 2){ return timeCode; } } return "ee"; } //grabs and returns the numbers from a given a hash public static String numCode(String hash){ int j = 0; String timeCode = ""; for(int i = 0; i < hash.length()-1; i++ ){ if(!(Character.isAlphabetic(hash.charAt(hash.length()-1-i)))){ timeCode += hash.charAt(hash.length()-1-i); j++; } if(j == 2){ return timeCode; } } return "12"; } public static char middleCharacter(String hash){ String timeCode = ""; return (hash.charAt(hash.length()-1)); } //magic function that gets the Timecode From 2 different times public static void getTimeCode(Calendar systemTime, Calendar epochTime){ //this is used to tell if either time is in DST and adjusts the time accordingly /* if(TimeZone.getTimeZone("US/Central").inDaylightTime(systemTime.getTime())){ System.out.println("systemtrue"); int currentHour = systemTime.get(systemTime.HOUR_OF_DAY); systemTime.set(systemTime.HOUR_OF_DAY, currentHour-1); } */ if(TimeZone.getTimeZone("US/Central").inDaylightTime(epochTime.getTime())){ int currentHour = epochTime.get(epochTime.HOUR_OF_DAY); epochTime.set(epochTime.HOUR_OF_DAY, currentHour+5); } else{ int currentHour = epochTime.get(epochTime.HOUR_OF_DAY); epochTime.set(epochTime.HOUR_OF_DAY, currentHour+6); } //This takes the difference in times and subtracts the modded seconds to remain within the time interval long timeAfterEpochRaw = ((systemTime.getTimeInMillis()-epochTime.getTimeInMillis())/(1000)); long timeAfterEpoch = timeAfterEpochRaw -(timeAfterEpochRaw%60); //double hash the seconds String holyHash = md5Hash(md5Hash(Long.toString(timeAfterEpoch))); String timeCode = ""; //get the code from the hash and print it out timeCode += letterCode(holyHash); timeCode += numCode(holyHash); SimpleDateFormat dateParser = new SimpleDateFormat("yyyy MM dd HH mm ss"); dateParser.setTimeZone(TimeZone.getTimeZone("UTC")); System.out.println(dateParser.format(epochTime.getTime())); System.out.println(dateParser.format(systemTime.getTime())); System.out.println(timeAfterEpoch); System.out.println(holyHash); System.out.println(timeCode); } }
package com.corneliouzbett.mpesasdk.enums; public enum Mode { PROD, TEST }
package com.example.databasefinal; import android.app.Application; import android.arch.lifecycle.AndroidViewModel; import android.arch.lifecycle.LiveData; import android.support.annotation.NonNull; import android.util.Log; public class UpdateProductViewModel extends AndroidViewModel { private String TAG = this.getClass().getSimpleName(); private ProductDao noteDao; private ProductRoomDatabase db; public UpdateProductViewModel(@NonNull Application application) { super(application); Log.i(TAG, "Update ViewModel"); db = ProductRoomDatabase.getDatabase(application); noteDao = db.noteDao(); } public LiveData<Product> getNote(String noteId) { return noteDao.getNote(noteId); } }
package com.mingrisoft; public class MaxMin { public static class Result { private double max; private double min; public Result(double max, double min) { this.max = max; this.min = min; } public double getMax() { return max; } public double getMin() { return min; } } public static Result getResult(double[] array) { double max = Double.MIN_VALUE; double min = Double.MAX_VALUE; for (double i : array) { if (i > max) { max = i; } if (i < min) { min = i; } } return new Result(max, min); } }
package edu.barrons.tran.don; import java.util.ArrayList; import java.util.List; import edu.jenks.dist.barrons.*; public class Sentence extends AbstractSentence{ public static void main(String arg[]) { Sentence what = new Sentence(" s"); System.out.println(what.countWords()); String[] arr = what.getWords(); for(int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } public Sentence() { super(); } public Sentence(String sentence) { super(sentence); //sent = getSentence(); } public int countWords() { ArrayList<Integer> temp = (ArrayList<Integer>) getBlankPositions(); if(getSentence().length() == 0) { return 0; } return temp.size() + 1; } @Override public List<Integer> getBlankPositions() { ArrayList<Integer> temp = new ArrayList<>(); for(int i = 0; i < getSentence().length(); i++) { if(getSentence().substring(i, i+1).equals(" ")) { //System.out.println("wo"); temp.add(i); } } return temp; } @Override public String[] getWords() { ArrayList<Integer> temp = (ArrayList<Integer>) getBlankPositions(); String[] temp2 = new String[countWords()]; if(countWords() == 0) return temp2; if(countWords() == 1) { temp2[0] = getSentence().substring(0, getSentence().length()); return temp2; } temp2[0] = getSentence().substring(0, temp.get(0)); System.out.println(temp.size()); for(int i = 1; i < temp.size(); i++) { System.out.println("woo"); temp2[i] = getSentence().substring(temp.get(i - 1) + 1, temp.get(i)); } temp2[temp2.length - 1] = getSentence().substring(temp.get(countWords() - 2) + 1, getSentence().length()); return temp2; } }
package com.sda.company.controller; import com.sda.company.components.CustomFakerCompany; import com.sda.company.model.Company; import com.sda.company.service.CompanyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @ControllerAdvice @RequestMapping("/api/v1/companies") public class CompanyController { private final CompanyService companyService; private final CustomFakerCompany customFakerCompany; @Autowired public CompanyController(CompanyService companyService, CustomFakerCompany customFakerCompany) { this.companyService = companyService; this.customFakerCompany = customFakerCompany; } @PostMapping("/create") public ResponseEntity<Company> create(@RequestBody Company company) { return ResponseEntity.ok(companyService.create(company)); } @CrossOrigin(origins = "http://localhost:4200") @GetMapping("/getAll") public ResponseEntity<List<Company>> getAll() { return ResponseEntity.ok(companyService.getAll()); } @GetMapping("/getAllPaginated") public ResponseEntity<List<Company>> getAllPaginated( @RequestParam(defaultValue = "0") Integer pageNumber, @RequestParam(defaultValue = "50") Integer pageSize, @RequestParam(defaultValue = "name") String shortBy) { return ResponseEntity.ok(companyService.getAllPaginated(pageNumber, pageSize, shortBy)); } @GetMapping("/findByName") public ResponseEntity<Company> findByName(@RequestParam String name) { return ResponseEntity.ok(companyService.findByName(name)); } @GetMapping("/populate") public ResponseEntity<String> populate() { return ResponseEntity.ok(companyService.populate(customFakerCompany.createDummyCompanyList())); } @DeleteMapping("/deleteById") void deleteById(@RequestParam Integer id) { companyService.deleteCompanyById(id); } @DeleteMapping("/deleteByRegistrationNumber") void deleteByRegistrationNumber(@RequestParam String registrationNumber) { companyService.deleteByRegistrationNumber(registrationNumber); } }
package byow.Core; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import edu.princeton.cs.algs4.Stopwatch; public class AStarSolver<Vertex> implements ShortestPathsSolver<Vertex> { private ArrayHeapMinPQ<Vertex> fringe; // private ArrayList<Double> distTo; // private ArrayList<Integer> edgeTo; // private HashMap<Vertex, Integer> vertexToIndex; //add to this when disTo/edgeTo has added private HashMap<Vertex, Double> distTo; private HashMap<Vertex, Vertex> edgeTo; private SolverOutcome result; private List<Vertex> solution; private double totalWeight; private int dequeueCount; //done private double time; //done /** * Constructor which finds the solution, computing everything * necessary for all other methods to return their results in * constant time. Note that timeout passed in is in seconds. * */ public AStarSolver(AStarGraph<Vertex> input, Vertex start, Vertex end, double timeout) { Stopwatch swOuter = new Stopwatch(); this.fringe = new ArrayHeapMinPQ<>(); //priority queue fringe with start vertex only this.fringe.add(start, input.estimatedDistanceToGoal(start, end)); this.distTo = new HashMap<>(); this.distTo.put(start, 0.0); this.edgeTo = new HashMap<>(); this.edgeTo.put(start, null); this.solution = new ArrayList<>(); //A list of vertices corresponding to a solution. this.totalWeight = 0.0; this.dequeueCount = 0; this.result = solveAStar(input, start, end, timeout); //run heavy duty constructor helper. this.time = swOuter.elapsedTime(); } //helper for the constructor. Returns result for termination purposes private SolverOutcome solveAStar(AStarGraph<Vertex> input, Vertex start, Vertex end, double timeout) { Stopwatch sw = new Stopwatch(); Vertex currVertex = start; while (!currVertex.equals(end)) { //DO NOT USE currVertex != end; if (sw.elapsedTime() > timeout) { this.solution.clear(); this.totalWeight = 0; return SolverOutcome.TIMEOUT; } currVertex = this.fringe.removeSmallest(); this.dequeueCount += 1; List<WeightedEdge<Vertex>> neighborEdges = input.neighbors(currVertex); //relaxing process for (WeightedEdge<Vertex> e : neighborEdges) { if (distTo.containsKey(e.to())) { //existing marked vertex double h = input.estimatedDistanceToGoal(e.to(), end); double pqOldEstimate = distTo.get(e.to()) + h; //fringe.priority(e.to()) double pqNewEstimate = distTo.get(currVertex) + e.weight() + h; if (pqNewEstimate < pqOldEstimate) { distTo.put(e.to(), distTo.get(currVertex) + e.weight()); edgeTo.put(e.to(), currVertex); this.fringe.changePriority(e.to(), pqNewEstimate); } } else { //newly visited vertex distTo.put(e.to(), distTo.get(currVertex) + e.weight()); edgeTo.put(e.to(), currVertex); this.fringe.add(e.to(), distTo.get(e.to()) + input.estimatedDistanceToGoal(e.to(), end)); } } if (this.fringe.size() != 0) { currVertex = this.fringe.getSmallest(); } else { this.solution.clear(); this.totalWeight = 0; return SolverOutcome.UNSOLVABLE; } } //answers to return solutionHelper(start, end); this.totalWeight = distTo.get(end); return SolverOutcome.SOLVED; } //helper for finding solution private void solutionHelper(Vertex start, Vertex end) { Vertex curr = end; while (curr != null) { this.solution.add(curr); curr = edgeTo.get(curr); } List<Vertex> reverseTemp = new ArrayList<>(); for (int i = 0; i < this.solution.size(); i++) { reverseTemp.add(this.solution.get(this.solution.size() - 1 - i)); } this.solution = reverseTemp; } /** Returns one of SolverOutcome.SOLVED, SolverOutcome.TIMEOUT, * or SolverOutcome.UNSOLVABLE. Should be SOLVED if the AStarSolver * was able to complete all work in the time given. UNSOLVABLE if * the priority queue became empty. TIMEOUT if the solver ran out * of time. You should check to see if you have run out of time * every time you dequeue. Constant time. * */ @Override public SolverOutcome outcome() { return result; } /** A list of vertices corresponding to a solution. * Should be empty if result was TIMEOUT or UNSOLVABLE. * Constant time. * */ @Override public List<Vertex> solution() { return solution; } /** The total weight of the given solution, taking into * account edge weights. Should be 0 if result was * TIMEOUT or UNSOLVABLE. Constant time. * */ @Override public double solutionWeight() { return totalWeight; } /** The total number of priority queue dequeue operations. * Constant time. * */ @Override public int numStatesExplored() { return dequeueCount; } /** The total time spent in seconds by the constructor. * Constant time. * */ @Override public double explorationTime() { return time; } }
package com.dzf.crm.workbench.service.impl; import com.dzf.crm.settings.dao.UserDao; import com.dzf.crm.settings.domain.User; import com.dzf.crm.vo.PaginationVo; import com.dzf.crm.workbench.dao.ActivityDao; import com.dzf.crm.workbench.dao.ActivityRemarkDao; import com.dzf.crm.workbench.domain.Activity; import com.dzf.crm.workbench.domain.ActivityRemark; import com.dzf.crm.workbench.service.ActivityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class ActivityServiceImpl implements ActivityService { @Autowired private ActivityDao activityDao; @Autowired private ActivityRemarkDao activityRemarkDao; @Autowired private UserDao userDao; @Override public boolean save(Activity at) { boolean flag=true; int count=activityDao.save(at); if(count!=1){ flag=false; } return flag; } @Override public PaginationVo<Activity> pageList(Map<String, Object> map) { // 取total int total=activityDao.getTotalByCondition(map); // 取datalist List<Activity> dataList= activityDao.getActivityByCondition(map); // 封装到vo PaginationVo<Activity> vo=new PaginationVo<>(); vo.setTotal(total); vo.setDataList(dataList); System.out.println("==========================total"+total); for(Activity i:dataList) System.out.println("======================datalist"+i); // 将vo返回 return vo; } @Override public boolean delete(String[] ids) { System.out.println("进入到删除操作的业务层"); boolean flag=true; // 查询出需要删除的备注的数量 int Count1=activityRemarkDao.getCountByAids(ids); System.out.println(Count1); // 删除备注,返回收到影响的条数(实际删除的数量) int Count2=activityRemarkDao.deleteByAids(ids); if(Count1!=Count2){ flag=false; } // 删除市场活动 int Count3=activityDao.delete(ids); if(Count3!=ids.length){ flag=false; } return flag; } @Override public Map<String, Object> getUserListAndActivity(String id) { Map<String,Object> map=new HashMap<>(); // 取ulist List<User> uList=userDao.getUserList(); // 取a Activity a=activityDao.getById(id); // 打包到map之中 map.put("uList",uList); map.put("a",a); return map; } @Override public boolean update(Activity at) { boolean flag=true; int count=activityDao.update(at); if(count!=1){ flag=false; } return flag; } @Override public Activity detail(String id) { Activity a=activityDao.detail(id); return a; } @Override public List<ActivityRemark> getRemarkListByAid(String id) { List<ActivityRemark> arList=activityRemarkDao.getRemarkListByAid(id); return arList; } @Override public boolean deleteRemark(String id) { boolean flag=true; int Count=activityRemarkDao.deleteRemark(id); if(Count!=1){ flag=false; } return flag; } @Override public boolean saveRemark(ActivityRemark ar) { Boolean flag=true; int Count=activityRemarkDao.saveRemark(ar); if(Count!=1){ flag=false; } return flag; } @Override public boolean updateRemark(ActivityRemark ar) { Boolean flag=true; int Count=activityRemarkDao.updateRemark(ar); if(Count!=1){ flag=false; } return flag; } @Override public List<Activity> getActivityListByClueId(String clueId) { List<Activity> aList=activityDao.getActivityListByClueId(clueId); return aList; } @Override public List<Activity> getActivityListByNameAndNotByClueId(Map<String, Object> map) { List<Activity> aList=activityDao.getActivityListByNameAndNotByClueId(map); return aList; } @Override public List<Activity> getActivityListByName(String aname) { List<Activity> aList=activityDao.getActivityListByName(aname); return aList; } }
import java.io.*; import java.util.*; class stringconcat { public static void main(String[] args) { Scanner kb=new Scanner(System.in); String str=kb.next(); String str1=kb.next(); if(str.length()<1001&&str1.length()<1001) System.out.println(str+str1); } }
package ru.timxmur.test.tochka.service; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ru.timxmur.test.tochka.domain.*; import ru.timxmur.test.tochka.repository.RuleRepository; import ru.timxmur.test.tochka.repository.SourceRepository; import java.util.List; import java.util.Optional; @Service @RequiredArgsConstructor public class NewsSourceService implements ISourceService { private final SourceRepository sourceRepository; private final RuleRepository ruleRepository; @Override public void delete(Long id) { sourceRepository.delete(id); } @Override public List<NewsSource> getAllSources() { return sourceRepository.findAll(); } @Override public void update(NewsSourceForm form, Optional<Long> id) { NewsSource newsSource = new NewsSource(); newsSource.setName(form.getName()); newsSource.setUri(form.getUri()); newsSource.setType((form.getType())); id.ifPresent(newsSource::setSourceId); Rule rule = new Rule(); if (newsSource.getType().equals(NewsSourceTypeEnum.RSS)) { if (form.getTopElement().equals("")) rule.setTopElement("item"); else rule.setTopElement(form.getTopElement()); if (form.getContentRule().equals("")) rule.setContentRule("description"); else rule.setContentRule(form.getContentRule()); if (form.getUrlRule().equals("")) rule.setUrlRule("link"); else rule.setUrlRule(form.getUrlRule()); if (form.getTitleRule().equals("")) rule.setTitleRule("title"); else rule.setTitleRule(form.getTitleRule()); rule.setContentType(form.getContentType()); rule.setTitleType(form.getTitleType()); rule.setTopElementType(form.getTopElementType()); rule.setUrlType(form.getUrlType()); } else { rule.setContentRule(form.getContentRule()); rule.setContentType(form.getContentType()); rule.setTitleRule(form.getTitleRule()); rule.setTitleType(form.getTitleType()); rule.setTopElement(form.getTopElement()); rule.setTopElementType(form.getTopElementType()); rule.setUrlRule(form.getUrlRule()); rule.setUrlType(form.getUrlType()); } rule.setSource(newsSource); newsSource.setRule(rule); save(newsSource); } @Override public void save(NewsSource source) { sourceRepository.findOneBySourceId(source.getSourceId()).ifPresent(n -> { source.setSourceId(n.getSourceId()); source.getRule().setRuleId(n.getRule().getRuleId()); }); sourceRepository.saveAndFlush(source); } @Override public Optional<NewsSource> getById(Long id) { return sourceRepository.findOneBySourceId(id); } }
package com.ajhlp.app.integrationTools.util; /** * 操作结果key * @author ajhlp * */ public class OperResultKey { public static final String OPER_SUCCESS_KEY = "success"; public static final String OPER_RESULT_MSG_KEY = "msg"; public static final String QUERY_RESULT_COUNT_KEY = "total"; public static final String QUERY_RESULT_DBTYPES_KEY = "dbtypes"; public static final String QUERY_RESULT_DBCONNS_KEY = "dbconns"; public static final String QUERY_RESULT_DBSQLTEMPLATES_KEY = "temps"; public static final String QUERY_RESULT_SERVERS_KEY = "servers"; public static final String QUERY_RESULT_TAGS_KEY = "tags"; public static final String QUERY_RESULT_DBTYPE_KEY = "type"; public static final String QUERY_RESULT_DBCONN_KEY = "conn"; public static final String QUERY_RESULT_SERVER_KEY = "server"; public static final String QUERY_RESULT_DBSQLTEMPLATE_KEY = "temp"; public static final String QUERY_CONDITION_KEY = "condition"; public static final String PAGEBAR = "pagebar"; public static final String PAGEBAR_CURRENT = "pagecurrent"; public static final String PAGEBAR_TOTAL = "pagetotal"; }
package com.lenovohit.bdrp.org.dao; import java.util.List; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.Assert; import com.lenovohit.bdrp.org.model.Org; import com.lenovohit.core.IcoreApplication; import com.lenovohit.core.dao.GenericDao; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes=IcoreApplication.class) @WebIntegrationTest @FixMethodOrder(value=MethodSorters.NAME_ASCENDING) public class OrgDaoTest{ @Autowired private GenericDao<Org, String> orgDao; @Test public void testSave(){ Org o = new Org(); o.setId("8a81e4aa4ed82de0014ed82e98180000"); o.setName("update"); o.setEnName("aaa"); this.orgDao.save(o); } @Test public void testGet(){ String id = "8a81e4aa4ed82de0014ed82e98180000"; Org o = this.orgDao.get(id); Assert.notNull(o, "is null"); } @Test public void testFindAll(){ List<Org> lst = this.orgDao.findAll(); for(Org o : lst){ System.out.println(o.getId()); } } }
import java.io.*; public class Second implements Serializable { int id; String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static void main(String[] args) { try { ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("/home/ankit/Desktop/myobject.txt")); Second obj = new Second(); obj.setId(35); obj.setName("ankit"); objectOutputStream.writeObject(obj); System.out.println("object state is stored"); objectOutputStream.close(); } catch (IOException ex){ System.out.println(ex); } Second obj2=null; try { ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("/home/ankit/Desktop/myobject.txt")); obj2=(Second) objectInputStream.readObject(); System.out.println("object state is retrieved"); System.out.println(obj2.getName()+" "+obj2.getId()); objectInputStream.close(); } catch (IOException ex1){ System.out.println(ex1); } catch (ClassNotFoundException ex2){ System.out.println(ex2); } } }
package com.madrun.springmongo.model; import java.util.List; import org.springframework.data.mongodb.core.mapping.Document; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @Document @NoArgsConstructor public class SocialMediaInfo { List<SocialMediaAccount> socialMediaAccounts; public SocialMediaInfo() { super(); } public SocialMediaInfo(List<SocialMediaAccount> socialMediaAccounts) { super(); this.socialMediaAccounts = socialMediaAccounts; } public List<SocialMediaAccount> getSocialMediaAccounts() { return socialMediaAccounts; } public void setSocialMediaAccounts(List<SocialMediaAccount> socialMediaAccounts) { this.socialMediaAccounts = socialMediaAccounts; } }
package alien4cloud.rest.deployment; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.Authorization; import java.util.Map; import javax.inject.Inject; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import alien4cloud.application.ApplicationEnvironmentService; import alien4cloud.application.ApplicationService; import alien4cloud.audit.annotation.Audit; import alien4cloud.deployment.DeploymentNodeSubstitutionService; import alien4cloud.deployment.DeploymentTopologyService; import alien4cloud.deployment.DeploymentTopologyValidationService; import alien4cloud.deployment.matching.services.location.TopologyLocationUtils; import alien4cloud.deployment.model.DeploymentConfiguration; import alien4cloud.model.application.Application; import alien4cloud.model.application.ApplicationEnvironment; import alien4cloud.model.deployment.DeploymentTopology; import alien4cloud.model.orchestrators.locations.LocationResourceTemplate; import alien4cloud.orchestrators.locations.services.LocationResourceService; import alien4cloud.paas.exception.OrchestratorDisabledException; import alien4cloud.rest.application.model.SetLocationPoliciesRequest; import alien4cloud.rest.application.model.UpdateDeploymentTopologyRequest; import alien4cloud.rest.model.RestErrorBuilder; import alien4cloud.rest.model.RestErrorCode; import alien4cloud.rest.model.RestResponse; import alien4cloud.rest.model.RestResponseBuilder; import alien4cloud.rest.topology.UpdatePropertyRequest; import alien4cloud.security.AuthorizationUtil; import alien4cloud.security.model.ApplicationEnvironmentRole; import alien4cloud.security.model.ApplicationRole; import alien4cloud.topology.TopologyDTO; import alien4cloud.topology.TopologyService; import alien4cloud.tosca.properties.constraints.ConstraintUtil; import alien4cloud.tosca.properties.constraints.exception.ConstraintFunctionalException; import alien4cloud.tosca.properties.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import alien4cloud.tosca.properties.constraints.exception.ConstraintViolationException; import alien4cloud.utils.ReflectionUtil; import alien4cloud.utils.RestConstraintValidator; @RestController @RequestMapping("/rest/applications/{appId}/environments/{environmentId}/deployment-topology") @Api(value = "", description = "Prepare a topology to be deployed on a specific environment (location matching, node matching and inputs configuration).") public class DeploymentTopologyController { @Inject private DeploymentTopologyService deploymentTopologyService; @Inject private ApplicationService applicationService; @Inject private ApplicationEnvironmentService appEnvironmentService; @Inject private DeploymentNodeSubstitutionService deploymentNodeSubstitutionService; @Inject private LocationResourceService locationResourceService; @Inject private TopologyService topologyService; @Inject private DeploymentTopologyValidationService deploymentTopologyValidationService; /** * Get the deployment topology of an application given an environment * * @param appId application Id * @param environmentId environment Id * @return the deployment topology DTO */ @ApiOperation(value = "Get the deployment topology of an application given an environment.", notes = "Application role required [ APPLICATION_MANAGER | APPLICATION_DEVOPS ] and Application environment role required [ DEPLOYMENT_MANAGER ]") @RequestMapping(value = "", method = RequestMethod.GET) @PreAuthorize("isAuthenticated()") public RestResponse<DeploymentTopologyDTO> getDeploymentTopology(@PathVariable String appId, @PathVariable String environmentId) { checkAuthorizations(appId, environmentId); DeploymentConfiguration deploymentConfiguration = deploymentTopologyService.getDeploymentConfiguration(environmentId); DeploymentTopologyDTO dto = buildDeploymentTopologyDTO(deploymentConfiguration); return RestResponseBuilder.<DeploymentTopologyDTO> builder().data(dto).build(); } /** * Update node substitution. * * @param appId id of the application. * @param environmentId id of the environment. * @return response containing the available substitutions. */ @ApiOperation(value = "Substitute a specific node by the location resource template in the topology of an application given an environment.", notes = "Application role required [ APPLICATION_MANAGER | APPLICATION_DEVOPS ] and Application environment role required [ DEPLOYMENT_MANAGER ]") @RequestMapping(value = "/substitutions/{nodeId}", method = RequestMethod.POST) @PreAuthorize("isAuthenticated()") @Audit public RestResponse<DeploymentTopologyDTO> updateSubstitution(@PathVariable String appId, @PathVariable String environmentId, @PathVariable String nodeId, @RequestParam String locationResourceTemplateId) { checkAuthorizations(appId, environmentId); DeploymentConfiguration deploymentConfiguration = deploymentTopologyService.updateSubstitution(environmentId, nodeId, locationResourceTemplateId); return RestResponseBuilder.<DeploymentTopologyDTO> builder().data(buildDeploymentTopologyDTO(deploymentConfiguration)).build(); } @ApiOperation(value = "Update substitution's property.", authorizations = { @Authorization("ADMIN") }) @RequestMapping(value = "/substitutions/{nodeId}/properties", method = RequestMethod.POST) @PreAuthorize("isAuthenticated()") @Audit public RestResponse<?> updateSubstitutionProperty(@PathVariable String appId, @PathVariable String environmentId, @PathVariable String nodeId, @RequestBody UpdatePropertyRequest updateRequest) { checkAuthorizations(appId, environmentId); try { deploymentTopologyService.updateProperty(environmentId, nodeId, updateRequest.getPropertyName(), updateRequest.getPropertyValue()); return RestResponseBuilder.<DeploymentTopologyDTO> builder() .data(buildDeploymentTopologyDTO(deploymentTopologyService.getDeploymentConfiguration(environmentId))).build(); } catch (ConstraintFunctionalException e) { return RestConstraintValidator.fromException(e, updateRequest.getPropertyName(), updateRequest.getPropertyValue()); } } @ApiOperation(value = "Update substitution's capability property.", authorizations = { @Authorization("ADMIN") }) @RequestMapping(value = "/substitutions/{nodeId}/capabilities/{capabilityName}/properties", method = RequestMethod.POST) @PreAuthorize("isAuthenticated()") @Audit public RestResponse<?> updateSubstitutionCapabilityProperty(@PathVariable String appId, @PathVariable String environmentId, @PathVariable String nodeId, @PathVariable String capabilityName, @RequestBody UpdatePropertyRequest updateRequest) { checkAuthorizations(appId, environmentId); try { deploymentTopologyService.updateCapabilityProperty(environmentId, nodeId, capabilityName, updateRequest.getPropertyName(), updateRequest.getPropertyValue()); return RestResponseBuilder.<DeploymentTopologyDTO> builder() .data(buildDeploymentTopologyDTO(deploymentTopologyService.getDeploymentConfiguration(environmentId))).build(); } catch (ConstraintFunctionalException e) { return RestConstraintValidator.fromException(e, updateRequest.getPropertyName(), updateRequest.getPropertyValue()); } } /** * Set location policies for a deployment. Creates if not yet the {@link DeploymentTopology} object linked to this deployment * * @param appId application Id * @param request {@link SetLocationPoliciesRequest} object: location policies * @return */ @ApiOperation(value = "Set location policies for a deployment. Creates if not yet the {@link DeploymentTopology} object linked to this deployment.", notes = "Application role required [ APPLICATION_MANAGER | APPLICATION_DEVOPS ] and Application environment role required [ DEPLOYMENT_MANAGER ]") @RequestMapping(value = "/location-policies", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) @Audit @PreAuthorize("isAuthenticated()") public RestResponse<DeploymentTopologyDTO> setLocationPolicies(@PathVariable String appId, @PathVariable String environmentId, @RequestBody SetLocationPoliciesRequest request) { checkAuthorizations(appId, environmentId); DeploymentConfiguration deploymentConfiguration = deploymentTopologyService.setLocationPolicies(environmentId, request.getOrchestratorId(), request.getGroupsToLocations()); return RestResponseBuilder.<DeploymentTopologyDTO> builder().data(buildDeploymentTopologyDTO(deploymentConfiguration)).build(); } /** * * * @param appId The application id * @param environmentId Id of the environment we want to update * @param updateRequest an {@link UpdateDeploymentTopologyRequest} object * @return a {@link RestResponse} with:<br> * the {@link DeploymentTopologyDTO} if everithing went well, the <br> * Error if not * * @throws OrchestratorDisabledException */ @ApiOperation(value = "Updates by merging the given request into the given application's deployment topology.", notes = "Application role required [ APPLICATION_MANAGER | APPLICATION_DEVOPS ] and Application environment role required [ DEPLOYMENT_MANAGER ]") @RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize("isAuthenticated()") @Audit public RestResponse<?> updateDeploymentSetup(@PathVariable String appId, @PathVariable String environmentId, @RequestBody UpdateDeploymentTopologyRequest updateRequest) throws OrchestratorDisabledException { // check rights on related environment checkAuthorizations(appId, environmentId); DeploymentConfiguration deploymentConfiguration = deploymentTopologyService.getDeploymentConfiguration(environmentId); DeploymentTopology deploymentTopology = deploymentConfiguration.getDeploymentTopology(); ReflectionUtil.mergeObject(updateRequest, deploymentTopology); // If someone modified the input properties, must validate them try { deploymentTopologyValidationService.checkPropertiesContraints(deploymentTopology); } catch (ConstraintViolationException e) { return RestResponseBuilder.<ConstraintUtil.ConstraintInformation> builder().data(e.getConstraintInformation()) .error(RestErrorBuilder.builder(RestErrorCode.PROPERTY_CONSTRAINT_VIOLATION_ERROR).message(e.getMessage()).build()).build(); } catch (ConstraintValueDoNotMatchPropertyTypeException e) { return RestResponseBuilder.<ConstraintUtil.ConstraintInformation> builder().data(e.getConstraintInformation()) .error(RestErrorBuilder.builder(RestErrorCode.PROPERTY_TYPE_VIOLATION_ERROR).message(e.getMessage()).build()).build(); } deploymentTopologyService.updateDeploymentTopologyInputsAndSave(deploymentTopology); return RestResponseBuilder.<DeploymentTopologyDTO> builder().data(buildDeploymentTopologyDTO(deploymentConfiguration)).build(); } /** * Security check on application and environment * * @param appId application's id * @param environmentId environment's id */ private void checkAuthorizations(String appId, String environmentId) { Application application = applicationService.getOrFail(appId); ApplicationEnvironment environment = appEnvironmentService.getOrFail(environmentId); // // Security check user must be authorized to deploy the environment (or be application manager) if (!AuthorizationUtil.hasAuthorizationForApplication(application, ApplicationRole.APPLICATION_MANAGER)) { AuthorizationUtil.checkAuthorizationForEnvironment(environment, ApplicationEnvironmentRole.DEPLOYMENT_MANAGER); } } private DeploymentTopologyDTO buildDeploymentTopologyDTO(DeploymentConfiguration deploymentConfiguration) { DeploymentTopology deploymentTopology = deploymentConfiguration.getDeploymentTopology(); TopologyDTO topologyDTO = topologyService.buildTopologyDTO(deploymentTopology); DeploymentTopologyDTO deploymentTopologyDTO = new DeploymentTopologyDTO(); ReflectionUtil.mergeObject(topologyDTO, deploymentTopologyDTO); Map<String, String> locationIds = TopologyLocationUtils.getLocationIds(deploymentTopology); for (Map.Entry<String, String> locationIdsEntry : locationIds.entrySet()) { deploymentTopologyDTO.getLocationPolicies().put(locationIdsEntry.getKey(), locationIdsEntry.getValue()); } deploymentTopologyDTO.setAvailableSubstitutions(deploymentConfiguration.getAvailableSubstitutions()); deploymentTopologyDTO.setValidation(deploymentTopologyValidationService.validateDeploymentTopology(deploymentTopology)); Map<String, LocationResourceTemplate> templates = locationResourceService.getMultiple(deploymentTopology.getSubstitutedNodes().values()); deploymentTopologyDTO.setLocationResourceTemplates(templates); return deploymentTopologyDTO; } }
package com.binfan.davantitest.model; import com.binfan.davantitest.model.asset.Page; import retrofit.http.GET; /** * Created by Bin on 28/3/2016. * An interface for retrofit to request and parse data */ public interface IModelRestService { /** * for retrofit to request data * @return Page include a category title and a list of events */ @GET("/") public Page getCurPageData(); }
package com.dadastory; import java.io.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @Author:chenda * @Date:2021/7/20 15:07 */ public class Maven_Tools { private static final Properties properties = new Properties(); static { try { File file = new File("config.properties"); if (file.exists()) { properties.load(new FileInputStream(file)); System.out.println("您的配置文件如下:"); String JavaWorkspacePath = properties.getProperty("JavaWorkspacePath"); String MavenRepositoryPath = properties.getProperty("MavenRepositoryPath"); if (JavaWorkspacePath != null && MavenRepositoryPath != null) { System.out.println("Java项目工作路径为:" + JavaWorkspacePath); System.out.println("Maven仓库路径地址为:" + MavenRepositoryPath); } else { changeProperties(); } System.out.println(""); } else { System.out.println("配置文件不存在!"); System.exit(1); } } catch (IOException e) { e.printStackTrace(); } } private static final Scanner sc = new Scanner(System.in); public static void main(String[] args) { while (true) { System.out.println("欢迎使用Idea清理小工具"); System.out.println("###################################"); System.out.println("-----------------------------------"); System.out.println("1.清除Maven仓库未成功下载的POM依赖文件 |"); System.out.println("2.清除Idea项目文件下所有的编译缓存 |"); System.out.println("3.修改配置文件路径 |"); System.out.println("4.退出 |"); System.out.println("-----------------------------------"); System.out.println("请选择你需要的功能项:"); String fuc = sc.nextLine(); if (!isDigit2(fuc)) System.out.println("您输入的格式有误,请重新输入!"); int num = Integer.parseInt(fuc); switch (num) { case 1: cleanMavenPom(); break; case 2: cleanMyProject(); break; case 3: try { changeProperties(); } catch (IOException e) { e.printStackTrace(); } break; case 4: System.exit(0); } } } //修改配置路径 private static void changeProperties() throws IOException { System.out.println("请输入新的项目工作空间的绝对路径路径:(例如:D:\\Java_workspace)"); String JavaWorkspacePath = sc.nextLine(); System.out.println("请输入新的Maven仓库文件夹的绝对路径路径:(例如:D:\\Maven\\Repository)"); String MavenRepositoryPath = sc.nextLine(); File file1 = new File(JavaWorkspacePath); File file2 = new File(MavenRepositoryPath); if (!file1.exists()) System.out.println("您输入的" + JavaWorkspacePath + "不存在!"); if (!file2.exists()) System.out.println("您输入的" + MavenRepositoryPath + "不存在!"); if (file1.exists() && file2.exists()) { properties.setProperty("JavaWorkspacePath", JavaWorkspacePath); properties.setProperty("MavenRepositoryPath", MavenRepositoryPath); File file = new File("config.properties"); FileWriter fileWriter = new FileWriter(file.getAbsolutePath()); properties.store(fileWriter, ""); System.out.println("配置更新成功!"); fileWriter.close(); } } //清除项目下面的所有target编译文件 private static void cleanMyProject() { String path = properties.getProperty("JavaWorkspacePath"); File destDir = new File(path); if (!destDir.exists()) { System.out.println("有效路径不存在,请重新配置!"); return; } List<File> list = new ArrayList<>(); findAllTarget(destDir, list); System.out.println("从您的项目中找到了以下的target文件夹:"); list.forEach(System.out::println); System.out.println("您确认是否删除上述文件?(y/n)"); String confirm = sc.nextLine(); if (confirm.equalsIgnoreCase("y")) { for (File file : list) { deleteFile(file); System.out.println(file.toString() + "清理成功!"); } } } //清除所有pom文件 private static void cleanMavenPom() { String path = properties.getProperty("MavenRepositoryPath"); File destDir = new File(path); if (!destDir.exists()) { System.out.println("有效路径不存在,请重新配置路径!"); return; } List<File> list = new ArrayList<>(); findAllPom(destDir, list); System.out.println("从仓库中找到了以下文件:"); list.forEach(System.out::println); System.out.println("您确认是否删除文件?(y/n)"); String confirm = sc.nextLine(); if ("y".equalsIgnoreCase(confirm)) { for (File file : list) { File parentFile = file.getParentFile(); file.delete(); parentFile.delete(); System.out.println(file.toString() + "清理成功!"); } } } //查询所有pom文件,并添加到集合 private static void findAllPom(File destDir, List<File> list) { File[] files = destDir.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) findAllPom(file, list); if (file.isFile()) { if (file.toString().contains("lastUpdated")) { list.add(file); } } } } } //查询所有target文件夹,并添加到集合 private static void findAllTarget(File destDir, List<File> list) { if (destDir.isFile()) return; if (destDir.isDirectory() && destDir.toString().endsWith("target")) list.add(destDir); File[] files = destDir.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) findAllTarget(file, list); } } } // 判断一个字符串是否都为数字 private static boolean isDigit2(String strNum) { Pattern pattern = Pattern.compile("[0-9]{1,}"); Matcher matcher = pattern.matcher((CharSequence) strNum); return matcher.matches(); } //递归删除文件夹 private static void deleteFile(File desDir) { File[] files = desDir.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) deleteFile(file); if (file.isFile()) file.delete(); } } desDir.delete(); } }
package caris.framework.tokens; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import com.vdurmont.emoji.Emoji; import sx.blah.discord.api.IDiscordClient; import sx.blah.discord.api.IShard; import sx.blah.discord.api.internal.json.objects.EmbedObject; import sx.blah.discord.handle.impl.obj.ReactionEmoji; import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IEmbed; import sx.blah.discord.handle.obj.IEmoji; import sx.blah.discord.handle.obj.IGuild; import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.handle.obj.IReaction; import sx.blah.discord.handle.obj.IRole; import sx.blah.discord.handle.obj.IUser; import sx.blah.discord.util.MessageTokenizer; public class RedirectedMessage implements IMessage { protected IMessage message; protected IChannel redirect; protected String content; public RedirectedMessage(IMessage message, IChannel redirect, String content) { this.message = message; this.redirect = redirect; this.content = content; } @Override public IDiscordClient getClient() { return message.getClient(); } @Override public IShard getShard() { return message.getShard(); } @Override public IMessage copy() { return message.copy(); } @Override public long getLongID() { return message.getLongID(); } @Override public String getContent() { return content; } @Override public IChannel getChannel() { return redirect; } @Override public IUser getAuthor() { return message.getAuthor(); } @Override public LocalDateTime getTimestamp() { return message.getTimestamp(); } @Override public List<IUser> getMentions() { return message.getMentions(); } @Override public List<IRole> getRoleMentions() { return message.getRoleMentions(); } @Override public List<IChannel> getChannelMentions() { return message.getChannelMentions(); } @Override public List<Attachment> getAttachments() { return message.getAttachments(); } @Override public List<IEmbed> getEmbeds() { return message.getEmbeds(); } @Override public IMessage reply(String content) { return message.reply(content); } @Override public IMessage reply(String content, EmbedObject embed) { return message.reply(content, embed); } @Override public IMessage edit(String content) { return message.edit(content); } @Override public IMessage edit(String content, EmbedObject embed) { return message.edit(content, embed); } @Override public IMessage edit(EmbedObject embed) { return message.edit(embed); } @Override public boolean mentionsEveryone() { return message.mentionsEveryone(); } @Override public boolean mentionsHere() { return message.mentionsHere(); } @Override public void delete() { message.delete(); } @Override public Optional<LocalDateTime> getEditedTimestamp() { return message.getEditedTimestamp(); } @Override public boolean isPinned() { return message.isPinned(); } @Override public IGuild getGuild() { return message.getGuild(); } @Override public String getFormattedContent() { return message.getFormattedContent(); } @Override public List<IReaction> getReactions() { return message.getReactions(); } @Override public IReaction getReactionByIEmoji(IEmoji emoji) { return message.getReactionByEmoji(emoji); } @Override public IReaction getReactionByEmoji(IEmoji emoji) { return message.getReactionByEmoji(emoji); } @Override public IReaction getReactionByID(long id) { return message.getReactionByID(id); } @Override public IReaction getReactionByUnicode(Emoji unicode) { return message.getReactionByUnicode(unicode); } @Override public IReaction getReactionByUnicode(String unicode) { return message.getReactionByUnicode(unicode); } @Override public IReaction getReactionByEmoji(ReactionEmoji emoji) { return message.getReactionByEmoji(emoji); } @Override public void addReaction(IReaction reaction) { message.addReaction(reaction); } @Override public void addReaction(IEmoji emoji) { message.addReaction(emoji); } @Override public void addReaction(Emoji emoji) { message.addReaction(emoji); } @SuppressWarnings("deprecation") @Override public void addReaction(String emoji) { message.addReaction(emoji); } @Override public void addReaction(ReactionEmoji emoji) { message.addReaction(emoji); } @SuppressWarnings("deprecation") @Override public void removeReaction(IReaction reaction) { message.removeReaction(reaction); } @Override public void removeReaction(IUser user, IReaction reaction) { message.removeReaction(user, reaction); } @Override public void removeReaction(IUser user, ReactionEmoji emoji) { message.removeReaction(user, emoji); } @Override public void removeReaction(IUser user, IEmoji emoji) { message.removeReaction(user, emoji); } @Override public void removeReaction(IUser user, Emoji emoji) { message.removeReaction(user, emoji); } @Override public void removeReaction(IUser user, String emoji) { message.removeReaction(user, emoji); } @Override public void removeAllReactions() { message.removeAllReactions(); } @Override public MessageTokenizer tokenize() { return message.tokenize(); } @Override public boolean isDeleted() { return message.isDeleted(); } @Override public long getWebhookLongID() { return message.getWebhookLongID(); } @Override public Type getType() { return message.getType(); } @Override public boolean isSystemMessage() { return message.isSystemMessage(); } }
/* * @(#) XmlDsigInfoDAO.java * Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved. */ package com.esum.wp.ebms.xmldsiginfo.dao.impl; import java.util.List; import com.esum.appframework.dao.impl.SqlMapDAO; import com.esum.appframework.exception.ApplicationException; import com.esum.wp.ebms.xmldsiginfo.dao.IXmlDsigInfoDAO; /** * * @author sjyim@esumtech.com * @version $Revision: 1.6 $ $Date: 2009/02/05 11:51:52 $ */ public class XmlDsigInfoDAO extends SqlMapDAO implements IXmlDsigInfoDAO { /** * Default constructor. Can be used in place of getInstance() */ public XmlDsigInfoDAO () {} public String searchXmlDsigInfoIdID = ""; public String selectXmlDsigInfoListID = ""; public String checkXmlDsigInfoDuplicateID = ""; public String selectDsiNodeListID = ""; public String getSelectDsiNodeListID() { return selectDsiNodeListID; } public void setSelectDsiNodeListID(String selectDsiNodeListID) { this.selectDsiNodeListID = selectDsiNodeListID; } public Object selectDsiNodeList(Object object) throws ApplicationException { try { return getSqlMapClientTemplate().queryForList(selectDsiNodeListID, object); } catch (Exception e) { throw new ApplicationException(e); } } public List searchXmlDsigInfoId(Object object) throws ApplicationException { try { return getSqlMapClientTemplate().queryForList(searchXmlDsigInfoIdID, object); } catch (Exception e) { throw new ApplicationException(e); } } public List selectXmlDsigInfoList(Object object) throws ApplicationException { try { return getSqlMapClientTemplate().queryForList(selectXmlDsigInfoListID, object); } catch (Exception e) { throw new ApplicationException(e); } } public List checkXmlDsigInfoDuplicate(Object object) throws ApplicationException { try { return getSqlMapClientTemplate().queryForList(checkXmlDsigInfoDuplicateID, object); } catch (Exception e) { throw new ApplicationException(e); } } /** * * * @return Returns the checkXmlDsigInfoDuplicateID. */ public String getCheckXmlDsigInfoDuplicateID() { return checkXmlDsigInfoDuplicateID; } /** * * * @param checkXmlDsigInfoDuplicateID The checkXmlDsigInfoDuplicateID to set. */ public void setCheckXmlDsigInfoDuplicateID(String checkXmlDsigInfoDuplicateID) { this.checkXmlDsigInfoDuplicateID = checkXmlDsigInfoDuplicateID; } /** * * * @return Returns the searchXmlDsigInfoIdID. */ public String getSearchXmlDsigInfoIdID() { return searchXmlDsigInfoIdID; } /** * * * @param searchXmlDsigInfoIdID The searchXmlDsigInfoIdID to set. */ public void setSearchXmlDsigInfoIdID(String searchXmlDsigInfoIdID) { this.searchXmlDsigInfoIdID = searchXmlDsigInfoIdID; } public String getSelectXmlDsigInfoListID() { return selectXmlDsigInfoListID; } public void setSelectXmlDsigInfoListID(String selectXmlDsigInfoListID) { this.selectXmlDsigInfoListID = selectXmlDsigInfoListID; } }
package com.egswebapp.egsweb.dto.request; import javax.validation.constraints.NotBlank; public class PostRequestDto { @NotBlank(message = "title may not be empty") private String title; @NotBlank(message = "description may not be empty") private String description; @NotBlank(message = "short text may not be empty") private String shortText; @NotBlank(message = "name of category may not be empty") private String categoryName; @NotBlank(message = "language may not be empty") private String language; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryId) { this.categoryName = categoryId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getShortText() { return shortText; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public void setShortText(String shortText) { this.shortText = shortText; } }
package Client.view.view_ra; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JTextField; import Client.api.Profille; import Client.api.RA; public class PRegistration extends JPanel { JTextField txtLogin; public PRegistration() { setLayout(null); txtLogin = new JTextField(); JButton btnLogin = new JButton("Login"); JButton btnLogout = new JButton("Logout"); txtLogin.setBounds(10, 10, 150, 40); btnLogin.setBounds(10, 80, 70, 40); btnLogout.setBounds(100, 80, 70, 40); btnLogin.addActionListener(new LoginAct()); btnLogout.addActionListener(new LogoutAct()); btnLogin.setActionCommand("LogIn"); btnLogout.setActionCommand("LogOut"); add(btnLogin); add(btnLogout); add(txtLogin); } class LoginAct implements ActionListener { @Override public void actionPerformed(ActionEvent e) { try { RA.getI().login(txtLogin.getText()); Profille.getI().send(); } catch (IOException e1) { e1.printStackTrace(); } } } class LogoutAct implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { try { RA.getI().logout(); } catch (IOException e1) { e1.printStackTrace(); } } } }
package br.com.wasys.gfin.cheqfast.cliente.endpoint; import br.com.wasys.gfin.cheqfast.cliente.dataset.DataSet; import br.com.wasys.gfin.cheqfast.cliente.model.ProcessoModel; import br.com.wasys.gfin.cheqfast.cliente.model.ProcessoRegraModel; import br.com.wasys.gfin.cheqfast.cliente.model.TransferenciaModel; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Path; /** * Created by pascke on 02/08/16. */ public interface ProcessoEndpoint { @GET("processo/criar") Call<ProcessoModel> criar(); @POST("processo/salvar") Call<ProcessoModel> salvar(@Body ProcessoModel processoModel); @GET("processo/editar/{id}") Call<DataSet<ProcessoModel, ProcessoRegraModel>> editar(@Path("id") Long id); @POST("processo/aprovar/{id}") Call<DataSet<ProcessoModel, ProcessoRegraModel>> aprovar(@Path("id") Long id, @Body TransferenciaModel transferenciaModel); @GET("processo/cancelar/{id}") Call<DataSet<ProcessoModel, ProcessoRegraModel>> cancelar(@Path("id") Long id); }
package cn.study.crawler.src.proxy.pool; import java.util.ArrayList; import java.util.List; public abstract class UrlPaseHandle { public static List<IPMessage> ipMessages=new ArrayList<>() ; abstract void parseInitPage(String url); }
// 이범석 // 20171664 // HW8 // Inheritance public abstract class Shape { protected Point position; public Shape() { this(new Point(0,0)); } public Shape(Point pt) { this.position = pt; } /*setMethod*/ public void setPostion(Point l) { this.position = l; } /*getMethod*/ public Point getPostion() { return position; } /*toString*/ public String toString() { return ("Shape" + position); } public abstract double computeArea(); }
package ffm.slc.model.enums; /** * An indication of the type of Title I program, if any, in which the student is participating and served. */ public enum TitleIPartAParticipantType { PUBLIC_TARGETED_ASSISTANCE_PROGRAM("Public Targeted Assistance Program"), PUBLIC_SCHOOLWIDE_PROGRAM("Public Schoolwide Program"), PRIVATE_SCHOOL_STUDENTS_PARTICIPATING("Private school students participating"), LOCAL_NEGLECTED_PROGRAM("Local Neglected Program"), WAS_NOT_SERVED("Was not served"); private String prettyName; TitleIPartAParticipantType(String prettyName) { this.prettyName = prettyName; } @Override public String toString() { return prettyName; } }
package com.megathrone.tmall.controller; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.megathrone.tmall.pojo.Order; import com.megathrone.tmall.service.OrderItemService; import com.megathrone.tmall.service.OrderService; import com.megathrone.tmall.util.Page; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import java.io.IOException; import java.util.Date; import java.util.List; @Controller @RequestMapping("") public class OrderController { @Autowired OrderService orderService; @Autowired OrderItemService orderItemService; @RequestMapping("admin_order_list") public String list(Model model, Page page){ PageHelper.offsetPage(page.getStart(),page.getCount()); List<Order> os= orderService.list(); int total = (int) new PageInfo<>(os).getTotal(); page.setTotal(total); orderItemService.fill(os); model.addAttribute("os", os); model.addAttribute("page", page); return "admin/listOrder"; } @RequestMapping("admin_order_delivery") public String delivery(Order o) throws IOException { o.setDeliveryDate(new Date()); o.setStatus(OrderService.waitConfirm); orderService.update(o); return "redirect:admin_order_list"; } }
/* * 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 model; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.HashMap; import java.util.Map; import javax.swing.JOptionPane; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.view.JasperViewer; /** * * @author Gen-Xander */ public class ReportModel { Connection con=null; Statement st=null; ResultSet rs=null; String sql=null; public ReportModel() { try{ Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dbperpusse03","root",""); st=con.createStatement(); }catch(Exception a){ JOptionPane.showMessageDialog(null, "Koneksi Database Gagal, Terjadi kesalahaan Pada : \n"+a); } } public void cetakanggota() { try{ InputStream sumber = getClass().getResourceAsStream("/report/reportanggota.jrxml"); JasperReport jr = JasperCompileManager.compileReport(sumber); Map params = new HashMap(); JasperPrint jp = JasperFillManager.fillReport(jr, params, con); JasperViewer viewer = new JasperViewer(jp, false); viewer.setExtendedState(viewer.getExtendedState() | 0x6); viewer.setVisible(true); viewer.setTitle("Laporan Semua Anggota"); }catch(JRException ex){ JOptionPane.showMessageDialog(null, "Tidak dapat tampil report "+ex); } } public void cetakkategori() { try{ InputStream sumber = getClass().getResourceAsStream("/report/reportkategori.jrxml"); JasperReport jr = JasperCompileManager.compileReport(sumber); Map params = new HashMap(); JasperPrint jp = JasperFillManager.fillReport(jr, params, con); JasperViewer viewer = new JasperViewer(jp, false); viewer.setExtendedState(viewer.getExtendedState() | 0x6); viewer.setVisible(true); viewer.setTitle("Laporan Kategori Buku"); }catch(JRException ex){ JOptionPane.showMessageDialog(null, "Tidak dapat tampil report "+ex); } } public void cetakbuku() { try{ InputStream sumber = getClass().getResourceAsStream("/report/reportbuku.jrxml"); JasperReport jr = JasperCompileManager.compileReport(sumber); Map params = new HashMap(); JasperPrint jp = JasperFillManager.fillReport(jr, params, con); JasperViewer viewer = new JasperViewer(jp, false); viewer.setExtendedState(viewer.getExtendedState() | 0x6); viewer.setVisible(true); viewer.setTitle("Laporan Semua Buku"); }catch(JRException ex){ JOptionPane.showMessageDialog(null, "Tidak dapat tampil report "+ex); } } }
/* * 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 ImpresionDocumentos; import static Formuarios.Inicio.Pane1; import Formularios_Maestro_empleados.IncioMaestro; import java.awt.Dimension; /** * * @author jluis */ public class ImpresionDoc extends javax.swing.JInternalFrame { /** * Creates new form ImpresionDoc */ public ImpresionDoc() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); setClosable(true); jPanel1.setBackground(new java.awt.Color(153, 204, 255)); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel1.setText("IMPRESION DE DOCUMENTOS"); jButton1.setText("INDUCCION INICIAL"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("INDUCCION AL PUESTO"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("GESTIONES DE PISO"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setText("EXAMEN PRE CONTRATACION"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(60, 60, 60) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(66, 66, 66) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton4) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(116, 116, 116) .addComponent(jLabel1))) .addContainerGap(60, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(25, 25, 25) .addComponent(jLabel1) .addGap(46, 46, 46) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed InduccionInicial tra = new InduccionInicial(); Pane1.add(tra); Dimension desktopSize = Pane1.getSize(); Dimension FrameSize = tra.getSize(); tra.setLocation((desktopSize.width - FrameSize.width) / 2, (desktopSize.height - FrameSize.height) / 2); tra.show(); try { this.dispose(); } catch (Exception e) {System.out.println("F "+e); } }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed InduccionAlPuesto tra = new InduccionAlPuesto(); Pane1.add(tra); Dimension desktopSize = Pane1.getSize(); Dimension FrameSize = tra.getSize(); tra.setLocation((desktopSize.width - FrameSize.width) / 2, (desktopSize.height - FrameSize.height) / 2); tra.show(); try { this.dispose(); } catch (Exception e) {System.out.println("F "+e); } }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed GestionesPiso tra = new GestionesPiso(); Pane1.add(tra); Dimension desktopSize = Pane1.getSize(); Dimension FrameSize = tra.getSize(); tra.setLocation((desktopSize.width - FrameSize.width) / 2, (desktopSize.height - FrameSize.height) / 2); tra.show(); try { this.dispose(); } catch (Exception e) {System.out.println("F "+e); } }//GEN-LAST:event_jButton3ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed PreContratacion tra = new PreContratacion(); Pane1.add(tra); Dimension desktopSize = Pane1.getSize(); Dimension FrameSize = tra.getSize(); tra.setLocation((desktopSize.width - FrameSize.width) / 2, (desktopSize.height - FrameSize.height) / 2); tra.show(); try { this.dispose(); } catch (Exception e) {System.out.println("F "+e); } }//GEN-LAST:event_jButton4ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; // End of variables declaration//GEN-END:variables }
package exercise2; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class MyClassReflection { public void printAllMethods() { Class<?> clazz = MyClass.class; while (clazz != null) { System.out.println(String.format("Класс [ %s ] декларирует следующие методы:", clazz)); for (Method method : clazz.getDeclaredMethods()) { System.out.println(" - " + method.getName()); } System.out.println(); clazz = clazz.getSuperclass(); } } public void printAllGetterMethods() { Method[] methods = MyClass.class.getDeclaredMethods(); for (Method method : methods) { if ((Modifier.isPublic(method.getModifiers())) && (!method.getReturnType().toString().contains("void")) && (method.getName().contains("get"))) { System.out.println(method.getName()); } } } public void isStringConstantsValueEqualsName() throws IllegalAccessException { Field[] fields = MyClass.class.getDeclaredFields(); int countStringConstants = 0; int countEqualsNameStringConstants = 0; for (Field field : fields) { if (Modifier.isFinal(field.getModifiers()) && (Modifier.isStatic(field.getModifiers())) && (field.getType().equals(String.class))) { countStringConstants++; if (field.getName().equals(field.get(MyClass.class).toString())) { System.out.println(field.getName()); countEqualsNameStringConstants++; } } } System.out.println(String.format("%d из %d имен строковых констант равны своему значению", countEqualsNameStringConstants, countStringConstants)); } }
package com.github.sedubois.factorization.presentation; import com.github.sedubois.factorization.FactorizationTask; import com.github.sedubois.factorization.service.FactorizationService; import javax.inject.Inject; import javax.inject.Singleton; import io.vertx.core.Vertx; import io.vertx.core.json.Json; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.BodyHandler; import static java.util.Optional.ofNullable; @Singleton public class FactorizationController { private final FactorizationService service; @Inject FactorizationController(FactorizationService service) { this.service = service; } public Router getRouter() { Router router = Router.router(Vertx.currentContext().owner()); router.route().consumes("application/json"); router.route().produces("application/json"); router.get("/tasks").handler(this::getAll); router.get("/tasks/:id").handler(this::getOne); router.route("/tasks*").handler(BodyHandler.create()); router.post("/tasks").handler(this::addOne); router.delete("/tasks/:id").handler(this::deleteOne); return router; } private void getAll(RoutingContext routingContext) { routingContext.response() .putHeader("content-type", "application/json; charset=utf-8") .end(Json.encodePrettily(service.getAll())); } private void getOne(RoutingContext routingContext) { Long id = getId(routingContext); if (id == null) { routingContext.response().setStatusCode(400).end(); } else { FactorizationTask task = service.getOne(id); if (task == null) { routingContext.response().setStatusCode(404).end(); } else { routingContext.response() .putHeader("content-type", "application/json; charset=utf-8") // TODO don't serialize null values .end(Json.encodePrettily(task)); } } } private void addOne(RoutingContext routingContext) { FactorizationTask task = Json.decodeValue(routingContext.getBodyAsString(), FactorizationTask.class); task = service.create(task.getNumber()); routingContext.response() .setStatusCode(201) .putHeader("content-type", "application/json; charset=utf-8") .end(Json.encodePrettily(task)); } private void deleteOne(RoutingContext routingContext) { Long id = getId(routingContext); if (id == null) { routingContext.response().setStatusCode(400).end(); } else { service.remove(id); } routingContext.response().setStatusCode(204).end(); } private Long getId(RoutingContext routingContext) { return ofNullable(routingContext.request().getParam("id")) .map(Long::valueOf) .orElse(null); } }
package org.gavrilov.domain; import javax.annotation.Nonnull; import javax.persistence.*; import javax.persistence.Entity; import java.util.List; @Entity @Table(name = "user_role") public class UserRole extends org.gavrilov.domain.Entity { @Column(name = "rolename", nullable = false) private String rolename; @OneToMany(mappedBy = "userRole", cascade = {CascadeType.MERGE, CascadeType.PERSIST}) private List<User> users; public UserRole() { } @Nonnull public String getRolename() { return rolename; } public void setRolename(String rolename) { this.rolename = rolename; } public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } @Override public String toString() { return rolename; } }
package edu.rit.se.reichmafia.htmleditor; /** * Hello world! * */ public class HTMLEditor { public static void main( String[] args ) { System.out.println( "Hello World!" ); } }
package org.point85.domain.file; import java.io.File; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import org.point85.domain.collector.CollectorDataSource; import org.point85.domain.collector.DataSourceType; import org.point85.domain.dto.FileSourceDto; @Entity @DiscriminatorValue(DataSourceType.FILE_VALUE) public class FileEventSource extends CollectorDataSource { public FileEventSource() { super(); setDataSourceType(DataSourceType.FILE); } public FileEventSource(String name, String description) { super(name, description); setDataSourceType(DataSourceType.FILE); } public FileEventSource(FileSourceDto dto) { super(dto); } @Override public String getId() { return getHost(); } @Override public void setId(String id) { setHost(id); } public String getNetworkPath(String sourceId) { return getHost() + File.separatorChar + sourceId; } }
package khosbayar.hs.com.droidpheramor.activities; import androidx.fragment.app.FragmentActivity; import khosbayar.hs.com.droidpheramor.R; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void goRegister(View view) { Intent i = new Intent(this, Step1Activity.class); startActivity(i); } }
package mockito; public class AuthService { private AuthDao dao; // some code... public boolean isLogin(String id) { boolean isLogin = dao.isLogin(id); if (isLogin) { // some code... System.out.println("Login success"); } return isLogin; } }
package david.socket_communication_rpi; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Color; import android.net.Uri; import android.net.wifi.WifiManager; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; import java.math.BigInteger; import java.net.*; import java.lang.*; import java.io.*; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Collections; import java.util.List; import android.os.Vibrator; public class IP_Selection extends AppCompatActivity { private void saveToFile(String fname, String content) { FileOutputStream fos = null; Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); if (isSDPresent) { try { String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Heizung-IP/"; File storageFile = new File(path); if (!storageFile.exists()) { storageFile.mkdirs(); } final File textFile = new File(storageFile, fname + ".txt"); if (!textFile.exists()) { textFile.createNewFile(); } fos = new FileOutputStream(textFile); fos.write(content.getBytes()); fos.close(); } catch (IOException e) { } } else { try { String file = fname + ".txt"; FileOutputStream fOut = openFileOutput(file, MODE_PRIVATE); fOut.write(content.getBytes()); fOut.close(); } catch (IOException e) { System.out.println("IOEXCEPTION"); } } } private void removeFile(String fname) { File file = new File(fname); file.delete(); } private String readFile(String fname) { Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); if (isSDPresent) { File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/Heizung-IP/" + fname + ".txt"); StringBuilder text = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(file)); String line; if ((line = br.readLine()) != null) { text.append(line); } br.close(); } catch (IOException e) { //You'll need to add proper error handling here return "none"; } return text.toString(); } else { StringBuilder text = new StringBuilder(); try { FileInputStream fin = openFileInput(fname + ".txt"); int c; String temp = ""; while ((c = fin.read()) != -1) { temp = temp + Character.toString((char) c); } fin.close(); return temp; } catch (IOException e) { } } return ""; } Client client1; private int clientRunning = 0; private String serverRequest = "OK"; private IP_Selection mainReference = this; public void setClientRunning(int val) { clientRunning = val; } private void WAIT(int millis) { try { Thread.sleep(millis); } catch (Exception e) { } } public static boolean validIP(String ip) { try { if (ip == null || ip.isEmpty()) { return false; } String[] parts = ip.split("\\."); if (parts.length != 4) { return false; } for (String s : parts) { int i = Integer.parseInt(s); if ((i < 0) || (i > 255)) { return false; } } if (ip.endsWith(".")) { return false; } return true; } catch (NumberFormatException nfe) { return false; } } /*private void getSynchronized() { while (client1.isRunning() | isSending) { synchronized (client1.lock) { try { client1.lock.wait(); } catch (InterruptedException e) { } } } }*/ public void recolor2(int numb) { TextView cTV = (TextView) findViewById(R.id.color_indicator); cTV.setBackgroundResource(R.drawable.gradienten); cTV.getBackground().setLevel(numb); } protected String wifiIpAddress(Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE); int ipAddress = wifiManager.getConnectionInfo().getIpAddress(); // Convert little-endian to big-endianif needed if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) { ipAddress = Integer.reverseBytes(ipAddress); } byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray(); String ipAddressString; try { ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress(); } catch (UnknownHostException ex) { Log.e("WIFIIP", "Unable to get host address."); ipAddressString = null; } return ipAddressString; } private GoogleApiClient client; @Override public void onConfigurationChanged(Configuration newConfig) { // ignore orientation change if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } //Commands must be separated by Space public void multiSend(String s, boolean front) { final String str = s; final String[] commands = str.split(" "); final boolean fr = front; new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < commands.length; i++) { client1.appendMessage(commands[i], fr); } } }).start(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ip__selection); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); final EditText ipField = (EditText) findViewById(R.id.ip_text); final TextView updateText = (TextView) findViewById(R.id.update_text); final TextView colorInd = (TextView) findViewById(R.id.color_indicator); final Button statBtn = (Button) findViewById(R.id.status_btn); colorInd.getBackground().setLevel(2); int actionBarTitleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android"); if (actionBarTitleId > 0) { TextView title = (TextView) findViewById(actionBarTitleId); if (title != null) { title.setTextColor(Color.BLACK); } } updateText.setSelected(true); //updateText.setMovementMethod(new ScrollingMovementMethod()); serverRequest = "OK"; //client1 = new Client("127.0.0.1", 50007, updateText, serverRequest, statusText, mainReference); client1 = new Client("127.0.0.1", 50007, updateText, serverRequest, mainReference, colorInd); clientRunning = 0; //WAIT(500); String savedIP = readFile("HeizungIP"); if (validIP(savedIP)) { ipField.setText(savedIP); client1 = new Client(savedIP, 50007, updateText, serverRequest, mainReference, colorInd); } colorInd.setOnClickListener(new View.OnClickListener() { Context context = getApplicationContext(); @Override public void onClick(View v) { Vibrator vib = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE); vib.vibrate(30); } }); findViewById(R.id.this_ip_btn).setOnClickListener(new View.OnClickListener() { Context context = getApplicationContext(); @Override public void onClick(View v) { String ipAddress = wifiIpAddress(context); if (validIP(ipAddress)) { updateText.setText(ipAddress); } else { updateText.setText("Keine geeignete IP Adresse."); } } }); findViewById(R.id.start_client_btn).setOnClickListener(new View.OnClickListener() { Context context = getApplicationContext(); @Override public void onClick(View v) { String deviceIP = ipField.getText().toString(); final String devIP = deviceIP; Thread reconnectThread = new Thread(new Runnable() { private void ToastMessage(String s) { try { final String inUI = s; mainReference.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(mainReference.getApplicationContext(), inUI, Toast.LENGTH_SHORT).show(); } }); } catch (Exception e) { } } @Override public void run() { if (clientRunning == 0) { if (!validIP(devIP)) { ToastMessage("Bitte eine valide IPv4 Adresse eingeben."); } else { Vibrator vib = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vib.vibrate(50); ToastMessage("Verbindung wird neu gestartet."); client1 = new Client(devIP, 50007, updateText, serverRequest, mainReference, colorInd); } } else { ToastMessage("Verbindung wird geprüft."); multiSend("OK", false); mainReference.WAIT(100); if (clientRunning == 1) { ToastMessage("Es besteht bereits eine Verbindung. Wenn diese nicht nutzbar scheint hilft wahrscheinlich ein Neustart."); } else { ToastMessage("Keine Verbindung gefunden. Verbindung wird neu gestartet."); mainReference.runOnUiThread(new Runnable() { @Override public void run() { recolor2(2); } }); if (!validIP(devIP)) { ToastMessage("Bitte eine valide IPv4 Adresse eingeben."); } else { client1 = new Client(devIP, 50007, updateText, serverRequest, mainReference, colorInd); } } } } }); reconnectThread.start(); } }); findViewById(R.id.start_btn).setOnClickListener(new View.OnClickListener() { Context context = getApplicationContext(); @Override public void onClick(View v) { if (clientRunning == 0) { Toast.makeText(context, "Es besteht keine Verbindung.", Toast.LENGTH_SHORT).show(); final String devIP = ipField.getText().toString(); Thread reconnectThread = new Thread(new Runnable() { private void ToastMessage(String s) { try { final String inUI = s; mainReference.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(mainReference.getApplicationContext(), inUI, Toast.LENGTH_SHORT).show(); } }); } catch (Exception e) { } } @Override public void run() { if (!validIP(devIP)) { ToastMessage("Bitte eine valide IPv4 Adresse eingeben."); } else { Vibrator vib = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vib.vibrate(50); ToastMessage("Verbindung wird neu gestartet."); client1 = new Client(devIP, 50007, updateText, serverRequest, mainReference, colorInd); } } }); reconnectThread.start(); } else { multiSend("TurnOn SendStatus", true); Vibrator vib = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE); vib.vibrate(30); } } }); findViewById(R.id.stop_btn).setOnClickListener(new View.OnClickListener() { Context context = getApplicationContext(); @Override public void onClick(View v) { client1.stopThread(); client1.closeConnection(); clientRunning = 0; Toast.makeText(context, "Client closed", Toast.LENGTH_SHORT).show(); Vibrator vib = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE); vib.vibrate(30); //Restarts Application Intent mStartActivity = new Intent(context, IP_Selection.class); int mPendingIntentId = 123456; PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent); finish(); System.exit(0); } }); findViewById(R.id.save_btn).setOnClickListener(new View.OnClickListener() { Context context = getApplicationContext(); @Override public void onClick(View v) { if (validIP(ipField.getText().toString())) { removeFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Heizung-IP/HeizungIP.txt"); saveToFile("HeizungIP", ipField.getText().toString()); Toast.makeText(context, "Gespeichert", Toast.LENGTH_SHORT).show(); Vibrator vib = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE); vib.vibrate(30); } else { Toast.makeText(context, "Please enter a valid IPv4-address", Toast.LENGTH_SHORT).show(); } } }); findViewById(R.id.remove_btn).setOnClickListener(new View.OnClickListener() { Context context = getApplicationContext(); @Override public void onClick(View v) { ipField.setText(""); Vibrator vib = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE); vib.vibrate(30); } }); findViewById(R.id.status_btn).setOnClickListener(new View.OnClickListener() { Context context = getApplicationContext(); @Override public void onClick(View v) { if (clientRunning == 0) { Toast.makeText(context, "Nicht verbunden.", Toast.LENGTH_SHORT).show(); } else if (client1.isRunning()) { } else { multiSend("SendStatus", false); Vibrator vib = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE); vib.vibrate(30); } } }); findViewById(R.id.sendalot).setOnClickListener(new View.OnClickListener() { Context context = getApplicationContext(); @Override public void onClick(View v) { if (clientRunning == 0) { Toast.makeText(context, "Nicht verbunden.", Toast.LENGTH_SHORT).show(); } else { new Thread(new Runnable() { @Override public void run() { for (int i = 0; i<1000; i++)multiSend("SendStatus", false); } }).start(); Vibrator vib = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE); vib.vibrate(30); } } }); client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "IP_Selection Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://david.socket_communication_rpi/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); } @Override public void onStop() { super.onStop(); client1.stopThread(); client1.closeConnection(); client1 = null; clientRunning = 0; finish(); System.exit(0); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "IP_Selection Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://david.socket_communication_rpi/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); } }
package com.myneu.project.pojo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="OrderTable") public class Order { @Id @GeneratedValue @Column(name = "OrderId", unique = true, nullable =false) private int Id; public int getId() { return Id; } public void setId(int id) { Id = id; } @Column(name="customerID") private int customerID; /*@OneToMany @JoinTable(joinColumns=@JoinColumn(name="OrderId"), inverseJoinColumns=@JoinColumn(name="productId")) private Collection<FinalProductsOrder> product = new ArrayList<FinalProductsOrder>(); */ public int getCustomerID() { return customerID; } public void setCustomerID(int customerID) { this.customerID = customerID; } }
package com.example.chordnote.ui.collectcomments; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Context; import android.content.Intent; import android.os.Bundle; import com.example.chordnote.R; import com.example.chordnote.data.network.model.Comment; import com.example.chordnote.ui.base.BaseActivity; import com.example.chordnote.ui.period.comment.CommentAdapter; import com.example.chordnote.ui.widget.CommonBar; import java.util.ArrayList; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; public class CollectCommentActivity extends BaseActivity implements CollectCommentView { @Inject CollectCommentPresenter<CollectCommentView> presenter; private String email; private ArrayList<Comment> comments; @BindView(R.id.collect_comment_list_view) RecyclerView collectComments; @BindView(R.id.collect_comment_commonbar) CommonBar bar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_collect_comment); ButterKnife.bind(this); getActivityComponent().inject(this); presenter.onAttach(this); collectComments.setLayoutManager(new LinearLayoutManager(this)); email = getIntent().getStringExtra("email"); if (email != null){ presenter.setDynamicList(email); } getSupportActionBar().hide(); bar.setBarTitleText("收藏评论"); } public static Intent getIntent(Context context, String email){ Intent intent = new Intent(context, CollectCommentActivity.class); intent.putExtra("email", email); return intent; } @Override public void setDynamicList(ArrayList<Comment> comments) { this.comments = comments; collectComments.setAdapter(new CommentAdapter(this, comments)); } }
/* * Copyright 2016 TeddySoft Technology. All rights reserved. * */ package tw.teddysoft.gof.abstractFactory; public class LinuxProcess extends Process { public LinuxProcess(int id){ super(id); } }
/* * Copyright (C) 2017 The Android Open Source Project * * 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. */ /** * Tests for simple integral reductions: same type for accumulator and data. */ public class Main { static final int N = 500; static final int M = 100; // // Basic reductions in loops. // // TODO: vectorize these (second step of b/64091002 plan) private static byte reductionByte(byte[] x) { byte sum = 0; for (int i = 0; i < x.length; i++) { sum += x[i]; } return sum; } private static short reductionShort(short[] x) { short sum = 0; for (int i = 0; i < x.length; i++) { sum += x[i]; } return sum; } private static char reductionChar(char[] x) { char sum = 0; for (int i = 0; i < x.length; i++) { sum += x[i]; } return sum; } /// CHECK-START: int Main.reductionInt(int[]) loop_optimization (before) /// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none /// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none /// CHECK-DAG: <<Phi2:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none /// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop>> outer_loop:none /// CHECK-DAG: <<Get:i\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Add [<<Phi2>>,<<Get>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Return [<<Phi2>>] loop:none // /// CHECK-START-{ARM,ARM64}: int Main.reductionInt(int[]) loop_optimization (after) /// CHECK-DAG: <<Cons:i\d+>> IntConstant {{2|4}} loop:none /// CHECK-DAG: <<Set:d\d+>> VecSetScalars [{{i\d+}}] loop:none /// CHECK-DAG: <<Phi:d\d+>> Phi [<<Set>>,{{d\d+}}] loop:<<Loop:B\d+>> outer_loop:none /// CHECK-DAG: <<Load:d\d+>> VecLoad [{{l\d+}},<<I:i\d+>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: VecAdd [<<Phi>>,<<Load>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Add [<<I>>,<<Cons>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: <<Red:d\d+>> VecReduce [<<Phi>>] loop:none /// CHECK-DAG: <<Extr:i\d+>> VecExtractScalar [<<Red>>] loop:none // Check that full 128-bit Q-Register are saved across SuspendCheck slow path. /// CHECK-START-ARM64: int Main.reductionInt(int[]) disassembly (after) /// CHECK: SuspendCheckSlowPathARM64 /// CHECK: stur q<<RegNo:\d+>>, [sp, #<<Offset:\d+>>] /// CHECK: ldur q<<RegNo>>, [sp, #<<Offset>>] private static int reductionInt(int[] x) { int sum = 0; for (int i = 0; i < x.length; i++) { sum += x[i]; } return sum; } /// CHECK-START: int Main.reductionIntChain() loop_optimization (before) /// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none /// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none /// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons1>>,{{i\d+}}] loop:<<Loop1:B\d+>> outer_loop:none /// CHECK-DAG: <<Phi2:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop1>> outer_loop:none /// CHECK-DAG: <<Get1:i\d+>> ArrayGet [{{l\d+}},<<Phi2>>] loop:<<Loop1>> outer_loop:none /// CHECK-DAG: Add [<<Phi1>>,<<Get1>>] loop:<<Loop1>> outer_loop:none /// CHECK-DAG: Add [<<Phi2>>,<<Cons1>>] loop:<<Loop1>> outer_loop:none /// CHECK-DAG: <<Phi3:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop2:B\d+>> outer_loop:none /// CHECK-DAG: <<Phi4:i\d+>> Phi [<<Phi1>>,{{i\d+}}] loop:<<Loop2>> outer_loop:none /// CHECK-DAG: <<Get2:i\d+>> ArrayGet [{{l\d+}},<<Phi3>>] loop:<<Loop2>> outer_loop:none /// CHECK-DAG: Add [<<Phi4>>,<<Get2>>] loop:<<Loop2>> outer_loop:none /// CHECK-DAG: Add [<<Phi3>>,<<Cons1>>] loop:<<Loop2>> outer_loop:none /// CHECK-DAG: Return [<<Phi4>>] loop:none // /// CHECK-EVAL: "<<Loop1>>" != "<<Loop2>>" // /// CHECK-START-{ARM,ARM64}: int Main.reductionIntChain() loop_optimization (after) /// CHECK-DAG: <<Set1:d\d+>> VecSetScalars [{{i\d+}}] loop:none /// CHECK-DAG: <<Phi1:d\d+>> Phi [<<Set1>>,{{d\d+}}] loop:<<Loop1:B\d+>> outer_loop:none /// CHECK-DAG: <<Load1:d\d+>> VecLoad [{{l\d+}},<<I1:i\d+>>] loop:<<Loop1>> outer_loop:none /// CHECK-DAG: VecAdd [<<Phi1>>,<<Load1>>] loop:<<Loop1>> outer_loop:none /// CHECK-DAG: Add [<<I1>>,{{i\d+}}] loop:<<Loop1>> outer_loop:none /// CHECK-DAG: <<Red1:d\d+>> VecReduce [<<Phi1>>] loop:none /// CHECK-DAG: <<Extr1:i\d+>> VecExtractScalar [<<Red1>>] loop:none /// CHECK-DAG: <<Set2:d\d+>> VecSetScalars [{{i\d+}}] loop:none /// CHECK-DAG: <<Phi2:d\d+>> Phi [<<Set2>>,{{d\d+}}] loop:<<Loop2:B\d+>> outer_loop:none /// CHECK-DAG: <<Load2:d\d+>> VecLoad [{{l\d+}},<<I2:i\d+>>] loop:<<Loop2>> outer_loop:none /// CHECK-DAG: VecAdd [<<Phi2>>,<<Load2>>] loop:<<Loop2>> outer_loop:none /// CHECK-DAG: Add [<<I2>>,{{i\d+}}] loop:<<Loop2>> outer_loop:none /// CHECK-DAG: <<Red2:d\d+>> VecReduce [<<Phi2>>] loop:none /// CHECK-DAG: <<Extr2:i\d+>> VecExtractScalar [<<Red2>>] loop:none // /// CHECK-EVAL: "<<Loop1>>" != "<<Loop2>>" // // NOTE: pattern is robust with respect to vector loop unrolling and peeling. private static int reductionIntChain() { int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; int r = 1; for (int i = 0; i < 16; i++) { r += x[i]; } for (int i = 0; i < 16; i++) { r += x[i]; } return r; } /// CHECK-START: int Main.reductionIntToLoop(int[]) loop_optimization (before) /// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none /// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none /// CHECK-DAG: <<Phi2:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop1:B\d+>> outer_loop:none /// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop1>> outer_loop:none /// CHECK-DAG: <<Get:i\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop1>> outer_loop:none /// CHECK-DAG: Add [<<Phi2>>,<<Get>>] loop:<<Loop1>> outer_loop:none /// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop1>> outer_loop:none /// CHECK-DAG: <<Phi3:i\d+>> Phi [<<Phi2>>,{{i\d+}}] loop:<<Loop2:B\d+>> outer_loop:none /// CHECK-DAG: <<Phi4:i\d+>> Phi [<<Phi2>>,{{i\d+}}] loop:<<Loop2>> outer_loop:none // /// CHECK-EVAL: "<<Loop1>>" != "<<Loop2>>" // /// CHECK-START-{ARM,ARM64}: int Main.reductionIntToLoop(int[]) loop_optimization (after) /// CHECK-DAG: <<Cons:i\d+>> IntConstant {{2|4}} loop:none /// CHECK-DAG: <<Set:d\d+>> VecSetScalars [{{i\d+}}] loop:none /// CHECK-DAG: <<Phi:d\d+>> Phi [<<Set>>,{{d\d+}}] loop:<<Loop1:B\d+>> outer_loop:none /// CHECK-DAG: <<Load:d\d+>> VecLoad [{{l\d+}},<<I:i\d+>>] loop:<<Loop1>> outer_loop:none /// CHECK-DAG: VecAdd [<<Phi>>,<<Load>>] loop:<<Loop1>> outer_loop:none /// CHECK-DAG: Add [<<I>>,<<Cons>>] loop:<<Loop1>> outer_loop:none /// CHECK-DAG: <<Red:d\d+>> VecReduce [<<Phi>>] loop:none /// CHECK-DAG: <<Extr:i\d+>> VecExtractScalar [<<Red>>] loop:none private static int reductionIntToLoop(int[] x) { int r = 0; for (int i = 0; i < 8; i++) { r += x[i]; } for (int i = r; i < 16; i++) { r += i; } return r; } /// CHECK-START: long Main.reductionLong(long[]) loop_optimization (before) /// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none /// CHECK-DAG: <<Long0:j\d+>> LongConstant 0 loop:none /// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none /// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none /// CHECK-DAG: <<Phi2:j\d+>> Phi [<<Long0>>,{{j\d+}}] loop:<<Loop>> outer_loop:none /// CHECK-DAG: <<Get:j\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Add [<<Phi2>>,<<Get>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Return [<<Phi2>>] loop:none // /// CHECK-START-ARM64: long Main.reductionLong(long[]) loop_optimization (after) /// CHECK-DAG: <<Cons2:i\d+>> IntConstant 2 loop:none /// CHECK-DAG: <<Set:d\d+>> VecSetScalars [{{j\d+}}] loop:none /// CHECK-DAG: <<Phi:d\d+>> Phi [<<Set>>,{{d\d+}}] loop:<<Loop:B\d+>> outer_loop:none /// CHECK-DAG: <<Load:d\d+>> VecLoad [{{l\d+}},<<I:i\d+>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: VecAdd [<<Phi>>,<<Load>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Add [<<I>>,<<Cons2>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: <<Red:d\d+>> VecReduce [<<Phi>>] loop:none /// CHECK-DAG: <<Extr:j\d+>> VecExtractScalar [<<Red>>] loop:none private static long reductionLong(long[] x) { long sum = 0; for (int i = 0; i < x.length; i++) { sum += x[i]; } return sum; } private static byte reductionByteM1(byte[] x) { byte sum = -1; for (int i = 0; i < x.length; i++) { sum += x[i]; } return sum; } private static short reductionShortM1(short[] x) { short sum = -1; for (int i = 0; i < x.length; i++) { sum += x[i]; } return sum; } private static char reductionCharM1(char[] x) { char sum = 0xffff; for (int i = 0; i < x.length; i++) { sum += x[i]; } return sum; } /// CHECK-START: int Main.reductionIntM1(int[]) loop_optimization (before) /// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none /// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none /// CHECK-DAG: <<ConsM1:i\d+>> IntConstant -1 loop:none /// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none /// CHECK-DAG: <<Phi2:i\d+>> Phi [<<ConsM1>>,{{i\d+}}] loop:<<Loop>> outer_loop:none /// CHECK-DAG: <<Get:i\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Add [<<Phi2>>,<<Get>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Return [<<Phi2>>] loop:none // /// CHECK-START-{ARM,ARM64}: int Main.reductionIntM1(int[]) loop_optimization (after) /// CHECK-DAG: <<Cons:i\d+>> IntConstant {{2|4}} loop:none /// CHECK-DAG: <<Set:d\d+>> VecSetScalars [{{i\d+}}] loop:none /// CHECK-DAG: <<Phi:d\d+>> Phi [<<Set>>,{{d\d+}}] loop:<<Loop:B\d+>> outer_loop:none /// CHECK-DAG: <<Load:d\d+>> VecLoad [{{l\d+}},<<I:i\d+>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: VecAdd [<<Phi>>,<<Load>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Add [<<I>>,<<Cons>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: <<Red:d\d+>> VecReduce [<<Phi>>] loop:none /// CHECK-DAG: <<Extr:i\d+>> VecExtractScalar [<<Red>>] loop:none private static int reductionIntM1(int[] x) { int sum = -1; for (int i = 0; i < x.length; i++) { sum += x[i]; } return sum; } /// CHECK-START: long Main.reductionLongM1(long[]) loop_optimization (before) /// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none /// CHECK-DAG: <<LongM1:j\d+>> LongConstant -1 loop:none /// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none /// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none /// CHECK-DAG: <<Phi2:j\d+>> Phi [<<LongM1>>,{{j\d+}}] loop:<<Loop>> outer_loop:none /// CHECK-DAG: <<Get:j\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Add [<<Phi2>>,<<Get>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Return [<<Phi2>>] loop:none // /// CHECK-START-ARM64: long Main.reductionLongM1(long[]) loop_optimization (after) /// CHECK-DAG: <<Cons2:i\d+>> IntConstant 2 loop:none /// CHECK-DAG: <<Set:d\d+>> VecSetScalars [{{j\d+}}] loop:none /// CHECK-DAG: <<Phi:d\d+>> Phi [<<Set>>,{{d\d+}}] loop:<<Loop:B\d+>> outer_loop:none /// CHECK-DAG: <<Load:d\d+>> VecLoad [{{l\d+}},<<I:i\d+>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: VecAdd [<<Phi>>,<<Load>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Add [<<I>>,<<Cons2>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: <<Red:d\d+>> VecReduce [<<Phi>>] loop:none /// CHECK-DAG: <<Extr:j\d+>> VecExtractScalar [<<Red>>] loop:none private static long reductionLongM1(long[] x) { long sum = -1L; for (int i = 0; i < x.length; i++) { sum += x[i]; } return sum; } private static byte reductionMinusByte(byte[] x) { byte sum = 0; for (int i = 0; i < x.length; i++) { sum -= x[i]; } return sum; } private static short reductionMinusShort(short[] x) { short sum = 0; for (int i = 0; i < x.length; i++) { sum -= x[i]; } return sum; } private static char reductionMinusChar(char[] x) { char sum = 0; for (int i = 0; i < x.length; i++) { sum -= x[i]; } return sum; } /// CHECK-START: int Main.reductionMinusInt(int[]) loop_optimization (before) /// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none /// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none /// CHECK-DAG: <<Phi2:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none /// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop>> outer_loop:none /// CHECK-DAG: <<Get:i\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Sub [<<Phi2>>,<<Get>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Return [<<Phi2>>] loop:none // /// CHECK-START-{ARM,ARM64}: int Main.reductionMinusInt(int[]) loop_optimization (after) /// CHECK-DAG: <<Cons:i\d+>> IntConstant {{2|4}} loop:none /// CHECK-DAG: <<Set:d\d+>> VecSetScalars [{{i\d+}}] loop:none /// CHECK-DAG: <<Phi:d\d+>> Phi [<<Set>>,{{d\d+}}] loop:<<Loop:B\d+>> outer_loop:none /// CHECK-DAG: <<Load:d\d+>> VecLoad [{{l\d+}},<<I:i\d+>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: VecSub [<<Phi>>,<<Load>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Add [<<I>>,<<Cons>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: <<Red:d\d+>> VecReduce [<<Phi>>] loop:none /// CHECK-DAG: <<Extr:i\d+>> VecExtractScalar [<<Red>>] loop:none private static int reductionMinusInt(int[] x) { int sum = 0; for (int i = 0; i < x.length; i++) { sum -= x[i]; } return sum; } /// CHECK-START: long Main.reductionMinusLong(long[]) loop_optimization (before) /// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none /// CHECK-DAG: <<Long0:j\d+>> LongConstant 0 loop:none /// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none /// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none /// CHECK-DAG: <<Phi2:j\d+>> Phi [<<Long0>>,{{j\d+}}] loop:<<Loop>> outer_loop:none /// CHECK-DAG: <<Get:j\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Sub [<<Phi2>>,<<Get>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Return [<<Phi2>>] loop:none // /// CHECK-START-ARM64: long Main.reductionMinusLong(long[]) loop_optimization (after) /// CHECK-DAG: <<Cons2:i\d+>> IntConstant 2 loop:none /// CHECK-DAG: <<Set:d\d+>> VecSetScalars [{{j\d+}}] loop:none /// CHECK-DAG: <<Phi:d\d+>> Phi [<<Set>>,{{d\d+}}] loop:<<Loop:B\d+>> outer_loop:none /// CHECK-DAG: <<Load:d\d+>> VecLoad [{{l\d+}},<<I:i\d+>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: VecSub [<<Phi>>,<<Load>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: Add [<<I>>,<<Cons2>>] loop:<<Loop>> outer_loop:none /// CHECK-DAG: <<Red:d\d+>> VecReduce [<<Phi>>] loop:none /// CHECK-DAG: <<Extr:j\d+>> VecExtractScalar [<<Red>>] loop:none private static long reductionMinusLong(long[] x) { long sum = 0; for (int i = 0; i < x.length; i++) { sum -= x[i]; } return sum; } // // A few special cases. // // TODO: consider unrolling private static int reductionInt10(int[] x) { int sum = 0; // Amenable to complete unrolling. for (int i = 10; i <= 10; i++) { sum += x[i]; } return sum; } private static int reductionMinusInt10(int[] x) { int sum = 0; // Amenable to complete unrolling. for (int i = 10; i <= 10; i++) { sum -= x[i]; } return sum; } // // Main driver. // public static void main(String[] args) { byte[] xb = new byte[N]; short[] xs = new short[N]; char[] xc = new char[N]; int[] xi = new int[N]; long[] xl = new long[N]; for (int i = 0, k = -17; i < N; i++, k += 3) { xb[i] = (byte) k; xs[i] = (short) k; xc[i] = (char) k; xi[i] = k; xl[i] = k; } // Arrays with all positive elements. byte[] xpb = new byte[M]; short[] xps = new short[M]; char[] xpc = new char[M]; int[] xpi = new int[M]; long[] xpl = new long[M]; for (int i = 0, k = 3; i < M; i++, k++) { xpb[i] = (byte) k; xps[i] = (short) k; xpc[i] = (char) k; xpi[i] = k; xpl[i] = k; } // Arrays with all negative elements. byte[] xnb = new byte[M]; short[] xns = new short[M]; int[] xni = new int[M]; long[] xnl = new long[M]; for (int i = 0, k = -103; i < M; i++, k++) { xnb[i] = (byte) k; xns[i] = (short) k; xni[i] = k; xnl[i] = k; } // Test various reductions in loops. int[] x0 = { 0, 0, 0, 0, 0, 0, 0, 0 }; int[] x1 = { 0, 0, 0, 1, 0, 0, 0, 0 }; int[] x2 = { 1, 1, 1, 1, 0, 0, 0, 0 }; expectEquals(-74, reductionByte(xb)); expectEquals(-27466, reductionShort(xs)); expectEquals(38070, reductionChar(xc)); expectEquals(365750, reductionInt(xi)); expectEquals(273, reductionIntChain()); expectEquals(120, reductionIntToLoop(x0)); expectEquals(121, reductionIntToLoop(x1)); expectEquals(118, reductionIntToLoop(x2)); expectEquals(-1310, reductionIntToLoop(xi)); expectEquals(365750L, reductionLong(xl)); expectEquals(-75, reductionByteM1(xb)); expectEquals(-27467, reductionShortM1(xs)); expectEquals(38069, reductionCharM1(xc)); expectEquals(365749, reductionIntM1(xi)); expectEquals(365749L, reductionLongM1(xl)); expectEquals(74, reductionMinusByte(xb)); expectEquals(27466, reductionMinusShort(xs)); expectEquals(27466, reductionMinusChar(xc)); expectEquals(-365750, reductionMinusInt(xi)); expectEquals(365750L, reductionLong(xl)); expectEquals(-75, reductionByteM1(xb)); expectEquals(-27467, reductionShortM1(xs)); expectEquals(38069, reductionCharM1(xc)); expectEquals(365749, reductionIntM1(xi)); expectEquals(365749L, reductionLongM1(xl)); expectEquals(74, reductionMinusByte(xb)); expectEquals(27466, reductionMinusShort(xs)); expectEquals(27466, reductionMinusChar(xc)); expectEquals(-365750, reductionMinusInt(xi)); expectEquals(-365750L, reductionMinusLong(xl)); // Test special cases. expectEquals(13, reductionInt10(xi)); expectEquals(-13, reductionMinusInt10(xi)); System.out.println("passed"); } private static void expectEquals(int expected, int result) { if (expected != result) { throw new Error("Expected: " + expected + ", found: " + result); } } private static void expectEquals(long expected, long result) { if (expected != result) { throw new Error("Expected: " + expected + ", found: " + result); } } }
package com.angular.angular.service; import com.angular.angular.dto.UserDto; public interface UserService { /** * Create new user * @param userDto Object * @return userDto */ UserDto createUser(UserDto userDto); }
/** * Jonathan Aguirre, 14349 * Yosemite Melendez, 14413 * Delbert Custodio, 14246 * * * Se siguieron las instrucciones indicadas en comentarios */ import java.io.*; import java.util.Scanner; class WordTypeCounter { public static void main(String[] args) throws Exception { if(args.length > 1) { // Declaración e inicialización de variables. // el primer parametro indica el nombre del archivo con las definiciones de las palabras File wordFile = new File(args[0]); // el segundo parametro indica el nombre del archivo que tiene el texto a analizar File textFile = new File(args[1]); int implementacion = Integer.parseInt(args[2]); BufferedReader wordreader; BufferedReader textreader; int verbs=0; int nouns=0; int adjectives=0; int adverbs=0; int gerunds=0; long starttime; long endtime; if(wordFile.isFile() && textFile.isFile()) { try { wordreader = new BufferedReader(new FileReader(wordFile)); textreader = new BufferedReader(new FileReader(textFile)); } catch (Exception ex) { System.out.println("Error al leer!"); return; } String seleccion = null; switch (implementacion){ case 1: seleccion = "SimpleSet"; break; case 2: seleccion = "Red Black Tree"; break; case 3: seleccion = "Splay Tree"; break; case 4: seleccion = "HashMap"; break; case 5: seleccion = "TreeMap"; break; } WordSet words = WordSetFactory.generateSet(implementacion); String line = null; String[] wordParts; starttime = System.currentTimeMillis(); line = wordreader.readLine(); while(line!=null) { wordParts = line.split("\\."); // lo que esta entre comillas es una expresión regular. if(wordParts.length == 2) { words.add(new Word(wordParts[0].trim(),wordParts[1].trim())); } line = wordreader.readLine(); } wordreader.close(); endtime = System.currentTimeMillis(); System.out.println("Palabras cargadas en " + (endtime-starttime) + " ms."); // Procesar archivo de texto starttime = System.currentTimeMillis(); line = textreader.readLine(); String[] textParts; Word currentword; Word lookupword = new Word(); while(line!=null) { // Separar todas las palabras en la línea. textParts = line.split("[^\\w-]+"); // utilizar de separador cualquier caracter que no sea una letra, número o guión. // Revisar cada palabra y verificar de que tipo es. for(int i=0;i<textParts.length;i++) { lookupword.setWord(textParts[i].trim().toLowerCase()); currentword = words.get(lookupword); if(currentword != null) { if(currentword.getType().equals("v-d") || currentword.getType().equals("v") || currentword.getType().equals("q")) verbs++; else if(currentword.getType().equals("g") ) gerunds++; else if(currentword.getType().equals("a-s") || currentword.getType().equals("a-c") || currentword.getType().equals("a")) adjectives++; else if(currentword.getType().equals("e")) adverbs++; else nouns++; } } line = textreader.readLine(); } textreader.close(); endtime = System.currentTimeMillis(); System.out.println("Texto analizado en " + (endtime-starttime) + " ms."); System.out.println(); System.out.println(); System.out.println(); // Presentar estadísticas System.out.println("El texto tiene:"); System.out.println(verbs + " verbos"); System.out.println(nouns + " sustantivos"); System.out.println(adjectives + " adjetivos"); System.out.println(adverbs + " adverbios"); System.out.println(gerunds + " gerundios"); System.out.println("Implementacion que se utilizo: "+seleccion); } else { System.out.println("No encuentro los archivos :'( "); } } else { System.out.println("Faltan Parametros."); } } }