text
stringlengths
10
2.72M
package com.networks.ghosttears.activities; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ProgressBar; import android.widget.RelativeLayout; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.ValueEventListener; import com.networks.ghosttears.R; import com.networks.ghosttears.adapters.AchievementsRecyclerAdapter; import com.networks.ghosttears.gameplay_package.General_Gameplay; import com.networks.ghosttears.gameplay_package.GhostTears; import com.networks.ghosttears.gameplay_package.ManagingImages; import com.networks.ghosttears.gameplay_package.ManagingSoundService; import com.networks.ghosttears.user_profiles.Achievement; import com.networks.ghosttears.user_profiles.SubAchievement; import java.util.ArrayList; public class Achievements extends AppCompatActivity { private static RecyclerView mRecyclerView; private static AchievementsRecyclerAdapter mAdapter; private static LinearLayoutManager mLinearLayoutManager; FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser(); ManagingImages managingImages = new ManagingImages(); static ArrayList<Achievement> achievementArrayList; General_Gameplay general_gameplay = new General_Gameplay(); private final String tag = "Achievements"; ManagingSoundService managingSoundService = new ManagingSoundService(); static ProgressBar mProgressBar ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_achievements); ((GhostTears) this.getApplication()).setShouldPlay(false); // Setting windows features Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); FullScreencall(); mProgressBar = (ProgressBar) findViewById(R.id.load_progress_bar); mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView); loadAchievementIntoRecyclerView(user); general_gameplay.log(1,tag,"Achievement activity created"); } public void loadAchievementIntoRecyclerView(final FirebaseUser user){ achievementArrayList = new ArrayList<>(); new Thread( new Runnable() { @Override public void run() { Log.e("Achievements","start loading recycler"); DatabaseReference myAchievementRef = GhostTears.firebaseDatabase.getReference().child("achievements").child(user.getUid()); myAchievementRef.addListenerForSingleValueEvent( new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot snap:dataSnapshot.getChildren()) { if(snap.getKey().length()>10) { general_gameplay.log(1,tag,snap.getKey().substring(0,11)); if (snap.getKey().substring(0,11).equalsIgnoreCase("Achievement")) { int starCount = snap.child("starCount").getValue(Integer.class); String achievementTitle = snap.child("achievementTitle").getValue(String.class); general_gameplay.log(1,tag,achievementTitle); boolean claimRewards = snap.child("claimRewards").getValue(Boolean.class); String subAchievementKey = ""; if(claimRewards){ subAchievementKey = starCount + ""; }else{ if (starCount+1<4) { subAchievementKey = starCount + 1 + ""; }else { subAchievementKey = 3+""; } } int achievementProgress = snap.child("achievementProgress").getValue(Integer.class); SubAchievement subAchievement = snap.child(subAchievementKey).getValue(SubAchievement.class); Achievement achievement = new Achievement(starCount, achievementTitle, achievementProgress, subAchievement, claimRewards); achievementArrayList.add(achievement); general_gameplay.log(1,tag, "Achievements data added to arraylist"); } } } runOnUiThread( new Runnable() { @Override public void run() { try{ mProgressBar.setVisibility(View.GONE); }catch (Exception e){} mLinearLayoutManager = new LinearLayoutManager(Achievements.this); mRecyclerView.setLayoutManager(mLinearLayoutManager); mAdapter = new AchievementsRecyclerAdapter(achievementArrayList); mRecyclerView.setAdapter(mAdapter); mAdapter.notifyDataSetChanged(); general_gameplay.log(1,tag, "Achievements notify data set changed"); } } ); } @Override public void onCancelled(DatabaseError databaseError) { Log.e("Achievements","load achievements error"); Log.e("Achievements",databaseError.toString()); } } ); } } ).start(); } public void FullScreencall() { if(Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api View v = this.getWindow().getDecorView(); v.setSystemUiVisibility(View.GONE); } else if(Build.VERSION.SDK_INT >= 19) { //for new api versions. View decorView = getWindow().getDecorView(); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; decorView.setSystemUiVisibility(uiOptions); } } @Override protected void onResume(){ super.onResume(); managingSoundService.resume(this,this.getApplication()); general_gameplay.log(0,tag,"Achievements activity resumed"); FullScreencall(); } @Override protected void onPause() { super.onPause(); general_gameplay.log(0,tag,"Achievements activity paused"); managingSoundService.pause(this,this.getApplication()); } }
package test; import java.io.File; import okhttp3.Cache; import okhttp3.CacheControl; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import rx.Observable; /** * Created by ZYB on 2017-03-10. */ public class TestClass { // private OkHttpClient getCacheOkHttpClient(Context context){ // final File baseDir = new File("E://"); // final File cacheDir = new File(baseDir, "HttpResponseCache"); // Cache cache = new Cache(cacheDir, 10 * 1024 * 1024); //缓存可用大小为10M // // Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = chain -> { // Request request = chain.request(); // request = request.newBuilder() // .cacheControl(CacheControl.FORCE_CACHE) // .build(); // // Response originalResponse = chain.proceed(request); // if (NetWorkUtils.isNetWorkAvailable()) { // int maxAge = 60; //在线缓存一分钟 // return originalResponse.newBuilder() // .removeHeader("Pragma") // .removeHeader("Cache-Control") // .header("Cache-Control", "public, max-age=" + maxAge) // .build(); // // } else { // int maxStale = 60 * 60 * 24 * 4 * 7; //离线缓存4周 // return originalResponse.newBuilder() // .removeHeader("Pragma") // .removeHeader("Cache-Control") // .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale) // .build(); // } // }; // // return new OkHttpClient.Builder() // .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR) // .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR) // .cache(cache) // .build(); // } // public static class NetWorkUtils{ // public static boolean isNetWorkAvailable(){ // return true; // } // } Observable observable = Observable.create(new Observable.OnSubscribe() { @Override public void call(Object o) { } }); }
/* * Test score: 100% * Total time used: 8 min */ import java.util.stream.IntStream; class Solution { public int solution(int[] A) { return (int) IntStream.of(A).distinct().count(); } }
package com.metoo.foundation.dao; import org.springframework.stereotype.Repository; import com.metoo.core.base.GenericDAO; import com.metoo.foundation.domain.Predeposit; @Repository("predepositDAO") public class PredepositDAO extends GenericDAO<Predeposit> { }
package com.user.test.servlet; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.google.gson.Gson; import com.user.test.service.UserInfoService; import com.user.test.service.impl.UserInfoServiceImpl; import com.user.test.vo.UserInfoVO; @WebServlet("/ajax/user") public class UserInfoServlet extends HttpServlet { private static final long serialVersionUID = 1L; Gson gson = new Gson(); UserInfoService userInfoService = new UserInfoServiceImpl(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedReader br = request.getReader(); String str; StringBuffer sb = new StringBuffer(); while((str=br.readLine()) != null) { sb.append(str); } System.out.println(sb); UserInfoVO userInfoVO = new UserInfoVO(); userInfoVO = gson.fromJson(sb.toString(), UserInfoVO.class); Map<String, Object> result = new HashMap<>(); if("join".equals(userInfoVO.getCmd())) { result.put("result", userInfoService.insertUserService(userInfoVO)); }else if("login".equals(userInfoVO.getCmd())) { result.put("result", userInfoService.selectUserLogin(userInfoVO)); if(userInfoVO != null) { HttpSession hs = request.getSession(); hs.setAttribute("user", userInfoVO); } } response.setContentType("application/json;charSet=utf-8"); PrintWriter pw = response.getWriter(); String json = gson.toJson(result); pw.print(json); } }
package za.ac.cput.views.tertiaryInstitution.department; import com.google.gson.Gson; import okhttp3.*; import za.ac.cput.entity.tertiaryInstitution.Department; import za.ac.cput.factory.tertiaryInstitution.DepartmentFactory; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; public class AddDepartment extends JFrame implements ActionListener { public static final MediaType JSON = MediaType.get("application/json; charset=utf-8"); private static OkHttpClient client = new OkHttpClient(); private JLabel lblDepartmentID, lblDepartmentName, lblDepartmentDesc; private JTextField txtDepId, txtDepName, txtDepDesc; private JButton btnSave, btnCancel; public JPanel pN, pS; public AddDepartment(){ super("Add new Department"); pN = new JPanel(); pS = new JPanel(); lblDepartmentName = new JLabel("Department Name: "); lblDepartmentID = new JLabel("Department ID: "); lblDepartmentDesc = new JLabel("Department Desc: "); txtDepId = new JTextField(30); txtDepName = new JTextField(30); txtDepDesc = new JTextField(30); btnSave = new JButton("Save"); btnCancel = new JButton("Cancel"); } public void setGUI() { pN.setLayout(new GridLayout(0,2)); pS.setLayout(new GridLayout(1,2)); pN.add(lblDepartmentName); pN.add(txtDepName); pN.add(lblDepartmentID); pN.add(txtDepId); pN.add(lblDepartmentDesc); pN.add(txtDepDesc); pS.add(btnSave); pS.add(btnCancel); this.add(pN, BorderLayout.NORTH); this.add(pS, BorderLayout.SOUTH); btnSave.addActionListener(this); btnCancel.addActionListener(this); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.pack(); this.setVisible(true); this.setLocationRelativeTo(null); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnSave) { store(txtDepId.getText(), txtDepName.getText(), txtDepDesc.getText()); } else if (e.getSource() == btnCancel) { DepartmentMainGUI.main(null); this.setVisible(false); } } public void store(String DepId, String DepName, String DepDesc){ try{ final String URL = "http://localhost:8080/department/create"; Department department = DepartmentFactory.build(DepId, DepName, DepDesc); Gson g = new Gson(); String jsonString = g.toJson(department); String r = post(URL, jsonString); if (r != null) { JOptionPane.showMessageDialog(null, "Department saved successfully!"); DepartmentMainGUI.main(null); this.setVisible(false); } else { JOptionPane.showMessageDialog(null, "Oops, Department could not save."); } } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage()); } } public String post(final String url, String json) throws IOException { RequestBody body = RequestBody.create(json, JSON); Request request = new Request.Builder().url(url).post(body).build(); try (Response response = client.newCall(request).execute()) { return response.body().string(); } } public static void main(String[] args){ new AddDepartment().setGUI(); } }
package com.eugenestewart.dialogapp; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; public abstract class MainActivity extends AppCompatActivity implements EmphasisFragment.EmphasisDialogSelectionListener { EditText mUsertext; Button mAddEmphasis; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mUsertext = (EditText) findViewById(R.id.usertext); mAddEmphasis = (Button) findViewById(R.id.addemphasis); mAddEmphasis.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EmphasisFragment dialog = EmphasisFragment.newInstance(); dialog.show(getFragmentManager(), "Emphasis Dialog"); } }); } @Override public void emphasisSelected(int emphasis) { String usertext = mUsertext.getText().toString(); switch (emphasis){ case 0: usertext = usertext.toUpperCase(); case 1: usertext = usertext + "!!!"; case 2: usertext = usertext + ":)"; } } }
package attributes.book; public class BookMain { public static void main(String[] args) { Book book = new Book("Kezdö cim"); System.out.printf(book.getTitle()); book.setTitle("Módositott cim"); System.out.printf(book.getTitle()); } }
package com.moh.departments.adapters; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.moh.departments.R; import com.moh.departments.models.LabTestDataModel; import com.moh.departments.models.Labtestcultnotemodel; import com.moh.departments.models.Labtestculturemodel; import java.util.ArrayList; public class LabTestAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public final int VIEW_LAB_TEST = 1; public final int VIEW_LAB_CULT = 2; public final int VIEW_LAB_CULT_NOTES = 3; LinearLayoutManager mLinearLayoutManager; private ArrayList<Object> dataSet; public LabTestAdapter(ArrayList<Object> dataSet) { this.dataSet = dataSet; Log.e("LAB_TEST", "size=" + dataSet.size()); } @Override public int getItemCount() { return dataSet.size(); } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { View view; RecyclerView.ViewHolder myHolder = null; LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext()); switch (viewType) { case VIEW_LAB_TEST: view = inflater.inflate(R.layout.lab_res_test_row, viewGroup, false); myHolder = new MyViewHolder(view); break; case VIEW_LAB_CULT: view = inflater.inflate(R.layout.culture_result, viewGroup, false); myHolder = new MyViewHolder2(view); break; case VIEW_LAB_CULT_NOTES: view = inflater.inflate(R.layout.culture_res_notes, viewGroup, false); myHolder = new MyViewHolder3(view); break; } return myHolder; } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int listPosition) { switch (viewHolder.getItemViewType()) { case VIEW_LAB_TEST: LabTestDataModel Carddata = (LabTestDataModel) dataSet.get(listPosition); ((MyViewHolder) viewHolder).txttestname.setText(Carddata.getTxttestname()); ((MyViewHolder) viewHolder).lbtestunit.setText(Carddata.getLbtestunit()); ((MyViewHolder) viewHolder).txttestvalue.setText(Carddata.getTxttestvalue()); ((MyViewHolder) viewHolder).lbtestminref.setText(Carddata.getLbtestminref()); ((MyViewHolder) viewHolder).lbtestmaxref.setText(Carddata.getLbtestmaxref()); break; case VIEW_LAB_CULT: // LinearLayout testlayoutheader = (LinearLayout)((MyViewHolder2) viewHolder).itemView.findViewById(R.id.testlayout_header); // testlayoutheader.setVisibility(View.GONE); Labtestculturemodel cultdata = (Labtestculturemodel) dataSet.get(listPosition); ((MyViewHolder2) viewHolder).culturname.setText(cultdata.getCulturname()); ((MyViewHolder2) viewHolder).cultureres.setText(cultdata.getCultureres()); ((MyViewHolder2) viewHolder).orgA.setText(cultdata.getOrgA()); ((MyViewHolder2) viewHolder).orgAcount.setText(cultdata.getOrgAcount()); ((MyViewHolder2) viewHolder).orgB.setText(cultdata.getOrgB()); ((MyViewHolder2) viewHolder).orgBcount.setText(cultdata.getOrgBcount()); ((MyViewHolder2) viewHolder).orgC.setText(cultdata.getOrgC()); ((MyViewHolder2) viewHolder).orgCcount.setText(cultdata.getOrgCcount()); ((MyViewHolder2) viewHolder).statcultcd.setText(cultdata.getStatcultcd()); if (cultdata.getStatcultcd().equals("4")) { LinearLayout cutantilayout = (LinearLayout) ((MyViewHolder2) viewHolder).itemView.findViewById(R.id.antibiotic_layout); cutantilayout.setVisibility(View.VISIBLE); com.moh.departments.adapters.CulturantiAdapter mCulturantiAdapter = new CulturantiAdapter(cultdata.getMantiList()); mLinearLayoutManager = new LinearLayoutManager(((MyViewHolder2) viewHolder).itemView.getContext()); ((MyViewHolder2) viewHolder).innercultRecyclerView.setLayoutManager(mLinearLayoutManager); ((MyViewHolder2) viewHolder).innercultRecyclerView.setAdapter(mCulturantiAdapter); } break; case VIEW_LAB_CULT_NOTES: Labtestcultnotemodel cultnotedata = (Labtestcultnotemodel) dataSet.get(listPosition); ((MyViewHolder3) viewHolder).gramstain.setText(cultnotedata.getGramstain()); ((MyViewHolder3) viewHolder).acidfaststain.setText(cultnotedata.getAcidfaststain()); ((MyViewHolder3) viewHolder).KOH.setText(cultnotedata.getKOH()); ((MyViewHolder3) viewHolder).Fungi.setText(cultnotedata.getFungi()); ((MyViewHolder3) viewHolder).notes.setText(cultnotedata.getNotes()); break; } // LabTestDataModel Carddata = (LabTestDataModel) dataSet.get(listPosition); // Log.e("LAB_TEST_min", Carddata.getLbtestminref() + " pos=" + listPosition); // Log.e("LAB_TEST_max", Carddata.getLbtestmaxref() + " pos=" + listPosition); // // } // else if(dataSet.get(listPosition) instanceof Labtestculturemodel) { // } } @Override public int getItemViewType(int position) { if (dataSet.get(position) instanceof LabTestDataModel) return VIEW_LAB_TEST; else if (dataSet.get(position) instanceof Labtestculturemodel) { return VIEW_LAB_CULT; } else if (dataSet.get(position) instanceof Labtestcultnotemodel) { return VIEW_LAB_CULT_NOTES; } return -1; } public static class MyViewHolder extends RecyclerView.ViewHolder { TextView txttestname, lbtestunit, txttestvalue, lbtestminref, lbtestmaxref; View divider; public MyViewHolder(View itemView) { super(itemView); this.txttestname = (TextView) itemView.findViewById(R.id.txttestname); this.lbtestunit = (TextView) itemView.findViewById(R.id.lbtestunit); this.txttestvalue = (TextView) itemView.findViewById(R.id.txttestvalue); this.lbtestminref = (TextView) itemView.findViewById(R.id.lbtestminref); this.lbtestmaxref = (TextView) itemView.findViewById(R.id.lbtestmaxref); } } public static class MyViewHolder2 extends RecyclerView.ViewHolder { TextView culturname, cultureres, orgA, orgAcount, orgB, orgBcount, orgC, orgCcount, statcultcd; RecyclerView innercultRecyclerView; public MyViewHolder2(View itemView) { super(itemView); this.culturname = (TextView) itemView.findViewById(R.id.txt_culturname); this.cultureres = (TextView) itemView.findViewById(R.id.txt_cultureres); this.orgA = (TextView) itemView.findViewById(R.id.txt_orgA); this.orgAcount = (TextView) itemView.findViewById(R.id.txt_orgAcount); this.orgB = (TextView) itemView.findViewById(R.id.txt_orgB); this.orgBcount = (TextView) itemView.findViewById(R.id.txt_orgBcount); this.orgC = (TextView) itemView.findViewById(R.id.txt_orgC); this.orgCcount = (TextView) itemView.findViewById(R.id.txt_orgCcount); this.statcultcd = (TextView) itemView.findViewById(R.id.txt_cultureresid); this.innercultRecyclerView = itemView.findViewById(R.id.innercultRecyclerView); } } public static class MyViewHolder3 extends RecyclerView.ViewHolder { TextView gramstain, acidfaststain, KOH, Fungi, notes; public MyViewHolder3(View itemView) { super(itemView); this.gramstain = (TextView) itemView.findViewById(R.id.txt_gramstain); this.acidfaststain = (TextView) itemView.findViewById(R.id.txt_acidfaststain); this.KOH = (TextView) itemView.findViewById(R.id.txt_KOH); this.Fungi = (TextView) itemView.findViewById(R.id.txt_Fungi); this.notes = (TextView) itemView.findViewById(R.id.txt_notes); } } }
import javafx.application.Application; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.stage.Stage; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; public class homework_11 extends Application{ @Override public void start(Stage primaryStage){ Pane pane = new Pane(); Circle circle = new Circle(50,50,20); circle.setStroke(Color.BLACK); circle.setFill(Color.WHITE); pane.getChildren().add(circle); circle.setFocusTraversable(true); circle.setOnKeyPressed(e->{ switch(e.getCode()){ case DOWN: circle.setCenterY(circle.getCenterY()+2); break; case UP: circle.setCenterY(circle.getCenterY()-2); break; case LEFT: circle.setCenterX(circle.getCenterX()-2); break; case RIGHT: circle.setCenterX(circle.getCenterX()+2); break; default: } }); Scene scene = new Scene(pane,300,200); primaryStage.setTitle("cck,20151681310210"); primaryStage.setScene(scene); primaryStage.show(); circle.requestFocus(); } }
package corpse.ui; import gui.db.ColoredTableRenderer; import java.awt.Color; import java.awt.Component; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JTable; import org.jdesktop.swingx.JXTable; import corpse.CORPSE; /** This will highlight unresolved tokens. */ public class TokenRenderer extends ColoredTableRenderer implements MouseListener, MouseMotionListener { private static final long serialVersionUID = 1; public static final String INVALID_OPEN = "<<"; public static final String INVALID_CLOSE = ">>"; // match unresolved tokens (but ignore the <!> last-match pattern) public static final String ERROR_REGEX = Pattern.quote(INVALID_OPEN) + "(.+)" + Pattern.quote(INVALID_CLOSE); private static final Pattern ERROR = Pattern.compile(ERROR_REGEX); private static final Pattern LINK = Pattern.compile("(.*)<(.+)=(.+)>(.*)"); private CORPSE app; private int mouseRow, mouseCol; private String link; private String firstResponse; public TokenRenderer (final CORPSE app) { this.app = app; } @Override public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int viewColumn) { JComponent cell = (JComponent) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, viewColumn); Matcher m = LINK.matcher(value.toString()); if (m.find()) { JLabel label = (JLabel) cell; String linkColor = isSelected ? "yellow" : "blue"; String html; firstResponse = m.group(3); // the text to be displayed to the user if (mouseRow == row && mouseCol == viewColumn) { link = m.group(2); // the script name html = "<font color=\"" + linkColor + "\"><u>" + firstResponse + "</u></font>"; } else { link = null; html = "<font color=\"" + linkColor + "\">" + firstResponse + "</font>"; } html = "<html>" + m.group(1) + html + m.group(4) + "</html>"; label.setText(html); } if (ERROR.matcher(value.toString()).find()) cell.setBorder(BorderFactory.createLineBorder(Color.RED, 2)); return cell; } @Override public void mouseClicked(MouseEvent e) { if (link != null) app.openScript(link, firstResponse); } @Override public void mouseMoved(MouseEvent e) { JXTable table = (JXTable) e.getSource(); Point p = e.getPoint(); mouseRow = table.rowAtPoint(p); mouseCol = table.columnAtPoint(p); table.repaint(); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseDragged(MouseEvent e) { } }
package com.github.nik9000.nnfa.builder; /** * Extend me to build an NfaBuilder. */ public abstract class AbstractNfaBuilder<Self extends AbstractNfaBuilder<Self>> extends AbstractForkedOperations<Self> { }
package com.what.yunbao.collection; import java.util.Set; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.CheckBox; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.what.yunbao.R; import com.what.yunbao.util.AppUtils; import com.what.yunbao.util.CommonUtil; import com.what.yunbao.util.Notes; import com.what.yunbao.util.Notes.CollectColumns; public class CollectionActivity extends Activity { private static final String TAG = "CollectionActivity"; private ListView collection_lv; private CollectionItemAdapter collection_adapter; private BackgroundQueryHandler backgroundQueryHandler; private ImageButton collection_edit_ib; private ImageButton collection_back_ib; private RelativeLayout delete_rl; private FrameLayout lvContainer; private TextView emptyTip; private Toast mToast; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.collection); mToast = Toast.makeText(this, null, Toast.LENGTH_SHORT); setUpView(); startAsyncQuery(); } @Override protected void onResume() { super.onResume(); if(collection_adapter!=null&&collection_adapter.getCount()==0) showEmptyTip(); } private void setUpView() { collection_lv = (ListView) findViewById(R.id.lv_collection_list); lvContainer = (FrameLayout) findViewById(R.id.frameLayout1); MyOnClickListener mClickListener = new MyOnClickListener(); collection_edit_ib = (ImageButton) findViewById(R.id.ib_collection_edit); collection_edit_ib.setOnClickListener(mClickListener); collection_back_ib = (ImageButton) findViewById(R.id.ib_collection_back); collection_back_ib.setOnClickListener(mClickListener); delete_rl = (RelativeLayout) findViewById(R.id.what); delete_rl.setOnClickListener(mClickListener); } public void showEmptyTip() { if (emptyTip != null) { emptyTip.setVisibility(View.VISIBLE); return; } FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); lp.gravity = Gravity.CENTER; emptyTip = new TextView(this); emptyTip.setText("您暂无收藏记录\n去逛逛吧~"); emptyTip.setGravity(Gravity.CENTER); emptyTip.setTextColor(Color.rgb(0xff, 0xff, 0xff)); emptyTip.setTextSize(17); emptyTip.setPadding(18, 8, 18, 8); emptyTip.setCompoundDrawablesWithIntrinsicBounds(0, android.R.drawable.stat_sys_warning, 0, 0); emptyTip.setBackgroundResource(R.drawable.address_add_positive_selector); emptyTip.setClickable(true); lvContainer.addView(emptyTip, lp); emptyTip.setOnClickListener(new OnClickListener() { public void onClick(View v) { startActivity(new Intent() .setClassName("com.icanit.app_v2", "com.icanit.app_v2.activity.MainActivity") .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .setAction("leadToMerchantList")); } }); } public void startAsyncQuery() { if (backgroundQueryHandler == null) backgroundQueryHandler = new BackgroundQueryHandler( this.getContentResolver()); backgroundQueryHandler.startQuery(1, null, Notes.COLLECTIONS_URI, CollectionItemData.COLLECT_COLUMNS, null, null, CollectColumns.ADDTIME + " DESC"); } private final class BackgroundQueryHandler extends AsyncQueryHandler { public BackgroundQueryHandler(ContentResolver cr) { super(cr); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { startManagingCursor(cursor); if (token == 1) { if (cursor == null || cursor.getCount() == 0) showEmptyTip(); else { if (collection_adapter == null) { collection_lv .setOnItemLongClickListener(new MyOnItemLongClickListener()); collection_lv .setOnItemClickListener(new MyOnListItemClickListener()); collection_adapter = new CollectionItemAdapter( CollectionActivity.this); collection_lv.setAdapter(collection_adapter); } collection_adapter.changeCursor(cursor); } } } } private class MyOnClickListener implements OnClickListener { @Override public void onClick(View v) { if (v.getId() == R.id.ib_collection_edit) { if (collection_adapter != null && collection_adapter.getCount() > 0) collection_adapter.toggleChoiceMode(delete_rl); } else if (v.getId() == R.id.ib_collection_back) { finish(); overridePendingTransition(R.anim.anim_fromleft_toup6, R.anim.anim_down_toright6); } else if (v.getId() == R.id.what) { if (collection_adapter == null || collection_adapter.checkedIds.isEmpty()) { CommonUtil.showToast("未选择任何项", mToast); return; } AlertDialog.Builder builder = new AlertDialog.Builder( CollectionActivity.this); builder.setTitle("删除信息"); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setMessage(getString( R.string.alert_message_delete_notes, collection_adapter.checkedIds.size())); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { batchDelete(); } }); builder.setNegativeButton(android.R.string.cancel, null); builder.show(); } } } private class MyOnItemLongClickListener implements OnItemLongClickListener { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { return !collection_adapter.toggleChoiceMode(delete_rl); } } private class MyOnListItemClickListener implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (collection_adapter.isChoiceMode) { if (view instanceof CollectionItem) { CheckBox cb = ((CollectionItem) view).checkBox; cb.setChecked(!cb.isChecked()); } } else openItem(collection_adapter.getCursor()); } } private void openItem(final Cursor cursor) { final ProgressDialog pd = new ProgressDialog(this); pd.setMessage("稍等。。。"); pd.setCanceledOnTouchOutside(true);pd.show(); new AsyncTask<Void, Void, Object>(){ @Override protected Object doInBackground(Void... params) { try { return Class.forName("com.icanit.app_v2.util.AppUtil").getMethod("newIntentForMerchandizeListActivity", int.class) .invoke(null,cursor.getInt(cursor.getColumnIndex(CollectColumns.MERID))); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Object obj) { pd.dismiss(); if(obj==null) CommonUtil.showToast("尝试失败。。。", mToast); else startActivity((Intent)obj); } }.execute(); } private void batchDelete() { new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { return batchMoveToFolder(getContentResolver(), collection_adapter.checkedIds, Notes.ID_TRASH_FOLER); } @Override protected void onPostExecute(Boolean b) { if (!b) CommonUtil.showToast("删除失败", mToast); else collection_adapter.toggleChoiceMode(delete_rl); }; }.execute(); } private boolean batchMoveToFolder(ContentResolver resolver, Set<Long> ids, long folderId) { if (ids == null || ids.isEmpty()) { return true; } return getContentResolver().delete(Notes.COLLECTIONS_URI, "_id IN(" + AppUtils.concatenateSet(ids) + ")", null) > 0; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { if (collection_adapter != null && collection_adapter.isChoiceMode) { collection_adapter.toggleChoiceMode(delete_rl); return true; } else { finish(); overridePendingTransition(R.anim.anim_fromleft_toup6, R.anim.anim_down_toright6); return true; } } else { return super.dispatchKeyEvent(event); } } }
package lk.egreen.booking.server.service; import org.springframework.stereotype.Repository; import java.io.Serializable; import java.util.HashMap; /** * Created by dewmal on 7/15/14. */ @Repository public class ViewDataBuilder { /** * GEt View Data Model * * @return */ public ViewDataModeler getViewDataModler() { return new ViewDataModeler(); } public class ViewDataModeler extends HashMap<String, Object> implements Serializable { /** * Add values to map * * @param key * @param data * @return */ public void loadData(String key, Object data) { this.put(key, data); } public ViewDataModeler getDataObject() { return this; } } }
package model.animation; import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.imageio.ImageIO; import model.Constants; /** * The Animation class is very helpful for iterating through * a sequence of frames that describe an animation. You can simply * pass in a directory path and it will load up all of the images * sequentially and prepare them for playback. * @author Nick Cheng */ public class Animation implements IteratingAnimation { /** * This hashtable contains all of the loaded animations for the game. * The purpose of storing them is so that if an movie clip is created multiple * times with the same animation, the first one will be loaded from disk, * but all subsequent movie clips will lookup the animation from this table. * * Specifically, this hashtable uses relative path as the key, and * the sequence of images as values. */ public static Map<String,List<BufferedImage>> loadedAnimations; /**The list of frames stored as buffered images */ List<BufferedImage> images; public int currentFrame = 0; private Direction dir = Direction.FORWARD; private Point dimensions; /** * Constructor that takes in the path of a directory (or individual image) and will load * the animations into a list for easy playback. Make sure that the * images inside the folder are in order alphabetically. * @param folder A File object that represents the folder which contains * the animation pictures, or individual image */ public Animation(File folder) { String path = folder.getPath(); if(loadedAnimations.containsKey(path)){ images = loadedAnimations.get(path); }else{ images = new ArrayList<BufferedImage>(); try { if (folder.isDirectory()){ if(Constants.DEBUG) System.out.println("Reading dir: "+path); File[] folderContents = folder.listFiles(); Arrays.sort(folderContents); //some platforms don't auto-sort (e.g. Ubuntu) for (final File fileEntry : folderContents) { if (fileEntry.isDirectory()){ System.err.println("Expecting image but got directory when reading:\n" + fileEntry.getPath() +"\nDid you forget to use the MovieClip(path, true)" + "\nconstructor to specify that it has subfolders?\n"); System.exit(-1); } images.add(ImageIO.read(fileEntry)); } }else{ //folder is actually a file, just read it if(Constants.DEBUG) System.out.println("Reading image: "+path); images.add(ImageIO.read(folder)); } } catch (IOException e) { System.err.println("Error Reading image: "+path); System.exit(-1); } loadedAnimations.put(path, images); } //read dimensions of animation from first image in sequence dimensions = new Point(images.get(0).getWidth(),images.get(0).getHeight()); } /** * Constructor that takes in the path of a directory (or individual image) and will load * the animations into a list for easy playback. Make sure that the * images inside the folder are in order alphabetically. * @param path A string representation of the path of the folder (or individual image) which * contains the animation pictures */ public Animation(String path) { this(new File(path)); } /** * This will increment the current frame to the next image in the sequence * and return the buffered image of that frame. The "next" image depends on what * the direction is set to. * @return The buffered image at the next frame */ @Override public BufferedImage getNextFrame() { currentFrame = ((currentFrame+dir.speed) + images.size())% images.size(); return images.get(currentFrame); } /** * This will change the current frame to the one given * @param n The frame to switch to */ @Override public void setFrame(int n) { currentFrame = (n + images.size())% images.size(); } /** * This will change the direction of the animation playback. * The options are: * Direction.FORWARD - normal playback, * Direction.BACKWARD - reverse playback, * Direction.PAUSED - the animation will stay put. * @param dir The desired direction */ @Override public void setDirection(Direction dir) { this.dir = dir; } /** * This will give the dimensions of the animation, assuming * all the frames are the same dimension * @return a Point of width,height */ public Point getDimensions(){ return dimensions; } /** * Is this animation at the last frame? * @return Whether it is at the last frame */ @Override public boolean isAtEnd(){ return currentFrame == images.size()-1; } }
/******************************************************************************* * Copyright 2012 Ivan Morgillo * * 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.dronix.android.unisannio.fragment; import java.io.IOException; import java.net.SocketException; import java.util.ArrayList; import java.util.List; import org.dronix.android.unisannio.LazyAdapter; import org.dronix.android.unisannio.News; import org.dronix.android.unisannio.R; import org.dronix.android.unisannio.R.id; import org.dronix.android.unisannio.R.layout; import org.dronix.android.unisannio.R.string; import org.dronix.android.unisannio.ateneo.AteneoAllegatiActivity; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import android.content.Intent; import android.content.res.TypedArray; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.format.DateUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener; import com.handmark.pulltorefresh.library.PullToRefreshListView; public class TabOne extends Fragment { private String URL = "http://www.unisannio.it/notizie/avvisi/index.php"; private String URLAllegati = "http://www.unisannio.it/notizie/avvisi/"; private ArrayList<News> news; private LazyAdapter mAdapter; private PullToRefreshListView mPullRefreshListView; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tabone, container, false); mPullRefreshListView = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_list); // Set a listener to be invoked when the list should be refreshed. mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) { mPullRefreshListView.setLastUpdatedLabel(DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL)); new NewsRetriever().execute(); } }); ListView actualListView = mPullRefreshListView.getRefreshableView(); news = new ArrayList<News>(); news.add(new News("", getString(R.string.pull))); mAdapter = new LazyAdapter(getActivity(), news); actualListView.setAdapter(mAdapter); actualListView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.i("TABONE CLICK ELEMENT", "Click ricevuto in posizione : "+position); Intent i = new Intent(getActivity(), AteneoAllegatiActivity.class); i.putExtra("newsate", news.get(--position)); startActivity(i); } }); return view; } public List<News> getNews() { List<News> newsList = new ArrayList<News>(); try { Document doc = Jsoup.connect(URL).timeout(10000).get(); Elements newsItems = doc.select("div.meta > table > tbody > tr"); for (int i = 2; i < newsItems.size(); i++) { String date = null; Element dateElement = newsItems.get(i).select("p").first(); if (dateElement != null) { date = dateElement.text(); } String href =null; String body = null; Element bodyElement = newsItems.get(i).select("a").first(); if (bodyElement != null) { href = URLAllegati.concat(bodyElement.attr("href")); body = bodyElement.text(); } if (date != null && body != null && href != null) newsList.add(new News(href,date, body)); } } catch (SocketException e) { return null; } catch (IOException e) { e.printStackTrace(); } /* * for (News n : newsList) { Log.i("NEWS", n.getDate() + " " + * n.getBody()); } */ return newsList; } class NewsRetriever extends AsyncTask<Void, Void, List<News>> { @Override protected void onPreExecute() { } @Override protected List<News> doInBackground(Void... params) { return getNews(); } @Override protected void onPostExecute(List<News> result) { if (result != null) { news.clear(); news.addAll(result); mAdapter.notifyDataSetChanged(); } mPullRefreshListView.onRefreshComplete(); } } }
package lt.eisgroup.laivumusis.vartotojosąsaja; import lt.eisgroup.laivumusis.laukas.MūšioLaukas; /** * Stebi pasikeitimus mūšio laule. * * @author giedrius */ public interface MūšioLaukoStebėtojas { /** * Iškviesdamas šį metodą mūšio laukas informuoja, kad į jį buvo šauta. * * @param mūšioLaukas */ public void mūšioLaukasPasikeitė(MūšioLaukas mūšioLaukas); }
package global.model; /** * 教学计划视图类 * * @author zzt * */ public class View_teachingplan { private String d_id; private String d_name; private String o_id; private String o_name; private String m_id; private String m_name; private String tp_id; private String tp_name; private String tp_mark; public View_teachingplan(String d_id, String d_name, String o_id, String o_name, String m_id, String m_name, String tp_id, String tp_name, String tp_mark) { super(); this.d_id = d_id; this.d_name = d_name; this.o_id = o_id; this.o_name = o_name; this.m_id = m_id; this.m_name = m_name; this.tp_id = tp_id; this.tp_name = tp_name; this.tp_mark = tp_mark; } public String getD_id() { return d_id; } public void setD_id(String d_id) { this.d_id = d_id; } public String getD_name() { return d_name; } public void setD_name(String d_name) { this.d_name = d_name; } public String getO_id() { return o_id; } public void setO_id(String o_id) { this.o_id = o_id; } public String getO_name() { return o_name; } public void setO_name(String o_name) { this.o_name = o_name; } public String getM_id() { return m_id; } public void setM_id(String m_id) { this.m_id = m_id; } public String getM_name() { return m_name; } public void setM_name(String m_name) { this.m_name = m_name; } public String getTp_id() { return tp_id; } public void setTp_id(String tp_id) { this.tp_id = tp_id; } public String getTp_name() { return tp_name; } public void setTp_name(String tp_name) { this.tp_name = tp_name; } public String getTp_mark() { return tp_mark; } public void setTp_mark(String tp_mark) { this.tp_mark = tp_mark; } }
package com.example.ips.service.impl; import com.example.ips.export.ResultMapUtil; import com.example.ips.export.error.EmBusinessCode; import com.example.ips.mapper.ServiceDepUatUpMapper; import com.example.ips.model.ServiceDepUatUp; import com.example.ips.service.ServiceDepUatUpService; import org.apache.shiro.SecurityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; import java.util.Map; @Service public class ServiceDepUatUpServiceImpl implements ServiceDepUatUpService { private static final Logger logger = LoggerFactory.getLogger(ServiceDepUatUpService.class); @Autowired ServiceDepUatUpMapper serviceDepUatUpMapper; @Override public List<ServiceDepUatUp> getAllUatUp() { return serviceDepUatUpMapper.getAllUatUp(); } @Override public ServiceDepUatUp getUatUpByKey(Integer id) { return serviceDepUatUpMapper.selectByPrimaryKey(id); } @Override public Map<String, Object> uatUpAdd(ServiceDepUatUp record) { Map<String, Object> resultMap; //系统当前时间 Date now = new Date(); // 从session获取操作用户ID,sysId Integer sysId= (Integer) SecurityUtils.getSubject().getSession().getAttribute("sysId"); try{ record.setCreateTime(now); record.setUpdateTime(now); record.setCreateUser(sysId); //设置状态为待提交 record.setStatus(EmBusinessCode.SERVICEDEP_UATUP_SAUTUS_SUBMITTED.getErrMsg()); int num=serviceDepUatUpMapper.insertSelective(record); if(num>0){ resultMap= ResultMapUtil.success(EmBusinessCode.SERVICEDEP_UATUP_ADD_SUCCESS.getErrMsg()); logger.info("uatUpAdd保存成功"); }else { resultMap= ResultMapUtil.fail(EmBusinessCode.SERVICEDEP_UATUP_ADD_ERROR.getErrMsg()); logger.info("uatUpAdd保存失败"); } }catch (Exception e){ resultMap= ResultMapUtil.fail(EmBusinessCode.SERVICEDEP_UATUP_ADD_ERROR.getErrMsg()); logger.error("uatUpAdd保存错误:{}",e); } return resultMap; } @Override public Map<String, Object> uatUpUpdate(ServiceDepUatUp record) { Map<String, Object> resultMap; //系统当前时间 Date now = new Date(); // 从session获取操作用户ID,sysId Integer sysId= (Integer) SecurityUtils.getSubject().getSession().getAttribute("sysId"); try{ record.setUpdateTime(now); record.setUpdateUser(sysId); //状态字段无权修改 record.setStatus(null); int num=serviceDepUatUpMapper.updateByPrimaryKeySelective(record); if(num>0){ resultMap= ResultMapUtil.success(EmBusinessCode.SYSTEM_UPDATE_SUCCESS.getErrMsg()); logger.info("uatUpUpdate更新成功"); }else { resultMap= ResultMapUtil.fail(EmBusinessCode.SYSTEM_UPDATE_ERROR.getErrMsg()); logger.info("uatUpUpdate更新失败"); } }catch (Exception e){ resultMap= ResultMapUtil.fail(EmBusinessCode.SYSTEM_UPDATE_ERROR.getErrMsg()); logger.error("uatUpUpdate更新错误:{}",e); } return resultMap; } @Override public Map<String, Object> uatUpDel(Integer id) { Map<String, Object> resultMap; try{ int num=serviceDepUatUpMapper.deleteByPrimaryKey(id); if(num>0){ resultMap=ResultMapUtil.success(EmBusinessCode.SYSTEM_DEL_SUCCESS.getErrMsg()); logger.info("uatUpDel删除成功"); }else { resultMap=ResultMapUtil.fail(EmBusinessCode.SYSTEM_DEL_ERROR.getErrMsg()); logger.info("uatUpDel删除失败"); } }catch (Exception e){ resultMap=ResultMapUtil.fail(EmBusinessCode.SYSTEM_DEL_ERROR.getErrMsg()); logger.error("uatUpDel错误:{}",e); } return resultMap; } }
/* ID: akshath LANG: JAVA TASK: radio */ import java.io.*; import java.util.*; public class radio { static int N, M, fxStart, fyStart, bxStart, byStart; static String fSteps, bSteps; static int[][] distanceSq; //only use squared distances static int[][] savedDist; //eliminates repeat recursion public static void main (String [] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader("radio.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("radio.out"))); StringTokenizer st = new StringTokenizer(in.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); st = new StringTokenizer(in.readLine()); fxStart = Integer.parseInt(st.nextToken()); fyStart = Integer.parseInt(st.nextToken()); st = new StringTokenizer(in.readLine()); bxStart = Integer.parseInt(st.nextToken()); byStart = Integer.parseInt(st.nextToken()); st = new StringTokenizer(in.readLine()); fSteps = st.nextToken(); st = new StringTokenizer(in.readLine()); bSteps = st.nextToken(); int fxNext = fxStart; int fyNext = fyStart; int bxNext = bxStart; int byNext = byStart; char fNextStep, bNextStep; distanceSq = new int[N+1][M+1]; savedDist = new int[N+1][M+1]; savedDist = init2DArray(savedDist); int m = 0, n = 0; fSteps = " " + fSteps; //filler for(int k = 1; k < N+1; k++) { fNextStep = fSteps.charAt(k); if(fNextStep == 'N') fyNext++; else if(fNextStep == 'E') fxNext++; else if(fNextStep == 'S') fyNext--; else if(fNextStep == 'W') fxNext--; distanceSq[k][0] = Math.abs(fyNext - byStart) * Math.abs(fyNext - byStart) + Math.abs(fxNext - bxStart) * Math.abs(fxNext - bxStart); } fxNext = fxStart; fyNext = fyStart; while(m < N+1) { fNextStep = fSteps.charAt(m); if(fNextStep == 'N') fyNext++; else if(fNextStep == 'E') fxNext++; else if(fNextStep == 'S') fyNext--; else if(fNextStep == 'W') fxNext--; n = 0; while(n < M) { n++; bNextStep = bSteps.charAt(n-1); if(bNextStep == 'N') byNext++; else if(bNextStep == 'E') bxNext++; else if(bNextStep == 'S') byNext--; else if(bNextStep == 'W') bxNext--; distanceSq[m][n] = (int) (Math.pow(Math.abs(fyNext - byNext), 2) + Math.pow(Math.abs(fxNext - bxNext), 2)); } bxNext = bxStart; byNext = byStart; m++; } int optimalSol = getBestPath(distanceSq, N, M); out.println(optimalSol); in.close(); out.close(); System.exit(0); } public static final int ARRAY_INIT_VAL = -1; public static int[][] init2DArray(int[][] input) { for(int i = 0; i < input.length; i++) { for(int j = 0; j < input[0].length; j++) { input[i][j] = ARRAY_INIT_VAL; } } return input; } public static int tripleMin(int x, int y, int z) { return (x < y) ? ((x < z) ? x : z) : ((y < z) ? y : z); } //dynamic programming the best way>???? public static int getBestPath(int[][] input, int m, int n) { if(savedDist[m][n] != ARRAY_INIT_VAL) return savedDist[m][n]; if (m <= 0 && n <= 0) return input[0][0]; else if (m == 0) { //no diagonal, horizontal savedDist[m][n] = input[m][n] + getBestPath(input, m, n-1); } else if (n == 0) { //no diagonal, vertical savedDist[m][n] = input[m][n] + getBestPath(input, m-1, n); } else { //diagonal, vertical, horizontal savedDist[m][n] = input[m][n] + tripleMin(getBestPath(input, m, n-1), getBestPath(input, m-1, n-1), getBestPath(input, m-1, n)); } return savedDist[m][n]; } }
package com.techelevator.models.jdbc; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; import com.techelevator.models.Campground; import com.techelevator.models.Park; import com.techelevator.models.ParkDAO; public class JDBCParkDAO implements ParkDAO { private JdbcTemplate jdbcTemplate; private JDBCObjectHelperDAO objectHelper; public JDBCParkDAO(DataSource dataSource) { jdbcTemplate = new JdbcTemplate(dataSource); objectHelper = new JDBCObjectHelperDAO(dataSource); } @Override public List<Park> getAvailableParks() { ArrayList<Park> parks = new ArrayList<>(); String sqlReturnAllParks = "SELECT park_id, name, location, establish_date, area, visitors, description " + "FROM park ORDER BY name ASC"; SqlRowSet results = jdbcTemplate.queryForRowSet(sqlReturnAllParks); while (results.next()) { Park thePark = objectHelper.mapRowToPark(results); parks.add(thePark); } return parks; } @Override public List<Campground> getCampgroundsForPark(long parkID) { ArrayList<Campground> campgrounds = new ArrayList<>(); String sqlReturnAllCampSitesForPark = "SELECT campground_id, park_id, name, open_from_mm, open_to_mm, daily_fee " + "FROM campground WHERE park_id = ? "; SqlRowSet results = jdbcTemplate.queryForRowSet(sqlReturnAllCampSitesForPark, parkID); while (results.next()) { Campground theCamp = objectHelper.mapRowToCampground(results); campgrounds.add(theCamp); } return campgrounds; } }
package cc.ipotato.jdbc.dbutils; import cc.ipotato.jdbc.basic.JDBCUtils; import cc.ipotato.jdbc.beans.Sort; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.*; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.Map; /** * Created by haohao on 2018/5/26. */ public class QueryRunnerQueryDemo { private static Connection conn = JDBCUtils.getConnection(); public static void main(String[] args) throws SQLException { // arrayHandler(); // arrayListHandler(); // beanHandler(); // beanListHandler(); // columnListHandler(); // scalarHandler(); // mapHandler(); mapListHandler(); DbUtils.closeQuietly(conn); } /* 1. ArrayHandler, 将结果集的第一行存储到Object数组中 */ public static void arrayHandler() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "SELECT * FROM sort"; Object[] result = qr.query(conn, sql, new ArrayHandler()); for (Object obj: result) { System.out.print(obj + " "); } } /* 2. ArrayListHandler, 将每一条结果存储到Object数组中,并将数组存储到List中 */ public static void arrayListHandler() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "SELECT * FROM sort where sid > ?"; List<Object[]> result= qr.query(conn, sql, new ArrayListHandler(), 3); for (Object[] objs: result) { for (Object obj: objs) { System.out.print(obj + " "); } System.out.println(); } } /* 3. BeanHandler, 将查询结果的第一条封装成JavaBean对象 若查询结果为空,则result为null */ public static void beanHandler() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "SELECT * FROM sort where sid > ?"; Sort result = qr.query(conn, sql, new BeanHandler<>(Sort.class), 3); System.out.println(result); } /* 4. BeanListHandler, 将查询结果的每一条封装成JavaBean对象,并将所有JavaBean对象存储到List中 */ public static void beanListHandler() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "SELECT * FROM sort where sid > ?"; List<Sort> result = qr.query(conn, sql, new BeanListHandler<>(Sort.class), 2); for (Sort s: result) { System.out.println(s); } } /* 5. ConlumnListHandler, 将查询结果的指定列存入List中 */ public static void columnListHandler() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "SELECT * FROM sort"; List<Object> result = qr.query(conn, sql, new ColumnListHandler<>("sname")); System.out.println(result); } /* 6. ScalarHandler, 对于查询后只有一个结果, 比如聚合查询count */ public static void scalarHandler() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "SELECT COUNT(*) FROM sort"; long count = qr.query(conn, sql, new ScalarHandler<>()); System.out.println(count); } /* 7. MapHandler, 将查询结果的第一行数据,封装到一个Map对象中 */ public static void mapHandler() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "SELECT * FROM sort"; Map<String, Object> resultMap = qr.query(conn, sql, new MapHandler()); for (Map.Entry<String, Object> entry: resultMap.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } } /* 8. MapListHandler, 将每一个查询结果封装成Map对象,并将所有Map对象存储到一个List中 */ public static void mapListHandler() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "SELECT * FROM sort"; List<Map<String, Object>> result = qr.query(conn, sql, new MapListHandler()); for (Map<String, Object> map: result) { for (Map.Entry<String, Object> entry: map.entrySet()) { System.out.print(entry.getKey() + "..." + entry.getValue() + " "); } System.out.println(); } } }
package AlertDialog; import java.io.IOException; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.layout.HBox; import javafx.stage.Modality; import javafx.stage.Stage; public class AlertUtil { private static boolean state; public static boolean showAlert(Stage baseStage,String msg) { try { FXMLLoader loader = new FXMLLoader(AlertUtil.class.getResource("AlertDialog.fxml")); Parent root = loader.load(); Scene scene = new Scene(root); Stage dialog = new Stage(); dialog.initModality(Modality.WINDOW_MODAL); dialog.initOwner(baseStage); dialog.setScene(scene); AlertDialogController test = loader.getController(); test.alertSet(msg); dialog.showingProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { state = test.getState(); } }); dialog.showAndWait(); } catch (IOException e) { e.printStackTrace(); } return state; } public static boolean showAlert(Stage baseStage,String cotent1,String cotent2,String button1,String button2) { try { FXMLLoader loader = new FXMLLoader(AlertUtil.class.getResource("AlertDialog2.fxml")); Parent root = loader.load(); Scene scene = new Scene(root); Stage dialog = new Stage(); dialog.initModality(Modality.WINDOW_MODAL); dialog.initOwner(baseStage); dialog.setScene(scene); AlertDialog2Controller test = loader.getController(); test.alertMessageSet(cotent1,cotent2); test.alertButtonSet(button1,button2); dialog.showingProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { state = test.getState(); } }); dialog.showAndWait(); } catch (IOException e) { e.printStackTrace(); } return state; } public static void showDonwload(Stage baseStage) { try { FXMLLoader loader = new FXMLLoader(AlertUtil.class.getResource("DirectoryChooseDialog.fxml")); Parent root; root = loader.load(); Scene scene = new Scene(root); Stage dialog = new Stage(); dialog.initModality(Modality.NONE); dialog.initOwner(baseStage); dialog.setScene(scene); dialog.show(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void sendDataDialog() { HBox box = new HBox(); box.setPrefSize(100, 50); } }
package br.com.ocjp7.genericos; import java.util.Iterator; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.RecursiveAction; import java.util.concurrent.RecursiveTask; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; public class Forks { public static void main(String[] args) { int v =ThreadLocalRandom.current().nextInt(5); System.out.println(v); ForkJoinPool forkJoinPool = new ForkJoinPool(); //executando um task com retorno. int val = forkJoinPool.invoke( new RecursiveTaskExemple() ); System.out.println(val); //executando um action sem retorno. RecursiveActionExemple pal = new RecursiveActionExemple(); pal.palpite = 3; forkJoinPool.invoke(pal); //pegadinhas feitas com CopyOnWriteList //só add, remove faz com que um novoa rray seja criado. CopyOnWriteArrayList<Integer> cpy = new CopyOnWriteArrayList<>(); cpy.add(11);//um novo array é criado. cpy.remove(11);//um novo array é criado. cpy.add(1); cpy.add(4); cpy.add(7); Iterator<Integer> iteracao = cpy.iterator(); cpy.add(8);//o iterator é obtido ante so 6 ser adicionado. cpy.remove(7);//funciona da mesma maneira. while ( iteracao.hasNext() ) { System.out.println( iteracao.next() ); } AtomicInteger i = new AtomicInteger(); i.incrementAndGet();//incrementa automaticamente o valor i.getAndAdd(12);//incrementa automaticamente o valor } } class RecursiveTaskExemple extends RecursiveTask<Integer>{ private static final long serialVersionUID = 1L; @Override protected Integer compute() { return 50; } } class RecursiveActionExemple extends RecursiveAction{ private static final long serialVersionUID = 1L; int palpite; @Override protected void compute() { int val = ThreadLocalRandom.current().nextInt(1, 11); if( palpite == val ){ System.out.println("Palpite :" + palpite + " Sorteio :" + val); }else{ System.out.println("Palpite :" + palpite + " Sorteio :" + val); } } }
//designpatterns.proxy.ProxySearcher.java package designpatterns.proxy; //代理查询类:代理主题类 public class ProxySearcher implements Searcher { private RealSearcher searcher = new RealSearcher(); //维持一个对真实主题的引用 private AccessValidator validator; private Logger logger; public String doSearch(String userId,String keyword) { //如果身份验证成功,则执行查询 if (this.validate(userId)) { String result = searcher.doSearch(userId,keyword); //调用真实主题对象的查询方法 this.log(userId); //记录查询日志 return result; //返回查询结果 } else { return null; } } //创建访问验证对象并调用其validate()方法实现身份验证 public boolean validate(String userId) { validator = new AccessValidator(); return validator.validate(userId); } //创建日志记录对象并调用其log()方法实现日志记录 public void log(String userId) { logger = new Logger(); logger.log(userId); } }
package mvc3.controllers; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import java.util.ArrayList; import java.util.List; /** * Обычный контроллер, после вызова каждого метода * которого будет рисоваться соответствующий view */ @Controller public class MyWebController { @RequestMapping("web/list") public String genList(Model model){ List<String> list = new ArrayList<>(); list.add("Санкт-Петербург"); list.add("Москва"); list.add("Брянск"); list.add("Воронеж"); // Добавляем список в параметры, которые переданы view model.addAttribute("list", list); // Создаём 2D массив int[][] mul = new int[10][10]; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { mul[i][j] = (i+1) * (j+1); } } // и передаём его в view model.addAttribute("mul", mul); return "web/list"; } }
/** * Package for junior.pack2.p8.ch5. Control tasks. * * @author Gureyev Ilya (mailto:ill-jah@yandex.ru) * @version 1 * @since 2017-10-09 */ package ru.job4j.control;
/* * 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 knn; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author romulo */ public class KNN { private final int k; private final Conjunto treino; private final Conjunto teste; public KNN(int k, Conjunto treino, Conjunto teste) { this.k = k; this.treino = (Conjunto) treino.clone(); this.teste = (Conjunto) teste.clone(); } public KNN(int k, InputStream treinoInputStream, InputStream testeInputStream) { this.k = k; this.teste = parseInputStream(testeInputStream); this.treino = parseInputStream(treinoInputStream); } private Conjunto parseInputStream(InputStream inputStream) { InputStreamReader inputStreamReader; BufferedReader bufferedReader; String strInstancia; List<Instancia> instancias; String[] strCaracteristicas; Caracteristica[] caracteristicas; Conjunto conjunto; conjunto = null; strInstancia = ""; instancias = new ArrayList(); inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader); try { while (strInstancia != null) { strInstancia = bufferedReader.readLine(); strCaracteristicas = strInstancia.split(", "); caracteristicas = new Caracteristica[strCaracteristicas.length - 1]; for (int i = 0; i < strCaracteristicas.length - 1; i++) { caracteristicas[i] = new Caracteristica(Double.parseDouble(strCaracteristicas[i])); } instancias.add(new Instancia(caracteristicas, Classe.parseClasse(strCaracteristicas[strCaracteristicas.length - 1]))); } conjunto = new Conjunto(instancias.toArray(new Instancia[instancias.size()])); } catch (IOException ex) { ex.printStackTrace(); } return conjunto; } public void classify() { for (Instancia instancia : this.treino) { for (Caracteristica caracteristica : instancia) { } } throw new UnsupportedOperationException(); } public double getEuclidienDistance(double[] a, double[] b) throws Exception { if (a.length != b.length) { throw new Exception("Vetores de tamanhos diferentes"); } int sum = 0; for (int i = 0; i < a.length; i++) { sum += Math.pow(a[i] - b[i], 2); } return Math.sqrt(sum); } }
package lemonfarm.gameUI; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.Intent; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.SoundPool; import android.os.Build; import android.os.Bundle; import android.os.SystemClock; import android.view.View; import android.view.animation.AccelerateInterpolator; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.BounceInterpolator; import android.widget.Button; import android.widget.Chronometer; import android.widget.EditText; import android.widget.GridLayout; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import cmpt276.as3.lemonfarm.R; import cmpt276.as3.lemonfarm.gameLogic.gameManager; import cmpt276.as3.lemonfarm.gameLogic.optionManager; import cmpt276.as3.lemonfarm.gameLogic.random; import cmpt276.as3.lemonfarm.music.song; import cmpt276.as3.lemonfarm.music.winSong; /** * Sets grid view * sets the grid with the correct number of * buttons according to optionManager * Sets random lemons * creates new set (array list) of random lemon index * Sets lemon view * when button clicked, either sets button image to lemon if random index or * sets button text to correct number of not-yet-found lemons in its row and column * Sets row and column found * initializes two array lists with the size of the board's row and column respectively * Update hint box * each time lemon button is found, for previous hint box/buttons clicked * that is in the row and column of the lemon button is updated with new number * (decrements hint box/button text by one) * Sets win message * has congratulatory message * plays new song for set duration * lemons fall from top of the screen * Increment methods * increments count and hintBoxCount to keep track of how many lemons were found * and how many hint boxes were used */ public class gamePage extends AppCompatActivity { private optionManager manager = optionManager.getInstance(); private random randomManager = random.getInstance(); private gameManager gameLogic = gameManager.getInstance(); private int count, columnVal, rowVal, hintBoxCount; private int hintRow, hintColumn; MediaPlayer lostSong; Chronometer time; @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game_page); time = findViewById(R.id.time); time.setBase(SystemClock.elapsedRealtime()); time.start(); setGrid(); setRandomLemons(); lemonView(); setRowColumnFound(); } @Override protected void onResume(){ super.onResume(); startService(new Intent(gamePage.this, song.class).setAction("PLAY")); } @Override protected void onPause(){ super.onPause(); startService(new Intent(gamePage.this, song.class).setAction("PAUSE")); startService(new Intent(gamePage.this, winSong.class).setAction("PAUSE")); } @SuppressLint("SetTextI18n") @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) private void setGrid() { int id = 0; final int column = Integer.parseInt(manager.getMyOption().get(0).getBoardColumn()); final int row = Integer.parseInt(manager.getMyOption().get(0).getBoardRow()); GridLayout lemonFarm = findViewById(R.id.lemonFarm); lemonFarm.setColumnCount(column); lemonFarm.setRowCount(row); for (int i = 0; i < row; i++) { GridLayout.Spec rowSpec = GridLayout.spec(i, 1, 0); for (int j = 0; j < column; j++) { GridLayout.Spec columnSpec = GridLayout.spec(j, 1, 0); final Button button = new Button(getApplicationContext()); button.setBackgroundResource(android.R.color.holo_orange_light); button.setId(id); button.setText(""); GridLayout.LayoutParams buttonParams = new GridLayout.LayoutParams(); buttonParams.height = getResources().getDisplayMetrics().heightPixels / 9; buttonParams.width = getResources().getDisplayMetrics().widthPixels / 17; buttonParams.columnSpec = columnSpec; buttonParams.rowSpec = rowSpec; buttonParams.setMargins(2, 1, 2, 1); lemonFarm.addView(button, buttonParams); id++; } } } public void incrementHintBox() { this.hintBoxCount = this.hintBoxCount + 1; } public void incrementCount() { this.count = this.count + 1; } private void setRandomLemons() { randomManager.setRandomArray(); } public void setRowColumnFound() { gameLogic.setRowColumnFound(); } public void setRowColumnVal(Button button) { gameLogic.setRowColumnVal(button); this.rowVal = gameLogic.getRowVal(); this.columnVal = gameLogic.getColumnVal(); } @SuppressLint("ResourceType") private void setHintVal(Button button) { gameLogic.setHintVal(button); this.hintRow = gameLogic.getHintRow(); this.hintColumn = gameLogic.getHintColumn(); } public void updateHintBox(Button randomButton) { final int column = Integer.parseInt(manager.getMyOption().get(0).getBoardColumn()); final int row = Integer.parseInt(manager.getMyOption().get(0).getBoardRow()); int j = this.hintColumn; for (int i = this.hintRow * column; i < column * (this.hintRow + 1); i++) { Button rowButton = findViewById(i); if (rowButton.isSelected() && randomButton.getId() != rowButton.getId()) { rowButton.setText(String.valueOf(Integer.parseInt((String) rowButton.getText())-1)); } } while (j <= column * (row - 1) + this.hintColumn) { Button columnButton = findViewById(j); if (columnButton.isSelected() && randomButton.getId() != columnButton.getId()) { columnButton.setText(String.valueOf(Integer.parseInt((String) columnButton.getText())-1)); } j = j + column; } } public void updateRestOfButtons(){ final int column = Integer.parseInt(manager.getMyOption().get(0).getBoardColumn()); final int row = Integer.parseInt(manager.getMyOption().get(0).getBoardRow()); for (int i=0; i< row*column; i++){ Button button = findViewById(i); if (!button.isSelected()){ button.setClickable(false); } } } @SuppressLint("SetTextI18n") private void lemonView() { final int column = Integer.parseInt(manager.getMyOption().get(0).getBoardColumn()); final int row = Integer.parseInt(manager.getMyOption().get(0).getBoardRow()); final int numb = Integer.parseInt(manager.getMyOption().get(0).getNumbOfLemon()); final TextView score = findViewById(R.id.score); final TextView hintBoxUsed = findViewById(R.id.hintBoxes); score.setText(this.count + " " + getString(R.string.score) + " " + numb); hintBoxUsed.setText(this.hintBoxCount + " " + getString(R.string.hintBox) + " " + ((row * column) - numb)); //soundPool code snippet found on stackOverflow -> button sound does not interfere with background music final SoundPool sound = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); sound.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { @Override public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { soundPool.play(sampleId, 1f, 1f, 0, 0, 1); } }); for (int i = 0; i < row*column; i++) { final Button button = findViewById(i); button.setOnClickListener(new View.OnClickListener() { @SuppressLint("ResourceType") @Override public void onClick(View v) { sound.load(gamePage.this, R.raw.button, 0); setHintVal(button); setRowColumnVal(button); if (randomManager.getRandom().contains(button.getId())) { button.setBackgroundResource(R.drawable.found); updateHintBox(button); incrementCount(); } else if (!randomManager.getRandom().contains(button.getId())) { button.setText(String.valueOf(columnVal + rowVal)); button.setSelected(true); incrementHintBox(); } score.setText(count + " " + getString(R.string.score) + " " + numb); hintBoxUsed.setText(hintBoxCount + " " + getString(R.string.hintBox) + " " + ((row * column) - numb)); if (count == numb && hintBoxCount < ((row*column)-numb)){ updateRestOfButtons(); time.stop(); setWinMessage(row, column, numb); }else if (count < numb && hintBoxCount == ((row*column)-numb)){ updateRestOfButtons(); time.stop(); setLoseMessage(); } button.setClickable(false); } }); } } public void setLoseMessage(){ final TextView loseMessage = findViewById(R.id.loseMessage); loseMessage.setVisibility(View.VISIBLE); final Button agreeToLost = findViewById(R.id.agreeToLosing); agreeToLost.setVisibility(View.VISIBLE); final GridLayout lemonGrid = findViewById(R.id.lemonFarm); lemonGrid.setVisibility(View.INVISIBLE); Animation blink = new AlphaAnimation(0.0f, 1.0f); blink.setDuration(700); blink.setRepeatMode(Animation.REVERSE); blink.setRepeatCount(5); loseMessage.startAnimation(blink); lostSong = MediaPlayer.create(getApplicationContext(), R.raw.lost); lostSong.seekTo(0); lostSong.start(); startService(new Intent(gamePage.this, song.class).setAction("PAUSE")); Toast.makeText(getApplicationContext(), R.string.agreeButtonToast, Toast.LENGTH_LONG).show(); agreeToLost.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { lostSong.pause(); startService(new Intent(gamePage.this, song.class).setAction("PLAY")); loseMessage.setVisibility(View.INVISIBLE); agreeToLost.setVisibility(View.INVISIBLE); startActivity(new Intent(gamePage.this, menuPage.class)); } }); } public void setWinMessage(final int row, final int column, final int numb){ final int score = (int)(SystemClock.elapsedRealtime() - time.getBase()); final TextView winMessage = findViewById(R.id.winMessage); winMessage.setVisibility(View.VISIBLE); final GridLayout lemonGrid = findViewById(R.id.lemonFarm); lemonGrid.setVisibility(View.INVISIBLE); final Button addButton = findViewById(R.id.add); final Button cancelButton = findViewById(R.id.cancel); final EditText nickname = findViewById(R.id.nickname); addButton.setVisibility(View.VISIBLE); cancelButton.setVisibility(View.VISIBLE); nickname.setVisibility(View.VISIBLE); Animation blink = new AlphaAnimation(0.0f, 1.0f); blink.setDuration(700); blink.setRepeatMode(Animation.REVERSE); blink.setRepeatCount(5); winMessage.startAnimation(blink); final ImageView lemon1 = findViewById(R.id.fallingLemon1); final ImageView lemon2 = findViewById(R.id.fallingLemon2); final ImageView lemon3 = findViewById(R.id.fallingLemon3); final ImageView lemon4 = findViewById(R.id.fallingLemon4); final ImageView lemon5 = findViewById(R.id.fallingLemon5); final ImageView lemon6 = findViewById(R.id.fallingLemon6); final ImageView lemon7 = findViewById(R.id.fallingLemon7); final ImageView lemon8 = findViewById(R.id.fallingLemon8); final ImageView lemon9 = findViewById(R.id.fallingLemon9); final ImageView lemon10 = findViewById(R.id.fallingLemon10); final ImageView lemon11 = findViewById(R.id.fallingLemon11); lemon1.setVisibility(View.VISIBLE); lemon2.setVisibility(View.VISIBLE); lemon3.setVisibility(View.VISIBLE); lemon4.setVisibility(View.VISIBLE); lemon5.setVisibility(View.VISIBLE); lemon6.setVisibility(View.VISIBLE); lemon7.setVisibility(View.VISIBLE); lemon8.setVisibility(View.VISIBLE); lemon9.setVisibility(View.VISIBLE); lemon10.setVisibility(View.VISIBLE); lemon11.setVisibility(View.VISIBLE); float bottom = getResources().getDisplayMetrics().heightPixels; lemon1.animate().translationY(bottom).setInterpolator(new AccelerateInterpolator()).setInterpolator(new BounceInterpolator()).setDuration(4098); lemon2.animate().translationY(bottom).setInterpolator(new AccelerateInterpolator()).setInterpolator(new BounceInterpolator()).setDuration(6356); lemon3.animate().translationY(bottom).setInterpolator(new AccelerateInterpolator()).setInterpolator(new BounceInterpolator()).setDuration(3754); lemon4.animate().translationY(bottom).setInterpolator(new AccelerateInterpolator()).setInterpolator(new BounceInterpolator()).setDuration(5456); lemon5.animate().translationY(bottom).setInterpolator(new AccelerateInterpolator()).setInterpolator(new BounceInterpolator()).setDuration(4756); lemon6.animate().translationY(bottom).setInterpolator(new AccelerateInterpolator()).setInterpolator(new BounceInterpolator()).setDuration(3463); lemon7.animate().translationY(bottom).setInterpolator(new AccelerateInterpolator()).setInterpolator(new BounceInterpolator()).setDuration(6098); lemon8.animate().translationY(bottom).setInterpolator(new AccelerateInterpolator()).setInterpolator(new BounceInterpolator()).setDuration(5356); lemon9.animate().translationY(bottom).setInterpolator(new AccelerateInterpolator()).setInterpolator(new BounceInterpolator()).setDuration(4754); lemon10.animate().translationY(bottom).setInterpolator(new AccelerateInterpolator()).setInterpolator(new BounceInterpolator()).setDuration(6456); lemon11.animate().translationY(bottom).setInterpolator(new AccelerateInterpolator()).setInterpolator(new BounceInterpolator()).setDuration(4756); startService(new Intent(gamePage.this, song.class).setAction("PAUSE")); Toast.makeText(getApplicationContext(), R.string.agreeButtonToast, Toast.LENGTH_LONG).show(); startService(new Intent(gamePage.this, winSong.class).setAction("PLAY")); if (addButton.isPressed() || cancelButton.isPressed()){ startService(new Intent(gamePage.this, winSong.class).setAction("PAUSE")); startService(new Intent(gamePage.this, song.class).setAction("PLAY")); winMessage.setVisibility(View.INVISIBLE); nickname.setVisibility(View.INVISIBLE); lemon1.setVisibility(View.INVISIBLE); lemon2.setVisibility(View.INVISIBLE); lemon3.setVisibility(View.INVISIBLE); lemon4.setVisibility(View.INVISIBLE); lemon5.setVisibility(View.INVISIBLE); lemon6.setVisibility(View.INVISIBLE); lemon7.setVisibility(View.INVISIBLE); lemon8.setVisibility(View.INVISIBLE); lemon9.setVisibility(View.INVISIBLE); lemon10.setVisibility(View.INVISIBLE); lemon11.setVisibility(View.INVISIBLE); } setAddButton(addButton, row, column, numb, nickname, score); setCancelButton(cancelButton); } public void setAddButton(final Button addButton, final int row, final int column, final int numb, final EditText nickname, final int score){ addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addButton.setVisibility(View.INVISIBLE); if (nickname.getText().toString().isEmpty()) { Toast.makeText(getApplicationContext(), R.string.nicknameMessage, Toast.LENGTH_LONG).show(); }else { Intent intent = new Intent(gamePage.this, scorePage.class); intent.putExtra("nickname", nickname.getText().toString()); intent.putExtra("score", score); intent.putExtra("gameMode", row + " rows " + column + " columns; " + numb + " lemons"); startActivity(intent); } } }); } public void setCancelButton(final Button cancelButton){ cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { cancelButton.setVisibility(View.INVISIBLE); startActivity(new Intent(gamePage.this, menuPage.class)); } }); } }
package com.daikit.graphql.execution; import java.util.List; import com.daikit.graphql.data.output.GQLExecutionErrorDetails; import graphql.ExceptionWhileDataFetching; import graphql.GraphQLError; /** * Default implementation of {@link IGQLErrorProcessor}. This class is intended * to be overridden to provide custom error handling. * * @author Thibaut Caselli */ public class GQLErrorProcessor implements IGQLErrorProcessor { // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // PUBLIC METHODS // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- @Override public GQLExecutionErrorDetails handleError(final List<GraphQLError> errors) { GQLExecutionErrorDetails error = null; if (errors != null) { if (errors.size() == 1 && errors.get(0) instanceof ExceptionWhileDataFetching) { error = handleError(((ExceptionWhileDataFetching) errors.get(0)).getException()); } else if (!errors.isEmpty()) { error = createError(); error.setType("GQLClientError"); error.setMessage((errors.size() <= 1 ? "An error" : "Multiple errors") + " happened while processing client request"); } } return error; } @Override public GQLExecutionErrorDetails handleError(final Throwable exception) { final GQLExecutionErrorDetails error = createError(); error.setMessage(exception.getMessage()); error.setType(exception.getClass().getSimpleName()); error.setWrappedException(exception); return error; } // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // PROTECTED METHODS // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- /** * Override to provide custom {@link GQLExecutionErrorDetails} extension * * @return a {@link GQLExecutionErrorDetails} */ protected GQLExecutionErrorDetails createError() { return new GQLExecutionErrorDetails(); } }
package rbtc.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.Size; @Entity @Table(name="mahasiswa") public class Mahasiswa { @Column(name="nama") private String nama; @Id @Column(name="nrp") private String nrp; @Column(name="email") private String email; @Column(name="no_hp") private String nohp; @Column(name="password") private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getNama() { return nama; } public void setNama(String nama) { this.nama = nama; } public String getNrp() { return nrp; } public void setNrp(String nrp) { this.nrp = nrp; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNohp() { return nohp; } public void setNohp(String nohp) { this.nohp = nohp; } public Mahasiswa() {} public Mahasiswa(String nama, String nrp, String email, String nohp, String password) { super(); this.nama = nama; this.nrp = nrp; this.email = email; this.nohp = nohp; this.password = password; } @Override public String toString() { return "Mahasiswa [nama=" + nama + ", nrp=" + nrp + ", email=" + email + ", nohp=" + nohp + ", password=" + password + "]"; } }
import java.util.*; public class tractor2bruteforce { public static int n; public static int ans; public static int half; public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); n = in.nextInt(); int[][] grid = new int[n][n]; for(int i = 0;i<n;i++) { for(int j = 0;j<n;j++) { grid[i][j] = in.nextInt(); } } half = n*n; if(half%2==1) half = half/2 +1; else half = half/2; ans = Integer.MAX_VALUE; for(int i = 0;i<n;i++) { for(int j =0;j<n;j++) { dfs(i,j,grid,new boolean[n][n],1,Integer.MAX_VALUE,0); } } System.out.println(ans); } public static void dfs(int x, int y, int[][] grid, boolean[][] visited, int cur,int min, int max) { if(x==-1||y==-1||x>=n||y>=n||visited[x][y]) { //System.out.println("broke"); return; } visited[x][y]=true; min = Math.min(min, grid[x][y]); max = Math.max(max, grid[x][y]); if(cur>=half) { ans = Math.min(max-min, ans); } dfs(x+1,y,grid, visited,cur+1,min,max); dfs(x,y+1,grid, visited,cur+1,min,max); dfs(x-1,y,grid, visited,cur+1,min,max); dfs(x,y-1,grid, visited,cur+1,min,max); } }
package org.tum.project.dashboard_controller; import com.mxgraph.swing.mxGraphComponent; import javafx.application.Platform; import javafx.embed.swing.SwingNode; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import javafx.scene.text.Text; import org.tum.project.dataservice.CefVisualizationService; import org.tum.project.login_controller.MenusHolderController; import org.tum.project.thread.TaskExecutorPool; import org.tum.project.utils.Utils; import javax.swing.*; import java.io.File; import java.net.URL; import java.util.ResourceBundle; /** * cef editor controller * set the layout for cef editor pane * Created by heylbly on 17-6-8. */ public class CefEditorController implements Initializable { private String separator = File.separator; @FXML private Text t_openFile; @FXML private Text t_savePath; @FXML private StackPane sp_editor; private CefVisualizationService cefVisualizationService; private File openFilePath; @FXML private Text t_loadingLabel; @FXML private Pane addPropertiesContainer; @Override public void initialize(URL location, ResourceBundle resources) { DashBoardController.getServiceInstanceMap().put(this.getClass().getName(), this); } /** * open the cef ecore xml file * * @param event */ @FXML void openAction(ActionEvent event) { t_loadingLabel.setVisible(true); openFilePath = Utils.openFileChooser("open", MenusHolderController.getDashBoardStage()); String[] split = new String[1]; if (openFilePath != null) { split = openFilePath.getAbsolutePath().split("/"); } t_openFile.setText("Open file: " + split[split.length - 1]); TaskExecutorPool.getExecutor().execute(() -> { //visualize the cef ecore file cefVisualizationService = (CefVisualizationService) DashBoardController.getDataServiceInstance(CefVisualizationService.class.getName()); mxGraphComponent mxGraphComponent = cefVisualizationService.startVisualization(openFilePath.getAbsolutePath(), sp_editor); Platform.runLater(() -> displayContent(mxGraphComponent)); }); } /** * display the graph of the ecore in the javafx application * * @param mxGraphComponent */ private void displayContent(mxGraphComponent mxGraphComponent) { //embed the Swing Component to the javafx Application SwingNode swingNode = new SwingNode(); SwingUtilities.invokeLater(() -> { swingNode.setContent(mxGraphComponent); Platform.runLater(() -> { if (!sp_editor.getChildren().isEmpty()) { sp_editor.getChildren().clear(); } sp_editor.getChildren().add(swingNode); }); }); } /** * select the save path to save the modified cef file * * @param event */ @FXML void saveAction(ActionEvent event) { Object[] objects = cefVisualizationService.saveFile(); String fileName = (String) objects[0]; String[] split = new String[1]; if (fileName != null) { split = fileName.split("/"); } t_savePath.setText("File save: " + split[split.length - 1]); displayContent((mxGraphComponent) objects[1]); } /** * refresh the graph after edit * * @param event */ @FXML void refreshAction(ActionEvent event) { TaskExecutorPool.getExecutor().execute(() -> { mxGraphComponent mxGraphComponent = cefVisualizationService.refresh(); Platform.runLater(() -> displayContent(mxGraphComponent)); }); } public static void main(String[] args) { String fe = "/home/heylbly/Desktop/multimedia_4x4_routed.xml"; String[] split = fe.split("/"); System.out.println(split[4]); } public Pane getAddPropertiesContainer() { return addPropertiesContainer; } }
package com.reactnative.googlecast.types; import androidx.annotation.Nullable; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableNativeMap; import com.google.android.gms.cast.MediaQueueData; import com.google.android.gms.cast.MediaQueueItem; import com.google.android.gms.common.images.WebImage; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class RNGCMediaQueueData { public static MediaQueueData fromJson(final ReadableMap json) { MediaQueueData.Builder builder = new MediaQueueData.Builder(); if (json.hasKey("containerMetadata")) { builder.setContainerMetadata(RNGCMediaQueueContainerMetadata.fromJson(json.getMap("containerMetadata"))); } if (json.hasKey("entity")) { builder.setEntity(json.getString("entity")); } if (json.hasKey("id")) { builder.setQueueId(json.getString("id")); } if (json.hasKey("items")) { final List<MediaQueueItem> items = new ArrayList<MediaQueueItem>(); ReadableArray itemsArray = json.getArray("items"); for (int i = 0; i < itemsArray.size(); i++) { items.add(RNGCMediaQueueItem.fromJson(itemsArray.getMap(i))); } builder.setItems(items); } if (json.hasKey("name")) { builder.setName(json.getString("name")); } if (json.hasKey("repeatMode")) { builder.setRepeatMode(RNGCMediaRepeatMode.fromJson(json.getString("repeatMode"))); } if (json.hasKey("startIndex")) { builder.setStartIndex(json.getInt("startIndex")); } if (json.hasKey("startTime")) { builder.setStartTime(Math.round(json.getDouble("startTime") * 1000)); } if (json.hasKey("type")) { builder.setQueueType(RNGCMediaQueueType.fromJson(json.getString("type"))); } return builder.build(); } public static @Nullable WritableMap toJson(final @Nullable MediaQueueData data) { if (data == null) return null; final WritableMap json = new WritableNativeMap(); json.putMap("containerMetadata", RNGCMediaQueueContainerMetadata.toJson(data.getContainerMetadata())); json.putString("entity", data.getEntity()); json.putString("id", data.getQueueId()); final WritableArray items = Arguments.createArray(); if (data.getItems() != null) { for (MediaQueueItem item : data.getItems()) { items.pushMap(RNGCMediaQueueItem.toJson(item)); } } json.putArray("items", items); json.putString("name", data.getName()); json.putString("repeatMode", RNGCMediaRepeatMode.toJson(data.getRepeatMode())); json.putString("type", RNGCMediaQueueType.toJson(data.getQueueType())); return json; } }
package zhuoxin.com.viewpagerdemo.activity; import android.content.Intent; import android.os.Handler; import android.os.Message; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import android.widget.TextView; import zhuoxin.com.viewpagerdemo.R; import zhuoxin.com.viewpagerdemo.info.CollectInfo; import zhuoxin.com.viewpagerdemo.info.ContentlistBean; import zhuoxin.com.viewpagerdemo.sql.MyCollectSQLiteUtil; public class LookActivity extends AppCompatActivity { private String url; private String title; private WebView webView; private Toolbar toolbar; private ProgressBar progressBar; private FloatingActionButton button; private MyCollectSQLiteUtil sqLiteUtil; private CoordinatorLayout layout; private LayoutInflater inflater; private Handler handler = new Handler(){ public void handleMessage(Message msg) { super.handleMessage(msg); progressBar.setProgress(msg.arg1); if(msg.arg1==100){ progressBar.setVisibility(View.GONE); } } }; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_look); inflater = LayoutInflater.from(this); ContentlistBean bean = (ContentlistBean) getIntent().getSerializableExtra("url"); url = bean.getLink(); title=bean.getTitle(); initView(); initData(url); } private void initView() { sqLiteUtil = new MyCollectSQLiteUtil(this); progressBar =(ProgressBar)findViewById(R.id.look_progressBar); layout= (CoordinatorLayout) findViewById(R.id.look_coordLayout); toolbar = (Toolbar) findViewById(R.id.activity_look_toolBar); toolbar.setTitle(""); toolbar.setTitleTextColor(getResources().getColor(R.color.colorWhite)); toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.btn_return)); setSupportActionBar(toolbar); toolbar.setNavigationOnClickListener(new View.OnClickListener() { public void onClick(View view) { finish(); } }); button= (FloatingActionButton) findViewById(R.id.look_fabtn); button.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { sqLiteUtil.insert(new CollectInfo(title,url)); // layout.setTextAlignment(); Snackbar.make(layout,"收藏成功!",Snackbar.LENGTH_INDEFINITE) .setAction("查看收藏", new View.OnClickListener() { public void onClick(View view) { Intent intent = new Intent(LookActivity.this,CollectActivity.class); intent.putExtra("title",title); startActivity(intent); } }) .show(); // setSnackbarColor(snackbar,R.color.colorWhite,R.color.colorDeepSkyBlue); } }); } private void initData(final String Url) { webView = (WebView) findViewById(R.id.activity_look_webView); webView.loadUrl(Url); webView.getSettings().setLoadWithOverviewMode(true);//back键返回 // webView.getSettings().setJavaScriptEnabled(true); webView.setWebChromeClient(new MyWebChromeClient()); webView.setWebViewClient(new MyWebViewClient()); } class MyWebChromeClient extends WebChromeClient{ public void onProgressChanged(WebView view, int newProgress) { //获取进度更新 Message message = Message.obtain(); message.arg1=newProgress; handler.sendMessage(message); super.onProgressChanged(view, newProgress); } } class MyWebViewClient extends WebViewClient{ public boolean shouldOverrideUrlLoading(WebView view, String url) { //拦截系统加载 view.loadUrl(url); return true; } } // public boolean onKeyDown(int keyCode, KeyEvent event) { // switch (keyCode){ // //返回键的监听,返回上一页 // case KeyEvent.KEYCODE_BACK: // Log.i("AAA","第一次"); // if(webView.canGoBack()){ // Log.i("AAA","第二次"); // webView.goBack(); // } // break; // } // return true; // } public void setSnackbarColor(Snackbar snackbar, int messageColor, int backgroundColor) { View view = snackbar.getView();//获取Snackbar的view if(view!=null){ view.setBackgroundColor(backgroundColor);//修改view的背景色 ((TextView) view.findViewById(R.id.snackbar_text)).setTextColor(messageColor);//获取Snackbar的message控件,修改字体颜色 } } }
package two; /** * Vrste programskih jezika; * <li>1. Statically ili strogo tipizirani</li> * <li>2. Slabo tipizirani</li> * * <p> * Tipovi podataka u programskom jeziku Java: * <li>1. Prosti ili ugrađeni ili primitivni tipovi</li> * * 1.1 byte -> 8 bita * * 1.2 short -> 16 bita * * 1.3 int -> 32 bitni //PODRAZUMIJEVANI CIJELI * * 1.4 long -> 64 bitni * * 1.5 float -> 32 bitni * * 1.6 double -> 64 bitni//PODRAZUIJEVANI decimalni zapis * * 1.7 char -> 16 bitakaraktere u memorijski prostor * * 1.8 boolean -> false ili true * <li>2. Složeni ili objektni </li> * NIZ * String * </p> */ public class Executor { public static void main(String[] args) { //TIP_SADRZAJA IME_MEMORIJSKE(varijabla) = VRIJEDNOST_PODATAK; byte number1 = 13; short number2 = 32767; int number3 = 69000;//podrazumijevani cijeli broj long number4 = 12324L; //AUTOMATSKOJ KONVERZIJI TIPA int intNumber = 234; long longNumber = intNumber; //EKSPLICITNA KONVERZIJA TIPAA long longNumber1 = 23456; int intNumber1 = (int)longNumber1; short br1 = 150; short br2 = (short)150.7; //int int rezultat=br1+br2; float floatNumber = 23.9F; double doubleNumber = 23.9; float nekiBroj = 0.1f; double nekiBroj1 = 0.1; //BigDecimal System.out.println(nekiBroj==nekiBroj1); char charVarijabla = '!'; charVarijabla = 'A'; char charVarijabla1 = 33; System.out.println(charVarijabla1); int brojPogadjamo = 0b111; System.out.println(brojPogadjamo); brojPogadjamo = 0x52; System.out.println(brojPogadjamo); } }
package gov.nih.mipav.view.renderer.J3D.surfaceview; import gov.nih.mipav.view.*; import gov.nih.mipav.view.renderer.J3D.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * The display panel control the red bounding box frame ( on/off ), texture aligned rendering mode, cubic controk, * perspective and parrallel viewing mode, and back ground color. */ public class JPanelDisplay extends JPanelRendererJ3D implements KeyListener { //~ Static fields/initializers ------------------------------------------------------------------------------------- /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = 926266253314679850L; //~ Instance fields ------------------------------------------------------------------------------------------------ /** Check box for turning box on and off. */ protected JCheckBox boundingCheck; /** Color button for changing color. */ protected JButton colorButton; /** Color button for changing z color. */ protected JButton colorButtonBackground; /** Color chooser dialog. */ protected ViewJColorChooser colorChooser; /** Panel for the rotation cube. */ protected JPanel cubePanel; /** Check box for cubic control. */ protected JCheckBox cubicCheck; /** Button group for projections. */ protected ButtonGroup radioButtonGroupProjections; /** Radio Button for Orthographic rendering. */ protected JRadioButton radioButtonOrthographic; /** Radio Button for Perspective rendering. */ protected JRadioButton radioButtonPerspective; /** Radio Button for Perspective rendering. */ protected JRadioButton viewAlignedButton; /** Radio Button for Orthographic rendering. */ protected JRadioButton viewButton; /** Button group for projections. */ protected ButtonGroup viewTextureButtonGroup; /** Coarse and fine value. */ private float coarseValue, fineValue; /** Coarse and fine value text field. */ private JTextField fine, coarse; /** Coarse and fine value label. */ private JLabel fineLabel, coarseLabel; /** Flag indicating if the red bounding box is on or off. */ private boolean flag = false; /** The scroll pane holding the panel content. Useful when the screen is small. */ private JScrollPane scroller; /** Scroll panel that holding the all the control components. */ private DrawingPanel scrollPanel; //~ Constructors --------------------------------------------------------------------------------------------------- /** * Creates new dialog for turning bounding box frame on and off. * * @param parent Should be of type ViewJFrameSurfaceRenderer */ public JPanelDisplay(RenderViewBase parent) { super(parent); init(); } //~ Methods -------------------------------------------------------------------------------------------------------- /** * Changes color of box frame and button if color button was pressed; turns bounding box on and off if checkbox was * pressed; and closes dialog if "Close" button was pressed. * * @param event Event that triggered function. */ public void actionPerformed(ActionEvent event) { Object source = event.getSource(); String command = event.getActionCommand(); if (source instanceof JButton) { colorChooser = new ViewJColorChooser(new Frame(), "Pick color", new OkColorListener((JButton) source), new CancelListener()); } else if (source == boundingCheck) { if (boundingCheck.isSelected() != flag) { flag = boundingCheck.isSelected(); if (flag == true) { ((SurfaceRender) renderBase).showBoxFrame(); colorButton.setEnabled(true); } else { ((SurfaceRender) renderBase).hideBoxFrame(); colorButton.setEnabled(false); } } } else if (source == radioButtonOrthographic) { if (renderBase instanceof SurfaceRender) { ((SurfaceRender) renderBase).setRenderPerspective(false); } } else if (source == radioButtonPerspective) { if (renderBase instanceof SurfaceRender) { ((SurfaceRender) renderBase).setRenderPerspective(true); } } else if (source == viewButton) { ((SurfaceRender) renderBase).setViewTextureAligned(false); setTextEnabled(false); } else if (source == viewAlignedButton) { ((SurfaceRender) renderBase).setViewTextureAligned(true); setTextEnabled(true); } else if (source == cubicCheck) { if (cubicCheck.isSelected()) { ((SurfaceRender) renderBase).addCubicControl(); } else { ((SurfaceRender) renderBase).removeCubicControl(); } } } /** * Dispose memory. */ public void dispose() { boundingCheck = null; cubicCheck = null; colorButton = null; colorButtonBackground = null; colorChooser = null; flag = false; radioButtonOrthographic = null; radioButtonPerspective = null; radioButtonGroupProjections = null; cubePanel = null; viewButton = null; viewAlignedButton = null; viewTextureButtonGroup = null; fineLabel = null; coarseLabel = null; fine = null; coarse = null; } /** * Get the coarse value. * * @return float coarse value. */ public float getCoarseVal() { return Float.parseFloat(coarse.getText()); } /** * Get the fine value. * * @return float fine value. */ public float getFineVal() { return Float.parseFloat(fine.getText()); } /** * Get the main control panel. * * @return mainPanel main GUI. */ public JPanel getMainPanel() { return mainPanel; } /** * Unchanged. * * @param e DOCUMENT ME! */ public void keyPressed(KeyEvent e) { } /** * Unchanged. * * @param e DOCUMENT ME! */ public void keyReleased(KeyEvent e) { } /** * When the user enter the coarse and fine value, invoke this event to update fine or coarse sampling. * * @param evt key event */ public void keyTyped(KeyEvent evt) { Object source = evt.getSource(); char ch = evt.getKeyChar(); if (ch == KeyEvent.VK_ENTER) { fineValue = Float.parseFloat(fine.getText()); coarseValue = Float.parseFloat(coarse.getText()); ((SurfaceRender) renderBase).setSliceSpacingFine(fineValue); ((SurfaceRender) renderBase).setSliceSpacingCoarse(coarseValue); if (source.equals(fine)) { ((SurfaceRender) renderBase).useSliceSpacingFine(); } else { ((SurfaceRender) renderBase).useSliceSpacingCoarse(); } } } /** * Resizig the control panel with ViewJFrameVolumeView's frame width and height. * * @param panelWidth int width * @param frameHeight int height */ public void resizePanel(int panelWidth, int frameHeight) { scroller.setPreferredSize(new Dimension(panelWidth, frameHeight - 40)); scroller.setSize(new Dimension(panelWidth, frameHeight - 40)); scroller.revalidate(); } /** * Set the color for the color button. * * @param _color Color */ public void setColorButton(Color _color) { colorButtonBackground.setBackground(_color); } /** * Set the radio button for view volume aligned enable or not. * * @param flag true enable and false disable. */ public void setEnable(boolean flag) { viewButton.setEnabled(flag); viewAlignedButton.setEnabled(flag); } /** * Enable the the fine or coarse labels and text fields with given flag value. * * @param flag true enable, false disable. */ public void setTextEnabled(boolean flag) { fineLabel.setEnabled(flag); coarseLabel.setEnabled(flag); fine.setEnabled(flag); coarse.setEnabled(flag); } /** * Calls the appropriate method in the parent frame. * * @param button DOCUMENT ME! * @param color Color to set box frame to. */ protected void setBoxColor(JButton button, Color color) { if (button == colorButton) { renderBase.setBoxColor(color); } if (button == colorButtonBackground) { renderBase.setBackgroundColor(color); } } /** * Initializes GUI components. */ private void init() { boundingCheck = new JCheckBox("Show bounding frame"); boundingCheck.setFont(serif12); boundingCheck.addActionListener(this); colorButton = new JButton(); colorButton.setPreferredSize(new Dimension(25, 25)); colorButton.setToolTipText("Change box frame color"); colorButton.addActionListener(this); colorButton.setBackground(Color.red); colorButton.setEnabled(false); JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.weightx = 1; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(5, 5, 5, 5); panel.add(colorButton, gbc); gbc.gridx = 1; panel.add(boundingCheck, gbc); panel.setBorder(buildTitledBorder("Bounding box options")); colorButtonBackground = new JButton(); colorButtonBackground.setPreferredSize(new Dimension(25, 25)); colorButtonBackground.setToolTipText("Change background color"); colorButtonBackground.addActionListener(this); colorButtonBackground.setBackground(Color.darkGray); JLabel backgroundLabel = new JLabel("Background color"); backgroundLabel.setFont(serif12); backgroundLabel.setForeground(Color.black); JPanel panel2 = new JPanel(new GridBagLayout()); gbc.gridx = 0; gbc.gridy = 0; panel2.add(colorButtonBackground, gbc); gbc.gridx = 1; panel2.add(backgroundLabel, gbc); panel2.setBorder(buildTitledBorder("Background")); JPanel projectionTypePanel = new JPanel(); projectionTypePanel.setBorder(buildTitledBorder("Projection Type")); Box projectionTypeBox = new Box(BoxLayout.X_AXIS); radioButtonPerspective = new JRadioButton(); radioButtonPerspective.addActionListener(this); radioButtonOrthographic = new JRadioButton(); radioButtonOrthographic.addActionListener(this); radioButtonGroupProjections = new ButtonGroup(); radioButtonPerspective.setSelected(true); radioButtonPerspective.setText("Perspective View "); radioButtonOrthographic.setText("Orthographic View"); radioButtonGroupProjections.add(radioButtonPerspective); radioButtonGroupProjections.add(radioButtonOrthographic); projectionTypeBox.add(radioButtonPerspective); projectionTypeBox.add(radioButtonOrthographic); projectionTypePanel.add(projectionTypeBox); cubicCheck = new JCheckBox("Show orientation cube"); cubicCheck.setFont(serif12); cubicCheck.addActionListener(this); cubePanel = new JPanel(new GridBagLayout()); gbc.weightx = 1; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(5, 5, 5, 5); cubePanel.add(cubicCheck, gbc); cubePanel.setBorder(buildTitledBorder("Orientation")); JPanel viewTexturePanel = new JPanel(); viewTexturePanel.setBorder(buildTitledBorder("Texture Type")); Box viewTextureBox = new Box(BoxLayout.Y_AXIS); viewButton = new JRadioButton(); viewButton.addActionListener(this); viewAlignedButton = new JRadioButton(); viewAlignedButton.addActionListener(this); viewTextureButtonGroup = new ButtonGroup(); viewButton.setSelected(true); viewButton.setText("View volume texture "); viewAlignedButton.setText("View aligned volume texture"); viewTextureButtonGroup.add(viewButton); viewTextureButtonGroup.add(viewAlignedButton); JPanel inputPanel = new JPanel(new GridBagLayout()); fineLabel = new JLabel("Fine"); fineLabel.setFont(serif12); fineLabel.setForeground(Color.black); fineLabel.setRequestFocusEnabled(false); gbc.weightx = 0.5; gbc.anchor = GridBagConstraints.CENTER; gbc.insets = new Insets(1, 1, 1, 1); gbc.gridx = 0; gbc.gridy = 0; inputPanel.add(fineLabel, gbc); fine = new JTextField(8); fineValue = ((SurfaceRender) renderBase).getSliceSpacingFine(); float resolX = renderBase.getImageA().getFileInfo(0).getResolutions()[0]; if ((1.0 - resolX) >= 0.5) { fineValue = fineValue / (1.0f / resolX); } fine.setText(MipavUtil.makeFloatString(fineValue, 7)); fine.addKeyListener(this); MipavUtil.makeNumericsOnly(fine, true, true); gbc.gridx = 1; inputPanel.add(fine, gbc); coarseLabel = new JLabel("Coarse"); coarseLabel.setFont(serif12); coarseLabel.setForeground(Color.black); coarseLabel.setRequestFocusEnabled(false); gbc.gridx = 0; gbc.gridy = 1; inputPanel.add(coarseLabel, gbc); coarse = new JTextField(8); coarseValue = ((SurfaceRender) renderBase).getSliceSpacingCoarse(); if ((1.0 - resolX) >= 0.5) { coarseValue = coarseValue / (1.0f / resolX); } coarse.setText(MipavUtil.makeFloatString(coarseValue, 7)); coarse.addKeyListener(this); MipavUtil.makeNumericsOnly(coarse, true, true); gbc.gridx = 1; inputPanel.add(coarse, gbc); viewTextureBox.add(viewButton); viewTextureBox.add(viewAlignedButton); viewTextureBox.add(inputPanel); viewTexturePanel.add(viewTextureBox); Box contentBox = new Box(BoxLayout.Y_AXIS); contentBox.add(panel); contentBox.add(panel2); contentBox.add(cubePanel); contentBox.add(projectionTypePanel); contentBox.add(viewTexturePanel); // Scroll panel that hold the control panel layout in order to use JScrollPane scrollPanel = new DrawingPanel(); scrollPanel.setLayout(new BorderLayout()); scrollPanel.add(contentBox, BorderLayout.NORTH); scroller = new JScrollPane(scrollPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); mainPanel = new JPanel(); mainPanel.add(scroller); setEnable(false); setTextEnabled(false); } //~ Inner Classes -------------------------------------------------------------------------------------------------- /** * Does nothing. */ class CancelListener implements ActionListener { /** * Does nothing. * * @param e DOCUMENT ME! */ public void actionPerformed(ActionEvent e) { } } /** * Wrapper in order to hold the control panel layout in the JScrollPane. */ class DrawingPanel extends JPanel { /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = -375187487188025368L; /** * DOCUMENT ME! * * @param g DOCUMENT ME! */ protected void paintComponent(Graphics g) { super.paintComponent(g); } } /** * Pick up the selected color and call method to change the color. */ class OkColorListener implements ActionListener { /** DOCUMENT ME! */ JButton button; /** * Creates a new OkColorListener object. * * @param _button DOCUMENT ME! */ OkColorListener(JButton _button) { super(); button = _button; } /** * Get color from chooser and set button and color. * * @param e Event that triggered function. */ public void actionPerformed(ActionEvent e) { Color color = colorChooser.getColor(); button.setBackground(color); setBoxColor(button, color); } } }
package pl.globallogic.qaa_academy.oop; public class Engine { private float volume; private String producer; public void ignite(){ System.out.println("wruum"); } }
package com.cn.daniel; 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.boot.context.embedded.EmbeddedServletContainerCustomizer; import org.springframework.boot.web.servlet.ErrorPage; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpStatus; import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; import com.cn.daniel.system.config.freemaker.MyFreemarkerView; /** * Spring Boot 应用启动类 * * @author Daniel * @time 2017-07-10 */ // Spring Boot 应用的标识 @SpringBootApplication // mapper 接口类扫描包配置 @MapperScan("com.cn.daniel.*.dao") public class Application { public static void main(String[] args) { // 程序启动入口 // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件 SpringApplication.run(Application.class, args); } //freemaker自定义 @Bean public CommandLineRunner customFreemarker(final FreeMarkerViewResolver resolver) { return new CommandLineRunner() { @Override public void run(String... strings) throws Exception { // 增加视图 resolver.setViewClass(MyFreemarkerView.class); // 添加自定义解析器 // Map<String, Object> map = resolver.getAttributesMap(); } }; } //自定义错误页面 @Bean public EmbeddedServletContainerCustomizer containerCustomizer() { return (container -> { ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html"); ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"); ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html"); container.addErrorPages(error401Page, error404Page, error500Page); }); } }
package br.crud.spring.service; import java.util.List; import br.crud.spring.model.Pessoa; public interface PessoaService { Pessoa cadastrar(Pessoa pessoa); String remover(Long id); List<Pessoa> listar(); Pessoa atualizar(Pessoa pessoa); }
package com.ngocdt.tttn.dto; import com.ngocdt.tttn.entity.SkinType; public class SkinTypeDTO { private int id; private String type; public static SkinTypeDTO toDTO(SkinType type){ if (type == null) return null; SkinTypeDTO dto = new SkinTypeDTO(); dto.setId(type.getId()); dto.setType(type.getType()); return dto; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
package edu.dlsu.securde; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; //import org.springframework.boot.autoconfigure.domain.EntityScan; //import org.springframework.context.annotation.ComponentScan; //import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication //@ComponentScan({"controller","configuration"}) //@EntityScan(basePackages = {"model"} ) //@EnableJpaRepositories(basePackages = {"repositories"}) public class SecurdempApplication { public static void main(String[] args) { SpringApplication.run(SecurdempApplication.class, args); } }
/* * Created on Mar 2, 2007 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.citibank.ods.persistence.pl.dao; import java.math.BigInteger; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.entity.pl.TplOfficerCmplMovementEntity; /** * @author bruno.zanetti * * TODO To change the template for this generated type comment go to Window - * Preferences - Java - Code Style - Code Templates */ public interface TplOfficerCmplMovDAO extends BaseTplOfficerCmplDAO { public void update( TplOfficerCmplMovementEntity officerCmplMovementEntity_ ); public void delete( TplOfficerCmplMovementEntity officerCmplMovementEntity_ ); public TplOfficerCmplMovementEntity insert( TplOfficerCmplMovementEntity officerCmplMovementEntity_ ); /** * @param lastUpdUserId_ TODO * @param offcrRefDate TODO * @return * @generated "UML to Java * (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)" */ public DataSet list( BigInteger offcrIntnlNbr_, BigInteger offcrNbr_, String offcrTypeCode_, String lastUpdUserId_, String offcrNameText_ ); public boolean exists( TplOfficerCmplMovementEntity tplOfficerCmplMovementEntity_ ); }
package DataStructures.arrays; /** * Created by User on 22-07-2017. */ public class EvenSum { public static boolean splitArray(int[] arr) { if (arr.length ==0) return false; // Sum up the array int arr_sum = 0; for (int item: arr) arr_sum+= item; // If sum is an odd number, it is impossible to split the array of elements evenly. if (arr_sum%2 != 0) return false; // If sum is an even number, check if the summation to half is possible. return groupSum(0,arr,arr_sum/2); } public static boolean groupSum(int start_index, int[] arr, int target) { // Base case: there is no number left. if (start_index >= arr.length) return (target == 0); else { // Recursive case 1: include the 1st number, check the remaining if (groupSum(start_index+1,arr,target-arr[start_index])) return true; // Recursive case 2: does not include the 1st number, check the remaining if (groupSum(start_index+1,arr,target)) return true; } return false; } public static void main(String a[]) { System.out.println(splitArray(new int[]{1,2,3,4,5,6})); } }
package com.arpit.equityposition.services; import com.arpit.equityposition.model.Position; import com.arpit.equityposition.model.Transaction; import com.arpit.equityposition.utilities.ValidActions; import com.arpit.equityposition.utilities.ValidSides; /** * Service Interface for Transaction Operations. * @author : Arpit * @version 1.0 * @since : 23-Jun-2020 */ public class TransactionServiceImpl implements TransactionService { private PositionService posSer; public TransactionServiceImpl(PositionService posSer) { this.posSer = posSer; } /** * To Process a transaction. * Will add/update/cancel based on action * * @param txn */ public void processTransaction(Transaction txn) { if(ValidActions.INSERT.equals(txn.getAction())){ insertTransaction(txn); }else if(ValidActions.UPDATE.equals(txn.getAction())){ updateTransaction(txn); }else if(ValidActions.CANCEL.equals(txn.getAction())){ cancelTransaction(txn); } } /** * To add a transaction to position. * * @param txn * @return */ public boolean insertTransaction(Transaction txn) { Position p = posSer.getPositions(txn.getSecurityCode(),txn.getTradeID()); if(p == null){ posSer.addPosition(new Position(txn.getSecurityCode(),txn.getVersion(),getActualQuanity(txn.getQuantity(),txn.getSide()),txn.getTradeID())); }else{ if ( p.getTradeId() >= txn.getTradeID() && p.getVersion() >= txn.getVersion()){ System.out.println("Position is already on an advanced version."); return false; }else{ long quantity = getActualQuanity(txn.getQuantity(),txn.getSide()); posSer.updatePosition(new Position(txn.getSecurityCode(), txn.getVersion(), p.getQuantity() + quantity,txn.getTradeID())); } } return false; } /** * This Method will cancel the given transaction * * @param txn * @return true if transactions is cancelled. */ public boolean cancelTransaction(Transaction txn) { Position p = posSer.getPositions(txn.getSecurityCode(),txn.getTradeID()); if(null == p){ System.out.println("Not A Valid Operation. No Existing Position Found to cancel."); return false; } posSer.updatePosition(new Position(p.getSecurityCode(),txn.getVersion(),0l,txn.getTradeID())); return true; } /** * To update the position. * SecurityCode, Quantity, Buy/Sell can change * * @param txn * @return */ public boolean updateTransaction(Transaction txn) { Position p = posSer.getPositions(txn.getSecurityCode(),txn.getTradeID()); if(p == null) { posSer.addPosition(new Position(txn.getSecurityCode(), txn.getVersion(), getActualQuanity(txn.getQuantity(),txn.getSide()), txn.getTradeID())); }else if ( p.getTradeId() >= txn.getTradeID() && p.getVersion() >= txn.getVersion()){ System.out.println("This is not a valid operation. "); }else{ posSer.updatePosition(new Position(txn.getSecurityCode(),txn.getVersion(),getActualQuanity(txn.getQuantity(),txn.getSide()),txn.getTradeID())); } return false; } /** * This method will utilize the side to get actual quatity. * @param quantity * @param side * @return */ private long getActualQuanity(long quantity, ValidSides side){ if (ValidSides.SELL.equals(side)){ return quantity*-1l; } else return quantity; } }
package org.mehaexample.asdDemo.dao.alignadmin; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.mehaexample.asdDemo.dao.alignprivate.StudentSessionFactory; import org.mehaexample.asdDemo.dao.alignprivate.StudentTestSessionFactory; import org.mehaexample.asdDemo.enums.Campus; import org.mehaexample.asdDemo.model.alignadmin.GenderRatio; import java.util.ArrayList; import java.util.List; public class GenderRatioDao { private SessionFactory factory; /** * Default constructor. */ public GenderRatioDao() { // it will check the hibernate.cfg.xml file and load it // next it goes to all table files in the hibernate file and loads them this.factory = StudentSessionFactory.getFactory(); } /** * Test constructor. * * @param test set true to construct test dao. */ public GenderRatioDao(boolean test) { if (test) { this.factory = StudentTestSessionFactory.getFactory(); } } /** * Get the gender ratio broke down in years based on the Campus Location. * * @param campuses to broke down the annual gender ratio. * @return list of gender ratio. */ public List<GenderRatio> getYearlyGenderRatio(List<Campus> campuses) { String hql = "SELECT NEW org.mehaexample.asdDemo.model.alignadmin.GenderRatio(s.entryYear, " + "COUNT(CASE s.gender WHEN 'M' THEN 1 ELSE NULL END), " + "COUNT(CASE s.gender WHEN 'F' THEN 1 ELSE NULL END)) " + "FROM Students s " + "WHERE s.campus IN (:campuses) " + "GROUP BY s.entryYear " + "ORDER BY s.entryYear ASC "; List<GenderRatio> list; Session session = factory.openSession(); try { org.hibernate.query.Query query = session.createQuery(hql); query.setParameter("campuses", campuses); list = query.list(); } finally { session.close(); } return list; } }
package project.handler; import java.sql.Date; import project.go.outside.domain.Review; import project.util.Prompt; public class ReviewHandler { UserHandler userList; static final int DEFAULT_CAPACITY = 3; Node first; Node last; int size = 0; public void add() { System.out.println("---------------------------------------------------------------------------------------------------------"); System.out.println("[리뷰 등록]"); Review r = new Review(); r.no = Prompt.inputInt("번호? "); r.title = Prompt.inputString("평점? "); r.title = Prompt.inputString("제목? "); r.content = Prompt.inputString("내용? "); r.writer = Prompt.inputString("작성자? "); r.password = Prompt.inputString("암호? "); r.registeredDate = new Date(System.currentTimeMillis()); r.stars = Prompt.inputInt("모험상태?\n0: 모험실패\n1: 모험중\n2: 모험완료\n> "); Node node = new Node(r); if (last == null) { last = node; first = node; } else { last.next = node; node.prev = last; last = node; } this.size++; System.out.println("리뷰를 등록하였습니다."); } public void list() { System.out.println("---------------------------------------------------------------------------------------------------------"); System.out.println("[리뷰 목록]"); Node cursor = first; while (cursor != null) { Review r = cursor.review; System.out.printf("[%d] %s ㅣ %s ㅣ %s ㅣ %s ㅣ %d ㅣ %d\n", r.no, r.title, r.registeredDate, r.writer, getStars(r.stars), r.viewCount, r.like); cursor = cursor.next; } } public void detail() { System.out.println("---------------------------------------------------------------------------------------------------------"); System.out.println("[리뷰 상세보기]"); int no = Prompt.inputInt("번호? "); Review review = findByNo(no); if (review == null) { System.out.println("해당 번호의 리뷰가 없습니다."); return; } review.viewCount++; System.out.println("-----------------------------------------------------------"); System.out.printf("[%s]\n", review.title); System.out.println("-----------------------------------------------------------"); System.out.printf("%s\n", review.content); System.out.println("-----------------------------------------------------------"); System.out.printf("작성자: %s ㅣ 작성일: %s ㅣ 조회수 : %d ㅣ 모험상태 : %s \n", review.writer, review.registeredDate, review.viewCount, getStars(review.stars)); } public void update() { System.out.println("---------------------------------------------------------------------------------------------------------"); System.out.println("[리뷰 변경]"); int no = Prompt.inputInt("번호? "); Review review = findByNo(no); if (review == null) { System.out.println("해당 번호의 리뷰가 없습니다."); return; } String title = Prompt.inputString(String.format("제목(%s) > ", review.title)); String content = Prompt.inputString(String.format("내용(%s) > ", review.content)); int stars = Prompt.inputInt(String.format( "상태(%s) > \n0: 모험중\n1: 모험실패\n2: 모험완료\n> ", getStars(review.stars))); String writer = inputUser(String.format("작성자: %s > (작성취소 = [] 공백) ", review.writer)); if(writer == null) { System.out.println("작업 변경을 취소합니다."); return; } String input = Prompt.inputString("정말 변경하시겠습니까?(y/N) "); if (input.equalsIgnoreCase("Y")) { review.title = title; review.content = content; System.out.println("리뷰를 변경하였습니다."); } else { System.out.println("리뷰 변경을 취소하였습니다."); } } public void delete() { System.out.println("---------------------------------------------------------------------------------------------------------"); System.out.println("[리뷰 삭제]"); int no = Prompt.inputInt("번호? "); Review review = findByNo(no); if (review == null) { System.out.println("해당 번호의 리뷰가 없습니다."); return; } String input = Prompt.inputString("정말 삭제하시겠습니까?(y/N) "); if (input.equalsIgnoreCase("Y")) { Node cursor = first; while (cursor != null) { if (cursor.review == review) { if (first == last) { first = last = null; break; } if (cursor == first) { first = cursor.next; cursor.prev = null; } else { cursor.prev.next = cursor.next; if (cursor.next != null) { cursor.next.prev = cursor.prev; } } if (cursor == last) { last = cursor.prev; } this.size--; break; } cursor = cursor.next; } System.out.println("리뷰를 삭제하였습니다."); } else { System.out.println("리뷰 삭제를 취소하였습니다."); } } Review findByNo(int reviewNo) { Node cursor = first; while (cursor != null) { Review r = cursor.review; if (r.no == reviewNo) { return r; } cursor = cursor.next; } return null; } String getStars(int stars) { switch (stars) { case 1: return "모험중"; case 2: return "모험실패"; default: return "모험완료"; } } static class Node { Review review; Node next; Node prev; Node(Review b) { this.review = b; } } String inputUser(String promptTitle) { while (true) { String name = Prompt.inputString(promptTitle); if (name.length() == 0) { return null; } else if (this.userList.exist(name)) { return name; } else { System.out.println("등록된 회원이 아닙니다."); } } } }
/******************************************************************************* * Copyright 2019 See AUTHORS file * * 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.mini2Dx.ui.navigation; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.lib.legacy.ClassImposteriser; import org.junit.Before; import org.junit.Test; import org.mini2Dx.ui.element.Actionable; import org.mini2Dx.ui.layout.ScreenSize; import com.badlogic.gdx.Input.Keys; import junit.framework.Assert; /** * Unit tests for {@link GridUiNavigation} */ public class GridUiNavigationTest { private final int COLUMNS = 3; private final int ROWS = 3; private final Mockery mockery = new Mockery(); private final GridUiNavigation navigation = new GridUiNavigation(COLUMNS); private final Actionable [][] elements = new Actionable[COLUMNS][ROWS]; @Before public void setUp() { mockery.setImposteriser(ClassImposteriser.INSTANCE); for(int x = 0; x < COLUMNS; x++) { for(int y = 0; y < ROWS; y++) { elements[x][y] = mockery.mock(Actionable.class, "actionable-" + x + "," + y); final Actionable actionable = elements[x][y]; mockery.checking(new Expectations() { { atLeast(1).of(actionable).addHoverListener(navigation); allowing(actionable).invokeEndHover(); } }); } } } @Test public void testSetXY() { addElementsToGrid(); for(int x = 0; x < COLUMNS; x++) { for(int y = 0; y < ROWS; y++) { Assert.assertEquals(elements[x][y], navigation.get(x, y)); } } } @Test public void testNavigate() { addElementsToGrid(); Actionable lastActionable = null; for(int x = 0; x <= COLUMNS; x++) { lastActionable = navigation.navigate(Keys.RIGHT); } Assert.assertEquals(elements[2][0], lastActionable); for(int y = 0; y <= ROWS; y++) { lastActionable = navigation.navigate(Keys.DOWN); } Assert.assertEquals(elements[2][2], lastActionable); for(int x = 0; x <= COLUMNS; x++) { lastActionable = navigation.navigate(Keys.LEFT); } Assert.assertEquals(elements[0][2], lastActionable); for(int y = 0; y <= ROWS; y++) { lastActionable = navigation.navigate(Keys.UP); } Assert.assertEquals(elements[0][0], lastActionable); } @Test public void testCursorReset() { addElementsToGrid(); Actionable lastActionable = null; for(int x = 0; x <= COLUMNS; x++) { lastActionable = navigation.navigate(Keys.RIGHT); } Assert.assertEquals(elements[2][0], lastActionable); navigation.layout(ScreenSize.XS); Assert.assertEquals(elements[2][0], navigation.getCursor()); } private void addElementsToGrid() { for(int x = 0; x < COLUMNS; x++) { for(int y = 0; y < ROWS; y++) { navigation.set(x, y, elements[x][y]); } } } }
package com.illknow.resource; import com.illknow.model.read.Exercise; import com.illknow.model.read.MediaType; import com.illknow.model.read.QuestionBuilder; import com.illknow.service.ExerciceService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import javax.ws.rs.*; import java.util.Map; @Controller @Path(AbstractResource.EXERCISES_URL) public class ExerciseResource extends AbstractResource { private static final String ID = "id"; private static final String NAME = "name"; private static final String MEDIA = "media"; @Autowired private ExerciceService exerciceService; /** * Get an exercise given its id. * @param exerciseId * @return */ @GET @Path(AbstractResource.ID_PATH) public Exercise getExercise(@PathParam(ID) Long exerciseId) { return exerciceService.find(exerciseId); } /** * Delete an exercise * @param exerciseId * @return */ @DELETE @Path(AbstractResource.ID_PATH) public Long deleteExercise(@PathParam(ID) Long exerciseId) { return exerciceService.delete(exerciseId); } /** * List all the exercises for an user. * @return */ @GET public Map<String, String> listExercices() { return exerciceService.list(); } /** * Create an Exercise with a name and a mediaType * @param name * @param media * @return */ @POST public Long createExercise(@FormParam(NAME) String name,@FormParam(MEDIA) MediaType media) { return exerciceService.create(new QuestionBuilder().withText(name).withMedia(media).setUrl(null).createQuestion()); } /** * Update all infos of an exercise * @param exerciseId * @param name * @param media * @return */ @PUT @Path(AbstractResource.ID_PATH) public Long updateExercise(@PathParam(ID) Long exerciseId,@FormParam(NAME) String name,@FormParam(MEDIA) MediaType media) { return exerciceService.update(exerciseId, new QuestionBuilder().withText(name).withMedia(media).setUrl(null).createQuestion()); } }
package com.funnums.funnums.classes; /** * Created by Rabia on 10/02/2019. */ import android.util.Log; import java.util.Random; import java.util.HashMap; import java.lang.Math; public class BubbleNumberGenerator { public static final String TAG = "BubbleNumberGenerator"; private final int MAX_UNCHECKED_NUM = 2; //max value that can be generated without checking private final int MAX_VALUE_REPETITIONS = 0; //max repeats of a given number on the screen private final int MAX_GENERATION_ATTEMPTS = 5; //max number of number generation attempts /* The hashtable containing a pair where the key is the number * the value is the count of it on the screen */ private HashMap<Integer, Integer> CurrentValues = new HashMap<>(); private Random r = new Random(); private int absTarget; //the initial absolute difference between Current and Target /* We generate a number from 1 to the (current absolute target - 1) If the number is not 1 or 2, we check if it's in the hastable, and if it is, then we generate a another number - we do this to maintain variety in the numbers generated, but we don't check for 1 or 2 because those are the smallest prime numbers which are useful for reaching the target. */ public int nextNum() { int maxNum = absTarget - 1; int newNum = r.nextInt(maxNum + 1); //to inclusively generate maxNum, we add 1 while (newNum > MAX_UNCHECKED_NUM && CurrentValues.get(newNum) != null && CurrentValues.get(newNum) > MAX_VALUE_REPETITIONS) { newNum = r.nextInt(maxNum + 1); } return Math.max(newNum, 1); } // Increments the count of the value in the CurrentNumbers on the screen hashtable. public void increment(int value) { if (!CurrentValues.containsKey(value)) { CurrentValues.put(value, 0); } int oldCount = CurrentValues.get(value); CurrentValues.put(value, oldCount + 1); } // Decremenets the count of the value in the CurrentNumbers on the screen hashtable public void decrement(int value) { int oldCount = CurrentValues.get(value); CurrentValues.put(value, oldCount - 1); } // Sets the absolute target of current - target to main how we generate numbers. public void setAbsoluteTarget(int target, int previousTarget) { absTarget = target - previousTarget; } }
import java.util.ArrayList; import java.util.Scanner; public class LamportLogical { ArrayList<Integer> processes=new ArrayList<Integer>(); int n; Scanner sc=new Scanner(System.in); public void input() { System.out.println("Enter the number of processes "); n=sc.nextInt(); for(int i=0;i<n;i++) { processes.add(0); } } public void printClocks() { for(int i=0;i<n;i++) { System.out.print("Process "+(i+1)+" :- "+processes.get(i)); System.out.println(); } } public void evaluate() { String choice; do { System.out.println("Enter the dependency. E.g.1 1 OR 1 2"); int send=sc.nextInt(); int rec=sc.nextInt(); if(send==rec) { processes.set(send-1,processes.get(send-1)+1); } else if(processes.get(send-1)>processes.get(rec-1)) { processes.set(rec-1, processes.get(send-1)+1); } printClocks(); System.out.println("Enter y to add more events "); choice=sc.next(); }while(choice.equalsIgnoreCase("y")); } public static void main(String[]args) { LamportLogical ll=new LamportLogical(); ll.input(); ll.evaluate(); } }
/* * Created by Angel Leon (@gubatron), Alden Torres (aldenml) * Copyright (c) 2011-2014, FrostWire(R). All rights reserved. * 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 com.frostwire.search; /** * Private class, only public to be able to share with other * search packages. * * @author gubatron * @author aldenml * */ public class MaxIterCharSequence implements CharSequence { private final CharSequence inner; private int counter; public MaxIterCharSequence(CharSequence inner, int counter) { this.inner = inner; this.counter = counter; } @Override public char charAt(int index) { if (counter < 0) { throw new RuntimeException("Iteration over the string exhausted"); } counter--; return inner.charAt(index); } @Override public int length() { return inner.length(); } @Override public CharSequence subSequence(int start, int end) { return new MaxIterCharSequence(inner.subSequence(start, end), counter); } @Override public String toString() { return inner.toString(); } }
package com.harlan.lhc.uitlsclass.utils; /** * 线程睡眠 * Created by a1 on 2017/10/13. */ public class CSleep { public static final long DEFAULT_SLEEP_TIME = 500; private boolean isRuning = false; public boolean isRuning() { return isRuning; } public void runWithTime(final long defaultSleepTime) { isRuning = true; new Thread() { @Override public void run() { try { sleep(defaultSleepTime, 0); } catch (InterruptedException e) { e.printStackTrace(); } isRuning = false; super.run(); } }.start(); } }
/** * */ package edu.mycourses.adt.client; import edu.mycourses.adt.basic.ArrayQueue; import edu.mycourses.adt.basic.ArrayStack; import edu.mycourses.adt.basic.LinkedList; import edu.mycourses.adt.basic.LinkedListStack; import edu.mycourses.adt.basic.Queue; import edu.mycourses.adt.basic.Stack; /** * @author Ibrahima Diarra * */ public class ADTClient { /** * * @param input * @return */ public static boolean checkParentheses(final String input) { final Stack<Character> stack = new ArrayStack<Character>(); final char[] tokens = input.toCharArray(); for (Character token : tokens) { if (token == ')' && (stack.isEmpty() || stack.pop() != '(')) return false; stack.push(token); } return true; } /** * * @param N * @return */ public static String positiveIntBinary(int N) { if (N < 1) return ""; final LinkedListStack<Integer> stack = new LinkedListStack<Integer>(); while (N > 0) { stack.push(N % 2); N = N / 2; } StringBuilder bd = new StringBuilder(); for (Integer i : stack) { bd.append(i); } return bd.toString(); } /** * * @param input * @return */ public static String balanceRightParenthesis(final String input) { LinkedListStack<Character> s1 = new LinkedListStack<Character>(); LinkedListStack<Character> s2 = new LinkedListStack<Character>(); final char[] data = input.toCharArray(); int newItem = 0; for (Character d : data) { if(d == ' ') continue; if(d == ')'){ s2.push(d); addLeftParenthesis(s1,s2,newItem); newItem = 0; }else{ s1.push(d); newItem++; } } return formatExpression(s1); } private static void addLeftParenthesis(LinkedListStack<Character> s1, LinkedListStack<Character> s2, int pushCount){ Character c = null; int count = 0; int threshold = pushCount > 2 ? 3 : 4; while(!s1.isEmpty()){ c = s1.pop(); s2.push(c); if(c == '(' || c == ')') count--; else count++; if(count == threshold) break; } s1.push('('); while(!s2.isEmpty()){ s1.push(s2.pop()); } } private static String formatExpression(final LinkedListStack<Character> stack){ final LinkedListStack<Character> t = new LinkedListStack<Character>(); for (Character e : stack) t.push(e); final StringBuilder bd = new StringBuilder(); for(Character e : t) bd.append(e).append(" "); return bd.toString(); } public static String infixToPostfix(final String input){ final LinkedListStack<Character> op = new LinkedListStack<Character>(); final Queue<Character> exp = new ArrayQueue<Character>(); final char[] data = input.toCharArray(); for(Character c : data){ if(c == ' ') continue; if(c == '+' || c == '-' || c == '/' || c == '*') op.push(c); else if(c == ')'){ exp.enqueue(op.pop()); }else if (c != '('){ exp.enqueue(c); } } final StringBuilder bd = new StringBuilder(); for(Character e : exp) bd.append(e); return bd.toString(); } public static int evaluatePostfix(final String input){ final char[] data = input.toCharArray(); final LinkedListStack<Integer> s = new LinkedListStack<Integer>(); for(Character c : data){ if(c == ' ') continue; if(c == '*') s.push(s.pop() * s.pop()); else if(c == '/') s.push(s.pop() / s.pop()); else if(c == '+') s.push(s.pop() + s.pop()); else if(c == '-') s.push(s.pop() - s.pop()); else s.push(Integer.valueOf(c.toString())); } return s.pop(); } public static <T> LinkedListStack<T> copy(final LinkedListStack<T> stack){ final LinkedListStack<T> s1 = new LinkedListStack<T>(); final LinkedListStack<T> s2 = new LinkedListStack<T>(); for(T item : stack) s1.push(item); for(T item : s1) s2.push(item); return s2; } public static <T> boolean find(final LinkedList<T> list, T item) { for (T e : list) { if (e.equals(item)) return true; } return false; } public static <T> int remove(final LinkedList<T> list, T item) { T previous = null; T current = null; int count = 0; for (T i : list) { if (current != null) previous = current; current = i; if (current.equals(item)) { list.removeAfter(previous); count++; } } return count; } }
package com.dian.diabetes.activity.indicator; import java.security.SecureRandom; import java.text.DecimalFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.UUID; import jiuan.androidnin1.bluetooth.BP.BluetoothComm; import jiuan.androidnin1.bluetooth.BP.BluetoothControlForBP; import jiuan.androidnin1.bluetooth.BPObserver.JiuanBPObserver; import android.annotation.SuppressLint; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Context; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.FragmentManager; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.dian.diabetes.R; import com.dian.diabetes.activity.BasicActivity; import com.dian.diabetes.db.IndicateBo; import com.dian.diabetes.db.dao.IndicateValue; import com.dian.diabetes.dialog.DayDialog; import com.dian.diabetes.dialog.TimeDialog; import com.dian.diabetes.tool.CallBack; import com.dian.diabetes.tool.Config; import com.dian.diabetes.tool.Preference; import com.dian.diabetes.tool.ToastTool; import com.dian.diabetes.utils.CheckUtil; import com.dian.diabetes.utils.ContantsUtil; import com.dian.diabetes.utils.DateUtil; import com.dian.diabetes.utils.StringUtil; import com.dian.diabetes.widget.anotation.ViewInject; /** * 手工录入高血压,低血压,心率等值 * * @author longbh * */ public class PressImpFragment extends BasicActivity implements OnClickListener, JiuanBPObserver { @ViewInject(id = R.id.delete) private ImageButton deleteBtn; @ViewInject(id = R.id.save_btn) private ImageButton saveBtn; @ViewInject(id = R.id.back_btn) private Button backBtn; @ViewInject(id = R.id.day) private LinearLayout day; @ViewInject(id = R.id.add_entry_day) private TextView dayView; @ViewInject(id = R.id.close_value) private EditText closeView; // 高血压 @ViewInject(id = R.id.open_value) private EditText openView; // 低血压 @ViewInject(id = R.id.heart) private EditText heartView; @ViewInject(id = R.id.high_con) private RelativeLayout highCon; @ViewInject(id = R.id.low_con) private RelativeLayout lowCon; @ViewInject(id = R.id.heart_con) private RelativeLayout heartCon; @ViewInject(id = R.id.add_entry_time) private TextView timeView; @ViewInject(id = R.id.sycn_equip_button) private LinearLayout equipBtn; @ViewInject(id = R.id.start_mesure) private Button startMesure; @ViewInject(id = R.id.mesure_line) private ImageView mesurLine; private PressImpFragment activity; private DayDialog dayDialog; private TimeDialog timeDialog; private CallBack callBack; private InputMethodManager imm; private BluetoothAdapter mAdapter; private DecimalFormat format; private IndicateValue openValue; private IndicateValue heartValue; private boolean isAdd = true; private Date selectDate; private IndicateBo bo; private long indicateId; private String key; private String group; private BluetoothControlForBP bpControl; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_press_impl); activity = (PressImpFragment) context; Bundle bundle = getIntent().getExtras(); isAdd = bundle.getBoolean("isAdd"); key = bundle.getString("key"); indicateId = bundle.getLong("indicateId"); format = new DecimalFormat("00"); bo = new IndicateBo(activity); if (!isAdd) { group = bundle.getString("group"); setIndicateValue(group); } selectDate = new Date(); imm = (InputMethodManager) context .getSystemService(Context.INPUT_METHOD_SERVICE); mAdapter = BluetoothAdapter.getDefaultAdapter(); initActivity(); } private void initActivity() { day.setOnClickListener(this); deleteBtn.setOnClickListener(this); saveBtn.setOnClickListener(this); backBtn.setOnClickListener(this); highCon.setOnClickListener(this); lowCon.setOnClickListener(this); heartCon.setOnClickListener(this); equipBtn.setOnClickListener(this); timeView.setOnClickListener(this); startMesure.setOnClickListener(this); if (isAdd) { deleteBtn.setVisibility(View.GONE); } else { setIndicateView(); } dayView.setText(DateUtil.parseToString(selectDate, DateUtil.yyyymmdd)); timeView.setText(DateUtil.parseToString(selectDate, DateUtil.HHmm)); } private void setIndicateView() { openView.setText(openValue.getValue1() + ""); openView.setSelection(openView.getText().length()); closeView.setText(openValue.getValue() + ""); closeView.setSelection(closeView.getText().length()); if (heartValue != null) { heartView.setText(heartValue.getValue() + ""); heartView.setSelection(heartView.getText().length()); } selectDate.setTime(openValue.getCreate_time()); dayView.setText(DateUtil.parseToString(selectDate, DateUtil.yyyymmdd)); timeView.setText(DateUtil.parseToString(selectDate, DateUtil.HHmm)); } public void setIndicateValue(String group) { Map<String, IndicateValue> datas = bo.keyMapIndicate(group); this.openValue = datas.get("openPress"); this.heartValue = datas.get("heart"); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.day: openDayDialog(); break; case R.id.back_btn: finish(); break; case R.id.delete: delete(); ContantsUtil.SELF_DETAIL = false; break; case R.id.save_btn: if (CheckUtil.isNull(openView.getText())) { Toast.makeText(activity, "舒张压不能为空", Toast.LENGTH_SHORT).show(); return; } if (CheckUtil.isNull(closeView.getText())) { Toast.makeText(activity, "收缩压不能为空", Toast.LENGTH_SHORT).show(); return; } if (!isAdd) { if (CheckUtil.isNull(heartView.getText())) { Toast.makeText(activity, "心率不能为空", Toast.LENGTH_SHORT) .show(); return; } } saveValue(); ContantsUtil.SELF_DETAIL = false; finish(); break; case R.id.high_con: closeView.requestFocus(); imm.showSoftInput(closeView, InputMethodManager.SHOW_FORCED); closeView.setSelection(closeView.getText().length()); break; case R.id.low_con: openView.requestFocus(); openView.setSelection(openView.getText().length()); imm.showSoftInput(openView, InputMethodManager.SHOW_FORCED); break; case R.id.heart_con: heartView.requestFocus(); heartView.setSelection(heartView.getText().length()); imm.showSoftInput(heartView, InputMethodManager.SHOW_FORCED); break; case R.id.sycn_equip_button: startMeansure(); break; case R.id.add_entry_time: openTimeDialog(); break; case R.id.start_mesure: startMeansure(); break; } } private void saveValue() { float open = StringUtil.toFloat(openView.getText()); float close = StringUtil.toFloat(closeView.getText()); if (isAdd) { // 舒张压 String group = UUID.randomUUID().toString(); bo.savePress("openPress", "press", group, close, open, indicateId, ContantsUtil.DEFAULT_TEMP_UID, Config.getIndicateLevel( close, "lowClosePress", "highClosePress"), Config .getIndicateLevel(open, "lowOpenPress", "highOpenPress"), selectDate.getTime()); // 心率 if (!CheckUtil.isNull(heartView.getText())) { float heat = StringUtil.toFloat(heartView.getText()); bo.saveValue("heart", "press", group, heat, indicateId, ContantsUtil.DEFAULT_TEMP_UID, Config.getIndicateLevel(heat, "lowHeart", "highHeart"), selectDate.getTime()); } } else { bo.updatePress(close, open, openValue, indicateId, Config.getIndicateLevel(close, "lowClosePress", "highClosePress"), Config.getIndicateLevel(open, "lowOpenPress", "highOpenPress"), selectDate .getTime()); // 心率 if (heartValue == null && !CheckUtil.isNull(heartView.getText())) { float heat = StringUtil.toFloat(heartView.getText()); bo.saveValue("heart", "press", group, heat, indicateId, ContantsUtil.DEFAULT_TEMP_UID, Config.getIndicateLevel(heat, "lowHeart", "highHeart"), selectDate.getTime()); } else if (heartValue != null && !CheckUtil.isNull(heartView.getText())) { float heat = StringUtil.toFloat(heartView.getText()); bo.updateValue(heat, heartValue, indicateId, Config.getIndicateLevel(heat, "lowHeart", "highHeart"), selectDate.getTime()); } } Preference.instance(activity).putBoolean(Preference.HAS_UPDATE, true); } private void delete() { bo.deleteByGroup(openValue.getMarkNo(), indicateId, ContantsUtil.DEFAULT_TEMP_UID); if (callBack != null) { callBack.callBack(); } finish(); } public String getRandom(int length) { SecureRandom random = new SecureRandom(); byte bytes[] = new byte[length]; random.nextBytes(bytes); return new String(bytes); } private void openDayDialog() { if (dayDialog == null) { dayDialog = new DayDialog(activity, "日期选择"); dayDialog.setCallBack(new DayDialog.CallBack() { @Override public boolean callBack(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.setTime(selectDate); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month - 1); calendar.set(Calendar.DATE, day); Date temp = calendar.getTime(); if (temp.compareTo(new Date()) > 0) { Toast.makeText(context, R.string.toast_time_after, Toast.LENGTH_SHORT).show(); return false; } selectDate = calendar.getTime(); dayView.setText(year + "-" + format.format(month) + "-" + format.format(day)); return true; } }); } dayDialog.show(); } private void openTimeDialog() { if (timeDialog == null) { timeDialog = new TimeDialog(activity, "时间选择"); timeDialog.setCallBack(new TimeDialog.CallBack() { @Override public boolean callBack(int hour, int mini) { Date temp = new Date(selectDate.getTime()); temp.setHours(hour); temp.setMinutes(mini); if (temp.compareTo(new Date()) > 0) { Toast.makeText(context, R.string.toast_time_after, Toast.LENGTH_SHORT).show(); return false; } selectDate.setHours(hour); selectDate.setMinutes(mini); timeView.setText(format.format(hour) + ":" + format.format(mini)); return true; } }); } timeDialog.show(); } public void setCallback(CallBack callBack) { this.callBack = callBack; } private void openEquipList() { String tag = "equip_list_dialog"; FragmentManager manager = context.getSupportFragmentManager(); EquipListDialog tempFragment = (EquipListDialog) context .getSupportFragmentManager().findFragmentByTag(tag); if (tempFragment == null) { tempFragment = EquipListDialog.getInstance(); tempFragment.setCallBack(new EquipListDialog.CallBack() { @Override public void callBack(BluetoothControlForBP tempControll) { bpControl = tempControll; bpControl.controlSubject.attach(activity); mesurLine.setImageResource(R.drawable.heart_animation); AnimationDrawable drawable = (AnimationDrawable) mesurLine .getDrawable(); drawable.start(); startMesure.setVisibility(View.GONE); startMeansure(); } }); } if (!tempFragment.isAdded()) { tempFragment.show(manager, tag); } } private void startMeansure() { if (bpControl == null) { openEquipList(); } else { bpControl.start(activity, ContantsUtil.clientID, ContantsUtil.clientSecret); } } private void stopMeansure() { mesurLine.clearAnimation(); startMesure.setVisibility(View.VISIBLE); } @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: Bundle bundle = (Bundle) msg.obj; int[] result = bundle.getIntArray("bp"); closeView.setText((result[0] + result[1]) + ""); closeView.setEnabled(false); openView.setText(result[1] + ""); openView.setEnabled(false); heartView.setText(result[2] + ""); heartView.setEnabled(false); highCon.setEnabled(false); lowCon.setEnabled(false); heartCon.setEnabled(false); break; case 2: Bundle bundle2 = (Bundle) msg.obj; int state = bundle2.getInt("num"); ToastTool.toastPress(state); stopMeansure(); break; case 3: ToastTool.toastPress(-1); stopMeansure(); break; default: break; } } }; @Override public void msgAngle(int arg0) { } @Override public void msgBattery(int arg0) { } @Override public void msgError(int num) { try { Message message = new Message(); message.what = 2; Bundle bundle = new Bundle(); bundle.putInt("error", num); message.obj = bundle; handler.sendMessage(message); } catch (Exception e) { // TODO: handle exception } } @Override public void msgInden() { } @Override public void msgMeasure(int arg0, int[] arg1, boolean arg2) { } @Override public void msgPowerOff() { handler.sendEmptyMessage(3); } @Override public void msgPressure(int arg0) { } @Override public void msgResult(int[] result) { Message message = new Message(); message.what = 1; Bundle bundle = new Bundle(); bundle.putIntArray("bp", result); message.obj = bundle; handler.sendMessage(message); } @Override public void msgUserStatus(int arg0) { } @Override public void msgZeroIng() { } @Override public void msgZeroOver() { } @Override protected void onDestroy() { super.onDestroy(); if (mAdapter.isEnabled()) { mAdapter.disable(); } Set<HashMap.Entry<BluetoothDevice, BluetoothControlForBP>> set = BluetoothComm.mapBPDeviceConnected .entrySet(); for (Iterator<Map.Entry<BluetoothDevice, BluetoothControlForBP>> it = set .iterator(); it.hasNext();) { Map.Entry<BluetoothDevice, BluetoothControlForBP> entry = (Map.Entry<BluetoothDevice, BluetoothControlForBP>) it .next(); entry.getValue().stop(); } } }
package com.diplom.repository; import com.diplom.domain.Column; import com.diplom.domain.KYF; import com.diplom.domain.Row; import com.diplom.domain.Table; import java.util.ArrayList; import java.util.List; /** * Created by Igor on 03.12.2016. */ //@Repository public class TableRepositoryMock { public void persist(Table table) { return; } public Table getTable(String tableId) { return constructTable(); } private Table constructTable() { Table table = new Table("myTable"); ArrayList<Row> rows = generateRowsForTable(table); ArrayList<Column> columns = generateColumnsForTable(table); List<List<KYF>> kyfs = generateKyfAndBindWithRowsColumnsTable(rows, columns, table); table.setRows(rows); table.setColumns(columns); table.setKyfMatrix(kyfs); return table; } private List<List<KYF>> generateKyfAndBindWithRowsColumnsTable(ArrayList<Row> rows, ArrayList<Column> columns, Table table) { List<List<KYF>> result = new ArrayList<>(); for (Row row : rows) { List<KYF> kyfRow = new ArrayList<>(); for (Column column : columns) { KYF kyf = new KYF(row.getRowNo(), column.getColumnNo(), row.getRowNo() + " " + column.getColumnNo()); kyf.setRow(row); kyf.setColumn(column); // kyf.setTable(table); kyfRow.add(kyf); } result.add(kyfRow); } return result; } private ArrayList<Column> generateColumnsForTable(Table table) { return new ArrayList<Column>() {{ add(new Column("col1", 1)); add(new Column("col2", 2)); }}; } private ArrayList<Row> generateRowsForTable(Table table) { return new ArrayList<Row>() {{ add(new Row( "row1", 1)); add(new Row( "row2", 2)); }}; } ; }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; abstract class community{ char com[]; } public class on_comm_connect extends community { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private char c,i,j; public on_comm_connect() throws IOException { // TODO Auto-generated constructor stub c=(char)br.read(); i=(char)br.read(); e=(char)br.read(); } public static void main(String[] args) { // whenever anew community comes this class is joined } }
package br.com.margel.softvinhows; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class Db { public static String POSTGRESQL_UNIT = "postgresql"; public static String H2_UNIT = "h2_memoria"; public static String PERSISTENCE_UNIT = POSTGRESQL_UNIT; private static EntityManagerFactory factory; private static ThreadLocal<EntityManager> tr = new ThreadLocal<>(); public static void createFactory(){ factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT); System.out.println("Factory criado para a unidade de persistência: "+PERSISTENCE_UNIT); } public static void closeFactory(){ if(factory != null){ rollback(); closeEm(); factory.close(); System.out.println("Factory fechado!"); } } /** * Retorna a sessão do EntityManager para esta conexão * @return EntityManager */ public static synchronized EntityManager em(){ if(tr.get()==null){ tr.set(factory.createEntityManager()); System.out.println("EntityManager criado!"); begin(); } return tr.get(); } private static void begin() { if(tr.get().getTransaction()!=null && !tr.get().getTransaction().isActive()){ tr.get().getTransaction().begin();; System.out.println("Transação iniciada!"); }else{ System.out.println("Nenhuma transação para iniciar!"); } } public static void commit() { if(tr.get()!=null && tr.get().getTransaction()!=null && tr.get().getTransaction().isActive()){ tr.get().getTransaction().commit(); System.out.println("Commit na Transação!"); }else{ System.out.println("Nenhuma transação para commit!"); } } public static void rollback() { if(tr.get()!=null && tr.get().getTransaction()!=null && tr.get().getTransaction().isActive()){ tr.get().getTransaction().rollback(); System.out.println("Rollback na Transação!"); }else{ System.out.println("Nenhuma transação para rollback!"); } } public static void closeEm() { if(tr.get()!=null){ if(tr.get().isOpen()){ tr.get().close(); System.out.println("EntityManager fechado!"); } tr.remove(); System.out.println("Thread Local removida!"); }else{ System.out.println("Nada incluído na Thread Local"); } } }
package net.inveed.rest.jpa.jackson; import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializationConfig; import com.fasterxml.jackson.databind.ser.BeanSerializerModifier; import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase; import com.fasterxml.jackson.databind.ser.std.CollectionSerializer; import com.fasterxml.jackson.databind.type.CollectionType; public class EntityBeanSerializerModifier extends BeanSerializerModifier { @Override public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) { if (serializer instanceof CollectionSerializer) { return new EntityCollectionSerializer((CollectionSerializer) serializer); } else if (serializer instanceof BeanSerializerBase) { return new EntitySerializer((BeanSerializerBase) serializer); } else { return serializer; } } @Override public JsonSerializer<?> modifyCollectionSerializer(SerializationConfig config, CollectionType valueType, BeanDescription beanDesc, JsonSerializer<?> serializer) { if (serializer instanceof CollectionSerializer) { return new EntityCollectionSerializer((CollectionSerializer) serializer); } else { return super.modifyCollectionSerializer(config, valueType, beanDesc, serializer); } } }
/* Name: Haris Kamran ID#: 112786164 Recitation: Monday 11 am */ /** * Class that extends the Exception Class. Thrown when the user inputs a negative GPA. * @author haris * */ public class NegativeGPAException extends Exception { public NegativeGPAException(String s) { super(s); } }
package old.Data20180411; import old.DataType.RandomListNode; public class CopyListWithRandomPointer { public RandomListNode copyRandomList(RandomListNode head) { if(head == null) return null; RandomListNode curNode = head; while(curNode != null){ RandomListNode node = new RandomListNode(curNode.label); node.next = curNode.next; curNode.next = node; curNode = node.next; } curNode = head; while(curNode != null){ if(curNode.random != null) curNode.next.random = curNode.random.next; curNode = curNode.next.next; } RandomListNode curCopyHead = head.next; RandomListNode curCopyNode = head.next; curNode = head; while(curNode != null){ curNode.next = curCopyNode.next; if(curCopyNode.next != null) curCopyNode.next = curCopyNode.next.next; curNode = curNode.next; curCopyNode = curCopyNode.next; } return curCopyHead; } }
package com.rachelgrau.rachel.health4theworldstroke.Models; /** * Created by rachel on 11/19/16. */ public class LearnContent { public String title; }
package com.ipincloud.iotbj.srv.domain; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Time; import java.sql.Date; import java.sql.Timestamp; import com.alibaba.fastjson.annotation.JSONField; //(Accesslog)访问记录 //generate by redcloud,2020-07-24 19:59:20 public class Accesslog implements Serializable { private static final long serialVersionUID = 2L; // 主键id private Long id ; // 访问时间 private String accesstime ; // 设备名称 private String equipment ; // 姓名 private String title ; // 性别 private String gender ; // 部门 private String org ; // 工号 private String cardno ; // 身份证 private String idnumber ; // 手机号 private String mobile ; // 状态 private String state ; // 抓拍图片 private String capturephoto ; // 底库照片 private String basementphoto ; public Long getId() { return id ; } public void setId(Long id) { this.id = id; } public String getAccesstime() { return accesstime ; } public void setAccesstime(String accesstime) { this.accesstime = accesstime; } public String getEquipment() { return equipment ; } public void setEquipment(String equipment) { this.equipment = equipment; } public String getTitle() { return title ; } public void setTitle(String title) { this.title = title; } public String getGender() { return gender ; } public void setGender(String gender) { this.gender = gender; } public String getOrg() { return org ; } public void setOrg(String org) { this.org = org; } public String getCardno() { return cardno ; } public void setCardno(String cardno) { this.cardno = cardno; } public String getIdnumber() { return idnumber ; } public void setIdnumber(String idnumber) { this.idnumber = idnumber; } public String getMobile() { return mobile ; } public void setMobile(String mobile) { this.mobile = mobile; } public String getState() { return state ; } public void setState(String state) { this.state = state; } public String getCapturephoto() { return capturephoto ; } public void setCapturephoto(String capturephoto) { this.capturephoto = capturephoto; } public String getBasementphoto() { return basementphoto ; } public void setBasementphoto(String basementphoto) { this.basementphoto = basementphoto; } }
package com.codecool.tripplanner.roomdatabase.entity; import androidx.annotation.NonNull; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity(tableName = "destinations") public class Destination { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "ID") @NonNull private Long id; @NonNull private String title; @NonNull private double longitude; @NonNull private double latitude; @NonNull private String urlPicture; public Destination(@NonNull String title, double longitude, double latitude, @NonNull String urlPicture) { this.title = title; this.longitude = longitude; this.latitude = latitude; this.urlPicture = urlPicture; } public void setId(@NonNull Long id) { this.id = id; } @NonNull public Long getId() { return id; } public String getTitle() { return title; } public double getLongitude() { return longitude; } public double getLatitude() { return latitude; } public String getUrlPicture() { return urlPicture; } }
package net.server; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import core.server.WelcomeSession; import utils.Log; /** * master side, used by framework to communicate with all players * * @author Harry * */ public class Server { public static final int DEFAULT_PORT = 12345; private static final String TAG = "Server"; private final int mPort; private final ExecutorService executor; private WelcomeSession session; public Server(int port) { session = new WelcomeSession(); mPort = port; executor = Executors.newCachedThreadPool(); } /** * initialize server with DEFAULT_PORT */ public Server() { session = new WelcomeSession(); mPort = DEFAULT_PORT; executor = Executors.newCachedThreadPool(); } /** * Start the server */ public void start() { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(mPort); Log.log(TAG, "waiting for connections..."); while (true) { final Socket socket = serverSocket.accept(); executor.execute(() -> { Log.log(TAG, "receiving new connection..."); try { ServerConnection connection = new ServerConnection(socket); session.onConnectionReceived(connection); } catch (IOException e) { Log.error(TAG, "I/O Exception"); e.printStackTrace(); } }); } } catch (IOException e) { Log.error(TAG, "error creating server socket"); e.printStackTrace(); } catch (RejectedExecutionException e) { e.printStackTrace(); } } public static void main(String[] args) { new Server().start(); } }
package control.main; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class ManualsController { @RequestMapping(value = "/manuals", method = RequestMethod.GET) public String requestManuals(ModelMap model) { return "/static/manuals.html"; } }
package com.bran.chordretriever; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.webkit.WebView; import android.widget.Toast; import java.util.Set; /** * Created by Beni on 8/4/14. */ public class SongChangeReceiver extends BroadcastReceiver { private static final String TAG = "ChordRetriever"; private MainActivity mainActivity; private WebView webview; public SongChangeReceiver(WebView wv, MainActivity ma) { webview = wv; mainActivity = ma; } @Override public void onReceive(Context context, Intent intent) { //webview.loadUrl("about:blank"); String url = getUrlOld(intent); webview.loadUrl(url); } private String getUrlOld(Intent intent) { String action = intent.getAction(); String cmd = intent.getStringExtra("command"); Log.v("tag ", action + " / " + cmd); String artist = intent.getStringExtra("artist"); String album = intent.getStringExtra("album"); String track = intent.getStringExtra("track"); String url = "https://www.google.com/search?q=" + track.replaceAll(" ", "+") + "+" + artist.replaceAll(" ", "+") + "+chords"; Log.v("tag", artist + ":" + album + ":" + track); Toast.makeText(mainActivity, track, Toast.LENGTH_SHORT).show(); Log.v("tag", "URL: " + url); return url; } private String getExtrasString(Intent pIntent) { String extrasString = ""; Bundle extras = pIntent.getExtras(); try { if (extras != null) { Set<String> keySet = extras.keySet(); for (String key : keySet) { try { String extraValue = pIntent.getExtras().get(key).toString(); extrasString += key + ": " + extraValue + "\n"; } catch (Exception e) { Log.d(TAG, "Exception 2 in getExtrasString(): " + e.toString()); extrasString += key + ": Exception:" + e.getMessage() + "\n"; } } } } catch (Exception e) { Log.d(TAG, "Exception in getExtrasString(): " + e.toString()); extrasString += "Exception:" + e.getMessage() + "\n"; } Log.d(TAG, "extras=" + extrasString); return extrasString; } }
package com.bakerbeach.market.newsletter.api.service; import java.util.Date; import org.springframework.data.mongodb.core.MongoTemplate; import com.bakerbeach.market.newsletter.api.model.NewsletterSubscription; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.QueryBuilder; import com.mongodb.WriteResult; public class SimpleNewsletterSubscriptionServiceDao { private static final String SUBSCRIPTION_COLLECTION_NAME = "newsletter_sbscriptions"; private MongoTemplate mongoTemplate; public boolean __update(NewsletterSubscription subscription) { QueryBuilder q = new QueryBuilder(); q.and("email").is(subscription.getEmail()).and("newsletter_code").is(subscription.getNewsletterCode()); DBObject u = encodeNewsletterSubscription(subscription); DBCollection collection = mongoTemplate.getCollection(SUBSCRIPTION_COLLECTION_NAME); WriteResult result = collection.update(q.get(), u, true, false); return result.isUpdateOfExisting(); } public boolean update(NewsletterSubscription subscription) { QueryBuilder q = new QueryBuilder(); q.and("email").is(subscription.getEmail()).and("newsletter_code").is(subscription.getNewsletterCode()); Date date = new Date(); BasicDBObject o = new BasicDBObject(); o.append("status", subscription.getStatus()); o.append("last_update", subscription.getLastUpdate()); if (subscription.getFirstName() != null && !subscription.getFirstName().isEmpty()) { o.append("first_name", subscription.getFirstName()); } if (subscription.getLastName() != null && !subscription.getLastName().isEmpty()) { o.append("last_name", subscription.getLastName()); } BasicDBObject u = new BasicDBObject("$set", o); u.append("$setOnInsert", new BasicDBObject("email", subscription.getEmail()).append("newsletter_code", subscription.getNewsletterCode())); u.append("$push", new BasicDBObject("booking", new BasicDBObject("status", subscription.getStatus()).append("date", date))); DBCollection collection = mongoTemplate.getCollection(SUBSCRIPTION_COLLECTION_NAME); WriteResult result = collection.update(q.get(), u, true, false); return result.isUpdateOfExisting(); } public NewsletterSubscription findByEmail(String email) { QueryBuilder q = new QueryBuilder(); q.and("email").is(email); DBCollection collection = mongoTemplate.getCollection(SUBSCRIPTION_COLLECTION_NAME); DBObject dbo = collection.findOne(q.get()); if (dbo != null) { return decodeNewsletterSubscription(dbo); } else { return null; } } private NewsletterSubscription decodeNewsletterSubscription(DBObject dbo) { NewsletterSubscription subscription = new NewsletterSubscription(); if (dbo.containsField("prefix")) { subscription.setPrefix((String) dbo.get("prefix")); } if (dbo.containsField("first_name")) { subscription.setFirstName((String) dbo.get("first_name")); } if (dbo.containsField("last_name")) { subscription.setLastName((String) dbo.get("last_name")); } subscription.setNewsletterCode((String) dbo.get("newsletter_code")); subscription.setEmail((String) dbo.get("email")); subscription.setLastUpdate((Date) dbo.get("last_update")); subscription.setStatus((String) dbo.get("status")); return subscription; } private DBObject encodeNewsletterSubscription(NewsletterSubscription subscription) { DBObject dbo = new BasicDBObject(); if (subscription.getPrefix() != null) { dbo.put("prefix", subscription.getPrefix()); } if (subscription.getFirstName() != null) { dbo.put("first_name", subscription.getFirstName()); } if (subscription.getLastName() != null) { dbo.put("last_name", subscription.getLastName()); } dbo.put("newsletter_code", subscription.getNewsletterCode()); dbo.put("email", subscription.getEmail()); dbo.put("last_update", subscription.getLastUpdate()); dbo.put("status", subscription.getStatus()); return dbo; } public void setMongoTemplate(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } }
package cn.novelweb.tool.cron.pojo; import com.fasterxml.jackson.annotation.JsonInclude; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * <p>执行定时任务时的各项参数</p> * <p>2020-03-27 11:07</p> * * @author Dai Yuanchuan **/ @NoArgsConstructor @AllArgsConstructor @Data @ApiModel(value = "执行任务参数") @JsonInclude(JsonInclude.Include.NON_NULL) public class TaskParam { /** * 如:cn.novelweb.tool.cron.pojo.TaskParam */ @ApiModelProperty(value = "需要执行定时任务的类路径[包含类名]") private String classPath; @ApiModelProperty(value = "需要执行定时任务的方法名称") private String methodName; @ApiModelProperty(value = "需要执行任务的方法的中的参数,没有为空") private Object[] param; @ApiModelProperty(value = "cron表达式") private String cron; public void setParam(Object... param) { this.param = param; } }
package com.freddy.sample.mpesa.ViewHolder; import android.support.annotation.NonNull; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.freddy.sample.mpesa.Interface.ItemClickListener; import com.freddy.sample.mpesa.R; public class PaymentsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public TextView paymentName, paymentPhoneNumber,paymentTotalAmount,paymentDateTime; public CardView cardView; public ItemClickListener listner; public PaymentsViewHolder(@NonNull View itemView) { super(itemView); paymentName=itemView.findViewById(R.id.person_payment_name); cardView=itemView.findViewById(R.id.card_payments); paymentPhoneNumber= itemView.findViewById(R.id.payment_phone_number); paymentTotalAmount=itemView.findViewById(R.id.payment_total_amount); paymentDateTime=itemView.findViewById(R.id.payment_date_time); } @Override public void onClick(View view) { listner.onClick(view, getAdapterPosition(), false); } public void setItemClickListner(ItemClickListener listner) { this.listner = listner; } }
package project.test; import org.junit.After; import org.junit.Assert; import org.junit.Test; import project.core.homePage.HomePage; import project.core.homePage.LeftContentBarItemsWrapper; import project.core.loginPage.LoginPage; import project.model.TestBot; import static com.codeborne.selenide.Selenide.*; public class Login extends TestBase { private TestBot bot = new TestBot("tests", "tests"); private String name = "Alona Deveraux"; @Test public void login() { String actualName = new LoginPage().doLogin(bot) .getLeftColumnContent() .getWrappedItem(LeftContentBarItemsWrapper.Items.UserInfo) .getText(); Assert.assertEquals(name, actualName); } }
package model; public enum Genre{ ROMANTICA, ACCION, SUSPENSO, TERROR, COMEDIA; }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ActiveEon Team * http://www.activeeon.com/ * Contributor(s): * * ################################################################ * $$ACTIVEEON_INITIAL_DEV$$ */ package functionaltests.workflow; import org.ow2.proactive.scheduler.common.task.flow.FlowActionType; /** * Tests the correctness of workflow-controlled jobs including {@link FlowActionType#LOOP} actions * * @author The ProActive Team * @since ProActive Scheduling 2.2 */ public class TestWorkflowLoopJobs extends TWorkflowJobs { @Override public final String[][] getJobs() { return new String[][] { // 1: loop on self { "T 0", "T1 1", "T1#1 2", "T1#2 3", "T1#3 4", "T2 5" }, // 2: loop on simple block { "T 0", "T1 1", "T2 2", "T1#1 3", "T2#1 4", "T1#2 5", "T2#2 6", "T1#3 7", "T2#3 8", "T3 9" }, // 3: loop on a complex block { "T 0", "T1 1", "T2 2", "T6 3", "T5 3", "T3 2", "T4 3", "T7 10", "T1#1 11", "T2#1 12", "T6#1 13", "T5#1 13", "T3#1 12", "T4#1 13", "T7#1 40", "T1#2 41", "T2#2 42", "T6#2 43", "T5#2 43", "T3#2 42", "T4#2 43", "T7#2 130", "T8 131", "T9 131", }, // 4: nested loops: block -> self { "T 0", "T1 1", "T1#1 2", "T1#2 3", "T2 4", "T#1 5", "T1#3 6", "T1#4 7", "T1#5 8", "T2#1 9", "T#2 10", "T1#6 11", "T1#7 12", "T1#8 13", "T2#2 14" }, // 5: nested loops: block -> block { "T 0", "T1 1", "T5 2", "T2 2", "T3 5", "T1#1 6", "T5#1 7", "T2#1 7", "T3#1 15", "T1#2 16", "T5#2 17", "T2#2 17", "T3#2 35", "T4 36", "T#1 37", "T1#3 38", "T5#3 39", "T2#3 39", "T3#3 79", "T1#4 80", "T5#4 81", "T2#4 81", "T3#4 163", "T1#5 164", "T5#5 165", "T2#5 165", "T3#5 331", "T4#1 332", "T#2 333", "T1#6 334", "T5#6 335", "T2#6 335", "T3#6 671", "T1#7 672", "T5#7 673", "T2#7 673", "T3#7 1347", "T1#8 1348", "T5#8 1349", "T2#8 1349", "T3#8 2699", "T4#2 2700" }, // 6: nested loops: block -> block -> self { "T 0", "T1 1", "T2 2", "T2#1 3", "T2#2 4", "T3 5", "T1#1 6", "T2#3 7", "T2#4 8", "T2#5 9", "T3#1 10", "T1#2 11", "T2#6 12", "T2#7 13", "T2#8 14", "T3#2 15", "T4 16", "T#1 17", "T1#3 18", "T2#9 19", "T2#10 20", "T2#11 21", "T3#3 22", "T1#4 23", "T2#12 24", "T2#13 25", "T2#14 26", "T3#4 27", "T1#5 28", "T2#15 29", "T2#16 30", "T2#17 31", "T3#5 32", "T4#1 33" }, // }; } @Override public final String getJobPrefix() { return "/functionaltests/workflow/descriptors/flow_loop_"; } @org.junit.Test public void run() throws Throwable { internalRun(); } }
/* * 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 jenkins.jautomate.GUI; import jautomate.ScriptLoggerTest; import jautomate.ScriptRunner; import org.junit.Test; /** * * @author fachrulpbm */ public class FrmMainTest { @Test public void testScenario() { ScriptRunner scriptRunner = new ScriptRunner(new ScriptLoggerTest()); scriptRunner.setParameter("scenario.jautomate", "scenario.jautomate"); scriptRunner.runScript("scenario.jautomate/scenario.txt"); } }
/* Copyright 2013 Andrew Joiner 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 uk.co.tekkies.readings.activity; import uk.co.tekkies.readings.fragment.SettingsFragment; import uk.co.tekkies.readings.util.Analytics; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.PreferenceManager; public class SettingsActivity extends BaseActivity implements OnSharedPreferenceChangeListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit(); } @Override protected void onResume() { super.onResume(); PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this); } @Override protected void onPause() { super.onPause(); PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Analytics.PrefsChange(this, key); } }
package com.mycompany.airportservice; import com.mycompany.airportservice.exceptions.WebException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.http.*; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.util.List; import org.json.JSONException; import org.springframework.web.client.RestTemplate; @RestController @RequestMapping("/api") public class ScheduleController{ @Autowired ScheduleRepository scheduleRepository; @Autowired AirplaneRepository airplaneRepository; private RestTemplate restTemplate = new RestTemplate(); @GetMapping("/schedules") public List<Schedule> getAllSchedules(@RequestParam(value = "embed", required = false) String embed) throws JSONException{ List<Schedule> schedules = scheduleRepository.findAll(); Schedule schedule = null; // airplane; for (int i = 0; i < schedules.size(); i++){ schedule = schedules.get(i); if(schedule.getAirplaneId() != null && embed != null && embed.contains("airplanes")){ final Airplane airplane = airplaneRepository.findById(schedule.getAirplaneId()).orElseThrow(() -> new WebException("GET api/schedules", "- no such airplane with id: " )); schedule.setAirplane(airplane); } if(schedule.getWeatherId() != null && embed != null && embed.contains("weathers")){ try{ Weather weather = restTemplate.getForObject("http://app2:5000/locations/" + schedule.getWeatherId(), Weather.class); schedule.setWeather(weather); } catch(Exception e){ if(!e.getMessage().contains("I/O error")){ throw new WebException("GET api/schedules", "- no weather found"); } schedule.setWeather(null); } } } return schedules; } @GetMapping("/schedules/{id}") public Schedule getScheduleById(@PathVariable(value = "id") Long scheduleId, @RequestParam(value = "embed", required = false) String embed) throws JSONException{ //Airplane airplane; Schedule schedule = scheduleRepository.findById(scheduleId).orElseThrow(() -> new WebException("GET api/schedules/id", "- no schedule found")); if(schedule.getAirplaneId() != null && embed != null && embed.contains("airplanes")){ final Airplane airplane = airplaneRepository.findById(schedule.getAirplaneId()).orElseThrow(() -> new WebException("GET api/schedules", "- no such airplane with id: " + schedule.getAirplaneId())); schedule.setAirplane(airplane); } if(schedule.getWeatherId() != null && embed != null && embed.contains("weathers")){ try{ Weather weather = restTemplate.getForObject("http://app2:5000/locations/" + schedule.getWeatherId(), Weather.class); schedule.setWeather(weather); } catch(Exception e){ if(!e.getMessage().contains("I/O error")){ throw new WebException("GET api/schedules/id", "- no weather found"); } schedule.setWeather(null); } } return schedule; } @PostMapping("/schedules") public Schedule createSchedule(@Valid @RequestBody Schedule schedule, HttpServletResponse response, @RequestParam(value = "embed", required = false) String embed){ if (schedule.getId() != null && scheduleRepository.existsById(schedule.getId())){ throw new WebException("POST api/schedules", "- schedule exists with this id: " + schedule.getId()); } if (schedule.getStartPort() == null || schedule.getDestination() == null ||schedule.getAirplaneId() == 0){ throw new WebException("POST api/schedules", "- missing fields"); } if(schedule.getWeather() != null && (schedule.getWeather().getCity() == null || schedule.getWeather().getTemperature() == null || schedule.getWeather().getDate() == null)){ throw new WebException("PUT api/schedules", "- weather - missing fields"); } final Airplane airplane = airplaneRepository.findById(schedule.getAirplaneId()).orElseThrow(() -> new WebException("POST api/schedules", "- no such airplane with id: " + schedule.getAirplaneId())); if (embed != null && embed.contains("airplanes")){ schedule.setAirplane(airplane); } Weather weather = null; if(schedule.getWeatherId() != null && schedule.getWeather() == null){ weather = getWeather(schedule.getWeatherId()); } else if(schedule.getWeather() != null){ weather = postWeather(schedule.getWeather()); } if(weather != null){ schedule.setWeatherId(weather.getId()); if (embed != null && embed.contains("weathers")){ schedule.setWeather(weather); } } response.setStatus(201); Schedule scheduleNew = scheduleRepository.save(schedule); response.addHeader("Location", "api/schedules/" + scheduleNew.getId()); scheduleNew.setWeather(weather); return scheduleNew; } @PutMapping("/schedules/{id}") public Schedule updateSchedule(@PathVariable(value = "id") Long scheduleId, @Valid @RequestBody Schedule newSchedule, HttpServletResponse response, @RequestParam(value = "embed", required = false) String embed){ Schedule schedule = scheduleRepository.findById(scheduleId).orElseThrow(() -> new WebException("PUT api/schedules/id", "- no such schedule")); if (newSchedule.getAirplaneId() == null || newSchedule.getStartPort() == null || newSchedule.getDestination() == null){ throw new WebException("PUT api/schedules", "- missing fields"); } if(newSchedule.getWeather() != null && (newSchedule.getWeather().getCity() == null || newSchedule.getWeather().getTemperature() == null || newSchedule.getWeather().getDate() == null)){ throw new WebException("PUT api/schedules", "- weather - missing fields"); } final Airplane airplane = airplaneRepository.findById(newSchedule.getAirplaneId()).orElseThrow(() -> new WebException("PUT api/schedules/id", "- no such airplane with id: " + newSchedule.getAirplaneId())); schedule.setStartPort(newSchedule.getStartPort()); schedule.setDestination(newSchedule.getDestination()); schedule.setAirplaneId(newSchedule.getAirplaneId()); if (embed != null && embed.contains("airplanes")){ schedule.setAirplane(airplane); } Weather weather = null; if(newSchedule.getWeatherId() != null && newSchedule.getWeather() == null){ weather = getWeather(newSchedule.getWeatherId()); } else if(newSchedule.getWeatherId() != null && newSchedule.getWeather() != null){ weather = putWeather(newSchedule.getWeatherId(), newSchedule.getWeather()); } else if(newSchedule.getWeatherId() == null && newSchedule.getWeather() != null){ weather = postWeather(newSchedule.getWeather()); } if(weather != null){ schedule.setWeatherId(weather.getId()); if (embed != null && embed.contains("weathers")){ schedule.setWeather(weather); } } response.setStatus(201); response.addHeader("Location", "api/schedules/" + scheduleId); return scheduleRepository.save(schedule); } @PatchMapping("/schedules/{id}") public Schedule patchSchedule(@PathVariable(value = "id") Long scheduleId, @Valid @RequestBody Schedule newSchedule, HttpServletResponse response, @RequestParam(value = "embed", required = false) String embed) { Schedule schedule = scheduleRepository.findById(scheduleId).orElseThrow(() -> new WebException("PATCH api/sechedules/id", "- no such schedule")); if(newSchedule.getStartPort() != null){ schedule.setStartPort(newSchedule.getStartPort()); } if(newSchedule.getDestination() != null){ schedule.setDestination(newSchedule.getDestination()); } if(newSchedule.getAirplaneId() != null){ final Airplane airplane = airplaneRepository.findById(newSchedule.getAirplaneId()).orElseThrow(() -> new WebException("PUT api/schedules/id", "- no such airplane with id: " + newSchedule.getAirplaneId())); schedule.setAirplaneId(newSchedule.getAirplaneId()); if (embed != null && embed.contains("airplanes")){ schedule.setAirplane(airplane); } } Weather weather = null; if(newSchedule.getWeatherId() != null && newSchedule.getWeather() == null){ weather = getWeather(newSchedule.getWeatherId()); } else if(newSchedule.getWeatherId() != null && newSchedule.getWeather() != null){ weather = patchWeather(newSchedule.getWeatherId(), newSchedule.getWeather()); } else if(newSchedule.getWeather() != null){ weather = postWeather(schedule.getWeather()); } if(weather != null){ schedule.setWeatherId(weather.getId()); if (embed != null && embed.contains("weathers")){ schedule.setWeather(weather); } } response.setStatus(202); response.addHeader("Location", "api/schedules/" + scheduleId); return scheduleRepository.save(schedule); } @DeleteMapping("/schedules/{id}") public ResponseEntity<?> deleteSchedule(@PathVariable(value = "id") Long scheduleId){ Schedule post = scheduleRepository.findById(scheduleId).orElseThrow(() -> new WebException("DELETE api/schedules/id", "- airplane with id: " + scheduleId + " does not exist.")); scheduleRepository.delete(post); return ResponseEntity.noContent().build(); } private Weather getWeather(long id){ RestTemplate restTemplate = new RestTemplate(); Weather weather = null; try{ weather = restTemplate.getForObject("http://app2:5000/locations/" + id, Weather.class); } catch(Exception e){ if(!e.getMessage().contains("I/O error")){ throw new WebException("GET api/schedules", "- no weather found"); } return null; } return weather; } private Weather postWeather(Weather w){ RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<Weather> requestBody = new HttpEntity<>(w, headers); try{ HttpEntity<String> msg = restTemplate.exchange("http://app2:5000/locations",HttpMethod.POST, requestBody, String.class); ResponseEntity<Weather[]> responseEntity = restTemplate.getForEntity("http://app2:5000/locations", Weather[].class); Weather[] weatherList = responseEntity.getBody(); return weatherList[weatherList.length - 1]; } catch(Exception e){ if(!e.getMessage().contains("I/O error")){ throw new WebException("POST api/schedules", "- weather - " + e.getMessage()); } return null; } } private Weather putWeather(Long id, Weather w){ Weather weather = null; try{ weather = restTemplate.getForObject("http://app2:5000/locations/" + id, Weather.class); } catch(Exception e){ if(!e.getMessage().contains("I/O error")){ throw new WebException("PUT api/schedules/id", "- no weather found"); } return null; } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<Weather> requestBody = new HttpEntity<>(w, headers); try{ HttpEntity<String> msg = restTemplate.exchange("http://app2:5000/locations/" + id,HttpMethod.PUT, requestBody, String.class); ResponseEntity<Weather[]> responseEntity = restTemplate.getForEntity("http://app2:5000/locations", Weather[].class); Weather[] weatherList = responseEntity.getBody(); return weatherList[id.intValue() - 1]; } catch(Exception e){ if(!e.getMessage().contains("I/O error")){ throw new WebException("PUT api/schedules/id", "- weather - " + e.getMessage()); } return null; } } private Weather patchWeather(Long id, Weather w){ Weather weather = null; try{ weather = restTemplate.getForObject("http://app2:5000/locations/" + id, Weather.class); if(weather == null){ throw new WebException("PATCH api/schedules/id", "- no weather found"); } if(w.getTemperature() != null){ weather.setTemperature(w.getTemperature()); } if(w.getCity() != null){ weather.setCity(w.getCity()); } if(w.getDate() != null){ weather.setDate(w.getDate()); } } catch(Exception e){ if(!e.getMessage().contains("I/O error")){ throw new WebException("PATCH api/schedules/id", "- no weather found"); } return null; } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<Weather> requestBody = new HttpEntity<>(weather, headers); try{ HttpEntity<String> msg = restTemplate.exchange("http://app2:5000/locations/" + id,HttpMethod.PUT, requestBody, String.class); ResponseEntity<Weather[]> responseEntity = restTemplate.getForEntity("http://app2:5000/locations", Weather[].class); Weather[] weatherList = responseEntity.getBody(); return weatherList[id.intValue() - 1]; } catch(Exception e){ if(!e.getMessage().contains("I/O error")){ throw new WebException("PUT api/schedules/id", "- weather - " + e.getMessage()); } return null; } } }
package dk.webbies.tscreate.util; /** * Java Program to Implement Tarjan Algorithm * Copy pasta from: http://www.sanfoundry.com/java-program-tarjan-algorithm/ **/ import java.util.*; /** class Tarjan **/ public class Tarjan<T extends Tarjan.Node<T>> { public static abstract class Node<T extends Node> { int low; int visited; public abstract Collection<T> getEdges(); } /** preorder number counter **/ private static int iterationCounter = 1; private int preCount; /** * function to get all strongly connected components **/ public List<List<T>> getSCComponents(T graph) { return getSCComponents(Collections.singletonList(graph), iterationCounter++); } /** * function to get all strongly connected components **/ public List<List<T>> getSCComponents(Collection<T> graph) { return getSCComponents(graph, iterationCounter++); } /** * function to get all strongly connected components **/ private List<List<T>> getSCComponents(Collection<T> graph, int iteration) { Deque<T> stack = new LinkedList<>(); List<List<T>> sccComp = new ArrayList<>(); for (T edge : graph) { if (edge.visited != iteration) { dfs(edge, iteration, stack, sccComp); } } return sccComp; } public List<T> getReachableSet(T graph) { return getReachableSet(graph, iterationCounter++); } /* * Finds how heep in the tree the different elements are. * The returned list of lists only contain the elements given as input. * The first element is the deepest in the tree (a leaf). */ public List<List<T>> getLevels(Collection<T> elements) { return getLevels(elements, iterationCounter++); } private List<List<T>> getLevels(Collection<T> elements, int iteration) { for (T element : elements) { markLevel(element, iteration); } List<List<T>> result = new ArrayList<>(); for (T element : elements) { for (int i = result.size(); i <= element.low; i++) { result.add(i, new ArrayList<T>()); } result.get(element.low).add(element); } return result; } private int markLevel(T node, int iteration) { if (node.visited == iteration) { node.low = 0; return node.low; } else { node.visited = iteration; int max = 0; for (T edge : node.getEdges()) { max = Math.max(max, markLevel(edge, iteration)); } node.low = max + 1; return node.low; } } private List<T> getReachableSet(T graph, int iteration) { ArrayList<T> result = new ArrayList<>(); reachableDfs(graph, iteration, result); return result; } private void reachableDfs(T node, int iteration, List<T> result) { if (node.visited != iteration) { node.visited = iteration; result.add(node); for (T edge : node.getEdges()) { reachableDfs(edge, iteration, result); } } } /** * function dfs **/ private void dfs(T v, int iteration, Deque<T> stack, List<List<T>> sccComp) { v.low = preCount++; v.visited = iteration; stack.push(v); int min = v.low; for (T edge : v.getEdges()) { if (edge.visited != iteration) { dfs(edge, iteration, stack, sccComp); } if (edge.low < min) { min = edge.low; } } if (min < v.low) { v.low = min; return; } List<T> component = new ArrayList<>(); T w; do { w = stack.pop(); component.add(w); w.low = Integer.MAX_VALUE; } while (w != v); sccComp.add(component); } private static class SimpleNode extends Node<SimpleNode> { List<SimpleNode> list = new ArrayList<>(); private String descrip; public SimpleNode(String descrip) { this.descrip = descrip; } @Override public String toString() { return descrip; } @Override public Collection<SimpleNode> getEdges() { return list; } } /** main **/ public static void main(String[] args) { SimpleNode node1 = new SimpleNode("1"); SimpleNode node2 = new SimpleNode("2"); SimpleNode node3 = new SimpleNode("3"); node1.list.add(node2); node2.list.add(node3); Tarjan<SimpleNode> t = new Tarjan<>(); System.out.println("\nSCC : "); /** print all strongly connected components **/ List<List<SimpleNode>> scComponents = t.getLevels(Arrays.asList(node1, node2, node3)); System.out.println(scComponents); } }
package com.timewarp.engine.animator; import com.timewarp.engine.Vector2D; public class AnimationStepData { public float time; public Vector2D position; public Vector2D size; public float rotation; boolean relative; public AnimationStepData() { this(new Vector2D(), new Vector2D()); } public AnimationStepData(float x, float y, float width, float height) { this(new Vector2D(x, y), new Vector2D(width, height), 0); } public AnimationStepData(Vector2D position, Vector2D size, float rotation) { this.position = position; this.size = size; this.rotation = rotation; this.relative = Animation.MODE_ABSOLUTE; } public AnimationStepData(Vector2D position, Vector2D size) { this(position, size, 0); } public boolean isRelative() { return this.relative; } public AnimationStepData copy() { return new AnimationStepData( this.position == null ? null : this.position.copy(), this.size == null ? null : this.size.copy(), this.rotation ); } }
package com.nematjon.edd_client_season_two.services; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import com.nematjon.edd_client_season_two.DbMgr; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import be.tarsos.dsp.AudioDispatcher; import be.tarsos.dsp.AudioEvent; import be.tarsos.dsp.AudioProcessor; import be.tarsos.dsp.SilenceDetector; import be.tarsos.dsp.io.android.AudioDispatcherFactory; import be.tarsos.dsp.mfcc.MFCC; import be.tarsos.dsp.pitch.PitchDetectionHandler; import be.tarsos.dsp.pitch.PitchDetectionResult; import be.tarsos.dsp.pitch.PitchDetector; import be.tarsos.dsp.pitch.PitchProcessor; class AudioFeatureRecorder { // region Constants private static final String TAG = AudioFeatureRecorder.class.getSimpleName(); private final int SAMPLING_RATE = 11025; private final int AUDIO_BUFFER_SIZE = 1024; private final double SILENCE_THRESHOLD = -65.0D; // endregion // region Variables private boolean started; private ExecutorService executor = Executors.newCachedThreadPool(); private AudioDispatcher dispatcher; // endregion AudioFeatureRecorder(final Context con) { final SharedPreferences prefs = con.getSharedPreferences("Configurations", Context.MODE_PRIVATE); dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(SAMPLING_RATE, AUDIO_BUFFER_SIZE, 512); final SilenceDetector silenceDetector = new SilenceDetector(SILENCE_THRESHOLD, false); final MFCC mfccProcessor = new MFCC(AUDIO_BUFFER_SIZE, SAMPLING_RATE, 13, 30, 133.33f, 8000f); final String sound_feature_type_energy = "ENERGY"; final String sound_feature_type_pitch = "PITCH"; final String sound_feature_type_mfcc = "MFCC"; final int dataSourceId = prefs.getInt("SOUND_DATA", -1); assert dataSourceId != -1; AudioProcessor mainProcessor = new AudioProcessor() { @Override public boolean process(AudioEvent audioEvent) { long nowTime = System.currentTimeMillis(); if (silenceDetector.currentSPL() >= -110.0D) { DbMgr.saveMixedData(dataSourceId, nowTime, 1.0f, nowTime, silenceDetector.currentSPL(), sound_feature_type_energy); } float[] mfccs = mfccProcessor.getMFCC(); DbMgr.saveMixedData(dataSourceId, nowTime, 1.0f, nowTime, Arrays.toString(mfccs).replace(" ", ""), sound_feature_type_mfcc); return true; } @Override public void processingFinished() { } }; //region Pitch extraction PitchDetectionHandler pitchHandler = new PitchDetectionHandler() { @Override public void handlePitch(PitchDetectionResult pitchDetectionResult, AudioEvent audioEvent) { if (pitchDetectionResult.getPitch() > -1.0f && pitchDetectionResult.getPitch() != 918.75f) { long nowTime = System.currentTimeMillis(); DbMgr.saveMixedData(dataSourceId, nowTime, 1.0f, nowTime, pitchDetectionResult.getPitch(), sound_feature_type_pitch); } } }; PitchProcessor pitchProcessor = new PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.AMDF, SAMPLING_RATE, AUDIO_BUFFER_SIZE, pitchHandler); //endregion if (dispatcher == null) Log.e(TAG, "Dispatcher is NULL: "); dispatcher.addAudioProcessor(silenceDetector); dispatcher.addAudioProcessor(pitchProcessor); dispatcher.addAudioProcessor(mfccProcessor); dispatcher.addAudioProcessor(mainProcessor); } void start() { Log.d(TAG, "Started: AudioFeatureRecorder"); executor.execute(dispatcher); started = true; } void stop() { Log.d(TAG, "Stopped: AudioFeatureRecorder"); if (started) { dispatcher.stop(); started = false; } } }
package com.jwebsite.dao; import java.sql.*; import java.util.List; import com.jwebsite.vo.FriendSite; public interface FriendSiteDao { //显示所有友情链接 public ResultSet showAllFs() throws Exception; public ResultSet showAllFs(String view) throws Exception; public ResultSet showAClassFs(String ClassId) throws Exception; //添加友情链接 public void insertFs(FriendSite friendSite) throws Exception; //删除友情链接 public void delFs(FriendSite friendSite) throws Exception; //更新友情链接 public void updateFs(FriendSite friendSite) throws Exception; //查询一条 public FriendSite quaryOneFs(int ID) throws Exception; //根据类别查找友情链接 public List<FriendSite> getOneClassFriendSite(int ClassId) throws Exception; }
package com.cc.list; import com.cc.R; import com.cc.activity.LoginActivity; import com.cc.activity.PersonalActivity; import com.cc.activity.PoiSearchActivity; import com.cc.activity.ReturnInfoActivity; import com.cc.data.Const; import com.cc.data.User; import com.cc.activity.AboutActivity; import com.cc.activity.BasemapActivity; import com.cc.activity.ChangePasswordActivity; import com.cc.activity.FeedbackActivity; import com.cc.util.Util; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import cn.bmob.v3.BmobUser; import android.view.ViewGroup; public class LeftFragment extends Fragment implements OnClickListener{ private View baseMapView; private View ePoolView; private View changepwdView; private View settingsView; private View personalView; private View aboutView; private View reloginView; private View exitView; private TextView name; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.layout_menu, null); findViews(view); return view; } public void findViews(View view) { baseMapView = view.findViewById(R.id.tvBasemap); ePoolView = view.findViewById(R.id.tvEpool); settingsView = view.findViewById(R.id.tvMySettings); //反馈 changepwdView = view.findViewById(R.id.tvChangepassword); personalView = view.findViewById(R.id.tvperson); aboutView = view.findViewById(R.id.tvabout); reloginView = view.findViewById(R.id.relogin); exitView = view.findViewById(R.id.exit); name =(TextView) view.findViewById(R.id.name); User bmobUser = BmobUser.getCurrentUser(User.class); if(bmobUser != null){ // 允许用户使用应用 name.setText(bmobUser.getName()); }else{ //缓存用户对象为空时, 可打开用户注册界面… name.setText("未登录"); } baseMapView.setOnClickListener(this); ePoolView.setOnClickListener(this); changepwdView.setOnClickListener(this); settingsView.setOnClickListener(this); reloginView.setOnClickListener(this); personalView.setOnClickListener(this); aboutView.setOnClickListener(this); exitView.setOnClickListener(this); name.setOnClickListener(this); } @Override public void onDestroyView() { super.onDestroyView(); } @Override public void onDestroy() { super.onDestroy(); } public void nameOnclick(){ if (name.getText().toString().equals("未登录")) { Util.startActivity(getActivity(), LoginActivity.class); } } @Override public void onClick(View v) { Fragment newContent = null; String title = null; Intent intent ; switch (v.getId()) { case R.id.tvBasemap: // 基础地图 Util.startActivity(getActivity(), BasemapActivity.class); break; case R.id.tvEpool:// 接单 if (Const.isSetStart) { Util.startActivity(getActivity(), ReturnInfoActivity.class); }else { Util.toast("请先设置您想匹配到的乘客位置", getActivity()); } break; case R.id.tvperson: // 个人中心 if (name.getText().toString().equals("未登录")) { Util.toast("请先登录", getActivity()); Util.startActivity(getActivity(), LoginActivity.class); }else { Util.startActivity(getActivity(), PersonalActivity.class); } break; case R.id.tvChangepassword: if (name.getText().toString().equals("未登录")) { Util.toast("请先登录", getActivity()); Util.startActivity(getActivity(), LoginActivity.class); }else { Util.startActivity(getActivity(), ChangePasswordActivity.class); } break; case R.id.tvMySettings: // 反馈 Util.startActivity(getActivity(), FeedbackActivity.class); break; case R.id.tvabout: Util.startActivity(getActivity(), AboutActivity.class); break; case R.id.relogin: BmobUser.logOut(); intent = new Intent(); intent.setClass(getActivity(), LoginActivity.class); getActivity().startActivity(intent); ((Activity) getActivity()).finish(); break; case R.id.exit: ((Activity) getActivity()).finish(); break; case R.id.name: nameOnclick(); default: break; } } }
/* $Id$ */ package djudge.remotefs; import java.io.File; import java.util.Random; import java.util.Vector; import djudge.common.ImplementMe; import djudge.common.JudgeDirs; import djudge.judge.dchecker.RemoteFile; import utils.FileTools; // FIXME: this is just a stub @ImplementMe public class RemoteFS { private static Vector<String> files = new Vector<String>(); public static void startSession() { files = new Vector<String>(); } public static void clearSession() { //for (int i = 0; i < files.size(); i++) // FileTools.deleteFile(files.get(i)); files.clear(); } public static String getUID() { StringBuffer s = new StringBuffer(); Random rand = new Random(); for (int i = 0; i < 50; i++) s.append((char)('A' + (rand.nextInt() % 26 + 26)%26)); return s.toString(); } public static String saveToRemoteStorage(RemoteFile file) { String name = getUID(); while (new File(JudgeDirs.getTempDir() + name).exists()) { name = getUID(); } FileTools.saveToFile(file, JudgeDirs.getTempDir() + name); files.add(JudgeDirs.getTempDir() + name); return JudgeDirs.getTempDir() + name; } public static String readContent(String filename) { return FileTools.readFile(filename); } public static boolean writeContent(String content, String filename) { FileTools.saveToFile(content, filename); return true; } }
package factoring.math; import factoring.sieve.triple.BitSetWithOffset; import org.junit.Test; import static java.lang.Math.*; import static org.junit.Assert.assertTrue; public class SmoothNumberGeneratorTest { @Test public void testIsSmoothByFourFactors(){ // int number = 87463; // long number = 3363 * 2287; final long number = 8_000_0009l * 4_000_037l; SmoothNumberGenerator smoothNumberGenerator = SmoothNumberGenerator.ofMaxSize(2 * number); int smoothNumberCount = 0; int smoothRightCount = 0; int numberSqrt = (int) ceil(sqrt(number)); final double factorBaseSize = smoothNumberGenerator.factorBaseSize(numberSqrt); System.out.println("factor base size : " + factorBaseSize); int rangeOrig = (int) (3* factorBaseSize); System.out.println("work per loop: " + rangeOrig / 64); double numberPowQuarter = pow(number, .25); final int variance = (int) (3 * numberPowQuarter * rangeOrig); System.out.println(" expected size of numbers : " + variance + " = " + (variance/ numberSqrt) + " * size of QS"); int zDiff = 0; int z = numberSqrt + zDiff; int range = rangeOrig; // z^2 - t for (; smoothNumberCount < factorBaseSize;) { BitSetWithOffset smoothNumbersSet = smoothNumberGenerator.getSmoothNumbersBy4Products(number, z, range); for (int yDiff = smoothNumbersSet.ysMinyOffset.nextSetBit(0); yDiff >= 0; yDiff = smoothNumbersSet.ysMinyOffset.nextSetBit(yDiff + 1)) { long y = smoothNumbersSet.yOffset + yDiff; long lowerProductSmooth = z - y; long higherProductSmooth = z + y; long smoothNumber = lowerProductSmooth * higherProductSmooth; assertTrue("lower number " + lowerProductSmooth + " is not smooth for number : " + number, smoothNumberGenerator.smoothNumber.get((int) lowerProductSmooth)); assertTrue(smoothNumberGenerator.smoothNumber.get((int) higherProductSmooth)); int right = (int) (smoothNumber - number); if (smoothNumberGenerator.smoothNumber.get(abs(right))) { System.out.println("found smooth number right : " + right); smoothRightCount++; } if (smoothNumber == 320007290814900l){ System.out.println(); } assertTrue("range does not fit for number : " + smoothNumber + " size of diff to sqrt n " + right, abs(right) < numberSqrt); assertTrue("generated number " + smoothNumber + " distance to number " + (smoothNumber - number) + " greater than .5 * sqrt(n) ", abs(right) < 1 * numberSqrt); smoothNumberCount++; } range = (int) (rangeOrig / sqrt(++zDiff)); z = numberSqrt + zDiff; } System.out.println("we have created " +smoothNumberCount + " numbers within " + zDiff + " loops. all smooth numbers smaller then .5 * sqrt(n)"); System.out.println("we have created " +smoothRightCount + " smooth numbers on the right"); System.out.println("last range " + range); } @Test public void testIsSmoothByTwoProducts(){ // int number = 87463; // long number = 3363 * 2287; final long number = 8_000_0009l * 4_000_037l; SmoothNumberGenerator smoothNumberGenerator = SmoothNumberGenerator.ofMaxSize(2 * number); int smoothNumberCount = 0; int smoothRightCount = 0; int numberSqrt = (int) ceil(sqrt(number)); final double factorBaseSize = smoothNumberGenerator.factorBaseSize(number); System.out.println("factor base size : " + factorBaseSize); int range = (int) (3* factorBaseSize); System.out.println("work per loop: " + range / 64); double numberPowQuarter = pow(number, .25); final int variance = (int) (3 * numberPowQuarter * range); System.out.println(" expected size of numbers : " + variance + " = " + (variance/ numberSqrt) + " * size of QS"); int zDiff = 0; int z = numberSqrt + zDiff; int rangeForZ = range; for (; smoothNumberCount < factorBaseSize;) { BitSetWithOffset smoothNumbersSet = smoothNumberGenerator.getSmoothNumbersBy2Products(number, z, rangeForZ); for (int yDiff = smoothNumbersSet.ysMinyOffset.nextSetBit(0); yDiff >= 0; yDiff = smoothNumbersSet.ysMinyOffset.nextSetBit(yDiff + 1)) { long y = smoothNumbersSet.yOffset + yDiff; long lowerProductSmooth = z - y; long higherProductSmooth = z + y; long smoothNumber = lowerProductSmooth * higherProductSmooth; assertTrue("lower number " + lowerProductSmooth + " is not smooth for number : " + number, smoothNumberGenerator.smoothNumber.get((int) lowerProductSmooth)); assertTrue(smoothNumberGenerator.smoothNumber.get((int) higherProductSmooth)); int right = (int) (smoothNumber - number); if (smoothNumberGenerator.smoothNumber.get(abs(right))) { System.out.println("found smooth number right : " + right); smoothRightCount++; } if (smoothNumber == 320007290814900l){ System.out.println(); } assertTrue("range does not fit for number : " + smoothNumber + " size of diff to sqrt n " + right, abs(right) < numberSqrt); assertTrue("generated number " + smoothNumber + " distance to number " + (smoothNumber - number) + " greater than .5 * sqrt(n) ", abs(right) < 1 * numberSqrt); smoothNumberCount++; } rangeForZ = (int) (range / sqrt(++zDiff)); z = numberSqrt + zDiff; } System.out.println("we have created " +smoothNumberCount + " numbers within " + zDiff + " loops. all smooth numbers smaller then .5 * sqrt(n)"); System.out.println("we have created " +smoothRightCount + " smooth numbers on the right"); System.out.println("last range " + rangeForZ); } @Test public void testIsSmoothByMultiplyingN(){ // int number = 87463; // long number = 3363 * 2287; final long numberOrig = 8_000_0009l * 4_000_037l; SmoothNumberGenerator smoothNumberGenerator = SmoothNumberGenerator.ofMaxSize(10 * numberOrig); int smoothNumberCount = 0; int smoothRightCount = 0; final double factorBaseSize = smoothNumberGenerator.factorBaseSize(numberOrig); System.out.println("factor base size : " + factorBaseSize); int range = (int) (2* factorBaseSize); System.out.println("work per loop: " + range / 64); double numberPowQuarter = pow(numberOrig, .25); int variance = (int) (3 * numberPowQuarter * range); int numberSqrt = (int) sqrt(numberOrig); System.out.println(" expected size of numbers : " + variance + " = " + (variance/ numberSqrt) + " * size sqrt(n) = " +numberSqrt); long number = 0; int k = 0; for (; smoothNumberCount < factorBaseSize;) { number += numberOrig; k++; System.out.println(" k = " + k); numberPowQuarter = pow(number, .25); variance = (int) (3 * numberPowQuarter * range); numberSqrt = (int) ceil(sqrt(number)); BitSetWithOffset smoothNumbersSet = smoothNumberGenerator.getSmoothNumbersBy2Products(number, numberSqrt, range); for (int yDiff = smoothNumbersSet.ysMinyOffset.nextSetBit(0); yDiff >= 0; yDiff = smoothNumbersSet.ysMinyOffset.nextSetBit(yDiff + 1)) { long y = smoothNumbersSet.yOffset + yDiff; long lowerProductSmooth = numberSqrt - y; long higherProductSmooth = numberSqrt + y; long smoothNumber = lowerProductSmooth * higherProductSmooth; assertTrue("lower number " + lowerProductSmooth + " is not smooth for number : " + number, smoothNumberGenerator.smoothNumber.get((int) lowerProductSmooth)); assertTrue(smoothNumberGenerator.smoothNumber.get((int) higherProductSmooth)); int right = (int) (smoothNumber - number); if (smoothNumberGenerator.smoothNumber.get(abs(right))) { System.out.println("found smooth number right : " + right); smoothRightCount++; } if (smoothNumber == 320000931906359l){ System.out.println(); } assertTrue("range does not fit for number : " + smoothNumber + " size of diff to sqrt n " + right, abs(right) < numberSqrt); assertTrue("generated number " + smoothNumber + " distance to number " + (smoothNumber - number) + " greater than .5 * sqrt(n) ", abs(right) < 1 * numberSqrt); smoothNumberCount++; } } System.out.println("we have created " +smoothNumberCount + " numbers within " + k + " loops. all smooth numbers smaller then .5 * sqrt(n)"); System.out.println("we have created " +smoothRightCount + " smooth numbers on the right"); } }
package com.example.submissionempat.ui.main.fragment.favorite; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.submissionempat.R; import com.example.submissionempat.model.MovieData; import com.example.submissionempat.ui.main.adapter.all.ListMovieAdapter; import com.example.submissionempat.viewmodel.MainViewModel; import java.util.ArrayList; public class ListMovieFavoriteFragment extends Fragment { private ListMovieAdapter listMovieAdapter; private RecyclerView recyclerData; private MainViewModel mainViewModel; private ProgressBar progressBar; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.recycler_recycler_item_tv_movie, container, false); progressBar = view.findViewById(R.id.progressBar); mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class); mainViewModel.getDataFavorite(getContext()).observe(this, getMovieData); listMovieAdapter = new ListMovieAdapter(getContext()); listMovieAdapter.notifyDataSetChanged(); recyclerData = (RecyclerView) view.findViewById(R.id.recycler_data); recyclerData.setLayoutManager(new LinearLayoutManager(getContext())); recyclerData.setAdapter(listMovieAdapter); mainViewModel.setListMovieData(); showLoading(true); return view; } private Observer<ArrayList<MovieData>> getMovieData = new Observer<ArrayList<MovieData>>() { @Override public void onChanged(@Nullable ArrayList<MovieData> movieData) { if (movieData != null){ listMovieAdapter.setMovieData(movieData); // showLoading(false); } } }; private void showLoading(Boolean state) { if (state) { progressBar.setVisibility(View.VISIBLE); } else { progressBar.setVisibility(View.GONE); } } }
package de.hofuniversity.ejbbean.data; import java.util.List; /** * * @author Michael Jahn * */ public interface MatchDetailsSummaryData { public String getHomeTeamName(); public String getHomeTeamIconURL(); public String getGuestTeamName(); public String getGuestTeamIconURL(); public String getFinalHomeScore(); public String getFinalGuestScore(); public String getHalfHomeScore(); public String getHalfGuestScore(); public String getStadiumName(); public String getStadiumAdress(); public int getStadiumCapacity(); public double getLongitude(); public double getLatitude(); public String getStadiumInsideURL(); public String getStadiumOutsideURL(); public List<MatchDetailsGoalSummaryData> getGoalList(); }
package sop.persistence.beans; /** * @Author: LCF * @Date: 2020/1/9 10:08 * @Package: sop.persistence.beans */ public class Supplier extends BaseBean { private static final long serialVersionUID = 1L; private Integer id; private String code; private String name; // private String suChn; private String email; private String contactPerson; private String address; private String tel; private String fax; private String payTerm; private String credit; private String type; /*这中间的field在表中都是空null,应该是不用了。*/ private String su_con_per1; private String su_con_per2; private String su_chn_add; private String su_tel1_cty; private String su_tel1_no; private String su_tel2_cty; private String su_tel2_no; private String su_fax1_cty; private String su_fax1_no; private String su_fax2_cty; private String su_fax2_no; private String su_pterm; private String su_ccy; private String su_cr_bal; private String su_cr_used; private String su_gl_inf_settle; /*这中间的field在表中都是空null,应该是不用了。*/ private String websiteUrl; private String fscCertCode; private String fscValidFm; private String fscValidTo; private String bsciCertCode; private String bsciValidFm; private String bsciValidTo; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getContactPerson() { return contactPerson; } public void setContactPerson(String contactPerson) { this.contactPerson = contactPerson; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getPayTerm() { return payTerm; } public void setPayTerm(String payTerm) { this.payTerm = payTerm; } public String getCredit() { return credit; } public void setCredit(String credit) { this.credit = credit; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSu_con_per1() { return su_con_per1; } public void setSu_con_per1(String su_con_per1) { this.su_con_per1 = su_con_per1; } public String getSu_con_per2() { return su_con_per2; } public void setSu_con_per2(String su_con_per2) { this.su_con_per2 = su_con_per2; } public String getSu_chn_add() { return su_chn_add; } public void setSu_chn_add(String su_chn_add) { this.su_chn_add = su_chn_add; } public String getSu_tel1_cty() { return su_tel1_cty; } public void setSu_tel1_cty(String su_tel1_cty) { this.su_tel1_cty = su_tel1_cty; } public String getSu_tel1_no() { return su_tel1_no; } public void setSu_tel1_no(String su_tel1_no) { this.su_tel1_no = su_tel1_no; } public String getSu_tel2_cty() { return su_tel2_cty; } public void setSu_tel2_cty(String su_tel2_cty) { this.su_tel2_cty = su_tel2_cty; } public String getSu_tel2_no() { return su_tel2_no; } public void setSu_tel2_no(String su_tel2_no) { this.su_tel2_no = su_tel2_no; } public String getSu_fax1_cty() { return su_fax1_cty; } public void setSu_fax1_cty(String su_fax1_cty) { this.su_fax1_cty = su_fax1_cty; } public String getSu_fax1_no() { return su_fax1_no; } public void setSu_fax1_no(String su_fax1_no) { this.su_fax1_no = su_fax1_no; } public String getSu_fax2_cty() { return su_fax2_cty; } public void setSu_fax2_cty(String su_fax2_cty) { this.su_fax2_cty = su_fax2_cty; } public String getSu_fax2_no() { return su_fax2_no; } public void setSu_fax2_no(String su_fax2_no) { this.su_fax2_no = su_fax2_no; } public String getSu_pterm() { return su_pterm; } public void setSu_pterm(String su_pterm) { this.su_pterm = su_pterm; } public String getSu_ccy() { return su_ccy; } public void setSu_ccy(String su_ccy) { this.su_ccy = su_ccy; } public String getSu_cr_bal() { return su_cr_bal; } public void setSu_cr_bal(String su_cr_bal) { this.su_cr_bal = su_cr_bal; } public String getSu_cr_used() { return su_cr_used; } public void setSu_cr_used(String su_cr_used) { this.su_cr_used = su_cr_used; } public String getSu_gl_inf_settle() { return su_gl_inf_settle; } public void setSu_gl_inf_settle(String su_gl_inf_settle) { this.su_gl_inf_settle = su_gl_inf_settle; } public String getWebsiteUrl() { return websiteUrl; } public void setWebsiteUrl(String websiteUrl) { this.websiteUrl = websiteUrl; } public String getFscCertCode() { return fscCertCode; } public void setFscCertCode(String fscCertCode) { this.fscCertCode = fscCertCode; } public String getFscValidFm() { return fscValidFm; } public void setFscValidFm(String fscValidFm) { this.fscValidFm = fscValidFm; } public String getFscValidTo() { return fscValidTo; } public void setFscValidTo(String fscValidTo) { this.fscValidTo = fscValidTo; } public String getBsciCertCode() { return bsciCertCode; } public void setBsciCertCode(String bsciCertCode) { this.bsciCertCode = bsciCertCode; } public String getBsciValidFm() { return bsciValidFm; } public void setBsciValidFm(String bsciValidFm) { this.bsciValidFm = bsciValidFm; } public String getBsciValidTo() { return bsciValidTo; } public void setBsciValidTo(String bsciValidTo) { this.bsciValidTo = bsciValidTo; } }
package com.geoblink.clientStore.dao.impl; import org.hibernate.Session; import com.geoblink.clientStore.service.IClientStoreService; import com.geoblink.clientStore.dao.IClientStoreDAO; import com.geoblink.clientStore.pojo.ClientStore; import com.geoblink.util.hibernate.HibernateSessionManager; public class ClientStoreDAO implements IClientStoreDAO { @Override public String saveClientStore(String param) { Session session = HibernateSessionManager.getSessionFactory().getCurrentSession(); try { session.beginTransaction(); ClientStore cs = new ClientStore(); cs.setName(param); cs.setIdBrand(1); cs.setIdCompany(1); session.save(cs); session.getTransaction().commit(); return "Guardado desde DAO"; } catch (Exception e) { session.getTransaction().rollback(); throw e; } } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ui.context; import org.springframework.lang.Nullable; /** * Interface to be implemented by objects that can resolve {@link Theme Themes}. * This enables parameterization and internationalization of messages * for a given 'theme'. * * @author Jean-Pierre Pawlak * @author Juergen Hoeller * @see Theme * @deprecated as of 6.0 in favor of using CSS, without direct replacement */ @Deprecated(since = "6.0") public interface ThemeSource { /** * Return the Theme instance for the given theme name. * <p>The returned Theme will resolve theme-specific messages, codes, * file paths, etc (e.g. CSS and image files in a web environment). * @param themeName the name of the theme * @return the corresponding Theme, or {@code null} if none defined. * Note that, by convention, a ThemeSource should at least be able to * return a default Theme for the default theme name "theme" but may also * return default Themes for other theme names. * @see org.springframework.web.servlet.theme.AbstractThemeResolver#ORIGINAL_DEFAULT_THEME_NAME */ @Nullable Theme getTheme(String themeName); }
package mikfuans.security.bean; import lombok.Getter; import lombok.Setter; @Setter @Getter public class SysPermission { private Long id; private String name; private String description; private String url; private Long pid; }
package br.com.tn.cap11; public class TestandoADivisao { public static void main (String args[]) { int i = 5571; i = i/0; System.out.println("O Resultado " + i); } }
package com.bradforj287.SimpleTextSearch.engine; import org.apache.commons.lang3.StringUtils; import java.io.StringReader; import java.util.ArrayList; import java.util.List; /** * Created by brad on 6/6/15. */ public class TextParseUtils { private TextParseUtils() { } public static String stemWord(String word) { return word; } public static List<String> tokenize(String rawText) { List<String> retVal = new ArrayList<>(); if (StringUtils.isEmpty(rawText)) { return retVal; } return retVal; } }
package com.cheese.radio.ui.home.clock; import com.cheese.radio.base.cycle.BaseFragment; /** * Created by 29283 on 2018/3/13. */ public class ClockFragment extends BaseFragment<ClockModel> { }
package com.illknow.service; import com.lateralthoughts.commons.nosql.redis.stub.FakeJedis; import org.springframework.stereotype.Repository; @Repository public class FakeJedisRepository extends FakeJedis { }
package com.dubeboard.dubeboard; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.Spinner; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; /** * Created by edgar on 20/02/16. */ public class gl { public static Bitmap scaleDown(Bitmap realImage, float maxImageSize, boolean filter) { float ratio = Math.min( (float) maxImageSize / realImage.getWidth(), (float) maxImageSize / realImage.getHeight()); int width = Math.round((float) ratio * realImage.getWidth()); int height = Math.round((float) ratio * realImage.getHeight()); Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width, height, filter); return newBitmap; } public static byte[] BitmaptoByteArray(Bitmap bmp){ ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); return byteArray; } public static Bitmap build_image(Context context, byte[] img){ Bitmap bmp; if (img != null){ try{ ByteArrayInputStream imageStream = new ByteArrayInputStream(img); bmp = BitmapFactory.decodeStream(imageStream); } catch (Throwable e) { bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.img_def_48x48); } }else{ // En el caso de que no se pueda cargar la imagen se devuelve una por defecto bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.image_def_128); } return bmp; } public static int getIndexSpinner(Spinner spinner, String myString){ int index = 0; for (int i=0;i<spinner.getCount();i++){ if (spinner.getItemAtPosition(i).equals(myString)){ index = i; } } return index; } }
package com.timewarp.games.onedroidcode.level.levels.normal; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.timewarp.engine.Vector2D; import com.timewarp.games.onedroidcode.AssetManager; import com.timewarp.games.onedroidcode.level.CourseInfo; import com.timewarp.games.onedroidcode.level.Level; import com.timewarp.games.onedroidcode.level.LevelGrid; import com.timewarp.games.onedroidcode.objects.CollectibleItem; import com.timewarp.games.onedroidcode.objects.tiles.TWall; import java.util.Locale; public class WinkingGateLevel implements Level { @Override public String getSId() { return "winking_gate"; } @Override public String getName() { return "Winking gate"; } @Override public TextureRegion getTexture() { return AssetManager.levelWinkingGateTexture; } @Override public Vector2D getSize() { return new Vector2D(10, 9); } @Override public void loadTo(LevelGrid grid, int courseId) { grid.player.setXY(new Vector2D(3, 1)); // =- WALLS AROUND MAP -= for (int i = 0; i < 9; ++i) { grid.add(new TWall(), i + 1, 0); grid.add(new TWall(), 0, i); grid.add(new TWall(), i, 8); grid.add(new TWall(), 9, i + 1); } // =- COLUMNS AND INNER WALL -= for (int i = 2; i < 9; i += 2) { grid.add(new TWall(), 2, i); grid.add(new TWall(), 4, i); grid.add(new TWall(), 6, i); grid.add(new TWall(), 7, i); // inner wall } // =- GATES -= for (int i = 0; i < 4; ++i) { if (courseId == i) continue; grid.add(new TWall(), 7, i * 2 + 1); } // =- COLLECTIBLES -= grid.add(new CollectibleItem(), 8, 1); grid.add(new CollectibleItem(), 8, 7); } @Override public int getCoursesCount() { return 4; } @Override public CourseInfo getCourseInfo(final int courseId) { return new CourseInfo() {{ id = courseId; name = String.format(Locale.US, "door #%d", id); minSteps = 3 + (7 * id) + 7; maxSteps = (3 + 10 * id) * TICKS_PER_STEP; data = id; }}; } }
import java.util.Iterator; import java.lang.Iterable; public class SinglyLinkedList<T> implements List<T>, Iterable<T> { private class Node { T data; Node next; public Node(T data, Node next) { this.data = data; this.next = next; } public Node(T data) { this(data, null); } } private Node head; private Node tail; private int size; public SinglyLinkedList() { this.head = null; this.tail = null; size = 0; } public SinglyLinkedList(T item) { Node node = this.new Node(item); this.head = node; this.tail = node; this.size = 1; } public SinglyLinkedList(T[] items) { this(); for (T item : items) { this.append(item); } } public SinglyLinkedList(List<T> items) { this(); for (T item : items) { this.append(item); } } public int size() { return this.size; } public boolean isEmpty() { return this.size == 0; } public boolean contains(T item) { Node rover = this.head; while (rover != null) { if (rover.data.equals(item)) { return true; } rover = rover.next; } return false; } public boolean equals(Iterable other) { Iterator<T> thisIterator = this.iterator(); Iterator<T> otherIterator = other.iterator(); while (thisIterator.hasNext() && otherIterator.hasNext()) { if (!thisIterator.next().equals(otherIterator.next())) { return false; } } return thisIterator.hasNext() == otherIterator.hasNext(); } @Override public boolean equals(Object other) { if (other instanceof Iterable) { return equals((Iterable) other); } else { return false; } } public T head() { return (this.head != null) ? this.head.data : null; } public T tail() { return (this.tail != null) ? this.tail.data : null; } public void append(T item) { Node node = new Node(item); if (this.head == null) { this.head = node; this.tail = node; } else { this.tail.next = node; this.tail = node; } this.size++; } public void append(T[] items) { for (T item : items) { this.append(item); } } public void append(List<T> items) { for (T item : items) { this.append(item); } } public void prepend(T item) { Node node = new Node(item, this.head); this.head = node; if (this.tail == null) { this.tail = node; } this.size++; } public void prepend(T[] items) { for (int i = items.length - 1; i >= 0; i--) { this.prepend(items[i]); } } public void prepend(List<T> items) { T[] array = (T[]) new Object[items.size()]; int index = 0; for (T item : items) { array[index++] = item; } this.prepend(array); } public T removeHead() { Node result = this.head; if (this.head != this.tail) { // List contains more than one element. // Make the second element the new head. this.head = this.head.next; this.size--; } else if (this.head != null) { // List contains exactly one element. // Make the list empty. this.head = null; this.tail = null; this.size = 0; } return (result != null) ? result.data : null; } public T removeTail() { Node current = this.head; Node previous = null; // Find the penultimate element on the list. while (current != tail) { previous = current; current = current.next; } // Make it be the new tail of the list. if (previous != null) { previous.next = null; } else { this.head = null; } // And return the old tail. this.tail = previous; this.size--; return (current != null) ? current.data : null; } public void remove(T item) { Node previous = null; Node current = this.head; // Traverse the list looking for the specified item(s). while (current != null) { if (current.data.equals(item)) { // Found one. Remove it by pointing the predecessor's // next field to this node's successor. Note that the // first element on the list does not have a predecessor // so the head of the list needs to be updated instead. if (previous == null) { this.head = current.next; } else { previous.next = current.next; } // Careful about removing the last element of the list. if (this.tail == current) { this.tail = previous; } // And dont forget: this.size--; } else { previous = current; } current = current.next; } } public void reverse() { Node previous = null; Node current = this.head; while (current != null) { Node next = current.next; current.next = previous; previous = current; current = next; } Node temp = this.head; this.head = this.tail; this.tail = temp; } public String toString() { String result = "{"; boolean first = true; for (T item : this) { if (!first) { result += ", "; } result += item; first = false; } result += "}"; return result; } public Iterator<T> iterator() { return new ListIterator(); } private class ListIterator implements Iterator<T> { private Node current; public ListIterator() { this.current = SinglyLinkedList.this.head; } public boolean hasNext() { return this.current != null; } public T next() { T result = this.current.data; this.current = this.current.next; return result; } } }
package my.yrzy.web.common.interceptors; import com.google.common.base.Throwables; import lombok.extern.slf4j.Slf4j; import my.yrzy.common.common.CommonConstants; import my.yrzy.common.util.BaseUser; import my.yrzy.common.util.UserUtil; import my.yrzy.user.model.User; import my.yrzy.user.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Created by yangzefeng on 14/12/18 */ @Slf4j public class LoginInterceptor extends HandlerInterceptorAdapter { @Autowired private UserService userService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{ HttpSession session = request.getSession(false); if(session != null) { Object userId = session.getAttribute(CommonConstants.SESSION_USER_ID); if(userId != null) { try { User user = userService.findById(Long.valueOf(userId.toString())); if(user != null) { UserUtil.putUser(makeBaseUser(user)); return true; } return false; }catch (Exception e) { log.error("fail to find user by id {}, cause:{}", userId, Throwables.getStackTraceAsString(e)); return false; } } } return true; } private BaseUser makeBaseUser(User user) { BaseUser baseUser = new BaseUser(); baseUser.setId(user.getId()); baseUser.setRealName(user.getRealName()); baseUser.setType(user.getType()); baseUser.setStatus(user.getStatus()); return baseUser; } @Override public void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { UserUtil.cleanCurrentUser(); } }
package edu.cb.whitt.rose; import edu.jenks.dist.cb.TestableArray; public class ArrayTester extends Object implements TestableArray { public static void main(String[] args) { ArrayTester t = new ArrayTester(); int[][] arr = {{1, 2}, {2, 1}}; System.out.println(arr.length); System.out.println(t.isLatin(arr)); // int[] ar = {3, 2, 1, 5, 6, 37, 40, 2}; // t.printArr(ar); // t.sort(ar); // t.printArr(ar); } public ArrayTester() { } public int[] getColumn(int[][] arr2D, int c) { int[] arr = new int[arr2D.length]; for (int i = 0; i < arr.length; i++) { arr[i] = arr2D[i][c]; } return arr; } public boolean hasAllValues(int[] arr1, int[] arr2) { for (int one = 0; one < arr1.length; one++) { int check = 0; for (int two = 0; two < arr2.length; two++) { if (arr1[one] == arr2[two]) { check++; } } if (check == 0) { return false; } } return true; } public boolean containsDuplicates(int[] arr) { for (int i = 0; i < arr.length; i++) { int check = 0; for (int k = 0; k < arr.length; k++) { if (arr[i] == arr[k]) { check++; } } if (check > 1) { return true; } } return false; } public int[] sort(int[] arr) { for (int i = 0; i < arr.length; i++) { for (int j = i; j < arr.length; j++) { if (arr[j] < arr[i]) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } return arr; } public boolean isLatin(int[][] square) { //contains duplicates on first row if (containsDuplicates(square[0]) == true) { return false; } //loop of every row for (int i = 0; i < square.length; i++) { //has all values if (hasAllValues(square[0], square[i]) == false) { return false; } } //contains duplicates on first column if (containsDuplicates(getColumn(square, 0)) == true) { return false; } //loop of every row (get column) for (int i = 0; i < square[0].length; i++) { //has all values if (hasAllValues(getColumn(square, 0), getColumn(square, i)) == false) { return false; } } return true; } public boolean areEqual(int[] arr1, int[] arr2) { for (int i = 0; i < arr1.length; i++) { if ((arr1[i] == arr2[i]) == false) { return false; } } return true; } public void printArr(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } public void printTwoArr(int[][] arr) { for (int row = 0; row < arr.length; row++) { for (int col = 0; col < arr[row].length; col++) { System.out.print(arr[row][col] + " "); } System.out.println(""); } } }
package jp.ac.kyushu_u.csce.modeltool.vdmsl; import org.eclipse.osgi.util.NLS; public class Messages extends NLS { private static final String BUNDLE_NAME = "jp.ac.kyushu_u.csce.modeltool.vdmsl.messages"; //$NON-NLS-1$ public static String VdmslConstants_1; public static String VdmslConstants_2; public static String VdmslConstants_3; public static String VdmslConstants_4; public static String VdmslConstants_5; public static String VdmslConstants_6; public static String VdmslModel_0; public static String VdmslModel_1; public static String VdmslModel_2; public static String VdmslModel_3; public static String VdmslModel_4; public static String VdmslModel_5; static { // initialize resource bundle NLS.initializeMessages(BUNDLE_NAME, Messages.class); } private Messages() { } }
package com.example.gtraderprototype.entity; import android.util.Log; import java.util.List; /** * Character class that initialize attributes and behaviors for both the player * and the NPCs */ public class Character { //singleton design pattern: Player.getPlayer() protected String name; protected int pilotSkillPoints; protected int engineerSkillPoints; protected int fighterSkillPoints; protected int traderSkillPoints; protected boolean isPirate; protected int money; protected Ship spaceShip; protected String currentLocationName; /** * Constructor that distribute skill points of the character * * @param name name of the player or NPC * @param pilotPoints skill points of piloting * @param engineerPoints skill points for engineering * @param fighterPoints skill points for fighting * @param traderPoints skill points for trading * @param spaceshiptype assigned spaceship */ public Character (String name, int pilotPoints, int engineerPoints, int fighterPoints, int traderPoints, Ship.ShipType spaceshiptype){ this.name = name; this.pilotSkillPoints = pilotPoints; this.engineerSkillPoints = engineerPoints; this.fighterSkillPoints = fighterPoints; this.traderSkillPoints = traderPoints; this.money = 1000; this.spaceShip = new Ship(Ship.ShipType.GNATT); this.spaceShip.shipType = spaceshiptype; } /** * character */ public Character (){} /** * setting name of a character * @param name name of the character */ public void setName(String name) { this.name = name; } /** * getting name of a character * @return name of character */ public String getName(){ return name; } /** * getting piloting skill point * @return piloting skill point */ public int getPilotSkillPoints(){return pilotSkillPoints;} /** * getting engineering skill point * @return engineering skill point */ public int getEngineerSkillPoints(){return engineerSkillPoints;} /** * getting fighting skill point * @return fighting skill point */ public int getFighterSkillPoints(){return fighterSkillPoints;} /** * getting trading skill point * @return trading skill point */ public int getTraderSkillPoints(){return traderSkillPoints;} /** * setting piloting skill point * @param points pilot skill point */ public void setPilotSkillPoints(int points){this.pilotSkillPoints = points;} /** * setting engineering skill point * @param points engineering skill point */ public void setEngineerSkillPoints(int points){this.engineerSkillPoints = points;} /** * setting fighting skill point * @param points fighting skill point */ public void setFighterSkillPoints(int points){this.fighterSkillPoints = points;} /** * setting trading skill point * @param points trading skill point */ public void setTraderSkillPoints(int points){this.traderSkillPoints = points;} /** * getting ship that this character owns * @return ship */ public Ship getSpaceShip(){ return spaceShip ; } /** * setting ship for the player * @param spaceship the spaceship to set the player to */ public void setShapeShip(Ship spaceship){ this.spaceShip = spaceship;} /** * getting region that this character is at * @return region */ public String getRegionName() { return currentLocationName;} /** * setting region that this character will be at * @param location the location the character is going to */ public void setRegionName(String location) { this.currentLocationName = location; Log.d("GTrader", "Updated location for "+name+" to "+location); } /** * getting the amount of money thic character owns * @return money */ public int getMoney(){ return money;} /** * paying money for an item * @param cost the cost of the item that will be deducted in money */ public void pay(int cost){ money-=cost; } /** * earning money * @param credit the amount of money being paid to character */ public void getPaid(int credit){ money+=credit; } /** * character choose to become a pirate * @param pirate boolean indicating this character is a pirate */ public void setPirate(boolean pirate){ this.isPirate = pirate; } /** * getting information of whether this character is a pirate or not * @return boolean indicating this character is a pirate or not */ public boolean getIsPirate(){ return isPirate; } /** * setting money of the character has * @param m money */ public void setMoney(int m){ money=m; } }