text
stringlengths
10
2.72M
package com.ramiromadriaga.viewpagerlistviewactivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; /** * Created by user on 23/12/2014. */ public class ListarCircuito extends ActionBarActivity { int[] imagenCircuitoChico = { R.drawable.circuitochico_plaza, R.drawable.circuitochico_iglesiacatedral, R.drawable.circuitochico_casanatalsarmiento, R.drawable.circuitochico_celdahistoriasanmartin, R.drawable.circuitochico_parque, R.drawable.circuitochico_auditorio, R.drawable.circuitochico_cienciasnaturales, R.drawable.circuitochico_museograffigna }; int[] imagenCircuitoLunar = { R.drawable.circuitolunar_caucete, R.drawable.circuitolunar_difunta, R.drawable.circuitolunar_vallefertil, R.drawable.circuitolunar_ischigualasto }; int[] imagenRutaDelVino = { R.drawable.rutadelvino_bodegaslaguarda, R.drawable.rutadelvino_champaneramiguelmas, R.drawable.rutadelvino_bodegasyvinedosfabril, R.drawable.rutadelvino_lasmarianasbodegafamliar, R.drawable.rutadelvino_vinassegisa }; int[] imagenCircuitoDelSol = { R.drawable.circuitodelsol_parquefaunistico, R.drawable.circuitodelsol_diquedeullum, R.drawable.circuitodelsol_quebradazonda, R.drawable.circuitodelsol_jardindelospoetas, R.drawable.circuitodelsol_autodromodezonda, R.drawable.circuitodelsol_cavasdezonda }; int[] imagenCircuitoVerde = { R.drawable.circuitoverde_iglesia, R.drawable.circuitoverde_pismanta, R.drawable.circuitoverde_rodeo, R.drawable.circuitoverde_tudcum, R.drawable.circuitoverde_cuestadelviento, R.drawable.circuitoverde_jachal, R.drawable.circuitoverde_huaco }; int[] imagenCircuitoDelRio = { R.drawable.circuitodelrio_calingasta, R.drawable.circuitodelrio_barreal, R.drawable.circuitodelrio_pampa, R.drawable.circuitodelrio_obsevatorio }; String[] titulo; String[] contenido; private ListView lista; ListViewAdapter adapter; int currentViewPager; String nombreCircuito; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listar_circuito); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); //ir atras Bundle extras = getIntent().getExtras(); currentViewPager = extras.getInt("currentViewPager"); nombreCircuito = extras.getString("nombreCircuito"); Log.i("ramiro", "currentViewPager: " + currentViewPager); /**INDICAR TITULO **/ actionBar.setTitle(nombreCircuito); lista = (ListView) findViewById(R.id.listView_listarCircuito); switch (currentViewPager){ case 0: //circuito chico titulo = getResources().getStringArray(R.array.circuitochico_titulo); contenido = getResources().getStringArray(R.array.circuitochico_contenido); adapter = new ListViewAdapter(this, imagenCircuitoChico, titulo, contenido); break; case 1: //circuito lunar titulo = getResources().getStringArray(R.array.circuitolunar_titulo); contenido = getResources().getStringArray(R.array.circuitolunar_contenido); adapter = new ListViewAdapter(this, imagenCircuitoLunar, titulo, contenido); break; case 2: //ruta del vino titulo = getResources().getStringArray(R.array.rutadelvino_titulo); contenido = getResources().getStringArray(R.array.rutadelvino_contenido); adapter = new ListViewAdapter(this, imagenRutaDelVino, titulo, contenido); break; case 3: //circuito del sol titulo = getResources().getStringArray(R.array.circuitodelsol_titulo); contenido = getResources().getStringArray(R.array.circuitodelsol_contenido); adapter = new ListViewAdapter(this, imagenCircuitoDelSol, titulo, contenido); break; case 4: //circuito verde titulo = getResources().getStringArray(R.array.circuitoverde_titulo); contenido = getResources().getStringArray(R.array.circuitoverde_contenido); adapter = new ListViewAdapter(this, imagenCircuitoVerde, titulo, contenido); break; case 5: //circuito del rรญo titulo = getResources().getStringArray(R.array.circuitodelrio_titulo); contenido = getResources().getStringArray(R.array.circuitodelrio_contenido); adapter = new ListViewAdapter(this, imagenCircuitoDelRio, titulo, contenido); break; default: Toast.makeText(getApplicationContext(), "no esta cargado, pronto lo estarรก", Toast.LENGTH_SHORT).show(); } lista.setAdapter(adapter); lista.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent i = new Intent(getApplicationContext(), ListarUnCircuito.class); i.putExtra("idcircuito",currentViewPager); i.putExtra("position", position); i.putExtra("nombreCircuito", nombreCircuito); i.putExtra("nombreSubCircuito", titulo[position]); startActivity(i); overridePendingTransition(R.anim.fade_in, R.anim.fade_out); } }); } /******************* LISTVIEW ADAPTER **************************/ public class ListViewAdapter extends BaseAdapter { // Declare Variables Context context; int[] imagenes; String[] titulos; String[] contenido; LayoutInflater inflater; public ListViewAdapter(Context context, int[] imagenes, String[] titulos, String[] contenido ) { this.context = context; this.imagenes = imagenes; this.titulos = titulos; this.contenido = contenido; } @Override public int getCount() { return titulos.length; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { // Declare Variables ImageView imgImg; TextView txtTitle; TextView txtContenido; //http://developer.android.com/intl/es/reference/android/view/LayoutInflater.html inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View itemView = inflater.inflate(R.layout.single_post_circuito, parent, false); // Locate the TextViews in listview_item.xml imgImg = (ImageView) itemView.findViewById(R.id.imagen_single_post_circuito); txtTitle = (TextView) itemView.findViewById(R.id.tv_titulo_single_post_circuito); txtContenido = (TextView) itemView.findViewById(R.id.tv_contenido_single_post_circuito); // Capture position and set to the TextViews imgImg.setImageResource(imagenes[position]); txtTitle.setText(titulos[position]); txtContenido.setText(contenido[position]); return itemView; } } }
package by.epam.gomel.trening; import by.epam.gomel.trening.Expression; import by.epam.gomel.trening.Settings; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; @RunWith(Parameterized.class) public class TestExpression { private double a; private double b; private double c; private double z; public TestExpression(double a, double b, double c, double z) { this.a = a; this.b = b; this.c = c; this.z = z; } @Parameterized.Parameters public static Collection addedNumbers(){ return Arrays.asList(new Double[][] { {1.1, 2.2, 3.3, 1.21}, {1.0, 2.0, 3.0, 1.0}, {2.4, 4.5, 6.7, 5.35}, }); } @Test public void testFindExpression(){ Assert.assertEquals(new Expression().findExpression(new Settings(a, b, c)), z, 0.0001); } }
package com.tencent.mm.plugin.account.ui; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.plugin.account.ui.BindFacebookUI.a; class BindFacebookUI$3 implements OnClickListener { final /* synthetic */ BindFacebookUI ePD; BindFacebookUI$3(BindFacebookUI bindFacebookUI) { this.ePD = bindFacebookUI; } public final void onClick(View view) { BindFacebookUI.c(this.ePD).a(this.ePD, FacebookAuthUI.eQb, new a(this.ePD, (byte) 0)); } }
package com.cn.jingfen.serviceimpl; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cn.jingfen.mapper.GridMapper; import com.cn.jingfen.mapper.RealGridMapper; import com.cn.jingfen.service.GridService; import com.cn.jingfen.service.RealGridService; import com.cn.jingfen.vo.Grid; @Service("realgridService") public class RealGridServiceImp implements RealGridService { @Autowired private RealGridMapper gridMapper; @Override public List selectGrid4infoo1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selectGrid4infoo1(map); } @Override public List selectGrid4infoo2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selectGrid4infoo2(map); } @Override public List selectGrid4infoo3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selectGrid4infoo3(map); } @Override public List selectGrid4infoo4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selectGrid4infoo4(map); } @Override public List selectGridTest1(Map<String,Object> map) { // TODO Auto-generated method stub return gridMapper.selctGridtest1(map); } @Override public List selectGridTest2(Map<String,Object> map) { // TODO Auto-generated method stub return gridMapper.selctGridtest2(map); } @Override public List selectGridTest3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGridtest3(map); } @Override public List selectGridTest4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGridtest4(map); } @Override public List selectGrid1info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid1rb1(map); } @Override public List selectGrid1info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid1rb2(map); } @Override public List selectGrid1info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid1rb3(map); } @Override public List selectGrid1info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid1rb4(map); } @Override public List selectGrid2info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid2rb1(map); } @Override public List selectGrid2info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid2rb2(map); } @Override public List selectGrid2info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid2rb3(map); } @Override public List selectGrid2info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid2rb4(map); } @Override public List selectGrid3info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid3rb1(map); } @Override public List selectGrid3info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid3rb2(map); } @Override public List selectGrid3info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid3rb3(map); } @Override public List selectGrid3info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid3rb4(map); } @Override public List selectGrid4info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid4rb1(map); } @Override public List selectGrid4info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid4rb2(map); } @Override public List selectGrid4info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid4rb3(map); } @Override public List selectGrid4info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid4rb4(map); } @Override public List selectGrid5info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid5rb1(map); } @Override public List selectGrid5info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid5rb2(map); } @Override public List selectGrid5info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid5rb3(map); } @Override public List selectGrid5info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid5rb4(map); } @Override public List selectGrid6info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid6rb1(map); } @Override public List selectGrid6info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid6rb2(map); } @Override public List selectGrid6info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid6rb3(map); } @Override public List selectGrid6info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid6rb4(map); } @Override public List selectGrid7info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid7rb1(map); } @Override public List selectGrid7info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid7rb2(map); } @Override public List selectGrid7info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid7rb3(map); } @Override public List selectGrid7info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid7rb4(map); } @Override public List selectGrid8info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid8rb1(map); } @Override public List selectGrid8info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid8rb2(map); } @Override public List selectGrid8info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid8rb3(map); } @Override public List selectGrid8info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid8rb4(map); } @Override public List selectGrid9info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid9rb1(map); } @Override public List selectGrid9info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid9rb2(map); } @Override public List selectGrid9info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid9rb3(map); } @Override public List selectGrid9info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid9rb4(map); } @Override public List selectGrid10info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid10rb1(map); } @Override public List selectGrid10info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid10rb2(map); } @Override public List selectGrid10info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid10rb3(map); } @Override public List selectGrid10info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid10rb4(map); } @Override public List selectGrid11info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid11rb1(map); } @Override public List selectGrid11info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid11rb2(map); } @Override public List selectGrid11info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid11rb3(map); } @Override public List selectGrid11info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid11rb4(map); } @Override public List selectGrid12info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid12rb1(map); } @Override public List selectGrid12info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid12rb2(map); } @Override public List selectGrid12info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid12rb3(map); } @Override public List selectGrid12info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid12rb4(map); } @Override public List selectGrid13info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid13rb1(map); } @Override public List selectGrid13info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid13rb2(map); } @Override public List selectGrid13info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid13rb3(map); } @Override public List selectGrid13info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid13rb4(map); } @Override public List selectGrid14info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid14rb1(map); } @Override public List selectGrid14info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid14rb2(map); } @Override public List selectGrid14info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid14rb3(map); } @Override public List selectGrid14info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid14rb4(map); } @Override public List selectGrid15info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid15rb1(map); } @Override public List selectGrid15info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid15rb2(map); } @Override public List selectGrid15info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid15rb3(map); } @Override public List selectGrid15info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid15rb4(map); } @Override public List selectGrid16info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid16rb1(map); } @Override public List selectGrid16info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid16rb2(map); } @Override public List selectGrid16info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid16rb3(map); } @Override public List selectGrid16info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid16rb4(map); } @Override public List selectGrid17info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid17rb1(map); } @Override public List selectGrid17info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid17rb2(map); } @Override public List selectGrid17info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid17rb3(map); } @Override public List selectGrid17info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid17rb4(map); } @Override public List selectGrid18info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid18rb1(map); } @Override public List selectGrid18info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid18rb2(map); } @Override public List selectGrid18info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid18rb3(map); } @Override public List selectGrid18info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid18rb4(map); } @Override public List selectGrid19info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid19rb1(map); } @Override public List selectGrid19info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid19rb2(map); } @Override public List selectGrid19info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid19rb3(map); } @Override public List selectGrid19info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid19rb4(map); } @Override public List selectGrid20info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid20rb1(map); } @Override public List selectGrid20info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid20rb2(map); } @Override public List selectGrid20info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid20rb3(map); } @Override public List selectGrid20info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid20rb4(map); } @Override public List selectGrid21info1(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid21rb1(map); } @Override public List selectGrid21info2(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid21rb2(map); } @Override public List selectGrid21info3(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid21rb3(map); } @Override public List selectGrid21info4(Map<String, Object> map) { // TODO Auto-generated method stub return gridMapper.selctGrid21rb4(map); } }
package gov.samhsa.c2s.pcm.service; import gov.samhsa.c2s.pcm.service.dto.ConsentAttestationDto; import gov.samhsa.c2s.pcm.service.dto.ConsentDto; import gov.samhsa.c2s.pcm.service.dto.ConsentRevocationDto; import gov.samhsa.c2s.pcm.service.dto.ConsentTermDto; import gov.samhsa.c2s.pcm.service.dto.DetailedConsentDto; import gov.samhsa.c2s.pcm.service.dto.SensitivityCategoryDto; import gov.samhsa.c2s.pcm.service.dto.XacmlRequestDto; import org.springframework.data.domain.Page; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; public interface ConsentService { @Transactional(readOnly = true) Page<DetailedConsentDto> getConsents(String patientId, Optional<Long> purposeOfUse, Optional<Long> fromProvider, Optional<Long> toProvider, Optional<Integer> page, Optional<Integer> size); @Transactional void saveConsent(String patientId, ConsentDto consentDto, Optional<String> createdBy, Optional<Boolean> createdByPatient); @Transactional void softDeleteConsent(String patientId, Long consentId, Optional<String> lastUpdatedBy); @Transactional void updateConsent(String patientId, Long consentId, ConsentDto consentDto, Optional<String> lastUpdatedBy, Optional<Boolean> updatedByPatient); @Transactional void attestConsent(String patientId, Long consentId, ConsentAttestationDto consentAttestationDto, Optional<String> attestedBy, Optional<Boolean> attestedByPatient); @Transactional void revokeConsent(String patientId, Long consentId, ConsentRevocationDto consentRevocationDto, Optional<String> revokedBy, Optional<Boolean> revokedByPatient); @Transactional(readOnly = true) Object getConsent(String patientId, Long consentId, String format); @Transactional(readOnly = true) Object getAttestedConsent(String patientId, Long consentId, String format); @Transactional(readOnly = true) Object getRevokedConsent(String patientId, Long consentId, String format); @Transactional(readOnly = true) ConsentTermDto getConsentAttestationTerm(Optional<Long> id); @Transactional(readOnly = true) ConsentTermDto getConsentRevocationTerm(Optional<Long> id); @Transactional(readOnly = true) List<SensitivityCategoryDto> getSharedSensitivityCategories(String patientId, Long consentId); @Transactional(readOnly = true) DetailedConsentDto searchConsent(XacmlRequestDto xacmlRequestDto); }
package services; import models.FootballClub; import models.Match; import models.SchoolFootballClub; import models.UniversityFootballClub; import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class PremierLeagueManager implements LeagueManager { private static PremierLeagueManager instance; private List<FootballClub> footballClubs = new ArrayList<>(); private List<Match> allMatches = new ArrayList<>(); public static PremierLeagueManager getInstance(){ if (instance == null ){ instance = new PremierLeagueManager(); } return instance; } public List<FootballClub> getFootballClubs() { return this.footballClubs; } public List<Match> getAllMatches() { return this.allMatches; } @Override public void addFootballClub(FootballClub footballClub) { // checking progress of if the team name is already taken for(FootballClub footballClub1 : getFootballClubs()){ if (footballClub1.getClubName().toLowerCase().equals(footballClub.getClubName().toLowerCase())){ System.out.println("Club Name is Already Taken !"); return; } } // if name is not same then getFootballClubs().add(footballClub); System.out.println("Successfully added the club "); saveToFile(); } @Override public void deleteFootballClub(String clubName) { /** * #resource link * https://www.geeksforgeeks.org/arraylist-removeif-method-in-java/ */ // checking if the football clubs list empty or not if empty then return from the method if (getFootballClubs().isEmpty()){ System.out.println("No Clubs yet !"); return; } // here used removeIf and it checks whether is it there, then delete and give msg or else give no msg if (!footballClubs.removeIf(footballClub -> footballClub.getClubName().toLowerCase().equals(clubName.toLowerCase()))){ System.out.println("No such Club as "+clubName); }else{ System.out.println("Successfully Deleted"); saveToFile(); } } @Override public void displayStatistics(String clubName) { // checks if the football clubs list empty or not if empty then return from the method if (getFootballClubs().isEmpty()){ System.out.println("No Clubs yet !"); return; } boolean checker = false; // this for the availability of club // loop through all the clubs checks for available for (FootballClub footballClub : getFootballClubs()){ if (footballClub.getClubName().toLowerCase().equals(clubName.toLowerCase())){ System.out.println(footballClub.toString()); checker = true; // set true because it available } } // if the given name not found this msg will display in console if (!checker){ System.out.println("No such club as "+clubName); } } @Override public void displayLeagueTable(String choice) { /** * # comparator and comparable interface * #resource link * https://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/ */ // checks if the football clubs list empty or not if empty then return from the method if (getFootballClubs().isEmpty()){ System.out.println("No Clubs yet !"); return; } Collections.sort(getFootballClubs(), Collections.reverseOrder()); // sort the list // loop all football clubs from football clubs list according to the choice System.out.printf("%25s%4s%4s%4s%4s%6s%6s%n","Club Name","PL","W","D","L","G","P"); switch (choice){ case "S": case "s": for (FootballClub footballClub : getFootballClubs()){ if (footballClub instanceof SchoolFootballClub){ System.out.printf("%25s%4d%4d%4d%4d%6d%6d%n",footballClub.getClubName(), footballClub.getNumOfMatchPlayed(),footballClub.getNumOfWins(),footballClub.getNumOfDraws(), footballClub.getNumOfDefeats(),footballClub.getGoalScored(),footballClub.getPoints()); } } break; case "U": case "u": for (FootballClub footballClub : getFootballClubs()){ if (footballClub instanceof UniversityFootballClub){ System.out.printf("%25s%4d%4d%4d%4d%6d%6d%n",footballClub.getClubName(), footballClub.getNumOfMatchPlayed(),footballClub.getNumOfWins(),footballClub.getNumOfDraws(), footballClub.getNumOfDefeats(),footballClub.getGoalScored(),footballClub.getPoints()); } } break; } } @Override public void addPlayedMatch(Match match) { boolean opponentWin = false; // this is check if opponent team win or not boolean opponentDefeat = false; // this is check if opponent team defeat or not boolean homeChecker = false; // this is check if home team exist in league boolean opponentChecker = false; // this is check if opponent team exist in league String homeClubType = null; // this is set the home team club type whether school or uni String opponentClubType = null; // this is set the opponent team club type boolean clubChecker = false; // this check whether both teams are same type or not // loop through football clubs list for check both teams are exist set the club types for (FootballClub footballClub : footballClubs){ if (footballClub.getClubName().toLowerCase().equals(match.getHomeTeam().toLowerCase())){ if (footballClub instanceof SchoolFootballClub){ homeClubType = "scl"; // updating club types }else if (footballClub instanceof UniversityFootballClub){ homeClubType = "uni"; // updating club types } homeChecker = true; // if home club exist then set to true // checks about the opponent team exist and its type for (FootballClub footballClub1 : footballClubs){ if (footballClub1.getClubName().toLowerCase().equals(match.getOpponentTeam().toLowerCase())){ if (footballClub1 instanceof SchoolFootballClub){ opponentClubType = "scl"; }else if (footballClub1 instanceof UniversityFootballClub){ opponentClubType = "uni"; } opponentChecker = true; } } if (homeClubType.equals(opponentClubType)){ clubChecker = true; // checks if both clubs are in same type and if true set it to true } // if home or opponent or club types are not match then return from the method if (!opponentChecker || !homeChecker || !clubChecker){ System.out.println("Something wrong check both clubs are registered in league"); return; } // checks the win team and update their statistics footballClub.setGoalScored(match.getHomeScore()); footballClub.setNumOfMatchPlayed(); if (match.getHomeScore() > match.getOpponentScore()){ footballClub.setNumOfWins(); footballClub.setPoints(3); opponentDefeat = true; }else if (match.getHomeScore() < match.getOpponentScore()){ footballClub.setNumOfDefeats(); opponentWin = true; }else{ footballClub.setNumOfDraws(); footballClub.setPoints(1); } } } // again same thing for opponent team for (FootballClub footballClub : footballClubs){ if (footballClub.getClubName().toLowerCase().equals(match.getOpponentTeam().toLowerCase())){ opponentChecker = true; for(FootballClub footballClub1 : footballClubs){ if (footballClub1.getClubName().toLowerCase().equals(match.getHomeTeam().toLowerCase())){ homeChecker = true; } } if (!opponentChecker || !homeChecker || !clubChecker){ System.out.println("Something wrong check both clubs are registered in league"); return; } footballClub.setGoalScored(match.getOpponentScore()); footballClub.setNumOfMatchPlayed(); if (opponentWin){ footballClub.setNumOfWins(); footballClub.setPoints(3); }else if (opponentDefeat){ footballClub.setNumOfDefeats(); }else { footballClub.setNumOfDraws(); footballClub.setPoints(1); } } } // finally added to the all matches list if (homeChecker && opponentChecker){ allMatches.add(match); saveToFile(); System.out.println("successfully added match"); } } @Override public void saveToFile() { // all football clubs to the file //create the file or get existing file for write try { FileOutputStream footballClubsFile = new FileOutputStream("football_clubs.txt"); ObjectOutputStream footballClubObjects = new ObjectOutputStream(footballClubsFile); //using for loop write all football objects to the file for (FootballClub footballClub: footballClubs){ footballClubObjects.writeObject(footballClub); // writing progress } System.out.println("Clubs data has been added to file"); }catch (Exception e){ System.err.println("Error Occurred!"); } /*all Matches to the file*/ try { FileOutputStream matchesFile = new FileOutputStream("matches.txt"); ObjectOutputStream matchObjects = new ObjectOutputStream(matchesFile); for (Match match : allMatches){ matchObjects.writeObject(match); } System.out.println("Matches data has been added to File"); }catch (Exception e){ System.err.println("Error Occurred!"); } } @Override public void loadFromFile() { /** * #infinite for loop * # InputStream#readObject * #resourse link * https://www.baeldung.com/infinite-loops-java * https://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html#readObject() */ // checks if the file is empty, if true then return File club_data = new File("football_clubs.txt"); if (club_data.length() == 0){ System.out.println("File is Empty"); return; } /*football club objects to arrayList*/ // setting the path for read objects to file try { FileInputStream footballClubFile = new FileInputStream("football_clubs.txt"); ObjectInputStream football_clubs = new ObjectInputStream(footballClubFile); // using infinite for loop read all objects to football clubs list for (;;){ try { footballClubs.add((FootballClub)football_clubs.readObject()); }catch (Exception e){ break; } } }catch (Exception e){ System.err.println("Error Occurred!"); } System.out.println("Club data loaded"); File match_data = new File("matches.txt"); if (match_data.length() == 0){ System.out.println("File is Empty"); return; } /*match objects to arrayList*/ try{ FileInputStream matchesFile = new FileInputStream("matches.txt"); ObjectInputStream matches = new ObjectInputStream(matchesFile); for (;;){ try{ allMatches.add((Match)matches.readObject()); }catch (Exception e){ break; } } }catch (Exception e){ System.err.println("Error Occurred!"); } System.out.println("Match data loaded"); } // open gui from console @Override public void gui(){ try{ ProcessBuilder builder = new ProcessBuilder(); // creating the process builder builder.command("cmd.exe","/c", "sbt run"); // give the command to run play Process process = builder.start(); // start the process System.out.println("Please wait...."); // give msg to console System.out.println("GUI will automatically open"); }catch (Exception e){ e.printStackTrace(); } } }
package com.summer.dao.demo.datasource.config; /** * ๆ•ฐๆฎๆบๆžšไธพ * * @author luke * @date 2019/06/03 */ public enum DataSourceEnum { MASTER, SLAVE }
package com.tencent.mm.plugin.location.ui.impl; import android.content.Intent; import android.view.MenuItem; import com.tencent.mm.bg.d; import com.tencent.mm.plugin.fav.a.b; import com.tencent.mm.plugin.fav.a.h; import com.tencent.mm.plugin.location.model.e; import com.tencent.mm.plugin.map.a; import com.tencent.mm.ui.base.n$d; class i$2 implements n$d { final /* synthetic */ i kKy; i$2(i iVar) { this.kKy = iVar; } public final void onMMMenuItemSelected(MenuItem menuItem, int i) { Intent intent; switch (menuItem.getItemId()) { case 0: this.kKy.baq(); return; case 1: if (this.kKy.type == 2) { h.f(this.kKy.activity.getIntent().getLongExtra("kFavInfoLocalId", -1), 1, 0); } intent = new Intent(); intent.putExtra("Retr_Msg_content", e.a(this.kKy.kHP)); intent.putExtra("Retr_Msg_Type", 9); d.e(this.kKy.activity, ".ui.transmit.MsgRetransmitUI", intent); return; case 2: this.kKy.bNP = 0; this.kKy.bas(); return; case 3: this.kKy.bar(); return; case 4: com.tencent.mm.ui.base.h.a(this.kKy.activity, this.kKy.activity.getString(a.h.app_delete_tips), "", new 1(this), null); return; case 5: long longExtra = this.kKy.activity.getIntent().getLongExtra("kFavInfoLocalId", -1); Intent intent2 = new Intent(); intent2.putExtra("key_fav_item_id", longExtra); intent2.putExtra("key_fav_scene", 2); b.a(this.kKy.activity, ".ui.FavTagEditUI", intent2); return; case 6: intent = new Intent(); intent.putExtra("Retr_Msg_content", e.a(this.kKy.kHP)); intent.putExtra("Retr_Msg_Id", this.kKy.bJC); d.e(this.kKy.activity, ".ui.chatting.ChattingSendDataToDeviceUI", intent); return; default: return; } } }
/* * JBoss, Home of Professional Open Source * * Copyright 2012 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.xnio.nativeimpl; import static org.xnio.Bits.allAreSet; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; /** * Integer-indexed hash map. * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ final class EPollMap extends AbstractCollection<EPollRegistration> { private static final int DEFAULT_INITIAL_CAPACITY = 512; private static final int MAXIMUM_CAPACITY = 1 << 30; private static final float DEFAULT_LOAD_FACTOR = 0.60f; private final float loadFactor; private final int initialCapacity; private EPollRegistration[][] table; int size; int threshold; EPollMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); } /** * Construct a new instance. * * @param initialCapacity the initial capacity * @param loadFactor the load factor */ EPollMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) { throw new IllegalArgumentException("Initial capacity must be > 0"); } if (initialCapacity > MAXIMUM_CAPACITY) { initialCapacity = MAXIMUM_CAPACITY; } if (loadFactor <= 0.0 || Float.isNaN(loadFactor) || loadFactor >= 1.0) { throw new IllegalArgumentException("Load factor must be between 0.0f and 1.0f"); } int capacity = 1; while (capacity < initialCapacity) { capacity <<= 1; } this.loadFactor = loadFactor; this.initialCapacity = capacity; threshold = (int) (capacity * loadFactor); table = new EPollRegistration[capacity][]; } public EPollRegistration putIfAbsent(final EPollRegistration value) { return doPut(value, true); } public EPollRegistration removeKey(final int index) { return doRemove(index); } public boolean remove(final Object value) { return value instanceof EPollRegistration && doRemove((EPollRegistration) value); } public boolean remove(final EPollRegistration value) { return value != null && doRemove(value); } public boolean containsKey(final int index) { return doGet(index) != null; } public EPollRegistration get(final int index) { return doGet(index); } public EPollRegistration put(final EPollRegistration value) { if (value == null) { throw new IllegalArgumentException("value is null"); } return doPut(value, false); } public EPollRegistration replace(final EPollRegistration value) { if (value == null) { throw new IllegalArgumentException("value is null"); } return doReplace(value); } public boolean replace(final EPollRegistration oldValue, final EPollRegistration newValue) { if (newValue == null) { throw new IllegalArgumentException("newValue is null"); } if (oldValue.id != newValue.id) { throw new IllegalArgumentException("Can only replace with value which has the same key"); } return doReplace(oldValue, newValue); } public int getKey(final EPollRegistration argument) { return argument.id; } public boolean add(final EPollRegistration value) { if (value == null) { throw new IllegalArgumentException("value is null"); } return doPut(value, true) == null; } @SuppressWarnings("unchecked") public <T> T[] toArray(final T[] a) { final T[] target; if (a.length < size) { target = Arrays.copyOfRange(a, a.length, a.length + size); } else { target = a; } int i = 0; for (final EPollRegistration[] row : table) { if (row != null) { for (EPollRegistration item : row) { if (item != null) { target[i++] = (T) item; } } } } return target; } public Object[] toArray() { final ArrayList<Object> list = new ArrayList<Object>(size()); list.addAll(this); return list.toArray(); } public boolean contains(final Object o) { return o instanceof EPollRegistration && o == get(((EPollRegistration) o).id); } public Iterator<EPollRegistration> iterator() { return new EntryIterator(); } public int size() { return size; } private boolean doReplace(final EPollRegistration oldValue, final EPollRegistration newValue) { if (oldValue.id != newValue.id) { return false; } EPollRegistration[][] table = this.table; final int idx = oldValue.id & table.length - 1; EPollRegistration[] row = table[idx]; if (row == null) { return false; } int rowLength = row.length; for (int i = 0; i < rowLength; i++) { EPollRegistration item = row[i]; if (item != null && item == oldValue) { row[i] = newValue; return true; } } return false; } private EPollRegistration doReplace(final EPollRegistration value) { EPollRegistration[][] table = this.table; final int idx = value.id & table.length - 1; EPollRegistration[] row = table[idx]; if (row == null) { return null; } int rowLength = row.length; for (int i = 0; i < rowLength; i++) { EPollRegistration item = row[i]; if (item != null && item.id == value.id) { row[i] = value; return item; } } return null; } private boolean doRemove(final EPollRegistration value) { EPollRegistration[][] table = this.table; final int idx = value.id & table.length - 1; EPollRegistration[] row = table[idx]; if (row == null) { return false; } int rowLength = row.length; for (int i = 0; i < rowLength; i++) { EPollRegistration item = row[i]; if (item != null && item == value) { row[i] = null; size--; return true; } } return false; } private EPollRegistration doRemove(final int key) { EPollRegistration[][] table = this.table; final int idx = key & table.length - 1; EPollRegistration[] row = table[idx]; if (row == null) { return null; } int rowLength = row.length; for (int i = 0; i < rowLength; i++) { EPollRegistration item = row[i]; if (item != null && item.id == key) { row[i] = null; size--; return item; } } return null; } private EPollRegistration doPut(EPollRegistration value, boolean ifAbsent) { final int hashCode = value.id; EPollRegistration[][] table = this.table; final int idx = hashCode & table.length - 1; EPollRegistration[] row = table[idx]; if (row == null) { if (grow()) { table = this.table; } table[idx] = new EPollRegistration[3]; table[idx][0] = value; return null; } int s = -1; int rowLength = row.length; for (int i = 0; i < rowLength; i++) { EPollRegistration item = row[i]; if (item == null) { if (s == -1) { s = i; } } else if (item.id == value.id) { if (! ifAbsent) { row[i] = value; } return item; } } // Search again when grown if (grow()) { return doPut(value, ifAbsent); } if (s != -1) { row[s] = value; return null; } row = Arrays.copyOf(row, rowLength + 2); row[rowLength] = value; table[idx] = row; return null; } private boolean grow() { if (size == Integer.MAX_VALUE) { throw new IllegalStateException("Table full"); } if (size ++ < threshold || threshold == Integer.MAX_VALUE) { return false; } final EPollRegistration[][] oldTable = table; final int oldLen = oldTable.length; assert Integer.bitCount(oldLen) == 1; final EPollRegistration[][] newTable = Arrays.copyOf(oldTable, oldLen << 1); for (int i = 0; i < oldLen; i++) { EPollRegistration[] row = newTable[i]; if (row != null) { EPollRegistration[] newRow = row.clone(); newTable[i + oldLen] = newRow; final int rowLen = row.length; for (int j = 0; j < rowLen; j++) { final EPollRegistration item = row[j]; if (item != null) { if (allAreSet(item.id, oldLen)) { row[j] = null; } else { newRow[j] = null; } } } } } table = newTable; threshold = (int) (newTable.length * loadFactor); return true; } private EPollRegistration doGet(final int key) { final EPollRegistration[][] table = this.table; int idx = key & (table.length - 1); final EPollRegistration[] row = table[idx]; if (row != null) for (EPollRegistration item : row) { if (item != null && key == item.id) { return item; } } return null; } public void clear() { table = new EPollRegistration[initialCapacity][]; size = 0; threshold = (int) (initialCapacity * loadFactor); } class EntryIterator implements Iterator<EPollRegistration> { int rowIdx; int itemIdx; EPollRegistration next; public boolean hasNext() { if (next == null) { while (rowIdx < table.length) { final EPollRegistration[] row = table[rowIdx]; if (row != null) { while (itemIdx < row.length) { final EPollRegistration item = row[itemIdx++]; if (item != null) { next = item; return true; } } itemIdx = 0; } rowIdx++; } return false; } else { return true; } } public EPollRegistration next() { if (! hasNext()) { throw new NoSuchElementException(); } try { return next; } finally { next = null; } } public void remove() { table[rowIdx][itemIdx - 1] = null; size--; } } }
package com.ybg.rbac.user.mapper; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.ybg.rbac.user.domain.User; public class UserMapper implements RowMapper<User> { public User mapRow(ResultSet rs, int index) throws SQLException { User user = new User(); user.setId(rs.getString("id")); user.setCreatetime(rs.getString("createtime")); user.setEmail(rs.getString("email")); user.setIsdelete(rs.getInt("isdelete")); user.setPassword(rs.getString("password")); user.setPhone(rs.getString("phone")); user.setState(rs.getString("state")); user.setUsername(rs.getString("username")); user.setRoleid(rs.getString("roleid")); user.setCredentialssalt(rs.getString("credentialssalt")); user.setRolename(rs.getString("rolename")); return user; } }
package com.example.homestay_kha.Model; import android.os.Parcel; import android.os.Parcelable; import androidx.annotation.NonNull; import com.example.homestay_kha.Controller.Interface.Tien_nghi_Interface; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class Tien_nghi_model implements Parcelable { private String id_tien_nghi, tentienich, hinhtienich; DatabaseReference databaseReference; public Tien_nghi_model(){ databaseReference = FirebaseDatabase.getInstance().getReference();} public Tien_nghi_model(String id_tien_nghi, String tentienich, String hinhtienich) { this.id_tien_nghi = id_tien_nghi; this.tentienich = tentienich; this.hinhtienich = hinhtienich; } protected Tien_nghi_model(Parcel in) { id_tien_nghi = in.readString(); tentienich = in.readString(); hinhtienich = in.readString(); } public static final Creator<Tien_nghi_model> CREATOR = new Creator<Tien_nghi_model>() { @Override public Tien_nghi_model createFromParcel(Parcel in) { return new Tien_nghi_model(in); } @Override public Tien_nghi_model[] newArray(int size) { return new Tien_nghi_model[size]; } }; public String getId_tien_nghi() { return id_tien_nghi; } public void setId_tien_nghi(String id_tien_nghi) { this.id_tien_nghi = id_tien_nghi; } public String getTentienich() { return tentienich; } public void setTentienich(String tentienich) { this.tentienich = tentienich; } public String getHinhtienich() { return hinhtienich; } public void setHinhtienich(String hinhtienich) { this.hinhtienich = hinhtienich; } public void getTienNghiModel(Tien_nghi_Interface tien_nghi_interface) { ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { DataSnapshot dataSnapshot_tiennghi_hotel = dataSnapshot.child("hotel").child("tienich"); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(id_tien_nghi); dest.writeString(tentienich); dest.writeString(hinhtienich); } }
package renderer.sub; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; public class TextElement { private String text; private int x; private int y; private Color color; private int size; public TextElement(String text, int x, int y, Color c, int size){ this.text = text; this.x = x; this.y = y; this.color = c; this.size = size; } public void render(Graphics g){ Font font = new Font("Franklin Gothic Demi", Font.PLAIN, size); g.setColor(color); g.setFont(font); g.drawString(text, x, y); } }
package com.youthchina.controller; /* @RunWith(SpringRunner.class) @SpringBootTest @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class, TransactionalTestExecutionListener.class}) @DatabaseSetup({"classpath:recommendation.xml"}) @WebAppConfiguration public class HomeControllerTest { @Autowired private WebApplicationContext context; @Autowired private ApplicationContext applicationContext; @Value("${web.url.prefix}") private String urlPrefix; private AuthGenerator authGenerator = new AuthGenerator(); MockMvc mvc; @Before public void setup() { this.mvc = MockMvcBuilders.webAppContextSetup(context).apply(SecurityMockMvcConfigurers.springSecurity()).build(); } @Test public void getNewJob() throws Exception { this.mvc.perform( get(this.urlPrefix + "/home/new") ).andDo(print()) .andExpect(status().is2xxSuccessful()) ; } @Test public void getHotJob() throws Exception { this.mvc.perform( get(this.urlPrefix + "/home/hot") ).andDo(print()) .andExpect(status().is2xxSuccessful()); } } */
package com.example.android.pokefinder; import com.example.android.pokefinder.data.Pokemon; import com.example.android.pokefinder.data.PokemonRepository; import com.example.android.pokefinder.data.Status; import androidx.lifecycle.LiveData; import androidx.lifecycle.ViewModel; public class PokemonViewModel extends ViewModel { private PokemonRepository mRepository; private LiveData<Pokemon> mSearchResults; private LiveData<Status> mLoadingStatus; public PokemonViewModel() { mRepository = new PokemonRepository(); mSearchResults = mRepository.getPokemon(); mLoadingStatus = mRepository.getLoadingStatus(); } public void resetStatus(){mRepository.resetStatus();} public void loadSearchResults(String query) { mRepository.loadPokemon(query); } public LiveData<Pokemon> getSearchResults() { return mSearchResults; } public LiveData<Status> getLoadingStatus() { return mLoadingStatus; } }
package com.chsoft.testng.cs; import java.io.File; import java.io.IOException; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriverService; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; /** * ่‡ชๅŠจๅŒ–ๆต‹่ฏ• * @author jacktomcat * */ public class SeleniumTest { private static ChromeDriverService service; private WebDriver driver; @BeforeClass public static void createAndStartService() throws IOException { System.setProperty("webdriver.chrome.driver", "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"); service = new ChromeDriverService.Builder().usingDriverExecutable(new File("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe")) .usingAnyFreePort().build(); service.start(); } @AfterClass public static void createAndStopService() { service.stop(); } @BeforeTest public void createDriver() { System.out.println(service.getUrl()); driver = new RemoteWebDriver(service.getUrl(), DesiredCapabilities.chrome()); } @AfterTest public void quitDriver() { driver.quit(); } @Test(invocationCount=1) public void testGoogleSearch() { driver.get("https://www.baidu.com"); WebElement searchBox = driver.findElement(By.id("kw")); searchBox.sendKeys("webdriver"); searchBox.submit(); Assert.assertEquals("webdriver - Google Search", driver.getTitle()); } }
package miggy.utils; import junit.framework.TestCase; // $Revision: 16 $ //TODO public class TextUtilTest extends TestCase { public TextUtilTest(String test) { super(test); } public void testDecodeRegList() { // int list = 0x00c0; // String s = TextUtil.decodeRegList(list, false); // assertEquals("Two together", "d6/d7", s); // // list = 0x03e0; // s = TextUtil.decodeRegList(list, false); // assertEquals("Two groups", "d5-d7/a0/a1", s); // // list = 0xc3e7; // s = TextUtil.decodeRegList(list, false); // assertEquals("Multiple groups", "d0-d2/d5-d7/a0/a1/a6/a7", s); // // //now in reverse mode // list = 0x00c0; // s = TextUtil.decodeRegList(list, true); // assertEquals("Reverse Two together", "a0/a1", s); // // list = 0x03e0; // s = TextUtil.decodeRegList(list, true); // assertEquals("Reverse Two groups", "d6/d7/a0-a2", s); // // list = 0xc3e7; // s = TextUtil.decodeRegList(list, true); // assertEquals("Reverse Multiple groups", "d0/d1/d6/d7/a0-a2/a5-a7", s); } }
package com.codeChallenge.dao; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Repository; import com.codeChallenge.model.User; /** * * @author Sara * */ @Repository @Qualifier("userDao") public class UserDaoImpl implements UserDao { @Autowired MongoTemplate mongoTemplate; final String COLLECTION = "users"; @Override public void add(User u) { mongoTemplate.insert(u); } @Override public void update(User u) { mongoTemplate.save(u); } @Override public void delete(User u) { mongoTemplate.remove(u); } @Override public List<User> getAll() { return mongoTemplate.findAll(User.class); } }
package org.newdawn.slick.tests; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame; import org.newdawn.slick.Color; import org.newdawn.slick.Game; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; public class ImageReadTest extends BasicGame { private Image image; private Color[] read = new Color[6]; private Graphics g; public ImageReadTest() { super("Image Read Test"); } public void init(GameContainer container) throws SlickException { this.image = new Image("testdata/testcard.png"); this.read[0] = this.image.getColor(0, 0); this.read[1] = this.image.getColor(30, 40); this.read[2] = this.image.getColor(55, 70); this.read[3] = this.image.getColor(80, 90); } public void render(GameContainer container, Graphics g) { this.g = g; this.image.draw(100.0F, 100.0F); g.setColor(Color.white); g.drawString("Move mouse over test image", 200.0F, 20.0F); g.setColor(this.read[0]); g.drawString(this.read[0].toString(), 100.0F, 300.0F); g.setColor(this.read[1]); g.drawString(this.read[1].toString(), 150.0F, 320.0F); g.setColor(this.read[2]); g.drawString(this.read[2].toString(), 200.0F, 340.0F); g.setColor(this.read[3]); g.drawString(this.read[3].toString(), 250.0F, 360.0F); if (this.read[4] != null) { g.setColor(this.read[4]); g.drawString("On image: " + this.read[4].toString(), 100.0F, 250.0F); } if (this.read[5] != null) { g.setColor(Color.white); g.drawString("On screen: " + this.read[5].toString(), 100.0F, 270.0F); } } public void update(GameContainer container, int delta) { int mx = container.getInput().getMouseX(); int my = container.getInput().getMouseY(); if (mx >= 100 && my >= 100 && mx < 200 && my < 200) { this.read[4] = this.image.getColor(mx - 100, my - 100); } else { this.read[4] = Color.black; } this.read[5] = this.g.getPixel(mx, my); } public static void main(String[] argv) { try { AppGameContainer container = new AppGameContainer((Game)new ImageReadTest()); container.setDisplayMode(800, 600, false); container.start(); } catch (SlickException e) { e.printStackTrace(); } } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\tests\ImageReadTest.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package mine_mine_loop; public class PrintChars { public static void main (String [] args){ String word = "python"; for(int i =0;i< word.length();i++){ System.out.println(word.charAt(i)); } System.out.println("**********REVERSE**************"); for(int i =word.length()-1 ;i>= 0;i--){ System.out.println(word.charAt(i)); } System.out.println("-------REVERSE 2--------"); word ="program"; for(int j= word.length()-1; j>=0; j--) { System.out.println(word.charAt(j)); } } }
package com.mysql.cj.protocol.a.authentication; import com.mysql.cj.protocol.AuthenticationPlugin; import com.mysql.cj.protocol.Message; import com.mysql.cj.protocol.Protocol; import com.mysql.cj.protocol.a.NativeConstants; import com.mysql.cj.protocol.a.NativePacketPayload; import com.mysql.cj.util.StringUtils; import java.io.UnsupportedEncodingException; import java.util.List; public class MysqlOldPasswordPlugin implements AuthenticationPlugin<NativePacketPayload> { private Protocol<NativePacketPayload> protocol; private String password = null; public void init(Protocol<NativePacketPayload> prot) { this.protocol = prot; } public void destroy() { this.password = null; } public String getProtocolPluginName() { return "mysql_old_password"; } public boolean requiresConfidentiality() { return false; } public boolean isReusable() { return true; } public void setAuthenticationParameters(String user, String password) { this.password = password; } public boolean nextAuthenticationStep(NativePacketPayload fromServer, List<NativePacketPayload> toServer) { toServer.clear(); NativePacketPayload bresp = null; String pwd = this.password; if (fromServer == null || pwd == null || pwd.length() == 0) { bresp = new NativePacketPayload(new byte[0]); } else { bresp = new NativePacketPayload(StringUtils.getBytes( newCrypt(pwd, fromServer.readString(NativeConstants.StringSelfDataType.STRING_TERM, null).substring(0, 8), this.protocol.getPasswordCharacterEncoding()))); bresp.setPosition(bresp.getPayloadLength()); bresp.writeInteger(NativeConstants.IntegerDataType.INT1, 0L); bresp.setPosition(0); } toServer.add(bresp); return true; } private static String newCrypt(String password, String seed, String encoding) { if (password == null || password.length() == 0) return password; long[] pw = newHash(seed.getBytes()); long[] msg = hashPre41Password(password, encoding); long max = 1073741823L; long seed1 = (pw[0] ^ msg[0]) % max; long seed2 = (pw[1] ^ msg[1]) % max; char[] chars = new char[seed.length()]; int i; for (i = 0; i < seed.length(); i++) { seed1 = (seed1 * 3L + seed2) % max; seed2 = (seed1 + seed2 + 33L) % max; double d1 = seed1 / max; byte b1 = (byte)(int)Math.floor(d1 * 31.0D + 64.0D); chars[i] = (char)b1; } seed1 = (seed1 * 3L + seed2) % max; seed2 = (seed1 + seed2 + 33L) % max; double d = seed1 / max; byte b = (byte)(int)Math.floor(d * 31.0D); for (i = 0; i < seed.length(); i++) chars[i] = (char)(chars[i] ^ (char)b); return new String(chars); } private static long[] hashPre41Password(String password, String encoding) { try { return newHash(password.replaceAll("\\s", "").getBytes(encoding)); } catch (UnsupportedEncodingException e) { return new long[0]; } } private static long[] newHash(byte[] password) { long nr = 1345345333L; long add = 7L; long nr2 = 305419889L; for (byte b : password) { long tmp = (0xFF & b); nr ^= ((nr & 0x3FL) + add) * tmp + (nr << 8L); nr2 += nr2 << 8L ^ nr; add += tmp; } long[] result = new long[2]; result[0] = nr & 0x7FFFFFFFL; result[1] = nr2 & 0x7FFFFFFFL; return result; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\protocol\a\authentication\MysqlOldPasswordPlugin.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.company.tpReverse; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class Worker extends Thread { Socket socket = null; BufferedReader fin = null; PrintWriter fout = null; public String reverse(String line){ return new StringBuilder(line).reverse().toString(); } public Worker(Socket s){ socket = s; } @Override public void run() { try { fin = new BufferedReader(new InputStreamReader(socket.getInputStream())); fout = new PrintWriter(socket.getOutputStream(), true); fout.println("bonjour , bienvenue dans le Tp Reverse String"); System.out.println(socket.getInetAddress()+" s'est connectรฉ"); boolean done = false; while(!done) { String msg = fin.readLine(); if(msg.isEmpty()) { done = true; fout.println("deconnexion"); }else { fout.println("inversรฉ : "+reverse(msg)); System.out.println(socket.getInetAddress()+" a ecrit : "+msg+" et inversรฉ en : "+reverse(msg)); } } System.out.println(socket.getInetAddress()+" s'est dรฉconnectรฉ"); socket.close(); }catch (Exception e){ e.printStackTrace(); } } }
package com.vetroumova.sixjars.ui; import android.Manifest; import android.app.Activity; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.VectorDrawable; import android.os.Bundle; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.graphics.drawable.VectorDrawableCompat; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatDelegate; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.animation.AlphaAnimation; import android.widget.FrameLayout; import android.widget.Toast; import com.aurelhubert.ahbottomnavigation.AHBottomNavigation; import com.aurelhubert.ahbottomnavigation.AHBottomNavigationItem; import com.vetroumova.sixjars.R; import com.vetroumova.sixjars.app.Prefs; import com.vetroumova.sixjars.database.RealmManager; import com.vetroumova.sixjars.ui.fragments.AddCashFragment; import com.vetroumova.sixjars.ui.fragments.CashInfoFragment; import com.vetroumova.sixjars.ui.fragments.HelpFragment; import com.vetroumova.sixjars.ui.fragments.JarInfoFragment; import com.vetroumova.sixjars.ui.fragments.RecyclerFragment; import com.vetroumova.sixjars.ui.fragments.SettingsFragment; import com.vetroumova.sixjars.ui.fragments.ShareFragment; import com.vetroumova.sixjars.ui.fragments.SpendFragment; import com.vetroumova.sixjars.ui.fragments.StatisticsFragment; import com.vetroumova.sixjars.ui.widget.JarsWidget; import com.vetroumova.sixjars.utils.DebugLogger; import com.vk.sdk.VKAccessToken; import com.vk.sdk.VKCallback; import com.vk.sdk.VKSdk; import com.vk.sdk.api.VKApi; import com.vk.sdk.api.VKApiConst; import com.vk.sdk.api.VKError; import com.vk.sdk.api.VKParameters; import com.vk.sdk.api.VKRequest; import com.vk.sdk.api.VKResponse; import com.vk.sdk.api.model.VKApiLink; import com.vk.sdk.api.model.VKApiPhoto; import com.vk.sdk.api.model.VKAttachments; import com.vk.sdk.api.model.VKPhotoArray; import com.vk.sdk.api.photo.VKImageParameters; import com.vk.sdk.api.photo.VKUploadImage; import java.util.Locale; import rx.Subscription; import rx.subscriptions.CompositeSubscription; import static android.content.Intent.FLAG_ACTIVITY_NO_HISTORY; public class MainActivity extends AppCompatActivity { // Storage Permissions private static final int REQUEST_EXTERNAL_STORAGE = 810; private static final int GOOGLEPLUS_REQUEST_CODE = 1001; private static final String TAG = "VOlga"; private static String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }; private static long back_pressed; FrameLayout contentLayout; AHBottomNavigation bottomNavigation; AHBottomNavigationItem itemSettings; AHBottomNavigationItem itemStatistics; AHBottomNavigationItem itemTutorial; AHBottomNavigationItem itemAbout; AlphaAnimation animationDisapear; AlphaAnimation animationGetVisible; private LinearLayoutManager layoutManager; private Subscription jarInRecyclerSubscription; private Subscription cashClickSubscription; private Subscription finishEditCashSubscription; private Subscription cashDeleteSubscription; private Subscription spendCashInJar; private Subscription finishSpendCashSubscription; private CompositeSubscription subscriptions = new CompositeSubscription(); //private List<String> mockItems = new ArrayList<>(); private int[] colors = {R.color.colorPrimary, R.color.colorAccent, R.color.colorPrimaryLight, R.color.colorPrimaryDark}; private FloatingActionButton fab; //Fragments private FragmentManager fragmentManager; private RecyclerFragment recyclerFragment; private JarInfoFragment jarInfoFragment; private SettingsFragment settingsFragment; private StatisticsFragment statisticsFragment; private HelpFragment helpFragment; private AddCashFragment addCashFragment; private SpendFragment spendFragment; private CashInfoFragment cashInfoFragment; private ShareFragment shareFragment; private int menuItem = 0; public static Bitmap getBitmapFromDrawable(Context context, @DrawableRes int drawableId) { Drawable drawable = ContextCompat.getDrawable(context, drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof VectorDrawable || drawable instanceof VectorDrawableCompat) { /*Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);*/ Bitmap bitmap = Bitmap.createBitmap(300, 400, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } else { throw new IllegalArgumentException("unsupported drawable type"); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //todo check if needed AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //WindowManager.LayoutParams params = getWindow().getAttributes(); //params.rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_ROTATE; //params.rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_CROSSFADE; //getWindow().setAttributes(params); fragmentManager = getSupportFragmentManager(); //recyclerFragment = new RecyclerFragment(); recyclerFragment = RecyclerFragment.newInstance(); fab = (FloatingActionButton) findViewById(R.id.fab); animationDisapear = new AlphaAnimation(1, 0); animationGetVisible = new AlphaAnimation(0, 1); animationDisapear.setDuration(500); animationDisapear.setStartOffset(100); animationDisapear.setFillAfter(true); animationGetVisible.setDuration(500); animationGetVisible.setStartOffset(200); animationGetVisible.setFillAfter(true); //fab.setAnimation(animation1); //add new income fab.setOnClickListener(view -> { fab.startAnimation(animationDisapear); DebugLogger.log("DebugLogger"); Log.d(TAG, "FAB"); addCashFragment = AddCashFragment.newInstance(); fragmentManager.beginTransaction() .replace(R.id.content_layout, addCashFragment) /*.setCustomAnimations(android.R.animator .fade_in, android.R.animator.fade_out)*/ .addToBackStack("addCash") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); fab.hide(); }); //set toolbar Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar); toolbar.setLogo(R.mipmap.ic_launcher); setSupportActionBar(toolbar); //getSupportActionBar().setLogo(R.mipmap.ic_launcher); contentLayout = (FrameLayout) findViewById(R.id.content_layout); bottomNavigation = (AHBottomNavigation) findViewById(R.id.bottom_navigation); itemSettings = new AHBottomNavigationItem(getString(R.string.action_settings), R.drawable.ic_settings_white_24dp); itemStatistics = new AHBottomNavigationItem(getString(R.string.statistics_text), R.drawable.ic_statistics_chart_white_24dp); itemTutorial = new AHBottomNavigationItem(getString(R.string.tutorial_text), R.drawable.ic_help_white_24dp); itemAbout = new AHBottomNavigationItem(getString(R.string.jars_text), R.drawable.water_to_jar_empty); bottomNavigation.addItem(itemAbout); bottomNavigation.addItem(itemSettings); bottomNavigation.addItem(itemStatistics); bottomNavigation.addItem(itemTutorial); bottomNavigation.setBehaviorTranslationEnabled(true); bottomNavigation.setColored(true); bottomNavigation.setColoredModeColors(colors[2], colors[3]); //to color an icon font //bottomNavigation.setForceTint(true); // FIXME: 31.01.2017 bottomNavigation.setCurrentItem(0); bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() { @Override public boolean onTabSelected(int position, boolean wasSelected) { int color = R.color.colorDivider; while (fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStackImmediate(); } Log.d("VOlga", "on Tab - backstack size after immediate " + fragmentManager.getBackStackEntryCount()); switch (position) { case 0: { fragmentManager.beginTransaction() .replace(R.id.content_layout, recyclerFragment, "RECYCLER") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); if (!fab.isShown()) { fab.show(); fab.startAnimation(animationGetVisible); } break; } case 1: { Log.d(TAG, "settings instance lang pref - " + Prefs.with(getApplicationContext()).getPrefLanguage()); settingsFragment = SettingsFragment.newInstance( Prefs.with(getApplicationContext()).getPrefLanguage()); fragmentManager.beginTransaction() .replace(R.id.content_layout, settingsFragment) .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); if (!fab.isShown()) { fab.show(); fab.startAnimation(animationGetVisible); } break; } case 2: { statisticsFragment = StatisticsFragment.newInstance(); fragmentManager.beginTransaction() .replace(R.id.content_layout, statisticsFragment) .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); if (!fab.isShown()) { fab.show(); fab.startAnimation(animationGetVisible); } break; } case 3: { helpFragment = HelpFragment.newInstance(); fragmentManager.beginTransaction() .replace(R.id.content_layout, helpFragment) .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); if (!fab.isShown()) { fab.show(); fab.startAnimation(animationGetVisible); } break; } default: { break; } } return true; } }); if (fragmentManager.getBackStackEntryCount() == 0 && !(fragmentManager.findFragmentById(R.id.content_layout) instanceof RecyclerFragment)) { fragmentManager.beginTransaction() .replace(R.id.content_layout, recyclerFragment, "RECYCLER") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); } updateAllWidgets(); jarInRecyclerSubscription = recyclerFragment.getJar() .subscribe(jar -> { DebugLogger.log("opening a JAR info: " + jar.getJar_id()); jarInfoFragment = JarInfoFragment.newInstance(jar.getJar_id()); Log.d(TAG, jarInfoFragment.toString()); fragmentManager.beginTransaction() .replace(R.id.content_layout, jarInfoFragment) .addToBackStack("JarInfo") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); getInnerSubscriptionsJar(jar.getJar_id()); }, error -> DebugLogger.log(error.getMessage()) ); subscriptions.add(jarInRecyclerSubscription); } private void getInnerSubscriptionsJar(String jar_id) { cashClickSubscription = jarInfoFragment.getCashflowItem() .subscribe(cash -> { DebugLogger.log("cash clicked : " + cash.getId() + ", " + cash.getSum()); Log.d(TAG, "cash clicked : " + cash.getId() + ", " + cash.getSum()); cashInfoFragment = CashInfoFragment.newInstance(cash.getId()); fragmentManager.beginTransaction() .replace(R.id.content_layout, cashInfoFragment) .addToBackStack("CashEdit") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); finishEditCashSubscription = cashInfoFragment.isFinishEdit() .subscribe(isEdited -> { DebugLogger.log("DL cash was edited : " + isEdited); Log.d(TAG, "cash was edited : " + isEdited); recyclerFragment.refreshRecycler(); jarInfoFragment.refreshData(); jarInfoFragment.refreshRecyclerArterDeleteItem(); updateAllWidgets(); }); subscriptions.add(finishEditCashSubscription); }, error -> DebugLogger.log(error.getMessage()) ); cashDeleteSubscription = jarInfoFragment.refreshRecyclerArterDeleteItem() .subscribe(deletedCashID -> { DebugLogger.log("DL refreshing mainRecycler after deleted cash : " + deletedCashID); Log.d(TAG, "refreshing mainRecycler after deleted cash : " + deletedCashID); recyclerFragment.refreshRecycler(); updateAllWidgets(); }, error -> DebugLogger.log(error.getMessage()) ); spendCashInJar = jarInfoFragment.spendCashInJar() .subscribe(jarSpend -> { DebugLogger.log("DL open spendcash fragment : " + jar_id); Log.d(TAG, "open spendcash fragment : " + jar_id); spendFragment = SpendFragment.newInstance(jar_id); fragmentManager.beginTransaction() .replace(R.id.content_layout, spendFragment, "spend") .addToBackStack("Spend") .commit(); finishSpendCashSubscription = spendFragment.finishSpend() .subscribe(isSpend -> { DebugLogger.log("spend cash and close : " + isSpend); Log.d(TAG, "spend cash and close : " + isSpend); //TODO CHECK if working and close the spend fragmentManager.popBackStackImmediate(); fab.show(); recyclerFragment.refreshRecycler(); jarInfoFragment.refreshData(); jarInfoFragment.refreshRecyclerArterDeleteItem(); updateAllWidgets(); }); subscriptions.add(finishSpendCashSubscription); }); subscriptions.add(cashClickSubscription); subscriptions.add(cashDeleteSubscription); subscriptions.add(spendCashInJar); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_share) { shareFragment = ShareFragment.newInstance(); fragmentManager.beginTransaction() .replace(R.id.content_layout, shareFragment) .addToBackStack("Share") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); return true; } else if (id == R.id.action_save_base) { menuItem = 1; checkStoragePermissions(this); return true; } else if (id == R.id.action_restore_base) { menuItem = 2; checkStoragePermissions(this); return true; } else if (id == R.id.action_send_base) { menuItem = 3; checkStoragePermissions(this); return true; } return super.onOptionsItemSelected(item); } private void checkStoragePermissions(Activity activity) { // Check if we have write permission int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE ); } else { if (menuItem == 1) { RealmManager.with(this).backup(this); } else if (menuItem == 2) { startActivity(new Intent(MainActivity.this, RestoreActivity.class) .addFlags(FLAG_ACTIVITY_NO_HISTORY)); } else if (menuItem == 3) { RealmManager.with(this).exportDatabase(this); } menuItem = 0; } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_EXTERNAL_STORAGE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { if (menuItem == 1) { RealmManager.with(this).backup(this); } else if (menuItem == 2) { startActivity(new Intent(MainActivity.this, RestoreActivity.class) .addFlags(FLAG_ACTIVITY_NO_HISTORY)); } else if (menuItem == 3) { RealmManager.with(this).exportDatabase(this); } menuItem = 0; } } super.onRequestPermissionsResult(requestCode, permissions, grantResults); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if ((requestCode == GOOGLEPLUS_REQUEST_CODE) && (resultCode == -1)) { Log.d(TAG, "Success on Google posting"); } if (!VKSdk.onActivityResult(requestCode, resultCode, data, new VKCallback<VKAccessToken>() { @Override public void onResult(VKAccessToken res) { uploadPhotoToVk(res.userId); } @Override public void onError(VKError error) { Toast.makeText(getBaseContext(), getString(R.string.vk_cant_authorize_text), Toast.LENGTH_LONG).show(); } })) { super.onActivityResult(requestCode, resultCode, data); } } private void uploadPhotoToVk(String userID) { //Bitmap photo = ((BitmapDrawable) ContextCompat.getDrawable(this,R.drawable.logo_on_bg_64)).getBitmap(); Bitmap photo = getBitmapFromDrawable(getApplicationContext(), R.mipmap.ic_launcher); Log.w("VK photo", "owner id " + userID); Log.w("VK photo", "photo " + photo); VKRequest request = VKApi.uploadWallPhotoRequest(new VKUploadImage(photo, VKImageParameters.pngImage()), Integer.parseInt(userID), 0); request.executeWithListener(new VKRequest.VKRequestListener() { @Override public void onComplete(VKResponse response) { super.onComplete(response); VKApiPhoto photoModel = ((VKPhotoArray) response.parsedModel).get(0); makeVKWallPost(new VKAttachments(photoModel)); } @Override public void attemptFailed(VKRequest request, int attemptNumber, int totalAttempts) { super.attemptFailed(request, attemptNumber, totalAttempts); Toast.makeText(getBaseContext(), getString(R.string.vk_cant_upload_text), Toast.LENGTH_LONG).show(); } @Override public void onError(VKError error) { super.onError(error); Log.w("VK photo", "error " + error.toString()); Toast.makeText(getBaseContext(), getString(R.string.vk_cant_upload_text), Toast.LENGTH_LONG).show(); } }); } private void makeVKWallPost(VKAttachments attachments) { final String appPackageName = getApplicationContext().getPackageName(); attachments.add(new VKApiLink("https://play.google.com/store/apps/details?id=" + appPackageName)); VKRequest request = VKApi.wall().post(VKParameters.from(VKAccessToken.currentToken().userId, -1, VKApiConst.ATTACHMENTS, attachments, VKApiConst.MESSAGE, getString(R.string.share_message_text))); request.executeWithListener(new VKRequest.VKRequestListener() { @Override public void onComplete(VKResponse response) { super.onComplete(response); //Toast.makeText(getBaseContext(),"ะŸะพัั‚ ัƒัะฟะตัˆะฝะพ ั€ะฐะทะผะตั‰ะตะฝ ะฝะฐ ะ’ะฐัˆะตะน ัั‚ะตะฝะต",Toast.LENGTH_LONG).show(); Toast.makeText(getBaseContext(), getString(R.string.vk_posted_text), Toast.LENGTH_LONG).show(); } @Override public void attemptFailed(VKRequest request, int attemptNumber, int totalAttempts) { super.attemptFailed(request, attemptNumber, totalAttempts); //Toast.makeText(getBaseContext(),"ะกะพะทะดะฐะฝะธะต ะฟะพัั‚ะฐ ะฟั€ะตั€ะฒะฐะฝะพ",Toast.LENGTH_LONG).show(); Toast.makeText(getBaseContext(), getString(R.string.vk_not_posted_text), Toast.LENGTH_LONG).show(); } @Override public void onError(VKError error) { super.onError(error); Log.w("VK post", "error " + error.toString()); Toast.makeText(getBaseContext(), getString(R.string.vk_error_posted_text), Toast.LENGTH_LONG).show(); } }); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean("IsSavedInst", true); //don't needed anymore, I guess - todo check super.onSaveInstanceState(outState); } @Override public void onBackPressed() { if (fragmentManager.getBackStackEntryCount() == 0) { if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed(); else Toast.makeText(getBaseContext(), R.string.click_to_exit_text, Toast.LENGTH_SHORT).show(); back_pressed = System.currentTimeMillis(); return; } else { if (!fab.isShown()) { fab.show(); fab.startAnimation(animationGetVisible); } //to clear subscriptions to JarInfo cashflows // FIXME: 31.01.2017 if (fragmentManager.findFragmentById(R.id.content_layout) instanceof CashInfoFragment) { } else if (fragmentManager.findFragmentById(R.id.content_layout) instanceof SpendFragment) { } else if (fragmentManager.findFragmentById(R.id.content_layout) instanceof JarInfoFragment) { /*if (!cashClickSubscription.isUnsubscribed()) { finishEditCashSubscription.unsubscribe(); cashClickSubscription.unsubscribe(); } if (!spendCashInJar.isUnsubscribed()) { finishSpendCashSubscription.unsubscribe(); spendCashInJar.unsubscribe(); }*/ cashDeleteSubscription.unsubscribe(); } super.onBackPressed(); } } //TODO check private void updateAllWidgets() { AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext()); ComponentName thisWidget = new ComponentName(this, JarsWidget.class); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget); if (appWidgetIds != null && appWidgetIds.length > 0) { for (int appWidgetId : appWidgetIds) { JarsWidget.updateAppWidget(this, appWidgetManager, appWidgetId); } } } @Override protected void onStart() { super.onStart(); if (Prefs.with(getApplicationContext()).getPrefRestoreMark()) { Log.d(TAG, "onStart - restore true"); //todo check RealmManager.loadUserPrefsToSharedPrefs(getApplicationContext(), RealmManager.with(this).getJar("NEC").getUser()); Log.d(TAG, ""); Prefs.with(getApplicationContext()).setPrefRestoreMark(false); Log.d(TAG, "onStart - restore false"); Configuration config = getApplicationContext().getResources().getConfiguration(); Locale locale = new Locale(Prefs.with(this).getPrefLanguage()); /*Locale previousLocale = getApplicationContext(). if (!"".equals(lang) && !Prefs.with(getContext().getApplicationContext()).equals(lang))*/ Locale.setDefault(locale); config.locale = locale; getApplicationContext().getResources().updateConfiguration(config, getApplicationContext().getResources().getDisplayMetrics()); Intent intent = getApplicationContext().getApplicationContext().getPackageManager() .getLaunchIntentForPackage(getApplicationContext().getPackageName()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } } @Override protected void onPostResume() { super.onPostResume(); if (Prefs.with(getApplicationContext()).getPrefRestoreMark()) { Log.d(TAG, "onPostResume - restore true"); RealmManager.loadUserPrefsToSharedPrefs(getApplicationContext(), RealmManager.with(this).getJar("NEC").getUser()); Log.d(TAG, ""); Prefs.with(getApplicationContext()).setPrefRestoreMark(false); Log.d(TAG, "onPostResume - restore false"); } } @Override protected void onDestroy() { super.onDestroy(); subscriptions.clear(); } @Override protected void onResume() { super.onResume(); //todo check Intent intentFromWidget = getIntent(); if (intentFromWidget.getStringExtra("JarInfoFragment") != null) { String value = intentFromWidget.getStringExtra("JarInfoFragment"); if (value != null) { Log.d(TAG, " widget value from intent " + value); if (fragmentManager.findFragmentById(R.id.content_layout) instanceof JarInfoFragment) { fragmentManager.popBackStackImmediate(); } jarInfoFragment = JarInfoFragment.newInstance(value); fragmentManager.beginTransaction() .replace(R.id.content_layout, jarInfoFragment) .addToBackStack("jarInfo") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); getInnerSubscriptionsJar(value); updateAllWidgets(); intentFromWidget.removeExtra("JarInfoFragment"); //todo check } else { Log.d(TAG, " widget value from intent null"); } } } @Override protected void onNewIntent(Intent intent) { /*Can not perform this (widget value from intent) action after onSaveInstanceState*/ super.onNewIntent(intent); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package unalcol.types.collection.array; import unalcol.types.collection.Location; import java.util.NoSuchElementException; /** * @author jgomez */ public class ArrayCollectionLocation<T> implements Location<T> { protected int pos; protected ArrayCollection<T> array; public ArrayCollectionLocation(int pos, ArrayCollection<T> array) { this.array = array; this.pos = pos; } @Override public T get() throws NoSuchElementException { try { return array.get(pos); } catch (Exception e) { throw new NoSuchElementException("Invalid index .." + pos); } } public int getPos() { return pos; } }
package com.mes.cep.meta.operationsDefinitionModel; /** * @author StephenยฐยงWen * @email 872003894@qq.com * @date 2017ล„ร4โ€˜ยฌ19ยปโ€™ * @Chinesename โ‰คล”โ—Šลณโˆ‚ล‘ */ public class OperationsSegment { }
package com.demondevelopers.launcherbadges; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.View; import android.widget.ImageView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.increment).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainActivity activity = (MainActivity)v.getContext(); if(AppBadge.incrementBadgeCount(activity)){ AppBadge.updateActivityIcon(activity); activity.updateIcon(AppBadge.getCurrentBadge(activity)); } } }); findViewById(R.id.decrement).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainActivity activity = (MainActivity)v.getContext(); if(AppBadge.decrementBadgeCount(activity)){ AppBadge.updateActivityIcon(activity); activity.updateIcon(AppBadge.getCurrentBadge(activity)); } } }); updateIcon(AppBadge.getCurrentBadge(this)); } public void updateIcon(Drawable drawable) { ImageView iconView = (ImageView)findViewById(R.id.icon); iconView.setImageDrawable(drawable); iconView.setScaleX(0.15f); iconView.setScaleY(0.15f); iconView.animate().setDuration(150) .scaleX(1.0f).scaleY(1.0f); iconView.invalidate(); } }
package de.jmda.gen.impl; import javax.validation.constraints.NotNull; import de.jmda.gen.Generator; import de.jmda.gen.GeneratorException; import de.jmda.gen.LineIndenter; public class DefaultGenerator implements Generator { private StringBuffer output; /** * Non null, but maybe producing nothing but "empty" string <code>""</code>. */ @NotNull(message = "'lineIndenter' must not be null") private LineIndenter lineIndenter; protected DefaultGenerator() { this(new StringBuffer(""), new LineIndenter()); } public DefaultGenerator(String input) { this(new StringBuffer(input), new LineIndenter()); } public DefaultGenerator(StringBuffer input) { this(input, new LineIndenter()); } public DefaultGenerator(String input, LineIndenter lineIndenter) { this(new StringBuffer(input), lineIndenter); } public DefaultGenerator(StringBuffer input, LineIndenter lineIndenter) { super(); setOutput(input); setLineIndenter(lineIndenter); } /** * @param lineIndenter noop if <code>lineIndenter</code> is <code>null</code> */ @Override public void setLineIndenter(LineIndenter lineIndenter) { this.lineIndenter = notNull(lineIndenter); } @Override public LineIndenter getLineIndenter() { return notNull(lineIndenter); } /** * @return indented {@link #output} * @see de.jmda.gen.Generator#generate() */ @Override public StringBuffer generate() throws GeneratorException { return lineIndenter.indent(output); } /** * @param input * @see #setOutput(StringBuffer) */ protected void setOutput(String input) { output = new StringBuffer(input); } /** * Subclasses need a way to modify {@link #output} other than constructor * injection. * * @param input */ protected void setOutput(StringBuffer input) { output = input; } private LineIndenter notNull(LineIndenter lineIndenter) { if (lineIndenter == null) { lineIndenter = new LineIndenter(); } return lineIndenter; } /** * convenience method * * @param input * @return generator that produces <code>input</code> */ public static Generator dg(String input) { return new DefaultGenerator(input); } }
package testDemo; import java.util.HashMap; import java.util.Map; import rabbitmq.bean.MqRequestEntity; import rabbitmq.bean.RabbitMqClient; import rabbitmq.entity.ConsumerConstants; import rabbitmq.entity.QueueContants; public class TestPublish { public static void main(String[] args) { Map<String, String> param = new HashMap<String, String>(); for(int i=0;i<3;i++) { param.clear(); param.put("id", i+""); System.out.println(messagePushQueue(param)); } } /** * * @ๆ่ฟฐ๏ผš็”จๆˆทไธ‹ๆณจๆถˆๆฏๅ…ฅ้˜Ÿ * @ไฝœ่€…๏ผšไธฅ็ฃŠ * @ๆ—ถ้—ด๏ผš2018ๅนด5ๆœˆ12ๆ—ฅ ไธ‹ๅˆ7:06:11 * @param param * @return */ public static boolean messagePushQueue(Map<String, String> param) { boolean boo = false; try { //ๅ‘ๅธƒ้˜Ÿๅˆ— MqRequestEntity entity = new MqRequestEntity(); entity.setQueueName(QueueContants.actQueueName); entity.setConsumerId(ConsumerConstants.TestConsumerId); entity.setParam(param); RabbitMqClient mqClient = new RabbitMqClient(); boo = mqClient.publish(entity); } catch (Exception e) { e.printStackTrace(); } return boo; } }
package io.github.scarger.chat.util; import io.github.scarger.chat.LowLevelChat; import java.io.*; public class Translator { public native int encrypt(final String text); public native String translate(int address); public native void dispose(); public Translator() { //Windows implementation, which is what I use File libFile = new File(LowLevelChat.context.getDataFolder(),"Translator.dll"); LowLevelChat.context.getDataFolder().mkdirs(); if(!libFile.exists()) { try { libFile.createNewFile(); try(InputStream in = getClass().getResourceAsStream("/Translator.dll"); FileOutputStream out = new FileOutputStream(libFile)) { byte buffer[] = new byte[1024]; int length; while((length = in.read(buffer)) > 0) { out.write(buffer,0,length); } } catch (Exception e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } System.load(libFile.getAbsolutePath()); } }
/* * Copyright 2009 Kjetil Valstadsve * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package vanadis.modules.scripting; import vanadis.common.text.Printer; import vanadis.ext.CommandExecution; import vanadis.osgi.Context; import vanadis.osgi.Reference; import vanadis.services.scripting.ScriptingSessions; class NewSessionExecution implements CommandExecution { private final ScriptingSessions sessions; NewSessionExecution(ScriptingSessions sessions) { this.sessions = sessions; } @Override public void exec(String command, String[] args, Printer ps, Context context) { String arg = args[2]; sessions.newSession(args[0], args.length > 1 ? args[1] : null, args.length > 2 ? ref(arg, context) : null, args.length > 3 ? args[3] : null); } private Reference<?> ref(String arg, Context context) { return Services.getReference(context, arg, null); } }
package ba.bitcamp.LabS02D05; public class IspisBrojevaOd100do1 { public static void main(String[] args) { int broj = 100; while (broj >= 1) { System.out.println(broj); broj--; } } }
package com.ljx.javaFx.utils; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.EnumSet; /** * @author lijx * @date 2021/1/19 - 10:13 */ public class FileUtil { /** * ๅˆ ้™ค็›ฎๆ ‡ๆ–‡ไปถๅคน๏ผŒๅณไฝฟๆ–‡ไปถๅคนไธไธบ็ฉบ๏ผŒ * ๅฝ“ๆ–‡ไปถๅคนไธไธบ็ฉบๆ—ถ๏ผŒ็›ดๆŽฅๅˆ ้™คไผšๆŠฅ้”™๏ผŒๅ› ๆญค้‡‡็”จ่ฟ™็งๆ–นๅผๅŽปๅˆ ้™ค * * @param target ็›ฎๆ ‡ๆ–‡ไปถๆˆ–่€…็›ฎๆ ‡ * @throws IOException IOException */ public static void delete(Path target) throws IOException { if (Files.isDirectory(target)) { Files.walkFileTree(target, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new DeleteFileVisitor()); } else { Files.deleteIfExists(target); } } private static class DeleteFileVisitor extends SimpleFileVisitor<Path> { /** * ่กจ็คบ่ฎฟ้—ฎไธ€ไธชๆ–‡ไปถๆ—ถ่ฆ่ฟ›่กŒ็š„ๆ“ไฝœ */ @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.deleteIfExists(file); return FileVisitResult.CONTINUE; } /** * ่กจ็คบ่ฎฟ้—ฎไธ€ไธช็›ฎๅฝ•ๅŽ่ฆ่ฟ›่กŒ็š„ๆ“ไฝœ */ @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { // directory iteration failed throw exc; } } } }
package com.tencent.mm.plugin.voiceprint.ui; import com.tencent.mm.plugin.voiceprint.model.p; import com.tencent.mm.plugin.voiceprint.model.p.a; import com.tencent.mm.sdk.platformtools.x; class BaseVoicePrintUI$1 implements a { final /* synthetic */ BaseVoicePrintUI oFR; BaseVoicePrintUI$1(BaseVoicePrintUI baseVoicePrintUI) { this.oFR = baseVoicePrintUI; } public final void bIY() { p a = BaseVoicePrintUI.a(this.oFR); if (a.bAY != null) { a.bAY.we(); x.e("MicroMsg.VoicePrintRecoder", "Reset recorder.stopReocrd"); } a.fileName = ""; a.oFx = null; a.orz = 0; a.iZe = 0; if (a.epT != null) { a.epT.zY(); } x.e("MicroMsg.BaseVoicePrintUI", "record stop on error"); BaseVoicePrintUI.a(this.oFR, null); BaseVoicePrintUI.b(this.oFR); } }
/** * 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 * * 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.apache.hadoop.mapreduce.lib.reduce; import java.io.IOException; import java.net.URI; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configuration.IntegerRanges; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.RawComparator; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.JobID; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.OutputCommitter; import org.apache.hadoop.mapreduce.OutputFormat; import org.apache.hadoop.mapreduce.Partitioner; import org.apache.hadoop.mapreduce.ReduceContext; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.security.Credentials; /** * A {@link Reducer} which wraps a given one to allow for custom * {@link Reducer.Context} implementations. */ @InterfaceAudience.Public @InterfaceStability.Evolving public class WrappedReducer<KEYIN, VALUEIN, KEYOUT, VALUEOUT> extends Reducer<KEYIN, VALUEIN, KEYOUT, VALUEOUT> { /** * A a wrapped {@link Reducer.Context} for custom implementations. * @param reduceContext <code>ReduceContext</code> to be wrapped * @return a wrapped <code>Reducer.Context</code> for custom implementations */ public Reducer<KEYIN, VALUEIN, KEYOUT, VALUEOUT>.Context getReducerContext(ReduceContext<KEYIN, VALUEIN, KEYOUT, VALUEOUT> reduceContext) { return new Context(reduceContext); } @InterfaceStability.Evolving public class Context extends Reducer<KEYIN, VALUEIN, KEYOUT, VALUEOUT>.Context { protected ReduceContext<KEYIN, VALUEIN, KEYOUT, VALUEOUT> reduceContext; public Context(ReduceContext<KEYIN, VALUEIN, KEYOUT, VALUEOUT> reduceContext) { this.reduceContext = reduceContext; } @Override public KEYIN getCurrentKey() throws IOException, InterruptedException { return reduceContext.getCurrentKey(); } @Override public VALUEIN getCurrentValue() throws IOException, InterruptedException { return reduceContext.getCurrentValue(); } @Override public boolean nextKeyValue() throws IOException, InterruptedException { return reduceContext.nextKeyValue(); } @Override public Counter getCounter(Enum counterName) { return reduceContext.getCounter(counterName); } @Override public Counter getCounter(String groupName, String counterName) { return reduceContext.getCounter(groupName, counterName); } @Override public OutputCommitter getOutputCommitter() { return reduceContext.getOutputCommitter(); } @Override public void write(KEYOUT key, VALUEOUT value) throws IOException, InterruptedException { reduceContext.write(key, value); } @Override public String getStatus() { return reduceContext.getStatus(); } @Override public TaskAttemptID getTaskAttemptID() { return reduceContext.getTaskAttemptID(); } @Override public void setStatus(String msg) { reduceContext.setStatus(msg); } @Override public Path[] getArchiveClassPaths() { return reduceContext.getArchiveClassPaths(); } @Override public String[] getArchiveTimestamps() { return reduceContext.getArchiveTimestamps(); } @Override public URI[] getCacheArchives() throws IOException { return reduceContext.getCacheArchives(); } @Override public URI[] getCacheFiles() throws IOException { return reduceContext.getCacheArchives(); } @Override public Class<? extends Reducer<?, ?, ?, ?>> getCombinerClass() throws ClassNotFoundException { return reduceContext.getCombinerClass(); } @Override public Configuration getConfiguration() { return reduceContext.getConfiguration(); } @Override public Path[] getFileClassPaths() { return reduceContext.getFileClassPaths(); } @Override public String[] getFileTimestamps() { return reduceContext.getFileTimestamps(); } @Override public RawComparator<?> getGroupingComparator() { return reduceContext.getGroupingComparator(); } @Override public Class<? extends InputFormat<?, ?>> getInputFormatClass() throws ClassNotFoundException { return reduceContext.getInputFormatClass(); } @Override public String getJar() { return reduceContext.getJar(); } @Override public JobID getJobID() { return reduceContext.getJobID(); } @Override public String getJobName() { return reduceContext.getJobName(); } @Override public boolean getJobSetupCleanupNeeded() { return reduceContext.getJobSetupCleanupNeeded(); } @Override public boolean getTaskCleanupNeeded() { return reduceContext.getTaskCleanupNeeded(); } @Override public Path[] getLocalCacheArchives() throws IOException { return reduceContext.getLocalCacheArchives(); } @Override public Path[] getLocalCacheFiles() throws IOException { return reduceContext.getLocalCacheFiles(); } @Override public Class<?> getMapOutputKeyClass() { return reduceContext.getMapOutputKeyClass(); } @Override public Class<?> getMapOutputValueClass() { return reduceContext.getMapOutputValueClass(); } @Override public Class<? extends Mapper<?, ?, ?, ?>> getMapperClass() throws ClassNotFoundException { return reduceContext.getMapperClass(); } @Override public int getMaxMapAttempts() { return reduceContext.getMaxMapAttempts(); } @Override public int getMaxReduceAttempts() { return reduceContext.getMaxReduceAttempts(); } @Override public int getNumReduceTasks() { return reduceContext.getNumReduceTasks(); } @Override public Class<? extends OutputFormat<?, ?>> getOutputFormatClass() throws ClassNotFoundException { return reduceContext.getOutputFormatClass(); } @Override public Class<?> getOutputKeyClass() { return reduceContext.getOutputKeyClass(); } @Override public Class<?> getOutputValueClass() { return reduceContext.getOutputValueClass(); } @Override public Class<? extends Partitioner<?, ?>> getPartitionerClass() throws ClassNotFoundException { return reduceContext.getPartitionerClass(); } @Override public Class<? extends Reducer<?, ?, ?, ?>> getReducerClass() throws ClassNotFoundException { return reduceContext.getReducerClass(); } @Override public RawComparator<?> getSortComparator() { return reduceContext.getSortComparator(); } @Override public boolean getSymlink() { return reduceContext.getSymlink(); } @Override public Path getWorkingDirectory() throws IOException { return reduceContext.getWorkingDirectory(); } @Override public void progress() { reduceContext.progress(); } @Override public Iterable<VALUEIN> getValues() throws IOException, InterruptedException { return reduceContext.getValues(); } @Override public boolean nextKey() throws IOException, InterruptedException { return reduceContext.nextKey(); } @Override public boolean getProfileEnabled() { return reduceContext.getProfileEnabled(); } @Override public String getProfileParams() { return reduceContext.getProfileParams(); } @Override public IntegerRanges getProfileTaskRange(boolean isMap) { return reduceContext.getProfileTaskRange(isMap); } @Override public String getUser() { return reduceContext.getUser(); } @Override public Credentials getCredentials() { return reduceContext.getCredentials(); } @Override public float getProgress() { return reduceContext.getProgress(); } } }
package abstratc.interfaces; import inheritance.polymorphism.Cargo; public /*abstract*/ class CanadAir implements FireFighterPlane{ private double consumption; private double autonomy; private int capacity; private Cargo cargo; public CanadAir(double con, double aut, int cap, Cargo water) { this.consumption = con; this.autonomy = aut; this.capacity = cap; this.cargo = water; } @Override public final void goTo(int distance, int load){ } @Override public void comeBack() { // TODO Auto-generated method stub } @Override public void dropWater() { // TODO Auto-generated method stub } public void stopFire(){ } }
/* * @Author : fengzhi * @date : 2019 - 04 - 14 20 : 31 * @Description : */ package nowcoder_leetcode; public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
package day03oparators; public class TypeCasting01 { public static void main(String[] args) { // Kรผcรผk data tipini buyuk data tipine jaava otomatik olarak yapar. byte by = 101; int sayi = by; System.out.println(sayi); int sayi2 = 53; byte by2 = (byte)sayi2; System.out.println(by2); double sayi3 = 23.9; int by3 =(int)sayi3; System.out.println(by3); float sayi4 = -23.9f; short by4 = (short)sayi4; System.out.println(by4); double sayi5 = 4.8; double sayi6 = 1.4; double sonuc = sayi5 / sayi6; System.out.println(sonuc); int sonuc2 = (int)(sayi5 / sayi6); System.out.println(sonuc2); int sayi7 = 5; int sayi8 = 3; int sonuc3 = sayi7 / sayi8; System.out.println(sonuc3); // Yuvarlamiyor sadece tam kismi aliyoruz. int sayi9 = 556; byte by5 = (byte)sayi9; System.out.println(by5); //normalde byte da 256 sayi var siniri gecen kismi eksi olark yazar } }
/** * */ package com.hermes.ah3.jdbc.communication; /** * ๅญ—ๆฎตๅ…ƒๆ•ฐๆฎไฟกๆฏ็ฑป * @author wuwl * */ public class ColumnMetaData { private String dataType; private int index; private String columnName; public String getColumnName() { return columnName; } public void setColumnName(String columnName) { this.columnName = columnName; } public String getDataType() { return dataType; } public void setDataType(String dataType) { this.dataType = dataType; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } }
package resource; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class Base { protected WebDriver driver; protected WebDriverWait wait; public Base(WebDriver driver) { this.driver = driver; this.wait = new WebDriverWait(driver, 10); } public WebDriverWait getWait() { return wait; } public void waitForVisibility(WebElement element) { wait.until(ExpectedConditions.visibilityOf(element)); } public boolean isPresent(WebElement element) { waitForVisibility(element); return element.isDisplayed(); } public void waitForClickable(WebElement element) { wait.until(ExpectedConditions.elementToBeClickable(element)); } public void clickOn(WebElement element) { wait.until(ExpectedConditions.elementToBeClickable(element)).click(); } public void sendKeys(WebElement element, String key) { element.sendKeys(key); } public String getText(WebElement element) { return element.getText(); } }
package com.tencent.smtt.sdk; import android.graphics.SurfaceTexture; import android.os.Bundle; public class TbsMediaPlayer { private ba a = null; public TbsMediaPlayer(ba baVar) { this.a = baVar; } public void audio(int i) { this.a.b(i); } public void close() { this.a.e(); } public float getVolume() { return this.a.b(); } public boolean isAvailable() { return this.a.a(); } public void pause() { this.a.c(); } public void play() { this.a.d(); } public void seek(long j) { this.a.a(j); } public void setPlayerListener(TbsMediaPlayerListener tbsMediaPlayerListener) { this.a.a(tbsMediaPlayerListener); } public void setSurfaceTexture(SurfaceTexture surfaceTexture) { this.a.a(surfaceTexture); } public void setVolume(float f) { this.a.a(f); } public void startPlay(String str, Bundle bundle) { this.a.a(str, bundle); } public void subtitle(int i) { this.a.a(i); } }
package com.payment.payment.controller; import com.payment.payment.domain.User; import com.payment.payment.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/user") public class UserController { @Autowired UserRepository repository; @GetMapping public ResponseEntity find(){ return ResponseEntity.ok(repository.findAll()); } @PostMapping public ResponseEntity save(@RequestBody User user){ return ResponseEntity.ok(repository.save(user)); } @PutMapping public ResponseEntity update(@RequestBody User user){ return ResponseEntity.ok(repository.save(user)); } @DeleteMapping public void delete(@RequestBody User user){ repository.delete(user); } @PatchMapping("{id}") public ResponseEntity modify(@PathVariable("id") int id ,@RequestBody User user){ return ResponseEntity.ok(repository.save(user)); //todo } }
package com.orca.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView; import com.orca.domain.CodeStatic; import com.orca.domain.Survey; import com.orca.service.SurveyService; @SessionAttributes({ "codeStatic" }) @Controller public class CodeStaticController { @Autowired private SurveyService surveyService; @RequestMapping(value = "codeStatic.html") public ModelAndView codeStatic(@RequestParam("surveyId") Integer surveyId) { Survey survey = surveyService.getSurvey(surveyId); if (!surveyService.authorizedUser(survey)){ return new ModelAndView("notAuthorized"); } ModelAndView mav = new ModelAndView("codeStatic"); mav.addObject("codeStatic", survey.getCodeStatic()); mav.addObject("survey", survey); return mav; } @RequestMapping(value = "saveCodeStatic.html") public String saveCodeStatic(@ModelAttribute("codeStatic") CodeStatic codeStatic, @RequestParam("surveyId") Integer surveyId, @RequestParam("submit") String submit) { Survey survey = surveyService.getSurvey(surveyId); if (!surveyService.authorizedUser(survey)){ return "redirect:notAuthorized.html"; } survey.setCodeStatic(codeStatic); surveyService.saveSurvey(survey); if (submit.equals("Next Metric")){ return "redirect:community.html?surveyId=" + survey.getId(); } else { return "redirect:evaluationSummary.html?evaluationId=" + survey.getEvaluation().getId(); } } }
public class Stack { private StackedInt bottom; public void push(int value) { System.out.println("Pushing " + value + "..."); StackedInt newInt = new StackedInt(value); if (bottom == null) { bottom = newInt; } else { bottom.push(newInt); } } public void pop() { if (bottom == null) { System.out.println("Stack is empty"); } else if (bottom.getNext() == null ) { System.out.println("Popping... it's a " + bottom.getValue()); bottom = null; } else { bottom.pop(); } } private int size() { int counter = 0; if ( bottom == null ) { return counter; } else { return bottom.size(counter); } } public void printSize() { System.out.println("There are " + size() + " requests in the stack."); } }
package com.quaero.quaerosmartplatform.domain.vo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.math.BigDecimal; import java.util.Date; /** * <p> * ๆŒ‰ๆ–™ๅท่ฎกๅˆ’ๅˆฐๆ–™ๆœชไบคๆŸฅ่ฏขๅˆ—่กจ่ฟ”ๅ›žๅ‚ * </p> * * @author wuhanzhang@ * @since 2021/1/19 8:33 */ @Data @ApiModel public class MaterialPlanUnpaidListVo { @ApiModelProperty("ๆฅๆบๅ•ๅท") private Integer docEntry; @ApiModelProperty("ๆฅๆบ่กŒๅท") private Integer lineNum; @ApiModelProperty("ๆ–™ๅท") private String itemCode; @ApiModelProperty("ๅ็งฐ่ง„ๆ ผ") private String dscription; @ApiModelProperty("ๆœชไบคๆ•ฐ้‡ๆ€ปๅ’Œ") private BigDecimal unpaidQuantity; @ApiModelProperty("ไบค่ดงๆ—ฅๆœŸ ่ฆๆฑ‚ๅˆฐๆ–™ๆ—ฅๆœŸ") private Date shipDate; @ApiModelProperty("ไธšๅŠกๅ‘˜") private String slpName; @ApiModelProperty("ไพ›ๅบ”ๅ•†็ผ–ๅท") private String cardCode; @ApiModelProperty("ไพ›ๅบ”ๅ•†ๅ็งฐ") private String cardName; @ApiModelProperty("ๆฅๆบ็ฑปๅž‹") private String objType; @ApiModelProperty("PMCๆŒ‡ๅฎšไบค่ดงๆ–นๅผ") private String pmcZD; @ApiModelProperty("ๆœ€ๆ—ฉ็ผบๆ–™ๆ—ฅๆœŸ") private String zzql; @ApiModelProperty("ๅปบ่ฎฎไบคไป˜ๆ•ฐ้‡") private BigDecimal jyjfQTY; @ApiModelProperty("่ฎกๅˆ’ๅˆฐๆ–™ๆ•ฐ") private BigDecimal plannedQty; @ApiModelProperty("่ฎกๅˆ’ๅˆฐๆ–™ๆ—ฅๆœŸ") private Date dueDate; @ApiModelProperty("ๅˆฐๆ–™ๆ–นๅผ") private String dlfs; @ApiModelProperty("็‰ฉๆตไฟกๆฏ") private String wlxx; }
package nl.ru.ai.SiemenLooijen4083679.reinforcement; import java.util.ArrayList; import java.util.Random; import nl.ru.ai.vroon.mdp.Action; import nl.ru.ai.vroon.mdp.Field; import nl.ru.ai.vroon.mdp.MarkovDecisionProblem; public class ValueIteration { private MarkovDecisionProblem mdp; private double[][] values; private double[][] newValues; private ArrayList<double[][]> vForEachK = new ArrayList<>(); private Q[][] qForEachK;// naam moet anders, is niet voor each k private double discount_factor = 0.9; private double threshold = 0.001; private int k = 0; public ValueIteration(MarkovDecisionProblem mdp) { this.mdp = mdp; this.values = new double[mdp.getWidth()][mdp.getHeight()]; this.newValues = new double[mdp.getWidth()][mdp.getHeight()]; this.qForEachK = new Q[mdp.getWidth()][mdp.getHeight()]; initialize(); do { valueIteration(); } while (!terminated()); System.out.println("lalala"); while (!mdp.isTerminated()) { int x = mdp.getStateXPosition(); int y = mdp.getStateYPostion(); Action best = qForEachK[x][y].getAction(); mdp.performAction(best); } } private void initialize() { for (int i = 0; i < values.length; i++) { //System.out.println(values.length); for (int j = 0; j < values[i].length; j++) { values[i][j] = new Random().nextDouble(); //System.out.println("INITIAL"); //System.out.println(values[i][j]); } } vForEachK.add(values); System.out.println("dingen0 " + vForEachK.get(0)[0][0]); } private boolean terminated() { boolean terminated = true; double[][] vCurrent = vForEachK.get(k); double[][] vPrevious = vForEachK.get(k - 1); for (int i = 0; i < vCurrent.length; i++) for (int j = 0; j < vCurrent[i].length; j++) { //System.out.println("Terminated? : " + (vCurrent[i][j])); double currentV = vCurrent[i][j]; //System.out.println(vPrevious[i][j]); double previousV = vPrevious[i][j]; System.out.println("difference = " + Math.abs(currentV - previousV)); if (Math.abs(vCurrent[i][j] - vPrevious[i][j]) > threshold) terminated = false; } return terminated; } private void valueIteration() { //while not terminated this.k++; updateV(); } /** * updates values per state */ private void updateV() { for (int i = 0; i < values.length; i++) { for (int j = 0; j < values[i].length; j++) { for (Action a : Action.values()) updateThisState(i, j, a); System.out.println(qForEachK[i][j]); } } double[][] copyOf = new double[mdp.getWidth()][mdp.getHeight()]; for (int i = 0; i < newValues.length; i++) { for (int j = 0; j < newValues[i].length; j++) { copyOf[i][j] = newValues[i][j]; } } vForEachK.add(copyOf); System.out.println("vForEachK0[0][0]" + vForEachK.get(0)[0][0]); System.out.println("vForEachK1[0][0]" + vForEachK.get(1)[0][0]); this.values = new double[mdp.getWidth()][mdp.getHeight()];//nadenken } /** * updates specifc state for all legal actions * * @param x * @param y * @param a */ private void updateThisState(int x, int y, Action a) { ArrayList<Double> all_p_r_gamma_previousV_per_legal_move_for_current_state = new ArrayList<>(); ArrayList<Action> actions = new ArrayList<>();//equal size and index to all_p_r_gamme_perviousV_per_legal_move_for_current_state //for each legal move from current state, put into arraylist the prob * (immediate reward, discount *Vk-1) Then pick the best one from arraylist and put into v for the state. Update v. //mdp.setState(x, y); Field f = mdp.getField(x, y);// = current state. Changed this in nl.ru.ai.vroon.mdp.Field for (Action action : Action.values()) { int nextX = x; int nextY = y; double p = 0; if (a == action) { p = mdp.getpPerform(); if (a == Action.UP) nextY++; if (a == Action.DOWN) nextY--; if (a == Action.LEFT) nextX--; if (a == Action.RIGHT) nextX++; } else if (a == Action.backAction(a)) { if (a == Action.UP) nextY--; if (a == Action.DOWN) nextY++; if (a == Action.LEFT) nextX++; if (a == Action.RIGHT) nextX--; } else if (a == Action.previousAction(a)) { p = mdp.getpSidestep(); if (a == Action.UP) nextX--; if (a == Action.DOWN) nextX++; if (a == Action.LEFT) nextY++; if (a == Action.RIGHT) nextY--; } else if (a == Action.nextAction(a)) { p = mdp.getpSidestep(); if (a == Action.UP) nextX++; if (a == Action.DOWN) nextX--; if (a == Action.LEFT) nextY++; if (a == Action.RIGHT) nextY--; } //System.out.println("x = " + x + " y = " + y); if (!(nextX < 0 || nextX >= mdp.getWidth() || nextY < 0 || nextY >= mdp.getHeight())) { all_p_r_gamma_previousV_per_legal_move_for_current_state.add(p * rewardForField(f, nextX, nextY) + discount_factor * vForEachK.get(k - 1)[nextX][nextY]); //System.out.println(all_p_r_gamma_previousV_per_legal_move_for_current_state); actions.add(action); } } //TODO beste uitkiezen -> functie double highest = 0; Action bestAction = null; for (int i = 0; i < all_p_r_gamma_previousV_per_legal_move_for_current_state.size(); i++) { double d = all_p_r_gamma_previousV_per_legal_move_for_current_state.get(i); if (d > highest) { highest = d; bestAction = actions.get(i); } } // System.out.println("x = " + x + " y = " + y + " " + values[x][y]); //values = //copy van velden, wsl niet hier maar boven? newValues[x][y] = highest; //actions[x][y][a] = bestAction? q value? qForEachK[x][y] = new Q(x, y, bestAction, highest); } private double rewardForField(Field f, int x, int y) { if (f != Field.OUTOFBOUNDS && f != Field.OBSTACLE) return mdp.getReward(x, y); return -9999; } }
package com.robot; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Scanner; public class WaterStrider_๋ถ€๊ถŒ๋‚จ { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub System.setIn(new FileInputStream("res\\Solution21.txt")); Scanner sc = new Scanner(System.in); StringBuffer sb = new StringBuffer(); int TC= sc.nextInt(); for (int i = 1; i <= TC; i++) { sb.append("#").append(i).append(" "); int N = sc.nextInt(); int num = sc.nextInt(); boolean[][] visited = new boolean[N][N]; // ๋ฐฉ๋ฌธํ–‡๋Š”์ง€ ์•ˆํ–ˆ๋Š”์ง€์˜ 2์ฐจ์›๋ฐฐ์—ด for(boolean[] bool:visited) //false ์ดˆ๊ธฐํ™” Arrays.fill(bool, false); int first =0; // ์ตœ์ดˆ์˜ ๊ฐ™์€ ์žฅ์†Œ ๊ฐ’ for (int j = 1; j <= num; j++) { int r = sc.nextInt(); // ํ–‰ int c = sc.nextInt(); // ์—ด int dir = sc.nextInt(); // ๋ฐฉํ–ฅ if(first > 0) continue; // first๊ฐ’์ด ๋‚˜์˜ค๋ฉด continue(๋”์ด์ƒ ํ• ํ•„์š”๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ์—) if(visited[r][c] ==true) // ์‹œ์ž‘์ ์„ True๋กœ ๋ฐ”๊พผ๋‹ค. ์ด๋ฏธ true๋ฉด ํ˜„์žฌ j๊ฐ€ first๊ฐ’ first = j; else visited[r][c] = true; if(first > 0) continue; if(dir ==2) { // ์˜ค๋ฅธ์ชฝ์œผ๋กœ ๋›ฐ๋ฉด first = jumpRight(visited,r,c,j); // jumpRight ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด first๊ฐ’์„ ์ฐพ๋Š”๋‹ค. ์—†์œผ๋ฉด 0 if(first > 0) continue; } else if(dir ==1) { // ์•„๋ž˜์ชฝ์œผ๋กœ ๋›ฐ๋ฉด first = jumpDown(visited,r,c,j); // jumpDown ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด first๊ฐ’์„ ์ฐพ๋Š”๋‹ค. ์—†์œผ๋ฉด 0 if(first > 0) continue; } } sb.append(first).append("\n"); } System.out.println(sb); } static int jumpRight(boolean[][] visited,int r, int c, int j){ // ์˜ค๋ฅธ์ชฝ์œผ๋กœ 3, 2, 1 ๋›ด๋‹ค int tmp = c; // ํ˜„์žฌ c์˜ ์ž„์‹œ ๋ณ€์ˆ˜ for (int i = 3; i > 0; i--) { if(visited[i].length-1 < tmp+i) break; // ๊ธธ์ด๋ฅผ ์ดˆ๊ณผํ•˜๋ฉด break tmp+=i; if(visited[r][tmp]==false) // ์•„์ง ๋ฐฉ๋ฌธํ•œ์ ์ด ์—†์œผ๋ฉด true visited[r][tmp] = true; else return j; // ์žˆ์œผ๋ฉด ํ˜„์žฌ ๋ฒˆํ˜ธ j return } return 0; // ๋‹ค ๋ฐฉ๋ฌธํ•œ์  ์—†์œผ๋ฉด 0 return } static int jumpDown(boolean[][] visited,int r, int c, int j){ // ์•„๋ž˜์ชฝ์œผ๋กœ 3, 2, 1 ๋›ด๋‹ค int tmp = r; // ํ˜„์žฌ r์˜ ์ž„์‹œ ๋ณ€์ˆ˜ for (int i = 3; i > 0; i--) { if(visited[i].length-1 < tmp+i) break; tmp+=i; if(visited[tmp][c]==false) // ํ˜•์‹์€ jumpRight์™€ ๋™์ผ visited[tmp][c] = true; else return j; } return 0; } }
package ralli.yugesh.com.primemovies.data; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; public class FavoritelistContentProvider extends ContentProvider { private FavoritelistDbHelper mFavoritelistDbHelper; // It's convention to use 100, 200, 300, etc for directories, // and related ints (101, 102, ..) for items in that directory. private static final int FAVORITELIST = 100; private static final UriMatcher sUriMatcher = buildUriMatcher(); private static UriMatcher buildUriMatcher(){ UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(FavoritelistContract.AUTHORITY,FavoritelistContract.PATH,FAVORITELIST); return uriMatcher; } @Override public boolean onCreate() { mFavoritelistDbHelper = new FavoritelistDbHelper(getContext()); return true; } @Nullable @Override public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) { final SQLiteDatabase sqLiteDatabase = mFavoritelistDbHelper.getReadableDatabase(); int match = sUriMatcher.match(uri); Cursor returnCursor; switch (match){ case FAVORITELIST: { returnCursor = sqLiteDatabase.query( FavoritelistContract.FavortitelistEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); break; } default: throw new UnsupportedOperationException("Unknown uri: " + uri); } returnCursor.setNotificationUri(getContext().getContentResolver(),uri); return returnCursor; } @Nullable @Override public String getType(@NonNull Uri uri) { return null; } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) { final SQLiteDatabase sqLiteDatabase = mFavoritelistDbHelper.getWritableDatabase(); int match = sUriMatcher.match(uri); Uri returnUri; switch (match){ case FAVORITELIST: { long id = sqLiteDatabase .insert(FavoritelistContract.FavortitelistEntry.TABLE_NAME,null,contentValues); if (id > 0) { returnUri = ContentUris.withAppendedId(FavoritelistContract.FavortitelistEntry.CONTENT_URI,id); }else { throw new SQLException("Failed to insert row into " + uri); } break; } default: throw new UnsupportedOperationException("Unknown uri: " + uri); } getContext().getContentResolver().notifyChange(uri,null); return returnUri; } @Override public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) { final SQLiteDatabase sqLiteDatabase = mFavoritelistDbHelper.getWritableDatabase(); int match = sUriMatcher.match(uri); int moviesDeleted; switch (match){ case FAVORITELIST: { moviesDeleted = sqLiteDatabase .delete(FavoritelistContract.FavortitelistEntry.TABLE_NAME, "movieId=?", selectionArgs); break; } default: throw new UnsupportedOperationException("Unknown uri: " + uri); } if (moviesDeleted != 0) { getContext().getContentResolver().notifyChange(uri, null); } return moviesDeleted; } @Override public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) { return 0; } }
package com.example.ComicToon.Models.ModelRepositories; import java.util.List; import com.example.ComicToon.Models.ReportedSeriesModel; import org.springframework.data.mongodb.repository.MongoRepository; public interface ReportedSeriesRepository extends MongoRepository<ReportedSeriesModel, String>{ public ReportedSeriesModel findByid(String id); public List<ReportedSeriesModel> findByuserID(String userID); //person who's reporting public List<ReportedSeriesModel> findByseriesID(String seriesID); //all instances of series reported public List<ReportedSeriesModel> findAll(); }
package com.tencent.tinker.lib.e; import android.content.Context; public final class c { public static void bP(Context context, String str) { a.hL(context).vsx.acN(str); } }
package de.jmda.app.uml.main.jaxb; import de.jmda.app.uml.diagram.type.jaxb.NodeManagerData; import de.jmda.core.cdi.event.ActionOnEvent.AbstractEvent; /** Used in CDI events to publish the {@code JavaModelConfig} currently in use. */ public class PublishNodeManagerDataResponse extends AbstractEvent<NodeManagerData> { public PublishNodeManagerDataResponse(Object source, NodeManagerData nodeManagerData) { super(source, nodeManagerData); } public NodeManagerData getNodeManagerData() { return getData().get(); } }
package com.temple.service; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.text.ParseException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.log4j.Logger; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONObject; import com.temple.repository.IRepositoryEntityTypes; import com.temple.repository.IRepositroyCommunication; import com.temple.repository.RepositoryCommunicationFactory; import com.temple.util.TempleUtility; /** * @author Mayur Jain * */ @Path("/programService") public class ProgramService { final static Logger logger = Logger.getLogger(ProgramService.class); @GET @Path("/addNewProgramType") @Produces(MediaType.APPLICATION_JSON) public Response addNewProgramType( @QueryParam("programType") String programType, @QueryParam("programDesc") String programDesc) { logger.debug("Calling addNewProgramType"); IRepositroyCommunication repository = null; PreparedStatement statement = null; try { repository = RepositoryCommunicationFactory.newInstance(); String SQL = "Insert into " + IRepositoryEntityTypes.PROGRAM_TYPE + "(PTProgramType,PTProgramDesc)" + " values(?,?)"; logger.debug(SQL); statement = repository.getPreparedStatement(SQL); statement.setString(1, programType); statement.setString(2, programDesc); if (statement.executeUpdate() > 0) { return Response .ok() .entity("sucessfully saved the " + "program type to repository").build(); } else { logger.error("Failed to save the " + "program type to repository"); return Response .serverError() .entity("Failed to save the " + "program type to repository").build(); } } catch (Exception e) { logger.error("Problem Occured atserver side", e); return Response .serverError() .entity("Problem Occured at " + "server side\n.Reason:" + e.getMessage()).build(); } finally { if (repository != null) try { repository.close(); } catch (Exception e) { logger.error("Problem Occured atserver side", e); return Response .serverError() .entity("Problem Occured at " + "server side\n.Details:"+e.getMessage()).build(); } } } @GET @Path("/getProgramTypes") @Produces(MediaType.APPLICATION_JSON) public Response getProgramType() { logger.debug("Calling getProgramType"); IRepositroyCommunication repository = null; PreparedStatement statement = null; try { repository = RepositoryCommunicationFactory.newInstance(); String SQL = "SELECT PTProgramType from " + IRepositoryEntityTypes.PROGRAM_TYPE; logger.debug(SQL); statement = repository.getPreparedStatement(SQL); ResultSet result=statement.executeQuery(); JSONArray array = new JSONArray(); while(result.next()){ JSONObject response=new JSONObject(); response.put("name", result.getString("PTProgramType")); response.put("id", result.getString("PTProgramType")); array.put(response); } return Response.ok().entity(array.toString()).build(); } catch (Exception e) { logger.error("Problem Occured atserver side", e); return Response .serverError() .entity("Problem Occured at " + "server side\n.Reason:" + e.getMessage()).build(); } finally { if (repository != null) try { repository.close(); } catch (Exception e) { logger.error("Problem Occured atserver side", e); return Response .serverError() .entity("Problem Occured at " + "server side\n.Details:"+e.getMessage()).build(); } } } @GET @Path("/getProgramNames") @Produces(MediaType.APPLICATION_JSON) public Response getProgramNames() { logger.debug("Calling getProgramNames"); IRepositroyCommunication repository = null; PreparedStatement statement = null; try { repository = RepositoryCommunicationFactory.newInstance(); String SQL = "SELECT PMProgramID,PMProgramName from " + IRepositoryEntityTypes.PROGRAM_MASTER; logger.debug(SQL); statement = repository.getPreparedStatement(SQL); ResultSet result=statement.executeQuery(); JSONArray array = new JSONArray(); while(result.next()){ JSONObject response=new JSONObject(); response.put("name", result.getString("PMProgramName")); response.put("id", result.getString("PMProgramID")); array.put(response); } return Response.ok().entity(array.toString()).build(); } catch (Exception e) { logger.error("Problem Occured at server side", e); return Response .serverError() .entity("Problem Occured at " + "server side\n.Reason:" + e.getMessage()).build(); } finally { if (repository != null) try { repository.close(); } catch (Exception e) { logger.error("Problem Occured at server side", e); return Response .serverError() .entity("Problem Occured at " + "server side\n.Details:"+e.getMessage()).build(); } } } @GET @Path("/getMentors") @Produces(MediaType.APPLICATION_JSON) public Response getMentors() { logger.debug("Calling getMentors"); IRepositroyCommunication repository = null; PreparedStatement statement = null; try { repository = RepositoryCommunicationFactory.newInstance(); String SQL = "SELECT MIMentorID,MIMentorInitiatedName from " + IRepositoryEntityTypes.MENTOR_INFO; logger.debug(SQL); statement = repository.getPreparedStatement(SQL); ResultSet result=statement.executeQuery(); JSONArray array = new JSONArray(); while(result.next()){ JSONObject response=new JSONObject(); response.put("name", result.getString("MIMentorInitiatedName")); response.put("id", result.getString("MIMentorID")); array.put(response); } return Response.ok().entity(array.toString()).build(); } catch (Exception e) { logger.error("Problem Occured at server side", e); return Response .serverError() .entity("Problem Occured at " + "server side\n.Reason:" + e.getMessage()).build(); } finally { if (repository != null) try { repository.close(); } catch (Exception e) { logger.error("Problem Occured at server side", e); return Response .serverError() .entity("Problem Occured at " + "server side\n.Details:"+e.getMessage()).build(); } } } @GET @Path("/programMaster") @Produces(MediaType.APPLICATION_JSON) public Response addNewProgramMaster( @QueryParam("programType") String programType, @QueryParam("programDesc") String programDesc, @QueryParam("programInterval") String programInterval, @QueryParam("mentorId") int mentorId, @QueryParam("assmentorId") int assmentorId, @QueryParam("programName") String programName) { logger.debug("Calling addNewProgramMaster"); IRepositroyCommunication repository = null; PreparedStatement statement = null; try { repository = RepositoryCommunicationFactory.newInstance(); String SQL = "Insert into " + IRepositoryEntityTypes.PROGRAM_MASTER + "(PMProgramType,PMProgramDescription" + ",PMProgramInterval,PMMentorID,PMAsstMentorID,PMProgramName)" + " values(?,?,?,?,?,?)"; logger.debug(SQL); statement = repository.getPreparedStatement(SQL, Statement.RETURN_GENERATED_KEYS); statement.setString(1, programType); statement.setString(2, programDesc); statement.setString(3, programInterval); statement.setInt(4, mentorId); statement.setInt(5, assmentorId); statement.setString(6, programName); if (statement.executeUpdate() > 0) { ResultSet tableKeys = statement.getGeneratedKeys(); tableKeys.next(); int autoGeneratedID = tableKeys.getInt(1); return Response .ok() .entity("Sucessfully saved the " + "program master with ID= " + autoGeneratedID + " to repository").build(); } else { logger.error("Failed to save the " + "program master to repository"); return Response .serverError() .entity("Failed to save the " + "program master to repository").build(); } } catch (Exception e) { logger.error("Problem Occured at server side", e); return Response .serverError() .entity("Problem Occured at " + "server side\n.Reason:" + e.getMessage()).build(); } finally { if (repository != null) try { statement.close(); repository.close(); } catch (Exception e) { logger.error("Problem Occured at server side", e); return Response .serverError() .entity("Problem Occured at " + "server side\n.Details:"+e.getMessage()).build(); } } } @GET @Path("/programParticipation") @Produces(MediaType.APPLICATION_JSON) public Response programParticipation( @QueryParam("programId") int programId, @QueryParam("enrolementDate") String enrolementDate, @QueryParam("devoteeId") int devoteeId, @QueryParam("devoteeName") String devoteeName) { logger.debug("Calling programParticipation"); IRepositroyCommunication repository = null; PreparedStatement statement = null; Date enrolement = null; try { repository = RepositoryCommunicationFactory.newInstance(); String SQL = "Insert into " + IRepositoryEntityTypes.PROGRAM_PARTICIPATION + " (PPDevoteeID,PPProgramID,PPEnrolementDate,PPDevoteeName)" + " values(?,?,?,?)"; logger.debug(SQL); try { enrolement = TempleUtility.getSQLDateFromString(enrolementDate); } catch (ParseException e) { return Response .serverError() .entity("Invalid date format provided for devotee enrolment date.") .build(); } statement = repository.getPreparedStatement(SQL); statement.setInt(1, devoteeId); statement.setInt(2, programId); statement.setDate(3, enrolement); statement.setString(4, devoteeName); if (statement.executeUpdate() > 0) { return Response .ok() .entity("sucessfully saved the " + "program participation to repository") .build(); } else { logger.error("Failed to save the " + "program participation to repository"); return Response .serverError() .entity("Failed to save the " + "program participation to repository") .build(); } } catch (Exception e) { logger.error("Problem Occured at server side", e); return Response .serverError() .entity("Problem Occured at " + "server side\n.Reason:" + e.getMessage()).build(); } finally { if (repository != null) try { statement.close(); repository.close(); } catch (Exception e) { logger.error("Problem Occured at server side", e); return Response .serverError() .entity("Problem Occured at " + "server side\n.Details:"+e.getMessage()).build(); } } } @GET @Path("/getProgramParticipants") @Produces(MediaType.APPLICATION_JSON) public Response getProgramParticipants(@QueryParam("programID") int programID) { logger.debug("Calling getProgramParticipants"); IRepositroyCommunication repository = null; PreparedStatement statement = null; try { repository = RepositoryCommunicationFactory.newInstance(); String SQL = "select PROGRAM_PARTICIPATION.PPDevoteeID , DEVOTEE_INFO.DILegalName, DEVOTEE_INFO.DIInitiatedName , DEVOTEE_INFO.DISmsPhone,DEVOTEE_INFO.DIArea from " +IRepositoryEntityTypes.DEVOTEE_INFO+"," +IRepositoryEntityTypes.PROGRAM_PARTICIPATION +" where PROGRAM_PARTICIPATION.PPDevoteeID=DEVOTEE_INFO.DIDevoteeID and PROGRAM_PARTICIPATION.PPProgramID=?" ; logger.debug(SQL); statement = repository.getPreparedStatement(SQL); statement.setInt(1, programID); ResultSet result=statement.executeQuery(); JSONArray array = new JSONArray(); while(result.next()){ JSONObject response=new JSONObject(); response.put("id", result.getString("PPDevoteeID")); response.put("lname", result.getString("DILegalName")); response.put("iname", result.getString("DIInitiatedName")); response.put("mobile", result.getString("DISmsPhone")); response.put("area", result.getString("DIArea")); array.put(response); } return Response.ok().entity(array.toString()).build(); } catch (Exception e) { logger.error("Problem Occured at server side", e); return Response .serverError() .entity("Problem Occured at " + "server side\n.Reason:" + e.getMessage()).build(); } finally { if (repository != null) try { repository.close(); } catch (Exception e) { logger.error("Problem Occured at server side", e); return Response .serverError() .entity("Problem Occured at " + "server side\n.Details:"+e.getMessage()).build(); } } } private int getDevoteeId(String mobileNo)throws Exception{ logger.debug("Calling getDevoteeId"); IRepositroyCommunication repository = null; PreparedStatement statement = null; int devoteeId=0; try { repository = RepositoryCommunicationFactory.newInstance(); String SQL = "select DIDevoteeID from " + IRepositoryEntityTypes.DEVOTEE_INFO+ " where DISmsPhone=?" ; statement = repository.getPreparedStatement(SQL); statement.setString(1, mobileNo); ResultSet result=statement.executeQuery(); while(result.next()){ devoteeId=result.getInt("DIDevoteeID"); } } catch (Exception e) { throw e; } finally { if (repository != null) try { statement.close(); repository.close(); } catch (Exception e) { e.printStackTrace(); } } return devoteeId; } @GET @Path("/programAttendance") @Produces(MediaType.APPLICATION_JSON) public Response programAttendance( @QueryParam("programId") int programId, @QueryParam("devoteeIds") String devoteeIds, @QueryParam("programdate") String programdate) { logger.debug("Calling programAttendance"); IRepositroyCommunication repository = null; PreparedStatement statement = null; Date date = null; try { repository = RepositoryCommunicationFactory.newInstance(); String SQL = "Insert into " + IRepositoryEntityTypes.PROGRAM_ATTENDANCE + "(PAProgramID,PADevoteeID,PAProgramDate)" + " values(?,?,?)"; logger.debug(SQL); try { date = TempleUtility.getSQLDateFromString(programdate); } catch (ParseException e) { logger.error("Invalid date format provided for program date."); return Response .serverError() .entity("Invalid date format provided for program date.") .build(); } String[]devoteesId= devoteeIds.split(","); statement = repository.getPreparedStatement(SQL); for(String devoteeId:devoteesId){ statement.setInt(1,programId); statement.setInt(2, Integer.parseInt(devoteeId)); statement.setDate(3, date); statement.addBatch(); } if (statement.executeBatch().length ==devoteesId.length) { return Response .ok() .entity("sucessfully saved the " + "program attendance to repository").build(); } else { logger.error("Failed to save the " + "program attendance to repository"); return Response .serverError() .entity("Failed to save the " + "program attendance to repository").build(); } } catch (Exception e) { logger.error("Problem Occured at " + "server side", e); return Response .serverError() .entity("Problem Occured at " + "server side\n.Reason:" + e.getMessage()).build(); } finally { if (repository != null) try { statement.close(); repository.close(); } catch (Exception e) { logger.error("Problem Occured at " + "server side", e); return Response .serverError() .entity("Problem Occured at " + "server side\n.Details:"+e.getMessage()).build(); } } } }
package com.baomidou.mybatisplus.samples.quickstart; import lombok.extern.slf4j.Slf4j; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import javax.annotation.Resource; import java.util.concurrent.ThreadPoolExecutor; @SpringBootApplication @MapperScan("com.baomidou.mybatisplus.samples.quickstart.mapper") @Slf4j public class MybatisApplication { @Resource private Environment env; public static void main(String[] args) { SpringApplication.run(MybatisApplication.class, args); } @Bean public ThreadPoolTaskExecutor threadPoolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(16); executor.setMaxPoolSize(300); executor.setQueueCapacity(500); executor.setThreadNamePrefix("defaultThreadPool_"); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //็บฟ็จ‹็ฉบ้—ฒๅŽ็š„ๆœ€ๅคงๅญ˜ๆดปๆ—ถ้—ด executor.setKeepAliveSeconds(60); executor.initialize(); log.info("ๅˆๅง‹ๅŒ–็บฟ็จ‹ๆฑ ๆˆๅŠŸ~"); return executor; } @Bean public CommandLineRunner commandLineRunner(ApplicationContext ctx) { return args -> { log.debug("Let's inspect the beans provided by Spring Boot:"); log.info(String.format("\n----------------------------------------------------------\n\t" + "Application '%s' is running! Access URLs:\n\t" + "Local: \t\thttp://localhost:%s\n\t" + "The following profiles are active: %s\n" + "----------------------------------------------------------", env.getProperty("spring.application.name"), env.getProperty("server.port"), env.getProperty("spring.profiles.active"))); }; } }
package it.polimi.se2019; import it.polimi.se2019.rmi.UserTimeoutException; import it.polimi.se2019.controller.GameBoardController; import it.polimi.se2019.controller.PlayerController; import it.polimi.se2019.model.GameBoard; import it.polimi.se2019.model.deck.Decks; import it.polimi.se2019.model.grabbable.*; import it.polimi.se2019.model.map.*; import it.polimi.se2019.model.player.Player; import it.polimi.se2019.view.player.PlayerViewOnServer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import java.util.ArrayList; import java.util.List; import static junit.framework.TestCase.assertTrue; import static junit.framework.TestCase.fail; import static org.mockito.Matchers.any; /** * @author Eugenio Ostrovan */ //@RunWith(MockitoJUnitRunner.class) public class TestMoveAndGrab { @Mock PlayerViewOnServer client; @Mock Decks decksReference; @Before public void initMocks() { MockitoAnnotations.initMocks(this); } @Test public void runAroundTest() throws UnknownMapTypeException { try { GameBoard gameBoard = new GameBoard(0); Player player = new Player("playerName", "playerCharacter", gameBoard); Player shooter = new Player("shooterName", "shooterCharacter", gameBoard); List<Player> players = new ArrayList<>(); players.add(player); players.add(shooter); gameBoard.addPlayers(players); GameBoardController gameBoardController = new GameBoardController(gameBoard); PlayerController playerController = new PlayerController(gameBoardController, player, client); player.moveToSquare(gameBoard.getMap().getMapSquares()[0][0]); List<Square> threeMovesAway = gameBoard.getMap().getReachableSquares(player.getPosition(), 3); List<List<Integer>> threeMovesAwayCoordinates = new ArrayList<>(); for(Square q : threeMovesAway){ threeMovesAwayCoordinates.add(gameBoard.getMap().getSquareCoordinates(q)); } Mockito.when(client.chooseTargetSquare(any())).thenReturn(threeMovesAwayCoordinates.get(0)); //test run around in state adrenaline 1 playerController.setState(1); playerController.getState().runAround(); assertTrue(player.getPosition().equals(threeMovesAway.get(0))); //test run around in state adrenaline 2 playerController.setState(2); threeMovesAway = gameBoard.getMap().getReachableSquares(player.getPosition(), 3); threeMovesAwayCoordinates.clear(); for(Square q : threeMovesAway){ threeMovesAwayCoordinates.add(gameBoard.getMap().getSquareCoordinates(q)); } playerController.getState().runAround(); assertTrue(player.getPosition().equals(threeMovesAway.get(0))); //test run around in state normal playerController.setState(0); threeMovesAway = gameBoard.getMap().getReachableSquares(player.getPosition(), 3); threeMovesAwayCoordinates.clear(); for(Square q : threeMovesAway){ threeMovesAwayCoordinates.add(gameBoard.getMap().getSquareCoordinates(q)); } playerController.getState().runAround(); assertTrue(player.getPosition().equals(threeMovesAway.get(0))); //test run around in state frenetic 1 playerController.setState(3); List<Square> fourMovesAway = gameBoard.getMap().getReachableSquares(player.getPosition(), 4); assertTrue(!fourMovesAway.isEmpty()); List<List<Integer>> fourMovesAwayCoordinates = new ArrayList<>(); for(Square q : fourMovesAway){ fourMovesAwayCoordinates.add(gameBoard.getMap().getSquareCoordinates(q)); } assertTrue(!fourMovesAwayCoordinates.isEmpty()); //Mockito.when(client.chooseTargetSquare(fourMovesAwayCoordinates)).thenReturn(fourMovesAwayCoordinates // .get(0)); playerController.getState().runAround(); assertTrue(player.getPosition().equals(fourMovesAway.get(0))); } catch (UserTimeoutException e){ fail("Network Timeout Reached"); } } @Test public void grabStuffAdrenaline1Test() throws UnknownMapTypeException{ GameBoard gameBoard = new GameBoard(0); Player player = new Player("playerName", "playerCharacter", gameBoard); Player shooter = new Player("shooterName", "shooterCharacter", gameBoard); GameBoardController gameBoardController = new GameBoardController(gameBoard); PlayerController playerController = new PlayerController(gameBoardController, player, client); try { player.moveToSquare(gameBoard.getMap().getMapSquares()[0][0]); gameBoard.getMap().getMapSquares()[0][0].refill(); List<Square> twoMovesAway = gameBoard.getMap().getReachableSquares(player.getPosition(), 2); List<List<Integer>> twoMovesAwayCoordinates = new ArrayList<>(); for(Square q : twoMovesAway){ twoMovesAwayCoordinates.add(gameBoard.getMap().getSquareCoordinates(q)); } Mockito.when(client.chooseTargetSquare(twoMovesAwayCoordinates)).thenReturn(twoMovesAwayCoordinates.get(0)); Mockito.when(client.chooseItemToGrab()).thenReturn(0); PowerUpCard powerUpCard = new PowerUpCard(new Ammo(1, 0, 0), "NewtonController"); //Mockito.when(decksReference.drawPowerUp()).thenReturn(powerUpCard); playerController.setState(1); Grabbable item = twoMovesAway.get(0).getItem().get(0); playerController.getState().grabStuff(); if(item instanceof Weapon){ Weapon weapon = (Weapon)item; assertTrue(player.getInventory().getWeapons().contains(weapon)); } else{ AmmoTile ammoTile = (AmmoTile)item; Ammo ammo = ammoTile.getAmmo(); if(ammoTile.getPowerUp()){ assertTrue(player.getInventory().getPowerUps().size() == 2); } assertTrue(player.getInventory().getAmmo().getBlue(). equals(1 + ammo.getBlue())); assertTrue(player.getInventory().getAmmo().getRed(). equals(1 + ammo.getRed())); assertTrue(player.getInventory().getAmmo().getYellow(). equals(1 + ammo.getYellow())); } } catch (UserTimeoutException e){ fail("Network Timeout Reached"); } } @Test public void grabStuffAdrenaline2Test() throws UnknownMapTypeException{ GameBoard gameBoard = new GameBoard(0); Player player = new Player("playerName", "playerCharacter", gameBoard); Player shooter = new Player("shooterName", "shooterCharacter", gameBoard); GameBoardController gameBoardController = new GameBoardController(gameBoard); PlayerController playerController = new PlayerController(gameBoardController, player, client); try { player.moveToSquare(gameBoard.getMap().getMapSquares()[0][0]); gameBoard.getMap().getMapSquares()[0][0].refill(); List<Square> twoMovesAway = gameBoard.getMap().getReachableSquares(player.getPosition(), 2); List<List<Integer>> twoMovesAwayCoordinates = new ArrayList<>(); for(Square q : twoMovesAway){ twoMovesAwayCoordinates.add(gameBoard.getMap().getSquareCoordinates(q)); } Mockito.when(client.chooseTargetSquare(twoMovesAwayCoordinates)).thenReturn(twoMovesAwayCoordinates.get(0)); Mockito.when(client.chooseItemToGrab()).thenReturn(0); PowerUpCard powerUpCard = new PowerUpCard(new Ammo(1, 0, 0), "NewtonController"); //Mockito.when(decksReference.drawPowerUp()).thenReturn(powerUpCard); playerController.setState(2); Grabbable item = twoMovesAway.get(0).getItem().get(0); playerController.getState().grabStuff(); if(item instanceof Weapon){ Weapon weapon = (Weapon)item; assertTrue(player.getInventory().getWeapons().contains(weapon)); } else{ AmmoTile ammoTile = (AmmoTile)item; Ammo ammo = ammoTile.getAmmo(); if(ammoTile.getPowerUp()){ assertTrue(player.getInventory().getPowerUps().size() == 2); } assertTrue(player.getInventory().getAmmo().getBlue(). equals(1 + ammo.getBlue())); assertTrue(player.getInventory().getAmmo().getRed(). equals(1 + ammo.getRed())); assertTrue(player.getInventory().getAmmo().getYellow(). equals(1 + ammo.getYellow())); } } catch (UserTimeoutException e){ fail("Network Timeout Reached"); } } @Test public void grabStuffNormalTest() throws UnknownMapTypeException{ GameBoard gameBoard = new GameBoard(0); Player player = new Player("playerName", "playerCharacter", gameBoard); Player shooter = new Player("shooterName", "shooterCharacter", gameBoard); GameBoardController gameBoardController = new GameBoardController(gameBoard); PlayerController playerController = new PlayerController(gameBoardController, player, client); try { player.moveToSquare(gameBoard.getMap().getMapSquares()[0][0]); gameBoard.getMap().getMapSquares()[0][0].refill(); List<Square> oneMoveAway = gameBoard.getMap().getReachableSquares(player.getPosition(), 2); List<List<Integer>> oneMoveAwayCoordinates = new ArrayList<>(); for(Square q : oneMoveAway){ oneMoveAwayCoordinates.add(gameBoard.getMap().getSquareCoordinates(q)); } //Mockito.when(client.chooseTargetSquare(oneMoveAwayCoordinates)).thenReturn(oneMoveAwayCoordinates.get(0)); Mockito.when(client.chooseItemToGrab()).thenReturn(0); Mockito.when(client.chooseDirection(any())).thenReturn(5); PowerUpCard powerUpCard = new PowerUpCard(new Ammo(1, 0, 0), "NewtonController"); //Mockito.when(decksReference.drawPowerUp()).thenReturn(powerUpCard); playerController.setState(0); assertTrue(playerController.getState() != null); Grabbable item = oneMoveAway.get(0).getItem().get(0); playerController.getState().grabStuff(); if(item instanceof Weapon){ Weapon weapon = (Weapon)item; assertTrue(player.getInventory().getWeapons().contains(weapon)); } else{ AmmoTile ammoTile = (AmmoTile)item; Ammo ammo = ammoTile.getAmmo(); if(ammoTile.getPowerUp()){ assertTrue(player.getInventory().getPowerUps().size() == 2); } assertTrue(player.getInventory().getAmmo().getBlue(). equals(1 + ammo.getBlue())); assertTrue(player.getInventory().getAmmo().getRed(). equals(1 + ammo.getRed())); assertTrue(player.getInventory().getAmmo().getYellow(). equals(1 + ammo.getYellow())); } } catch (UserTimeoutException e){ fail("Network Timeout Reached"); } } }
/** * */ package kit.edu.pse.goapp.server.creating_obj_with_dao; import java.io.IOException; import kit.edu.pse.goapp.server.daos.MeetingDAO; import kit.edu.pse.goapp.server.daos.MeetingDaoImpl; import kit.edu.pse.goapp.server.datamodels.Meeting; import kit.edu.pse.goapp.server.exceptions.CustomServerException; /** * @author Iris * */ public class MeetingWithDao { /** * Creates a meeting with DAO * * @param meetingId * meetingId * @param userId * the user's ID who has to be added to the meeting * @return meeting meeting * @throws IOException * IOException * @throws CustomServerException * CustomServerException */ public Meeting createMeetingWithDao(int meetingId, int userId) throws IOException, CustomServerException { MeetingDAO dao = new MeetingDaoImpl(); dao.setMeetingId(meetingId); dao.setUserId(userId); Meeting meeting = dao.getMeetingByID(); return meeting; } }
package states; import foodchain.products.Apple; import foodchain.products.Milk; import foodchain.states.*; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class StateTest { // ---------- UNIT TESTS ---------- @Test public void prepare_GrowingApple_CollectedApple(){ // ARRANGE Apple apple = new Apple(); GrowingState stateControl = new GrowingState(); String expectedAppleState = "Collected"; // ACT stateControl.prepare(apple); String realAppleState = apple.getState().getStateName(); // ASSERT assertEquals(expectedAppleState, realAppleState); } // TEST FAILS - ERROR DETECTED // Expected : some kind of exception // Actual : nothing @Test public void prepare_Milk_throwsException(){ // ARRANGE Milk milk = new Milk(); RawState stateControl = new RawState(); // ASSERT assertThrows(Exception.class, () -> { // ACT stateControl.prepare(milk); }); } }
package Generic_class; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.testng.Reporter; public class Generic_Excel { public static String getData(String sheet,int row,int cell) throws EncryptedDocumentException, InvalidFormatException, IOException { String v=""; try { FileInputStream fis=new FileInputStream("./Excel/data3.xlsx"); Workbook wb = WorkbookFactory.create(fis); Sheet sh = wb.getSheet(sheet); Row r = sh.getRow(row); Cell c = r.getCell(cell); v=c.toString(); System.out.println(v); } catch (Exception e) { Reporter.log("path is invalid",true); } return v; } }
package com.xxxair; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.xxxair.medet.util.UserSecurityInterceptor; @SpringBootApplication public class Application extends WebMvcConfigurerAdapter{ public static void main(String[] args) throws Exception { SpringApplication.run(Application.class); } @Bean public UserSecurityInterceptor initUserSecurityInterceptor(){ return new UserSecurityInterceptor(); } public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(initUserSecurityInterceptor()).addPathPatterns("/delivery/v1/mobile/auth/**"); } }
package tests.amazonTest; import org.openqa.selenium.WebDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import selenium.DriverSetup; public class AmazonTest { @BeforeClass(alwaysRun = true) public void setupClass() { } @BeforeMethod(alwaysRun = true) public void setupTest() { } @Parameters() @Test(description = "Test Description") public void groupSetup() throws Exception{ WebDriver driver = DriverSetup.setupDriver(DriverSetup.Browser.Chrome, "chromedriver 3"); driver.get("https://www.amazon.com"); } @AfterMethod(alwaysRun = true) public void tearDownTest() { } @AfterClass(alwaysRun = true) public void tearDownClass() { } }
/* * Copyright (C) 2018 askaeks * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package restaurant.frames; import java.text.NumberFormat; import java.util.Locale; import javax.swing.JFrame; import javax.swing.event.ListSelectionEvent; import restaurant.dialogs.PesananDialog; import restaurant.dialogs.PesananExtendDialog; import restaurant.models.OrderKasirModel; import restaurant.objects.KasirObject; import restaurant.objects.MenuObject; import restaurant.objects.OrderObject; import restaurant.states.ApplicationState; /** * * @author askaeks */ public class Kasir extends javax.swing.JFrame { private final String username; private final OrderKasirModel modelOrderKasir = new OrderKasirModel(); /** * Creates new form Cashier * @param pFrame */ public Kasir(JFrame pFrame) { this.setLocationRelativeTo(pFrame); pFrame.dispose(); username = ApplicationState.getUsername(); initComponents(); tblPesanan.getSelectionModel().addListSelectionListener((ListSelectionEvent event) -> { // do some actions here, for example // print first column value from selected row if (event.getValueIsAdjusting() == false) { btnSelengkapnya.setEnabled(true); } }); } /** * 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() { jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); tblTambahPesanan = new javax.swing.JButton(); btnSelengkapnya = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); tblPesanan = new javax.swing.JTable(); jPanel3 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Restaurant Order Management System - Kasir"); setResizable(false); tblTambahPesanan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/restaurant/images/add.png"))); // NOI18N tblTambahPesanan.setText("Tambah Pesanan"); tblTambahPesanan.setIconTextGap(5); tblTambahPesanan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tblTambahPesananActionPerformed(evt); } }); btnSelengkapnya.setIcon(new javax.swing.ImageIcon(getClass().getResource("/restaurant/images/more.png"))); // NOI18N btnSelengkapnya.setText("Lihat Lengkap"); btnSelengkapnya.setEnabled(false); btnSelengkapnya.setIconTextGap(5); btnSelengkapnya.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSelengkapnyaActionPerformed(evt); } }); tblPesanan.setModel(modelOrderKasir); jScrollPane2.setViewportView(tblPesanan); 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() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btnSelengkapnya, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 340, Short.MAX_VALUE) .addComponent(tblTambahPesanan, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(tblTambahPesanan, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnSelengkapnya, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)) .addGap(6, 6, 6)) ); jTabbedPane1.addTab("Riwayat Pesanan", jPanel1); jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/restaurant/images/enter.png"))); // NOI18N jButton1.setText("Keluar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); 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() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(511, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(299, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Help", jPanel3); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jTabbedPane1) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jTabbedPane1) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void tblTambahPesananActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tblTambahPesananActionPerformed PesananDialog dialog = new PesananDialog(this, true); dialog.setVisible(true); if (dialog != (null)) { if (dialog.isSaved) { OrderObject o = new OrderObject(null, dialog.meja, dialog.pelayan, new KasirObject(null, ApplicationState.getUsername(), null, null), dialog.totalHarga); modelOrderKasir.add(o, dialog.selectedMenu); } } }//GEN-LAST:event_tblTambahPesananActionPerformed private String rupiah(Integer rupiah) { return NumberFormat.getCurrencyInstance(new Locale("id", "ID")).format(rupiah); } private void btnSelengkapnyaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelengkapnyaActionPerformed if (!tblPesanan.getSelectionModel().isSelectionEmpty()) { OrderObject order = modelOrderKasir.get(tblPesanan.getSelectedRow()); StringBuilder stringOutput = new StringBuilder(); stringOutput.append("========== INFO ==========\n"); stringOutput.append("Nomor\t: ").append(order.getIdPesanan()).append("\n"); stringOutput.append("Pelayan\t: ").append(order.getPelayan().getNama()).append("\n"); stringOutput.append("Meja\t: ").append(order.getMeja().getKode()).append("\n"); stringOutput.append("========== PESANAN ==========\n"); Integer i = 0; for (MenuObject m : order.getMenuList()) { stringOutput.append(++i).append(". ").append(m.getNama()).append("\n"); } stringOutput.append("========== PEMBAYARAN ==========\n"); stringOutput.append("Total Harga\t: ").append(rupiah(order.getHarga())); stringOutput.append("\n\nTerima kasih telah membeli produk kami.\n"); stringOutput.append("========== TERIMA KASIH ==========\n"); PesananExtendDialog pes = new PesananExtendDialog(this, true, stringOutput.toString()); pes.setVisible(true); } }//GEN-LAST:event_btnSelengkapnyaActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed ApplicationState.logout(); new Masuk(this).setVisible(true); this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnSelengkapnya; private javax.swing.JButton jButton1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTable tblPesanan; private javax.swing.JButton tblTambahPesanan; // End of variables declaration//GEN-END:variables }
package org.jcarvajal.webapp.servlet.controllers.impl; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Role allowed. * * @author jhilario * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Role { public String name(); }
package techokami.lib.block; import techokami.lib.block.TileEntitySlots.EnumIO; import techokami.lib.client.BlockBaseRender; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.World; public class BlockSlots extends BlockBase { private IIcon sideInput, sideOutput; public BlockSlots(Material material, Object parent) { super(material, parent); } @Override public TileEntity createNewTileEntity(World world, int metadata) { return new TileEntitySlots(); } @Override public boolean renderAsNormalBlock() { return false; } @Override public boolean canRenderInPass(int pass) { BlockBaseRender.renderPass = pass; return true; } @Override public int getRenderBlockPass() { return 1; } public IIcon getSlotIcon(World world, int x, int y, int z, int side) { TileEntitySlots te = (TileEntitySlots)world.getTileEntity(x, y, z); EnumIO slot = te.getSlotForSide(side); return slot == EnumIO.INPUT ? sideInput : (slot == EnumIO.OUTPUT ? sideOutput : null); } @Override public void registerBlockIcons(IIconRegister ir) { super.registerBlockIcons(ir); sideInput = ir.registerIcon("asielib:side_input"); sideOutput = ir.registerIcon("asielib:side_output"); } }
package pl.lua.aws.core.config; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.oauth2.client.CommonOAuth2Provider; import org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient; import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient; import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository; import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository; import org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import pl.lua.aws.core.filter.UserFilter; import javax.servlet.Filter; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @Configuration @PropertySource("classpath:application.yml") @Slf4j public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static List<String> clients = Arrays.asList("google"); private static String CLIENT_PROPERTY_KEY = "spring.security.oauth2.client.registration."; @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterAfter(userFilter(), BasicAuthenticationFilter.class); http.csrf() .disable(); http.authorizeRequests() .antMatchers("/oauth_login","/css/**","/js/**","/img/**","/vendor/**","/fonts/**") .permitAll() .anyRequest() .authenticated() .and() .oauth2Login() .loginPage("/oauth_login") .authorizationEndpoint() .baseUri("/oauth2/authorize-client") .authorizationRequestRepository(authorizationRequestRepository()) .and() .tokenEndpoint() .accessTokenResponseClient(accessTokenResponseClient()) .and() .defaultSuccessUrl("/loginSuccess",true) .failureUrl("/loginFailure"); } @Bean public Filter userFilter() { return new UserFilter(); } @Bean public AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository() { return new HttpSessionOAuth2AuthorizationRequestRepository(); } @Bean public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() { DefaultAuthorizationCodeTokenResponseClient accessTokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient(); return accessTokenResponseClient; } public ClientRegistrationRepository clientRegistrationRepository() { List<ClientRegistration> registrations = clients.stream() .map(c -> getRegistration(c)) .filter(registration -> registration != null) .collect(Collectors.toList()); return new InMemoryClientRegistrationRepository(registrations); } @Autowired private Environment env; private ClientRegistration getRegistration(String client) { String clientId = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-id"); if (clientId == null) { return null; } String clientSecret = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-secret"); if (client.equals("google")) { return CommonOAuth2Provider.GOOGLE.getBuilder(client) .clientId(clientId) .clientSecret(clientSecret) .build(); } // if (client.equals("facebook")) { // return CommonOAuth2Provider.FACEBOOK.getBuilder(client) // .clientId(clientId) // .clientSecret(clientSecret) // .build(); // } return null; } }
package com.tencent.mm.plugin.game.gamewebview.ipc; import android.content.Intent; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.MMActivity.a; class GameProcessActivityTask$1 implements a { final /* synthetic */ GameProcessActivityTask jGi; GameProcessActivityTask$1(GameProcessActivityTask gameProcessActivityTask) { this.jGi = gameProcessActivityTask; } public final void b(int i, int i2, Intent intent) { if (i == (this.jGi.hashCode() & 65535) && intent != null) { GameProcessActivityTask gameProcessActivityTask = (GameProcessActivityTask) intent.getParcelableExtra("task_object"); GameProcessActivityTask Dd = GameProcessActivityTask.Dd(intent.getStringExtra("task_id")); if (Dd == null) { x.e("MicroMsg.GameProcessActivityTask", "task is null"); return; } GameProcessActivityTask.a(gameProcessActivityTask, Dd); GameProcessActivityTask.fEi.remove(Dd); Dd.aaj(); this.jGi.mContext = null; } } }
package edu.buet.cse.spring.ch03.v3.impl; import javax.inject.Inject; import edu.buet.cse.spring.ch03.v3.model.Instrument; import edu.buet.cse.spring.ch03.v3.model.Performer; import edu.buet.cse.spring.ch03.v3.qualifier.StringedInstrument; public class Guiterist implements Performer { private final Instrument instrument; @Inject public Guiterist(@StringedInstrument Instrument instrument) { this.instrument = instrument; } public Instrument getInstrument() { return instrument; } @Override public void perform() { System.out.printf("Playing the instrument %s: %n", instrument.getName()); instrument.play(); } }
package com.weekendproject.connectivly.repository; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.weekendproject.connectivly.model.SalesOrder; @Repository public interface SalesOrderRepository extends JpaRepository<SalesOrder, Long>, JpaSpecificationExecutor<SalesOrder> { SalesOrder findByPoCode(String poNumber); Optional<SalesOrder> findByCode(String code); Page<SalesOrder> findAllByUserIdAndIsLinkedAndIsApproved(Pageable page, String string, String string2, boolean b); interface SalesOrderViewDetail{ Long getSoId(); Long getSopId(); String getCode(); String getPoCode(); Date getSoDate(); Integer getAvailable(); Integer getQuantity(); Double getPrice(); Double getPercent(); Double getTotal(); String getName(); String getBrands(); } @Query(value = "select so.id as soId, so.code, so.po_code as poCode, so.so_date as soDate, "+ "sop.id as sopId, sop.available_qty as available, sop.quantity, sop.price, sop.percent_1 as percent, sop.total, "+ "p.name, m.brands from sales_order so "+ "inner join sales_order_product sop "+ "on so.id = sop.sales_order_id "+ "inner join products p "+ "on sop.product_id = p.id "+ "inner join master m "+ "on p.brand_id = m.id "+ "where so.code = :code and so.user_id = :userId", nativeQuery = true) List<SalesOrderViewDetail> viewSalesOrderDetail(@Param("userId") String userId, @Param("code") String code); }
package ws_service; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.xml.ws.Endpoint; import java.io.IOException; /** * Created by Just on 2016/3/3. */ @WebFilter(value = "") public class MyWebServicePublishFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { String address = "http://192.168.155.3:8080/webservice"; //ๅ‘ๅธƒWebService๏ผŒWebServiceImpl็ฑปๆ˜ฏWebServieๆŽฅๅฃ็š„ๅ…ทไฝ“ๅฎž็Žฐ็ฑป Endpoint.publish(address, new MyWebServiceImpl()); System.out.println("ไฝฟ็”จWebServicePublishFilterๅ‘ๅธƒwebserviceๆˆๅŠŸ!"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { } @Override public void destroy() { } }
package kickercup.xml; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.Collections; import java.util.Collection; import kickercup.xml.Gruppierungen; import kickercup.xml.Gruppierung; import kickercup.xml.Mannschaften; import kickercup.xml.Mannschaft; /** * Write a description of class Tabelle here. * * @author (your name) * @version (a version number or a date) */ public class Tabelle { private Map<String,MannschaftContainer> tabelleMap; /** * Constructor for objects of class Tabelle */ public Tabelle() { tabelleMap = new HashMap<String,MannschaftContainer>(); } private void addMannschaft(MannschaftContainer mannschaftContainer){ String key = mannschaftContainer.getMannschaftID(); MannschaftContainer value = mannschaftContainer; tabelleMap.put(key, value); } public void addMannschaften(Mannschaften mannschaften){ if(mannschaften != null){ List<Mannschaft> list = mannschaften.selectAll(); if(list != null && !list.isEmpty()){ for(Iterator<Mannschaft> it = list.iterator(); it.hasNext();){ Mannschaft mannschaft = it.next(); MannschaftContainer mannschaftContainer = new MannschaftContainer(mannschaft); addMannschaft(mannschaftContainer); } } } } public void addGruppierungen(Gruppierungen gruppierungen){ if(gruppierungen != null){ List<Gruppierung> list = gruppierungen.selectAll(); if(list != null && !list.isEmpty()){ setErgebnisse(list); } } } public List<MannschaftContainer> getTabelleMannschaften(String geschlecht, int klasse){ List<MannschaftContainer> newList = new ArrayList<MannschaftContainer>(); if(!tabelleMap.isEmpty()){ Collection<MannschaftContainer> coll = tabelleMap.values(); for(Iterator<MannschaftContainer> it = coll.iterator(); it.hasNext();){ MannschaftContainer mannschaftContainer = it.next(); String geschechtC = mannschaftContainer.getGeschlecht(); int klasseC = mannschaftContainer.getKlasse(); if(klasse == klasseC && geschlecht.equals(geschechtC)){ newList.add(mannschaftContainer); } } Collections.sort(newList, new ComparatorRangliste()); } return newList; } private void setErgebnisse(List<Gruppierung> lisGruppierung ){ if(lisGruppierung != null && !lisGruppierung.isEmpty()){ for(Iterator<Gruppierung> it = lisGruppierung.iterator(); it.hasNext();){ Gruppierung gruppierung = it.next(); String id1 = gruppierung.getMannschaftID1(); String id2 = gruppierung.getMannschaftID2(); if(tabelleMap != null && !tabelleMap.isEmpty() && tabelleMap.containsKey(id1) && tabelleMap.containsKey(id1)){ MannschaftContainer mann1 = tabelleMap.get(id1); MannschaftContainer mann2 = tabelleMap.get(id2); int tore1 = gruppierung.getTore1(); int tore2 = gruppierung.getTore2(); if(tore1 >= 0 && tore2 >= 0){ mann1.addToreErhalten(tore2); mann1.addToreGeschossen(tore1); mann2.addToreErhalten(tore1); mann2.addToreGeschossen(tore2); mann1.addSpiel(); mann2.addSpiel(); if(tore1 == tore2){ mann1.addPunkte(1); mann2.addPunkte(1); mann1.addUnentschieden(); mann2.addUnentschieden(); }else if(tore1 > tore2){ mann1.addPunkte(3); mann1.addSiege(); mann2.addNiederlagen(); }else{ mann2.addPunkte(3); mann2.addSiege(); mann1.addNiederlagen(); } } } } } } public static void main(String[] args){ Mannschaften m = new Mannschaften("C:\\Temp\\mannschaften.xml"); Gruppierungen g = new Gruppierungen("C:\\Temp\\gruppierungen.xml"); Tabelle tabelle = new Tabelle(); tabelle.addMannschaften(m); tabelle.addGruppierungen(g); List<MannschaftContainer> listKlasse5Jungs = tabelle.getTabelleMannschaften("m", 5); System.out.printf(" %1$s %7$-40.40s %2$s %3$s %4$s %5$s %6$s %8$s %n","ID", "G", "Punkte", "ToreGeschossen", "ToreErhalten", "Tordifferenz", "Schule", "Spiele"); for(Iterator<MannschaftContainer> it = listKlasse5Jungs.iterator(); it.hasNext();){ MannschaftContainer ma = it.next(); System.out.printf(" %1$s %7$-40.40s %2$s %3$d %4$d %5$d %6$d %8$s %n",ma.getMannschaftID(), ma.getGeschlecht(), ma.getPunkte(), ma.getToreGeschossen(), ma.getToreErhalten(), ma.getTordifferenz(), ma.getSchule(), ma.getSpiele()); } } }
package com.zhowin.miyou.recommend.widget; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.PagerSnapHelper; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.SnapHelper; /** * author : zho * date ๏ผš2020/9/22 * desc ๏ผšrecyclerView ๅฎž็Žฐ viewpager็š„ๆป‘ๅŠจๆ•ˆๆžœ */ public class VpRecyclerView extends RecyclerView { private int position = 0; public VpRecyclerView(@NonNull Context context) { super(context); initView(); } public VpRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); initView(); } private void initView() { LinearLayoutManager llm = new LinearLayoutManager(this.getContext()); llm.setOrientation(LinearLayoutManager.HORIZONTAL); this.setLayoutManager(llm); SnapHelper snapHelper = new PagerSnapHelper(); // SnapHelper snapHelper = new LinearSnapHelper(); //ไธ€ๆฌกๅฏๆป‘ๅŠจๅคšไธช snapHelper.attachToRecyclerView(this);//ๅฑ…ไธญๆ˜พ็คบRecyclerView this.addItemDecoration(new DividerItemDecoration(this.getContext(), DividerItemDecoration.HORIZONTAL)); this.addOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); if (layoutManager instanceof LinearLayoutManager) { int firs = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition(); if (position != firs) { position = firs; if (onpagerChangeListener != null) onpagerChangeListener.onPagerChange(position); } } } }); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { this.requestDisallowInterceptTouchEvent(true); //ไบ‹ไปถไธไผ ้€’็ป™็ˆถๅธƒๅฑ€ return super.dispatchTouchEvent(ev); } public void setOnPagerPosition(int position) { // this.position = position; RecyclerView.LayoutManager layoutManager = this.getLayoutManager(); layoutManager.scrollToPosition(position); } public int getOnPagerPosition() { RecyclerView.LayoutManager layoutManager = this.getLayoutManager(); return ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition(); } public interface onPagerChangeListener { void onPagerChange(int position); } private onPagerChangeListener onpagerChangeListener; public void setOnpagerChangeListener(onPagerChangeListener onpagerChangeListener) { this.onpagerChangeListener = onpagerChangeListener; } }
public class BacteriaGrowth{ public static Funksionet fn; public static NevilleN nv; public static GraphingBacteria gb; public static void main(String[] bgArgs){ double[] minutat = {35.0,43.0,52.0,73.0,84.0,91.0,95.0,98.0}; double[] bakterie = new double[minutat.length]; double vlperParashikim = 96.0; for(int i = 0; i<minutat.length; i++){ fn = new Funksionet(); bakterie[i] = fn.bacteriagrowth(minutat[i]); //System.out.println(bakterie[i]); } nv = new NevilleN(); double nrBakterieve = (nv.neville(minutat, bakterie,vlperParashikim)); System.out.println("Supozojme se nje bakterie ne kuzhine dyfishohet qdo 5 minuta, duke startuar me nje, pas " +vlperParashikim+ " minutash numri i baktereve(bazuar ne funksion) do te jete do te jete " +nrBakterieve ); //Pjesa e Vizatimit: double[] allMinutat = new double[minutat.length+1]; double[] allBakterie = new double[minutat.length+1]; for(int i = 0; i < allMinutat.length; i++){ if(i == allMinutat.length-1){ allMinutat[i] = vlperParashikim; allBakterie[i] = nrBakterieve; }else{ allMinutat[i] = minutat[i]; allBakterie[i] = bakterie[i]; } } allMinutat = sortMe(allMinutat); allBakterie = sortMe(allBakterie); gb = new GraphingBacteria(); gb.main(allMinutat, allBakterie, nrBakterieve, vlperParashikim); } public static double[] sortMe(double[] m){ double temp = 0.0; for (int i = 1; i < m.length; i++) { for(int j = i ; j > 0 ; j--){ if(m[j] < m[j-1]){ temp = m[j]; m[j] = m[j-1]; m[j-1] = temp; } } } return m; } }
package com.example.xinruigao.musicinbackground; import android.content.Context; import android.content.Intent; import android.renderscript.ScriptGroup; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { private Button buttonStart; private Button buttonStop; private EditText editTextInput; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //getting buttons from xml buttonStart = (Button) findViewById(R.id.button_start); buttonStop = (Button) findViewById(R.id.button_stop); editTextInput = findViewById(R.id.edit_text_input); //attaching onclicklistener to buttons } //onClick method public void startService(View v) { String input = editTextInput.getText().toString(); Intent serviceIntent = new Intent(this, MyService.class); serviceIntent.putExtra("inputExtra", input); //start service when app is in the background startForegroundService(serviceIntent); //hide soft keyboard after pressing button closeKeyBoard(); } //onClick method public void stopService(View v) { Intent serviceIntent = new Intent(this, MyService.class); stopService(serviceIntent); } private void closeKeyBoard(){ //current view View view = this.getCurrentFocus(); //if there is a view on focus if (view != null){ InputMethodManager imm = (InputMethodManager)getSystemService( Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } } }
/** * */ package org.cssociety.tincan.api.impl; import java.net.URI; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import org.cssociety.tincan.api.Activity; import org.cssociety.tincan.api.ActivityProfileResource; import org.cssociety.tincan.api.ActivityResource; import org.cssociety.tincan.api.StateResource; /** */ @ApplicationScoped class ActivityResourceImpl implements ActivityResource { @Inject private ActivityProfileResource profile; @Inject private StateResource state; /* * (non-Javadoc) * * @see org.cssociety.tincan.api.ActivityResource#get(java.net.URI) */ @Override public Activity get(URI activityId) { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see org.cssociety.tincan.api.ActivityResource#getProfileResource() */ @Override public ActivityProfileResource getProfileResource() { return profile; } /* * (non-Javadoc) * * @see org.cssociety.tincan.api.ActivityResource#getStateResource() */ @Override public StateResource getStateResource() { return state; } }
package com.tencent.mm.plugin.freewifi.ui; import android.content.Intent; import android.content.IntentFilter; import android.net.NetworkInfo.State; import android.view.KeyEvent; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.tencent.mm.R; import com.tencent.mm.ak.a.a.c; import com.tencent.mm.ak.o; import com.tencent.mm.compatible.e.q; import com.tencent.mm.plugin.freewifi.g; import com.tencent.mm.plugin.freewifi.l; import com.tencent.mm.plugin.freewifi.m; import com.tencent.mm.plugin.freewifi.model.FreeWifiNetworkReceiver; import com.tencent.mm.plugin.freewifi.model.FreeWifiNetworkReceiver.a; import com.tencent.mm.plugin.freewifi.model.FreeWifiNetworkReceiver.b; import com.tencent.mm.plugin.freewifi.model.d; import com.tencent.mm.sdk.e.j; import com.tencent.mm.sdk.platformtools.al; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.ui.base.h; import com.tencent.mm.ui.base.p; @Deprecated public abstract class FreeWifiStateUI extends MMActivity implements a, b { protected String bIQ; private int bLv = 1; protected String bPS; protected String bPg; protected int bxk; private final c dXk; protected String jkH; protected String jkJ; protected String jlY; protected FreeWifiNetworkReceiver jlZ; private TextView jmC; private ImageView jmP; private TextView jmQ; private TextView jmR; private Button jmS; private Button jmT; protected String jmW; protected String jmX; protected String jmY; protected String jmZ; protected boolean jma = false; private al jmc = new al(new 1(this), false); private al jmd = new al(new 2(this), true); private j.a jme; private p jnR = null; protected int jnW; protected String jnX; protected String jnY; protected String signature; protected int source; protected String ssid; protected abstract void Yz(); public abstract void a(State state); protected abstract void aPp(); protected abstract int aPq(); public FreeWifiStateUI() { c.a aVar = new c.a(); aVar.dXw = true; aVar.dXx = true; aVar.dXN = R.g.free_wifi_icon_default; aVar.dXW = true; aVar.dXX = 0.0f; this.dXk = aVar.Pt(); this.jme = new 3(this); } static /* synthetic */ void d(FreeWifiStateUI freeWifiStateUI) { if (freeWifiStateUI.jlZ == null) { freeWifiStateUI.aPv(); } freeWifiStateUI.jlZ.jjY = freeWifiStateUI; d.aOw(); } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ public void onCreate(android.os.Bundle r9) { /* r8 = this; r7 = 3; r6 = 2; r1 = 1; r2 = 0; super.onCreate(r9); r0 = r8.getIntent(); r3 = "free_wifi_ap_key"; r0 = r0.getStringExtra(r3); r8.bIQ = r0; r0 = r8.getIntent(); r3 = "free_wifi_ssid"; r0 = r0.getStringExtra(r3); r8.ssid = r0; r0 = r8.getIntent(); r3 = "free_wifi_mid"; r0 = r0.getStringExtra(r3); r8.jlY = r0; r0 = r8.getIntent(); r3 = "free_wifi_url"; r0 = r0.getStringExtra(r3); r8.jkH = r0; r0 = r8.getIntent(); r3 = "free_wifi_source"; r0 = r0.getIntExtra(r3, r1); r8.source = r0; r0 = r8.getIntent(); r3 = "free_wifi_channel_id"; r0 = r0.getIntExtra(r3, r2); r8.bxk = r0; r0 = r8.getIntent(); r3 = "free_wifi_appid"; r0 = r0.getStringExtra(r3); r8.bPS = r0; r0 = r8.getIntent(); r3 = "free_wifi_head_img_url"; r0 = r0.getStringExtra(r3); r8.jmW = r0; r0 = r8.getIntent(); r3 = "free_wifi_welcome_msg"; r0 = r0.getStringExtra(r3); r8.jmX = r0; r0 = r8.getIntent(); r3 = "free_wifi_welcome_sub_title"; r0 = r0.getStringExtra(r3); r8.jmY = r0; r0 = r8.getIntent(); r3 = "free_wifi_privacy_url"; r0 = r0.getStringExtra(r3); r8.jmZ = r0; r0 = r8.getIntent(); r3 = "free_wifi_app_nickname"; r0 = r0.getStringExtra(r3); r8.jkJ = r0; r0 = r8.source; switch(r0) { case 1: goto L_0x011b; case 2: goto L_0x00e3; case 3: goto L_0x011b; case 4: goto L_0x011b; case 5: goto L_0x011b; case 6: goto L_0x011b; default: goto L_0x00a8; }; L_0x00a8: r0 = r8.ssid; r0 = com.tencent.mm.sdk.platformtools.bi.oW(r0); if (r0 == 0) goto L_0x0178; L_0x00b0: r0 = "MicroMsg.FreeWifi.FreeWifiStateUI"; r1 = "ssid is null"; com.tencent.mm.sdk.platformtools.x.e(r0, r1); L_0x00b9: r8.initView(); r0 = com.tencent.mm.plugin.freewifi.model.j.aOK(); r1 = r8.jme; r0.c(r1); r0 = com.tencent.mm.plugin.freewifi.model.d.aOB(); r1 = r8.getIntent(); r3 = "free_wifi_ap_key"; r1 = r1.getStringExtra(r3); r3 = r8.getIntent(); r4 = "free_wifi_protocol_type"; r2 = r3.getIntExtra(r4, r2); com.tencent.mm.plugin.freewifi.l.s(r0, r1, r2); return; L_0x00e3: r0 = com.tencent.mm.plugin.freewifi.model.j.aOK(); r0 = r0.aPn(); if (r0 == 0) goto L_0x0111; L_0x00ed: r3 = r0.field_ssid; r8.ssid = r3; r3 = r0.field_mid; r8.jlY = r3; r0 = r0.field_url; r8.jkH = r0; r0 = "MicroMsg.FreeWifi.FreeWifiStateUI"; r3 = "source from mainui banner, ssid : %s, mid : %s, url : %s"; r4 = new java.lang.Object[r7]; r5 = r8.ssid; r4[r2] = r5; r5 = r8.jlY; r4[r1] = r5; r5 = r8.jkH; r4[r6] = r5; com.tencent.mm.sdk.platformtools.x.i(r0, r3, r4); goto L_0x00a8; L_0x0111: r0 = "MicroMsg.FreeWifi.FreeWifiStateUI"; r3 = "there is no connect sucessfull wifi info"; com.tencent.mm.sdk.platformtools.x.i(r0, r3); goto L_0x00a8; L_0x011b: r0 = r8.ssid; r0 = com.tencent.mm.sdk.platformtools.bi.oW(r0); if (r0 == 0) goto L_0x012d; L_0x0123: r0 = "MicroMsg.FreeWifi.FreeWifiStateUI"; r1 = "ssid is null"; com.tencent.mm.sdk.platformtools.x.e(r0, r1); goto L_0x00b9; L_0x012d: r0 = com.tencent.mm.plugin.freewifi.model.j.aOK(); r3 = r8.ssid; r3 = r0.Cg(r3); if (r3 != 0) goto L_0x0195; L_0x0139: r3 = new com.tencent.mm.plugin.freewifi.g.c; r3.<init>(); r0 = r8.ssid; r0 = com.tencent.mm.sdk.platformtools.ac.ce(r0); r3.field_ssidmd5 = r0; r0 = r8.ssid; r3.field_ssid = r0; r0 = r1; L_0x014b: r4 = r8.jkH; r3.field_url = r4; r4 = r8.jlY; r3.field_mid = r4; r4 = r8.getIntent(); r5 = "free_wifi_auth_type"; r4 = r4.getIntExtra(r5, r6); r3.field_wifiType = r4; r3.field_connectState = r1; if (r0 == 0) goto L_0x016d; L_0x0164: r0 = com.tencent.mm.plugin.freewifi.model.j.aOK(); r0.b(r3); goto L_0x00a8; L_0x016d: r0 = com.tencent.mm.plugin.freewifi.model.j.aOK(); r4 = new java.lang.String[r2]; r0.c(r3, r4); goto L_0x00a8; L_0x0178: r0 = "MicroMsg.FreeWifi.FreeWifiStateUI"; r3 = "ssid : %s, mid : %s, source : %d"; r4 = new java.lang.Object[r7]; r5 = r8.ssid; r4[r2] = r5; r5 = r8.jlY; r4[r1] = r5; r1 = r8.source; r1 = java.lang.Integer.valueOf(r1); r4[r6] = r1; com.tencent.mm.sdk.platformtools.x.i(r0, r3, r4); goto L_0x00b9; L_0x0195: r0 = r2; goto L_0x014b; */ throw new UnsupportedOperationException("Method not decompiled: com.tencent.mm.plugin.freewifi.ui.FreeWifiStateUI.onCreate(android.os.Bundle):void"); } protected final int getForceOrientation() { return 1; } protected void initView() { setBackBtn(new 4(this)); if (getIntent().getIntExtra("free_wifi_protocol_type", 0) == 1) { findViewById(R.h.user_protocol_phone_text).setVisibility(0); } this.jmP = (ImageView) findViewById(R.h.free_wifi_app_logo_iv); this.jmQ = (TextView) findViewById(R.h.free_wifi_welcomemsg_tv); this.jmR = (TextView) findViewById(R.h.free_wifi_ssidname_tv); this.jmC = (TextView) findViewById(R.h.free_wifi_connectfail_tv); this.jmS = (Button) findViewById(R.h.connect_wifi_btn); this.jmS.setOnClickListener(new 5(this)); this.jmT = (Button) findViewById(R.h.user_protocol_privacy_btn); this.jmT.setOnClickListener(new 6(this)); if (bi.oW(this.ssid)) { this.jmR.setText(getString(R.l.free_wifi_ssid_empty_tips)); this.jmS.setVisibility(4); } } protected final void aPs() { if (this.jlZ != null) { x.i("MicroMsg.FreeWifi.FreeWifiStateUI", "now unregister wifi state change receiver"); this.jlZ.jjY = null; } } protected final void aPt() { if (this.jlZ == null) { aPv(); } this.jlZ.jjZ = this; } protected final void aPu() { if (this.jlZ != null) { x.i("MicroMsg.FreeWifi.FreeWifiStateUI", "now unregister network changed receiver"); this.jlZ.jjZ = null; } } private void aPv() { this.jlZ = new FreeWifiNetworkReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED"); intentFilter.addAction("android.net.wifi.STATE_CHANGE"); registerReceiver(this.jlZ, intentFilter); } protected final void aPw() { if (d.isWifiEnabled()) { this.bLv = aPq(); x.i("MicroMsg.FreeWifi.FreeWifiStateUI", "now before connect, the connect state : %d", Integer.valueOf(this.bLv)); if (this.bLv != 2) { if (m.G(getIntent()) == 4) { this.jmc.J(30000, 30000); } else { this.jmc.J(60000, 60000); } this.jmd.J(1000, 1000); if (d.BY(this.ssid)) { x.i("MicroMsg.FreeWifi.FreeWifiStateUI", "start auth now, isAuting : %b", Boolean.valueOf(this.jma)); if (this.jma) { x.d("MicroMsg.FreeWifi.FreeWifiStateUI", "now it is authing"); return; } this.jmc.J(60000, 60000); this.jmd.J(1000, 1000); Yz(); this.jma = true; return; } com.tencent.mm.plugin.freewifi.model.j.aON().aOv().post(new 8(this)); return; } d.a(this.ssid, this.bLv, getIntent()); return; } this.jmc.J(60000, 60000); this.jmd.J(1000, 1000); x.i("MicroMsg.FreeWifi.FreeWifiStateUI", "wifi is not enable, enable it"); com.tencent.mm.plugin.freewifi.model.j.aON().aOv().post(new 7(this)); } protected final void ph(int i) { x.i("MicroMsg.FreeWifi.FreeWifiStateUI", "Current connection state : %d", Integer.valueOf(i)); switch (i) { case -2014: if (this.jnR != null) { this.jnR.dismiss(); } this.jmc.SO(); this.jmd.SO(); this.jmC.setVisibility(0); this.jmS.setText(R.l.free_wifi_re_connect); return; case -1: return; case 1: this.jmC.setVisibility(4); this.jmS.setText(R.l.connect_state_connecting_ing); this.jnR = h.a(this.mController.tml, getString(R.l.connect_state_connecting_ing), true, new 9(this)); return; case 2: if (this.jnR != null) { this.jnR.dismiss(); } this.jmc.SO(); this.jmd.SO(); this.jmS.setText(R.l.connect_state_connected); this.jmS.setClickable(false); Intent intent = getIntent(); intent.putExtra("free_wifi_appid", this.bPS); intent.putExtra("free_wifi_app_nickname", this.jkJ); intent.putExtra("free_wifi_app_username", this.bPg); intent.putExtra("free_wifi_signature", this.signature); intent.putExtra("free_wifi_finish_actioncode", this.jnW); intent.putExtra("free_wifi_finish_url", this.jnX); if (bi.oW(this.jnY)) { intent.setClass(this, FreeWifiSuccUI.class); } else { intent.putExtra("free_wifi_qinghuai_url", this.jnY); intent.setClass(this, FreeWifiSuccWebViewUI.class); } a(); startActivity(intent); d.xP(); return; case 3: if (this.jnR != null) { this.jnR.dismiss(); } this.jmc.SO(); this.jmd.SO(); this.jmC.setVisibility(0); this.jmS.setText(R.l.free_wifi_re_connect); return; case 4: if (this.jnR != null) { this.jnR.dismiss(); } this.jmc.SO(); this.jmd.SO(); this.jma = false; this.jmC.setVisibility(4); this.jmS.setText(R.l.connect_state_wating); if (!(m.H(getIntent()) != 10 || m.isEmpty(q.deR.dfn) || m.isEmpty(q.br(this.mController.tml)))) { this.jmS.setText(String.format(getString(R.l.free_wifi_connect_btn_manu_wording), new Object[]{q.br(this.mController.tml)})); } if (this.source == 3) { this.jmR.setText(getString(R.l.mig_connect_state_connecting_tips, new Object[]{this.ssid})); } else if (bi.oW(this.jmY)) { this.jmR.setText(getString(R.l.connect_state_connecting_default_tips)); } else { this.jmR.setText(this.jmY); } if (!bi.oW(this.bPS)) { if (!bi.oW(this.jmX)) { this.jmQ.setText(this.jmX); } if (!bi.oW(this.jmW)) { o.Pj().a(this.jmW, this.jmP, this.dXk); return; } return; } return; default: if (this.jnR != null) { this.jnR.dismiss(); } this.jmC.setVisibility(4); this.jmS.setText(R.l.connect_state_wating); if (this.source == 3) { this.jmR.setText(getString(R.l.mig_connect_state_connecting_tips, new Object[]{this.ssid})); } else if (bi.oW(this.jmY)) { this.jmR.setText(getString(R.l.connect_state_connecting_default_tips)); } else { this.jmR.setText(this.jmY); } if (!bi.oW(this.bPS)) { if (!bi.oW(this.jmX)) { this.jmQ.setText(this.jmX); } if (!bi.oW(this.jmW)) { o.Pj().a(this.jmW, this.jmP, this.dXk); return; } return; } return; } } protected final int getLayoutId() { return R.i.free_wifi_front_page; } protected void onDestroy() { super.onDestroy(); com.tencent.mm.plugin.freewifi.model.j.aOK().d(this.jme); aPs(); aPu(); if (this.jlZ != null) { unregisterReceiver(this.jlZ); } this.jmc.SO(); this.jmd.SO(); com.tencent.mm.plugin.freewifi.model.j.aON().release(); } public final void qa(int i) { x.i("MicroMsg.FreeWifi.FreeWifiStateUI", "now wifi state : %d", Integer.valueOf(i)); switch (i) { case 3: aPs(); aPw(); return; default: return; } } public boolean onKeyDown(int i, KeyEvent keyEvent) { if (i != 4 || keyEvent.getRepeatCount() != 0) { return super.onKeyDown(i, keyEvent); } goBack(); return true; } private void goBack() { l.u(d.aOB(), getIntent().getStringExtra("free_wifi_ap_key"), getIntent().getIntExtra("free_wifi_protocol_type", 0)); g.ezn.i(new Intent(), this); a(); } }
package cpen221.mp3.wikimediator; public class NotInCacheException extends Exception { }
package com.salaboy.conferences.agenda.controller; import com.salaboy.conferences.agenda.util.AgendaItemCreator; import com.salaboy.conferences.agenda.AgendaServiceApplication; import com.salaboy.conferences.agenda.TestConfiguration; import com.salaboy.conferences.agenda.model.AgendaItem; import com.salaboy.conferences.agenda.repository.AgendaItemRepository; import org.junit.After; import org.junit.Test; import org.junit.jupiter.api.TestInstance; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; import org.springframework.data.mongodb.core.ReactiveMongoTemplate; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.BodyInserters; import static com.salaboy.conferences.agenda.util.AgendaItemCreator.otherValidWithDefaultDay; import static com.salaboy.conferences.agenda.util.AgendaItemCreator.validWithDefaultDay; import static org.assertj.core.api.Assertions.assertThat; @ContextConfiguration(classes = AgendaServiceApplication.class) @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureWebTestClient @Import(TestConfiguration.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class AgendaControllerIntegrationTest { @Autowired private WebTestClient webTestClient; @Autowired private AgendaItemRepository agendaItemRepository; @Autowired private ReactiveMongoTemplate reactiveMongoTemplate; @After public void after() { reactiveMongoTemplate.dropCollection(AgendaItem.class) .subscribe(); } @Test public void getAll_ShouldReturnsAll() { createAgendaItem(validWithDefaultDay()); createAgendaItem(otherValidWithDefaultDay()); var responseBody = getAll() .expectStatus() .isOk() .expectBodyList(AgendaItem.class) .returnResult() .getResponseBody(); assertThat(responseBody).hasSizeGreaterThan(0); } @Test public void newAgendaItem_shouldBeCreateANewAgendaItem() { // arrange var agendaItem = validWithDefaultDay(); // action, assert var responseBody = createAgendaItem(agendaItem) .expectStatus() .isOk() .expectBody(String.class) .returnResult() .getResponseBody(); assertThat(responseBody).isEqualTo("Agenda Item Added to Agenda"); } @Test public void newAgendaItem_shouldThrowsErrorIfTitleContainsFail() { // arrange var agendaItem = AgendaItemCreator.withFail(); // action, assert var responseBody = createAgendaItem(agendaItem) .expectStatus() .is5xxServerError() .expectBody(String.class) .returnResult() .getResponseBody(); assertThat(responseBody).contains("Internal Server Error"); } @Test public void clearAgendaItems_shouldBeClearAllAgendaItems() { // arrange deleteAll() .expectStatus() .isOk() .expectBody(Void.class) .returnResult().getResponseBody(); // action, assert getAll().expectBodyList(AgendaItem.class).hasSize(0); } @Test public void getAllByDay() { // arrange var agendaItem = validWithDefaultDay(); var otherAgendaItem = otherValidWithDefaultDay(); createAgendaItem(agendaItem); createAgendaItem(otherAgendaItem); var responseBody = webTestClient.get() .uri("/day/" + AgendaItemCreator.DAY) .exchange() .expectBodyList(AgendaItem.class) .returnResult() .getResponseBody(); assertThat(responseBody).first().isNotNull(); responseBody.stream().forEach(i -> { assertThat(i.getDay()).isEqualTo(AgendaItemCreator.DAY); }); } @Test public void getById_ShouldReturnsTheAgendaItemById() { createAgendaItem(validWithDefaultDay()); var responseBody = getAll().expectBodyList(AgendaItem.class).returnResult().getResponseBody(); var first = responseBody.stream().findFirst(); assertThat(first.isPresent()).isTrue(); var agendaItem = webTestClient.get() .uri("/" + first.get().getId()) .exchange() .expectBody(AgendaItem.class) .returnResult() .getResponseBody(); assertThat(agendaItem).isNotNull(); assertThat(agendaItem.getId()).isEqualTo(first.get().getId()); } private WebTestClient.ResponseSpec getAll() { return webTestClient.get().uri("/").exchange(); } private WebTestClient.ResponseSpec createAgendaItem(final AgendaItem agendaItem) { return webTestClient.post() .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(agendaItem)) .exchange(); } private WebTestClient.ResponseSpec deleteAll() { return webTestClient.delete().uri("/").exchange(); } }
/* * Copyright 2002-2013 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 * * 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.springframework.integration.kafka.support; import java.util.Collection; import java.util.Map; import java.util.Properties; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.*; import org.springframework.messaging.Message; /** * @author Soby Chacko * @author Rajasekar Elango * @since 0.5 */ public class KafkaProducerContext<K,V> implements BeanFactoryAware { private static final Log LOGGER = LogFactory.getLog(KafkaProducerContext.class); private Map<String, ProducerConfiguration<K,V>> topicsConfiguration; private Properties producerProperties; public void send(final Message<?> message) throws Exception { final ProducerConfiguration<K,V> producerConfiguration = getTopicConfiguration(message.getHeaders().get("topic", String.class)); if (producerConfiguration != null) { producerConfiguration.send(message); } } public ProducerConfiguration<K, V> getTopicConfiguration(final String topic) { final Collection<ProducerConfiguration<K,V>> topics = topicsConfiguration.values(); for (final ProducerConfiguration<K,V> producerConfiguration : topics){ if (topic.matches(producerConfiguration.getProducerMetadata().getTopic())){ return producerConfiguration; } } LOGGER.error("No producer-configuration defined for topic " + topic + ". cannot send message"); return null; } public Map<String, ProducerConfiguration<K,V>> getTopicsConfiguration() { return topicsConfiguration; } @Override @SuppressWarnings("unchecked") public void setBeanFactory(final BeanFactory beanFactory) throws BeansException { topicsConfiguration = (Map<String, ProducerConfiguration<K,V>>) (Object) ((ListableBeanFactory)beanFactory).getBeansOfType(ProducerConfiguration.class); } /** * @param producerProperties * The producerProperties to set. */ public void setProducerProperties(Properties producerProperties) { this.producerProperties = producerProperties; } /** * @return Returns the producerProperties. */ public Properties getProducerProperties() { return producerProperties; } }
package com.revature.page; import java.time.Duration; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class FinanceManagerHomepage { private WebDriver driver; private WebDriverWait wdw; // explicit waits // PageFactory annotation = @FindBy... @FindBy(xpath = "//h1[contains(text(),'Welcome to Finance Manager Homepage')]") private WebElement welcomeHeading; @FindBy(xpath = "//button[@id='logout-btn']") private WebElement signOutButton; @FindBy(xpath = "//select[@id='status-dropdown']") private WebElement filterStatusInput; @FindBy(xpath = "//button[@id='status-filter-btn']") private WebElement filterStatusButton; @FindBy(xpath = "//tbody//tr//td//select") private WebElement upDateStatusInput; @FindBy(xpath = "//tbody/tr/td[12]/button[1]") private WebElement upDateStatusButton; public FinanceManagerHomepage(WebDriver driver) { this.driver = driver; // wait for a max of 10 sec before throwing an exception this.wdw = new WebDriverWait(driver, Duration.ofSeconds(10)); // PageFactor initialization PageFactory.initElements(driver, this); } public WebElement getWelcomeHeading() { return this.wdw.until(ExpectedConditions.visibilityOf(welcomeHeading)); } public WebElement getSignOutButton() { return this.signOutButton; } public WebElement getFilterStatusInput() { return this.filterStatusInput; } public WebElement getFilterStatusButton() { return this.filterStatusButton; } public WebElement getUpDateStatusInput() { return this.upDateStatusInput; } public WebElement getUpDateStatusButton() { return this.upDateStatusButton; } }
package com.hrms.synerzip; public class Constants { public static String URL = "https://hrms.synerzip.in/"; public static String advancereportpath ="E:\\TestNGAdvancedReport\\report\\"; public static String URL1 = "https://gmail.com"; public static String datadrivenexcel = "E:\\synerzip_workspace\\synerzip\\hrms\\datadriven"; public static String usernameuploadfile = "komal.hargunani@synerzip.com"; public static String passworduploadfile = "waheguru@1234"; public static String autoitfile = "E:\\AutoIT_script\\gmail_upload.exe"; public static String uploadfile1= "E:\\hrms\\testdata.xlsx"; public static String uploadfile12= "E:\\hrms\\abc.txt"; public static String multipleautoitfile = "E:\\AutoIT_script\\gmail_multiple_upload.exe"; // public static final String Username = "komal.hargunani"; // public static final String Password = "Synerzip@1234"; public static final String Path_TestData = "E:\\synerzip_workspace\\synerzip\\hrms\\testdata.xlsx"; public static final String File_TestData = "testdata.xlsx"; }
package Kap3; public class Digest { private String text; private String hashValue; public Digest() { } public Digest(String text) { this.text = text; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getHashValue() { return hashValue; } public void setHashValue(String hashValue) { this.hashValue = hashValue; } }
package university; public class Demo { public static void main(String[] args) { Studente enrico = new Studente("Enrico", "Bacis"); // ERROR: // Studente enrico = new Studente("", "Bacis"); // Studente enrico = new Studente("Enrico", ""); // Inserisco 4 voti enrico.aggiungiVoto(30); enrico.aggiungiVoto(27); enrico.aggiungiVoto(18); enrico.aggiungiVoto(28); // ERROR: // enrico.aggiungiVoto(17); // enrico.aggiungiVoto(31); // Verifichiamo che la lista sia ordinata System.out.println("Voti Inseriti: " + enrico.getNumeroVoti()); System.out.println(enrico); // Modifico l'anno di corso System.out.println(); enrico.incrementaAnnocorso(); System.out.println("Anno di corso: " + enrico.getAnnocorso()); // Verifica di max, min, numerovoti System.out.println(); System.out.println("Voto piรน basso: " + enrico.getMin()); System.out.println("Secondo voto piรน basso: " + enrico.getVoto(1)); System.out.println("Secondo voto piรน alto: " + enrico.getVoto(enrico.getNumeroVoti() - 2)); System.out.println("Voto piรน alto: " + enrico.getMax()); //ERROR: // System.out.println("Voto inesistente: " + enrico.getVoto(-1)); // System.out.println("Voto inesistente: " + enrico.getVoto(enrico.getNumeroVoti())); // Cambio di identitร  enrico.setNome("Buffer"); enrico.setCognome("Overflow"); // ERROR: // enrico.setNome(""); // enrico.setCognome(""); System.out.println(); System.out.println(enrico); } }
package per.goweii.wanandroid.utils; import per.goweii.basic.utils.AppInfoUtils; import per.goweii.basic.utils.SPUtils; /** * @author CuiZhen * @date 2019/5/19 * QQ: 302833254 * E-mail: goweii@163.com * GitHub: https://github.com/goweii */ public class UpdateUtils { private static final String SP_NAME = "update"; private static final String KEY_VERSION_CODE = "KEY_VERSION_CODE"; private static final String KEY_TIME = "KEY_TIME"; private final SPUtils mSPUtils = SPUtils.newInstance(SP_NAME); public static UpdateUtils newInstance() { return new UpdateUtils(); } private UpdateUtils() { } public void ignore(int versionCode) { mSPUtils.save(KEY_VERSION_CODE, versionCode); mSPUtils.save(KEY_TIME, System.currentTimeMillis()); } public boolean shouldUpdate(int versionCode){ if (!isNewest(versionCode)) { return false; } int ignoreCode = mSPUtils.get(KEY_VERSION_CODE, 0); if (versionCode > ignoreCode) { return true; } long currTime = System.currentTimeMillis(); long ignoreTime = mSPUtils.get(KEY_TIME, 0L); long duration = SettingUtils.getInstance().getUpdateIgnoreDuration(); return currTime - ignoreTime > duration; } public boolean isNewest(int versionCode){ int currCode = AppInfoUtils.getVersionCode(); return versionCode > currCode; } }
package day06_arithmetic_operators; public class ArithmeticOperators { public static void main (String [] args ){ System.out.println(5 + 10); System.out.println(10 - 3); System.out.println(3 * 3); System.out.println(15 / 5 ); System.out.println (17 % 6); System.out.println(-2 * 2); int chairs = 4 + 2 ; System.out.println(chairs); int plates = 10 + 12 + 20; System.out.println(plates); System.out.println("There are " + plates + " plates on the table."); } }
package com.tingke.admin.entity; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; import java.util.Date; /** * <p> * * </p> * * @author zhx * @since 2020-05-31 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @ApiModel(value="FrUserๅฏน่ฑก", description="") public class FrUser implements Serializable { private static final long serialVersionUID=1L; @ApiModelProperty(value = "ไธป้”ฎ") @TableId(value = "id", type = IdType.ID_WORKER_STR) private String id; @ApiModelProperty(value = "้‚ฎ็ฎฑ") private String email; @ApiModelProperty(value = "็”จๆˆทๅ") private String name; @ApiModelProperty(value = "ๅฏ†็ ") private String password; @ApiModelProperty(value = "็›") private String salt; @ApiModelProperty(value = "้€ป่พ‘ๅˆ ้™ค 0้ป˜่ฎค 1ๅทฒๅˆ ้™ค") private Integer isDeleted; @ApiModelProperty(value = "ๅˆ›ๅปบๆ—ถ้—ด") @TableField(fill = FieldFill.INSERT) private Date createTime; @ApiModelProperty(value = "ไฟฎๆ”นๆ—ถ้—ด") @TableField(fill = FieldFill.INSERT_UPDATE) private Date modifiedTime; }
package com.penzias.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import freemarker.cache.FileTemplateLoader; import freemarker.cache.StringTemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; public class TemplateUtil { private Logger logger = LoggerFactory.getLogger(getClass()); public String getReplacedStr(String src, Map<String, String> params){ Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); StringTemplateLoader loader = new StringTemplateLoader(); loader.putTemplate("urlTemplate", src); configuration.setTemplateLoader(loader); StringWriter sw = new StringWriter(); try { Template template = configuration.getTemplate("urlTemplate", "UTF-8"); template.process(params, sw); return sw.toString(); } catch (IOException e) { logger.error("่ฏปๅ–ๆจกๆฟ["+src+"]ๅคฑ่ดฅ๏ผ"); } catch (TemplateException e) { logger.error("ๆธฒๆŸ“ๆจกๆฟ["+src+"]้”™่ฏฏ๏ผ"); }finally{ try { sw.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } public void renderFile(String templatePath, String templateName,String fileName, Map<String, String> map) throws IOException{ Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); FileTemplateLoader loader = new FileTemplateLoader(new File(templatePath)); configuration.setTemplateLoader(loader); Template template = configuration.getTemplate(templateName); FileOutputStream out = new FileOutputStream(fileName); OutputStreamWriter osw = new OutputStreamWriter(out); try{ template.process(map, osw); } catch (TemplateException e){ e.printStackTrace(); }finally{ osw.close(); out.close(); } } }
package ch.ubx.startlist.server; import java.util.List; import java.util.Map; import ch.ubx.startlist.shared.Job; public interface JobDAO { public void removeJob(Job job); public void createOrUpdateJob(Job job); public List<Job> listAllJob(); public Map<String, Job> listJob(List<String> names); }
/** * Created by xyz on 20-Mar-17. */ public class treinumere { public static void main(String[] args) { int x; int y; int z; x=SkeletonJava.readIntConsole(" x = " ); y=SkeletonJava.readIntConsole(" y = " ); z=SkeletonJava.readIntConsole(" z = " ); if (x<y) { if (x < z) System.out.println(" X este cel mai mic"); else System.out.println(" Z este cel mai mic"); } else { if (y<z) System.out.println(" Y este cel mai mic"); else System.out.println(" Z este cel mai mic"); } } }
/* * Main.java * * MDK 4.0.1 - Clase para crear BD. * * 05/03/2016 * * Copyright Drintinยฉ 2016 */ package uy.com.karibe.console; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; public class Main { public static void main(String[] args) { Connection con = null; try { Properties p = new Properties(); String nomArch = "src/main/resources/Config.properties"; p.load(new FileInputStream(nomArch)); String driver = p.getProperty("persistencia.driver"); String url = p.getProperty("persistencia.url"); String user = p.getProperty("persistencia.user"); String password = p.getProperty("persistencia.password"); /* cargo el driver */ Class.forName(driver); con = (Connection) DriverManager.getConnection(url, user, password); /* creo la base de datos */ String database = "CREATE DATABASE mdk"; PreparedStatement pstmt = (PreparedStatement) con .prepareStatement(database); pstmt.executeUpdate(); pstmt.close(); /* creo la tabla para los juegos */ String games = "CREATE TABLE mdk.game " + "(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, " + "code varchar(10))"; pstmt = (PreparedStatement) con.prepareStatement(games); pstmt.executeUpdate(); pstmt.close(); /* inserto las 2 instancias del juego ("en curso" y "guardado") */ String insertGame1 = "insert into mdk.game(id) values (1)"; pstmt = (PreparedStatement) con.prepareStatement(insertGame1); pstmt.executeUpdate(); pstmt.close(); String insertGame2 = "insert into mdk.game(id) values (2)"; pstmt = (PreparedStatement) con.prepareStatement(insertGame2); pstmt.executeUpdate(); pstmt.close(); /* creo la tabla para las islas */ String islands = "CREATE TABLE mdk.islands " + "(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, " + " x int NOT NULL, " + " y int NOT NULL, " + " width int NOT NULL, " + " height int NOT NULL, " + " gameId int NOT NULL, " + " FOREIGN KEY (gameId) REFERENCES mdk.game(id))"; pstmt = (PreparedStatement) con.prepareStatement(islands); pstmt.executeUpdate(); pstmt.close(); /* creo la tabla de los puertos */ String ports = "CREATE TABLE mdk.ports " + "(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, " + " name varchar(50) NOT NULL, " + " x INT NOT NULL, " + " gameId int NOT NULL, " + " FOREIGN KEY (gameId) REFERENCES mdk.game(id))"; pstmt = (PreparedStatement) con.prepareStatement(ports); pstmt.executeUpdate(); pstmt.close(); /* creo la tabla de las naves */ String ships = "CREATE TABLE mdk.ships " + "(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, " + " name varchar(50) NOT NULL, " + " x int NOT NULL, " + " y int NOT NULL, " + " rotation int NOT NULL, " + " health int NOT NULL, " + " state varchar(50), " + " gameId int NOT NULL, " + " nickname varchar(50), " + " FOREIGN KEY (gameId) REFERENCES mdk.game(id))"; pstmt = (PreparedStatement) con.prepareStatement(ships); pstmt.executeUpdate(); pstmt.close(); } catch (FileNotFoundException e) { /* si no encuentra el archivo de configuracion */ e.printStackTrace(); } catch (IOException e) { /* si hay problema al leer el archivo de configuracion */ e.printStackTrace(); } catch (SQLException e) { /* si hay algun problema vinculado al DBMS o la BD */ e.printStackTrace(); } catch (ClassNotFoundException e) { /* si no se puede hallar la clase correspondiente al driver */ e.printStackTrace(); } finally { try { /* en cualquier caso, cierro la conexion */ if (con != null) con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
package com.microsilver.mrcard.basicservice.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @Data @ApiModel public class DeliveryScoreDto { @ApiModelProperty(value="้ช‘ๆ‰‹id") private Integer deliveryId; @ApiModelProperty(value="็”จๆˆทid") private Integer userId; @ApiModelProperty(value="่ฎขๅ•id") private Integer orderId; @ApiModelProperty(value="้ช‘ๆ‰‹่ฏ„ไปท็ฑปๅž‹") private Byte deliveryRaiseType; @ApiModelProperty(value="้ช‘ๆ‰‹่ฏ„ไปทๆ˜Ÿ็บง") private Integer starLevel; @ApiModelProperty(value="็”จๆˆทๆ€ป่ฏ„ๅˆ†") private Double levelScore; @ApiModelProperty(value="็”จๆˆท่ฎขๅ•ๆ•ฐ") private Integer orderCount; @ApiModelProperty(value="็”จๆˆท็ปผๅˆๅˆ†ๆ•ฐ") private Double serviceScore; }
package com.cotescu.radu.http.server.constants; import java.util.HashMap; import java.util.Map; /** * This class provides a useful map that associates {@link HTTPStatusCode}s with more descriptive error messages, used for displaying error * pages. * * @author Radu Cotescu * */ public class HTTPErrorStatusCodesMap { private static final Map<HTTPStatusCode, String> statusCodesMap = new HashMap<HTTPStatusCode, String>(); static { statusCodesMap.put(HTTPStatusCode.HTTP_NOT_FOUND, formatDescription(HTTPStatusCode.HTTP_NOT_FOUND.getStatusMessage(), "Resource not found.")); statusCodesMap.put(HTTPStatusCode.HTTP_FORBIDDEN, formatDescription(HTTPStatusCode.HTTP_FORBIDDEN.getStatusMessage(), "You are not allowed to access this resource.")); statusCodesMap .put(HTTPStatusCode.HTTP_BAD_REQUEST, formatDescription(HTTPStatusCode.HTTP_BAD_REQUEST.getStatusMessage(), "The request cannot be fulfilled due to bad syntax.")); statusCodesMap.put( HTTPStatusCode.HTTP_INTERNAL_SERVER_ERROR, formatDescription(HTTPStatusCode.HTTP_INTERNAL_SERVER_ERROR.getStatusMessage(), "The server encountered an internal error and cannot fulfill the request.")); statusCodesMap.put(HTTPStatusCode.HTTP_NOT_IMPLEMENTED, formatDescription(HTTPStatusCode.HTTP_NOT_IMPLEMENTED.getStatusMessage(), "The request method is not implemented.")); } /** * Provide a HTML formatted description. * * @param shortStatus * the short status of the HTTPStatusCode * @param description * the description of the HTTPStatus error code * @return a HTML formatted string */ private static String formatDescription(String shortStatus, String description) { return String.format("<h1>%s</h1>\n<p>%s</p>", shortStatus, description); } /** * Creates a HTML formatted string with the error message for a HTTPStatus error code. * * @param statusCode * the HTTPStatusCode for which the error will be generated * @return a String containing the HTML formatted error message */ public static String getErrorMessage(HTTPStatusCode statusCode) { return statusCodesMap.get(statusCode); } }
package PredicatesLamda; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; public class PredicateExamples { public static void main(String[] args) { Predicate<Employee> stringPredicate = (employee) -> employee.getName().startsWith("Raj"); Predicate<Employee> employeeNamePredicate = (employee) -> employee.getName().equals("Rajnikant"); Predicate<Employee> employeeAgePredicate = (employee) -> employee.getAge() > 35; Employee employee = new Employee(100, "Rajnikant", 38, "Software Engineer"); Employee employee1 = new Employee(101, "Rajnikant", 19, "Senior Software Engineer"); Employee employee2 = new Employee(102, "Vikas", 23, "Software Engineer"); Employee employee3 = new Employee(103, "Anubhav", 48, "Software Engineer"); Employee employee4 = new Employee(104, "Sreeni", 45, "Software Engineer"); List<Employee> employeeList = Arrays.asList(employee, employee1, employee2, employee3, employee4); employeeList.stream() .filter(stringPredicate) .forEach(System.out::println); // for (Employee employee123 : employeeList){ // if(employee123.getName().startsWith("Raj")){ // System.out.println(); } }
package com.hx.entity; /** * @program: eqds-ms * @description: * @author: yangyue * @create: 2019/12/19 17:06 */ public class User { private String id; private String username; private String password; private boolean simpled; @Override public String toString() { return "User{" + "id='" + id + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + ", simpled='" + simpled + '\'' + '}'; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isSimpled() { return simpled; } public void setSimpled(boolean simpled) { this.simpled = simpled; } }
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { //use the fast and slow pointer to get the middle of a ListNode ListNode getMiddleOfList(ListNode head) { ListNode slow = head; ListNode fast = head; while(fast.next!=null && fast.next.next!=null) { slow = slow.next; fast = fast.next.next; } return slow; } public ListNode sortList(ListNode head) { if(head==null||head.next==null) { return head; } ListNode middle = getMiddleOfList(head); ListNode next = middle.next; middle.next = null; return mergeList(sortList(head), sortList(next)); } //merge the two sorted list ListNode mergeList(ListNode a, ListNode b) { ListNode dummyHead = new ListNode(-1); ListNode curr = dummyHead; while(a!=null&&b!=null) { if(a.val<=b.val) { curr.next=a;a=a.next; } else { curr.next=b;b=b.next; } curr = curr.next; } curr.next = a!=null?a:b; return dummyHead.next; } }
/* * ExecuteSend.java * * Created on February 26, 2008, 3:05 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.sunspotworld; import com.sun.spot.sensorboard.EDemoBoard; import com.sun.spot.sensorboard.peripheral.TriColorLED; import com.sun.spot.sensorboard.peripheral.ITriColorLED; import com.sun.spot.sensorboard.peripheral.LEDColor; import com.sun.spot.sensorboard.io.PinDescriptor; import com.sun.spot.sensorboard.peripheral.IAccelerometer3D; import com.sun.spot.util.Utils; import com.sun.spot.sensorboard.io.InputPin ; import com.sun.spot.sensorboard.peripheral.ISwitch; import com.sun.spot.sensorboard.io.IInputPin; import com.sun.spot.sensorboard.io.IOutputPin; import com.sun.spot.peripheral.*; import com.sun.spot.util.Utils; import java.io.IOException; import java.lang.Object.*; import com.sun.spot.peripheral.radio.IRadioPolicyManager; import com.sun.spot.io.j2me.radiogram.*; import com.sun.spot.util.*; import java.io.*; import javax.microedition.io.*; import com.sun.spot.peripheral.Spot; import com.sun.spot.sensorboard.EDemoBoard; import com.sun.spot.peripheral.radio.IRadioPolicyManager; import java.util.Random; import java.util.Vector; import javax.microedition.io.Connector; import javax.microedition.io.Datagram; import javax.microedition.io.DatagramConnection; import org.sunspotworld.demo.utilities.RadioDataIOStream; //handles the data packets import org.sunspotworld.demo.utilities.StringTokenizer; //separately stores each word seperated by a space in a string import com.sun.spot.peripheral.IAT91_TC; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; import com.sun.spot.sensorboard.peripheral.LEDColor; /** * * @author Nikhil */ public class ExecuteSend implements Runnable{ EstComm estComm; Control_Sense controlSense = new Control_Sense(); ITriColorLED leds[] = EDemoBoard.getInstance().getLEDs(); byte DirCmd; String received; private Thread runThread; private boolean running = false; RadioDataIOStream OStream; public String message; public static boolean newcommand = false, newturn = false; public static byte direction; public static double arg1, arg2; public static int turnleft, turnright; public ExecuteSend() { } /****************************************************************** /*This method opens the Output radioStream to the Base-station / It is called from StartApplication when it receives any command. *It also initializes the UART for communication with PIC * / Input: null (uses global variables) * / Output: null (sets global variables) ******************************************************************/ public void reqStart () { System.out.println("started..."); OStream = RadioDataIOStream.openOutput(estComm.BASE_ID, 100); controlSense.demoBoard.initUART(9600, false); running = true; leds[3].setRGB(60,60,60); leds[3].setOff(); } /****************************************************************** /*This method closes the radioStream for the TriSpot and stops * execution of the Thread. / It is called from StartApplication when it receives a Disconnect * (END_COMM) command. * / Input: null (uses global variables) * / Output: null (sets global variables) ******************************************************************/ public void reqStop () { running = false; leds[3].setOff(); if (runThread != null) { runThread.interrupt(); } OStream.OutputClose(); System.out.println("thread stopped"); } /** On executing Thread.start(), the runnable interface * calls this method. * Start executing command and sending data to host. */ public void run() { runThread = Thread.currentThread(); while (running) { ExecuteAndSend(); } } /****************************************************************** /*This main program loop, calls all the relevant functions from the * Control_Sense.java file / * / Input: null (uses global variables) * / Output: null (sets global variables) ******************************************************************/ public void ExecuteAndSend(){ if(newcommand){ controlSense.setDirPosVel(direction, arg1, arg2); controlSense.leftPWM = (int)((4.27*arg2*100) + 91); controlSense.rightPWM = (int)((5.36*arg2*100) + 52); controlSense.motorEnable.setHigh(); newcommand = false; } if(newturn){ controlSense.setSpeeds(turnleft, turnright); controlSense.leftPWM = (int)((4.27*turnleft) + 91); controlSense.rightPWM = (int)((5.36*turnright) + 52); newturn = false; } controlSense.getEncTravel(); controlSense.setPWM(); controlSense.moveWheel(controlSense.leftPWM, controlSense.rightPWM); controlSense.getEncValues(); controlSense.getAccel(); try{ message = controlSense.getData(); OStream.writeUTF(message); OStream.flush(); //blink a light if(leds[3].isOn()) leds[3].setOff(); else leds[3].setOn(); } catch(IOException ex){} try { Thread.sleep(1); }catch (InterruptedException x) { // re-assert interrupt Thread.currentThread().interrupt(); } // if specified distance is traversed, then 'Stop' the TriSpot if(controlSense.lefttravel > controlSense.setLeftPosition && controlSense.righttravel > controlSense.setRightPosition){ controlSense.cmdFinish(); } } }
/* * 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 UserInterface; import Business.Address; import Business.Person; /** * * @author graceshi */ public class ViewPersonJPanel extends javax.swing.JPanel { /** * Creates new form ViewPersonJPanel */ Person P; Address address; public ViewPersonJPanel(Person P,Address address) { initComponents(); this.P=P; this.address=address; P.setAddress(address); firstnameJTextField.setText(P.getFirstname()); lastnameJTextField.setText(P.getLastname()); ssnJTextField.setText(String.valueOf(P.getSsn())); dobJTextField.setText(P.getDateofbirth()); firstnameJTextField.setText(P.getFirstname()); lastnameJTextField.setText(P.getLastname()); ssnJTextField.setText(String.valueOf(P.getSsn())); dobJTextField.setText(P.getDateofbirth()); streetJTextField.setText(P.getAddress().getStreetname()); cityJTextField.setText(P.getAddress().getCity()); countryJTextField.setText(P.getAddress().getCountry()); stateJTextField.setText(P.getAddress().getState()); zipcodeJTextField.setText(String.valueOf(P.getAddress().getZipcode())); } /** * 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() { firstnameJLabel = new javax.swing.JLabel(); firstnameJTextField = new javax.swing.JTextField(); lastnameJLabel = new javax.swing.JLabel(); lastnameJTextField = new javax.swing.JTextField(); dobJLabel = new javax.swing.JLabel(); dobJTextField = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); ssnJTextField = new javax.swing.JTextField(); streetJLabel = new javax.swing.JLabel(); streetJTextField = new javax.swing.JTextField(); cityJLabel = new javax.swing.JLabel(); cityJTextField = new javax.swing.JTextField(); stateJLabel = new javax.swing.JLabel(); stateJTextField = new javax.swing.JTextField(); countryJLabel = new javax.swing.JLabel(); countryJTextField = new javax.swing.JTextField(); zipcodeJLabel = new javax.swing.JLabel(); zipcodeJTextField = new javax.swing.JTextField(); firstnameJLabel.setText("FirstName"); lastnameJLabel.setText("LastName"); dobJLabel.setText("Date Of Birth"); jLabel1.setText("SSN"); streetJLabel.setText("Street"); cityJLabel.setText("County/City"); stateJLabel.setText("State"); countryJLabel.setText("Country"); zipcodeJLabel.setText("Zip Code"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(firstnameJLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lastnameJLabel) .addComponent(dobJLabel) .addComponent(jLabel1) .addComponent(streetJLabel) .addComponent(cityJLabel) .addComponent(stateJLabel) .addComponent(countryJLabel) .addComponent(zipcodeJLabel)) .addGap(63, 63, 63) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(firstnameJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lastnameJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(dobJTextField) .addComponent(ssnJTextField) .addComponent(streetJTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .addComponent(cityJTextField) .addComponent(stateJTextField)) .addComponent(countryJTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE) .addComponent(zipcodeJTextField)) .addContainerGap(80, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(firstnameJLabel) .addComponent(firstnameJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lastnameJLabel) .addComponent(lastnameJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(dobJLabel) .addComponent(dobJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(ssnJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(streetJLabel) .addComponent(streetJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cityJLabel) .addComponent(cityJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(stateJLabel) .addComponent(stateJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(26, 26, 26) .addComponent(countryJLabel)) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(countryJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(28, 28, 28) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(zipcodeJLabel) .addComponent(zipcodeJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(66, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel cityJLabel; private javax.swing.JTextField cityJTextField; private javax.swing.JLabel countryJLabel; private javax.swing.JTextField countryJTextField; private javax.swing.JLabel dobJLabel; private javax.swing.JTextField dobJTextField; private javax.swing.JLabel firstnameJLabel; private javax.swing.JTextField firstnameJTextField; private javax.swing.JLabel jLabel1; private javax.swing.JLabel lastnameJLabel; private javax.swing.JTextField lastnameJTextField; private javax.swing.JTextField ssnJTextField; private javax.swing.JLabel stateJLabel; private javax.swing.JTextField stateJTextField; private javax.swing.JLabel streetJLabel; private javax.swing.JTextField streetJTextField; private javax.swing.JLabel zipcodeJLabel; private javax.swing.JTextField zipcodeJTextField; // End of variables declaration//GEN-END:variables }
import java.nio.charset.Charset; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class EchoClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { //channelActive์ด๋ฒคํŠธ๋Š” ChannelInboundHandler์— ์ •์˜๋œ ์ด๋ฒคํŠธ๋กœ ์†Œ์ผ“์ฑ„๋„์ด ์ตœ์ดˆ๋กœ ํ™œ์„ฑํ™” ๋  ๋•Œ ์‹คํ–‰๋œ๋‹ค. String sendMessage = "Hello, Netty"; ByteBuf messageBuffer = Unpooled.buffer(); messageBuffer.writeBytes(sendMessage.getBytes()); StringBuilder builder = new StringBuilder(); builder.append("์ „์†กํ•œ ๋ฌธ์ž์—ด ["); builder.append(sendMessage); builder.append("]"); System.out.println(builder.toString()); ctx.writeAndFlush(messageBuffer); //writeAndFlush๋ฉ”์†Œ๋“œ๋Š” ๋‚ด๋ถ€์ ์œผ๋กœ ๋ฐ์ดํ„ฐ ๊ธฐ๋ก๊ณผ ์ „์†ก์˜ ๋‘ ๊ฐ€์ง€ ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•œ๋‹ค. //์ฑ„๋„์— ๋ฐ์ดํ„ฐ๋ฅผ ๊ธฐ๋กํ•˜๋Š” write๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•œ ๋’ค, //์ฑ„๋„์— ์žˆ๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ์„œ๋ฒ„๋กœ ์ „์†กํ•˜๋Š” flush๋ฉ”์†Œ๋“œ์ด๋‹ค. } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { //์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ ์ˆ˜์‹ ๋œ ๋ฉ”์„ธ์ง€๊ฐ€ ์žˆ์„ ๋•Œ ํ˜ธ์ถœ๋˜๋Š” ์ด๋ฒคํŠธ์ด๋‹ค. String readMessage = ((ByteBuf)msg).toString(Charset.defaultCharset()); //์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ ์ˆ˜์‹ ๋œ ๋ฐ์ดํ„ฐ๊ฐ€ ์ €์žฅ๋œ msg๊ฐ์ฒด๋ฅผ ๋ฌธ์ž์—ด ๋ฐ์ดํ„ฐ๋กœ ํƒ€์ž…์บ์ŠคํŒ…ํ•œ๋‹ค. StringBuilder builder = new StringBuilder(); builder.append("์ˆ˜์‹ ํ•œ ๋ฌธ์ž์—ด ["); builder.append(readMessage); builder.append("]"); System.out.println(builder.toString()); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { //์ˆ˜์‹ ๋œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ชจ๋‘ ์ฝ์—ˆ์„ ๋•Œ ์ž๋™์œผ๋กœ ํ˜ธ์ถœ๋˜๋Š” ์ด๋ฒคํŠธ์ด๋‹ค. //channelRead์ด๋ฒคํŠธ์˜ ์ˆ˜ํ–‰์ด ์™„๋ฃŒ๋˜์„œ ๋‚˜์„œ ํ˜ธ์ถœ๋œ๋‹ค. ctx.close(); //์ˆ˜์‹ ๋œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ชจ๋‘ ์ฝ์€ ํ›„, ์„œ๋ฒ„์™€ ์—ฐ๊ฒฐ๋œ ์ฑ„๋„์„ ๋‹ซ๋Š”๋‹ค. ๋ฐ์ดํ„ฐ ์†ก์ˆ˜์‹  ์ฑ„๋„์€ ๋‹ซํžˆ๊ณ  ํด๋ผ์ด์–ธํŠธ ํ”„๋กœ๊ทธ๋žจ์€ ์ข…๋ฃŒ๋œ๋‹ค. } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
package nl.rug.oop.flaps.aircraft_editor.view.frame; import lombok.Getter; import nl.rug.oop.flaps.aircraft_editor.controller.errors.NotReachable; import nl.rug.oop.flaps.aircraft_editor.util.IsDestinationReachable; import nl.rug.oop.flaps.aircraft_editor.view.panels.blueprint.BluePrintPanel; import nl.rug.oop.flaps.aircraft_editor.view.panels.aircraft_info.InfoPanel; import nl.rug.oop.flaps.simulation.model.aircraft.Aircraft; import nl.rug.oop.flaps.simulation.model.world.WorldSelectionModel; import javax.swing.*; import java.awt.*; /** * The main frame in which the editor is be displayed. * * @author T.O.W.E.R. */ @Getter public class EditorFrame extends JFrame { @Getter private static final int WIDTH = 1600; @Getter private static final int HEIGHT = 800; private static JSplitPane mainSplitPane; @Getter private static JFrame frame; private final Aircraft aircraft; public EditorFrame(Aircraft aircraft, WorldSelectionModel selectionModel) { super("Aircraft Editor"); this.aircraft = aircraft; /* if destination is not reachable with even full tanks. The user is asked if they want to configure it anyways*/ if(!IsDestinationReachable.isDestinationReachable(aircraft, selectionModel)) { NotReachable choice = new NotReachable(); if(!choice.isConfigureAnyWay()) { return; } } setLayout(new BorderLayout()); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setPreferredSize(new Dimension(WIDTH, HEIGHT)); frame = this; BluePrintPanel bluePrintPanel = new BluePrintPanel(aircraft); new InfoPanel(aircraft, selectionModel, bluePrintPanel); /* splits the blueprint part and the info panel part */ mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, bluePrintPanel.getBluePrintScrollPane(), InfoPanel.getInfoSplitPane()); mainSplitPane.setOneTouchExpandable(false); mainSplitPane.setDividerLocation(BluePrintPanel.getWIDTH()+10); this.add(mainSplitPane, BorderLayout.CENTER); addMenuBar(); setExtendedState(JFrame.MAXIMIZED_BOTH); pack(); setLocationRelativeTo(null); setVisible(true); } /** * adds a {@link MenuBar} on top of the frame * */ private void addMenuBar() { if (aircraft.getEditMenu() == null) { aircraft.setEditMenu(new EditMenu()); } frame.setJMenuBar(aircraft.getEditMenu()); } }
package com.saraew.main; public class Main { public static void main(String[] args) { MainWindow window = new MainWindow(9, 9); window.setVisible(true); } }
package id.tfn.code.myscanner; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.lifecycle.ViewModelProvider; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Filter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.Toast; import com.arasthel.asyncjob.AsyncJob; import net.alhazmy13.imagefilter.ImageFilter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.Random; import id.tfn.code.myscanner.data.Photo; import id.tfn.code.myscanner.data.PhotoViewModel; import id.tfn.code.myscanner.helpers.MyConstants; import id.tfn.code.myscanner.libraries.NativeClass; public class FilterActivity extends AppCompatActivity { Toolbar toolbar; ImageView img; LinearLayout originalLayout, gothamLayout, oldLayout, sketchLayout, hdrLayout, magicLayout, grayLayout; ImageView originalImage, gothamImage, oldImage, sketchImage, hdrImage, magicImage, grayImage; int id = 0; NativeClass nativeClass = new NativeClass(); Bitmap originalBitmap; int code = 0; private PhotoViewModel photoViewModel; Button applyButton, applyAllButton; Bitmap tempBitMap; String filter = "original"; ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_filter); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); photoViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(PhotoViewModel.class); img = (ImageView) findViewById(R.id.img); originalLayout = (LinearLayout) findViewById(R.id.original_layout); gothamLayout = (LinearLayout) findViewById(R.id.gotham_layout); oldLayout = (LinearLayout) findViewById(R.id.old_layout); sketchLayout = (LinearLayout) findViewById(R.id.sketch_layout); hdrLayout = (LinearLayout) findViewById(R.id.hdr_layout); magicLayout = (LinearLayout) findViewById(R.id.magic_layout); grayLayout = (LinearLayout) findViewById(R.id.gray_layout); originalImage = (ImageView) findViewById(R.id.original_image); gothamImage = (ImageView) findViewById(R.id.gotham_image); oldImage = (ImageView) findViewById(R.id.old_image); sketchImage = (ImageView) findViewById(R.id.sketch_image); hdrImage = (ImageView) findViewById(R.id.hdr_image); magicImage = (ImageView) findViewById(R.id.magic_image); grayImage = (ImageView) findViewById(R.id.gray_image); applyButton = (Button) findViewById(R.id.apply_button); applyAllButton = (Button) findViewById(R.id.apply_all_button); progressBar = (ProgressBar) findViewById(R.id.progressBar); originalBitmap = MyConstants.selectedImageBitmapList.get(MyConstants.count); tempBitMap = originalBitmap; img.setImageBitmap(originalBitmap); originalImage.setImageBitmap(originalBitmap); gothamImage.setImageBitmap(ImageFilter.applyFilter(originalBitmap, ImageFilter.Filter.GOTHAM)); oldImage.setImageBitmap(ImageFilter.applyFilter(originalBitmap, ImageFilter.Filter.OLD)); sketchImage.setImageBitmap(ImageFilter.applyFilter(originalBitmap, ImageFilter.Filter.SKETCH)); hdrImage.setImageBitmap(ImageFilter.applyFilter(originalBitmap, ImageFilter.Filter.HDR)); grayImage.setImageBitmap(nativeClass.FilterGray(originalBitmap)); magicImage.setImageBitmap(nativeClass.FilterMagic(originalBitmap)); originalLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { img.setImageBitmap(originalBitmap); filter = "original"; } }); grayLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { tempBitMap = nativeClass.FilterGray(originalBitmap); img.setImageBitmap(tempBitMap); filter = "gray"; } }); magicLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { tempBitMap = nativeClass.FilterMagic(originalBitmap); img.setImageBitmap(tempBitMap); filter = "magic"; } }); gothamLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { tempBitMap = ImageFilter.applyFilter(originalBitmap, ImageFilter.Filter.GOTHAM); img.setImageBitmap(tempBitMap); filter = "gotham"; } }); oldLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { tempBitMap = ImageFilter.applyFilter(originalBitmap, ImageFilter.Filter.OLD); img.setImageBitmap(tempBitMap); filter = "old"; } }); sketchLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { tempBitMap = ImageFilter.applyFilter(originalBitmap, ImageFilter.Filter.SKETCH); img.setImageBitmap(tempBitMap); filter = "sketch"; } }); hdrLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { tempBitMap = ImageFilter.applyFilter(originalBitmap, ImageFilter.Filter.HDR); img.setImageBitmap(tempBitMap); filter = "hdr"; } }); applyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { progressBar.setVisibility(View.VISIBLE); applyAllButton.setEnabled(false); applyButton.setEnabled(false); new AsyncJob.AsyncJobBuilder<Boolean>() .doInBackground(new AsyncJob.AsyncAction<Boolean>() { @Override public Boolean doAsync() { try { saveImage(tempBitMap, filter); } catch (Exception e) { e.printStackTrace(); } return true; } }) .doWhenFinished(new AsyncJob.AsyncResultAction<Boolean>() { @Override public void onResult(Boolean result) { applyAllButton.setEnabled(true); applyButton.setEnabled(true); } }).create().start(); } }); applyAllButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { progressBar.setVisibility(View.VISIBLE); applyAllButton.setEnabled(false); applyButton.setEnabled(false); new AsyncJob.AsyncJobBuilder<Boolean>() .doInBackground(new AsyncJob.AsyncAction<Boolean>() { @Override public Boolean doAsync() { try { for (int i = MyConstants.count; i < MyConstants.selectedImageBitmapList.size(); i++) { try { Random r = new Random(); int name = r.nextInt(10000000) + 10000000; ByteArrayOutputStream stream = new ByteArrayOutputStream(); tempBitMap.compress(Bitmap.CompressFormat.PNG, 100, stream); OutputStream fOut = null; String path = MyConstants.directoryPath + "/" + name + ".png"; File file = new File(path); fOut = new FileOutputStream(file); tempBitMap.compress(Bitmap.CompressFormat.PNG, 85, fOut); fOut.flush(); fOut.close(); Photo photo = new Photo(path, filter); photoViewModel.insert(photo); MyConstants.count += 1; Log.i("COUNT", MyConstants.count + ""); if (MyConstants.selectedImageBitmapList.size() <= MyConstants.count) { Intent intent = new Intent(FilterActivity.this, HomeActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); }else{ tempBitMap = getBitmap(MyConstants.selectedImageBitmapList.get(MyConstants.count),filter); img.setImageBitmap(tempBitMap); } } catch (Exception e) { } } } catch (Exception e) { e.printStackTrace(); } return true; } }) .doWhenFinished(new AsyncJob.AsyncResultAction<Boolean>() { @Override public void onResult(Boolean result) { } }).create().start(); } }); } void saveImage(Bitmap bitmap, String filter) { try { Random r = new Random(); int name = r.nextInt(10000000) + 10000000; ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); OutputStream fOut = null; String path = MyConstants.directoryPath + "/" + name + ".png"; File file = new File(path); fOut = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut); fOut.flush(); fOut.close(); Photo photo = new Photo(path, filter); photoViewModel.insert(photo); MyConstants.count += 1; if (MyConstants.selectedImageBitmapList.size() > MyConstants.count) { Intent intent = new Intent(FilterActivity.this, FilterActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } else { Intent intent = new Intent(FilterActivity.this, HomeActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } } catch (Exception e) { } } void saveAllmage(Bitmap bitmap, String filter) { for (int i = MyConstants.count; i < MyConstants.selectedImageBitmapList.size(); i++) { try { Random r = new Random(); int name = r.nextInt(10000000) + 10000000; ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); OutputStream fOut = null; String path = MyConstants.directoryPath + "/" + name + ".png"; File file = new File(path); fOut = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut); fOut.flush(); fOut.close(); Photo photo = new Photo(path, filter); photoViewModel.insert(photo); MyConstants.count += 1; Log.i("COUNT", MyConstants.count + ""); if (MyConstants.selectedImageBitmapList.size() <= MyConstants.count) { Intent intent = new Intent(FilterActivity.this, HomeActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); }else{ bitmap = getBitmap(MyConstants.selectedImageBitmapList.get(MyConstants.count),filter); } } catch (Exception e) { } } } Bitmap getBitmap(Bitmap bitmap, String filter) { switch (filter) { case "original": bitmap = bitmap; break; case "gray": bitmap = nativeClass.FilterGray(bitmap); break; case "magic": bitmap = nativeClass.FilterMagic(bitmap); break; case "gotham": bitmap = ImageFilter.applyFilter(originalBitmap, ImageFilter.Filter.GOTHAM); break; case "old": bitmap = ImageFilter.applyFilter(bitmap, ImageFilter.Filter.OLD); break; case "sketch": bitmap = ImageFilter.applyFilter(bitmap, ImageFilter.Filter.SKETCH); break; case "hdr": bitmap = ImageFilter.applyFilter(bitmap, ImageFilter.Filter.HDR); break; default: bitmap = bitmap; } return bitmap; } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } }
package com.haarman.listviewanimations.view; public interface OnSwapListener { public void onItemSwapped(int pos1, int pos2); }
package at.cooperation.rezeptdb.service; import android.util.Base64; import android.util.Log; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import at.cooperation.rezeptdb.RecipesActivity; import at.cooperation.rezeptdb.model.Recipe; public class RecipeManager { public void loadRecipes(final RecipesActivity recipesView) { RequestQueue queue = Volley.newRequestQueue(recipesView); String url = Settings.getInstance(recipesView).getBaseUrl() + "recipes"; // Request a string response from the provided URL. StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { RecipeManager recipeManager = new RecipeManager(); try { List<Recipe> recipes = recipeManager.readJsonStream(new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8))); recipesView.setRecipes(recipes); } catch (IOException e) { Log.e("server_communication", "Json could not be parsed.", e); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("server_communication", "Error contacting the server.", error); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<>(); String authString = Settings.getInstance(recipesView).getAuthString(); byte[] authEncBytes = Base64.encode(authString.getBytes(), 64); String authStringEnc = new String(authEncBytes); headers.put("Authorization", "Basic " + authStringEnc); return headers; } }; // Add the request to the RequestQueue. queue.add(stringRequest); } private List<Recipe> readJsonStream(InputStream in) throws IOException { List<Recipe> recipes = new ArrayList<>(); ObjectMapper mapper = new ObjectMapper(); try { recipes = Arrays.asList(mapper.readValue(in, Recipe[].class)); } catch (IOException e) { Log.e("server_communication", "Error parsing JSON.", e); } return recipes; } }
package rs.pupin.custompolyline2; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; /** * A simple {@link Fragment} subclass. */ public class StartFragment extends Fragment implements View.OnClickListener { static interface StartListener { void drawSomethingNewButtonClicked(); void showShapesAtLayerButtonClicked(); } private StartListener listener; public StartFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {// Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_start, container, false); Button drawSomethingNewButton = (Button) v.findViewById(R.id.drawSomethingNew); Button showShapesAtLayerButton = (Button) v.findViewById(R.id.showShapesAtLayer); drawSomethingNewButton.setOnClickListener(this); showShapesAtLayerButton.setOnClickListener(this); return v; } @Override public void onClick(View v) { if (listener != null) { switch (v.getId()) { case R.id.drawSomethingNew: listener.drawSomethingNewButtonClicked(); break; case R.id.showShapesAtLayer: listener.showShapesAtLayerButtonClicked(); break; default: break; } } } @TargetApi(23) @Override public void onAttach(Context context) { super.onAttach(context); Activity a; if (context instanceof Activity) { a = (Activity) context; this.listener = (StartListener) a; } } /* * Deprecated on API 23 * Use onAttachToContext instead */ @SuppressWarnings("deprecation") @Override public void onAttach(Activity activity) { super.onAttach(activity); if (Build.VERSION.SDK_INT < 23) { this.listener = (StartListener) activity; } } }
package webmail.pages; import org.stringtemplate.v4.ST; import webmail.entities.Email; import webmail.managers.otherManagers.SQLManager; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by JOKER on 11/29/14. */ public class ReplyPage extends MailPage { public ReplyPage(HttpServletRequest request, HttpServletResponse response) { super(request, response); } public void verify() { } @Override public ST body() { String tmp_emailID = request.getParameter("emailID"); int int_emailID = Integer.parseInt(tmp_emailID); Email email = SQLManager.getEmailInfoSQL(int_emailID); String infolder = request.getParameter("infolder"); ST st = templates.getInstanceOf("reply"); st.add("username", getUsername()); st.add("ea_address", getAccount()); st.add("email", email); st.add("infolder", infolder); return st; } @Override public ST getTitle() { return new ST("Reply: "+getStrAccount()); } }