text
stringlengths
10
2.72M
package com.tencent.mm.plugin.game.model; import com.tencent.mm.plugin.game.e.d; import java.util.Iterator; import java.util.LinkedList; public final class k extends j { protected k(String str) { super(str); } public final void aTP() { LinkedList m = j.m(optJSONArray("items")); Iterator it = m.iterator(); while (it.hasNext()) { d dVar = (d) it.next(); dVar.dj(dVar.jLc); } d.S(m); } }
package com.serhii.cryptobook.project.service; import java.security.*; public interface ServiceKey { Key generateSecretKey(String alg, int keysize); KeyPair generateKeyPair(String alg, int keysize); PrivateKey loadPrivateKeyFromFile(); PublicKey loadPublicKeyFromFile(); void savePrivateKeyFromFile(); void savePublicKeyFromFile(); }
package com.socialcard.entity; import java.io.Serializable; /** * Created by Administrator on 14-5-9. */ public class passpro implements Serializable { String username; String problem; String pass; public passpro(){ super(); } public passpro( String username, String problem, String pass){ this.username=username; this.problem=problem; this.pass=pass; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public String getProblem() { return problem; } public void setProblem(String problem) { this.problem = problem; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
package com.skycreateware.android.nanodegree.builditbigger; /** * Created by lalo on 22/12/15. */ import android.content.Context; import android.os.AsyncTask; import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import com.skycreateware.android.nanodegree.builditbigger.backend.myApi.MyApi; import java.io.IOException; /** * Async Task used to retreive jokes from our endpoint. */ class EndpointAsyncTask extends AsyncTask<EndpointAsyncTask.OnJokeReceived, Void, String> { private static MyApi myApiService = null; private OnJokeReceived mListener; public interface OnJokeReceived { public void onJokeReceived(String joke); } @Override protected String doInBackground(EndpointAsyncTask.OnJokeReceived... params) { if (myApiService == null) { MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null) // Setting up local server IP. Set your local server or local server if in // emulator. // - 10.0.2.2 is localhost-s IP address in Android emulator. .setRootUrl("http://192.168.1.65:8080/_ah/api/") // Disable gzip compression on devappserver .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() { @Override public void initialize(AbstractGoogleClientRequest<?> request) throws IOException { request.setDisableGZipContent(true); } }); // end options for devappserver myApiService = builder.build(); } mListener = params[0]; try { return myApiService.tellJoke().execute().getData(); } catch (IOException e) { return e.getMessage(); } } @Override protected void onPostExecute(String s) { super.onPostExecute(s); mListener.onJokeReceived(s); } }
package VEW.Planktonica2; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.Observable; import java.util.Observer; import javax.swing.JEditorPane; import javax.swing.JFileChooser; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextPane; import org.antlr.runtime.RecognitionException; import VEW.Planktonica2.ControllerStructure.SourcePath; import VEW.Planktonica2.ControllerStructure.VEWController; import VEW.Planktonica2.Model.Function; import VEW.Planktonica2.UIComponents.AutocompleteBox; import VEW.Planktonica2.UIComponents.BACONFilter; import VEW.Planktonica2.UIComponents.LatexPreview; import VEW.Planktonica2.UIComponents.SyntaxHighlighter; import VEW.XMLCompiler.ANTLR.ANTLRParser; import VEW.XMLCompiler.ASTNodes.ConstructedASTree; import VEW.XMLCompiler.ASTNodes.SemanticCheckException; import VEW.XMLCompiler.ASTNodes.TreeWalkerException; public class EditorPanel extends JPanel implements Observer { private VEWController controller; private static final long serialVersionUID = 960655324263522980L; private JTextPane syntax; private LatexPreview preview; private SyntaxHighlighter syntax_highlighter; private AutocompleteBox auto_complete; private JEditorPane error_log; private String current_source; // Open/save components final static JFileChooser file_chooser = new JFileChooser(); public EditorPanel (VEWController controller) { super(); this.controller = controller; this.controller.addObserver(this); initialise(); } @Override public void update(Observable o, Object arg) { if (arg instanceof SourcePath) { SourcePath p = (SourcePath) arg; open_source_file(p.getPath()); } } public void initialise() { this.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.fill = GridBagConstraints.BOTH; c.weightx = 0.5; c.weighty = 0.75; c.gridx = 0; c.gridy = 0; syntax = new JTextPane(); this.syntax.setEnabled(false); final JPanel no_wrap_syntax = new JPanel(new BorderLayout()); no_wrap_syntax.add(syntax); JScrollPane scroll_pane_syntax = new JScrollPane(no_wrap_syntax); scroll_pane_syntax.setPreferredSize(new Dimension(300,350)); syntax_highlighter = new SyntaxHighlighter(); this.add(scroll_pane_syntax, c); c.gridx = 1; c.gridy = 0; preview = new LatexPreview(); final JPanel no_wrap_preview = new JPanel(new BorderLayout()); no_wrap_preview.add(preview,BorderLayout.NORTH); JScrollPane scroll_pane_preview = new JScrollPane(no_wrap_preview); scroll_pane_preview.setPreferredSize(new Dimension(300,350)); this.add(scroll_pane_preview, c); c.weighty = 0.25; c.gridwidth = 2; c.gridx = 0; c.gridy = 1; error_log = new JEditorPane(); JScrollPane scroll_pane_errors = new JScrollPane(error_log); scroll_pane_errors.setPreferredSize(new Dimension(606,125)); this.add(scroll_pane_errors, c); syntax.addKeyListener(new TypingListener(this)); Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 12); syntax.setFont(font); syntax.setContentType("text/html"); syntax.setText("<html><PRE></PRE></html>"); auto_complete = new AutocompleteBox(syntax,controller); error_log.setEditable(false); error_log.setFont(font); error_log.setContentType("text/html"); error_log.setText("<html><PRE></PRE></html>"); //this.add(scroll_pane_syntax); //this.add(scroll_pane_preview); //this.add(scroll_pane_errors); javax.swing.filechooser.FileFilter f = new BACONFilter(); file_chooser.setFileFilter(f); this.setSize((850), (600)); this.setVisible(true); preview.update_preview("pre"); preview.setVisible(false); } private void highlight_syntax() { int pos = syntax.getCaret().getDot(); syntax.setText(syntax_highlighter.highlight(syntax.getText())); syntax.getCaret().setDot(pos); } public void compile() { if (this.current_source == null) return; syntax_highlighter.clear_flags(); ANTLRParser p = new ANTLRParser (syntax_highlighter.getPlainText(syntax.getText())); try { ConstructedASTree ct = p.getAST(); //ct.getTree().check(); if (ct.getExceptions().isEmpty()) { if (ct.hasWarnings()) { String errors = "<html><PRE>Warnings in source file:\n"; errors = format_warnings(ct, errors); errors += "\nCheck succeeded!</PRE></html>"; error_log.setText(errors); } else { error_log.setText("<html><PRE>Check succeeded!</PRE></html>"); } String latex = "\\begin{array}{lr}"; latex += ct.getTree().generateLatex(); latex += "\\end{array}"; preview.setVisible(true); preview.update_preview(latex); System.out.println(ct.getTree().generateXML()); } else { String errors = "<html><PRE>Compilation errors occurred:\n"; errors = format_errors(ct, errors); errors += "Compilation aborted!</PRE></html>"; error_log.setText(errors); } highlight_syntax(); } catch (RecognitionException e) { System.out.println("RECOGNITION EXCEPTION"); e.printStackTrace(); } } private String format_errors(ConstructedASTree ct, String errors) { errors += "<font color=#FF0000>"; for (Exception t : ct.getExceptions()) { syntax_highlighter.flag_line(t); if (t instanceof TreeWalkerException) { TreeWalkerException twe = (TreeWalkerException) t; errors += twe.getError() + "\n"; } else if (t instanceof SemanticCheckException) { SemanticCheckException sce = (SemanticCheckException) t; errors += sce.getError() + "\n"; } else { errors += "Unknown error\n"; } } errors += "</font>\n"; errors = format_warnings(ct, errors); return errors; } private String format_warnings(ConstructedASTree ct, String errors) { errors += "<font color=#FF9900>"; for (String s : ct.getWarnings()) { errors += "Warning: " + s + "\n"; } errors += "</font>"; return errors; } public void check() { if (this.current_source == null) return; syntax_highlighter.clear_flags(); ANTLRParser p = new ANTLRParser (syntax_highlighter.getPlainText(syntax.getText())); try { ConstructedASTree ct = p.getAST(); if (ct.getExceptions().isEmpty()) ct.getTree().check(controller.getCurrentlySelectedFunction().getParent(), ct); if (ct.getExceptions().isEmpty()) { if (ct.hasWarnings()) { String errors = "<html><PRE>Warnings in source file:\n"; errors = format_warnings(ct, errors); errors += "\nCheck succeeded!</PRE></html>"; error_log.setText(errors); } else { error_log.setText("<html><PRE>Check succeeded!</PRE></html>"); } String latex = "\\begin{array}{lr}"; latex += ct.getTree().generateLatex(); latex += "\\end{array}"; preview.setVisible(true); preview.update_preview(latex); } else { String errors = "<html><PRE>Errors in source file:\n"; errors = format_errors(ct, errors); errors += "</PRE></html>"; error_log.setText(errors); } highlight_syntax(); } catch (RecognitionException e) { System.out.println("RECOGNITION EXCEPTION"); e.printStackTrace(); } } public void preview() { if (this.current_source == null) return; ANTLRParser p = new ANTLRParser (syntax_highlighter.getPlainText(syntax.getText())); //System.out.println(syntax_highlighter.getPlainText(syntax.getText())); try { ConstructedASTree ct = p.getAST(); if (ct.getTree() != null) { String latex = "\\begin{array}{lr}"; latex += ct.getTree().generateLatex(); latex += "\\end{array}"; preview.setVisible(true); preview.update_preview(latex); }/* if (ct.getExceptions().isEmpty()) { error_log.setText(""); } else { String errors = "<html><PRE>Compilation errors occurred:\n"; errors += "<font color=#FF0000>"; for (TreeWalkerException t : ct.getExceptions()) { syntax_highlighter.flag_line(t); errors += t.getError() + "\n"; } errors += "</font>"; errors += "</PRE></html>"; error_log.setText(errors); }*/ //highlight_syntax(); } catch (RecognitionException e) { System.out.println("RECOGNITION EXCEPTION"); e.printStackTrace(); } } public void show_autocomplete(KeyEvent e) { auto_complete.show_suggestions(e); } public void hide_autocomplete() { auto_complete.hide_suggestions(); } public String current_autocomplete() { return auto_complete.getCurrent_word(); } public boolean caret_in_comment() { int pos = syntax.getCaretPosition() - 2; char[] chars = syntax_highlighter.getPlainText(syntax.getText()).toCharArray(); if (pos >= chars.length) return false; for (int i = pos; i > 0; i--) { if (chars[i] == '\n') return false; if (chars[i] == '/' && chars[i-1] == '/') return true; } return false; } public int get_caret_line() { int newlines = 1; int pos = syntax.getCaretPosition() - 2; char[] chars = syntax_highlighter.getPlainText(syntax.getText()).toCharArray(); for (int i = pos; i > 0; i--) { if (chars[i] == '\n') newlines++; } return newlines; } private boolean space_before_caret() { int pos = syntax.getCaretPosition() - 3; if (pos <= 0 || pos >= syntax_highlighter.getPlainText(syntax.getText()).length()) return true; char c = syntax_highlighter.getPlainText(syntax.getText()).charAt(pos); return !Character.isLetterOrDigit(c); } public void open_source_file(String filePath) { try { FileInputStream fstream = new FileInputStream(filePath); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String source = "<html><head></head><PRE>", line = ""; String file_text = ""; while ((line = br.readLine()) != null) { file_text += (line + "\n"); } in.close(); file_text = file_text.replaceAll("<","&lt;"); file_text = file_text.replaceAll(">","&gt;"); file_text = file_text.replaceAll("\"","&quot;"); source += file_text; source += "</PRE></html>"; syntax.setEnabled(true); preview.setVisible(false); syntax.setText(source); highlight_syntax(); syntax.setCaretPosition(0); this.current_source = filePath; } catch (Exception e) { syntax.setText("<html><head></head><PRE>Could not find source file " + filePath + "</PRE></html>"); } } public void save() { Function f = controller.getCurrentlySelectedFunction(); if (f == null) return; String file_path = f.getSource_code(); file_path += f.getParent().getName(); file_path += "\\"; file_path += f.getName(); file_path += ".bacon"; try { FileOutputStream fstream = new FileOutputStream(file_path); PrintStream out = new PrintStream(fstream); out.print(syntax_highlighter.getPlainText(syntax.getText())); out.close(); error_log.setText("Save successful"); } catch (Exception e) { error_log.setText("<html><head></head><PRE>Error when saving to file " + file_path + "</PRE></html>"); } } public void clear() { this.current_source = null; this.syntax.setEnabled(false); this.syntax.setText("<html><PRE></PRE></html>"); this.preview.setVisible(false); this.error_log.setText("<html><PRE></PRE></html>"); } /* static class CompileListener implements ActionListener { private EditorPanel parent; public CompileListener(EditorPanel edit) { parent = edit; } public void actionPerformed(ActionEvent event) { syntax_highlighter.clear_flags(); ANTLRParser p = new ANTLRParser (syntax_highlighter.getPlainText(syntax.getText())); try { ConstructedASTree ct = p.getAST(); //ct.getTree().check(); if (ct.getExceptions().isEmpty()) { String latex = "\\begin{array}{lr}"; latex += ct.getTree().generateLatex(); latex += "\\end{array}"; preview.setVisible(true); preview.update_preview(latex); System.out.println(ct.getTree().generateXML()); error_log.setText("<html><PRE>Compilation succeeded!</PRE></html>"); } else { String errors = "<html><PRE>Compilation errors occurred:\n"; errors += "<font color=#FF0000>"; for (Exception t : ct.getExceptions()) { syntax_highlighter.flag_line(t); if (t instanceof TreeWalkerException) { TreeWalkerException twe = (TreeWalkerException) t; errors += twe.getError() + "\n"; } else if (t instanceof SemanticCheckException) { SemanticCheckException sce = (SemanticCheckException) t; errors += sce.getError() + "\n"; } else { errors += "Unknown error\n"; } } errors += "</font>"; errors += "\nCompilation aborted!</PRE></html>"; error_log.setText(errors); } parent.highlight_syntax(); } catch (RecognitionException e) { System.out.println("RECOGNITION EXCEPTION"); e.printStackTrace(); } } }*/ /* static class OpenListener implements ActionListener { private JPanel parent; public OpenListener(JPanel editorPanel) { parent = editorPanel; } public void actionPerformed(ActionEvent event) { int choice = file_chooser.showOpenDialog(parent); if (choice == JFileChooser.APPROVE_OPTION) { File file = file_chooser.getSelectedFile(); String fpath = file.getAbsolutePath(); try { FileInputStream fstream = new FileInputStream(fpath); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String file_text = "<html><head></head><PRE>", line = ""; while ((line = br.readLine()) != null) { file_text += (line + "\n"); } in.close(); file_text += "</PRE></html>"; syntax.setText(file_text); highlight_syntax(); } catch (Exception e) { syntax.setText("Could not find the file!"); } } } }*/ /* static class SaveListener implements ActionListener { private JPanel parent; public SaveListener(JPanel editorPanel) { parent = editorPanel; } public void actionPerformed(ActionEvent event) { int choice = file_chooser.showSaveDialog(parent); if (choice == JFileChooser.APPROVE_OPTION) { File file = file_chooser.getSelectedFile(); String fpath = file.getAbsolutePath() + ".bacon"; // TODO - check for overwrites, extensions etc. try { FileOutputStream fstream = new FileOutputStream(fpath); PrintStream out = new PrintStream(fstream); out.print(syntax_highlighter.getPlainText(syntax.getText())); out.close(); } catch (Exception e) { System.out.println("Save failed!"); } } } }*/ class PreviewListener implements ActionListener { EditorPanel parent; public PreviewListener(EditorPanel edit) { parent = edit; } public void actionPerformed(ActionEvent event) { parent.preview(); } } class TypingListener implements KeyListener { private EditorPanel parent; public TypingListener(EditorPanel edit) { parent = edit; } @Override public void keyPressed(KeyEvent e) {} @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SHIFT || e.getKeyCode() == KeyEvent.VK_CONTROL || e.getKeyCode() == KeyEvent.VK_ALT) // Ignore them return; if (!parent.caret_in_comment() && (!parent.current_autocomplete().equals("") || parent.space_before_caret())) { parent.show_autocomplete(e); } else { parent.hide_autocomplete(); } //System.out.println(space_before_caret()); if (e.getKeyCode() == KeyEvent.VK_ENTER) { // Parse text and check for errors? parent.preview(); } else if (e.getKeyCode() != KeyEvent.VK_BACK_SPACE && e.getKeyCode() != KeyEvent.VK_UP && e.getKeyCode() != KeyEvent.VK_DOWN && e.getKeyCode() != KeyEvent.VK_RIGHT && e.getKeyCode() != KeyEvent.VK_LEFT) { // Update the syntax pane with highlighting, ensuring caret // position remains the same parent.highlight_syntax(); } } @Override public void keyTyped(KeyEvent e) {} } }
package com.example.android.miwok; import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; /** * Class which represents the business logic for the ColorsFragment of the MainActivity. * * * <p> * Author: William Walsh * Version: 2.0 (Fragments) * Date: 18-05-18 */ public class ColorsFragment extends Fragment { // AudioManager responsible for getting and abandoning AudioFocus private AudioManager audioManager; // MediaPlayer which can play mp3 and mp4 private MediaPlayer mediaPlayer; public ColorsFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.activity_list_view, container, false); // Arraylist of words to display in list. final ArrayList<Word> colors = new ArrayList<Word>(); // Each word has its own English String resource, Miwok language String resource, Image resource Id & Sound resource Id. // Adding color words to colors ArrayList colors.add(new Word(getString(R.string.red), getString(R.string.red_miwok), R.drawable.color_red, R.raw.color_red)); colors.add(new Word(getString(R.string.green), getString(R.string.green_miwok), R.drawable.color_green, R.raw.color_green)); colors.add(new Word(getString(R.string.brown), getString(R.string.brown_miwok), R.drawable.color_brown, R.raw.color_brown)); colors.add(new Word(getString(R.string.gray), getString(R.string.gray_miwok), R.drawable.color_gray, R.raw.color_gray)); colors.add(new Word(getString(R.string.black), getString(R.string.black_miwok), R.drawable.color_black, R.raw.color_black)); colors.add(new Word(getString(R.string.white), getString(R.string.white_miwok), R.drawable.color_white, R.raw.color_white)); colors.add(new Word(getString(R.string.dusty_yellow), getString(R.string.dusty_yellow_miwok), R.drawable.color_dusty_yellow)); colors.add(new Word(getString(R.string.mustard_yellow), getString(R.string.mustard_yellow_miwok), R.drawable.color_mustard_yellow, R.raw.color_mustard_yellow)); // Create ArrayAdapter Point it to the activity context and colors ArrayList WordAdapter colorAdapter = new WordAdapter(getActivity(), colors, R.color.category_colors); // Get ListView.xml reference ListView listView = (ListView) rootView.findViewById(R.id.list); // Associate adapter to ListView listView.setAdapter(colorAdapter); // Create click listener for all the Items in the ListView. listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { // Get AudioManager audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE); // Request AudioFocus using the local audioManager instance // pass in the AudioFocusChangeListener, Stream type and AudioFocus Type int result = audioManager.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE); // If the AudioFocus request is granted if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { // Release mediaPlayer before playing another song releaseMediaPlayer(); // Get the data associated with the list element selected using the position index Word word = colors.get(position); // Create MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(), word.getMusicRef()); // Set the onCompletionListener mediaPlayer.setOnCompletionListener(mpCompletionListener); // start playing audio mediaPlayer.start(); } } }); return rootView; } @Override public void onStop() { super.onStop(); // When the App goes into the Stopped State release the MediaPlayer resource releaseMediaPlayer(); } // Listener which listens for when media playback completes private MediaPlayer.OnCompletionListener mpCompletionListener = new MediaPlayer.OnCompletionListener() { // Release Media Player resource if finished playing the sound. @Override public void onCompletion(MediaPlayer mp) { releaseMediaPlayer(); } }; // Listener which listens for an AudioFocusChange event public AudioManager.OnAudioFocusChangeListener afChangeListener = new AudioManager.OnAudioFocusChangeListener() { // Interface method to be implemented to deal with changes in AudioFocus @Override public void onAudioFocusChange(int i) { // If the AudioFocus is lost temporarily or when its lost yet ducking is allowed if (i == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT || i == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) { // Pause the media player mediaPlayer.pause(); // Change playback to beginning mediaPlayer.seekTo(0); } else if (i == AudioManager.AUDIOFOCUS_GAIN) { // If you gain the audiofocus // Resume playing music mediaPlayer.start(); } else if (i == AudioManager.AUDIOFOCUS_LOSS) { // When audioFocus is lost long term // Stop Audio playback mediaPlayer.stop(); // Release the MediaPlayer resource releaseMediaPlayer(); } } }; /** * Clean up the media player by releasing associated resources. */ private final void releaseMediaPlayer() { // If the media player is not null, then it may be currently playing a sound. if (mediaPlayer != null) { // Regardless of the current state of the media player, release its resources // because we no longer need it. mediaPlayer.release(); // Set the media player back to null. For our code, we've decided that // setting the media player to null is an easy way to tell that the media player // is not configured to play an audio file at the moment. mediaPlayer = null; // Release audioFocus when playback is complete audioManager.abandonAudioFocus(afChangeListener); } } }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.components.devtools_bridge.apiary; import android.util.JsonReader; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.chromium.components.devtools_bridge.RTCConfiguration; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Client for fetching TURN configuration form a demo server. */ public final class TurnConfigClient { private static final String URL = "http://computeengineondemand.appspot.com/turn?username=28230128&key=4080218913"; private static final String STUN_URL = "stun.l.google.com:19302"; private final HttpClient mHttpClient; TurnConfigClient(HttpClient httpClient) { mHttpClient = httpClient; } public RTCConfiguration fetch() throws IOException { return mHttpClient.execute( new HttpGet(URL), new ConfigResponseHandler()); } private class ConfigResponseHandler extends JsonResponseHandler<RTCConfiguration> { public RTCConfiguration readResponse(JsonReader reader) throws IOException { List<String> uris = null; String username = null; String password = null; reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if ("username".equals(name)) { username = reader.nextString(); } else if ("password".equals(name)) { password = reader.nextString(); } else if ("uris".equals(name)) { uris = readStringList(reader); } else { reader.skipValue(); } } reader.endObject(); RTCConfiguration.Builder builder = new RTCConfiguration.Builder(); builder.addIceServer(STUN_URL); for (String uri : uris) { builder.addIceServer(uri, username, password); } return builder.build(); } } private List<String> readStringList(JsonReader reader) throws IOException { ArrayList<String> result = new ArrayList<String>(); reader.beginArray(); while (reader.hasNext()) { result.add(reader.nextString()); } reader.endArray(); return result; } }
package com.omdbapi.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.NetworkImageView; import com.omdbapi.R; import com.omdbapi.async.CustomVolleyRequest; import com.omdbapi.model.OmdbMovie; import java.util.List; /** * * Created by agrip on 28-Dec-16. */ public class OmdbMovieAdapter extends RecyclerView.Adapter<OmdbMovieAdapter.ViewHolder> { private List<OmdbMovie> mDataset; private ImageLoader imgLoader; // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder public static class ViewHolder extends RecyclerView.ViewHolder { // each data item is just a string in this case private TextView movieNameTextView; private NetworkImageView posterImageView; private TextView plotTextView; private TextView directorTextViewTextView; private TextView actorsTextViewTextView; private TextView genreTextViewTextView; public ViewHolder(View v) { super(v); movieNameTextView = (TextView) v.findViewById( R.id.movie_name_textView ); posterImageView = (NetworkImageView) v.findViewById( R.id.poster_imageView ); plotTextView = (TextView) v.findViewById( R.id.plot_textView ); directorTextViewTextView = (TextView) v.findViewById( R.id.director_textView_textView ); actorsTextViewTextView = (TextView) v.findViewById( R.id.actors_textView_textView ); genreTextViewTextView = (TextView) v.findViewById( R.id.genre_textView_textView ); } } // Provide a suitable constructor (depends on the kind of dataset) public OmdbMovieAdapter(List<OmdbMovie> myDataset, Context context) { mDataset = myDataset; imgLoader = CustomVolleyRequest.getInstance(context.getApplicationContext()).getImageLoader(); } // Create new views (invoked by the layout manager) @Override public OmdbMovieAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_complete_item_layout, parent, false); // set the view's size, margins, paddings and layout parameters return new ViewHolder(v); } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(final ViewHolder holder, int position) { // - get element from your dataset at this position // - replace the contents of the view with that element final OmdbMovie movie = mDataset.get(position); final Context context = holder.posterImageView.getContext(); holder.movieNameTextView.setText(context.getString(R.string.movie_name_year, movie.getTitle(), movie.getYear())); holder.plotTextView.setText(movie.getPlot()); holder.directorTextViewTextView.setText(context.getString(R.string.director_colon_x, movie.getDirector())); holder.actorsTextViewTextView.setText(context.getString(R.string.actors_colon_x, movie.getActors())); holder.genreTextViewTextView.setText(context.getString(R.string.genre_colon_x, movie.getGenre())); imgLoader.get(movie.getPoster(), ImageLoader.getImageListener(holder.posterImageView, R.drawable.no_image, R.drawable.no_image)); holder.posterImageView.setImageUrl(movie.getPoster(), imgLoader); holder.posterImageView.setDefaultImageResId(R.drawable.no_image); holder.posterImageView.setErrorImageResId(R.drawable.no_image); } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return mDataset.size(); } }
package com.smxknife.rxjava2.demo06; import io.reactivex.Notification; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; /** * @author smxknife * 2020/5/15 */ public class JustDo { public static void main(String[] args) { Observable.just("Hello world") .doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(Disposable disposable) throws Exception { Log.log("doOnSubscribe | " + disposable.toString()); } }) .doOnNext(new Consumer<String>() { @Override public void accept(String s) throws Exception { Log.log("doOnNext | " + s); } }) .doAfterNext(new Consumer<String>() { @Override public void accept(String s) throws Exception { Log.log("doAfterNext | " + s); } }) .doAfterTerminate(new Action() { @Override public void run() throws Exception { Log.log("doAfterTerminate | "); } }) .doFinally(new Action() { @Override public void run() throws Exception { Log.log("doFinally"); } }) .doOnComplete(new Action() { @Override public void run() throws Exception { Log.log("doOnComplete"); } }) .doOnDispose(new Action() { @Override public void run() throws Exception { Log.log("doOnDispose"); } }) .doOnEach(new Observer<String>() { @Override public void onSubscribe(Disposable disposable) { Log.log("doOnEach onSubscribe | " + disposable); } @Override public void onNext(String s) { Log.log("doOnEach onNext | " + s); } @Override public void onError(Throwable throwable) { Log.log("doOnEach onError | " + throwable.getMessage()); } @Override public void onComplete() { Log.log("doOnEach onComplete"); } }) .doOnEach(new Consumer<Notification<String>>() { @Override public void accept(Notification<String> stringNotification) throws Exception { Log.log("doOnEach Consumer | " + stringNotification.getValue()); } }) .doOnLifecycle(new Consumer<Disposable>() { @Override public void accept(Disposable disposable) throws Exception { Log.log("doOnLifecycle accept | " + disposable); } }, new Action() { @Override public void run() throws Exception { Log.log("doOnLifecycle Action"); } }) .subscribe(new Consumer<String>() { @Override public void accept(String s) throws Exception { Log.log("onNext | "); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { Log.log("onError | "); } }, new Action() { @Override public void run() throws Exception { Log.log("onComplete | "); } }, new Consumer<Disposable>() { @Override public void accept(Disposable disposable) throws Exception { Log.log("onSubscribe | "); } }); } }
package com.devskiller.sample; public interface StringProcessor { String abbreviate(String input, int maxLength); }
package org.buaa.ly.MyCar.logic.impl; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.buaa.ly.MyCar.entity.VehicleInfo; import org.buaa.ly.MyCar.http.dto.VehicleInfoCostDTO; import org.buaa.ly.MyCar.internal.VehicleInfoCost; import org.buaa.ly.MyCar.logic.VehicleInfoCostLogic; import org.buaa.ly.MyCar.repository.VehicleInfoRepository; import org.buaa.ly.MyCar.utils.BeanCopyUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.data.jpa.repository.Modifying; import org.springframework.stereotype.Component; import java.util.List; @Component("vehicleInfoCostLogic") @Slf4j @PropertySource("classpath:default-value.properties") public class VehicleInfoCostLogicImpl implements VehicleInfoCostLogic { @Value("${vehicle.info.cost.insurance}") private String insurance; @Value("${vehicle.info.cost.day_cost}") private int cost; @Value("${vehicle.info.cost.discount}") private int discount; private VehicleInfoRepository vehicleInfoRepository; @Autowired void setVehicleInfoRepository(VehicleInfoRepository vehicleInfoRepository) { this.vehicleInfoRepository = vehicleInfoRepository; } private List<Integer> parseInsurance() { String[] list = insurance.split(","); List<Integer> ins = Lists.newArrayList(list.length); for ( String s : list ) { ins.add(Integer.parseInt(s)); } return ins; } @Override public VehicleInfoCost find(int id) { VehicleInfo vehicleInfo = vehicleInfoRepository.findById(id); if ( vehicleInfo == null ) return null; if ( vehicleInfo.getCost() == null ) { return update(id, VehicleInfoCostDTO.build(10000, 100, null)); } else { return JSONObject.parseObject(vehicleInfo.getCost(), VehicleInfoCost.class); } } @Override public VehicleInfoCost insert(int id, VehicleInfoCost vehicleInfoCost) { return update(id, vehicleInfoCost); } @Modifying @Override public VehicleInfoCost update(int id, VehicleInfoCost vehicleInfoCost) { VehicleInfo vehicleInfo = vehicleInfoRepository.findById(id); if ( vehicleInfo == null ) return null; if ( vehicleInfo.getCost() == null ) { vehicleInfo.setCost(JSONObject.toJSONString(vehicleInfoCost)); return vehicleInfoCost; } else { VehicleInfoCost v = JSONObject.parseObject(vehicleInfo.getCost(), VehicleInfoCost.class); BeanCopyUtils.copyPropertiesIgnoreNull(vehicleInfoCost, v); vehicleInfo.setCost(JSONObject.toJSONString(v)); return v; } } @Override public VehicleInfoCostDTO defaultCost() { return VehicleInfoCostDTO.build(cost, discount, parseInsurance()); } }
package com.gym.appointments.Model; import java.util.List; public class Coordenada { int coordenadaAlturaInicial; int coordenadaAnchoInicial; int coordenadaAlturaFinal; int coordenadaAnchoFinal; int longitud; List<Par> pares; Ubicacion ubicacion; public Coordenada() { } public Coordenada( int coordenadaAlturaInicial, int coordenadaAnchoInicial, int coordenadaAlturaFinal, int coordenadaAnchoFinal, int longitud, List<Par> pares, Ubicacion ubicacion) { this.coordenadaAlturaInicial = coordenadaAlturaInicial; this.coordenadaAnchoInicial = coordenadaAnchoInicial; this.coordenadaAlturaFinal = coordenadaAlturaFinal; this.coordenadaAnchoFinal = coordenadaAnchoFinal; this.longitud = longitud; this.pares = pares; this.ubicacion = ubicacion; } public int getCoordenadaAnchoInicial() { return coordenadaAnchoInicial; } public void setCoordenadaAnchoInicial(int coordenadaAnchoInicial) { this.coordenadaAnchoInicial = coordenadaAnchoInicial; } public int getCoordenadaAlturaInicial() { return coordenadaAlturaInicial; } public void setCoordenadaAlturaInicial(int coordenadaAlturaInicial) { this.coordenadaAlturaInicial = coordenadaAlturaInicial; } public int getCoordenadaAnchoFinal() { return coordenadaAnchoFinal; } public void setCoordenadaAnchoFinal(int coordenadaAnchoFinal) { this.coordenadaAnchoFinal = coordenadaAnchoFinal; } public int getCoordenadaAlturaFinal() { return coordenadaAlturaFinal; } public void setCoordenadaAlturaFinal(int coordenadaAlturaFinal) { this.coordenadaAlturaFinal = coordenadaAlturaFinal; } public int getLongitud() { return longitud; } public void setLongitud(int longitud) { this.longitud = longitud; } public List<Par> getPares() { return pares; } public void setPares(List<Par> pares) { this.pares = pares; } public Ubicacion getUbicacion() { return ubicacion; } public void setUbicacion(Ubicacion ubicacion) { this.ubicacion = ubicacion; } }
import java.io.File; import javax.sound.sampled.*; public class SoundMachine extends Thread{ private File sf; private final int EXTERNAL_BUFFER_SIZE = 524288; private SourceDataLine line = null; private AudioInputStream ais = null; public SoundMachine(String path) { try { sf = new File(path); } catch (Exception e) { System.out.println("No Wave file found at :" + path); } init(); } public void init() { long now = System.currentTimeMillis(); if (!sf.exists()) { System.out.println("Wave file not found: " + sf.getName()); return; } try { ais = AudioSystem.getAudioInputStream(sf); } catch (Exception e) { e.printStackTrace(); return; } AudioFormat format = ais.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); try { line = (SourceDataLine) AudioSystem.getLine(info); line.open(format); } catch (Exception e) { e.printStackTrace(); return; } FloatControl gain = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN); gain.setValue(gain.getMaximum()); } @Override public void run() { line.start(); int nBytesRead = 0; byte[] abData = new byte[EXTERNAL_BUFFER_SIZE]; try { while(nBytesRead != -1) { nBytesRead = ais.read(abData, 0, abData.length); if (nBytesRead >= 0) { line.write(abData, 0, nBytesRead); } } } catch (Exception e) { e.printStackTrace(); return; } finally { line.drain(); line.close(); } } }
package cco; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Transient; import lombok.Getter; import lombok.Setter; @Entity public class CcoImagem { @Id @Column(name = "ID_IMAGEM") @GeneratedValue private @Getter @Setter Long id; @Column(name = "SEQUENCIAL") private @Getter @Setter String sequencial; @Column(name = "IMAGEM_PATH") private @Getter @Setter String imagemPath; @Column(name = "TIPO_FOCO") private @Getter @Setter String tipoFoco; @ManyToOne @JoinColumn(name = "FLUXO_ID") private @Getter @Setter CcoFluxo fluxo; @Transient private @Getter @Setter byte[] bytes; public CcoImagem() { } public CcoImagem(String sequencial) { this.sequencial = sequencial; } }
/* * LumaQQ - Java QQ Client * * Copyright (C) 2004 luma <stubma@163.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.tsinghua.lumaqq.qq; import java.util.concurrent.Callable; import edu.tsinghua.lumaqq.qq.events.PacketEvent; import edu.tsinghua.lumaqq.qq.packets.InPacket; /** * 触发PacketEvent * * @author luma */ public class PacketEventTrigger<T> implements Callable<T> { private QQClient client; public PacketEventTrigger(QQClient client) { this.client = client; } /* (non-Javadoc) * @see java.util.concurrent.Callable#call() */ public T call() throws Exception { InPacket packet = client.removeIncomingPacket(); while(packet != null) { // 通知所有包事件监听器 PacketEvent e = new PacketEvent(packet); client.firePacketArrivedEvent(e); // 得到下一个包 packet = client.removeIncomingPacket(); } return null; } }
package LeetCodeUtils.Contest.C2021_04_04; import LeetCodeUtils.MyPrint; import org.junit.Test; import java.util.Arrays; import java.util.*; import java.util.PriorityQueue; public class Third { @Test public void test() { //System.out.println(find(new int[]{1,2,3,4,5,7}, 5, 0, 5)); System.out.println(minAbsoluteSumDiff(new int[]{1,10,4,4,2,7}, new int[]{9,3,5,1,7,4})); } public int minAbsoluteSumDiff(int[] nums1, int[] nums2) { int[] diff = new int[nums1.length]; int tem = 0, max = 0; for (int i = 0; i < nums1.length; ++i) { int val = nums1[i] - nums2[i]; diff[i] = val < 0 ? -val : val; tem += diff[i]; tem %= (1e9 + 7); } Arrays.sort(nums1); for (int i = 0; i < nums1.length; ++i) { int val = nums1[find(nums1, nums2[i], 0, nums1.length - 1)] - nums2[i]; val = val < 0 ? -val : val; val = diff[i] - val; max = max > val ? max : val; } return (int) ((tem - max) % (1e9 + 7)); } public int find(int[] arr, int target, int l, int r) { if (l == r) return l; if (r - l == 1) { if (arr[r] - target < target - arr[l]) return r; else return l; } int mid = (l + r) / 2; if (arr[mid] == target) return mid; else if (arr[mid] > target) return find(arr, target, l, mid); else return find(arr, target, mid, r); } }
package solution; import java.util.LinkedList; import java.util.Queue; /** * User: jieyu * Date: 12/25/16. */ public class SurroundedRegions130 { public void solve(char[][] board) { if (board.length == 0) return; fill(board); for (int y = 0; y < board.length; ++y) { for (int x = 0; x < board[0].length; ++x) { if (board[y][x] == '#') board[y][x] = 'O'; else if (board[y][x] == 'O') board[y][x] = 'X'; } } } private void fill(char[][] board) { Queue<Integer> queue = new LinkedList<>(); int key = board[0].length; for (int x = 0; x < board[0].length; ++x) { if (board[0][x] == 'O') { queue.add(x); board[0][x] = '#'; } if (board[board.length - 1][x] == 'O') { queue.add((board.length - 1) * key + x); board[board.length - 1][x] = '#'; } } for (int y = 0; y < board.length; ++y) { if (board[y][0] == 'O') { queue.add(y * key); board[y][0] = '#'; } if (board[y][board[0].length - 1] == 'O') { queue.add(y * key + (board[0].length - 1)); board[y][board[0].length - 1] = '#'; } } while (!queue.isEmpty()) { int temp = queue.poll(); int x = temp % key; int y = temp / key; if (x - 1 >= 0 && board[y][x - 1] == 'O') { queue.add(y * key + x - 1); board[y][x - 1] = '#'; } if (y - 1 >= 0 && board[y - 1][x] == 'O') { queue.add((y - 1) * key + x); board[y - 1][x] = '#'; } if (x + 1 < board[0].length && board[y][x + 1] == 'O') { queue.add(y * key + x + 1); board[y][x + 1] = '#'; } if (y + 1 < board.length && board[y + 1][x] == 'O') { queue.add((y + 1) * key + x); board[y + 1][x] = '#'; } } } }
package jp.noxi.collection; import java.math.BigDecimal; import javax.annotation.Nonnull; public interface Numeric extends Comparable<Numeric> { /** * Returns the value of the specified number as an <code>int</code>. This may involve rounding or truncation. * * @return the numeric value represented by this object after conversion to type <code>int</code>. */ int intValue(); /** * Returns the value of the specified number as a <code>long</code>. This may involve rounding or truncation. * * @return the numeric value represented by this object after conversion to type <code>long</code>. */ long longValue(); /** * Returns the value of the specified number as a <code>float</code>. This may involve rounding. * * @return the numeric value represented by this object after conversion to type <code>float</code>. */ float floatValue(); /** * Returns the value of the specified number as a <code>double</code>. This may involve rounding. * * @return the numeric value represented by this object after conversion to type <code>double</code>. */ double doubleValue(); /** * Returns the value of the specified number as a <code>BigDecimal</code>. * * @return the numeric value represented by this object after conversion to type <code>BigDecimal</code>. */ @Nonnull BigDecimal decimalValue(); }
package com.TokChatBackend.daos; import com.TokChatBackend.models.ProfilePicture; public interface ProfilePictureDao { void uploadProfilePicture(ProfilePicture profilePicture); ProfilePicture getImage(String email); }
package unalcol.algorithm; import unalcol.math.function.Function; import unalcol.tracer.Tracer; /** * <p>Abstract Function defined as a Thread</p> * <p> * <p>Copyright: Copyright (c) 2010</p> * * @author Jonatan Gomez Perdomo * @version 1.0 */ public abstract class ThreadFunction<S, T> implements Function<S, T> { /** * Flag used for determining if the function was stopped or not */ protected boolean continueFlag = true; /** * Stops the function computation */ public void stop() { continueFlag = false; } /** * Determines if the function was stopped or not * * @return true if the function was stopped, false otherwise */ public boolean stopped() { return continueFlag; } /** * Adds the given object to the set of tracers defined for that object */ public void addToTrace(Object obj) { Tracer.trace(this, obj); } }
package com.elvarg.world.entity.updating; import java.util.Iterator; import com.elvarg.net.packet.ByteOrder; import com.elvarg.net.packet.PacketBuilder; import com.elvarg.net.packet.PacketBuilder.AccessType; import com.elvarg.net.packet.ValueType; import com.elvarg.world.World; import com.elvarg.world.entity.Entity; import com.elvarg.world.entity.impl.npc.NPC; import com.elvarg.world.entity.impl.player.Player; import com.elvarg.world.model.Direction; import com.elvarg.world.model.Flag; import com.elvarg.world.model.Position; import com.elvarg.world.model.UpdateFlag; /** * Represents a player's npc updating task, which loops through all local * npcs and updates their masks according to their current attributes. * * @author Relex lawl */ public class NPCUpdating { /** * Handles the actual npc updating for the associated player. * @return The NPCUpdating instance. */ public static void update(Player player) { PacketBuilder update = new PacketBuilder(); PacketBuilder packet = new PacketBuilder(65); packet.initializeAccess(AccessType.BIT); packet.putBits(8, player.getLocalNpcs().size()); for (Iterator<NPC> npcIterator = player.getLocalNpcs().iterator(); npcIterator.hasNext();) { NPC npc = npcIterator.next(); if (World.getNpcs().get(npc.getIndex()) != null && npc.isVisible() && player.getPosition().isWithinDistance(npc.getPosition()) && !npc.isNeedsPlacement()) { updateMovement(npc, packet); if (npc.getUpdateFlag().isUpdateRequired()) { appendUpdates(npc, update); } } else { // player.getNpcFacesUpdated().remove(npc); npcIterator.remove(); packet.putBits(1, 1); packet.putBits(2, 3); } } for(NPC npc : World.getNpcs()) { if (player.getLocalNpcs().size() >= 79) //Originally 255 break; if (npc == null || player.getLocalNpcs().contains(npc) || !npc.isVisible() || npc.isNeedsPlacement()) continue; if (npc.getPosition().isWithinDistance(player.getPosition())) { player.getLocalNpcs().add(npc); addNPC(player, npc, packet); if (npc.getUpdateFlag().isUpdateRequired()) { appendUpdates(npc, update); } } } if (update.buffer().writerIndex() > 0) { packet.putBits(14, 16383); packet.initializeAccess(AccessType.BYTE); packet.writeBuffer(update.buffer()); } else { packet.initializeAccess(AccessType.BYTE); } player.getSession().writeAndFlush(packet); } /** * Adds an npc to the associated player's client. * @param npc The npc to add. * @param builder The packet builder to write information on. * @return The NPCUpdating instance. */ private static void addNPC(Player player, NPC npc, PacketBuilder builder) { builder.putBits(14, npc.getIndex()); builder.putBits(5, npc.getPosition().getY()-player.getPosition().getY()); builder.putBits(5, npc.getPosition().getX()-player.getPosition().getX()); builder.putBits(1, 0); builder.putBits(14, npc.getId()); builder.putBits(1, npc.getUpdateFlag().isUpdateRequired() ? 1 : 0); } /** * Updates the npc's movement queue. * @param npc The npc who's movement is updated. * @param builder The packet builder to write information on. * @return The NPCUpdating instance. */ private static void updateMovement(NPC npc, PacketBuilder out) { if (npc.getRunningDirection().toInteger() == -1) { if (npc.getWalkingDirection().toInteger() == -1) { if (npc.getUpdateFlag().isUpdateRequired()) { out.putBits(1, 1); out.putBits(2, 0); } else { out.putBits(1, 0); } } else { out.putBits(1, 1); out.putBits(2, 1); out.putBits(3, npc.getWalkingDirection().toInteger()); out.putBits(1, npc.getUpdateFlag().isUpdateRequired() ? 1 : 0); } } else { out.putBits(1, 1); out.putBits(2, 2); out.putBits(3, npc.getWalkingDirection().toInteger()); out.putBits(3, npc.getRunningDirection().toInteger()); out.putBits(1, npc.getUpdateFlag().isUpdateRequired() ? 1 : 0); } } /** * Appends a mask update for {@code npc}. * @param npc The npc to update masks for. * @param builder The packet builder to write information on. * @return The NPCUpdating instance. */ private static void appendUpdates(NPC npc, PacketBuilder block) { int mask = 0; UpdateFlag flag = npc.getUpdateFlag(); if (flag.flagged(Flag.ANIMATION) && npc.getAnimation() != null) { mask |= 0x10; } if (flag.flagged(Flag.GRAPHIC) && npc.getGraphic() != null) { mask |= 0x80; } if (flag.flagged(Flag.SINGLE_HIT)) { mask |= 0x8; } if (flag.flagged(Flag.ENTITY_INTERACTION)) { mask |= 0x20; } if (flag.flagged(Flag.FORCED_CHAT) && npc.getForcedChat().length() > 0) { mask |= 0x1; } if (flag.flagged(Flag.DOUBLE_HIT)) { mask |= 0x40; } if (flag.flagged(Flag.NPC_APPEARANCE) && npc.getTransformationId() != -1) { mask |= 0x2; } if (flag.flagged(Flag.FACE_POSITION) && npc.getPositionToFace() != null) { mask |= 0x4; } block.put(mask); if (flag.flagged(Flag.ANIMATION) && npc.getAnimation() != null) { updateAnimation(block, npc); } if (flag.flagged(Flag.GRAPHIC) && npc.getGraphic() != null) { updateGraphics(block, npc); } if (flag.flagged(Flag.SINGLE_HIT)) { updateSingleHit(block, npc); } if (flag.flagged(Flag.ENTITY_INTERACTION)) { Entity entity = npc.getInteractingEntity(); block.putShort(entity == null ? -1 : entity.getIndex() + (entity instanceof Player ? 32768 : 0)); } if (flag.flagged(Flag.FORCED_CHAT) && npc.getForcedChat().length() > 0) { block.putString(npc.getForcedChat()); } if (flag.flagged(Flag.DOUBLE_HIT)) { updateDoubleHit(block, npc); } if (flag.flagged(Flag.NPC_APPEARANCE)) { boolean transform = npc.getTransformationId() != -1; //Changes the npc's headicon. block.put(npc.getHeadIcon()); //Should we transform the npc into anotehr npc? block.put(transform ? 1 : 0); //Transforms the npc into another npc. if(transform) { block.putShort(npc.getTransformationId(), ValueType.A, ByteOrder.LITTLE); } } if (flag.flagged(Flag.FACE_POSITION) && npc.getPositionToFace() != null) { final Position position = npc.getPositionToFace(); int x = position == null ? 0 : position.getX(); int y = position == null ? 0 : position.getY(); block.putShort(x * 2 + 1, ByteOrder.LITTLE); block.putShort(y * 2 + 1, ByteOrder.LITTLE); } } /** * Updates {@code npc}'s current animation and displays it for all local players. * @param builder The packet builder to write information on. * @param npc The npc to update animation for. * @return The NPCUpdating instance. */ private static void updateAnimation(PacketBuilder builder, NPC npc) { builder.putShort(npc.getAnimation().getId(), ByteOrder.LITTLE); builder.put(npc.getAnimation().getDelay()); } /** * Updates {@code npc}'s current graphics and displays it for all local players. * @param builder The packet builder to write information on. * @param npc The npc to update graphics for. * @return The NPCUpdating instance. */ private static void updateGraphics(PacketBuilder builder, NPC npc) { builder.putShort(npc.getGraphic().getId()); builder.putInt(((npc.getGraphic().getHeight().ordinal() * 50) << 16) + (npc.getGraphic().getDelay() & 0xffff)); } /** * Updates the npc's single hit. * @param builder The packet builder to write information on. * @param npc The npc to update the single hit for. * @return The NPCUpdating instance. */ private static void updateSingleHit(PacketBuilder builder, NPC npc) { builder.putShort(npc.getPrimaryHit().getDamage()); builder.put(npc.getPrimaryHit().getHitmask().ordinal()); builder.putShort(npc.getHitpoints()); builder.putShort(npc.getDefinition().getHitpoints()); } /** * Updates the npc's double hit. * @param builder The packet builder to write information on. * @param npc The npc to update the double hit for. * @return The NPCUpdating instance. */ private static void updateDoubleHit(PacketBuilder builder, NPC npc) { builder.putShort(npc.getSecondaryHit().getDamage()); builder.put(npc.getSecondaryHit().getHitmask().ordinal()); builder.putShort(npc.getHitpoints()); builder.putShort(npc.getDefinition().getHitpoints()); } /** * Resets all the npc's flags that should be reset after a tick's update * @param npc The npc to reset flags for. */ public static void resetFlags(NPC npc) { npc.getUpdateFlag().reset(); npc.setForcedChat(""); npc.setNeedsPlacement(false); npc.setResetMovementQueue(false); npc.setWalkingDirection(Direction.NONE); npc.setRunningDirection(Direction.NONE); npc.performAnimation(null); npc.performGraphic(null); } }
package application.controller; import java.net.URL; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; public class EventHandlingController implements Initializable{ @FXML private Button btnNumber01; @FXML private Button btnNumber02; @FXML private Button btnNumber03; @FXML private Button btnNumber04; @FXML private Button btnNumber05; @FXML private Button btnNumber06; @FXML private Button btnNumber07; @FXML private Button btnNumber08; @FXML private Button btnNumber09; @FXML private Button btnNumber00; @FXML private Button btnNumberDot; @FXML private Button btnEnter; @FXML private Button btnCorrect; @FXML private TextField txtWater; @FXML private TextField txtCurrent; @FXML private Label lblWater; @FXML private Label lblCurrent; @FXML private Label lblL; @FXML private Label lblKw; private Boolean bool1 = false; private Boolean bool2 = false; @FXML private void listenerNumbers(MouseEvent event){ Button btn = (Button) event.getSource(); if(bool1){ txtWater.setText(txtWater.getText() + btn.getText()); System.out.println(txtWater.getText()); } if(bool2){ txtCurrent.setText(txtCurrent.getText() + btn.getText()); System.out.println(txtCurrent.getText()); } } @FXML private void listenerOk(MouseEvent event){ LocalDateTime now = LocalDateTime.now(); DateTimeFormatter df = DateTimeFormatter.BASIC_ISO_DATE; String url = null; if (bool1){ url = "http://192.168.43.111:821/addverbrauch?typ=wasser&date="+now.format(df)+"&value="+txtWater.getText(); System.out.println(url); } if(bool2){ url = "http://192.168.43.111:821/addverbrauch?typ=strom&date="+now.format(df)+"&value="+txtCurrent.getText(); System.out.println(url); } new Thread(new BackgroundAnsware(url)); } @FXML private void listenerCorrect(MouseEvent event){ if (bool1){ if(txtWater.getText().length() > 0){ txtWater.setText(correct(txtWater.getText())); System.out.println(txtWater.getText()); } } if (bool2){ if(txtCurrent.getText().length() > 0){ txtCurrent.setText(correct(txtCurrent.getText())); System.out.println(txtCurrent.getText()); } } } private String correct(String str){ char[] charArray = str.toCharArray(); char[] newCharArray = Arrays.copyOf(charArray, charArray.length-1); return String.valueOf(newCharArray); } @FXML private void txtWaterListener (MouseEvent event){ String url = "http://192.168.0.111:821/getconsumption?typ=wasser"; System.out.println(url); new Thread(new BackgroundAnsware(url)); bool1=true; bool2=false; } @FXML private void txtCurrentListener (MouseEvent event){ String url = "http://192.168.0.111:821/getconsumption?typ=strom"; System.out.println(url); new Thread(new BackgroundAnsware(url)); bool1=false; bool2=true; } @Override public void initialize(URL location, ResourceBundle resources) { txtWater = new TextField(); txtCurrent = new TextField(); } }
package rhtn_homework; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class BOJ_1613_역사 { private static int N,K,S; private static int[][] adMap; private static StringBuilder sb = new StringBuilder(); public static void main(String[] args) throws IOException{ // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); K = Integer.parseInt(st.nextToken()); adMap = new int[N][N]; for (int i = 0; i < K; i++) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken())-1; int b = Integer.parseInt(st.nextToken())-1; adMap[a][b] = 1; } S = Integer.parseInt(br.readLine()); // 경유 for (int k = 0; k < N; k++) { // 출발 for (int r = 0; r < N; r++) { if(k == r) continue; //도착 for (int c = 0; c < N; c++) { if(k == c || k ==r) continue; if(adMap[r][k] == 1 && adMap[k][c] == 1) adMap[r][c] =1; } } } for (int i = 0; i < S; i++) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken())-1; int b = Integer.parseInt(st.nextToken())-1; if(adMap[a][b] == 0 && adMap[b][a] == 0) sb.append(0 + "\n"); else if(adMap[a][b] == 1) sb.append(-1 + "\n"); else if(adMap[b][a] == 1) sb.append(1 + "\n"); } System.out.println(sb); } }
package com.example.root.curriculum.base; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import com.example.root.curriculum.R; import java.util.ArrayList; import java.util.List; import butterknife.ButterKnife; public abstract class BaseRequestPermissionActivity extends AppCompatActivity { /** * Id to identity READ_CONTACTS permission request. */ private static final int PERMISSON_REQUESTCODE = 0; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public abstract void requestPermissionResult(boolean allowPermission); /** * @param permissions */ private void checkPermissions(String... permissions) { List<String> needRequestPermissonList = findDeniedPermissions(permissions); if (null != needRequestPermissonList && needRequestPermissonList.size() > 0) { ActivityCompat.requestPermissions(this, needRequestPermissonList.toArray( new String[needRequestPermissonList.size()]), PERMISSON_REQUESTCODE); } } /** * 获取权限集中需要申请权限的列表 */ private List<String> findDeniedPermissions(String[] permissions) { List<String> needRequestPermissonList = new ArrayList<String>(); for (String perm : permissions) { if (ContextCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED || ActivityCompat.shouldShowRequestPermissionRationale( this, perm)) { needRequestPermissonList.add(perm); } } return needRequestPermissonList; } /** * 检测是否说有的权限都已经授权 * * @param grantResults * @return * @since 2.5.0 */ private boolean verifyPermissions(int[] grantResults) { for (int result : grantResults) { if (result != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } public boolean mayRequestPermission(String[] permissions) { boolean mayPermission = false; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true; } for (String req : permissions) { if (checkSelfPermission(req) != PackageManager.PERMISSION_GRANTED) { //确定是否你授予了指定的权限 mayPermission = false; break; } else { mayPermission = true; } } if (mayPermission) { return true; } checkPermissions(permissions); return false; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == PERMISSON_REQUESTCODE) { if (verifyPermissions(grantResults)) { requestPermissionResult(true); } else { requestPermissionResult(false); showMissingPermissionDialog(); } } } /** * 显示提示信息 * * @since 2.5.0 */ public void showMissingPermissionDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.notifyTitle); builder.setMessage(R.string.notifyMsg); // 拒绝, 退出应用 builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setPositiveButton(R.string.setting, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startAppSettings(); } }); builder.setCancelable(false); builder.show(); } /** * 启动应用的设置 * * @since 2.5.0 */ private void startAppSettings() { Intent intent = new Intent( Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.setData(Uri.parse("package:" + getPackageName())); startActivity(intent); } }
package com.diozero.example; import org.tinylog.Logger; import com.diozero.api.I2CConstants; import com.diozero.api.RuntimeIOException; import com.diozero.devices.HD44780Lcd; import com.diozero.devices.LcdConnection; import com.diozero.devices.LcdConnection.PCF8574LcdConnection; import com.diozero.util.Diozero; import com.diozero.util.SleepUtil; /** * I2C LCD sample application. To run: * {@code java -cp tinylog-api-$TINYLOG_VERSION.jar:tinylog-impl-$TINYLOG_VERSION.jar:diozero-core-$DIOZERO_VERSION.jar:diozero-example-0.1.jar com.diozero.example.LcdApp [i2c_address] [i2c_controller]}</li> */ public class LcdApp { // Main program block public static void main(String[] args) { int device_address = LcdConnection.PCF8574LcdConnection.DEFAULT_DEVICE_ADDRESS; if (args.length > 0) { device_address = Integer.decode(args[0]).intValue(); } int controller = I2CConstants.CONTROLLER_1; if (args.length > 1) { controller = Integer.parseInt(args[1]); } int columns = 16; int rows = 2; // Initialise display try (LcdConnection lcd_connection = new PCF8574LcdConnection(controller, device_address); HD44780Lcd lcd = new HD44780Lcd(lcd_connection, columns, rows)) { LcdApp.test(lcd); } catch (RuntimeIOException e) { Logger.error(e, "Error: {}", e); } finally { // Required if there are non-daemon threads that will prevent the // built-in clean-up routines from running Diozero.shutdown(); } } @SuppressWarnings("resource") public static void test(HD44780Lcd lcd) { lcd.setBacklightEnabled(true); /*- Logger.info("Calling setText"); lcd.setText(0, "Hello World!"); SleepUtil.sleepSeconds(2); */ // 0, 14, 21, 31, 10, 4, 10, 17 byte[] space_invader = HD44780Lcd.Characters.get("space_invader"); byte[] smilie = HD44780Lcd.Characters.get("smilie"); byte[] frownie = HD44780Lcd.Characters.get("frownie"); lcd.createChar(0, space_invader); lcd.createChar(1, smilie); lcd.createChar(2, frownie); lcd.clear(); Logger.info("Adding text"); lcd.setCursorPosition(0, 0); lcd.addText('H'); lcd.addText('e'); lcd.addText('l'); lcd.addText('l'); lcd.addText('o'); lcd.addText(' '); lcd.addText(' '); lcd.addText(0); lcd.addText(1); lcd.addText(2); lcd.setCursorPosition(0, 1); lcd.addText('W'); lcd.addText('o'); lcd.addText('r'); lcd.addText('l'); lcd.addText('d'); lcd.addText('!'); lcd.addText(' '); lcd.addText(0); lcd.addText(1); lcd.addText(2); SleepUtil.sleepSeconds(2); lcd.clear(); lcd.createChar(3, HD44780Lcd.Characters.get("runninga")); lcd.createChar(4, HD44780Lcd.Characters.get("runningb")); lcd.clear(); lcd.displayControl(true, false, false); for (int i = 0; i < 40; i++) { lcd.setCursorPosition(0, 0); lcd.addText(3); SleepUtil.sleepMillis(100); lcd.setCursorPosition(0, 0); lcd.addText(4); SleepUtil.sleepMillis(100); } SleepUtil.sleepSeconds(1); lcd.displayControl(true, true, true); lcd.clear(); for (int i = 0; i < 4; i++) { // Send some text lcd.setText(0, "Hello - "); lcd.setText(1, "World! " + i); SleepUtil.sleepSeconds(0.5); lcd.clear(); // Send some more text lcd.setText(0, "> diozero"); lcd.setText(1, "> HD44780 LCD"); SleepUtil.sleepSeconds(0.5); } SleepUtil.sleepSeconds(1); lcd.clear(); for (byte b : "Hello Matt!".getBytes()) { lcd.addText(b); SleepUtil.sleepSeconds(.2); } SleepUtil.sleepSeconds(1); lcd.clear(); int x = 0; for (int i = 0; i < 3; i++) { for (byte b : "Hello World! ".getBytes()) { if (x++ == lcd.getColumnCount()) { lcd.entryModeControl(true, true); } lcd.addText(b); SleepUtil.sleepSeconds(.1); } } SleepUtil.sleepSeconds(1); lcd.clear(); lcd.entryModeControl(true, false); lcd.setCursorPosition(0, 0); lcd.addText('H'); lcd.addText('e'); lcd.addText('l'); lcd.addText('l'); lcd.addText('o'); lcd.addText(' '); lcd.addText(' '); lcd.addText(0); lcd.addText(1); lcd.addText(2); lcd.setCursorPosition(0, 1); lcd.addText('W'); lcd.addText('o'); lcd.addText('r'); lcd.addText('l'); lcd.addText('d'); lcd.addText('!'); lcd.addText(' '); lcd.addText(0); lcd.addText(1); lcd.addText(2); Logger.info("Sleeping for 4 seconds..."); SleepUtil.sleepSeconds(4); lcd.clear(); } }
package de.jmda9.core.mproc.task; import static de.jmda9.core.mproc.ProcessingUtilities.withEnclosedTypeElements; import static de.jmda9.core.util.CollectionsUtil.asSet; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import javax.lang.model.element.TypeElement; import javax.xml.bind.annotation.XmlType; /** * Reads all types in a package and returns a set containing type elements for each type annotated with <code>XMLType * </code>. * * @author ruu@jmda.de */ public class XMLTypeElementFinder extends AbstractTypeElementsTaskPackages { private Set<TypeElement> xmlTypeElements; public XMLTypeElementFinder(Package pckg) { super(asSet(pckg)); } /** * Because this class is a {@link Task} and will be run in a {@link TaskRunner} this method will be called for each * processing round (at least twice). Therefore caution has to be taken when (re-)initialising local state (see * xmlTypeElements). * * @see Task#execute() */ @Override public boolean execute() throws TaskException { if (xmlTypeElements == null) { xmlTypeElements = new HashSet<>(); } xmlTypeElements.addAll( withEnclosedTypeElements( getTypeElements()) .stream() .filter(te -> te.getAnnotation(XmlType.class) != null) .collect(Collectors.toList())); return false; } public Set<TypeElement> find() throws IOException { TaskRunner.run(this); return xmlTypeElements; } }
package com.tt.miniapp.debug.network; import org.json.JSONObject; public class Network { public static class DataReceivedParams { public int dataLength; public int encodedDataLength; public String requestId; public double timestamp; } public static class GetResponseBodyResponse { public boolean base64Encoded; public String body; } public static class Initiator { public Network.InitiatorType type; } public enum InitiatorType { OTHER, PARSER("parser"), SCRIPT("script"); private final String mProtocolValue; static { $VALUES = new InitiatorType[] { PARSER, SCRIPT, OTHER }; } InitiatorType(String param1String1) { this.mProtocolValue = param1String1; } public final String getProtocolValue() { return this.mProtocolValue; } } public static class LoadingFailedParams { public String errorText; public String requestId; public double timestamp; public ResourceTypeHelper.ResourceType type; } public static class LoadingFinishedParams { public String requestId; public double timestamp; } public static class Request { public JSONObject headers; public String method; public String postData; public String url; } public static class RequestWillBeSentParams { public String documentURL; public String frameId; public Network.Initiator initiator; public String loaderId; public Network.Response redirectResponse; public Network.Request request; public String requestId; public double timestamp; public ResourceTypeHelper.ResourceType type; } public static class ResourceTiming { public double connectionEnd; public double connectionStart; public double dnsEnd; public double dnsStart; public double proxyEnd; public double proxyStart; public double receivedHeadersEnd; public double requestTime; public double sendEnd; public double sendStart; public double sslEnd; public double sslStart; } public static class Response { public int connectionId; public boolean connectionReused; public Boolean fromDiskCache; public JSONObject headers; public String headersText; public String mimeType; public JSONObject requestHeaders; public String requestHeadersTest; public int status; public String statusText; public Network.ResourceTiming timing; public String url; } public static class ResponseReceivedParams { public String frameId; public String loaderId; public String requestId; public Network.Response response; public double timestamp; public ResourceTypeHelper.ResourceType type; } public static class WebSocketClosedParams { public String requestId; public double timestamp; } public static class WebSocketCreatedParams { public String requestId; public String url; } public static class WebSocketFrame { public boolean mask; public int opcode; public String payloadData; } public static class WebSocketFrameErrorParams { public String errorMessage; public String requestId; public double timestamp; } public static class WebSocketFrameReceivedParams { public String requestId; public Network.WebSocketFrame response; public double timestamp; } public static class WebSocketFrameSentParams { public String requestId; public Network.WebSocketFrame response; public double timestamp; } public static class WebSocketHandshakeResponseReceivedParams { public String requestId; public Network.WebSocketResponse response; public double timestamp; } public static class WebSocketRequest { public JSONObject headers; } public static class WebSocketResponse { public JSONObject headers; public String headersText; public JSONObject requestHeaders; public String requestHeadersText; public int status; public String statusText; } public static class WebSocketWillSendHandshakeRequestParams { public Network.WebSocketRequest request; public String requestId; public double timestamp; public double wallTime; } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\debug\network\Network.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package org.wicket_sapporo.workshop01.page.template.replace_pattern; import org.apache.wicket.Component; import org.apache.wicket.bootstrap.Bootstrap; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.Model; public class BasePage extends WebPage { private static final long serialVersionUID = -6867115414492462716L; Component menu; Component content; public BasePage() { add(new Label("headerLabel", Model.of("ヘッダ部分です"))); add(homePageLink("homePageLink")); add(new Label("fotterLabel", Model.of("フッタ部分です"))); add(new WebMarkupContainer("menuPanel")); add(new WebMarkupContainer("contentPanel")); } @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); // wicket-bootstrap.jar を導入したプロジェクトで、以下の様に書くと、Bootsrapを使うためのhtmlヘッダが書き込まれます。 // Wicket v6.10.0用のwicket-bootstrap v0.12では、Bootstrapv2.3.2 が利用できます。 Bootstrap.renderHeadPlain(response); Bootstrap.renderHeadResponsive(response); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ntconsult.devtest.entities; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.Test; /** * * @author Marcos Freitas Nunes <marcosn@gmail.com> */ public class SaleTest { @Test public void testGetSaleFromArray(){ String[] sale = {"003","10","[1-10-100,2-30-2.50,3-40-3.10]","Diego"}; Sale result = Sale.fromArray(sale); assertThat(result.getId(), equalTo(10L)); assertThat(result.getSeller(), equalTo("Diego")); assertThat(result.getAmount(), equalTo(105.60F)); } }
package gui; import gui.excecao.PrecoDeCompraNaoDeclaradoException; import gui.excecao.PrecoDeVendaNaoDeclaradoException; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import negocio.entidade.Produto; import negocio.excecao.*; import negocio.fachada.Fachada; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import java.net.URL; import java.util.ResourceBundle; public class ControleProduto implements Initializable{ private Fachada fachada; public ControleProduto(){ this.fachada = fachada.getInstance(); } @FXML private Button registrar; @FXML private Label lb1; @FXML private Label lb2; @FXML private Label lb3; @FXML private TextField tipoTF; @FXML private TextField precoCompraTF; @FXML private TextField precoVendaTF; @Override public void initialize(URL url, ResourceBundle rs){ // } public void addProduto(){ try{ String tipo = tipoTF.getText(); double precoCompra = Double.valueOf(precoCompraTF.getText()); double precoVenda = Double.valueOf(precoVendaTF.getText()); Produto produto = new Produto(tipo, precoCompra, precoVenda); this.fachada.adicionarProduto(produto); Alert alerta = new Alert(Alert.AlertType.INFORMATION); alerta.setTitle("Confirmacao"); alerta.setHeaderText("Cadastro efetuado com sucesso"); alerta.setContentText("Produto foi cadastrado"); alerta.showAndWait(); } catch (ProdutoRepetidoException e){ Alert alerta = new Alert(Alert.AlertType.WARNING); alerta.setTitle("Erro"); alerta.setHeaderText("ERRO"); alerta.setContentText("Produto ja cadastrado"); alerta.showAndWait(); } catch (TipoNaoDeclaradoException e){ Alert alerta = new Alert(Alert.AlertType.WARNING); alerta.setTitle("Erro"); alerta.setHeaderText("ERRO"); alerta.setContentText("tipo nao declarado"); alerta.showAndWait(); } catch (PrecoDeCompraNaoDeclaradoException e){ Alert alerta = new Alert(Alert.AlertType.WARNING); alerta.setTitle("Erro"); alerta.setHeaderText("ERRO"); alerta.setContentText("Preco de compra nao declarado"); alerta.showAndWait(); } catch (PrecoDeVendaNaoDeclaradoException e){ Alert alerta = new Alert(Alert.AlertType.WARNING); alerta.setTitle("Erro"); alerta.setHeaderText("ERRO"); alerta.setContentText("Preco de venda nao declarado"); alerta.showAndWait(); } catch (Exception e){ Alert alerta = new Alert(Alert.AlertType.WARNING); alerta.setTitle("Erro"); alerta.setHeaderText("ERRO"); alerta.setContentText("Dados formatados de forma incorreta"); alerta.showAndWait(); } } }
package net.minecraft.client.gui; import net.minecraft.client.Minecraft; import net.minecraft.network.play.server.SPacketUpdateBossInfo; import net.minecraft.util.math.MathHelper; import net.minecraft.world.BossInfo; public class BossInfoClient extends BossInfo { protected float rawPercent; protected long percentSetTime; public BossInfoClient(SPacketUpdateBossInfo packetIn) { super(packetIn.getUniqueId(), packetIn.getName(), packetIn.getColor(), packetIn.getOverlay()); this.rawPercent = packetIn.getPercent(); this.percent = packetIn.getPercent(); this.percentSetTime = Minecraft.getSystemTime(); setDarkenSky(packetIn.shouldDarkenSky()); setPlayEndBossMusic(packetIn.shouldPlayEndBossMusic()); setCreateFog(packetIn.shouldCreateFog()); } public void setPercent(float percentIn) { this.percent = getPercent(); this.rawPercent = percentIn; this.percentSetTime = Minecraft.getSystemTime(); } public float getPercent() { long i = Minecraft.getSystemTime() - this.percentSetTime; float f = MathHelper.clamp((float)i / 100.0F, 0.0F, 1.0F); return this.percent + (this.rawPercent - this.percent) * f; } public void updateFromPacket(SPacketUpdateBossInfo packetIn) { switch (packetIn.getOperation()) { case UPDATE_NAME: setName(packetIn.getName()); break; case UPDATE_PCT: setPercent(packetIn.getPercent()); break; case UPDATE_STYLE: setColor(packetIn.getColor()); setOverlay(packetIn.getOverlay()); break; case UPDATE_PROPERTIES: setDarkenSky(packetIn.shouldDarkenSky()); setPlayEndBossMusic(packetIn.shouldPlayEndBossMusic()); break; } } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\client\gui\BossInfoClient.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.facebook.react.bridge; public interface INativeLibraryLoader { void loadLibrary(String paramString) throws UnsatisfiedLinkError; } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\bridge\INativeLibraryLoader.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.javarush.task.task24.task2401; /** * Created by Администратор on 26.05.2017. */ public class SelfInterfaceMarkerImpl implements SelfInterfaceMarker{ public void A () {} public void B () {} }
package com.tencent.mm.plugin.subapp; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.api.f; import com.tencent.mm.g.a.fi; import com.tencent.mm.kernel.g; import com.tencent.mm.model.au; import com.tencent.mm.model.q; import com.tencent.mm.modelvoice.m; import com.tencent.mm.modelvoice.o; import com.tencent.mm.modelvoice.p; import com.tencent.mm.plugin.messenger.foundation.a.i; import com.tencent.mm.plugin.subapp.a.1; import com.tencent.mm.plugin.subapp.ui.voicetranstext.a; import com.tencent.mm.plugin.subapp.ui.voicetranstext.b; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.al; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.bd; import com.tencent.mm.storage.bx; import com.tencent.mm.storage.by; import java.util.HashMap; import java.util.Map; public class a$a extends c<fi> implements e { private int bNS; private int bNT; private String bSS; private boolean djH; private boolean fsJ; private a opZ; private com.tencent.mm.plugin.subapp.ui.voicetranstext.c oqa; private b oqb; private com.tencent.mm.modelvoice.b oqc; private p oqd; private volatile boolean oqe; boolean oqf; private al oqg; private fi oqh; private int oqi; private Map<String, String> oqj; private int oqk; private boolean oql; private long oqm; private long oqn; private String toUser; public a$a() { this.oqe = false; this.oqf = false; this.oql = true; this.oqm = 0; this.djH = false; this.oqj = new HashMap(); this.sFo = fi.class.getName().hashCode(); } private boolean a(fi fiVar) { if (!(fiVar instanceof fi)) { x.f("MicroMsg.SubCoreSubapp", "mismatched event"); return false; } else if (fiVar.bNF.bNI == 2) { a(a.oqw); this.oqj.clear(); x.i("MicroMsg.SubCoreSubapp", "Have clear the cache of the translate voice results."); return true; } else if (fiVar.bNF.bNI == 1) { a(a.oqw); x.i("MicroMsg.SubCoreSubapp", "Have cancel translate voice action."); return true; } else if (fiVar.bNF.bNI == 3) { a(a.oqx); x.i("MicroMsg.SubCoreSubapp", "alvinluo Have cancel translate voice action by user."); return true; } else if (fiVar.bNF.bNI != 0) { x.i("MicroMsg.SubCoreSubapp", "The opCode(%d) is out of range.", new Object[]{Integer.valueOf(this.oqh.bNF.bNI)}); return false; } else if (this.fsJ) { x.w("MicroMsg.SubCoreSubapp", "The Event handler is busy."); return false; } else if (m.TI() == null) { x.e("MicroMsg.SubCoreSubapp", "SubCoreVoice.getVoiceStg() == null" + bi.cjd()); return false; } else { this.oqh = fiVar; String str = this.oqh.bNF.bNH; String str2 = this.oqh.bNF.fileName; if (bi.oW(str) || bi.oW(str2)) { x.e("MicroMsg.SubCoreSubapp", "The localId(%s) is null or fileName(%s) is null.", new Object[]{str, str2}); a(a.oqy); return false; } bFW(); String str3 = (String) this.oqj.get(str2); if (bi.oW(str3)) { bx Zs = m.TJ().Zs(str2); a.opT = Zs; if (Zs == null || bi.oW(a.opT.field_content)) { x.i("MicroMsg.SubCoreSubapp", "alvinluo transform test voice scene: %d", new Object[]{Integer.valueOf(fiVar.bNF.scene)}); this.oqd = m.TI().ow(str2); try { if (this.oqd == null) { x.i("MicroMsg.SubCoreSubapp", "alvinluo the VoiceInfo do not exist. (localId : %s, fileName : %s)", new Object[]{str, str2}); this.oqd = new p(); this.oqd.fileName = str2; this.oqd.createTime = System.currentTimeMillis() / 1000; this.oqd.clientId = str2; this.oqd.enK = System.currentTimeMillis() / 1000; this.oqd.status = 1; if (fiVar.bNF.scene == 8) { this.oqd.enN = -1; } else { this.oqd.enN = Integer.valueOf(str).intValue(); } x.i("MicroMsg.SubCoreSubapp", "size : %d", new Object[]{Integer.valueOf(o.nM(str2))}); this.oqd.dHI = r0; } if (this.oqd.enN < 0) { x.i("MicroMsg.SubCoreSubapp", "alvinluo voiceInfo msgLocalId < 0"); } else { bd dW = ((i) g.l(i.class)).bcY().dW((long) this.oqd.enN); com.tencent.mm.ac.a.c ak; if (dW.field_isSend == 1) { this.bSS = q.GF(); if (this.oqh.bNF.scene == 4 || this.oqh.bNF.scene == 5) { ak = ((f) g.l(f.class)).ak(dW.field_bizChatId); if (ak != null) { this.toUser = ak.field_bizChatServId; } else { this.toUser = ""; } } else { this.toUser = dW.field_talker; } } else if (dW.field_isSend == 0) { this.toUser = q.GF(); if (this.oqh.bNF.scene == 4 || this.oqh.bNF.scene == 5) { ak = ((f) g.l(f.class)).ak(dW.field_bizChatId); if (ak != null) { this.bSS = ak.field_bizChatServId; } else { this.bSS = ""; } } else { this.bSS = dW.field_talker; } } } this.oqk = this.oqh.bNF.scene; x.d("MicroMsg.SubCoreSubapp", "alvinluo VoiceTransformText fromUser: %s, toUser: %s, scene: %d", new Object[]{this.bSS, this.toUser, Integer.valueOf(this.oqk)}); this.oqc = com.tencent.mm.modelvoice.q.ok(this.oqd.fileName); this.fsJ = true; this.oqi = 20; a(a.oqq); return true; } catch (Throwable e) { x.printErrStackTrace("MicroMsg.SubCoreSubapp", e, "alvinluo set voiceInfo exception", new Object[0]); a(a.oqy); return true; } } x.i("MicroMsg.SubCoreSubapp", "finish With DB localId:%s,fileName:%s", new Object[]{str, str2}); a(a.opT.field_content, a.oqu); return true; } x.i("MicroMsg.SubCoreSubapp", "finish With Cache localId:%s,fileName:%s", new Object[]{str, str2}); a(str3, a.oqu); return true; } } private void bFW() { this.oql = true; this.oqm = 0; this.oqn = 0; this.bNS = 0; this.bNT = 0; this.djH = false; } final void a(a aVar) { switch (1.opY[aVar.ordinal()]) { case 1: x.i("MicroMsg.SubCoreSubapp", "net check"); if (this.oqd.bYu > 0) { x.i("MicroMsg.SubCoreSubapp", "has msg svr id: %d", new Object[]{Long.valueOf(this.oqd.bYu)}); this.opZ = new a(this.oqd.clientId, this.oqd.dHI, this.oqc.getFormat(), this.oqd.bYu, this.oqd.fileName, this.oqk, this.bSS, this.toUser); } else { x.i("MicroMsg.SubCoreSubapp", "not existex msg svr id: %d", new Object[]{Long.valueOf(this.oqd.bYu)}); this.opZ = new a(this.oqd.clientId, this.oqd.dHI, this.oqd.fileName, this.oqk, this.bSS, this.toUser); } au.DF().a(this.opZ, 0); au.DF().a(this.opZ.getType(), this); this.oqn = System.currentTimeMillis(); return; case 2: x.i("MicroMsg.SubCoreSubapp", "net upload"); if (this.opZ == null) { x.w("MicroMsg.SubCoreSubapp", "request upload must after check!"); return; } this.oqa = new com.tencent.mm.plugin.subapp.ui.voicetranstext.c(this.oqd.clientId, this.opZ.oue, this.oqc.getFormat(), this.oqd.fileName, this.oqk, this.bSS, this.toUser); au.DF().a(this.oqa, 0); au.DF().a(this.oqa.getType(), this); return; case 3: x.i("MicroMsg.SubCoreSubapp", "net upload more"); if (this.oqa == null) { x.w("MicroMsg.SubCoreSubapp", "upload more need has upload netScene!"); return; } this.oqa = new com.tencent.mm.plugin.subapp.ui.voicetranstext.c(this.oqa); au.DF().a(this.oqa, 0); au.DF().a(this.oqa.getType(), this); return; case 4: if (this.oqe) { x.i("MicroMsg.SubCoreSubapp", "pulling so pass"); return; } x.i("MicroMsg.SubCoreSubapp", "net get"); if (this.opZ == null) { x.w("MicroMsg.SubCoreSubapp", "request get must after check!"); return; } this.oqe = true; this.oqb = new b(this.oqd.clientId); au.DF().a(this.oqb, 0); au.DF().a(this.oqb.getType(), this); return; case 5: this.oqf = true; return; case 6: au.DF().c(this.opZ); au.DF().c(this.oqa); au.DF().c(this.oqb); this.djH = true; a(null, a.oqw); return; case 7: case 8: this.djH = true; a(null, aVar); return; case 9: this.djH = true; a(null, aVar); return; default: return; } } private void bFX() { if (this.oql) { this.oql = false; this.oqm = System.currentTimeMillis(); this.bNS = (int) (this.oqm - this.oqn); } } private void a(String str, a aVar) { x.i("MicroMsg.SubCoreSubapp", "finishWithResult mstate:%s", new Object[]{aVar}); if (this.oqg != null) { this.oqg.SO(); } au.DF().b(546, this); au.DF().b(547, this); au.DF().b(548, this); if (this.oqh != null) { if (!bi.oW(str)) { this.oqj.put(this.oqh.bNF.fileName, str); if ((a.opT == null || bi.oW(a.opT.field_content)) && this.oqh.bNF.bJu == 1) { by TJ = m.TJ(); x.i("MicroMsg.SubCoreSubapp", "createVoiceTT localId(%s) , fileName(%s).", new Object[]{this.oqh.bNF.bNH, this.oqh.bNF.fileName}); bx bxVar = new bx(); bxVar.field_msgId = Long.valueOf(this.oqh.bNF.bNH).longValue(); bxVar.Zr(this.oqh.bNF.fileName); bxVar.field_content = str; TJ.a(bxVar); } } else if (aVar == a.oqu) { x.i("MicroMsg.SubCoreSubapp", "finishWithResult State.FINISH id:%s", new Object[]{this.oqh.bNF.bNH}); this.oqh.bNG.state = 2; } this.oqh.bNG.aoy = true; this.oqh.bNG.content = str; if (aVar == a.oqw) { this.oqh.bNG.state = 1; } else if (aVar == a.oqy || aVar == a.oqz) { this.oqh.bNG.state = 2; } x.d("MicroMsg.SubCoreSubapp", "finishWithResult result : %s", new Object[]{str}); if (this.oqh.bNF.bNJ != null) { this.oqh.bNF.bNJ.run(); } } if (this.djH && this.oqd != null) { int length; int i; if (str != null) { length = str.length(); } else { length = 0; } if (aVar != a.oqu) { this.bNS = 0; this.bNT = 0; if (aVar == a.oqw) { i = 5; length = 0; } else if (aVar == a.oqz) { length = 0; i = 3; } else if (aVar == a.oqy) { i = 4; length = 0; } else if (aVar == a.oqA) { length = 0; i = 2; } else { length = 0; i = 0; } } else if (bi.oW(str)) { this.bNS = 0; this.bNT = 0; length = 0; i = 3; } else { i = 1; } x.i("MicroMsg.SubCoreSubapp", "alvinluo transformTextResult voiceId: %s, wordCount: %d, waitTime: %d, animationTime: %d, transformResult: %d", new Object[]{this.oqd.clientId, Integer.valueOf(length), Integer.valueOf(this.bNS), Integer.valueOf(this.bNT), Integer.valueOf(i)}); if (i != 0) { com.tencent.mm.plugin.subapp.d.b.b(this.oqd.clientId, length, this.bNS, this.bNT, i); } } this.opZ = null; this.oqa = null; this.oqb = null; this.oqh = null; this.fsJ = false; this.oqf = false; this.oqe = false; this.oqi = 20; a.opT = null; bFW(); } public final void a(int i, int i2, String str, l lVar) { String str2 = null; x.i("MicroMsg.SubCoreSubapp", "onSceneEnd errType(%d) , errCode(%d).", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)}); if (i == 0 && i2 == 0) { int i3; switch (lVar.getType()) { case 546: if (this.opZ.mState == a.ouc) { x.i("MicroMsg.SubCoreSubapp", "check result: done"); a(a.oqu); bFX(); this.bNT = 0; this.djH = true; if (this.opZ.bGC()) { str2 = this.opZ.oud.suF; } a(str2, a.oqu); return; } else if (this.opZ.mState == a.oub) { if (this.opZ.oud != null) { bi.oW(this.opZ.oud.suF); } x.i("MicroMsg.SubCoreSubapp", "check result: processing"); a(a.oqt); return; } else if (this.opZ.mState == a.oua) { x.i("MicroMsg.SubCoreSubapp", "check result: not exist"); a(a.oqr); return; } else if (this.opZ.ouf != null) { i3 = this.opZ.ouf.sga; return; } else { return; } case 547: if (this.oqa.bGE()) { x.i("MicroMsg.SubCoreSubapp", "succeed upload"); a(a.oqt); return; } x.d("MicroMsg.SubCoreSubapp", "start upload more: start:%d, len:%d", new Object[]{Integer.valueOf(this.oqa.oue.rdW), Integer.valueOf(this.oqa.oue.rdX)}); a(a.oqs); return; case 548: int i4 = this.oqb.ouh; x.i("MicroMsg.SubCoreSubapp", "get mIntervalSec:%ds", new Object[]{Integer.valueOf(i4)}); this.oqe = false; bFX(); if (!this.oqb.isComplete() && this.oqb.bGC()) { x.i("MicroMsg.SubCoreSubapp", "refreshResult result"); String str3 = this.oqb.oud.suF; if (this.oqh != null) { this.oqh.bNG.aoy = false; this.oqh.bNG.content = str3; x.i("MicroMsg.SubCoreSubapp", "refreshResult result is null ? : %s", new Object[]{Boolean.valueOf(bi.oW(str3))}); if (this.oqh.bNF.bNJ != null) { this.oqh.bNF.bNJ.run(); } } } else if (!this.oqb.bGC()) { x.d("MicroMsg.SubCoreSubapp", "result not valid"); } if (this.oqb.isComplete()) { x.i("MicroMsg.SubCoreSubapp", "succeed get"); if (this.oqb.bGC()) { str2 = this.oqb.oud.suF; } a(a.oqu); this.bNT = (int) (System.currentTimeMillis() - this.oqm); this.djH = true; a(str2, a.oqu); return; } x.i("MicroMsg.SubCoreSubapp", "do get again after:%ds", new Object[]{Integer.valueOf(i4)}); if (!this.oqf) { i3 = this.oqi - 1; this.oqi = i3; if (i3 < 0) { x.e("MicroMsg.SubCoreSubapp", "Has try to translate delay for %d times.", new Object[]{Integer.valueOf(20)}); a(a.oqz); return; } if (this.oqg == null) { this.oqg = new al(new 1(this, i4), false); } long j = (long) (i4 * 1000); this.oqg.J(j, j); return; } return; default: return; } } else if (i == 2) { a(a.oqA); } else { a(a.oqz); } } }
package modelo; public class PorcionQueso implements Porcion { private String nombrePorcion; private double precioExtra; private Porcion porcionExtra; public PorcionQueso(Porcion porcion) { this.nombrePorcion = "Porcion Queso"; this.precioExtra = 20; this.porcionExtra = porcion; } @Override public String descripcion() { if (porcionExtra == null) { return this.nombrePorcion; } else return (this.porcionExtra.descripcion() + "\n" + this.nombrePorcion); } @Override public double precio() { if (porcionExtra == null) { return precioExtra; } else return precioExtra + this.porcionExtra.precio(); } }
package com.test; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8080); while (true) { Socket accept = serverSocket.accept(); OutputStream outputStream = accept.getOutputStream(); outputStream.write("xxxx".getBytes()); outputStream.flush(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.openwebbeans.se; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Set; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.inject.se.SeContainer; import jakarta.enterprise.inject.se.SeContainerInitializer; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.BeanManager; public final class CDILauncher { private CDILauncher() { // no-op } public static void main(final String[] args) { final SeContainerInitializer initializer = SeContainerInitializer.newInstance(); final Config config = configure(initializer, args); try (final SeContainer container = initializer.initialize()) { if (config.main != null) { executeMain(config, container); } // else the app can use other ways to execute code like @PreDestroy of a startup bean } } private static void executeMain(final Config config, final SeContainer container) { final BeanManager manager = container.getBeanManager(); Set<Bean<?>> beans = manager.getBeans(config.main); if (beans == null || beans.isEmpty()) { try { beans = manager.getBeans(Thread.currentThread().getContextClassLoader().loadClass(config.main)); } catch (final ClassNotFoundException e) { throw new IllegalArgumentException("No bean '" + config.main + "' found"); } } final Bean<?> bean = manager.resolve(beans); final CreationalContext<Object> context = manager.createCreationalContext(null); final Object reference = manager.getReference(bean, selectProxyType(bean.getTypes()), context); try { if (Runnable.class.isInstance(reference)) { Runnable.class.cast(reference).run(); } else // by reflection { // try a main method taking parameters // then just a main or run method Method method = null; try { method = bean.getBeanClass() .getMethod("main", String[].class); } catch (final Exception e) { try { method = bean.getBeanClass() .getMethod("main"); } catch (final Exception e2) { try { method = bean.getBeanClass() .getMethod("main"); } catch (final Exception e3) { throw new IllegalArgumentException( bean + " does not implements Runnable or has a public main method"); } } } try { final Object output = method.invoke( Modifier.isStatic(method.getModifiers()) ? null : reference, method.getParameterCount() == 1 ? new Object[] { config.args } : new Object[0]); if (output != null) { System.out.println(output); } } catch (final IllegalAccessException e) { throw new IllegalStateException(e); } catch (final InvocationTargetException e) { throw new IllegalStateException(e.getTargetException()); } } } finally { if (!manager.isNormalScope(bean.getScope())) { context.release(); } } } private static Class<?> selectProxyType(final Set<Type> types) { if (types.contains(Runnable.class)) { return Runnable.class; } return Object.class; } private static Config configure(final SeContainerInitializer initializer, final String[] args) { String main = null; final Collection<String> remaining = new ArrayList<>(args.length); for (int i = 0; i < args.length; i++) { final String current = args[i]; if (current != null && current.startsWith("--openwebbeans.")) { if (args.length <= i + 1) { throw new IllegalArgumentException("Missing argument value for: '" + args[i] + "'"); } if (current.equals("--openwebbeans.main")) { if (main != null) { throw new IllegalArgumentException("Ambiguous main '" + main + "' vs '" + args[i + 1] + "'"); } main = args[i + 1]; } else { initializer.addProperty(current.substring("--".length()), args[i + 1]); } i++; } else { remaining.add(current); } } return new Config(remaining.toArray(new String[0]), main); } private static class Config { private final String[] args; private final String main; private Config(final String[] args, final String main) { this.args = args; this.main = main; } } }
/** * */ package uk.gov.hmcts.befta.factory; import org.hamcrest.MatcherAssert; import org.hamcrest.core.IsInstanceOf; import org.junit.jupiter.api.Test; import uk.gov.hmcts.befta.player.BackEndFunctionalTestScenarioContext; /** * @author korneleehenry * */ class BeftaScenarioContextFactoryTest { /** * Test method for {@link uk.gov.hmcts.befta.factory.BeftaScenarioContextFactory#createBeftaScenarioContext()}. */ @Test void testCreateBeftaScenarioContext() { MatcherAssert.assertThat(BeftaScenarioContextFactory.createBeftaScenarioContext(), IsInstanceOf.instanceOf(BackEndFunctionalTestScenarioContext.class)); } }
package com.company; import java.util.Arrays; public class Main { public static void main(String[] args) { int[] a = {1, 2, 3, 4, 5}; int[] b = a.clone(); int[] c = new int[a.length]; System.arraycopy(a, 0, c, 0, c.length); String str = "a = "; for(int i = 0; i < a.length; i++) str += a[i] + " "; System.out.println(str); str = "b = "; for(int i = 0; i < b.length; i++) str += b[i] + " "; System.out.println(str); str = "c = "; for(int i = 0; i < c.length; i++) str += c[i] + " "; System.out.println(str); int[] a1 = {1, 2, 3, 4, 5}; int[] b1 = {6, 7, 8, 9}; System.arraycopy(a1, 2, b1, 1, 3); //[6, 3, 4, 5] str = "a1 = "; for(int i = 0; i < a1.length; i++) str += a1[i] + " "; System.out.println(str); str = "b1 = "; for(int i = 0; i < b1.length; i++) str += b1[i] + " "; System.out.println(str); int[] array = new int[10]; int[] arrayB = new int[10]; Arrays.fill(array, -1); Arrays.fill(arrayB, 0, a.length / 2, 1); System.out.println(Arrays.toString(array)); array[1] = 6; array[3] = 8; array[5] = -4; array[7] = 9; Arrays.sort(array); System.out.println(Arrays.toString(array)); int[] aA = {1, 2, 3, 4, 5}; int[] aB = a.clone(); System.out.println( (a == b) + " "+(Arrays.equals(a, b))); //бинарный поиск int intArr[] = {30, 20, 5, 12, 55}; Arrays.sort(intArr); int retVal = Arrays.binarySearch(intArr, 12); System.out.println("Элемент с о значением 12 находится по индексу " + retVal); } }
package net.d4rk.inventorychef.inventory.expandablelistview.roomembedded.adapter; import android.app.Activity; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.util.SparseArray; import android.util.SparseIntArray; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import net.d4rk.inventorychef.R; import net.d4rk.inventorychef.database.room.AppDatabase; import net.d4rk.inventorychef.inventory.expandablelistview.roomembedded.database.dao.Ingredient; import net.d4rk.inventorychef.inventory.expandablelistview.roomembedded.database.dao.Purchase; import net.d4rk.inventorychef.inventory.expandablelistview.roomembedded.database.dao.StoragePlace; import net.d4rk.inventorychef.inventory.expandablelistview.roomembedded.database.dao.StoragePlaceAndAllIngredients; import net.d4rk.inventorychef.inventory.expandablelistview.roomembedded.model.PositionMapping; import net.d4rk.inventorychef.util.DatabaseInitializer; import org.joda.time.DateTime; import java.util.Collections; import java.util.List; import java.util.Locale; public abstract class ExpandableInventoryAdapter< SVH extends ExpandableInventoryAdapter.StorageViewHolder, IVH extends ExpandableInventoryAdapter.IngredientViewHolder > extends RecyclerView.Adapter { private static final String TAG = ExpandableInventoryAdapter.class.getSimpleName(); private static final int TYPE_STORAGE = 0; private static final int TYPE_INGREDIENT = 1; List<StoragePlaceAndAllIngredients> mStoragePlacesAndIngredients = Collections.emptyList(); SparseIntArray mGroupIndexList = new SparseIntArray(); SparseArray<PositionMapping> mElementIndexList = new SparseArray<>(); ExpandableInventoryAdapter() { } @Override public RecyclerView.ViewHolder onCreateViewHolder( @NonNull ViewGroup parent, int viewType ) { switch (viewType) { case TYPE_STORAGE: View inventoryView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_storageplaces, parent, false); return new StorageViewHolder(inventoryView); case TYPE_INGREDIENT: // View ingredientView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_ingredients, parent, false); View ingredientView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_ingredients_swipe, parent, false); return new IngredientViewHolder(ingredientView); default: throw new IllegalArgumentException("Given viewType is not valid"); } } @Override public void onBindViewHolder( @NonNull RecyclerView.ViewHolder viewHolder, int position ) { switch (getItemViewType(position)) { case TYPE_STORAGE: StoragePlace currentStoragePlace = mStoragePlacesAndIngredients.get(mGroupIndexList.get(position)).getStoragePlace(); ((SVH) viewHolder).setStorageTitle(currentStoragePlace.getName()); break; case TYPE_INGREDIENT: Ingredient currentIngredient = mStoragePlacesAndIngredients.get(mElementIndexList.get(position).getGroupIndex()).getIngredients().get(mElementIndexList.get(position).getChildIndex()); IVH ingredientViewHolder = (IVH) viewHolder; ingredientViewHolder.itemView.setTag(currentIngredient); ingredientViewHolder.initialize(); break; } } @Override public int getItemViewType(int position) { if (mGroupIndexList.get(position, -1) != -1) { return TYPE_STORAGE; } else if (mElementIndexList.get(position) != null) { return TYPE_INGREDIENT; } else { throw new RuntimeException("Position out of range"); } } @Override public int getItemCount() { int visibleCount = 0; for (StoragePlaceAndAllIngredients inventoryElement : mStoragePlacesAndIngredients) { // get visible count of all Inventory elements in the list visibleCount += inventoryElement.getIngredients().size() + 1; } return visibleCount; } class StorageViewHolder extends RecyclerView.ViewHolder { TextView mStorageTitle; StorageViewHolder(View itemView) { super(itemView); mStorageTitle = itemView.findViewById(R.id.storage_name); } void setStorageTitle(String storageTitle) { mStorageTitle.setText(storageTitle); } } public class IngredientViewHolder extends RecyclerView.ViewHolder { public RelativeLayout viewBackground, viewForeground; EditText mAmount; TextView mName; ImageButton mIncreaseAmount; SeekBar mAmountBar; IngredientViewHolder(View itemView) { super(itemView); this.viewBackground = itemView.findViewById(R.id.ingredient_background); this.viewForeground = itemView.findViewById(R.id.ingredient_foreground); this.mAmount = itemView.findViewById(R.id.ingredient_amount); this.mName = itemView.findViewById(R.id.ingredient_name); this.mIncreaseAmount = itemView.findViewById(R.id.ingredient_increaseamount); this.mAmountBar = itemView.findViewById(R.id.ingredient_amountbar); } void initialize() { Ingredient currentIngredient = (Ingredient) itemView.getTag(); setIngredientAmount(currentIngredient.getAmount()); setIngredientName(currentIngredient.getName()); mAmount.setOnEditorActionListener(new EditText.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { int previousAmount = ((Ingredient) itemView.getTag()).getAmount(); try { ((Ingredient) itemView.getTag()).setAmount(Integer.parseInt(v.getText().toString())); DatabaseInitializer.updateAmountAsync(AppDatabase.getAppDatabase(mAmount.getContext()), (Ingredient) itemView.getTag()); // int amountDifference = ((Ingredient) itemView.getTag()).getAmount() - previousAmount; // // if (amountDifference > 0) { // Purchase newPurchase = new Purchase(); // newPurchase.setIngredientId(((Ingredient) itemView.getTag()).getId()); // newPurchase.setAmount(amountDifference); // newPurchase.setPurchaseTimestamp(new DateTime().getMillis()); // // DatabaseInitializer.insertOrUpdatePurchase(AppDatabase.getAppDatabase(mAmount.getContext()), newPurchase); // } InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } if (mAmountBar.getVisibility() == View.VISIBLE) { mAmountBar.setVisibility(View.GONE); } } catch (Exception e) { Log.e(TAG, "(onEditorAction): amount update not valid"); } return true; } return false; } }); mAmount.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { mAmountBar.setVisibility(View.VISIBLE); mAmountBar.setProgress(((Ingredient) itemView.getTag()).getAmount()); if (mAmount.isFocused()) { mAmount.clearFocus(); } mAmountBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int mPreviousAmount = 0; @Override public void onProgressChanged( SeekBar seekBar, int amountProgress, boolean fromUser ) { if (mPreviousAmount == 0) { mPreviousAmount = ((Ingredient) itemView.getTag()).getAmount(); } mAmount.setText(String.valueOf(amountProgress)); ((Ingredient) itemView.getTag()).setAmount(amountProgress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch( SeekBar seekBar ) { seekBar.setVisibility(View.GONE); InputMethodManager imm = (InputMethodManager) seekBar.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(seekBar.getWindowToken(), 0); } DatabaseInitializer.updateAmountAsync(AppDatabase.getAppDatabase(mAmount.getContext()), (Ingredient) itemView.getTag()); // int amountDifference = ((Ingredient) itemView.getTag()).getAmount() - mPreviousAmount; // // if (amountDifference > 0) { // Purchase newPurchase = new Purchase(); // // newPurchase.setIngredientId(((Ingredient) itemView.getTag()).getId()); // newPurchase.setAmount(amountDifference); // newPurchase.setPurchaseTimestamp(new DateTime().getMillis()); // // DatabaseInitializer.insertOrUpdatePurchase(AppDatabase.getAppDatabase(mAmount.getContext()), newPurchase); // } } }); return false; } }); mIncreaseAmount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ((Ingredient) itemView.getTag()).setAmount(((Ingredient) itemView.getTag()).getAmount() + 1); DatabaseInitializer.updateAmountAsync(AppDatabase.getAppDatabase(mAmount.getContext()), (Ingredient) itemView.getTag()); // Purchase newPurchase = new Purchase(); // newPurchase.setIngredientId(((Ingredient) itemView.getTag()).getId()); // newPurchase.setAmount(1); // newPurchase.setPurchaseTimestamp(new DateTime().getMillis()); // // DatabaseInitializer.insertOrUpdatePurchase(AppDatabase.getAppDatabase(mAmount.getContext()), newPurchase); } }); } void setIngredientAmount(int ingredientAmount) { mAmount.setText(String.format(Locale.getDefault(), "%d", ingredientAmount)); } void setIngredientName(String ingredientName) { mName.setText(ingredientName); } } }
package com.project.model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "devconscore") public class DevconScore { @Id String id; String paperName, evaluatorName; String[] criteria, weightage, score, comments, totalWeightage; String finalWeightedScore; public DevconScore(String id, String paperName, String evaluatorName, String[] criteria, String[] weightage, String[] score, String[] comments, String finalWeightedScore, String[] totalWeightage) { super(); this.id = id; this.paperName = paperName; this.evaluatorName = evaluatorName; this.criteria = criteria; this.weightage = weightage; this.score = score; this.comments = comments; this.finalWeightedScore = finalWeightedScore; this.totalWeightage = totalWeightage; } public DevconScore() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPaperName() { return paperName; } public void setPaperName(String paperName) { this.paperName = paperName; } public String getEvaluatorName() { return evaluatorName; } public void setEvaluatorName(String evaluatorName) { this.evaluatorName = evaluatorName; } public String[] getCriteria() { return criteria; } public void setCriteria(String[] criteria) { this.criteria = criteria; } public String[] getWeightage() { return weightage; } public void setWeightage(String[] weightage) { this.weightage = weightage; } public String[] getScore() { return score; } public void setScore(String[] score) { this.score = score; } public String[] getComments() { return comments; } public void setComments(String[] comments) { this.comments = comments; } public String getFinalWeightedScore() { return finalWeightedScore; } public void setFinalWeightedScore(String finalWeightedScore) { this.finalWeightedScore = finalWeightedScore; } public String[] getTotalWeightage() { return totalWeightage; } public void setTotalWeightage(String[] totalWeightage) { this.totalWeightage = totalWeightage; } }
package com.wit.getaride; import com.parse.LogInCallback; import com.parse.ParseException; import com.parse.ParseUser; import com.parse.SignUpCallback; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class LoggIn extends Activity { EditText un; EditText pw; public static Activity alogin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_logg_in); un = (EditText)findViewById(R.id.userName); pw = (EditText)findViewById(R.id.password); alogin = this; } public void toSignup(View v){ startActivity (new Intent(getApplicationContext(), Signup.class)); } public void loggin(View v){ ParseUser.logInInBackground(un.getText().toString(), pw.getText().toString(), new LogInCallback() { public void done(ParseUser user, ParseException e) { if (user != null) { Log.v("signin", "Signin sucessful"); GetArideApp app = new GetArideApp(); app.thisUser= app.toUser(ParseUser.getCurrentUser()); app.currentParseUser = ParseUser.getCurrentUser(); startActivity (new Intent(getApplicationContext(), MainActivity.class)); finish(); } else { // Signup failed. Look at the ParseException to see what happened. Log.v("signin", "Signin faild"); Toast.makeText(getBaseContext(), "Incorrect Username or Password.", Toast.LENGTH_LONG).show(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.logg_in, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package it.dstech.formazione.service; import java.time.LocalDateTime; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import it.dstech.formazione.model.Messaggio; import it.dstech.formazione.model.Persona; import it.dstech.formazione.repository.MessaggioRepository; import it.dstech.formazione.repository.PersonaRepository; @Service public class PersonaServiceDAOImpl implements PersonaServiceDAO{ @Autowired private PersonaRepository personaRepos; @Autowired private MessaggioRepository messageRepos; public List<Persona> cercaUsernames() { return personaRepos.findAll(); } public void sendMessaggio(String persona, Messaggio messaggio) { Persona controparte = findPersona(messaggio.getControparte().getUsername()); Persona sender = findPersona(persona); LocalDateTime now = LocalDateTime.now(); messaggio.setTimestamp(now); messaggio.setControparte(controparte); messageRepos.save(messaggio); sender.getListaMessaggi().add(messaggio); personaRepos.save(sender); Messaggio duplicato = new Messaggio(); duplicato.setMittente(!messaggio.getMittente()); duplicato.setControparte(sender); duplicato.setTimestamp(now); duplicato.setTesto(messaggio.getTesto()); messageRepos.save(duplicato); controparte.getListaMessaggi().add(duplicato); personaRepos.save(controparte); } public Persona findPersona(String username) { return personaRepos.findByUsername(username); } public Persona createPersona(Persona persona) { return personaRepos.save(persona); } }
/* 1: */ package com.kaldin.test.scheduletest.action; /* 2: */ /* 3: */ enum SendMailAction$OPTIONS /* 4: */ { /* 5:33 */ SEND, REGISTRATION, EDIT, VIEW_MAIL; /* 6: */ /* 7: */ private SendMailAction$OPTIONS() {} /* 8: */ /* 9: */ public static SendMailAction$OPTIONS get(String str) /* 10: */ { /* 11: */ try /* 12: */ { /* 13:37 */ return valueOf(str.toUpperCase()); /* 14: */ } /* 15: */ catch (Exception ex) {} /* 16:40 */ return null; /* 17: */ } /* 18: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.test.scheduletest.action.SendMailAction.OPTIONS * JD-Core Version: 0.7.0.1 */
package controllers; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.ServletException; import java.io.IOException; import java.io.OutputStream; import java.io.InputStream; import models.User; public class SaveProfilePicServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException{ HttpSession session = request.getSession(); User user = (User)session.getAttribute("user"); OutputStream os = response.getOutputStream(); String profPicPath = "static/images/user.png"; if(user!=null){ String profPic = user.getProfPic(); profPicPath = "/WEB-INF/uploads/"+profPic; } InputStream is = getServletContext().getResourceAsStream(profPicPath); byte[] byt = new byte[1024]; int count = 0; while((count=is.read(byt))!=-1){ os.write(byt); } os.flush(); os.close(); } }
package mapgenerator.gui; import java.util.Random; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; import mapgenerator.domain.BiomeColor; import mapgenerator.domain.Biomes; import mapgenerator.domain.Map; /** * Class is responsible for drawing maps on canvas. */ public class Painter { private Map mapStorage; private Biomes biomes; private int canvasSize; private double waterlevel; private GraphicsContext brush; private String biomeDrawType; private String drawType; private String showBiome; private Random random; /** * Constructor initializes all necessary variables. * * @param map * @param biomes * @param canvasSize * @param waterlevel * @param brush * @param random */ public Painter(Map map, Biomes biomes, int canvasSize, double waterlevel, GraphicsContext brush, Random random) { this.mapStorage = map; this.biomes = biomes; this.canvasSize = canvasSize; this.waterlevel = waterlevel; this.brush = brush; this.random = random; } /** * Draws a map on screen. Gets the maximum values of height and moisture, * then goes trough every cell in the map and draws a rectangle the color of * which is based on the information stored in the mapCell of the location * and the maximum height and moisture values of the map. */ public void drawMap() { Long drawingStarts = System.nanoTime(); double maxHeight = mapStorage.getMaxHeight(); double maxMoisture = mapStorage.getMaxMoisture(); Color[] colors = new Color[20]; fillColorArray(); for (int x = 0; x < canvasSize; x++) { for (int y = 0; y < canvasSize; y++) { drawMapCell(x, y, maxHeight, maxMoisture, colors); } } Long drawingEnds = System.nanoTime(); Long drawingTime = drawingEnds - drawingStarts; System.out.println("Map drawn in " + drawingTime + " nanoseconds (" + (drawingTime / 1000000) + " milliseconds)"); System.out.println(""); } /** * Draws a rectangle on screen based on a mapCell object. The placement of * the rectange is based on the coordinates of the mapCell- The color of the * rectangle is based on information contained in mapCell and the maximum * values of height and moisture. * * @param x * @param y * @param maxHeight * @param maxMoisture * @param colors */ public void drawMapCell(int x, int y, double maxHeight, double maxMoisture, Color[] colors) { double height = mapStorage.getMap()[x][y].getHeight(); double moisture = mapStorage.getMap()[x][y].getMoisture(); double landHeightRange = maxHeight - (waterlevel * maxHeight); double landHeight = height - (waterlevel * maxHeight); double heightShade = betweenZeroAndOne(height / maxHeight); double moistureShade = betweenZeroAndOne(moisture / maxMoisture); //double biomeShade = betweenZeroAndOne(landHeight / landHeightRange); double biomeShade = heightShade; String biome = mapStorage.getMap()[x][y].getBiome(); calculateWaterColor(heightShade); Color color = chooseColor(heightShade, moistureShade, biomeShade, biome); brush.setFill(color); brush.fillRect(x, y, 1, 1); } /** * Chooses the color of the rectangle based on given information. If * drawtype is height, then the color is a shade of grey based on * heightShade. If drawtype is moisture, then the color is a shade of grey * based on moistureShade. If drawtype is biome the method calls for another * method to choose the color of the biome. After that if the biome in this * location is biome that is selected for showing, the color is set to red. * * @param heightShade * @param moistureShade * @param biomeShade * @param biome * @return */ public Color chooseColor(double heightShade, double moistureShade, double biomeShade, String biome) { if (drawType.equals("height")) { int drawShade = (int) Math.round(heightShade * 255); return Color.grayRgb(drawShade); } else if (drawType.equals("moisture")) { int drawShade = (int) Math.round(moistureShade * 255); return Color.grayRgb(drawShade); } else { Color color = pickBiomeColor(biomeShade, biome); if (biome.equals(showBiome)) { color = Color.RED; } return color; } } /** * Picks correct brush color based on biome. If biomeDrawType is smooth, the * new biome colors are calculated based on shade. * * @param shade A height map based integer which can be used to affect color * @param biome An integer telling which biome to base color on * @return brush color */ public Color pickBiomeColor(double shade, String biome) { Color color; if (biomeDrawType.equals("shaded")) { fillColorArrayUsingShades((int) Math.round(shade * 255)); } color = getBiomeColor(biome); color = color.deriveColor(random.nextInt(1), 0.7 + random.nextDouble() * 0.3, 0.95 + random.nextDouble() * 0.05, 1); return color; } /** * Sets a different color to every biome. */ public void fillColorArray() { biomes.getBiomeColors()[1].setColor(Color.rgb(212, 230, 200)); //sand biomes.getBiomeColors()[2].setColor(Color.rgb(180, 230, 141)); //beachGrass biomes.getBiomeColors()[3].setColor(Color.rgb(140, 194, 132)); //beachForest biomes.getBiomeColors()[4].setColor(Color.rgb(154, 181, 138)); //dryGrass biomes.getBiomeColors()[5].setColor(Color.rgb(120, 200, 140)); //grass biomes.getBiomeColors()[6].setColor(Color.rgb(152, 222, 138)); //sparseLeaf biomes.getBiomeColors()[7].setColor(Color.rgb(120, 173, 95)); //dryGrassWithTrees biomes.getBiomeColors()[8].setColor(Color.rgb(84, 184, 84)); //leaf biomes.getBiomeColors()[9].setColor(Color.rgb(63, 166, 92)); //mixedForest biomes.getBiomeColors()[10].setColor(Color.rgb(102, 140, 80)); //dryLeaf biomes.getBiomeColors()[11].setColor(Color.rgb(71, 125, 57)); //taigaPine biomes.getBiomeColors()[12].setColor(Color.rgb(56, 128, 88)); //taigaSpruce biomes.getBiomeColors()[13].setColor(Color.rgb(120, 153, 112)); //dryMountainForest biomes.getBiomeColors()[14].setColor(Color.rgb(90, 153, 100)); //mountainForest biomes.getBiomeColors()[15].setColor(Color.rgb(100, 180, 130)); //tundra biomes.getBiomeColors()[16].setColor(Color.rgb(130, 162, 163)); //bare biomes.getBiomeColors()[17].setColor(Color.rgb(130, 162, 163)); //bare biomes.getBiomeColors()[18].setColor(Color.rgb(140, 180, 168)); //bareTundra biomes.getBiomeColors()[19].setColor(Color.rgb(110, 142, 145)); //volcano biomes.getBiomeColors()[20].setColor(Color.rgb(222, 234, 233)); //snow biomes.getBiomeColors()[21].setColor(Color.rgb(222, 234, 233)); //snow } /** * Sets a color to every biome that is calculated using a shade which varies * based on the height of the location. * * @param shade */ public void fillColorArrayUsingShades(int shade) { shade = betweenZeroAnd255(shade); biomes.getBiomeColors()[1].setColor(Color.rgb(Math.min(255, shade + 100), Math.min(255, shade + 100), Math.min(255, shade + 70))); //sand biomes.getBiomeColors()[2].setColor(Color.rgb(Math.min(255, shade + 60), Math.min(255, shade + 100), Math.min(255, shade + 20))); //beachGrass biomes.getBiomeColors()[3].setColor(Color.rgb(shade, Math.min(255, shade + 50), Math.max(0, shade - 20))); //beachForest biomes.getBiomeColors()[4].setColor(Color.rgb(Math.max(0, shade - 10), Math.min(255, shade + 30), Math.max(0, shade - 30))); //dryGrass biomes.getBiomeColors()[5].setColor(Color.rgb(Math.max(0, shade - 30), Math.min(255, shade + 50), Math.max(0, shade - 10))); //grass biomes.getBiomeColors()[6].setColor(Color.rgb(Math.min(255, shade), Math.min(255, shade + 100), Math.max(0, shade - 20))); //sparseLeaf biomes.getBiomeColors()[7].setColor(Color.rgb(Math.max(0, shade - 40), Math.min(255, shade + 20), Math.max(0, shade - 60))); //dryGrassWithTrees biomes.getBiomeColors()[8].setColor(Color.rgb(Math.max(0, shade - 60), Math.min(255, shade + 30), Math.max(0, shade - 60))); //leaf biomes.getBiomeColors()[9].setColor(Color.rgb(0, Math.min(255, shade + 20), Math.max(0, shade - 50))); //mixedForest biomes.getBiomeColors()[10].setColor(Color.rgb(Math.max(0, shade - 80), Math.max(0, shade - 40), Math.max(0, shade - 100))); //dryDeciduous biomes.getBiomeColors()[11].setColor(Color.rgb(Math.max(0, shade - 100), Math.max(0, shade - 40), Math.max(0, shade - 120))); //Pine biomes.getBiomeColors()[12].setColor(Color.rgb(Math.max(0, shade - 120), Math.max(0, shade - 50), Math.max(0, shade - 90))); //taigaSpruce biomes.getBiomeColors()[13].setColor(Color.rgb(Math.max(0, shade - 70), Math.max(0, shade - 40), Math.max(0, shade - 90))); //dryMountainForest biomes.getBiomeColors()[14].setColor(Color.rgb(Math.max(0, shade - 90), Math.max(0, shade - 30), Math.max(0, shade - 100))); //mountainForest biomes.getBiomeColors()[15].setColor(Color.rgb(Math.max(0, shade - 60), Math.max(0, shade - 5), Math.max(0, shade - 50))); //tundra biomes.getBiomeColors()[16].setColor(Color.rgb(Math.max(0, shade - 80), Math.max(0, shade - 60), Math.max(0, shade - 60))); //bare biomes.getBiomeColors()[17].setColor(Color.rgb(Math.max(0, shade - 80), Math.max(0, shade - 60), Math.max(0, shade - 60))); //bare biomes.getBiomeColors()[18].setColor(Color.rgb(Math.max(0, shade - 60), Math.max(0, shade - 30), Math.max(0, shade - 40))); //bareTundra biomes.getBiomeColors()[19].setColor(Color.rgb(Math.max(0, shade - 90), Math.max(0, shade - 80), Math.max(0, shade - 70))); //volcano biomes.getBiomeColors()[20].setColor(Color.rgb(Math.min(255, shade + 5), Math.min(255, shade + 5), Math.min(255, shade + 10))); //snow biomes.getBiomeColors()[21].setColor(Color.rgb(Math.min(255, shade + 5), Math.min(255, shade + 5), Math.min(255, shade + 10))); //snow } /** * Calculates the color of water using a shade which varies based on the * height of the location. * * @param shade */ public void calculateWaterColor(double shade) { double blueShade = shade * 255; blueShade = Math.min(140, blueShade); blueShade = Math.max(100, blueShade); int waterBlue = (int) Math.round(blueShade); int waterGreen = (int) Math.round(0.75 * blueShade); biomes.getBiomeColors()[0].setColor(Color.rgb(0, waterGreen, waterBlue)); } public double betweenZeroAndOne(double number) { if (number < 0) { return 0; } if (number > 1) { return 1; } return number; } public int betweenZeroAnd255(double number) { if (number < 0) { return 0; } if (number > 255) { return 255; } return (int) Math.round(number); } public void setBiomeDrawType(String biomeDrawType) { this.biomeDrawType = biomeDrawType; } public void setDrawType(String drawType) { this.drawType = drawType; } public void setShowBiome(String showBiome) { this.showBiome = showBiome; } /** * Returns the color currently paired with given biome. * * @param biome * @return */ public Color getBiomeColor(String biome) { BiomeColor[] biomeColors = biomes.getBiomeColors(); for (int i = 0; i < biomeColors.length; i++) { if (biomeColors[i].getBiome().equals(biome)) { return biomeColors[i].getColor(); } } return biomeColors[0].getColor(); } }
package fr.lteconsulting.formations; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashSet; import java.util.Set; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; /** * Servlet Filter implementation class Angular2GwtFilter */ @WebFilter( "/" ) public class Angular2GwtFilter implements Filter { private Set<String> servedStaticFiles = new HashSet<>(); public Angular2GwtFilter() { servedStaticFiles.add( "/Reflect.js" ); servedStaticFiles.add( "/zone.js" ); servedStaticFiles.add( "/angular2-all.umd.js" ); } @Override public void init( FilterConfig filterConfig ) throws ServletException { } public void destroy() { } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { if( request instanceof HttpServletRequest ) { HttpServletRequest httpRequest = (HttpServletRequest) request; String uri = httpRequest.getRequestURI(); int lastSlashIndex = uri.lastIndexOf( "/" ); if( lastSlashIndex >= 0 ) { String requestedFile = uri.substring( lastSlashIndex ); if( servedStaticFiles.contains( requestedFile ) ) { InputStream resource = getClass().getClassLoader().getResourceAsStream( "/static" + requestedFile ); response.setContentType( "text/javascript" ); response.setCharacterEncoding( "UTF-8" ); pipe( resource, response.getOutputStream() ); return; } } } chain.doFilter( request, response ); } private void pipe( InputStream is, OutputStream os ) throws IOException { int n; byte[] buffer = new byte[1024]; while( (n = is.read( buffer )) > -1 ) os.write( buffer, 0, n ); os.close(); is.close(); } }
/** * */ package edu.fjnu.smd.controller; import java.util.Map; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.Errors; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; import edu.fjnu.smd.domain.User; import edu.fjnu.smd.exception.SMDException; import edu.fjnu.smd.service.UserService; /** * @author xiaoze * */ @Controller @SessionAttributes(value={"loginedUser"}) @RequestMapping("/security") public class SecurityController extends BaseController{ @Autowired private UserService userService ; public void setUserService(UserService userService) { this.userService = userService; } @RequestMapping("/toLogin") public String toLogin(Map<String, Object> map) throws Exception { System.out.println("进来了进来了进来了进来了进来了"); map.put("user", new User()); return "login"; } @RequestMapping(value="/login", method=RequestMethod.POST) public String login(@Valid User user, Errors result,Map<String, Object> map) throws Exception { try { User dbUser = userService.get(user.getUserNo()); if(result.getErrorCount() > 0){ System.out.println("出错了!"); for(FieldError error:result.getFieldErrors()){ System.out.println(error.getField() + ":" + error.getDefaultMessage()); } }else if (dbUser==null){ map.put("userError", "用户不存在,请检查!"); } else if (!(dbUser.getUserPwd().equals(user.getUserPwd()))) { map.put("userPwdError", "用户密码不正确,请检查!"); }else { map.put("loginedUser", dbUser); System.out.println("啊啊啊啊啊 啊啊啊啊 啊啊啊"); return "redirect:/security/mainController"; } } catch (SMDException e) { map.put("exceptionMessage", e.getMessage()); } return "login"; } @RequestMapping("/mainController") public String main() throws Exception{ return "main"; } @RequestMapping("/logout") public String logout(SessionStatus status) throws Exception{ status.setComplete(); return "redirect:/security/toLogin"; } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.common.predicate; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.category.model.CategoryModel; import de.hybris.platform.cmsfacades.common.service.ProductCatalogItemModelFinder; import de.hybris.platform.servicelayer.exceptions.UnknownIdentifierException; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @UnitTest @RunWith(MockitoJUnitRunner.class) public class CategoryExistsPredicateTest { @InjectMocks private CategoryExistsPredicate predicate; @Mock private ProductCatalogItemModelFinder productCatalogItemModelFinder; @Test public void shouldFail_CategoryCodeNotFound() { final String invalidKey = "invalid"; when(productCatalogItemModelFinder.getCategoryForCompositeKey(invalidKey)) .thenThrow(new UnknownIdentifierException("invalid key")); final boolean result = predicate.test(invalidKey); assertFalse(result); } @Test public void shouldPass_CategoryCodeExists() { final String validKey = "apple-staged-phone"; when(productCatalogItemModelFinder.getCategoryForCompositeKey(validKey)).thenReturn(new CategoryModel()); final boolean result = predicate.test(validKey); assertTrue(result); } }
package com.java.rest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.java.error.NotFoundException; import java.util.List; import java.util.Optional; import static java.util.stream.Collectors.toList; /** * This service class saves {@link com.java.rest.BillOfMaterials} objects * to MongoDB database. */ @Service public final class MongoDBBillOfMaterialsService implements BillOfMaterialsService { private static final Logger LOGGER = LoggerFactory.getLogger(MongoDBBillOfMaterialsService.class); private final BillOfMaterialsRepository repository; @Autowired public MongoDBBillOfMaterialsService(BillOfMaterialsRepository repository) { this.repository = repository; } @Override public BillOfMaterialsDTO create(BillOfMaterialsDTO billOfMaterials) { LOGGER.info("Creating a new bill of materials entry with information: {}", billOfMaterials); BillOfMaterials persisted = BillOfMaterials.getBuilder() .description(billOfMaterials.getDescription()) .parts(billOfMaterials.getParts()) .build(); persisted = repository.save(persisted); LOGGER.info("Created a new bill of materials entry with information: {}", persisted); return convertToDTO(persisted); } @Override public BillOfMaterialsDTO delete(String id) { LOGGER.info("Deleting a bill of materials entry with id: {}", id); BillOfMaterials deleted = findbillOfMaterialsById(id); repository.delete(deleted); LOGGER.info("Deleted bill of materials entry with informtation: {}", deleted); return convertToDTO(deleted); } @Override public List<BillOfMaterialsDTO> findAll() { LOGGER.info("Finding all bill of materials entries."); List<BillOfMaterials> billOfMaterialsEntries = repository.findAll(); LOGGER.info("Found {} billOfMaterials entries", billOfMaterialsEntries.size()); return convertToDTOs(billOfMaterialsEntries); } private List<BillOfMaterialsDTO> convertToDTOs(List<BillOfMaterials> models) { return models.stream() .map(this::convertToDTO) .collect(toList()); } @Override public BillOfMaterialsDTO findById(String id) { LOGGER.info("Finding bill of materials entry with id: {}", id); BillOfMaterials found = findbillOfMaterialsById(id); LOGGER.info("Found bill of materials entry: {}", found); return convertToDTO(found); } @Override public BillOfMaterialsDTO update(BillOfMaterialsDTO billOfMaterials) { LOGGER.info("Updating bill of materials entry with information: {}", billOfMaterials); BillOfMaterials updated = findbillOfMaterialsById(billOfMaterials.getId()); updated.update(billOfMaterials.getDescription(), billOfMaterials.getParts()); updated = repository.save(updated); LOGGER.info("Updated bill of materials entry with information: {}", updated); return convertToDTO(updated); } private BillOfMaterials findbillOfMaterialsById(String id) { Optional<BillOfMaterials> result = repository.findOne(id); return result.orElseThrow(() -> new NotFoundException(id)); } private BillOfMaterialsDTO convertToDTO(BillOfMaterials model) { BillOfMaterialsDTO dto = new BillOfMaterialsDTO(); dto.setId(model.getId()); dto.setDescription(model.getDescription()); dto.setParts(model.getParts()); return dto; } }
package ru.sberbank.ex2.steps; import io.qameta.allure.Step; import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebDriver; import ru.sberbank.ex2.GeneralMethods; import ru.sberbank.ex2.pageObjects.TravelInsurancePage; public class TravelIsuranceSteps { private WebDriver driver; private TravelInsurancePage travelInsurancePage; public TravelIsuranceSteps(WebDriver driver) { this.driver = driver; this.travelInsurancePage = new TravelInsurancePage(driver); } @Step("Наличие на странице заголовка – {titleText}") public void checkTitle(String titleText) { if(travelInsurancePage.checkTravelInsuranceTitle(titleText)) { Assertions.assertTrue(true); } else { GeneralMethods.getScreenshot(driver); Assertions.assertTrue(false, "Заголовок - " + titleText + " не найден"); } } @Step("Нажать кнопку 'Оформить онлайн'") public void clickIssueOnlineButton() { travelInsurancePage.clickIssueOnlineButton(); } }
package ca.csf.dfc.poo.Observer.classes; import java.util.Observable; public class BinaryObserver extends Observer implements java.util.Observer{ public BinaryObserver(Subject subject){ this.subject = subject; this.subject.attach(this); } @Override public void update(Observable o, Object arg) { System.out.println( "Binary String: " + Integer.toBinaryString( subject.getState() ) ); } @Override public void update() { // TODO Auto-generated method stub } }
#include<iostream> using namespace std; int main() { int n,start=6,factor=5; cin>>n; int i=1; cout<<start<<" "; for(i=1;n>1;i++,n--) { start=start+factor*i; cout<<start<<" "; } }
package org.lxy.thread; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * @author menglanyingfei * @date 2017-4-16 */ public class Demo4_ReentrantLock { public static void main(String[] args) { final Printer1 p = new Printer1(); new Thread() { public void run() { while (true) { try { p.print1(); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (true) { try { p.print2(); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); } } class Printer1 { private ReentrantLock r = new ReentrantLock(); private Condition c1 = r.newCondition(); private Condition c2 = r.newCondition(); private int flag = 1; public void print1() throws InterruptedException { r.lock(); if (flag != 1) { c1.await(); } System.out.print("黑"); System.out.print("马"); System.out.print("程"); System.out.print("序"); System.out.print("员"); System.out.print("\r\n"); flag = 2; c2.signal(); r.unlock(); } public void print2() throws InterruptedException { r.lock(); if (flag != 2) { c2.await(); } System.out.print("传"); System.out.print("智"); System.out.print("播"); System.out.print("客"); System.out.print("\r\n"); flag = 1; c1.signal(); r.unlock(); } }
package soduku.main; import java.util.ArrayList; public class SodukuField { SodukuCell[][] sodukuField = new SodukuCell[9][9]; String message; public SodukuField(){ ArrayList<NumberContainer> rowNumberContainerList = new ArrayList<NumberContainer>(); ArrayList<NumberContainer> columnNumberContainerList = new ArrayList<NumberContainer>(); ArrayList<NumberContainer> blockContainerList = new ArrayList<NumberContainer>(); this.message = "New field"; for(int i=0; i < 9; i++){ rowNumberContainerList.add(new NumberContainer()); columnNumberContainerList.add(new NumberContainer()); blockContainerList.add(new NumberContainer()); } for(int row=0; row < 9; row++){ for(int column=0; column < 9;column++) { NumberContainer rowNumberContainer = rowNumberContainerList.get(row); NumberContainer columnNumberContainer = columnNumberContainerList.get(column); int blockNumberOfCoordinates = this.getBlockNumberOfCoordinates(new Coordinates(row, column)); NumberContainer blockNumberContainer = blockContainerList.get(blockNumberOfCoordinates); this.sodukuField[row][column] = new SodukuCell(rowNumberContainer, columnNumberContainer, blockNumberContainer); } } } public boolean areValidCoordinates(Coordinates invalidCoords) { return (this.numberIsWithinCoordinateBounds(invalidCoords.row) && this.numberIsWithinCoordinateBounds(invalidCoords.column)); } private boolean numberIsWithinCoordinateBounds(int number){ boolean result = false; if(number >= 0 && number <= 8) { result = true; } return result; } public ArrayList<Integer> getNumbersAt(Coordinates coordinates) throws Exception { if( this.areValidCoordinates(coordinates)){ return this.sodukuField[coordinates.row][coordinates.column].getAvailableNumbers(); }else { throw new Exception("Coordinates are invalid"); } } public int getIndexOfCellCoordinates(Coordinates coordinates) { return (coordinates.row * 8) + coordinates.row + coordinates.column; } public int getBlockNumberOfCoordinates(Coordinates coordinates) { int rowValue = (coordinates.row / 3) * 3; int columnValue = (coordinates.column / 3); return (rowValue + columnValue); } public String toString(){ final String FATLINE = "===================\n"; String result = ""; String tail = "|"; result = result + FATLINE; for(int row=0; row < 9; row++){ for(int column=0; column < 9;column++) { if(column % 3 == 0){ result = result + "║"; }if( (column + 1) % 3 == 0 && column != 8){ tail = ""; }else if( column == 8) { tail = "║"; }else { tail = "|"; } result = result + this.sodukuField[row][column] + tail; } if(row > 0 && (row + 1) % 3 == 0) { result = result + "\n" + FATLINE; }else{ result = result + "\n"; } } return result; } public void setNumber(Coordinates coordinates, int number) throws Exception{ if(this.areValidCoordinates(coordinates)){ this.sodukuField[coordinates.row][coordinates.column].setNumber(number); }else{ throw new Exception("Coordinates are invalid"); } } }
package Manufacturing.ProductLine; /** * TODO:抽象工厂生成类 * * @author 孟繁霖 * @date 2021-10-11 23:39 */ public class FactoryProducer { public static Factory getAbstractFactory(String lineName) { if ("fruit".equalsIgnoreCase(lineName)) { return new FruitLineFactory(); } else if ("fresh".equalsIgnoreCase(lineName)) { return new FreshLineFactory(); } else return null; } }
package org.corbin.common.base.convert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import java.util.ArrayList; import java.util.List; /** * @Author: Corbin * @Date: 2018/12/4 * @ClassName: BaseConvert * @Descripton: */ public class BaseConvert<VO,DO> { private static final Logger logger = LoggerFactory.getLogger(BaseConvert.class); /** * 单个对象转换 * @param from 需要转换的对象 * @param clazz 转成的目标对象类 * @return */ public VO convert(DO from, Class<VO> clazz) { return convert(from, clazz, null); } public DO counvert2Entity(VO from,Class<DO> clazz){ return convert2Entity(from,clazz,null); } /** * 单个对象转换 * * @param from 需要转换的对象 * @param clazz 转成的目标对象类 * @param ignoreProperties 转换对象中,不需要copy的属性 */ public VO convert(DO from, Class<VO> clazz, String... ignoreProperties) { if (from == null) { return null; } VO to = null; try { to = clazz.newInstance(); } catch (ReflectiveOperationException e) { e.printStackTrace(); logger.error("初始化{}对象失败。", clazz, e); } convert(from, to, ignoreProperties); return to; } /** * 单个对象转换 * * @param from 需要转换的对象 * @param clazz 转成的目标对象类 * @param ignoreProperties 转换对象中,不需要copy的属性 */ public DO convert2Entity(VO from, Class<DO> clazz, String... ignoreProperties) { if (from == null) { return null; } DO to = null; try { to = clazz.newInstance(); } catch (ReflectiveOperationException e) { e.printStackTrace(); logger.error("初始化{}对象失败。", clazz, e); } convert2Entity(from, to, ignoreProperties); return to; } /** * 批量对象转换 * @param fromList 需要转换的对象列表 * @param clazz 转成的目标对象类 */ public List<VO> convert(List<DO> fromList, Class<VO> clazz) { return convert(fromList, clazz, null); } /** * 批量对象转换 * * @param fromList 需要转换的对象列表 * @param clazz 转成的目标对象类 * @param ignoreProperties 转换对象中,不需要copy的属性 */ public List<VO> convert(List<DO> fromList, Class<VO> clazz, String... ignoreProperties) { List<VO> toList = new ArrayList<VO>(); if (fromList != null) { for (DO from : fromList) { toList.add(convert(from, clazz, ignoreProperties)); } } return toList; } /** * 分页对象转换 * @param fromPage 需要转换的分页对象 * @param clazz 转成的目标对象类 */ public Page<VO> convert(Page<DO> fromPage, Class<VO> clazz) { return convert(fromPage, clazz, null); } /** * 分页对象转换 * * @param fromPage 需要转换的分页对象 * @param clazz 转成的目标对象类 * @param ignoreProperties 转换对象中,不需要copy的属性 */ public Page<VO> convert(Page<DO> fromPage, Class<VO> clazz, String... ignoreProperties) { List<VO> voContent = new ArrayList(); PageRequest pageRequest = null; if (fromPage != null && fromPage.getContent() != null) { voContent = convert(fromPage.getContent(), clazz, ignoreProperties); pageRequest = new PageRequest(fromPage.getNumber(), fromPage.getSize(), fromPage.getSort()); } Page<VO> voPage = new PageImpl<>(voContent, pageRequest, fromPage.getTotalElements()); return voPage; } /** * 属性拷贝方法,有特殊需求时子类覆写此方法 */ protected void convert(DO from, VO to) { convert(from, to, null); } protected void convert2Entity(VO from,DO to){ convert2Entity(from,to,null); } /** * 对象装换 * * @param from 需要转换的对象 * @param to 转换成的目标对象 * @param ignoreProperties 目标对象中不需要转换的属性 */ protected void convert(DO from, VO to, String... ignoreProperties) { BeanUtils.copyProperties(from, to, ignoreProperties); } /** * 对象装换 * * @param from 需要转换的对象 * @param to 转换成的目标对象 * @param ignoreProperties 目标对象中不需要转换的属性 */ protected void convert2Entity(VO from, DO to, String... ignoreProperties) { BeanUtils.copyProperties(from, to, ignoreProperties); } }
package com.fleet.forest.consumer; import com.thebeastshop.forest.springboot.annotation.ForestScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @ForestScan(basePackages = "com.fleet.forest.consumer.service") public class ForestConsumerApplication { public static void main(String[] args) { SpringApplication.run(ForestConsumerApplication.class, args); } }
package com.example.calendarbuilderexample; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import java.util.Date; public class MainActivity extends Activity implements CalendarDialogBuilder.OnDateSetListener { private Date initialDate = new Date(); private Date startDate = new Date(); private Date endDate = new Date(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startDate.setYear(2015); startDate.setMonth(10); startDate.setDate(1); initialDate.setYear(2015); initialDate.setMonth(10); initialDate.setDate(5); endDate.setYear(2015); endDate.setMonth(10); endDate.setDate(25); } // That is the method of OnDateSetListener interface of CalendarDialogBuilder class @Override public void onDateSet(int Year, int Month, int Day) { TextView txt = (TextView) findViewById(R.id.text1); txt.setText(Month + "/" + Day + "/" + Year); } // This is the button method, were we call the calendar. public void selectDate(View v) { CalendarDialogBuilder calendar; if(initialDate != null) { calendar = new CalendarDialogBuilder(this, this, initialDate.getTime()); } else { calendar = new CalendarDialogBuilder(this, this); } calendar.setStartDate(startDate.getTime()); calendar.setEndDate(endDate.getTime()); calendar.showCalendar(); } }
import static org.junit.Assert.*; import org.junit.Test; import br.ita.sem1dia1.IntroducaoJavaOo.Carro; public class TesteCArro { @Test public void testAcelerar() { Carro c = new Carro(); c.potencia = 10; c.acelerar(); assertEquals(10, c.getVelocidade()); } @Test public void testCarroParado() { Carro c = new Carro(); assertEquals(0, c.getVelocidade()); } @Test public void testFrear() { Carro c = new Carro(); c.potencia = 10; c.acelerar(); c.frear(); assertEquals(5, c.getVelocidade()); } @Test public void testFrearAteZero() { Carro c = new Carro(); c.potencia = 10; c.acelerar(); c.frear(); //na primeira ele arrendonda para baixo...2 c.frear(); c.frear(); c.frear(); assertEquals(0, c.getVelocidade()); } }
package Selinium; public class Q13Palindrom { public static void main(String[] args) { int ans = 0 ; for(int no=90;no<=120;no++) { int n1 = no; int n3 = 0; while(n1!=0) { int x = n1 % 10; n3 = (n3 * 10) + x; n1 = n1/10; } if(no==n3) { ans = ans + no; } }System.out.println(ans); } }
package com.awsp8.wizardry.gui; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.util.ResourceLocation; import com.awsp8.wizardry.Arcane.Blocks.ArcaneSlot; import com.awsp8.wizardry.Arcane.Blocks.ContainerArcaneHarnesser; import com.awsp8.wizardry.Arcane.Blocks.TileEntityArcaneHarnesser; public class ArcaneHarnesserGui extends GuiContainer{ private TileEntityArcaneHarnesser tileEntity; public ArcaneHarnesserGui(InventoryPlayer inv, TileEntityArcaneHarnesser tileEntity) { super(new ContainerArcaneHarnesser(inv, tileEntity)); this.tileEntity = tileEntity; } public static final int GUI_ID = 20; private static final ResourceLocation guiTexture = new ResourceLocation("wizardry", "/textures/gui/arcaneHarnesserGui.png"); private int ImageWidth = 176; private int ImageHeight = 166; @Override public void drawScreen(int x, int y, float par3){ int k = (this.width - this.ImageWidth) / 2; byte b0 = 2; this.mc.getTextureManager().bindTexture(guiTexture); this.drawTexturedModalRect(k, b0, 0, 0, this.ImageWidth, this.ImageHeight); } @Override protected void drawGuiContainerBackgroundLayer(float p_146976_1_, int p_146976_2_, int p_146976_3_) { } }
package com.tencent.mm.plugin.wallet.balance.a.a; import com.tencent.mm.protocal.c.bft; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.vending.g.b; import com.tencent.mm.vending.g.g; import com.tencent.mm.vending.h.e; public class n$c implements e<bft, com.tencent.mm.vending.j.e<Integer, String, String, Integer>> { final /* synthetic */ n oZh; public n$c(n nVar) { this.oZh = nVar; } public final /* synthetic */ Object call(Object obj) { com.tencent.mm.vending.j.e eVar = (com.tencent.mm.vending.j.e) obj; m mVar = this.oZh.oZc; int intValue = ((Integer) eVar.get(0)).intValue(); String str = (String) eVar.get(1); x.i("MicroMsg.LqtSaveFetchInteractor", "do lqtRedeemFund, redeemListId: %s, accountType: %s", new Object[]{(String) eVar.get(2), Integer.valueOf(((Integer) eVar.get(3)).intValue())}); x.d("MicroMsg.LqtSaveFetchInteractor", "do lqtRedeemFund, redeemFee: %s, payPasswdEnc: %s, redeemListId: %s", new Object[]{Integer.valueOf(intValue), str, r1}); b cBF = g.cBF(); cBF.cBE(); new h(intValue, str, r1, r2).KM().f(new m$3(mVar, cBF)); return null; } public final String xr() { return "Vending.UI"; } }
package fr.mb.volontario.model.bean; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonManagedReference; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import javax.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Objects; import java.util.Set; @Entity @Table(name = "mission") @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class Mission implements Serializable { private Integer idMission; private String nom; private String description; private String complement; private String competence; private Set<Inscription> inscriptions=new HashSet<>(); private Association association; private Adresse adresse; private Domaine domaine; public Mission() { } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_mission", nullable = false, unique = true) public Integer getIdMission() { return idMission; } public void setIdMission(Integer idMission) { this.idMission = idMission; } @Basic @Column(name = "nom", nullable = false) public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } @Basic @Column(name = "description", nullable = false) public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Basic @Column(name = "complement", nullable = true) public String getComplement() { return complement; } public void setComplement(String complement) { this.complement = complement; } @Basic @Column(name = "competence", nullable = false) public String getCompetence() { return competence; } public void setCompetence(String competence) { this.competence = competence; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Mission mission = (Mission) o; return Objects.equals(nom, mission.nom) && Objects.equals(description, mission.description) && Objects.equals(complement, mission.complement) && Objects.equals(competence, mission.competence); } @Override public int hashCode() { return Objects.hash(nom, description, complement, competence); } @OneToMany(mappedBy = "mission", cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JsonManagedReference(value = "mission-inscri") public Set<Inscription> getInscriptions() { return inscriptions; } public void setInscriptions(Set<Inscription> inscriptions) { this.inscriptions = inscriptions; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_association", referencedColumnName = "id_association", nullable = false) public Association getAssociation() { return association; } public void setAssociation(Association association) { this.association = association; } @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY) @JoinColumn(name = "id_adresse", referencedColumnName = "id_adresse", nullable = false) public Adresse getAdresse() { return adresse; } public void setAdresse(Adresse adresse) { this.adresse = adresse; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_domaine", referencedColumnName = "id_domaine", nullable = false) public Domaine getDomaine() { return domaine; } public void setDomaine(Domaine domaine) { this.domaine = domaine; } }
package symblink.com.track_me; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.view.Menu; import android.widget.Toast; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import android.database.sqlite.SQLiteDatabase; /** * Created by Meraj Ahmed on 10/6/2016. */ public class BackgroundTask extends AsyncTask<String, Void, String> { Context ctx; String logid,log; AlertDialog alertDialog; BackgroundTask(Context ctx){ this.ctx=ctx; } @Override protected void onPreExecute(){ alertDialog=new AlertDialog.Builder(ctx).create(); alertDialog.setTitle("Login Information"); } @Override protected String doInBackground(String... params) { String method=params[0]; String reg_url="http://10.0.2.2/appdb/register.php"; String login_url="http://10.0.2.2/appdb/login.php"; if (method.equals("registeration")){ String stuname=params[1]; String stuid=params[2]; String stupass=params[3]; String stuprg=params[4]; String stucontact=params[5]; String stuadd=params[6]; String stufee=params[7]; try { URL url=new URL(reg_url); HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); OutputStream OS=httpURLConnection.getOutputStream(); BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(OS,"UTF-8")); String data= URLEncoder.encode("stuname","UTF-8")+"="+ URLEncoder.encode(stuname,"UTF-8")+"&" + URLEncoder.encode("stuid","UTF-8")+"="+ URLEncoder.encode(stuid,"UTF-8")+"&"+ URLEncoder.encode("stupass","UTF-8")+"="+ URLEncoder.encode(stupass,"UTF-8")+"&"+ URLEncoder.encode("stuprg","UTF-8")+"="+ URLEncoder.encode(stuprg,"UTF-8")+"&" + URLEncoder.encode("stucontact","UTF-8")+"="+ URLEncoder.encode(stucontact,"UTF-8")+"&" + URLEncoder.encode("stuadd","UTF-8")+"="+ URLEncoder.encode(stuadd,"UTF-8") +"&" + URLEncoder.encode("stufee","UTF-8")+"="+ URLEncoder.encode(stufee,"UTF-8"); bufferedWriter.write(data); bufferedWriter.flush(); bufferedWriter.close(); OS.close(); InputStream IS=httpURLConnection.getInputStream(); IS.close(); return "Success"; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else if (method.equals("login")) { String logid = params[1]; String logpass = params[2]; try { URL url = new URL(login_url); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); OutputStream outputStream = httpURLConnection.getOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); String data = URLEncoder.encode("logid", "UTF-8") + "=" + URLEncoder.encode(logid, "UTF-8") + "&" + URLEncoder.encode("logpass", "UTF-8") + "=" + URLEncoder.encode(logpass, "UTF-8"); bufferedWriter.write(data); bufferedWriter.flush(); bufferedWriter.close(); outputStream.close(); InputStream inputStream = httpURLConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1")); String response = ""; String line = ""; while ((line = bufferedReader.readLine()) != null) { response += line; } bufferedReader.close(); inputStream.close(); httpURLConnection.disconnect(); return response; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // return null; } @Override protected void onProgressUpdate(Void... values){ super.onProgressUpdate(values); } @Override protected void onPostExecute(String result) { if(result == null) { alertDialog.setMessage("Please Fill In Login Information"); // do what you want to do } if(result.equals("Success")){ Toast.makeText(ctx,result, Toast.LENGTH_LONG).show(); Intent i = new Intent(ctx,MainActivity.class); ctx.startActivity(i); } else if(result.contains("Login Successful")) // msg you get from success like "Login Success" { MainActivity mm=new MainActivity(); Intent i = new Intent(ctx,Menu.class); ctx.startActivity(i); alertDialog.setMessage(result); alertDialog.show(); } else { alertDialog.setMessage(result); alertDialog.show(); } } }
package jneiva.hexbattle.estado; import java.util.List; import java.util.concurrent.TimeUnit; import com.badlogic.gdx.graphics.Color; import jneiva.hexbattle.ControladorBatalha; import jneiva.hexbattle.ControladorEstrutura; import jneiva.hexbattle.ControladorTurnos; import jneiva.hexbattle.componente.Movimento; import jneiva.hexbattle.eventos.EventoCelula; import jneiva.hexbattle.tiles.Celula; import jneiva.hexbattle.unidade.Unidade; public class EstadoMovimento extends EstadoBatalha { private Unidade unidadeAtual; private Celula alvo; ControladorTurnos controlador; public EstadoMovimento(ControladorBatalha d, Celula alvo) { super(d); this.alvo = alvo; } @Override public void entrar() { super.entrar(); System.out.println("Entrou Movimento!"); controlador = this.dono.controladorTurnos; unidadeAtual = controlador.getUnidadeAtual(); List<Celula> caminho = getMapa().buscaCaminho(unidadeAtual.getCelula(), alvo, unidadeAtual.equipe.getTime(), true); unidadeAtual.movimento.atravessar(caminho); this.dono.mudarEstado(new EstadoEscolherAcao(this.dono)); } }
package org.utarid.room; import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.snackbar.Snackbar; import org.utarid.room.databinding.ActivityMainBinding; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private ActivityMainBinding binding; private DatabaseWorker databaseWorker; private List<EntityWorker> globalWorkersList; private AdapterWorker mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); View view = binding.getRoot(); setContentView(view); databaseWorker = DatabaseWorker.getInstance(this); globalWorkersList = new ArrayList<>(); RecyclerView recyclerView = binding.recyclerView; mAdapter = new AdapterWorker(this, globalWorkersList); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(mAdapter); binding.btnInsertWorker.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { insertWorker(); } }); binding.btnGetAllWorkers.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getAllWorkers(); } }); binding.btnDeleteWorker.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { deleteWorker(); } }); } public void insertWorker() { new Thread(new Runnable() { @Override public void run() { EntityWorker worker = new EntityWorker(binding.txtInsertWorkerName.getText().toString(), binding.txtInsertWorkerSurname.getText().toString(), binding.txtInsertWorkerAge.getText().toString()); long newInsertedID = databaseWorker.daoWorker().insertWorker(worker); Snackbar snackbar = Snackbar.make(binding.mainLayout, "id : " + newInsertedID + " is added", Snackbar.LENGTH_LONG); snackbar.show(); } }).start(); } public void deleteWorker() { new Thread(new Runnable() { @Override public void run() { EntityWorker worker = new EntityWorker(Integer.parseInt(binding.txtDeleteWorkderID.getText().toString())); int deletedRow = databaseWorker.daoWorker().deleteWorker(worker); Snackbar snackbar; if (deletedRow == 1) { snackbar = Snackbar.make(binding.mainLayout, "id : " + binding.txtDeleteWorkderID.getText().toString() + " is deleted", Snackbar.LENGTH_LONG); } else { snackbar = Snackbar.make(binding.mainLayout, "deletion is not successful", Snackbar.LENGTH_LONG); } snackbar.show(); } }).start(); } public void getAllWorkers() { new Thread(new Runnable() { @Override public void run() { globalWorkersList.clear(); List<EntityWorker> workersList = databaseWorker.daoWorker().getAllWorkers(); runOnUiThread(new Runnable() { @Override public void run() { globalWorkersList.addAll(workersList); mAdapter.notifyDataSetChanged(); } }); } }).start(); } }
package org.dkni.experimental.dao; import org.dkni.experimental.domain.MealType; import java.util.List; /** * Created by DK on 08.01.2016. */ public interface MealTypeDao { void addMealType(MealType mealType); MealType getMealTypeById(Long id); List<MealType> getAllMealTypes(); }
/** * \file UserDefinedSimbolization.java * This class represents the UserDefinedSimbolization node of the XML. */ package br.org.funcate.glue.model.xml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; /** * * \brief This class represents the UserDefinedSimbolization node of the XML. * * @author Emerson Leite de Moraes * @author Willyan Aleksander * * Version 1.0 */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "_value" }) @XmlRootElement(name = "UserDefinedSymbolization") public class UserDefinedSymbolization { @XmlValue protected String _value; @XmlAttribute(name = "SupportSLD") protected Byte _supportSLD; @XmlAttribute(name = "UserLayer") protected Byte _userLayer; @XmlAttribute(name = "UserStyle") protected Byte _userStyle; @XmlAttribute(name = "RemoteWFS") protected Byte _remoteWFS; /** * \brief Gets the value of the value property. * * @return possible object is {@link String } * */ public String getValue() { return _value; } /** * \brief Sets the value of the value property. * * @param value * allowed object is {@link String } * */ public void setValue(String value) { this._value = value; } /** * \brief Gets the value of the supportSLD property. * * @return possible object is {@link Byte } * */ public Byte getSupportSLD() { return _supportSLD; } /** * \brief Sets the value of the supportSLD property. * * @param value * allowed object is {@link Byte } * */ public void setSupportSLD(Byte value) { this._supportSLD = value; } /** * \brief Gets the value of the userLayer property. * * @return possible object is {@link Byte } * */ public Byte getUserLayer() { return _userLayer; } /** * \brief Sets the value of the userLayer property. * * @param value * allowed object is {@link Byte } * */ public void setUserLayer(Byte value) { this._userLayer = value; } /** * \brief Gets the value of the userStyle property. * * @return possible object is {@link Byte } * */ public Byte getUserStyle() { return _userStyle; } /** * \brief Sets the value of the userStyle property. * * @param value * allowed object is {@link Byte } * */ public void setUserStyle(Byte value) { this._userStyle = value; } /** * \brief Gets the value of the remoteWFS property. * * @return possible object is {@link Byte } * */ public Byte getRemoteWFS() { return _remoteWFS; } /** * \brief Sets the value of the remoteWFS property. * * @param value * allowed object is {@link Byte } * */ public void setRemoteWFS(Byte value) { this._remoteWFS = value; } }
package com.jim.multipos.core; import android.graphics.Color; import android.text.Editable; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.jim.mpviews.MpEditText; import com.jim.multipos.R; import com.jim.multipos.utils.DateIntervalPicker; import com.jim.multipos.utils.ExportDialog; import java.text.SimpleDateFormat; import java.util.Calendar; import butterknife.BindView; import butterknife.OnClick; import butterknife.OnTextChanged; public abstract class BaseTableReportFragment extends BaseFragment { @BindView(R.id.tvDateInterval) TextView tvDateInterval; @BindView(R.id.llDateInterval) LinearLayout llDateInterval; @BindView(R.id.ivSearchImage) ImageView ivSearchImage; @BindView(R.id.mpSearchEditText) MpEditText mpSearchEditText; @BindView(R.id.llChooseTill) LinearLayout llChooseTill; @BindView(R.id.tvFirtPanel) TextView tvFirtPanel; @BindView(R.id.tvSecondPanel) TextView tvSecondPanel; @BindView(R.id.tvThirdPanel) TextView tvThirdPanel; @BindView(R.id.tvFourPanel) TextView tvFourPanel; @BindView(R.id.tvFivePanel) TextView tvFivePanel; @BindView(R.id.llChoiserPanel) LinearLayout llChoiserPanel; @BindView(R.id.llFilter) LinearLayout llFilter; @BindView(R.id.llExpert) LinearLayout llExpert; @BindView(R.id.tvTitleReport) TextView tvTitleReport; @BindView(R.id.llSearch) LinearLayout llSearch; @BindView(R.id.flTable) FrameLayout flTable; @BindView(R.id.pbLoading) ProgressBar pbLoading; int panelCount = 0; private BaseTableReportPresenter baseTableReportPresenter; private SimpleDateFormat simpleDateFormat; protected BaseTableReportFragment() { simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm"); } @Override protected int getLayout() { return R.layout.report_fragment; } protected void init(BaseTableReportPresenter baseTableReportPresenter) { this.baseTableReportPresenter = baseTableReportPresenter; } public void setTable(FrameLayout frameLayout) { flTable.removeAllViews(); flTable.addView(frameLayout); pbLoading.setVisibility(View.GONE); } public ProgressBar getPbLoading() { return pbLoading; } public void disableSearch() { llSearch.setVisibility(View.GONE); } public void enableSearch() { llSearch.setVisibility(View.VISIBLE); } public void disableFilter() { llFilter.setVisibility(View.GONE); } public void enableFilter() { llFilter.setVisibility(View.VISIBLE); } public void enableTillChooseBtn() { llChooseTill.setVisibility(View.VISIBLE); } public void disableTillChooseBtn() { llChooseTill.setVisibility(View.GONE); } public void disableDateIntervalPicker() { llDateInterval.setVisibility(View.GONE); tvDateInterval.setVisibility(View.INVISIBLE); } public void disableExport() { llExpert.setVisibility(View.GONE); } public void enableDateIntervalPicker() { llDateInterval.setVisibility(View.VISIBLE); tvDateInterval.setVisibility(View.VISIBLE); } public void updateDateIntervalUi(Calendar fromDate, Calendar toDate) { tvDateInterval.setText(simpleDateFormat.format(fromDate.getTime()) + " - " + simpleDateFormat.format(toDate.getTime())); } public void openDateInterval(Calendar fromDate, Calendar toDate) { DateIntervalPicker dateIntervalPicker = new DateIntervalPicker(getContext(), fromDate, toDate, (fromDate1, toDate1) -> { pbLoading.setVisibility(View.VISIBLE); pbLoading.postDelayed(() -> baseTableReportPresenter.onChooseDateInterval(fromDate1, toDate1), 50); }); dateIntervalPicker.show(); } public void setSingleTitle(String titleReport) { llChoiserPanel.setVisibility(View.GONE); tvTitleReport.setVisibility(View.VISIBLE); tvTitleReport.setText(titleReport); panelCount = 1; } public void setChoiserPanel(String[] titles) { tvTitleReport.setVisibility(View.GONE); llChoiserPanel.setVisibility(View.VISIBLE); panelCount = titles.length; if (panelCount > 5) { new Exception("Panel title can maximum 5, for all questions ISLOMOV SARDOR").printStackTrace(); } if (panelCount == 1) { setSingleTitle(titles[0]); } else if (panelCount == 2) { tvFirtPanel.setVisibility(View.VISIBLE); tvSecondPanel.setVisibility(View.GONE); tvThirdPanel.setVisibility(View.GONE); tvFourPanel.setVisibility(View.GONE); tvFivePanel.setVisibility(View.VISIBLE); tvFirtPanel.setText(titles[0]); tvFivePanel.setText(titles[1]); tvFirtPanel.setBackgroundResource(R.drawable.left_switch_title_pressed); tvFirtPanel.setTextColor(Color.parseColor("#2e91cc")); tvFirtPanel.setOnClickListener((view) -> { disableAllPanelButtons(); pbLoading.setVisibility(View.VISIBLE); pbLoading.postDelayed(() -> baseTableReportPresenter.onChoisedPanel(0), 50); tvFirtPanel.setBackgroundResource(R.drawable.left_switch_title_pressed); tvFirtPanel.setTextColor(Color.parseColor("#2e91cc")); }); tvFivePanel.setOnClickListener((view) -> { disableAllPanelButtons(); pbLoading.setVisibility(View.VISIBLE); pbLoading.postDelayed(() -> baseTableReportPresenter.onChoisedPanel(1), 50); tvFivePanel.setBackgroundResource(R.drawable.right_switch_title_pressed); tvFivePanel.setTextColor(Color.parseColor("#2e91cc")); }); } else if (panelCount == 3) { tvFirtPanel.setVisibility(View.VISIBLE); tvSecondPanel.setVisibility(View.VISIBLE); tvThirdPanel.setVisibility(View.GONE); tvFourPanel.setVisibility(View.GONE); tvFivePanel.setVisibility(View.VISIBLE); tvFirtPanel.setText(titles[0]); tvSecondPanel.setText(titles[1]); tvFivePanel.setText(titles[2]); tvFirtPanel.setBackgroundResource(R.drawable.left_switch_title_pressed); tvFirtPanel.setTextColor(Color.parseColor("#2e91cc")); tvFirtPanel.setOnClickListener((view -> { disableAllPanelButtons(); pbLoading.setVisibility(View.VISIBLE); pbLoading.postDelayed(() -> baseTableReportPresenter.onChoisedPanel(0), 50); tvFirtPanel.setBackgroundResource(R.drawable.left_switch_title_pressed); tvFirtPanel.setTextColor(Color.parseColor("#2e91cc")); })); tvSecondPanel.setOnClickListener((view -> { disableAllPanelButtons(); pbLoading.setVisibility(View.VISIBLE); pbLoading.postDelayed(() -> baseTableReportPresenter.onChoisedPanel(1), 50); tvSecondPanel.setBackgroundResource(R.drawable.center_switch_title_pressed); tvSecondPanel.setTextColor(Color.parseColor("#2e91cc")); })); tvFivePanel.setOnClickListener((view -> { disableAllPanelButtons(); pbLoading.setVisibility(View.VISIBLE); pbLoading.postDelayed(() -> baseTableReportPresenter.onChoisedPanel(2), 50); tvFivePanel.setBackgroundResource(R.drawable.right_switch_title_pressed); tvFivePanel.setTextColor(Color.parseColor("#2e91cc")); })); } else if (panelCount == 4) { tvFirtPanel.setVisibility(View.VISIBLE); tvSecondPanel.setVisibility(View.VISIBLE); tvThirdPanel.setVisibility(View.VISIBLE); tvFourPanel.setVisibility(View.GONE); tvFivePanel.setVisibility(View.VISIBLE); tvFirtPanel.setText(titles[0]); tvSecondPanel.setText(titles[1]); tvThirdPanel.setText(titles[2]); tvFivePanel.setText(titles[3]); tvFirtPanel.setBackgroundResource(R.drawable.left_switch_title_pressed); tvFirtPanel.setTextColor(Color.parseColor("#2e91cc")); tvFirtPanel.setOnClickListener((view -> { disableAllPanelButtons(); pbLoading.setVisibility(View.VISIBLE); pbLoading.postDelayed(() -> baseTableReportPresenter.onChoisedPanel(0), 50); tvFirtPanel.setBackgroundResource(R.drawable.left_switch_title_pressed); tvFirtPanel.setTextColor(Color.parseColor("#2e91cc")); })); tvSecondPanel.setOnClickListener((view -> { pbLoading.setVisibility(View.VISIBLE); disableAllPanelButtons(); pbLoading.postDelayed(() -> baseTableReportPresenter.onChoisedPanel(1), 50); tvSecondPanel.setBackgroundResource(R.drawable.center_switch_title_pressed); tvSecondPanel.setTextColor(Color.parseColor("#2e91cc")); })); tvThirdPanel.setOnClickListener((view -> { pbLoading.setVisibility(View.VISIBLE); disableAllPanelButtons(); pbLoading.postDelayed(() -> baseTableReportPresenter.onChoisedPanel(2), 50); tvThirdPanel.setBackgroundResource(R.drawable.center_switch_title_pressed); tvThirdPanel.setTextColor(Color.parseColor("#2e91cc")); })); tvFivePanel.setOnClickListener((view -> { pbLoading.setVisibility(View.VISIBLE); disableAllPanelButtons(); pbLoading.postDelayed(() -> baseTableReportPresenter.onChoisedPanel(3), 50); tvFivePanel.setBackgroundResource(R.drawable.right_switch_title_pressed); tvFivePanel.setTextColor(Color.parseColor("#2e91cc")); })); } else if (panelCount == 5) { tvFirtPanel.setVisibility(View.VISIBLE); tvSecondPanel.setVisibility(View.VISIBLE); tvThirdPanel.setVisibility(View.VISIBLE); tvFourPanel.setVisibility(View.VISIBLE); tvFivePanel.setVisibility(View.VISIBLE); tvFirtPanel.setText(titles[0]); tvSecondPanel.setText(titles[1]); tvThirdPanel.setText(titles[2]); tvFourPanel.setText(titles[3]); tvFivePanel.setText(titles[4]); tvFirtPanel.setBackgroundResource(R.drawable.left_switch_title_pressed); tvFirtPanel.setTextColor(Color.parseColor("#2e91cc")); tvFirtPanel.setOnClickListener((view -> { pbLoading.setVisibility(View.VISIBLE); disableAllPanelButtons(); pbLoading.postDelayed(() -> baseTableReportPresenter.onChoisedPanel(0), 50); tvFirtPanel.setBackgroundResource(R.drawable.left_switch_title_pressed); tvFirtPanel.setTextColor(Color.parseColor("#2e91cc")); })); tvSecondPanel.setOnClickListener((view -> { pbLoading.setVisibility(View.VISIBLE); disableAllPanelButtons(); pbLoading.postDelayed(() -> baseTableReportPresenter.onChoisedPanel(1), 50); tvSecondPanel.setBackgroundResource(R.drawable.center_switch_title_pressed); tvSecondPanel.setTextColor(Color.parseColor("#2e91cc")); })); tvThirdPanel.setOnClickListener((view -> { disableAllPanelButtons(); pbLoading.setVisibility(View.VISIBLE); pbLoading.postDelayed(() -> baseTableReportPresenter.onChoisedPanel(2), 50); tvThirdPanel.setBackgroundResource(R.drawable.center_switch_title_pressed); tvThirdPanel.setTextColor(Color.parseColor("#2e91cc")); })); tvFourPanel.setOnClickListener((view -> { disableAllPanelButtons(); pbLoading.setVisibility(View.VISIBLE); pbLoading.postDelayed(() -> baseTableReportPresenter.onChoisedPanel(3), 50); tvFourPanel.setBackgroundResource(R.drawable.center_switch_title_pressed); tvFourPanel.setTextColor(Color.parseColor("#2e91cc")); })); tvFivePanel.setOnClickListener((view -> { disableAllPanelButtons(); pbLoading.setVisibility(View.VISIBLE); pbLoading.postDelayed(() -> baseTableReportPresenter.onChoisedPanel(4), 50); tvFivePanel.setBackgroundResource(R.drawable.right_switch_title_pressed); tvFivePanel.setTextColor(Color.parseColor("#2e91cc")); })); } } public void disableAllPanelButtons() { tvFirtPanel.setBackgroundResource(R.drawable.left_switch_title); tvSecondPanel.setBackgroundResource(R.drawable.center_switch_title); tvThirdPanel.setBackgroundResource(R.drawable.center_switch_title); tvFourPanel.setBackgroundResource(R.drawable.center_switch_title); tvFivePanel.setBackgroundResource(R.drawable.right_switch_title); tvFirtPanel.setTextColor(Color.parseColor("#999999")); tvSecondPanel.setTextColor(Color.parseColor("#999999")); tvThirdPanel.setTextColor(Color.parseColor("#999999")); tvFourPanel.setTextColor(Color.parseColor("#999999")); tvFivePanel.setTextColor(Color.parseColor("#999999")); } @OnClick(R.id.llFilter) public void onClickedFilterButton() { Runnable runnable = () -> baseTableReportPresenter.onClickedFilter(); runnable.run(); } @OnClick(R.id.llChooseTill) public void onTillChooseButton() { Runnable runnable = () -> baseTableReportPresenter.onTillPickerClicked(); runnable.run(); } @OnTextChanged(R.id.mpSearchEditText) protected void handleTextChange(Editable editable) { if (isAllright) { Runnable runnable = () -> baseTableReportPresenter.onSearchTyped(editable.toString()); runnable.run(); } else isAllright = true; if (editable.toString().isEmpty()) { ivSearchImage.setImageResource(R.drawable.search_app); } else { ivSearchImage.setImageResource(R.drawable.cancel_search); } } @OnClick(R.id.llDateInterval) public void onClickedDateIntervalButton() { llDateInterval.setEnabled(false); clearSearch(); Runnable runnable = () -> baseTableReportPresenter.onClickedDateInterval(); llDateInterval.postDelayed(runnable, 30); llDateInterval.setEnabled(true); } @OnClick(R.id.flCleareSearch) public void onCleareSearch() { if (!mpSearchEditText.getText().toString().isEmpty()) mpSearchEditText.setText(""); } @OnClick(R.id.llExpert) public void showExportPanel() { ExportDialog exportDialog = new ExportDialog(getContext(), panelCount, new ExportDialog.OnExportItemClick() { @Override public void onToExcel() { baseTableReportPresenter.onClickedExportExcel(); } @Override public void onToPdf() { baseTableReportPresenter.onClickedExportPDF(); } }); exportDialog.show(); } boolean isAllright = true; public void clearSearch() { isAllright = false; mpSearchEditText.setText(""); } ; public void setTextToSearch(String searchText) { mpSearchEditText.setText(searchText); } }
package com.share.dao; import com.share.model.share_project; public interface share_projectMapper { int deleteByPrimaryKey(Integer pid); int insert(share_project record); int insertSelective(share_project record); share_project selectByPrimaryKey(Integer pid); int updateByPrimaryKeySelective(share_project record); int updateByPrimaryKey(share_project record); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.webbeans.component; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.Producer; import org.apache.webbeans.config.WebBeansContext; /** * OWB specific extension of the {@link Bean} interface. * It is used internally. Do not use it. Instead use {@link AbstractOwbBean} * for extension. * * @version $Rev$ $Date$ * <T> bean class */ public interface OwbBean<T> extends Bean<T> { /** * @return the producer for this bean; */ Producer<T> getProducer(); /** * Returns bean type. * * @return webbeans type * @see WebBeansType */ WebBeansType getWebBeansType(); /** * Returns bean class type * @return bean class type */ Class<T> getReturnType(); /** * Set specialized flag. * @param specialized flag */ void setSpecializedBean(boolean specialized); /** * Returns true if bean is a specialized bean, false otherwise. * @return true if bean is a specialized bean */ boolean isSpecializedBean(); /** * Set enableed flag. * @param enabled flag */ void setEnabled(boolean enabled); /** * Bean is enabled or not. * @return true if enabled */ boolean isEnabled(); /** * Gets id of the bean. * @return id of the bean */ String getId(); /** * True if passivation capable false otherwise. * @return true if this bean is passivation capable */ boolean isPassivationCapable(); /** * This determines if this bean is really a dependent bean, * and as such always creats a freshl instance for each * InjectionPoint. A BeanManagerBean is e.g. not a dependent bean. * @return <code>true</code> if this is a dependent bean */ boolean isDependent(); /** * Gets the context instance in which this bean belongs to. * @return the {@link WebBeansContext} instance */ WebBeansContext getWebBeansContext(); }
package com.tencent.mm.plugin.sns.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.bg.d; import com.tencent.mm.kernel.g; import com.tencent.mm.model.q; import com.tencent.mm.plugin.messenger.foundation.a.i; import com.tencent.mm.plugin.sns.i.j; import com.tencent.mm.plugin.sns.model.af; import com.tencent.mm.plugin.sns.model.aj; import com.tencent.mm.plugin.sns.model.v; import com.tencent.mm.plugin.sns.model.w; import com.tencent.mm.plugin.sns.storage.t; import com.tencent.mm.pluginsdk.ui.applet.ContactListExpandPreference; import com.tencent.mm.pluginsdk.ui.applet.ContactListExpandPreference.a; import com.tencent.mm.pluginsdk.ui.applet.k; import com.tencent.mm.sdk.e.m; import com.tencent.mm.sdk.e.m.b; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ay; import com.tencent.mm.ui.base.h; import com.tencent.mm.ui.base.p; import com.tencent.mm.ui.base.preference.MMPreference; import com.tencent.mm.ui.base.preference.Preference; import com.tencent.mm.ui.base.preference.f; import com.tencent.mm.ui.contact.s; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class SnsTagDetailUI extends MMPreference implements e, b { protected String bKg = ""; protected f eOE; protected ContactListExpandPreference hLp; protected List<String> jzp = new ArrayList(); protected long noJ; protected String obG = ""; private boolean obH = false; protected a obI = new 9(this); protected int scene = 0; protected p tipDialog = null; static /* synthetic */ void a(SnsTagDetailUI snsTagDetailUI) { String c = bi.c(snsTagDetailUI.jzp, ","); Intent intent = new Intent(); intent.putExtra("titile", snsTagDetailUI.getString(j.address_title_select_contact)); intent.putExtra("list_type", 1); intent.putExtra("list_attr", s.s(new int[]{s.ukF, 1024})); intent.putExtra("always_select_contact", c); d.b(snsTagDetailUI, ".ui.contact.SelectContactUI", intent, 1); } protected void bCV() { x.d("MicroMsg.SnsTagDetailUI", "Base __onCreate"); g.Ek(); g.Eh().dpP.a(290, this); g.Ek(); g.Eh().dpP.a(291, this); g.Ek(); g.Eh().dpP.a(com.tencent.mm.plugin.appbrand.jsapi.audio.j.CTRL_INDEX, this); g.Ek(); g.Eh().dpP.a(293, this); g.Ek(); ((i) g.l(i.class)).FR().a(this); if (af.byu().bBG().size() == 0) { g.Ek(); g.Eh().dpP.a(new v(1), 0); this.obH = true; } } public void onCreate(Bundle bundle) { super.onCreate(bundle); bCV(); this.scene = getIntent().getIntExtra("k_tag_detail_sns_block_scene", 0); this.noJ = getIntent().getLongExtra("k_sns_tag_id", 0); if (this.noJ == 4) { this.obG = getString(j.sns_tag_outsiders); } else if (this.noJ == 5) { this.obG = getString(j.sns_tag_snsblack); } else { this.obG = af.byu().fk(this.noJ).field_tagName; } if (this.noJ == 0) { String stringExtra = getIntent().getStringExtra("k_sns_tag_list"); this.obG = bi.aG(getIntent().getStringExtra("k_sns_tag_name"), ""); ay byc = af.byc(); String GF = q.GF(); List<String> F = bi.F(stringExtra.split(",")); if (F != null) { for (String stringExtra2 : F) { if (!(this.jzp.contains(stringExtra2) || !com.tencent.mm.l.a.gd(byc.Yg(stringExtra2).field_type) || GF.equals(stringExtra2))) { this.jzp.add(stringExtra2); } } } } else { this.jzp = bCY(); } if (this.obG == null || this.obG.equals("")) { this.obG = getString(j.sns_tag_name_unknow); this.obG = aj.Mm(getString(j.sns_tag_name_unknow)); } initView(); bDN(); updateTitle(); if (this.noJ < 6) { this.eOE.aaa("delete_tag_name"); this.eOE.aaa("delete_tag_name_category"); if (this.noJ > 0) { this.eOE.aaa("settings_tag_name"); this.eOE.aaa("settings_tag_name_category"); } } if (this.noJ == 4) { this.eOE.aaa("black"); this.eOE.aaa("group"); } else if (this.noJ == 5) { this.eOE.aaa("outside"); this.eOE.aaa("group"); } else { this.eOE.aaa("black"); this.eOE.aaa("outside"); } if (this.noJ == 0) { enableOptionMenu(true); } else { enableOptionMenu(false); } this.bKg = this.obG + " " + bi.c(this.jzp, ","); } protected void bCW() { x.d("MicroMsg.SnsTagDetailUI", "Base __onDestroy"); g.Ek(); g.Eh().dpP.b(290, this); g.Ek(); g.Eh().dpP.b(291, this); g.Ek(); g.Eh().dpP.b(com.tencent.mm.plugin.appbrand.jsapi.audio.j.CTRL_INDEX, this); g.Ek(); g.Eh().dpP.b(293, this); g.Ek(); if (g.Eg().Dx()) { g.Ek(); ((i) g.l(i.class)).FR().b(this); } } public void onDestroy() { if (this.tipDialog != null) { this.tipDialog.dismiss(); } bCW(); super.onDestroy(); } public final void a(int i, m mVar, Object obj) { } public final int Ys() { return com.tencent.mm.plugin.sns.i.m.tag_detail_pref; } public void onResume() { super.onResume(); bDN(); } public final boolean a(f fVar, Preference preference) { String str = preference.mKey; if (str.equals("settings_tag_name") && (this.noJ >= 6 || this.noJ == 0)) { Intent intent = new Intent(); intent.putExtra("Contact_mode_name_type", 3); intent.putExtra("Contact_Nick", bi.aG(this.obG, " ")); com.tencent.mm.plugin.sns.c.a.ezn.a(intent, this); } if (str.equals("delete_tag_name")) { h.a(this, j.set_tag_del_cmd, j.app_tip, new 1(this), new 2(this)); } return false; } protected final void updateTitle() { setMMTitle(this.obG + "(" + this.jzp.size() + ")"); } private void bDN() { Preference ZZ = this.eOE.ZZ("settings_tag_name"); if (ZZ != null) { if (this.obG.length() > 20) { this.obG = this.obG.substring(0, 20); } ZZ.setSummary(this.obG); this.eOE.notifyDataSetChanged(); } } protected void bCX() { if (this.noJ != 0) { g.Ek(); g.Eh().dpP.a(new com.tencent.mm.plugin.sns.model.x(this.noJ, this.obG), 0); } getString(j.app_tip); this.tipDialog = h.a(this, getString(j.sns_tag_save), true, new 3(this)); } protected final void initView() { this.eOE = this.tCL; this.hLp = (ContactListExpandPreference) this.eOE.ZZ("roominfo_contact_anchor"); if (this.hLp != null) { this.hLp.a(this.eOE, this.hLp.mKey); this.hLp.kG(true).kH(true); this.hLp.p(null, this.jzp); this.hLp.a(new k.b() { public final boolean oe(int i) { boolean Ca; ContactListExpandPreference contactListExpandPreference = SnsTagDetailUI.this.hLp; if (contactListExpandPreference.qJA != null) { Ca = contactListExpandPreference.qJA.qIM.Ca(i); } else { Ca = true; } if (!Ca) { x.d("MicroMsg.SnsTagDetailUI", "onItemLongClick " + i); } return true; } }); this.hLp.a(this.obI); } getIntent().getIntExtra("k_sns_from_settings_about_sns", 0); setBackBtn(new 5(this)); a(0, getString(j.app_finish), new OnMenuItemClickListener() { public final boolean onMenuItemClick(MenuItem menuItem) { SnsTagDetailUI.this.aZV(); return true; } }, com.tencent.mm.ui.s.b.tmX); } public boolean dispatchKeyEvent(KeyEvent keyEvent) { if (keyEvent.getKeyCode() != 4 || keyEvent.getAction() != 0) { return super.dispatchKeyEvent(keyEvent); } if (!(this.obG + " " + bi.c(this.jzp, ",")).equals(this.bKg) || this.noJ == 0) { h.a(this, j.sns_tag_cancel, j.app_tip, new OnClickListener() { public final void onClick(DialogInterface dialogInterface, int i) { SnsTagDetailUI.this.finish(); } }, null); } else { finish(); } return true; } protected void aZV() { if ((this.obG + " " + bi.c(this.jzp, ",")).equals(this.bKg) && this.noJ != 0) { finish(); } else if (af.byu().q(this.noJ, this.obG)) { h.b(this, getString(j.sns_tag_exist, new Object[]{this.obG}), getString(j.app_tip), true); } else { final w wVar = new w(3, this.noJ, this.obG, this.jzp.size(), this.jzp, this.scene); g.Ek(); g.Eh().dpP.a(wVar, 0); getString(j.app_tip); this.tipDialog = h.a(this, getString(j.sns_tag_save), true, new OnCancelListener() { public final void onCancel(DialogInterface dialogInterface) { g.Ek(); g.Eh().dpP.c(wVar); } }); } } protected List<String> bCY() { List<String> linkedList = new LinkedList(); t fk = af.byu().fk(this.noJ); if (fk.field_memberList == null || fk.field_memberList.equals("")) { return linkedList; } return bi.F(fk.field_memberList.split(",")); } protected void yp(String str) { if (str != null && !str.equals("")) { this.jzp.remove(str); if (this.hLp != null) { this.hLp.bt(this.jzp); this.hLp.notifyChanged(); } if (this.jzp.size() == 0 && this.hLp != null) { this.hLp.cdV(); this.hLp.kG(true).kH(false); this.eOE.notifyDataSetChanged(); } else if (this.hLp != null) { this.hLp.kG(true).kH(true); } updateTitle(); } } protected void cr(List<String> list) { ay byc = af.byc(); String GF = q.GF(); for (String str : list) { if (!(this.jzp.contains(str) || !com.tencent.mm.l.a.gd(byc.Yg(str).field_type) || GF.equals(str))) { this.jzp.add(str); } } if (this.hLp != null) { this.hLp.bt(this.jzp); this.hLp.notifyChanged(); } if (this.jzp.size() > 0) { this.hLp.kG(true).kH(true); } else { this.hLp.kG(true).kH(false); } updateTitle(); } protected void onActivityResult(int i, int i2, Intent intent) { super.onActivityResult(i, i2, intent); if (i2 == -1) { String stringExtra; switch (i) { case 1: if (intent != null) { boolean z; String stringExtra2 = intent.getStringExtra("Select_Contact"); if (bi.oV(q.GF()).equals(stringExtra2)) { z = true; } else if (this.jzp == null) { z = false; } else { z = false; for (String stringExtra3 : this.jzp) { boolean z2; if (stringExtra3.equals(stringExtra2)) { z2 = true; } else { z2 = z; } z = z2; } } if (z) { h.b(this, getString(j.add_room_mem_memberExits, new Object[]{Integer.valueOf(0), Integer.valueOf(0)}), getString(j.app_tip), true); return; } List F = bi.F(stringExtra2.split(",")); if (F != null) { cr(F); break; } return; } return; case 2: stringExtra3 = intent.getStringExtra("k_sns_tag_name"); if (stringExtra3 != null) { this.obG = stringExtra3; } updateTitle(); x.d("MicroMsg.SnsTagDetailUI", "updateName " + this.obG); break; default: return; } if (!(this.obG + " " + bi.c(this.jzp, ",")).equals(this.bKg) || this.noJ == 0) { enableOptionMenu(true); } else { enableOptionMenu(false); } } } public void a(int i, int i2, String str, l lVar) { x.i("MicroMsg.SnsTagDetailUI", "onSceneEnd: errType = " + i + " errCode = " + i2 + " errMsg = " + str); if (this.tipDialog != null) { this.tipDialog.dismiss(); } switch (lVar.getType()) { case 290: finish(); return; case 291: finish(); return; case com.tencent.mm.plugin.appbrand.jsapi.audio.j.CTRL_INDEX /*292*/: if (this.hLp != null && this.obH && !(this instanceof SnsBlackDetailUI)) { x.d("MicroMsg.SnsTagDetailUI", "update form net"); this.bKg = this.obG + " " + bi.c(((v) lVar).eQ(this.noJ), ","); LinkedList linkedList = new LinkedList(); List<String> list = this.jzp; this.jzp = bCY(); if (list != null) { for (String str2 : list) { if (!this.jzp.contains(str2)) { this.jzp.add(str2); } } } this.hLp.bt(this.jzp); this.hLp.notifyChanged(); return; } return; default: return; } } }
package com.silver.dan.castdemo; import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.NonNull; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.api.Scope; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.google.gson.JsonObject; import com.koushikdutta.async.future.FutureCallback; import com.koushikdutta.ion.Ion; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * Created by dan on 1/8/17. */ public class AuthHelper { private String AuthHelperSharedPreferences = "AuthHelperSharedPreferences"; private String SERVICE_JWT = "SERVICE_JWT"; public static FirebaseUser user; static String userJwt; public static Set<Scope> grantedScopes; private static String googleAccessToken; private static Date googleAccessTokenExpiresAt; private final Context context; private FirebaseAuth mAuth; public AuthHelper(Context context) { this.context = context; mAuth = FirebaseAuth.getInstance(); } // Configure Google Sign In GoogleSignInOptions getGoogleGSO() { return getGoogleGSO(new HashSet<Scope>()); } public GoogleSignInOptions getGoogleGSO(Set<Scope> scopes) { GoogleSignInOptions.Builder gsoBuilder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(context.getString(R.string.web_client_id)) .requestServerAuthCode(context.getString(R.string.web_client_id), false) .requestEmail(); for (Scope scope : scopes) gsoBuilder.requestScopes(scope); return gsoBuilder.build(); } String getSavedServiceJwt() { SharedPreferences prefs = context.getSharedPreferences(AuthHelperSharedPreferences, Context.MODE_PRIVATE); String jwt = prefs.getString(SERVICE_JWT, ""); if (jwt.equals("")) { return null; } return jwt; } void setServiceJwt(String userJwt) { AuthHelper.userJwt = userJwt; } void setNewUserInfo(FirebaseUser user, Set<Scope> grantedScopes) { AuthHelper.user = user; AuthHelper.grantedScopes = grantedScopes; } void completeCommonAuth(final GoogleSignInAccount acct, final SimpleCallback<String> callback) { AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential).addOnSuccessListener(new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult authResult) { setNewUserInfo(authResult.getUser(), acct.getGrantedScopes()); String userId = authResult.getUser().getUid(); String serverAuthCode = acct.getServerAuthCode(); AuthHelper authHelper = new AuthHelper(context); authHelper.exchangeServerAuthCodeForJWT(userId, serverAuthCode, acct.getGrantedScopes(), new SimpleCallback<String>() { @Override public void onComplete(String jwt) { clearGoogleTokenCache(); SharedPreferences prefs = context.getSharedPreferences(AuthHelperSharedPreferences, Context.MODE_PRIVATE); prefs.edit().putString(SERVICE_JWT, jwt).apply(); callback.onComplete(jwt); } @Override public void onError(Exception e) { callback.onError(e); } }); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { callback.onError(e); } }); } private void clearGoogleTokenCache() { AuthHelper.googleAccessToken = null; } // implements caching on expiresAt field public static void getGoogleAccessToken(Context context, final SimpleCallback<String> callback) { if (AuthHelper.googleAccessToken != null) { Date now = new Date(); // won't expire within the next 5 minutes if (AuthHelper.googleAccessTokenExpiresAt.getTime() - now.getTime()>= 5*60*1000) { callback.onComplete(AuthHelper.googleAccessToken); return; } } Ion.with(context) .load(context.getString(R.string.APP_URL) + "/exchangeServiceJWTForGoogleAccessToken") .setBodyParameter("jwt", userJwt) .asJsonObject() .setCallback(new FutureCallback<JsonObject>() { @Override public void onCompleted(Exception e, JsonObject result) { if (e != null) { callback.onError(e); return; } String accessToken = result.get("googleAccessToken").getAsString(); long expiresAt = result.get("expiresAt").getAsLong(); AuthHelper.googleAccessToken = accessToken; AuthHelper.googleAccessTokenExpiresAt = new Date(expiresAt); callback.onComplete(accessToken); } }); } static void signout() { AuthHelper.googleAccessToken = null; AuthHelper.googleAccessTokenExpiresAt = null; } private void exchangeServerAuthCodeForJWT(String firebaseUserId, String authCode, Set<Scope> grantedScopes, final SimpleCallback<String> jwtCallback) { Ion.with(context) .load(context.getString(R.string.APP_URL) + "/exchangeServerAuthCodeForJWT") .setBodyParameter("serverCode", authCode) .setBodyParameter("firebaseUserId", firebaseUserId) .setBodyParameter("grantedScopes", android.text.TextUtils.join(",", grantedScopes)) .asJsonObject() .setCallback(new com.koushikdutta.async.future.FutureCallback<JsonObject>() { @Override public void onCompleted(Exception e, JsonObject result) { if (e != null) { jwtCallback.onError(e); return; } String jwt = result.get("serviceAccessToken").getAsString(); AuthHelper.userJwt = jwt; jwtCallback.onComplete(jwt); } }); } }
package util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Van-anh et Sébastien * *La classe Bdd permet de se connecter et se déconnecter de la base de données */ public class Bdd { static String url = "jdbc:mysql://localhost/proxibanque"; static String login = "root"; static String password = ""; /** * La méthode seConnecter permet la connexion à la base de données * */ public static Connection seConnecter() { Connection cnx = null; try { Class.forName("com.mysql.jdbc.Driver"); cnx = DriverManager.getConnection(url, login, password); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(Bdd.class.getName()).log(Level.SEVERE, null, ex); } return cnx; } /** * La méthode seDeconnecter permet la déconnexion à la base de données * */ public static void seDeconnecter(Connection cnx) { try { cnx.close(); } catch (SQLException ex) { Logger.getLogger(Bdd.class.getName()).log(Level.SEVERE, null, ex); } } }
package com.outbrain.aletheia.datum.production; public interface DatumKeyAwareSender<TInput> { void send(final TInput data, String key) throws SilentSenderException; }
package com.xu.easyweb.report.entity; /** * @author Yangcl * @描述:这个类继承了GenericField类,详细说明请参考:GenericField */ public class BodyField { private String name; private int BeginCell; private String value; public int getBeginCell() { return BeginCell; } public void setBeginCell(int beginCell) { BeginCell = beginCell; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
package com.hotmail.at.jablonski.michal.shoppinglist.ui.main.listAdapter; import com.hotmail.at.jablonski.michal.shoppinglist.db.entities.RootEntity; import java.io.Serializable; public class RootItem implements Serializable { private Integer id; private String name; private boolean isArchived; private boolean isLiked; private long timestamp; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public boolean isArchived() { return isArchived; } public void setArchived(boolean archived) { isArchived = archived; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public boolean isLiked() { return isLiked; } public void setLiked(boolean liked) { isLiked = liked; } public RootEntity toEntity() { RootEntity entity = new RootEntity(); entity.setId(id); entity.setArchived(isArchived); entity.setLiked(isLiked); entity.setName(name); entity.setTimestamp(timestamp); return entity; } }
package com.zjh.stock.service.stock; import com.baomidou.mybatisplus.extension.service.IService; import com.zjh.stock.entity.StockDailyData; import java.util.Map; /** * * * @author zhujianhao * @email 1205628174@qq.com * @date 2021-02-03 15:20:49 */ public interface StockDailyDataService extends IService<StockDailyData> { void judgeBoll(String stockCode,Integer day); }
package com.gnomikx.www.gnomikx.ViewHolders; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.gnomikx.www.gnomikx.R; /** * Class to act as view holder for Upload Report Fragment */ public class AllUsersViewHolder extends RecyclerView.ViewHolder { private TextView userNameTextView; private TextView userEmailTextView; private TextView userPhoneTextView; public AllUsersViewHolder(View itemView) { super(itemView); this.userNameTextView = itemView.findViewById(R.id.all_users_user_name); this.userEmailTextView = itemView.findViewById(R.id.all_users_email_id); this.userPhoneTextView = itemView.findViewById(R.id.all_users_phone); } public TextView getUserNameTextView() { return userNameTextView; } public void setUserNameTextView(TextView userNameTextView) { this.userNameTextView = userNameTextView; } public TextView getUserEmailTextView() { return userEmailTextView; } public void setUserEmailTextView(TextView userEmailTextView) { this.userEmailTextView = userEmailTextView; } public TextView getUserPhoneTextView() { return userPhoneTextView; } public void setUserPhoneTextView(TextView userPhoneTextView) { this.userPhoneTextView = userPhoneTextView; } public void bind(String userName, String userEmail, String userPhone) { userNameTextView.setText(userName); userEmailTextView.setText(userEmail); userPhoneTextView.setText(userPhone); } }
package me.DawnBudgie.pandoralimits; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; public class PandoraLimits extends JavaPlugin implements Listener { private YamlConfiguration config; private YamlConfiguration PEXconfig; private Logger log = Logger.getLogger("Minecraft"); public void onEnable() { LoadConfig(); Bukkit.getServer().getPluginManager().registerEvents(this, this); } public void LoadConfig() { File configFile = new File(getDataFolder(), "config.yml"); this.config = YamlConfiguration.loadConfiguration(configFile); if (!configFile.exists()) { this.config.set("Groups.mason", Integer.valueOf(20000)); this.config.set("Groups.adept", Integer.valueOf(20000)); this.config.set("Groups.artisan", Integer.valueOf(75000)); this.config.set("Groups.helper", Integer.valueOf(75000)); this.config.set("Groups.architect", Integer.valueOf(300000)); this.config.set("Groups.buildteam", Integer.valueOf(500000)); this.config.set("Groups.legend", Integer.valueOf(1000000)); ArrayList<String> ignored = new ArrayList<String>(); ignored.add("guest"); this.config.set("Ignore", ignored); try { this.config.save(configFile); } catch (IOException e) { e.printStackTrace(); } } Plugin pex = Bukkit.getServer().getPluginManager().getPlugin("PermissionsEx"); File pexFile = new File(pex.getDataFolder(), "permissions.yml"); this.PEXconfig = YamlConfiguration.loadConfiguration(pexFile); } @EventHandler(priority=EventPriority.HIGH) private void onPlayerLogin(PlayerJoinEvent event) { Player player = event.getPlayer(); @SuppressWarnings("unchecked") ArrayList<String> playergroups = (ArrayList<String>)this.PEXconfig.get("users." + player.getName() + ".group"); String group = (String)playergroups.get(0); this.log.info("Player is of " + group); @SuppressWarnings("unchecked") List<String> ignorelist = (List<String>)this.config.get("Ignore"); if (!ignorelist.contains(group)) { String command = "pex user " + player.getName() + " add worldedit.limit"; Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command); Integer blocklimit = Integer.valueOf(this.config.getInt("Groups." + group)); player.chat("//limit " + blocklimit); String command2 = "pex user " + player.getName() + " remove worldedit.limit"; Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command2); } } }
package com.twitter.controller; import com.twitter.model.Tweet; import com.twitter.model.Twitter; import com.twitter.model.TweetActions; import com.twitter.service.TwitterService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @CrossOrigin(origins = {"http://localhost:3000"}) @RestController public class TwitterController { private final TwitterService twitterService; @Autowired public TwitterController(TwitterService twitterService) { this.twitterService = twitterService; } @GetMapping("/api/getTweets") public List<Tweet> getAllTweets() { return this.twitterService.getTweets(); } @GetMapping("/api/getRetweets") public List<Tweet> getRetweets() { return this.twitterService.getRetweets(); } @GetMapping("/api/getLikeTweets") public List<Tweet> getLikeTweets() { return this.twitterService.getLikeTweets(); } @PostMapping("/api/addTweet") public List<Tweet> addTweet(@RequestBody String content) { return this.twitterService.addTweet(content); } @PostMapping("/api/deleteTweet") public List<Tweet> deleteTweet(@RequestBody Long tweetId) { return this.twitterService.deleteTweet(tweetId); } @PostMapping("/api/addLike") public TweetActions toggleLike(@RequestBody Long tweetId) { return this.twitterService.toggleLike(tweetId); } @PostMapping("/api/getUserActionDetails") public TweetActions getUserActionDetails(@RequestBody Long tweetId) { return this.twitterService.getUserActionDetails(tweetId); } @PostMapping("/api/addRetweet") public List<Tweet> addRetweet(@RequestBody Long tweetId) { return this.twitterService.addRetweet(tweetId); } @PostMapping("/api/deleteRetweet") public List<Tweet> deleteRetweet(@RequestBody Long tweetId) { return this.twitterService.deleteRetweet(tweetId); } @GetMapping("/api/getUserDetails/{userId}") public Twitter getTwitterDetails(@PathVariable String userId) { return this.twitterService.getTwitterDetails(userId); } }
package edu.neu.dreamapp.survey; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.PersistableBundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import butterknife.BindView; import edu.neu.dreamapp.MainActivity; import edu.neu.dreamapp.R; import edu.neu.dreamapp.base.BaseActivity; import edu.neu.dreamapp.model.SurveyQuestion; import edu.neu.dreamapp.widget.CustomProgressBar; /** * @author agrawroh * @version v1.0 */ public class SurveyActivity extends BaseActivity implements SurveyFragment.SelectionCallback { @BindView(R.id.ivBack) ImageView ivBack; @BindView(R.id.tvTitle) TextView tvTitle; @BindView(R.id.horizontalProgress) CustomProgressBar horizontalProgress; @BindView(R.id.btnPrevious) Button btnPrevious; @BindView(R.id.btnNext) Button btnNext; private List<SurveyQuestion> surveyQuestions; private int progress; private SurveyFragment surveyFragment; @Override protected String getTAG() { return this.toString(); } @Override protected int getLayoutId() { return R.layout.activity_survey; } @Override public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) { super.onCreate(savedInstanceState, persistentState); } /** * Initialize Views */ @Override protected void initResAndListener() { ivBack.setVisibility(View.VISIBLE); ivBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { initEndDialog(); } }); /* Get Info */ Bundle b = getIntent().getExtras(); int step = b.getInt("S"); if (1 == step) { tvTitle.setText("Pre-Evaluation Survey"); } else { tvTitle.setText("Post-Evaluation Survey"); } /* Grab Fragment */ surveyFragment = (SurveyFragment) getSupportFragmentManager().findFragmentById(R.id.surveyFragment); surveyFragment.setSelectionCallback(this); btnNext.setEnabled(true); /* Next Question Button */ btnNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (progress == surveyQuestions.size() - 1) { pushAnswersOnFirebase(); } else { progress++; surveyFragment.nextQuestion(progress, surveyQuestions.get(progress)); horizontalProgress.setProgress((int) (((double) progress / (double) surveyQuestions.size()) * 100)); /* Enable previous button since there is always a question to go back to */ btnPrevious.setEnabled(true); } btnNext.setEnabled(isChecked(progress)); } }); /* Previous Question Button */ btnPrevious.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { progress--; surveyFragment.previousQuestion(progress, surveyQuestions.get(progress)); horizontalProgress.setProgress((int) (((double) progress / (double) surveyQuestions.size()) * 100)); /* Disable previous button if progress is pushed back to 0 */ if (progress == 0) { btnPrevious.setEnabled(false); } btnNext.setEnabled(isChecked(progress)); } }); initQuestion(); } /** * Initializing Survey Questions (Pre-entered) */ private void initQuestion() { surveyQuestions = new ArrayList<>(); /* Attendance */ surveyQuestions.add(new SurveyQuestion("Attendance", "", Arrays.asList("Adalquiris", "Jhon Olivo", "Elvis Manuel", "Elianny", "Adelyn Sanchez", "Samuel Arturo"))); /* Questions */ surveyQuestions.add(new SurveyQuestion("1. Tener relaciones sexuales con una persona mayor que t˙ (5 aÒos o·s) te pone en peligro de contagiarse del VIH.\n\n" + "1. Have sex with a person older than you (5 years or\n" + "more) puts you in danger of getting HIV.", "", Arrays.asList("Excellent", "Good", "Fair", "Poor"))); surveyQuestions.add(new SurveyQuestion("2. Los condones funcionan para prevenir el VIH/SIDA.\n\n" + "2. Condoms work to prevent HIV / AIDS.", "", Arrays.asList("I am not physically active", "less than 75 minutes", "75 - 149 minutes", "150 - 300 minutes", "more than 300 minutes"))); surveyQuestions.add(new SurveyQuestion("3. Una persona que se ve sana puede tener el VIH.\n\n" + "3. A person who looks healthy can have HIV.", "", Arrays.asList("I do not stretch often, if ever", "1 day/week", "2 days/week", "3 or more days/week"))); surveyQuestions.add(new SurveyQuestion("4. Puedes saber si tienes VIH sin hacer una prueba de VIH.\n\n" + "4. You can know if you have HIV without an HIV test.", "", Arrays.asList("I do not typically weight-lift or resistance train", "1 day/week", "2 days/week", "3 or more days/week"))); surveyQuestions.add(new SurveyQuestion("5. Tener varias parejas al mismo tiempo aumenta el peligro de contagiarse del VIH y otras infecciones.\n\n" + "5. Having several partners at the same time increases the danger of get HIV and other infections.", "", Arrays.asList("I do not typically weight-lift or resistance train", "1 day/week", "2 days/week", "3 or more days/week"))); /* Set current Progress to 0 */ progress = 0; /* Call nextQuestion on SurveyFragment to load out the first question */ surveyFragment.nextQuestion(progress, surveyQuestions.get(progress)); /* Set current Progressbar to show 0 */ horizontalProgress.setProgress(0); /* Disable previous button since it is the first question */ btnPrevious.setEnabled(false); } /** * Overwrites the interface and creates callback from SurveyFragment * * @param index Index Location * @param selection Selection */ @Override public void itemSelected(int index, String selection) { surveyQuestions.get(index).setSelected(selection); if (0 == index) { List<String> options = new ArrayList<>(); int valPresent = 0; for (final String name : surveyQuestions.get(0).getOption()) { if (Arrays.asList(selection.substring(1, selection.length() - 1).split(", ")).contains(String.valueOf(valPresent))) { options.add(name + " : True? Cierto?"); } ++valPresent; } for (int i = 1; i < surveyQuestions.size(); i++) { surveyQuestions.get(i).setOption(options); } } btnNext.setEnabled(true); } /** * Push Answers */ public void pushAnswersOnFirebase() { /* Get Info */ String key = ""; Bundle b = getIntent().getExtras(); int step = b.getInt("S"); if (1 == step) { key = "SR_RESP_SET_PRE"; } else { key = "SR_RESP_SET_POST"; } /* Get Shared Preferences */ SharedPreferences prefs = getApplicationContext().getSharedPreferences("DREAM_APP_CXT", Context.MODE_PRIVATE); SharedPreferences.Editor scoreEditor = prefs.edit(); /* Get Responses */ Set<String> set = prefs.getStringSet(key, new HashSet<String>()); StringBuilder builder = new StringBuilder(); builder.append(new Date()).append(";"); builder.append(surveyQuestions.get(0).getOption()).append(";"); builder.append(surveyQuestions.get(0).getSelected()).append(";"); for (int i = 1; i < surveyQuestions.size(); i++) { builder.append(surveyQuestions.get(i).getSelected()).append(";"); } set.add(builder.toString()); scoreEditor.putStringSet(key, set); scoreEditor.commit(); /* Finish */ if (1 == step) { Intent i = new Intent(getApplicationContext(), SurveyStartActivity.class); i.putExtra("S", 1); startActivity(i); } finish(); } /** * return if any of the options are selected * * @return Return Value */ public boolean isChecked(int position) { return null != surveyQuestions.get(position).getSelected(); } /** * Survey entry confirmation dialog initialization */ @SuppressWarnings("all") private void initEndDialog() { View layout = LayoutInflater.from(mContext).inflate(R.layout.dialog_popup, null); final AlertDialog dialog = new AlertDialog.Builder(mContext).setView(layout).show(); TextView tvContent = (TextView) layout.findViewById(R.id.tvContent); tvContent.setText(getResources().getString(R.string.end_survey)); TextView tv_cancel = (TextView) layout.findViewById(R.id.tv_cancel); tv_cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); TextView tv_confirm = (TextView) layout.findViewById(R.id.tv_confirm); /* if confirm, launch MainActivity */ tv_confirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); Intent intent = new Intent(mContext, MainActivity.class); ((Activity) mContext).startActivity(intent); finish(); overridePendingTransition(R.anim.fade_in_500, R.anim.fade_out_500); } }); } }
package org.drooms.api; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Assume; import org.junit.Test; public class CollectibleTest { @Test public void testCollectibleConstructorExpiring() { final int points = 5; final int expiration = 2; final Collectible c = new Collectible(points, expiration); Assume.assumeThat(c.getPoints(), CoreMatchers.is(points)); Assert.assertTrue(c.expires()); Assert.assertThat(c.expiresInTurn(), CoreMatchers.is(expiration)); } @SuppressWarnings("unused") @Test(expected = IllegalArgumentException.class) public void testCollectibleConstructorNegativeExpiration() { new Collectible(1, -1); } @SuppressWarnings("unused") @Test(expected = IllegalArgumentException.class) public void testCollectibleConstructorNegativePoints() { new Collectible(-1); } @SuppressWarnings("unused") @Test(expected = IllegalArgumentException.class) public void testCollectibleConstructorProperExpirationNegativePoints() { new Collectible(-1, 1); } @SuppressWarnings("unused") @Test(expected = IllegalArgumentException.class) public void testCollectibleConstructorProperExpirationZeroPoints() { new Collectible(0, 1); } @Test public void testCollectibleConstructorUnexpiring() { final int points = 10; final Collectible c = new Collectible(points); Assume.assumeThat(c.getPoints(), CoreMatchers.is(points)); Assert.assertFalse(c.expires()); Assert.assertThat(c.expiresInTurn(), CoreMatchers.is(-1)); } @SuppressWarnings("unused") @Test(expected = IllegalArgumentException.class) public void testCollectibleConstructorZeroExpiration() { new Collectible(1, 0); } @SuppressWarnings("unused") @Test(expected = IllegalArgumentException.class) public void testCollectibleConstructorZeroPoints() { new Collectible(0); } @Test public void testEqualsSame() { final Collectible c = new Collectible(5, 2); Assert.assertEquals(c, c); } @Test public void testEqualsSameParameters() { final Collectible c1 = new Collectible(5, 2); final Collectible c2 = new Collectible(5, 2); Assert.assertNotEquals(c1, c2); } }
package Onlineshoppingstore; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.server.browserlaunchers.Sleeper; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.BeforeTest; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(Onlineshoppingstore.TestNGListeneres.class) public class TC1 { private static Logger log=Logger.getLogger(TC1.class); FirefoxDriver driver; Sellerloginobj page1; Productmaneg page2; Dropdowns page3; FileInputStream fso; FileOutputStream fo; XSSFWorkbook wbo; XSSFSheet wso; @BeforeTest public void open(){ DOMConfigurator.configure("log4j.xml"); driver=new FirefoxDriver(); log.info("successfully browser opened"); driver.get("http://webwaves.in/ecommerce/seller/"); log.info("successfully page navigated"); } @Test public void Slogin(){ page1=PageFactory.initElements(driver,Sellerloginobj.class); page1.login("kalpanaQA@gmail.com", "12345"); log.info("successfully login with inserted details"); Sleeper.sleepTightInSeconds(5); } @Test(priority=1) public void click(){ page2=PageFactory.initElements(driver, Productmaneg.class); page2.pm(); log.info("successfully link clicked"); Sleeper.sleepTightInSeconds(5); } @Test(priority=2) public void selectvalue() throws IOException{ page3=PageFactory.initElements(driver,Dropdowns.class); page3.select(); Sleeper.sleepTightInSeconds(5); fso=new FileInputStream("C:\\Users\\sai\\Downloads\\Dropdowns Expected (2).xlsx"); wbo=new XSSFWorkbook(fso); wso=wbo.getSheet("Select Catagory"); Row r; WebElement selectcategory=page3.selectcat.findElement(By.id("category")); log.info("successfully select category dropdown clicked" ); List<WebElement>value=selectcategory.findElements(By.tagName("option")); for(int v=0;v<value.size();v++){ r=wso.getRow(v+1); try{ String expected=r.getCell(0).getStringCellValue(); log.info("sucessfully get the expected values"); String actual=value.get(v).getText(); r.createCell(1).setCellValue(actual); log.info("successfully actual dropdown values are inserted"); if(expected.equals(actual)){ r.createCell(2).setCellValue("pass"); } else{ r.createCell(2).setCellValue("fail"); } }catch(Exception e){ System.out.println(e); } fo=new FileOutputStream("C:\\Users\\sai\\Downloads\\Dropdowns Expected (2).xlsx"); wbo.write(fo); } } @Test(priority=3) public void selectstock() throws IOException{ page3=PageFactory.initElements(driver,Dropdowns.class); page3.select(); fso=new FileInputStream("C:\\Users\\sai\\Downloads\\Dropdowns Expected (2).xlsx"); wbo=new XSSFWorkbook(fso); wso=wbo.getSheet("Stock"); Row r; WebElement selectstockvalue=page3.selectstock.findElement(By.id("stock")); log.info("successfully select stock dropdown clicked"); List<WebElement>value=selectstockvalue.findElements(By.tagName("option")); for(int i=0;i<value.size();i++){ r=wso.getRow(i+1); try{ String expected=r.getCell(0).getStringCellValue(); log.info("successfully get the expected values"); String actual=value.get(i).getText(); r.createCell(1).setCellValue(actual); log.info("successfully actual dropdown values are inserted"); if(expected.equals(actual)){ r.createCell(2).setCellValue("pass"); } else{ r.createCell(2).setCellValue("fail"); } }catch(Exception e){ System.out.println(e); } fo=new FileOutputStream("C:\\Users\\sai\\Downloads\\Dropdowns Expected (2).xlsx"); wbo.write(fo); log.info("successfully saved all values in excel"); } } }
package org.exoplatform.rest; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.ArchivePaths; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.formatter.Formatters; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.testng.annotations.Test; import java.io.File; import static com.jayway.restassured.RestAssured.expect; import static com.jayway.restassured.RestAssured.get; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; @Test(groups = "integration") public class UserServiceIT extends Arquillian { private final static String WEBAPP_CONTEXT = "rest"; @Deployment public static WebArchive createTestableDeployment() { final WebArchive war = ShrinkWrap.create(WebArchive.class, WEBAPP_CONTEXT + ".war") .addClasses(User.class, UserService.class) .setWebXML(new File("src/main/webapp/WEB-INF/web.xml")); return war; } @Test public void testUserFetchesSuccess() { expect(). body("id", equalTo("12")). body("firstName", equalTo("Tim")). body("lastName", equalTo("Tester")). body("birthday", equalTo("1970-01-16T07:56:49.871+01:00")). when(). get("/" + WEBAPP_CONTEXT + "/user/id/12"); } @Test public void testUserNotFound() { expect(). body(nullValue()). when(). get("/" + WEBAPP_CONTEXT + "/user/id/666"); } }
package com.miguelcr.customlistviewfruits; import android.content.Context; import android.media.Image; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.List; /** * Created by miguelcampos on 6/6/16. */ public class FruitAdapter extends ArrayAdapter<Fruit>{ Context ctx; List<Fruit> items; public FruitAdapter(Context ctx, List<Fruit> items) { super(ctx,R.layout.fruit_item,items); this.ctx = ctx; this.items = items; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) ctx .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflater.inflate(R.layout.fruit_item, parent, false); // 1. Get the layout components ImageView imageViewIcon = (ImageView)v.findViewById(R.id.iconFruit); TextView textViewName = (TextView)v.findViewById(R.id.nameFruit); TextView textViewPrice = (TextView)v.findViewById(R.id.priceFruit); // 2. Get the current item info Fruit current = items.get(position); String name = current.getName(); int icon = current.getIcon(); float price = current.getPrice(); // 3. Set the info in the View Components textViewName.setText(name); textViewPrice.setText(String.valueOf(price)); imageViewIcon.setImageResource(icon); return v; } }
package graphics; import java.awt.*; import javax.swing.*; import java.util.*; import board.Board; import board.Cell; import city.City; public class Grid extends Box { private int n_rows; private int n_cols; private Board board; private GridCell[][] grid_cells; private Hashtable<String, GridCell> grid_cityCells; // Used for quick cell update when an action occurs in a // specific city // Actual panel dimensions (pixels) private int cell_size; // Constructors public Grid(Board board, Renderer r, int cell_size) { this.r = r; this.cell_size = cell_size; this.grid_cityCells = new Hashtable<String, GridCell>(); this.board = board; int[] dimensions = board.getDimensions(); this.n_rows = dimensions[0]; this.n_cols = dimensions[1]; this.width = this.cell_size * this.n_cols; this.height = this.cell_size * this.n_rows; this.grid_cells = new GridCell[this.n_rows][this.n_cols]; this.updateSize(); this.setLayout(new GridLayout(this.n_rows, this.n_cols, 0, 0)); this.drawCells(); } /* * Refresh the grid cells containing the specified city aliases */ public void refresh(ArrayList<String> city_aliases) { for (String city_alias : city_aliases) { // System.out.println(">>>>>Refreshing graphs for city " + city_alias); // Retrieves relevant grid cell and calls its update method GridCell gcell = this.grid_cityCells.get(city_alias); if (gcell == null) { System.out.printf("conflict with city %s\n", city_alias); } gcell.refresh(); // System.out.println("updated city "+city_alias); } } /* * Resolves the grid graphics */ public void drawCells() { // Draws grid cells one by one for (int row = 0; row < this.n_rows; row++) { // System.out.printf(">>>>>>row %d\n", row); for (int col = 0; col < this.n_cols; col++) { // System.out.printf(">>col %d\n", col); // Initializes graphic object and adds it to the main panel // Also updates the control array (grid_cells) Cell cell_board = this.board.getCell(row, col); City cell_city = cell_board.getCity(); GridCell gcell = new GridCell(this.cell_size, cell_board, this.r); // If cell contains a city, save data to hashtable if (cell_city != null) { String cell_cityAlias = cell_city.alias; grid_cityCells.put(cell_cityAlias, gcell); } this.grid_cells[row][col] = gcell; this.add(gcell); } } } }
package BLL; import DAL.BookInfo; import DAL.BorrowerInfo; import DAL.BorrowingInfo; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; public class BorrowBookController { private ArrayList<BookInfo> book_list = new ArrayList<>(); /** * Get information of all book that is Available and Borrowable * * @param keyword a string that input to look up data * @param catalogue a string that specifies catalogue on where to look up, can be "all" for all catalogues * @return non-empty ArrayList of BookInfo, null otherwise */ public ArrayList<BookInfo> getBookInfo(String keyword, String catalogue) { ArrayList<BookInfo> lists = BookInfo.getBookInfo(keyword, catalogue); if (lists != null) { if (lists.isEmpty()) return null; } else { return null; } book_list.clear(); for (BookInfo book : lists) { if (book.getStatus().equals("Available") && book.getType().equals("Borrowable")) { book_list.add(book); } } lists.clear(); int i = 0; while (i < this.book_list.size()) { int count = 1; int j = i + 1; while (j < this.book_list.size()) { if (this.book_list.get(j).getBookID().equals(this.book_list.get(i).getBookID())) { count++; j++; } else break; } for (int k = i; k < j; k++) this.book_list.get(k).setNumberLeft(count); i += count; } return this.book_list; } /** * Get number of current borrowing book of that User * * @param borrower a BorrowerInfo indicates Borrower using system * @return int */ private int getNumberOfCurrentBook(BorrowerInfo borrower) { int cardID = borrower.getCardID(); ArrayList<BorrowingInfo> list = BorrowingInfo.getBorrowingInfo(Integer.toString(cardID), "cardID"); if (list == null) { return 0; } if (list.isEmpty()) { return 0; } int count = 0; for (BorrowingInfo one : list) { if (one.getStatus().equals("Taken") || one.getStatus().equals("Pending")) { count++; } } return count; } private boolean updateBookInfo(BookInfo book) { book.setStatus("Borrowed"); return book.updateQuery(); } /** * create borrowing info * @param borrower borrower who borrow * @param book a bookInfo to be borrowed * @return true if success, false otherwise */ private boolean createBorrowingInfo(BorrowerInfo borrower, BookInfo book) { BorrowingInfo borrowingInfo = new BorrowingInfo(); borrowingInfo.setStatus("Pending"); borrowingInfo.setBookNumber(book.getBookID()); borrowingInfo.setCardNumber(borrower.getCardID()); borrowingInfo.setCopyNumber(book.getSequenceNumber()); Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_YEAR, 2); Date collectDate = c.getTime(); c.add(Calendar.MONTH, 2); Date dueDate = c.getTime(); borrowingInfo.setCollectDate(collectDate); borrowingInfo.setDueDate(dueDate); return borrowingInfo.insertQuery(); } /** * check request to checkout * * @param borrower a BorrowerInfo indicates borrower using system * @param select_list an ArrayList of BookInfo contains list of selected books * @return 1 if no problem, 2 if not able to borrow, 3 if select excess number of books */ public int checkRequest(BorrowerInfo borrower, ArrayList<BookInfo> select_list) { boolean status = borrower.getBorrowerStatus(); if (!status) return 2; int numBook = getNumberOfCurrentBook(borrower) + select_list.size(); if (numBook > 5) { return 3; } return 1; } /** * process checkout * @param borrower borrower that do the checkout * @param select_list selected book list for the checkout * @return 1 if success, 0 otherwise */ public int checkOut(BorrowerInfo borrower, ArrayList<BookInfo> select_list) { int numBook = getNumberOfCurrentBook(borrower) + select_list.size(); if (numBook == 5){ borrower.setBorrowerStatus(false); borrower.updateQuery(); } for (BookInfo book : select_list) { if (!updateBookInfo(book) || !createBorrowingInfo(borrower, book)) return 0; } return 1; } /** * Warn Borrower time to collect book expired * * @param borrower a BorrowerInfo indicates borrower using system * @return true if there is a overdue date book, false otherwise */ public boolean warnExpireTime(BorrowerInfo borrower) { ReturnBookController rController = new ReturnBookController(); ArrayList<BorrowingInfo> lists = getBorrowingInfo(Integer.toString(borrower.getCardID()), "cardID"); if (lists != null){ if (!lists.isEmpty()){ for (BorrowingInfo one : lists){ rController.update(one); } return true; } } return false; } /** get borrowing info to check expire time * * @param keyword keyword to search * @param category category applied * @return non-empty lists of borrowingInfo, null otherwise */ private ArrayList<BorrowingInfo> getBorrowingInfo(String keyword, String category) { ArrayList<BorrowingInfo> borrowingInfos = new ArrayList<>(); ArrayList<BorrowingInfo> lists; lists = BorrowingInfo.getBorrowingInfo(keyword, category); if (lists != null) { if (!lists.isEmpty()) { for (BorrowingInfo one : lists) { if (one.getCollectDate().before(new Date()) && one.getStatus().equals("Pending")) borrowingInfos.add(one); } lists.clear(); if (borrowingInfos.isEmpty()) return null; return borrowingInfos; } } return null; } }
package ua.lviv.iot.uklon.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import ua.lviv.iot.uklon.domain.Adress; @Repository public interface AdressRepository extends JpaRepository<Adress, Integer> { }
public class Percolation { private int gridSize; // number of sites in grid private int gridEdgeLength; //square root of gridSize private WeightedQuickUnionUF uf; private int[] status; //keeps track of open/closed status. public Percolation(int N) { // create N-by-N grid, with all sites blocked if (N < 1) { throw new IllegalArgumentException(); //invalid grid-size } else { gridSize = N*N; //(0 is for virtual top, N+2 is for virtual bottom) uf = new WeightedQuickUnionUF(gridSize+2); gridEdgeLength = N; status = new int[gridSize+1]; for (int i = 1; i < gridSize+1; i++) { status[i] = 0; } connectVirtualSites(); } } private int xyTo1D(int x, int y) { //index 0 is reserved for the virtual "top". Hence, (1,1) returns 1. return (gridEdgeLength*x)-(gridEdgeLength-y); } private void indexOutOfBounds(int i, int j) { if (i < 1 || j < 1 || i > gridSize || j > gridSize) { throw new IndexOutOfBoundsException(); } } private boolean hasTopNeighbor(int i, int j) { return i > 1; } private boolean hasBottomNeighbor(int i, int j) { return i < gridEdgeLength; } private boolean hasLeftNeighbor(int i, int j) { return j > 1; } private boolean hasRightNeighbor(int i, int j) { return j < gridEdgeLength; } private int getTopNeighbor(int i, int j) { return xyTo1D(i , j) - gridEdgeLength; } private int getBottomNeighbor(int i, int j) { return xyTo1D(i , j) + gridEdgeLength; } private int getLeftNeighbor(int i, int j) { return xyTo1D(i , j) - 1; } private int getRightNeighbor(int i, int j) { return xyTo1D(i , j) + 1; } private void connectOpenNeighbors(int i, int j) { if (hasTopNeighbor(i , j) && isOpen(i-1 , j)) { uf.union(xyTo1D(i , j) , getTopNeighbor(i , j)); } if (hasBottomNeighbor(i , j) && isOpen(i+1 , j)) { uf.union(xyTo1D(i , j) , getBottomNeighbor(i , j)); } if (hasLeftNeighbor(i , j) && isOpen(i , j-1)) { uf.union(xyTo1D(i , j) , getLeftNeighbor(i , j)); } if (hasRightNeighbor(i , j) && isOpen(i , j+1)) { uf.union(xyTo1D(i , j) , getRightNeighbor(i , j)); } } //connects the top and bottom virtual sites to the first and last row private void connectVirtualSites() { int i = 1; while (i < gridEdgeLength+1) { uf.union(0 , i); i++; } i = gridSize; while (i > gridSize-gridEdgeLength) { uf.union(gridSize+1 , i); i--; } } /* *open site (row i, column j) if it is not already */ public void open(int i, int j) { indexOutOfBounds(i , j); if (status[xyTo1D(i , j)] != 1) { status[xyTo1D(i , j)] = 1; connectOpenNeighbors(i , j); } } public boolean isOpen(int i, int j) { // is site (row i, column j) open? indexOutOfBounds(i , j); return (status[xyTo1D(i , j)] == 1); } public boolean isFull(int i, int j) { // is site (row i, column j) full? indexOutOfBounds(i , j); if (isOpen(i , j)) { return uf.connected(0 , xyTo1D(i , j)); } return false; } public boolean percolates() { // does the system percolate? return uf.connected(0 , gridSize+1); } public static void main(String[] args) { } }
package com.zhouyi.business.core.service; /** * @author 李秸康 * @ClassNmae: PhoneService * @Description: TODO 手机信息业务接口 * @date 2019/7/12 9:27 * @Version 1.0 **/ public interface PhoneService { /** * 解析文件入库 * @param path * @return */ boolean parseXml(String path); }
package epam.ph.sg.models.xo; /** * @author Paul Michael T. */ public class XOBox { private int status = XO.EMPTY; private int x; private int y; public XOBox(int x, int y) { this.x = x; this.y = y; } /** * Status getter * * @return XO.EMPTY, XO.X or XO.O */ public int getStatus() { return status; } /** * Status setter * * @param status * - XO.EMPTY, XO.X or XO.O */ public int setStatus(int status) { if (this.status == XO.EMPTY) { this.status = status; return XO.DONE; } else { return XO.NOT_EMPTY; } } /** * X coordinate getter * * @return X coordinate of this box */ public int getX() { return x; } /** * Y coordinate getter * * @return Y coordinate of this box */ public int getY() { return y; } }
package com.gmail.vasylvovkast.ht01; /** * @author Vasyl Vovk * Завдання в якому потрібно вивести на екран всі непарні числа числа у * діапазоні [0..10]. */ public class HT01 { public static void main(String... args) { int N = 10; int odd = 1; while (odd <= N) { System.out.print(odd + "\t"); odd += 2; } System.out.println(); } }
package bst; import javax.swing.event.TreeModelListener; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; public class BST extends IBST { private Node<Integer, Integer> root = null; public boolean containsKey(Integer k) { Node<Integer, Integer> x = root; while (x != null) { int cmp = k.compareTo(x.key); if (cmp == 0) { return true; } if (cmp < 0) { x = x.left; } else { x = x.right; } } return false; } public Integer get(Integer k) { Node<Integer, Integer> x = root; while (x != null) { int cmp = k.compareTo(x.key); if (cmp == 0) { return x.value; } if (cmp < 0) { x = x.left; } else { x = x.right; } } return null; } public void add(Integer k, Integer v) { int nHeight = 1; Node<Integer, Integer> x = root, y = null; while (x != null) { int cmp = k.compareTo(x.key); if (cmp == 0) { x.value = v; return; } else { y = x; if (cmp < 0) { x = x.left; } else { x = x.right; } nHeight++; } } Node<Integer, Integer> newNode = new Node<Integer, Integer>(k, v); if (y == null) { root = newNode; } else { if (k.compareTo(y.key) < 0) { y.left = newNode; } else { y.right = newNode; } } size++; if (nHeight > height) { height = nHeight; } } public void remove(Integer k) { Node<Integer, Integer> x = root, y = null; while (x != null) { int cmp = k.compareTo(x.key); if (cmp == 0) { break; } else { y = x; if (cmp < 0) { x = x.left; } else { x = x.right; } } } if (x == null) { return; } if (x.right == null) { if (y == null) { root = x.left; } else { if (x == y.left) { y.left = x.left; } else { y.right = x.left; } } } else { Node<Integer, Integer> leftMost = x.right; y = null; while (leftMost.left != null) { y = leftMost; leftMost = leftMost.left; } if (y != null) { y.left = leftMost.right; } else { x.right = leftMost.right; } x.key = leftMost.key; x.value = leftMost.value; } size--; } public void traverseAll(ConsoleTreeVisitor visitor) { root.traverse(visitor); } public void addTreeModelListener(TreeModelListener l) { // TODO Auto-generated method stub } public Object getChild(Object parent, int index) { Node nparent = (Node) parent; Object toReturn; toReturn = (index == 0 ? nparent.left : nparent.right); toReturn = (toReturn == null ? "NULL" : toReturn); return toReturn; } public int getChildCount(Object parent) { return 2; } public int getIndexOfChild(Object parent, Object child) { return 0; } public Object getRoot() { return root; } public boolean isLeaf(Object node) { if (node instanceof Node) { Node n = (Node) node; if (n.left == null && n.right == null) { return true; } return false; } return true; } public void removeTreeModelListener(TreeModelListener l) { // TODO Auto-generated method stub } public void valueForPathChanged(TreePath path, Object newValue) { // TODO Auto-generated method stub } }
package com.rishi.baldawa.iq; import org.junit.Test; import static org.junit.Assert.*; public class IntegerToRomanTest { @Test public void intToRoman() throws Exception { assertEquals(new IntegerToRoman().intToRoman(47),"XLVII"); assertEquals(new IntegerToRoman().intToRoman(123),"CXXIII"); assertEquals(new IntegerToRoman().intToRoman(1998),"MCMXCVIII"); assertEquals(new IntegerToRoman().intToRoman(2345),"MMCCCXLV"); } }
package com.base.crm.salary.service.impl; import java.math.BigDecimal; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.base.crm.salary.dao.ServerSalaryMapper; import com.base.crm.salary.entity.ServerSalary; import com.base.crm.salary.service.ServerSalaryService; @Service public class ServerSalaryServiceImpl implements ServerSalaryService { @Autowired private ServerSalaryMapper serverSalaryMapper; @Override public int deleteByPrimaryKey(Long id) { return serverSalaryMapper.deleteByPrimaryKey(id); } @Override public int insertSelective(ServerSalary record) { return serverSalaryMapper.insertSelective(record); } @Override public ServerSalary selectByPrimaryKey(Long id) { return serverSalaryMapper.selectByPrimaryKey(id); } @Override public int updateByPrimaryKeySelective(ServerSalary record) { return serverSalaryMapper.updateByPrimaryKeySelective(record); } @Override public Long selectPageTotalCount(ServerSalary queryObject) { return serverSalaryMapper.selectPageTotalCount(queryObject); } @Override public List<ServerSalary> selectPageByObjectForList(ServerSalary queryObject) { return serverSalaryMapper.selectPageByObjectForList(queryObject); } @Override public BigDecimal querySumAmountByMonth(String month) { return serverSalaryMapper.querySumAmountByMonth(month); } }
package com.travel_agency.service; import com.travel_agency.entity.Room; import java.util.List; public interface RoomService { void add(Room room); Room getRoomById(int id); List<Room> getRoomsByHotelId(int id); List<Room> getAvailableRoomsOnDateInHotel(String startDate, String endDate, int hotelId); }
package com.favccxx.shy.dao; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import com.favccxx.shy.entity.ShyUser; public interface UserInfoRepository extends CrudRepository<ShyUser, Long> { /** * 根据用户名查询用户信息 * @param userName * @return */ ShyUser findByUserName(String userName); @Query( value = "from ShyUser su", countQuery = " select count(su) from ShyUser su" ) Page<ShyUser> pageUsers(String userName, String nickName, Pageable pageable); }
package org.ecsoya.yamail.handlers; import org.eclipse.e4.core.di.annotations.Execute; public class DeleteMailCommand { @Execute public void execute() { } }