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
55ad62867cb36592400be9e208887938404c7914
Java
alsdud110/Spring-MVC_ShoppingMall
/ShoppingMall/src/main/java/product/ProductVO.java
UTF-8
1,410
2.625
3
[]
no_license
package product; import java.util.List; public class ProductVO { private String P_CODE; private String P_NAME; private String P_KIND; private String P_IMAGE; private int P_PRICE; private int qty; private List<ProductStdVO> productstdvo; public List<ProductStdVO> getProductstdvo() { return productstdvo; } public void setProductstdvo(List<ProductStdVO> productstdvo) { this.productstdvo = productstdvo; } public int getQty() { return qty; } public void setQty(int qty) { this.qty = qty; } public ProductVO() { } //값 불러와서 저장하기 위한 모든 값 구현. public ProductVO(String P_CODE, String P_NAME, String P_KIND, String P_IMAGE, int P_PRICE,int qty) { this.P_CODE=P_CODE; this.P_NAME=P_NAME; this.P_KIND=P_KIND; this.P_IMAGE=P_IMAGE; this.P_PRICE=P_PRICE; this.qty=qty; } public String getP_CODE() { return P_CODE; } public void setP_CODE(String p_CODE) { P_CODE = p_CODE; } public String getP_NAME() { return P_NAME; } public void setP_NAME(String p_NAME) { P_NAME = p_NAME; } public String getP_KIND() { return P_KIND; } public void setP_KIND(String p_KIND) { P_KIND = p_KIND; } public String getP_IMAGE() { return P_IMAGE; } public void setP_IMAGE(String p_IMAGE) { P_IMAGE = p_IMAGE; } public int getP_PRICE() { return P_PRICE; } public void setP_PRICE(int p_PRICE) { P_PRICE = p_PRICE; } }
true
065f43a76a2c222a4f5d96d1db07e6418cbae6ee
Java
khalilSaidane/tunisia-charity-land
/_tunisia_charity_land_esprit-development/_Tunisia_Charity_Land_Esprit/src/Entity/public_chat.java
UTF-8
963
2.296875
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 Entity; /** * * @author leanbois */ public class public_chat { public String username; public String meassage; public public_chat(String username, String meassage) { this.username = username; this.meassage = meassage; } public public_chat() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getMeassage() { return meassage; } public void setMeassage(String meassage) { this.meassage = meassage; } }
true
e7ceec6c203da300ef6352078616957df7ac539e
Java
cloudecho/spring-data-mybatis
/spring-data-mybatis/src/main/java/org/springframework/data/mybatis/dialect/identity/IdentityColumnSupport.java
UTF-8
2,348
2.46875
2
[ "Apache-2.0" ]
permissive
package org.springframework.data.mybatis.dialect.identity; import org.springframework.data.mapping.MappingException; public interface IdentityColumnSupport { /** * Does this dialect support identity column key generation? * * @return True if IDENTITY columns are supported; false otherwise. */ boolean supportsIdentityColumns(); /** * Does the dialect support some form of inserting and selecting the generated IDENTITY value all in the same * statement. * * @return True if the dialect supports selecting the just generated IDENTITY in the insert statement. */ boolean supportsInsertSelectIdentity(); /** * Whether this dialect have an Identity clause added to the data type or a completely separate identity data type * * @return boolean */ boolean hasDataTypeInIdentityColumn(); /** * Provided we {@link #supportsInsertSelectIdentity}, then attach the "select identity" clause to the insert * statement. * <p/> * Note, if {@link #supportsInsertSelectIdentity} == false then the insert-string should be returned without * modification. * * @param insertString The insert command * @return The insert command with any necessary identity select clause attached. */ String appendIdentitySelectToInsert(String insertString); /** * Get the select command to use to retrieve the last generated IDENTITY value for a particular table * * @param table The table into which the insert was done * @param column The PK column. * @param type The {@link java.sql.Types} type code. * @return The appropriate select command * @throws MappingException If IDENTITY generation is not supported. */ String getIdentitySelectString(String table, String column, int type) throws MappingException; /** * The syntax used during DDL to define a column as being an IDENTITY of a particular type. * * @param type The {@link java.sql.Types} type code. * @return The appropriate DDL fragment. * @throws MappingException If IDENTITY generation is not supported. */ String getIdentityColumnString(int type) throws MappingException; /** * The keyword used to insert a generated value into an identity column (or null). Need if the dialect does not * support inserts that specify no column values. * * @return The appropriate keyword. */ String getIdentityInsertString(); }
true
289d3cea8c3afb3203afa179835f23dbc2faea0d
Java
juaser/MeiZhi
/app/src/main/java/com/shizhefei/meizhi/view/adapter/DetailPagerAdapter.java
UTF-8
2,537
2.265625
2
[ "Apache-2.0" ]
permissive
package com.shizhefei.meizhi.view.adapter; import android.content.Context; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.shizhefei.meizhi.R; import com.shizhefei.meizhi.modle.entry.Gank; import com.shizhefei.mvc.IDataAdapter; import com.shizhefei.utils.ArrayListMap; import com.shizhefei.view.indicator.IndicatorViewPager; import java.util.ArrayList; import java.util.List; public class DetailPagerAdapter extends IndicatorViewPager.IndicatorViewPagerAdapter implements IDataAdapter<ArrayListMap<String, List<Gank>>> { private ArrayListMap<String, List<Gank>> data = new ArrayListMap<>(); @Override public int getCount() { return data.size(); } @Override public View getViewForTab(int position, View convertView, ViewGroup container) { if (convertView == null) { convertView = LayoutInflater.from(container.getContext()).inflate(R.layout.tab_top, container, false); } TextView textView = (TextView) convertView; textView.setText(data.keyAt(position).trim()); return convertView; } @Override public View getViewForPage(int position, View convertView, ViewGroup container) { if (convertView == null) { Context context = container.getContext(); RecyclerView recyclerView = new RecyclerView(context); recyclerView.setLayoutManager(new LinearLayoutManager(context)); recyclerView.setAdapter(new GankAdapter()); recyclerView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); convertView = recyclerView; } RecyclerView recyclerView = (RecyclerView) convertView; GankAdapter adapter = (GankAdapter) recyclerView.getAdapter(); List<Gank> ganks = data.valueAt(position); adapter.notifyDataChanged(ganks, true); return convertView; } @Override public void notifyDataChanged(ArrayListMap<String, List<Gank>> stringListArrayListMap, boolean isRefresh) { data.putAll(stringListArrayListMap); notifyDataSetChanged(); } private static int a; @Override public ArrayListMap<String, List<Gank>> getData() { return data; } @Override public boolean isEmpty() { return data.isEmpty(); } }
true
0bb52aaf42f89ce9bc66b84b5a9bddfa5bcb1cc1
Java
skysearcher/MyCs355
/src/cs355/model/drawing/Line.java
UTF-8
4,390
3.3125
3
[]
no_license
package cs355.model.drawing; import cs355.controller.SelectPoint; import cs355.controller.TShapeEnum; import java.awt.Color; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; /** * Add your line code here. You can add fields, but you cannot * change the ones that already exist. This includes the names! */ public class Line extends Shape { private double myTol; private double normalize; private double normalOne; private double normalTwo; private double distance; private double pointDis; private double xValue; private double yValue; // The ending point of the line. private Point2D.Double end; /** * Basic constructor that sets all fields. * * @param color the color for the new shape. * @param start the starting point. * @param end the ending point. */ public Line(Color color, Point2D.Double start, Point2D.Double end) { // Initialize the superclass. super(color, start); // Set the field. this.end = end; } /** * Getter for this Line's ending point. * * @return the ending point as a Java point. */ public Point2D.Double getEnd() { return end; } /** * Setter for this Line's ending point. * * @param end the new ending point for the Line. */ public void setEnd(Point2D.Double end) { this.end = end; } /** * Add your code to do an intersection test * here. You <i>will</i> need the tolerance. * * @param pt = the point to test against. * @param tolerance = the allowable tolerance. * @return true if pt is in the shape, * false otherwise. */ @Override public boolean pointInShape(Point2D.Double pt, double tolerance) { AffineTransform worldToObj = new AffineTransform(); worldToObj.translate(-this.getCenter().getX(), -this.getCenter().getY()); worldToObj.transform(pt, pt); myTol = tolerance; normalize = Math.sqrt(Math.pow(end.getX() - 0, 2.0) + Math.pow(end.getY() - 0, 2.0)); normalOne = (end.getX() - 0)/normalize; normalTwo = -(end.getY() - 0)/normalize; //now number one distance = 0.0; if ((pt.getX() * normalTwo) + (pt.getY() * normalOne) <= myTol && (pt.getX() * normalTwo) + (pt.getY() * normalOne) >= -myTol) {//within tolerance of line xValue = (normalOne * (pt.getX())); yValue = (-normalTwo * (pt.getY())); pointDis = xValue + yValue; if(pointDis <= normalize + myTol && pointDis >= -myTol){ return true; }else{ return false; } } else { return false; } } @Override public boolean hitHandle(Point2D.Double pt, double zoomD) { return pt.getY() > - 5.0 && pt.getY() < 5.0 && pt.getX() > -5.0 && pt.getX() < 5.0; } public boolean endHit(Point2D.Double pt){ return pt.getY() > - 5.0 + end.getY() && pt.getY() < 5.0 + end.getY() && pt.getX() > -5.0 + end.getX() && pt.getX() < 5.0 + end.getX(); } public void setAffEnd(Point2D.Double pt){ AffineTransform worldToObj = new AffineTransform(); worldToObj.concatenate(new AffineTransform(1, 0, 0, 1, -this.getCenter().getX(), -this.getCenter().getY())); worldToObj.transform(pt, pt); end = pt; } public void changeCenter(Point2D.Double pt){ AffineTransform worldToObj = new AffineTransform(); worldToObj.concatenate(new AffineTransform(1, 0, 0, 1, -this.getCenter().getX(), -this.getCenter().getY())); worldToObj.transform(pt, pt); end.setLocation(end.getX() - pt.getX(), end.getY() - pt.getY()); center.setLocation(center.getX() + pt.getX(), center.getY() + pt.getY()); } @Override public TShapeEnum whatShape() { return TShapeEnum.LINE; } @Override public SelectPoint rotationHit(Point2D.Double pt, double tolerance, double zoom) { if (pointInShape(pt, tolerance)) { if(hitHandle(pt, zoom)) { return SelectPoint.LinePoint; } if(endHit(pt)){ return SelectPoint.LinePointTwo; } return SelectPoint.Center; }else{ return SelectPoint.None; } } }
true
3bffdecb8b87692b51d5fa91363d43f04f62e482
Java
18380163461/hibernate
/src/main/java/utils/SessionFactory.java
UTF-8
1,274
2.40625
2
[]
no_license
package utils; import org.hibernate.Session; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class SessionFactory { static Session session; public static Session getSession() { if (null == session) { synchronized (SessionFactory.class) { if (null == session) { StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build(); // org.hibernate.SessionFactory sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory(); org.hibernate.SessionFactory sessionFactory= new Configuration() .configure() .buildSessionFactory(); session = sessionFactory.getCurrentSession(); } } } return session; } public void setSession(Session session) { this.session = session; } public static void closeSession() { if (null != session) { if (session.isOpen()) { session.close(); } } } }
true
8c12fe33c36c17542044f524e5fc8ea600978313
Java
nawazish-github/game-of-thrones
/src/main/java/com/everest/engineering/parser/CampaigningKingdomsParser.java
UTF-8
848
2.765625
3
[]
no_license
package com.everest.engineering.parser; import com.everest.engineering.constants.StringConstants; import com.everest.engineering.exceptions.ParseException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class CampaigningKingdomsParser implements InputParser { @Override public Map<String, Object> parse(List<String> inputs) { String campaigningKingdoms = inputs.get(0); List<String> list = Arrays.asList(campaigningKingdoms.split(" ")); if (list.size() == 0) throw new IllegalArgumentException("No kingdom participating for " + "being ruler of Southeros! Needs at least one kingdom"); Map<String, Object> map = new HashMap<>(); map.put(StringConstants.CAMPAIGNING_KINGDOMS, list); return map; } }
true
4b6e89f46d76925bc91c1ab610df5b3fc76a931d
Java
akselreiten/Java
/TDT4100/self/patterns/observable/highscorelist/HighscoreList.java
UTF-8
1,776
3.1875
3
[]
no_license
package patterns.observable.highscorelist; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class HighscoreList { private List<HighscoreListListener> listeners = new ArrayList<HighscoreListListener>(); private List<Integer> results = new ArrayList<Integer>(); private int maxSize; public HighscoreList(int maxSize){ this.maxSize = maxSize; } public void addHighscoreListListener(HighscoreListListener listener){ if (!listeners.contains(listener)){ listeners.add(listener); } } public void removeHighscoreListListener(HighscoreListListener listener){ if (listeners.contains(listener)){ listeners.remove(listeners.indexOf(listener)); } } public int size(){ return results.size(); } public int getElement(int index){ if (index < size()){ return results.get(index); } else { throw new IllegalArgumentException(); } } public void broadcastChange(int index){ for (HighscoreListListener l : listeners){ l.listChanged(this, index); } } public void addResult(int result){ int pos = 0; while (pos < size() && result >= results.get(pos)){ pos++; } if (pos < maxSize){ while (size() >= maxSize){ results.remove(size()-1); } results.add(pos,result); broadcastChange(pos); } } /*public String toString(){ String out = ""; int num = 1; for (int res : results){ out += num + ". " + res + "\n"; num++; } return out; } public static void main(String[] args) { HighscoreList hs = new HighscoreList(5); hs.addResult(103); hs.addResult(200); hs.addResult(33); hs.addResult(4512); hs.addResult(512); hs.addResult(215); hs.addResult(11364); hs.addResult(89); System.out.println(hs.results); }*/ }
true
f0b7aaa9fb30bcefb08b1bd19b3185b82c1dec62
Java
connectschool/connectschool
/src/main/java/com/connected/school/persistence/model/Pays.java
UTF-8
1,262
2.0625
2
[]
no_license
package com.connected.school.persistence.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; import java.util.*; @Entity @Table(name = "pays") public class Pays implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", nullable = false) private Long id; @Column(name = "codePays", nullable = true) private String codePays; @Column(name = "nomPays", nullable = true) private String nomPays; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCodePays() { return codePays; } public void setCodePays(String codePays) { this.codePays = codePays; } public String getNomPays() { return nomPays; } public void setNomPays(String nomPays) { this.nomPays = nomPays; } public static long getSerialversionuid() { return serialVersionUID; } // public Region[] region; }
true
174ff73792669a5157757ddf3b730bf68a62b77e
Java
sebin-vincent/E-Shoper
/order-service/src/main/java/com/example/orderservice/kafka/consumer/ReservationConfirmationService.java
UTF-8
1,661
2.109375
2
[]
no_license
package com.example.orderservice.kafka.consumer; import com.example.orderservice.dto.ReservationConfirmation; import com.example.orderservice.model.Order; import com.example.orderservice.model.OrderStatus; import com.example.orderservice.repository.OrderRepository; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.stereotype.Service; @Service public class ReservationConfirmationService{ Logger logger=LoggerFactory.getLogger(ReservationConfirmationService.class); @Autowired private OrderRepository orderRepository; @KafkaListener(topics = "ReservationConfirmation", groupId = "RESERVATION_GROUP",containerFactory = "reservationListenerFactory") public void changeOrderStatus(String confirmationObject) throws JSONException, JsonProcessingException { JSONObject jsonObject=new JSONObject(confirmationObject); ObjectMapper mapper=new ObjectMapper(); ReservationConfirmation confirmation=mapper.readValue(jsonObject.toString(),ReservationConfirmation.class); logger.info("Order Confirmation request from Inventory for orderId {}",confirmation.getOrderId()); Order order=orderRepository.findById(confirmation.getOrderId()).get(); order.setStatus(OrderStatus.ACCEPTED); orderRepository.save(order); } }
true
d00bca391adb79e110389e4d200144e861ab01e4
Java
matheushrq/DevGLPI
/TelaAtendente.java
UTF-8
12,783
2.109375
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 View; import devglpi.CRUD; import devglpi.DevGLPI; /** * * @author mathe */ public class TelaAtendente extends javax.swing.JFrame { /** * Creates new form TelaAtendente */ CRUD tableModel = new CRUD(); public TelaAtendente() { initComponents(); jtChamados.setModel(tableModel); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPasswordField1 = new javax.swing.JPasswordField(); jPanel1 = new javax.swing.JPanel(); jlBemVindo = new javax.swing.JLabel(); jbOutroUsuario = new javax.swing.JButton(); jlCampo = new javax.swing.JLabel(); jlPesquisa = new javax.swing.JLabel(); jcbCampo = new javax.swing.JComboBox<>(); jtfPesquisa = new javax.swing.JTextField(); jbOk = new javax.swing.JButton(); jbAtualizar = new javax.swing.JButton(); jbNovo = new javax.swing.JButton(); jbExcluir = new javax.swing.JButton(); jbAlterar = new javax.swing.JButton(); jbImportar = new javax.swing.JButton(); jbExportar = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jtChamados = new javax.swing.JTable(); jPasswordField1.setText("jPasswordField1"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setPreferredSize(new java.awt.Dimension(684, 613)); jlBemVindo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jlBemVindo.setText("Bem-vindo"); jbOutroUsuario.setText("Acessar com outro usuário"); jlCampo.setText("Campo"); jlPesquisa.setText("Pesquisa"); jlPesquisa.setToolTipText(""); jcbCampo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Descrição" })); jbOk.setText("Ok"); jbAtualizar.setText("Atualizar"); jbAtualizar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbAtualizarActionPerformed(evt); } }); jbNovo.setText("Novo"); jbExcluir.setText("Excluir"); jbAlterar.setText("Alterar"); jbImportar.setText("Importar XML"); jbExportar.setText("Exportar XML"); jtChamados.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jtChamados); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(31, 31, 31) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jcbCampo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlCampo)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlPesquisa) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtfPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 410, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(166, 166, 166) .addComponent(jlBemVindo, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbOk, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jbAtualizar) .addComponent(jbOutroUsuario)))) .addContainerGap(57, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane1) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jbNovo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbExcluir, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbAlterar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbImportar, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jbExportar, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(27, 27, 27)))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlBemVindo) .addComponent(jbOutroUsuario)) .addGap(48, 48, 48) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlCampo) .addComponent(jlPesquisa)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcbCampo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtfPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbOk) .addComponent(jbAtualizar)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(17, 17, 17) .addComponent(jbNovo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbExcluir) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbAlterar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbImportar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbExportar)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(36, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 841, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 606, Short.MAX_VALUE) ); pack(); }// </editor-fold> private void jbAtualizarActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } /** * @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(TelaAtendente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaAtendente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaAtendente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaAtendente.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() { TelaAtendente tela = new TelaAtendente(); tela.setLocationRelativeTo(tela); tela.setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JPanel jPanel1; private javax.swing.JPasswordField jPasswordField1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton jbAlterar; private javax.swing.JButton jbAtualizar; private javax.swing.JButton jbExcluir; private javax.swing.JButton jbExportar; private javax.swing.JButton jbImportar; private javax.swing.JButton jbNovo; private javax.swing.JButton jbOk; private javax.swing.JButton jbOutroUsuario; private javax.swing.JComboBox<String> jcbCampo; private javax.swing.JLabel jlBemVindo; private javax.swing.JLabel jlCampo; private javax.swing.JLabel jlPesquisa; private javax.swing.JTable jtChamados; private javax.swing.JTextField jtfPesquisa; // End of variables declaration }
true
168d6e8a62c50a2e309e007f65787bf5816bbd81
Java
HONGJEONGHO/test7
/src/main/java/itor/example/test7/database/PersonDao.java
UTF-8
706
2.234375
2
[]
no_license
package itor.example.test7.database; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; public class PersonDao { protected Log log = LogFactory.getLog(PersonDao.class); @Autowired private SqlSessionTemplate sqlSessionTemplate; protected void printQueryId(String queryId){ if(log.isDebugEnabled()){ log.debug("|t QueryId |t: " + queryId); } } public Object insertPerson(String queryId , Object params) { printQueryId(queryId); return sqlSessionTemplate.insert(queryId, params); } }
true
4ffc5b656dc3604cce5669a357a32834ab6a1697
Java
jahlborn/jackcess
/src/main/java/com/healthmarketscience/jackcess/expr/Value.java
UTF-8
3,311
2.90625
3
[ "Apache-2.0" ]
permissive
/* Copyright (c) 2016 James Ahlborn 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.healthmarketscience.jackcess.expr; import java.math.BigDecimal; import java.time.LocalDateTime; /** * Wrapper for a typed primitive value used within the expression evaluation * engine. Note that the "Null" value is represented by an actual Value * instance with the type of {@link Type#NULL}. Also note that all the * conversion methods will throw an {@link EvalException} if the conversion is * not supported for the current value. * * @author James Ahlborn */ public interface Value { /** the types supported within the expression evaluation engine */ public enum Type { NULL, STRING, DATE, TIME, DATE_TIME, LONG, DOUBLE, BIG_DEC; public boolean isString() { return (this == STRING); } public boolean isNumeric() { return inRange(LONG, BIG_DEC); } public boolean isIntegral() { return (this == LONG); } public boolean isTemporal() { return inRange(DATE, DATE_TIME); } public Type getPreferredFPType() { return((ordinal() <= DOUBLE.ordinal()) ? DOUBLE : BIG_DEC); } public Type getPreferredNumericType() { if(isNumeric()) { return this; } if(isTemporal()) { return ((this == DATE) ? LONG : DOUBLE); } return null; } private boolean inRange(Type start, Type end) { return ((start.ordinal() <= ordinal()) && (ordinal() <= end.ordinal())); } } /** * @return the type of this value */ public Type getType(); /** * @return the raw primitive value */ public Object get(); /** * @return {@code true} if this value represents a "Null" value, * {@code false} otherwise. */ public boolean isNull(); /** * @return this primitive value converted to a boolean */ public boolean getAsBoolean(LocaleContext ctx); /** * @return this primitive value converted to a String */ public String getAsString(LocaleContext ctx); /** * @return this primitive value converted to a LocalDateTime */ public LocalDateTime getAsLocalDateTime(LocaleContext ctx); /** * Since date/time values have different types, it may be more convenient to * get the date/time primitive value with the appropriate type information. * * @return this value converted to a date/time value */ public Value getAsDateTimeValue(LocaleContext ctx); /** * @return this primitive value converted (rounded) to an int */ public Integer getAsLongInt(LocaleContext ctx); /** * @return this primitive value converted (rounded) to a double */ public Double getAsDouble(LocaleContext ctx); /** * @return this primitive value converted to a BigDecimal */ public BigDecimal getAsBigDecimal(LocaleContext ctx); }
true
cd53ed65e76012d01bf1073d7ea83d38ab50f6e6
Java
hhnewbee/CA-ApplicationMall
/源代码/CA应用商城-源码1.0/src/com/example/downloadui/jsonservic/MySQL.java
GB18030
1,845
2.25
2
[]
no_license
package com.example.downloadui.jsonservic; import com.example.downlaodui.infodata.AppContext; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by user on 2016/8/1. */ public class MySQL extends SQLiteOpenHelper{ public static MySQL mInstance = null; private static final String test = "(id text primary key, " +"category text, " +"true_name text, " +"name text, " +"content text, " +"size text, " +"version text, " +"download_times text, " +"time_upload text, " +"directoty_soft text, " +"directory_img text, " +"directory_img_content_1 text, " +"directory_img_content_2 text, " +"directory_img_content_3 text, " +"time text)"; public static final String CREATE_RECORD = "create table record " + test; public static final String CREATE_DOWNLOADLINE = "create table downloadline " + test; public static final String CREATE_UPDATE = "create table updateline " + test; public static MySQL getInstance() { if (mInstance == null) { mInstance = new MySQL(AppContext.getInstence(),"SOFT.db",null,1); } return mInstance; } private MySQL(Context context, String name, SQLiteDatabase.CursorFactory factory,int version){ super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_RECORD); db.execSQL(CREATE_DOWNLOADLINE); db.execSQL(CREATE_UPDATE); System.out.println("¼ɹ"); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } }
true
d87da7acf9c772bb8ec25eef4e8bbc8579519717
Java
lebonhomme17/TP_Ordo
/src/solveur/SolutionIntermediaireDeux.java
UTF-8
2,866
3.140625
3
[]
no_license
package solveur; import probleme.Job; import java.util.ArrayList; public class SolutionIntermediaireDeux { private SolutionDeux solution; private ArrayList<Job> reste; private int binf; public SolutionIntermediaireDeux(ArrayList<Job> jobs){ this.solution = new SolutionDeux(new ArrayList<>(), new ArrayList<>()); this.reste = new ArrayList<>(jobs); this.binf=-1; } public SolutionIntermediaireDeux(SolutionIntermediaireDeux pred, int machine){ this.solution = new SolutionDeux(new ArrayList<>(pred.getSolution().getM1()), new ArrayList<>(pred.getSolution().getM2())); this.reste = new ArrayList<>(pred.getReste()); if(machine == 1) { this.solution.getM1().add(reste.get(0)); }else if(machine == 2){ this.solution.getM2().add(reste.get(0)); } this.reste.remove(0); this.binf=-1; } public boolean hasNext(){ return !reste.isEmpty(); } public SolutionDeux getSolution(){ return solution; } public ArrayList<Job> getReste(){ return reste; } public ArrayList<SolutionIntermediaireDeux> nexts(){ ArrayList<SolutionIntermediaireDeux> res = new ArrayList<>(); if(reste.size()!=0){ if(reste.size()==1){ /****** Utilisation de la propriété 1 ****/ //Calcule des Cmax des 2 machines int c1=0; int c2=0; for(Job j : solution.getM1()){ c1 += j.getP(); } for(Job j : solution.getM2()){ c2 += j.getP(); } /***** * On ajoute la solution si elle respecte les 2 propriétés suivantes : * 1) la dernière tâches est placée sur la machine libre le plus tôt * 2) la fin de la dernière tache se termine après ou en même temps que la dernière tâche sur l'autre machine. * autrement dit, la difference entre les dates de fin des 2 machines (avant que la dernière tache soit * placée) doit etre inférieure ou égale au P de cette tache. *****/ if(c1<=c2 && c2-c1<=reste.get(0).getP()){ res.add(new SolutionIntermediaireDeux(this, 1)); } else if(c2<c1 && c1-c2<=reste.get(0).getP()){ res.add(new SolutionIntermediaireDeux(this, 2)); } }else{ res.add(new SolutionIntermediaireDeux(this, 1)); res.add(new SolutionIntermediaireDeux(this, 2)); } } return res; } public int borneInf(){ if(binf==-1){ binf = solution.eval(); } return binf; } }
true
2fd1a74d545ebb70aad41cddd0bb0fe2257a19b8
Java
CivclassicBot/BlockLimits
/src/main/java/com/civclassic/blocklimits/BlockManager.java
UTF-8
4,025
2.625
3
[ "BSD-3-Clause" ]
permissive
package com.civclassic.blocklimits; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Chunk; import org.bukkit.Material; import vg.civcraft.mc.civmodcore.dao.ManagedDatasource; public class BlockManager { private static final String GET_COUNT = "select count from blocklimits where world=? and x=? and z=? and mat=?;"; private static final String INCREMENT = "insert into blocklimits (world, x, z, mat, count) values (?, ?, ?, ?, 1) on duplicate key update count = count + 1;"; private static final String DECREMENT = "update blocklimits set count = count - 1 where world=? and x=? and z=? and mat=?;"; private ManagedDatasource db; private Logger log; private Map<Material, Integer> limits; public BlockManager(ManagedDatasource db, Logger log, Map<Material, Integer> limits) { this.db = db; this.log = log; this.limits = limits; } public void registerMigrations() { db.registerMigration(1, true, "create table if not exists blocklimits(" + "world int not null," + "x int not null," + "z int not null," + "mat varchar(40) not null," + "count int not null default 1," + "constraint chunkKey primary key (world, x, z, mat));"); } /** * Handles logic for adding a block to a chunk * @param chunk * @param type * @return if the block should be kept in the chunk */ public boolean handleBlockAdded(Chunk chunk, Material type) { if(!limits.containsKey(type) || limits.get(type) == null) return true; if(canHaveMore(chunk, type)) { incrementChunkCount(chunk, type); return true; } return false; } public boolean canHaveMore(Chunk chunk, Material type) { if(!limits.containsKey(type) || limits.get(type) == null) return true; return getChunkCount(chunk, type) < limits.get(type); } public void handleBlockRemoved(Chunk chunk, Material type) { if(!limits.containsKey(type) || limits.get(type) == null) return; decrementChunkCount(chunk, type); } private void incrementChunkCount(Chunk chunk, Material mat) { try(Connection conn = db.getConnection(); PreparedStatement ps = conn.prepareStatement(INCREMENT)) { ps.setInt(1, chunk.getWorld().getName().hashCode()); ps.setInt(2, chunk.getX()); ps.setInt(3, chunk.getZ()); ps.setString(4, mat.name()); ps.executeUpdate(); } catch (SQLException e) { log.log(Level.WARNING, "Failed to increment count for " + mat + " at " + chunk.getWorld() + " [" + chunk.getX() + ", " + chunk.getZ() + "]", e); } } private void decrementChunkCount(Chunk chunk, Material mat) { try(Connection conn = db.getConnection(); PreparedStatement ps = conn.prepareStatement(DECREMENT)) { ps.setInt(1, chunk.getWorld().getName().hashCode()); ps.setInt(2, chunk.getX()); ps.setInt(3, chunk.getZ()); ps.setString(4, mat.name()); ps.executeUpdate(); } catch (SQLException e) { log.log(Level.WARNING, "Failed to decrement count for " + mat + " at " + chunk.getWorld() + " [" + chunk.getX() + ", " + chunk.getZ() + "]", e); } } private int getChunkCount(Chunk chunk, Material mat) { try(Connection conn = db.getConnection(); PreparedStatement ps = conn.prepareStatement(GET_COUNT)) { ps.setInt(1, chunk.getWorld().getName().hashCode()); ps.setInt(2, chunk.getX()); ps.setInt(3, chunk.getZ()); ps.setString(4, mat.name()); ResultSet res = ps.executeQuery(); if(res.next()) { return res.getInt("count"); } } catch (SQLException e) { log.log(Level.WARNING, "Failed to get count for " + mat + " at " + chunk.getWorld() + " [" + chunk.getX() + ", " + chunk.getZ() + "]", e); } return 0; } public void cull() { try (Connection conn = db.getConnection()) { conn.prepareStatement("delete from blocklimits where count=0;").executeUpdate(); } catch (SQLException e) { log.log(Level.WARNING, "Failed to cull empty rows", e); } } }
true
22c8bac3ad6b4a4aa11fb7b51884ebddef3b3c48
Java
SelfStudyGuide/repo
/ssg-gwt/src/main/java/org/ssg/core/dto/TopicTaskInfo.java
UTF-8
1,094
2.171875
2
[]
no_license
package org.ssg.core.dto; import java.io.Serializable; public class TopicTaskInfo implements Serializable { private static final long serialVersionUID = 7363754530636194857L; private int id; private TaskType type; private int execrisesCount; private int completedCount; private int homeworkId; public int getId() { return id; } public void setId(int id) { this.id = id; } public TaskType getType() { return type; } public void setType(TaskType type) { this.type = type; } public int getExecrisesCount() { return execrisesCount; } public void setExecrisesCount(int execrisesCount) { this.execrisesCount = execrisesCount; } public int getCompletedCount() { return completedCount; } public void setCompletedCount(int completedCount) { this.completedCount = completedCount; } public boolean isType(TaskType type) { return getType() == type; } public int getHomeworkId() { return homeworkId; } public void setHomeworkId(int homeworkId) { this.homeworkId = homeworkId; } }
true
5c50c636cc6400f1065a49efef33901dc5d831a9
Java
pmerienne/task-manager
/src/main/java/com/pmerienne/taskmanager/client/MobileClientFactoryImpl.java
UTF-8
4,081
1.5
2
[]
no_license
/* * Copyright 2010 Daniel Kurka * * 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.pmerienne.taskmanager.client; import com.google.gwt.event.shared.EventBus; import com.google.gwt.event.shared.SimpleEventBus; import com.google.gwt.place.shared.PlaceController; import com.pmerienne.taskmanager.client.view.mobile.EditProjectView; import com.pmerienne.taskmanager.client.view.mobile.EditProjectViewImpl; import com.pmerienne.taskmanager.client.view.mobile.EditTaskView; import com.pmerienne.taskmanager.client.view.mobile.EditTaskViewImpl; import com.pmerienne.taskmanager.client.view.mobile.HomeView; import com.pmerienne.taskmanager.client.view.mobile.HomeViewImpl; import com.pmerienne.taskmanager.client.view.mobile.PendingView; import com.pmerienne.taskmanager.client.view.mobile.PendingViewImpl; import com.pmerienne.taskmanager.client.view.mobile.ProjectDetailView; import com.pmerienne.taskmanager.client.view.mobile.ProjectDetailViewImpl; import com.pmerienne.taskmanager.client.view.mobile.ProjectListView; import com.pmerienne.taskmanager.client.view.mobile.ProjectListViewImpl; import com.pmerienne.taskmanager.client.view.mobile.RegisterView; import com.pmerienne.taskmanager.client.view.mobile.RegisterViewImpl; import com.pmerienne.taskmanager.client.view.mobile.TaskDetailView; import com.pmerienne.taskmanager.client.view.mobile.TaskDetailViewImpl; import com.pmerienne.taskmanager.client.view.mobile.TaskListView; import com.pmerienne.taskmanager.client.view.mobile.TaskListViewImpl; import com.pmerienne.taskmanager.client.view.mobile.TaskStatusView; import com.pmerienne.taskmanager.client.view.mobile.TaskStatusViewImpl; public class MobileClientFactoryImpl implements MobileClientFactory { private final EventBus eventBus = new SimpleEventBus(); @SuppressWarnings("deprecation") private final PlaceController placeController = new PlaceController(eventBus); private final HomeView homeView = new HomeViewImpl(); private final TaskStatusView taskSatusView = new TaskStatusViewImpl(); private final TaskListView taskListView = new TaskListViewImpl(); private final TaskDetailView taskDetailView = new TaskDetailViewImpl(); private final EditTaskView editTaskView = new EditTaskViewImpl(); private final ProjectListView projectListView = new ProjectListViewImpl(); private final EditProjectView editProjectView = new EditProjectViewImpl(); private final ProjectDetailView projectDetailView = new ProjectDetailViewImpl(); private final RegisterView registerView = new RegisterViewImpl(); private final PendingView pendingView = new PendingViewImpl(); @Override public EventBus getEventBus() { return eventBus; } @Override public PlaceController getPlaceController() { return placeController; } @Override public TaskStatusView getTaskStatusView() { return taskSatusView; } @Override public TaskListView getTaskListView() { return taskListView; } @Override public TaskDetailView getTaskDetailView() { return taskDetailView; } @Override public EditTaskView getEditTaskView() { return editTaskView; } @Override public HomeView getHomeView() { return homeView; } @Override public ProjectListView getProjectListView() { return projectListView; } @Override public EditProjectView getEditProjectView() { return editProjectView; } @Override public ProjectDetailView getProjectDetailView() { return projectDetailView; } @Override public RegisterView getRegisterView() { return registerView; } @Override public PendingView getPendingView() { return pendingView; } }
true
29e67be70674cfd6d1eba564fc98d6d5da512b5b
Java
xiongkai888/kang
/kang/app/src/main/java/com/lanmei/kang/event/CollectItemsEvent.java
UTF-8
425
1.875
2
[]
no_license
package com.lanmei.kang.event; /** * Created by xkai on 2018/1/10. * 服务收藏事件 */ public class CollectItemsEvent { private String id; private String favoured; public String getFavoured() { return favoured; } public String getId() { return id; } public CollectItemsEvent(String id,String favoured) { this.id = id; this.favoured = favoured; } }
true
95b9e2d1660ce99560a6bfe9af453c9463afc177
Java
tryingpfq/jxpg
/jxpg/src/com/biyeseng/web/controller/CourseController.java
UTF-8
1,937
2.1875
2
[]
no_license
package com.biyeseng.web.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.biyeseng.pojo.Course; import com.biyeseng.service.CourseService; import com.biyeseng.utils.Page; @Controller @RequestMapping("/stumenue") public class CourseController { @Autowired private CourseService courseService; @RequestMapping("/courseList") public String findCourseList(HttpServletRequest request) throws Exception { List<Course> courseList = courseService.findCourseList(); request.setAttribute("courseList", courseList); return "courseList.jsp"; } @RequestMapping("/courseDetail") public String findByNo( @RequestParam(value = "course_No", required = false) String courseNo, HttpServletRequest request) throws Exception { Course course = courseService.findByNo(courseNo); request.setAttribute("course", course); return "detail.jsp"; } // 根据条件 进行模糊查询 @RequestMapping("/courseFind") public String query( @RequestParam(value = "pageNum", required = false) Integer pageNum, Course course, HttpServletRequest request) throws Exception { Page<Course> pageBean = courseService.query(course, pageNum); request.setAttribute("course", course); request.setAttribute("pageBean", pageBean); return "querylist.jsp"; } // 分页查询 @RequestMapping("/coursePage") public String pageBean( @RequestParam(value = "pageNum", required = false) Integer pageNum, HttpServletRequest request) throws Exception { Page<Course> pageBean = courseService.queryPage(pageNum); request.setAttribute("pageBean", pageBean); return "courseslist.jsp"; } }
true
31e2d22bae864c69d351dbdcf3cfb4dd46598493
Java
Schiepek/RedditClone
/src/redditFinal/UsernameValidator.java
UTF-8
931
2.453125
2
[]
no_license
package redditFinal; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.Validator; import javax.faces.validator.ValidatorException; public class UsernameValidator implements Validator { @Override public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { redditBean redditBean = (redditBean)FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get("redditBean"); List<User> users = redditBean.getUsers(); String username = (String)value; for (User u : users) { if (u.getUsername().equals(username)) { //nameComponent.setValid(false); // So that it's marked invalid. System.out.println("UserValidator"); throw new ValidatorException(new FacesMessage("Username already exists.")); } } } }
true
857687f8f1f86924a865fb86d45a49b1af60fc5d
Java
rvanasa/vekta
/src/main/java/vekta/world/AttributeMaxZoomController.java
UTF-8
588
2.65625
3
[ "MIT" ]
permissive
package vekta.world; import vekta.player.Player; public class AttributeMaxZoomController implements ZoomController { private final Class<? extends Player.Attribute> type; private final float maxZoom; public AttributeMaxZoomController(Class<? extends Player.Attribute> type, float maxZoom) { this.type = type; this.maxZoom = maxZoom; } @Override public boolean shouldCancelZoomControl(Player player) { return !player.hasAttribute(type); } @Override public float controlZoom(Player player, float zoom) { if(zoom > maxZoom) { zoom = maxZoom; } return zoom; } }
true
5a21f0495433567599b1a2f99c50bf3968b9f310
Java
tobiasquinteiro/alura-cursos
/design-patterns-1/src/main/java/alura/curso/designpatterns1/strategy/Imposto.java
UTF-8
517
2.84375
3
[]
no_license
package alura.curso.designpatterns1.strategy; import alura.curso.designpatterns1.model.orcamento.Orcamento; public abstract class Imposto { protected Imposto outroImposto; public Imposto() { } public Imposto(Imposto outroImposto) { this.outroImposto = outroImposto; } public abstract double calcula(Orcamento orcamento); protected double calculoDoOutroImposto(Orcamento orcamento) { if (outroImposto == null) return 0.0; return outroImposto.calcula(orcamento); } }
true
cff182c7db0a21095b7abb7cceeae1b52a1b2467
Java
stdio-yj/packaging_yjyj
/src/study/jsp/myschool/controller/ProfDelete.java
UTF-8
1,653
2.171875
2
[]
no_license
package study.jsp.myschool.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.ibatis.session.SqlSession; import study.jsp.helper.BaseController; import study.jsp.helper.WebHelper; import study.jsp.myschool.dao.MyBatisConnectionFactory; import study.jsp.myschool.model.Professor; import study.jsp.myschool.service.ProfessorService; import study.jsp.myschool.service.impl.ProfessorServiceImpl; @WebServlet("/prof_delete.do") public class ProfDelete extends BaseController { private static final long serialVersionUID = -5683216243527784382L; WebHelper web; SqlSession sqlSession; ProfessorService professorService; @Override public String doRun(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { web = WebHelper.getInstance(request, response); int profno = web.getInt("profno"); logger.debug("profno=" + profno); if (profno == 0) { web.redirect(null, "교수번호가 없습니다."); return null; } Professor professor = new Professor(); professor.setProfno(profno); sqlSession = MyBatisConnectionFactory.getSqlSession(); professorService = new ProfessorServiceImpl(sqlSession, logger); try { professorService.deleteProfessor(professor); } catch (Exception e) { web.redirect(null, e.getLocalizedMessage()); return null; } finally { sqlSession.close(); } web.redirect(request.getContextPath()+ "/prof_list.do", "삭제되었습니다."); return null; } }
true
6b4c32373157848c609c129de19795da8d755421
Java
mavpokit/RxRetrofitMVP
/app/src/main/java/com/mavpokit/rxretrofitmvp/Presenter/QuestionsPresenter.java
UTF-8
5,155
2.21875
2
[]
no_license
package com.mavpokit.rxretrofitmvp.Presenter; import android.net.Uri; import android.os.Bundle; import com.mavpokit.rxretrofitmvp.DI.MyApplication; import com.mavpokit.rxretrofitmvp.Model.IModel; import com.mavpokit.rxretrofitmvp.Model.Pojo.ListQuestion; import com.mavpokit.rxretrofitmvp.View.IQuestionsView; import java.util.List; import javax.inject.Inject; import rx.Observer; import rx.Subscription; import rx.subscriptions.Subscriptions; /** * Created by Alex on 27.07.2016. */ public class QuestionsPresenter implements IQuestionsPresenter { //IModel model = new Model(); //before DI @Inject IModel model; private IQuestionsView view; private Subscription subscription = Subscriptions.empty(); private Subscription subscriptionSuggestions = Subscriptions.empty(); private ListQuestion listQuestion; private final static String Q_LIST_KEY = "questionList"; public QuestionsPresenter() { MyApplication.getAppComponent().inject(this); } @Override public void onSearchClick(String query) { if (!subscription.isUnsubscribed()) subscription.unsubscribe(); view.showSpinner(); subscription = model.getQuestionList(query).subscribe(new Observer<ListQuestion>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { view.showError(e.getLocalizedMessage()); view.hideSpinner(); } @Override public void onNext(ListQuestion questionList) { if (isListNotEmpty(questionList)) { listQuestion = questionList; view.showQuestionList(questionList); view.hideSpinner(); } else { listQuestion=null; view.showNothing(); view.hideSpinner(); } } }); model.addQueryToSuggestionsList(query, () -> initSuggestionList()); } @Override public void onStop() { if (!subscription.isUnsubscribed()) subscription.unsubscribe(); if (!subscriptionSuggestions.isUnsubscribed()) subscriptionSuggestions.unsubscribe(); } @Override public void onDestroy() { listQuestion=null; } @Override public void onCreate(IQuestionsView view, Bundle savedInstanceState) { this.view = view; // if (savedInstanceState != null) listQuestion = (ListQuestion) savedInstanceState.getSerializable(Q_LIST_KEY); initSuggestionList(); } /** * model asynchronously loads suggestions array and view adds it to searchview suggestion list */ void initSuggestionList() { if (!subscriptionSuggestions.isUnsubscribed()) subscriptionSuggestions.unsubscribe(); subscriptionSuggestions=model.loadSuggestions().subscribe(new Observer<List<String>>() { @Override public void onCompleted() {} @Override public void onError(Throwable e) {} @Override public void onNext(List<String> strings) { System.out.println("----------------------------------"+strings); view.initSuggestions(strings); } }); //this case worked well, but in QuestionsFragmentIntegrationTest we got rx.exceptions.OnErrorNotImplementedException //subscriptionSuggestions=model.loadSuggestions().subscribe(strings -> view.initSuggestions(strings)); } @Override public void onCreateView() { if (isListNotEmpty(listQuestion)) view.showQuestionList(listQuestion); else view.runQueryArrowAnimation(); } @Override public void onSaveInstanceState(Bundle outState) { //after retaining, we don't need to save this //if (isListNotEmpty(listQuestion)) //outState.putSerializable(Q_LIST_KEY, listQuestion); } @Override public void showAnswers(int position) { view.openAnswers(listQuestion.getItems().get(position)); } @Override public void openLink(int position) { view.openLink(Uri.parse(listQuestion.getItems().get(position).getLink())); } @Override public void onSuggestionClick(int position) { //suggestions are already loaded, so we can get suggest synchronously view.selectSuggestion(model.getSuggestion(position)); } private boolean isListNotEmpty(ListQuestion questionList) { return questionList != null && !questionList.getItems().isEmpty(); } //for Tests @Override public void setListQuestion(ListQuestion listQuestion) { this.listQuestion = listQuestion; } //for Tests @Override public ListQuestion getListQuestion() { return listQuestion; } }
true
055158414d6ac11c4ca94442d9fd8f689e4df174
Java
otailai/qrencode
/src/security/RSAEncrypt.java
UTF-8
1,006
2.796875
3
[]
no_license
package security; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.interfaces.RSAPrivateKey; import java.security.spec.PKCS8EncodedKeySpec; import javax.crypto.Cipher; public class RSAEncrypt { private static final String KEY_GENERATOR_ALGORITHM_NAME = "RSA"; private static final String CIPHER_INSTANCE_ALGORITHM_NAME = "RSA/ECB/NoPadding"; public static byte[] getRSAEncode(String src, RSAPrivateKey rsaPrivateKey) { byte[] result = null; try { PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded()); KeyFactory keyFactoryEncode = KeyFactory.getInstance(KEY_GENERATOR_ALGORITHM_NAME); PrivateKey privateKey = keyFactoryEncode.generatePrivate(pkcs8EncodedKeySpec); Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE_ALGORITHM_NAME); cipher.init(Cipher.ENCRYPT_MODE, privateKey); result = cipher.doFinal(src.getBytes()); } catch (Exception e) { e.printStackTrace(); } return result; } }
true
9a18c82e5c9657faa523b279f60a7be031755ab0
Java
pallavij/PCheck
/zook-fi/src/contrib/bookkeeper/src/java/org/apache/bookkeeper/client/LedgerMetadata.java
UTF-8
5,672
2.5
2
[ "Apache-2.0" ]
permissive
package org.apache.bookkeeper.client; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.apache.bookkeeper.util.StringUtils; import org.apache.log4j.Logger; /** * This class encapsulates all the ledger metadata that is persistently stored * in zookeeper. It provides parsing and serialization methods of such metadata. * */ class LedgerMetadata { static final Logger LOG = Logger.getLogger(LedgerMetadata.class); private static final String closed = "CLOSED"; private static final String lSplitter = "\n"; private static final String tSplitter = "\t"; // can't use -1 for NOTCLOSED because that is reserved for a closed, empty // ledger public static final int NOTCLOSED = -101; int ensembleSize; int quorumSize; long close; private SortedMap<Long, ArrayList<InetSocketAddress>> ensembles = new TreeMap<Long, ArrayList<InetSocketAddress>>(); ArrayList<InetSocketAddress> currentEnsemble; public LedgerMetadata(int ensembleSize, int quorumSize) { this.ensembleSize = ensembleSize; this.quorumSize = quorumSize; this.close = NOTCLOSED; }; private LedgerMetadata() { this(0, 0); } boolean isClosed() { return close != NOTCLOSED; } void close(long entryId) { close = entryId; } void addEnsemble(long startEntryId, ArrayList<InetSocketAddress> ensemble) { assert ensembles.isEmpty() || startEntryId >= ensembles.lastKey(); ensembles.put(startEntryId, ensemble); currentEnsemble = ensemble; } ArrayList<InetSocketAddress> getEnsemble(long entryId) { // the head map cannot be empty, since we insert an ensemble for // entry-id 0, right when we start return ensembles.get(ensembles.headMap(entryId + 1).lastKey()); } /** * the entry id > the given entry-id at which the next ensemble change takes * place ( -1 if no further ensemble changes) * * @param entryId * @return */ long getNextEnsembleChange(long entryId) { SortedMap<Long, ArrayList<InetSocketAddress>> tailMap = ensembles.tailMap(entryId + 1); if (tailMap.isEmpty()) { return -1; } else { return tailMap.firstKey(); } } /** * Generates a byte array based on a LedgerConfig object received. * * @param config * LedgerConfig object * @return byte[] */ public byte[] serialize() { StringBuilder s = new StringBuilder(); s.append(quorumSize).append(lSplitter).append(ensembleSize); for (Map.Entry<Long, ArrayList<InetSocketAddress>> entry : ensembles.entrySet()) { s.append(lSplitter).append(entry.getKey()); for (InetSocketAddress addr : entry.getValue()) { s.append(tSplitter); StringUtils.addrToString(s, addr); } } if (close != NOTCLOSED) { s.append(lSplitter).append(close).append(tSplitter).append(closed); } if (LOG.isDebugEnabled()) { LOG.debug("Serialized config: " + s.toString()); } return s.toString().getBytes(); } /** * Parses a given byte array and transforms into a LedgerConfig object * * @param array * byte array to parse * @return LedgerConfig * @throws IOException * if the given byte[] cannot be parsed */ static LedgerMetadata parseConfig(byte[] bytes) throws IOException { LedgerMetadata lc = new LedgerMetadata(); String config = new String(bytes); if (LOG.isDebugEnabled()) { LOG.debug("Parsing Config: " + config); } String lines[] = config.split(lSplitter); if (lines.length < 2) { throw new IOException("Quorum size or ensemble size absent from config: " + config); } try { lc.quorumSize = new Integer(lines[0]); lc.ensembleSize = new Integer(lines[1]); for (int i = 2; i < lines.length; i++) { String parts[] = lines[i].split(tSplitter); if (parts[1].equals(closed)) { lc.close = new Long(parts[0]); break; } ArrayList<InetSocketAddress> addrs = new ArrayList<InetSocketAddress>(); for (int j = 1; j < parts.length; j++) { addrs.add(StringUtils.parseAddr(parts[j])); } lc.addEnsemble(new Long(parts[0]), addrs); } } catch (NumberFormatException e) { throw new IOException(e); } return lc; } }
true
4f2c06ad8e0892f9884e925da8585453933781ad
Java
miroshnychenko/javacore
/src/main/java/com/serhii/app/classwork/lesson13/composition/Phone.java
UTF-8
601
2.921875
3
[]
no_license
package com.serhii.app.classwork.lesson13.composition; public class Phone { private NFC nfc; private Bluetooth bluetooth; private Battery battery; public Phone(NFC nfc, Bluetooth bluetooth, Battery battery) { this.nfc = nfc; this.bluetooth = bluetooth; this.battery = battery; } public NFC getNfc() { return nfc; } public Bluetooth getBluetooth() { return bluetooth; } public Battery getBattery() { return battery; } public void setBattery(Battery battery) { this.battery = battery; } }
true
4eff977b8b57b4a443d2ccbe567b265d5f8d58e7
Java
tomwhite/kite
/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/Constraints.java
UTF-8
21,390
1.71875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2013 Cloudera 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. */ package org.kitesdk.data.spi; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Range; import com.google.common.collect.Ranges; import com.google.common.collect.Sets; import org.apache.avro.Schema; import org.apache.avro.Schema.Parser; import org.apache.avro.generic.GenericRecord; import org.kitesdk.data.PartitionStrategy; import org.kitesdk.data.spi.partition.CalendarFieldPartitioner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.Locale; import java.util.Map; import java.util.Set; /** * A set of simultaneous constraints. * * This class accumulates and manages a set of logical constraints. */ @Immutable public class Constraints implements Serializable{ private static final long serialVersionUID = -155119355851820161L; private static final Logger LOG = LoggerFactory.getLogger(Constraints.class); private transient Schema schema; private transient Map<String, Predicate> constraints; public Constraints(Schema schema) { this.schema = schema; this.constraints = ImmutableMap.of(); } private Constraints(Schema schema, Map<String, Predicate> constraints, String name, Predicate predicate) { this.schema = schema; Map<String, Predicate> copy = Maps.newHashMap(constraints); copy.put(name, predicate); this.constraints = ImmutableMap.copyOf(copy); } /** * Get a {@link Predicate} for testing entity objects. * * @param <E> The type of entities to be matched * @return a Predicate to test if entity objects satisfy this constraint set */ public <E> Predicate<E> toEntityPredicate() { return new EntityPredicate<E>(constraints); } /** * Get a {@link Predicate} for testing entity objects that match the given * {@link StorageKey}. * * @param <E> The type of entities to be matched * @param key a StorageKey for entities tested with the Predicate * @return a Predicate to test if entity objects satisfy this constraint set */ public <E> Predicate<E> toEntityPredicate(StorageKey key) { if (key != null) { Map<String, Predicate> predicates = minimizeFor(key); if (predicates.isEmpty()) { return com.google.common.base.Predicates.alwaysTrue(); } return new EntityPredicate<E>(predicates); } return toEntityPredicate(); } @VisibleForTesting @SuppressWarnings("unchecked") Map<String, Predicate> minimizeFor(StorageKey key) { Map<String, Predicate> unsatisfied = Maps.newHashMap(constraints); PartitionStrategy strategy = key.getPartitionStrategy(); Set<String> timeFields = Sets.newHashSet(); int i = 0; for (FieldPartitioner fp : strategy.getFieldPartitioners()) { String field = fp.getSourceName(); if (fp instanceof CalendarFieldPartitioner) { // keep track of time fields to consider timeFields.add(field); } // remove the field if it is satisfied by the StorageKey Predicate original = unsatisfied.get(field); if (original != null) { Predicate isSatisfiedBy = fp.projectStrict(original); LOG.debug("original: " + original + ", strict: " + isSatisfiedBy); if ((isSatisfiedBy != null) && isSatisfiedBy.apply(key.get(i))) { LOG.debug("removing " + field + " satisfied by " + key.get(i)); unsatisfied.remove(field); } } i += 1; } // remove fields satisfied by the time predicates for (String timeField : timeFields) { Predicate<Long> original = unsatisfied.get(timeField); if (original != null) { Predicate<Marker> isSatisfiedBy = TimeDomain.get(strategy, timeField) .projectStrict(original); LOG.debug("original: " + original + ", strict: " + isSatisfiedBy); if ((isSatisfiedBy != null) && isSatisfiedBy.apply(key)) { LOG.debug("removing " + timeField + " satisfied by " + key); unsatisfied.remove(timeField); } } } return ImmutableMap.copyOf(unsatisfied); } @VisibleForTesting @SuppressWarnings("unchecked") Map<String, Predicate> minimizeFor( PartitionStrategy strategy, MarkerRange keyRange) { Map<String, Predicate> unsatisfied = Maps.newHashMap(constraints); Set<String> timeFields = Sets.newHashSet(); for (FieldPartitioner fp : strategy.getFieldPartitioners()) { String field = fp.getSourceName(); if (fp instanceof CalendarFieldPartitioner) { // keep track of time fields to consider timeFields.add(field); } String partitionName = fp.getName(); // add the non-time field if it is not satisfied by the MarkerRange Predicate original = unsatisfied.get(field); if (original != null) { Predicate isSatisfiedBy = fp.projectStrict(original); Marker start = keyRange.getStart().getBound(); Marker end = keyRange.getEnd().getBound(); // check both endpoints. this duplicates a lot of work because we are // using Markers rather than the original predicates if ((isSatisfiedBy != null) && !isSatisfiedBy.apply(start.get(partitionName)) && !isSatisfiedBy.apply(end.get(partitionName))) { unsatisfied.remove(field); } } } // add any time predicates that aren't satisfied by the MarkerRange for (String timeField : timeFields) { Predicate<Long> original = unsatisfied.get(timeField); if (original != null) { Predicate<Marker> isSatisfiedBy = TimeDomain.get(strategy, timeField) .projectStrict(original); // check both endpoints. this duplicates a lot of work because we are // using Markers rather than the original predicates if ((isSatisfiedBy != null) && isSatisfiedBy.apply(keyRange.getStart().getBound()) && isSatisfiedBy.apply(keyRange.getEnd().getBound())) { unsatisfied.remove(timeField); } } } return ImmutableMap.copyOf(unsatisfied); } /** * Get a {@link Predicate} that tests {@link StorageKey} objects. * * If a {@code StorageKey} matches the predicate, it <em>may</em> represent a * partition that is responsible for entities that match this set of * constraints. If it does not match the predicate, it cannot be responsible * for entities that match this constraint set. * * @return a Predicate for testing StorageKey objects */ public Predicate<StorageKey> toKeyPredicate() { return new KeyPredicate(constraints); } /** * Get a set of {@link MarkerRange} objects that covers the set of possible * {@link StorageKey} partitions for this constraint set, with respect to the * give {@link PartitionStrategy}. If a {@code StorageKey} is not in one of * the ranges returned by this method, then its partition cannot contain * entities that satisfy this constraint set. * * @param strategy a PartitionStrategy * @return an Iterable of MarkerRange */ public Iterable<MarkerRange> toKeyRanges(PartitionStrategy strategy) { return new KeyRangeIterable(strategy, constraints); } /** * If this returns true, the entities selected by this set of constraints * align to partition boundaries. * * For example, for a partition strategy [hash(num), identity(num)], * any constraint on the "num" field will be correctly enforced by the * partition predicate for this constraint set. However, a "color" field * wouldn't be satisfied by considering partition values alone and would * require further checks. * * An alternate explanation: This returns whether the key {@link Predicate} * from {@link #toKeyPredicate()} is equivalent to this set of constraints * under the given {@link PartitionStrategy}. The key predicate must accept a * key if that key's partition might include entities matched by this * constraint set. If this method returns true, then all entities in the * partitions it matches are guaranteed to match this constraint set. So, the * partitions are equivalent to the constraints. * * @param strategy a {@link PartitionStrategy} * @return true if this constraint set is satisfied by partitioning */ @SuppressWarnings("unchecked") public boolean alignedWithBoundaries(PartitionStrategy strategy) { Multimap<String, FieldPartitioner> partitioners = HashMultimap.create(); for (FieldPartitioner fp : strategy.getFieldPartitioners()) { partitioners.put(fp.getSourceName(), fp); } // The key predicate is equivalent to a constraint set when the permissive // projection for each predicate can be used in its place. This happens if // fp.project(predicate) == fp.projectStrict(predicate): // // let D = some value domain // let pred : D -> {0, 1} // let D_{pred} = {x \in D | pred(x) == 1} (a subset of D selected by pred) // // let fp : D -> S (also a value domain) // let fp.strict(pred) = pred_{fp.strict} : S -> {0, 1} (project strict) // s.t. pred_{fp.strict}(fp(x)) == 1 => pred(x) == 1 // let fp.project(pred) = pred_{fp.project} : S -> {0, 1} (project) // s.t. pred(x) == 1 => pred_{fp.project}(fp(x)) == 1 // // lemma. {x \in D | pred_{fp.strict}(fp(x))} is a subset of D_{pred} // pred_{fp.strict}(fp(x)) == 1 => pred(x) == 1 => x \in D_{pred} // // theorem. (pred_{fp.project}(s) => pred_{fp.strict}(s)) => // D_{pred} == {x \in D | pred_{fp.strict}(fp(x))} // // => let x \in D_{pred}. then pred_{fp.project}(fp(x)) == 1 by def // then pred_{fp.strict(fp(x)) == 1 by premise // therefore {x \in D | pred_{fp.strict}(fp(x))} \subsetOf D_{pred} // <= by previous lemma // // Note: if projectStrict is too conservative or project is too permissive, // then this logic cannot determine that that the original predicate is // satisfied for (Map.Entry<String, Predicate> entry : constraints.entrySet()) { Collection<FieldPartitioner> fps = partitioners.get(entry.getKey()); if (fps.isEmpty()) { return false; } Predicate predicate = entry.getValue(); if (!(predicate instanceof Predicates.Exists)) { boolean satisfied = false; for (FieldPartitioner fp : fps) { if (fp instanceof CalendarFieldPartitioner) { TimeDomain domain = TimeDomain.get(strategy, entry.getKey()); Predicate strict = domain.projectStrict(predicate); Predicate permissive = domain.project(predicate); satisfied = strict != null && strict.equals(permissive); break; } else { Predicate strict = fp.projectStrict(predicate); Predicate permissive = fp.project(predicate); if (strict != null && strict.equals(permissive)) { satisfied = true; break; } } } // this predicate cannot be satisfied by the partition information if (!satisfied) { return false; } } } return true; } @SuppressWarnings("unchecked") public Constraints with(String name, Object... values) { SchemaUtil.checkTypeConsistency(schema, name, values); if (values.length > 0) { checkContained(name, values); // this is the most specific constraint and is idempotent under "and" return new Constraints(schema, constraints, name, new Predicates.In<Object>(values)); } else { if (!constraints.containsKey(name)) { // no other constraint => add the exists return new Constraints(schema, constraints, name, Predicates.exists()); } else { // satisfied by an existing constraint return this; } } } public Constraints from(String name, Comparable value) { SchemaUtil.checkTypeConsistency(schema, name, value); checkContained(name, value); Range added = Ranges.atLeast(value); if (constraints.containsKey(name)) { return new Constraints(schema, constraints, name, and(constraints.get(name), added)); } else { return new Constraints(schema, constraints, name, added); } } public Constraints fromAfter(String name, Comparable value) { SchemaUtil.checkTypeConsistency(schema, name, value); checkContained(name, value); Range added = Ranges.greaterThan(value); if (constraints.containsKey(name)) { return new Constraints(schema, constraints, name, and(constraints.get(name), added)); } else { return new Constraints(schema, constraints, name, added); } } public Constraints to(String name, Comparable value) { SchemaUtil.checkTypeConsistency(schema, name, value); checkContained(name, value); Range added = Ranges.atMost(value); if (constraints.containsKey(name)) { return new Constraints(schema, constraints, name, and(constraints.get(name), added)); } else { return new Constraints(schema, constraints, name, added); } } public Constraints toBefore(String name, Comparable value) { SchemaUtil.checkTypeConsistency(schema, name, value); checkContained(name, value); Range added = Ranges.lessThan(value); if (constraints.containsKey(name)) { return new Constraints(schema, constraints, name, and(constraints.get(name), added)); } else { return new Constraints(schema, constraints, name, added); } } /** * Returns the predicate for a named field. * * For testing. * * @param name a String field name * @return a Predicate for the given field, or null if none is set */ @VisibleForTesting Predicate get(String name) { return constraints.get(name); } @SuppressWarnings("unchecked") private void checkContained(String name, Object... values) { for (Object value : values) { if (constraints.containsKey(name)) { Predicate current = constraints.get(name); Preconditions.checkArgument(current.apply(value), "%s does not match %s", current, value); } } } @Override public String toString() { return Objects.toStringHelper(this).addValue(constraints).toString(); } /** * Writes out the {@link Constraints} using Java serialization. */ private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeUTF(schema.toString()); ConstraintsSerialization.writeConstraints(schema, constraints, out); } /** * Reads in the {@link Constraints} from the provided {@code in} stream. * @param in the stream from which to deserialize the object. * @throws IOException error deserializing the {@link Constraints} * @throws ClassNotFoundException Unable to properly access values inside the {@link Constraints} */ private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException{ in.defaultReadObject(); schema = new Parser().parse(in.readUTF()); constraints = ImmutableMap.copyOf(ConstraintsSerialization.readConstraints(schema, in)); } @SuppressWarnings("unchecked") private static Predicate and(Predicate previous, Range additional) { if (previous instanceof Range) { // return the intersection return ((Range) previous).intersection(additional); } else if (previous instanceof Predicates.In) { // filter the set using the range return ((Predicates.In) previous).filter(additional); } else if (previous instanceof Predicates.Exists) { // exists is the weakest constraint, satisfied by any existing constraint // all values in the range are non-null return additional; } else { // previous must be null, return the new constraint return additional; } } /** * A {@link Predicate} for testing entities against a set of predicates. * * @param <E> The type of entities this predicate tests */ private static class EntityPredicate<E> implements Predicate<E> { private final Map<String, Predicate> predicates; public EntityPredicate(Map<String, Predicate> predicates) { this.predicates = predicates; } @Override @SuppressWarnings("unchecked") public boolean apply(@Nullable E entity) { if (entity == null) { return false; } // check each constraint and fail immediately for (Map.Entry<String, Predicate> entry : predicates.entrySet()) { if (!entry.getValue().apply(get(entity, entry.getKey()))) { return false; } } // all constraints were satisfied return true; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || !getClass().equals(obj.getClass())) { return false; } return Objects.equal(predicates, ((EntityPredicate) obj).predicates); } @Override public int hashCode() { return Objects.hashCode(predicates); } private static Object get(Object entity, String name) { if (entity instanceof GenericRecord) { return ((GenericRecord) entity).get(name); } else { try { PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, entity.getClass(), getter(name), null /* assume read only */); return propertyDescriptor.getReadMethod().invoke(entity); } catch (IllegalAccessException e) { throw new IllegalStateException("Cannot read property " + name + " from " + entity, e); } catch (InvocationTargetException e) { throw new IllegalStateException("Cannot read property " + name + " from " + entity, e); } catch (IntrospectionException e) { throw new IllegalStateException("Cannot read property " + name + " from " + entity, e); } } } private static String getter(String name) { return "get" + name.substring(0, 1).toUpperCase(Locale.ENGLISH) + name.substring(1); } @Override public String toString() { return Objects.toStringHelper(this).addValue(predicates).toString(); } } /** * A {@link Predicate} for testing a {@link StorageKey} against a set of * predicates. */ private static class KeyPredicate implements Predicate<StorageKey> { private final Map<String, Predicate> predicates; private KeyPredicate(Map<String, Predicate> predicates) { this.predicates = predicates; } @Override @SuppressWarnings("unchecked") public boolean apply(StorageKey key) { if (key == null) { return false; } PartitionStrategy strategy = key.getPartitionStrategy(); // (source) time fields that affect the partition strategy Set<String> timeFields = Sets.newHashSet(); // this is fail-fast: if the key fails a constraint, then drop it for (FieldPartitioner fp : strategy.getFieldPartitioners()) { Predicate constraint = predicates.get(fp.getSourceName()); if (constraint == null) { // no constraints => anything matches continue; } Object pValue = key.get(fp.getName()); if (fp instanceof CalendarFieldPartitioner) { timeFields.add(fp.getSourceName()); } Predicate projectedConstraint = fp.project(constraint); if (projectedConstraint != null && !(projectedConstraint.apply(pValue))) { return false; } } // check multi-field time groups for (String sourceName : timeFields) { Predicate<Marker> timePredicate = TimeDomain .get(strategy, sourceName) .project(predicates.get(sourceName)); if (timePredicate != null && !timePredicate.apply(key)) { return false; } } // if we made it this far, everything passed return true; } @Override public String toString() { return Objects.toStringHelper(this).addValue(predicates).toString(); } } }
true
d99bebf1361364f39bae0b00ae7810bfe7e687c3
Java
Akshay8797/IBM-Training
/AdApplication/src/main/java/com/Spring/Controller/AdvertisementController.java
UTF-8
2,080
2.1875
2
[]
no_license
package com.Spring.Controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.Spring.Json.Advertise; import com.Spring.Service.AdvertiseService; import com.Spring.Service.UserService; @RestController @RequestMapping("/Ad") public class AdvertisementController { @Autowired private AdvertiseService advService; @PostMapping(value = "/advertise", consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody Advertise createNewAdvertise(@RequestBody Advertise advertise, @RequestHeader(value = "auth-token") String authToken) { if (UserService.isValid(authToken)) { return advService.createNewAdvertise(advertise); } else return null; } @GetMapping("/advertise") public List<Advertise> getAllAdvertises() { return advService.getAllAds(); } @GetMapping("/advertise/{id}") public Advertise getAdvertisesById(@PathVariable(value = "aid") String Aid) { return advService.getAdById(Aid); } @PutMapping(value = "/advertise/{id}", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody Advertise updateAdvertise(@RequestBody Advertise advertise, @PathVariable(value = "aid") String Aid) { return advService.update(advertise, Aid); } @DeleteMapping(value = "/advertise/{id}") public boolean deleteAd(@PathVariable(value = "id") String Aid) { return advService.delete(Aid); } }
true
0cf357c44acf4a652557f9b21e4c71f02412d53a
Java
ahjszhds/grpc-java
/okhttp/src/main/java/io/grpc/okhttp/OkHttpClientStream.java
UTF-8
12,154
1.570313
2
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
/* * Copyright 2014, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.grpc.okhttp; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.io.BaseEncoding; import io.grpc.Attributes; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.Status; import io.grpc.internal.AbstractClientStream2; import io.grpc.internal.GrpcUtil; import io.grpc.internal.Http2ClientStreamTransportState; import io.grpc.internal.StatsTraceContext; import io.grpc.internal.WritableBuffer; import io.grpc.okhttp.internal.framed.ErrorCode; import io.grpc.okhttp.internal.framed.Header; import java.util.ArrayDeque; import java.util.List; import java.util.Queue; import javax.annotation.concurrent.GuardedBy; import okio.Buffer; /** * Client stream for the okhttp transport. */ class OkHttpClientStream extends AbstractClientStream2 { private static final int WINDOW_UPDATE_THRESHOLD = Utils.DEFAULT_WINDOW_SIZE / 2; private static final Buffer EMPTY_BUFFER = new Buffer(); public static final int ABSENT_ID = -1; private final MethodDescriptor<?, ?> method; private final String userAgent; private final StatsTraceContext statsTraceCtx; private String authority; private Object outboundFlowState; private volatile int id = ABSENT_ID; private final TransportState state; private final Sink sink = new Sink(); OkHttpClientStream( MethodDescriptor<?, ?> method, Metadata headers, AsyncFrameWriter frameWriter, OkHttpClientTransport transport, OutboundFlowController outboundFlow, Object lock, int maxMessageSize, String authority, String userAgent, StatsTraceContext statsTraceCtx) { super(new OkHttpWritableBufferAllocator(), statsTraceCtx, headers, method.isSafe()); this.statsTraceCtx = checkNotNull(statsTraceCtx, "statsTraceCtx"); this.method = method; this.authority = authority; this.userAgent = userAgent; this.state = new TransportState(maxMessageSize, statsTraceCtx, lock, frameWriter, outboundFlow, transport); } @Override protected TransportState transportState() { return state; } @Override protected Sink abstractClientStreamSink() { return sink; } /** * Returns the type of this stream. */ public MethodDescriptor.MethodType getType() { return method.getType(); } public int id() { return id; } @Override public void setAuthority(String authority) { this.authority = checkNotNull(authority, "authority"); } @Override public Attributes getAttributes() { return Attributes.EMPTY; } class Sink implements AbstractClientStream2.Sink { @Override public void writeHeaders(Metadata metadata, byte[] payload) { String defaultPath = "/" + method.getFullMethodName(); if (payload != null) { defaultPath += "?" + BaseEncoding.base64().encode(payload); } metadata.discardAll(GrpcUtil.USER_AGENT_KEY); synchronized (state.lock) { state.streamReady(metadata, defaultPath); } } @Override public void writeFrame(WritableBuffer frame, boolean endOfStream, boolean flush) { Buffer buffer; if (frame == null) { buffer = EMPTY_BUFFER; } else { buffer = ((OkHttpWritableBuffer) frame).buffer(); int size = (int) buffer.size(); if (size > 0) { onSendingBytes(size); } } synchronized (state.lock) { state.sendBuffer(buffer, endOfStream, flush); } } @Override public void request(final int numMessages) { synchronized (state.lock) { state.requestMessagesFromDeframer(numMessages); } } @Override public void cancel(Status reason) { synchronized (state.lock) { state.cancel(reason, null); } } } class TransportState extends Http2ClientStreamTransportState { private final Object lock; @GuardedBy("lock") private List<Header> requestHeaders; /** * Null iff {@link #requestHeaders} is null. Non-null iff neither {@link #cancel} nor * {@link #start(int)} have been called. */ @GuardedBy("lock") private Queue<PendingData> pendingData = new ArrayDeque<PendingData>(); @GuardedBy("lock") private boolean cancelSent = false; @GuardedBy("lock") private int window = Utils.DEFAULT_WINDOW_SIZE; @GuardedBy("lock") private int processedWindow = Utils.DEFAULT_WINDOW_SIZE; @GuardedBy("lock") private final AsyncFrameWriter frameWriter; @GuardedBy("lock") private final OutboundFlowController outboundFlow; @GuardedBy("lock") private final OkHttpClientTransport transport; public TransportState( int maxMessageSize, StatsTraceContext statsTraceCtx, Object lock, AsyncFrameWriter frameWriter, OutboundFlowController outboundFlow, OkHttpClientTransport transport) { super(maxMessageSize, statsTraceCtx); this.lock = checkNotNull(lock, "lock"); this.frameWriter = frameWriter; this.outboundFlow = outboundFlow; this.transport = transport; } @GuardedBy("lock") public void start(int streamId) { checkState(id == ABSENT_ID, "the stream has been started with id %s", streamId); id = streamId; state.onStreamAllocated(); if (pendingData != null) { // Only happens when the stream has neither been started nor cancelled. frameWriter.synStream(false, false, id, 0, requestHeaders); statsTraceCtx.clientOutboundHeaders(); requestHeaders = null; boolean flush = false; while (!pendingData.isEmpty()) { PendingData data = pendingData.poll(); outboundFlow.data(data.endOfStream, id, data.buffer, false); if (data.flush) { flush = true; } } if (flush) { outboundFlow.flush(); } pendingData = null; } } @GuardedBy("lock") @Override protected void onStreamAllocated() { super.onStreamAllocated(); } @GuardedBy("lock") @Override protected void http2ProcessingFailed(Status status, Metadata trailers) { cancel(status, trailers); } @GuardedBy("lock") @Override protected void deframeFailed(Throwable cause) { http2ProcessingFailed(Status.fromThrowable(cause), new Metadata()); } @GuardedBy("lock") @Override public void bytesRead(int processedBytes) { processedWindow -= processedBytes; if (processedWindow <= WINDOW_UPDATE_THRESHOLD) { int delta = Utils.DEFAULT_WINDOW_SIZE - processedWindow; window += delta; processedWindow += delta; frameWriter.windowUpdate(id(), delta); } } /** * Must be called with holding the transport lock. */ @GuardedBy("lock") public void transportHeadersReceived(List<Header> headers, boolean endOfStream) { if (endOfStream) { transportTrailersReceived(Utils.convertTrailers(headers)); onEndOfStream(); } else { transportHeadersReceived(Utils.convertHeaders(headers)); } } /** * Must be called with holding the transport lock. */ @GuardedBy("lock") public void transportDataReceived(okio.Buffer frame, boolean endOfStream) { // We only support 16 KiB frames, and the max permitted in HTTP/2 is 16 MiB. This is verified // in OkHttp's Http2 deframer. In addition, this code is after the data has been read. int length = (int) frame.size(); window -= length; if (window < 0) { frameWriter.rstStream(id(), ErrorCode.FLOW_CONTROL_ERROR); transport.finishStream(id(), Status.INTERNAL.withDescription( "Received data size exceeded our receiving window size"), null, null); return; } super.transportDataReceived(new OkHttpReadableBuffer(frame), endOfStream); if (endOfStream) { onEndOfStream(); } } @GuardedBy("lock") private void onEndOfStream() { if (!framer().isClosed()) { // If server's end-of-stream is received before client sends end-of-stream, we just send a // reset to server to fully close the server side stream. transport.finishStream(id(), null, ErrorCode.CANCEL, null); } else { transport.finishStream(id(), null, null, null); } } @GuardedBy("lock") private void cancel(Status reason, Metadata trailers) { if (cancelSent) { return; } cancelSent = true; if (pendingData != null) { // stream is pending. transport.removePendingStream(OkHttpClientStream.this); // release holding data, so they can be GCed or returned to pool earlier. requestHeaders = null; for (PendingData data : pendingData) { data.buffer.clear(); } pendingData = null; transportReportStatus(reason, true, trailers != null ? trailers : new Metadata()); } else { // If pendingData is null, start must have already been called, which means synStream has // been called as well. transport.finishStream(id(), reason, ErrorCode.CANCEL, trailers); } } @GuardedBy("lock") private void sendBuffer(Buffer buffer, boolean endOfStream, boolean flush) { if (cancelSent) { return; } if (pendingData != null) { // Stream is pending start, queue the data. pendingData.add(new PendingData(buffer, endOfStream, flush)); } else { checkState(id() != ABSENT_ID, "streamId should be set"); // If buffer > frameWriter.maxDataLength() the flow-controller will ensure that it is // properly chunked. outboundFlow.data(endOfStream, id(), buffer, flush); } } @GuardedBy("lock") private void streamReady(Metadata metadata, String path) { requestHeaders = Headers.createRequestHeaders(metadata, path, authority, userAgent); transport.streamReadyToStart(OkHttpClientStream.this); } } void setOutboundFlowState(Object outboundFlowState) { this.outboundFlowState = outboundFlowState; } Object getOutboundFlowState() { return outboundFlowState; } private static class PendingData { Buffer buffer; boolean endOfStream; boolean flush; PendingData(Buffer buffer, boolean endOfStream, boolean flush) { this.buffer = buffer; this.endOfStream = endOfStream; this.flush = flush; } } }
true
050ff3f3550c40b584ca4e944f3b3bb0b314c31c
Java
JellyB/code_back
/tk_code/course-server/course-web-server/src/main/java/com/huatu/tiku/course/service/v1/practice/CoursewarePracticeQuestionInfoService.java
UTF-8
687
1.828125
2
[]
no_license
package com.huatu.tiku.course.service.v1.practice; import com.huatu.tiku.course.bean.vo.CoursewarePracticeQuestionVo; import com.huatu.tiku.entity.CoursewarePracticeQuestionInfo; import service.BaseServiceHelper; /** * @author shanjigang * @date 2019/3/23 18:56 */ public interface CoursewarePracticeQuestionInfoService extends BaseServiceHelper<CoursewarePracticeQuestionInfo> { /** * 根据 roomId coursewareId 列表查询 */ CoursewarePracticeQuestionVo findByCoursewareIdAndRoomId(Long roomId, Long coursewareId); /** * 生成课件下试题作答信息 * @param roomId roomId */ void generateCoursewareAnswerCardInfo(Long roomId); }
true
aab708a4d56de8d0af7a7996fc0675d196db5989
Java
IELBHJY/DS_exercise
/maze/src/com/company/Node.java
UTF-8
387
2.640625
3
[]
no_license
package com.company; /** * Created by apple on 2018/3/1. */ public class Node { int x; int y; Node pre; int gCost; int hEstimate; int fTotal; public Node(int x, int y) { this.x = x; this.y = y; } @Override public String toString(){ return "["+x+","+y+"]"; } }
true
3ce7fbde97577bca172e7e4eb9458b03a11ea9d7
Java
WxSmile/ReactiveXLearn
/rxjavademo/src/main/java/com/weixiao/rxjavademo/创建操作/Create.java
UTF-8
1,500
3.40625
3
[]
no_license
package com.weixiao.rxjavademo.创建操作; import rx.Observable; import rx.Subscriber; /** * Created by weixiao-sm on 2016/9/27. */ public class Create { public static void main(String[] args) { Observable.create(new Observable.OnSubscribe<Integer>(){ @Override public void call(Subscriber<? super Integer> obsever) { try { if(!obsever.isUnsubscribed()){//如果没有被取消订阅 for (int i = 0; i < 5; i++) { obsever.onNext(i); } } obsever.onCompleted(); } catch (Exception e) { obsever.onError(e); } } }).subscribe(new Subscriber<Integer>() { @Override public void onCompleted() { System.out.println("Sequence complete."); } @Override public void onError(Throwable e) { System.out.println("e = [" + e.getMessage() + "]"); } @Override public void onNext(Integer item) { System.out.println("Next item = [" + item + "]"); } }); } /** * 使用一个函数从头创建一个可观察对象 * 运行结果 Next item = [0] Next item = [1] Next item = [2] Next item = [3] Next item = [4] Sequence complete. */ }
true
7164d49b337b6f7805b0ee3d75d5a29f20013fcd
Java
AlbertProfe/JAVA_pqtm2019
/EmpleadoComisionEx/src/herenciaEx/Persona.java
UTF-8
1,064
3.125
3
[]
no_license
package herenciaEx; public class Persona { private String nombre; private Fecha fechaNacimiento; private int dni; public Persona(String nombre, Fecha fechaNacimiento, int dni) { this.nombre = nombre; this.fechaNacimiento = fechaNacimiento; this.dni = dni; } public Persona(String nombre, int dni) { this.nombre = nombre; this.fechaNacimiento = null; this.dni = dni; } public void imprimirDatos() { System.out.print("DNI: "); System.out.println(dni); System.out.println("NOMBRE: " + nombre); System.out.print("FECHA DE NACIMIENTO: "); fechaNacimiento.imprimir(); System.out.println(); } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public Fecha getFechaNacimiento() { return fechaNacimiento; } public void setFechaNacimiento(Fecha fechaNacimiento) { this.fechaNacimiento = fechaNacimiento; } public int getDni() { return dni; } public void setDni(int dni) { this.dni = dni; } }
true
bdbde0adcd9214748da298245a874bc8abf9fcc1
Java
kr11/incubator-iotdb
/cluster/src/main/java/org/apache/iotdb/cluster/query/fill/ClusterPreviousFill.java
UTF-8
9,546
1.523438
2
[ "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "MIT", "EPL-1.0", "CDDL-1.1" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iotdb.cluster.query.fill; import org.apache.iotdb.cluster.client.async.AsyncDataClient; import org.apache.iotdb.cluster.client.sync.SyncClientAdaptor; import org.apache.iotdb.cluster.client.sync.SyncDataClient; import org.apache.iotdb.cluster.config.ClusterDescriptor; import org.apache.iotdb.cluster.exception.CheckConsistencyException; import org.apache.iotdb.cluster.exception.QueryTimeOutException; import org.apache.iotdb.cluster.partition.PartitionGroup; import org.apache.iotdb.cluster.rpc.thrift.Node; import org.apache.iotdb.cluster.rpc.thrift.PreviousFillRequest; import org.apache.iotdb.cluster.server.RaftServer; import org.apache.iotdb.cluster.server.handlers.caller.PreviousFillHandler; import org.apache.iotdb.cluster.server.member.DataGroupMember; import org.apache.iotdb.cluster.server.member.MetaGroupMember; import org.apache.iotdb.cluster.utils.ClientUtils; import org.apache.iotdb.cluster.utils.PartitionUtils.Intervals; import org.apache.iotdb.db.exception.StorageEngineException; import org.apache.iotdb.db.exception.query.QueryProcessException; import org.apache.iotdb.db.metadata.PartialPath; import org.apache.iotdb.db.query.context.QueryContext; import org.apache.iotdb.db.query.executor.fill.PreviousFill; import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType; import org.apache.iotdb.tsfile.read.TimeValuePair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class ClusterPreviousFill extends PreviousFill { private static final Logger logger = LoggerFactory.getLogger(ClusterPreviousFill.class); private MetaGroupMember metaGroupMember; private TimeValuePair fillResult; ClusterPreviousFill(PreviousFill fill, MetaGroupMember metaGroupMember) { super(fill.getDataType(), fill.getQueryTime(), fill.getBeforeRange()); this.metaGroupMember = metaGroupMember; } ClusterPreviousFill( TSDataType dataType, long queryTime, long beforeRange, MetaGroupMember metaGroupMember) { super(dataType, queryTime, beforeRange); this.metaGroupMember = metaGroupMember; } @Override public void configureFill( PartialPath path, TSDataType dataType, long queryTime, Set<String> deviceMeasurements, QueryContext context) { try { fillResult = performPreviousFill( path, dataType, queryTime, getBeforeRange(), deviceMeasurements, context); } catch (StorageEngineException e) { logger.error("Failed to configure previous fill for Path {}", path, e); } } @Override public TimeValuePair getFillResult() { return fillResult; } private TimeValuePair performPreviousFill( PartialPath path, TSDataType dataType, long queryTime, long beforeRange, Set<String> deviceMeasurements, QueryContext context) throws StorageEngineException { // make sure the partition table is new try { metaGroupMember.syncLeaderWithConsistencyCheck(false); } catch (CheckConsistencyException e) { throw new StorageEngineException(e); } // find the groups that should be queried using the time range Intervals intervals = new Intervals(); long lowerBound = beforeRange == -1 ? Long.MIN_VALUE : queryTime - beforeRange; intervals.addInterval(lowerBound, queryTime); List<PartitionGroup> partitionGroups = metaGroupMember.routeIntervals(intervals, path); if (logger.isDebugEnabled()) { logger.debug( "{}: Sending data query of {} to {} groups", metaGroupMember.getName(), path, partitionGroups.size()); } CountDownLatch latch = new CountDownLatch(partitionGroups.size()); PreviousFillHandler handler = new PreviousFillHandler(latch); ExecutorService fillService = Executors.newFixedThreadPool(partitionGroups.size()); PreviousFillArguments arguments = new PreviousFillArguments(path, dataType, queryTime, beforeRange, deviceMeasurements); for (PartitionGroup partitionGroup : partitionGroups) { fillService.submit(() -> performPreviousFill(arguments, context, partitionGroup, handler)); } fillService.shutdown(); try { fillService.awaitTermination(RaftServer.getReadOperationTimeoutMS(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error("Unexpected interruption when waiting for fill pool to stop", e); } return handler.getResult(); } private void performPreviousFill( PreviousFillArguments arguments, QueryContext context, PartitionGroup group, PreviousFillHandler fillHandler) { if (group.contains(metaGroupMember.getThisNode())) { localPreviousFill(arguments, context, group, fillHandler); } else { remotePreviousFill(arguments, context, group, fillHandler); } } private void localPreviousFill( PreviousFillArguments arguments, QueryContext context, PartitionGroup group, PreviousFillHandler fillHandler) { DataGroupMember localDataMember = metaGroupMember.getLocalDataMember(group.getHeader()); try { fillHandler.onComplete( localDataMember .getLocalQueryExecutor() .localPreviousFill( arguments.getPath(), arguments.getDataType(), arguments.getQueryTime(), arguments.getBeforeRange(), arguments.getDeviceMeasurements(), context)); } catch (QueryProcessException | StorageEngineException | IOException e) { fillHandler.onError(e); } } private void remotePreviousFill( PreviousFillArguments arguments, QueryContext context, PartitionGroup group, PreviousFillHandler fillHandler) { PreviousFillRequest request = new PreviousFillRequest( arguments.getPath().getFullPath(), arguments.getQueryTime(), arguments.getBeforeRange(), context.getQueryId(), metaGroupMember.getThisNode(), group.getHeader(), arguments.getDataType().ordinal(), arguments.getDeviceMeasurements()); for (Node node : group) { ByteBuffer byteBuffer; if (ClusterDescriptor.getInstance().getConfig().isUseAsyncServer()) { byteBuffer = remoteAsyncPreviousFill(node, request, arguments); } else { byteBuffer = remoteSyncPreviousFill(node, request, arguments); } if (byteBuffer != null) { fillHandler.onComplete(byteBuffer); return; } } fillHandler.onError( new QueryTimeOutException( String.format( "PreviousFill %s@%d range: %d", arguments.getPath().getFullPath(), arguments.getQueryTime(), arguments.getBeforeRange()))); } private ByteBuffer remoteAsyncPreviousFill( Node node, PreviousFillRequest request, PreviousFillArguments arguments) { ByteBuffer byteBuffer = null; AsyncDataClient asyncDataClient; try { asyncDataClient = metaGroupMember .getClientProvider() .getAsyncDataClient(node, RaftServer.getReadOperationTimeoutMS()); } catch (IOException e) { logger.warn("{}: Cannot connect to {} during previous fill", metaGroupMember, node); return null; } try { byteBuffer = SyncClientAdaptor.previousFill(asyncDataClient, request); } catch (Exception e) { logger.error( "{}: Cannot perform previous fill of {} to {}", metaGroupMember, arguments.getPath(), node, e); } return byteBuffer; } private ByteBuffer remoteSyncPreviousFill( Node node, PreviousFillRequest request, PreviousFillArguments arguments) { ByteBuffer byteBuffer = null; SyncDataClient syncDataClient = null; try { syncDataClient = metaGroupMember .getClientProvider() .getSyncDataClient(node, RaftServer.getReadOperationTimeoutMS()); byteBuffer = syncDataClient.previousFill(request); } catch (Exception e) { logger.error( "{}: Cannot perform previous fill of {} to {}", metaGroupMember.getName(), arguments.getPath(), node, e); } finally { ClientUtils.putBackSyncClient(syncDataClient); } return byteBuffer; } }
true
e0d24e57fff7155613adf3c1c505f7b8a6a0caf1
Java
dursunkoc/Wolf
/src/main/java/com/aric/esb/arguments/SimpleArgument.java
UTF-8
1,174
3.359375
3
[]
no_license
package com.aric.esb.arguments; /** * @author Dursun KOC * */ public class SimpleArgument extends Argument { private Object value; private Class<?> represantClass; public SimpleArgument(String name, Object value) { super(name); if (value == null) { throw new RuntimeException("value cannot be null!"); } this.value = value; } public SimpleArgument(String name, Object value, Class<?> represantClass) { super(name); if (value == null && represantClass == null) { throw new RuntimeException( "Both value and represantClass cannot be null at the same time."); } if (value != null && represantClass != null && !represantClass.isAssignableFrom(value.getClass())) { throw new RuntimeException( "represantClass is not assignable from value"); } this.value = value; this.represantClass = represantClass; } @Override public Class<?> getRepresantClass() { if (this.represantClass != null) { return this.represantClass; } else if (value != null) { return value.getClass(); } else { return null; } } @Override public Object getValue() { return value; } }
true
56b5860f06585d1aad77f677eee38361ea9fd70e
Java
tkhdfz/spring-data-elasticsearch-sample
/src/main/java/my/sample/elasticsearch/service/ESService.java
UTF-8
262
1.53125
2
[]
no_license
package my.sample.elasticsearch.service; import java.util.List; import java.util.Map; public interface ESService { List<String> handleLocalPlugin(String command, String target); List<String> getPluginInfo(); Map<String, String> getNodeSetting(); }
true
065e17c7c3d8649370c92f4cbbaaa3bc9b6571b9
Java
FlaviaSalazar27/pumitachatbot
/src/main/java/com/ChiquiBot/core/From.java
UTF-8
523
2.046875
2
[]
no_license
package com.ChiquiBot.core; public class From { private int id; private boolean is_bot; private String first_name; private String last_name; private String language_code; public int getId() { return id; } public boolean isIs_bot() { return is_bot; } public String getFirst_name() { return first_name; } public String getLast_name() { return last_name; } public String getLanguage_code() { return language_code; } }
true
c66ffb1013a7eff54fd9efec44fce4de47fd440f
Java
SkyTaill/MailKurs
/ZeroHomework/src/com/company/Main.java
UTF-8
661
3.203125
3
[]
no_license
package com.company; import java.util.Random; import java.util.Scanner; public class Main { private static Scanner scanner=new Scanner(System.in); public static void main(String[] args) { System.out.println("ВВедите число"); for (int i=10;i<=30;i+=10) { int inputNumber = scanner.nextInt(); FindRand(inputNumber); } } public static int FindRand(int i){ final Random random = new Random(); int x = random.nextInt(10) + 0; if (i==x) System.out.println("Угадали"); else {System.out.println("Ne ygodal"); System.out.println(x);} return(1); } }
true
279dcf57a36782889069f1b49b7fdd5b73a5a7cd
Java
marcio944/triagemeletronica
/TriagemEletronica/src/triagemeletronica/paciente/Paciente.java
UTF-8
4,517
2.265625
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 triagemeletronica.paciente; /** * * @author Esdras Fragoso */ public class Paciente { private String nome; private String rua; private int numero; private String bairro; private String cidade; private String cep; private String cartao_sus; private String rg; private String procedencia; private String motivo_da_vinda; private String zona; private boolean dores; private float temperatura; private float sistole; private float diastola; private boolean diabetico; private float resultado_test_clicemia; private boolean alergia; private String resultado_alergia; private int cor; private int diarreia; private int vomito; public int getDiarreia() { return diarreia; } public void setDiarreia(int diarreia) { this.diarreia = diarreia; } public int getVomito() { return vomito; } public void setVomito(int vomito) { this.vomito = vomito; } public int getNumero() { return numero; } public void setNumero(int numero) { this.numero = numero; } public int getCor() { return cor; } public void setCor(int cor) { this.cor = cor; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getRua() { return rua; } public void setRua(String rua) { this.rua = rua; } public String getBairro() { return bairro; } public void setBairro(String bairro) { this.bairro = bairro; } public String getCidade() { return cidade; } public void setCidade(String cidade) { this.cidade = cidade; } public String getCep() { return cep; } public void setCep(String cep) { this.cep = cep; } public String getCartao_sus() { return cartao_sus; } public void setCartao_sus(String cartao_sus) { this.cartao_sus = cartao_sus; } public String getRg() { return rg; } public void setRg(String rg) { this.rg = rg; } public String getProcedencia() { return procedencia; } public void setProcedencia(String procedencia) { this.procedencia = procedencia; } public String getMotivo_da_vinda() { return motivo_da_vinda; } public void setMotivo_da_vinda(String motivo_da_vinda) { this.motivo_da_vinda = motivo_da_vinda; } public String getZona() { return zona; } public void setZona(String zona) { this.zona = zona; } public boolean isDores() { return dores; } public void setDores(boolean dores) { this.dores = dores; } public float getTemperatura() { return temperatura; } public void setTemperatura(float temperatura) { this.temperatura = temperatura; } public float getSistole() { return sistole; } public void setSistole(float sistole) { this.sistole = sistole; } public float getDiastola() { return diastola; } public void setDiastola(float diastola) { this.diastola = diastola; } public boolean isDiabetico() { return diabetico; } public void setDiabetico(boolean diabetico) { this.diabetico = diabetico; } public float getResultado_test_clicemia() { return resultado_test_clicemia; } public void setResultado_test_clicemia(float resultado_test_clicemia) { this.resultado_test_clicemia = resultado_test_clicemia; } public boolean isAlergia() { return alergia; } public void setAlergia(boolean alergia) { this.alergia = alergia; } public String getResultado_alergia() { return resultado_alergia; } public void setResultado_alergia(String resultado_alergia) { this.resultado_alergia = resultado_alergia; } public Paciente() { } }
true
db6f43f671e1392737b20e3c0e3dfb073eacc5db
Java
maanasasubrahmanyam-sd/eclipse-workspace
/MyLearning/src/com/home/test/BinarySearch.java
UTF-8
901
3.734375
4
[]
no_license
package com.home.test; import java.util.Arrays; public class BinarySearch { // public static void main(String[] args) { int[] sortedList = new int [] {10,20,30,40,50,60,70,80,90}; Arrays.sort(sortedList); int target = 30; int result = SortArray(sortedList, target); System.out.println(result); } private static int SortArray(int[] sortedList, int target) { int left =0; int right = sortedList.length-1; while (left <=right) { int middle = (left + right) / 2; System.out.println("Middle is "+ middle); if(target < sortedList[middle]) { right = middle -1; System.out.println("Now right is " + right); }else if( target > sortedList[middle]) { left = middle + 1; System.out.println("Now left is " + left); }else { target = middle; System.out.println("Found target at :" +middle); return middle; } } return -1; } }
true
1dbee4db52fe78ddc4bf12e3ea2be2cf38aeed5b
Java
JunjunPanJoseph/Java-multiplayer-online-uno-game
/src/application/scene/gameLocal/GameLocal.java
UTF-8
1,160
2.59375
3
[]
no_license
package application.scene.gameLocal; import java.io.IOException; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.stage.Stage; public class GameLocal { private Stage stage; private Scene scene; private GameLocalController controller; /** * * @param stage * @throws IOException */ public GameLocal(Stage stage) throws IOException { this.stage = stage; FXMLLoader loader = new FXMLLoader(getClass().getResource("gameView.fxml")); controller = new GameLocalController(this, stage); loader.setController(controller); // load into a Parent node called root Parent root = loader.load(); root.requestFocus(); scene = new Scene(root); root.requestFocus(); } /** * Start the scene. */ public void start() { //stage.setTitle("tempTitle"); controller.bootstrap(); stage.setScene(scene); stage.show(); } }
true
aa5274314fcf7f9eac44867fad68f468d5771264
Java
dkolotovkin/mouse_red5
/mousesrvred5/src/mouseapp/utils/gameaction/useitem/GameActionUseItem.java
UTF-8
613
2.1875
2
[]
no_license
package mouseapp.utils.gameaction.useitem; import mouseapp.utils.gameaction.GameAction; public class GameActionUseItem extends GameAction { public int initiatorID; public int itemID; public int gwitemID; //game world public int itemtype; public Float itemx; public Float itemy; public GameActionUseItem(byte type, int roomID, int itemID, int gwitemID, int itemtype, int initiatorID, Float itemx, Float itemy){ super(type, roomID); this.initiatorID = initiatorID; this.itemID = itemID; this.gwitemID = gwitemID; this.itemtype = itemtype; this.itemx = itemx; this.itemy = itemy; } }
true
7d65e392639a98cc44afd3a87748db505efbd619
Java
michaelramon/SonyTestCase
/SonyStoreTestCase/src/framework/data/ProductData.java
UTF-8
356
2.15625
2
[]
no_license
package framework.data; import java.io.IOException; public class ProductData { ImportProductData product1; public ProductData() throws IOException { product1 = new ImportProductData(); } public String getItem(int location){ return product1.productString.get(location); } public int getListSize(){ return product1.getSize(); } }
true
359327bc2fbbb6efb450f5d9c24c465c724efacc
Java
burhanuddinMuhammad89/automation
/admin/src/main/java/led/automation/admin/repository/QuestionRepository.java
UTF-8
911
2.046875
2
[ "Apache-2.0" ]
permissive
/** * */ package led.automation.admin.repository; import java.util.stream.Stream; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import led.automation.admin.model.Question; /** * @author gederanadewadatta * */ public interface QuestionRepository extends CrudRepository<Question, Long>{ @Query("select c.question from Question c where c.grade = :grade and c.subgrade= :subgrade and c.id=:id") Stream<Question> findByGradeReturnStream(@Param("grade") String grade,@Param("subgrade") String subGrade,@Param("id") String id); // @Query("select c.answer from Question c where c.grade = :grade and c.subgrade= :subgrade and c.id=:id") // Stream<Question> findAnswerByGradeReturnStream(@Param("grade") String grade,@Param("subgrade") String subGrade,@Param("id") String id); }
true
e0c784c1c41281bc2d17243b5e9602c3f610f9b1
Java
zsx488266907/Circlemove
/Circle/src/main/java/zsx/com/circle/Circleview.java
UTF-8
2,416
2.40625
2
[]
no_license
package zsx.com.circle; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.util.AttributeSet; import android.widget.ImageView; @SuppressLint("AppCompatCustomView") public class Circleview extends ImageView { public Circleview(Context context) { super(context); } public Circleview(Context context, AttributeSet attrs) { super(context, attrs); } public Circleview(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } /* public Circleview(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); }*/ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); BitmapDrawable bitmapDrawable = (BitmapDrawable) getDrawable(); Bitmap bitmap = bitmapDrawable.getBitmap(); if (bitmap!=null){ Bitmap bit= getRound(bitmap); canvas.drawBitmap(bit,0,0,null); } } private Bitmap getRound(Bitmap bitmap){ //宽高缩放比 float widthScale = getMeasuredWidth() / bitmap.getWidth(); float heightScale= getMeasuredHeight()/bitmap.getHeight(); //矩阵变换类 Matrix matrix = new Matrix(); matrix.setScale(widthScale,heightScale); //对bitmap进行变换 Bitmap bitmap1 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); //最终输出的对象 Bitmap bitmap2 = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.RGB_565); // 创建画布 Canvas canvas = new Canvas(bitmap2); //创建画笔 Paint paint = new Paint(); //个圆角的图形 RectF rectF = new RectF(0, 0, getMeasuredWidth(), getMeasuredHeight()); canvas.drawRoundRect(rectF,30,30,paint); //设置画笔的xfermode模式 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap1,0,0,paint); return bitmap2; } }
true
adbf5e1459e8c4fadfc5eec0b7108a5106816524
Java
arindam7development/CertWare
/ftp/src/ftp/impl/PTransistorImpl.java
UTF-8
9,359
1.875
2
[ "Apache-2.0" ]
permissive
/** */ package ftp.impl; import ftp.FtpPackage; import ftp.PTransistor; import ftp.Port; import ftp.SignalPort; import ftp.TypedPortValue; import java.util.ArrayList; import java.util.List; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>PTransistor</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link ftp.impl.PTransistorImpl#getGate <em>Gate</em>}</li> * <li>{@link ftp.impl.PTransistorImpl#getSource <em>Source</em>}</li> * <li>{@link ftp.impl.PTransistorImpl#getDrain <em>Drain</em>}</li> * </ul> * * @generated */ public class PTransistorImpl extends PrimitiveComponentImpl implements PTransistor { /** * The cached value of the '{@link #getGate() <em>Gate</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getGate() * @generated * @ordered */ protected SignalPort gate; /** * The cached value of the '{@link #getSource() <em>Source</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSource() * @generated * @ordered */ protected SignalPort source; /** * The cached value of the '{@link #getDrain() <em>Drain</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDrain() * @generated * @ordered */ protected SignalPort drain; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ protected PTransistorImpl() { super(); setType("ptrans"); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return FtpPackage.Literals.PTRANSISTOR; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ public SignalPort getGate() { if (gate == null) { SignalPort sp = new SignalPortImpl(); sp.setType("Gate"); setGate(sp); } return gate; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetGate(SignalPort newGate, NotificationChain msgs) { SignalPort oldGate = gate; gate = newGate; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FtpPackage.PTRANSISTOR__GATE, oldGate, newGate); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setGate(SignalPort newGate) { if (newGate != gate) { NotificationChain msgs = null; if (gate != null) msgs = ((InternalEObject)gate).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FtpPackage.PTRANSISTOR__GATE, null, msgs); if (newGate != null) msgs = ((InternalEObject)newGate).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FtpPackage.PTRANSISTOR__GATE, null, msgs); msgs = basicSetGate(newGate, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FtpPackage.PTRANSISTOR__GATE, newGate, newGate)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ public SignalPort getSource() { if (source == null) { SignalPort sp = new SignalPortImpl(); sp.setType("Source"); setSource(sp); } return source; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetSource(SignalPort newSource, NotificationChain msgs) { SignalPort oldSource = source; source = newSource; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FtpPackage.PTRANSISTOR__SOURCE, oldSource, newSource); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSource(SignalPort newSource) { if (newSource != source) { NotificationChain msgs = null; if (source != null) msgs = ((InternalEObject)source).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FtpPackage.PTRANSISTOR__SOURCE, null, msgs); if (newSource != null) msgs = ((InternalEObject)newSource).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FtpPackage.PTRANSISTOR__SOURCE, null, msgs); msgs = basicSetSource(newSource, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FtpPackage.PTRANSISTOR__SOURCE, newSource, newSource)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ public SignalPort getDrain() { if (drain == null) { SignalPort sp = new SignalPortImpl(); sp.setType("Drain"); setDrain(sp); } return drain; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetDrain(SignalPort newDrain, NotificationChain msgs) { SignalPort oldDrain = drain; drain = newDrain; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FtpPackage.PTRANSISTOR__DRAIN, oldDrain, newDrain); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDrain(SignalPort newDrain) { if (newDrain != drain) { NotificationChain msgs = null; if (drain != null) msgs = ((InternalEObject)drain).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FtpPackage.PTRANSISTOR__DRAIN, null, msgs); if (newDrain != null) msgs = ((InternalEObject)newDrain).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FtpPackage.PTRANSISTOR__DRAIN, null, msgs); msgs = basicSetDrain(newDrain, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FtpPackage.PTRANSISTOR__DRAIN, newDrain, newDrain)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case FtpPackage.PTRANSISTOR__GATE: return basicSetGate(null, msgs); case FtpPackage.PTRANSISTOR__SOURCE: return basicSetSource(null, msgs); case FtpPackage.PTRANSISTOR__DRAIN: return basicSetDrain(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case FtpPackage.PTRANSISTOR__GATE: return getGate(); case FtpPackage.PTRANSISTOR__SOURCE: return getSource(); case FtpPackage.PTRANSISTOR__DRAIN: return getDrain(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case FtpPackage.PTRANSISTOR__GATE: setGate((SignalPort)newValue); return; case FtpPackage.PTRANSISTOR__SOURCE: setSource((SignalPort)newValue); return; case FtpPackage.PTRANSISTOR__DRAIN: setDrain((SignalPort)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case FtpPackage.PTRANSISTOR__GATE: setGate((SignalPort)null); return; case FtpPackage.PTRANSISTOR__SOURCE: setSource((SignalPort)null); return; case FtpPackage.PTRANSISTOR__DRAIN: setDrain((SignalPort)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case FtpPackage.PTRANSISTOR__GATE: return gate != null; case FtpPackage.PTRANSISTOR__SOURCE: return source != null; case FtpPackage.PTRANSISTOR__DRAIN: return drain != null; } return super.eIsSet(featureID); } public List<Port> retrievePorts() { List<Port> ports = new ArrayList<Port>(); ports.add(getGate()); ports.add(getSource()); ports.add(getDrain()); return ports; } public List<TypedPortValue> retrieveParams() { return null; } public List<Predicate> translateToLogic() { if (logic == null) { Predicate pred = new Predicate(); pred.functor = "ptrans/4"; pred.stateArgs = 1; List<String> clauses = new ArrayList<String>(); clauses.add("ptrans(signal(0),signal(Y),signal(Y),ok)"); clauses.add("ptrans(signal(1),signal(_),signal(_),ok)"); clauses.add("ptrans(signal(_),signal(_),signal(_),failed)"); pred.clauses = clauses; List<Predicate> preds = new ArrayList<Predicate>(); preds.add(pred); logic = preds; } return logic; } } //PTransistorImpl
true
e796da120a67fd2c2fce7c5380877c177f298bdd
Java
arjankahlon/CSW-Programming-and-Algorithms-P-A
/MonteCarlo.java
UTF-8
2,085
3.625
4
[]
no_license
public class MonteCarlo { public static void main(String[] args){ int r2= 0; int r3= 0; int r4= 0; int r5= 0; int r6= 0; int r7= 0; int r8= 0; int r9= 0; int r10= 0; int r11= 0; int r12= 0; for(int count=0; count<10000; count++){ int dice1 = (int) (Math.random() * 6 + 1); int dice2 = (int) (Math.random() * 6 + 1); int result= dice1+dice2; if(result==2){ r2++; }else if(result==3){ r3++; }else if(result==4){ r4++; }else if(result==5){ r5++; }else if(result==6){ r6++; }else if(result==7){ r7++; }else if(result==8){ r8++; }else if(result==9){ r9++; }else if(result==10){ r10++; }else if(result==11){ r11++; }else if(result==12){ r12++; }else{ System.out.println ("An error occured on roll "+count); } } System.out.println("Done! 2 dice were rolled together 10,000 times, resulting in the following totals of both dice:"); System.out.println("The total 2 was rolled "+ r2+" times"); System.out.println("The total 3 was rolled "+ r3+" times"); System.out.println("The total 4 was rolled "+ r4+" times"); System.out.println("The total 5 was rolled "+ r5+" times"); System.out.println("The total 6 was rolled "+ r6+" times"); System.out.println("The total 7 was rolled "+ r7+" times"); System.out.println("The total 8 was rolled "+ r8+" times"); System.out.println("The total 9 was rolled "+ r9+" times"); System.out.println("The total 10 was rolled "+ r10+" times"); System.out.println("The total 11 was rolled "+ r11+" times"); System.out.println("The total 12 was rolled "+ r12+" times"); } }
true
1e013bb31c8f43f2098cd619af2d89bf97806531
Java
xuyongisgoop/all-study
/j2se-study/src/main/java/com/xuyong/study/general/Node.java
UTF-8
235
2.46875
2
[]
no_license
package com.xuyong.study.general; /** * Created by xuyong on 2018/1/17. */ public abstract class Node<T> { private T data; public Node(T data) { this.data = data; } public abstract void setData(T data); }
true
350bbf442d19800683eff4aaebc6788850b28bf0
Java
086-rasikadivekar-kh/DAC
/Java_assignments/q36.java
UTF-8
510
3.734375
4
[]
no_license
class mathOperation{ void multiply(int n1, int n2){ int mul = n1*n2; System.out.println("1st output: "+mul); } void multiply(float n1, float n2, float n3){ double mul = n1*n2*n3; System.out.println("2st output: "+mul); } void multiply(int [] arr){ int mul=1; for(int i=0; i<arr.length;i++) { mul=mul*arr[i]; } System.out.println("3rd output: "+mul); } void multiply(double n1, int n2){ double mul = n1*n2; System.out.println("4th output: "+mul); } }
true
300f54ec62cb442fc5cba66a1cddadcd264a7d2e
Java
NightRa/CompilersCourse
/src/main/java/compiler/ast/atom/Atom.java
UTF-8
276
2.125
2
[]
no_license
package compiler.ast.atom; import compiler.ast.Type; import compiler.ast.expr.Expr; import java.util.Map; public abstract class Atom<A> extends Expr<A> { public abstract Type rawType(Map<String, Type> typeTable); public int precedence() { return 0; } }
true
ae830945f1e4db6c48945bc507a4a33d2f7080ae
Java
tsuzcx/qq_apk
/com.tencent.mm/classes.jar/com/tencent/mm/protocal/protobuf/ent.java
UTF-8
6,162
1.703125
2
[]
no_license
package com.tencent.mm.protocal.protobuf; import com.tencent.matrix.trace.core.AppMethodBeat; import java.util.LinkedList; public final class ent extends com.tencent.mm.bx.a { public String MRI; public long aaxM; public String absk; public double absl; public LinkedList<wx> absm; public String absn; public LinkedList<esp> abso; public String appid; public String nickname; public String username; public ent() { AppMethodBeat.i(50103); this.absm = new LinkedList(); this.abso = new LinkedList(); AppMethodBeat.o(50103); } public final int op(int paramInt, Object... paramVarArgs) { AppMethodBeat.i(50104); if (paramInt == 0) { paramVarArgs = (i.a.a.c.a)paramVarArgs[0]; if (this.appid != null) { paramVarArgs.g(1, this.appid); } if (this.username != null) { paramVarArgs.g(2, this.username); } if (this.nickname != null) { paramVarArgs.g(3, this.nickname); } if (this.MRI != null) { paramVarArgs.g(4, this.MRI); } paramVarArgs.bv(5, this.aaxM); if (this.absk != null) { paramVarArgs.g(6, this.absk); } paramVarArgs.d(7, this.absl); paramVarArgs.e(16, 8, this.absm); if (this.absn != null) { paramVarArgs.g(17, this.absn); } paramVarArgs.e(19, 8, this.abso); AppMethodBeat.o(50104); return 0; } if (paramInt == 1) { if (this.appid == null) { break label885; } } label885: for (int i = i.a.a.b.b.a.h(1, this.appid) + 0;; i = 0) { paramInt = i; if (this.username != null) { paramInt = i + i.a.a.b.b.a.h(2, this.username); } i = paramInt; if (this.nickname != null) { i = paramInt + i.a.a.b.b.a.h(3, this.nickname); } paramInt = i; if (this.MRI != null) { paramInt = i + i.a.a.b.b.a.h(4, this.MRI); } i = paramInt + i.a.a.b.b.a.q(5, this.aaxM); paramInt = i; if (this.absk != null) { paramInt = i + i.a.a.b.b.a.h(6, this.absk); } i = paramInt + (i.a.a.b.b.a.ko(7) + 8) + i.a.a.a.c(16, 8, this.absm); paramInt = i; if (this.absn != null) { paramInt = i + i.a.a.b.b.a.h(17, this.absn); } i = i.a.a.a.c(19, 8, this.abso); AppMethodBeat.o(50104); return paramInt + i; if (paramInt == 2) { paramVarArgs = (byte[])paramVarArgs[0]; this.absm.clear(); this.abso.clear(); paramVarArgs = new i.a.a.a.a(paramVarArgs, unknownTagHandler); for (paramInt = com.tencent.mm.bx.a.getNextFieldNumber(paramVarArgs); paramInt > 0; paramInt = com.tencent.mm.bx.a.getNextFieldNumber(paramVarArgs)) { if (!super.populateBuilderWithField(paramVarArgs, this, paramInt)) { paramVarArgs.kFT(); } } AppMethodBeat.o(50104); return 0; } if (paramInt == 3) { Object localObject1 = (i.a.a.a.a)paramVarArgs[0]; ent localent = (ent)paramVarArgs[1]; paramInt = ((Integer)paramVarArgs[2]).intValue(); Object localObject2; switch (paramInt) { case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 18: default: AppMethodBeat.o(50104); return -1; case 1: localent.appid = ((i.a.a.a.a)localObject1).ajGk.readString(); AppMethodBeat.o(50104); return 0; case 2: localent.username = ((i.a.a.a.a)localObject1).ajGk.readString(); AppMethodBeat.o(50104); return 0; case 3: localent.nickname = ((i.a.a.a.a)localObject1).ajGk.readString(); AppMethodBeat.o(50104); return 0; case 4: localent.MRI = ((i.a.a.a.a)localObject1).ajGk.readString(); AppMethodBeat.o(50104); return 0; case 5: localent.aaxM = ((i.a.a.a.a)localObject1).ajGk.aaw(); AppMethodBeat.o(50104); return 0; case 6: localent.absk = ((i.a.a.a.a)localObject1).ajGk.readString(); AppMethodBeat.o(50104); return 0; case 7: localent.absl = Double.longBitsToDouble(((i.a.a.a.a)localObject1).ajGk.aay()); AppMethodBeat.o(50104); return 0; case 16: paramVarArgs = ((i.a.a.a.a)localObject1).aMP(paramInt); i = paramVarArgs.size(); paramInt = 0; while (paramInt < i) { localObject1 = (byte[])paramVarArgs.get(paramInt); localObject2 = new wx(); if ((localObject1 != null) && (localObject1.length > 0)) { ((wx)localObject2).parseFrom((byte[])localObject1); } localent.absm.add(localObject2); paramInt += 1; } AppMethodBeat.o(50104); return 0; case 17: localent.absn = ((i.a.a.a.a)localObject1).ajGk.readString(); AppMethodBeat.o(50104); return 0; } paramVarArgs = ((i.a.a.a.a)localObject1).aMP(paramInt); i = paramVarArgs.size(); paramInt = 0; while (paramInt < i) { localObject1 = (byte[])paramVarArgs.get(paramInt); localObject2 = new esp(); if ((localObject1 != null) && (localObject1.length > 0)) { ((esp)localObject2).parseFrom((byte[])localObject1); } localent.abso.add(localObject2); paramInt += 1; } AppMethodBeat.o(50104); return 0; } AppMethodBeat.o(50104); return -1; } } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes2.jar * Qualified Name: com.tencent.mm.protocal.protobuf.ent * JD-Core Version: 0.7.0.1 */
true
99de96c52085c79a8cc906c5b5e8301267a087bd
Java
LifeAndTech/LiveWell
/LiveWell/src/com/example/livewell/BaseActivity.java
UTF-8
941
2.09375
2
[]
no_license
package com.example.livewell; import android.app.Activity; import android.content.Intent; import android.view.Menu; public class BaseActivity extends Activity { // Shared Preferences public static final String SETTINGS_PREFS = "SETTINGS PREFS"; public static final String SETTINGS_PREFS_WEIGHT = "CURRENT WEIGHT"; public static final String SETTINGS_PREFS_GOAL = "GOAL WEIGHT"; public static final String SETTINGS_PREFS_GENDER = "GENDER"; public static final String SETTINGS_PREFS_EXERCISE = "TYPICAL EXERCISE"; public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // ask super to create Option menu getMenuInflater().inflate(R.menu.main, menu); // use getMenuInflater to inflate the menu items menu.findItem(R.id.menuitem_home).setIntent(new Intent(this, MainActivity.class)); // find options in menu with Intent to open OptionsActivity return true; } }
true
850abe3fe826b215ccb75b5954784cb1974256ed
Java
winshu/mymud
/src/com/ys168/gam/cmd/std/Go.java
UTF-8
1,957
2.828125
3
[]
no_license
package com.ys168.gam.cmd.std; import com.ys168.gam.cmd.Cmd; import com.ys168.gam.cmd.base.CmdName; import com.ys168.gam.cmd.base.Context; import com.ys168.gam.constant.Direction; import com.ys168.gam.holder.MapHolder; import com.ys168.gam.model.Room; import com.ys168.gam.simple.SimpleRoomInfo; /** * * @author Kevin * @since 2017年4月26日 */ @CmdName("go") public class Go extends Cmd { private Direction direction; private Room nextRoom; public Go(Context context) { super(context); } @Override protected boolean beforeExecute() { if (!hasArgument()) { return fail("你要往哪个方向走?"); } if (context.getUser().isBusy()) { return fail("你的动作还没有完成,不能移动。"); } if (context.getRoom() == null) { return fail("你待在家还想怎样?"); } String arg0 = getArgument(); String[] args = arg0.split("\\."); direction = Direction.get(args[0]); if (direction == null) { return fail("找不到这个方向。"); } int roomId = args.length > 1 ? parseInt(args[1]) : context.getRoom().getId(); roomId = roomId >= 0 ? roomId : context.getRoom().getId(); Room current = MapHolder.getRoom(roomId); SimpleRoomInfo exit = current.getExit(direction); if (exit == null) { return fail("这儿没有这个方向"); } nextRoom = MapHolder.getRoom(exit.getId()); if (current.isLocked()) { return fail("当前房间被锁上了"); } if (nextRoom.isLocked()) { return fail("这个房间被锁上了"); } return true; } @Override protected boolean doExecute() { context.getUser().changeRoom(nextRoom); return true; } }
true
22b67aa1d87dcec3977e4cee1ad84713cb05a385
Java
tarang-dawer/practice.one
/src/main/java/com/tarang/practice/cdci/three/MyQueue.java
UTF-8
715
3.421875
3
[]
no_license
package com.tarang.practice.cdci.three; import java.util.Stack; //queue using two stacks public class MyQueue { private Stack<Integer> newStack, oldStack; public MyQueue() { this.newStack = new Stack<Integer>(); this.oldStack = new Stack<Integer>(); } public static void main() { } public int size() { return newStack.size() + oldStack.size(); } public void push(int val) { this.newStack.push(val); } public int remove() { shiftStacks(); return oldStack.pop(); } public int peek() { shiftStacks(); return oldStack.peek(); } private void shiftStacks() { if (oldStack.isEmpty()) { while (!newStack.isEmpty()) { oldStack.push(newStack.pop()); } } return; } }
true
b5a3f358edc200e43faca1840e43284be367738b
Java
vaadin/grid-renderers-collection-addon
/grid-renderers-collection-addon/src/main/java/org/vaadin/grid/cellrenderers/view/ConverterRenderer.java
UTF-8
2,019
2.453125
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package org.vaadin.grid.cellrenderers.view; import org.vaadin.grid.cellrenderers.client.view.ConverterRendererState; import com.vaadin.data.Converter; import com.vaadin.data.ValueContext; import com.vaadin.ui.renderers.AbstractRenderer; import elemental.json.JsonValue; /** * @author Tatu Lund - Vaadin */ public class ConverterRenderer<T,A> extends AbstractRenderer<T,A> { private Converter<String,A> converter; /** * Set converter to be used with the renderer. * * @param converter A custom String to something converter to be used with renderer. HTML allowed. * */ public void setConverter(Converter<String,A> converter) { this.converter = converter; } /** * Set converter to be used with the renderer. * * @param nullRepresentation String to be shown if result of conversion is null. HTML allowed. * */ public void setNullRepresentation(String nullRepresentation) { getState().nullRepresentation = nullRepresentation; } /** * Constructor for a new ConverterRenderer * */ public ConverterRenderer() { super((Class<A>) Object.class); } /** * Constructor for a new ConverterRenderer with parameter settings * * @param converter A custom String to something converter to be used with renderer. */ public ConverterRenderer(Converter<String,A> converter) { super((Class<A>) Object.class); this.converter = converter; } @Override public String getNullRepresentation() { return getState().nullRepresentation; } @Override public JsonValue encode(A value) { if (converter == null) { return encode((String) value, String.class); } else { return encode(converter.convertToPresentation(value, new ValueContext()), String.class); } } @Override protected ConverterRendererState getState() { return (ConverterRendererState) super.getState(); } }
true
8565af06de91f7449959da0fb04d81c35637a289
Java
PhanNgocHT/Code
/app/src/main/java/com/zuckerteam/adapter/DanhSachChuyenAdapter.java
UTF-8
1,695
2.390625
2
[]
no_license
package com.zuckerteam.adapter; import android.content.Context; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.zuckerteam.mevabe.R; import com.zuckerteam.model.KeChuyenChoBe; import java.util.ArrayList; import java.util.List; /** * Created by Dung Ali on 9/16/2017. */ public class DanhSachChuyenAdapter<String> extends ArrayAdapter { Context context; ArrayList<String> danhSachChuyens; public DanhSachChuyenAdapter(@NonNull Context context, @NonNull ArrayList<String> objects) { super(context, android.R.layout.simple_list_item_1, objects); this.context = context; this.danhSachChuyens = objects; } @NonNull @Override public View getView(int position, @Nullable View v, @NonNull ViewGroup parent) { ViewHolder holder = null; if (v == null) { holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = inflater.inflate(R.layout.item_listview_danh_sach_chuyen, parent, false); holder.tvTenChuyen = v.findViewById(R.id.tvTenChuyen); v.setTag(holder); } else { holder = (ViewHolder) v.getTag(); } String tenChuyen = danhSachChuyens.get(position); holder.tvTenChuyen.setText(tenChuyen+""); return v; } public class ViewHolder { TextView tvTenChuyen; } }
true
5c8cf50e7f906b5e9b9f50e21e34747268860447
Java
HansaTharuka/Ergo
/app/src/main/java/org/techknights/ergo/UserAreas/SingleViews/ProjectSingleActivity.java
UTF-8
4,859
2
2
[]
no_license
package org.techknights.ergo.UserAreas.SingleViews; import android.app.ProgressDialog; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast; import org.techknights.ergo.Login.helper.SQLiteHandler; import org.techknights.ergo.R; import org.techknights.ergo.Retrofit.ApiClient; import org.techknights.ergo.Retrofit.SingleViews.ProjectData; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class ProjectSingleActivity extends AppCompatActivity { private List<ProjectData> projectDataList; private SQLiteHandler db; private TextView mProjectName1; private TextView mProjectCatogary1; //private TextView mProjectDiscription1; private TextView mProjectStartDate1; private TextView mProjectEndDate1; private ProgressDialog mRegProgress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_project_single); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mRegProgress = new ProgressDialog(this); //mRegProgress.setTitle(""); mRegProgress.setMessage("Loading Project Details"); mRegProgress.setCanceledOnTouchOutside(false); mRegProgress.show(); mProjectName1 = (TextView) findViewById(R.id.projectname1); mProjectCatogary1 = (TextView) findViewById(R.id.projectcatagory1); // mProjectDiscription1 = (TextView) findViewById(R.id.projectst); mProjectStartDate1 = (TextView) findViewById(R.id.projectstartdate1); mProjectEndDate1 = (TextView) findViewById(R.id.projectenddate1); projectDataList = new ArrayList<>(); db = SQLiteHandler.getInstance(getApplicationContext()); HashMap<String, String> user = db.getUserDetails(); String uid = user.get("uid"); //this is important for get user detail loged user token Intent intent = getIntent(); String projectidfrommemberList = intent.getStringExtra("ProjectId"); //Toast.makeText(getApplicationContext(),""+taskidfrommemberList, Toast.LENGTH_LONG).show(); Retrofit.Builder builder = new Retrofit.Builder() .baseUrl("https://kinna.000webhostapp.com/") .addConverterFactory(GsonConverterFactory.create()); //remote localhost Retrofit retrofit = builder.build(); ApiClient client = retrofit.create(ApiClient.class); Call<ArrayList<ProjectData>> call3 = client.getProjectData("Bearer " + uid, projectidfrommemberList); call3.enqueue(new Callback<ArrayList<ProjectData>>() { @Override public void onResponse(Call<ArrayList<ProjectData>> call, Response<ArrayList<ProjectData>> response) { //Toast.makeText(getApplicationContext(),"OK " + response.body().get(0).getName(), Toast.LENGTH_LONG).show(); projectDataList = response.body(); mRegProgress.dismiss(); if (projectDataList != null) { mProjectName1.setText(projectDataList.get(0).getName()); mProjectCatogary1.setText(projectDataList.get(0).getCategory()); // mProjectDiscription1.setText(projectDataList.get(0).getCategory()); mProjectStartDate1.setText(projectDataList.get(0).getStart_date()); mProjectEndDate1.setText(projectDataList.get(0).getEnd_date()); //Toast.makeText(getApplicationContext(),"hello"+projectDataList.get(0).getName(), Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "No Project to show", Toast.LENGTH_LONG).show(); } } @Override public void onFailure(Call<ArrayList<ProjectData>> call3, Throwable t) { Toast.makeText(getApplicationContext(), "Error " + t.getMessage(), Toast.LENGTH_LONG).show(); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == android.R.id.home) { // finish the activity onBackPressed(); return true; } return super.onOptionsItemSelected(item); } }
true
01f7dfab906d63f52cc00d53e747042d800e0ba2
Java
kiracookie/ResearchMS
/app/src/main/java/com/cookie/kira/researchms/entity/AnswerDetail.java
UTF-8
973
1.890625
2
[]
no_license
package com.cookie.kira.researchms.entity; /** * Created by 11669 on 2017-07-11. */ class AnswerDetail { private int paperId; private int questionId; private int OptionId; private String owner; private String comment; public int getPaperId() { return paperId; } public void setPaperId(int paperId) { this.paperId = paperId; } public int getQuestionId() { return questionId; } public void setQuestionId(int questionId) { this.questionId = questionId; } public int getOptionId() { return OptionId; } public void setOptionId(int optionId) { OptionId = optionId; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } }
true
7d3df16057f7ea81522542fa6baf2c9d4b117a5a
Java
sunyaoxiang/testproject
/src/study/factory/java/AbstractFactory.java
UTF-8
159
2.125
2
[]
no_license
package study.factory.java; abstract class AbstractFactory { abstract MachineMake getMake(String name); abstract VendorSell getVendor(String sell); }
true
91b9e8819485f98ee8ea3693694a46d651372380
Java
btraas/browser
/app/src/main/java/ca/bcit/comp3717/a00968178/Browser/LinksActivity.java
UTF-8
2,485
2.109375
2
[]
no_license
package ca.bcit.comp3717.a00968178.Browser; import android.content.Intent; import android.database.Cursor; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; import ca.bcit.comp3717.a00968178.Browser.databases.OpenHelper; public class LinksActivity extends AppCompatActivity implements AdapterView.OnItemClickListener { private static final String TAG = LinksActivity.class.getName(); private ListView list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_links); load(); } private void load() { list = (ListView) findViewById(R.id.links_list); list.setOnItemClickListener(this); OpenHelper helper = new LinksOpenHelper(this); //Messaging.showMessage(this, ""+helper.getNumberOfRows()); Cursor c = helper.getRows(); Log.d(TAG, OpenHelper.cursorCSV(c)); CursorAdapter adapter = new LinkAdapter(this, R.layout.link_row, c, new String[] { LinksOpenHelper.NAME_COLUMN, }, new int[] { android.R.id.text1, }); list.setAdapter(adapter); /* final LoaderManager manager = getLoaderManager(); manager.initLoader(0, null, new CustomLoaderCallbacks(LinksActivity.this, adapter, Uri.parse(OpenHelper.URI_BASE + LinksOpenHelper.TABLE_NAME))); */ } @Override public void onItemClick(AdapterView<?> adapter, final View view, int position, long id) { Log.d(TAG, "onItemClick begin"); // Must be called here because it's relative to *this* view (category row) TextView nameText = (TextView)(view.findViewById(R.id.name)); // text -> Used for the title of the next view String text = nameText.getText().toString(); //int linkId = position+1; final Intent intent; intent = new Intent(this, LinkWebviewActivity.class); final int linkId = view.getId(); intent.putExtra("id", linkId); startActivity(intent); Log.d(TAG, "onItemClick end for id: "+id); } }
true
455dec0613d22ffa3065dd68fcfa4ecb6a32e85c
Java
wuhaoqiu/UBC-Assignments
/Java Course/Project/PC.java
UTF-8
174
2.453125
2
[]
no_license
package P5; /** same as before **/ public class PC extends Register { public PC(int value) { super(value); } public void increment() { setValue(getValue()+1);; } }
true
d5bb34b68397e73c5924d30728dbc319fe106343
Java
hymanath/PA
/partyanalyst-service/trunk/src/main/java/com/itgrids/partyanalyst/model/PartyWorkingCommittee.java
UTF-8
3,701
1.976563
2
[]
no_license
/* * Copyright (c) 2009 IT Grids. * All Rights Reserved. * * IT Grids Confidential Information. * Created on August 09, 2010 */ package com.itgrids.partyanalyst.model; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.LazyToOne; import org.hibernate.annotations.LazyToOneOption; import org.hibernate.annotations.NotFoundAction; /** * PartyWorkingCommittee entity. * @author <a href="mailto:[email protected]">Raghav</a> */ @Entity @Table(name = "party_working_committee") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class PartyWorkingCommittee implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1L; private Long partyWorkingCommitteeId; private Party party; private String committeeName; private Set<PartyWorkingCommitteeDesignation> partyWkgCommitteeDesignations = new HashSet<PartyWorkingCommitteeDesignation>(); private CadreLevel regionLevel; private Long regionLevelValue; public PartyWorkingCommittee() { super(); } public PartyWorkingCommittee(Long partyWorkingCommitteeId, Party party, String committeeName) { super(); this.partyWorkingCommitteeId = partyWorkingCommitteeId; this.party = party; this.committeeName = committeeName; } @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "party_working_committee_id", unique = true, nullable = false) public Long getPartyWorkingCommitteeId() { return partyWorkingCommitteeId; } public void setPartyWorkingCommitteeId(Long partyWorkingCommitteeId) { this.partyWorkingCommitteeId = partyWorkingCommitteeId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="party_id") @LazyToOne(LazyToOneOption.NO_PROXY) @org.hibernate.annotations.NotFound(action=NotFoundAction.IGNORE) public Party getParty() { return party; } public void setParty(Party party) { this.party = party; } @Column(name = "committee_name", length = 100) public String getCommitteeName() { return committeeName; } public void setCommitteeName(String committeeName) { this.committeeName = committeeName; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "partyWorkingCommittee") @org.hibernate.annotations.NotFound(action=NotFoundAction.IGNORE) public Set<PartyWorkingCommitteeDesignation> getPartyWkgCommitteeDesignations() { return partyWkgCommitteeDesignations; } public void setPartyWkgCommitteeDesignations( Set<PartyWorkingCommitteeDesignation> partyWkgCommitteeDesignations) { this.partyWkgCommitteeDesignations = partyWkgCommitteeDesignations; } @ManyToOne(cascade=CascadeType.ALL,fetch = FetchType.LAZY) @JoinColumn(name = "region_level") public CadreLevel getRegionLevel() { return regionLevel; } public void setRegionLevel(CadreLevel regionLevel) { this.regionLevel = regionLevel; } @Column(name = "region_level_value") public Long getRegionLevelValue() { return regionLevelValue; } public void setRegionLevelValue(Long regionLevelValue) { this.regionLevelValue = regionLevelValue; } }
true
4d3f0cc7f4b73e82c1dfb5ef7378813ee1967226
Java
qycode/qy-code-generator
/src/main/java/qy/generator/demo/entity/SimpleDemoEntity.java
UTF-8
478
2.328125
2
[]
no_license
package qy.generator.demo.entity; import com.qy.code.generator.annotation.Column; import com.qy.code.generator.annotation.Table; /** * 描述:这是一个最简单demo * @author 七脉 */ @Table public class SimpleDemoEntity { @Column(id=true, comment="主键") private Long id; @Column(comment="名字") private String name; @Column(comment="年龄") private Integer age; @Column(comment="是否已婚") private boolean married; }
true
b7f0a119ff6bc43497a244a500cc804ce5488c38
Java
NaeraeGojo/NaeraeGojo
/NaeraeGojo/src/main/res/kr/or/ddit/aop/LogPrintUtil.java
UTF-8
2,830
2.96875
3
[]
no_license
package kr.or.ddit.aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.slf4j.Logger; import org.springframework.stereotype.Component; // 빈등록 시킴 // <bean name="logPrintUtil" class="kr.or.ddit.aop.LogPrintUtil"> // -><bean name="logPrintAspect" class="kr.or.ddit.aop.LogPrintUtil"> @Component("logPrintAspect") public class LogPrintUtil { //이제 로그 찍어주는 코들르 얘가 가지고 있으면 됨 @Loggable public static Logger logger; // 스프링 프레임 워크에서 Advice(시점, 언제) : 메서드 호출 전 // 메서드 종료 후 // 메서드 호출에 의한 익셉션 발생 후 // 메서드 호출/종료 페어(둘다) // joinpoint : org.aspectj. public void theWholeJPCallBefore(JoinPoint joinPoint){ String className = joinPoint.getTarget().getClass().getName(); // 조인포인트 이름 = 메서드 이름 String joinpointName = joinPoint.getSignature().getName(); logger.debug("weaving target class : {} - target method : {} 콜백됩니다." ,className, joinpointName); } // 종료후 콜백 public void theWholeJPCallAfter(JoinPoint joinPoint){ String className = joinPoint.getTarget().getClass().getName(); // 조인포인트 이름 = 메서드 이름 String joinpointName = joinPoint.getSignature().getName(); logger.debug("weaving target class : {} - target method : {} 종료됩니다." ,className, joinpointName); } // 예외 발생 후 콜백 , 익셉션 정보도 얻을 수 있음 // advice 설정시의 throwing="ex" 속성에 변수이름 넣어줌 public void theWholeJPCallThrowsAfter(JoinPoint joinPoint, Exception ex){ String className = joinPoint.getTarget().getClass().getName(); // 조인포인트 이름 = 메서드 이름 String joinpointName = joinPoint.getSignature().getName(); logger.debug("weaving target class : {} - target method : {} - {} 익셉션이 발생되었습니다" ,className, joinpointName, ex.getMessage()); } // 호출 전후(페어) 때는 ProceedingJoinPoint가 사용된다. public Object theWholeJPCallBeforeNAfter(ProceedingJoinPoint joinPoint) throws Throwable{ String className = joinPoint.getTarget().getClass().getName(); // 조인포인트 이름 = 메서드 이름 String joinpointName = joinPoint.getSignature().getName(); logger.debug("weaving target class : {} - target method : {} 호출 후...." ,className, joinpointName); // 여기가 구분자 얘 위로는 호출하고 , 얘 때는 실제 그 메서드가 호출, 얘 밑으로는 종료후 위빙되는 어스펙트 Object returnValue = joinPoint.proceed(); logger.debug("weaving target class : {} - target method : {} 종료 됩니다." ,className, joinpointName); return returnValue; } }
true
6baaa679fb5e0d0ae72084ec3018d01507a8b891
Java
VicenteLugo/AutoExample
/Auto/src/auto/TestAuto.java
UTF-8
1,574
2.90625
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 auto; import java.util.ArrayList; /** * * @author LugoD */ public class TestAuto { public static void main(String[] args) { Auto car=new Auto(); car.setMarca("Ford"); car.setAño("1995"); car.setTipo("Deportivo"); Auto schlitten=new Auto(); schlitten.setMarca("Nissan"); schlitten.setAño("2051"); schlitten.setTipo("Limosina"); Auto auto=new Auto(); auto.setMarca("Lamborgini"); auto.setAño("6515"); auto.setTipo("Camioneta"); Auto warthog=new Auto(); warthog.setMarca("Audi"); warthog.setAño("2015"); warthog.setTipo("Furgoneta"); Auto halconMilenario=new Auto(); halconMilenario.setMarca("Ferrari"); halconMilenario.setAño("1995"); halconMilenario.setTipo("Deportivo"); ArrayList lista =new ArrayList(); lista.add(car); lista.add(schlitten); lista.add(auto); lista.add(warthog); lista.add(halconMilenario); Auto aut; int cont=1; for (Object listaCarros : lista) { aut=(Auto) listaCarros; System.out.println(cont++ +".-"+aut.getMarca()+" "+aut.getAño()+" "+aut.getTipo()); } } }
true
743c25edda227e34cf8c112cfc19c813c9e709a8
Java
sandysaisandeep/asdsad
/src/test/java/packagetest/sample2.java
UTF-8
165
1.648438
2
[]
no_license
package packagetest; import org.testng.annotations.Test; public class sample2 { @Test public void ran(){ System.out.println("dummy printed"); } }
true
4fad20570492db649e146ce9ef7955804131847d
Java
Jouramie/GLO-4003-Architecture
/src/main/java/ca/ulaval/glo4003/service/stock/trend/StockVariationTrendService.java
UTF-8
1,449
2.359375
2
[]
no_license
package ca.ulaval.glo4003.service.stock.trend; import ca.ulaval.glo4003.domain.Component; import ca.ulaval.glo4003.domain.stock.Stock; import ca.ulaval.glo4003.domain.stock.StockHistory; import ca.ulaval.glo4003.domain.stock.StockRepository; import ca.ulaval.glo4003.domain.stock.exception.StockNotFoundException; import ca.ulaval.glo4003.service.date.DateService; import ca.ulaval.glo4003.service.stock.StockDoesNotExistException; import javax.inject.Inject; @Component public class StockVariationTrendService { private final StockRepository stockRepository; private final DateService dateService; @Inject public StockVariationTrendService(StockRepository stockRepository, DateService dateService) { this.stockRepository = stockRepository; this.dateService = dateService; } public StockVariationSummary getStockVariationSummary(String stockTitle) { try { Stock stock = stockRepository.findByTitle(stockTitle); StockHistory valueHistory = stock.getValueHistory(); return new StockVariationSummary( valueHistory.getStockVariationTrendSinceDate(dateService.getFiveDaysAgo()), valueHistory.getStockVariationTrendSinceDate(dateService.getThirtyDaysAgo()), valueHistory.getStockVariationTrendSinceDate(dateService.getOneYearAgo()) ); } catch (StockNotFoundException e) { throw new StockDoesNotExistException(e); } } }
true
4a9bb43920625738376fe21c7263997875805a9b
Java
gga4638/1stProject
/src/View/MemberShipGUI2.java
UHC
12,097
2.3125
2
[]
no_license
package View; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ButtonGroup; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.SwingConstants; import Model.MemberDAO; import Model.MemberDTO; public class MemberShipGUI2 { private JFrame frame; private JTextField tf_Name; private JTextField tf_Id; private JTextField tf_Phone; private JTextField tf_Address; private final ButtonGroup buttonGroup = new ButtonGroup(); private int saletarget; private JPasswordField pw_1; private JPasswordField pw_2; /** * Launch the application. */ // public static void main(String[] args) { // EventQueue.invokeLater(new Runnable() { // public void run() { // try { // MemberShipGUI2 window = new MemberShipGUI2(null); // //window.frame.setVisible(true); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } /** * Create the application. */ public MemberShipGUI2(MemberDTO dto) { initialize(dto); frame.setVisible(true); frame.setLocationRelativeTo(null); } /** * Initialize the contents of the frame. */ private void initialize(MemberDTO dto) { frame = new JFrame(); frame.getContentPane().setBackground(Color.WHITE); frame.setBounds(100, 100, 520, 600); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JPanel panel = new JPanel(); panel.setBounds(12, 77, 480, 405); panel.setBackground(new Color(250, 236, 197)); frame.getContentPane().add(panel); panel.setLayout(null); JLabel lbl_Address = new JLabel("\uC8FC \uC18C"); lbl_Address.setBounds(49, 212, 57, 15); lbl_Address.setForeground(new Color(233, 113, 113)); panel.add(lbl_Address); lbl_Address.setFont(new Font("", Font.BOLD, 15)); lbl_Address.setHorizontalAlignment(SwingConstants.CENTER); tf_Address = new JTextField(); tf_Address.setBounds(136, 209, 260, 21); panel.add(tf_Address); tf_Address.setColumns(10); JLabel lbl_Name = new JLabel("\uC774 \uB984"); lbl_Name.setBounds(49, 170, 57, 15); lbl_Name.setForeground(new Color(233, 113, 113)); panel.add(lbl_Name); lbl_Name.setFont(new Font("", Font.BOLD, 15)); lbl_Name.setHorizontalAlignment(SwingConstants.CENTER); tf_Name = new JTextField(); tf_Name.setBounds(136, 167, 260, 21); panel.add(tf_Name); tf_Name.setColumns(10); JLabel lbl_RePw = new JLabel("\uC7AC\uC785\uB825"); lbl_RePw.setBounds(49, 128, 63, 15); panel.add(lbl_RePw); lbl_RePw.setFont(new Font("", Font.BOLD, 15)); lbl_RePw.setForeground(new Color(233, 113, 113)); lbl_RePw.setHorizontalAlignment(SwingConstants.CENTER); pw_2 = new JPasswordField(); pw_2.setBounds(136, 125, 260, 21); panel.add(pw_2); JLabel lbl_Pw = new JLabel("P W"); lbl_Pw.setBounds(49, 86, 57, 15); panel.add(lbl_Pw); lbl_Pw.setFont(new Font("", Font.BOLD, 15)); lbl_Pw.setForeground(new Color(233, 113, 113)); lbl_Pw.setHorizontalAlignment(SwingConstants.CENTER); pw_1 = new JPasswordField(); pw_1.setBounds(136, 83, 260, 21); panel.add(pw_1); JLabel lbl_Phone = new JLabel("\uD734\uB300\uD3F0\uBC88\uD638"); lbl_Phone.setFont(new Font("", Font.BOLD, 15)); lbl_Phone.setBounds(52, 263, 83, 15); lbl_Phone.setForeground(new Color(233, 113, 113)); panel.add(lbl_Phone); lbl_Phone.setHorizontalAlignment(SwingConstants.CENTER); JComboBox comboBox = new JComboBox(); comboBox.setBackground(new Color(250, 236, 197)); comboBox.setBounds(136, 257, 60, 21); panel.add(comboBox); comboBox.setModel(new DefaultComboBoxModel(new String[] { "010", "011" })); tf_Phone = new JTextField(); tf_Phone.setBounds(208, 257, 188, 21); panel.add(tf_Phone); tf_Phone.setColumns(10); JRadioButton rb_No = new JRadioButton("\uD574\uB2F9\uC5C6\uC74C"); rb_No.setForeground(Color.DARK_GRAY); rb_No.setBackground(new Color(250, 236, 197)); rb_No.setFont(new Font("", Font.BOLD, 15)); rb_No.setBounds(136, 305, 90, 23); panel.add(rb_No); buttonGroup.add(rb_No); JRadioButton rb_disabled = new JRadioButton("\uD560\uC778 \uB300\uC0C1\uC790"); rb_disabled.setForeground(Color.DARK_GRAY); rb_disabled.setBackground(new Color(250, 236, 197)); rb_disabled.setFont(new Font("", Font.BOLD, 15)); rb_disabled.setBounds(232, 305, 112, 23); panel.add(rb_disabled); buttonGroup.add(rb_disabled); JLabel lbl_Sale = new JLabel("\uD560\uC778\uC0AC\uD56D"); lbl_Sale.setFont(new Font("", Font.BOLD, 15)); lbl_Sale.setForeground(new Color(233, 113, 113)); lbl_Sale.setBounds(49, 309, 71, 15); panel.add(lbl_Sale); lbl_Sale.setHorizontalAlignment(SwingConstants.CENTER); String a = this.getClass().getResource("../img/flower.png").getPath(); JLabel lblNewLabel = new JLabel(""); lblNewLabel.setIcon(new ImageIcon(a)); lblNewLabel.setBounds(30, 37, 16, 21); panel.add(lblNewLabel); JLabel lbl_Id = new JLabel("I D"); lbl_Id.setBounds(49, 37, 57, 15); panel.add(lbl_Id); lbl_Id.setFont(new Font("", Font.BOLD, 15)); lbl_Id.setHorizontalAlignment(SwingConstants.CENTER); lbl_Id.setForeground(new Color(233, 113, 113)); tf_Id = new JTextField(); tf_Id.setBounds(136, 37, 261, 21); panel.add(tf_Id); tf_Id.setColumns(10); String b = this.getClass().getResource("../img/flower.png").getPath(); JLabel label = new JLabel(""); label.setIcon(new ImageIcon(b)); label.setBounds(30, 83, 16, 21); panel.add(label); String c = this.getClass().getResource("../img/flower.png").getPath(); JLabel label_1 = new JLabel(""); label_1.setIcon(new ImageIcon(c)); label_1.setBounds(30, 167, 16, 21); panel.add(label_1); String d = this.getClass().getResource("../img/flower.png").getPath(); JLabel label_2 = new JLabel(""); label_2.setIcon(new ImageIcon(d)); label_2.setBounds(30, 125, 16, 21); panel.add(label_2); String e = this.getClass().getResource("../img/flower.png").getPath(); JLabel label_3 = new JLabel(""); label_3.setIcon(new ImageIcon(e)); label_3.setBounds(30, 210, 16, 21); panel.add(label_3); String f = this.getClass().getResource("../img/flower.png").getPath(); JLabel label_4 = new JLabel(""); label_4.setIcon(new ImageIcon(f)); label_4.setBounds(30, 260, 16, 21); panel.add(label_4); String g = this.getClass().getResource("../img/flower.png").getPath(); JLabel label_5 = new JLabel(""); label_5.setIcon(new ImageIcon(g)); label_5.setBounds(30, 305, 16, 21); panel.add(label_5); JButton btnNewButton = new JButton("\uC99D\uBE59\uC11C\uB958\uC81C\uCD9C"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(null)) { } } }); btnNewButton.setBounds(347, 305, 112, 23); panel.add(btnNewButton); JLabel lblNewLabel_2 = new JLabel("\u203B\uD560\uC778\uB300\uC0C1\uC790 : \uAE30\uCD08\uC218\uAE09\uC790,\uB2E4\uC790\uB140\uAC00\uC815,\uB2E4\uBB38\uD654\uAC00\uC815,\uC7A5\uC560\uC544\uB3D9\uAC00\uC815,\uAD6D\uAC00\uC720\uACF5\uC790"); lblNewLabel_2.setBounds(30, 334, 438, 61); panel.add(lblNewLabel_2); JLabel lbl_Member = new JLabel("\uD68C \uC6D0 \uAC00 \uC785"); lbl_Member.setBounds(186, 21, 164, 35); frame.getContentPane().add(lbl_Member); lbl_Member.setFont(new Font("", Font.BOLD, 30)); lbl_Member.setForeground(new Color(240, 150, 97)); lbl_Member.setHorizontalAlignment(SwingConstants.CENTER); JButton bnt_Ok = new JButton("\uAC00\uC785\uC644\uB8CC"); bnt_Ok.setBounds(74, 505, 164, 31); frame.getContentPane().add(bnt_Ok); bnt_Ok.setFont(new Font("", Font.BOLD, 15)); bnt_Ok.setForeground(Color.white); bnt_Ok.setBackground(new Color(240, 150, 97)); JButton bnt_refuse = new JButton("\uAC00\uC785\uCDE8\uC18C"); bnt_refuse.setBounds(262, 505, 164, 31); frame.getContentPane().add(bnt_refuse); bnt_refuse.setFont(new Font("", Font.BOLD, 15)); bnt_refuse.setForeground(Color.white); bnt_refuse.setBackground(new Color(250, 236, 197)); bnt_refuse.setBackground(new Color(240, 150, 97)); String h = this.getClass().getResource("../img/horse.png").getPath(); JLabel lblNewLabel_1 = new JLabel(""); lblNewLabel_1.setIcon(new ImageIcon(h)); lblNewLabel_1.setBounds(105, 21, 57, 36); frame.getContentPane().add(lblNewLabel_1); bnt_refuse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, " մϴ", "ȸ", JOptionPane.ERROR_MESSAGE); frame.dispose(); // â ݱ LoginGUI login = new LoginGUI(dto); // â ü } }); bnt_Ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (tf_Id.getText().trim().length() == 0 || tf_Id.getText().trim().equals("̵")) { JOptionPane.showMessageDialog(null, "̵ Է ּ.", "̵ Է", JOptionPane.WARNING_MESSAGE); tf_Id.grabFocus(); return; } if (pw_1.getText().trim().length() == 0) { JOptionPane.showMessageDialog(null, "йȣ Է ּ.", "йȣ Է", JOptionPane.WARNING_MESSAGE); pw_1.grabFocus(); return; } if (pw_2.getText().trim().length() == 0) { JOptionPane.showMessageDialog(null, "йȣ Ȯ Է ּ.", "йȣ Ȯ Է", JOptionPane.WARNING_MESSAGE); pw_2.grabFocus(); return; } if (!(pw_1.getText().trim().equals(pw_2.getText().trim()))) { JOptionPane.showMessageDialog(null, "йȣ ʽϴ.!!", "йȣ Ȯ", JOptionPane.WARNING_MESSAGE); return; } if (tf_Address.getText().trim().length() == 0 || tf_Address.getText().trim().equals("ּ")) { JOptionPane.showMessageDialog(null, "ּҸ Է ּ.", "ּ Է", JOptionPane.WARNING_MESSAGE); tf_Address.grabFocus(); return; } if (tf_Phone.getText().trim().length() == 0 || tf_Phone.getText().trim().equals("ڵ ȣ")) { JOptionPane.showMessageDialog(null, "ڵ ȣ Է ּ.", "ڵ ȣ Է", JOptionPane.WARNING_MESSAGE); tf_Phone.grabFocus(); return; } if (tf_Name.getText().trim().length() == 0 || tf_Name.getText().trim().equals("̸")) { JOptionPane.showMessageDialog(null, "̸ Է ּ.", "̸ Է", JOptionPane.WARNING_MESSAGE); tf_Name.grabFocus(); return; } else { JOptionPane.showMessageDialog(null, " ϵ帳ϴ", "ȸ", JOptionPane.INFORMATION_MESSAGE); frame.dispose(); // â ݱ LoginGUI login = new LoginGUI(dto); // â ü } String id = tf_Id.getText(); String pw = pw_1.getText(); String name = tf_Name.getText(); String address = tf_Address.getText(); String phonenumber = tf_Phone.getText(); if (rb_No.isSelected()) { saletarget = 1;// ش } else if (rb_disabled.isSelected()) { saletarget = 2;// , ʼ } MemberDTO dto = new MemberDTO(id, pw, name, address, phonenumber, saletarget); MemberDAO dao = new MemberDAO(); dao.joinInsert(dto); } }); } }
true
e87d9f22df86db1cefbdd740c6673fe360e5c6a9
Java
wikibook/jboss5
/D.WebServiceExampleWeb/src/com/jbossnotebook/webservice/MathWebService.java
UTF-8
557
2.46875
2
[]
no_license
package com.jbossnotebook.webservice; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; @WebService(targetNamespace = "http://www.jbossnotebook.com/", serviceName = "MathService") @SOAPBinding(style = SOAPBinding.Style.RPC) public class MathWebService { @WebMethod @WebResult(name="result") public double addDouble(@WebParam(name="first") double first, @WebParam(name="second") double second) { return first + second; } }
true
f582a36806599e4dced5f3e38c140a579a9d78bf
Java
Tobi-Akindele/v2-backend-stockbroker-report
/src/main/java/com/ap/greenpole/stockbroker/service/NotificationPostingsService.java
UTF-8
249
1.765625
2
[]
no_license
package com.ap.greenpole.stockbroker.service; import com.ap.greenpole.stockbroker.dto.Notification; public interface NotificationPostingsService { public void determineVerdictAndCallNotificationService(Notification notification, int verdict); }
true
bb49bbf988fe96d4db9bd774a668c5225084ec10
Java
HamoAtayan/SQA-Java
/lilia/src/Week_3/Person/personRepo.java
UTF-8
711
2.96875
3
[]
no_license
package src.Week_3.Person; public class personRepo { static String[] companies = {"Pixar","Webb", "Google", "Microsoft", "Apple", "Picsart"}; static String[] names = {"Alan","Bradley", "Carol", "Drake", "Fabio", "Gary"}; public static person[] getData() { person[] persons = new person[10]; for (int i = 0; i < persons.length; i++) { person person = new person(); person.name = names[(int) (Math.random() * 6)]; person.company = companies[(int) (Math.random() * 6)]; person.age = (int) (Math.random() * 100); persons[i] = person; } return persons; } }
true
deb6a582aa0f4a85b2e1866e2d121985b1a4e58b
Java
TheSunGodLives/decisions-loops-TheSunGodLives-master
/decisions-loops-TheSunGodLives-master/Chapter 6 Notes/Warmup.java
UTF-8
363
3.125
3
[]
no_license
/** * Write a description of class Warmup here. * * @author (your name) * @version (a version number or a date) */ public class Warmup { public Warmup() { } public void forLoop() { for( int count = 10; count >= -10; count -= 5) { System.out.println(count); } } }
true
c093b08317cc761df5cb0e79552ccf903d3a28a1
Java
builder-soft/BSframework
/src/cl/buildersoft/framework/web/servlet/RedirectServlet.java
UTF-8
1,046
2.28125
2
[]
no_license
package cl.buildersoft.framework.web.servlet; import java.io.IOException; import java.net.URLDecoder; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class RedirectServlet */ @WebServlet("/servlet/RedirectServlet") public class RedirectServlet extends BSHttpServlet_ { private static final Logger LOG = LogManager.getLogger(RedirectServlet.class); private static final long serialVersionUID = -7842326785701649806L; public RedirectServlet() { super(); } protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = request.getParameter("URL"); url = URLDecoder.decode(url, "UTF-8"); LOG.trace(String.format("Forwarding to '%s'", url)); forward(request, response, url); } }
true
8eba6b08d7f3c2f1435c0a83b3f815668b5ccf53
Java
nalcsmn/stacks
/staks/src/quizstak/stak.java
UTF-8
1,526
3.375
3
[]
no_license
package quizstak; import java.util.Scanner; import java.util.Stack; public class stak { static Stack<String> pileofshit = new Stack<>(); static Scanner input = new Scanner(System.in); public static void main(String[] args) { inputstackablestack(); } public static void choys() { // TODO Auto-generated method stub System.out.println("1. view top stack"); System.out.println("2. delete top stak"); int choice = input.nextInt(); if (choice == 1) { accessthetop(); } else if (choice == 2) { deletestak(); } else { System.out.print("Invalid"); inputstackablestack(); } } public static void inputstackablestack() { // TODO Auto-generated method stub System.out.println("Enter 4 shits: "); String temp =input.nextLine(); String temp2 =input.nextLine(); String temp3 =input.nextLine(); String temp4 =input.nextLine(); pileofshit.push(temp); pileofshit.push(temp2); pileofshit.push(temp3); pileofshit.push(temp4); choys(); } public static void accessthetop() { // TODO Auto-generated method stub String view= pileofshit.peek(); System.out.println("peek()=> "+ view); choys(); } private static void deletestak() { // TODO Auto-generated method stub System.out.println(); String DEL=pileofshit.pop(); System.out.println(pileofshit); choys(); } }
true
82712afeb4951709279958aa12169ebb1b2aa4d1
Java
mihajlo-perendija/XML_WS
/MainApp/Servers/vehicle/src/main/java/vehicle/controller/BrandController.java
UTF-8
3,298
2.25
2
[]
no_license
package vehicle.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import saga.dto.BrandDTO; import vehicle.dto.BrandPageDTO; import vehicle.exceptions.ConversionFailedError; import vehicle.exceptions.DuplicateEntity; import vehicle.exceptions.EntityNotFound; import vehicle.exceptions.UnexpectedError; import vehicle.service.BrandService; import java.util.List; @RestController @RequestMapping(value = "brand") @CrossOrigin(origins = "*") public class BrandController { @Autowired BrandService brandService; @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> getAll( @RequestHeader(value = "page", required = false) Integer pageNo, @RequestHeader(value = "sort", required = false) String sort, @RequestHeader(value = "pageable", required = false) Boolean pageable) throws ConversionFailedError, EntityNotFound { sort = (sort != null) ? sort : "id"; pageNo = (pageNo != null) ? pageNo : 0; if (pageable) { BrandPageDTO page = brandService.getAllPageable(pageNo, sort); return new ResponseEntity<>(page, HttpStatus.OK); } else { List<BrandDTO> allBrands = brandService.getAll(); return new ResponseEntity<>(allBrands, HttpStatus.OK); } } @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize("hasAuthority('CREATE_VEHICLE_PART_PERMISSION')") public ResponseEntity<BrandDTO> createNew(@RequestBody BrandDTO brandDTO) throws DuplicateEntity, ConversionFailedError { BrandDTO added = brandService.add(brandDTO); return new ResponseEntity<>(added, HttpStatus.ACCEPTED); } @GetMapping(path = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<BrandDTO> getOne(@PathVariable Long id) throws EntityNotFound, ConversionFailedError { BrandDTO brandDTO = brandService.getOne(id); return new ResponseEntity<>(brandDTO, HttpStatus.ACCEPTED); } @PutMapping(path = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize("hasAuthority('CHANGE_VEHICLE_PART_PERMISSION')") public ResponseEntity<BrandDTO> update(@PathVariable Long id, @RequestBody BrandDTO brandDTO) throws UnexpectedError, ConversionFailedError, EntityNotFound { BrandDTO updated = brandService.update(id, brandDTO); return new ResponseEntity<>(updated, HttpStatus.ACCEPTED); } @DeleteMapping(path = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize("hasAuthority('DELETE_VEHICLE_PART_PERMISSION')") public ResponseEntity<BrandDTO> delete(@PathVariable Long id) throws EntityNotFound, ConversionFailedError { brandService.delete(id); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } }
true
9e8387d12daa7b1d39d28ae9174281a8553be456
Java
KsonCode/MvpDesignFramework
/app/src/main/java/com/example/kson/mvpdesignframework/contract/user/LoginContract.java
UTF-8
1,084
2.109375
2
[]
no_license
package com.example.kson.mvpdesignframework.contract.user; import com.example.kson.library.base.base.BasePresenter; import com.example.kson.library.base.base.IBaseModel; import com.example.kson.library.base.base.IBaseView; import com.example.kson.mvpdesignframework.bean.UserBean; import com.example.kson.mvpdesignframework.model.user.LoginModel; import java.util.Map; import io.reactivex.Observable; /** * Author:kson * E-mail:[email protected] * Time:2018/03/15 * Description:登录contract类, */ public interface LoginContract { abstract class LoginPresenter extends BasePresenter<ILoginModel,ILoginView> { @Override public ILoginModel getmModel() { return new LoginModel(); } public abstract void login(Map<String,String> params); public abstract void verify(String mobile,String pass); } interface ILoginModel extends IBaseModel { Observable<UserBean> login(Map<String,String> params); } interface ILoginView extends IBaseView { void success(UserBean userBean); } }
true
870658c67b8232ef271550bba0c5ef8517a24cf0
Java
98bazsikaX/CSAPAT_PROJEKT
/csapat-desktop/src/main/java/hu/alkfejl/controller/OrgController.java
UTF-8
3,387
2.34375
2
[]
no_license
package hu.alkfejl.controller; import com.sun.tools.javac.Main; import dao.OrgDAO; import dao.OrgDAOImpl; import hu.alkfejl.App; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.HBox; import model.Organization; import model.Player; import java.net.URL; import java.time.LocalDate; import java.util.ResourceBundle; public class OrgController implements Initializable { OrgDAO dao = new OrgDAOImpl(); @FXML private TableView<Organization> orgTable; @FXML private TableColumn<Organization,Integer> idColumn; @FXML private TableColumn<Organization,String> nameColumn; @FXML private TableColumn<Organization,String> foundedColumn; @FXML private TableColumn<Organization,Void> settingsColumn; private URL url; private ResourceBundle b; @Override public void initialize(URL url, ResourceBundle resourceBundle){ refreshTable(); idColumn.setCellValueFactory(new PropertyValueFactory<>("id")); nameColumn.setCellValueFactory(new PropertyValueFactory<>("name")); foundedColumn.setCellValueFactory(new PropertyValueFactory<>("foundation")); settingsColumn.setCellFactory(param -> new TableCell<>(){ private final Button deleteButton = new Button("Delete"); private final Button editButton = new Button("Edit"); { //STATIKUS CUCC__________________________________ deleteButton.setOnAction(event -> { Organization org = getTableRow().getItem(); deleteOrg(org); refreshTable(); }); editButton.setOnAction(event -> { Organization org = getTableRow().getItem(); editOrg(org); refreshTable(); }); }//________________________________________________ @Override protected void updateItem(Void item, boolean empty) { super.updateItem(item, empty); if(empty){ setGraphic(null); }else{ HBox container = new HBox(); container.getChildren().addAll(editButton,deleteButton); container.setSpacing(10); setGraphic(container); } } }); } public void addOrg(){ Organization org = new Organization(); editOrg(org); } private void editOrg(Organization org) { FXMLLoader loader = App.loadFXML("/fxml/add_edit_org.fxml"); AddEditOrg edit = loader.getController(); edit.setOrg(org); refreshTable(); } private void deleteOrg(Organization org) { Alert confirm = new Alert(Alert.AlertType.CONFIRMATION,"Biztos törölni akarja a céget?" ,ButtonType.APPLY,ButtonType.CANCEL); confirm.showAndWait().ifPresent(buttonType -> { if(buttonType.equals(ButtonType.APPLY)){ dao.delete(org); } }); } private void refreshTable() { orgTable.getItems().addAll(dao.findAll()); } public void showPlayer(){ App.loadFXML("/fxml/mainWindow.fxml"); } }
true
62890c0e35432222a5e7b895255a4cdc80bb5747
Java
JamesWillLewis/WSIntelliAuction
/WSIntelliAuction/src/com/uct/cs/wsintelliauction/network/message/CloseConnectionMessage.java
UTF-8
685
2.421875
2
[]
no_license
package com.uct.cs.wsintelliauction.network.message; /** * Indicates that the server has disconnected. * * @author James * */ public class CloseConnectionMessage extends ConnectionMessage { /** * */ private static final long serialVersionUID = 6774572759680575701L; /** * If the host instantiating this message was the host who initialized the disconnect. */ public boolean isInitializer; /** * If this message was created due to a communication failure. */ public boolean communicationFail; public CloseConnectionMessage(boolean isInitializer) { this.isInitializer = isInitializer; communicationFail = false; } }
true
b9f5d146c1c297a583f72c7689e895dc376daf27
Java
captPatches/narayana
/kvstore/src/test/java/org/jboss/narayana/kvstore/infinispan/perftests/ReplicatedStoreTester.java
UTF-8
733
2.1875
2
[]
no_license
package org.jboss.narayana.kvstore.infinispan.perftests; public class ReplicatedStoreTester extends MillTester { @Override public void setup() { System.setProperty("ObjectStoreEnvironmentBean.objectStoreType", "com.arjuna.ats.internal.arjuna.objectstore.kvstore.KVObjectStoreAdaptor"); if(runOnMill()) { System.setProperty( "KVStoreEnvironmentBean.storeImplementationClassName", "org.jboss.narayana.kvstore.infinispan.mill.MillReplCacheStore"); setMessage("(Mill) Replicated Cache Store"); } else { System.setProperty( "KVStoreEnvironmentBean.storeImplementationClassName", "org.jboss.narayana.kvstore.infinispan.ReplicatedStore"); setMessage("Replicated Cache Store"); } } }
true
dbc87b8993129c308b4036596eee90cc73e8b7c5
Java
SwimmingHwang/Humuson-IMC-Intern
/intern-agent-common/src/main/java/com/humuson/agent/domain/entity/FtReport.java
UTF-8
1,883
1.976563
2
[]
no_license
package com.humuson.agent.domain.entity; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import javax.persistence.*; @Getter @NoArgsConstructor @Table(name = "imc_ft_biz_msg_log") @Entity public class FtReport { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String status; private String priority; private String reserved_date; private String sender_key; private String phone_number; private String message; private String request_uid; private String request_date; private String response_date; private String response_code; private String report_type; private String report_date; private String report_code; private String arrival_date; private String etc1; private String etc2; @Builder public FtReport(Long id, String status, String priority, String reserved_date, String sender_key, String phone_number, String message, String request_uid, String request_date, String response_date, String response_code, String report_type, String report_date, String report_code, String arrival_date, String etc1, String etc2) { this.id = id; this.status = status; this.priority = priority; this.reserved_date = reserved_date; this.sender_key = sender_key; this.phone_number = phone_number; this.message = message; this.request_uid = request_uid; this.request_date = request_date; this.response_date = response_date; this.response_code = response_code; this.report_type = report_type; this.report_date = report_date; this.report_code = report_code; this.arrival_date = arrival_date; this.etc1 = etc1; this.etc2 = etc2; } public void setEtc1Status(String etc1) { this.etc1 = etc1; } }
true
5444a486f1fd95811482b8e36e8989cd3b9b4c24
Java
sgremalschi/cisco
/src/test/java/cisco/java/challenge/NodeTest.java
UTF-8
900
2.921875
3
[]
no_license
package cisco.java.challenge; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import cisco.java.challenge.impl.Node; public class NodeTest { @Test(expected = IllegalArgumentException.class) public void whenExceptionThrown_nullOrEmpty() { String name = null; new Node(name); name = ""; new Node(name); } @Test(expected = NullPointerException.class) public void whenExceptionThrown_null_node() { Node node = new Node("A"); node.addChild(null); } @Test public void testGetChildren() { Node a = new Node("A"); assertNotNull(a.getChildren()); assertEquals(0, a.getChildren().length); assertTrue("A".equals(a.getName())); assertTrue("A".equals(a.toString())); Node b = new Node("B"); a.addChild(b); assertTrue(1 == a.getChildren().length); } }
true
4f65fd778bfc43d4b9d4463af77b15c6aac6a628
Java
4201VitruvianBots/DeepSpace2019
/src/main/java/frc/robot/commands/wrist/UpdateWristSetpoint.java
UTF-8
2,609
2.34375
2
[]
no_license
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.commands.wrist; import edu.wpi.first.wpilibj.command.Command; import frc.robot.Robot; import frc.robot.subsystems.Wrist; /** * An example command. You can replace me with your own command. */ public class UpdateWristSetpoint extends Command { public UpdateWristSetpoint() { // Use requires() here to declare subsystem dependencies requires(Robot.wrist); } // Called just before this Command runs the first time @Override protected void initialize() { } // Called repeatedly when this Command is scheduled to run @Override protected void execute() { double joystickOutput = Robot.m_oi.getXBoxRightY(); if (Wrist.controlMode == 1) { if(Math.abs(joystickOutput) > 0.05) { double setpoint = joystickOutput * 10; // TODO: Change this logic to use limit switches when they are fixed if(setpoint <= 0 && Robot.wrist.getAngle() < 0.1 || setpoint >= 120 && Robot.wrist.getAngle() > 119.9) Robot.m_oi.enableXBoxRumbleTimed(0.2); Robot.wrist.setIncrementedPosition(setpoint); } } else { // TODO: Uncomment once limit switches are implemented /*if(Robot.wrist.getLimitSwitchState(0) || Robot.wrist.getLimitSwitchState(1)) { joystickOutput = 0; Robot.m_oi.setXBoxRumble(0.8); } else Robot.m_oi.setXBoxRumble(0);*/ if(Math.abs(joystickOutput) > 0.05) Robot.wrist.setDirectOutput (joystickOutput); else Robot.wrist.setDirectOutput (0); } } // Make this return true when this Command no longer needs to run execute() @Override protected boolean isFinished() { return false; } // Called once after isFinished returns true @Override protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run @Override protected void interrupted() { } }
true
f0f5f180c7c000bfaca5dfbbe385a5d759e4c9c7
Java
TheLogicalNights/spring-framework
/ListInjection/src/main/java/com/spring/ListInjection/Employee.java
UTF-8
581
2.5625
3
[ "MIT" ]
permissive
package com.spring.ListInjection; import java.util.*; public class Employee { private int empId; private List<String> empPhoneNo; private List<String> empAddress; public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public List<String> getEmpPhoneNo() { return empPhoneNo; } public void setEmpPhoneNo(List<String> empPhoneNo) { this.empPhoneNo = empPhoneNo; } public List<String> getEmpAddress() { return empAddress; } public void setEmpAddress(List<String> empAddress) { this.empAddress = empAddress; } }
true
0e94180674e546ee4001401d1accb44d902a2b51
Java
dfudger/PacMan-DinoStyle
/src/pacmangame/Collision.java
UTF-8
1,867
3.359375
3
[]
no_license
/* * * Pacman Game - Collision.java * CIS*3760 Assignment Two * University of Guelph * * Author: Danielle Fudger 0621496 * Contact: [email protected] * Date: Januray 26, 2013 * * This is a java based pacman style game. For more information, please see the README. * */ package pacmangame; /** * This class is responsible for methods related to collision detection in the pacman game. * @author dfudger */ public class Collision { /** * This function is passed two coordinates as parameters. * If the object represented in the gameMap at the specified coordinates is the same as a wall, return that wall collision is true. * @param x * @param y * @return boolean if wall has been hit */ public static boolean hitWall(int x, int y) { if(Window.getMapItem(x, y) == 0) return true; else return false; } /** * This function is passed two coordinates as parameters. * If the object represented in the gameMap at the specified coordinates is the same as an enemy, return that enemy collision is true. * @param x * @param y * @return boolean if enemy has been hit */ public static boolean hitEnemy(int x, int y) { if(Window.getMapItem(x, y) == 4) return true; else return false; } /** * This function is passed two coordinates as parameters. * If the object represented in the gameMap at the specified coordinates is the same as the hero, return that hero collision from enemy is true. * @param x * @param y * @return boolean if hero has been hit */ public static boolean hitHero(int x, int y) { if(Window.getMapItem(x, y) == 5) return true; else return false; } }
true
4e156081150258a91f5c7e20b43c16f539046c89
Java
SinghDharmendra/DSA-PS
/src/main/java/ps/dp/mcm/EvaluateExpressionToTrueParenthesization.java
UTF-8
1,884
3.046875
3
[]
no_license
package ps.dp.mcm; import javax.print.StreamPrintServiceFactory; public class EvaluateExpressionToTrueParenthesization { public static void main(String[] args) { String exp = "T|T&F^T"; int res = solve(exp, 0, exp.length() - 1, true); System.out.println("total number of ways : "+res); } private static int solve(String s, int i, int j, boolean isTrue) { if (i > j) return 0; if (i == j) { if (isTrue == true) { return s.charAt(i) == 'T' ? 1 : 0; } else { return s.charAt(i) == 'F' ? 1 : 0; } } int ans = 0; for (int k = i + 1; k < j; k = k + 2) { int lt = solve(s, i, k - 1, true); int lf = solve(s, i, k - 1, false); int rt = solve(s, k + 1, j, true); int rf = solve(s, k + 1, j, false); char c = s.charAt(k); switch (c) { case '&': { if (isTrue == true) { ans = ans + lt * rt; } else { ans = ans + lt * rf + lf * rt + lf * rf; } break; } case '|': { if (isTrue == true) { ans = ans + lt * rt + lt * rf + lf * rt; } else { ans = ans + lf * rf; } break; } case '^': { if (isTrue == true) { ans = ans + lt * rf + lf * rt; } else { ans = ans + lf * rf + lt * rt; } break; } } } return ans; } }
true
758a7b839624509caf9a88e4383110f6ec887974
Java
wernerware/video-notes
/obfuscation/test_1_out/org/a/a/a/p/class_317.java
UTF-8
1,161
2.1875
2
[]
no_license
package org.a.a.a.p; import java.util.NoSuchElementException; import java.util.Map.Entry; // $FF: renamed from: org.a.a.a.p.o final class class_317 extends class_311 { // $FF: renamed from: f java.lang.Object private final Object field_519; // $FF: renamed from: a org.a.a.a.p.n // $FF: synthetic field final class_323 field_520; private class_317(class_323 var1, class_301 var2, class_301 var3) { super(var1.field_541, var2); this.field_520 = var1; this.field_519 = var3 != null ? var3.getKey() : null; } public boolean hasNext() { return this.c != null && !class_302.method_711(this.c.a, this.field_519); } // $FF: renamed from: a () java.util.Map.Entry public Entry method_750() { if (this.c != null && !class_302.method_711(this.c.a, this.field_519)) { return this.c(); } else { throw new NoSuchElementException(); } } // $FF: synthetic method public Object next() { return this.method_750(); } // $FF: synthetic method class_317(class_323 var1, class_301 var2, class_301 var3, class_330 var4) { this(var1, var2, var3); } }
true
1697ad9d822809e87a5bb19907f1a3bc5dca4e1a
Java
MarceloMr83/tpfinal
/src/main/java/com/poo/tpfinal/entities/Cancellation.java
UTF-8
1,694
2.390625
2
[]
no_license
package com.poo.tpfinal.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Version; import javax.validation.constraints.NotNull; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.JoinColumn; import java.util.Date; @Entity public class Cancellation { @Version private int version; @Id @NotNull @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "idCancelation") private long idCancelation; @NotNull @DateTimeFormat(pattern="yyyy-MM-dd") @Column(name = "createdAt", nullable = false) private Date createdAt; @NotNull @OneToOne @JoinColumn(name = "Booking", updatable = false, nullable = false) private Booking booking; public void setVersionNum(int version){ this.version=version; } public int getVersionNum(){ return version; } public long getId() { return idCancelation; } public void setId(long idCancelation) { this.idCancelation = idCancelation; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Booking getBooking() { return booking; } public void setBooking(Booking booking) { this.booking = booking; } @Override public String toString() { return "User [id=" + idCancelation + ", createdAt=" + createdAt.toString() + ", booking=" + booking.toString() +"]"; } }
true
727abf89e4b33c3ccd4b1cdf244ffa351a8523a0
Java
letimome/CustomDiff
/src/main/java/customs/models/DevelopersInCustomizations.java
UTF-8
958
2.34375
2
[]
no_license
package customs.models; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table (name="developers_in_customizations") public class DevelopersInCustomizations { @Id int id; int id_customization; int id_developer; int name; int email; public DevelopersInCustomizations() {} public int getId() { return id; } public void setId(int id) { this.id = id; } public int getId_customization() { return id_customization; } public void setId_customization(int id_customization) { this.id_customization = id_customization; } public int getId_developer() { return id_developer; } public void setId_developer(int id_developer) { this.id_developer = id_developer; } public int getName() { return name; } public void setName(int name) { this.name = name; } public int getEmail() { return email; } public void setEmail(int email) { this.email = email; } }
true
4d8758272d1ab30ab3e581f5a56c36f0dfa2e92c
Java
Chipitos/Tmbd
/app/src/main/java/com/tmbdnews/view/activities/BaseBindingActivity.java
UTF-8
842
1.953125
2
[]
no_license
package com.tmbdnews.view.activities; import android.databinding.DataBindingUtil; import android.databinding.ViewDataBinding; import android.os.Bundle; import android.support.annotation.Nullable; import com.tmbdnews.annotations.Layout; public abstract class BaseBindingActivity<B extends ViewDataBinding> extends BaseInjectActivity { private B binding; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (binding == null) { int layout = getClass().getAnnotation(Layout.class).value(); if (layout == 0) { throw new IllegalStateException("Layout must not be null and should be implemented via initLayout"); } binding = DataBindingUtil.setContentView(this, layout); } } }
true
ab5eda7739f687dd7155cd42c680315e0cf4c54f
Java
csgrabt/training-solutions
/src/test/java/week06d04/junior/ItemTest.java
UTF-8
964
2.8125
3
[]
no_license
package week06d04.junior; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import week06d04.junior.Item; import static org.junit.jupiter.api.Assertions.*; class ItemTest { @Test void priceIsNotValid() { IllegalArgumentException ioe = Assertions.assertThrows(IllegalArgumentException.class, () -> new Item(-10, 5, "Alma")); assertEquals("Price is not valid!", ioe.getMessage()); } @Test void monthIsNegative() { IllegalArgumentException ioe = Assertions.assertThrows(IllegalArgumentException.class, () -> new Item(10, -5, "Alma")); assertEquals("Date is not valid!", ioe.getMessage()); } @Test void monthIsHigherThan12() { IllegalArgumentException ioe = Assertions.assertThrows(IllegalArgumentException.class, () -> new Item(10, 13, "Alma")); assertEquals("Date is not valid!", ioe.getMessage()); } }
true
849dcee2519b496331a929839db5c58a9a22fd1f
Java
MelonsYum/leap-client
/leap/util/MoveUtil.java
UTF-8
11,590
2.203125
2
[]
no_license
/* */ package leap.util; /* */ import leap.events.listeners.EventMotion; /* */ import net.minecraft.block.Block; /* */ import net.minecraft.block.state.IBlockState; /* */ import net.minecraft.client.Minecraft; /* */ import net.minecraft.entity.Entity; /* */ import net.minecraft.network.Packet; /* */ import net.minecraft.network.play.client.C03PacketPlayer; /* */ import net.minecraft.potion.Potion; /* */ import net.minecraft.util.BlockPos; /* */ import org.lwjgl.input.Keyboard; /* */ /* */ public class MoveUtil { /* 14 */ protected static Minecraft mc = Minecraft.getMinecraft(); /* */ /* */ public static void setSpeed(EventMotion moveEvent, double moveSpeed) { /* 17 */ setSpeed(moveEvent, moveSpeed, mc.thePlayer.rotationYaw, mc.thePlayer.movementInput.moveStrafe, mc.thePlayer.movementInput.moveForward); /* */ } /* */ /* */ public static boolean isMovingOnGround() { /* 21 */ return (isMoving() && mc.thePlayer.onGround); /* */ } /* */ /* */ public static float getRetarded() { /* 25 */ return 0.2873F; /* */ } /* */ /* */ public static double getJumpHeight(double speed) { /* 29 */ return mc.thePlayer.isPotionActive(Potion.jump) ? (speed + 0.1D * (mc.thePlayer.getActivePotionEffect(Potion.jump).getAmplifier() + 1)) : speed; /* */ } /* */ /* */ /* */ public static void strafe(float speed) { /* 34 */ if (!isMoving()) { /* */ return; /* */ } /* 37 */ double yaw = getDirection(); /* 38 */ mc.thePlayer.motionX = -Math.sin(yaw) * speed; /* 39 */ mc.thePlayer.motionZ = Math.cos(yaw) * speed; /* */ } /* */ /* */ public static double getDirection() { /* 43 */ float rotationYaw = mc.thePlayer.rotationYaw; /* */ /* 45 */ if (mc.thePlayer.moveForward < 0.0F) { /* 46 */ rotationYaw += 180.0F; /* */ } /* 48 */ float forward = 1.0F; /* 49 */ if (mc.thePlayer.moveForward < 0.0F) { /* 50 */ forward = -0.5F; /* 51 */ } else if (mc.thePlayer.moveForward > 0.0F) { /* 52 */ forward = 0.5F; /* */ } /* 54 */ if (mc.thePlayer.moveStrafing > 0.0F) { /* 55 */ rotationYaw -= 90.0F * forward; /* */ } /* 57 */ if (mc.thePlayer.moveStrafing < 0.0F) { /* 58 */ rotationYaw += 90.0F * forward; /* */ } /* 60 */ return Math.toRadians(rotationYaw); /* */ } /* */ /* */ public static void sendPosition(double x, double y, double z, boolean ground, boolean moving) { /* 64 */ if (!moving) { /* 65 */ mc.getNetHandler().addToSendQueue((Packet)new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY + y, mc.thePlayer.posZ, ground)); /* */ } else { /* 67 */ mc.getNetHandler().addToSendQueue((Packet)new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX + x, mc.thePlayer.posY + y, mc.thePlayer.posZ + z, ground)); /* */ } /* */ } /* */ /* */ public static Block getBlockAtPos(BlockPos inBlockPos) { /* 72 */ IBlockState s = mc.theWorld.getBlockState(inBlockPos); /* 73 */ return s.getBlock(); /* */ } /* */ /* */ public static void setSpeed(EventMotion moveEvent, double moveSpeed, float pseudoYaw, double pseudoStrafe, double pseudoForward) { /* 77 */ double forward = pseudoForward; /* 78 */ double strafe = pseudoStrafe; /* 79 */ float yaw = pseudoYaw; /* */ /* 81 */ if (forward != 0.0D) { /* 82 */ if (strafe > 0.0D) { /* 83 */ yaw += ((forward > 0.0D) ? -45 : 45); /* 84 */ } else if (strafe < 0.0D) { /* 85 */ yaw += ((forward > 0.0D) ? 45 : -45); /* */ } /* 87 */ strafe = 0.0D; /* 88 */ if (forward > 0.0D) { /* 89 */ forward = 1.0D; /* 90 */ } else if (forward < 0.0D) { /* 91 */ forward = -1.0D; /* */ } /* */ } /* */ /* 95 */ if (strafe > 0.0D) { /* 96 */ strafe = 1.0D; /* 97 */ } else if (strafe < 0.0D) { /* 98 */ strafe = -1.0D; /* */ } /* 100 */ double mx = Math.cos(Math.toRadians((yaw + 90.0F))); /* 101 */ double mz = Math.sin(Math.toRadians((yaw + 90.0F))); /* 102 */ moveEvent.x = forward * moveSpeed * mx + strafe * moveSpeed * mz; /* 103 */ moveEvent.z = forward * moveSpeed * mz - strafe * moveSpeed * mx; /* */ } /* */ /* */ /* */ public static double getBaseMoveSpeed() { /* 108 */ double baseSpeed = 0.2875D; /* 109 */ if (mc.thePlayer.isPotionActive(Potion.moveSpeed)) /* 110 */ baseSpeed *= 1.0D + 0.2D * (mc.thePlayer.getActivePotionEffect(Potion.moveSpeed).getAmplifier() + 1); /* 111 */ return baseSpeed; /* */ } /* */ /* */ public static boolean isMoving() { /* 115 */ return !(mc.thePlayer.movementInput.moveForward == 0.0F && mc.thePlayer.movementInput.moveStrafe == 0.0F); /* */ } /* */ /* */ public static double defaultMoveSpeed() { /* 119 */ return mc.thePlayer.isSprinting() ? 0.28700000047683716D : 0.22300000488758087D; /* */ } /* */ /* */ public static double getLastDistance() { /* 123 */ return Math.hypot(mc.thePlayer.posX - mc.thePlayer.prevPosX, mc.thePlayer.posZ - mc.thePlayer.prevPosZ); /* */ } /* */ /* */ public static boolean isOnGround(double height) { /* 127 */ return !mc.theWorld.getCollidingBoundingBoxes((Entity)mc.thePlayer, mc.thePlayer.getEntityBoundingBox().offset(0.0D, -height, 0.0D)).isEmpty(); /* */ } /* */ /* */ public static double jumpHeight() { /* 131 */ if (mc.thePlayer.isPotionActive(Potion.jump)) { /* 132 */ return 0.419999986886978D + 0.1D * (mc.thePlayer.getActivePotionEffect(Potion.jump).getAmplifier() + 1); /* */ } /* 134 */ return 0.419999986886978D; /* */ } /* */ /* */ public static double getJumpBoostModifier(double baseJumpHeight) { /* 138 */ if (mc.thePlayer.isPotionActive(Potion.jump)) { /* 139 */ int amplifier = mc.thePlayer.getActivePotionEffect(Potion.jump).getAmplifier(); /* 140 */ baseJumpHeight += ((amplifier + 1) * 0.1F); /* */ } /* */ /* 143 */ return baseJumpHeight; /* */ } /* */ /* */ /* */ public static void setSpeed(double moveSpeed, float yaw, double strafe, double forward) { /* 148 */ double fforward = mc.thePlayer.movementInput.moveForward; /* 149 */ double sstrafe = mc.thePlayer.movementInput.moveStrafe; /* 150 */ float yyaw = mc.thePlayer.rotationYaw; /* 151 */ if (forward != 0.0D) { /* 152 */ if (strafe > 0.0D) { /* 153 */ yaw += ((forward > 0.0D) ? -45 : 45); /* 154 */ } else if (strafe < 0.0D) { /* 155 */ yaw += ((forward > 0.0D) ? 45 : -45); /* */ } /* 157 */ strafe = 0.0D; /* 158 */ if (forward > 0.0D) { /* 159 */ forward = 1.0D; /* 160 */ } else if (forward < 0.0D) { /* 161 */ forward = -1.0D; /* */ } /* */ } /* 164 */ if (strafe > 0.0D) { /* 165 */ strafe = 1.0D; /* 166 */ } else if (strafe < 0.0D) { /* 167 */ strafe = -1.0D; /* */ } /* 169 */ double mx = Math.cos(Math.toRadians((yaw + 90.0F))); /* 170 */ double mz = Math.sin(Math.toRadians((yaw + 90.0F))); /* 171 */ mc.thePlayer.motionX = forward * moveSpeed * mx + strafe * moveSpeed * mz; /* 172 */ mc.thePlayer.motionZ = forward * moveSpeed * mz - strafe * moveSpeed * mx; /* */ } /* */ /* */ /* */ /* */ public static void setMotionWithValues(EventMotion em, double speed, float yaw, double forward, double strafe) { /* 178 */ if (forward == 0.0D && strafe == 0.0D) { /* 179 */ if (em != null) { /* 180 */ em.setX(0.0D); /* 181 */ em.setZ(0.0D); /* */ } else { /* 183 */ mc.thePlayer.motionX = 0.0D; /* 184 */ mc.thePlayer.motionZ = 0.0D; /* */ } /* */ } else { /* 187 */ if (forward != 0.0D) { /* 188 */ if (strafe > 0.0D) { /* 189 */ yaw += ((forward > 0.0D) ? -45 : 45); /* 190 */ } else if (strafe < 0.0D) { /* 191 */ yaw += ((forward > 0.0D) ? 45 : -45); /* */ } /* 193 */ strafe = 0.0D; /* 194 */ if (forward > 0.0D) { /* 195 */ forward = 1.0D; /* 196 */ } else if (forward < 0.0D) { /* 197 */ forward = -1.0D; /* */ } /* */ } /* 200 */ mc.thePlayer.motionX = forward * speed * Math.cos(Math.toRadians((yaw + 90.0F))) + strafe * speed * Math.sin(Math.toRadians((yaw + 90.0F))); /* 201 */ mc.thePlayer.motionZ = forward * speed * Math.sin(Math.toRadians((yaw + 90.0F))) - strafe * speed * Math.cos(Math.toRadians((yaw + 90.0F))); /* */ } /* */ } /* */ /* */ public static void setSilentMotionWithValues(EventMotion em, double speed, float yaw, double forward, double strafe) { /* 206 */ if (forward == 0.0D && strafe == 0.0D) { /* 207 */ if (em != null) { /* 208 */ em.setX(0.0D); /* 209 */ em.setZ(0.0D); /* */ } else { /* 211 */ mc.thePlayer.motionX = 0.0D; /* 212 */ mc.thePlayer.motionZ = 0.0D; /* */ } /* */ } else { /* 215 */ if (forward != 0.0D) { /* 216 */ if (strafe > 0.0D) { /* 217 */ yaw += ((forward > 0.0D) ? -45 : 45); /* 218 */ } else if (strafe < 0.0D) { /* 219 */ yaw += ((forward > 0.0D) ? 45 : -45); /* */ } /* 221 */ strafe = 0.0D; /* 222 */ if (forward > 0.0D) { /* 223 */ forward = 1.0D; /* 224 */ } else if (forward < 0.0D) { /* 225 */ forward = -1.0D; /* */ } /* */ } /* 228 */ em.x = forward * speed * Math.cos(Math.toRadians((yaw + 90.0F))) + strafe * speed * Math.sin(Math.toRadians((yaw + 90.0F))); /* 229 */ em.z = forward * speed * Math.sin(Math.toRadians((yaw + 90.0F))) - strafe * speed * Math.cos(Math.toRadians((yaw + 90.0F))); /* */ } /* */ } /* */ /* */ public static float getSpeed() { /* 234 */ return (float)Math.sqrt(mc.thePlayer.motionX * mc.thePlayer.motionX + mc.thePlayer.motionZ * mc.thePlayer.motionZ); /* */ } /* */ /* */ public static boolean isMovingWithKeys() { /* 238 */ if (!Keyboard.isKeyDown(mc.gameSettings.keyBindForward.getKeyCode()) && !Keyboard.isKeyDown(mc.gameSettings.keyBindBack.getKeyCode()) && !Keyboard.isKeyDown(mc.gameSettings.keyBindLeft.getKeyCode()) && !Keyboard.isKeyDown(mc.gameSettings.keyBindRight.getKeyCode())) { /* 239 */ return false; /* */ } /* 241 */ return true; /* */ } /* */ /* */ /* */ public static void setSpeed(double moveSpeed) { /* 246 */ setSpeed(moveSpeed, mc.thePlayer.rotationYaw, mc.thePlayer.movementInput.moveStrafe, mc.thePlayer.movementInput.moveForward); /* */ } /* */ /* */ public double getTickDist() { /* 250 */ double xDist = mc.thePlayer.posX - mc.thePlayer.lastTickPosX; /* 251 */ double zDist = mc.thePlayer.posZ - mc.thePlayer.lastTickPosZ; /* 252 */ return Math.sqrt(Math.pow(xDist, 2.0D) + Math.pow(zDist, 2.0D)); /* */ } /* */ } /* Location: C:\Users\wyatt\Downloads\Leap-Client.jar!\lea\\util\MoveUtil.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
true
4abdc93ec5447d53f4cb851387da161ba688dac0
Java
thomas82/interop
/src/main/java/org/mediaserv/fibre/protocole/domain/gestionfichier/TypeProtocole.java
UTF-8
400
2.234375
2
[]
no_license
package org.mediaserv.fibre.protocole.domain.gestionfichier; /** * * @author Thomas Lecocq */ public enum TypeProtocole { PM("PM"), ACCES("ACCES"), SAV("SAV"), WKF("WKF"),; private final String protocole; public String getProtocole() { return protocole; } private TypeProtocole(final String typeProtocole) { this.protocole = typeProtocole; } }
true
5ae5d34aca6622b73be85bce9a7f39465df0142c
Java
Accomple/AndroidApp
/app/src/main/java/live/sockets/accomple/AccommodationListAdapter.java
UTF-8
5,139
2.140625
2
[ "MIT" ]
permissive
package live.sockets.accomple; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class AccommodationListAdapter extends RecyclerView.Adapter<AccommodationListAdapter.AccommodationViewHolder> { JSONArray accommodations; Context context; public AccommodationListAdapter(Context context, JSONArray accommodations) { this.context = context; this.accommodations = accommodations; } @NonNull @Override public AccommodationViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view = inflater.inflate(R.layout.building_item,parent,false); return new AccommodationViewHolder(view); } @Override public void onBindViewHolder(@NonNull AccommodationViewHolder holder, int position) { try { JSONObject accommodation = (JSONObject) accommodations.get(position); holder.buildingNameTextView.setText(accommodation.getString("building_name")); holder.areaTextView.setText(accommodation.getString("area")); String gender_label = accommodation.getString("gender_label"); if(gender_label.equalsIgnoreCase("M")){ holder.genderLabelTextView.setText("Male"); holder.genderLabelImageView.setImageResource(R.drawable.male_icon); } else if (gender_label.equalsIgnoreCase("F")){ holder.genderLabelTextView.setText("Female"); holder.genderLabelImageView.setImageResource(R.drawable.female_icon); } else if(gender_label.equalsIgnoreCase("U")){ holder.genderLabelTextView.setText("Male/Female"); holder.genderLabelImageView.setImageResource(R.drawable.unisex_icon); } String starPerks = getStarPerks(accommodation.getJSONArray("perks")); holder.starPerksTextView.setText(starPerks); int startingRent = accommodation.getInt("starting_rent"); holder.rentTextView.setText("Starting @ ₹"+startingRent+"/mo"); Glide.with(holder.imageView.getContext()).load(Shared.ROOT_URL + accommodation.getString("display_pic")).into(holder.imageView); holder.itemView.setOnClickListener(v -> { try { String id = accommodation.getString("id"); Intent intent = new Intent(context,BuildingDetailActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("id",id); context.startActivity(intent); } catch (JSONException e){ } }); } catch (JSONException e){ } } @Override public int getItemCount() { return accommodations.length(); } public class AccommodationViewHolder extends RecyclerView.ViewHolder { ImageView imageView; ImageView genderLabelImageView; TextView buildingNameTextView; TextView areaTextView; TextView genderLabelTextView; TextView starPerksTextView; TextView rentTextView; public AccommodationViewHolder(@NonNull View itemView) { super(itemView); imageView = itemView.findViewById(R.id.buildingImageView); genderLabelImageView = itemView.findViewById(R.id.genderLabelImageView); buildingNameTextView = itemView.findViewById(R.id.bulidingNameTextView); areaTextView = itemView.findViewById(R.id.areaTextView); genderLabelTextView = itemView.findViewById(R.id.genderLabelTextView); starPerksTextView = itemView.findViewById(R.id.starPerksTextView); rentTextView = itemView.findViewById(R.id.rentTextView); } } private String getStarPerks(JSONArray perks) throws JSONException{ String all_perks = ""; for (int i=0; i<perks.length(); i++) all_perks += perks.getJSONObject(i).getString("description")+" "; List<String> list = new ArrayList<>(); if(all_perks.toLowerCase().contains("wifi")) list.add("WiFi"); if(all_perks.toLowerCase().contains("food")) list.add("Food"); if(all_perks.toLowerCase().contains("laundry")) list.add("Laundry"); int n = list.size(); if(n == 0) return "None"; String starPerks = ""; for(int i=0; i<n; i++){ if(i == n-1) starPerks += list.get(i); else starPerks += list.get(i) + ", "; } return starPerks; } }
true
db8e47f0f153ba2c64892ab159e03bc7ba309d60
Java
snowjak88/rays3d
/rays3d/core/src/main/java/org/rays3d/spectrum/RGB.java
UTF-8
6,565
2.734375
3
[ "MIT" ]
permissive
package org.rays3d.spectrum; import static org.apache.commons.math3.util.FastMath.abs; import static org.apache.commons.math3.util.FastMath.max; import static org.apache.commons.math3.util.FastMath.min; import java.io.Serializable; import java.util.Arrays; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** * Simple holder for a trio of RGB values. * <p> * <strong>Note</strong> that these components are not clamped in any way -- * they may take any value, positive or negative. * </p> * * @author snowjak88 */ @JsonIgnoreProperties(ignoreUnknown = true) public class RGB implements Serializable { @JsonIgnore private static final long serialVersionUID = 9081734196618975104L; /** * <code>RGB(0,0,0)</code> */ @JsonIgnore public static final RGB BLACK = new RGB(0d, 0d, 0d); /** * <code>RGB(1,0,0)</code> */ @JsonIgnore public static final RGB RED = new RGB(1d, 0d, 0d); /** * <code>RGB(0,1,0)</code> */ @JsonIgnore public static final RGB GREEN = new RGB(0d, 1d, 0d); /** * <code>RGB(0,0,1)</code> */ @JsonIgnore public static final RGB BLUE = new RGB(0d, 0d, 1d); /** * <code>RGB(1,1,1)</code> */ @JsonIgnore public static final RGB WHITE = new RGB(1d, 1d, 1d); @JsonIgnore private double[] rgb; /** * Construct a new RGB trio from an HSL trio. * * @param hue * hue-angle, given in <strong>degrees</strong> * @param saturation * saturation-value, given in <code>[0,1]</code> * @param lightness * lightness-value, given in <code>[0,1]</code> * @return */ public static RGB fromHSL(double hue, double saturation, double lightness) { final double chroma = ( 1d - abs(2d * lightness - 1) ) * saturation; final double h_prime = hue / 60d; final double x = chroma * ( 1d - abs(( h_prime % 2 ) - 1) ); final double r1, g1, b1; if (h_prime >= 0d && h_prime <= 1d) { r1 = chroma; g1 = x; b1 = 0d; } else if (h_prime >= 1d && h_prime <= 2d) { r1 = x; g1 = chroma; b1 = 0d; } else if (h_prime >= 2d && h_prime <= 3d) { r1 = 0d; g1 = chroma; b1 = x; } else if (h_prime >= 3d && h_prime <= 4d) { r1 = 0d; g1 = x; b1 = chroma; } else if (h_prime >= 4d && h_prime <= 5d) { r1 = x; g1 = 0d; b1 = chroma; } else if (h_prime >= 5d && h_prime <= 6d) { r1 = chroma; g1 = 0d; b1 = x; } else { r1 = 0d; g1 = 0d; b1 = 0d; } final double m = lightness - chroma / 2d; return new RGB(r1 + m, g1 + m, b1 + m); } /** * Given an integer containing a packed ARGB quadruple, unpack it into an * RGB instance. * * @param packedRGB * @return */ public static RGB fromPacked(int packedRGB) { final int b = packedRGB & 255; packedRGB = packedRGB >> 8; final int g = packedRGB & 255; packedRGB = packedRGB >> 8; final int r = packedRGB & 255; return new RGB((double) r / 256d, (double) g / 256d, (double) b / 256d); } /** * Given an RGB instance, transform it to a packed ARGB quadruple. * * @param rgb * @return * @see #toPacked() */ public static int toPacked(RGB rgb) { final double a = 1d; final double r = max(min(rgb.getRed(), 1d), 0d); final double g = max(min(rgb.getGreen(), 1d), 0d); final double b = max(min(rgb.getBlue(), 1d), 0d); return ( (int) ( a * 255d ) ) << 24 | ( (int) ( r * 255d ) ) << 16 | ( (int) ( g * 255d ) ) << 8 | ( (int) ( b * 255d ) ); } /** * Pack this RGB instance into an ARGB quadruple. * * @return * @see #toPacked(RGB) */ public int toPacked() { return RGB.toPacked(this); } public RGB() { this(0d, 0d, 0d); } public RGB(double red, double green, double blue) { this.rgb = new double[] { red, green, blue }; } public RGB add(RGB addend) { return new RGB(this.rgb[0] + addend.rgb[0], this.rgb[1] + addend.rgb[1], this.rgb[2] + addend.rgb[2]); } public RGB subtract(RGB subtrahend) { return new RGB(this.rgb[0] - subtrahend.rgb[0], this.rgb[1] - subtrahend.rgb[1], this.rgb[2] - subtrahend.rgb[2]); } public RGB multiply(double multiplicand) { return new RGB(this.rgb[0] * multiplicand, this.rgb[1] * multiplicand, this.rgb[2] * multiplicand); } public RGB multiply(RGB multiplicand) { return new RGB(this.rgb[0] * multiplicand.rgb[0], this.rgb[1] * multiplicand.rgb[1], this.rgb[2] * multiplicand.rgb[2]); } public RGB divide(double divisor) { return new RGB(this.rgb[0] / divisor, this.rgb[1] / divisor, this.rgb[2] / divisor); } public RGB divide(RGB divisor) { return new RGB(this.rgb[0] / divisor.rgb[0], this.rgb[1] / divisor.rgb[1], this.rgb[2] / divisor.rgb[2]); } /** * @return a new RGB trio with each component clamped to <code>[0,1]</code> */ public RGB clamp() { return new RGB(clampFraction(rgb[0]), clampFraction(rgb[1]), clampFraction(rgb[2])); } public double getRed() { return rgb[0]; } @JsonProperty protected void setRed(double red) { rgb[0] = red; } @JsonProperty public double getGreen() { return rgb[1]; } @JsonProperty protected void setGreen(double green) { rgb[1] = green; } @JsonProperty public double getBlue() { return rgb[2]; } @JsonProperty protected void setBlue(double blue) { rgb[2] = blue; } /** * <strong>Note</strong> that the <code>double</code> array returned here is * the backing array of this RGB object. Modifying this array directly is * considered to be unsafe, as it breaks the "value-object" paradigm. * * @return an array of 3 <code>double</code>s: * <code>{ red, green, blue }</code> */ @JsonIgnore public double[] getComponents() { return rgb; } private double clampFraction(double v) { return max(min(v, 1d), 0d); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(rgb); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RGB other = (RGB) obj; if (!Arrays.equals(rgb, other.rgb)) return false; return true; } }
true
a1d3f18be7b84b98417c2c1bfe5fcc0976b8af33
Java
CarlosBeltranP/CUMapp
/app/src/main/java/com/jcstudio/com/calculation/CumCalculator.java
UTF-8
1,292
2.734375
3
[]
no_license
package com.jcstudio.com.calculation; import com.jcstudio.com.model.Materia; import java.text.DecimalFormat; import java.util.List; import java.util.Vector; public class CumCalculator { private DecimalFormat precision = new DecimalFormat("0.00"); public String cumCalculado(List<Materia> courseList){ double sum = 0; double total_nota = 0; double cum_calculado; for(int i=0; i<courseList.size(); i++){ sum += courseList.get(i).getMateria_uv()*courseList.get(i).getNota_obtenida(); total_nota += courseList.get(i).getMateria_uv(); } cum_calculado = sum / total_nota; return courseList.isEmpty() ? "0.00000000":String.valueOf(precision.format(cum_calculado)); } public Vector<Double> calculation(List<Materia> courseList){ Vector<Double> ret = new Vector<>(); double sum = 0; double total_nota = 0; double cum_calculado; for(int i=0; i<courseList.size(); i++){ sum += courseList.get(i).getMateria_uv()*courseList.get(i).getNota_obtenida(); total_nota += courseList.get(i).getMateria_uv(); } cum_calculado = sum / total_nota; ret.add(cum_calculado); ret.add(total_nota); return ret; } }
true
23b52232877fa0f433874b314d30d1e8760fb808
Java
VasyaPogoriliy/XMLParser
/src/sample/GetXmlContent_SAX.java
UTF-8
4,944
2.828125
3
[]
no_license
package sample; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.util.ArrayList; public class GetXmlContent_SAX implements ParseXMLStrategy { @Override public ArrayList<Scientist> Search(Scientist parameters) { final String fileName = "src/sample/scientists.xml"; ArrayList<Scientist> scientistsInfo = new ArrayList<>(); try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); // Ініціалізуємо та розширюємо клас DefaultHandler DefaultHandler defaultHandler = new DefaultHandler() { // Якщо поле true, то тег почався boolean isName, isFaculty, isDepartment, isPosition, isSalary, isTimeInOffice = false; String name = ""; String faculty = ""; String department = ""; String position = ""; String salary = ""; String timeInOffice = ""; // Метод, що викликається, коли SAXParser доходить до початку тега @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { //thisElement = qName; if (qName.equalsIgnoreCase("NAME")) { isName = true; } else if (qName.equalsIgnoreCase("Faculty")) { isFaculty = true; } else if (qName.equalsIgnoreCase("Department")) { isDepartment = true; } else if (qName.equalsIgnoreCase("Position")) { isPosition = true; } else if (qName.equalsIgnoreCase("Salary")) { isSalary = true; } else if (qName.equalsIgnoreCase("TimeInOffice")) { isTimeInOffice = true; } } // Метод викликається коли SAXParser зчитує текст між тегами @Override public void characters(char[] ch, int start, int length) throws SAXException { String value = new String(ch, start, length); if (isName && (value.equals(parameters.getName()) || parameters.getName().equals("default"))) { cleanValues(); name = value; isName = false; } else if (isFaculty && (value.equals(parameters.getFaculty()) || parameters.getFaculty().equals("default"))) { faculty = value; isFaculty = false; } else if (isDepartment && (value.equals(parameters.getDepartment()) || parameters.getDepartment().equals("default"))) { department = value; isDepartment = false; } else if (isPosition && (value.equals(parameters.getPosition()) || parameters.getPosition().equals("default"))) { position = value; isPosition = false; } else if (isSalary && (Integer.parseInt(value) == parameters.getSalary() || parameters.getSalary() == 0)) { salary = value; isSalary = false; } else if (isTimeInOffice && (Integer.parseInt(value) == parameters.getTimeInOffice() || parameters.getTimeInOffice() == 0)) { timeInOffice = value; isTimeInOffice = false; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (!name.equals("") && !faculty.equals("") && !department.equals("") && !position.equals("") && !salary.equals("") && !timeInOffice.equals("")){ scientistsInfo.add(new Scientist(name, faculty, department, position, Integer.parseInt(salary), Integer.parseInt(timeInOffice))); cleanValues(); } } void cleanValues(){ name = ""; faculty = ""; department = ""; position = ""; salary = ""; timeInOffice = ""; } }; saxParser.parse(fileName, defaultHandler); } catch (Exception e) { e.printStackTrace(); } return scientistsInfo; } }
true
d806528c996822cc02e1f694649a52ecd7a36bd4
Java
szilex/Project_Java_Mentoring
/mentoring/src/main/java/com/euvic/mentoring/entity/MeetingDTO.java
UTF-8
2,658
2.65625
3
[]
no_license
package com.euvic.mentoring.entity; import java.time.LocalDate; import java.time.LocalTime; public class MeetingDTO { private static final long serialVersionUID = 1L; private int id; private LocalDate date; private LocalTime startTime; private LocalTime endTime; private int mentorId; private int studentId; public MeetingDTO() { } public MeetingDTO(LocalDate date, LocalTime startTime, LocalTime endTime, Integer mentorId) { this.date = date; this.startTime = startTime; this.endTime = endTime; this.mentorId = (mentorId == null) ? 0 : mentorId; } public MeetingDTO(LocalDate date, LocalTime startTime, LocalTime endTime, Integer mentorId, Integer studentId) { this.date = date; this.startTime = startTime; this.endTime = endTime; this.mentorId = (mentorId == null) ? 0 : mentorId; this.studentId = (studentId == null) ? 0 : studentId; } public MeetingDTO(Meeting meeting) { this(meeting.getDate(), meeting.getStartTime(), meeting.getEndTime(), meeting.getMentor().getId()); this.id = meeting.getId(); if (meeting.getStudent() != null) { studentId = meeting.getStudent().getId(); } } public Integer getId() { return (id == 0) ? null : id; } public void setId(Integer id) { this.id = (id == null) ? 0 : id; } public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } public LocalTime getStartTime() { return startTime; } public void setStartTime(LocalTime startTime) { this.startTime = startTime; } public LocalTime getEndTime() { return endTime; } public void setEndTime(LocalTime endTime) { this.endTime = endTime; } public Integer getMentorId() { return (mentorId == 0) ? null : mentorId; } public void setMentorId(Integer mentorId) { this.mentorId = (mentorId == null) ? 0 : mentorId; } public Integer getStudentId() { return (studentId == 0) ? null : studentId; } public void setStudentId(Integer studentId) { this.studentId = (studentId == null) ? 0 : studentId; } @Override public String toString() { return "SimpleMeeting{" + "id=" + id + ", date=" + date + ", startTime=" + startTime + ", endTime=" + endTime + ", mentorId=" + mentorId + ", studentId=" + studentId + '}'; } }
true
c84ec26c9c3a9d240559bd4917cd20d3ba239efe
Java
fmutlu68/NewsApi
/src/main/java/com/fm/newsProject/core/repository/GenericRepository.java
UTF-8
327
2.21875
2
[]
no_license
package com.fm.newsProject.core.repository; import java.util.List; import java.util.function.Predicate; public interface GenericRepository<T> { T add(T entity); T update(T entity); void delete(T entity); List<T> getAll(); List<T> getAll(Predicate<? super T> filter); T get(Predicate<? super T> filter, String model); }
true