blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
4df40b3e11e85c73c6dee28be1380f5e3f9e22f2
Java
hugolyra/projetoescolar
/ProjetoHistoricoEscolar/src/Form/LoginAlunoForm.java
ISO-8859-1
8,033
2.421875
2
[]
no_license
package Form; import java.awt.Component; import java.awt.EventQueue; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import java.awt.Toolkit; public class LoginAlunoForm extends JFrame { private JPanel contentPane; private JTextField textField; private JPasswordField passwordField; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { LoginAlunoForm frame = new LoginAlunoForm(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public LoginAlunoForm() { setTitle("Faculdade Matriz"); setResizable(false); setIconImage(Toolkit.getDefaultToolkit().getImage("E:\\Documentos de LeO\\Cursos\\Faculdade de S.I\\4\u00B0 Per\u00EDodo\\Cadeira (Projeto de Banco de Dados)\\Imagens do Projeto de BD\\Logo FaculdadeMenor.png")); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 550, 400); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); JLabel lblNewLabel = new JLabel(""); lblNewLabel.setIcon(new ImageIcon("E:\\Documentos de LeO\\Cursos\\Faculdade de S.I\\4\u00B0 Per\u00EDodo\\Cadeira (Projeto de Banco de Dados)\\Imagens do Projeto de BD\\Logo FaculdadeMenor.png")); JLabel lblFaculdadeMatriz = new JLabel("Faculdade Matriz"); lblFaculdadeMatriz.setFont(new Font("Tahoma", Font.BOLD, 16)); JLabel lblLogin = new JLabel("Login:"); lblLogin.setFont(new Font("Tahoma", Font.PLAIN, 14)); textField = new JTextField(); textField.setColumns(10); JLabel lblSenha = new JLabel("Senha:"); lblSenha.setFont(new Font("Tahoma", Font.PLAIN, 14)); passwordField = new JPasswordField(); JLabel lblAluno = new JLabel("Aluno"); lblAluno.setFont(new Font("Tahoma", Font.BOLD, 14)); JButton btnCancelar = new JButton("Cancelar"); btnCancelar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JOptionPane.showMessageDialog(null, "Operao Cancelada"); textField.setText(""); passwordField.setText(""); } private void dispose() { } }); btnCancelar.setFont(new Font("Tahoma", Font.PLAIN, 14)); btnCancelar.setIcon(new ImageIcon("E:\\Documentos de LeO\\Cursos\\Faculdade de S.I\\4\u00B0 Per\u00EDodo\\Cadeira (Projeto de Banco de Dados)\\Imagens do Projeto de BD\\Errado.png")); JButton btnAcessar = new JButton("Acessar"); btnAcessar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (textField.getText().equals("adm") && (passwordField.getText().equals("123"))){ JOptionPane.showMessageDialog(null, "Acesso Concedido"); //new PainelSecretariaForm().setVisible(true); this.dispose(); }else{ JOptionPane.showMessageDialog(null, "Acesso Negado"); textField.setText(""); passwordField.setText(""); } } private void dispose() { } }); btnAcessar.setFont(new Font("Tahoma", Font.PLAIN, 14)); btnAcessar.setIcon(new ImageIcon("E:\\Documentos de LeO\\Cursos\\Faculdade de S.I\\4\u00B0 Per\u00EDodo\\Cadeira (Projeto de Banco de Dados)\\Imagens do Projeto de BD\\Correto.png")); JButton btnVoltar = new JButton("Voltar"); btnVoltar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new TelaPrincipalForm().setVisible(true); this.dispose(); } private void dispose() { } }); btnVoltar.setIcon(new ImageIcon("E:\\Documentos de LeO\\Cursos\\Faculdade de S.I\\4\u00B0 Per\u00EDodo\\Cadeira (Projeto de Banco de Dados)\\Imagens do Projeto de BD\\VoltarPNG.png")); GroupLayout gl_contentPane = new GroupLayout(contentPane); gl_contentPane.setHorizontalGroup( gl_contentPane.createParallelGroup(Alignment.TRAILING) .addGroup(gl_contentPane.createSequentialGroup() .addContainerGap() .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addComponent(btnVoltar) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addPreferredGap(ComponentPlacement.RELATED, 49, Short.MAX_VALUE) .addComponent(btnAcessar, GroupLayout.PREFERRED_SIZE, 110, GroupLayout.PREFERRED_SIZE) .addGap(35) .addComponent(btnCancelar) .addGap(133)) .addGroup(gl_contentPane.createSequentialGroup() .addGap(118) .addComponent(lblNewLabel) .addContainerGap()))) .addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup() .addComponent(lblFaculdadeMatriz) .addGap(192))) .addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup() .addComponent(lblAluno) .addGap(242))) .addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup() .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING, false) .addGroup(gl_contentPane.createSequentialGroup() .addComponent(lblSenha) .addGap(18)) .addGroup(gl_contentPane.createSequentialGroup() .addComponent(lblLogin, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(ComponentPlacement.RELATED))) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false) .addComponent(passwordField) .addComponent(textField, GroupLayout.PREFERRED_SIZE, 98, GroupLayout.PREFERRED_SIZE)) .addGap(182)))) ); gl_contentPane.setVerticalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addGap(9) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addComponent(btnVoltar) .addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup() .addPreferredGap(ComponentPlacement.RELATED) .addComponent(lblNewLabel, GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(lblFaculdadeMatriz) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(lblAluno) .addGap(38) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblLogin)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(passwordField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblSenha)) .addGap(20) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(btnCancelar) .addComponent(btnAcessar, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE)))) .addContainerGap()) ); gl_contentPane.linkSize(SwingConstants.HORIZONTAL, new Component[] {btnCancelar, btnAcessar}); contentPane.setLayout(gl_contentPane); } }
true
f6dc4b2c94dff4240b98515ac2221cbdae0f4260
Java
jinhuh229/MeetUp
/app/src/main/java/com/mobileappdev/teamone/meetup/DbRepository/Repository.java
UTF-8
22,088
2.34375
2
[]
no_license
package com.mobileappdev.teamone.meetup.DbRepository; import android.os.AsyncTask; import android.os.Build; import com.mobileappdev.teamone.meetup.MapModels.MapEventAttendee; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; public class Repository { public class Event { public Integer event_id; public String event_name; public Date event_created; public Date event_start; public Date event_end; public Double event_latitude; public Double event_longitude; public Integer event_radius; public Boolean event_link_sharing; public Boolean event_require_approval; public List<EventUser> Attendees; public Integer AttendeesCount; } public class User { public Integer user_id; public String user_name; public Double user_lat; public Double user_lng; } public class Chat { public Integer chat_id; public Event event; public Integer user_count; } public class ChatMessage { public Integer chatmesssage_id; public String chatmessage_message; public Date chatmessage_date; public String chatmessage_user_name; public Integer chatmessage_user_id; } private class EventUser extends User { } private class NonResultQuery extends AsyncTask<String, Void, Boolean> { @Override protected Boolean doInBackground(String... strings) { Boolean executed = false; Connection con = null; Statement stmt = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://frankencluster.com:3306/mdevteam1", "mdevteam1user", "sjw.yq97b.H2n" ); stmt = con.createStatement(); String sql = strings[0]; executed = stmt.execute(sql); stmt.close(); con.close(); } catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(con!=null) con.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try return executed; } } private class GetUserList extends AsyncTask<String, Void, List<User>> { @Override protected List<User> doInBackground(String... strings) { List<User> userList = new ArrayList<>(); Connection con = null; Statement stmt = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://frankencluster.com:3306/mdevteam1", "mdevteam1user", "sjw.yq97b.H2n" ); stmt = con.createStatement(); String sql = strings[0]; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { User user = new User(); user.user_id = rs.getInt(1); user.user_name = rs.getString(2); user.user_lat = rs.getDouble(3); user.user_lng = rs.getDouble(4); userList.add(user); } rs.close(); stmt.close(); con.close(); } catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(con!=null) con.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try return userList; } } private class GetChatList extends AsyncTask<String, Void, List<Chat>> { @Override protected List<Chat> doInBackground(String... strings) { List<Chat> chatList = new ArrayList<>(); Connection con = null; Statement stmt = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://frankencluster.com:3306/mdevteam1", "mdevteam1user", "sjw.yq97b.H2n" ); stmt = con.createStatement(); String sql = strings[0]; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { Chat chat = new Chat(); chat.chat_id = rs.getInt(1); chat.user_count = rs.getInt(2); String eventname = rs.getString(3); if (!rs.wasNull()) { chat.event = new Event(); chat.event.event_name = eventname; chat.event.event_start = rs.getDate(4); chat.event.event_end = rs.getDate(5); chat.event.event_latitude = rs.getDouble(6); chat.event.event_longitude = rs.getDouble(7); } else { chat.event = null; } // user.user_lat = rs.getDouble(3); // user.user_lng = rs.getDouble(4); chatList.add(chat); } rs.close(); stmt.close(); con.close(); } catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(con!=null) con.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try return chatList; } } private class GetEventList extends AsyncTask<String, Void, List<Event>> { @Override protected List<Event> doInBackground(String... strings) { List<Event> eventList = new ArrayList<>(); Connection con = null; Statement stmt = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://frankencluster.com:3306/mdevteam1", "mdevteam1user", "sjw.yq97b.H2n" ); stmt = con.createStatement(); String sql = strings[0]; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { Event event = new Event(); event.event_id = rs.getInt(1); event.event_name = rs.getString(2); event.event_created = rs.getDate(3); event.event_start = rs.getDate(4); event.event_end = rs.getDate(5); event.event_latitude = rs.getDouble(6); event.event_longitude = rs.getDouble(7); event.event_radius = rs.getInt(8); event.event_link_sharing = rs.getBoolean(9); event.event_require_approval = rs.getBoolean(10); event.AttendeesCount = rs.getInt(11); eventList.add(event); } rs.close(); stmt.close(); con.close(); } catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(con!=null) con.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try return eventList; } } private class GetChatMessageList extends AsyncTask<String, Void, List<ChatMessage>> { @Override protected List<ChatMessage> doInBackground(String... strings) { List<ChatMessage> chatMessageList = new ArrayList<>(); Connection con = null; Statement stmt = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://frankencluster.com:3306/mdevteam1", "mdevteam1user", "sjw.yq97b.H2n" ); stmt = con.createStatement(); String sql = strings[0]; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { ChatMessage chatMessage = new ChatMessage(); chatMessage.chatmesssage_id = rs.getInt(1); chatMessage.chatmessage_message = rs.getString(2); chatMessage.chatmessage_date = rs.getDate(3); chatMessage.chatmessage_user_name = rs.getString(4); chatMessage.chatmessage_user_id = rs.getInt(5); chatMessageList.add(chatMessage); } rs.close(); stmt.close(); con.close(); } catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(con!=null) con.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try return chatMessageList; } } public List<MapEventAttendee> GetEventAttendees(Integer event_id) { String sql = "SELECT `user_id`, `user_name`, `user_centerLatitude`, `user_centerLongitude` FROM `user` inner join `xrefEventAttendance_event_user` on `user_id`=`eventAttendance_user_id` inner join `event` on `event_id`=`eventAttendance_event_id` WHERE `event_id`=" + event_id; try { List<User> users = (new GetUserList().execute(sql).get()); List<MapEventAttendee> attendees = new ArrayList<>(); for(User user:users) { MapEventAttendee attendee = new MapEventAttendee( user.user_id, user.user_name, user.user_lat, user.user_lng ); attendees.add(attendee); } return attendees; } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return null; } public List<User> ListAllUsers() { String sql = "SELECT `user_id`, `user_name`, `user_centerLatitude`, `user_centerLongitude` FROM `user`"; try { return (new GetUserList().execute(sql).get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return null; } public Boolean UpdateUserPosition(int user_id, double lat, double lng) { String sql = "UPDATE `user` SET `user`.`user_centerLatitude`=" + lat + ", `user`.`user_centerLongitude`=" + lng + " WHERE `user`.`user_id`=" + user_id; try { return (new NonResultQuery()).execute(sql).get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return false; } private class InsertQuery extends AsyncTask<String, Void, List<Integer>> { @Override protected List<Integer> doInBackground(String... strings) { List<Integer> ids = new ArrayList<>(); Connection con = null; Statement stmt = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://frankencluster.com:3306/mdevteam1", "mdevteam1user", "sjw.yq97b.H2n" ); stmt = con.createStatement(); String sql = strings[0]; stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); int autoIncKeyFromApi = -1; ResultSet rs = stmt.getGeneratedKeys(); while(rs.next()) { ids.add(rs.getInt(1)); } rs.close(); rs = null; stmt.close(); con.close(); } catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(con!=null) con.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try return ids; } } public List<Integer> InsertEvent(String name, double lat, double lng, java.util.Date start, java.util.Date end, Integer radius) { java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String sql = "INSERT INTO `event` " + "(`event_name`, `event_dateCreated`, `event_startTime`, `event_endTime`, `event_centerLatitude`, `event_centerLongitude`, `event_radius`) " + "VALUES " + "('" + name + "','" + sdf.format(new java.util.Date()) + "','" + sdf.format(start) + "','" + sdf.format(end) + "'," + lat + "," + lng + "," + radius + ")"; try { return (new InsertQuery()).execute(sql).get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return null; /* `event_name` varchar(500), `event_dateCreated` datetime, `event_startTime` datetime, `event_endTime` datetime, `event_centerLatitude` double not null default 0.0, `event_centerLongitude` double not null default 0.0, `event_radius` int not null default 0, */ } public List<Integer> InsertUserInEvent(Integer event_id, List<Integer> user_id) { String sql = "INSERT INTO `xrefEventAttendance_event_user` (`eventAttendance_event_id`,`eventAttendance_user_id`) VALUES "; for (Integer userId:user_id) { sql += "(" + event_id + "," + userId + "),"; } sql = sql.substring(0, sql.length()-1); try { return (new InsertQuery()).execute(sql).get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return null; } public List<Event> GetEventsForUser(Integer user_id) { String sql = "SELECT `event_id`, `event_name`, `event_dateCreated`, `event_startTime`, `event_endTime`, `event_centerLatitude`, `event_centerLongitude`, `event_radius`, `event_link_sharing`, `event_require_approval`, count(`eventAttendance_user_id`) FROM `event` inner join `xrefEventAttendance_event_user` on `event_id`=`eventAttendance_event_id` WHERE `event_id` IN (SELECT `event_id` FROM `event` inner join `xrefEventAttendance_event_user` on `event_id`=`eventAttendance_event_id` where `eventAttendance_user_id`=" + user_id +") GROUP BY `event_id`;"; try { return (new GetEventList()).execute(sql).get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return null; } public Event GetEventById(Integer event_id) { String sql = "SELECT `event_id`, `event_name`, `event_dateCreated`, `event_startTime`, `event_endTime`, `event_centerLatitude`, `event_centerLongitude`, `event_radius`, `event_link_sharing`, `event_require_approval`, count(`eventAttendance_user_id`) FROM `event` inner join `xrefEventAttendance_event_user` on `event_id`=`eventAttendance_event_id` WHERE `event_id`=" + event_id + " GROUP BY `event_id`;"; try { List<Event> events = (new GetEventList()).execute(sql).get(); if(events.size()==1) return events.get(0); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return null; } public List<Integer> InsertEventChat(Integer event_id) { String sql = "INSERT INTO `chat` (`chat_event_id`) VALUES (" + event_id + ")"; try { return (new InsertQuery().execute(sql).get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return null; } public List<Integer> InsertUsersIntoChat(List<Integer> user_ids, Integer chat_id) { String sql = "INSERT INTO `xrefChatUser_chat_user` (`chatuser_chat_id`, `chatuser_user_id`) VALUES "; for (Integer user_id:user_ids) { sql += "(" + chat_id + "," + user_id + "),"; } sql = sql.substring(0,sql.length()-1); try { return (new InsertQuery().execute(sql).get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return null; } public List<Chat> ListAllChatsForUser(Integer user_id) { String sql = "SELECT `chat_id`, count(`chat_id`), `event_name`, `event_startTime`, `event_endTime`, `event_centerLatitude`, `event_centerLongitude` " + "FROM (`chat` inner join `xrefChatUser_chat_user` on `chat_id` = `chatuser_chat_id`) left join `event` on `chat_event_id`=`event_id` " + "WHERE `chat_id` IN " + "( " + " SELECT `chat_id` FROM `chat` inner join `xrefChatUser_chat_user` on `chat_id` = `chatuser_chat_id` WHERE `chatuser_user_id`=" + user_id + ") " + "group by `chat_id`, `event_name`, `event_startTime`, `event_endTime`, `event_centerLatitude`, `event_centerLongitude`"; try { return (new GetChatList()).execute(sql).get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return null; } public List<ChatMessage> ListMessagesForChat(Integer chat_id) { String sql = "SELECT `chatmessage_id`, `chatmessage_message`, `chatmessage_time`, `chatmessage_user_name`, `chatmessage_user_id` FROM `chatmessage` WHERE `chatmessage_chat_id`=" + chat_id; try { return (new GetChatMessageList()).execute(sql).get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return null; }; public Boolean InsertChatMessage(String message, Integer user_id, Integer chat_id) { java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String sql="insert into `chatmessage` (`chatmessage_message`, `chatmessage_time`, `chatmessage_chat_id`, `chatmessage_user_id`, `chatmessage_user_name`) " + "VALUES (" + "'" + message + "'," + "'"+ sdf.format(new java.util.Date()) + "'," + chat_id + "," + user_id + "," + "(SELECT `user_name` FROM `user` WHERE `user_id`="+user_id+" limit 1)" + ")"; try { return (new NonResultQuery()).execute(sql).get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return false; } }
true
34a4f7490c9ebd0fb2c862fb1995406b1b594fe9
Java
ShikhaAndroid/NoticeBoard
/app/src/main/java/com/rajinder/noticeboard/UI/ViewHolder/FilterCategoryViewHolder.java
UTF-8
353
1.828125
2
[]
no_license
package com.rajinder.noticeboard.UI.ViewHolder; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.View; public class FilterCategoryViewHolder extends RecyclerView.ViewHolder { private static Context mContext; public FilterCategoryViewHolder(View itemView) { super(itemView); } }
true
e911bd3c25847d3759e6d461771bd097db65ab5c
Java
AICP/packages_apps_Settings
/src/com/android/settings/development/AdbIpAddressPreferenceController.java
UTF-8
4,924
1.867188
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings.development; import android.content.Context; import android.debug.IAdbManager; import android.net.ConnectivityManager; import android.net.LinkProperties; import android.net.wifi.WifiManager; import android.os.RemoteException; import android.os.ServiceManager; import android.util.Log; import androidx.preference.Preference; import androidx.preference.PreferenceScreen; import com.android.settings.R; import com.android.settingslib.core.lifecycle.Lifecycle; import com.android.settingslib.deviceinfo.AbstractConnectivityPreferenceController; import java.net.Inet4Address; import java.net.InetAddress; import java.util.Iterator; /** * Controller for the ip address preference in the Wireless debugging * fragment. */ public class AdbIpAddressPreferenceController extends AbstractConnectivityPreferenceController { private static final String TAG = "AdbIpAddrPrefCtrl"; private static final String[] CONNECTIVITY_INTENTS = { ConnectivityManager.CONNECTIVITY_ACTION, WifiManager.ACTION_LINK_CONFIGURATION_CHANGED, WifiManager.NETWORK_STATE_CHANGED_ACTION, }; private static final String PREF_KEY = "adb_ip_addr_pref"; private Preference mAdbIpAddrPref; private int mPort; private final ConnectivityManager mCM; private IAdbManager mAdbManager; public AdbIpAddressPreferenceController(Context context, Lifecycle lifecycle) { super(context, lifecycle); mCM = context.getSystemService(ConnectivityManager.class); mAdbManager = IAdbManager.Stub.asInterface(ServiceManager.getService( Context.ADB_SERVICE)); } @Override public boolean isAvailable() { return true; } @Override public String getPreferenceKey() { return PREF_KEY; } @Override public void displayPreference(PreferenceScreen screen) { super.displayPreference(screen); mAdbIpAddrPref = screen.findPreference(PREF_KEY); updateConnectivity(); } @Override public void updateState(Preference preference) { super.updateState(preference); updateConnectivity(); } @Override protected String[] getConnectivityIntents() { return CONNECTIVITY_INTENTS; } protected int getPort() { try { return mAdbManager.getAdbWirelessPort(); } catch (RemoteException e) { Log.e(TAG, "Unable to get the adbwifi port"); } return 0; } public String getIpv4Address() { return getDefaultIpAddresses(mCM); } @Override protected void updateConnectivity() { String ipAddress = getDefaultIpAddresses(mCM); if (ipAddress != null) { int port = getPort(); if (port <= 0) { mAdbIpAddrPref.setSummary(R.string.status_unavailable); } else { ipAddress += ":" + port; } mAdbIpAddrPref.setSummary(ipAddress); } else { mAdbIpAddrPref.setSummary(R.string.status_unavailable); } } /** * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style * addresses. * @param cm ConnectivityManager * @return the formatted and newline-separated IP addresses, or null if none. */ private static String getDefaultIpAddresses(ConnectivityManager cm) { LinkProperties prop = cm.getActiveLinkProperties(); return formatIpAddresses(prop); } private static String formatIpAddresses(LinkProperties prop) { if (prop == null) { return null; } Iterator<InetAddress> iter = prop.getAllAddresses().iterator(); // If there are no entries, return null if (!iter.hasNext()) { return null; } // Concatenate all available addresses, newline separated StringBuilder addresses = new StringBuilder(); while (iter.hasNext()) { InetAddress addr = iter.next(); if (addr instanceof Inet4Address) { // adb only supports ipv4 at the moment addresses.append(addr.getHostAddress()); break; } } return addresses.toString(); } }
true
eb116be86ef540a5d154a23ac2feeb3a48aba159
Java
Learner-wangbw/TmallTest
/src/main/java/stu/wbw/mapper/ProductMapper.java
UTF-8
647
2.171875
2
[]
no_license
package stu.wbw.mapper; import stu.wbw.pojo.Product; import java.util.List; public interface ProductMapper { //增加一个产品 int addProduct(Product product); //删除一个产品 int deleteProduct(Integer id); //修改一个产品 int updateProduct(Product product); //查询一个产品 Product queryProductById(Integer id); //查询所有产品 List<Product> queryAllProduct(); //根据category_id返回所有对应的Product数据 List<Product> queryAllProductByCategoryId(Integer category_id); //根据关键字查询相应的产品集合 List<Product> search(String keyword); }
true
9e1b41e8f5e3151104182653cebb49d189a1203e
Java
tdjysu/flinkProj
/DataReportJava/src/main/java/com/dafy/bean/ReportDeptBean.java
UTF-8
2,658
1.960938
2
[]
no_license
package com.dafy.bean; public class ReportDeptBean { private long eventTime = 0; private String deptCode=""; private String deptName = ""; private String busiAreaCode = ""; private String busiAreaName = ""; private String adminAreaCode = ""; private String adminAreaName = ""; private String fundcode = ""; private Integer lendCnt = 0; private Integer lamount = 0; public ReportDeptBean(long eventTime, String deptCode, String deptName, String busiAreaCode, String busiAreaName, String adminAreaCode, String adminAreaName, String fundcode, Integer lendCnt, Integer lamount) { this.eventTime = eventTime; this.deptCode = deptCode; this.deptName = deptName; this.busiAreaCode = busiAreaCode; this.busiAreaName = busiAreaName; this.adminAreaCode = adminAreaCode; this.adminAreaName = adminAreaName; this.fundcode = fundcode; this.lendCnt = lendCnt; this.lamount = lamount; } public long getEventTime() { return eventTime; } public void setEventTime(long eventTime) { this.eventTime = eventTime; } public String getDeptCode() { return deptCode; } public void setDeptCode(String deptCode) { this.deptCode = deptCode; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public String getBusiAreaCode() { return busiAreaCode; } public void setBusiAreaCode(String busiAreaCode) { this.busiAreaCode = busiAreaCode; } public String getBusiAreaName() { return busiAreaName; } public void setBusiAreaName(String busiAreaName) { this.busiAreaName = busiAreaName; } public String getAdminAreaCode() { return adminAreaCode; } public void setAdminAreaCode(String adminAreaCode) { this.adminAreaCode = adminAreaCode; } public String getAdminAreaName() { return adminAreaName; } public void setAdminAreaName(String adminAreaName) { this.adminAreaName = adminAreaName; } public String getFundcode() { return fundcode; } public void setFundcode(String fundcode) { this.fundcode = fundcode; } public Integer getLendCnt() { return lendCnt; } public void setLendCnt(Integer lendCnt) { this.lendCnt = lendCnt; } public Integer getLamount() { return lamount; } public void setLamount(Integer lamount) { this.lamount = lamount; } }
true
d95d8c22d8fb0670d49814d47f7e13e3c3a0d6b8
Java
Sword-Is-Cat/Programmers_JAVA
/Programmers_JAVA/src/level0/ex부분문자열인지확인하기/Solution.java
UTF-8
175
2.796875
3
[]
no_license
package level0.ex부분문자열인지확인하기; class Solution { public int solution(String my_string, String target) { return my_string.contains(target) ? 1 : 0; } }
true
57b620bd0415e6d59abb75bbb40467c0d67abf03
Java
marcelohenrique95/backendAutoSafe
/src/main/java/br/com/collareda/business/domain/service/ServiceService.java
UTF-8
3,188
2.234375
2
[]
no_license
package br.com.collareda.business.domain.service; import java.io.IOException; import java.time.LocalDateTime; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import br.com.collareda.business.domain.exception.NegocioException; import br.com.collareda.business.domain.model.PartnerEntity; import br.com.collareda.business.domain.model.ServiceBranchEntity; import br.com.collareda.business.domain.model.ServiceEntity; import br.com.collareda.business.domain.repository.ServiceBranchRepository; import br.com.collareda.business.domain.repository.ServiceRepository; import br.com.collareda.business.domain.util.GenerateGUIDFile; import br.com.collareda.business.jwt.JwtTokenUtil; @Service public class ServiceService { private static final Logger log = LoggerFactory.getLogger(ServiceService.class); @Autowired private ServiceRepository serviceRepository; @Autowired private ServiceBranchRepository serviceBranchRepository; @Autowired private AmazonS3Service amazonService; @Autowired private JwtTokenUtil jwt; public ServiceEntity createService(ServiceEntity service, String token) throws NegocioException { serviceIsValid(service); service.setPartner(new PartnerEntity()); service.getPartner().setId(jwt.getPartnerID(token)); service.setCreateDate(LocalDateTime.now()); service.setIdUserCreate(jwt.getUserID(token)); ServiceEntity serviceReturn = serviceRepository.saveAndFlush(service); for (ServiceBranchEntity branchEntity : service.getBranchs()) { branchEntity.setIdService(service.getId()); serviceBranchRepository.updateIdService(branchEntity.getIdService() , branchEntity.getId()); } return serviceReturn; } private String verifyImage(MultipartFile multipartfile, Long partnerId) throws IOException { if (multipartfile == null || multipartfile.getInputStream() == null) { throw new NegocioException("A Imagem está nula"); } String nameFile = GenerateGUIDFile.generateImageId(partnerId); String[] fileFrags = multipartfile.getOriginalFilename().split("\\."); amazonService.putObjectAmazon(nameFile + "." + fileFrags[1], multipartfile.getInputStream()); return nameFile + "." + fileFrags[1]; } public void serviceIsValid(ServiceEntity service) throws NegocioException { if (service.getBranchs() == null || service.getBranchs().isEmpty()) { log.info("O Ramo deve ser informado"); throw new NegocioException("O Ramo deve ser informado"); } if (service.getPartner() == null || service.getPartner().getId() == null) { log.info("O Parceiro deve ser informado"); throw new NegocioException("O Parceiro deve ser informado"); } } public void addImg(MultipartFile file, Long serviceId) { try { String nameFile = verifyImage(file, serviceId); Optional<ServiceEntity> entity = serviceRepository.findById(serviceId); if (entity.isPresent()) { entity.get().setImgUrl(nameFile); serviceRepository.save(entity.get()); } } catch (IOException e) { e.printStackTrace(); } } }
true
f22fc376b6bade8d7e4564ba836bce5550213063
Java
ligenghuang/WineCulture
/app/src/main/java/com/zhifeng/wineculture/adapters/ProvinceAdapter.java
UTF-8
1,336
2.21875
2
[]
no_license
package com.zhifeng.wineculture.adapters; import android.graphics.Color; import android.view.View; import android.widget.TextView; import androidx.annotation.Nullable; import com.zhifeng.wineculture.R; import com.zhifeng.wineculture.modules.RegionDto; import java.util.List; public class ProvinceAdapter extends BaseRecyclerAdapter<RegionDto.DataBean> { OnClickListener onClickListener; public void setOnClickListener(OnClickListener onClickListener) { this.onClickListener = onClickListener; } public ProvinceAdapter(int layoutResId, @Nullable List<RegionDto.DataBean> data) { super(data,layoutResId); } @Override protected void onBindViewHolder(SmartViewHolder holder, RegionDto.DataBean model, int position) { holder.text(R.id.textview, model.getArea_name()); TextView textview = holder.itemView.findViewById(R.id.textview); textview.setTextColor(model.isStatus() ? Color.parseColor("#65C15C") : Color.parseColor("#444444")); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickListener.onClick(model.getCode(),position); } }); } public interface OnClickListener{ void onClick(String code, int position); } }
true
4773636ff719ed49a1f56ca4c9d8f577df88da8a
Java
SagittariusZhu/hurricane
/core/hclient/src/main/java/org/iipg/hurricane/client/response/UpdateResponse.java
UTF-8
209
2.109375
2
[ "Apache-2.0" ]
permissive
package org.iipg.hurricane.client.response; public class UpdateResponse { private int rows = 0; public void setRows(int rows) { this.rows = rows; } public int getRows() { return this.rows; } }
true
8318e4ff4dc1c6a4e78dcbf51903f0cc04c85e84
Java
cidzoo/android-group-accounting
/src/ch/hesso/iuam/groupaccounting/HeadlinesFragment.java
UTF-8
9,498
1.851563
2
[]
no_license
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.hesso.iuam.groupaccounting; import iuam.group.accounting.R; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import android.app.Activity; import android.app.ListFragment; import android.os.Bundle; import android.view.ActionMode; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AbsListView.MultiChoiceModeListener; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; public class HeadlinesFragment extends ListFragment { HeadlinesFragmentListener mListener; ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>(); // informations for one item HashMap<String, String> item; private SimpleAdapter expensesAdapter; private ListAdapter membersAdapter; protected Object mActionMode; private Boolean isGroupSetupMode; // The container Activity must implement this interface so the frag can deliver messages public interface HeadlinesFragmentListener { /** Called by HeadlinesFragment when a list item is selected */ public void onHeadlineSelected(int position); /** Called by HeadlinesFragment when a list item is selected for edit*/ public void onHeadlineEdit(int position); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); expensesAdapter = new SimpleAdapter ( getActivity(), listItem, R.layout.listview_expense, new String[] {"img", "description", "payer", "price"}, new int[] {R.id.img, R.id.description, R.id.payer, R.id.price} ); membersAdapter = new SimpleAdapter ( getActivity(), listItem, R.layout.listview_member, new String[] {"img", "name"}, new int[] {R.id.img, R.id.name} ); update(getArguments().getBoolean("isGroupSetupMode")); //This has menus setHasOptionsMenu(true); } @Override public void onActivityCreated(Bundle savedState) { super.onActivityCreated(savedState); // Animation spinin = AnimationUtils.loadAnimation(this.getActivity(), android.R.anim.slide_in_left); // LayoutAnimationController controller =new LayoutAnimationController(spinin); // getListView().setLayoutAnimation(controller); getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); getListView().setMultiChoiceModeListener(new MultiChoiceModeListener() { private LinkedList<Object> selectedItems = new LinkedList<Object>(); private LinkedList<Integer> selectedItemsId = new LinkedList<Integer>(); @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { Object o; if(isGroupSetupMode) o = Member.getMembers().get(position); else o = Expense.getExpenses().get(position); if (checked){ selectedItems.add(o); selectedItemsId.add(position); getListView().getChildAt(position).setBackgroundColor(0x6633b5e5); //getResources().getColor(android.R.color.holo_blue_light)); }else{ selectedItems.remove(o); selectedItemsId.remove(position); getListView().getChildAt(position).setBackgroundColor(0x5c5cff); } /* update interface */ mode.setTitle(String.valueOf(selectedItems.size())+" selected"); if(selectedItems.size() > 1) mode.getMenu().findItem(R.id.menu_edit).setVisible(false); else mode.getMenu().findItem(R.id.menu_edit).setVisible(true); } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { // Respond to clicks on the actions in the CAB switch (item.getItemId()) { case R.id.menu_delete: int size = selectedItems.size(); for (int i=0;i<size;i++){ if(isGroupSetupMode) Member.getMembers().remove(selectedItems.remove()); else Expense.getExpenses().remove(selectedItems.remove()); } mode.finish(); // Action picked, so close the CAB return true; case R.id.menu_edit: // Notify the parent activity of selected item mListener.onHeadlineEdit(selectedItemsId.removeFirst()); mode.finish(); // Action picked, so close the CAB return true; // Set the item as checked to be highlighted when in two-pane layout //getListView().setItemChecked(position, true); default: return false; } } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { // Inflate the menu for the CAB MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); return true; } @Override public void onDestroyActionMode(ActionMode mode) { // Here you can make any necessary updates to the activity when // the CAB is removed. By default, selected items are deselected/unchecked. for (Integer i : selectedItemsId){ getListView().getChildAt(i).setBackgroundColor(0x5c5cff); } selectedItems.clear(); update(isGroupSetupMode); getActivity().invalidateOptionsMenu(); } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // Here you can perform updates to the CAB due to // an invalidate() request return false; } }); } @Override public void onStart() { super.onStart(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception. try { mListener = (HeadlinesFragmentListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener"); } } public void addItem(Expense exp){ setListAdapter(expensesAdapter); item = new HashMap<String, String>(); item.put("description", exp.getDescription()); item.put("payer", exp.getPayerName()); item.put("img", String.valueOf(R.drawable.ic_expense)); item.put("price", String.valueOf(exp.getPrice())+".-"); listItem.add(item); } public void update(Boolean isGroupSetupMode){ this.isGroupSetupMode = isGroupSetupMode; listItem.clear(); if(isGroupSetupMode){ setListAdapter(membersAdapter); Iterator<Member> i = Member.getMembers().iterator(); while (i.hasNext()){ Member m= i.next(); item = new HashMap<String, String>(); item.put("name", m.getName()); item.put("img", String.valueOf(R.drawable.ic_member)); listItem.add(item); } }else{ setListAdapter(expensesAdapter); Iterator<Expense> i = Expense.getExpenses().iterator(); while (i.hasNext()){ Expense exp= i.next(); item = new HashMap<String, String>(); item.put("description", exp.getDescription()); item.put("payer", exp.getPayerName()); item.put("img", String.valueOf(R.drawable.ic_expense)); item.put("price", String.valueOf(exp.getPrice())+".-"); listItem.add(item); } } super.onResume(); } @Override public void onListItemClick(ListView l, View v, int position, long id) { if(!isGroupSetupMode){ mListener.onHeadlineSelected(position); } super.onListItemClick(l, v, position, id); } }
true
65ab11c714784c6a3e10166ca8a0570d7e3c2370
Java
narate/guide-droid-android-app
/src/com/narate/ar/facebook/ShareToFacebook.java
UTF-8
15,814
1.835938
2
[]
no_license
package com.narate.ar.facebook; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import com.facebook.android.AsyncFacebookRunner; import com.facebook.android.BaseRequestListener; import com.facebook.android.DialogError; import com.facebook.android.Facebook; import com.facebook.android.SessionStore; import com.facebook.android.Util; import com.facebook.android.Facebook.DialogListener; import com.facebook.android.FacebookError; import com.narate.ar.facebook.LoginWithFacebook.FacebookLoginDialogListener; import com.narate.ar.facebook.LoginWithFacebook.SampleUploadListener; import com.narate.ar.facebook.LoginWithFacebook.WallPostListener; import com.narate.ar.fork_framework.AddForm; import com.narate.ar.fork_framework.MainActivity; import com.narate.ar.fork_framework.R; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; public class ShareToFacebook extends Activity { private EditText text_post; private Button share; private TextView description; String name = "", description_text = "", url = "", image_url = "", TAG = ""; /* * For facebook check is loged in if loged in ready to share else login and * prepare to share */ private Facebook facebook; private static final String APP_ID = "396205990411489"; private static final String[] PERMISSIONS = new String[] { "publish_stream", "read_stream", "offline_access", "user_photos", "publish_actions" }; private boolean isLogin = false; private ProgressDialog mProgress; private Handler mRunOnUi = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.share_to_facebook); mProgress = new ProgressDialog(this); mProgress.setTitle("Share to facebook"); facebook = new Facebook(APP_ID); SessionStore.restore(facebook, this); if (facebook.isSessionValid()) { isLogin = true; Toast.makeText(ShareToFacebook.this, "Loged in", Toast.LENGTH_LONG) .show(); } else { isLogin = false; Toast.makeText(ShareToFacebook.this, "Not Loged in", Toast.LENGTH_LONG).show(); } text_post = (EditText) findViewById(R.id.text_post); share = (Button) findViewById(R.id.share); description = (TextView) findViewById(R.id.description); TAG = getIntent().getExtras().getString("TAG"); if (TAG.equalsIgnoreCase("AddForm")) { name = " new place name : " + getIntent().getExtras().getString("name"); description_text = getIntent().getExtras().getString("description"); url = getIntent().getExtras().getString("url"); description.setText(name + ", " + description_text); } else if (TAG.equalsIgnoreCase("ShowSelectedPlace")) { name = "name : " + getIntent().getExtras().getString("name"); description_text = getIntent().getExtras().getString("description"); url = getIntent().getExtras().getString("url"); // image_url = getIntent().getExtras().getString("image_url"); description.setText(name + ", " + description_text); /* * new DownloadImageTask((ImageView) findViewById(R.id.image)) * .execute(image_url); */ } else if (TAG.equalsIgnoreCase("AddPhoto")) { name = "name : " + getIntent().getExtras().getString("name"); description_text = getIntent().getExtras().getString("description"); url = getIntent().getExtras().getString("url"); description.setText(name + ", " + description_text); } else { } share.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (!isLogin) { login(); } else { try { postToFacebook(text_post.getText().toString()); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); } public void onFacebookClick() { if (facebook.isSessionValid()) { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle("onFacebook click"); builder.setMessage("on facebook click message") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { logout(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); isLogin = true; } }); final AlertDialog alert = builder.create(); alert.show(); } else { isLogin = false; facebook.authorize(this, PERMISSIONS, -1, new FacebookLoginDialogListener()); } } public final class FacebookLoginDialogListener implements DialogListener { public void onComplete(Bundle values) { SessionStore.save(facebook, ShareToFacebook.this); isLogin = true; getFacebookName(); } public void onFacebookError(FacebookError error) { Toast.makeText(ShareToFacebook.this, "Facebook error", Toast.LENGTH_SHORT).show(); isLogin = false; } public void onError(DialogError error) { Toast.makeText(ShareToFacebook.this, "On error", Toast.LENGTH_SHORT) .show(); isLogin = false; } public void onCancel() { isLogin = false; } } public void getFacebookName() { SharedPreferences sharedPreferences = getSharedPreferences( "facebook_login", MODE_PRIVATE); final SharedPreferences.Editor editor = sharedPreferences.edit(); mProgress.setMessage("getFacebookName"); mProgress.show(); new Thread() { @Override public void run() { String name = ""; String id = ""; int what = 1; try { String me = facebook.request("me"); JSONObject jsonObj = (JSONObject) new JSONTokener(me) .nextValue(); name = jsonObj.getString("name"); editor.putString("id", jsonObj.getString("id")); editor.putString("name", jsonObj.getString("name")); editor.putString("user_name", jsonObj.getString("username")); editor.commit(); what = 0; } catch (Exception ex) { ex.printStackTrace(); } mFbHandler.sendMessage(mFbHandler.obtainMessage(what, name)); } }.start(); } private void login() { isLogin = false; facebook.authorize(this, PERMISSIONS, -1, new FacebookLoginDialogListener()); } public void logout() { mProgress.setMessage("Logout"); mProgress.show(); new Thread() { @Override public void run() { SessionStore.clear(ShareToFacebook.this); int what = 1; try { facebook.logout(ShareToFacebook.this); what = 0; } catch (Exception ex) { ex.printStackTrace(); } mHandler.sendMessage(mHandler.obtainMessage(what)); } }.start(); } public Handler mFbHandler = new Handler() { @Override public void handleMessage(Message msg) { mProgress.dismiss(); if (msg.what == 0) { String username = (String) msg.obj; username = (username.equals("")) ? "Unknown" : username; SessionStore.saveName(username, ShareToFacebook.this); Toast.makeText(ShareToFacebook.this, "handler message " + username, Toast.LENGTH_SHORT) .show(); } else { Toast.makeText(ShareToFacebook.this, "else handler message", Toast.LENGTH_SHORT).show(); } } }; public Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { SharedPreferences sharedPreferences = getSharedPreferences( "facebook_login", MODE_PRIVATE); final SharedPreferences.Editor editor = sharedPreferences.edit(); mProgress.dismiss(); if (msg.what == 1) { Toast.makeText(ShareToFacebook.this, "wgat == 1", Toast.LENGTH_SHORT).show(); } else { // mFacebookBtn.setChecked(false); isLogin = false; Toast.makeText(ShareToFacebook.this, "else of what == 1", Toast.LENGTH_SHORT).show(); editor.putString("name", ""); editor.putString("user_name", ""); editor.commit(); } } }; public void postToFacebook(String message) throws URISyntaxException { mProgress.setMessage("Posting to facebook"); mProgress.show(); AsyncFacebookRunner mAsyncFbRunner = new AsyncFacebookRunner(facebook); Bundle params = new Bundle(); params.putString("message", message); // params.putString("source", // "https://fbcdn-sphotos-a.akamaihd.net/hphotos-ak-snc7/318285_2980677483425_1456569621_32006335_424866767_n.jpg"); params.putString("link", url); params.putString("name", name); params.putString("caption", description_text); /* * params.putString( "description", * "ทดสอบโพสมายัง facebook โดย�ารเขียน�อพบน�อนดรอยน์ ร่วม�ับ�ารใช้ facebook Adnroid SDK" * ); */ mAsyncFbRunner.request("me/feed", params, "POST", new WallPostListener()); } public void loginAlert() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Login alert"); builder.setMessage("Login to facebook") .setCancelable(false) .setPositiveButton("Log me in", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { onFacebookClick(); } }); builder.setNegativeButton("No, Thanks", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } public void enableGPS() { Intent gpsOptionsIntent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(gpsOptionsIntent); } public void takePhoto() { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); File photo = new File(Environment.getExternalStorageDirectory(), "oh_wow.jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo)); startActivityForResult(intent, 0); } public void postPhoto() { mProgress.setMessage("Post photo to facebook"); mProgress.show(); byte[] data = null; Bitmap bi = BitmapFactory.decodeFile("/sdcard/oh_wow.jpg"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bi.compress(Bitmap.CompressFormat.JPEG, 100, baos); data = baos.toByteArray(); Bundle params = new Bundle(); params.putString(Facebook.TOKEN, facebook.getAccessToken()); params.putString("method", "photos.upload"); params.putString("caption", "PHOTO_CAPTION"); params.putByteArray("picture", data); AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook); mAsyncRunner.request(null, params, "POST", new SampleUploadListener()); } public void postPhoto(Bitmap bitmap, String message) { mProgress.setMessage("Post photo to facebook"); mProgress.show(); byte[] data = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); data = baos.toByteArray(); Bundle params = new Bundle(); params.putString(Facebook.TOKEN, facebook.getAccessToken()); params.putString("method", "photos.upload"); params.putString("caption", message); params.putByteArray("picture", data); AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook); mAsyncRunner.request(null, params, "POST", new SampleUploadListener()); } void test() { Toast.makeText(this, "Test", Toast.LENGTH_LONG).show(); } public final class WallPostListener extends BaseRequestListener { public void onComplete(final String response) { mRunOnUi.post(new Runnable() { @Override public void run() { mProgress.cancel(); Toast.makeText(ShareToFacebook.this, "wall post listener", Toast.LENGTH_SHORT).show(); if (TAG.equalsIgnoreCase("AddForm")) { AlertDialog.Builder builder = new AlertDialog.Builder( ShareToFacebook.this); builder.setIcon(android.R.drawable.ic_menu_share); builder.setTitle("share menu"); builder.setMessage("share message") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int id) { Intent intent = new Intent( ShareToFacebook.this, MainActivity.class); startActivityForResult(intent, 0); } }); AlertDialog alert = builder.create(); alert.show(); } else { AlertDialog.Builder builder = new AlertDialog.Builder( ShareToFacebook.this); builder.setIcon(android.R.drawable.ic_menu_share); builder.setTitle("share title"); builder.setMessage("share message") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int id) { finish(); } }); AlertDialog alert = builder.create(); alert.show(); } } }); } } public final class SampleUploadListener extends BaseRequestListener { @Override public void onComplete(String response) { // TODO Auto-generated method stub try { // process the response here: (executed in background thread) Log.d("Facebook-Example", "Response: " + response.toString()); JSONObject json = Util.parseJson(response); final String src = json.getString("src"); // then post the processed result back to the UI thread // if we do not do this, an runtime exception will be generated // e.g. "CalledFromWrongThreadException: Only the original // thread that created a view hierarchy can touch its views." mRunOnUi.post(new Runnable() { @Override public void run() { mProgress.cancel(); Toast.makeText(ShareToFacebook.this, "sample upload listener", Toast.LENGTH_SHORT) .show(); } }); } catch (JSONException e) { Log.w("Facebook-Example", "JSON Error in response"); } catch (FacebookError e) { Log.w("Facebook-Example", "Facebook Error: " + e.getMessage()); } } } private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { ImageView bmImage; public DownloadImageTask(ImageView bmImage) { this.bmImage = bmImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return mIcon11; } protected void onPostExecute(Bitmap result) { bmImage.setImageBitmap(result); } } }
true
ae7cc32c56059f41563a75c3430571a5c878820a
Java
yazid2016/com.incorporateapps.fakegps.fre
/src/com/google/android/gms/games/multiplayer/realtime/RoomRef.java
UTF-8
3,081
1.84375
2
[]
no_license
package com.google.android.gms.games.multiplayer.realtime; import android.database.CharArrayBuffer; import android.os.Bundle; import android.os.Parcel; import com.google.android.gms.common.data.DataHolder; import com.google.android.gms.common.data.zzc; import com.google.android.gms.games.multiplayer.Participant; import com.google.android.gms.games.multiplayer.ParticipantRef; import java.util.ArrayList; public final class RoomRef extends zzc implements Room { private final int zzaDQ; RoomRef(DataHolder paramDataHolder, int paramInt1, int paramInt2) { super(paramDataHolder, paramInt1); zzaDQ = paramInt2; } public final int describeContents() { return 0; } public final boolean equals(Object paramObject) { return RoomEntity.zza(this, paramObject); } public final Room freeze() { return new RoomEntity(this); } public final Bundle getAutoMatchCriteria() { if (!getBoolean("has_automatch_criteria")) { return null; } return RoomConfig.createAutoMatchCriteria(getInteger("automatch_min_players"), getInteger("automatch_max_players"), getLong("automatch_bit_mask")); } public final int getAutoMatchWaitEstimateSeconds() { return getInteger("automatch_wait_estimate_sec"); } public final long getCreationTimestamp() { return getLong("creation_timestamp"); } public final String getCreatorId() { return getString("creator_external"); } public final String getDescription() { return getString("description"); } public final void getDescription(CharArrayBuffer paramCharArrayBuffer) { zza("description", paramCharArrayBuffer); } public final Participant getParticipant(String paramString) { return RoomEntity.zzc(this, paramString); } public final String getParticipantId(String paramString) { return RoomEntity.zzb(this, paramString); } public final ArrayList getParticipantIds() { return RoomEntity.zzc(this); } public final int getParticipantStatus(String paramString) { return RoomEntity.zza(this, paramString); } public final ArrayList getParticipants() { ArrayList localArrayList = new ArrayList(zzaDQ); int i = 0; while (i < zzaDQ) { localArrayList.add(new ParticipantRef(zzahi, zzaje + i)); i += 1; } return localArrayList; } public final String getRoomId() { return getString("external_match_id"); } public final int getStatus() { return getInteger("status"); } public final int getVariant() { return getInteger("variant"); } public final int hashCode() { return RoomEntity.zza(this); } public final String toString() { return RoomEntity.zzb(this); } public final void writeToParcel(Parcel paramParcel, int paramInt) { ((RoomEntity)freeze()).writeToParcel(paramParcel, paramInt); } } /* Location: * Qualified Name: com.google.android.gms.games.multiplayer.realtime.RoomRef * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
f394658f54a70107ff8285c901daaebd5f1a6e78
Java
Sigi5mund/Text-Based_Adventure_Game
/src/main/java/Magic/StunSleepKnockDown.java
UTF-8
1,312
3.09375
3
[]
no_license
package Magic; import Characters.Archetypes.Character; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class StunSleepKnockDown implements ITick{ Character target; Integer duration; ArrayList<Double> stunnedModifier; public StunSleepKnockDown(Character target, Integer duration) { this.target = target; this.duration = duration; this.stunnedModifier = new ArrayList<>(Arrays.asList(0.0, 0.0, 0.2, 0.4, 0.8)); } public double randomStunnedModifier() { Collections.shuffle(this.stunnedModifier); return stunnedModifier.get(0); } public Character getTarget() { return this.target; } public Integer getDuration() { return this.duration; } public void setDuration(Integer duration) { this.duration = duration; } public boolean stunWearsOffEarly(){ if (randomStunnedModifier() + target.getStunnedChance() >= 1){ return true; } else { return false; } } public void tick(){ if (duration <=0 || stunWearsOffEarly() == true) { this.duration = 0; } else { target.setStunned(true); setDuration(duration -1); } } }
true
17ec2dff94145f57ba3a2ed9ca2d57d3b7b41512
Java
Lindar84/PA165
/currency-convertor/MainAnnotations.java
UTF-8
1,037
2.90625
3
[]
no_license
package cz.muni.fi.pa165; import cz.muni.fi.pa165.currency.CurrencyConvertor; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.math.BigDecimal; import java.util.Currency; /** * Creates Spring ApplicationContext based on JSR-330 annotations. * * @author Ludmila Fialova */ public class MainAnnotations { public static void main(String ... args) { ApplicationContext applicationContext = new AnnotationConfigApplicationContext("cz.muni.fi.pa165"); CurrencyConvertor currencyConvertor = applicationContext.getBean(CurrencyConvertor.class); Currency eur = Currency.getInstance("EUR"); Currency czk = Currency.getInstance("CZK"); // get instance of CurrencyConvertor and try convert one euro to czk. Test, if the main method is working well. System.err.println(currencyConvertor.convert(eur, czk, new BigDecimal(2))); } }
true
03ccc8a83d66718d1342e4a042ce9107bbdbf701
Java
simon4360/DQ_APP
/dq_app/src/test/java/com/microgen/quality/ut/DataComparisonOperatorFactory.java
UTF-8
481
1.726563
2
[]
no_license
package com.microgen.quality.ut; import com.microgen.quality.tlf.database.IDatabaseConnector; import com.microgen.quality.tlf.database.IDataComparisonOperator; import com.microgen.quality.tlf.database.OracleDataComparisonOperator; public class DataComparisonOperatorFactory { public static IDataComparisonOperator getDataComparisonOperator ( final IDatabaseConnector pIDatabaseConnector ) { return new OracleDataComparisonOperator ( pIDatabaseConnector ); } }
true
76e19e1be6d4f605b9230677d03ada5e90f6e3f9
Java
senycorp/FPT-1516
/u5u6/src/main/java/fpt/com/problem4/Main.java
UTF-8
680
2.5625
3
[ "MIT" ]
permissive
package fpt.com.problem4; import fpt.com.problem4.threads.Acquisition; import fpt.com.problem4.threads.Cashpoint; /** * Main-Thread-Class for Problem 4 * * @author Selcuk Kekec */ public class Main { /** * Main-Method * * @param args */ public static void main(String[] args) { Thread t1 = new Thread ( new Acquisition () ) ; t1.start(); try{ t1.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Ende...") ; } public static void pooledThreads() { Thread Acquisition = fpt.com.problem4.threads.Acquisition.factory(); } }
true
c0cffeb6baec139fcdce8a5ef45781023972b3d0
Java
Timmy11223/PCVT_TPM20
/src/java/src/com/trustiphi/asn1/ComponentAddress.java
UTF-8
5,952
2.265625
2
[ "BSD-3-Clause" ]
permissive
/******** * The terms of the software license agreement included with any software you * download will control your use of the software. * * INTEL SOFTWARE LICENSE AGREEMENT * * IMPORTANT - READ BEFORE COPYING, INSTALLING OR USING. * * Do not use or load this software and any associated materials (collectively, * the "Software") until you have carefully read the following terms and * conditions. By loading or using the Software, you agree to the terms of this * Agreement. If you do not wish to so agree, do not install or use the Software. * * SEE "Intel Software License Agreement" file included with this package. * * Copyright Intel, Inc 2017 */ package com.trustiphi.asn1; import java.io.IOException; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERUTF8String; import org.bouncycastle.asn1.DLSequence; /** * ASN1 structure. * * * ComponentAddress ::= SEQUENCE { * addressType AddressType, * addressValue UTF8String (SIZE (1..STRMAX)) } * * AddressType ::= OBJECT IDENTIFIER ( * tcg-address-ethernetmac | tcg-address-wlanmac | tcg-address-bluetoothmac) * * * */ public class ComponentAddress extends Asn1Translator { private ASN1ObjectIdentifier addressType=null; private String addressValue=null; /** * Create an empty ComponentAddress */ public ComponentAddress() { } /** * Create an ComponentAddress with input values */ public ComponentAddress(ASN1ObjectIdentifier addressType, String addressValue) { this.addressType = addressType; this.addressValue = addressValue; } /** * Create a ComponentAddress from an ASN1Sequence. * The ASN1Sequence should be formatted correctly and contain the correct information. * If it is missing information it is not assigned. If an unexpected format is encountered * an IOException is thrown. * * The expected format is: * * ASN1Sequence * addressType (ASN1ObjectIdentifier) * addressValue (DERUTF8String) * * @param componentAddressEncodable * @throws IOException if unexpected ASN1 formatting is encountered */ public ComponentAddress(ASN1Encodable componentAddressEncodable) throws IOException { if(componentAddressEncodable instanceof ASN1Sequence) { ASN1Sequence componentAddressSeq = (ASN1Sequence) componentAddressEncodable; if(componentAddressSeq.size() > 0) { ASN1Encodable[] componentAddress_array = componentAddressSeq.toArray(); if(componentAddress_array.length > 0) { if(componentAddress_array[0] instanceof ASN1ObjectIdentifier) { this.addressType = (ASN1ObjectIdentifier) componentAddress_array[0]; } else { // unexpected type throw new IOException( "Unexpected ASN1 formatting while parsing ComponentAddress.addressType. Expected ASN1ObjectIdentifier; Found " + componentAddress_array[0].getClass().toString()); } } if(componentAddress_array.length > 1) { if(componentAddress_array[1] instanceof DERUTF8String) { this.addressValue = ((DERUTF8String)componentAddress_array[1]).getString(); } else { // unexpected type throw new IOException( "Unexpected ASN1 formatting while parsing ComponentAddress.addressValue. Expected DERUTF8String; Found " + componentAddress_array[1].getClass().toString()); } } } } else { // unexpected type throw new IOException( "Unexpected ASN1 formatting while parsing ComponentAddress. Expected ASN1Seqeunce; Found " + componentAddressEncodable.getClass().toString()); } } /* (non-Javadoc) * * DLSequence * adressType (ASN1ObjectIdentifier) * addressValue (DERUTF8String) * * @see org.bouncycastle.asn1.ASN1Encodable#toASN1Primitive() */ @Override public ASN1Primitive toASN1Primitive() { ASN1Encodable[] asn1EncodableArr = new ASN1Encodable[2]; asn1EncodableArr[0] = asn1EncodableArr[1] = null; if(addressType != null) { asn1EncodableArr[0] = addressType; } if(addressValue != null) { asn1EncodableArr[1] = new DERUTF8String(addressValue); } DLSequence asn1_componentAddress = new DLSequence(asn1EncodableArr); return asn1_componentAddress; } /** * @return the addressType */ public ASN1ObjectIdentifier getAddressType() { return addressType; } /** * @param addressType the addressType to set */ public void setAddressType(ASN1ObjectIdentifier addressType) { this.addressType = addressType; } /** * @return the addressValue */ public String getAddressValue() { return addressValue; } /** * @param addressValue the addressValue to set */ public void setAddressValue(String addressValue) { this.addressValue = addressValue; } }
true
7a501180ab207ab6924531d9b7de4b4fadc17110
Java
ucsd-ext-android-rja/android-1-week-3-snap
/app/src/main/java/com/ucsdextandroid1/snapapp/DataSources.java
UTF-8
3,376
2.625
3
[]
no_license
package com.ucsdextandroid1.snapapp; import com.ucsdextandroid1.snapapp.chat.Chat; import com.ucsdextandroid1.snapapp.stories.Story; import com.ucsdextandroid1.snapapp.util.ColorUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by rjaylward on 2019-04-20 */ public class DataSources { private static DataSources instance; public static DataSources getInstance() { if(instance == null) instance = new DataSources(); return instance; } public void getChatItems(Callback<List<Chat>> callback) { List<Chat> chats = new ArrayList<>(); for(int i = 0; i < 25; i++) { Chat.State state; switch(i % 3) { case 0: state = Chat.State.RECEIVED; break; case 1: state = Chat.State.OPENED; break; case 2: default: state = Chat.State.SENT; break; } chats.add(new Chat("User " + i, state, null, ColorUtil.getRandomColor())); } callback.onDataFetched(chats); } public void getStoryCards(Callback<List<Story>> callback) { callback.onDataFetched(Arrays.asList( new Story( "Space", "space is neat", "https://ucsd-ext-android-rja-1.firebaseapp.com/images/space_1.jpg", null ),new Story( "More Space", "space is cold", "https://ucsd-ext-android-rja-1.firebaseapp.com/images/space_3.jpg", null ), new Story( "Some Space", "space is fun", "https://ucsd-ext-android-rja-1.firebaseapp.com/images/space_10.jpg", null ), new Story( "Other Space", "space is awesome", "https://ucsd-ext-android-rja-1.firebaseapp.com/images/space_5.jpg", null ), new Story( "Spaceish", "space is cool", "https://ucsd-ext-android-rja-1.firebaseapp.com/images/space_6.jpg", null ), new Story( "Space Space", "space is great", "https://ucsd-ext-android-rja-1.firebaseapp.com/images/space_7.jpg", null ), new Story( "Big Space", "space is neat", "https://ucsd-ext-android-rja-1.firebaseapp.com/images/space_8.jpg", null ), new Story( "Far Space", "space is sweet", "https://ucsd-ext-android-rja-1.firebaseapp.com/images/space_9.jpg", null ) )); } public interface Callback<T> { void onDataFetched(T data); } }
true
85007bf34efd25105df03933f3e7d121989dc920
Java
sivakumm/apm-fs21
/week-12/code/CopyFile.java
UTF-8
1,003
3.109375
3
[]
no_license
package nio.timing; import java.io.*; import java.nio.*; import java.nio.channels.*; public class CopyFile { static public void main( String args[] ) throws Exception { if (args.length<2) { System.err.println( "Usage: java StreamCopyFile infile outfile" ); System.exit( 1 ); } long start = System.currentTimeMillis(); copy(args[0], args[1], 1024); System.out.println(System.currentTimeMillis()-start + "ms to copy " + args[0] + " to " + args[1]); } static public void copy(String src, String dest, int buffersize) throws Exception { FileInputStream fin = new FileInputStream( src ); FileOutputStream fout = new FileOutputStream( dest ); FileChannel fcin = fin.getChannel(); FileChannel fcout = fout.getChannel(); ByteBuffer buffer = ByteBuffer.allocate( buffersize ); int r = fcin.read( buffer ); while (r >= 0) { buffer.flip(); fcout.write( buffer ); buffer.clear(); r = fcin.read( buffer ); } } }
true
a06fad97d705fce0dcc3acfbe2f7085934a90171
Java
AndreMiras/ema-ghost
/java-client/EmaBs/src/com/standard/dev/ui/services/ListeRestauration/ListeRestauration.java
UTF-8
5,605
1.914063
2
[]
no_license
package com.standard.dev.ui.services.ListeRestauration; import java.awt.Color; import java.awt.event.ActionListener; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; import javax.swing.JPanel; import com.standard.architecture.ui.Controler; import com.standard.architecture.ui.navigation.JButtonS; import com.standard.architecture.ui.navigation.JFrameS; import com.standard.architecture.ui.navigation.JLabelS; import com.standard.architecture.ui.service.AbstractMessage; import com.standard.architecture.ui.service.MessageInterService; import com.standard.architecture.ui.service.Service; import com.standard.architecture.ui.service.ServiceInterface; import com.standard.dev.business.util.WOL; import com.standard.dev.ressources.Fichier; import com.standard.dev.ui.sequences.DeploiementSequence; import com.standard.dev.ui.services.ListeRestauration.LarEspace; public class ListeRestauration extends Service implements ServiceInterface{ DeploiementSequence unDeploiementSequence; public ListeRestauration(Controler controleur, JFrameS frame) { super(controleur, frame); // TODO Auto-generated constructor stub } @Override public boolean init() { // TODO Auto-generated method stub boolean result = true; List<DeploiementSequence> sequence = ((MessageInterService)this.getAbstractMessage()).getlistData(); // unDeploiementSequence = sequence.get(0); JPanel pnl_titre = new JPanel(); // JButtonS jbutton = new JButtonS("lar.btn_home", getControler()); // jbutton.setBorderPainted(false); // jbutton.setBackground(Color.WHITE); // pnl_titre.add(jbutton); pnl_titre.add(new JLabelS("lar.Home",getControler())); getJFrameS().setPnl_titre(pnl_titre); getJFrameS().setPnl_espace(new LarEspace(getControler())); getJFrameS().pack(); chargeList(); return result; } @Override public boolean decharger() { // TODO Auto-generated method stub boolean result = true; getJFrameS().dechargerPanel(); return result; } @Override public AbstractMessage action(String e) { // TODO Auto-generated method stub AbstractMessage result = null; System.out.println(e); this.getJFrameS().setErreur(""); if(e.equals("btn_home")) { decharger(); result = new MessageInterService("lrs","lar",1,null); } if(e.equals("btn_cancel")) { decharger(); result = new MessageInterService("lrs","lar",1,null); } if(e.equals("btn_Apply")) { if(isvalid()) { if(JOptionPane.showConfirmDialog(getJFrameS(), "Voulez-vous le deploiement ?", "Apply",JOptionPane.YES_NO_OPTION) == 0 ) { //Sequences List<DeploiementSequence> sequence = ((MessageInterService)this.getAbstractMessage()).getlistData(); DeploiementSequence unDeploiementSequence = sequence.get(0); Fichier file = new Fichier("AddrMac.emabs"); List addr = ((LarEspace)this.getJFrameS().getPnl_espace()).getList().getSelectedList(); unDeploiementSequence.setList_addr_mac(addr); unDeploiementSequence.setAddrDiffusion(file.getTexte().get(0)); unDeploiementSequence.setPartage(this.getControler().getConfiguration().getChemin_dossier_partage()); System.out.println(unDeploiementSequence); unDeploiementSequence.lanceDeploiement(); // sequence.add(unDeploiementSequence); decharger(); sequence = new ArrayList<DeploiementSequence>(); sequence.add(unDeploiementSequence); //UI decharger(); result = new MessageInterService("mon","lar",1,sequence); } } } if(e.equals("btn_plus1"))//add { result = new MessageInterService("ama","lar",1,null); } if(e.equals("btn_plus2"))//supp { if(((LarEspace)this.getJFrameS().getPnl_espace()).getList().getList().size() != 0) { if(((LarEspace)this.getJFrameS().getPnl_espace()).getList().getSelectedIndex() != -1) { if(JOptionPane.showConfirmDialog(getJFrameS(), "Voulez-vous supprimer les elements selectionnes ?", "Apply",JOptionPane.YES_NO_OPTION) == 0 ) { ((LarEspace)this.getJFrameS().getPnl_espace()).getList().removeALLSelected(); Fichier file = new Fichier("AddrMac.emabs"); List addr = ((LarEspace)this.getJFrameS().getPnl_espace()).getList().getList(); try { file.newTexte(file.getTexte().get(0), addr); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } else { this.getJFrameS().setErreur("err.ListunSelect"); } }else { this.getJFrameS().setErreur("err.ListNone"); } } return result; } @Override public boolean isvalid() { // TODO Auto-generated method stub int[] test = ((LarEspace)this.getJFrameS().getPnl_espace()).getList().getSelectedIndices(); if(((LarEspace)this.getJFrameS().getPnl_espace()).getList().getSelectedIndices().length == 0) { this.getJFrameS().setErreur("err.listAddrMacunSelected"); return false; } return true; } @Override public void mise_a_jour_fils() { // TODO Auto-generated method stub System.err.println("retour lar"); chargeList(); } public void chargeList() { ((LarEspace)this.getJFrameS().getPnl_espace()).getList().vide(); List<String> listMac = new Fichier("AddrMac.emabs").getTexte(); for(int i = 1 ; i < listMac.size() ; i++) { ((LarEspace)this.getJFrameS().getPnl_espace()).getList().addToList((listMac.get(i))); } } }
true
746c3d8158094232b57bc68a3a251fba3c02e118
Java
hendisantika/spring-boot-reactjs-example
/backend/src/main/java/com/hendisantika/reactjs/backend/PongController.java
UTF-8
550
1.835938
2
[]
no_license
package com.hendisantika.reactjs.backend; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by IntelliJ IDEA. * Project : backend * User: hendisantika * Email: hendisantika@gmail.com * Telegram : @hendisantika34 * Date: 2018-12-19 * Time: 06:46 */ @RestController public class PongController { @GetMapping("/pong") @CrossOrigin(origins = "*") public String pong() { return "pong"; } }
true
85d30dc1774d066c8f61b70d125d464cff6cba4a
Java
shykunkv/WebStore
/src/main/java/commands/ProductAction.java
UTF-8
1,599
2.609375
3
[]
no_license
package commands; import ents.Category; import ents.Product; import manager.CategoryManager; import manager.ProductManager; import org.apache.log4j.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.SQLException; import java.util.List; /** * Get product from database and put it to jsp page */ public class ProductAction extends Action { /** * Manager that provide work with database (product table) */ private ProductManager productManager = new ProductManager(); /** * Manager that provide work with database (category table) */ private CategoryManager categoryManager = new CategoryManager(); @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String res= "product.jsp"; int productId = Integer.parseInt(request.getParameter("id")); //get product id from jsp input try { // get all catogories for menu List<Category> categories = categoryManager.getAllCategories(); // get product with id Product product = productManager.getById(productId); request.setAttribute("categories", categories); request.setAttribute("product", product); } catch (SQLException e) { e.printStackTrace(); Logger.getLogger(getClass()).error(e.getMessage()); res = "/error"; } return res; } }
true
9666dbcf3e0b263c71e17b879acd85c7204059a5
Java
mindvv0rk/Fasten
/app/src/main/java/ai/testtask/fasten/weather/current/ICurrentWeatherView.java
UTF-8
297
1.882813
2
[]
no_license
package ai.testtask.fasten.weather.current; import ai.testtask.fasten.core.IView; import ai.testtask.fasten.weather.model.weather.Weather; public interface ICurrentWeatherView extends IView { void showLoading(); void showError(String message); void showWeather(Weather weather); }
true
0ee046b8959107953b5451d8906556ef23ca22f4
Java
zycupc/mavenLearning
/src/test/java/JedisTest.java
UTF-8
1,060
2.59375
3
[]
no_license
import org.junit.Test; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class JedisTest { @Test public void testString(){ Jedis jedis = new Jedis("192.168.242.128", 6379); jedis.set("uname","lisi"); String uname = jedis.get("uname"); System.out.println(uname); String na = jedis.getSet("uname", "我爱你"); System.out.println(na); System.out.println(jedis.get("uname")); } /** * jedis连接池 */ @Test public void testPool(){ //连接池配置对象 JedisPoolConfig jedisPoll = new JedisPoolConfig(); jedisPoll.setMaxTotal(50); jedisPoll.setMaxIdle(20); //连接池对象 JedisPool pool = new JedisPool(jedisPoll,"192.168.242.128", 6379); Jedis je = pool.getResource(); System.out.println(je.get("uname")); Long del = je.del("uname"); System.out.println(del); //归还连接 je.close(); } }
true
69a86c5153033401ff65f730720024310767b2df
Java
LeoCR07/orden
/app/src/main/java/com/example/orden/Comanda/Menu.java
UTF-8
9,250
2.46875
2
[]
no_license
package com.example.orden.Comanda; import com.example.orden.Configuracion.ModeloNuevoPlato; import java.util.ArrayList; public class Menu{ /************ Definiciones de las propiedades mas abstractas de la clase menu ******************/ /* Tipo */ /** Un plato de cualquier menu de cualquier restaunte tiene varias posibiliades a la hora de perdir lo y prepararlo ,por ejemplo un batido tiene la posiblidad que su preparacion sea en agua o en leche cuando esto sucede el valor que almacena la propiedad tipo sera "unica" ya que solo una opcion es valida. Cuando el plato no posea ninguna variacion signiificativa a la hora de preparlos sera "simple" como una orden de arroz y cuando un plato posea la posibilidad de elegir varias acompañamientos sera multiple ej: un gallo pinto que se pueda elegir con varias acompañamientos*/ /*Opciones */ /**es un array generico(ModeloNuevoPlato) que guarda las variaciones o acompañamientos que posean los platos que sean multiples o unicos ej: aqui es donde se almacera los valores de agua y leche del objeto fresa con sus respectivos precio **/ /*Categoria*/ /**Para mostrar los platos y guardarlos en firebase se ubican por categorias(Almuerzo,entrada,desayuno...)***/ /*Sub*/ /**Toda categoria tiene 4 subcategoria ej: la categoria Bebida posee: bebida caliente ,gaseoso,batido y Licores en el futuro me gustaria ser mas robusto esta propiedad dejando por liberdad al usuario que crea las subcategoria que quiera y solo limitarlos con las categorias pero dandole liberta en las subcategoria**/ /*Estado*/ /** Permite bloquear los platos cuando se acaben para no ofrecerlos*/ /*Seleccion*//** contador que nunca va ser mayor a cantidad y permitira disminuir la cantidad ej: en selecion vale 2 y cantidad vale 5 entoces cantidad valdra 3 */ /** RealTime **/ //private FirebaseDatabase database = FirebaseDatabase.getInstance(); //private DatabaseReference myRef = database.getReference("SodaPoas"); /** ID **/ private int id; private String ID; // private static int contador; /** menu **/ private String Nombre; private int Cantidad; private int Precio; private Categorias categoria; private String category; private Boolean EleccionMultiple; private Boolean Estado; private String Comentario; private String Preferencia; /** Beta **/ private ArrayList<ModeloNuevoPlato>Opciones; private String Tipo; private String Sub; private int Seleccion; /** multiple y unica ***/ public Menu(String nombre, int precio, String categoria, Boolean estado, ArrayList<ModeloNuevoPlato> opciones, String tipo) { Nombre = nombre; Precio = precio; this.category= categoria; Estado = estado; Opciones = opciones; Tipo = tipo; } /** Crear un plato simple cambiar **/ public Menu(String nombre, int precio, String categoria, Boolean estado, String tipo) { Nombre = nombre; Precio = precio; this.category= categoria; Estado = estado; Tipo = tipo; } /******************************** Multiple y unica ***********************************/ /**Se usa en el metodo CreacionObjMenu en ComandaActity para obtner la informacion de fireBase y enviarla a Salon en firebase**/ public Menu(Boolean estado,String nombre, int precio, String sub,String tipo,String categoria,String comentario,ArrayList<ModeloNuevoPlato>lista) { Nombre = nombre; Precio = precio; this.Comentario = comentario; this.category= categoria; this.Sub = sub; Estado = estado; Tipo = tipo; this.Opciones = lista; } /*********************************** Simple ***************************************/ /** Se utiliza para crear un nuevo plato en AgregarPlato2Activity **/ public Menu(Boolean estado,String nombre, int precio, String sub,String tipo,String categoria) { Nombre = nombre; Precio = precio; this.category= categoria; this.Sub = sub; Estado = estado; Tipo = tipo; } /**Se usa en el metodo CreacionObjMenu en ComandaActity para obtner la informacion de fireBase y posteriormente enviarla a salon **/ public Menu(Boolean estado,String nombre, int precio, String sub,String tipo,String categoria,String comentario) { Nombre = nombre; Precio = precio; this.Comentario = comentario; this.category= categoria; this.Sub = sub; Estado = estado; Tipo = tipo; } /** Se utiliza para crear un Objeto a la LinkList Pedido en ExplVAadpater **/ public Menu(String nombre,int cantidad,int precio, String comentario,String tipo,String category) { this.Cantidad = cantidad; this.category = category; Nombre = nombre; Tipo = tipo; Precio = precio; this.Comentario = comentario; } /*********************************** Unica y multiple ***************************************/ /** Se utiliza para crear un Objeto a la LinkList Pedido en ExplVAadpater **/ public Menu(String nombre, int precio, String comentario,ArrayList<ModeloNuevoPlato> opciones,int cantidad,String tipo) { Nombre = nombre; Tipo = tipo; Cantidad = cantidad; Precio = precio; Comentario = comentario; Opciones = opciones; } /*********************************** Modificar el plato en ModificarPlatoActivity ************************/ public Menu(String iddd,String nombre, int precio, String categoria,boolean estado,String tipo) { // this.iddd = iddd; Nombre = nombre; Precio = precio; category = categoria; this.Tipo = tipo; Estado = estado; } /** Constructor **/ public Menu(String nombre, int precio, Categorias tipo, boolean eleccionMultiple) { // id = contador; Nombre = nombre; Precio = precio; categoria = tipo; EleccionMultiple = eleccionMultiple; Cantidad = 0; Estado = true; Comentario = ""; Preferencia = ""; //contador++; } public Menu(String nombre, Categorias categoria){ Nombre = nombre; Precio = 0; categoria = categoria; EleccionMultiple = false; Cantidad = 0; Estado = true; Comentario = ""; Preferencia = ""; //id = contador; // contador++; } public Menu() { } /*** GETTER ***/ public String getNombre() { return Nombre; } public Categorias getCategoria() { return categoria; } public int getPrecio() { return Precio; } public int getCantidad() { return Cantidad; } public Boolean getEleccionMultiple() { return EleccionMultiple; } public Boolean getEstado() { return Estado; } public String getComentario() { return Comentario.toString(); } public String getPreferencia() { return Preferencia; } /** Metodos **/ public void Aumentar() { Cantidad+=1; } public void Disminuir() { Cantidad-=1; } /** Metodos de firebase **/ /* public void AumentarRTime(String ruta,int cant) { cant++; myRef.child(ruta).child("cantidad").setValue(cant); } public void DisminuirRTime(String ruta,int cant) { //Disminuye el plato o elimina cuando llegue a cero cant--; if (cant == 0) { myRef.child(ruta).removeValue(); } else { myRef.child(ruta).child("cantidad").setValue(cant); } } public void Agregar(){Seleccion+=1;} public int getSeleccion() { return Seleccion; } public void setSeleccion(int seleccion) { Seleccion = seleccion; } */ /*** Setters ***/ public void setCantidad(int cantidad) { Cantidad = cantidad; } public void setComentario(String comentario) { Comentario = comentario; } public void setPreferencia(String preferencia) { Preferencia = preferencia; } /*********** ID *******************/ public int getIddd() { return id; } public void setIddd(int id) { this.id = id; } public String getID() { return ID; } public void setID(String ID) { this.ID = ID; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getTipo() { return Tipo; } public void setTipo(String tipo) { Tipo = tipo; } public void setEstado(Boolean estado) { Estado = estado; } public ArrayList<ModeloNuevoPlato> getOpciones() { return Opciones; } public void setOpciones(ArrayList<ModeloNuevoPlato> opciones) { Opciones = opciones; } public String getSub() { return Sub; } public void setSub(String sub) { Sub = sub; } }
true
4de634d945d869d1f96eab0e5d4960a37455f66a
Java
PacktPublishing/Cloud-native-Application-Development-with-Java-EE
/Section-5/metrics-service/src/main/java/cloud/nativ/javaee/MetricsDemoResource.java
UTF-8
1,463
2.234375
2
[ "MIT" ]
permissive
package cloud.nativ.javaee; import org.eclipse.microprofile.metrics.Counter; import org.eclipse.microprofile.metrics.MetricUnits; import org.eclipse.microprofile.metrics.annotation.Gauge; import org.eclipse.microprofile.metrics.annotation.Metric; import org.eclipse.microprofile.metrics.annotation.Timed; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.json.Json; import javax.json.JsonObject; import javax.ws.rs.GET; import javax.ws.rs.Path; import java.util.concurrent.atomic.AtomicInteger; @ApplicationScoped @Path("metrics-demo") public class MetricsDemoResource { @Inject @Metric(name = "globalMetricsDemoCounter", absolute = true) private Counter counter; private final AtomicInteger concurrentInvocations = new AtomicInteger(0); @GET @Timed(name = "metricsDemo", unit = MetricUnits.MILLISECONDS) public JsonObject metricsDemo() { counter.inc(); try { return Json.createObjectBuilder() .add("counter", counter.getCount()) .add("currentConcurrentInvocations", concurrentInvocations.incrementAndGet()) .build(); } finally { concurrentInvocations.decrementAndGet(); } } @Gauge(name = "currentConcurrentMetricsDemoInvocations", unit = MetricUnits.NONE) public Integer currentConcurrentInvocations() { return concurrentInvocations.get(); } }
true
d7ba14bd710b477ab71a3b682a525956a815b566
Java
PizzaStack/project-zero-johnmasiello
/src/main/java/com/revature/project_0/entity/TransactionOutcome.java
UTF-8
281
1.710938
2
[]
no_license
package com.revature.project_0.entity; public final class TransactionOutcome { public static final int SUCCESS = 0; public static final int ACCOUNT_FROZEN = 1; public static final int RECIPIENT_ACCOUNT_FROZEN = 2; public static final int INSUFFICIENT_FUNDS = 3; }
true
99ebd769cd7b9a871a1a29442786e46be252d794
Java
faizsiddiqui/ProGram
/app/src/main/java/app/program/TutorialActivity.java
UTF-8
6,080
2.046875
2
[]
no_license
package app.program; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; /** * Not for public use * Created by FAIZ on 07-04-2015. */ public class TutorialActivity extends Activity { private ViewPager mViewPager; private TutorialView mAdapter; Button mNext; private ArrayList<Integer> mImages, mTitles, mDescription; LinearLayout mDotsLayout; private int mDotsCount; private TextView[] mDots; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tutorial); initViews(); mNext = (Button) findViewById(R.id.tutorial_next); mNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int next = mViewPager.getCurrentItem() + 1; if (next == 6) { String caller = getIntent().getStringExtra("caller"); if (caller.equals("SplashActivity")) { Intent home = new Intent(TutorialActivity.this, MainActivity.class); startActivity(home); } finish(); } else { mViewPager.setCurrentItem(next, true); } } }); setViewPagerItemsWithAdapter(); setUiPageViewController(); } private void setUiPageViewController() { mDotsLayout = (LinearLayout) findViewById(R.id.tutorial_pager_count_dots); mDotsCount = mAdapter.getCount(); mDots = new TextView[mDotsCount]; for (int i = 0; i < mDotsCount; i++) { mDots[i] = new TextView(this); mDots[i].setText(Html.fromHtml("&#8226;")); mDots[i].setTextSize(30); mDots[i].setTextColor(getResources().getColor(R.color.colorText)); mDotsLayout.addView(mDots[i]); } mDots[0].setTextColor(getResources().getColor(R.color.colorPrimary)); } private void setViewPagerItemsWithAdapter() { mAdapter = new TutorialView(); mViewPager.setAdapter(mAdapter); mViewPager.setCurrentItem(0); mViewPager.setOnPageChangeListener(tutorialPagerChangeListener); } ViewPager.OnPageChangeListener tutorialPagerChangeListener = new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { for (int i = 0; i < mDotsCount; i++) { mDots[i].setTextColor(getResources().getColor(R.color.colorText)); mDots[i].setTextSize(30); } mDots[position].setTextColor(getResources().getColor(R.color.colorPrimary)); } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } }; private void initViews() { mViewPager = (ViewPager) findViewById(R.id.tutorial_pager); mImages = new ArrayList<Integer>(); mTitles = new ArrayList<Integer>(); mDescription = new ArrayList<Integer>(); mImages.add(R.mipmap.ic_forum_learn); mImages.add(R.mipmap.ic_forum_learn); mImages.add(R.mipmap.ic_home_calendar); mImages.add(R.mipmap.ic_forum_q_a); mImages.add(R.mipmap.ic_forum_scheme); mImages.add(R.mipmap.ic_forum_job); mTitles.add(R.string.tutorial_title_learn); mTitles.add(R.string.tutorial_title_SelectCrop); mTitles.add(R.string.tutorial_title_Calender); mTitles.add(R.string.tutorial_title_QuestionAndAnswers); mTitles.add(R.string.tutorial_title_SchemesAndAwards); mTitles.add(R.string.tutorial_title_employment); mDescription.add(R.string.tutorial_description_learn); mDescription.add(R.string.tutorial_description_SelectCrop); mDescription.add(R.string.tutorial_description_Calender); mDescription.add(R.string.tutorial_description_QuestionAndAnswers); mDescription.add(R.string.tutorial_description_SchemesAndAwards); mDescription.add(R.string.tutorial_description_employment); } public class TutorialView extends PagerAdapter { private LayoutInflater inflater; TextView titles, description; ImageView images; @Override public Object instantiateItem(ViewGroup container, int position) { inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.activity_tutorial_view, container, false); images = (ImageView) view.findViewById(R.id.tutorial_image); titles = (TextView) view.findViewById(R.id.tutorial_title); description = (TextView) view.findViewById(R.id.tutorial_description); images.setBackgroundResource(mImages.get(position)); titles.setText(mTitles.get(position)); description.setText(mDescription.get(position)); ((ViewPager) container).addView(view); return view; } @Override public int getCount() { return mTitles.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == ((View) object); } @Override public void destroyItem(ViewGroup container, int position, Object object) { View view = (View) object; ((ViewPager) container).removeView(view); } } }
true
794b4a17a7905de6c32d2d6c7f2a2b8c38589c65
Java
TAMULib/CAP
/src/main/java/edu/tamu/cap/model/response/FixityReport.java
UTF-8
1,822
2.3125
2
[ "MIT" ]
permissive
package edu.tamu.cap.model.response; import java.io.Serializable; import java.util.List; public class FixityReport implements Serializable { private static final long serialVersionUID = 2796084431207624730L; private static final String PRIMIS_HAS_EVENT_OUTCOME_PREDICATE = "http://www.loc.gov/premis/rdf/v1#hasEventOutcome"; private static final String PRIMIS_HAS_MESSAGE_DIGEST_PREDICATE = "http://www.loc.gov/premis/rdf/v1#hasMessageDigest"; private static final String PRIMIS_HAS_SIZE_PREDICATE = "http://www.loc.gov/premis/rdf/v1#hasSize"; private String status; private String messageDigest; private String size; public FixityReport() { } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMessageDigest() { return messageDigest; } public void setMessageDigest(String messageDigest) { this.messageDigest = messageDigest; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public static FixityReport of(List<Triple> properties) { FixityReport fixityReport = new FixityReport(); properties.forEach(triple -> { switch (triple.getPredicate()) { case PRIMIS_HAS_EVENT_OUTCOME_PREDICATE: fixityReport.setStatus(triple.getObject()); break; case PRIMIS_HAS_MESSAGE_DIGEST_PREDICATE: fixityReport.setMessageDigest(triple.getObject()); break; case PRIMIS_HAS_SIZE_PREDICATE: fixityReport.setSize(triple.getObject()); break; } }); return fixityReport; } }
true
c25bb9a2f86cda21efeeb4d75b5c6cb10d75b42f
Java
fchristysen/androidmvp-bind
/app/src/main/java/org/greenfroyo/androidmvp_bind/app/intentparam/front/IntentParamFrontActivity.java
UTF-8
1,521
2.140625
2
[]
no_license
package org.greenfroyo.androidmvp_bind.app.intentparam.front; import android.databinding.ViewDataBinding; import android.os.Bundle; import android.view.View; import org.greenfroyo.androidmvp_bind.R; import org.greenfroyo.androidmvp_bind.app._core.toolbar.BaseToolbarActivity; import org.greenfroyo.androidmvp_bind.databinding.IntentParamFrontActivityBinding; /** * Created by fchristysen on 6/7/16. * This page demonstrates : * - Use of dart and henson library for navigation and send parameter */ public class IntentParamFrontActivity extends BaseToolbarActivity<IntentParamFrontPresenter, IntentParamFrontViewModel> implements View.OnClickListener { private IntentParamFrontActivityBinding mBinding; @Override public IntentParamFrontPresenter createPresenter() { return new IntentParamFrontPresenter(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected ViewDataBinding onInitView(IntentParamFrontViewModel viewModel) { mBinding = setBindView(R.layout.intent_param_front_activity); mBinding.setViewModel(getPresenter().getViewModel()); mBinding.setOnClickListener(this); return mBinding; } @Override public void onClick(View v) { if(v.equals(mBinding.btnAdd)){ getPresenter().onIncrementValue(); }else if(v.equals(mBinding.btnNext)){ getPresenter().openIntentParamBack(this); } } }
true
5abf5ec713962842019e7d0654c088b8ab17db9f
Java
mantee/VCS
/src/models/entities/Repository.java
UTF-8
1,444
2.5625
3
[ "MIT" ]
permissive
package models.entities; import models.processing.CommitData; import java.io.FileNotFoundException; import java.util.ArrayList; public class Repository { private int id; private String title; private ArrayList<Commit> commits; private User owner; private String dateCreated; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public ArrayList<Commit> getCommits() throws FileNotFoundException { CommitData cd = new CommitData(); setCommits(cd.getAllCommits("repository" + this.id)); return commits; } public void setCommits(ArrayList<Commit> commits) { this.commits = commits; } public User getOwner() { return owner; } public void setOwner(User owner) { this.owner = owner; } public String getDateCreated() { return dateCreated; } public void setDateCreated(String dateCreated) { this.dateCreated = dateCreated; } @Override public String toString() { return "Repository{" + "id=" + id + ", title='" + title + '\'' + ", commits=" + commits + ", owner=" + owner + ", dateCreated='" + dateCreated + '\'' + '}'; } }
true
0cfc2e1be577ad4360dfd27329a745997351dab9
Java
canadanicolas/Programacion-II
/Final 21.12.18/src/Libro.java
UTF-8
551
2.9375
3
[]
no_license
import java.util.ArrayList; public class Libro { protected double precio; protected String nombre; protected String autor; protected String resumen; protected ArrayList<String> generos; public Libro(double precio, String nombre, String autor, String resumen){ this.precio = precio; this.nombre = nombre; this.autor = autor; this.resumen = resumen; this.generos = new ArrayList<String>(); } public boolean esGenero(String genero) { for(String g: generos){ if(g.equals(genero)){ return true; } } return false; } }
true
8aba9f72eb7868673a523a0c18e75e3fd5563c51
Java
yangyh11/activeMQdemo
/src/main/java/com/yamgyh/activemq/TestConsumer.java
UTF-8
526
1.914063
2
[]
no_license
package com.yamgyh.activemq; import java.sql.Connection; /** * @author yangyh6 * @version v1.0.0 * @Description: * @date 2018/6/28 * @time 15:03 */ public class TestConsumer { public static void main(String[] args) { ConsumerThread consumerThread=new ConsumerThread("test2"); new Thread(consumerThread).start(); new Thread(consumerThread).start(); new Thread(consumerThread).start(); new Thread(consumerThread).start(); new Thread(consumerThread).start(); } }
true
42ba96490750b1e600f05f35f1f4fec1b43580c6
Java
Lexkane/Java
/NewestFile/src/menu/RecursiveFolders.java
UTF-8
769
3.203125
3
[]
no_license
package menu; import java.io.File; import java.io.FileFilter; public class RecursiveFolders { void listFolder(File dir) { File[] subDirs; subDirs = dir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }); System.out.println("\nDirectory of "+ dir.getAbsolutePath()); listFile(dir); for (File folder: subDirs){ listFolder(folder); } } private void listFile(File dir){ File[] files= dir.listFiles(); for (File file:files){ System.out.println(file.getName()); } } public static void main(String[] args) { new RecursiveFolders().listFolder(new File("d:\\!Documentary")); } }
true
e22a533403987b7c892252e82bdf2e320ad94feb
Java
compbio-UofT/medsavant
/MedSavantClient/src/main/java/org/ut/biolab/medsavant/client/view/login/ServerDetailedView.java
UTF-8
18,793
1.742188
2
[]
no_license
/** * Copyright (c) 2014 Marc Fiume <mfiume@cs.toronto.edu> * Unauthorized use of this file is strictly prohibited. * * All rights reserved. No warranty, explicit or implicit, provided. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package org.ut.biolab.medsavant.client.view.login; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JToggleButton; import javax.swing.SwingUtilities; import net.miginfocom.swing.MigLayout; import org.ut.biolab.medsavant.MedSavantClient; import org.ut.biolab.medsavant.client.controller.ServerController; import org.ut.biolab.medsavant.client.util.ClientMiscUtils; import org.ut.biolab.medsavant.client.view.component.KeyValuePairPanel; import org.ut.biolab.medsavant.client.view.component.NiceMenu; import org.ut.biolab.medsavant.client.view.component.WaitPanel; import org.ut.biolab.medsavant.client.view.dialog.ProgressDialog; import org.ut.biolab.medsavant.client.view.list.DetailedView; import org.ut.biolab.medsavant.client.view.util.DialogUtils; import org.ut.biolab.medsavant.client.view.util.ViewUtil; import org.ut.biolab.medsavant.component.field.editable.EditableField; import org.ut.biolab.medsavant.component.field.editable.EditableFieldValidator; import org.ut.biolab.medsavant.component.field.editable.EnumEditableField; import org.ut.biolab.medsavant.component.field.editable.FieldCommittedListener; import org.ut.biolab.medsavant.component.field.editable.FieldEditedListener; import org.ut.biolab.medsavant.component.field.editable.PasswordEditableField; import org.ut.biolab.medsavant.component.field.editable.StringEditableField; import org.ut.biolab.medsavant.component.field.validator.HostnameValidator; import org.ut.biolab.medsavant.component.field.validator.NonEmptyStringValidator; import org.ut.biolab.medsavant.component.field.validator.PositiveNumberValidator; /** * * @author mfiume */ public class ServerDetailedView extends DetailedView implements FieldCommittedListener, FieldEditedListener { private StringEditableField nameField; private StringEditableField hostField; private StringEditableField portField; private StringEditableField databaseField; private StringEditableField usernameField; private PasswordEditableField passwordField; private EnumEditableField rememberPasswordField; private final SplashServerManagementComponent serverManagementComponent; private MedSavantServerInfo server; private JButton chooseButton; private KeyValuePairPanel kvp; private final SplashFrame splash; public ServerDetailedView(SplashFrame splash, SplashServerManagementComponent serverManagementComponent) { super("Servers"); this.serverManagementComponent = serverManagementComponent; this.splash = splash; setSelectedItem(null); } @Override public void setSelectedItem(Object[] selectedRow) { if (selectedRow == null || selectedRow.length == 0) { showBlockPanel(); return; } MedSavantServerInfo server = (MedSavantServerInfo) selectedRow[1]; showServerInfo(server); } @Override public void setMultipleSelections(List<Object[]> selectedRows) { } @Override public JPopupMenu createPopup() { return new JPopupMenu(); } private KeyValuePairPanel getNiceFormForServer(final MedSavantServerInfo server) { final String DBNAME_KEY = "Database name"; final KeyValuePairPanel kvp = new KeyValuePairPanel(1, true); final NonEmptyStringValidator nonEmptyStringValidator = new NonEmptyStringValidator("server name"); EditableFieldValidator nameValidator = new EditableFieldValidator<String>() { @Override public boolean validate(String value) { if (nonEmptyStringValidator.validate(value)) { // check if there's already a different server with this name return !isDifferentServerWithName(value, server); } return false; } @Override public String getDescriptionOfValidValue() { return "Invalid name (must not be blank or already exist)"; } }; nameField = new StringEditableField(); nameField.setName("Server name"); nameField.setAutonomousEditingEnabled(false); nameField.setEditing(true); nameField.setValidator(nameValidator); nameField.setValue(server.getNickname()); hostField = new StringEditableField(); hostField.setAutonomousEditingEnabled(false); hostField.setEditing(true); hostField.setValidator(new HostnameValidator()); hostField.setValue(server.getHost()); portField = new StringEditableField(); portField.setAutonomousEditingEnabled(false); portField.setEditing(true); portField.setValidator(new PositiveNumberValidator("port")); portField.setValue(server.getPort() + ""); databaseField = new StringEditableField(); databaseField.setAutonomousEditingEnabled(false); databaseField.setEditing(true); databaseField.setValidator(new NonEmptyStringValidator("database name")); databaseField.setValue(server.getDatabase()); usernameField = new StringEditableField(); usernameField.setAutonomousEditingEnabled(false); usernameField.setEditing(true); usernameField.setValidator(new NonEmptyStringValidator("username")); usernameField.setValue(server.getUsername()); passwordField = new PasswordEditableField(); passwordField.setAutonomousEditingEnabled(false); passwordField.setEditing(true); passwordField.setValidator(new NonEmptyStringValidator("password")); passwordField.setValue(server.getPassword()); rememberPasswordField = new EnumEditableField(new String[]{"No", "Yes"}); rememberPasswordField.setAutonomousEditingEnabled(false); rememberPasswordField.setEditing(true); rememberPasswordField.setValue(server.isRememberPassword() ? "Yes" : "No"); addCommitListenersToFields(nameField, hostField, portField, databaseField, usernameField, passwordField, rememberPasswordField); addChangeListenersToFields(nameField, hostField, portField, databaseField, usernameField, passwordField, rememberPasswordField); kvp.addKeyWithValue("Server name", nameField); kvp.addKeyWithValue("Host name", hostField); kvp.addKeyWithValue("Port", portField); kvp.addKeyWithValue("Username", usernameField); kvp.addKeyWithValue("Password", passwordField); kvp.addKeyWithValue("Remember password", rememberPasswordField); kvp.addKeyWithValue(DBNAME_KEY, databaseField); final JToggleButton adminButton = ViewUtil.getSoftToggleButton("Admin"); final JLabel adminLabel = ViewUtil.getSettingsHelpLabel("Requires administrative priviledges"); final JButton createDBButton = ViewUtil.getTexturedButton("Create Database"); final JButton deleteDBButton = ViewUtil.getTexturedButton("Delete Database"); createDBButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Creating db"); createDatabaseSpecifiedByForm(); } }); deleteDBButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Deleting db"); deleteDatabaseSpecifiedByForm(); } }); JPanel adminPanel = ViewUtil.getClearPanel(); adminPanel.setLayout(new MigLayout("insets 0")); //adminPanel.add(admin, "wrap"); adminPanel.add(adminLabel, "wrap"); adminPanel.add(createDBButton, "split"); adminPanel.add(deleteDBButton, "wrap"); adminButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { kvp.toggleDetailVisibility(DBNAME_KEY, adminButton.isSelected()); } }); kvp.setAdditionalColumn(DBNAME_KEY, 0, adminButton); kvp.setDetailComponent(DBNAME_KEY, adminPanel); kvp.toggleDetailVisibility(DBNAME_KEY, adminButton.isSelected()); return kvp; } private boolean isDifferentServerWithName(String name, MedSavantServerInfo server) { MedSavantServerInfo existingServer = ServerController.getInstance().getServerNamed(name); // true if the server with this name exists boolean result = existingServer != null && !existingServer.equals(server); return result; } private void showServerInfo(final MedSavantServerInfo server) { if (this.server != null && server.getUniqueID().equals(this.server.getUniqueID())) { return; } System.out.println("Setting server to " + server.getNickname()); this.server = server; this.removeAll(); this.revalidate(); this.setLayout(new BorderLayout()); this.setBackground(Color.white); JPanel container = ViewUtil.getClearPanel(); NiceMenu bottomMenu = new NiceMenu(NiceMenu.MenuLocation.BOTTOM); bottomMenu.setOpaque(false); bottomMenu.setBorder(BorderFactory.createEmptyBorder()); container.setLayout(new MigLayout("fillx, insets 20, hidemode 3")); if (server == null) { return; } kvp = getNiceFormForServer(server); container.add(kvp, "wrap, aligny top, growx 1.0, wmax 100%"); chooseButton = ViewUtil.getTexturedButton("Connect"); chooseButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (validateServerSettings()) { ServerController.getInstance().setCurrentServer(server); splash.switchToLogin(); } } }); bottomMenu.addRightComponent(chooseButton); this.add(container, BorderLayout.CENTER); this.add(bottomMenu, BorderLayout.SOUTH); this.updateUI(); } private boolean validateServerSettings() { EditableField[] fields = new EditableField[]{ nameField, hostField, portField, usernameField, passwordField, rememberPasswordField, databaseField }; for (EditableField f : fields) { if (!f.validateCurrentValue()) { return false; } } return true; } private void createDatabaseSpecifiedByForm() { String host = hostField.getValue(); int port = Integer.parseInt(portField.getValue()); String database = databaseField.getValue(); String username = usernameField.getValue(); String password = passwordField.getValue(); createDatabase(host, port, database, username, password); } private void deleteDatabaseSpecifiedByForm() { String host = hostField.getValue(); int port = Integer.parseInt(portField.getValue()); String database = databaseField.getValue(); String username = usernameField.getValue(); String password = passwordField.getValue(); removeDatabase(host, port, database, username, password); } private void removeDatabase(final String address, final int port, final String database, final String username, final String password) { if (DialogUtils.askYesNo("Confirm", "<html>Are you sure you want to remove <i>%s</i>?<br>This operation cannot be undone.", database) == DialogUtils.YES) { new ProgressDialog("Removing Database", String.format("<html>Removing database <i>%s</i>. Please wait.</html>", database)) { @Override public void run() { try { MedSavantClient.initializeRegistry(address, port + ""); MedSavantClient.SetupManager.removeDatabase(address, port, database, username, password.toCharArray()); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { setVisible(false); } }); ServerController.getInstance().removeServer(server); DialogUtils.displayMessage("Database Removed", String.format("<html>Database <i>%s</i> successfully removed.</html>", database)); } catch (Exception ex) { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { setVisible(false); } }); } catch (Exception ex1) { Logger.getLogger(SplashFrame.class.getName()).log(Level.SEVERE, null, ex1); } ClientMiscUtils.reportError("Database could not be removed: %s", ex); } } }.setVisible(true); } } private void createDatabase(final String address, final int port, final String database, final String username, final String password) { if (DialogUtils.askYesNo( "Create Database", String.format( "<html>Are you sure you want to create the database <i>%s</i>?</html>", database)) == DialogUtils.YES) { new ProgressDialog("Creating Database", String.format("<html>Creating database <i>%s</i>. Please wait.</html>", database)) { @Override public void run() { try { MedSavantClient.initializeRegistry(address, port + ""); MedSavantClient.SetupManager.createDatabase(address, port, database, username, password.toCharArray()); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { setVisible(false); } }); doSave(); DialogUtils.displayMessage("Database Created", String.format("<html>Database <i>%s</i> successfully created.</html>", database)); } catch (Throwable ex) { ex.printStackTrace(); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { setVisible(false); } }); } catch (Exception ex1) { } ClientMiscUtils.reportError("Database could not be created: %s\nPlease check the settings and try again.", ex); } } }.setVisible(true); } } private void showBlockPanel() { this.removeAll(); this.setLayout(new MigLayout("center, fillx, filly, wrap 1")); WaitPanel blockCard = new WaitPanel("No server selected"); blockCard.setProgressBarVisible(false); this.add(blockCard, "width 100%, height 100%"); this.updateUI(); } private void doSave() { doSave(true); } private void doSave(boolean requiresListRefresh) { String name = nameField.getValue(); String host = hostField.getValue(); Integer portInt = Integer.parseInt(portField.getValue()); int port = portInt == null ? 0 : portInt; String database = databaseField.getValue(); String username = usernameField.getValue(); String password = passwordField.getValue(); boolean rememberPass = rememberPasswordField.getValue().equals("Yes"); server.setHost(host); server.setPort(port); server.setDatabase(database); server.setNickname(name); server.setUsername(username); server.setPassword(password); server.setRememberPassword(rememberPass); // check if there's already a different server with this name if (isDifferentServerWithName(server.getNickname(), server)) { System.out.println("Not saving with duplicate server name"); return; } //System.out.println("Edited server, new name is " + server.getNickname()); ServerController.getInstance().saveServers(requiresListRefresh); serverManagementComponent.getServerList().selectItemWithKey(name); } @Override public void handleCommitEvent(EditableField f) { doSave(); } @Override public void handleEditEvent(EditableField f) { if (f.validateCurrentValue()) { doSave(false); if (f.getName() != null && f.getName().equals("Server name")) { parent.setSelectedItemText(f.getValue().toString()); } } } private void addCommitListenersToFields(EditableField... fields) { for (EditableField f : fields) { f.addFieldComittedListener(this); } } private void addChangeListenersToFields(EditableField... fields) { for (EditableField f : fields) { f.addFieldEditedListener(this); } } }
true
1de3f9f2885032c0d61c688c84f0ac2ad6ed6ad9
Java
wangyc0104/ego
/ego-manage/src/main/java/com/ego/manage/controller/TbContentCategoryController.java
UTF-8
1,795
1.953125
2
[]
no_license
package com.ego.manage.controller; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.ego.commons.pojo.EasyUiTree; import com.ego.commons.pojo.EgoResult; import com.ego.manage.service.TbContentCategoryService; import com.ego.pojo.TbContentCategory; /** * 页面内容分类管理控制器 * @author 王以诚 */ @Controller public class TbContentCategoryController { @Resource private TbContentCategoryService tbContentCategoryServiceImpl; /** * 将页面内容分类管理列举出来 * @param id * @return */ @RequestMapping("content/category/list") @ResponseBody public List<EasyUiTree> showCategory(@RequestParam(defaultValue="0") long id) { return tbContentCategoryServiceImpl.showCategory(id); } /** * 新增页面内容分类(右键新增提交后触发的控制器) * @param cat * @return */ @RequestMapping("content/category/create") @ResponseBody public EgoResult create(TbContentCategory cat) { return tbContentCategoryServiceImpl.create(cat); } /** * 重命名页面内容分类 * @param cat * @return */ @RequestMapping("content/category/update") @ResponseBody public EgoResult update(TbContentCategory cat) { return tbContentCategoryServiceImpl.update(cat); } /** * 删除页面内容分类 * @param cat * @return */ @RequestMapping("content/category/delete") @ResponseBody public EgoResult delete(TbContentCategory cat) { return tbContentCategoryServiceImpl.delete(cat); } }
true
95ba304b26f3d196907a49c42f8d84a7a481d149
Java
aortich/asili
/Asili/src/Objetos/Fondo.java
UTF-8
1,567
3.21875
3
[]
no_license
package Objetos; import Main.Asili; import java.io.IOException; import javax.microedition.lcdui.Graphics; import javax.microedition.lcdui.Image; /** * EL fondo, con scroll automático del juego. * @author Alberto Ortiz */ public class Fondo { private Image imagen; private int x, y; private int scrollSpeed; /** * El constructos, que crea la imágen. * @param archivo La ruta del archivo que se usará como fondo * @param speed La velocidad de scroll del fondo * @throws IOException Avisa si existe un problema con la ruta o el archivo */ public Fondo(String archivo, int speed) throws IOException { imagen = Image.createImage(archivo); this.x = 0; this.y = (-imagen.getHeight() + Asili.ALTO); this.scrollSpeed = speed; } /** * Dibuja el fondo * @param g - Para dibujar */ public void dibujar(Graphics g) { g.drawImage(imagen, x, y, Graphics.LEFT|Graphics.TOP); if( y > (0)) { g.drawImage(imagen, x, y = imagen.getHeight(), Graphics.LEFT|Graphics.TOP); } } /** * Mueve el fondo, a la velocidad que marca scrollSpeed */ public void actualizar() { this.y = this.y + scrollSpeed; if ( this.y>=(0)) { // Si ya se salió completamente la imagen //System.out.println(y); y=(-imagen.getHeight() + Asili.ALTO); //System.out.println(y); } } public void resetearFondo() { this.y = (-imagen.getHeight() + Asili.ALTO); } }
true
e2b1a9ebc4ac0e86e87c9847bfbed1d188e311e7
Java
alaner79/YouTrackRestApi
/src/youtrack/commands/GetProjects.java
UTF-8
559
2.0625
2
[]
no_license
package youtrack.commands; import com.sun.istack.internal.NotNull; import org.apache.commons.httpclient.methods.GetMethod; import youtrack.Project; import youtrack.YouTrack; import youtrack.commands.base.ListCommand; /** * Created by egor.malyshev on 01.04.2014. */ public class GetProjects extends ListCommand<YouTrack, Project> { public GetProjects(@NotNull YouTrack owner) { super(owner); } @Override public void createCommandMethod() { method = new GetMethod(owner.getYouTrack().getHostAddress() + "project/all"); } }
true
b3a8a034d076f734b4b9d972059694a933502a2c
Java
TheShermanTanker/NMS-1.16.3
/com/google/common/base/Objects.java
UTF-8
1,420
1.875
2
[]
no_license
/* */ package com.google.common.base; /* */ /* */ import com.google.common.annotations.GwtCompatible; /* */ import java.util.Arrays; /* */ import javax.annotation.Nullable; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ @GwtCompatible /* */ public final class Objects /* */ extends ExtraObjectsMethodsForWeb /* */ { /* */ public static boolean equal(@Nullable Object a, @Nullable Object b) { /* 52 */ return (a == b || (a != null && a.equals(b))); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public static int hashCode(@Nullable Object... objects) { /* 76 */ return Arrays.hashCode(objects); /* */ } /* */ } /* Location: C:\Users\Josep\Downloads\Decompile Minecraft\tuinity-1.16.3.jar!\com\google\common\base\Objects.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
true
ea5681a3d4a1a4c259e6f5b9f52791e2d7af9762
Java
gerdkolano/Uhr
/app/src/main/java/net/za/dyndns/gerd/uhr/MainActivity.java
UTF-8
9,274
1.890625
2
[]
no_license
/* * sudo studio.sh # sonst hat der Installer nicht die erforderlichen Schreibrechte * >> File >> New >> New Project >> Uhr >> API 17 >> Add no Activity * root@zoe:~$ chown -R hanno: /data6/AndroidStudioProjects/Uhr/ * hanno@zoe:~$ cp -auv /zoe-home/zoe-hanno/android/Uhr0/uhr/src/main/java/net/za/dyndns/gerd/uhr0/uhr/ * package net.za.dyndns.gerd.uhr0.uhr * --> package net.za.dyndns.gerd.uhr; * hanno@zoe:~$ cp -auv /zoe-home/zoe-hanno/android/Uhr0/uhr/src/main/res/* /data6/AndroidStudioProjects/Uhr/app/src/main/res/ * hanno@zoe:~$ cp -av /zoe-home/zoe-hanno/android/Uhr0/uhr/src/main/res/values/strings.xml /data6/AndroidStudioProjects/Uhr/app/src/main/res/values/ * for i in hdpi mdpi xhdpi xxhdpi ; do cp -av /zoe-home/zoe-hanno/android/Uhr0/uhr/src/main/res/drawable-$i/* /data6/AndroidStudioProjects/Uhr/app/src/main/res/mipmap-$i/ ; done * public class MainActivity extends Activity { * --> public class MainActivity extends AppCompatActivity { * getActionBar geht in Version 1.1 unter android-22 nicht * --> getSupportActionBar().setHomeButtonEnabled(true); * * */ package net.za.dyndns.gerd.uhr; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity { private int[] R_array_minuten; private int[] R_array_viertel; private int[] R_array_zahlen; private Empfänger receiver; private Ansager ansager; private int debug = 1; private boolean jedeMinute = false; private boolean jedeViertelstunde = true; private boolean kuckuckUndGong = true; private boolean einMal = false; private Button tast1; private Button tast2; private Button tast4; private Button tast3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // enables the activity icon as a 'home' button. // required if "android:targetSdkVersion" > 14 // getActionBar geht in Version 1.1 unter android-22 nicht getSupportActionBar().setHomeButtonEnabled(true); String versionName = ""; int versionCode = 0; try { PackageInfo packageInfo; packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0); versionName = packageInfo.versionName; versionCode = packageInfo.versionCode; // build.gradle hängt diesen "versionCode" an "versionName" an. } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } String anzeige; /* Date nun = new Date(); SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss"); String anzeige = "Zeitansage " + versionName //+ versionCode + " von " + ft.format(nun); */ anzeige = "Uhr mit Ansage " + versionName //+ versionCode + " von " + new Version().buildZeit; getSupportActionBar().setTitle(anzeige); Log.e("U000", String.format("-\n%s", anzeige)); setContentView(R.layout.activity_main); // für findViewById tast1 = (Button) findViewById(R.id.jedeMinute); tast2 = (Button) findViewById(R.id.jedeViertelstunde); tast3 = (Button) findViewById(R.id.mitKuckuck); tast4 = (Button) findViewById(R.id.nurEinMal); TextView textViertel = (TextView) findViewById(R.id.textViertel); TextView zeitKomplettView = (TextView) findViewById(R.id.zeitKomplett); TextView inWortenView = (TextView) findViewById(R.id.inWorten); //WebView textWeb = (WebView) findViewById(R.id.textWeb); TextView textMinute = (TextView) findViewById(R.id.textMinute); TextView textKuckuck = (TextView) findViewById(R.id.textKuckuck); TextView heuteView = (TextView) findViewById(R.id.heute); TextView stundeView = (TextView) findViewById(R.id.stunde); TextView zeitzoneView = (TextView) findViewById(R.id.zeitzone); TextView einstellungenView = (TextView) findViewById(R.id.einstellungen); TextView xx = (TextView) findViewById(R.id.zeitzone); TextView yy = (TextView) findViewById(R.id.zeitzone); ansager = new Ansager(this, zeitKomplettView, heuteView, stundeView, zeitzoneView, einstellungenView, inWortenView, textViertel, textMinute, textKuckuck ); //, textWeb); } class Empfänger extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ansager.zeigeZeit(laut, einMal, jedeMinute, jedeViertelstunde, kuckuckUndGong); } } /* * Activity net.za.dyndns.gerd.uhr.uhr.MainActivity has leaked * IntentReceiver net.za.dyndns.gerd.uhr.uhr.MainActivity$Empfänger@41d96638 * that was originally registered here. * Are you missing a call to unregisterReceiver()? * * */ @Override protected void onStop() { this.unregisterReceiver(receiver); super.onStop(); } boolean leise = false, laut = true; @Override protected void onStart() { super.onStart(); ansager.zeigeZeit(leise, einMal, jedeMinute, jedeViertelstunde, kuckuckUndGong); // Register Empfänger to track minute ticks. IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK); receiver = new Empfänger(); this.registerReceiver(receiver, filter); toggle(tast1, jedeMinute, DochOderNicht.DOCH, DochOderNicht.NICHT); tast1.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { jedeMinute = !jedeMinute; ansager.zeigeZeit(leise, einMal, jedeMinute, jedeViertelstunde, kuckuckUndGong); toggle(tast1, jedeMinute, DochOderNicht.DOCH, DochOderNicht.NICHT); } } ); toggle(tast2, jedeViertelstunde, DochOderNicht.DOCH, DochOderNicht.NICHT); tast2.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { jedeViertelstunde = !jedeViertelstunde; ansager.zeigeZeit(leise, einMal, jedeMinute, jedeViertelstunde, kuckuckUndGong); toggle(tast2, jedeViertelstunde, DochOderNicht.DOCH, DochOderNicht.NICHT); } } ); tast4.setText(R.string.sagDieZeitEinmal); tast4.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { ansager.zeigeZeit(laut, true, jedeMinute, jedeViertelstunde, kuckuckUndGong); } } ); toggle(tast3, kuckuckUndGong, DochOderNicht.DOCH, DochOderNicht.NICHT); tast3.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { kuckuckUndGong = !kuckuckUndGong; ansager.zeigeZeit(leise, einMal, jedeMinute, jedeViertelstunde, kuckuckUndGong); toggle(tast3, kuckuckUndGong, DochOderNicht.DOCH, DochOderNicht.NICHT); } } ); } void togg(Button taste, boolean kriterium, int wennJa, int wennNein) { if (kriterium) taste.setText(wennNein); else taste.setText(wennJa); } void toggle(Button taste, boolean kriterium, DochOderNicht wennJa, DochOderNicht wennNein) { if (kriterium) taste.setText(translate(wennNein)); else taste.setText(translate(wennJa)); } int translate(DochOderNicht wennJa) { if (wennJa == DochOderNicht.DOCH) { return R.string.doch; } return R.string.lieberNicht; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); int uniqueItemID = 1; menu.add(Menu.NONE, uniqueItemID, Menu.NONE, getString(R.string.programmaticallyAdded)); 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(); switch (id) { case android.R.id.home: // Berühre das DLF-Icon links oben auf dem Bildschirm if (debug > 1) Log.i("o030", "startActivityAfterCleanup(WahlActivity.class)"); // ProjectsActivity is my 'home' activity startActivityAfterCleanup(MainActivity.class); return true; case R.id.action_settings: { return true; } case R.id.vorgaben: { return true; } default: { //return true; } } return super.onOptionsItemSelected(item); } private void startActivityAfterCleanup(Class<?> cls) { // für den Home-Button //if (projectsDao != null) projectsDao.close(); Intent intent = new Intent(getApplicationContext(), cls); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }
true
316ce0b01dd130f502290427a9e332fed54fab7a
Java
Inquisitors/crime-data-analytic-platform
/src/main/java/org/inquisitors/platform/controller/ColumnList.java
UTF-8
282
1.882813
2
[]
no_license
package org.inquisitors.platform.controller; import java.util.ArrayList; /** * Created by Buwaneka on 12/18/2016. */ public class ColumnList { private ArrayList<String> columns; public void setColumns(ArrayList<String> columns){ this.columns = columns; } }
true
42d153f1a1797c07c667a73235aa6f4b36aec04d
Java
gusuperstar/Detector
/OpenCVAndroidBoilerplate/src/com/example/opencvandroidboilerplate/MainActivity.java
GB18030
11,713
1.578125
2
[]
no_license
package com.example.opencvandroidboilerplate; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import org.opencv.android.BaseLoaderCallback; import org.opencv.android.CameraBridgeViewBase; import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame; import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2; import org.opencv.android.LoaderCallbackInterface; import org.opencv.android.OpenCVLoader; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import org.winplus.serial.SerialPortInterface; import com.example.protocol.MyHandler; import com.example.protocol.TcpThread; import com.example.protocol.WifiConnect; //import com.example.linptcptest.MainActivity.TcpThread; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.StrictMode; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.telephony.TelephonyManager; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.SurfaceView; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity implements CvCameraViewListener2 { private static final String TAG = "Rectangle"; private String imei = "862937024426652"; private String l2 = "76379j098509639"; private String l3 = "fadgafgsdfewqrjhkk"; private String ssid = "ZCY304"; private String pwd = "Welcome1"; private CameraBridgeViewBase mOpenCvCameraView; private WifiConnect mWifiConn; private static boolean isWIFIConnected = false; private static boolean isTCPConnected = false; private SerialPortInterface spi; private long lastSendTime = 0; private int nframe = 0; //for home key public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000; //Socket socket ; PrintWriter out; private long mExitTime1 = 0; private long mExitTime2 = 0; private long mExitTime3 = 0; private final int TIMER_INVALIDATE = 51706; private String SOCKET_IP = "192.168.1.100";//"10.11.12.1"4001 192.168.1.102 private int sendnum = 1; private String last_signal0 = "0"; private String last_signal1 = "0"; private String last_signal2 = "0"; // public static final int CONNECT = 0; // public static final int CLOSE = 1; // public static final int SEND = 2; // public static final int RECEIVE = 3; boolean flag=true; public long startTime; //Handler mTcpHandler; // MyHandler myHandler ; // TcpThread myTcpThread; static { if (!OpenCVLoader.initDebug()) { } else { System.loadLibrary("zzz"); } } private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) { @Override public void onManagerConnected(int status) { switch (status) { case LoaderCallbackInterface.SUCCESS: { System.loadLibrary("zzz"); mOpenCvCameraView.enableView(); } break; default: { super.onManagerConnected(status); } break; } } }; @Override public void onResume() { super.onResume(); } @Override public void onCreate(Bundle savedInstanceState) { // TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); Log.i(TAG, "Goose called onCreate cpu:("+tm.getDeviceId()+"),("+l2+")"); // if(!tm.getDeviceId().toLowerCase().equals(imei)) // finish(); super.onCreate(savedInstanceState); // getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);//ؼ // requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.CameraView ); mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE); mOpenCvCameraView.setCvCameraViewListener(this); mOpenCvCameraView.setFocusable(false); mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS); // mOpenCvCameraView.setMaxFrameSize(480, 320); // myHandler = new MyHandler() ; // myTcpThread = new TcpThread(); // myTcpThread.start(); // Log.i(TAG, "Goose new TcpThread().start 1"); // connectWIFI(3); // connectTCP(3); Log.i(TAG, "Goose init finish"); //spi = new SerialPortInterface(); } public boolean connectTCP(int retries) { // for(int i = 0; i < 10000;i++) // { // try // { // Message connectMsg = new Message(); // connectMsg.obj = SOCKET_IP; // connectMsg.what =CONNECT; // this.myTcpThread.getHandler().sendMessage(connectMsg); // isTCPConnected = true; // break; // } // catch(Exception e){ // // Log.i(TAG, "Goose connectTCP Exception :"+e); // continue; // } // } // // Log.i(TAG, "Goose connectTCP isTCPConnected 2:"+isTCPConnected); return isTCPConnected; } public boolean connectWIFI(int retries) { // int cnt = 0; // while(!isWIFIConnected && cnt < retries) // { // try // { // Log.i(TAG, "Goose connectWIFI connect 1"); // mWifiConn = new WifiConnect(this); // mWifiConn.openWifi(); // isWIFIConnected = mWifiConn.addNetwork(mWifiConn.CreateWifiInfo(ssid, pwd, 3)); // Thread.sleep(1000); // } // catch(Throwable e) // { // Log.i(TAG, "Goose isWIFIConnected failed 1:"+cnt); // } // cnt++; // } // if(isWIFIConnected) // Log.i(TAG, "Goose isWIFIConnected succ!"); // else // { // Log.i(TAG, "Goose isWIFIConnected onDestroy!"); // } isWIFIConnected = true; return isWIFIConnected; } public boolean disconnect() { // Message closeMsg = new Message(); // closeMsg.what =CLOSE; // this.myTcpThread.getHandler().sendMessage(closeMsg); // mWifiConn.closeWifi(); // mWifiConn.openWifi(); return true; } @Override public void onPause() { super.onPause(); if (mOpenCvCameraView != null) mOpenCvCameraView.disableView(); } public void onDestroy() { super.onDestroy(); if (mOpenCvCameraView != null) mOpenCvCameraView.disableView(); // if(isTCPConnected) // { // Message closeMsg = new Message(); // closeMsg.what =CLOSE; // this.myTcpThread.getHandler().sendMessage(closeMsg); // isTCPConnected = false; // } } public void onCameraViewStarted(int width, int height) { Log.i(TAG, "Goose onCameraViewStarted width:"+width+ " height:"+height); } public void onCameraViewStopped() { } public Mat onCameraFrame(CvCameraViewFrame inputFrame) { // Log.i(TAG, "Goose onCameraFrame in 1"); // long enterTime = System.currentTimeMillis(); Mat mat = new Mat(); Mat input = inputFrame.rgba(); // float scale = 0.6f; // Size dsize = new Size(input.width() * scale, input.height() * scale); // ͼƬĴС // Mat img2 = new Mat();// һµMatopencvľͣ //dsize, CvType.CV_16S, // Imgproc.resize(input, img2,dsize);//ImgprocResizeͼƬ //, 0.5, 0.5, INTER_AREA DV dv = new DV(); dv = zzz(input.getNativeObjAddr(), mat.getNativeObjAddr(), dv); // Log.i(TAG, "Goose onCameraFrame 2 succ:" // +" d0:"+dv.d0+" d1:"+dv.d1+" d2:"+dv.d2+" v1:"+dv.v1+" v2:"+dv.v2); // // // if(isTCPConnected)//"10.11.12.1"4001 // { Log.i(TAG, "Goose onCameraFrame ("+input.width()+","+input.height()+") sent:"+nframe++); String signal0 = last_signal0; String signal1 = last_signal1; String signal2 = last_signal2; if(dv.d0 > 0) { signal0 = "C%" + 1 + "0" ; // sendTCPMsg(signal0); // sendSerialMsg(signal0); } else if(dv.d1 > 0 || dv.d2 > 0) { if(dv.d1 > 0) { if(dv.v1 > 9) { dv.v1 = 9; } String v = String.valueOf(dv.v1); signal1 = "C*" + v + "0" ; // Log.i(TAG, "Goose onCameraFrame 2: v1:" + v + " x:" + signal1); // sendTCPMsg(signal1); // sendSerialMsg(signal1); } else { signal1 = "C*" + 0 + "0" ; } if(dv.d2 > 0) { if(dv.v2 > 9) { dv.v2 = 9; } String v = String.valueOf(dv.v2); signal2 = "C#" + v + "0" ; // Log.i(TAG, "Goose onCameraFrame 2: v1:" + v + " x:" + signal2); // sendTCPMsg(signal2); // sendSerialMsg(signal2); } else { signal2 = "C#" + 0 + "0" ; } } else { signal0 = "C%" + 0 + "0" ; //sendTCPMsg(signal); } // else // WifiConnect.udpSend("0000", SOCKET_IP, SOCKET_PORT); long outTime = System.currentTimeMillis(); if(outTime - lastSendTime > 3000000) { // sendSerialMsg("C@00"); lastSendTime = outTime; } // Size dsize2 = new Size(input.width() , input.height() ); // ͼƬĴС // Mat out = new Mat();// һµMatopencvľͣdsize2, CvType.CV_16S // Imgproc.resize(mat, out, dsize2); // Log.i(TAG, "Goose frame cost:"+ (outTime-enterTime)); return mat;//out;//mat; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // if(keyCode == KeyEvent.KEYCODE_BACK) { ////ηؼ // return true; // } else if(keyCode == KeyEvent.KEYCODE_MENU) {//MENU ///ز˵ mExitTime1 = System.currentTimeMillis(); if ((System.currentTimeMillis() - mExitTime3) < 300) finish(); else return true; } else if(keyCode == KeyEvent.KEYCODE_POWER) { return true; } else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) return true; else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP) { if ((System.currentTimeMillis() - mExitTime1) < 300) { mExitTime2 = System.currentTimeMillis(); } return true; } else if(keyCode == KeyEvent.KEYCODE_HOME) { if ((System.currentTimeMillis() - mExitTime2) < 300) mExitTime3 = System.currentTimeMillis(); return true; } return super.onKeyDown(keyCode, event); } // @Override // public void onAttachedToWindow() //android 2.3 // { // this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); // super.onAttachedToWindow(); // } public void sendTCPMsg(String msg) { // Message sendMsg = new Message(); // sendMsg.obj = msg; // sendMsg.arg1 = 1; // sendMsg.what =SEND; // this.myTcpThread.getHandler().sendMessage(sendMsg); } public void sendSerialMsg(String msg) { try { spi.getOutputStream().write(msg.getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public native DV zzz(long matAddrInRGBA, long matAddrOutInRGBA, DV dv); }
true
fd18b4e0dea96f7586330b0331f5d0bac46b67c2
Java
andrejpetras/quarkus
/independent-projects/bootstrap/gradle-resolver/src/main/java/io/quarkus/bootstrap/resolver/model/impl/SourceSetImpl.java
UTF-8
1,309
2.46875
2
[ "Apache-2.0" ]
permissive
package io.quarkus.bootstrap.resolver.model.impl; import io.quarkus.bootstrap.resolver.model.SourceSet; import java.io.File; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; public class SourceSetImpl implements SourceSet, Serializable { private Set<File> sourceDirectories = new HashSet<>(); private File resourceDirectory; public SourceSetImpl(Set<File> sourceDirectories, File resourceDirectory) { this.sourceDirectories.addAll(sourceDirectories); this.resourceDirectory = resourceDirectory; } public SourceSetImpl(Set<File> sourceDirectories) { this.sourceDirectories.addAll(sourceDirectories); } public void addSourceDirectories(Set<File> files) { sourceDirectories.addAll(files); } @Override public Set<File> getSourceDirectories() { return sourceDirectories; } @Override public File getResourceDirectory() { return resourceDirectory; } @Override public String toString() { return "SourceSetImpl{" + "sourceDirectories=" + sourceDirectories.stream().map(File::getPath).collect(Collectors.joining(":")) + ", resourceDirectory=" + resourceDirectory + '}'; } }
true
7ba8df8e733b3bbe310308e3213c118202647363
Java
zzlhs/parking
/cf-ucenter/cf-ucenter-domain/src/main/java/com/cf/ucenter/domain/CfUserExample.java
UTF-8
27,391
2.171875
2
[ "Zlib" ]
permissive
package com.cf.ucenter.domain; import java.util.ArrayList; import java.util.List; public class CfUserExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public CfUserExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(String value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(String value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(String value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(String value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(String value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(String value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdLike(String value) { addCriterion("id like", value, "id"); return (Criteria) this; } public Criteria andIdNotLike(String value) { addCriterion("id not like", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<String> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<String> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(String value1, String value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(String value1, String value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andUserNameIsNull() { addCriterion("user_name is null"); return (Criteria) this; } public Criteria andUserNameIsNotNull() { addCriterion("user_name is not null"); return (Criteria) this; } public Criteria andUserNameEqualTo(String value) { addCriterion("user_name =", value, "userName"); return (Criteria) this; } public Criteria andPhoneEqualTo(String value) { addCriterion("phone =", value, "phone"); return (Criteria) this; } public Criteria andUserNameNotEqualTo(String value) { addCriterion("user_name <>", value, "userName"); return (Criteria) this; } public Criteria andUserNameGreaterThan(String value) { addCriterion("user_name >", value, "userName"); return (Criteria) this; } public Criteria andUserNameGreaterThanOrEqualTo(String value) { addCriterion("user_name >=", value, "userName"); return (Criteria) this; } public Criteria andUserNameLessThan(String value) { addCriterion("user_name <", value, "userName"); return (Criteria) this; } public Criteria andUserNameLessThanOrEqualTo(String value) { addCriterion("user_name <=", value, "userName"); return (Criteria) this; } public Criteria andUserNameLike(String value) { addCriterion("user_name like", value, "userName"); return (Criteria) this; } public Criteria andUserNameNotLike(String value) { addCriterion("user_name not like", value, "userName"); return (Criteria) this; } public Criteria andUserNameIn(List<String> values) { addCriterion("user_name in", values, "userName"); return (Criteria) this; } public Criteria andUserNameNotIn(List<String> values) { addCriterion("user_name not in", values, "userName"); return (Criteria) this; } public Criteria andUserNameBetween(String value1, String value2) { addCriterion("user_name between", value1, value2, "userName"); return (Criteria) this; } public Criteria andUserNameNotBetween(String value1, String value2) { addCriterion("user_name not between", value1, value2, "userName"); return (Criteria) this; } public Criteria andPasswordIsNull() { addCriterion("password is null"); return (Criteria) this; } public Criteria andPasswordIsNotNull() { addCriterion("password is not null"); return (Criteria) this; } public Criteria andPasswordEqualTo(String value) { addCriterion("password =", value, "password"); return (Criteria) this; } public Criteria andPasswordNotEqualTo(String value) { addCriterion("password <>", value, "password"); return (Criteria) this; } public Criteria andPasswordGreaterThan(String value) { addCriterion("password >", value, "password"); return (Criteria) this; } public Criteria andPasswordGreaterThanOrEqualTo(String value) { addCriterion("password >=", value, "password"); return (Criteria) this; } public Criteria andPasswordLessThan(String value) { addCriterion("password <", value, "password"); return (Criteria) this; } public Criteria andPasswordLessThanOrEqualTo(String value) { addCriterion("password <=", value, "password"); return (Criteria) this; } public Criteria andPasswordLike(String value) { addCriterion("password like", value, "password"); return (Criteria) this; } public Criteria andPasswordNotLike(String value) { addCriterion("password not like", value, "password"); return (Criteria) this; } public Criteria andPasswordIn(List<String> values) { addCriterion("password in", values, "password"); return (Criteria) this; } public Criteria andPasswordNotIn(List<String> values) { addCriterion("password not in", values, "password"); return (Criteria) this; } public Criteria andPasswordBetween(String value1, String value2) { addCriterion("password between", value1, value2, "password"); return (Criteria) this; } public Criteria andPasswordNotBetween(String value1, String value2) { addCriterion("password not between", value1, value2, "password"); return (Criteria) this; } public Criteria andAvatarIsNull() { addCriterion("avatar is null"); return (Criteria) this; } public Criteria andAvatarIsNotNull() { addCriterion("avatar is not null"); return (Criteria) this; } public Criteria andAvatarEqualTo(String value) { addCriterion("avatar =", value, "avatar"); return (Criteria) this; } public Criteria andAvatarNotEqualTo(String value) { addCriterion("avatar <>", value, "avatar"); return (Criteria) this; } public Criteria andAvatarGreaterThan(String value) { addCriterion("avatar >", value, "avatar"); return (Criteria) this; } public Criteria andAvatarGreaterThanOrEqualTo(String value) { addCriterion("avatar >=", value, "avatar"); return (Criteria) this; } public Criteria andAvatarLessThan(String value) { addCriterion("avatar <", value, "avatar"); return (Criteria) this; } public Criteria andAvatarLessThanOrEqualTo(String value) { addCriterion("avatar <=", value, "avatar"); return (Criteria) this; } public Criteria andAvatarLike(String value) { addCriterion("avatar like", value, "avatar"); return (Criteria) this; } public Criteria andAvatarNotLike(String value) { addCriterion("avatar not like", value, "avatar"); return (Criteria) this; } public Criteria andAvatarIn(List<String> values) { addCriterion("avatar in", values, "avatar"); return (Criteria) this; } public Criteria andAvatarNotIn(List<String> values) { addCriterion("avatar not in", values, "avatar"); return (Criteria) this; } public Criteria andAvatarBetween(String value1, String value2) { addCriterion("avatar between", value1, value2, "avatar"); return (Criteria) this; } public Criteria andAvatarNotBetween(String value1, String value2) { addCriterion("avatar not between", value1, value2, "avatar"); return (Criteria) this; } public Criteria andTypeIsNull() { addCriterion("type is null"); return (Criteria) this; } public Criteria andTypeIsNotNull() { addCriterion("type is not null"); return (Criteria) this; } public Criteria andTypeEqualTo(Byte value) { addCriterion("type =", value, "type"); return (Criteria) this; } public Criteria andTypeNotEqualTo(Byte value) { addCriterion("type <>", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThan(Byte value) { addCriterion("type >", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThanOrEqualTo(Byte value) { addCriterion("type >=", value, "type"); return (Criteria) this; } public Criteria andTypeLessThan(Byte value) { addCriterion("type <", value, "type"); return (Criteria) this; } public Criteria andTypeLessThanOrEqualTo(Byte value) { addCriterion("type <=", value, "type"); return (Criteria) this; } public Criteria andTypeIn(List<Byte> values) { addCriterion("type in", values, "type"); return (Criteria) this; } public Criteria andTypeNotIn(List<Byte> values) { addCriterion("type not in", values, "type"); return (Criteria) this; } public Criteria andTypeBetween(Byte value1, Byte value2) { addCriterion("type between", value1, value2, "type"); return (Criteria) this; } public Criteria andTypeNotBetween(Byte value1, Byte value2) { addCriterion("type not between", value1, value2, "type"); return (Criteria) this; } public Criteria andNickNameIsNull() { addCriterion("nick_name is null"); return (Criteria) this; } public Criteria andNickNameIsNotNull() { addCriterion("nick_name is not null"); return (Criteria) this; } public Criteria andNickNameEqualTo(String value) { addCriterion("nick_name =", value, "nickName"); return (Criteria) this; } public Criteria andNickNameNotEqualTo(String value) { addCriterion("nick_name <>", value, "nickName"); return (Criteria) this; } public Criteria andNickNameGreaterThan(String value) { addCriterion("nick_name >", value, "nickName"); return (Criteria) this; } public Criteria andNickNameGreaterThanOrEqualTo(String value) { addCriterion("nick_name >=", value, "nickName"); return (Criteria) this; } public Criteria andNickNameLessThan(String value) { addCriterion("nick_name <", value, "nickName"); return (Criteria) this; } public Criteria andNickNameLessThanOrEqualTo(String value) { addCriterion("nick_name <=", value, "nickName"); return (Criteria) this; } public Criteria andNickNameLike(String value) { addCriterion("nick_name like", value, "nickName"); return (Criteria) this; } public Criteria andNickNameNotLike(String value) { addCriterion("nick_name not like", value, "nickName"); return (Criteria) this; } public Criteria andNickNameIn(List<String> values) { addCriterion("nick_name in", values, "nickName"); return (Criteria) this; } public Criteria andNickNameNotIn(List<String> values) { addCriterion("nick_name not in", values, "nickName"); return (Criteria) this; } public Criteria andNickNameBetween(String value1, String value2) { addCriterion("nick_name between", value1, value2, "nickName"); return (Criteria) this; } public Criteria andNickNameNotBetween(String value1, String value2) { addCriterion("nick_name not between", value1, value2, "nickName"); return (Criteria) this; } public Criteria andTrueNameIsNull() { addCriterion("true_name is null"); return (Criteria) this; } public Criteria andTrueNameIsNotNull() { addCriterion("true_name is not null"); return (Criteria) this; } public Criteria andTrueNameEqualTo(String value) { addCriterion("true_name =", value, "trueName"); return (Criteria) this; } public Criteria andTrueNameNotEqualTo(String value) { addCriterion("true_name <>", value, "trueName"); return (Criteria) this; } public Criteria andTrueNameGreaterThan(String value) { addCriterion("true_name >", value, "trueName"); return (Criteria) this; } public Criteria andTrueNameGreaterThanOrEqualTo(String value) { addCriterion("true_name >=", value, "trueName"); return (Criteria) this; } public Criteria andTrueNameLessThan(String value) { addCriterion("true_name <", value, "trueName"); return (Criteria) this; } public Criteria andTrueNameLessThanOrEqualTo(String value) { addCriterion("true_name <=", value, "trueName"); return (Criteria) this; } public Criteria andTrueNameLike(String value) { addCriterion("true_name like", value, "trueName"); return (Criteria) this; } public Criteria andTrueNameNotLike(String value) { addCriterion("true_name not like", value, "trueName"); return (Criteria) this; } public Criteria andTrueNameIn(List<String> values) { addCriterion("true_name in", values, "trueName"); return (Criteria) this; } public Criteria andTrueNameNotIn(List<String> values) { addCriterion("true_name not in", values, "trueName"); return (Criteria) this; } public Criteria andTrueNameBetween(String value1, String value2) { addCriterion("true_name between", value1, value2, "trueName"); return (Criteria) this; } public Criteria andTrueNameNotBetween(String value1, String value2) { addCriterion("true_name not between", value1, value2, "trueName"); return (Criteria) this; } public Criteria andBirthdayIsNull() { addCriterion("birthday is null"); return (Criteria) this; } public Criteria andBirthdayIsNotNull() { addCriterion("birthday is not null"); return (Criteria) this; } public Criteria andBirthdayEqualTo(Integer value) { addCriterion("birthday =", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayNotEqualTo(Integer value) { addCriterion("birthday <>", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayGreaterThan(Integer value) { addCriterion("birthday >", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayGreaterThanOrEqualTo(Integer value) { addCriterion("birthday >=", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayLessThan(Integer value) { addCriterion("birthday <", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayLessThanOrEqualTo(Integer value) { addCriterion("birthday <=", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayIn(List<Integer> values) { addCriterion("birthday in", values, "birthday"); return (Criteria) this; } public Criteria andBirthdayNotIn(List<Integer> values) { addCriterion("birthday not in", values, "birthday"); return (Criteria) this; } public Criteria andBirthdayBetween(Integer value1, Integer value2) { addCriterion("birthday between", value1, value2, "birthday"); return (Criteria) this; } public Criteria andBirthdayNotBetween(Integer value1, Integer value2) { addCriterion("birthday not between", value1, value2, "birthday"); return (Criteria) this; } public Criteria andSexIsNull() { addCriterion("sex is null"); return (Criteria) this; } public Criteria andSexIsNotNull() { addCriterion("sex is not null"); return (Criteria) this; } public Criteria andSexEqualTo(Integer value) { addCriterion("sex =", value, "sex"); return (Criteria) this; } public Criteria andSexNotEqualTo(Integer value) { addCriterion("sex <>", value, "sex"); return (Criteria) this; } public Criteria andSexGreaterThan(Integer value) { addCriterion("sex >", value, "sex"); return (Criteria) this; } public Criteria andSexGreaterThanOrEqualTo(Integer value) { addCriterion("sex >=", value, "sex"); return (Criteria) this; } public Criteria andSexLessThan(Integer value) { addCriterion("sex <", value, "sex"); return (Criteria) this; } public Criteria andSexLessThanOrEqualTo(Integer value) { addCriterion("sex <=", value, "sex"); return (Criteria) this; } public Criteria andSexIn(List<Integer> values) { addCriterion("sex in", values, "sex"); return (Criteria) this; } public Criteria andSexNotIn(List<Integer> values) { addCriterion("sex not in", values, "sex"); return (Criteria) this; } public Criteria andSexBetween(Integer value1, Integer value2) { addCriterion("sex between", value1, value2, "sex"); return (Criteria) this; } public Criteria andSexNotBetween(Integer value1, Integer value2) { addCriterion("sex not between", value1, value2, "sex"); return (Criteria) this; } public Criteria andSignIsNull() { addCriterion("sign is null"); return (Criteria) this; } public Criteria andSignIsNotNull() { addCriterion("sign is not null"); return (Criteria) this; } public Criteria andSignEqualTo(String value) { addCriterion("sign =", value, "sign"); return (Criteria) this; } public Criteria andSignNotEqualTo(String value) { addCriterion("sign <>", value, "sign"); return (Criteria) this; } public Criteria andSignGreaterThan(String value) { addCriterion("sign >", value, "sign"); return (Criteria) this; } public Criteria andSignGreaterThanOrEqualTo(String value) { addCriterion("sign >=", value, "sign"); return (Criteria) this; } public Criteria andSignLessThan(String value) { addCriterion("sign <", value, "sign"); return (Criteria) this; } public Criteria andSignLessThanOrEqualTo(String value) { addCriterion("sign <=", value, "sign"); return (Criteria) this; } public Criteria andSignLike(String value) { addCriterion("sign like", value, "sign"); return (Criteria) this; } public Criteria andSignNotLike(String value) { addCriterion("sign not like", value, "sign"); return (Criteria) this; } public Criteria andSignIn(List<String> values) { addCriterion("sign in", values, "sign"); return (Criteria) this; } public Criteria andSignNotIn(List<String> values) { addCriterion("sign not in", values, "sign"); return (Criteria) this; } public Criteria andSignBetween(String value1, String value2) { addCriterion("sign between", value1, value2, "sign"); return (Criteria) this; } public Criteria andSignNotBetween(String value1, String value2) { addCriterion("sign not between", value1, value2, "sign"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
true
f973f9d43a8aad6131b1b29c9f1eda232a612a95
Java
gdyoon/DoranDoran
/app/src/main/java/com/doraesol/dorandoran/calendar/CalendarMainFragment.java
UTF-8
5,782
2.15625
2
[]
no_license
package com.doraesol.dorandoran.calendar; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.doraesol.dorandoran.R; import com.github.sundeepk.compactcalendarview.CompactCalendarView; import com.github.sundeepk.compactcalendarview.domain.Event; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static com.google.android.gms.internal.zzt.TAG; /** * A simple {@link Fragment} subclass. */ public class CalendarMainFragment extends Fragment { final String LOG_TAG = CalendarMainFragment.class.getSimpleName(); CompactCalendarView compactCalendarView; Calendar currentCalender = Calendar.getInstance(Locale.KOREAN); private SimpleDateFormat dateFormatForMonth = new SimpleDateFormat("yyyy년 MM월", Locale.KOREAN); @BindView(R.id.iv_calendar_month_prev) ImageView iv_calendar_moth_prev; @BindView(R.id.iv_calendar_month_next) ImageView iv_calendar_moth_next; @BindView(R.id.tv_calendar_month) TextView tv_calendar_month; @BindView(R.id.lv_calendar_schedule) ListView lv_calendar_schedule; public CalendarMainFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment final List<String> scheduleList = new ArrayList<>(); final View rootView = inflater.inflate(R.layout.fragment_calendar_main, container, false); final ArrayAdapter adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, scheduleList); ButterKnife.bind(this, rootView); lv_calendar_schedule.setAdapter(adapter); compactCalendarView = (CompactCalendarView)rootView.findViewById(R.id.compactcalendar_view); compactCalendarView.setLocale(TimeZone.getDefault(), Locale.KOREAN); // 그레고리안력으로 변경 후 2017년 4월 6일에 스케쥴 설정 currentCalender.set(Calendar.ERA, GregorianCalendar.AD); currentCalender.set(Calendar.YEAR, 2017); currentCalender.set(Calendar.MONTH, Calendar.APRIL); currentCalender.add(Calendar.DATE, 5); Event event = new Event(Color.BLUE, currentCalender.getTimeInMillis(), "스케쥴 저장하기"); setToMidnight(currentCalender); compactCalendarView.addEvent(event, true); compactCalendarView.setListener(new CompactCalendarView.CompactCalendarViewListener() { @Override public void onDayClick(Date dateClicked) { List<Event> bookingsFromMap = compactCalendarView.getEvents(dateClicked); if (bookingsFromMap != null) { Log.d(TAG, bookingsFromMap.toString()); scheduleList.clear(); for (Event booking : bookingsFromMap) { scheduleList.add((String) booking.getData()); } adapter.notifyDataSetChanged(); } } @Override public void onMonthScroll(Date firstDayOfNewMonth) { tv_calendar_month.setText(dateFormatForMonth.format(firstDayOfNewMonth)); } }); return rootView; } @OnClick({R.id.iv_calendar_month_next, R.id.iv_calendar_month_prev}) public void OnTitleImageButtonClicked(View view){ switch (view.getId()){ case R.id.iv_calendar_month_prev: compactCalendarView.showPreviousMonth(); break; case R.id.iv_calendar_month_next: compactCalendarView.showNextMonth(); break; } } private void addEvents(int month, int year) { currentCalender.setTime(new Date()); currentCalender.set(Calendar.DAY_OF_MONTH, 1); Date firstDayOfMonth = currentCalender.getTime(); for (int i = 0; i < 5; i++) { currentCalender.setTime(firstDayOfMonth); if (month > -1) { currentCalender.set(Calendar.MONTH, month); } if (year > -1) { currentCalender.set(Calendar.ERA, GregorianCalendar.AD); currentCalender.set(Calendar.YEAR, year); } currentCalender.add(Calendar.DATE, i); //setToMidnight(currentCalender); long timeInMillis = currentCalender.getTimeInMillis(); List<Event> events = getEvents(timeInMillis, i); compactCalendarView.addEvents(events); } } private List<Event> getEvents(long timeInMillis, int day) { return Arrays.asList( new Event(Color.argb(255, 169, 68, 65), timeInMillis, "스케쥴 : " + new Date(timeInMillis)), new Event(Color.argb(255, 169, 68, 65), timeInMillis, "스케쥴 : " + new Date(timeInMillis))); } private void setToMidnight(Calendar calendar) { calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); } }
true
8f9c42e038bdba315441f7e185995d3b668b2c98
Java
IanaNeaga/Interfaces
/src/main/java/com/sda/abstracte/Masina.java
UTF-8
327
2.296875
2
[]
no_license
package com.sda.abstracte; import com.sda.interfete.IMotor; import java.util.HashMap; public class Masina extends ACaroserie implements IMotor { @Override public String getTip() { return "Cabrio"; } @Override public String getCilindre() { return "4.7 Hemi"; } }
true
1b3643c19baa7535515710409f7d318cfa55dc02
Java
ev-wilt/Java-Minesweeper-Clone
/Minesweeper.java
UTF-8
11,445
3.09375
3
[]
no_license
// Minesweeper.java // A clone of Minesweeper built in a Java GUI // By: Evan Wilt // Created: 4-4-16 // Last Revised: 4-25-16 import java.util.ArrayList; import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.Random; public class Minesweeper extends JFrame implements ActionListener { // Instantiating variables private boolean currentlyFlagging = false; private boolean gameOver = false; private boolean keepGoing = true; private int turnCounter = 0; private int pressedButtonCounter = 0; private int bombNumber = 15; private int xSize = 10; private int ySize = 10; private Button currentButton = new Button(); private Button randButton = new Button(); private ArrayList<Button> buttons = new ArrayList<>(); private ArrayList<Bomb> bombs = new ArrayList<>(); Random random = new Random(); Font font = new Font("Verdana", Font.BOLD, 60); JTextField turnField = new JTextField("0"); JButton flagButton = new JButton("Click to flag"); JPanel menu = new JPanel(); JPanel playField = new JPanel(); public Minesweeper() { // Constructor for the minesweeper class this.setupGUI(); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); this.setSize(120*this.xSize, 70*ySize); } // end constructor public void setupGUI() { // Adding all of the GUI components and also placing bombs Container mainPanel = this.getContentPane(); mainPanel.setLayout(new GridLayout(1,1)); menu.setLayout(new GridLayout(5,5)); playField.setLayout(new GridLayout(this.xSize+2,this.ySize+2)); turnField.setFont(font); turnField.setEditable(false); mainPanel.add(menu); mainPanel.add(playField); menu.add(turnField); menu.add(flagButton); for (int x = 0; x < this.xSize+1; x++) { for (int y = 0; y < this.ySize+1; y++) { buttons.add(new Button(x,y)); for (int i = 0; i < buttons.size(); i++) { if (buttons.get(i).getXCoordinate() == x) { if (buttons.get(i).getYCoordinate() == y) { playField.add(buttons.get(i)); } // end y if } // end x if } // end for } // end y for } // end x for this.hideEdges(); this.addBombs(); this.countButtons(); // Action listeners flagButton.addActionListener(this); for (int j = 0; j < buttons.size(); j++) { buttons.get(j).addActionListener(this); } // end for } // end setupGUI public void actionPerformed(ActionEvent e){ if (e.getSource() == flagButton) { if (this.gameOver == false) { if (currentlyFlagging == false) { currentlyFlagging = true; flagButton.setText("Flagging"); } // end if else { currentlyFlagging = false; flagButton.setText("Click to flag"); } // end else } // end if } // end if for (int i = 0; i < buttons.size(); i++) { if (e.getSource() == buttons.get(i)) { this.buttonClicked(buttons.get(i)); } // end if } // end for } // end action listener public void callTurnCounter() { // Counter shows how many turns the player has made if (gameOver == false) { turnCounter++; if (turnCounter == 1) { turnField.setText(Integer.toString(turnCounter) + " Turn"); } // end if else { turnField.setText(Integer.toString(turnCounter) + " Turns"); } // end else } // end if } // end callTimer public void buttonClicked(Button currentButton) { // Recursive algorithm to check the nearby bombs for buttons if (currentlyFlagging == false) { // If the player isn't flagging, if (currentButton.getIsHidden() == false) { // the button isn't hidden, if (currentButton.getFlagged() == false) { // and the button isn't flagged... if (currentButton.getBombsChecked() == false) { // Call the turn counter if the button hasn't been checked this.callTurnCounter(); } if (currentButton.getHasBomb() == true) { // Checking for a loss gameOver = true; flagButton.setText("You lost"); this.showAllBombs(); } // end if if (pressedButtonCounter == 0) { // Checking for a win gameOver = true; flagButton.setText("You won!"); this.showAllBombs(); } // end if if (gameOver == false) { // Check nearby spaces for bombs for (int currentX = currentButton.getXCoordinate() - 1; currentX < currentButton.getXCoordinate() + 2; currentX++) { for (int currentY = currentButton.getYCoordinate() - 1; currentY < currentButton.getYCoordinate() + 2; currentY++) { for (int currentBomb = 0; currentBomb < bombs.size(); currentBomb++) { if (currentX == bombs.get(currentBomb).getXCoordinate()) { if (currentY == bombs.get(currentBomb).getYCoordinate()) { currentButton.setNearbyBombs(currentButton.getNearbyBombs()+1); } // end Y if } // end X if } // end bomb for } // end Y for } // end X for if (currentButton.getNearbyBombs() == 0) { // If no bombs are nearby, call the method for every nearby button for (int i = 0; i < buttons.size(); i++) { for (int currentX = currentButton.getXCoordinate() - 1; currentX < currentButton.getXCoordinate() + 2; currentX++) { for (int currentY = currentButton.getYCoordinate() - 1; currentY < currentButton.getYCoordinate() + 2; currentY++) { if (currentX == buttons.get(i).getXCoordinate()) { if (currentY == buttons.get(i).getYCoordinate()) { if (buttons.get(i).getBombsChecked() == false) { buttons.get(i).setBombsChecked(true); currentButton.setText(Integer.toString(currentButton.getNearbyBombs())); this.buttonClicked(buttons.get(i)); } // end bombsChecked if } // end Y if } // end X if } // end Y for } // end X for } // end for } // end if else if (currentButton.getNearbyBombs() > 0) { // If there's bombs near show the number of them nearby currentButton.setBombsChecked(true); if (currentButton.getText() == "") { this.pressedButtonCounter--; currentButton.setText(Integer.toString(currentButton.getNearbyBombs())); } // end if } // end else } // end gameOver if } // end if } // end if } // end if else if (currentlyFlagging == true) { if (currentButton.getFlagged() == false) { if (currentButton.getBombsChecked() == false) { currentButton.setFlagged(true); currentButton.setText("?"); } // end if } // end if else if (currentButton.getFlagged() == true) { if (currentButton.getBombsChecked() == false) { currentButton.setFlagged(false); currentButton.setText(""); } // end if } // end else } // end else } // end buttonClicked public void hideEdges() { // Hides edge cases on the playfield for (int i = 0; i < buttons.size(); i++) { if (buttons.get(i).getXCoordinate() == 0) { buttons.get(i).setVisible(false); buttons.get(i).setIsHidden(true); } // end if else if (buttons.get(i).getXCoordinate() == this.xSize+1) { buttons.get(i).setVisible(false); buttons.get(i).setIsHidden(true); } // end else else if (buttons.get(i).getYCoordinate() == 0) { buttons.get(i).setVisible(false); buttons.get(i).setIsHidden(true); } // end else else if (buttons.get(i).getYCoordinate() == this.ySize+1) { buttons.get(i).setVisible(false); buttons.get(i).setIsHidden(true); } // end else } // end for } // end hideEdges public void countButtons() { // Counter for buttons without a bomb to check when all of the buttons have been pressed for (int i = 0; i < buttons.size(); i++) { if (buttons.get(i).getHasBomb() == false) { if (buttons.get(i).getIsHidden() == false) { this.pressedButtonCounter++; } // end if } // end if } // end for } // end countButtons public void addBombs() { // Adds bombs to the playfield in a random area while (keepGoing == true) { if (bombs.size() <= this.bombNumber-1) { this.randButton = buttons.get(random.nextInt(buttons.size()) + 0); if (randButton.getIsHidden() == false) { if (randButton.getHasBomb() == false) { randButton.setHasBomb(random.nextBoolean()); if (randButton.getHasBomb() == true) { bombs.add(new Bomb(randButton.getXCoordinate(), randButton.getYCoordinate())); } // end if } // end if }// end if } // end if if (bombs.size() > this.bombNumber-1) { keepGoing = false; } // end if } // end while } // end addBombs public void showAllBombs() { // Shows all bombs on the playfield for (int i = 0; i < buttons.size(); i++) { if (buttons.get(i).getHasBomb() == true) { buttons.get(i).setText("*"); } // end if } // end for } // end showAllBombs public static void main(String[] args){ // Main method new Minesweeper(); } // end main } // end Minesweeper class
true
7d552733087bda7c381a152e3d3b4d14652bc2c0
Java
948017056/SSFS
/app/src/main/java/com/cctv/ssfs/entity/DataSynEvent.java
UTF-8
276
1.757813
2
[]
no_license
package com.cctv.ssfs.entity; /** * Created by sanjin on 2018/4/26. */ public class DataSynEvent { private boolean status; public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } }
true
7cf913140ff314b82bd0c63a82810bfe076771e5
Java
zhangyu2046196/interview_question
/src/main/java/com/youyuan/lock/SpinLockDemo.java
UTF-8
2,118
4.03125
4
[]
no_license
package com.youyuan.lock; import java.util.concurrent.atomic.AtomicReference; /** * @author zhangy * @version 1.0 * @description 自定义自旋锁 * <p> * 自旋锁是在获取锁的时候不会立即阻塞,如果获取不到通过循环的方式不断去尝试,好处是避免上下文切换造成性能损耗,缺点是 * 循环会造成CPU性能损耗 * @date 2019/10/16 19:02 */ public class SpinLockDemo { private AtomicReference<Thread> atomicReference = new AtomicReference<Thread>(); //定义原子引用,原子引用传的值是thread默认是空 /** * 获取锁,通过自旋锁的方式 */ public void myLock() { Thread thread = Thread.currentThread(); //获取当前线程,用当前线程对象作为CAS的期望值 System.out.println(thread.getName() + "\t come in myLock"); //判断期望值是不是null,如果是null把当前线程放入获取锁 while (!atomicReference.compareAndSet(null, thread)) { } } /** * 释放锁 */ public void unLock() { Thread thread = Thread.currentThread(); //获取当前线程,用当前线程对象作为CAS的期望值 System.out.println(thread.getName() + "\t invoked unLock"); //释放锁,如果当前期望值是当前线程,设置为空,使别的线程能获取锁 atomicReference.compareAndSet(thread, null); } public static void main(String[] args) { SpinLockDemo spinLockDemo = new SpinLockDemo(); new Thread(() -> { spinLockDemo.myLock(); //获取锁 try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } spinLockDemo.unLock(); //释放锁 }, "A").start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(() -> { spinLockDemo.myLock(); //获取锁 spinLockDemo.unLock(); //释放锁 }, "B").start(); } }
true
de3e9735d9602ae72eaed2a343c3735e1506228a
Java
NickyHeijningen/bagageSysteem
/bagageSysteem/src/gui/logIn.java
UTF-8
11,179
2.375
2
[]
no_license
/* * 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 gui; import bagagesysteem.BagageDatabase; import bagagesysteem.Main; import bagagesysteem.Gebruikers; import bagagesysteem.bcrypt.BCrypt; import java.awt.Color; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JLabel; /** * * @author Nicky */ public class logIn extends javax.swing.JFrame { Main main = new Main(); ImageIcon corendon = new ImageIcon(getClass().getResource("corendon.png")); int rechten; int taal; public logIn(int taal) { this.taal = taal; initComponents(); kiesTaalKnop.setSelectedIndex(taal); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { gebruikersnaamTekstVeld = new javax.swing.JTextField(); logInKnop = new javax.swing.JButton(); gebruikersnaamTekst = new javax.swing.JLabel(); wachtwoordTekst = new javax.swing.JLabel(); jToolBar1 = new javax.swing.JToolBar(); kiesTaalKnop = new javax.swing.JComboBox<>(); jPanel1 = new javax.swing.JPanel(); wachtwoordTekstVeld = new javax.swing.JPasswordField(); errorTekst = new javax.swing.JLabel(); jLabel1 = new JLabel(corendon); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); gebruikersnaamTekstVeld.setToolTipText("Gebruikersnaam"); gebruikersnaamTekstVeld.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { gebruikersnaamTekstVeldActionPerformed(evt); } }); gebruikersnaamTekstVeld.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { gebruikersnaamTekstVeldKeyPressed(evt); } }); getContentPane().add(gebruikersnaamTekstVeld, new org.netbeans.lib.awtextra.AbsoluteConstraints(217, 150, 249, 35)); logInKnop.setText("Log in"); logInKnop.setBackground(Color.decode("#CC0000")); logInKnop.setForeground(Color.WHITE); logInKnop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { logInKnopActionPerformed(evt); } }); logInKnop.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { logInKnopKeyPressed(evt); } }); getContentPane().add(logInKnop, new org.netbeans.lib.awtextra.AbsoluteConstraints(217, 262, 249, 35)); gebruikersnaamTekst.setText("Gebruikersnaam"); getContentPane().add(gebruikersnaamTekst, new org.netbeans.lib.awtextra.AbsoluteConstraints(217, 130, -1, -1)); wachtwoordTekst.setText("Wachtwoord"); getContentPane().add(wachtwoordTekst, new org.netbeans.lib.awtextra.AbsoluteConstraints(217, 189, -1, -1)); jToolBar1.setRollover(true); kiesTaalKnop.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Nederlands", "English", "Türk" })); kiesTaalKnop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { kiesTaalKnopActionPerformed(evt); } }); jToolBar1.add(kiesTaalKnop); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 606, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 23, Short.MAX_VALUE) ); jToolBar1.add(jPanel1); getContentPane().add(jToolBar1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 575, 700, -1)); wachtwoordTekstVeld.setToolTipText("Wachtwoord"); wachtwoordTekstVeld.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { wachtwoordTekstVeldKeyPressed(evt); } }); getContentPane().add(wachtwoordTekstVeld, new org.netbeans.lib.awtextra.AbsoluteConstraints(217, 209, 249, 35)); errorTekst.setForeground(Color.RED); getContentPane().add(errorTekst, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 310, 240, 40)); jLabel1.setText(null); getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 20, 360, 100)); pack(); }// </editor-fold>//GEN-END:initComponents private void gebruikersnaamTekstVeldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_gebruikersnaamTekstVeldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_gebruikersnaamTekstVeldActionPerformed private void logInKnopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logInKnopActionPerformed try { String gebruikersnaam = gebruikersnaamTekstVeld.getText(); String wachtwoord = wachtwoordTekstVeld.getText(); String rechtenNaam = null; if (main.nullOrEmpty(gebruikersnaam) || main.nullOrEmpty(wachtwoord)) { errorTekst.setText("Niet alle tekstvelden zijn ingevuld."); } else { BagageDatabase db = new BagageDatabase(); Gebruikers users = db.getUsers(gebruikersnaam); if (main.nullOrEmpty(users.getEmail())) { errorTekst.setText("Incorrecte gebruikersnaam"); } else if (BCrypt.checkpw(wachtwoord, users.getWachtwoord())) { switch (users.getRechten()) { case 0: rechtenNaam = "Bagagebalie medewerker"; rechten = 0; break; case 1: rechtenNaam = "Bagage medewerker"; rechten = 1; break; case 2: rechtenNaam = "Leidinggevende"; rechten = 2; break; } String huidigeGebruiker = users.getVoornaam() + " " + users.getAchternaam() + ", " + rechtenNaam; hoofdMenu m = new hoofdMenu(taal, rechten); hoofdMenu.ingelogdAlsTekst.setText(huidigeGebruiker); m.setVisible(true); setVisible(false); dispose(); } else { errorTekst.setText("Incorrect wachtwoord"); } } } catch (Exception e) { errorTekst.setText("Geen verbinding met de database."); } }//GEN-LAST:event_logInKnopActionPerformed private void wachtwoordTekstVeldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_wachtwoordTekstVeldKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { logInKnop.doClick(); } if (evt.getKeyCode() == KeyEvent.VK_UP) { gebruikersnaamTekstVeld.requestFocus(); } if (evt.getKeyCode() == KeyEvent.VK_DOWN) { logInKnop.requestFocus(); } }//GEN-LAST:event_wachtwoordTekstVeldKeyPressed private void gebruikersnaamTekstVeldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_gebruikersnaamTekstVeldKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { wachtwoordTekstVeld.requestFocus(); } if (evt.getKeyCode() == KeyEvent.VK_DOWN) { wachtwoordTekstVeld.requestFocus(); } }//GEN-LAST:event_gebruikersnaamTekstVeldKeyPressed private void logInKnopKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_logInKnopKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { logInKnop.doClick(); } if (evt.getKeyCode() == KeyEvent.VK_UP) { wachtwoordTekstVeld.requestFocus(); } }//GEN-LAST:event_logInKnopKeyPressed private void kiesTaalKnopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_kiesTaalKnopActionPerformed taal = kiesTaalKnop.getSelectedIndex(); }//GEN-LAST:event_kiesTaalKnopActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(logIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(logIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(logIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(logIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new logIn(0).setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel errorTekst; private javax.swing.JLabel gebruikersnaamTekst; private javax.swing.JTextField gebruikersnaamTekstVeld; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JToolBar jToolBar1; private javax.swing.JComboBox<String> kiesTaalKnop; private javax.swing.JButton logInKnop; private javax.swing.JLabel wachtwoordTekst; private javax.swing.JPasswordField wachtwoordTekstVeld; // End of variables declaration//GEN-END:variables }
true
58267ab35d84a1c05a0ba39cd0f82e8d0212620c
Java
AlexDam4703/Tema1
/TestGeometria.java
UTF-8
603
3.234375
3
[]
no_license
public class TestGeometria{ public static void main (String [] args){ double areaCuadrado = AreaCuadrado.hacerAreaCuadrado (2,2); double areaTriangulo = AreaTriangulo.hacerAreaTriangulo (2,2); double areaRectangulo = AreaRectangulo.hacerAreaRectangulo (2,2); double areaCirculo = AreaCirculo.hacerAreaCirculo (2); System.out.println ("El area del cuadrado es: " + areaCuadrado); System.out.println ("El area del triangulo es: " + areaTriangulo); System.out.println ("El area del Resctangulo es: " + areaRectangulo); System.out.println ("El area del circulo es: " + areaCirculo); } }
true
6aee9416a2762a18995b45c08c5795cbaed490be
Java
Android-Spotify-Project/project-pre
/app/src/main/java/com/com/clone_spotify/model/Home.java
UTF-8
2,703
2.0625
2
[]
no_license
package com.com.clone_spotify.model; import android.media.Image; import android.widget.ImageView; import lombok.Data; @Data public class Home { private String songTitle; private String albumImg1; private String albumImg2; private String albumImg3; private String albumImg4; private String albumImg5; private String albumImg6; private String artistName1; private String artistName2; private String artistName3; private String artistName4; private String artistName5; private String artistName6; public String getSongTitle() { return songTitle; } public void setSongTitle(String songTitle) { this.songTitle = songTitle; } public String getAlbumImg1() { return albumImg1; } public void setAlbumImg1(String albumImg1) { this.albumImg1 = albumImg1; } public String getAlbumImg2() { return albumImg2; } public void setAlbumImg2(String albumImg2) { this.albumImg2 = albumImg2; } public String getAlbumImg3() { return albumImg3; } public void setAlbumImg3(String albumImg3) { this.albumImg3 = albumImg3; } public String getAlbumImg4() { return albumImg4; } public void setAlbumImg4(String albumImg4) { this.albumImg4 = albumImg4; } public String getAlbumImg5() { return albumImg5; } public void setAlbumImg5(String albumImg5) { this.albumImg5 = albumImg5; } public String getAlbumImg6() { return albumImg6; } public void setAlbumImg6(String albumImg6) { this.albumImg6 = albumImg6; } public String getArtistName1() { return artistName1; } public void setArtistName1(String artistName1) { this.artistName1 = artistName1; } public String getArtistName2() { return artistName2; } public void setArtistName2(String artistName2) { this.artistName2 = artistName2; } public String getArtistName3() { return artistName3; } public void setArtistName3(String artistName3) { this.artistName3 = artistName3; } public String getArtistName4() { return artistName4; } public void setArtistName4(String artistName4) { this.artistName4 = artistName4; } public String getArtistName5() { return artistName5; } public void setArtistName5(String artistName5) { this.artistName5 = artistName5; } public String getArtistName6() { return artistName6; } public void setArtistName6(String artistName6) { this.artistName6 = artistName6; } }
true
193ed70ae5974d728316b7d5505008641741687a
Java
SnoopInf/pzks
/ComputerSystemsSoftwareGui/src/main/java/edu/kpi/pzks/gui/ui/MainFrame.java
UTF-8
7,480
2.3125
2
[]
no_license
package edu.kpi.pzks.gui.ui; import edu.kpi.pzks.gui.ui.panels.TaskPanel; import edu.kpi.pzks.gui.ui.panels.SystemPanel; import edu.kpi.pzks.gui.ui.panels.GraphPanel; import edu.kpi.pzks.core.validator.ConsistencyValidator; import edu.kpi.pzks.core.validator.CyclingValidator; import edu.kpi.pzks.core.validator.SubGraphValidator; import edu.kpi.pzks.gui.actions.graph.GenTaskGraphAction; import edu.kpi.pzks.gui.actions.graph.LinkCreationToolAction; import edu.kpi.pzks.gui.actions.graph.NodeCreationToolAction; import edu.kpi.pzks.gui.actions.graph.RemoveAction; import edu.kpi.pzks.gui.actions.graph.SelectionDraggingToolAction; import edu.kpi.pzks.gui.actions.ui.ExitAction; import edu.kpi.pzks.gui.actions.ui.OpenAction; import edu.kpi.pzks.gui.actions.ui.SaveAsAction; import edu.kpi.pzks.gui.utils.CONSTANTS; import edu.kpi.pzks.gui.utils.STRINGS; import edu.kpi.pzks.gui.utils.Utils; import javax.swing.*; import java.awt.*; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Aloren */ public class MainFrame extends JFrame { private final int TOOLBAR_ORIENTATION = JToolBar.HORIZONTAL; protected GraphPanel systemPanel; protected GraphPanel taskPanel; protected final OpenAction openAction = new OpenAction(this); protected final SaveAsAction saveAsAction = new SaveAsAction(this); protected final ExitAction exitAction = new ExitAction(this); protected final GenTaskGraphAction genTaskGraphAction = new GenTaskGraphAction(this); public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } MainFrame frame = new MainFrame(STRINGS.MAIN_TITLE); frame.setVisible(true); } public MainFrame(String title) { super(title); setComponents(); setSizeAndPosition(); } protected JMenuBar getMainMenuBar() { JMenuBar bar = new JMenuBar(); bar.add(getFileMenu()); bar.add(getModelingMenu()); bar.add(getStatisticMenu()); bar.add(getHelpMenu()); return bar; } protected JMenu getModelingMenu() { JMenu modelingMenu = new JMenu(STRINGS.MODELING_MENU); return modelingMenu; } protected JMenu getStatisticMenu() { JMenu statisticMenu = new JMenu(STRINGS.STATISTIC_MENU); return statisticMenu; } protected JMenu getHelpMenu() { JMenu helpMenu = new JMenu(STRINGS.HELP_MENU); return helpMenu; } protected JMenu getFileMenu() { JMenu fileMenu = new JMenu(STRINGS.FILE_MENU); JMenuItem openMenuItem = new JMenuItem(openAction); openMenuItem.setText(STRINGS.OPEN); JMenuItem saveAsMenuItem = new JMenuItem(saveAsAction); saveAsMenuItem.setText(STRINGS.SAVE); JMenuItem exitMenuItem = new JMenuItem(exitAction); exitMenuItem.setText(STRINGS.EXIT); fileMenu.add(openMenuItem); fileMenu.add(saveAsMenuItem); fileMenu.add(exitMenuItem); return fileMenu; } protected JToolBar getToolBar(int orientation) { JToolBar toolBar = new JToolBar(orientation); toolBar.setFloatable(false); ImageIcon openIcon = Utils.createImageIcon(CONSTANTS.iconsPath + "/open.png"); JButton openButton = new JButton(openAction); openButton.setIcon(openIcon); openButton.setToolTipText(STRINGS.OPEN); ImageIcon saveIcon = Utils.createImageIcon(CONSTANTS.iconsPath + "/save.png"); JButton saveButton = new JButton(saveAsAction); saveButton.setIcon(saveIcon); saveButton.setToolTipText(STRINGS.SAVE); ImageIcon taskIcon = Utils.createImageIcon(CONSTANTS.iconsPath + "/task.png"); JButton genTaskGraphButton = new JButton(genTaskGraphAction); genTaskGraphButton.setIcon(taskIcon); genTaskGraphButton.setToolTipText(STRINGS.GEN_TASK_GRAPH); // ImageIcon systemIcon = Utils.createImageIcon(CONSTANTS.iconsPath + "/system.png"); // JButton genSystemGraphButton = new JButton(systemIcon); // genSystemGraphButton.setToolTipText(STRINGS.GEN_SYSTEM_GRAPH); ImageIcon nodeIcon = Utils.createImageIcon(CONSTANTS.iconsPath + "/node.png"); JButton newNodeButton = new JButton(new NodeCreationToolAction(this)); newNodeButton.setIcon(nodeIcon); ImageIcon linkIcon = Utils.createImageIcon(CONSTANTS.iconsPath + "/link.png"); JButton newLinkButton = new JButton(new LinkCreationToolAction(this)); newLinkButton.setIcon(linkIcon); ImageIcon selectIcon = Utils.createImageIcon(CONSTANTS.iconsPath + "/select.png"); JButton selectButton = new JButton(new SelectionDraggingToolAction(this)); selectButton.setIcon(selectIcon); ImageIcon removeIcon = Utils.createImageIcon(CONSTANTS.iconsPath + "/remove.png"); JButton removeButton = new JButton(new RemoveAction(this)); removeButton.setIcon(removeIcon); toolBar.add(openButton); toolBar.add(saveButton); toolBar.addSeparator(); toolBar.add(newNodeButton); toolBar.add(newLinkButton); toolBar.add(selectButton); toolBar.add(removeButton); toolBar.addSeparator(); toolBar.add(genTaskGraphButton); // toolBar.add(genSystemGraphButton); toolBar.addSeparator(); return toolBar; } protected Container getMainPane(JPanel taskPanel, JPanel systemPanel) { JSplitPane pane = new JSplitPane(); JScrollPane taskPane = new JScrollPane(); taskPane.setViewportView(taskPanel); pane.setLeftComponent(taskPane); JScrollPane systemPane = new JScrollPane(); systemPane.setViewportView(systemPanel); pane.setRightComponent(systemPane); return pane; } protected GraphPanel createTaskPanel() { GraphPanel localTaskPanel = new TaskPanel(); localTaskPanel.setName("taskPanel"); localTaskPanel.setBorder(BorderFactory.createTitledBorder(STRINGS.TASK_GRAPH)); localTaskPanel.addValidator(new CyclingValidator()); return localTaskPanel; } protected GraphPanel createSystemPanel() { GraphPanel localSystemPanel = new SystemPanel(); localSystemPanel.setName("systemPanel"); localSystemPanel.setBorder(BorderFactory.createTitledBorder(STRINGS.SYSTEM_GRAPH)); localSystemPanel.addValidator(new ConsistencyValidator()); localSystemPanel.addValidator(new SubGraphValidator()); return localSystemPanel; } public GraphPanel getSystemPanel() { return systemPanel; } public GraphPanel getTaskPanel() { return taskPanel; } protected void setComponents() { this.taskPanel = createTaskPanel(); this.systemPanel = createSystemPanel(); setJMenuBar(getMainMenuBar()); add(getToolBar(TOOLBAR_ORIENTATION), BorderLayout.NORTH); add(getMainPane(taskPanel, systemPanel), BorderLayout.CENTER); } protected void setSizeAndPosition() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setLocationRelativeTo(null); } }
true
cf9f476fba4b3e4579d7425d1a62b36b98861b33
Java
Chevron94/NetCrackerGames
/gamepub/webapp/src/main/java/gamepub/encode/shaCode.java
UTF-8
836
2.28125
2
[]
no_license
/* * 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 gamepub.encode; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.servlet.ServletException; /** * * @author fitok */ public class shaCode { public static String code(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException{ String result=""; MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(str.getBytes("UTF-8")); byte[] digest = md.digest(); result = String.format("%064x", new BigInteger(1,digest)); return result; } }
true
b5857fa13de4d60e2ebd40a43ef4c2c77e9b35df
Java
sculs/Team-Work
/team/GameRunner.java
UTF-8
6,702
3.421875
3
[]
no_license
package team; import java.util.Scanner; import java.util.concurrent.TimeUnit; public class GameRunner { public static final Scanner sc = new Scanner(System.in); public static void main(String[] args) { new GameRunner().run(); } private void run() { /////// Preface for new variables, Objects, etc.////////////////////// System.out.println("---------------------------------------"); System.out.println("Welcome to BLACKJACK created by Team 2!"); System.out.println("---------------------------------------"); Game game = new Game(); Player play = new Player(); Player[] players = play.multiPlayers(); /// multi players; Player dealer = new Player("Dealer"); int numberOfPlayers = players.length; boolean oneDone = false; boolean dealerDone = false; int money[] = new int[numberOfPlayers]; int bet[] = new int[numberOfPlayers]; int points[] = new int[numberOfPlayers]; for (int i = 0; i < numberOfPlayers; i++) money[i] = 100; Deck theDeck = new Deck(); //////// The Game Starts!!! /////////////////////////////////////////////////// for (;;){ // Loop here is prepared for additional rounds; //------------------------------------------------------------------------------- // Firstly, Request for options of individual bet; for (int i = 0; i < numberOfPlayers; i++) { System.out.println("\n" + players[i].getName() + ", Bet amount(You have " +money[i] + "$):" + "\nNo bet? press \"ENTER\":"); String answer1 = sc.nextLine(); while (!game.checkNumber(answer1)) { answer1 = sc.nextLine(); } bet[i] = answer1.equals("") ? 0 : Integer.parseInt(answer1); bet[i] = game.bet(money[i], bet[i]); money[i] -= bet[i]; } //------------------------------------------------------------------------------- // Secondly, Hand out first two cards for all players & the dealer; for (int i = 0; i < numberOfPlayers; i++) { players[i].addCard(theDeck.dealNextCard(theDeck)); players[i].addCard(theDeck.dealNextCard(theDeck)); } dealer.addCard(theDeck.dealNextCard(theDeck)); dealer.addCard(theDeck.dealNextCard(theDeck)); System.out.print ("\nAll set! Game starts in "); game.countDown(3); // And show both cards of all players, one card of the dealer; System.out.println("\n---------------------------------------\n"); System.out.println("Cards are dealt\n"); for (int i = 0; i < numberOfPlayers; i++) { players[i].printHand(players[i].getName(), true); System.out.printf("Total points: %s%n%n", players[i].getSum()); game.pause(2); } dealer.printHand(dealer.getName(), false); System.out.println("Total points are hidden\n"); game.pause(2); //------------------------------------------------------------------------------- // Thirdly, each player HIT/STAY respectively, then dealer process afterwards; for (int i = 0; i < numberOfPlayers; i++) { players[i].printHand(players[i].getName(), true); System.out.println("Total points are: " + players[i].getSum() + "\n"); while (!oneDone) { oneDone = game.playerTurn(players[i]); points[i] = players[i].getSum(); } if (i < numberOfPlayers - 1) oneDone = false; } dealer.printHand(dealer.getName(), true); System.out.println("Total for dealer: " + dealer.getSum() + "\n"); while (!dealerDone) { Boolean allPlayerBusted = false; for (int point : points) { if (point > 21) allPlayerBusted = true; else { allPlayerBusted = false; break; } } if (allPlayerBusted){ dealerDone = true; System.out.println("The dealer stays!\n"); dealer.printHand(dealer.getName(), true); System.out.println("Total for dealer: " + dealer.getSum()); } else dealerDone = game.dealerTurn(dealer); } //------------------------------------------------------------------------------- // Finally, print all cards; System.out.println("\n---------------------------------------\n"); System.out.println("RESULT:"); int dealerSum = dealer.getSum(); System.out.println("Total for dealer: " + dealerSum + "\n"); for (int i = 0; i < numberOfPlayers; i++) { int oneSum = players[i].getSum(); System.out.printf("Total for %s: %s%n", players[i].getName(), oneSum); // player always wins if he/she got BLACKJACK! if (oneSum == 21 && players[i].getNumCards() == 2) { System.out.printf("%s wins against the dealer with BLACKJACK!%n", players[i].getName()); money[i] += 4 * bet[i]; } // player wins when his points below 21 and higher and the dealer, or dealer busted; else if ((oneSum > dealerSum && oneSum <= 21) || dealerSum > 21) { System.out.printf("%s wins against the dealer!%n", players[i].getName()); money[i] += 2 * bet[i]; } // (oneSum <= dealerSum || oneSum > 21) && dealerSum <= 21 else { System.out.println("Dealer wins against " + players[i].getName()); } System.out.println(players[i].getName() + "'s actual stack: " +money[i] + "$\n"); game.pause(2); } //------------------------------------------------------------------------------- //// Function 2: Ask players about next round; if (game.nextRound()) { oneDone = dealerDone = false; for (Player p : players) p.empty(); dealer.empty(); theDeck = new Deck(); } else System.exit(0); } //// End of additional round loop; } }
true
eb843a9b9749762164afe47efeca59b0e7c03b31
Java
Solopie/Five-in-a-Row
/PlayerOne.java
UTF-8
216
2.6875
3
[]
no_license
class PlayerOne extends Player{ public PlayerOne() { playerID = 1; } void drawShape(int x, int y) { line(x, y, x + Cell.SIZE,y + Cell.SIZE); line(x + Cell.SIZE, y, x, y + Cell.SIZE); } }
true
42e94cea884cd0773ad120cf7b3bac1da9f4bc4b
Java
x3chaos/WegBot
/src/org/x3chaos/WegBot/utils/TweetUtils.java
UTF-8
6,464
3.265625
3
[]
no_license
/* * Author: Shawn Lutch * Project: MarkovBot * Description: Generates pseudo-random text, given my tweets * * Class: org.x3chaos.MarkovBot.TweetUtils * Description: Several static util methods for processing tweets */ package org.x3chaos.WegBot.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.x3chaos.WegBot.utils.TweetFormat; import twitter4j.Status; public class TweetUtils { public static List<String> extractText(List<Status> statuses) { int entries = statuses.size(); List<String> result = new ArrayList<>(entries); for (int i = 0; i < entries; i++) { String text = statuses.get(i).getText(); result.add(text); } return result; } public static void printList(List<String> list) { for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } } public static List<String> getFirstWords(List<String> statuses) { List<String> result = new ArrayList<>(); for (int i = 0; i < statuses.size(); i++) { String status = statuses.get(i); result.add(getFirstWord(status)); } return result; } private static String getFirstWord(String line) { return line.split(" ")[0]; } public static List<String> formatLines(List<String> lines) { List<String> result = new ArrayList<>(); for (int i = 0; i < lines.size(); i++) { String origLine = lines.get(i); result.add(formatLine(origLine)); } return result; } private static String formatLine(String line) { String result; // strip whitespace Pattern whitespace = Pattern.compile("\\s+"); Matcher matcher = whitespace.matcher(line); result = matcher.replaceAll(" "); return result; } public static String getRandomWord(List<String> words) { int random = new Random().nextInt(words.size()); return words.get(random); } /* IMPORTANT STUFF BELOW */ /** * Processes a list of Strings and returns a HashMap that is structured as * such: * * KEY: STRING word1<br /> * VALUE: LIST { nextword1, nextword2, ... , nextwordN } * * This HashMap contains information about each word that can be found in * the list of Strings that is passed to the method. * * @param statuses The list of Strings to use * @return a HashMap containing lists of words that follow other words */ public static HashMap<String, List<String>> markov(List<String> statuses) { HashMap<String, List<String>> result = new HashMap<>(); for (int s = 0; s < statuses.size(); s++) { String status = statuses.get(s); // split the status into words at ANY WHITESPACE // ( this regex is shorthand for [\\t\\n\\x0B\\f\\r] ) String[] words = status.split("\\s+"); for (int w = 0; w < words.length - 1; w++) { String word = words[w]; String nextWord = words[w + 1]; if (!isAcceptable(word) || !isAcceptable(nextWord)) continue; String key1 = TweetFormat.hashMapKey(word); String key2 = TweetFormat.hashMapKey(nextWord); if (key1.equals("") || key2.equals("")) continue; // get the following words, or new list if null List<String> followingWords = result.get(key1); if (followingWords == null) followingWords = new ArrayList<>(); // add to the list and put it back followingWords.add(nextWord); result.put(key1, followingWords); } // done with each word! } // done with each status! return result; } public static String createTweet(List<String> statuses) { StringBuilder result = new StringBuilder(); // get first words List<String> firstWords = getFirstWords(statuses); // pick a random first word String firstWord; do { firstWord = getRandomWord(firstWords); } while (!isAcceptable(firstWord)); result.append(firstWord).append(" "); // GO FROM THERE, BUD HashMap<String, List<String>> markov = markov(statuses); // DON'T STOP TIL YOU HIT 140 CHARS // or, y'know, you wind up using what was the last word in a tweet int chars = 0, tries = 0, words = 0; String lastWord = firstWord; do { List<String> possibles = markov.get(lastWord); if (possibles == null) { if (words <= 3) { // reset the loop with a new first word lastWord = getRandomWord(firstWords); continue; } else { // eh just forget it break; } } String randomWord = getRandomWord(possibles); if (isLink(randomWord)) { // don't let it link pls, that's bannable tries++; if (tries >= 3) break; else continue; } chars += (randomWord.length() + 1); // don't forget about the space! if (chars <= 140) { result.append(randomWord).append(" "); words++; } lastWord = randomWord; } while (chars <= 140); return result.toString(); } private static boolean isAcceptable(String word) { return !isLink(word) && !isMention(word) && !isRT(word); } private static boolean isMention(String word) { return word.startsWith("@"); } private static boolean isRT(String word) { return word.startsWith("RT"); } private static boolean isLink(String word) { return word.startsWith("http"); } }
true
31ecc7ea0b283be8c5a25a13ed0382c9bcc6d88d
Java
Pragmatism0220/Kira
/app/src/main/java/com/moemoe/lalala/view/activity/CommonUseActivity.java
UTF-8
3,675
1.875
2
[ "Apache-2.0" ]
permissive
package com.moemoe.lalala.view.activity; import android.content.DialogInterface; import android.databinding.DataBindingUtil; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.google.android.exoplayer2.C; import com.moemoe.lalala.R; import com.moemoe.lalala.databinding.ActivityCommonUseBinding; import com.moemoe.lalala.dialog.AlertDialog; import com.moemoe.lalala.utils.CommonLoadingTask; import com.moemoe.lalala.utils.FileUtil; import com.moemoe.lalala.utils.NoDoubleClickListener; import com.moemoe.lalala.view.base.BaseActivity; public class CommonUseActivity extends BaseActivity { private ActivityCommonUseBinding binding; private TextView mTvTitle; private ImageView mIvBack; @Override protected void initComponent() { binding = DataBindingUtil.setContentView(this, R.layout.activity_common_use); binding.setPresenter(new Presenter()); mTvTitle = findViewById(R.id.tv_toolbar_title); mIvBack = findViewById(R.id.iv_back); } @Override protected void initViews(Bundle savedInstanceState) { } @Override protected void initToolbar(Bundle savedInstanceState) { mTvTitle.setText(R.string.common); mTvTitle.setTextColor(getResources().getColor(R.color.black)); mIvBack.setVisibility(View.VISIBLE); mIvBack.setImageResource(R.drawable.btn_back_black_normal); mIvBack.setOnClickListener(new NoDoubleClickListener() { @Override public void onNoDoubleClick(View v) { finish(); } }); } @Override protected void initListeners() { } @Override protected void initData() { } private TextView getFunDetailTv(View v){ return (TextView) v.findViewById(R.id.tv_function_detail); } /** * 清理缓存 */ private void clearCache(){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.a_dlg_title); builder.setMessage(R.string.a_dlg_clear_cache); builder.setPositiveButton(R.string.label_clear, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new CommonLoadingTask(CommonUseActivity.this, new CommonLoadingTask.TaskCallback() { @Override public Object processDataInBackground() { return FileUtil.clearAllCache(CommonUseActivity.this); } @Override public void handleData(Object o) { TextView funDetailTv = getFunDetailTv(CommonUseActivity.this.findViewById(R.id.set_clear_cache)); funDetailTv.setText(""); funDetailTv.setVisibility(View.INVISIBLE); showToast(R.string.msg_clear_cache_succ_with_size); } }, null).execute(); } }); builder.setNegativeButton(R.string.label_cancel, null); try { builder.show(); } catch (Exception e) { e.printStackTrace(); } } public class Presenter { public void onClick(View view) { switch (view.getId()) { case R.id.wifi_item: break; case R.id.up_data_number_item: break; case R.id.clean_item: break; } } } }
true
15cf6b597a077c94a9ed4bebd485f0fe8a8fdb44
Java
luizpatroclos/projects
/epec4/commons-epec-ejb/ejbModule/br/gov/inpi/epec/beans/Tbclassificacao.java
UTF-8
3,280
2
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.gov.inpi.epec.beans; import java.io.Serializable; import java.util.List; import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author lasilva */ @Entity @Table(name = "TBCLASSIFICACAO") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Tbclassificacao.findAll", query = "SELECT t FROM Tbclassificacao t order by t.txClassificacao"), @NamedQuery(name = "Tbclassificacao.findByIdClassificacao", query = "SELECT t FROM Tbclassificacao t WHERE t.idClassificacao = :idClassificacao"), @NamedQuery(name = "Tbclassificacao.findByTxClassificacao", query = "SELECT t FROM Tbclassificacao t WHERE t.txClassificacao = :txClassificacao")}) public class Tbclassificacao implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID_CLASSIFICACAO") private Long idClassificacao; @Column(name = "TX_CLASSIFICACAO") private String txClassificacao; @OneToMany(cascade = CascadeType.ALL, mappedBy = "tbclassificacao") private List<Tbclassificacaopatente> tbclassificacaopatenteList; @Transient private long ordem; public Tbclassificacao() { } public Tbclassificacao(Long idClassificacao) { this.idClassificacao = idClassificacao; } public Long getIdClassificacao() { return idClassificacao; } public void setIdClassificacao(Long idClassificacao) { this.idClassificacao = idClassificacao; } public String getTxClassificacao() { return txClassificacao; } public void setTxClassificacao(String txClassificacao) { this.txClassificacao = txClassificacao; } @XmlTransient public List<Tbclassificacaopatente> getTbclassificacaopatenteList() { return tbclassificacaopatenteList; } public void setTbclassificacaopatenteList(List<Tbclassificacaopatente> tbclassificacaopatenteList) { this.tbclassificacaopatenteList = tbclassificacaopatenteList; } @Override public int hashCode() { int hash = 0; hash += (idClassificacao != null ? idClassificacao.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Tbclassificacao)) { return false; } Tbclassificacao other = (Tbclassificacao) object; if ((this.idClassificacao == null && other.idClassificacao != null) || (this.idClassificacao != null && !this.idClassificacao.equals(other.idClassificacao))) { return false; } return true; } @Override public String toString() { return "br.gov.inpi.epec.beans.Tbclassificacao[ idClassificacao=" + idClassificacao + " ]"; } public long getOrdem() { return ordem; } public void setOrdem(long ordem) { this.ordem = ordem; } }
true
faebf39d4cab23c3f7ac5046b9810c746a5b2074
Java
Christianhoej/FlexicuV2
/app/src/main/java/com/example/chris/flexicuv2/startskærm/indbakke/forhandling/Forhandling_indhold.java
UTF-8
24,828
1.8125
2
[]
no_license
package com.example.chris.flexicuv2.startskærm.indbakke.forhandling; import android.app.DatePickerDialog; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CompoundButton; import android.widget.DatePicker; import android.widget.EditText; import android.widget.Switch; import android.widget.TextView; import com.example.chris.flexicuv2.Bekraeftelse_aftale_indgået_fragment; import com.example.chris.flexicuv2.Bekraeftelse_bud_medarbejder_fragment; import com.example.chris.flexicuv2.R; import com.example.chris.flexicuv2.database.DBManager; import com.example.chris.flexicuv2.model.Aftale; import com.example.chris.flexicuv2.model.Forhandling; import com.example.chris.flexicuv2.model.Singleton; import java.text.DecimalFormat; import java.util.Calendar; /** * A simple {@link Fragment} subclass. */ public class Forhandling_indhold extends Fragment implements View.OnClickListener, Forhandling_presenter.UpdateForhandling, CompoundButton.OnCheckedChangeListener { private Singleton singleton; private DBManager dbManager; private Bekraeftelse_bud_medarbejder_fragment bekræftelse; private Bekraeftelse_aftale_indgået_fragment bekræft_aftale; private Calendar c1; private Calendar c2; private DatePickerDialog.OnDateSetListener datepickerListener; private DatePickerDialog datepickerdialog; //Redigerbar private TextView startdato_redigerTV, slutdato_redigerTV, antalArbejdsdage_redigerTV, subtotalen_redigerTV, flexicugebyr_redigerTV, totalprisen_redigerTV; private EditText timepris_redigerET; private Switch egetVærktøj_rediger_switch; //Faste private TextView startdato_fastTV, slutdato_fastTV, antalArbejdsdage_fastTV, timePris_fastTV, subtotalen_fastTV, flexicugebyr_fastTV, totalprisen_fastTV; private TextView egetVærktøj_fast_switch; private Button anullerButton, accepter_sendTilbud_Button, kommentarButton; private Forhandling_presenter presenter; private TextView startdatoET, slutdatoET, timepris; public Forhandling_indhold() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.forhandling_indhold_fragment, container, false); singleton = Singleton.getInstance(); dbManager = new DBManager(); bekræftelse = new Bekraeftelse_bud_medarbejder_fragment(); bekræft_aftale = new Bekraeftelse_aftale_indgået_fragment(); presenter = new Forhandling_presenter(this); c1 = Calendar.getInstance(); c2 = Calendar.getInstance(); TextView udlejerNavn = v.findViewById(R.id.forhandling_udlejer_navn_textview); udlejerNavn.setText(singleton.midlertidigAftale.getUdlejer().getVirksomhedsnavn()); TextView lejerNavn = v.findViewById(R.id.forhandling_lejer_navn_textview); lejerNavn.setText(singleton.midlertidigForhandling.getLejer().getVirksomhedsnavn()); TextView medarbejderNavnTV = v.findViewById(R.id.forhandling_medarbejder); medarbejderNavnTV.setText(singleton.midlertidigForhandling.getMedarbejder().getNavn()); TextView titel_fastTV = v.findViewById(R.id.forhandling_lejer_udlejer_fast_textview); TextView titel_redigerTV = v.findViewById(R.id.forhandling_lejer_udlejer_rediger_textview); TextView overskrift_TV = v.findViewById(R.id.forhandling_overskrift); //Fastlagt //Dato startdato_fastTV = v.findViewById(R.id.forhandling_startdato_fast_textview); slutdato_fastTV = v.findViewById(R.id.forhandling_slutdato_fast_textview); //Arbejdsdage antalArbejdsdage_fastTV = v.findViewById(R.id.forhandling_antal_arbejdsdage_fast_textview); //Prisen timePris_fastTV = v.findViewById(R.id.forhandling_timepris_fast_textview); subtotalen_fastTV = v.findViewById(R.id.forhandling_subtotalen_excl_flexicuspris_fast_textview); flexicugebyr_fastTV = v.findViewById(R.id.forhandling_flexicu_pris_fest_textview); totalprisen_fastTV = v.findViewById(R.id.forhandling_total_pris_fast_textview); //Eget værktøj egetVærktøj_fast_switch = v.findViewById(R.id.forhandling_egetværktøj_fast_textview); //Rediger //Dato startdato_redigerTV = v.findViewById(R.id.forhandling_startdato_rediger_textview); startdato_redigerTV.setOnClickListener(this); slutdato_redigerTV = v.findViewById(R.id.forhandling_slutdato_rediger_textview); slutdato_redigerTV.setOnClickListener(this); //Arbejdsdage antalArbejdsdage_redigerTV = v.findViewById(R.id.forhandling_antal_arbejdsdage_rediger_textview); //Pris timepris_redigerET = v.findViewById(R.id.forhandling_timepris_rediger_editview); timepris_redigerET.addTextChangedListener(prisTextWatch); timepris_redigerET.addTextChangedListener(erAltEnsTextWatcher); subtotalen_redigerTV = v.findViewById(R.id.forhandling_subtotalen_excl_flexicuspris_rediger_textview); flexicugebyr_redigerTV = v.findViewById(R.id.forhandling_flexicu_pris_rediger_textview); totalprisen_redigerTV = v.findViewById(R.id.forhandling_total_pris_rediger_textview); //presenter.udregnPriser(Integer.parseInt(singleton.midlertidigAftale.getUdlejPris()), Integer.parseInt(antalArbejdsdage_lejerTV.getText().toString()), 7.4, true); slutdato_redigerTV.addTextChangedListener(arbDageTextWatcher); slutdato_redigerTV.addTextChangedListener(slutDatoTextWatcher); slutdato_redigerTV.addTextChangedListener(erAltEnsTextWatcher); startdato_redigerTV.addTextChangedListener(erAltEnsTextWatcher); startdato_redigerTV.addTextChangedListener(startDatoTextWatcher); //Eget værktøj egetVærktøj_rediger_switch = v.findViewById(R.id.forhandling_egetværktøj_rediger_switch); egetVærktøj_rediger_switch.setOnCheckedChangeListener(this); egetVærktøj_rediger_switch.addTextChangedListener(erAltEnsTextWatcher); anullerButton = v.findViewById(R.id.forhandling_annuller_button); anullerButton.setOnClickListener(this); accepter_sendTilbud_Button = v.findViewById(R.id.forhandling_send_eller_accepter_tilbud_button); accepter_sendTilbud_Button.setOnClickListener(this); //kommentarButton = v.findViewById(R.id.forhandling_tilføj_besked_button); //kommentarButton.setOnClickListener(this); startdatoET = v.findViewById(R.id.forhandling_startdato_rediger_textview); startdatoET.setOnClickListener(this); slutdatoET = v.findViewById(R.id.forhandling_slutdato_rediger_textview); slutdatoET.setOnClickListener(this); timepris = v.findViewById(R.id.forhandling_timepris_rediger_editview); //Hvis lejer har redigeret sidst: if(singleton.midlertidigForhandling.getSidstSendtAftale().getBrugerID().equals(singleton.midlertidigForhandling.getLejer().getBrugerID())){ presenter.updateFaste(true, singleton.midlertidigForhandling.getLejerStartDato(), singleton.midlertidigForhandling.getLejerSlutDato(), singleton.midlertidigForhandling.getLejPris(), singleton.midlertidigForhandling.isLejEgetVærktøj()); presenter.updateRediger(false,singleton.midlertidigForhandling.getUdlejerStartDato(), singleton.midlertidigForhandling.getUdlejerSlutDato(), singleton.midlertidigForhandling.getUdlejPris(), singleton.midlertidigForhandling.isUdlejEgetVærktøj()); titel_fastTV.setText("Lejer"); titel_redigerTV.setText("Udlejer"); overskrift_TV.setText("Udlej medarbejder"); } else{ presenter.updateFaste(false,singleton.midlertidigForhandling.getUdlejerStartDato(), singleton.midlertidigForhandling.getUdlejerSlutDato(), singleton.midlertidigForhandling.getUdlejPris(), singleton.midlertidigForhandling.isUdlejEgetVærktøj()); presenter.updateRediger(true,singleton.midlertidigForhandling.getLejerStartDato(), singleton.midlertidigForhandling.getLejerSlutDato(), singleton.midlertidigForhandling.getLejPris(), singleton.midlertidigForhandling.isLejEgetVærktøj()); titel_fastTV.setText("Udlejer"); titel_redigerTV.setText("Lejer"); overskrift_TV.setText("Lej medarbejder"); } presenter.updateKnap(singleton.midlertidigForhandling.getLejerStartDato(), singleton.midlertidigForhandling.getLejerSlutDato(), singleton.midlertidigForhandling.getLejPris(), singleton.midlertidigForhandling.isLejEgetVærktøj(), singleton.midlertidigForhandling.getUdlejerStartDato(), singleton.midlertidigForhandling.getUdlejerSlutDato(), singleton.midlertidigForhandling.getUdlejPris(), singleton.midlertidigForhandling.isUdlejEgetVærktøj()); return v; } @Override public void onClick(View v) { switch (v.getId()){ case R.id.forhandling_send_eller_accepter_tilbud_button: int pris = 0; if(!timepris_redigerET.getText().toString().equals("")){ pris = Integer.parseInt(timepris_redigerET.getText().toString()); } int arbDage = 0; if (antalArbejdsdage_redigerTV.getText().equals("antal arb. dage")) { arbDage = 0; }else arbDage = Integer.parseInt(antalArbejdsdage_redigerTV.getText().toString()); if (presenter.checkKorrektUdfyldtInformation(startdatoET.getText().toString(), slutdatoET.getText().toString(), arbDage, pris)) { Forhandling forhandling = singleton.midlertidigForhandling; if(singleton.midlertidigForhandling.getSidstSendtAftale().getBrugerID().equals(singleton.midlertidigForhandling.getLejer().getBrugerID())){ //Jeg er udlejer if(singleton.midlertidigForhandling.getUdlejKommentar()!=null){ forhandling.setUdlejKommentar(singleton.midlertidigForhandling.getUdlejKommentar()); } forhandling.setUdlejPris(timepris_redigerET.getText().toString()); forhandling.setUdlejEgetVærktøj(egetVærktøj_rediger_switch.isChecked()); forhandling.setUdlejerSlutDato(slutdato_redigerTV.getText().toString()); forhandling.setUdlejerStartDato(startdato_redigerTV.getText().toString()); } else{ //Jeg er lejer if(singleton.midlertidigForhandling.getLejKommentar()!=null){ forhandling.setLejKommentar(singleton.midlertidigForhandling.getLejKommentar()); } forhandling.setLejPris(timepris_redigerET.getText().toString()); forhandling.setLejEgetVærktøj(egetVærktøj_rediger_switch.isChecked()); forhandling.setLejerSlutDato(slutdato_redigerTV.getText().toString()); forhandling.setLejerStartDato(startdato_redigerTV.getText().toString()); } forhandling.setSidstSendtAftale(singleton.getBruger()); //Få index af aktuelle aftale int indexAftale = 0; for(Aftale aftale : singleton.getAlleMineAftalerMedForhandling()){ if(aftale.getAftaleID().equals(forhandling.getAftaleID())){ indexAftale = singleton.getAlleMineAftalerMedForhandling().indexOf(aftale); break; } } int indexForhandling = 0; for(Forhandling forhandling1 : singleton.getAlleMineAftalerMedForhandling().get(indexAftale).getForhandlinger()){ if(forhandling1.getForhandlingID().equals(forhandling.getForhandlingID())){ indexForhandling = singleton.getAlleMineAftalerMedForhandling().get(indexAftale).getForhandlinger().indexOf(forhandling1); } } if(accepter_sendTilbud_Button.getText().toString().equals("Godkend")){ forhandling.setAftaleIndgået(true); forhandling.setAktiv(false); singleton.getAlleMineAftalerMedForhandling().get(indexAftale).getForhandlinger().set(indexForhandling, forhandling); dbManager.updateIndgåetAftale(singleton.getAlleMineAftalerMedForhandling().get(indexAftale),forhandling); setFragment(bekræft_aftale); } else { singleton.getAlleMineAftalerMedForhandling().get(indexAftale).getForhandlinger().set(indexForhandling, forhandling); forhandling.setAftaleIndgået(false); forhandling.setAktiv(false); dbManager.updateForhandling(forhandling); setFragment(bekræftelse); } } break; case R.id.forhandling_annuller_button: getActivity().getSupportFragmentManager().popBackStack(); break; case R.id.forhandling_slutdato_rediger_textview: findEnDato(false, R.id.forhandling_slutdato_rediger_textview, c2); break; case R.id.forhandling_startdato_rediger_textview: findEnDato(true, R.id.forhandling_startdato_rediger_textview, c1); break; } } public void setFragment(Fragment fragment) { //startskærmFrameTilDiverse.removeAllViews(); FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.startskærm_frame_til_diverse, fragment); fragmentTransaction.addToBackStack("fragment"); fragmentTransaction.commit(); } private void findEnDato(final boolean start, int id, Calendar c) { datepickerListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { month = month+1; String måned = ""+month; if(month < 10){ måned = "0" + month; } String dag = ""+dayOfMonth; if(dayOfMonth < 10){ dag = "0" + dayOfMonth ; } String s = " " + dag + " / " + måned + " / " + year + " "; if(start) { startdatoET.setText(s); c1.set(year,month-1,dayOfMonth); slutdatoET.setEnabled(true); } else { c2.set(year, month-1,dayOfMonth); slutdatoET.setText(s); } } }; final int år = c.get(Calendar.YEAR); final int måned = c.get(Calendar.MONTH); final int dag = c.get(Calendar.DAY_OF_MONTH); datepickerdialog = new DatePickerDialog(getContext(),datepickerListener,år,måned,dag ); if(c1.getTimeInMillis()>(System.currentTimeMillis()-1000)){ if(id != R.id.udlejning_startdato_textview1) { datepickerdialog.getDatePicker().setMinDate(c1.getTimeInMillis()); } else datepickerdialog.getDatePicker().setMinDate(System.currentTimeMillis()); } else{ datepickerdialog.getDatePicker().setMinDate(System.currentTimeMillis()); } datepickerdialog.show(); } private TextWatcher prisTextWatch = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length()>0 && !(antalArbejdsdage_redigerTV.getText().toString().equals("antal arb. dage"))){ presenter.udregnPriser(Integer.parseInt(s.toString()), Integer.parseInt(antalArbejdsdage_redigerTV.getText().toString()), 7.4, true); } //TODO skal også tjekke om der er værdier i de to datoer } @Override public void afterTextChanged(Editable s) { } }; private TextWatcher arbDageTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { presenter.udregnArbejdsdage(startdato_redigerTV.getText().toString(), slutdato_redigerTV.getText().toString(), true); } @Override public void afterTextChanged(Editable s) { if(!(timepris_redigerET.getText().toString().equals("")) ) presenter.udregnPriser(Integer.parseInt(timepris_redigerET.getText().toString()),Integer.parseInt(antalArbejdsdage_redigerTV.getText().toString()), 7.4, true); } }; private TextWatcher slutDatoTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { //presenter.udregnArbejdsdage(startdatoET.getText().toString(), slutdatoET.getText().toString()); presenter.udregnArbejdsdage(startdato_redigerTV.getText().toString(), slutdato_redigerTV.getText().toString(), true); if(!timepris_redigerET.getText().toString().equals("")) { presenter.udregnPriser(Integer.parseInt(timepris_redigerET.getText().toString()), Integer.parseInt(antalArbejdsdage_redigerTV.getText().toString()), 7.4, true); } } @Override public void afterTextChanged(Editable s) { if(!antalArbejdsdage_redigerTV.getText().toString().equals("0")) { slutdatoET.setError(null); antalArbejdsdage_redigerTV.setError(null); } } }; private TextWatcher startDatoTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(!timepris_redigerET.getText().toString().equals("") && !slutdatoET.getText().toString().equals(" dd / mm / yyyy ")) { presenter.udregnArbejdsdage(startdato_redigerTV.getText().toString(), slutdato_redigerTV.getText().toString(), true); presenter.udregnPriser(Integer.parseInt(timepris_redigerET.getText().toString()), Integer.parseInt(antalArbejdsdage_redigerTV.getText().toString()), 7.4, true); } if(!slutdatoET.getText().toString().equals(" dd / mm / yyyy ")){ presenter.udregnArbejdsdage(startdato_redigerTV.getText().toString(), slutdato_redigerTV.getText().toString(),true); } } @Override public void afterTextChanged(Editable s) { startdatoET.setError(null); } }; private TextWatcher erAltEnsTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if(egetVærktøj_fast_switch.getText().toString().equals("JA")) { presenter.updateKnap(startdato_fastTV.getText().toString(), slutdato_fastTV.getText().toString(), timePris_fastTV.getText().toString(), true, startdato_redigerTV.getText().toString(), slutdato_redigerTV.getText().toString(), timepris_redigerET.getText().toString(), egetVærktøj_rediger_switch.isChecked()); } else { presenter.updateKnap(startdato_fastTV.getText().toString(), slutdato_fastTV.getText().toString(), timePris_fastTV.getText().toString(), false, startdato_redigerTV.getText().toString(), slutdato_redigerTV.getText().toString(), timepris_redigerET.getText().toString(), egetVærktøj_rediger_switch.isChecked()); } } }; @Override public void errorStartdato(String errorMSG) { startdato_redigerTV.setError(errorMSG); } @Override public void errorSlutdato(String errorMSG) { slutdato_redigerTV.setError(errorMSG); } @Override public void errorTimepris(String errorMSG) { timepris_redigerET.setError(errorMSG); } @Override public void errorArbejdsdage(String errorMSG) { antalArbejdsdage_redigerTV.setError(errorMSG); } @Override public void opdaterAntalArbejdsdageRediger(int dage) { antalArbejdsdage_redigerTV.setText(""+dage); } @Override public void opdaterSubtotalRediger(double værdi) { DecimalFormat numberFormat = new DecimalFormat("#.00"); subtotalen_redigerTV.setText(numberFormat.format(værdi) + " dkk"); } @Override public void opdaterFlexicufeeRediger(double værdi) { DecimalFormat numberFormat = new DecimalFormat("#.00"); flexicugebyr_redigerTV.setText(numberFormat.format(værdi) + " dkk"); } @Override public void opdaterTotalRediger(double værdi) { DecimalFormat numberFormat = new DecimalFormat("#.00"); totalprisen_redigerTV.setText(numberFormat.format(værdi) + " dkk"); } @Override public void opdaterStartDatoRediger(String startDato) { startdato_redigerTV.setText(startDato); } @Override public void opdaterSlutDatoRediger(String slutdato) { slutdato_redigerTV.setText(slutdato); } @Override public void opdaterTimePrisRediger(String timepris) { timepris_redigerET.setText(timepris); } @Override public void opdaterEgetVærktøjRediger(String egetVærktøj) { if(egetVærktøj.equals("Ja")) { egetVærktøj_rediger_switch.setChecked(true); egetVærktøj_rediger_switch.setText("Ja"); } else { egetVærktøj_rediger_switch.setChecked(false); egetVærktøj_rediger_switch.setText("Nej"); } } @Override public void opdaterAntalArbejdsdageFast(int dage) { antalArbejdsdage_fastTV.setText(""+dage); } @Override public void opdaterSubtotalFast(double værdi) { DecimalFormat numberFormat = new DecimalFormat("#.00"); subtotalen_fastTV.setText(numberFormat.format(værdi) + " dkk"); } @Override public void opdaterFlexicufeeFast(double værdi) { DecimalFormat numberFormat = new DecimalFormat("#.00"); flexicugebyr_fastTV.setText(numberFormat.format(værdi) + " dkk"); } @Override public void opdaterTotalFast(double værdi) { DecimalFormat numberFormat = new DecimalFormat("#.00"); totalprisen_fastTV.setText(numberFormat.format(værdi) + " dkk"); } @Override public void opdaterStartDatoFast(String startDato) { startdato_fastTV.setText(startDato); } @Override public void opdaterSlutDatoFast(String slutdato) { slutdato_fastTV.setText(slutdato); } @Override public void opdaterTimePrisFast(String timepris) { timePris_fastTV.setText(timepris); } @Override public void opdaterEgetVærktøjFast(String egetVærktøj) { egetVærktøj_fast_switch.setText(egetVærktøj); } @Override public void opdaterKnap(String knapText) { accepter_sendTilbud_Button.setText(knapText); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) egetVærktøj_rediger_switch.setText("Ja"); else egetVærktøj_rediger_switch.setText("Nej"); } }
true
851779416537b67ddcfd22d2522d431be66aeef1
Java
wangyang135/ddd-simple-designer-order
/simple-designer-order-domain/src/main/java/com/screw/domain/order/DesignerOrder.java
UTF-8
6,354
2.28125
2
[]
no_license
package com.screw.domain.order; import com.screw.BusinessException; import com.screw.domain.DomainExceptionMessage; import com.screw.domain.Entity; import com.screw.domain.refund.RefundOrder; import com.screw.domain.refund.RefundOrderFactory; import lombok.Data; import lombok.EqualsAndHashCode; import org.springframework.util.Assert; import java.util.Date; import java.util.function.Consumer; @Data @EqualsAndHashCode(of = {"id"}) public class DesignerOrder implements Entity<DesignerOrder> { private int id; private DesignerOrderState state; private int customerId; private int designerId; private float area; private float expectedAmount; private int estimatedDays; private DesigningProgressReport progressReport; private String abortCause; private float actualPaidAmount; private int feedbackStar; private String feedbackDescription; private Date createdTime; private Date updatedTime; public void measure(float area) { Assert.isTrue(area > 0, "The area must be bigger than 0."); this.state = DesignerOrderWorkflowService.changeState(this.id, state, DesignerOrderState.MEASURED); this.area = area; } public void quote(float amount, int[] estimatedDaysList) { Assert.isTrue(amount > 0, "The price must be bigger than 0."); this.assertEstimatedDaysList(estimatedDaysList); this.state = DesignerOrderWorkflowService.changeState(this.id, state, DesignerOrderState.QUOTED); this.expectedAmount = amount; this.progressReport = DesigningProgressReportFactory.newReport(this, estimatedDaysList); this.estimatedDays = this.progressReport.getEstimatedCompletionDays(); } private void assertEstimatedDaysList(int[] estimatedDaysList) { if (null == estimatedDaysList || estimatedDaysList.length != 4) { throw new IllegalArgumentException("The size of estimatedDaysList must be 4."); } for (int days : estimatedDaysList) { if (days <= 0) { throw new IllegalArgumentException("Each element of estimatedDaysList must be bigger than 0."); } } } public void acceptQuote() { this.state = DesignerOrderWorkflowService.changeState(this.id, state, DesignerOrderState.ACCEPT_QUOTE); } public void rejectQuote() { this.state = DesignerOrderWorkflowService.changeState(this.id, state, DesignerOrderState.REJECT_QUOTE); } public void abort(String cause) { this.state = DesignerOrderWorkflowService.changeState(this.id, state, DesignerOrderState.ABORTED); this.abortCause = cause; } public void pay(float amount) { Assert.isTrue(amount > 0, "The amount must be bigger than 0."); if (!DesignerOrderWorkflowService.canChangeState(state, DesignerOrderState.PAID)) { BusinessException.throwException(DomainExceptionMessage.PAYMENT_NOT_IN_READY_STATE_CODE, DomainExceptionMessage.PAYMENT_NOT_IN_READY_STATE, this.id, this.state); } if (Math.abs(amount - this.expectedAmount) > 0.01) { BusinessException.throwException(DomainExceptionMessage.PAYMENT_NOT_MATCHED_CODE, DomainExceptionMessage.PAYMENT_NOT_MATCHED, this.id, this.expectedAmount, amount); } this.state = DesignerOrderWorkflowService.changeState(this.id, state, DesignerOrderState.PAID); this.actualPaidAmount = amount; // 付款完成后,自动启动进度跟踪 this.progressReport.startup(); } public void requestCompletionForProgressNode(DesigningProgressNodeType nodeType, String achievement) { Assert.notNull(nodeType, "The nodeType can not be null."); Assert.hasText(achievement, "The achievement can not be empty."); this.assertCanUpdateProgress(); this.progressReport.requestCompletionForProgressNode(nodeType, achievement); } public void confirmCompletionForProgressNode(DesigningProgressNodeType nodeType) { this.assertCanUpdateProgress(); this.progressReport.confirmCompletionForProgressNode(nodeType); } private void assertCanUpdateProgress() { if (this.state != DesignerOrderState.PAID) { BusinessException.throwException(DomainExceptionMessage.PROGRESS_UPDATE_FAILED_FOR_ERROR_STATE_CODE, DomainExceptionMessage.PROGRESS_UPDATE_FAILED_FOR_ERROR_STATE, this.id, this.state); } } public RefundOrder refund(String cause) { this.assertCanRefund(); this.state = DesignerOrderWorkflowService.changeState(this.id, state, DesignerOrderState.REFUND); return RefundOrderFactory.newRefundOrder(this, cause); } private void assertCanRefund() { DesigningProgressNode constructionDrawingDesignNode = this.progressReport.getNode(DesigningProgressNodeType.CONSTRUCTION_DRAWING_DESIGN); if (constructionDrawingDesignNode.getState() == DesigningProgressNodeState.REQUEST_COMPLETION || constructionDrawingDesignNode.getState() == DesigningProgressNodeState.CONFIRM_COMPLETION) { BusinessException.throwException(DomainExceptionMessage.FAILED_TO_REFUND_FOR_PROGRESS_CODE, DomainExceptionMessage.FAILED_TO_REFUND_FOR_PROGRESS, this.id); } } public void complete() { this.state = DesignerOrderWorkflowService.changeState(this.id, state, DesignerOrderState.COMPLETION); } public void feedback(int star, String description) { Assert.isTrue(star > 0 && star <= 5, "The star must between 1 and 5."); Assert.hasText(description, "The description can not be empty."); this.state = DesignerOrderWorkflowService.changeState(this.id, state, DesignerOrderState.FEEDBACK); this.feedbackStar = star; this.feedbackDescription = description; } @Override public boolean sameIdentityAs(DesignerOrder other) { return this.equals(other); } private void changeStateWithAction(Consumer<DesignerOrder> action, DesignerOrderState nextState) { DesignerOrderState currentState = this.state; try { action.accept(this); this.state = DesignerOrderWorkflowService.changeState(this.id, this.state, nextState); } catch (Exception ex) { this.state = currentState; } } }
true
f5aff81936e87ddb1166d283d0424ff31228747f
Java
Thalyta-dev/ManageClass
/src/main/java/com/manageclass/ManageClass/Annotation/ExistCpfValidator.java
UTF-8
1,075
2.359375
2
[]
no_license
package com.manageclass.ManageClass.Annotation; import com.manageclass.ManageClass.Student.Student; import com.manageclass.ManageClass.Student.StudentRepository; import com.manageclass.ManageClass.Teacher.Teacher; import com.manageclass.ManageClass.Teacher.TeacherRepository; import org.springframework.beans.factory.annotation.Autowired; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.Optional; public class ExistCpfValidator implements ConstraintValidator<ExistCpf,String> { @Override public void initialize(ExistCpf constraintAnnotation) { } @Autowired private StudentRepository studentRepository; @Autowired private TeacherRepository teacherRepository; @Override public boolean isValid(String cpf, ConstraintValidatorContext constraintValidatorContext) { Optional<Student> student = studentRepository.findByCpf(cpf); Optional<Teacher> teacher = teacherRepository.findByCpf(cpf); return (student.isEmpty() && teacher.isEmpty()); } }
true
4f662de0bee9adc268e8b0b73c42ea8c6e72680e
Java
shangshiwei/bicycle2
/bicycle-service/src/main/java/com/aowin/dao/Bicycle_stationMapper.java
UTF-8
224
1.898438
2
[]
no_license
package com.aowin.dao; import java.util.List; import com.aowin.model.Bicycle_station; public interface Bicycle_stationMapper { /** * 分页查询 * @return */ public List<Bicycle_station> select(); }
true
afe2dbd27cca3a05e40bd3e8dce2ad8a805f5b75
Java
crosart/citylib_plus
/citylib-services/src/main/java/com/citylib/citylibservices/dto/ReservationDto.java
UTF-8
458
1.921875
2
[]
no_license
package com.citylib.citylibservices.dto; import lombok.Data; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; /** * DTO reservation object to retrieve data sent by the frontend service and serve it to the controller. * * @author crosart */ @Data public class ReservationDto { @NotNull @NotEmpty private long bookId; @NotNull @NotEmpty private long userId; }
true
b78a887fde5eb4dc4d5ac1d0e48b5ec766c587f5
Java
amber-888/ProjectNews
/2.StudentDataAnalayWeb/1.Code/CodeCaculate/hadoopOne.java
UTF-8
2,784
2.609375
3
[]
no_license
package HadoopDemo; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.util.GenericOptionsParser; import java.io.IOException; import java.util.NoSuchElementException; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; // 统计网站最多,男、女最多的网站 public class hadoopOne { public static class WCMap extends Mapper<LongWritable, Text, Text,IntWritable > { private final static IntWritable one = new IntWritable(1); @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException, NoSuchElementException { StringTokenizer itr = new StringTokenizer(value.toString(),","); if(itr.hasMoreTokens()) { String num = itr.nextToken(); String name = itr.nextToken(); String sex = itr.nextToken(); String time = itr.nextToken(); String web = itr.nextToken(); context.write(new Text( sex + "," + web), one); } } } public static class WCReduce extends Reducer<Text, IntWritable, Text, IntWritable> { private IntWritable result = new IntWritable(); @Override protected void reduce(Text key, Iterable<IntWritable> values, Context context)throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) sum += val.get(); result.set(sum); context.write(key, result); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "one"); job.setJarByClass(hadoopOne.class); job.setMapperClass(WCMap.class); job.setCombinerClass(WCReduce.class); job.setReducerClass(WCReduce.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path("hdfs://192.168.43.20:9000/input/students.txt")); FileSystem fs = FileSystem.get(conf); Path op = new Path("hdfs://192.168.43.20:9000/output8"); if (fs.exists(op)) { fs.delete(op, true); } FileOutputFormat.setOutputPath(job, op); job.waitForCompletion(true); } }
true
652dc9b6e857832c6858eede9f0f9dbb83b080bb
Java
jaindhairyahere/Yearbook-2021
/app/src/main/java/com/example/yearbook/api/model/Student_Profile.java
UTF-8
6,166
2.09375
2
[]
no_license
package com.example.yearbook.api.model; import android.content.Context; import android.util.Log; import android.view.View; import com.example.yearbook.Constants; import com.example.yearbook.api.response.LoginResponse; import com.example.yearbook.interfaces.Clickable; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.util.Date; public class Student_Profile{ protected int id; protected String email; protected Date dob; protected String profile_image; protected Student student; protected String hostel; protected String room_no; protected String department; protected String program; protected String degree; protected int join_year; protected int graduation_year; protected String nickname; protected String tagline; protected String ib1; protected String ib2; protected String ib3; protected String img1; protected String img2; protected String img3; protected String img4; protected String question1; protected String answer1; protected boolean details_done; public Student_Profile(int id, String email, Date dob, String profile_image, Student student, String hostel, String room_no, String department, String program, String degree, int join_year, int graduation_year, String nickname, String tagline, String ib1, String ib2, String ib3, String img1, String img2, String img3, String img4, String question1, String answer1, boolean details_done) { this.id = id; this.email = email; this.dob = dob; this.profile_image = Constants.BASE_URL + profile_image; this.student = student; this.hostel = hostel; this.room_no = room_no; this.department = department; this.program = program; this.degree = degree; this.join_year = join_year; this.graduation_year = graduation_year; this.nickname = nickname; this.tagline = tagline; this.ib1 = ib1; this.ib2 = ib2; this.ib3 = ib3; this.img1 = Constants.BASE_URL + img1; this.img2 = Constants.BASE_URL + img2; this.img3 = Constants.BASE_URL + img3; this.img4 = Constants.BASE_URL + img4; this.question1 = question1; this.answer1 = answer1; this.details_done = details_done; } public Student_Profile() { } public int getId() { return id; } public String getEmail() { return email; } public Date getDob() { return dob; } public String getProfile_image() { return profile_image; } public Student getStudent() { return student; } public String getHostel() { return hostel; } public String getRoom_no() { return room_no; } public String getDepartment() { return department; } public String getProgram() { return program; } public String getDegree() { return degree; } public int getJoin_year() { return join_year; } public int getGraduation_year() { return graduation_year; } public String getNickname() { return nickname; } public String getTagline() { return tagline; } public String getIb1() { return ib1; } public String getIb2() { return ib2; } public String getIb3() { return ib3; } public String getImg1() { return img1; } public String getImg2() { return img2; } public String getImg3() { return img3; } public String getImg4() { return img4; } public String getQuestion1() { return question1; } public String getAnswer1() { return answer1; } public void setId(int id) { this.id = id; } public void setEmail(String email) { this.email = email; } public void setDob(Date dob) { this.dob = dob; } public void setProfile_image(String profile_image) { this.profile_image = profile_image; } public void setStudent(Student student) { this.student = student; } public void setHostel(String hostel) { this.hostel = hostel; } public void setRoom_no(String room_no) { this.room_no = room_no; } public void setDepartment(String department) { this.department = department; } public void setProgram(String program) { this.program = program; } public void setDegree(String degree) { this.degree = degree; } public void setJoin_year(int join_year) { this.join_year = join_year; } public void setGraduation_year(int graduation_year) { this.graduation_year = graduation_year; } public void setNickname(String nickname) { this.nickname = nickname; } public void setTagline(String tagline) { this.tagline = tagline; } public void setIb1(String ib1) { this.ib1 = ib1; } public void setIb2(String ib2) { this.ib2 = ib2; } public void setIb3(String ib3) { this.ib3 = ib3; } public void setImg1(String img1) { this.img1 = img1; } public void setImg2(String img2) { this.img2 = img2; } public void setImg3(String img3) { this.img3 = img3; } public void setImg4(String img4) { this.img4 = img4; } public void setQuestion1(String question1) { this.question1 = question1; } public void setAnswer1(String answer1) { this.answer1 = answer1; } public boolean isDetails_done() { return details_done; } public void setDetails_done(boolean details_done) { this.details_done = details_done; } public static Student_Profile fromString(String json) { try { return new Gson().fromJson(json, Student_Profile.class); } catch (JsonSyntaxException e) { Log.d("Student Profile", "fromString: " + json); return null; } } @Override public String toString() { return new Gson().toJson(this); } public String getFullName() { return student.toString(); } }
true
05e07f64346e6120e6de7f86adafdb6ad62b8a11
Java
dlsyaim/EQIMSERVER
/src/main/java/com/gisinfo/sand/queryGeographyInfo/geographyData/condition/ActiveFaultCondition.java
UTF-8
1,298
2.234375
2
[]
no_license
package com.gisinfo.sand.queryGeographyInfo.geographyData.condition; //活跃断层条件类 public class ActiveFaultCondition { //断层名称 private String faultName; //断层性质 private String feature; //当前页数 private Integer pageNo; //每页记录条数 private Integer pageSize; //分页上限 private Integer top; //分页下限 private Integer bottom; public String getFaultName() { return faultName; } public void setFaultName(String faultName) { this.faultName = faultName; } public String getFeature() { return feature; } public void setFeature(String feature) { this.feature = feature; } public Integer getPageNo() { return pageNo; } public void setPageNo(Integer pageNo) { this.pageNo = pageNo; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Integer getTop() { return top; } public void setTop(Integer top) { this.top = top; } public Integer getBottom() { return bottom; } public void setBottom(Integer bottom) { this.bottom = bottom; } }
true
7374620fa94ac9726b84c61d0d1aea6028efda49
Java
cckmit/ms-lims
/src/main/java/com/compomics/mslims/util/fileio/ABI4700SpectrumStorageEngine.java
UTF-8
8,151
2.28125
2
[ "Apache-2.0" ]
permissive
/** * Created by IntelliJ IDEA. * User: martlenn * Date: 04-May-2007 * Time: 14:48:52 */ package com.compomics.mslims.util.fileio; import com.compomics.mslims.db.accessors.Fragmentation; import com.compomics.mslims.db.accessors.Spectrum; import com.compomics.mslims.db.accessors.Spectrum_file; import org.apache.log4j.Logger; import com.compomics.mslims.util.fileio.interfaces.SpectrumStorageEngine; import com.compomics.mslims.util.workers.Load4700MGFWorker; import com.compomics.mslims.gui.progressbars.DefaultProgressBar; import com.compomics.mslims.db.accessors.LCRun; import com.compomics.util.interfaces.Flamable; import java.io.File; import java.io.IOException; import java.util.Vector; import java.util.HashMap; import java.sql.Connection; import java.sql.SQLException; /* * CVS information: * * $Revision: 1.2 $ * $Date: 2009/06/22 09:13:36 $ */ /** * This class presents an implementation of the SpectrumStorageEngine that is designed to load and store ms/ms data from * an ABI 4700 mass spectrometer. * * @author Lennart Martens * @version $Id: ABI4700SpectrumStorageEngine.java,v 1.2 2009/06/22 09:13:36 lennart Exp $ */ public class ABI4700SpectrumStorageEngine implements SpectrumStorageEngine { // Class specific log4j logger for ABI4700SpectrumStorageEngine instances. private static Logger logger = Logger.getLogger(ABI4700SpectrumStorageEngine.class); /** * This method takes care of loading all ms/ms data from the file system, while displaying a progressbar. * <b><i>Please note</i></b> that the 'aFoundLCRuns' Vector is a reference parameter that will contain the Lcrun * instances after completion of the method! * * @param aList File[] with the listing of the top-level directory to browse through. * @param aStoredLCRuns Vector with the Lcrun instances that were retrieved from the database. When found on the * filesystem, these will not be included in the 'aNames' Vector with the results, since they * are already stored. * @param aFoundLCRuns Vector that will contain the new (not yet in DB) Lcrun instances found on the local * harddrive. * @param aParent Flamable with the parent that will do the error handling. * @param aProgress DefaulProgressBar to display the progress on. */ public void findAllLCRunsFromFileSystem(File[] aList, Vector aStoredLCRuns, Vector aFoundLCRuns, Flamable aParent, DefaultProgressBar aProgress) { Load4700MGFWorker lmw = new Load4700MGFWorker(aList, aStoredLCRuns, aFoundLCRuns, aParent, aProgress); lmw.start(); aProgress.setVisible(true); } /** * This method actually takes care of finding all the spectrumfiles for the indiciated LCRun and transforming these * into Spectrum instances for storage in the database over the specified connection. * * @param aLCRun LCRun instances for which the spectrumfiles need to be found and stored. * @param aProjectid long with the projectid to associate the Spectrumfiles with. * @param aInstrumentid long with the instrumentid to associate the spectrumfiles with. * @param aConn Connection on which to write the Spectrumfiles. * @return int with the number of spectra stored. * @throws java.io.IOException when the filereading goes wrong. * @throws java.sql.SQLException when the DB storage goes wrong. */ public int loadAndStoreSpectrumFiles(LCRun aLCRun, long aProjectid, long aInstrumentid, Connection aConn, Fragmentation aFragmentation) throws IOException, SQLException { int counter = 0; // Get a hanlde to the parent folder. File parent = new File(aLCRun.getPathname()); // Get a handle on all the peaklists in this LCRun. Vector spectra = new Vector(10, 5); this.browseRunRecursively(parent, spectra); if (spectra.size() != aLCRun.getFilecount()) { throw new IOException("Found only " + spectra.size() + " MS/MS MGF files in " + aLCRun.getPathname() + " instead of the expected " + aLCRun.getFilecount() + "!"); } // Cycle through all the files, storing each in the DB with the appropriate // links (L_LCRUNID and L_PROJECTID). The SEARCHED and IDENTIFIED flags default to '0'. // Filename and data are provided through the MascotGenericFile class, but note that we // convert the file contents from a String into a byte[] using the platforms default encoding. int liSize = spectra.size(); for (int i = 0; i < liSize; i++) { T2Extractor_MascotGenericFile lFile = (T2Extractor_MascotGenericFile) spectra.elementAt(i); HashMap data = new HashMap(9); data.put(Spectrum.L_INSTRUMENTID, new Long(aInstrumentid)); // The links. data.put(Spectrum.L_LCRUNID, new Long(aLCRun.getLcrunid())); data.put(Spectrum.L_PROJECTID, new Long(aProjectid)); data.put(Spectrum.L_FRAGMENTATIONID, aFragmentation.getFragmentationid()); // The flags. data.put(Spectrum.IDENTIFIED, new Long(0)); data.put(Spectrum.SEARCHED, new Long(0)); // The filename. data.put(Spectrum.FILENAME, lFile.getFilename()); // The total intensity. data.put(Spectrum.TOTAL_SPECTRUM_INTENSITY, lFile.getTotalIntensity()); // The highest intensity. data.put(Spectrum.HIGHEST_PEAK_IN_SPECTRUM, lFile.getHighestIntensity()); // The charge - as long for the database accessor. Long lCharge = new Long(lFile.getCharge()); data.put(Spectrum.CHARGE, lCharge); // The precursorMZ. data.put(Spectrum.MASS_TO_CHARGE, lFile.getPrecursorMZ()); // Create the database object. Spectrum lSpectrum = new Spectrum(data); lSpectrum.persist(aConn); // Get the spectrumid from the generated keys. Long lSpectrumfileID = (Long) lSpectrum.getGeneratedKeys()[0]; // Create the Spectrum_file instance. Spectrum_file lSpectrum_file = new Spectrum_file(); // Set spectrumid lSpectrum_file.setL_spectrumid(lSpectrumfileID); // Set the filecontent // Read the contents for the file into a byte[]. byte[] fileContents = lFile.toString().getBytes(); // Set the byte[]. lSpectrum_file.setUnzippedFile(fileContents); // Create the database object. lSpectrum_file.persist(aConn); counter++; } return counter; } /** * This method finds all the MS/MS files for a certain run. * * @param aParent File with the run top folder. * @param aSpectra Vector with the spectra found (reference parameter). * @throws java.io.IOException when the recursive browsing fails. */ private void browseRunRecursively(File aParent, Vector aSpectra) throws IOException { File[] list = aParent.listFiles(); for (int i = 0; i < list.length; i++) { File lFile = list[i]; if (lFile.isDirectory()) { this.browseRunRecursively(lFile, aSpectra); } else if (lFile.getName().toUpperCase().indexOf("_MSMS_") > 0 && lFile.getName().toUpperCase().endsWith(".MGF")) { loadSpectrum(lFile, aSpectra); } } } /** * This method finds all the MGF spectra in a certain folder. * * @param aFile File to load. * @param aSpectra Vector with the spectra found (reference parameter). * @throws java.io.IOException when the recursive browsing fails. */ private void loadSpectrum(File aFile, Vector aSpectra) throws IOException { T2Extractor_MascotGenericFile t2_mgf = new T2Extractor_MascotGenericFile(aFile); t2_mgf.setFilename(aFile.getParentFile().getName() + "_" + t2_mgf.getFilename()); aSpectra.add(t2_mgf); } }
true
bcb05581893a1aefa6d7231a435c85a7c6e14fa2
Java
Nishant-S/FeedViewer
/FeedViewer/src/com/cts/feedviewer/model/FeedCollection.java
UTF-8
1,005
2.78125
3
[]
no_license
package com.cts.feedviewer.model; import java.util.ArrayList; /** * Custom collection to store Feeds in an ArrayList * @author 330016 * */ public class FeedCollection { private ArrayList<Feed> feedCollectionArray; private String pageTitle; private static FeedCollection feedCollection; private FeedCollection() { feedCollectionArray = new ArrayList<Feed>(); } public static FeedCollection getFeedCollection() { if (feedCollection == null) { feedCollection = new FeedCollection(); } return feedCollection; } public void addFeed(Feed feed) { feedCollectionArray.add(feed); } public ArrayList<Feed> getFeedCollectionArray() { return feedCollectionArray; } public String getPageTitle() { return pageTitle; } public void setPageTitle(String pageTitle) { this.pageTitle = pageTitle; } public void clearAll(){ feedCollectionArray.clear(); } }
true
3b54ad8b3b4aa795fe9dcf3eb38d5080ae78f0cd
Java
pooja716/NearPark
/app/src/main/java/aksharproject/np/parkingtimer.java
UTF-8
3,814
2.28125
2
[]
no_license
package aksharproject.np; import android.app.AlarmManager; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import java.util.Calendar; public class parkingtimer extends Fragment { private static int timeHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); private static int timeMinute = Calendar.getInstance().get(Calendar.MINUTE); TextView textView1; private static TextView textView2; Context mcontext; public static TextView getTextView2() { return textView2; } AlarmManager alarmManager; private PendingIntent pendingIntent; public static final String TAG = parkingtimer.class.getSimpleName(); public parkingtimer() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v1 = inflater.inflate(R.layout.fragment_parkingtimer, container, false); getActivity().setTitle("Parking Timer"); textView1 = (TextView) v1.findViewById(R.id.msg1); textView1.setText(timeHour + ":" + timeMinute); textView2 = (TextView) v1.findViewById(R.id.msg2); Button btn1 = (Button) v1.findViewById(R.id.button1); Button btn2 = (Button) v1.findViewById(R.id.button2); alarmManager = (AlarmManager)getActivity().getSystemService(mcontext.ALARM_SERVICE); Intent myIntent = new Intent(getActivity(), AlarmReceiver.class); pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent, 0); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { textView2.setText(""); Bundle bundle = new Bundle(); bundle.putInt(Constant.HOUR, timeHour); bundle.putInt(Constant.MINUTE, timeMinute); MyDialogFragment fragment = new MyDialogFragment(new MyHandler()); fragment.setArguments(bundle); FragmentManager manager = getFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); transaction.add(fragment, Constant.TIME_PICKER); transaction.commit(); } }); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { textView2.setText(""); cancelAlarm(); } private void cancelAlarm() { if (alarmManager != null) { alarmManager.cancel(pendingIntent); } } }); return v1; } class MyHandler extends Handler { @Override public void handleMessage(Message msg) { Bundle bundle = msg.getData(); timeHour = bundle.getInt(Constant.HOUR); timeMinute = bundle.getInt(Constant.MINUTE); textView1.setText(timeHour + ":" + timeMinute); setAlarm(); } private void setAlarm() { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, timeHour); calendar.set(Calendar.MINUTE, timeMinute); alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); } } }
true
653f3e05ab20a0efb585bddabe7c5418bf8d2266
Java
HKChefo/Chefo_Android
/app/src/main/java/com/example/user/chefo/chef_profile/photo_upload.java
UTF-8
7,680
2.0625
2
[]
no_license
package com.example.user.chefo.chef_profile; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Camera; import android.graphics.Matrix; import android.hardware.camera2.CameraDevice; import android.net.Uri; import android.os.Bundle; import android.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import com.example.user.chefo.R; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link photo_upload.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link photo_upload#newInstance} factory method to * create an instance of this fragment. */ public class photo_upload extends Fragment{ final String TAG="photo_upload_fragment"; // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private android.hardware.Camera camera; private Button takingbut; private SurfaceView surfaceView; private ImageView imageView; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment photo_upload. */ // TODO: Rename and change types and number of parameters public static photo_upload newInstance(String param1, String param2) { photo_upload fragment = new photo_upload(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } public photo_upload() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v =inflater.inflate(R.layout.fragment_photo_upload, container, false); takingbut= (Button) v.findViewById(R.id.phototakingbut); surfaceView= (SurfaceView) v.findViewById(R.id.surfaceView); imageView= (ImageView) v.findViewById(R.id.imageView); if(camera==null){ try{ camera= android.hardware.Camera.open(); takingbut.setEnabled(true); Log.i(TAG,"setup the camera"); } catch(Exception e){ takingbut.setEnabled(false); Toast.makeText(getActivity(),"Camera not available",Toast.LENGTH_LONG).show(); Log.i(TAG,e.getMessage()); } } takingbut.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (camera == null) { Log.i(TAG, "cannot detect camera from onClick"); return; } camera.takePicture(new android.hardware.Camera.ShutterCallback() { @Override public void onShutter() { } }, null, new android.hardware.Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, android.hardware.Camera camera) { Log.i(TAG, "entering scalephoto"); scalePhoto(data); } }); } }); SurfaceHolder holder=surfaceView.getHolder(); holder.addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { try { Log.i(TAG, "surface created callback"); if (camera != null) { Log.i(TAG, "camera is not null setting camera"); camera.setDisplayOrientation(90); camera.setPreviewDisplay(holder); camera.startPreview(); } } catch (IOException e) { Log.e(TAG, "Error setting up preview", e); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { } }); return v; } private void scalePhoto(byte[] data){ Log.i(TAG,"enter scalephoto"); //resize the phto BitmapFactory.Options options=new BitmapFactory.Options(); options.inPurgeable=true; Bitmap photo = BitmapFactory.decodeByteArray(data, 0, data.length,options); Bitmap scaledphoto=Bitmap.createScaledBitmap(photo, 200, 200 * photo.getHeight() / photo.getWidth(), false); Log.i(TAG,"start scaling"); //change to portrait Matrix matrix=new Matrix(); matrix.postRotate(90); Bitmap rotatedscaledphoto = Bitmap.createBitmap(scaledphoto,0,0,scaledphoto.getWidth(),scaledphoto.getHeight(),matrix,true); ByteArrayOutputStream bos=new ByteArrayOutputStream(); rotatedscaledphoto.compress(Bitmap.CompressFormat.JPEG,100,bos); byte[] scaleddata=bos.toByteArray(); Log.i(TAG,"finished scaling"); imageView.setImageBitmap(rotatedscaledphoto); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name public void onFragmentInteraction(Uri uri); } }
true
4e09b379d45080a8d7509156875a107e016fe72b
Java
esaver/Project12
/src/com/mypackage/core/general/SwitchTest.java
UTF-8
815
3.421875
3
[]
no_license
package com.mypackage.core.general; public class SwitchTest { public static void main(String[] args) { String day = "THU1"; switch (day) { case "MON": System.out.println("Its Monday !!"); break; case "TUE": System.out.println("Its Tuesday !!"); break; case "WED": System.out.println("Its Wednesday !!"); break; case "THU": System.out.println("Its Thursday !!"); break; default: System.out.println("Wrong day !!"); break; case "FRI": System.out.println("Its Friday !!"); break; case "SAT": System.out.println("Its Saturday !!"); break; case "SUN": System.out.println("Its Sunday !!"); break; // System.out.println(toString()); } } /* public static String toString(){ System.out.println("Test toString called"); return ""; }*/ }
true
c4236d03c443ecd1c541862a19a6dd3cde8a758c
Java
HubertYoung/AcFun
/acfun5_7/src/main/java/org/cybergarage/http/HTTPServer.java
UTF-8
5,510
2.390625
2
[]
no_license
package org.cybergarage.http; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import org.cybergarage.util.ListenerList; import org.cybergarage.util.UPnPLog; public class HTTPServer implements Runnable { public static final int DEFAULT_PORT = 80; public static final int DEFAULT_TIMEOUT = 80000; public static final String NAME = "CyberHTTP"; private static final String TAG = "Cyber-HTTPServer"; public static final String VERSION = "1.0"; private InetAddress bindAddr; private int bindPort; private ListenerList httpRequestListenerList; private Thread httpServerThread; private ServerSocket serverSock; protected int timeout; public static String getName() { String property = System.getProperty("os.name"); String property2 = System.getProperty("os.version"); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(property); stringBuilder.append("/"); stringBuilder.append(property2); stringBuilder.append(" "); stringBuilder.append(NAME); stringBuilder.append("/"); stringBuilder.append("1.0"); return stringBuilder.toString(); } public HTTPServer() { this.serverSock = null; this.bindAddr = null; this.bindPort = 0; this.timeout = 80000; this.httpRequestListenerList = new ListenerList(); this.httpServerThread = null; this.serverSock = null; } public ServerSocket getServerSock() { return this.serverSock; } public String getBindAddress() { if (this.bindAddr == null) { return ""; } return this.bindAddr.toString(); } public int getBindPort() { return this.bindPort; } public synchronized int getTimeout() { return this.timeout; } public synchronized void setTimeout(int i) { this.timeout = i; } public boolean open(InetAddress inetAddress, int i) { if (this.serverSock != null) { return true; } try { this.serverSock = new ServerSocket(this.bindPort, 0, this.bindAddr); return true; } catch (IOException unused) { return false; } } public boolean open(String str, int i) { if (this.serverSock != null) { return true; } try { this.bindAddr = InetAddress.getByName(str); this.bindPort = i; this.serverSock = new ServerSocket(this.bindPort, 0, this.bindAddr); return true; } catch (IOException unused) { return false; } } public boolean close() { if (this.serverSock == null) { return true; } try { this.serverSock.close(); this.serverSock = null; this.bindAddr = null; this.bindPort = 0; return true; } catch (Throwable e) { UPnPLog.d(TAG, null, e); return false; } } public Socket accept() { if (this.serverSock == null) { return null; } try { Socket accept = this.serverSock.accept(); accept.setSoTimeout(getTimeout()); return accept; } catch (Exception unused) { return null; } } public boolean isOpened() { return this.serverSock != null; } public void addRequestListener(HTTPRequestListener hTTPRequestListener) { this.httpRequestListenerList.add(hTTPRequestListener); } public void removeRequestListener(HTTPRequestListener hTTPRequestListener) { this.httpRequestListenerList.remove(hTTPRequestListener); } public void performRequestListener(HTTPRequest hTTPRequest) { int size = this.httpRequestListenerList.size(); for (int i = 0; i < size; i++) { ((HTTPRequestListener) this.httpRequestListenerList.get(i)).httpRequestRecieved(hTTPRequest); } } public void run() { if (isOpened()) { Thread currentThread = Thread.currentThread(); while (this.httpServerThread == currentThread) { Thread.yield(); try { UPnPLog.d(TAG, "accept ..."); Socket accept = accept(); if (accept == null) { break; } String str = TAG; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("sock = "); stringBuilder.append(accept.getRemoteSocketAddress()); UPnPLog.d(str, stringBuilder.toString()); new HTTPServerThread(this, accept).start(); UPnPLog.d(TAG, "httpServThread ..."); } catch (Throwable e) { UPnPLog.d(TAG, null, e); } } } } public boolean start() { StringBuffer stringBuffer = new StringBuffer("Cyber.HTTPServer/"); stringBuffer.append(this.serverSock.getLocalSocketAddress()); this.httpServerThread = new Thread(this, stringBuffer.toString()); this.httpServerThread.start(); return true; } public boolean stop() { this.httpServerThread = null; return true; } }
true
6fd0e94f691e4eadb8e331cf417037b486b54c6e
Java
Sithum-DIlshan/Super-Market-Project
/SuperMarket/src/entity/OrderDetails.java
UTF-8
1,255
2.796875
3
[]
no_license
package entity; public class OrderDetails { private String itemCode; private String orderId; private int qty; private double discount; public OrderDetails(String itemCode, String orderId, int qty, double discount) { this.itemCode = itemCode; this.orderId = orderId; this.qty = qty; this.discount = discount; } public OrderDetails() { } public String getItemCode() { return itemCode; } public void setItemCode(String itemCode) { this.itemCode = itemCode; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public int getQty() { return qty; } public void setQty(int qty) { this.qty = qty; } public double getDiscount() { return discount; } public void setDiscount(double discount) { this.discount = discount; } @Override public String toString() { return "OrderDetails{" + "itemCode='" + itemCode + '\'' + ", orderId='" + orderId + '\'' + ", qty=" + qty + ", discount=" + discount + '}'; } }
true
64efce6c49f8c8be5240768a826ebf74aee78743
Java
wschaefer91/Objektorientierte-Programmierung-in-Java
/Woche 1 - Praxis/1.6 Methoden/1.6.2 Programmieraufgabe/ReadingRobot.java
UTF-8
112
1.703125
2
[]
no_license
class ReadingRobot { void giveTask() { System.out.println("Ich kann lesen."); } }
true
c2db382683ca0bae12f46e373ff612b22757266d
Java
shell22/stpbe
/sr-tvis-server/src/main/java/com/zhuanjingkj/stpbe/tvis_server/service/ITvisImageRecogService.java
UTF-8
567
1.742188
2
[]
no_license
package com.zhuanjingkj.stpbe.tvis_server.service; import java.util.Map; public interface ITvisImageRecogService { Map<String, Object> createLib(String name); Map<String, Object> queryLib(String id); Map<String, Object> updateLib(Map<String, Object> params); Map<String, Object> recognition(String cameraId, String gcxh, String mrhpt, String hphm, byte[] imageData); Map<String, Object> compareVehicle(String cltzxx1, String cltzxx2); Map<String, Object> compareInLib(String cltzxx, String kid, String xsdyz, String fydx, String ys); }
true
72d45f641c606c238a8cec801ebb50bbd6c775b9
Java
18877126235/project_OA_SSM
/src/main/java/com/ssm/OaManager/dao/stationery/impl/ReceiveDaoimpl.java
UTF-8
468
1.984375
2
[]
no_license
package com.ssm.OaManager.dao.stationery.impl; import org.springframework.stereotype.Repository; import com.ssm.OaManager.dao.impl.BaseDaoImpl; import com.ssm.OaManager.dao.stationery.ReceiveDao; import com.ssm.OaManager.entity.stationery.Receive; @Repository public class ReceiveDaoimpl extends BaseDaoImpl<Receive> implements ReceiveDao{ //利用默认构造方法初始化命名空间 public ReceiveDaoimpl() { super.setNs( Receive.class.getName()); } }
true
056c288731bb832a41f6c71146dfc088e14819f4
Java
5542111/nowcoder
/src/a1380luckyNumbers.java
UTF-8
841
3.1875
3
[]
no_license
import java.util.ArrayList; import java.util.List; public class a1380luckyNumbers { public List<Integer> luckyNumbers(int[][] matrix) { List<Integer> res = new ArrayList<>(); int[] minRow = new int[matrix.length]; int[] maxCol = new int[matrix[0].length]; for (int i = 0; i < matrix.length; i++) { minRow[i] = Integer.MAX_VALUE; for (int j = 0; j < matrix[0].length; j++) { minRow[i] = Math.min(matrix[i][j], minRow[i]); maxCol[j] = Math.max(matrix[i][j], maxCol[j]); } } for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if (minRow[i] == matrix[i][j] && maxCol[j] == matrix[i][j]) res.add(minRow[i]); } } return res; } }
true
5fa8ff472bedbbf36b1006afb3b9c3b750f87367
Java
Ievgeniya-kn/home-work-task
/src/main/java/com/hillel/lecture_10/Star.java
UTF-8
1,605
3.25
3
[]
no_license
package com.hillel.lecture_10; public class Star extends Galaxy { String starWeight; String starClass; public Star(String name, int id,String starClass,String starWeight) { super(name, id); this.starWeight = starWeight; this.starClass = starClass; } public String starColorFounder() { switch (starClass) { case "O": return "Blue"; case "A": return "Blue"; case "B": return "Blue"; case "F": return "Blue to White"; case "G": return "White to Yellow"; case "K": return "Orange to Red"; case "M": return "Red"; default: return "Uknown planet's type"; } } public String starWeight() { switch (starWeight) { case "Ia": return "Very luminous supergiants"; case "Ib": return "Less luminous supergiants"; case "II": return "Luminous giants"; case "III": return "Giants"; case "IV": return "Subgiants"; case "V": return "Main sequence stars (dwarf stars)"; case "VI": return "Subdwarf"; case "VII": return "White Dwarf"; default: return "Uknown planet's type"; } } @Override public String testGalaxy() { return "Star"; } }
true
206a1994dd14bfd6b6a98e9c3667a9feadfc6acf
Java
bbung224/trss-feed
/src/main/java/com/opal/torrent/rss/util/FileUtil.java
UTF-8
914
2.640625
3
[]
no_license
package com.opal.torrent.rss.util; import java.util.regex.Matcher; import java.util.regex.Pattern; public class FileUtil { public static long getFileSize(String fileSize) { Pattern pattern = Pattern.compile("(.+)([GMKT])"); Matcher matcher = pattern.matcher(fileSize); if (!matcher.find()) { return 0; } String unit = matcher.group(2); if ("G".equals(unit)) { return (long) Float.parseFloat(matcher.group(1)) * 1073741824; } if ("M".equals(unit)) { return (long) Float.parseFloat(matcher.group(1)) * 1048576; } if ("K".equals(unit)) { return (long) Float.parseFloat(matcher.group(1)) * 1024; } if ("T".equals(unit)) { return (long) Float.parseFloat(matcher.group(1)) * 1024; } return (long) Float.parseFloat(matcher.group(1)); } }
true
25a06dfe076712785eee5b8641d303436dbfabc4
Java
bnaresh1331/employee-management
/employeemanagement/src/main/java/org/mindtree/employeemanagement/repository/EmployeeRepository.java
UTF-8
400
2.046875
2
[]
no_license
package org.mindtree.employeemanagement.repository; import org.mindtree.employeemanagement.model.Employee; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface EmployeeRepository extends JpaRepository<Employee, Long>{ Employee findEmployeeByUserNameAndPassword(String userName, String password); }
true
cf46eb5c8b51edfd37d015bc4ae60000189b02ea
Java
ksumi/avenger
/BookStore/src/com/lovo/cq/shopping10_1/servlet/RandomCodeServlet.java
GB18030
2,696
2.890625
3
[]
no_license
package com.lovo.cq.shopping10_1.servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.*; public class RandomCodeServlet extends HttpServlet { // ֤Ŀ private int width = 60; // ֤ĸ߶ private int height = 20; protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = buffImg.createGraphics(); // һ Random random = new Random(); g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); // 壬ĴСӦøͼƬĸ߶ Font font = new Font("Times New Roman", Font.PLAIN, 18); g.setFont(font); // ߿ g.setColor(Color.BLACK); g.drawRect(0, 0, width - 1, height - 1); // 160,ʹͼе֤벻ױ̽⵽ g.setColor(Color.GRAY); for (int i = 0; i < 160; i++) { int x = random.nextInt(width); int y = random.nextInt(height); int x1 = random.nextInt(12); int y1 = random.nextInt(12); g.drawLine(x, y, x1, y1); } // randomCodeڱ֤룬Աû¼֤ StringBuffer randomCode = new StringBuffer(); int red = 0, green = 0, blue = 0; // 4λֵ֤ for (int i = 0; i < 4; i++) { // õ֤ String strRand = String.valueOf(random.nextInt(10)); // ɫɫֵÿλֵɫֵͬ red = random.nextInt(110); green = random.nextInt(50); blue = random.nextInt(50); // ɫ֤Ƶͼ g.setColor(new Color(red, green, blue)); g.drawString(strRand, 13 * i + 6, 16); // ĸһ randomCode.append(strRand); } // λֵ֤뱣浽Session HttpSession session = req.getSession(); session.setAttribute("randomCode", randomCode.toString()); // ֹͼ񻺴 resp.setHeader("Pragma", "no-cache"); resp.setHeader("Cache-Control", "no-cache"); resp.setDateHeader("Expires", 0); resp.setContentType("image/jpeg"); // ͼServlet ServletOutputStream sos = resp.getOutputStream(); ImageIO.write(buffImg, "jpeg", sos); sos.close(); } }
true
942be3633f37e31648747f0d5aa59fcc753f6187
Java
DuncanDHall/DSA-17
/DP/day01/src/EditDistance.java
UTF-8
1,336
3.40625
3
[]
no_license
public class EditDistance { /* sub-problem: After making an edit, what is the distance? Recurrence relation: Which edit provides minimum distance? */ public static int minEditDist(String a, String b) { int[][] memo = new int[a.length()][b.length()]; for (int i = 0; i < a.length(); i++) { for (int j = 0; j < b.length(); j++) { memo[i][j] = -1; } } return recursive(a.toCharArray(), b.toCharArray(), 0, 0, memo); // TODO: Your code here } private static int recursive(char[] a, char[] b, int i, int j, int[][] memo) { // base cases if (i == a.length) return b.length - j; if (j == b.length) return a.length - i; // previously solved? if (memo[i][j] != -1) return memo[i][j]; // recurrence relation int best; if (a[i] == b[j]) { best = recursive(a, b, i + 1, j + 1, memo); } else { int opD = recursive(a, b, i + 1, j, memo); // delete int opA = recursive(a, b, i, j + 1, memo); // add int opS = recursive(a, b, i + 1, j + 1, memo); // substitute best = 1 + Math.min(opD, Math.min(opA, opS)); } memo[i][j] = best; return best; } }
true
7d716a99d2fa0b126347183518a4a5fac77a1896
Java
Zoriginal/1.WorkingWithAbstraction
/A1Lab/A3StudentSystem/StudentSystem.java
UTF-8
1,532
3.96875
4
[]
no_license
package A1WorkingWithAbstraction.A1Lab.A3StudentSystem; import java.util.HashMap; import java.util.Map; public class StudentSystem { private Map<String, Student> studentMap; public StudentSystem() { this.studentMap = new HashMap<>(); } public Map<String, Student> getRepo() { return this.studentMap; } public void parseCommand(String[] args) { String command = args[0]; String name = args[1]; switch (command){ case "Create": int age = Integer.parseInt(args[2]); double grade = Double.parseDouble(args[3]); Student student = new Student(name,age,grade); studentMap.putIfAbsent(name,student); break; case "Show": if(studentMap.containsKey(name)){ Student student1 = studentMap.get(name); StringBuilder output = new StringBuilder(); output.append(String.format("%s is %s years old.", student1.getName(), student1.getAge())); if(student1.getGrade() >= 5){ output.append(" Excellent student."); }else if(student1.getGrade() >= 3.50){ output.append(" Average student."); }else { output.append(" Very nice person."); } System.out.println(output.toString()); } break; } } }
true
ccb7b5ebd3beb7ecc5c24068346c22d19c140106
Java
faheemzunjani/OOM-Java-Practice-Projects
/Lab2_2/src/lab2_2/Lab2_2.java
UTF-8
1,087
3.40625
3
[]
no_license
/* * 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 lab2_2; import java.util.*; public class Lab2_2 { public static void main(String[] args) { Student stud1 = new Student(); Student stud2 = new Student(); Scanner sc = new Scanner(System.in); String studName; String studRNo; int studAge; stud1.SetData("Faheem", "IIT2015113", 19); System.out.println("Enter details of student 2:\n"); System.out.println("Enter name: "); studName = sc.nextLine(); System.out.println("Enter roll no: "); studRNo = sc.nextLine(); System.out.println("Enter age: "); studAge = Integer.parseInt(sc.nextLine()); stud2.SetData(studName, studRNo, studAge); System.out.println("Student 1: \n"); stud1.GetData(); System.out.println("Studetn 2: \n"); stud2.GetData(); } }
true
6c3644615e5909fbdb2290fb1c52443acb14e243
Java
JamikaLove/Microblog
/MicroBlogFinal/User.java
UTF-8
1,204
2.578125
3
[]
no_license
public class User { private static int nextUserNumber = 0; private int userNumber; private String name; private String userName; private String firstName; private String lastName; private String emailAddress; private String webAddress; public User(String name, String userName, String firstName, String lastName, String emailAddress, String webAddress) { this.userNumber = nextUserNumber; nextUserNumber++; this.name = name; this.userName = userName; this.firstName = firstName; this.lastName = lastName; this.emailAddress = emailAddress; this.webAddress = webAddress; } public String getName() { return name; } public String getuserName() { return userName; } public int getuserNumber() { return userNumber; } public String getfirstName() { return firstName; } public String getlastName() { return lastName; } public String getemailAddress() { return emailAddress; } public String getwebAddress() { return webAddress; } }
true
ce7c6bf81933356d1d3ed9c0876d1cd13d9a45d8
Java
247452312/leetcode
/leetcode-只出现一次的数字/src/main/java/Solution.java
UTF-8
888
3.59375
4
[]
no_license
import java.util.ArrayList; import java.util.List; /** * 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。 * <p> * 说明: * <p> * 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? * <p> * 示例 1: * <p> * 输入: [2,2,1] * 输出: 1 * 示例 2: * <p> * 输入: [4,1,2,1,2] * 输出: 4 * * @author 龙龙 E-mail: 247452312@qq.com * @version 1.0 * @date 2018-08-27 15:04 */ public class Solution { public int singleNumber(int[] nums) { int a = nums[0]; for (int i = 1; i < nums.length; i++) { a = a ^ nums[i]; } return a; } public static void main(String[] args) { int i = new Solution().singleNumber(new int[]{2,2,1}); System.out.println(i); } }
true
3f67acc0425786342e6350a73ce12d57387abaab
Java
Ross-Savill/sparta-final-project
/src/test/java/com/spartaglobal/finalweek/pages/SchedulerPage.java
UTF-8
8,822
2.1875
2
[]
no_license
package com.spartaglobal.finalweek.pages; import com.spartaglobal.finalweek.base.TestBase; import com.spartaglobal.finalweek.interfaces.URLable; import com.spartaglobal.finalweek.tests.NavTemplateTests; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; import java.util.List; import static com.spartaglobal.finalweek.base.TestBase.webDriver; public class SchedulerPage extends NavTemplate implements URLable { @FindBy(how = How.CLASS_NAME , using="td.sticky-col footable-first-visible") public List<WebElement> trainingCourseNames; @FindBy(how = How.CSS , using="table.table tr") public List<WebElement> trainingCourses; @FindBy(xpath = "(//td[normalize-space()='Jedi Training'])[1]") WebElement FirstcourseName; @FindBy(xpath = "//td[contains(text(),'JarJar Binks')]") WebElement FirstTrainerName; @FindBy(xpath = "//td[contains(text(),'Coruscant')]") WebElement FirstCouseLocationName; @FindBy(how = How.XPATH , using="//tr[@class='footable-detail-row']//td//tr") public List<WebElement> FirstScheduleTrainingTable; @FindBy(xpath = "//tr[@class='footable-detail-row']//td//tr[1]") WebElement discipline; @FindBy(xpath = "//tr[@class='footable-detail-row']//td//tr[2]") WebElement courseType; @FindBy(xpath = "//tr[@class='footable-detail-row']//td//tr[3]") WebElement courseStart; @FindBy(xpath = "//tr[@class='footable-detail-row']//td//tr[4]") WebElement courseDuration; @FindBy(xpath = "//tr[@class='footable-detail-row']//td//tr[5]") WebElement courseEnd; @FindBy(xpath = "//tr[@class='footable-detail-row']//td//tr[6]") WebElement bond; @FindBy(xpath = "//tr[@class='footable-detail-row']//td//tr[7]") WebElement traineesInCourse; public SchedulerPage() { PageFactory.initElements(webDriver, this); } public boolean getCourse() { boolean staleElement = true; while (staleElement) { try { staleElement = false; Thread.sleep(2000); if (FirstcourseName.isDisplayed()) { return true; } } catch (StaleElementReferenceException | InterruptedException e) { staleElement = true; } } return false; } public String getTrainer(){ boolean staleElement = true; while (staleElement) { try { staleElement = false; Thread.sleep(2000); return FirstTrainerName.getText(); } catch (StaleElementReferenceException | InterruptedException e) { staleElement = true; } } return ""; } public String getCourseLocation(){ boolean staleElement = true; while (staleElement) { try { staleElement = false; Thread.sleep(2000); return FirstCouseLocationName.getText(); } catch (StaleElementReferenceException | InterruptedException e) { staleElement = true; } } return ""; } public void firstGetCourseClick(){ boolean staleElement = true; while (staleElement) { try { staleElement = false; Thread.sleep(2000); FirstcourseName.click(); } catch (StaleElementReferenceException | InterruptedException e) { staleElement = true; } } } public boolean isClickablefirstGetCourse(){ boolean staleElement = true; while (staleElement) { try { staleElement = false; Thread.sleep(2000); return FirstcourseName.isEnabled(); } catch (StaleElementReferenceException | InterruptedException e) { staleElement = true; } } return false; } public boolean isFirstCourseDisplayed(){ boolean staleElement = true; while (staleElement) { try { staleElement = false; Thread.sleep(2000); firstGetCourseClick(); if (discipline.isDisplayed() && courseType.isDisplayed() && courseStart.isDisplayed() && courseDuration.isDisplayed() && courseEnd.isDisplayed() && bond.isDisplayed() && traineesInCourse.isDisplayed()) { return true; } else return false; } catch (StaleElementReferenceException | InterruptedException e) { staleElement = true; } } return false; } public String getDicipline() { boolean staleElement = true; while (staleElement) { try { staleElement = false; firstGetCourseClick(); Thread.sleep(3000); return discipline.getText(); } catch (StaleElementReferenceException | InterruptedException e) { staleElement = true; } } return ""; } public String getCourseType(){ boolean staleElement = true; while(staleElement){ try{ staleElement = false; firstGetCourseClick(); Thread.sleep(2000); return courseType.getText(); } catch(StaleElementReferenceException | InterruptedException e){ staleElement = true; } } return ""; } public String getStartOfCourse(){ boolean staleElement = true; while (staleElement) { try { staleElement = false; Thread.sleep(2000); firstGetCourseClick(); return courseStart.getText(); } catch (StaleElementReferenceException | InterruptedException e) { staleElement = true; } } return ""; } public String getDuration(){ boolean staleElement = true; while(staleElement){ try{ staleElement = false; firstGetCourseClick(); Thread.sleep(2000); return courseDuration.getText(); } catch(StaleElementReferenceException | InterruptedException e){ staleElement = true; } } return ""; } public String getEndOfCouse(){ boolean staleElement = true; while (staleElement) { try { staleElement = false; Thread.sleep(2000); firstGetCourseClick(); return courseEnd.getText(); } catch (StaleElementReferenceException | InterruptedException e) { staleElement = true; } } return ""; } public String getBond(){ boolean staleElement = true; while (staleElement) { try { staleElement = false; Thread.sleep(2000); firstGetCourseClick(); return bond.getText(); } catch (StaleElementReferenceException | InterruptedException e) { staleElement = true; } } return ""; } public String getTraineesInCourse(){ boolean staleElement = true; while (staleElement) { try { staleElement = false; Thread.sleep(2000); firstGetCourseClick(); return traineesInCourse.getText(); } catch (StaleElementReferenceException | InterruptedException e) { staleElement = true; } } return ""; } public boolean isTrainingCourseTrainerCourseLocationContains(String TrainingCourse,String Trainer,String CourseLocation) throws InterruptedException { int count = 0; for (WebElement trainingCourse : trainingCourses) { Thread.sleep(2000); String str = ""; if (count > 0) { str = trainingCourse.getText(); if (str.contains(TrainingCourse) && str.contains(Trainer) && str.contains(CourseLocation)) return true; } count++; } return false; } @Override public String getURL() { return webDriver.getCurrentUrl(); } }
true
c49f0c93388211603bd5b5a751c45945bb6c3a8f
Java
kedar-s/bugtest
/org.tolven.fdb/ejb/source/org/tolven/fdb/entity/FdbPreclactRtdfgenPK.java
UTF-8
1,261
2.3125
2
[]
no_license
package org.tolven.fdb.entity; import java.io.Serializable; import javax.persistence.*; /** * The primary key class for the fdb_preclact_rtdfgen database table. * */ @Embeddable public class FdbPreclactRtdfgenPK implements Serializable { //default serial version id, required for serializable classes. private static final long serialVersionUID = 1L; private Integer rtdfgenid; private Integer lactcode; public FdbPreclactRtdfgenPK() { } public Integer getRtdfgenid() { return this.rtdfgenid; } public void setRtdfgenid(Integer rtdfgenid) { this.rtdfgenid = rtdfgenid; } public Integer getLactcode() { return this.lactcode; } public void setLactcode(Integer lactcode) { this.lactcode = lactcode; } public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof FdbPreclactRtdfgenPK)) { return false; } FdbPreclactRtdfgenPK castOther = (FdbPreclactRtdfgenPK)other; return this.rtdfgenid.equals(castOther.rtdfgenid) && this.lactcode.equals(castOther.lactcode); } public int hashCode() { final int prime = 31; int hash = 17; hash = hash * prime + this.rtdfgenid.hashCode(); hash = hash * prime + this.lactcode.hashCode(); return hash; } }
true
099dfbc0e3ec6dab358551d3f5443cc4a11bdc33
Java
dreamsh19/algo
/PROGRAMMERS/src/Solution12.java
UTF-8
328
2.453125
2
[]
no_license
import java.util.Arrays; public class Solution12 { public int solution(int[] citations) { int l = citations.length; Arrays.sort(citations); for (int i = l; i > 0; i--) { int min = citations[l - i]; if (min >= i) return i; } return 0; } }
true
021c93414876276285761d4a8ab5bee268b8ffad
Java
YA2O/jaxrs-guice-webservice
/src/main/java/bzh/ya2o/Configuration.java
UTF-8
1,997
1.953125
2
[ "Apache-2.0" ]
permissive
package bzh.ya2o; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.TypeLiteral; import com.google.inject.servlet.GuiceServletContextListener; import com.sun.jersey.api.container.filter.GZIPContentEncodingFilter; import com.sun.jersey.api.core.PackagesResourceConfig; import com.sun.jersey.api.core.ResourceConfig; import com.sun.jersey.guice.JerseyServletModule; import com.sun.jersey.guice.spi.container.servlet.GuiceContainer; import javax.servlet.annotation.*; import java.util.HashMap; import java.util.Map; @WebListener public class Configuration extends GuiceServletContextListener { @Override protected Injector getInjector() { return Guice.createInjector( new JerseyServletModule() { @Override protected void configureServlets() { ResourceConfig config = new PackagesResourceConfig(WebService.class.getPackage().getName()); for (Class<?> resource : config.getClasses()) { bind(resource); } Map<String, String> params = new HashMap<String, String>(); params.put(PackagesResourceConfig.PROPERTY_PACKAGES, WebService.class.getPackage().getName()); params.put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, GZIPContentEncodingFilter.class.getName()); params.put(ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, GZIPContentEncodingFilter.class.getName()); serve("/*").with(GuiceContainer.class, params); } }, new AbstractModule() { @Override protected void configure() { bind(new TypeLiteral<Dao<String>>() {}).to(FooDao.class); } } ); } }
true
6c057b4f0f9cd126aab0fc0e8325c8a720a47f4a
Java
mvlasoff/mvlasov
/chapter_005/src/main/java/ru/job4j/storegeneric/RoleStore.java
UTF-8
453
2.53125
3
[ "Apache-2.0" ]
permissive
package ru.job4j.storegeneric; import ru.job4j.simplearray.SimpleArray; import java.util.NoSuchElementException; /**. * Class UserStore extends AbstractStore, implements Store. * @author Mikhail Vlasov * @since 03.21.2018 * @version 1 */ public class RoleStore<Role extends Base> extends AbstractStore<Role> { /**. * Constructor. * @param size of the new role container. */ public RoleStore(int size) { super(size); } }
true
0d457320a020feb457071c3ac125fb6c7f83b408
Java
Rex7/Java_Beginner
/JavaBasic/PrimeNumberDemo.java
UTF-8
725
3.28125
3
[]
no_license
/* * 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 JavaBasic; /** * * @author Regis */ public class PrimeNumberDemo { public static void main(String[] args) { //printing prime number from 1 to 100 int count = 0; int number, j; for (number = 1; number < 100; number++) { for (j = 1; j < 100; j++) { if (number % j == 0) { count++; } } if (count == 2) { System.out.println(number); } count = 0; } } }
true
3f94cfaab7bed9ca014deb800ebf526680f04fa2
Java
frostjogla/bigdatasandbox
/custominputformat/src/main/java/ru/fj/custominputformat/DataParser.java
UTF-8
721
3.140625
3
[]
no_license
package ru.fj.custominputformat; class DataParser { private final String delimiter; private String name; private Integer age; public DataParser(String delimiter) { this.delimiter = delimiter; } void parse(String line) { if (line != null) { String[] split = line.split(delimiter); name = split[0]; try { age = Integer.valueOf(split[1]); } catch (NumberFormatException e) { age = -1; e.printStackTrace(System.err); } } } String getName() { return name; } Integer getAge() { return age; } }
true
72e86b609dc89b5d95770c418c92d8d7e4ffe3c4
Java
zebrunner/reporting-service
/src/main/java/com/zebrunner/reporting/service/WidgetService.java
UTF-8
7,003
2.15625
2
[ "Apache-2.0" ]
permissive
package com.zebrunner.reporting.service; import com.zebrunner.reporting.persistence.dao.mysql.application.WidgetMapper; import com.zebrunner.reporting.persistence.utils.SQLTemplateAdapter; import com.zebrunner.reporting.domain.db.Widget; import com.zebrunner.reporting.domain.db.WidgetTemplate; import com.zebrunner.reporting.service.exception.IllegalOperationException; import com.zebrunner.reporting.service.exception.ProcessingException; import com.zebrunner.reporting.service.util.FreemarkerUtil; import com.zebrunner.reporting.service.util.URLResolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.zebrunner.reporting.service.exception.IllegalOperationException.IllegalOperationErrorDetail.WIDGET_CAN_NOT_BE_CREATED; import static com.zebrunner.reporting.service.exception.ProcessingException.ProcessingErrorDetail.WIDGET_QUERY_EXECUTION_ERROR; @Service public class WidgetService { private static final Logger LOGGER = LoggerFactory.getLogger(WidgetService.class); private static final String ERR_MSG_INVALID_CHART_QUERY = "Invalid chart query"; public static final String ERR_MSG_WIDGET_WITH_SUCH_NAME_ALREADY_EXISTS = "Widget with such name already exists for template %d"; private final WidgetMapper widgetMapper; private final FreemarkerUtil freemarkerUtil; private final URLResolver urlResolver; private final WidgetTemplateService widgetTemplateService; public WidgetService(WidgetMapper widgetMapper, FreemarkerUtil freemarkerUtil, URLResolver urlResolver, WidgetTemplateService widgetTemplateService) { this.widgetMapper = widgetMapper; this.freemarkerUtil = freemarkerUtil; this.urlResolver = urlResolver; this.widgetTemplateService = widgetTemplateService; } public enum DefaultParam { SERVICE_URL("serviceUrl"), CURRENT_USER_ID("currentUserId"), CURRENT_USER_NAME("currentUserName"), HASHCODE("hashcode"), TEST_CASE_ID("testCaseId"); private final String parameterName; DefaultParam(String parameterName) { this.parameterName = parameterName; } } @Transactional(rollbackFor = Exception.class) public Widget createWidget(Widget widget) { WidgetTemplate widgetTemplate = widget.getWidgetTemplate(); if (widgetTemplate != null) { Widget existingWidget = getWidgetByTitleAndTemplateId(widget.getTitle(), widgetTemplate.getId()); if (existingWidget != null) { throw new IllegalOperationException(WIDGET_CAN_NOT_BE_CREATED, String.format(ERR_MSG_WIDGET_WITH_SUCH_NAME_ALREADY_EXISTS, widgetTemplate.getId())); } WidgetTemplate preparedWidgetTemplate = prepareWidgetTemplate(widget); widget.setType(preparedWidgetTemplate.getType().name()); } widgetMapper.createWidget(widget); return widget; } @Transactional(readOnly = true) public Widget getWidgetById(long id) { return widgetMapper.getWidgetById(id); } @Transactional(readOnly = true) public Widget getWidgetByTitleAndTemplateId(String title, long templateId) { return widgetMapper.getWidgetByTitleAndTemplateId(title, templateId); } @Transactional(readOnly = true) public List<Widget> getAllWidgets() { return widgetMapper.getAllWidgets(); } @Transactional(rollbackFor = Exception.class) public Widget updateWidget(Widget widget) { if (widget.getWidgetTemplate() != null) { prepareWidgetTemplate(widget); } widgetMapper.updateWidget(widget); return widget; } private WidgetTemplate prepareWidgetTemplate(Widget widget) { long templateId = widget.getWidgetTemplate().getId(); WidgetTemplate widgetTemplate = widgetTemplateService.getNotNullWidgetTemplateById(templateId); widgetTemplateService.clearRedundantParamsValues(widgetTemplate); widget.setWidgetTemplate(widgetTemplate); return widgetTemplate; } @Transactional(rollbackFor = Exception.class) public void deleteWidgetById(Long id) { widgetMapper.deleteWidgetById(id); } @Transactional(readOnly = true) public List<Map<String, Object>> getQueryResults(Map<String, Object> params, Long templateId, Long userId, String userName) { WidgetTemplate widgetTemplate = widgetTemplateService.getNotNullWidgetTemplateById(templateId); List<Map<String, Object>> resultList; try { Map<WidgetService.DefaultParam, Object> additionalParams = new HashMap<>(); additionalParams.put(WidgetService.DefaultParam.CURRENT_USER_NAME, userName); additionalParams.put(WidgetService.DefaultParam.CURRENT_USER_ID, userId); resultList = executeSQL(widgetTemplate.getSql(), params, additionalParams, true); } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw new ProcessingException(WIDGET_QUERY_EXECUTION_ERROR, ERR_MSG_INVALID_CHART_QUERY); } return resultList; } @Transactional(readOnly = true) public List<Map<String, Object>> executeSQL(String sql, Map<String, Object> params, Map<DefaultParam, Object> additionalParams, boolean isSqlFreemarkerTemplate) { if (isSqlFreemarkerTemplate) { sql = freemarkerUtil.getFreeMarkerTemplateContent(sql, processDefaultParameters(params, additionalParams), false); } return widgetMapper.executeSQLTemplate(new SQLTemplateAdapter(sql, params)); } private Map<String, Object> processDefaultParameters(Map<String, Object> params, Map<DefaultParam, Object> additionalParams) { Arrays.asList(DefaultParam.values()).forEach(defaultParam -> { if (!params.containsKey(defaultParam.parameterName)) { params.put(defaultParam.parameterName, getDefaultParamValue(defaultParam, additionalParams)); } }); return params; } private Object getDefaultParamValue(DefaultParam param, Map<DefaultParam, Object> additionalParams) { Object result = null; try { switch (param) { case SERVICE_URL: result = urlResolver.getServiceURL(); break; case CURRENT_USER_ID: case CURRENT_USER_NAME: result = additionalParams.get(param); break; case HASHCODE: case TEST_CASE_ID: result = 0; break; } } catch (RuntimeException e) { LOGGER.error(e.getMessage(), e); } return result; } }
true
8a5750fa9e7ef9108536f68ae28217fd9cc2e2c0
Java
NemanjaZoric/Mundus
/editor/src/main/com/mbrlabs/mundus/ui/modules/menu/EnvironmentMenu.java
UTF-8
2,425
2.3125
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2016. See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mbrlabs.mundus.ui.modules.menu; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.kotcrab.vis.ui.widget.Menu; import com.kotcrab.vis.ui.widget.MenuItem; import com.mbrlabs.mundus.ui.Ui; /** * @author Marcus Brummer * @version 20-12-2015 */ public class EnvironmentMenu extends Menu { private MenuItem ambientLight; private MenuItem skybox; private MenuItem fog; public EnvironmentMenu() { super("Environment"); ambientLight = new MenuItem("Ambient Light"); fog = new MenuItem("Fog"); skybox = new MenuItem("Skybox"); addItem(ambientLight); addItem(skybox); addItem(fog); setupListeners(); } private void setupListeners() { // ambient light ambientLight.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { Ui.getInstance().showDialog(Ui.getInstance().getAmbientLightDialog()); } }); // fog fog.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { Ui.getInstance().showDialog(Ui.getInstance().getFogDialog()); } }); // skybox skybox.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { Ui.getInstance().showDialog(Ui.getInstance().getSkyboxDialog()); } }); } public MenuItem getAmbientLight() { return ambientLight; } public MenuItem getFog() { return fog; } public MenuItem getSkybox() { return skybox; } }
true
fdfd7dc2b5b2fdb7c61f24b3ef835f2d3b0bf972
Java
JeremyBilic/480_Term_Project
/src/Client/ManagerFrame.java
UTF-8
399
1.851563
2
[]
no_license
package Client; public class ManagerFrame extends UserFrame { public ManagerFrame() { super(); panel.remove(btnSearch); panel.remove(btnLogin); panel.remove(btnSubscribe); panel.remove(btnCheckSubscription); panel.remove(btnRegisterProperty); panel.remove(btnPayFees); panel.remove(btnDisplayOwned); panel.remove(btnEmail); panel.remove(btnLandlordManageProperty); } }
true
612ee3b7fcbf3512691b9228b138fbd186f18fae
Java
niloc132/simple-graph
/src/main/java/com/sencha/gxt/sample/graph/client/draw/NodePositionDnD.java
UTF-8
1,741
2.328125
2
[]
no_license
package com.sencha.gxt.sample.graph.client.draw; /* * #%L * simple-graph * %% * Copyright (C) 2013 Sencha Inc * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.util.HashMap; import java.util.Map; import com.sencha.gxt.sample.graph.client.model.Edge; import com.sencha.gxt.sample.graph.client.model.Node; public class NodePositionDnD<N extends Node, E extends Edge> extends GraphDnD<N,E> { private Map<String, N> activeNodes = new HashMap<String, N>(); public NodePositionDnD(GraphComponent<N, E> graph) { super(graph); } protected boolean onStartDrag(String key, int x, int y) { N activeNode = getGraph().getNodeAtCoords(x, y); if (activeNode != null) { activeNodes.put(key, activeNode); getGraph().setNodeLocked(activeNode, true); return true; } return false; } protected void onDrag(String key, int x, int y) { getGraph().setCoords(activeNodes.get(key), x, y); } protected void onDrop(String key, int x, int y) { getGraph().setNodeLocked(activeNodes.remove(key), false); } protected void onCancel() { for (String key : activeNodes.keySet()) { getGraph().setNodeLocked(activeNodes.remove(key), false); } } }
true
4ae3ae25ecbf2634cfca909ea7578f25641d1db5
Java
rhscqe/rhsc-shell-rest-api-automation
/src/test/java/com/redhat/qe/test/rest/RestTestBase.java
UTF-8
1,734
2.09375
2
[]
no_license
package com.redhat.qe.test.rest; import org.calgb.test.performance.HttpSession; import org.calgb.test.performance.UseSslException; import org.junit.After; import org.junit.Before; import com.redhat.qe.config.RhscConfiguration; import com.redhat.qe.helpers.rest.HttpSessionFactory; import com.redhat.qe.model.Cluster; import com.redhat.qe.repository.IClusterRepository; import com.redhat.qe.repository.IHostRepository; import com.redhat.qe.repository.rest.ClusterRepository; import com.redhat.qe.repository.rest.DatacenterRepository; import com.redhat.qe.repository.rest.HostRepository; import com.redhat.qe.repository.rest.VolumeRepository; public class RestTestBase extends TestBase { HttpSession session; @Before public void setup() throws UseSslException{ session = new HttpSessionFactory().createHttpSession(RhscConfiguration.getConfiguration().getRestApi()); } @After public void teardownTestBase(){ session.stop(); } protected HttpSession getSession(){ return session; } /* (non-Javadoc) * @see com.redhat.qe.rest.ITestBase#getClusterRepository() */ public ClusterRepository getClusterRepository() { return new ClusterRepository(getSession()); } /** * @return */ protected DatacenterRepository getDatacenterRepository() { return new DatacenterRepository(getSession()); } /* (non-Javadoc) * @see com.redhat.qe.rest.ITestBase#getHostRepository() */ public IHostRepository getHostRepository() { return new HostRepository(getSession()); } /* (non-Javadoc) * @see com.redhat.qe.rest.ITestBase#getVolumeRepository(com.redhat.qe.model.Cluster) */ public VolumeRepository getVolumeRepository(Cluster cluster) { return new VolumeRepository(getSession(), cluster); } }
true