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 |
---|---|---|---|---|---|---|---|---|---|---|---|
b45e0b5f485b8e7cf1cb0226ceed506d149e724e
|
Java
|
agermenos/skillmatch
|
/src/main/java/com/skillmatch/daos/SkillDao.java
|
UTF-8
| 235 | 1.515625 | 2 |
[] |
no_license
|
package com.skillmatch.daos;
import com.skillmatch.pojos.Skill;
import org.springframework.stereotype.Repository;
/**
* Created by agermenos on 5/30/16.
*/
@Repository("skillDao")
public class SkillDao extends GeneralDao<Skill>{
}
| true |
7bf9e4ba8b3621bf1871738e03ab1a3e9aa62b1e
|
Java
|
MarcusViniciusCavalcanti/teste-ilias
|
/atm/src/main/java/com/zonework/atm/domain/transactional/service/ExecutorUpdateRetirementBalance.java
|
UTF-8
| 2,714 | 2.171875 | 2 |
[] |
no_license
|
package com.zonework.atm.domain.transactional.service;
import com.zonework.atm.domain.adapter.send.AsynchronousProcessingWithTopicForSendingMessage;
import com.zonework.atm.domain.transactional.entity.StatusTransactionalEnum;
import com.zonework.atm.domain.transactional.entity.TransactionalBalance;
import com.zonework.atm.domain.transactional.repository.TransactionalRepository;
import com.zonework.atm.struture.dto.TransactionalDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ExecutorUpdateRetirementBalance {
private final TransactionalRepository transactionalRepository;
private final BeanFactory beanFactory;
private final AsynchronousProcessingWithTopicForSendingMessage sendingMessage;
@Transactional(propagation = Propagation.MANDATORY)
public void execute(Integer id) {
log.info("Running update retirement");
log.debug("By id {}", id);
transactionalRepository.findById(id)
.ifPresentOrElse(
transactionalBalance -> {
calculateNewPalance(transactionalBalance);
updateTransactionStatusAwattingResponse(transactionalBalance);
},
() -> log.warn("Transactional not found by id {}", id)
);
}
private void updateTransactionStatusAwattingResponse(TransactionalBalance transactionalBalance) {
log.debug("Running Update status transaction to AWATTING");
transactionalBalance.setStatus(StatusTransactionalEnum.AWATTING);
sendingMessage.scheduleAsynchronousProcessing(transactionalBalance);
transactionalRepository.saveAndFlush(transactionalBalance);
}
private void calculateNewPalance(TransactionalBalance transactionalBalance) {
try {
log.debug("Running calculate new retirement balance");
var operator = beanFactory.getBean(transactionalBalance.getType().name(), OperationTransactionl.class);
operator.calculate(transactionalBalance, transactionalBalance.getValue());
} catch (BeansException exception) {
log.error("Operation invalid {}", transactionalBalance.getType());
throw new RuntimeException("Operation ilegal");
}
}
}
| true |
e741badd3f6509ace3ab5c9f6311cefd58dcf325
|
Java
|
JCFlores93/AndroidAvanzado
|
/DesarrolloApurata/apurata_android/app/src/main/java/com/apurata/prestamos/creditos/RequestModels/Coord.java
|
UTF-8
| 3,275 | 2.578125 | 3 |
[] |
no_license
|
package com.apurata.prestamos.creditos.RequestModels;
import android.location.Location;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
/**
* Created by USUARIO on 5/06/2017.
*/
public class Coord implements Parcelable {
public Coord() {
}
@SerializedName("speed")
private float speed;
@SerializedName("heading")
private String heading;
@SerializedName("altitudeAccuracy")
private float altitudeAccuracy;
@SerializedName("accuracy")
private float accuracy;
@SerializedName("altitude")
private float altitude;
@SerializedName("longitude")
private float longitude;
@SerializedName("latitude")
private float latitude;
protected Coord(Parcel in) {
speed = in.readFloat();
heading = in.readString();
altitudeAccuracy = in.readFloat();
accuracy = in.readFloat();
altitude = in.readFloat();
longitude = in.readFloat();
latitude = in.readFloat();
}
public static final Creator<Coord> CREATOR = new Creator<Coord>() {
@Override
public Coord createFromParcel(Parcel in) {
return new Coord(in);
}
@Override
public Coord[] newArray(int size) {
return new Coord[size];
}
};
public float getSpeed() {
return speed;
}
public void setSpeed(float speed) {
this.speed = speed;
}
public String getHeading() {
return heading;
}
public void setHeading(String heading) {
this.heading = heading;
}
public float getAltitudeAccuracy() {
return altitudeAccuracy;
}
public void setAltitudeAccuracy(float altitudeAccuracy) {
this.altitudeAccuracy = altitudeAccuracy;
}
public float getAccuracy() {
return accuracy;
}
public void setAccuracy(float accuracy) {
this.accuracy = accuracy;
}
public float getAltitude() {
return altitude;
}
public void setAltitude(float altitude) {
this.altitude = altitude;
}
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
public float getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public String getStringPosition() {
return String.valueOf(this.longitude) + " " + this.latitude;
}
public Coord(Location location){
this.setSpeed(location.getSpeed());
this.setAccuracy(location.getAccuracy());
this.setAltitude((float) location.getAltitude());
this.setLongitude((float) location.getLongitude());
this.setLatitude((float) location.getLatitude());
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeFloat(speed);
dest.writeString(heading);
dest.writeFloat(altitudeAccuracy);
dest.writeFloat(accuracy);
dest.writeFloat(altitude);
dest.writeFloat(longitude);
dest.writeFloat(latitude);
}
}
| true |
3dc787c18f22f9e1cf07cda7694c188050fa7992
|
Java
|
LiteracyBridge/acm
|
/acm/src/main/java/org/literacybridge/acm/gui/messages/AudioItemTableSortOrderMessage.java
|
UTF-8
| 497 | 2.21875 | 2 |
[] |
no_license
|
package org.literacybridge.acm.gui.messages;
import javax.swing.SortOrder;
public class AudioItemTableSortOrderMessage extends Message {
private final Object identifier;
private final SortOrder sortOrder;
public AudioItemTableSortOrderMessage(Object identifier,
SortOrder sortOrder) {
this.identifier = identifier;
this.sortOrder = sortOrder;
}
public Object getIdentifier() {
return identifier;
}
public SortOrder getSortOrder() {
return sortOrder;
}
}
| true |
2c10639b5f8a1c199ff61883eaab165f0e266515
|
Java
|
prabhuSub/Java-Assignments
|
/Assignment_3/src/UserInterface/TravelAgency/UserDirectoryJPanel.java
|
UTF-8
| 6,452 | 2.40625 | 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 UserInterface.TravelAgency;
import Business.Customer.Customer;
import Business.TravelAgency.Airline;
import Business.TravelAgency.AirlineDirectory;
import Business.TravelAgency.Flight;
import javax.swing.JPanel;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
/**
*
* @author Prabhu Surbamanian
*/
public class UserDirectoryJPanel extends javax.swing.JPanel {
/**
* Creates new form UserDirectory
*/
private DefaultTableModel dtm;
private AirlineDirectory airlineDirectory;
UserDirectoryJPanel(JPanel rightJPanel, AirlineDirectory airlineDirectory) {
initComponents();
this.airlineDirectory=airlineDirectory;
populate();
}
public void populate(){
dtm = (DefaultTableModel)userDirectory.getModel();
dtm.setRowCount(0);
for(Airline airline : airlineDirectory.getAirlinerDiroctory()){
for(Flight flight : airline.getFlightDirectory()){
for(Customer customer : flight.getCustomerDirectory()){
Object[] row = new Object[dtm.getColumnCount()];
row[0]=customer;
row[1]=customer.getCustomerLastName();
row[2]=customer.getSeat();
row[3]=customer.getFlightCode();
row[4]=customer.getAirline();
dtm.addRow(row);
}
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
userDirectory = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
lblSearchAccNo = new javax.swing.JLabel();
txtSearch = new javax.swing.JTextField();
setBackground(new java.awt.Color(255, 255, 255));
userDirectory.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
userDirectory.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"First Name", "Last Name", "Seat No.", "Flight Code", "Airline"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(userDirectory);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel1.setText("User Directory");
lblSearchAccNo.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblSearchAccNo.setText("Search Customer:");
txtSearch.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
txtSearch.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
txtSearchKeyReleased(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(391, 391, 391)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(192, 192, 192)
.addComponent(lblSearchAccNo)
.addGap(18, 18, 18)
.addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(190, 190, 190)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 642, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(110, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(106, 106, 106)
.addComponent(jLabel1)
.addGap(47, 47, 47)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblSearchAccNo)
.addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(123, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void txtSearchKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSearchKeyReleased
// TODO add your handling code here:
String query = txtSearch.getText();
filter(query);
}//GEN-LAST:event_txtSearchKeyReleased
private void filter(String query){
TableRowSorter<DefaultTableModel> tr = new TableRowSorter<DefaultTableModel>(dtm);
userDirectory.setRowSorter(tr);
tr.setRowFilter(RowFilter.regexFilter(query));
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lblSearchAccNo;
private javax.swing.JTextField txtSearch;
private javax.swing.JTable userDirectory;
// End of variables declaration//GEN-END:variables
}
| true |
1d8af354c0a125fdc27295872d03af88d7db729a
|
Java
|
moutainhigh/foss
|
/tfr/tfr-partialline/src/main/java/com/deppon/foss/module/transfer/partialline/server/interceptor/AllHandlerInterceptor.java
|
UTF-8
| 885 | 1.789063 | 2 |
[] |
no_license
|
package com.deppon.foss.module.transfer.partialline.server.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class AllHandlerInterceptor implements HandlerInterceptor {
private static final String ESB_RESULT_CODE = "ESB-ResultCode";
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setHeader(ESB_RESULT_CODE, "1");
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
| true |
c500b44923f532bbfaa1e226a5af64a794292762
|
Java
|
NeilDuToit92/satisfactory-calculator-java
|
/src/main/java/item/basic/SteelBeam.java
|
UTF-8
| 804 | 2.734375 | 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 item.basic;
import item.Item;
import item.ItemBase;
import javax.swing.*;
import java.util.Map;
public class SteelBeam extends ItemBase {
public SteelBeam(double num, Map<Item, JComboBox<String>> alternateRecipes, JTextArea output) {
super(num, alternateRecipes, output);
defaultSteelBeam();
}
public void defaultSteelBeam() {
double SteelIngots = num * 4;
append(ds.format(num) + " Steel Beams / Minute: " + ds.format(SteelIngots) + " Steel Ingots / minute. Requires " + ds.format(num / 15) + " Constructors\n\n");
new SteelIngot(SteelIngots, alternateRecipes, output);
}
}
| true |
ddfce2e0f8b33edbc183e6b3d1cf7e00ef0204fe
|
Java
|
haoxizhong/Android
|
/app/src/main/java/com/ihandy/a2014011384/Main2Activity.java
|
UTF-8
| 5,548 | 1.84375 | 2 |
[] |
no_license
|
package com.ihandy.a2014011384;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXTextObject;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import okhttp3.internal.Util;
/**
* The second activity
*/
public class Main2Activity extends AppCompatActivity{
static News news = null;
private static final String appid = "wx01cee72f6183d77d";
private static IWXAPI api = null;
MenuItem love;
/**
* Change the status of icon
* @param prefer whther to like
*/
void updateStatus(int prefer)
{
if (prefer == 0) love.setIcon(R.drawable.love_false);
else love.setIcon(R.drawable.love_true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar, menu);
love = menu.findItem(R.id.action_love);
updateStatus(news.prefer);
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//getActionBar().setTitle("");
api = WXAPIFactory.createWXAPI(this,appid,true);
api.registerApp(appid);
Log.d("URL",news.source);
WebView web = (WebView) findViewById(R.id.webpage);
WebSettings settings = web.getSettings();
//settings.setJavaScriptEnabled(true);
settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
if (Build.VERSION.SDK_INT >= 19) {
// chromium, enable hardware acceleration
web.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
// older android version, disable hardware acceleration
web.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
/*final Activity activity = this;
web.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
activity.setProgress(progress * 1000);
}
});*/
web.loadUrl(news.source);
//web.loadData();
}
/**
* Share to WX
* @param flag Share to where
*/
void Share(int flag)
{
if (api.isWXAppInstalled() == false)
{
Toast.makeText(this, "您还未安装微信客户端",Toast.LENGTH_SHORT).show();
return;
}
WXWebpageObject webpage = new WXWebpageObject();
webpage.webpageUrl = news.source;
WXMediaMessage msg = new WXMediaMessage(webpage);
msg.title = news.title;
msg.description = news.title;
Bitmap thumb = BitmapFactory.decodeResource(getResources(),R.drawable.zhinai);
msg.setThumbImage(thumb);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = String.valueOf(System.currentTimeMillis());
req.message = msg;
if (flag == 0) req.scene = SendMessageToWX.Req.WXSceneSession;
else req.scene = SendMessageToWX.Req.WXSceneTimeline;
System.out.println(req);
System.out.println(api);
if (api.sendReq(req)) Toast.makeText(this, "分享成功",Toast.LENGTH_SHORT).show();
else Toast.makeText(this, "分享失败",Toast.LENGTH_SHORT).show();
}
void change_love()
{
news.prefer = 1 - news.prefer;
updateStatus(news.prefer);
SQLHelper.saveNews(news);
}
@Override
public void onBackPressed()
{
if (Main3Activity.on3)
{
Intent intent = new Intent(getBaseContext(),Main3Activity.class);
startActivity(intent);
finish();
}
else super.onBackPressed();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_love:
change_love();
return true;
case R.id.action_haoyou:
Share(0);
return true;
//case R.id.action_pengyouquan:
// User chose the "Favorite" action, mark the current item
// as a favorite...
// Share(1);
// return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
}
| true |
3a92c26ca988c285c997ff0ab9e5d4d1e65902b9
|
Java
|
daeunchung/Java
|
/hijava/hijava/Exam31_2.java
|
UHC
| 570 | 3.296875 | 3 |
[] |
no_license
|
package hijava;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Exam31_2 extends Applet{
int x,y;
public void init() {
this.setBackground(Color.green);
this.setSize(300, 200);
this.addMouseListener(new MouseHandler());
}
public void paint(Graphics g) {
g.fillOval(x, y, 20, 20);
}
class MouseHandler extends MouseAdapter{
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
//repaint()ȣ update()ȣ
//update()̵X -> ڵ ο paint()ȣ
}
}
}
| true |
4fae884d2ae8d77ed0b3e16f0132dc7ef4256e38
|
Java
|
ITneko/Java
|
/JSL/Day_1015/src/Exam_01.java
|
UTF-8
| 408 | 3.46875 | 3 |
[] |
no_license
|
import java.util.Vector;
// List -> ArrayList, Vector, LinkedList
public class Exam_01 {
public static void main(String[] args) {
Vector vc = new Vector();
Vector vc2 = new Vector(10);
System.out.println("기본크기 :" + vc.capacity());
System.out.println("기본크기 :" + vc2.capacity()); //물리적인 공간
vc.add("aaa");
vc.add("bbb");
System.out.println(vc.firstElement());
}
}
| true |
837991714106a93fa507b9e5f822361e62309704
|
Java
|
AnderJoeSun/JavaSE-Demos
|
/base/Cla.java
|
UTF-8
| 961 | 2.859375 | 3 |
[] |
no_license
|
class Cla{
public static void main(String agr[]){
/*Point p=new Point();
Class c1=p.getClass();
System.out.println(c1.getName());
try{
Class c2=Class.forName("Point");
System.out.println(c2.getName());
}catch(Exception e){
System.out.println(e);
}
Class c3=Point.class;
System.out.println(c3.getName());
Class c4=int.class;
System.out.println(c4.getName());
Class c5=Integer.class;
System.out.println(c5.getName());
Class c6=Integer.TYPE;
System.out.println(c6.getName());*/
System.out.println("before new Line()");
new Line();
System.out.println("after new Line() and before Class Line");
Class c=Line.class;
System.out.println(c.getName());
System.out.println("after Class Line");
}
}
class Point{
int a;int b;
static {
System.out.println("loading Point");
}
}
class Line{
static {
System.out.println("Loading Line");
}
}
| true |
1f1337d63d3423476ebffb8dc56fde3da74ecc54
|
Java
|
ComputationalReflection/weaveJ
|
/example/src/example/aspect/ProfilerAspect.java
|
UTF-8
| 961 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
package example.aspect;
import java.lang.invoke.MethodHandle;
import example.component.CreditCard;
public class ProfilerAspect {
/*
private long timeBefore;
public void checkTimeBefore(CreditCard card, double amount) {
timeBefore = System.nanoTime();
}
public void profileAfter(String methodName, CreditCard card, double amount) {
long after = System.nanoTime();
System.out.printf("> Elapsed time in a " + methodName
+ "operation on the " + card.toString()
+ " credit card: %d nanos.\n", after - timeBefore);
}
*/
public static double profileOperation(String methodName, MethodHandle mh,
CreditCard card, double amount) throws Throwable {
long timeBefore = System.nanoTime();
double res=(double) mh.invokeWithArguments(card, amount);
System.out.printf("> Elapsed time in a " + methodName
+ " operation on the " + card.toString()
+ " credit card: %d nanos.\n", System.nanoTime() - timeBefore);
return res;
}
}
| true |
95700b246c60a82216cb9ec63e4b03ac1e427e47
|
Java
|
marianogili/TraceabilityEditor
|
/TraceEditor/src/com/marianogili/traceeditor/TraceLink.java
|
UTF-8
| 3,956 | 2 | 2 |
[] |
no_license
|
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package com.marianogili.traceeditor;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Trace Link</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link com.marianogili.traceeditor.TraceLink#getSources <em>Sources</em>}</li>
* <li>{@link com.marianogili.traceeditor.TraceLink#getTargets <em>Targets</em>}</li>
* <li>{@link com.marianogili.traceeditor.TraceLink#getType <em>Type</em>}</li>
* <li>{@link com.marianogili.traceeditor.TraceLink#getTransformation <em>Transformation</em>}</li>
* </ul>
* </p>
*
* @see com.marianogili.traceeditor.TraceeditorPackage#getTraceLink()
* @model
* @generated
*/
public interface TraceLink extends NamedElement {
/**
* Returns the value of the '<em><b>Sources</b></em>' reference list.
* The list contents are of type {@link com.marianogili.traceeditor.Artefact}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Sources</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Sources</em>' reference list.
* @see com.marianogili.traceeditor.TraceeditorPackage#getTraceLink_Sources()
* @model
* @generated
*/
EList<Artefact> getSources();
/**
* Returns the value of the '<em><b>Targets</b></em>' reference list.
* The list contents are of type {@link com.marianogili.traceeditor.Artefact}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Targets</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Targets</em>' reference list.
* @see com.marianogili.traceeditor.TraceeditorPackage#getTraceLink_Targets()
* @model
* @generated
*/
EList<Artefact> getTargets();
/**
* Returns the value of the '<em><b>Type</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Type</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Type</em>' reference.
* @see #setType(LinkType)
* @see com.marianogili.traceeditor.TraceeditorPackage#getTraceLink_Type()
* @model
* @generated
*/
LinkType getType();
/**
* Sets the value of the '{@link com.marianogili.traceeditor.TraceLink#getType <em>Type</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Type</em>' reference.
* @see #getType()
* @generated
*/
void setType(LinkType value);
/**
* Returns the value of the '<em><b>Transformation</b></em>' container reference.
* It is bidirectional and its opposite is '{@link com.marianogili.traceeditor.Transformation#getTraceLinks <em>Trace Links</em>}'.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Transformation</em>' container reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Transformation</em>' container reference.
* @see #setTransformation(Transformation)
* @see com.marianogili.traceeditor.TraceeditorPackage#getTraceLink_Transformation()
* @see com.marianogili.traceeditor.Transformation#getTraceLinks
* @model opposite="traceLinks" transient="false"
* @generated
*/
Transformation getTransformation();
/**
* Sets the value of the '{@link com.marianogili.traceeditor.TraceLink#getTransformation <em>Transformation</em>}' container reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Transformation</em>' container reference.
* @see #getTransformation()
* @generated
*/
void setTransformation(Transformation value);
} // TraceLink
| true |
e5b7f899804cf629fea4d128fe1af4a756f87f08
|
Java
|
timboudreau/netbeans-contrib
|
/cnd.fortran/fortran_highlighting/src/main/java/org/netbeans/modules/fort/model/util/IntervalSet.java
|
UTF-8
| 4,015 | 2.765625 | 3 |
[
"Apache-2.0"
] |
permissive
|
package org.netbeans.modules.fort.model.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.netbeans.modules.fort.model.lang.FOffsetable;
import org.netbeans.modules.fort.model.lang.impl.SimpleOffsetable;
/**
* utility class for set of intervals
* @author Andrey Gubichev
*/
public class IntervalSet<E extends FOffsetable> implements Iterable<E> {
private List<E> intervals;
/**
* create a new instance of IntervalSet
*/
public IntervalSet() {
intervals = new ArrayList<E>();
}
/**
* create a new instance of IntervalSet
*/
public IntervalSet(int cap) {
intervals = new ArrayList<E>(cap);
}
/**
* @return true if set is empty
*/
public boolean isEmpty() {
return intervals.isEmpty();
}
/**
* @return lower bound of intervals
*/
public int getLowerBound() {
if (isEmpty())
throw new IndexOutOfBoundsException("Empty"); // NOI18N
return intervals.get(0).getStartOffset();
}
/**
* @return upper bound of intervals
*/
public int getUpperBound() {
if (isEmpty())
throw new IndexOutOfBoundsException("Empty"); // NOI18N
return intervals.get(intervals.size() - 1).getEndOffset();
}
/**
* @return "from" bounds of intervals
*/
public IntervalSet<E> getFromBounds(int start, int end) {
IntervalSet<E> result = new IntervalSet<E>();
FOffsetable off = new SimpleOffsetable(start, end);
for (E cur : this) {
int res =
IntersectionComparator.getInstance().compare(off, cur);
if (res == 0) {
result.add(cur);
} else if (res < 0 ) {
break;
}
}
return result;
}
/**
* add to set
*/
public void add(E interval) {
int res = Collections.binarySearch(intervals, interval,
IntersectionComparator.getInstance());
if (res >= 0)
throw new IllegalArgumentException("Intersection"); // NOI18N
intervals.add(-res - 1, interval);
}
/**
* @return element at pos
*/
public E getElementAtPosition(int pos) {
int res = Collections.binarySearch(intervals, new DummyOffsetable(pos),
IntersectionComparator.getInstance());
return (res < 0) ? null : intervals.get(res);
}
/**
* @return set-to-list
*/
public List<E> getList() {
return Collections.<E>unmodifiableList(intervals);
}
/**
* @return list iterator
*/
public Iterator<E> iterator() {
return getList().iterator();
}
private static class IntersectionComparator implements Comparator<FOffsetable> {
private final static Comparator<FOffsetable> instance = new IntersectionComparator();
public static Comparator<FOffsetable> getInstance() {
return instance;
}
public int compare(FOffsetable o1, FOffsetable o2) {
if (o1.getEndOffset() < o2.getStartOffset())
return -1;
if (o2.getEndOffset() < o1.getStartOffset()) {
return 1;
}
return 0;
}
private IntersectionComparator() { }
}
private static class DummyOffsetable implements FOffsetable {
private int pos;
public DummyOffsetable(int pos) {
this.pos = pos;
}
public int getStartOffset() {
return pos;
}
public int getEndOffset() {
return pos;
}
}
}
| true |
fbc9b34da0b56cdf30ce4a48236268591a954cfd
|
Java
|
PrachiBora/ComputerArchitecture
|
/src/Global.java
|
UTF-8
| 899 | 2.0625 | 2 |
[] |
no_license
|
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Queue;
public class Global
{
static HashMap<String,Integer> RegisterValuePair = new HashMap<String,Integer>();
static HashMap<String,String> opcodeFunctionalUnit = new HashMap<String,String>();
static HashMap<String,Boolean> functionalUnitStatus = new HashMap<String,Boolean>();
static ArrayList<Instruction> instruction = new ArrayList<Instruction>();
static ArrayList<Register> register = new ArrayList<Register>();
static Queue<Instruction> queue = new ArrayDeque<Instruction>();
static int clockCycle = 1;
static HashMap<String,Integer> stateCycle = new HashMap<String,Integer>();
static int PC;
static boolean flag = true;
static ArrayList<Instruction> result = new ArrayList<Instruction>();
static HashMap<String,Integer> functionalUnitCycle = new HashMap<String,Integer>();
}
| true |
905a032f669cb6e45c19f4857093779f3f82e53d
|
Java
|
Ashish-Goyal1234/Javaprogrammes
|
/ExceptionHandling/ExceptionHandling/Case14_PrintingExceptionMessage.java
|
UTF-8
| 762 | 3.5625 | 4 |
[] |
no_license
|
package ExceptionHandling;
public class Case14_PrintingExceptionMessage {
void m3(){
try{
System.out.println(10/0);
}catch(ArithmeticException ae){
System.out.println(ae); //print exception and message
System.out.println(ae.toString()); // this is same as ae. print exception and message
System.out.println(ae.getMessage()); // only print message / by zero
ae.printStackTrace(); // shows complete stack tree (we use in our projects realtime)
}
}
void m2() {
m3();
}
void m1 (){
m2();
}
public static void main(String[] args) {
Case14_PrintingExceptionMessage t = new Case14_PrintingExceptionMessage();
t.m1();
}
}
| true |
69d1ebcaed0980888fdb3180bbb960db3233b4ce
|
Java
|
soarchen2k/MOOC
|
/Part2/src/ca/monor/week08/W8_13_RichFirstPoorLast/cours_Generics/Slot.java
|
UTF-8
| 304 | 2.65625 | 3 |
[] |
no_license
|
package ca.monor.week08.W8_13_RichFirstPoorLast.cours_Generics;
public class Slot<T> {
private T key;
public T getValue() {
return key;
}
public void setValue(T key) {
this.key = key;
}
@Override
public String toString() {
return "" + key;
}
}
| true |
c3ab5037aa3b2570454a3e44275a75cfc459409e
|
Java
|
gspandy/hermes-1
|
/hermes-portal/src/main/java/com/ctrip/hermes/portal/console/application/JspFile.java
|
UTF-8
| 440 | 2.109375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.ctrip.hermes.portal.console.application;
public enum JspFile {
VIEW("/jsp/console/application/application.jsp"),
TOPIC("/jsp/console/application/application-topic.jsp"),
CONSUMER("/jsp/console/application/application-consumer.jsp"),
REVIEW("/jsp/console/application/application-review.jsp"),
;
private String m_path;
private JspFile(String path) {
m_path = path;
}
public String getPath() {
return m_path;
}
}
| true |
49966539db1de3bc83e2a4f29ae8256e26d3cd75
|
Java
|
yeahyung/board
|
/src/main/java/com/example/board/controller/AutoController.java
|
UTF-8
| 23,358 | 1.789063 | 2 |
[] |
no_license
|
package com.example.board.controller;
import com.example.board.service.AutoService;
import com.example.board.vo.request.ImgAugRequestVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.util.Iterator;
@Controller
@AllArgsConstructor
public class AutoController {
private AutoService autoService;
@RequestMapping("/script")
public String getScript(){
return "#!/bin/bash\n" +
"#ARG=($@)\n" +
"\n" +
"WORK_HOME=\"/home1/irteam\"\n" +
"APP_HOME=\"${WORK_HOME}/apps\"\n" +
"DIRS=\"apps deploy logs logs/apache logs/tomcat scripts\"\n" +
"TIMEIDX=$(date +%y%m%d%H%M%S)\n" +
"REPO_ADDR=\"repo.nhnsystem.com\";\n" +
"\n" +
"\n" +
"#Print message & Exit\n" +
"msgexit() {\n" +
" echo $1\n" +
" exit 1\n" +
"}\n" +
"\n" +
"\n" +
"help() {\n" +
" echo \"Usage: $0 [OPTIONS]\"\n" +
" echo \"Options:\"\n" +
" echo \" -h, --help print this messages\"\n" +
" echo \" -v, --version print available version\"\n" +
" echo \" -a {version}, --apache {version} set apache version\"\n" +
" echo \" -t {version}, --tomcat {version} set tomcat version\"\n" +
" echo \" -j {version}, --jdk {version} set jdk version\"\n" +
" echo \" -m {naver|nbp}, --module {naver|nbp} install auth module\"\n" +
" exit 1\n" +
"}\n" +
"\n" +
"\n" +
"version() {\n" +
" curl -s http://$REPO_ADDR/webapps/VERSIONS.TXT\n" +
"}\n" +
"\n" +
"\n" +
"# Check Version\n" +
"check_version() {\n" +
"\n" +
" VER_TXT=$(curl -s http://$REPO_ADDR/webapps/VERSION.TXT|sed 's/\\s//g;/^$/d')\n" +
"\n" +
" cd $WORK_HOME\n" +
" wget -q http://$REPO_ADDR/webapps/README.WEBAPPS -O README.WEBAPPS\n" +
"\n" +
" for i in $VER_TXT\n" +
" do\n" +
" temp=${i/=*/}\n" +
" if [ -z ${!temp} ];then\n" +
" # Assignment BUILD,SCRIPT,APACHE,TOMCAT,JDK\n" +
" eval $i\n" +
" fi\n" +
" done\n" +
"\n" +
" JDK_VER_MAJOR=`echo $JDK | cut -d'.' -f1`\n" +
" catalina_opt='#CATALINA_OPTS=\"-server -Xms1024m -Xmx1024m -XX:MaxPermSize=128m -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -Xloggc:/home1/irteam/logs/gc.log -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=2M -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/home1/irteam/logs/heap-was1.log\"'\n" +
"\n" +
" ## Àӽà Tomcat6 / jdk6 ¼³Ä¡ Áö¿ø ¸ñÀû\n" +
" if [[ ${JDK} =~ ^1\\.8 ]];then\n" +
" catalina_opt='#CATALINA_OPTS=\"-server -Xms1024m -Xmx1024m -XX:+UseG1GC -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -Xloggc:/home1/irteam/logs/gc.log -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=2M -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/home1/irteam/logs/heap-was1.hprof\"'\n" +
" elif [ $JDK_VER_MAJOR -ge 10 ];then\n" +
" catalina_opt='#CATALINA_OPTS=\"-server -Xms1024m -Xmx1024m -XX:+UseG1GC -verbose:gc -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/home1/irteam/logs/heap-was1.hprof\"'\n" +
" fi\n" +
" TOMCAT_TAR=\"tomcat-${TOMCAT}.tar.gz\"\n" +
"\n" +
" D_APACHE=\"apache-${APACHE}\"\n" +
" D_TOMCAT=\"apache-tomcat-${TOMCAT}\"\n" +
"\n" +
" [ $JDK_VER_MAJOR -lt 10 ] && D_JDK=\"jdk${JDK}\" || D_JDK=\"jdk-${JDK}\"\n" +
"\n" +
" echo \"--------------------\"\n" +
" echo \"1. Build Information\"\n" +
" echo \" - Build: $BUILD\"\n" +
" echo \" - Apache: $D_APACHE\"\n" +
" echo \" - Tomcat: $D_TOMCAT\"\n" +
" echo \" - JDK: $D_JDK\"\n" +
" echo \"--------------------\"\n" +
"}\n" +
"\n" +
"# Check existence\n" +
"check_pre() {\n" +
" if [ -d $APP_HOME ];then\n" +
" cd $APP_HOME\n" +
"\n" +
" for i in $D_TOMCAT tomcat\n" +
" do\n" +
" if [ -d \"$i\" -o -h \"$i\" ];then\n" +
" msgexit \"$APP_HOME/$i is already exist\"\n" +
" fi\n" +
" done\n" +
" fi\n" +
" echo \"--------------------\"\n" +
" echo \"2. Installtaion\"\n" +
"}\n" +
"\n" +
"# OS version check\n" +
"check_os() {\n" +
" OS_VERSION=$(sed -r 's/.*release ([0-9]).*/\\1/' /etc/redhat-release)\n" +
" OS_ARCH=$(uname -i)\n" +
"}\n" +
"\n" +
"# User check\n" +
"check_user() {\n" +
" #UID=$(id -u)\n" +
"\n" +
" if [ \"$UID\" != \"0\" ];then\n" +
" echo \"UID:$UID => This has to be ran by root(or sudo)\"\n" +
" exit 1\n" +
" fi\n" +
"}\n" +
"\n" +
"# Setting directory\n" +
"set_dir() {\n" +
" cd $WORK_HOME\n" +
"\n" +
" for i in $DIRS\n" +
" do\n" +
" if [ ! -d $i ];then\n" +
" mkdir -p $i\n" +
" chown -R irteam.irteam $i\n" +
" fi\n" +
" done\n" +
"}\n" +
"\n" +
"# User bash enviornment\n" +
"\n" +
"set_bashenv(){\n" +
"\n" +
" BASH_ENV='\\t### WEBAPPS ENV ###\n" +
" export APP_HOME=/home1/irteam\n" +
" export JAVA_HOME=${APP_HOME}/apps/jdk\n" +
" export APACHE_HTTP_HOME=${APP_HOME}/apps/apache\n" +
" export TOMCAT_HOME=${APP_HOME}/apps/tomcat\n" +
" export PATH=${JAVA_HOME}/bin:$PATH\n" +
" export PATH=${APACHE_HTTP_HOME}/bin:$PATH'\n" +
"\n" +
" JHOME=$(su -s /bin/bash - irteam -c 'echo $JAVA_HOME')\n" +
" if [ \"$?\" -eq 0 ] && [ \"${JHOME}\" == \"\" ]; then\n" +
" echo -e \"$BASH_ENV\" >> ${WORK_HOME}/.bashrc\n" +
" else\n" +
" echo -e \"\\n### Set Shell Environment please ###\\n$BASH_ENV\"\n" +
" fi\n" +
"}\n" +
"\n" +
"# Apache setting\n" +
"set_apache(){\n" +
" cd $APP_HOME\n" +
" if [ \"$OS_ARCH\" == \"x86_64\" ];then\n" +
" APACHE_TAR=\"apache-${APACHE}-c${OS_VERSION}-x64.tar.gz\";\n" +
" nauth_arch=\"64\";\n" +
" else\n" +
" APACHE_TAR=\"apache-${APACHE}-c${OS_VERSION}-i386.tar.gz\";\n" +
" nauth_arch=\"86\";\n" +
" fi\n" +
"\n" +
" echo -n \" - Apache Installation =>\"\n" +
" if [ ${OS_VERSION} -ge 7 ] && [[ \"${APACHE}\" =~ ^2.4. ]];then\n" +
" if [ `rpm -q nghttp2 lignghttp2|grep -v 'not installed' -c` -ne 2 ];then\n" +
" yum -y install nghttp2 libnghttp2\n" +
" fi\n" +
" fi\n" +
"\n" +
" wget -q http://$REPO_ADDR/webapps/application/apache/${APACHE_TAR} -O ${APACHE_TAR}\n" +
" tar -zxf ${APACHE_TAR}\n" +
" rm -f ${APACHE_TAR}\n" +
"\n" +
" (test -h apache) || (ln -s apache-${APACHE} apache)\n" +
" chown -R irteam.irteam apache-${APACHE}\n" +
" chown -h irteam.irteam apache\n" +
" if [ ${OS_VERSION} -ge 6 ];then\n" +
" chown irteam.irteam apache-${APACHE}/bin/httpd\n" +
" /usr/sbin/setcap 'cap_net_bind_service=+ep' apache-${APACHE}/bin/httpd\n" +
" else\n" +
" chown root.irteam apache-${APACHE}/bin/httpd\n" +
" chmod 4750 apache-${APACHE}/bin/httpd\n" +
" fi\n" +
"\n" +
" echo \"OK!!\"\n" +
"}\n" +
"\n" +
"\n" +
"# Tomcat setting\n" +
"set_tomcat(){\n" +
" cd $APP_HOME\n" +
"\n" +
" echo -n \" - Tomcat Installtaion =>\"\n" +
"\n" +
" wget -q http://$REPO_ADDR/webapps/application/tomcat/${TOMCAT_TAR} -O ${TOMCAT_TAR}\n" +
" tar -zxf ${TOMCAT_TAR}\n" +
" rm -f ${TOMCAT_TAR}\n" +
" ( test -h tomcat ) || (ln -s apache-tomcat-${TOMCAT} tomcat)\n" +
" chown -h irteam.irteam tomcat\n" +
" echo \"OK!!\"\n" +
"}\n" +
"\n" +
"# JDK setting\n" +
"set_jdk(){\n" +
" cd $APP_HOME\n" +
"\n" +
" JDK_VER_MAJOR=`echo $JDK | cut -d'.' -f1`\n" +
"\n" +
" if [ $JDK_VER_MAJOR -lt 10 ];then\n" +
" JDK_VER=`echo $JDK|sed 's/^[0-9]\\+\\.//;s/\\.0_/u/'`\n" +
" if [ \"$OS_ARCH\" == \"x86_64\" ];then\n" +
" JDK_BIN=\"jdk-${JDK_VER}-linux-x64.bin\"\n" +
" JDK_TAR=\"jdk-${JDK_VER}-linux-x64.tar.gz\"\n" +
" else\n" +
" JDK_BIN=\"jdk-${JDK_VER}-linux-i586.bin\"\n" +
" JDK_TAR=\"jdk-${JDK_VER}-linux-i586.tar.gz\"\n" +
" fi\n" +
" else\n" +
" JDK_BIN=\"\" # not used\n" +
" JDK_VER=$JDK\n" +
" if [ \"$OS_ARCH\" == \"x86_64\" ];then\n" +
" [ $JDK_VER_MAJOR -ge 11 ] && OPEN=\"open\" || OPEN=\"\"\n" +
" JDK_TAR=\"${OPEN}jdk-${JDK_VER}_linux-x64_bin.tar.gz\"\n" +
" else\n" +
" # JAVA does not support\n" +
" msgexit \"only support x86_64 for JDK version over 9\"\n" +
" fi\n" +
" fi\n" +
"\n" +
" echo -n \" - JDK Installtaion =>\"\n" +
"\n" +
" if [[ ${JDK_VER} =~ ^6u.* ]]; then\n" +
"\n" +
" wget -q http://$REPO_ADDR/webapps/application/jdk/$JDK_BIN -O $JDK_BIN\n" +
" chmod 755 $JDK_BIN\n" +
" ./$JDK_BIN -noregister > /dev/null\n" +
" rm -f $JDK_BIN\n" +
" else\n" +
" wget -q http://$REPO_ADDR/webapps/application/jdk/$JDK_TAR -O $JDK_TAR\n" +
" tar xfz $JDK_TAR\n" +
" rm -f $JDK_TAR\n" +
" fi\n" +
"\n" +
" ( test -h jdk ) || (ln -s $D_JDK jdk)\n" +
" chown -h irteam.irteam jdk\n" +
" echo \"OK!!\"\n" +
"}\n" +
"\n" +
"# Cronolog for Tomcat Setting\n" +
"set_cronolog(){\n" +
" cd $WORK_HOME\n" +
" ( test -f $APP_HOME/cronolog/sbin/cronolog ) && msgexit \"Cronolog is already exist\"\n" +
" ( test -d src ) || (mkdir src)\n" +
"\n" +
" cd src\n" +
" echo -n \" - Cronolog Installation => \"\n" +
" wget -q http://$REPO_ADDR/webapps/application/tomcat/cronolog-1.6.2.tar.gz -O cronolog-1.6.2.tar.gz\n" +
" tar -zxf cronolog-1.6.2.tar.gz >/dev/null\n" +
"\n" +
" cd cronolog-1.6.2\n" +
" ./configure --prefix=$APP_HOME/cronolog-1.6.2 >/dev/null\n" +
" (make > /dev/null && make install > /dev/null) &> ../cronolog.err\n" +
"\n" +
" cd $APP_HOME\n" +
" chown -R irteam.irteam cronolog-1.6.2\n" +
" ( test -h cronolog ) || (ln -s cronolog-1.6.2 cronolog)\n" +
" chown -h irteam.irteam cronolog\n" +
" chown -R irteam.irteam $WORK_HOME/src\n" +
"\n" +
" echo \"OK!! (errror log: $APP_HOME/src/cronolog.err)\"\n" +
"}\n" +
"\n" +
"# sync files\n" +
"sync_common(){\n" +
" echo -n \" - Sync files => \"\n" +
" # rsync #1\n" +
" rsync -a --exclude=.svn --exclude=apps $REPO_ADDR::webapps/ $WORK_HOME/\n" +
" rsync -a --exclude=.svn --exclude=modules $REPO_ADDR::webapps/apps/apache-${APACHE}/ $WORK_HOME/apps/apache-${APACHE}/\n" +
" rsync -a --exclude=.svn $REPO_ADDR::webapps/apps/apache-tomcat-${TOMCAT}/ $WORK_HOME/apps/apache-tomcat-${TOMCAT}/\n" +
" rsync -a --exclude=.svn $REPO_ADDR::webapps/apps/$D_JDK/ $WORK_HOME/apps/$D_JDK/\n" +
"\n" +
" if [ \"${NAUTH}\" != \"\" ];then\n" +
"\n" +
" rsync -a -L \\\n" +
" $REPO_ADDR::webapps/apps/apache-${APACHE}/modules/${OS_ARCH}/mod_${NAUTH}-latest_apache-${APACHE%.*}_CentOS-${OS_VERSION}.x_x${nauth_arch}.so \\\n" +
" $WORK_HOME/apps/apache-${APACHE}/modules/\n" +
" chmod 755 $WORK_HOME/apps/apache-${APACHE}/modules/mod_${NAUTH}-latest_apache-${APACHE%.*}_CentOS-${OS_VERSION}.x_x${nauth_arch}.so\n" +
" ln -s mod_${NAUTH}-latest_apache-${APACHE%.*}_CentOS-${OS_VERSION}.x_x${nauth_arch}.so $WORK_HOME/apps/apache-${APACHE}/modules/mod_nvauth.so\n" +
" chown -h irteam.irteam $WORK_HOME/apps/apache-${APACHE}/modules/mod_nvauth.so\n" +
" sed -i '/mod_nvauth.so/s/^#//' $WORK_HOME/apps/apache-${APACHE}/conf/httpd.conf\n" +
"\n" +
" fi\n" +
" chown -R irteam.irteam $WORK_HOME/apps/apache-${APACHE}/conf $WORK_HOME/apps/apache-${APACHE}/modules\n" +
" chown -R irteam.irteam $WORK_HOME/apps/apache-tomcat-${TOMCAT}\n" +
" chown -R irteam.irteam $WORK_HOME/apps/$D_JDK\n" +
" chown -R irteam.irteam $WORK_HOME/scripts\n" +
"\n" +
" echo ${catalina_opt} >> $WORK_HOME/apps/apache-tomcat-${TOMCAT}/bin/setenv.sh\n" +
" echo \"OK!!\"\n" +
" echo \"--------------------\"\n" +
"\n" +
" # 위의 rsync #1 에 의해서 /home1/irteam 의 소유권과 퍼미션이 변경이 된다.\n" +
" # irteam -> root, 750 -> 755\n" +
" # 일단 소유권만 복구 시킨다.\n" +
" chown irteam.irteam $WORK_HOME\n" +
" chown -h irteam.irteam $WORK_HOME/apps/*\n" +
" chown -R irteam.irteam $WORK_HOME/deploy/\n" +
"}\n" +
"\n" +
"### main ###\n" +
"OPTS=$(getopt -o hva:t:j:m: -l help,version,apache:,tomcat:,jdk:,module: -- $*)\n" +
"set -- ${OPTS}\n" +
"\n" +
"while true; do\n" +
" case \"$1\" in\n" +
" -h|--help)\n" +
" help\n" +
" break;\n" +
" ;;\n" +
" -v|--version)\n" +
" version\n" +
" exit 1;\n" +
" ;;\n" +
" -a|--apache)\n" +
" APACHE=${2//\\'/}\n" +
" if ! $(version|grep '^apache'|grep -qw ${2//\\'/}) ;then\n" +
" version\n" +
" msgexit \"No usable version $2\"\n" +
" fi\n" +
" shift 2;\n" +
" ;;\n" +
" -t|--tomcat)\n" +
" TOMCAT=${2//\\'/}\n" +
" if ! $(version|grep '^tomcat'|grep -qw ${2//\\'/}) ;then\n" +
" version\n" +
" msgexit \"No usable version $2\"\n" +
" fi\n" +
" shift 2;\n" +
" ;;\n" +
" -j|--jdk)\n" +
" JDK=${2//\\'/}\n" +
" if ! $(version|grep '^jdk'|grep -qw ${2//\\'/}) ;then\n" +
" version\n" +
" msgexit \"No usable version $2\"\n" +
" fi\n" +
" shift 2;\n" +
" ;;\n" +
" -m|--module)\n" +
" MODULE=${2//\\'/}\n" +
" if [ $MODULE == \"naver\" ];then\n" +
" NAUTH=\"nvauth\"\n" +
" elif [ $MODULE == \"nbp\" ];then\n" +
" NAUTH=\"nvextauth\"\n" +
" else\n" +
" msgexit \"Not exist module $2\"\n" +
" fi\n" +
" shift 2;\n" +
" ;;\n" +
" --)\n" +
" break;\n" +
" esac\n" +
"done\n" +
"\n" +
"### Pre Checking ###\n" +
"#check_options\n" +
"#check_idc\n" +
"check_version\n" +
"check_os\n" +
"check_user\n" +
"check_pre\n" +
"##check_update\n" +
"\n" +
"### setting apache/tomcat/jdk ###\n" +
"set_dir\n" +
"#set_apache\n" +
"set_tomcat\n" +
"#set_jdk\n" +
"#set_cronolog\n" +
"sync_common\n" +
"set_bashenv\n" +
"\n" +
"echo \"Completed!!\"\n" +
"\n" +
"# Embeded VIM Configurations\n" +
"# vim: filetype=sh si smarttab noet sw=4 ts=4 fdm=marker\n" +
"\n";
}
// 이미지 upload 기본 html
@RequestMapping("/test")
public String test() {
// 사용자에게 현재 폴더에 있는 이미지 목록 제공
String result = autoService.getFileList();
System.out.println(result);
return "/project/home.html";
}
// Java에서 cmd 실행 test
@RequestMapping("/terminal")
@ResponseBody
public String terminalTest() { // 추후에는 request에 명령어를 담아서 오자.
String[] cmd = {"ifconfig"};
String result = autoService.execCommand(cmd);
return result;
}
// 이미지 upload test
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String fileUpload(MultipartHttpServletRequest request) {
return autoService.fileUpload(request);
}
// image augmentation 요청
@RequestMapping(value = "/imgAug", method = RequestMethod.POST)
@ResponseBody
public String imageAugmentation(MultipartHttpServletRequest request) { // 추후에 @Requestbody?? ImgAugRequestVo request로 수정해야하는데 FE에서 어떻게 전달해야하는지 모르겠네
return autoService.imgAug(request);
}
}
| true |
bca0de8db46f8d5e352cfbc20f7295a98977b366
|
Java
|
lhogie/jalinopt
|
/src/main/java/jalinopt/Result.java
|
UTF-8
| 960 | 2.921875 | 3 |
[] |
no_license
|
package jalinopt;
import java.util.Collection;
import java.util.HashSet;
public class Result
{
private final Collection<Variable> variables = new HashSet<Variable>();
private double objective = Double.NaN;
private LP problem;
public Result(LP p)
{
this.problem = p;
variables.addAll(p.getVariables());
}
public LP getProblem()
{
return problem;
}
public double getObjective()
{
return objective;
}
public void setObjective(double objective)
{
this.objective = objective;
}
@Override
public String toString()
{
StringBuilder b = new StringBuilder();
b.append("objective: " );
b.append(objective);
b.append('\n');
for (Variable v : variables)
{
b.append(v.getName());
b.append(" = ");
b.append(v.getValue());
b.append('\n');
}
return b.toString();
}
public Collection<Variable> getVariables()
{
return variables;
}
}
| true |
4858c2a7c7709d75f63093c3f7e78695f039d3dd
|
Java
|
GertKanter/HyperFlex
|
/src/org.hyperflex.compositionmodels.ros.model/src/org/hyperflex/roscompositionmodel/impl/ROSSrvConsumerImpl.java
|
UTF-8
| 4,775 | 1.679688 | 2 |
[] |
no_license
|
/**
* HyperFlex Toolchain
*
* Copyright (c) 2013
* All rights reserved.
*
* Luca Gherardi
* University of Bergamo
* Department of Engineering
*
* ***********************************************************************************************
*
* Author: <A HREF="mailto:[email protected]">Luca Gherardi</A>
*
* In collaboration with:
* <A HREF="mailto:[email protected]">Davide Brugali</A>, Department of Engineering
*
* ***********************************************************************************************
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*
*/
package org.hyperflex.roscompositionmodel.impl;
import org.hyperflex.compositionmodel.impl.CompRequiredInterfImpl;
import org.hyperflex.roscomponentmodel.CompositeSrvConsumer;
import org.hyperflex.roscompositionmodel.ROSSrvConsumer;
import org.hyperflex.roscompositionmodel.roscompositionmodelPackage;
import org.eclipse.emf.common.notify.Notification;
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>ROS Srv Consumer</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.hyperflex.roscompositionmodel.impl.ROSSrvConsumerImpl#getSrvConsumer <em>Srv Consumer</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class ROSSrvConsumerImpl extends CompRequiredInterfImpl implements ROSSrvConsumer {
/**
* The cached value of the '{@link #getSrvConsumer() <em>Srv Consumer</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSrvConsumer()
* @generated
* @ordered
*/
protected CompositeSrvConsumer srvConsumer;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ROSSrvConsumerImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return roscompositionmodelPackage.Literals.ROS_SRV_CONSUMER;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CompositeSrvConsumer getSrvConsumer() {
if (srvConsumer != null && srvConsumer.eIsProxy()) {
InternalEObject oldSrvConsumer = (InternalEObject)srvConsumer;
srvConsumer = (CompositeSrvConsumer)eResolveProxy(oldSrvConsumer);
if (srvConsumer != oldSrvConsumer) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, roscompositionmodelPackage.ROS_SRV_CONSUMER__SRV_CONSUMER, oldSrvConsumer, srvConsumer));
}
}
return srvConsumer;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CompositeSrvConsumer basicGetSrvConsumer() {
return srvConsumer;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setSrvConsumer(CompositeSrvConsumer newSrvConsumer) {
CompositeSrvConsumer oldSrvConsumer = srvConsumer;
srvConsumer = newSrvConsumer;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, roscompositionmodelPackage.ROS_SRV_CONSUMER__SRV_CONSUMER, oldSrvConsumer, srvConsumer));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case roscompositionmodelPackage.ROS_SRV_CONSUMER__SRV_CONSUMER:
if (resolve) return getSrvConsumer();
return basicGetSrvConsumer();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case roscompositionmodelPackage.ROS_SRV_CONSUMER__SRV_CONSUMER:
setSrvConsumer((CompositeSrvConsumer)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case roscompositionmodelPackage.ROS_SRV_CONSUMER__SRV_CONSUMER:
setSrvConsumer((CompositeSrvConsumer)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case roscompositionmodelPackage.ROS_SRV_CONSUMER__SRV_CONSUMER:
return srvConsumer != null;
}
return super.eIsSet(featureID);
}
} //ROSSrvConsumerImpl
| true |
28baabb50e9e37efd9a82ac1c01b788c7b949f37
|
Java
|
wangpo1991/Sentinel
|
/sentinel-demo/sentinel-demo-quarkus/src/main/java/com/alibaba/csp/sentinel/demo/quarkus/AppLifecycleBean.java
|
UTF-8
| 2,615 | 1.921875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.csp.sentinel.demo.quarkus;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
import io.quarkus.runtime.StartupEvent;
import org.jboss.logging.Logger;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import java.util.Arrays;
/**
* @author sea
*/
@ApplicationScoped
public class AppLifecycleBean {
private static final Logger LOGGER = Logger.getLogger("ListenerBean");
void onStart(@Observes StartupEvent ev) {
LOGGER.info("The application is starting...");
FlowRule rule = new FlowRule()
.setCount(1)
.setGrade(RuleConstant.FLOW_GRADE_QPS)
.setResource("GET:/hello/txt")
.setLimitApp("default")
.as(FlowRule.class);
FlowRuleManager.loadRules(Arrays.asList(rule));
SystemRule systemRule = new SystemRule();
systemRule.setLimitApp("default");
systemRule.setAvgRt(3000);
SystemRuleManager.loadRules(Arrays.asList(systemRule));
DegradeRule degradeRule1 = new DegradeRule("greeting1")
.setCount(1)
.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT)
.setTimeWindow(10)
.setMinRequestAmount(1);
DegradeRule degradeRule2 = new DegradeRule("greeting2")
.setCount(1)
.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT)
.setTimeWindow(10)
.setMinRequestAmount(1);
DegradeRuleManager.loadRules(Arrays.asList(degradeRule1, degradeRule2));
}
}
| true |
fc13b7f5422e7557cea89a6b8cdd2068660503e1
|
Java
|
zalak16/Project-Nemo
|
/NetworkMotif/src/main/java/edu/uw/nemo/motifSignificant/mapreduce/NemoRandomGraphMain.java
|
UTF-8
| 1,697 | 2.515625 | 3 |
[] |
no_license
|
package edu.uw.nemo.motifSignificant.mapreduce;
import java.io.IOException;
import java.net.URISyntaxException;
/**
* Created by Zalak on 5/5/2015.
*/
public class NemoRandomGraphMain
{
public static void main(String args[]) throws IOException, InterruptedException, URISyntaxException, ClassNotFoundException {
long startTime = System.currentTimeMillis();
System.out.println(args.length);
if(args.length < 7)
{
System.out.println("Invalid Input: ");
return;
}
String biologicalNetworkFile = args[0];
String outputFile = args[1];
String totalRandomGraph = args[2];
if(Double.valueOf(args[3]) < 0.0 || Double.valueOf(args[3])> 1.0)
{
System.out.println("Invalid probability: probability should be within 0 and 1");
return;
}
String probability = args[3];
String jarFileName = args[4];
String logDir = args[5];
String size = args[6];
for(int i= 0; i< args.length; i++)
{
System.out.println(args[i]);
}
GraphGeneratorJob graphGeneratorJob = new GraphGeneratorJob();
String jobArgs[] = new String[args.length];
jobArgs[0] = biologicalNetworkFile;
jobArgs[1]= outputFile;
jobArgs[2] = totalRandomGraph;
jobArgs[3]= probability;
jobArgs[4]= jarFileName;
jobArgs[5] = logDir;
jobArgs[6] = size;
graphGeneratorJob.run(jobArgs);
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("Elapsed Time: " + elapsedTime);
}
}
| true |
8b4449ab8fd4f6876602d858ef5be735fdf71221
|
Java
|
aws-samples/aws-greengrass-lambda-functions
|
/foundation/CDDBaselineJava/src/main/java/com/awslabs/aws/iot/greengrass/cdd/helpers/implementations/BasicJsonHelper.java
|
UTF-8
| 2,810 | 2.46875 | 2 |
[
"MIT-0",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
package com.awslabs.aws.iot.greengrass.cdd.helpers.implementations;
import com.awslabs.aws.iot.greengrass.cdd.events.GreengrassLambdaEvent;
import com.awslabs.aws.iot.greengrass.cdd.helpers.JsonHelper;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapterFactory;
import io.vavr.gson.VavrGson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.util.Map;
import java.util.Optional;
import java.util.ServiceLoader;
public class BasicJsonHelper implements JsonHelper {
private final Logger log = LoggerFactory.getLogger(BasicJsonHelper.class);
private Optional<GsonBuilder> optionalGsonBuilder = Optional.empty();
@Inject
public BasicJsonHelper() {
}
@Override
public String toJson(Object object) {
return getGsonBuilder()
.disableHtmlEscaping()
.setPrettyPrinting()
.create()
.toJson(object);
}
private GsonBuilder getGsonBuilder() {
if (!optionalGsonBuilder.isPresent()) {
GsonBuilder gsonBuilder = new GsonBuilder();
// This allows us to use GSON with Immutables - https://immutables.github.io/json.html#type-adapter-registration
for (TypeAdapterFactory factory : ServiceLoader.load(TypeAdapterFactory.class)) {
gsonBuilder.registerTypeAdapterFactory(factory);
}
// This allows us to use GSON with Vavr - https://github.com/vavr-io/vavr-gson
VavrGson.registerAll(gsonBuilder);
optionalGsonBuilder = Optional.of(gsonBuilder);
}
return optionalGsonBuilder.get();
}
@Override
public <T> T fromJson(Class<T> clazz, byte[] json) {
return fromJson(clazz, new String(json));
}
@Override
public <T> T fromJson(Class<T> clazz, String json) {
return getGsonBuilder().create()
.fromJson(json, clazz);
}
@Override
public <T> Optional<T> fromJson(Class<T> clazz, GreengrassLambdaEvent greengrassLambdaEvent) {
if (!greengrassLambdaEvent.getJsonInput().isPresent()) {
log.error("No JSON payload present for conversion to a [" + clazz.getName() + "]");
return Optional.empty();
}
// Get the JSON input as a map
Map input = greengrassLambdaEvent.getJsonInput().get();
// Convert it back to a JSON string
String jsonString = toJson(input);
try {
// Convert the JSON string to the requested class
return Optional.ofNullable(fromJson(clazz, jsonString));
} catch (Exception e) {
log.error("Could not convert JSON [" + jsonString + "], to a [" + clazz.getName() + "]");
return Optional.empty();
}
}
}
| true |
a63ae191a207275f9cda42d39bfecdda8682f101
|
Java
|
Sutonline/task-list
|
/task-list-web/src/test/java/cn/kevin/dao/TaskLabelTest.java
|
UTF-8
| 1,404 | 2.265625 | 2 |
[] |
no_license
|
package cn.kevin.dao;
import cn.kevin.domain.TaskLabel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by yongkang.zhang on 2017/5/18.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"/spring-config.xml", "classpath:spring-config-test.xml"})
public class TaskLabelTest {
@Resource
private TaskLabelMapper taskLabelMapper;
@Test
public void test() {
taskLabelMapper.deleteByPrimaryKey(1);
taskLabelMapper.deleteByPrimaryKey(2);
taskLabelMapper.deleteByPrimaryKey(3);
TaskLabel label1 = new TaskLabel();
label1.setName("work");
label1.setValue("工作");
taskLabelMapper.insert(label1);
TaskLabel label2 = new TaskLabel();
label2.setName("life");
label2.setValue("生活");
TaskLabel label3 = new TaskLabel();
label3.setName("study");
label3.setValue("学习");
taskLabelMapper.insert(label2);
taskLabelMapper.insert(label3);
}
@Test
public void testQuery() {
List<TaskLabel> taskLabels = taskLabelMapper.selectAll();
taskLabels.forEach(taskLabel -> System.out.println(taskLabel.toString()));
}
}
| true |
4f5c1afd9ec340fb4a2520de6e41f5b662196e42
|
Java
|
neucloudzouaodi/iotdb
|
/src/main/java/cn/edu/tsinghua/iotdb/qp/logical/crud/BasicOperatorType.java
|
UTF-8
| 3,072 | 2.609375 | 3 |
[] |
no_license
|
package cn.edu.tsinghua.iotdb.qp.logical.crud;
import cn.edu.tsinghua.iotdb.qp.constant.SQLConstant;
import cn.edu.tsinghua.iotdb.qp.exception.LogicalOperatorException;
import cn.edu.tsinghua.tsfile.timeseries.filter.definition.FilterFactory;
import cn.edu.tsinghua.tsfile.timeseries.filter.definition.SingleSeriesFilterExpression;
import cn.edu.tsinghua.tsfile.timeseries.filter.definition.filterseries.FilterSeries;
/**
* all basic operator in filter
*
* @author kangrong
*
*/
public enum BasicOperatorType {
EQ {
@Override
public <T extends Comparable<T>, C extends FilterSeries<T>> SingleSeriesFilterExpression getSingleSeriesFilterExpression(
C column, T value) {
return FilterFactory.eq(column, value);
}
},
LTEQ {
@Override
public <T extends Comparable<T>, C extends FilterSeries<T>> SingleSeriesFilterExpression getSingleSeriesFilterExpression(
C column, T value) {
return FilterFactory.ltEq(column, value, true);
}
},
LT {
@Override
public <T extends Comparable<T>, C extends FilterSeries<T>> SingleSeriesFilterExpression getSingleSeriesFilterExpression(
C column, T value) {
return FilterFactory.ltEq(column, value, false);
}
},
GTEQ {
@Override
public <T extends Comparable<T>, C extends FilterSeries<T>> SingleSeriesFilterExpression getSingleSeriesFilterExpression(
C column, T value) {
return FilterFactory.gtEq(column, value, true);
}
},
GT {
@Override
public <T extends Comparable<T>, C extends FilterSeries<T>> SingleSeriesFilterExpression getSingleSeriesFilterExpression(
C column, T value) {
return FilterFactory.gtEq(column, value, false);
}
},
NOTEQUAL {
@Override
public <T extends Comparable<T>, C extends FilterSeries<T>> SingleSeriesFilterExpression getSingleSeriesFilterExpression(
C column, T value) {
return FilterFactory.noteq(column, value);
}
};
public static BasicOperatorType getBasicOpBySymbol(int tokenIntType)
throws LogicalOperatorException {
switch (tokenIntType) {
case SQLConstant.EQUAL:
return EQ;
case SQLConstant.LESSTHANOREQUALTO:
return LTEQ;
case SQLConstant.LESSTHAN:
return LT;
case SQLConstant.GREATERTHANOREQUALTO:
return GTEQ;
case SQLConstant.GREATERTHAN:
return GT;
case SQLConstant.NOTEQUAL:
return NOTEQUAL;
default:
throw new LogicalOperatorException("unsupported type:{}"
+ SQLConstant.tokenNames.get(tokenIntType));
}
}
public abstract <T extends Comparable<T>, C extends FilterSeries<T>> SingleSeriesFilterExpression getSingleSeriesFilterExpression(
C column, T value);
}
| true |
54ea3c6ec807116abad08002e93329652aba98f9
|
Java
|
ankita1797/school-bus-driver-navigator
|
/app/src/main/java/fragmentstabs/SelectBusFragment.java
|
UTF-8
| 1,996 | 2.171875 | 2 |
[] |
no_license
|
package fragmentstabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.ankita.internshipapplication.HomeFragment;
import com.example.ankita.internshipapplication.MainActivity;
import com.example.ankita.internshipapplication.R;
public class SelectBusFragment extends Fragment{
private TextView et_busplate;
private MainActivity mainActivity;
private TextView start, stop;
public SelectBusFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_selectbus, container, false);
et_busplate= (TextView) rootview.findViewById(R.id.et_busplate);
start= (TextView) rootview.findViewById(R.id.start);
stop= (TextView) rootview.findViewById(R.id.stop);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stop.setVisibility(View.VISIBLE);
start.setVisibility(View.GONE);
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
start.setVisibility(View.VISIBLE);
stop.setVisibility(View.GONE);
}
});
et_busplate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
BusList busList= new BusList(getActivity(), et_busplate);
busList.show();
}
});
return rootview;
}
}
| true |
dc1611c9d34de861a6eb9fcb25028ebca7c07990
|
Java
|
iu7/tasktracker
|
/PROJECTS/src/main/java/ru/bmstu/iu7/rsoi/gulyy/coursework/issue/types/IssueTypeResource.java
|
UTF-8
| 2,538 | 2.25 | 2 |
[] |
no_license
|
package ru.bmstu.iu7.rsoi.gulyy.coursework.issue.types;
import ru.bmstu.iu7.rsoi.gulyy.coursework.projects.Project;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;
import java.net.URI;
import java.util.List;
/**
* @author Konstantin Gulyy
*/
@Path("projects")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
@Stateless
public class IssueTypeResource {
@PersistenceContext(unitName = "PROJECTS")
private EntityManager em;
@Context
private UriInfo uriInfo;
@GET
@Path("{projectName}/issuetypes/{id}")
public IssueType getIssueType(@PathParam("id") int id, @PathParam("projectName") String projectName) {
IssueTypePK pk = new IssueTypePK(id, projectName);
IssueType issueType = em.find(IssueType.class, pk);
return issueType;
}
@GET
@Path("{projectName}/issuetypes")
public List<IssueType> getAllIssueTypesForProject(@PathParam("projectName") String projectName) {
Query query = em.createNamedQuery(IssueType.FIND_ALL_FOR_PROJECT);
query.setParameter(1, projectName);
List<IssueType> issueTypes = query.getResultList();
return issueTypes;
}
@POST
@Path("{projectName}/issuetypes")
public Response createNewIssueType(@PathParam("projectName") String projectName, JAXBElement<IssueType> issueTypeJAXB) {
Project project = em.find(Project.class, projectName);
if (project == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
IssueType issueType = issueTypeJAXB.getValue();
issueType.setId(project.incAndGetLastIssueTypeId());
issueType.setProjectName(project.getName());
em.persist(project);
em.persist(issueType);
URI issueTypeUri = uriInfo.getAbsolutePathBuilder().path(String.valueOf(issueType.getId())).build();
return Response.created(issueTypeUri).build();
}
@DELETE
@Path("{projectName}/issuetypes/{id}")
public void deleteIssueType(@PathParam("id") int id, @PathParam("projectName") String projectName) {
IssueTypePK pk = new IssueTypePK(id, projectName);
IssueType issueType = em.find(IssueType.class, pk);
em.remove(issueType);
}
}
| true |
75d3afea85f705aeab3963214206857def60fceb
|
Java
|
kurartur/dualpair-server
|
/src/main/java/lt/dualpair/server/security/Authorizer.java
|
UTF-8
| 397 | 2.125 | 2 |
[] |
no_license
|
package lt.dualpair.server.security;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
@Component
public class Authorizer {
public boolean hasPermission(Authentication authentication, Long userId) {
UserDetails principal = (UserDetails) authentication.getPrincipal();
return principal.getId().equals(userId);
}
}
| true |
2c71c55747977e44f20828974cdc9efb1820acb1
|
Java
|
povilasb/gwttestcase-sample
|
/src/com/example/client/Main.java
|
UTF-8
| 400 | 2.359375 | 2 |
[] |
no_license
|
package com.example.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
public class Main implements EntryPoint{
@Override
public void onModuleLoad(){
Element textDiv = Document.get().getElementById("text");
Person me = new Person("Povilas", 23);
textDiv.setInnerHTML("Hello " + me.getName());
}
}
| true |
877afd009f32ad2a5a90f320774d6665779e1b9b
|
Java
|
RiccardoCecco/ing-sw-2020-asaro-cassata-cecco
|
/src/main/java/it/polimi/ingsw/Client.java
|
UTF-8
| 4,323 | 2.921875 | 3 |
[] |
no_license
|
package it.polimi.ingsw;
import it.polimi.ingsw.ParserClient.BuilderCommand;
import it.polimi.ingsw.ParserClient.ParserEvent;
import it.polimi.ingsw.commands.Command;
import it.polimi.ingsw.events.Event;
import it.polimi.ingsw.events.ExceptionEvent;
import it.polimi.ingsw.view.Gui;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
/**
* it is the class that handle the client side
*/
public class Client extends Thread {
/**
* it is the view of the player
*/
private Gui view;
/**
* it is the socket whwere communicate with server
*/
private Socket socket = null;
private BufferedWriter writer = null;
private PrintWriter out = null;
/**
* it is the port number
*/
private int portNumber;
/**
* it is the ip address of the server
*/
private String ipAddress;
private InputStreamReader input;
private Scanner scanner;
private boolean started=false;
/**
* it is true if is connect, false otherwise
*/
private boolean isConnected = true;
/**
* default constructor
* @param text it is the ip address
* @param port it is the port where communicate
* @param gui it is the corresponding gui of the player
*/
public Client(String text, int port, Gui gui) {
this.view = gui;
this.ipAddress = text;
this.portNumber = port;
try {
socket = new Socket(ipAddress, portNumber);
started=true;
} catch (IOException e) {
gui.update(new ExceptionEvent("No Server available, please try again"));
return;
}
try {
this.input = new InputStreamReader(socket.getInputStream());
System.out.println(socket.getInputStream());
System.out.println(input.toString());
this.scanner = new Scanner(input);
System.out.println(scanner.toString());
System.out.println("Client started " + socket);
//Stream del client
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out = new PrintWriter(writer, true);
//stream input da tastiera
} catch (UnknownHostException exp2) {
System.err.println("Errore: " + exp2.getMessage());
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Client closing");
//out.close();
//stdin.close();
//in.close();
// socket.close();
}
/**
* this method is called to send a command to the virtual view
* @param cmd is the command to send
*/
public void send(Command cmd) {
if (socket != null) {
BuilderCommand b = new BuilderCommand();
String json = b.builder(cmd);
this.out.println(json);
System.out.println(json);
System.out.println("Command: " + cmd.toString());
}
}
/**
* this method is called when Client receive an event from the model
* @param json is the string json that contains the event
*/
public void receive(String json) {
System.out.println(json);
ParserEvent p = new ParserEvent();
Event event = p.parser(json);
event.send(view);
//System.out.println(event.getClass());
}
@Override
public void run() {
while (isConnected) {
String s = null;
if(!started)
break;
if (scanner.hasNext()) {
s = scanner.nextLine();
System.out.println(s);
receive(s);
}
}
//System.out.println("client correctly closed");
// System.out.println("Event: "+ s);
}
/**
* this method is called when player disconnects
* @throws IOException
*/
public void disconnect() throws IOException {
isConnected = false;
if(input!=null)
input.close();
if(out!=null)
writer.close();
if(out!=null)
out.close();
if(scanner!=null)
scanner.close();
if(socket!=null)
socket.close();
}
}
| true |
8b670b47d014e54e9f59c0803b9473e0c3a67c69
|
Java
|
bagus-stimata/spring-hibernate-integration
|
/Spring3-Hibernate4-Simple-Maven/src/main/java/org/config/spring/hibernate/dao/impl/Product2DaoImpl.java
|
UTF-8
| 1,209 | 2.46875 | 2 |
[] |
no_license
|
package org.config.spring.hibernate.dao.impl;
import java.util.List;
import org.config.spring.hibernate.dao.Product2Dao;
import org.config.spring.hibernate.model.Product;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
//@Service
public class Product2DaoImpl implements Product2Dao {
//@Autowired
private SessionFactory sessionFactory;
public Product getById(String id) {
Criteria crit = sessionFactory.getCurrentSession().createCriteria(Product.class);
crit.add(Restrictions.like("idProduct", id, MatchMode.ANYWHERE));
return (Product) crit.list().get(0);
}
public Product getByName(String name) {
Criteria crit = sessionFactory.getCurrentSession().createCriteria(Product.class);
crit.add(Restrictions.like("description", name, MatchMode.ANYWHERE));
return (Product) crit.list().get(0);
}
@SuppressWarnings("unchecked")
public List<Product> getAll() {
Criteria crit = sessionFactory
.getCurrentSession()
.createCriteria(Product.class);
return crit.list();
}
public void insert(Product product) {
sessionFactory.getCurrentSession().save(product);
}
}
| true |
7505281ce0a98d2690cd4772a13b58e586f9bd45
|
Java
|
Stalyon/stalyon-bot
|
/src/main/java/com/stalyon/ogame/service/SaveFleetService.java
|
UTF-8
| 1,409 | 1.835938 | 2 |
[] |
no_license
|
package com.stalyon.ogame.service;
import com.stalyon.ogame.OgameApiService;
import com.stalyon.ogame.constants.OgameCst;
import com.stalyon.ogame.utils.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
@Service
@Profile("saveFleet")
public class SaveFleetService {
@Autowired
private OgameApiService ogameApiService;
@Autowired
private MessageService messageService;
@Scheduled(cron = "30 14 13 * * *")
public void saveFleet() {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("ships", OgameCst.LARGE_CARGO_ID + "," + "2");
formData.add("mission", OgameCst.TRANSPORT.toString());
formData.add("speed", OgameCst.TEN_PERCENT.toString());
formData.add("galaxy", "3");
formData.add("system", "310");
formData.add("position", "11");
formData.add("metal", "0");
formData.add("crystal", "0");
formData.add("deuterium", "0");
this.ogameApiService.sendFleet(33630004, formData);
this.messageService.logInfo("Flotte envoyée", Boolean.FALSE, Boolean.FALSE);
}
}
| true |
23377ff09971ca5c1d96529dc7d933a606972d9d
|
Java
|
infinispan/infinispan
|
/server/core/src/test/java/org/infinispan/server/core/MockProtocolServer.java
|
UTF-8
| 1,468 | 2.09375 | 2 |
[
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] |
permissive
|
package org.infinispan.server.core;
import org.infinispan.server.core.configuration.MockServerConfiguration;
import org.infinispan.server.core.configuration.MockServerConfigurationBuilder;
import org.infinispan.server.core.transport.NettyTransport;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOutboundHandler;
import io.netty.channel.group.ChannelMatcher;
public class MockProtocolServer extends AbstractProtocolServer<MockServerConfiguration> {
public static final String DEFAULT_CACHE_NAME = "dummyCache";
public static final int DEFAULT_PORT = 1245;
public MockProtocolServer(String protocolName, NettyTransport transport) {
super(protocolName);
configuration = new MockServerConfigurationBuilder()
.defaultCacheName(DEFAULT_CACHE_NAME)
.port(DEFAULT_PORT)
.build();
this.transport = transport;
}
public MockProtocolServer() {
super(null);
}
@Override
public ChannelOutboundHandler getEncoder() {
return null;
}
@Override
public ChannelInboundHandler getDecoder() {
return null;
}
@Override
public ChannelMatcher getChannelMatcher() {
return channel -> true;
}
@Override
public void installDetector(Channel ch) {
}
@Override
public ChannelInitializer<Channel> getInitializer() {
return null;
}
}
| true |
c0468681b597018a7d89d26b9b9865c689f3c590
|
Java
|
rogeryee/JavaStudy
|
/java-study-core/src/main/java/com/yee/study/java/security/samples/crypt/AESSample.java
|
UTF-8
| 2,468 | 3.140625 | 3 |
[] |
no_license
|
package com.yee.study.java.security.samples.crypt;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;
/**
* AES加解密的示例
*
* @author Roger.Yi
*/
public class AESSample
{
public static final String src = "hello world";
public static void main(String[] args) throws Exception
{
jdkAES();
bcAES();
}
/**
* JDK实现
*/
public static void jdkAES() throws Exception
{
// 获取KEY生成器
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
// 产生并获取KEY
SecretKey secretKey = keyGenerator.generateKey();
byte[] keyBytes = secretKey.getEncoded();
// KEY转换
Key key = new SecretKeySpec(keyBytes, "AES");
// 加密
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(src.getBytes());
System.out.println("jdk aes encrypt:" + Hex.encodeHexString(result));
// 解密
cipher.init(Cipher.DECRYPT_MODE, key);
result = cipher.doFinal(result);
System.out.println("jdk aes decrypt:" + new String(result));
}
/**
* bouncy castle实现
*/
public static void bcAES() throws Exception
{
Security.addProvider(new BouncyCastleProvider());
// 获取KEY生成器
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES", "BC");
keyGenerator.getProvider();
keyGenerator.init(128);
// 产生并获取KEY
SecretKey secretKey = keyGenerator.generateKey();
byte[] keyBytes = secretKey.getEncoded();
// KEY转换
Key key = new SecretKeySpec(keyBytes, "AES");
// 加密
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(src.getBytes());
System.out.println("bc aes encrypt:" + Hex.encodeHexString(result));
// 解密
cipher.init(Cipher.DECRYPT_MODE, key);
result = cipher.doFinal(result);
System.out.println("bc aes decrypt:" + new String(result));
}
}
| true |
9b6081c3c8ce20fb49b1b7d81604b05d24a51286
|
Java
|
liuyunpeng01/CEPMS
|
/src/main/java/com/submit/web/controller/base/CommController.java
|
UTF-8
| 9,610 | 2.03125 | 2 |
[] |
no_license
|
package com.submit.web.controller.base;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.submit.util.*;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Map;
import java.util.UUID;
/**
* 公共的请求action
* @author submitX
*
*/
@Controller
@Scope("prototype")
@RequestMapping("comm")
public class CommController extends BaseController {
/**
* 验证码对象
*/
private Producer captchaProducer = null;
@Autowired
public void setCaptchaProducer(Producer captchaProducer) {
this.captchaProducer = captchaProducer;
}
/**
* 获取验证码图形化,验证码放在session名为KAPTCHA_SESSION_KEY中
* @param request
* @param response
* @return null,write验证码的图片到response中
* @throws Exception
*/
@RequestMapping(value="/captcha-image", method=RequestMethod.GET)
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setDateHeader("Expires", 0);// 禁止服务器端缓存
// 设置标准的 HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// 设置IE扩展 HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");// 设置标准 HTTP/1.0 不缓存图片
response.setContentType("image/jpeg");// 返回一个 jpeg 图片,默认是text/html(输出文档的MIMI类型)
String capText = captchaProducer.createText();// 为图片创建文本
capText = capText.toUpperCase();
// 将文本保存在session中,这里就使用包中的静态变量吧
request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
BufferedImage bi = captchaProducer.createImage(capText); // 创建带有文本的图片
ServletOutputStream out = response.getOutputStream();
// 图片数据输出
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
System.out.println("Session 验证码是:" + request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY));
return null;
}
/**
* 邮件发送
* @param request
* @param emailId
* @return 操作码
*/
@ResponseBody
@RequestMapping(value="email", method=RequestMethod.GET)
public Map<String, Object> emailActivationCode(HttpServletResponse response, HttpServletRequest request,
@RequestParam("email")String emailAddress, @RequestParam("type")int type) {
String code = UUID.randomUUID().toString();
// session的键值 存活30分钟
request.getSession().setMaxInactiveInterval(60 * 30);
request.getSession().setAttribute(MailUtil.EMAIL_KEY, code);
try {
if (type == MailUtil.TYPE_REPASSWORD) {
MailUtil.sendMail("学生管理系统: 更新密码", emailAddress, MailUtil.getRePasswordMsg(code));
}
resultMap.put(resultKey, ResultValue.SUCCESS);
} catch (Exception e) {
LoggerUtil.error(CommController.class, "邮件发送失败");
resultMap.put(resultKey, ResultValue.FAIL);
}
return resultMap;
}
/**
* 文件下载,某个角色的id用户所对应的文件
* /download/student/100000/score.docx
* @param request
* @param name
* @param sub
* @return
* @throws IOException
*/
@RequiresAuthentication
@RequestMapping(value= {"/download//{roleName:student}/{userId:[1-9][0-9]{9}}/{fielName}.{sub}",
"/download//{roleName:teacher}/{userId:[1-9][0-9]{3}}/{fielName}.{sub}", "/download/{fielName}.{sub}"}, method=RequestMethod.GET)
public ResponseEntity<byte[]> download(HttpServletRequest request, @PathVariable(value="roleName", required=false)String roleName,
@PathVariable(value="userId", required=false)Integer userId, @PathVariable("fielName")String name, @PathVariable("sub")String sub) throws IOException {
if (roleName != null) {
return export(roleName, userId, name, sub);
} else {
return export(null, null, name, sub);
}
}
/**
* 文件下载逻辑
* @param request
* @param directory
* @param fileName
* @return
* @throws IOException
*/
public ResponseEntity<byte[]> export(String roleName, Integer userId, String fileName, String fileSuffix) throws IOException {
StringBuffer url = new StringBuffer();
if (userId == null || roleName == null) {
// 基础文件下载
url.append(Utils.getFileByNameInFiles(fileName + "." + fileSuffix));
} else {
url.append(Utils.getFilesSaveRootPath()).append(roleName).append("/").append(userId).append("/")
.append(fileName).append(".").append(fileSuffix);
}
HttpHeaders headers = new HttpHeaders();
File file = new File(url.toString());
try {
fileName = fileName + "." + fileSuffix;
fileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", fileName);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}
/**
* 显示zip里面的文件列表
* @param filePath
* @return
*/
@RequiresAuthentication
@RequestMapping(value= {"/show/{roleName:student}/{userId:[1-9][0-9]{9}}/{fielName}.{sub}",
"/show/{roleName:teacher}/{userId:[1-9][0-9]{3}}/{fielName}.{sub}"}, method=RequestMethod.GET)
public ModelAndView showZip(HttpServletRequest request, @PathVariable(value="roleName")String roleName,
@PathVariable(value="userId")Integer userId, @PathVariable("fielName")String name, @PathVariable("sub")String sub) {
StringBuffer url = new StringBuffer();
if (userId == null || roleName == null) {
// 基础文件
url.append(Utils.getFileByNameInFiles(name + "." + sub));
} else {
url.append("/").append(roleName).append("/").append(userId).append("/")
.append(name).append(".").append(sub);
}
ArrayList<String> list = ZipUtil.getZipFilesPath(Utils.getFilesSaveRootPath() + url.toString());
resultMap.put("zipPath", url.toString());
resultMap.put("catalog", list);
return new ModelAndView("work/show", "files", resultMap);
}
/**
* 阅读zip文件中的某个文件
* @param request
* @param roleName
* @param userId
* @param name
* @param sub
*/
@RequiresAuthentication
@RequestMapping(value= {"/read//{roleName:student}/{userId:[1-9][0-9]{9}}/{fielName}.{sub}",
"/read//{roleName:teacher}/{userId:[1-9][0-9]{3}}/{fielName}.{sub}"}, method=RequestMethod.GET)
public ResponseEntity<byte[]> readZipItem(HttpServletRequest request, @PathVariable(value="roleName")String roleName, @RequestParam("item")String item,
@PathVariable(value="userId")Integer userId, @PathVariable("fielName")String name, @PathVariable("sub")String sub) {
String path = Utils.getFilesSaveRootPath();
StringBuffer url = new StringBuffer();
url.append(Utils.getFilesSaveRootPath()).append(roleName).append("/").append(userId).append("/")
.append(name).append(".").append(sub);
String itemFile = ZipUtil.readZipFileItem(url.toString(), item);
ResponseEntity<byte[]> entity = null;
try {
File file = Office2PdfUtil.converter(itemFile);
if (file != null) {
entity = Office2PdfUtil.preview(file);
}
} catch (IOException e) {
LoggerUtil.error(CommController.class, "读取pdf失败", e);
e.printStackTrace();
}
return entity;
}
@RequestMapping(value= {"/view//{roleName:student}/{userId:[1-9][0-9]{9}}/{fielName}.{sub}",
"/view//{roleName:teacher}/{userId:[1-9][0-9]{3}}/{fielName}.{sub}"}, method=RequestMethod.GET)
public ModelAndView viewPDF(HttpServletRequest request, @PathVariable(value="roleName")String roleName, @RequestParam("item")String item,
@PathVariable(value="userId")Integer userId, @PathVariable("fielName")String name, @PathVariable("sub")String sub) {
StringBuffer url = new StringBuffer();
url.append("/").append(roleName).append("/").append(userId).append("/")
.append(name).append(".").append(sub);
resultMap.put("file", url.toString());
resultMap.put("item", item);
return new ModelAndView("/page/pdfjs/web/view.html", resultMap);
}
}
| true |
d1c81df9a8c796031c08970b02eff9dc382ebfc0
|
Java
|
paralysedforce/Tsuro
|
/src/test/ParserTests/TokenNetworkingTest.java
|
UTF-8
| 793 | 2.390625 | 2 |
[] |
no_license
|
package test.ParserTests;
import org.junit.Assert;
import org.junit.Test;
import javafx.util.Pair;
import main.BoardSpace;
import main.Token;
/**
* Created by William on 5/22/2018.
*/
public class TokenNetworkingTest {
@Test
public void pawnLocFromLocationTest() {
BoardSpace space = new BoardSpace(3, 5);
Pair<BoardSpace, Integer> location = new Pair<>(space, 3);
Assert.assertEquals(
Token.pawnLocFromLocation(location),
"<pawn-loc>" +
"<v></v>" +
"<n>" +
"6" +
"</n>" +
"<n>" +
"7" +
"</n>" +
"</pawn-loc>"
);
}
}
| true |
46a5810bcba0599441d0a30a987e9bc915cc0e3a
|
Java
|
Vivek99srivastava/java
|
/Hyperlink.java
|
UTF-8
| 944 | 2.578125 | 3 |
[] |
no_license
|
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
public class Hyperlink extends JFrame
{
public static void main(String arg[])throws Exception
{
new Hyperlink();
}
public Hyperlink() throws Exception
{
String s = "http://www.rashmikantadas.com";
JEditorPane pane = new JEditorPane(s);
pane.setEditable(false);
final JEditorPane finalpane = pane;
pane.addHyperlinkListener(new HyperlinkListener()
{
public void hyperlinkUpdate(HyperlinkEvent r)
{
try
{
if(r.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
finalpane.setPage(r.getURL());
}catch(Exception e)
{}
}
});
setContentPane(new JScrollPane(pane));
setSize(400,400);
setVisible(true);
}
}
| true |
169a924fa196dae098ede9997e22b155f5008a43
|
Java
|
burhanorkun/tdesignpatterns
|
/TurkcellDesignPatterns/src/com/training/turkcell/dp/creational/abstractfactory/PrinterSystem1.java
|
UTF-8
| 510 | 2.921875 | 3 |
[] |
no_license
|
package com.training.turkcell.dp.creational.abstractfactory;
import com.training.turkcell.dp.creational.abstractfactory.formatter.IPersonFormatter;
public class PrinterSystem1 implements IPrinterSystem {
@Override
public void print(final Person person,
final IPersonFormatter formatter) {
System.out.println(formatter.getNameFormatter()
.format(person)
+ " " + formatter.getSurNameFormatter()
.format(person));
}
}
| true |
cc9aacbccbbb3f4ccbc0f23c931305bf0d122af9
|
Java
|
Sawyron/poultry-farm
|
/src/com/poultryfarm/birds/Bird.java
|
UTF-8
| 3,882 | 2.8125 | 3 |
[] |
no_license
|
package com.poultryfarm.birds;
import com.poultryfarm.IBehaviour;
import javax.swing.*;
import java.awt.*;
import java.io.Serial;
import java.io.Serializable;
import java.util.*;
public abstract class Bird implements IBehaviour, Serializable {
@Serial
private static final long serialVersionUID = 1L;
private int x = 0;
private int y = 0;
protected int vX = (int) (Math.random() * (10 + 1) + -5) + 1;
protected int vY = (int) (Math.random() * (10 + 1) + -5) + 1;
private final static Set<Long> ID_SET = new TreeSet<>();
public void setVelocity(int vX, int vY) {
this.vX = vX;
this.vY = vY;
stopped = false;
}
private static Random random = new Random();
private long ID;
private boolean isDead = false;
private boolean stopped = false;
private ImageIcon imageIcon;
private final static ImageIcon DeadImageIcon = new ImageIcon(Bird.class.getResource("/kfc.png"));
private static long deadTime = 5_000;
protected int ImageH = 50;
protected int ImageW = 50;
public boolean isOutOfX() {
return outOfX;
}
public boolean isOutOfY() {
return outOfY;
}
private boolean outOfX = false;
private boolean outOfY = false;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Bird bird = (Bird) o;
return ID == bird.ID;
}
@Override
public int hashCode() {
return Objects.hash(ID);
}
public long getID() {
return ID;
}
public Bird() {
do {
ID = random.nextInt(Integer.MAX_VALUE);
} while (ID_SET.contains(ID));
ID_SET.add(ID);
}
public Bird(Dimension frameSize, Dimension imageSize) {
this();
setImageSize(imageSize);
Random rng = new Random();
x = rng.nextInt(frameSize.width - ImageW);
y = rng.nextInt(frameSize.height - ImageH);
}
public Bird(Dimension frameSize, ImageIcon imageIcon, Dimension imageSize) {
this(frameSize, imageSize);
this.imageIcon = imageIcon;
}
public ImageIcon getImageIcon() {
return imageIcon;
}
public void setImageIcon(ImageIcon imageIcon) {
this.imageIcon = imageIcon;
}
public void setImageSize(Dimension imageSize) {
this.ImageH = imageSize.height;
this.ImageW = imageSize.width;
}
public abstract long getLifeTime();
public boolean isDead() {
return isDead;
}
public void getKilled() {
vX = 0;
vY = 0;
setImageSize(new Dimension(50, 65));
isDead = true;
setImageIcon(DeadImageIcon);
}
public long getDeadTime() {
return deadTime;
}
public static void IDsRemoveAll(Collection<Long> c) {
ID_SET.removeAll(c);
}
@Override
public void paint(Graphics g) {
if ((x < 0 || (x >= g.getClipBounds().width - ImageW)) && !isDead && !stopped) {
outOfX = true;
getStopped();
} else outOfX = false;
if ((y < 0 || y >= g.getClipBounds().height - ImageH) && !isDead && !stopped) {
outOfY = true;
getStopped();
} else outOfY = false;
g.drawImage(imageIcon.getImage(), x, y, ImageW, ImageH, null);
}
@Override
public String toString() {
return "Bird{" +
"x=" + x +
", y=" + y +
", ID=" + ID +
'}';
}
private void getStopped() {
vX *= -1;
vY *= -1;
move();
stopped = true;
vX = vY = 0;
}
public void move() {
x += vX;
y += vY;
}
public int getVX() {
return vX;
}
public int getVY() {
return vY;
}
}
| true |
b66ca6eb052c75a9c7420754431bd90a1479ec4b
|
Java
|
heidisu/mlworkshop
|
/common/src/main/java/no/kantega/mlworkshop/submission/TaskSubmission.java
|
UTF-8
| 488 | 2.046875 | 2 |
[] |
no_license
|
package no.kantega.mlworkshop.submission;
import java.util.List;
public class TaskSubmission {
private String name;
private List<Prediction> predictions;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Prediction> getPredictions() {
return predictions;
}
public void setPredictions(List<Prediction> predictions) {
this.predictions = predictions;
}
}
| true |
8787d30ab725de155f53676c6c2a8530b6e91dfe
|
Java
|
FRC3683/FRC-2019-Public
|
/src/main/java/frc/robot/subsystems/Arm.java
|
UTF-8
| 7,227 | 1.96875 | 2 |
[] |
no_license
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 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.subsystems;
import com.ctre.phoenix.motorcontrol.ControlMode;
import com.ctre.phoenix.motorcontrol.can.VictorSPX;
import edu.wpi.first.networktables.NetworkTableEntry;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard;
import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardTab;
import frc.robot.Robot;
import frc.robot.commands.ArmOpenLoop;
import frc.robot.commands.ArmWristTeleopControl;
import frc.robot.config.Config;
import frc.robot.config.Constants;
import frc.robot.utils.DaveDigitalInput;
import frc.robot.utils.MathUtils;
import frc.robot.utils.PID;
public class Arm extends Subsystem {
private static Arm instance;
private VictorSPX mLeft;
private VictorSPX mRight;
private Encoder mEnc;
private DaveDigitalInput mHome;
private State currentState;
private State targetState;
private State lastState;
private PID mPID;
private double output;
private ShuffleboardTab tab;
private NetworkTableEntry armAngle;
private NetworkTableEntry armOutputEntry;
private NetworkTableEntry armAtHome;
private NetworkTableEntry currentStateData;
private NetworkTableEntry targetStateData;
private NetworkTableEntry targetPosition;
public enum State{
OPEN_LOOP("OPEN_LOOP", 0),
DISC_HP("DISC_HP", Constants.armIntakeDiscPos),
BALL_HP("BALL_HP", Constants.armIntakeBallHP),
BALL_FLOOR("BALL_FLOOR", Constants.armIntakeBallFloor),
LOADED_STOWED("LOADED_STOWED", Constants.armHoldingGamePiece),
STOWED("STOWED", Constants.armStowedPos),
DISC_LOW("DISC_LOW", Constants.armScoreDisc1),
DISC_MID("DISC_MID", Constants.armScoreDisc2),
DISC_HIGH("DISC_HIGH", Constants.armScoreDisc3),
BALL_LOW("BALL_LOW", Constants.armScoreBall1),
BALL_MID("BALL_MID", Constants.armScoreBall2),
BALL_HIGH("BALL_HIGH", Constants.armScoreBall3),
BALL_CARGO("BALL_CARGO", Constants.armScoreBallCargo),
CLIMB_SETUP("CLIMB_SETUP", Constants.armClimbSetup),
CLIMB("CLIMB", Constants.armClimb),
DISABLED("DISABLED", 0);
private String name;
private double setpoint;
private State(String nString, double num){
name = nString;
setpoint = num;
}
public String getName(){
return name;
}
public double getSetpoint() {
return setpoint;
}
}
public static Arm getInstance() {
if (instance == null) {
instance = new Arm(Robot.m_cfg);
}
return instance;
}
private Arm(Config cfg){
mLeft = cfg.getArmMotorLeft();
mRight = cfg.getArmMotorRight();
mEnc = cfg.getArmEncoder();
mHome = cfg.getArmHomeSensor();
currentState = State.STOWED;
targetState = State.STOWED;
lastState = State.STOWED;
mPID = new PID(Constants.armKP,Constants.armKI,Constants.armKD, Constants.armTol);
output = 0.0;
mEnc.reset();
tab = Shuffleboard.getTab(Constants.SuperStructureTabName);
tab.add("Encoder", mEnc);
armAngle = tab.add("Arm Angle", 0).getEntry();
armAtHome = tab.add("Arm at Home", false).getEntry();
currentStateData = tab.add("Arm Current State", currentState.getName()).getEntry();
targetStateData = tab.add("Arm Target State", targetState.getName()).getEntry();
targetPosition = tab.add("Target Arm Position", targetState.getSetpoint()).getEntry();
armOutputEntry = tab.add("Arm output", output).getEntry();
}
@Override
public void initDefaultCommand() {
setDefaultCommand(new ArmWristTeleopControl());
}
public void handleState(){
switch (targetState){
case DISC_HP:
case BALL_HP:
case BALL_FLOOR:
case LOADED_STOWED:
case STOWED:
case DISC_LOW:
case DISC_MID:
case DISC_HIGH:
case BALL_LOW:
case BALL_MID:
case BALL_HIGH:
case BALL_CARGO:
case CLIMB_SETUP:
case CLIMB:
handleCLOSED_LOOP();
break;
case DISABLED:
handleDISABLED();
break;
case OPEN_LOOP:
handleOPEN_LOOP();
break;
}
}
private void handleOPEN_LOOP(){
currentState = State.OPEN_LOOP;
}
private void handleCLOSED_LOOP(){
mPID.setTarget(targetState.getSetpoint());
setOutput(mPID.calculate(getAngle()));
if(Math.abs(getAngle() - targetState.getSetpoint()) <= 5){
currentState = targetState;
}
}
private void handleDISABLED(){
if(currentState != State.DISABLED){
lastState = currentState;
}
currentState = State.DISABLED;
setOutput(0);
}
public State getCurrentState(){
return currentState;
}
public State getTargetState(){
return targetState;
}
public State getLastState(){
return lastState;
}
public void setTargetState(State state){
targetState = state;
}
public void runMotors (double power){
mLeft.set(ControlMode.PercentOutput, -power);
mRight.set(ControlMode.PercentOutput, power);
}
public double getAngle(){
return mEnc.getDistance() + Constants.armHomeOffset;
}
public double getAngularVelocity(){
return mEnc.getRate();
}
public boolean isAtHome(){
return !mHome.get();
}
public boolean EnteredHome(){
return mHome.getTriggered();
}
public boolean staggerReady(){
if(targetState == State.DISC_MID)
return Math.abs(getAngle() - targetState.getSetpoint()) <= Constants.armStaggerThresholdMid;
else
return Math.abs(getAngle() - targetState.getSetpoint()) <= Constants.armStaggerThreshold;
}
public void zeroEncoder() {
mEnc.reset();
}
public void setOutput(double power){
output = power;
}
private void sendToDashboard(){
armAngle.setDouble(getAngle());
armAtHome.setBoolean(isAtHome());
currentStateData.setString(currentState.getName());
targetStateData.setString(targetState.getName());
targetPosition.setDouble(targetState.getSetpoint());
armOutputEntry.setDouble(output);
}
@Override
public void periodic() {
handleState();
mHome.update();
if(targetState == State.CLIMB){
if(output <= -0.65) {
output = -0.65;
}
}
if(targetState == State.BALL_LOW) {
if (Math.abs(output) > 0.4) {
output = Math.signum(output)*0.4;
}
}
if (getAngle() <= Constants.armThrottleThreshold && output < 0 && targetState==State.STOWED){
double alpha = MathUtils.unlerp(Constants.armThrottleThreshold, Constants.armHomeOffset, getAngle());
if(output <= -0.5) {
output = -0.5;
}//MathUtils.lerp(0.7, 0.4, alpha);
}
if(EnteredHome() && (currentState == State.OPEN_LOOP || currentState == State.DISABLED)){
zeroEncoder();
}
if(isAtHome()){
if(output <= 0) {
output = 0;
}
}
if(getAngle() <= Constants.armHomeOffset){
if(currentState == State.OPEN_LOOP){
if(output <= -0.3) {
output = -0.3;
}
}
else{
if(output <= 0) {
output = 0;
}
}
}
if (getAngle() >= Constants.armUpperLimit){
if(output > 0) {
output = 0;
}
}
runMotors(output);
sendToDashboard();
}
}
| true |
f1112f57aa12fc289d052a16bdc346de39720cfc
|
Java
|
gbaufake/hawkular-agent
|
/hawkular-javaagent/src/main/java/org/hawkular/agent/javaagent/cmd/UpdateCollectionIntervalsCommand.java
|
UTF-8
| 9,498 | 1.5625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2015-2017 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.hawkular.agent.javaagent.cmd;
import java.util.Map;
import org.hawkular.agent.javaagent.JavaAgentEngine;
import org.hawkular.agent.javaagent.config.Configuration;
import org.hawkular.agent.javaagent.config.DMRAvail;
import org.hawkular.agent.javaagent.config.DMRAvailSet;
import org.hawkular.agent.javaagent.config.DMRMetric;
import org.hawkular.agent.javaagent.config.DMRMetricSet;
import org.hawkular.agent.javaagent.config.JMXAvail;
import org.hawkular.agent.javaagent.config.JMXAvailSet;
import org.hawkular.agent.javaagent.config.JMXMetric;
import org.hawkular.agent.javaagent.config.JMXMetricSet;
import org.hawkular.agent.javaagent.config.TimeUnits;
import org.hawkular.agent.javaagent.log.JavaAgentLoggers;
import org.hawkular.agent.javaagent.log.MsgLogger;
import org.hawkular.agent.monitor.cmd.AbstractJMXResourcePathCommand;
import org.hawkular.agent.monitor.cmd.CommandContext;
import org.hawkular.agent.monitor.cmd.CommandContext.ResponseSentListener;
import org.hawkular.agent.monitor.config.AgentCoreEngineConfiguration.AbstractEndpointConfiguration;
import org.hawkular.agent.monitor.inventory.MonitoredEndpoint;
import org.hawkular.agent.monitor.protocol.EndpointService;
import org.hawkular.agent.monitor.protocol.jmx.JMXNodeLocation;
import org.hawkular.agent.monitor.protocol.jmx.JMXSession;
import org.hawkular.bus.common.BasicMessage;
import org.hawkular.bus.common.BasicMessageWithExtraData;
import org.hawkular.bus.common.BinaryData;
import org.hawkular.cmdgw.api.UpdateCollectionIntervalsRequest;
import org.hawkular.cmdgw.api.UpdateCollectionIntervalsResponse;
/**
* Update the specified metric and avail type collection intervals.
* Because metric types are not guaranteed to be consistent across agents, it is
* not a failure if a requested metric type does not exist.
*
* Note that this really doesn't involve JMX but it makes more sense to extend the JMX superclass
* rather than extend the DMR one or to write a command from scratch.
*
* @author Jay Shaughnessy
* @author John Mazzitelli
*/
public class UpdateCollectionIntervalsCommand
extends AbstractJMXResourcePathCommand<UpdateCollectionIntervalsRequest, UpdateCollectionIntervalsResponse> {
private static final MsgLogger log = JavaAgentLoggers.getLogger(UpdateCollectionIntervalsCommand.class);
public static final Class<UpdateCollectionIntervalsRequest> REQUEST_CLASS = UpdateCollectionIntervalsRequest.class;
public UpdateCollectionIntervalsCommand() {
super("Update Collection Intervals", "Agent[JMX]");
}
@Override
protected UpdateCollectionIntervalsResponse createResponse() {
return new UpdateCollectionIntervalsResponse();
}
@Override
protected BinaryData execute(
EndpointService<JMXNodeLocation, JMXSession> endpointService,
String resourceId,
BasicMessageWithExtraData<UpdateCollectionIntervalsRequest> envelope,
UpdateCollectionIntervalsResponse response,
CommandContext context) throws Exception {
// we can cast this because we know our command implementation is only ever installed in a JavaAgentEngine
JavaAgentEngine javaAgent = (JavaAgentEngine) context.getAgentCoreEngine();
Configuration javaAgentConfig = javaAgent.getConfigurationManager().getConfiguration();
UpdateCollectionIntervalsRequest request = envelope.getBasicMessage();
Map<String, String> metricTypes = request.getMetricTypes();
Map<String, String> availTypes = request.getAvailTypes();
boolean requireRestart = false;
if (metricTypes != null && !metricTypes.isEmpty()) {
NEXT_AVAIL: for (Map.Entry<String, String> entry : metricTypes.entrySet()) {
String metricTypeId = entry.getKey();
String[] names = parseMetricTypeId(metricTypeId);
String metricSetName = names[0];
String metricName = names[1];
// find the metric and change its interval if found
for (DMRMetricSet metricSet : javaAgentConfig.getDmrMetricSets()) {
if (metricSetName.equals(metricSet.getName())) {
for (DMRMetric metric : metricSet.getDmrMetrics()) {
if (metricName.equals(metric.getName())) {
metric.setInterval(Integer.valueOf(entry.getValue()));
metric.setTimeUnits(TimeUnits.seconds); // the command always assumes seconds
requireRestart = true;
continue NEXT_AVAIL;
}
}
}
}
for (JMXMetricSet metricSet : javaAgentConfig.getJmxMetricSets()) {
if (metricSetName.equals(metricSet.getName())) {
for (JMXMetric metric : metricSet.getJmxMetrics()) {
if (metricName.equals(metric.getName())) {
metric.setInterval(Integer.valueOf(entry.getValue()));
metric.setTimeUnits(TimeUnits.seconds); // the command always assumes seconds
requireRestart = true;
continue NEXT_AVAIL;
}
}
}
}
}
}
if (availTypes != null && !availTypes.isEmpty()) {
NEXT_AVAIL: for (Map.Entry<String, String> entry : availTypes.entrySet()) {
String availTypeId = entry.getKey();
String[] names = parseAvailTypeId(availTypeId);
String availSetName = names[0];
String availName = names[1];
// find the avail and change its interval if found
for (DMRAvailSet availSet : javaAgentConfig.getDmrAvailSets()) {
if (availSetName.equals(availSet.getName())) {
for (DMRAvail avail : availSet.getDmrAvails()) {
if (availName.equals(avail.getName())) {
avail.setInterval(Integer.valueOf(entry.getValue()));
avail.setTimeUnits(TimeUnits.seconds); // the command always assumes seconds
requireRestart = true;
continue NEXT_AVAIL;
}
}
}
}
for (JMXAvailSet availSet : javaAgentConfig.getJmxAvailSets()) {
if (availSetName.equals(availSet.getName())) {
for (JMXAvail avail : availSet.getJmxAvails()) {
if (availName.equals(avail.getName())) {
avail.setInterval(Integer.valueOf(entry.getValue()));
avail.setTimeUnits(TimeUnits.seconds); // the command always assumes seconds
requireRestart = true;
continue NEXT_AVAIL;
}
}
}
}
}
}
if (requireRestart) {
context.addResponseSentListener(new ResponseSentListener() {
@Override
public void onSend(BasicMessageWithExtraData<? extends BasicMessage> response, Exception sendError) {
log.info("Collection intervals updated. Persisting changes and restarting agent.");
javaAgent.stopHawkularAgent();
javaAgent.startHawkularAgent(javaAgentConfig);
}
});
} else {
log.debug("Skipping collection interval update, no valid type updates provided.");
}
return null;
}
@Override
protected void validate(BasicMessageWithExtraData<UpdateCollectionIntervalsRequest> envelope,
MonitoredEndpoint<? extends AbstractEndpointConfiguration> endpoint) {
return; // no-op
}
private String[] parseMetricTypeId(String metricTypeId) {
String[] names = metricTypeId.split("~");
if (names.length != 2) {
throw new IllegalArgumentException(
"MetricTypeId must be of form MetricTypeSetName~MetricTypeName: " + metricTypeId);
}
return names;
}
private String[] parseAvailTypeId(String availTypeId) {
String[] names = availTypeId.split("~");
if (names.length != 2) {
throw new IllegalArgumentException(
"AvailTypeId must be of form AvailTypeSetName~AvailTypeName: " + availTypeId);
}
return names;
}
}
| true |
4728b996c7dd7f299f01dc428bf3150089228153
|
Java
|
ozubk/java_auto
|
/addressbook-web-tests/src/test/java/ru/stqa/auto/addressbook/tests/ContactCreationTests.java
|
UTF-8
| 582 | 1.96875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package ru.stqa.auto.addressbook.tests;
import org.testng.annotations.Test;
import ru.stqa.auto.addressbook.model.ContactData;
public class ContactCreationTests extends TestBase {
@Test
public void testContactCreation() {
app.getNavigationHelper().gotoHomePage();
app.getContactHelper().initContactCreation();
app.getContactHelper().fillContactForm(new ContactData("Test name1", "Test last name1",
"1-111-111", "1-111-111-11-11", "[email protected]", "test1"), true);
app.getContactHelper().submitContactCreation();
app.getNavigationHelper().gotoHomePage();
}
}
| true |
1812b05f0173646e620d5ce2e47c5868f7fb31d7
|
Java
|
Freudzhu/weibo
|
/src/main/java/com/zhuhaihuan/dao/IUserDAO.java
|
UTF-8
| 280 | 1.929688 | 2 |
[] |
no_license
|
package com.zhuhaihuan.dao;
import java.util.List;
import com.zhuhaihuan.domain.User;
public interface IUserDAO {
public boolean add(User user);
public User getUser(User user);
public List<User> searchUser(String username);
public String findUidByUsername(String username);
}
| true |
815a990e1d144d2a5cc11e16a74fe36299c940bb
|
Java
|
RockychengJson/eclipsender
|
/com.ibm.gers.mailviewer/src/com/ibm/gers/mailviewer/editors/AttachementsLabelProvider.java
|
UTF-8
| 995 | 1.9375 | 2 |
[] |
no_license
|
package com.ibm.gers.mailviewer.editors;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import com.ibm.gers.mailviewer.Activator;
import exs.serv.WCMailAttachment;
public class AttachementsLabelProvider extends LabelProvider implements ITableLabelProvider {
public String getColumnText(Object obj, int index) {
if (obj instanceof WCMailAttachment) {
return ((WCMailAttachment)obj).getFileName();
}
return obj.toString();
}
public Image getColumnImage(Object obj, int index) {
if (obj instanceof WCMailAttachment) {
String fileName = ((WCMailAttachment)obj).getFileName();
if (fileName != null) {
return Activator.getImageByExt(Activator.getFileFix(fileName, Activator.SUFFIX));
}
return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
}
return null;
}
}
| true |
a98716ddd6ff97e8e1dfb43a96164cbad369c6bc
|
Java
|
Mbote-Joseph/Java-Collection
|
/Test/RemoveBottomStack.java
|
UTF-8
| 1,205 | 3.859375 | 4 |
[] |
no_license
|
package Test;
public class RemoveBottomStack<E> extends StackGenericArray<E>{
@SuppressWarnings("unchecked")
public StackGenericArray<E> removeBottom(){
// get the size of the stack ('super' is reference variable used to refer to parent class object)
int size = super.stackSize();
// create a temporary StackGenericArray to store the elements of stack in reverse
StackGenericArray<E> temp = new StackGenericArray<E>(size);
// the top element at first is null (it is not useful to us)
super.pop();
// pop the element from stack and push it to temporary StackGenericArray
for (int i=0; i < size; i++){
temp.push(super.pop());
}
// At this point, the temp contains elements of stack in reverse (for example, if 'a' was at botttom of stack, then 'a' is at top of temp)
//
// pop top element of temp (i.e bottom element of stack)
temp.pop();
// push the remaining elements from temp to stack
for (int i=0; i < size-1; i++ ){
super.push(temp.pop());
}
// return the parent class object
return this;
}
}
// End of the class
| true |
2279ead6dd9d768bfe2e5bb5a7b9d88ca10150fd
|
Java
|
wyrover/jensoft-core
|
/src/main/java/org/jensoft/core/plugin/bubble/Bubble.java
|
UTF-8
| 4,745 | 2.65625 | 3 |
[] |
no_license
|
/*
* Copyright (c) JenSoft API
* This source file is part of JenSoft API, All rights reserved.
* JENSOFT PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package org.jensoft.core.plugin.bubble;
import java.awt.Color;
import java.awt.Shape;
import org.jensoft.core.plugin.bubble.painter.BubbleDraw;
import org.jensoft.core.plugin.bubble.painter.BubbleEffect;
import org.jensoft.core.plugin.bubble.painter.BubbleFill;
/**
* Bubble <br>
* <center><img src="doc-files/bubble1.png"></center> <br>
*
* @see BubblePlugin
* @see BubbleDraw
* @see BubbleFill
* @see BubbleEffect
* @author Sebastien Janaud
*/
public class Bubble {
/** center x coordinate */
private double x;
/** center y coordinate */
private double y;
/** radius */
private double radius;
/** theme color */
private Color themeColor;
/** bubble draw */
private BubbleDraw bubbleDraw;
/** bubble fill */
private BubbleFill bubbleFill;
/** bubble effect */
private BubbleEffect bubbleEffect;
/** bubble shape */
private Shape bubbleShape;
/** bubble host plugin */
private BubblePlugin host;
/**
* create bubble with specified parameters
*
* @param x
* the center x coordinate to set
* @param y
* the center y coordinate to set
* @param radius
* the bubble radius to set
* @param themeColor
* the bubble theme color to set
*/
public Bubble(double x, double y, double radius, Color themeColor) {
super();
this.x = x;
this.y = y;
this.radius = radius;
this.themeColor = themeColor;
}
/**
* get bubble shape
*
* @return the bubble shape
*/
public Shape getBubbleShape() {
return bubbleShape;
}
/**
* set bubble shape
*
* @param bubbleShape
* the shape to set
*/
public void setBubbleShape(Shape bubbleShape) {
this.bubbleShape = bubbleShape;
}
/**
* get host plugin
*
* @return host plugin
*/
public BubblePlugin getHost() {
return host;
}
/**
* set host plugin
*
* @param host
* the host plugin to set
*/
public void setHost(BubblePlugin host) {
this.host = host;
}
/**
* get center x coordinate
*
* @return center x coordinate
*/
public double getX() {
return x;
}
/**
* set center x coordinate
*
* @param x
* the center x coordinate to set
*/
public void setX(double x) {
this.x = x;
}
/**
* get center y coordinate
*
* @return center y
*/
public double getY() {
return y;
}
/**
* set center y coordinate
*
* @param y
* the y coordinate to set
*/
public void setY(double y) {
this.y = y;
}
/**
* get bubble radius
*
* @return the bubble radius
*/
public double getRadius() {
return radius;
}
/**
* set radius
*
* @param radius
* radius to set
*/
public void setRadius(double radius) {
this.radius = radius;
}
/**
* get theme color
*
* @return theme color
*/
public Color getThemeColor() {
return themeColor;
}
/**
* set theme color
*
* @param themeColor
* theme color to set
*/
public void setThemeColor(Color themeColor) {
this.themeColor = themeColor;
}
/**
* get bubble draw
*
* @return draw
*/
public BubbleDraw getBubbleDraw() {
return bubbleDraw;
}
/**
* set bubble draw
*
* @param bubbleDraw
* the draw to set
*/
public void setBubbleDraw(BubbleDraw bubbleDraw) {
this.bubbleDraw = bubbleDraw;
}
/**
* get bubble fill
*
* @return fill
*/
public BubbleFill getBubbleFill() {
return bubbleFill;
}
/**
* set bubble fill
*
* @param bubbleFill
* the fill to set
*/
public void setBubbleFill(BubbleFill bubbleFill) {
this.bubbleFill = bubbleFill;
}
/**
* get bubble effect
*
* @return effect
*/
public BubbleEffect getBubbleEffect() {
return bubbleEffect;
}
/**
* set bubble effect
*
* @param bubbleEffect
* the bubble effect to set
*/
public void setBubbleEffect(BubbleEffect bubbleEffect) {
this.bubbleEffect = bubbleEffect;
}
}
| true |
a4b67e963fd1fdd6a36bf50e76952136882f83b3
|
Java
|
amantewary/Elo-Community-Based-Product-Reviewing-Android-Application
|
/app/src/main/java/group/hashtag/projectelo/Activities/ForgotPassword.java
|
UTF-8
| 4,948 | 2.21875 | 2 |
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT",
"Apache-2.0"
] |
permissive
|
package group.hashtag.projectelo.Activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import group.hashtag.projectelo.R;
/**
* Created by nikhilkamath on 01/03/18.
* This class helps user to set password.
*/
public class ForgotPassword extends AppCompatActivity {
private TextInputLayout forgotEmail;
private EditText forgotEmailEditText;
private Button forgotButton;
/**
* Adapted from:Validation code taken from:- https://stackoverflow.com/a/6119777/3966666
* @param email
* @return
*/
public static boolean isEmailValid(String email) {
String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.forgot_password);
final FirebaseAuth auth = FirebaseAuth.getInstance();
forgotEmail = findViewById(R.id.input_layout_email_forgot);
forgotEmailEditText = findViewById(R.id.forgot_email);
forgotButton = findViewById(R.id.button_forgot_password);
forgotEmailEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if (!b) {
hideKeyboard(view);
}
}
});
forgotButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
if (forgotEmailEditText.getText().toString().equals("")) {
forgotEmail.setError("Don't leave this field empty");
} else if (!isEmailValid(forgotEmailEditText.getText().toString())) {
forgotEmail.setError("Please enter a valid email Id");
} else {
auth.sendPasswordResetEmail(forgotEmailEditText.getText().toString())
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.e(ForgotPassword.class.getCanonicalName(), "Email sent.");
forgotEmail.setError("");
//Add a snackbar
hideKeyboard(view);
Snackbar loginGuide = Snackbar.make(findViewById(R.id.linear_layout_forgot_password),
"Go back to login screen", Snackbar.LENGTH_INDEFINITE);
loginGuide.setAction("Okay!", new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
finish();
}
});
loginGuide.setActionTextColor(getResources().getColor(R.color.colorPrimary));
loginGuide.show();
}
}
});
}
}
});
}
/**
* Adapted from: https://stackoverflow.com/a/19828165/3966666
* @param view
*/
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
| true |
a58368cdbded1557a27e875abc7225ab4f0c2e04
|
Java
|
Allitter/final-task-hr
|
/src/main/java/com/epam/hr/domain/controller/command/impl/resume/page/ResumeInfoCommand.java
|
UTF-8
| 1,416 | 2.09375 | 2 |
[] |
no_license
|
package com.epam.hr.domain.controller.command.impl.resume.page;
import com.epam.hr.domain.controller.Router;
import com.epam.hr.domain.controller.command.Attributes;
import com.epam.hr.domain.controller.command.Pages;
import com.epam.hr.domain.controller.command.impl.resume.AbstractResumeCommand;
import com.epam.hr.domain.model.Resume;
import com.epam.hr.domain.model.User;
import com.epam.hr.domain.service.ResumeService;
import com.epam.hr.domain.service.UserService;
import com.epam.hr.exception.ServiceException;
import javax.servlet.http.HttpServletRequest;
public class ResumeInfoCommand extends AbstractResumeCommand {
private final ResumeService resumeService;
private final UserService userService;
public ResumeInfoCommand(ResumeService resumeService, UserService userService) {
this.resumeService = resumeService;
this.userService = userService;
}
@Override
public Router execute(HttpServletRequest request) throws ServiceException {
long idResume = Long.parseLong((String) request.getAttribute(Attributes.RESUME_ID));
Resume resume = resumeService.tryFindById(idResume);
long idUser = resume.getIdUser();
User user = userService.tryFindById(idUser);
request.setAttribute(Attributes.RESUME, resume);
request.setAttribute(Attributes.JOB_SEEKER, user);
return Router.forward(Pages.RESUME_INFO);
}
}
| true |
aa10f7b514f46992ac7b271008719d96bf6739e7
|
Java
|
quenton-sh/x-commons-memcached
|
/src/main/java/x/commons/memcached/MemcachedClientFactory.java
|
UTF-8
| 187 | 1.804688 | 2 |
[] |
no_license
|
package x.commons.memcached;
public interface MemcachedClientFactory {
public MemcachedClient getDefaultMemcachedClient();
public MemcachedClient getMemcachedClient(String name);
}
| true |
bb32606e2ba0ccad1af7c1e64f489001449ef208
|
Java
|
ssharkov/LearningJava
|
/src/Learning/Generics/Stats.java
|
UTF-8
| 500 | 3.203125 | 3 |
[] |
no_license
|
package Learning.Generics;
/**
* Created by ssharkov on 25.01.2017.
*/
public class Stats<T extends Number> {
T[] nums;
public Stats(T[] nums) {
this.nums = nums;
}
double average(){
double sum = 0.0;
for (int i = 0; i< nums.length; i++)
sum = sum + nums[i].doubleValue();
return sum / nums.length;
}
boolean sameAvg(Stats<?> ob){
if( average()==ob.average())
return true;
return false;
}
}
| true |
4f4a2a2bf2c2d94111b511f712d8ec8921e13d50
|
Java
|
Kabbej/Springlab
|
/src/test/java/se/iths/springlab/controller/ControllerTest.java
|
UTF-8
| 1,453 | 2.4375 | 2 |
[] |
no_license
|
package se.iths.springlab.controller;
import org.assertj.core.error.ShouldHaveSizeGreaterThanOrEqualTo;
import org.junit.jupiter.api.Test;
import se.iths.springlab.controllers.Controller;
import se.iths.springlab.dto.FootBallPlayerDto;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class ControllerTest {
Controller controller = new Controller(new TestService());
@Test
void checkingOnePlayerById (){
var footballPlayer = controller.getOne(1);
System.out.println(footballPlayer);
}
@Test
void createPlayerTest(){
var newPlayer = controller.createFootballPlayer((new FootBallPlayerDto()));
assertThat(newPlayer.getFirstName()).isEqualTo("Kabbe");
assertThat(newPlayer.getLastName()).isEqualTo("Jartun");
assertThat(newPlayer.getTeam()).isEqualTo("IFK");
}
@Test
void searchPlayer(){
List<FootBallPlayerDto> list = controller.searchByFirstName("Kabbe");
assertEquals(list.size(), 1);
assertThat(list.get(0).getLastName()).isEqualTo("Jartun");
}
@Test
void updatePlayer(){
var player = controller.replace(new FootBallPlayerDto(2,"Test","Test","Test"),1);
assertThat(player.getFirstName()).isEqualTo("Test");
}
}
| true |
1a8ab413459591edb44b2541ec0e1838ed29e8c6
|
Java
|
CleitonCardoso/generic-stack
|
/app/src/main/java/com/genericstack/repositories/InformacoesGeraisRepository.java
|
UTF-8
| 275 | 1.53125 | 2 |
[] |
no_license
|
package com.genericstack.repositories;
import java.util.UUID;
import org.springframework.data.jpa.repository.JpaRepository;
import com.genericstack.models.InformacoesGerais;
public interface InformacoesGeraisRepository extends JpaRepository<InformacoesGerais, UUID> {
}
| true |
1f488e1207775301fd468ed17389162a157f7f78
|
Java
|
balloonmarci/progettoWEB
|
/BryanAir/src/java/controller/PrenotationManager.java
|
UTF-8
| 32,295 | 1.890625 | 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 controller;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.dao.AirportDAO;
import model.dao.CheckInDAO;
import model.dao.ConcreteFlightDAO;
import model.dao.DAOFactory;
import model.dao.PrenotationDAO;
import model.dao.PushedFlightDAO;
import model.dao.VirtualFlightDAO;
import model.mo.Airport;
import model.mo.ConcreteFlight;
import model.mo.Prenotation;
import model.mo.PrenotationView;
import model.mo.PushedFlight;
import model.mo.User;
import model.mo.VirtualFlight;
import model.session.dao.LoggedUserDAO;
import model.session.dao.SessionDAOFactory;
import model.session.mo.LoggedUser;
import org.joda.time.DateTime;
import services.config.Configuration;
import services.logservice.LogService;
/**
*
* @author Filippo
*/
public class PrenotationManager {
private PrenotationManager(){
}
public static void view (HttpServletRequest request, HttpServletResponse response){
Logger logger = LogService.getApplicationLogger();
LoggedUserDAO loggedUserDAO;
LoggedUser loggedUser;
DAOFactory daoFactory = null;
SessionDAOFactory sessionDAOFactory;
sessionDAOFactory = SessionDAOFactory.getSessionDAOFactory(Configuration.SESSION_IMPL);
sessionDAOFactory.initSession(request, response);
loggedUserDAO = sessionDAOFactory.getLoggedUserDAO();
loggedUser = loggedUserDAO.find();
int numeroPosti = Integer.parseInt(request.getParameter("numeroposti"));
String departureFlightCode = request.getParameter("departureflightcode");
DateTime departureFlightDepartureDate = new DateTime(request.getParameter("departureflightdeparturedate"));
DateTime departureFlightArrivalDate = new DateTime(request.getParameter("departureflightarrivaldate"));
String returnFlightCode = request.getParameter("returnflightcode");
DateTime returnFlightDepartureDate = new DateTime(request.getParameter("departuredate"));
DateTime returnFlightArrivalDate = new DateTime(request.getParameter("arrivaldate"));
try{
daoFactory = DAOFactory.getDAOFactory(Configuration.DAO_IMPL);
daoFactory.beginTransaction();
ConcreteFlightDAO concreteFlightDAO = daoFactory.getConcreteFlightDAO();
VirtualFlightDAO virtualFlightDAO = daoFactory.getVirtualFlightDAO();
AirportDAO airportDAO = daoFactory.getAirportDAO();
ConcreteFlight departureFlight = concreteFlightDAO.findByFlightCodeAndDate(departureFlightCode,
departureFlightDepartureDate, departureFlightArrivalDate);
departureFlight.setVirtualFlight(virtualFlightDAO.findByFlightCode(departureFlightCode));
String departureIata = departureFlight.getVirtualFlight().getDepartureAirport().getIata();
String arrivalIata = departureFlight.getVirtualFlight().getArrivalAirport().getIata();
departureFlight.getVirtualFlight().setDepartureAirport(airportDAO.findByIata(departureIata));
departureFlight.getVirtualFlight().setArrivalAirport(airportDAO.findByIata(arrivalIata));
ConcreteFlight returnFlight = concreteFlightDAO.findByFlightCodeAndDate(returnFlightCode,
returnFlightDepartureDate, returnFlightArrivalDate);
returnFlight.setVirtualFlight(virtualFlightDAO.findByFlightCode(returnFlightCode));
departureIata = returnFlight.getVirtualFlight().getDepartureAirport().getIata();
arrivalIata = returnFlight.getVirtualFlight().getArrivalAirport().getIata();
returnFlight.getVirtualFlight().setDepartureAirport(airportDAO.findByIata(departureIata));
returnFlight.getVirtualFlight().setArrivalAirport(airportDAO.findByIata(arrivalIata));
daoFactory.commitTransaction();
request.setAttribute("departureflight", departureFlight);
request.setAttribute("returnflight", returnFlight);
request.setAttribute("numeroposti", numeroPosti);
request.setAttribute("loggedUser", loggedUser);
request.setAttribute("loggedOn", loggedUser != null);
request.setAttribute("applicationMessage", null);
request.setAttribute("viewUrl", "prenotationManager/view");
}catch(Exception e){
logger.log(Level.SEVERE, "Controller Error", e);
try {
if(daoFactory != null){
daoFactory.rollbackTransaction();
}
}catch (Throwable t){
}
throw new RuntimeException(e);
} finally {
try {
if(daoFactory != null) {
daoFactory.closeTransaction();
}
}catch(Throwable t){
}
}
}
public static void onlyDepartureView (HttpServletRequest request, HttpServletResponse response){
Logger logger = LogService.getApplicationLogger();
LoggedUserDAO loggedUserDAO;
LoggedUser loggedUser;
DAOFactory daoFactory = null;
SessionDAOFactory sessionDAOFactory;
sessionDAOFactory = SessionDAOFactory.getSessionDAOFactory(Configuration.SESSION_IMPL);
sessionDAOFactory.initSession(request, response);
loggedUserDAO = sessionDAOFactory.getLoggedUserDAO();
loggedUser = loggedUserDAO.find();
int numeroPosti = Integer.parseInt(request.getParameter("numeroposti"));
String flightCode = request.getParameter("flightcode");
DateTime departureDate = new DateTime(request.getParameter("departuredate"));
DateTime arrivalDate = new DateTime(request.getParameter("arrivaldate"));
try{
daoFactory = DAOFactory.getDAOFactory(Configuration.DAO_IMPL);
daoFactory.beginTransaction();
ConcreteFlightDAO concreteFlightDAO = daoFactory.getConcreteFlightDAO();
VirtualFlightDAO virtualFlightDAO = daoFactory.getVirtualFlightDAO();
AirportDAO airportDAO = daoFactory.getAirportDAO();
ConcreteFlight selectedFlight = concreteFlightDAO.findByFlightCodeAndDate(flightCode,
departureDate, arrivalDate);
selectedFlight.setVirtualFlight(virtualFlightDAO.findByFlightCode(flightCode));
String departureIata = selectedFlight.getVirtualFlight().getDepartureAirport().getIata();
String arrivalIata = selectedFlight.getVirtualFlight().getArrivalAirport().getIata();
selectedFlight.getVirtualFlight().setDepartureAirport(airportDAO.findByIata(departureIata));
selectedFlight.getVirtualFlight().setArrivalAirport(airportDAO.findByIata(arrivalIata));
daoFactory.commitTransaction();
request.setAttribute("departureflight", selectedFlight);
request.setAttribute("numeroposti", numeroPosti);
request.setAttribute("loggedUser", loggedUser);
request.setAttribute("loggedOn", loggedUser != null);
request.setAttribute("applicationMessage", null);
request.setAttribute("viewUrl", "prenotationManager/view");
}catch(Exception e){
logger.log(Level.SEVERE, "Controller Error", e);
try {
if(daoFactory != null){
daoFactory.rollbackTransaction();
}
}catch (Throwable t){
}
throw new RuntimeException(e);
} finally {
try {
if(daoFactory != null) {
daoFactory.closeTransaction();
}
}catch(Throwable t){
}
}
}
public static void onlyDepartureViewMillis (HttpServletRequest request, HttpServletResponse response){
Logger logger = LogService.getApplicationLogger();
LoggedUserDAO loggedUserDAO;
LoggedUser loggedUser;
DAOFactory daoFactory = null;
SessionDAOFactory sessionDAOFactory;
sessionDAOFactory = SessionDAOFactory.getSessionDAOFactory(Configuration.SESSION_IMPL);
sessionDAOFactory.initSession(request, response);
loggedUserDAO = sessionDAOFactory.getLoggedUserDAO();
loggedUser = loggedUserDAO.find();
int numeroPosti = Integer.parseInt(request.getParameter("numeroposti"));
String flightCode = request.getParameter("flightcode");
DateTime departureDate = new DateTime(Long.parseLong(request.getParameter("departuredate")));
DateTime arrivalDate = new DateTime(Long.parseLong(request.getParameter("arrivaldate")));
try{
daoFactory = DAOFactory.getDAOFactory(Configuration.DAO_IMPL);
daoFactory.beginTransaction();
ConcreteFlightDAO concreteFlightDAO = daoFactory.getConcreteFlightDAO();
VirtualFlightDAO virtualFlightDAO = daoFactory.getVirtualFlightDAO();
AirportDAO airportDAO = daoFactory.getAirportDAO();
ConcreteFlight selectedFlight = concreteFlightDAO.findByFlightCodeAndDate(flightCode,
departureDate, arrivalDate);
selectedFlight.setVirtualFlight(virtualFlightDAO.findByFlightCode(flightCode));
String departureIata = selectedFlight.getVirtualFlight().getDepartureAirport().getIata();
String arrivalIata = selectedFlight.getVirtualFlight().getArrivalAirport().getIata();
selectedFlight.getVirtualFlight().setDepartureAirport(airportDAO.findByIata(departureIata));
selectedFlight.getVirtualFlight().setArrivalAirport(airportDAO.findByIata(arrivalIata));
daoFactory.commitTransaction();
request.setAttribute("departureflight", selectedFlight);
request.setAttribute("numeroposti", numeroPosti);
request.setAttribute("loggedUser", loggedUser);
request.setAttribute("loggedOn", loggedUser != null);
request.setAttribute("applicationMessage", null);
request.setAttribute("viewUrl", "prenotationManager/view");
}catch(Exception e){
logger.log(Level.SEVERE, "Controller Error", e);
try {
if(daoFactory != null){
daoFactory.rollbackTransaction();
}
}catch (Throwable t){
}
throw new RuntimeException(e);
} finally {
try {
if(daoFactory != null) {
daoFactory.closeTransaction();
}
}catch(Throwable t){
}
}
}
public static void createPrenotation(HttpServletRequest request, HttpServletResponse response){
Logger logger = LogService.getApplicationLogger();
LoggedUserDAO loggedUserDAO;
LoggedUser loggedUser;
DAOFactory daoFactory = null;
SessionDAOFactory sessionDAOFactory;
Prenotation prenotation;
try{
sessionDAOFactory = SessionDAOFactory.getSessionDAOFactory(Configuration.SESSION_IMPL);
sessionDAOFactory.initSession(request, response);
loggedUserDAO = sessionDAOFactory.getLoggedUserDAO();
loggedUser = loggedUserDAO.find();
int numeroPosti = Integer.parseInt(request.getParameter("numeroposti"));
int departureClass = Integer.parseInt(request.getParameter("departureclass"));
float departurePrice = Float.parseFloat(request.getParameter("departureprice"));
ConcreteFlight departureFlight = new ConcreteFlight();
departureFlight.setVirtualFlight(new VirtualFlight());
departureFlight.getVirtualFlight().setFlightCode(request.getParameter("departureflightcode"));
departureFlight.setDate(new DateTime(request.getParameter("departureflightdeparturedate")));
departureFlight.setArrivalDate(new DateTime(request.getParameter("departureflightarrivaldate")));
int returnClass = Integer.parseInt(request.getParameter("returnclass"));
float returnPrice = Float.parseFloat(request.getParameter("returnprice"));
ConcreteFlight returnFlight = new ConcreteFlight();
returnFlight.setVirtualFlight(new VirtualFlight());
returnFlight.getVirtualFlight().setFlightCode(request.getParameter("returnflightcode"));
returnFlight.setDate(new DateTime(request.getParameter("returnflightdeparturedate")));
returnFlight.setArrivalDate(new DateTime(request.getParameter("returnflightarrivaldate")));
User user = new User();
user.setUserId(loggedUser.getUserId());
List<Prenotation> departurePrenotations = new ArrayList();
for(int i=1; i <= numeroPosti; i++){
prenotation = new Prenotation();
prenotation.setClas(departureClass);
prenotation.setPricetotal(departurePrice);
prenotation.setPassengerfirstname(request.getParameter("passengerfirstname"+i));
prenotation.setPassengerlastname(request.getParameter("passengerlastname"+i));
prenotation.setPassengerTitle(request.getParameter("passengertitle"+i));
prenotation.setPrenotationDate(DateTime.now());
prenotation.setConcreteFlight(departureFlight);
prenotation.setUser(user);
departurePrenotations.add(prenotation);
}
List<Prenotation> returnPrenotations = new ArrayList();
for(int i=0; i < numeroPosti; i++){
prenotation = new Prenotation();
prenotation.setClas(returnClass);
prenotation.setPricetotal(returnPrice);
prenotation.setPassengerfirstname(departurePrenotations.get(i).getPassengerfirstname());
prenotation.setPassengerlastname(departurePrenotations.get(i).getPassengerlastname());
prenotation.setPassengerTitle(departurePrenotations.get(i).getPassengerTitle());
prenotation.setPrenotationDate(DateTime.now());
prenotation.setConcreteFlight(returnFlight);
prenotation.setUser(user);
returnPrenotations.add(prenotation);
}
daoFactory = DAOFactory.getDAOFactory(Configuration.DAO_IMPL);
daoFactory.beginTransaction();
PrenotationDAO prenotationDAO = daoFactory.getPrenotationDAO();
prenotationDAO.newPrenotation(departurePrenotations);
prenotationDAO.newPrenotation(returnPrenotations);
ConcreteFlightDAO concreteFlightDAO = daoFactory.getConcreteFlightDAO();
ConcreteFlight concreteDepartureFlight = concreteFlightDAO.findByFlightCodeAndDate(
departureFlight.getVirtualFlight().getFlightCode(), departureFlight.getDate(), departureFlight.getArrivalDate());
ConcreteFlight concreteReturnFlight = concreteFlightDAO.findByFlightCodeAndDate(
returnFlight.getVirtualFlight().getFlightCode(), returnFlight.getDate(), returnFlight.getArrivalDate());
if(departureClass == 1)
concreteDepartureFlight.setSeatFirst(concreteDepartureFlight.getSeatFirst() - numeroPosti);
else
concreteDepartureFlight.setSeatSecond(concreteDepartureFlight.getSeatSecond() - numeroPosti);
if(returnClass == 1)
concreteReturnFlight.setSeatFirst(concreteReturnFlight.getSeatFirst() - numeroPosti);
else
concreteReturnFlight.setSeatSecond(concreteReturnFlight.getSeatSecond() - numeroPosti);
concreteFlightDAO.update(concreteDepartureFlight);
concreteFlightDAO.update(concreteReturnFlight);
commonView(daoFactory, request, loggedUser);
daoFactory.commitTransaction();
request.setAttribute("viewUrl", "homeManager/view");
request.setAttribute("loggedUser", loggedUser);
request.setAttribute("loggedOn", true);
request.setAttribute("applicationMessage", null);
}catch(Exception e){
logger.log(Level.SEVERE, "Controller Error", e);
try {
if(daoFactory != null){
daoFactory.rollbackTransaction();
}
}catch (Throwable t){
}
throw new RuntimeException(e);
} finally {
try {
if(daoFactory != null) {
daoFactory.closeTransaction();
}
}catch(Throwable t){
}
}
}
public static void createOnlyDeparturePrenotation(HttpServletRequest request, HttpServletResponse response){
Logger logger = LogService.getApplicationLogger();
LoggedUserDAO loggedUserDAO;
LoggedUser loggedUser;
DAOFactory daoFactory = null;
SessionDAOFactory sessionDAOFactory;
Prenotation prenotation;
try{
sessionDAOFactory = SessionDAOFactory.getSessionDAOFactory(Configuration.SESSION_IMPL);
sessionDAOFactory.initSession(request, response);
loggedUserDAO = sessionDAOFactory.getLoggedUserDAO();
loggedUser = loggedUserDAO.find();
int numeroPosti = Integer.parseInt(request.getParameter("numeroposti"));
int departureClass = Integer.parseInt(request.getParameter("departureclass"));
float departurePrice = Float.parseFloat(request.getParameter("departureprice"));
ConcreteFlight departureFlight = new ConcreteFlight();
departureFlight.setVirtualFlight(new VirtualFlight());
departureFlight.getVirtualFlight().setFlightCode(request.getParameter("departureflightcode"));
departureFlight.setDate(new DateTime(request.getParameter("departureflightdeparturedate")));
departureFlight.setArrivalDate(new DateTime(request.getParameter("departureflightarrivaldate")));
User user = new User();
user.setUserId(loggedUser.getUserId());
List<Prenotation> prenotations = new ArrayList();
for(int i=1; i <= numeroPosti; i++){
prenotation = new Prenotation();
prenotation.setClas(departureClass);
prenotation.setPricetotal(departurePrice);
prenotation.setPassengerfirstname(request.getParameter("passengerfirstname"+i));
prenotation.setPassengerlastname(request.getParameter("passengerlastname"+i));
prenotation.setPassengerTitle(request.getParameter("passengertitle"+i));
prenotation.setPrenotationDate(DateTime.now());
prenotation.setConcreteFlight(departureFlight);
prenotation.setUser(user);
prenotations.add(prenotation);
}
daoFactory = DAOFactory.getDAOFactory(Configuration.DAO_IMPL);
daoFactory.beginTransaction();
PrenotationDAO prenotationDAO = daoFactory.getPrenotationDAO();
prenotationDAO.newPrenotation(prenotations);
ConcreteFlightDAO concreteFlightDAO = daoFactory.getConcreteFlightDAO();
ConcreteFlight concreteFlight = concreteFlightDAO.findByFlightCodeAndDate(
departureFlight.getVirtualFlight().getFlightCode(), departureFlight.getDate(), departureFlight.getArrivalDate());
if(departureClass == 1)
concreteFlight.setSeatFirst(concreteFlight.getSeatFirst() - numeroPosti);
else
concreteFlight.setSeatSecond(concreteFlight.getSeatSecond() - numeroPosti);
concreteFlightDAO.update(concreteFlight);
commonView(daoFactory, request, loggedUser);
daoFactory.commitTransaction();
request.setAttribute("viewUrl", "homeManager/view");
request.setAttribute("loggedUser", loggedUser);
request.setAttribute("loggedOn", true);
request.setAttribute("applicationMessage", null);
}catch(Exception e){
logger.log(Level.SEVERE, "Controller Error", e);
try {
if(daoFactory != null){
daoFactory.rollbackTransaction();
}
}catch (Throwable t){
}
throw new RuntimeException(e);
} finally {
try {
if(daoFactory != null) {
daoFactory.closeTransaction();
}
}catch(Throwable t){
}
}
}
private static void commonView(DAOFactory daoFactory, HttpServletRequest request, LoggedUser loggedUser){
List<Airport> airports = new ArrayList();
PushedFlightDAO pushedFlightDAO = daoFactory.getPushedFlightDAO();
List<PushedFlight> pushedFlights = pushedFlightDAO.getPushedFlights();
AirportDAO airportDAO = daoFactory.getAirportDAO();
airports = airportDAO.findAllAirport();
List<PushedFlight> wishlist = new ArrayList<PushedFlight>();
if(loggedUser != null){
wishlist = pushedFlightDAO.getWishlist(loggedUser);
}
request.setAttribute("wishlist", wishlist);
request.setAttribute("airports", airports);
request.setAttribute("pushedFlights", pushedFlights);
}
public static void prenotationView(HttpServletRequest request, HttpServletResponse response){
SessionDAOFactory sessionDAOFactory;
DAOFactory daoFactory = null;
LoggedUser loggedUser;
String applicationMessage = null;
Logger logger = LogService.getApplicationLogger();
try{
sessionDAOFactory = SessionDAOFactory.getSessionDAOFactory(Configuration.SESSION_IMPL);
sessionDAOFactory.initSession(request, response);
LoggedUserDAO loggedUserDAO = sessionDAOFactory.getLoggedUserDAO();
loggedUser = loggedUserDAO.find();
daoFactory = DAOFactory.getDAOFactory(Configuration.DAO_IMPL);
daoFactory.beginTransaction();
PrenotationDAO prenotationDAO = daoFactory.getPrenotationDAO();
List<PrenotationView> prenotations = prenotationDAO.findUserPrenotations(loggedUser);
List<PrenotationView> checkPrenotations = prenotationDAO.findUserPrenotationsCheckIn(loggedUser);
daoFactory.commitTransaction();
request.setAttribute("prenotations", prenotations);
request.setAttribute("checkprenotations", checkPrenotations);
request.setAttribute("loggedOn", loggedUser != null);
request.setAttribute("loggedUser", loggedUser);
request.setAttribute("viewUrl", "prenotationManager/prenotations");
}
catch (Exception e) {
logger.log(Level.SEVERE, "Controller Error", e);
try {
if (daoFactory != null) {
daoFactory.rollbackTransaction();
}
}
catch (Throwable t) {
}
throw new RuntimeException(e);
}
finally {
try {
if (daoFactory != null) {
daoFactory.closeTransaction();
}
} catch (Throwable t) {
}
}
}
public static void prenotationViewDetails(HttpServletRequest request, HttpServletResponse response){
SessionDAOFactory sessionDAOFactory;
DAOFactory daoFactory = null;
LoggedUser loggedUser;
String applicationMessage = null;
Logger logger = LogService.getApplicationLogger();
try{
sessionDAOFactory = SessionDAOFactory.getSessionDAOFactory(Configuration.SESSION_IMPL);
sessionDAOFactory.initSession(request, response);
LoggedUserDAO loggedUserDAO = sessionDAOFactory.getLoggedUserDAO();
loggedUser = loggedUserDAO.find();
String flightcode = request.getParameter("flightcode");
DateTime departuredate = new DateTime(Long.parseLong(request.getParameter("departuredate")));
DateTime arrivaldate = new DateTime(Long.parseLong(request.getParameter("arrivaldate")));
int clas = Integer.parseInt(request.getParameter("class"));
DateTime date = new DateTime(Long.parseLong(request.getParameter("date")));
daoFactory = DAOFactory.getDAOFactory(Configuration.DAO_IMPL);
daoFactory.beginTransaction();
PrenotationDAO prenotationDAO = daoFactory.getPrenotationDAO();
List<Prenotation> prenotations = prenotationDAO.findPrenotationDetail(loggedUser, flightcode, departuredate, arrivaldate, clas, date);
daoFactory.commitTransaction();
request.setAttribute("prenotations", prenotations);
request.setAttribute("loggedOn", loggedUser != null);
request.setAttribute("loggedUser", loggedUser);
request.setAttribute("viewUrl", "prenotationManager/prenotationsDetails");
}
catch (Exception e) {
logger.log(Level.SEVERE, "Controller Error", e);
try {
if (daoFactory != null) {
daoFactory.rollbackTransaction();
}
}
catch (Throwable t) {
}
throw new RuntimeException(e);
}
finally {
try {
if (daoFactory != null) {
daoFactory.closeTransaction();
}
} catch (Throwable t) {
}
}
}
public static void prenotationViewCheckIn(HttpServletRequest request, HttpServletResponse response){
SessionDAOFactory sessionDAOFactory;
DAOFactory daoFactory = null;
LoggedUser loggedUser;
String applicationMessage = null;
Logger logger = LogService.getApplicationLogger();
try{
sessionDAOFactory = SessionDAOFactory.getSessionDAOFactory(Configuration.SESSION_IMPL);
sessionDAOFactory.initSession(request, response);
LoggedUserDAO loggedUserDAO = sessionDAOFactory.getLoggedUserDAO();
loggedUser = loggedUserDAO.find();
String flightcode = request.getParameter("flightcode");
DateTime departuredate = new DateTime(Long.parseLong(request.getParameter("departuredate")));
DateTime arrivaldate = new DateTime(Long.parseLong(request.getParameter("arrivaldate")));
int clas = Integer.parseInt(request.getParameter("class"));
DateTime date = new DateTime(Long.parseLong(request.getParameter("date")));
daoFactory = DAOFactory.getDAOFactory(Configuration.DAO_IMPL);
daoFactory.beginTransaction();
PrenotationDAO prenotationDAO = daoFactory.getPrenotationDAO();
List<Prenotation> prenotations = prenotationDAO.findPrenotationDetail(loggedUser, flightcode, departuredate, arrivaldate, clas, date);
daoFactory.commitTransaction();
request.setAttribute("prenotations", prenotations);
request.setAttribute("loggedOn", loggedUser != null);
request.setAttribute("loggedUser", loggedUser);
request.setAttribute("viewUrl", "prenotationManager/prenotationsCheckIn");
}
catch (Exception e) {
logger.log(Level.SEVERE, "Controller Error", e);
try {
if (daoFactory != null) {
daoFactory.rollbackTransaction();
}
}
catch (Throwable t) {
}
throw new RuntimeException(e);
}
finally {
try {
if (daoFactory != null) {
daoFactory.closeTransaction();
}
} catch (Throwable t) {
}
}
}
public static void insertCheckIn(HttpServletRequest request, HttpServletResponse response){
SessionDAOFactory sessionDAOFactory;
DAOFactory daoFactory = null;
LoggedUser loggedUser;
String applicationMessage = null;
Logger logger = LogService.getApplicationLogger();
try{
sessionDAOFactory = SessionDAOFactory.getSessionDAOFactory(Configuration.SESSION_IMPL);
sessionDAOFactory.initSession(request, response);
LoggedUserDAO loggedUserDAO = sessionDAOFactory.getLoggedUserDAO();
loggedUser = loggedUserDAO.find();
int passengers = Integer.parseInt(request.getParameter("passengers"));
ArrayList<String> doctype = new ArrayList<String>(passengers);
ArrayList<Long> doccode = new ArrayList<Long>(passengers);
ArrayList<String> prencode = new ArrayList<String>(passengers);
for(int i=0; i<passengers; i++){
doctype.add(request.getParameter("documento"+Integer.toString(i)));
doccode.add(Long.parseLong(request.getParameter("documentocodice"+Integer.toString(i))));
prencode.add(request.getParameter("prencode"+Integer.toString(i)));
}
daoFactory = DAOFactory.getDAOFactory(Configuration.DAO_IMPL);
daoFactory.beginTransaction();
PrenotationDAO prenotationDAO = daoFactory.getPrenotationDAO();
CheckInDAO checkInDAO = daoFactory.getCheckInDAO();
for(int i=0; i<passengers; i++){
checkInDAO.insertCheckIns(doctype.get(i), doccode.get(i), prencode.get(i));
}
List<PrenotationView> prenotations = prenotationDAO.findUserPrenotations(loggedUser);
List<PrenotationView> checkPrenotations = prenotationDAO.findUserPrenotationsCheckIn(loggedUser);
daoFactory.commitTransaction();
request.setAttribute("prenotations", prenotations);
request.setAttribute("checkprenotations", checkPrenotations);
request.setAttribute("loggedOn", loggedUser != null);
request.setAttribute("loggedUser", loggedUser);
request.setAttribute("viewUrl", "prenotationManager/prenotations");
}
catch (Exception e) {
logger.log(Level.SEVERE, "Controller Error", e);
try {
if (daoFactory != null) {
daoFactory.rollbackTransaction();
}
}
catch (Throwable t) {
}
throw new RuntimeException(e);
}
finally {
try {
if (daoFactory != null) {
daoFactory.closeTransaction();
}
} catch (Throwable t) {
}
}
}
}
| true |
47bd243045e849768ecc313d115f96a7011efc2a
|
Java
|
alphadev-sthlm/k8s-test
|
/src/test/java/se/alphadev/k8stest/BaseITest.java
|
UTF-8
| 304 | 1.734375 | 2 |
[] |
no_license
|
package se.alphadev.k8stest;
import static java.lang.System.out;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestInfo;
public class BaseITest {
@BeforeEach
void beforeEach(TestInfo testInfo) {
out.println("*** "+ testInfo.getDisplayName() +" ***");
}
}
| true |
3a811782dbcec07205e7e1bb38d5465d71466743
|
Java
|
Gaute94/FrameworksFinalProject-Back
|
/src/main/java/me/gaute/redditcloneback/controller/PostController.java
|
UTF-8
| 2,358 | 2.25 | 2 |
[] |
no_license
|
package me.gaute.redditcloneback.controller;
import me.gaute.redditcloneback.model.Post;
import me.gaute.redditcloneback.model.Subreddit;
import me.gaute.redditcloneback.model.SubredditAndUser;
import me.gaute.redditcloneback.service.PostService;
import me.gaute.redditcloneback.service.SubredditService;
import me.gaute.redditcloneback.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@org.springframework.web.bind.annotation.RestController
public class PostController {
@Autowired
PostService postService;
@Autowired
SubredditService subredditService;
@Autowired
UserService userService;
@GetMapping("/posts")
public List<Post> getAllPosts() {
return postService.getAllPosts();
}
@GetMapping("/posts/ordered")
public List<Post> getAllPostsByDate() {
return postService.getAllPostsByDate();
}
@GetMapping("/posts/id/{id}")
public Optional<Post> getPostById(@PathVariable long id) {
return postService.getOne(id);
}
/*
@GetMapping("/subreddits/id/{id}")
public Optional<User> getUserById(@PathVariable long id){
return userService.getOne(id);
}
*/
@GetMapping("/posts/{subreddit}")
public List<Post> getPostBySubreddit(@PathVariable String subreddit) {
Optional<Subreddit> subreddit2 = subredditService.getById(subreddit);
if (!subreddit2.isPresent()) {
return null;
}
return postService.getAllSubredditPosts(subreddit2.get());
}
@DeleteMapping("/posts/{id}")
public void deletePostById(@PathVariable long id) {
postService.deleteById(id);
}
@PostMapping("/posts")
public Post savePost(@RequestBody Post newPost) {
return postService.save(newPost);
}
@PutMapping("/posts/{id}")
public Post updatePost(@PathVariable long id, @RequestBody Post newPost) {
newPost.setId(id);
return postService.save(newPost);
}
@PostMapping("/posts/postsFeed")
public List<Post> getAllSubscribedAndFollowed(@RequestBody SubredditAndUser subredditAndUser) {
return postService.getAllSubscribedAndFollowed(subredditAndUser.getSubreddits(), subredditAndUser.getUsers());
}
}
| true |
2cfbcc2a436972214bb335c2ed4105a374b0e9ee
|
Java
|
cqingwo/Messenger
|
/Libraries/Services/src/main/java/com/cqwo/services/BannedIPs.java
|
UTF-8
| 2,709 | 2.0625 | 2 |
[] |
no_license
|
/*
* Copyright (C) 2017.
* 用于JAVA项目开发
* 重庆青沃科技有限公司 版权所有
* Copyright © 2017. CqingWo Systems Incorporated. All rights reserved.
*/
package com.cqwo.services;
import com.cqwo.core.domain.BannedIPInfo;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
/**
* Created by cqnews on 2017/4/11.
*/
//禁止ip表
public class BannedIPs {
@Resource(name = "BannedIPsData")
com.cqwo.data.BannedIPs bannedips;
//region 条禁止ip表方法
/**
* 获得禁止ip表数量
*
* @param condition 条件
* @return 返回数量
**/
public int GetBannedIPCount(String condition) throws IOException {
return bannedips.GetBannedIPCount(condition);
}
/**
* 创建一条禁止ip表数据
*
* @param bannedipInfo 禁止ip表模型
* @return 返回创建信息
**/
public int CreateBannedIP(BannedIPInfo bannedipInfo) throws IOException {
return bannedips.CreateBannedIP(bannedipInfo);
}
/**
* 更新一条禁止ip表数据
*
* @param bannedipInfo 禁止ip表模型
**/
public void UpdateBannedIP(BannedIPInfo bannedipInfo) throws IOException {
bannedips.UpdateBannedIP(bannedipInfo);
}
/**
* 删除一条禁止ip表数据
*
* @param id 禁止ip表模型
**/
public void DeleteBannedIPById(int id) throws IOException {
bannedips.DeleteBannedIPById(id);
}
/**
* 批量删除一批禁止ip表数据
**/
public void DeleteBannedIPByIdList(String idList) throws IOException {
bannedips.DeleteBannedIPByIdList(idList);
}
/**
* 获取一条禁止ip表数据
*
* @param id 禁止ip表模型
**/
public BannedIPInfo GetBannedIPById(int id) throws IOException {
return bannedips.GetBannedIPById(id);
}
/**
* 获得禁止ip表数据列表
*
* @param condition 条件
* @param sort 排序
* @return 返回BannedIPInfo
**/
public List<BannedIPInfo> GetBannedIPList(String condition, String sort) throws IOException {
return bannedips.GetBannedIPList(condition, sort);
}
/**
* 获得禁止ip表数据列表
*
* @param pageSize 每页数
* @param pageNumber 当前页数
* @param condition 条件
* @param sort 排序
* @return 返回BannedIPInfo
**/
public List<BannedIPInfo> GetBannedIPList(int pageSize, int pageNumber, String condition, String sort) throws IOException {
return bannedips.GetBannedIPList(pageSize, pageNumber, condition, sort);
}
//endregion
}
| true |
d928a932919d817b25ba7b67d49e1c88a29fc922
|
Java
|
mutyalart/fastcodingtools
|
/trunk/fastcodingtools/src/com/fastcodingtools/util/io/FileUtils.java
|
ISO-8859-1
| 20,808 | 2.421875 | 2 |
[
"Apache-2.0"
] |
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 com.fastcodingtools.util.io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import com.fastcodingtools.excecao.FileCopyException;
import com.fastcodingtools.util.RegexUtils;
import com.fastcodingtools.util.log.log4j.LogFastLevel;
/**
* Classe com mtodos utilitrios para leitura e escrita de arquivos.
*
* @author macg
*
*/
public class FileUtils {
private static final Logger logger = Logger.getLogger(FileUtils.class.getName());
private static final String FILE_SEPARATOR = File.separator.equals("\\") ? "\\\\" : "/";
private static final String SEPARATOR01 = "\\\\";
private static final String SEPARATOR02 = "/";
public static String getFileSeparator() {
return FILE_SEPARATOR;
}
public static String[] listRoots() {
File[] listRoots = File.listRoots();
String[] roots = new String[listRoots.length];
File file;
for (int i = 0; i < listRoots.length; i++) {
file = listRoots[i];
roots[i] = file.getPath();
}
return roots;
}
public static boolean isDirectory(String path){
return new File(path).isDirectory();
}
public static boolean isFile(String path){
return new File(path).isFile();
}
public static long freeSpace(String path) {
long freeSpace = 11;
try {
freeSpace = org.apache.commons.io.FileSystemUtils.freeSpace(RegexUtils.createRegexInstance("(\\w:|)"+FILE_SEPARATOR).grep(path)[0]);
} catch (IOException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
}
return freeSpace;
}
public static long freeSpaceKb(String path) {
long freeSpace = 11;
try {
freeSpace = org.apache.commons.io.FileSystemUtils.freeSpaceKb(path);
} catch (IOException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
}
return freeSpace;
}
public static double getTotalBytesDir(String dirPath){
return getTotalBytes(getFilePaths(dirPath, ".*"));
}
/**
* Mtodo para clculo do total de bytes de um conjunto de arquivos
* @param paths
* @return
*/
public static double getTotalBytes(String... paths){
double totalBytes =0;
File file;
for(int contadorArquivos=0; contadorArquivos < paths.length; contadorArquivos++){
file = new File(paths[contadorArquivos]);
totalBytes += file.length();
}
return totalBytes;
}
/**
* Converte os separadores de arquivo para os separadores especficos dos
* sistema operacional onde a aplicao est rodando.
*
* @return
*/
public static String convertPathSeparators(String path) {
if (path.indexOf(SEPARATOR01) != -1) {
path = path.replaceAll(SEPARATOR01, FILE_SEPARATOR);
} else {
if (path.indexOf(SEPARATOR02) != -1) {
path = path.replaceAll(SEPARATOR02, FILE_SEPARATOR);
}
}
return path;
}
public static boolean delete(String filePath) {
return delete(new File(filePath));
}
public static boolean delete(File file) {
try {
org.apache.commons.io.FileUtils.forceDelete(file);
} catch (IOException e) {
}
return file.exists();
}
public static void deleteFiles(String dirPath, List<String> fileNamePatterns) {
deleteFiles(dirPath, fileNamePatterns.toArray(new String[fileNamePatterns.size()]));
}
public static void deleteAllFilesExcept(String dirPath, boolean deleteDirs, String... fileNamePatterns){
File[] files;
for (int i = 0; i < fileNamePatterns.length; i++) {
files = getFiles(dirPath, fileNamePatterns[i], false, false);
for (int j = 0; j < files.length; j++) {
if(!files[j].isDirectory() || (files[j].isDirectory() && deleteDirs)){
delete(files[j]);
}
}
}
}
public static void deleteFiles(String dirPath) {
deleteFiles(dirPath, ".*");
}
public static void deleteFiles(String dirPath, String... fileNamePatterns) {
File[] files;
for (int i = 0; i < fileNamePatterns.length; i++) {
files = getFiles(dirPath, fileNamePatterns[i]);
for (int j = 0; j < files.length; j++) {
delete(files[j]);
}
}
}
public static void renameExt(String filePath, String newExt) throws FileCopyException {
String newFilePath = getFilePathWithoutExtension(filePath) + newExt;
File file = new File(filePath);
// copy(filePath, newFilePath);
copyFile(file, new File(newFilePath));
// delete(filePath);
delete(file);
}
public static void moveFile(String filePath, String toDir) {
copyFileToDirectory(filePath, toDir);
delete(filePath);
}
public static void moveDir(String filePath, String toDir) throws FileCopyException {
copyDirectoryToDirectory(filePath, toDir);
delete(filePath);
}
public static boolean isSameSize(String path01, String path02) {
return new File(path01).length() == new File(path02).length();
}
public static void copyFilesToDirectory(String filePath[], String dirPath) {
for (int i = 0; i < filePath.length; i++) {
File dir = new File(dirPath);
copyFileToDirectory(new File(filePath[i]), dir);
}
}
public static void copyFileToDirectory(String filePath, String dirPath) {
copyFileToDirectory(new File(filePath), new File(dirPath));
}
public static void copyFileToDirectory(File file, File dir) {
try {
org.apache.commons.io.FileUtils.copyFileToDirectory(file, dir);
} catch (IOException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
}
}
public static void copyDirectory(String from, String to) throws FileCopyException {
copyDirectory(new File(from), new File(to));
}
public static void copyDirectory(File from, File to) throws FileCopyException {
try {
org.apache.commons.io.FileUtils.copyDirectory(from, to);
} catch (IOException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
}
}
public static void copyDirectoryToDirectory(String from, String to) throws FileCopyException {
copyDirectoryToDirectory(new File(from), new File(to));
}
public static void copyDirectoryToDirectory(File from, File to) throws FileCopyException {
try {
org.apache.commons.io.FileUtils.copyDirectoryToDirectory(from, to);
} catch (IOException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
}
}
public static void copyFile(String from, String to) throws FileCopyException {
copyFile(new File(from), new File(to));
}
public static void copyFile(File from, File to) throws FileCopyException {
try {
org.apache.commons.io.FileUtils.copyFile(from, to);
} catch (IOException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
}
}
public static boolean exists(String dirPath, String fileNamePattern) {
String[] fileNames = getFileNames(dirPath, fileNamePattern);
return ((fileNames != null) && (fileNames.length > 0));
}
public static boolean exists(String filePath) {
return new File(filePath).exists();
}
public static String getFileExtension(String filePath) {
String name = new File(filePath).getName();
String ext = "";
if(name.indexOf(".") > -1) {
ext = name.substring(name.indexOf("."));
}
return ext;
}
public static String getFilePathWithoutExtension(String filePath) {
File file = new File(filePath);
if(file.isDirectory()){
return filePath;
}
return filePath.replaceAll(getFileExtension(filePath), "");
}
public static String getFileNameWithoutExtension(String filePath) {
File file = new File(filePath);
String name = file.getName();
if(file.isDirectory()){
return name;
}
return name.replaceAll(getFileExtension(filePath), "");
}
public static String getFileName(String filePath) {
return new File(filePath).getName();
}
public static String getFileDir(String filePath) {
return new File(filePath).getParent()+getFileSeparator();
}
public static String getFilePathNewer(String dirPath, String fileNamePattern) {
File file = getFileNewer(dirPath, fileNamePattern);
return ( file == null ) ? null : file.getPath();
}
public static File getFileNewer(String dirPath, String fileNamePattern) {
File[] files = getFiles(dirPath, fileNamePattern);
if(files.length == 0) {
return null;
}
/*
* Ordenao por ordem decrescente de data.
*/
Arrays.sort(files, new Comparator<File>() {
public int compare(File f1, File f2) {
//multiplicao por -1 para inverter a comparao de crescente para
//decrescente.
return Long.valueOf(f1.lastModified()).compareTo(Long.valueOf(f2.lastModified())) * -1;
}});
return files[0];
}
public static File[] getFiles(String dirPath) {
return getFiles(dirPath, ".*", true, false);
}
public static File[] getFiles(String dirPath, String fileNamePattern) {
return getFiles(dirPath, fileNamePattern, true, false);
}
public static File[] getFiles(String dirPath, boolean foundInSubDirs) {
return getFiles(dirPath, ".*", true, foundInSubDirs);
}
public static File[] getFiles(String dirPath, String fileNamePattern, boolean foundInSubDirs) {
return getFiles(dirPath, fileNamePattern, true, foundInSubDirs);
}
private static File[] getFiles(String dirPath,
String fileNamePattern,
boolean nameMatchesEr,
boolean foundInSubDirs) {
ArrayList<File> foundFiles = new ArrayList<File>();
getFiles(dirPath, fileNamePattern, nameMatchesEr, foundInSubDirs, foundFiles);
/*
* Ordenao por ordem alfabtica.
*/
Collections.sort(foundFiles, new Comparator<File>() {
public int compare(File f1, File f2) {
return f1.getName().compareTo(f2.getName());
}});
return foundFiles.toArray(new File[foundFiles.size()]);
}
private static List<File> getFiles(String dirPath,
String fileNamePattern,
boolean nameMatchesEr,
boolean foundInSubDirs,
ArrayList<File> foundFiles) {
FileNameFilter fileNameFilter = new FileNameFilter(fileNamePattern, nameMatchesEr);
File[] files = new File(dirPath).listFiles(fileNameFilter);
if(files != null){
Collections.addAll(foundFiles, files);
}
if (foundInSubDirs) {
FileFilter dirFilter = new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory();
}
};
File[] dirs = new File(dirPath).listFiles(dirFilter);
for (int i = 0; i < dirs.length; i++) {
getFiles(dirs[i].getPath(), fileNamePattern, nameMatchesEr, foundInSubDirs, foundFiles);
}
}
return foundFiles;
}
public static String[] getDirPaths(String dirPath, String fileNamePattern) {
File[] files = getFiles(dirPath, fileNamePattern);
ArrayList<String> dirPaths = new ArrayList<String>();
for (int i = 0; i < files.length; i++) {
if(files[i].isDirectory()){
dirPaths.add(files[i].getPath());
}
}
return dirPaths.toArray(new String[dirPaths.size()]);
}
public static String[] getFilePaths(String dirPath) {
File[] files = getFiles(dirPath);
String[] fileNames = new String[files.length];
for (int i = 0; i < files.length; i++) {
fileNames[i] = files[i].getPath();
}
return fileNames;
}
public static String[] getFilePaths(String dirPath, String fileNamePattern) {
return getFilePaths(dirPath, fileNamePattern, true, false);
}
public static String[] getFilePaths(String dirPath, String fileNamePattern, boolean nameMatchesEr, boolean foundInSubDirs) {
File[] files = getFiles(dirPath, fileNamePattern, nameMatchesEr, foundInSubDirs);
String[] fileNames = new String[files.length];
for (int i = 0; i < files.length; i++) {
fileNames[i] = files[i].getPath();
}
return fileNames;
}
public static String[] getFilePaths(String dirPath, String[] extensions){
return getFilePaths(dirPath, extensions,true, false);
}
public static String[] getFilePaths(String dirPath, String[] extensions, boolean nameMatchesEr, boolean foundInSubDirs){
StringBuilder exts = new StringBuilder();
exts.append("(");
for (int i = 0; i < extensions.length; i++) {
String ext = extensions[i];
exts.append(".*\\");
exts.append(ext);
if(i < extensions.length-1){
exts.append("|");
}else{
exts.append(")");
}
}
return getFilePaths(dirPath, exts.toString(), nameMatchesEr, foundInSubDirs);
}
public static String[] getFileNames(String dirPath, String fileNamePattern) {
FileNameFilter fileNameFilter = new FileNameFilter(fileNamePattern,true);
File dir = new File(dirPath);
return dir.list(fileNameFilter);
}
public static void writeFile(String path, String content) {
StringWriter writer = new StringWriter();
writer.write(content);
writeFile(path, writer);
}
public static String getFileTextContent(String path) throws IOException{
StringBuilder content = new StringBuilder();
try {
RandomAccessFile ranFile = new RandomAccessFile(path,"r");
String linha = null;
while((linha = ranFile.readLine()) != null){
content.append(linha);
content.append("\n");
}
ranFile.close();
} catch (FileNotFoundException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
throw e;
} catch (IOException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
throw e;
}
return content.toString();
}
public static void appendContent(String path, String content) {
StringWriter writer = new StringWriter();
writer.write(content);
try {
createFile(new File(path));
FileWriter fileWriter = new FileWriter(path);
fileWriter.append(writer.toString());
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
}
}
public static void writeFile(String path, StringWriter content) {
try {
createFile(new File(path));
FileWriter fileWriter = new FileWriter(path);
fileWriter.write(content.toString());
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
}
}
public static InputStream readFileInputStream(String path) throws FileNotFoundException {
return new FileInputStream(new File(path));
}
public static boolean createFile(String path) {
return createFile(new File(path));
}
public static boolean createFile(File file) {
createDirs(file.getParent());
try {
return file.createNewFile();
} catch (IOException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
return false;
}
}
public static void createDirs(String dirPath) {
File file = new File(dirPath);
file.mkdirs();
try {
org.apache.commons.io.FileUtils.forceMkdir(file);
} catch (IOException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
}
}
public static void write(String data, OutputStream output, String encoding) {
try {
org.apache.commons.io.IOUtils.write(data, output, encoding);
} catch (IOException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
}
}
public static void write(byte[] data, OutputStream output) {
try {
output.write(data);
output.flush();
output.close();
} catch (IOException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
}
}
public static ObjectOutputStream getObjectOutputStream(String path) {
ObjectOutputStream o = null;
try {
FileOutputStream fos = new FileOutputStream(new File(path));
BufferedOutputStream bos = new BufferedOutputStream(fos);
o = new ObjectOutputStream(bos);
} catch (FileNotFoundException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
} catch (IOException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
}
return o;
}
public static ObjectInputStream getObjectInputStream(String path) {
ObjectInputStream o = null;
try {
FileInputStream fos = new FileInputStream(new File(path));
BufferedInputStream bos = new BufferedInputStream(fos);
o = new ObjectInputStream(bos);
} catch (FileNotFoundException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
} catch (IOException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
}
return o;
}
public static FileWriter getFileWriter(String path){
FileWriter o = null;
try {
createFile(path);
o = new FileWriter(path);
} catch (FileNotFoundException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
} catch (IOException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
}
return o;
}
public static OutputStream getOutputStream(String path) {
OutputStream o = null;
try {
createFile(path);
FileOutputStream fos = new FileOutputStream(path);
BufferedOutputStream bos = new BufferedOutputStream(fos);
o = bos;
} catch (FileNotFoundException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
} catch (Exception e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
}
return o;
}
public static InputStream getInputStream(String path) {
InputStream o = null;
try {
createFile(path);
FileInputStream fos = new FileInputStream(new File(path));
BufferedInputStream bos = new BufferedInputStream(fos);
o = bos;
} catch (FileNotFoundException e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
} catch (Exception e) {
logger.log(LogFastLevel.LOGFAST,e.getMessage(),e);
}
return o;
}
public static Date getDateModified(String path){
return new Date(new File(path).lastModified());
}
/*
* *****************************************************************************
* *****************************************************************************
* *****************************************************************************
*/
public String getSubDiretoriesNames(String pathNames) {
String nameList = deepFindDirectories(pathNames);
if(!nameList.equals("")) {
nameList = nameList.substring(0, nameList.length() - 1);
}else {
nameList = pathNames;
}
return nameList;
}
private String deepFindDirectories(String pathNames) {
StringBuffer pathList = new StringBuffer();
String[] paths = pathNames.split(",");
File dir = null;
File file = null;
String path = null;
String[] subDiretoriesNames = null;
for (int j = 0; j < paths.length; j++) {
path = paths[j];
dir = new File(path);
subDiretoriesNames = dir.list();
for (int i = 0; i < subDiretoriesNames.length; i++) {
file = new File(path + getFileSeparator() + subDiretoriesNames[i]);
if (file.isDirectory()) {
pathList.append(path + getFileSeparator() + subDiretoriesNames[i] + ",");
getSubDiretoriesNames(path + getFileSeparator() + subDiretoriesNames[i]);
}
}
}
return pathList.toString();
}
}
| true |
1d126a1ee4a461b175118d9b426d46cd875307a3
|
Java
|
jiaxinli0907/document-analysis
|
/src/main/java/de/dbvis/utils/VMath.java
|
UTF-8
| 1,143 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
/*
* 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 de.dbvis.utils;
import org.apache.commons.math3.linear.RealVector;
/**
*
* @author JiaxinLi
*/
public class VMath implements VectorMath{
@Override
public double euclideanNorm(RealVector v) {
double[] a1 = v.toArray();
double en=0.0;
for(int i=0;i<a1.length;i++){
en+=Math.pow(a1[i], 2);
}
return Math.sqrt(en);
}
@Override
public double dotProduct(RealVector v1, RealVector v2) {
double[] tmp1 = v1.toArray();
double[] tmp2 = v2.toArray();
double sum=0.0;
for(int i=0; i<tmp1.length;i++ ){
sum+=tmp1[i]*tmp2[i];
}
return sum;
}
@Override
public double cosineSimilarity(RealVector v1, RealVector v2) {
double dotpro = dotProduct(v1,v2);
double en1 = euclideanNorm(v1);
double en2 = euclideanNorm(v2);
return dotpro/(en1*en2);
}
}
| true |
8d012feb5a44e3deefaee70340066a9f411ed7ac
|
Java
|
jeronimovf/nucleo
|
/src/main/java/br/jus/trt23/nucleo/enums/TipoPessoa.java
|
UTF-8
| 314 | 2.6875 | 3 |
[] |
no_license
|
package br.jus.trt23.nucleo.enums;
public enum TipoPessoa
{
F("Pessoa Física"), J("Pessoa Jurídica");
private String descricao;
private TipoPessoa(String descricao)
{
this.descricao = descricao;
}
public String getDescricao()
{
return descricao;
}
}
| true |
2229ab02c57998276a355ddf322beee905c94db4
|
Java
|
dpenic23/JavaTecajZI
|
/src/hr/fer/zemris/java/tecaj/zi/LabelaBrojKrugova.java
|
UTF-8
| 359 | 2.390625 | 2 |
[] |
no_license
|
package hr.fer.zemris.java.tecaj.zi;
import javax.swing.JLabel;
public class LabelaBrojKrugova extends JLabel implements PromatracModelaCrteza {
private static final long serialVersionUID = 1L;
@Override
public void dogodilaSePromjena(ModelCrteza model) {
this.setText("Broj krugova: " + String.valueOf(model.brojKrugova()));
}
}
| true |
e3f1b057ad640abddea6320e253aba9da9575971
|
Java
|
ashwinicodetreasure/Fitorto
|
/app/src/main/java/com/ct/fitorto/adapter/CityAdapter.java
|
UTF-8
| 1,214 | 2.515625 | 3 |
[] |
no_license
|
package com.ct.fitorto.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.ct.fitorto.R;
import com.ct.fitorto.model.City;
import java.util.List;
/**
* Created by Ashwini on 5/26/2016.
*/
public class CityAdapter extends ArrayAdapter<City> {
private Context context;
private List<City> cityList;
public CityAdapter(Context context, int resource, List<City> city) {
super(context, resource, city);
this.context = context;
this.cityList = city;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//return super.getView(position, convertView, parent);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.city_list_item, parent, false);
City sr = cityList.get(position);
TextView tv = (TextView) view.findViewById(R.id.city_item);
tv.setText(sr.getCityName());//+"\n" +sr.getArea()+"\n"+sr.getCity());
return view;
}
}
| true |
b03ebdef3f52a9e3e372b93ffc256d854aa70eba
|
Java
|
aminkashiri/LivingSimulation
|
/src/project/thread/world/Territory.java
|
UTF-8
| 3,069 | 3.0625 | 3 |
[] |
no_license
|
package project.thread.world;
import java.util.ArrayList;
import project.thread.animals.Animal;
import project.thread.animals.AnimalsController;
import project.utils.AllObjects;
import project.utils.Colors;
public class Territory {
int species;
int maxResident;
ArrayList<Animal> animals;
int x;
int y;
AnimalsController animalsController;
public Territory(int maxResidnet, int x, int y) {
animals = new ArrayList<Animal>();
this.maxResident = maxResidnet;
this.x = x;
this.y = y;
species = 0;
animalsController = AllObjects.getAllObjects().getAnimalsControllerThread();
}
public void giveLife(Animal animal) {
species = animal.getSpecies();
animals.add(animal);
}
synchronized public boolean requestMoving(Animal animal) {
if(species == 0) {
animals.add(animal);
species = animal.getSpecies();
}else if(species == animal.getSpecies() && animals.size()<maxResident) {
animals.add(animal);
}else {
return false;
}
return true;
}
synchronized public void removeAnimal(Animal animal) {
animals.remove(animal);
if(animals.size() == 0) {
species = 0;
}
}
public int starve() {
int temp = 0;
while(animals.size() > maxResident) {
animals.get(animals.size()-1).interrupt();
animals.remove(animals.size()-1);
temp++;
}
return temp;
}
public int birth(int k) {
int size = 0;
if(species != 0 && (k%species) == 0) {
size = animals.size();
for(int i = 0 ; i < size ; i++) {
Animal animal = new Animal(x,y,species);
animals.add(animal);
animal.start();
}
}
return size;
}
public void live() {
for(Animal animal : animals) {
animal.start();
}
}
public int die() {
int temp = animals.size();
while(animals.size() > 0) {
animals.get(animals.size()-1).interrupt();
animals.remove(animals.size()-1);
}
species = 0;
return temp;
}
public int getSpecies() {
return species;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getCount() {
return animals.size();
}
public int getPower() {
return animals.size()*species;
}
public void print() {
switch (species) {
case 1:
System.out.print(""+Colors.BLACK_BACKGROUND+animals.size()+Colors.RESET);
break;
case 2:
System.out.print(""+Colors.RED_BACKGROUND+animals.size()+Colors.RESET);
break;
case 3:
System.out.print(""+Colors.BLACK+Colors.YELLOW_BACKGROUND+animals.size()+Colors.RESET);
break;
case 4:
System.out.print(""+Colors.BLUE_BACKGROUND+animals.size()+Colors.RESET);
break;
case 5:
System.out.print(""+Colors.BLACK+Colors.GREEN_BACKGROUND+animals.size()+Colors.RESET);
break;
case 6:
System.out.print(""+Colors.BLACK+Colors.WHITE_BACKGROUND+animals.size()+Colors.RESET);
break;
case 7:
System.out.print(""+Colors.MAGENTA_BACKGROUND+animals.size()+Colors.RESET);
break;
case 8:
System.out.print(""+Colors.BLACK+Colors.CYAN_BACKGROUND+animals.size()+Colors.RESET);
break;
default:
System.out.print(""+animals.size()+Colors.RESET);
break;
}
}
}
| true |
8d8ea72145782bf3ad92ef9c9e3171f2ebd9ec3c
|
Java
|
Yjq14114/thinkingJava
|
/src/com/designmodel/Main.java
|
UTF-8
| 742 | 3.234375 | 3 |
[] |
no_license
|
package com.designmodel;
/**
* Created by 佳琦 on 2016/5/20.
*/
class Singleton{
private static Singleton instance;
public static Singleton getInstance(){
//synchronized加锁同步会降低效率,这里先判断是否为空
//不为空则需要加锁,提高程序效率
if(instance!=null){
synchronized (Singleton.class){
if(instance ==null){
instance = new Singleton();
}
}
}
return instance;
}
}
public class Main {
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1==s2);
}
}
| true |
d52c34795ccf45c12d242fb3f3569b7038121145
|
Java
|
pabplanalp/pvmail
|
/java/source/com/jwApps/servlet/field/ScListField.java
|
UTF-8
| 3,682 | 2.234375 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
Copyright 2011 JwApps.com
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.jwApps.servlet.field;
import com.jwApps.collection.JwList;
import com.jwApps.html.JwHtmlBuffer;
import com.jwApps.servlet.ScServletData;
import com.jwApps.servlet.encoder.ScDecoder;
import com.jwApps.servlet.encoder.ScEncoder;
public class ScListField
extends ScField<Object>
{
//##################################################
//# constructor
//##################################################//
public ScListField()
{
super();
}
public ScListField(String key)
{
super(key);
}
//##################################################
//# state
//##################################################//
public ScListFieldState newState()
{
return new ScListFieldState();
}
public ScListFieldState getState()
{
return (ScListFieldState)super.getState();
}
public ScListFieldState getState(ScServletData data)
{
return (ScListFieldState)super.getState(data);
}
//##################################################
//# value
//##################################################//
public Object getValue()
{
return getState().getSelectedValue();
}
public void setValue(Object e)
{
getState().setSelectedValue(e);
}
//##################################################
//# parameters
//##################################################//
public void applyParameters(ScServletData data)
{
super.applyParameters(data);
Object value = null;
if ( hasKeyParameter(data) )
value = ScDecoder.decodeStatic(getKeyParameter(data));
getState(data).setSelectedValue(value);
}
//##################################################
//# print
//##################################################//
public void renderControl(ScServletData data, JwHtmlBuffer buf)
{
ScListFieldState state = getState(data);
JwList<ScOption> options = state.getOptions();
int size = 8;
if ( state.hasMaximumSize() )
size = state.getMaximumSize();
if ( state.isAutoSize() )
{
int n = options.size();
if ( n < size && n > 1 )
size = n;
}
buf.open("select");
buf.printAttribute("name", getKey());
if ( isDisabled() )
buf.printAttribute("disabled");
buf.printAttribute("size", size);
buf.close();
if ( state.hasDefaultFocus() )
renderDefaultFocus(data, buf, getKey());
for ( ScOption e : options )
{
buf.open("option");
if ( e.hasValue() )
{
String value = ScEncoder.encodeStatic(e.getValue());
buf.printAttribute("value", value);
}
if ( e.hasSelectedValue(state.getSelectedValue()) )
buf.printAttribute("selected");
buf.close();
buf.print(e.getLabel());
buf.end("option");
}
buf.end("select");
}
}
| true |
336e6dd9f074d054cc49dd53d8d91315c207a0dd
|
Java
|
yjdwbj/BleReadTool
|
/app/src/main/java/lcy/gles3d/util/TextureUtils.java
|
UTF-8
| 3,927 | 2.109375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package lcy.gles3d.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.opengl.GLES20;
import android.opengl.GLUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import androidx.annotation.NonNull;
import androidx.annotation.RawRes;
import androidx.core.graphics.drawable.IconCompat;
import java.io.IOException;
import java.io.InputStream;
import bt.lcy.btread.LoggerConfig;
import bt.lcy.btread.R;
import bt.lcy.btread.fragments.StringStream;
import static android.opengl.GLES20.GL_REPEAT;
import static android.opengl.GLES20.GL_TEXTURE_2D;
import static android.opengl.GLES20.GL_TEXTURE_WRAP_S;
import static android.opengl.GLES20.GL_TEXTURE_WRAP_T;
import static android.opengl.GLES20.glBindTexture;
import static android.opengl.GLES20.glGenTextures;
import static android.opengl.GLES20.glGenerateMipmap;
import static android.opengl.GLES20.glTexParameterf;
import static android.opengl.GLUtils.texImage2D;
public class TextureUtils {
private final static String TAG = TextureUtils.class.getName();
public static int loadTexture(Context context, int drawableID) {
return loadTexture(context, drawableID, true);
}
public static int loadTexture(Context context, int drawableID, boolean isBottomLeftOrigin) {
Bitmap bitmap = null;
Bitmap flippedBitmap = null;
int textureName;
bitmap = BitmapFactory.decodeResource(context.getResources(), drawableID);
if (isBottomLeftOrigin) {
Matrix flip = new Matrix();
flip.postScale(1f, -1f);
flippedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), flip, false);
textureName = loadTexture(flippedBitmap);
bitmap.recycle();
} else {
textureName = loadTexture(bitmap);
}
// textureName = loadTexture(bitmap);
return textureName;
}
public static int loadTexture(Bitmap bitmap) {
final int[] textureName = new int[1];
GLES20.glGenTextures(1, textureName, 0);
GLES20.glBindTexture(GL_TEXTURE_2D, textureName[0]);
glTexParameterf(GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLUtils.texImage2D(GL_TEXTURE_2D, 0, bitmap, 0);
// glGenerateMipmap(GL_TEXTURE_2D);
bitmap.recycle();
glBindTexture(GL_TEXTURE_2D, 0);
return textureName[0];
}
public static int loadCubeTexture2D(@NonNull Context context, @RawRes int[] cubeResources) {
final int[] textureId = new int[6];
glGenTextures(6, textureId, 0);
GLES20.glBindTexture(GL_TEXTURE_2D, textureId[0]);
glTexParameterf(GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
Bitmap bitmap = null;
// https://stackoverflow.com/questions/24389043/bitmapfactory-decoderesource-returns-null-for-shape-defined-in-xml-drawable
for (int face = 0; face < 6; face++) {
Drawable drawable = context.getResources().getDrawableForDensity(cubeResources[face], DisplayMetrics.DENSITY_MEDIUM);
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0,0,canvas.getWidth(),canvas.getHeight());
drawable.draw(canvas);
glBindTexture(GL_TEXTURE_2D, textureId[face]);
texImage2D(GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
}
return textureId[0];
}
}
| true |
beeae6ffcb789c2c0746633f88d33f64bf0f2232
|
Java
|
serkushner/backend-team1
|
/src/main/java/com/exadel/project/configurations/emailConfig/EmailConfigLogger.java
|
UTF-8
| 792 | 1.984375 | 2 |
[] |
no_license
|
package com.exadel.project.configurations.emailConfig;
import com.exadel.project.common.mailSender.EmailService;
import com.exadel.project.common.mailSender.EmailServiceLoggingMockImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:application.properties")
public class EmailConfigLogger {
@Bean
@ConditionalOnProperty(prefix = "notification", name = "service", havingValue = "logger",
matchIfMissing = true)
public EmailService emailNotificationLogger() {
return new EmailServiceLoggingMockImpl();
}
}
| true |
ba0958fca123cc8c91030a48d54cc89dcb55c1dd
|
Java
|
PatriciaOrriens/onzeMoestuin
|
/src/test/java/groentjes/onzeMoestuin/repository/UserRepositoryTest.java
|
UTF-8
| 1,964 | 2.34375 | 2 |
[] |
no_license
|
package groentjes.onzeMoestuin.repository;
import groentjes.onzeMoestuin.model.User;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author Eric van Dalen
* DataJpaTest of the UserRepository
*/
@RunWith(SpringRunner.class)
@DataJpaTest
class UserRepositoryTest {
private static final String USERNAME = "gebruikersnaam";
private static final String OTHER_USERNAME = "gebruikersnaam2";
private static final String EMAIL = "[email protected]";
private static final String OTHER_EMAIL = "[email protected]";
@Autowired
private UserRepository userRepository;
@Test
void testFindByUsername() {
// Arrange
User testUser = new User();
testUser.setUsername(USERNAME);
userRepository.save(testUser);
// Activate
Optional<User> foundUser = userRepository.findByUsername(USERNAME);
Optional<User> noFoundUser = userRepository.findByUsername(OTHER_USERNAME);
// Assert
assertTrue(foundUser.isPresent());
Assertions.assertEquals(USERNAME, foundUser.get().getUsername());
assertFalse(noFoundUser.isPresent());
}
@Test
void testFindByEmail() {
// Arrange
User testUser = new User();
testUser.setEmail(EMAIL);
userRepository.save(testUser);
// Activate
Optional<User> foundUser = userRepository.findByEmail(EMAIL);
Optional<User> noFoundUser = userRepository.findByEmail(OTHER_EMAIL);
// Assert
assertTrue(foundUser.isPresent());
Assertions.assertEquals(EMAIL, foundUser.get().getEmail());
assertFalse(noFoundUser.isPresent());
}
}
| true |
62121347eb57e98d9f09d078f02161ed08690b00
|
Java
|
alarangeiras/iot-kafka-poc
|
/src/main/java/dev/allanlarangeiras/kafkapoc/mappers/PresenceMapper.java
|
UTF-8
| 1,055 | 2.109375 | 2 |
[] |
no_license
|
package dev.allanlarangeiras.kafkapoc.mappers;
import dev.allanlarangeiras.kafkapoc.dto.PresenceDTO;
import dev.allanlarangeiras.kafkapoc.proto.Presence;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class PresenceMapper {
public List<PresenceDTO> mapFrom(Presence.presence_event presenceEvent) {
long timestamp = presenceEvent.getTimestamp();
List<Presence.proximity> proximityList = presenceEvent.getPaProximityEvent().getProximityList();
return proximityList
.stream()
.map(proximity -> {
return PresenceDTO
.builder()
.eventTimestamp(timestamp)
.clientMacAddress(proximity.getStaEthMac().getAddr().toStringUtf8())
.apMacAddress(proximity.getApEthMac().getAddr().toStringUtf8())
.build();
}).collect(Collectors.toList());
}
}
| true |
dd6b9190c6616550e2729ab6b75ae647eb3458b8
|
Java
|
ahkm6/oldProgram
|
/MakeObject.java
|
UTF-8
| 8,494 | 2.875 | 3 |
[] |
no_license
|
package h280314;
import java.util.ArrayList;
import java.util.Random;
public class MakeObject {
final public static int RANDOM = 0;
final public static int GOODBAD = 1;
final public static int VIASGOOD = 2;
final public static int NORMAL = 3;
public int deadlineBorder = 15;
public int deadlineRange = 10;
public void makeAgent(ArrayList<Agent> agent, Random random, int N,
int policy, int TYPE) {
switch (TYPE) {
case RANDOM:
for (int i = 0; i < N; i++) {
int[] resource = new int[3];
resource[0] = random.nextInt(6) + 2;
resource[1] = random.nextInt(6) + 2;
resource[2] = random.nextInt(6) + 2;
agent.add(new Agent(i, resource, policy, random));
}
break;
case GOODBAD:
for (int i = 0; i < N / 2; i++) {
int[] resource = new int[3];
resource[0] = random.nextInt(3) + 5;
resource[1] = random.nextInt(3) + 5;
resource[2] = random.nextInt(3) + 5;
agent.add(new Agent(i, resource, policy, random));
}
for (int i = N / 2; i < N; i++) {
int[] resource = new int[3];
resource[0] = random.nextInt(3) + 2;
resource[1] = random.nextInt(3) + 2;
resource[2] = random.nextInt(3) + 2;
agent.add(new Agent(i, resource, policy, random));
}
break;
case VIASGOOD:
for (int i = 0; i < N / 4; i++) {
int[] resource = new int[3];
resource[0] = random.nextInt(3) + 4;
resource[1] = random.nextInt(3) + 4;
resource[2] = random.nextInt(3) + 4;
agent.add(new Agent(i, resource, policy, random));
}
for (int i = N / 4; i < N/2; i++) {
int[] resource = new int[3];
resource[0] = random.nextInt(3) + 2;
resource[1] = random.nextInt(3) + 2;
resource[2] = random.nextInt(3) + 7;
agent.add(new Agent(i, resource, policy, random));
}
for (int i = N / 2; i < (3 * N)/4; i++) {
int[] resource = new int[3];
resource[0] = random.nextInt(3) + 2;
resource[1] = random.nextInt(3) + 7;
resource[2] = random.nextInt(3) + 2;
agent.add(new Agent(i, resource, policy, random));
}
for (int i = (3 * N)/4; i < N; i++) {
int[] resource = new int[3];
resource[0] = random.nextInt(3) + 7;
resource[1] = random.nextInt(3) + 2;
resource[2] = random.nextInt(3) + 2;
agent.add(new Agent(i, resource, policy, random));
}
break;
case NORMAL:
for (int i = 0; i < N; i++) {
int[] resource = new int[3];
if(i<N/5)
resource = lowAgent(random);
else if(i<(N/5)*2)
resource = highAgent(random);
else if(i<(N/5)*3)
resource = aBias(random);
else if(i<(N/5)*4)
resource = bBias(random);
else
resource = cBias(random);
agent.add(new Agent(i, resource, policy, random));
}
break;
}
}
public void makeTask(ArrayList<Task> task, Random random, int load,
double[] th,int slice) {
int reward;
int taskNumber;
int thresh = 0;
if (task.isEmpty()) {
taskNumber = 0;
} else {
for (int i = 0; i < task.size(); i++) {
task.get(i).taskNumber(i);
}
taskNumber = task.size();
}
for (int i = taskNumber; i < load + taskNumber; i++) {
double d = random.nextDouble();
int resource[] = new int[3];
if (d < th[0]) {
thresh = 0;
} else if (d < th[1]) {
thresh = 1;
} else if (d < th[2]) {
thresh = 2;
} else {
thresh = 3;
}
switch (thresh) {
case 0:
resource = normalTask(random);
reward = resource[0] + resource[1] + resource[2];
task.add(new Task(i, resource, reward, random
.nextInt(deadlineRange + 1) + deadlineBorder, 0,slice,random));
break;
case 1:
resource = aBiasTask(random);
reward = resource[0] + resource[1] + resource[2];
task.add(new Task(i, resource, reward, random
.nextInt(deadlineRange + 1) + deadlineBorder, 1,slice,random));
break;
case 2:
resource = bBiasTask(random);
reward = resource[0] + resource[1] + resource[2];
task.add(new Task(i, resource, reward, random
.nextInt(deadlineRange + 1) + deadlineBorder, 2,slice,random));
break;
case 3:
resource = cBiasTask(random);
reward = resource[0] + resource[1] + resource[2];
task.add(new Task(i, resource, reward, random
.nextInt(deadlineRange + 1) + deadlineBorder, 3,slice,random));
break;
}
}
}
public void makeBid(int flag, ArrayList<Task> task,
ArrayList<ArrayList<Bid>> Bid, ArrayList<Agent> agent,
ArrayList<ArrayList<Bid>> agentBid, int bidNumber, Tactics tactics,
int value, int ratio, Random random) {
int timeHigh[];
int state = 0;
ArrayList<Bid> tempBid = new ArrayList<Bid>();
for (Agent bidder : agent) { // エージェントごとに
state = bidder.state();
if (bidder.state() > 0)
continue; // no queue
// タスクへ仮入札
/* if(bidder.queue() > 0){
for(Bid qTask : bidder.queue){
state += qTask.processingTime();
}
}*/
for (Task item : task) {
timeHigh = calculate(bidder.resource(), item.requiredResource()); // 処理時間、得意度計算
if (timeHigh[0] + state > item.deadline()) // 処理が間に合わないなら飛ばす
continue;
tempBid.add(new Bid(bidder.agentNumber(), item,
timeHigh[0]+state, timeHigh[2], 1,
timeHigh[1], value, ratio, random,timeHigh[0],bidder.tactics())); // 入札候補作成
}
// タスクへ仮入札
// 各戦略ごとに並び替え
if (tempBid.isEmpty() != true) {
tactics.sort(flag, bidder.tactics(), bidNumber, tempBid, Bid,
agentBid, tactics, value,random);
}
tempBid.clear();
}
}
public int[] calculate(int[] resource, int[] requiredResource) {
int time = (int) Math.ceil((double) requiredResource[0] / resource[0]);
int High = time;
int resourceSum = resource[0];
int requiredResourceSum = requiredResource[0];
int[] timeHigh = { time, High, 0 };
for (int i = 1; i < resource.length; i++) {
resourceSum += resource[i];
requiredResourceSum += requiredResource[i];
time = (int) Math.ceil((double) requiredResource[i] / resource[i]);
High = time;
if (timeHigh[0] < time)
timeHigh[0] = time;
if (timeHigh[1] > High)
timeHigh[1] = High;
}
timeHigh[1] = timeHigh[0] - timeHigh[1];
timeHigh[2] = resourceSum * timeHigh[0] - requiredResourceSum;
return timeHigh;
}
public void changeDeadline(int border, int range){
this.deadlineBorder = border;
this.deadlineRange = range;
}
public int[] normalAgent(Random random){
int resource[] = new int[3];
resource[0] = random.nextInt(4) + 4;
resource[1] = random.nextInt(4) + 4;
resource[2] = random.nextInt(4) + 4;
return resource;
}
public int[] highAgent(Random random){
int resource[] = new int[3];
resource[0] = random.nextInt(3) + 5;
resource[1] = random.nextInt(3) + 5;
resource[2] = random.nextInt(3) + 5;
return resource;
}
public int[] lowAgent(Random random){
int resource[] = new int[3];
resource[0] = random.nextInt(3) + 2;
resource[1] = random.nextInt(3) + 2;
resource[2] = random.nextInt(3) + 2;
return resource;
}
public int[] normalTask(Random random){
int resource[] = new int[3];
resource[0] = random.nextInt(21) + 30;
resource[1] = random.nextInt(21) + 30;
resource[2] = random.nextInt(21) + 30;
return resource;
}
public int[] aBias(Random random){
int resource[] = new int[3];
resource[0] = random.nextInt(3) + 7;
resource[1] = random.nextInt(3) + 2;
resource[2] = random.nextInt(3) + 2;
return resource;
}
public int[] aBiasTask(Random random){
int resource[] = new int[3];
resource[0] = random.nextInt(21) + 50;
resource[1] = random.nextInt(21) + 20;
resource[2] = random.nextInt(21) + 20;
return resource;
}
public int[] bBias(Random random){
int resource[] = new int[3];
resource[0] = random.nextInt(3) + 2;
resource[1] = random.nextInt(3) + 7;
resource[2] = random.nextInt(3) + 2;
return resource;
}
public int[] bBiasTask(Random random){
int resource[] = new int[3];
resource[0] = random.nextInt(21) + 20;
resource[1] = random.nextInt(21) + 50;
resource[2] = random.nextInt(21) + 20;
return resource;
}
public int[] cBias(Random random){
int resource[] = new int[3];
resource[0] = random.nextInt(3) + 2;
resource[1] = random.nextInt(3) + 2;
resource[2] = random.nextInt(3) + 7;
return resource;
}
public int[] cBiasTask(Random random){
int resource[] = new int[3];
resource[0] = random.nextInt(21) + 20;
resource[1] = random.nextInt(21) + 20;
resource[2] = random.nextInt(21) + 50;
return resource;
}
}
| true |
af9d5f92b9062db2045225c46e2729016cacd506
|
Java
|
igomez10/springTutorial
|
/src/main/java/com/company/SpringTutorial/dao/FakePersonDataAccessService.java
|
UTF-8
| 1,071 | 2.8125 | 3 |
[] |
no_license
|
package com.company.SpringTutorial.dao;
import com.company.SpringTutorial.model.Person;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Repository("fakeDao")
public class FakePersonDataAccessService implements PersonDao {
private static List<Person> DB = new ArrayList<>();
@Override
public int insertPerson(UUID id, Person person){
DB.add(new Person(id, person.getName()));
return 1;
}
@Override
public List<Person> selectAllPeople() {
return DB;
}
@Override
public Optional<Person> selectPersonByID(UUID id) {
for (Person currentPerson : DB) {
if (currentPerson.getId().equals(id)) {
return Optional.of(currentPerson);
}
}
return Optional.empty();
}
@Override
public int deletePersonById(UUID id) {
return 0;
}
@Override
public int updatePersonById(UUID id, Person person) {
return 0;
}
}
| true |
c5f175453df8a29b2be2a144f536b7b29a29d93d
|
Java
|
rnapoles/trunk-qooxdoo-contrib-code
|
/qooxdoo-contrib/QWT/tags/sushi-1.3.11/core/src/test/java/org/qooxdoo/sushi/metadata/reflect/ReflectSchemaTest.java
|
UTF-8
| 1,194 | 2.0625 | 2 |
[] |
no_license
|
/* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2006-2008 1&1 Internet AG, Germany, http://www.1and1.org
License:
LGPL: http://www.gnu.org/licenses/lgpl.html
EPL: http://www.eclipse.org/org/documents/epl-v10.php
See the LICENSE file in the project's top-level directory for details.
Authors:
* Michael Hartmeier (mlhartme)
************************************************************************ */
package org.qooxdoo.sushi.metadata.reflect;
import org.junit.Test;
import static org.junit.Assert.*;
import org.qooxdoo.sushi.fs.IO;
import org.qooxdoo.sushi.fs.Node;
import org.qooxdoo.sushi.fs.file.FileNode;
import org.qooxdoo.sushi.metadata.Type;
public class ReflectSchemaTest {
@Test
public void normal() {
Type type;
type = new ReflectSchema().type(IO.class);
assertEquals("iO", type.getName());
}
@Test
public void nodes() {
new ReflectSchema().type(IO.class);
new ReflectSchema().type(Node.class);
new ReflectSchema().type(FileNode.class);
}
}
| true |
881a25df3fc74b4966c373bc94cd77277b315f29
|
Java
|
mdh-git/learn
|
/src/main/java/com/mdh/algorithm/GreedyTest.java
|
UTF-8
| 2,257 | 3.84375 | 4 |
[] |
no_license
|
package com.mdh.algorithm;
import static java.lang.Math.min;
/**
* 贪心算法
*
* https://www.cxyxiaowu.com/852.html
*
* 从问题的某一初始解出发
* while (能朝给定总目标前进一步)
* do
* 选择当前最优解作为可行解的一个解元素;
* 由所有解元素组合成问题的一个可行解。
*
*
*
* 小明手中有 1,5,10,50,100 五种面额的纸币,每种纸币对应张数分别为 5,2,2,3,5 张。若小明需要支付 456 元,则需要多少张纸币?
* 制定的贪心策略为:在允许的条件下选择面额最大的纸币。
* @author madonghao
* @create 2020-01-15 13:57
**/
public class GreedyTest {
public static void main(String[] args) {
// 五种纸币的面额
int[] quota = { 1, 5, 10, 50, 100};
// 五种纸币对应的数量
int[] count = { 5, 2, 2, 3, 5};
int money = 456;
getResult(money, quota, count);
System.out.println("---------------------");
solve(money, quota, count);
}
private static int solve(int money, int[] quota, int[] count) {
int n = quota.length;
while (money > 0) {
int num = 0;
for(int i = n-1;i>=0;i--) {
int c = min(money/quota[i],count[i]);//每一个所需要的张数
money = money-c*quota[i];
num += c;//总张数
System.out.println("金额:" + quota[i] + ",需要" + c + "张");
}
if(money>0) num=-1;
System.out.println("一共需要:" + num + "张");
return num;
}
return -1;
}
private static void getResult(int money, int[] quota, int[] count) {
while (money > 0){
for (int i = quota.length; i > 0; i--) {
for(int j = count[i -1]; j > 0; j--){
if(money >= quota[i -1]){
money = money - quota[i -1];
System.out.println("面额:"+ quota[i -1]);
}
}
}
if(money > 0){
System.out.println("没有解决方法");
break;
}
}
}
}
| true |
ec64f7e8287a20dfdb03f2ccbe3a721bdbab0814
|
Java
|
pulumi/pulumi-gcp
|
/sdk/java/src/main/java/com/pulumi/gcp/workstations/inputs/WorkstationConfigHostGceInstanceShieldedInstanceConfigArgs.java
|
UTF-8
| 4,946 | 1.820313 | 2 |
[
"BSD-3-Clause",
"MPL-2.0",
"Apache-2.0"
] |
permissive
|
// *** WARNING: this file was generated by pulumi-java-gen. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package com.pulumi.gcp.workstations.inputs;
import com.pulumi.core.Output;
import com.pulumi.core.annotations.Import;
import java.lang.Boolean;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nullable;
public final class WorkstationConfigHostGceInstanceShieldedInstanceConfigArgs extends com.pulumi.resources.ResourceArgs {
public static final WorkstationConfigHostGceInstanceShieldedInstanceConfigArgs Empty = new WorkstationConfigHostGceInstanceShieldedInstanceConfigArgs();
/**
* Whether the instance has integrity monitoring enabled.
*
*/
@Import(name="enableIntegrityMonitoring")
private @Nullable Output<Boolean> enableIntegrityMonitoring;
/**
* @return Whether the instance has integrity monitoring enabled.
*
*/
public Optional<Output<Boolean>> enableIntegrityMonitoring() {
return Optional.ofNullable(this.enableIntegrityMonitoring);
}
/**
* Whether the instance has Secure Boot enabled.
*
*/
@Import(name="enableSecureBoot")
private @Nullable Output<Boolean> enableSecureBoot;
/**
* @return Whether the instance has Secure Boot enabled.
*
*/
public Optional<Output<Boolean>> enableSecureBoot() {
return Optional.ofNullable(this.enableSecureBoot);
}
/**
* Whether the instance has the vTPM enabled.
*
*/
@Import(name="enableVtpm")
private @Nullable Output<Boolean> enableVtpm;
/**
* @return Whether the instance has the vTPM enabled.
*
*/
public Optional<Output<Boolean>> enableVtpm() {
return Optional.ofNullable(this.enableVtpm);
}
private WorkstationConfigHostGceInstanceShieldedInstanceConfigArgs() {}
private WorkstationConfigHostGceInstanceShieldedInstanceConfigArgs(WorkstationConfigHostGceInstanceShieldedInstanceConfigArgs $) {
this.enableIntegrityMonitoring = $.enableIntegrityMonitoring;
this.enableSecureBoot = $.enableSecureBoot;
this.enableVtpm = $.enableVtpm;
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(WorkstationConfigHostGceInstanceShieldedInstanceConfigArgs defaults) {
return new Builder(defaults);
}
public static final class Builder {
private WorkstationConfigHostGceInstanceShieldedInstanceConfigArgs $;
public Builder() {
$ = new WorkstationConfigHostGceInstanceShieldedInstanceConfigArgs();
}
public Builder(WorkstationConfigHostGceInstanceShieldedInstanceConfigArgs defaults) {
$ = new WorkstationConfigHostGceInstanceShieldedInstanceConfigArgs(Objects.requireNonNull(defaults));
}
/**
* @param enableIntegrityMonitoring Whether the instance has integrity monitoring enabled.
*
* @return builder
*
*/
public Builder enableIntegrityMonitoring(@Nullable Output<Boolean> enableIntegrityMonitoring) {
$.enableIntegrityMonitoring = enableIntegrityMonitoring;
return this;
}
/**
* @param enableIntegrityMonitoring Whether the instance has integrity monitoring enabled.
*
* @return builder
*
*/
public Builder enableIntegrityMonitoring(Boolean enableIntegrityMonitoring) {
return enableIntegrityMonitoring(Output.of(enableIntegrityMonitoring));
}
/**
* @param enableSecureBoot Whether the instance has Secure Boot enabled.
*
* @return builder
*
*/
public Builder enableSecureBoot(@Nullable Output<Boolean> enableSecureBoot) {
$.enableSecureBoot = enableSecureBoot;
return this;
}
/**
* @param enableSecureBoot Whether the instance has Secure Boot enabled.
*
* @return builder
*
*/
public Builder enableSecureBoot(Boolean enableSecureBoot) {
return enableSecureBoot(Output.of(enableSecureBoot));
}
/**
* @param enableVtpm Whether the instance has the vTPM enabled.
*
* @return builder
*
*/
public Builder enableVtpm(@Nullable Output<Boolean> enableVtpm) {
$.enableVtpm = enableVtpm;
return this;
}
/**
* @param enableVtpm Whether the instance has the vTPM enabled.
*
* @return builder
*
*/
public Builder enableVtpm(Boolean enableVtpm) {
return enableVtpm(Output.of(enableVtpm));
}
public WorkstationConfigHostGceInstanceShieldedInstanceConfigArgs build() {
return $;
}
}
}
| true |
aa6b59e130746e5c5ad372b5280538184708975a
|
Java
|
fortestaa/leetcode
|
/easy/BalancedBinaryTree.java
|
UTF-8
| 883 | 3.859375 | 4 |
[] |
no_license
|
package easy;
/**
* 110 Balanced Binary Tree
* https://leetcode.com/problems/balanced-binary-tree/
*
* Given a binary tree, determine if it is height-balanced.
* For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
*/
public class BalancedBinaryTree {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1
&& isBalanced(root.left)
&& isBalanced(root.right);
}
private int maxDepth(TreeNode n) {
if (n == null) return 0;
return Math.max(maxDepth(n.left), maxDepth(n.right)) + 1;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
}
| true |
33d6094d27ca0d4ba17af66e6f90e83441ea3570
|
Java
|
UchihaSean/Web_Similar_To_Zhihu
|
/IdeaProjects/PJ2/src/RegisterServlet.java
|
UTF-8
| 1,691 | 2.546875 | 3 |
[] |
no_license
|
import net.sf.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
response.setHeader("Access-Control-Allow-Origin","*");
String username = request.getParameter("username");
String email = request.getParameter("email");
String password = request.getParameter("password");
DBUtil db = new DBUtil();//构建数据库对象
// System.out.print("hello");
String registerStat = db.registerSuccess(username, email, password);
System.out.print(registerStat);
if(!registerStat.equals("-1")){
//注册成功!
String uid = registerStat;
JSONObject obj = new JSONObject();
obj.put("status","true");
obj.put("uid",uid);
// obj.toString();
response.getWriter().print(obj);
}
else{
//注册失败
JSONObject obj = new JSONObject();
obj.put("status","false");
// obj.put("uid","-1");
// obj.toString();
response.getWriter().print(obj);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
| true |
980405dc4f1b4e2d3812e1431372e38782b7213c
|
Java
|
big-long/virus
|
/src/main/java/com/kemyond/virus/service/impl/VirusServiceImpl.java
|
UTF-8
| 2,747 | 2.015625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.kemyond.virus.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kemyond.virus.common.CodeMessage;
import com.kemyond.virus.common.Record;
import com.kemyond.virus.dao.HisVirusMapper;
import com.kemyond.virus.domain.HisVirus;
import com.kemyond.virus.domain.HisVirusExample;
import com.kemyond.virus.service.VirusService;
import com.kemyond.virus.util.ClamavUtil;
import com.kemyond.virus.vo.qo.BaseQo;
import com.kemyond.virus.vo.qo.HisVirusQo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author zdl
* @Date 2021/1/5 10:54
* @Version 1.0
*/
@Service
public class VirusServiceImpl implements VirusService {
@Autowired
HisVirusMapper hisVirusMapper;
@Override
public Record getList(HisVirusQo qo) {
PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
List<HisVirus> hisViri = hisVirusMapper.selecltByCondition(qo);
return new Record(new PageInfo(hisViri));
}
@Override
public Record startTask(String fileName) {
return null;
}
@Override
public Record getVersion() throws Exception {
Map<String,Object> map=new HashMap<>();
String result = ClamavUtil.getVersion();
String[] arr = result.split("\\s+");
String month=ClamavUtil.getMonthNum(arr[2]);
String[] versions = arr[1].split("/");
StringBuffer buffer=new StringBuffer();
buffer.append(arr[5].trim()).append("-").append(month).append("-").append(arr[3]).append(" ").append(arr[4]);
map.put("sysVersion",versions[0]);
map.put("dbVersion",versions[1]);
map.put("status",1);
map.put("dbVersionDate",buffer.toString());
return new Record(map);
}
@Override
public Record getScanStatus(String fileMark) throws Exception {
Record result=null;
Byte scanStatus=3;
String detail ="";
try {
HisVirusExample example=new HisVirusExample();
example.createCriteria().andFileMarkEqualTo(fileMark);
List<HisVirus> hisViri = hisVirusMapper.selectByExample(example);
if(hisViri!=null&&hisViri.size()>0){
scanStatus = hisViri.get(0).getScanStatus();
detail=hisViri.get(0).getDetail();
}
Map map=new HashMap();
map.put("scanStatus",scanStatus);
map.put("scanDetail", detail);
result=new Record(map);
}catch (Exception e){
result=new Record(Record.FAILURE,"操作失败",e);
}
return result;
}
}
| true |
db2625123ef14cd4b223d59b0b5b3925e7a7a7ea
|
Java
|
jalpan-randeri/map-reduce
|
/flight_delay_v2/src/mapper/FlightMapper.java
|
UTF-8
| 1,785 | 2.796875 | 3 |
[] |
no_license
|
package mapper;
import com.opencsv.CSVParser;
import conts.FlightConst;
import model.Key;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
/**
* Created by jalpanranderi on 3/13/15.
*/
public class FlightMapper extends Mapper<Object, Text, Key, DoubleWritable> {
private static final String DIVERTED = "1";
private static final String CANCELLED = "1";
private static final String YEAR = "2008";
private CSVParser mParser = new CSVParser();
@Override
protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String[] data = mParser.parseLine(value.toString());
if (isValid(data) &&
!(data[FlightConst.INDEX_DIVERTED].equals(DIVERTED) ||
data[FlightConst.INDEX_CANCELED].equals(CANCELLED)) &&
data[FlightConst.INDEX_YEAR].equals(YEAR)) {
Key mKey = new Key(data[FlightConst.INDEX_AIRLINE], Integer.parseInt(data[FlightConst.INDEX_MONTH]));
double mValue = Double.parseDouble(data[FlightConst.INDEX_DELAY]);
context.write(mKey, new DoubleWritable(mValue));
}
}
/**
* isValid checks for empty values in input
*
* @param data String[] input
* @return true iff input does not contains any empty values
*/
private boolean isValid(String[] data) {
return !(data[FlightConst.INDEX_MONTH].isEmpty() ||
data[FlightConst.INDEX_AIRLINE].isEmpty() ||
data[FlightConst.INDEX_CANCELED].isEmpty() ||
data[FlightConst.INDEX_DIVERTED].isEmpty() ||
data[FlightConst.INDEX_DELAY].isEmpty());
}
}
| true |
0d5e0045a924f94dc08dea51fa908c06942a9380
|
Java
|
jiangyukun/ttsales-web
|
/src/main/java/cn/ttsales/work/persistence/sys/impl/SysRoleDaoImpl.java
|
UTF-8
| 1,621 | 2.1875 | 2 |
[] |
no_license
|
/**
* Copyright (c) 2013 RATANSOFT.All rights reserved.
* @filename SysRoleDaoImpl.java
* @package cn.ttsales.work.persistence.sys.impl
* @author dandyzheng
* @date 2012-7-27
*/
package cn.ttsales.work.persistence.sys.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import cn.ttsales.work.core.jpa.AbstractFacade;
import cn.ttsales.work.domain.SysRole;
import cn.ttsales.work.persistence.sys.SysRoleDao;
/**
* SysRole Dao Impl
* @author dandyzheng
*
*/
@Repository("sysRoleDao")
public class SysRoleDaoImpl extends AbstractFacade implements SysRoleDao {
@PersistenceContext(unitName="MAIN_DATABASE_PER")
private EntityManager entityManager;
@Override
protected EntityManager getEntityManager() {
return entityManager;
}
public SysRole saveSysRole(SysRole sysRole) {
return persist(sysRole);
}
public List<SysRole> saveSysRoles(List<SysRole> sysRoles) {
return persist(sysRoles);
}
public SysRole editSysRole(SysRole sysRole) {
return merge(sysRole);
}
public List<SysRole> editSysRoles(List<SysRole> sysRoles) {
return merge(sysRoles);
}
public void removeSysRole(SysRole sysRole) {
remove(getSysRole(sysRole.getRoleId()));
}
public void removeSysRoles(List<SysRole> sysRoles) {
remove(sysRoles);
}
public void removeSysRole(String sysRoleId) {
remove(sysRoleId);
}
public SysRole getSysRole(String sysRoleId) {
return find(SysRole.class, sysRoleId);
}
public List<SysRole> getAllSysRoles() {
return this.find("from SysRole s");
}
}
| true |
9e7ba7365d7557933f096cd70a21f14bdea2e0c7
|
Java
|
tjudoubi/vben-admin-java
|
/api-server/src/main/java/com/xm/api/authorization/constant/TokenConstant.java
|
UTF-8
| 1,389 | 2.21875 | 2 |
[] |
no_license
|
package com.xm.api.authorization.constant;
/**
* Token相关常量
*
* @author xiaomalover <[email protected]>
*/
public class TokenConstant {
/**
* 控制端TOKEN
*/
public final static int TOKEN_TYPE_CONTROL = 1;
/**
* 设备端TOKEN
*/
public final static int TOKEN_TYPE_TERMINAL = 2;
/**
* 控制端TOKEN过期时间常量
*/
public final static int CONTROL_TOKEN_EXPIRED = 15 * 3600;
/**
* 设备端TOKEN过过期时间常量
*/
public final static int TERMINAL_TOKEN_EXPIRED = 15 * 3600;
/**
* 控制端用户Token前缀常量
*/
public final static String CONTROL_TOKEN_KEY_PREFIX = "control_token_";
/**
* 设备端用户Token前缀常量
*/
public final static String TERMINAL_TOKEN_KEY_PREFIX = "terminal_token_";
/**
* 控制端用户id与token映射缓存常量
*/
public final static String CONTROL_TOKEN_HASH_KEY_PREFIX = "control_token_hash_";
/**
* 设备端用户id与token映射缓存常量
*/
public final static String TERMINAL_TOKEN_HASH_KEY_PREFIX = "terminal_token_hash_";
/**
* 校验参数名常量
*/
public final static String CONTROL_TOKEN_PARAM_NAME = "control_token";
/**
* 校验参数名常量
*/
public final static String TERMINAL_TOKEN_PARAM_NAME = "terminal_token";
}
| true |
006327064b3d56931289253a05a230e48829c91f
|
Java
|
hegdevishwa/packer
|
/src/test/java/com/mobiquityinc/packer/PackerTest.java
|
UTF-8
| 1,309 | 2.875 | 3 |
[] |
no_license
|
package com.mobiquityinc.packer;
import static org.junit.Assert.*;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import org.junit.Test;
import com.mobiquityinc.exception.APIException;
public class PackerTest {
private static String validInputFile = "resource/valid-input-file.txt";
private static String invalidInputFile = "resource/invalid-input-file.txt";
@Test
public void testPack_with_valid_input_format() throws APIException, URISyntaxException {
String expected = "4\n" + "-\n" + "2,7\n" + "8,9\n";
String actual = Packer.pack(getAbsolutePath(validInputFile));
System.out.println(actual);
assertEquals(expected, actual);
}
@Test(expected = APIException.class)
public void testPack_with_invalid_input_format() throws APIException, URISyntaxException {
Packer.pack(getAbsolutePath(invalidInputFile));
}
@Test(expected = APIException.class)
public void testPack_no_file_available() throws APIException {
Packer.pack("fileDoesNotExist");
}
private String getAbsolutePath(String relativePath) throws URISyntaxException {
URL res = getClass().getClassLoader().getResource(relativePath);
File file = Paths.get(res.toURI()).toFile();
String absolutePath = file.getAbsolutePath();
return absolutePath;
}
}
| true |
30faf0fc78e9b0448f29fa3ba983aea402ba3c8c
|
Java
|
jackyoh/superagent-example-practice
|
/webproject/src/main/java/idv/jack/webserver/HelloWroldResource.java
|
UTF-8
| 1,014 | 2.421875 | 2 |
[] |
no_license
|
package idv.jack.webserver;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.google.gson.Gson;
@Path("hello")
public class HelloWroldResource {
@GET
@Path("function1")
@Produces(MediaType.APPLICATION_JSON)
public Response function1(){
//return "{key:\'value\'}";
Gson gson = new Gson();
String toJson = gson.toJson("runningJobsTest");
return Response.status(200).entity(toJson).build();
}
@GET
@Path("list")
public Response list(){
List<String> list = new ArrayList<String>();
list.add("aaaa");
list.add("bbbb");
list.add("ccccc");
Gson gson = new Gson();
String toJson = gson.toJson(list);
return Response.status(200)
.entity(toJson)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.build();
}
}
| true |
778fc1cc7b01f19f4171597a642a653901d29f62
|
Java
|
yataoXu/janusgraph-example
|
/src/main/java/com/example/janusgraph/DTO/EdgeDTO.java
|
UTF-8
| 266 | 1.59375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.example.janusgraph.DTO;
import lombok.Data;
/**
* @Classname EdgeDto
* @Description
* @Date 2019/12/17 10:26
* @Created by Evan
*/
@Data
public class EdgeDTO {
private long LVRecord;
private long RVRecord;
private String Content;
}
| true |
2f7d7318864429eeb99c4e19356b0c6eacff8e95
|
Java
|
david-shao/codepath-app1
|
/app/src/main/java/com/david/flickster/models/Movie.java
|
UTF-8
| 5,359 | 2.453125 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.david.flickster.models;
import com.david.flickster.activities.MovieActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by David on 3/11/2017.
*/
public class Movie implements Serializable {
String posterPath;
String backdropPath;
String originalTitle;
String overview;
double rating;
String releaseDate;
int movieId;
List<String> videoKeys;
static Random rand = new Random();
public Movie(JSONObject jsonObject) throws JSONException {
posterPath = jsonObject.getString("poster_path");
originalTitle = jsonObject.getString("original_title");
overview = jsonObject.getString("overview");
backdropPath = jsonObject.getString("backdrop_path");
rating = jsonObject.getDouble("vote_average");
releaseDate = jsonObject.getString("release_date");
movieId = jsonObject.getInt("id");
videoKeys = new ArrayList<>();
// String videoUrl = "https://api.themoviedb.org/3/movie/%s/videos?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed";
// Log.d("DEBUG", "doing async call to get videos for movie " + movieId);
// AsyncHttpClient client = new AsyncHttpClient();
// client.get(String.format(videoUrl, movieId), new JsonHttpResponseHandler() {
// @Override
// public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// JSONArray movieJsonResults = null;
// try {
// movieJsonResults = response.getJSONArray("results");
// for (int i = 0; i < movieJsonResults.length(); i++) {
// JSONObject video = movieJsonResults.getJSONObject(i);
// if (video.getString("type").equals("Trailer")) {
// videoKeys.add(video.getString("key"));
// }
// }
// } catch (JSONException e) {
// e.printStackTrace();
// }
// }
//
// @Override
// public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
// Log.d("DEBUG", "Failed getting videos: " + responseString);
// }
// });
String url = "https://api.themoviedb.org/3/movie/%s/videos";
url = String.format(url, movieId);
HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
urlBuilder.addQueryParameter("api_key", "a07e22bc18f5cb106bfe4cc1f83ad8ed");
url = urlBuilder.build().toString();
Request request = new Request.Builder()
.url(url)
.build();
MovieActivity.httpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Movie response unsuccessful for id: " + movieId + " response: " + response);
}
JSONArray movieJsonResults = null;
try {
String responseData = response.body().string();
JSONObject json = new JSONObject(responseData);
movieJsonResults = json.getJSONArray("results");
for (int i = 0; i < movieJsonResults.length(); i++) {
JSONObject video = movieJsonResults.getJSONObject(i);
if (video.getString("type").equals("Trailer")) {
videoKeys.add(video.getString("key"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public static List<Movie> fromJSONArray(JSONArray array) {
List<Movie> results = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
try {
results.add(new Movie(array.getJSONObject(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
return results;
}
public String getPosterPath() {
return String.format("https://image.tmdb.org/t/p/w342%s", posterPath);
}
public String getOriginalTitle() {
return originalTitle;
}
public String getOverview() {
return overview;
}
public String getBackdropPath() {
return String.format("https://image.tmdb.org/t/p/w342%s", backdropPath);
}
public double getRating() {
return rating;
}
public String getReleaseDate() {
return releaseDate;
}
public String getVideoKey() {
if (videoKeys.size() > 0) {
int i = rand.nextInt(videoKeys.size());
if (i < videoKeys.size()) {
return videoKeys.get(i);
}
}
return "";
}
}
| true |
14b1d627b2073909532bf9ddfa0f66e520c0e55c
|
Java
|
SkyJourney/vermilion
|
/src/main/java/top/icdat/vermilion/exception/NotOperatorClassException.java
|
UTF-8
| 351 | 2.28125 | 2 |
[] |
no_license
|
package top.icdat.vermilion.exception;
public class NotOperatorClassException extends RuntimeException {
public NotOperatorClassException() {
}
public NotOperatorClassException(String message) {
super(message);
}
public NotOperatorClassException(String message, Throwable cause) {
super(message, cause);
}
}
| true |
1c4e82046bcdad041bfbcf19e729f7d5571b40f8
|
Java
|
Programito/Proyecto2
|
/app-collection/src/main/java/entities/User.java
|
UTF-8
| 1,305 | 2.3125 | 2 |
[] |
no_license
|
package entities;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
@Entity
@NamedQueries({
@NamedQuery(name=User.QUERY_USER_BY_EMAIL,
query = "SELECT u FROM User u WHERE u.email =:email"),
})
public class User {
public static final String QUERY_USER_BY_EMAIL="findByEmail";
@Id
@GeneratedValue(strategy =GenerationType.AUTO)
private String id;
private String name;
private String email;
@OneToMany(mappedBy ="user",
cascade = CascadeType.ALL, orphanRemoval=true)
private Set<Collection> collections = new HashSet<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Set<Collection> getCollections() {
return collections;
}
}
| true |
175085af39523e0328a9262ab90393e78d2ea9e3
|
Java
|
jgbcientista/desafio-01
|
/src/test/java/br/com/bluesoft/desafio/api/PedidoControllerTest.java
|
UTF-8
| 4,386 | 2.140625 | 2 |
[] |
no_license
|
package br.com.bluesoft.desafio.api;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import br.com.bluesoft.desafio.DesafioApplication;
import br.com.bluesoft.desafio.data.PedidoRequest;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = DesafioApplication.class)
@SpringBootTest
public class PedidoControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setUpBeforeClass() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
}
@Test
public void testRecuperarPedidos() throws Exception {
this.mockMvc.perform(get("/api/pedidos")).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.pedidos", hasSize(0)))
.andExpect(jsonPath("$.mensagem", isEmptyOrNullString()));
}
@Test
public void testRealizarPedido() throws Exception {
List<PedidoRequest> pedidoRequestLista = new ArrayList<>();
PedidoRequest pedidoRequest01 = new PedidoRequest();
pedidoRequest01.setGtin("7891000053508");
pedidoRequest01.setQuantidade(5);
PedidoRequest pedidoRequest02 = new PedidoRequest();
pedidoRequest02.setGtin("7891000100103");
pedidoRequest02.setQuantidade(3);
PedidoRequest pedidoRequest03 = new PedidoRequest();
pedidoRequest03.setGtin("7891910000197");
pedidoRequest03.setQuantidade(2);
pedidoRequestLista.add(pedidoRequest01);
pedidoRequestLista.add(pedidoRequest02);
pedidoRequestLista.add(pedidoRequest03);
this.mockMvc
.perform(post("/api/pedidos")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(pedidoRequestLista)))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.pedidos", hasSize(2))) // Valor previamente identificado para o teste
.andExpect(jsonPath("$.mensagem", isEmptyOrNullString()));
}
@Test
public void testRealizarPedidoFornecedoresNaoIdentificados() throws Exception {
List<PedidoRequest> pedidoRequestLista = new ArrayList<>();
PedidoRequest pedidoRequest01 = new PedidoRequest();
pedidoRequest01.setGtin("7891000053508");
pedidoRequest01.setQuantidade(0);
PedidoRequest pedidoRequest02 = new PedidoRequest();
pedidoRequest02.setGtin("7891000100103");
pedidoRequest02.setQuantidade(0);
PedidoRequest pedidoRequest03 = new PedidoRequest();
pedidoRequest03.setGtin("7891910000197");
pedidoRequest03.setQuantidade(0);
pedidoRequestLista.add(pedidoRequest01);
pedidoRequestLista.add(pedidoRequest02);
pedidoRequestLista.add(pedidoRequest03);
this.mockMvc
.perform(post("/api/pedidos")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(pedidoRequestLista)))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.pedidos").isEmpty())
.andExpect(jsonPath("$.mensagem")
.value("Nenhum fornecedor encontrado para a quantidade solicitada do(s) produto(s)"));
}
}
| true |
9ca08874cce02b8364bd99cf8c726a9e2eb89874
|
Java
|
josemarsp/GitHubAPI
|
/app/src/main/java/br/com/josef/desafioconcretegit/view/adapter/GitAdapter.java
|
UTF-8
| 3,119 | 2.28125 | 2 |
[] |
no_license
|
package br.com.josef.desafioconcretegit.view.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.List;
import br.com.josef.desafioconcretegit.R;
import br.com.josef.desafioconcretegit.model.pojo.repositories.Item;
import br.com.josef.desafioconcretegit.view.interfaces.GitOnClick;
import de.hdodenhof.circleimageview.CircleImageView;
public class GitAdapter extends RecyclerView.Adapter<GitAdapter.ViewHolder> {
private List<Item> resultList;
private GitOnClick listener;
public GitAdapter(List<Item> resultList, GitOnClick listener) {
this.resultList = resultList;
this.listener = listener;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_recycler_main, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Item result = this.resultList.get(position);
holder.onBind(result);
holder.itemView.setOnClickListener(v -> {
listener.OnClick(result);
});
}
@Override
public int getItemCount() {
return resultList.size();
}
public void atualizalista(List<Item> results) {
if (resultList.isEmpty()) {
this.resultList = results;
notifyDataSetChanged();
} else {
this.resultList.addAll(results);
}
notifyDataSetChanged();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView nomeRep;
private TextView nomeCompleto;
private TextView nomeLogin;
private TextView descricaoRepo;
private TextView numerosForks;
private TextView numeroStars;
private CircleImageView fotoPerfil;
public ViewHolder(View view) {
super(view);
nomeRep = view.findViewById(R.id.NomeRepo);
nomeLogin = view.findViewById(R.id.UserNameLogin);
nomeCompleto = view.findViewById(R.id.nomeSobrenome);
descricaoRepo = view.findViewById(R.id.DescriRepo);
numerosForks = view.findViewById(R.id.ForksRepo);
numeroStars = view.findViewById(R.id.numeroStars);
fotoPerfil = view.findViewById(R.id.fotoPerfilCard);
}
void onBind(Item result) {
nomeRep.setText(result.getName());
nomeLogin.setText(result.getOwner().getLogin());
nomeCompleto.setText(result.getFullName());
descricaoRepo.setText(result.getDescription());
numeroStars.setText(result.getStargazersCount().toString());
numerosForks.setText(result.getForksCount().toString());
Picasso.get().load(result.getOwner().getAvatarUrl()).into(fotoPerfil);
}
}
}
| true |
4f349864ef43560e6617f76ba6ce404f981fa980
|
Java
|
peanutes/firstrepository
|
/repository/ht1/src/main/java/cn/tarena/ht/mapper/RoleMapper.java
|
UTF-8
| 192 | 1.710938 | 2 |
[] |
no_license
|
package cn.tarena.ht.mapper;
import java.util.List;
import cn.tarena.ht.pojo.Role;
public interface RoleMapper {
public List<Role> findAll();
public void delete(String[] roleIds);
}
| true |
df3869c4c5f5acc0ddb3b774f81b04d66b1175e1
|
Java
|
maurocabor521/FitnessGoal2
|
/app/src/main/java/com/example/andrescabal/navdrawer/presentation/contract/CategoriaAlimentosContract.java
|
UTF-8
| 728 | 2.21875 | 2 |
[] |
no_license
|
package com.example.andrescabal.navdrawer.presentation.contract;
import android.content.Context;
import com.example.andrescabal.navdrawer.domain.model.Alimento;
import java.util.List;
/**
* Created by Andrés Cabal on 7/05/2018.
*/
public interface CategoriaAlimentosContract {
interface Presenter{
List<Alimento> getListaAlimentos();
//devuelve el resultado lista, no va a lc caso de uso
List<String> getLstNombreAlimentos();
//llama el caso de uso
void loadListaAlimentos();
void crearReceta(Context context,String nombre, List<String>alimentos);
}
interface View{
void disableButtons();
void showListaAlimentos();
void getAdapter();
}
}
| true |
bc1ad86c7cc29f231a73d210ad00b9234afa7e3f
|
Java
|
shaunmahony/multigps-archive
|
/src/edu/psu/compbio/seqcode/gse/deepseq/utilities/BowtieFileReader.java
|
UTF-8
| 4,677 | 2.5 | 2 |
[
"MIT"
] |
permissive
|
package edu.psu.compbio.seqcode.gse.deepseq.utilities;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import edu.psu.compbio.seqcode.gse.datasets.species.Genome;
import edu.psu.compbio.seqcode.gse.deepseq.Read;
import edu.psu.compbio.seqcode.gse.deepseq.ReadHit;
/**
* Here: <br>
* <tt>totalHits</tt>: total number of hits for this file. (Only unique reads are
* counted if the corresponding boolean parameter <tt>useNonUnique</tt> is set to false. <br>
* <tt>totalWeight = totalHits</tt>
* @author shaunmahony
*
*/
public class BowtieFileReader extends AlignmentFileReader {
public BowtieFileReader(File f, Genome g, boolean useNonUnique, int idStart) {
super(f,g,-1,useNonUnique, idStart);
}
//Estimate chromosome lengths
protected void estimateGenome() {
HashMap<String, Integer> chrLenMap = new HashMap<String, Integer>();
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(inFile));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if(line.charAt(0)!='#'){
String[] words = line.split("\\s+");
if(readLength==-1)
readLength = words[4].length();
String chr = words[2];
String[] tmp = chr.split("\\.");
chr=tmp[0].replaceFirst("chr", "");
chr=chr.replaceFirst("^>", "");
int max = new Integer(words[3]).intValue()+readLength;
if(!chrLenMap.containsKey(chr) || chrLenMap.get(chr)<max)
chrLenMap.put(chr, max);
}
}
gen=new Genome("Genome", chrLenMap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Return the total reads and weight
protected void countReads() {
try {
readLength=-1;
totalHits=0;
totalWeight=0;
BufferedReader reader = new BufferedReader(new FileReader(inFile));
String line, lastID="";
double currReadHitCount=0;
Read currRead=null;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.length()==0) continue;
if(line.charAt(0)!='#'){
String[] words = line.split("\\t");
String chr="."; char strand = '.';
int start=0, end=0;
String ID = words[0];
if(readLength==-1)
readLength = words[4].length();
boolean newRead=true;
if(ID.equals(lastID)){
currReadHitCount++;
newRead=false;
}else{
if(currRead!=null){
Read filterRead = currReadHitCount==1 ? currRead : currRead.filter();
if(filterRead.getNumHits()==1 || useNonUnique){
//Add the hits to the data structure
addHits(filterRead);
totalWeight++;
}currRead=null;
}
currReadHitCount=1;
}
int mis=0;
if(words.length>7 && words[7].length()>1){
mis = words[7].split(",").length;
}
chr = words[2];
String[] tmp = chr.split("\\.");
chr=tmp[0].replaceFirst("chr", "");
chr=chr.replaceFirst("^>", "");
start = new Integer(words[3]).intValue();
end =start+readLength-1;
strand = words[1].charAt(0);
ReadHit currHit = new ReadHit(gen,currID,chr, start, end, strand, 1, mis);
currID++;
if(newRead || currRead==null){
currRead = new Read((int)totalWeight);
}
currRead.addHit(currHit);
lastID=ID;
}
}
if(currRead!=null){
Read filterRead = currReadHitCount==1 ? currRead : currRead.filter();
if(filterRead.getNumHits()==1 || useNonUnique){
//Add the hits to the data structure
addHits(filterRead);
totalWeight++;
}
}
reader.close();
populateArrays();
} catch (IOException e) {
e.printStackTrace();
}
}//end of countReads method
}//end of BowtieFileReader class
| true |
aa4c80bc8469ed31febcab0604c2f6c0cff3fa88
|
Java
|
Volcannozzz/FirstDemo_struts
|
/src/com/hb/services/UserService.java
|
UTF-8
| 1,697 | 2.515625 | 3 |
[] |
no_license
|
package com.hb.services;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import com.hb.domain.User;
import com.hb.util.SqlHelper;
public class UserService {
public User getUser(String username){
String sqlString = "select * from users where name=?";
String[] para = {username};
ResultSet rs = SqlHelper.executeQuery(sqlString, para);
ArrayList al = getUserList();
User user = new User();
user.setName(username);
user.setGoalfilename(((User)(al.get(0))).getGoalfilename());
user.setSourcefilename(((User)(al.get(0))).getSourcefilename());
return user;
}
public boolean saveRegisterUsers(User user){
String sqlString = "insert into users values(?,?,?)";
String[] para = {user.getName(),user.getGoalfilename(),user.getSourcefilename()};
try {
SqlHelper.executeUpdate(sqlString, para);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public ArrayList getUserList(){
String sql = "select * from users";
try {
ArrayList aList = SqlHelper.convertList(SqlHelper.executeQuery(sql, null));
ArrayList<User> aList2 = new ArrayList<User>();
for(int i = 0;i<aList.size();i++){
User user = new User();
user.setName(((Map)(aList.get(i))).get("name").toString());
user.setGoalfilename(((Map)(aList.get(i))).get("goalfilename").toString());
user.setSourcefilename(((Map)(aList.get(i))).get("sourcefilename").toString());
aList2.add(user);
}
return aList2;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
| true |
1183cef5857634f0fedd186e912bc549c492eae4
|
Java
|
jferna57/sceain2
|
/demo-webapp/src/test/java/es/in2/framework/demo/persistence/hibernate/AlunoPK.java
|
UTF-8
| 1,695 | 1.882813 | 2 |
[] |
no_license
|
/*
* Demoiselle Framework
* Copyright (c) 2009 Serpro and other contributors as indicated
* by the @author tag. See the copyright.txt in the distribution for a
* full listing of contributors.
*
* Demoiselle Framework is an open source Java EE library designed to accelerate
* the development of transactional database Web applications.
*
* Demoiselle Framework is released under the terms of the LGPL license 3
* http://www.gnu.org/licenses/lgpl.html LGPL License 3
*
* This file is part of Demoiselle Framework.
*
* Demoiselle Framework is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License 3 as published by
* the Free Software Foundation.
*
* Demoiselle Framework is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Demoiselle Framework. If not, see <http://www.gnu.org/licenses/>.
*/
package es.in2.framework.demo.persistence.hibernate;
import java.io.Serializable;
import javax.persistence.Embeddable;
/**
* @author CETEC/CTJEE
*/
@Embeddable
public class AlunoPK implements Serializable{
private static final long serialVersionUID = 1L;
private String sobrenome,nome;
public String getSobrenome() {
return sobrenome;
}
public void setSobrenome(String sobrenome) {
this.sobrenome = sobrenome;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
| true |
b65dd9714d0fa206f16b7f3be6815f7c8e7d0b4a
|
Java
|
NickJosephson/Myme
|
/app/src/test/java/com/nitrogen/myme/tests/Business/AccessMemeTemplatesIT.java
|
UTF-8
| 2,568 | 2.71875 | 3 |
[] |
no_license
|
package com.nitrogen.myme.tests.Business;
import com.nitrogen.myme.application.Services;
import com.nitrogen.myme.business.AccessMemeTemplates;
import com.nitrogen.myme.business.Exceptions.TemplateNotFoundException;
import com.nitrogen.myme.tests.utils.TestUtils;
import org.junit.Test;
import org.junit.After;
import org.junit.Before;
import java.io.File;
import java.io.IOException;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
public class AccessMemeTemplatesIT {
private File tempDB;
private AccessMemeTemplates accessMemeTemplates;
@Before
public void setUp() throws IOException {
System.out.println("Starting tests for AccessMemeTemplates...");
// build database
tempDB = TestUtils.copyDB();
accessMemeTemplates = new AccessMemeTemplates();
assertNotNull(accessMemeTemplates);
}
@Test
public void testInstanceNotNull() {
AccessMemeTemplates newInstance = new AccessMemeTemplates();
assertNotNull(newInstance);
}
/* Method: getTemplates() */
@Test
public void testGetTemplates() {
// Retrieve all templates in the database
System.out.println("...Testing getTemplates()");
assertTrue(accessMemeTemplates.getTemplates().size() >= 0);
}
/* Method: getTemplateByName() */
@Test
public void testGetTemplateByName_validName() {
// Retrieve a template with a name we know exists in the database
System.out.println("...Testing getTemplateByID() with a name we know is in the database");
boolean success = true;
try{
accessMemeTemplates.getTemplateByName("Two buttons");
} catch (TemplateNotFoundException e) {
success = false;
}
assertTrue(success);
}
@Test
public void testGetTemplateByName_invalidName() {
// Retrieve a template with a name we know doesn't exist in the database
System.out.println("...Testing getTemplateByName() with an name we know is not in the database");
boolean success = true;
try{
accessMemeTemplates.getTemplateByName("");
} catch (TemplateNotFoundException e) {
success = false;
}
assertFalse(success);
}
@After
public void tearDown() {
// delete file
tempDB.delete();
// forget DB
Services.clean();
System.out.println("\nFinished tests.\n");
}
}
| true |
72ed305a494d972bbc4488ae1c9e272d6e3ca66b
|
Java
|
sola97/VRChatNotificationBot
|
/src/main/java/cn/sola97/vrchat/utils/ProxyUtil.java
|
UTF-8
| 2,303 | 2.640625 | 3 |
[] |
no_license
|
package cn.sola97.vrchat.utils;
import org.eclipse.jetty.client.HttpProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ProxyUtil {
private static String proxyPatternString = "(http|socks)[5]?://(.+):(\\d+)";
private static Pattern proxyPattern = Pattern.compile(proxyPatternString, Pattern.CASE_INSENSITIVE);
private static final Logger logger = LoggerFactory.getLogger(ProxyUtil.class);
private static String[] parseProxy(String proxyString) {
Matcher m = proxyPattern.matcher(proxyString);
if (m.find())
return new String[]{m.group(1), m.group(2), m.group(3)};
return new String[0];
}
public static Proxy getProxy(String proxy) {
if(proxy==null || proxy.isEmpty())return null;
String[] args = parseProxy(proxy);
if(args.length==0)return null;
switch (args[0].toUpperCase()) {
case "HTTP":
return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(args[1], Integer.parseInt(args[2])));
case "SOCKS":
return new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(args[1], Integer.parseInt(args[2])));
default:
logger.warn("unsupport proxy type,ignored.");
return null;
}
}
public static org.eclipse.jetty.client.ProxyConfiguration.Proxy getJettyProxy(String proxy) {
if (proxy == null || proxy.isEmpty()) return null;
String[] args = parseProxy(proxy);
if (args.length == 0) return null;
switch (args[0].toUpperCase()) {
case "HTTP":
return new HttpProxy(args[1], Integer.parseInt(args[2]));
// case "SOCKS":
// return new Socks4Proxy(args[1],Integer.parseInt(args[2]));
default:
logger.warn("unsupport proxy type,ignored.");
return null;
}
}
public static String[] getHostAndPort(String proxy) {
String[] args = parseProxy(proxy);
if (args.length == 0) return null;
String[] ret = new String[2];
ret[0] = args[1];
ret[1] = args[2];
return ret;
}
}
| true |
6030aac55e2c3b10b16192e2dd726a7a15f03c21
|
Java
|
Shapherds/Collect_elements
|
/app/src/main/java/com/fall/crazyfall/web/WebCommunication.java
|
UTF-8
| 10,711 | 1.726563 | 2 |
[] |
no_license
|
package com.fall.crazyfall.web;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.toolbox.JsonObjectRequest;
import com.appsflyer.AFInAppEventType;
import com.appsflyer.AppsFlyerLib;
import com.appsflyer.attribution.AppsFlyerRequestListener;
import com.facebook.appevents.AppEventsConstants;
import com.facebook.appevents.AppEventsLogger;
import com.fall.crazyfall.MainActivity;
import com.fall.crazyfall.StaticData;
import org.json.JSONException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import androidx.annotation.NonNull;
import static com.facebook.FacebookSdk.getApplicationContext;
import static java.lang.Thread.sleep;
public class WebCommunication {
private String gitUrl = "";
private final Context context;
private final SharedPreferences myPreferences;
private final MainActivity activity;
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private String hash = "";
private boolean isNotStopCycle = true;
private final SharedPreferences.Editor myEditor;
private String deep;
private String geo;
public WebCommunication(Context context, SharedPreferences myPreferences, MainActivity activity, SharedPreferences.Editor myEditor, String deep) {
this.context = context;
this.myPreferences = myPreferences;
this.activity = activity;
this.myEditor = myEditor;
this.deep = deep;
}
public void regEvent() {
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(21);
Random random = new Random();
for (int i = 0; i < 21; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
hash = myPreferences.getString("Hash", sb.toString());
myEditor.putString("Hash" , hash);
String eventUrl = "http://sayyespro.com/event?app_id=" + context.getPackageName() + "&hash=" + hash + "&sender=android_request";
Log.e("deep", " json data " + eventUrl);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, eventUrl, null,
response -> {
try {
AppEventsLogger logger = AppEventsLogger.newLogger(context);
if (response.get("reg").toString().equals("1")) {
if (myPreferences.getBoolean("reg", true)) {
sendAppsflyeraddInfo();
Log.e("reg send", " sent eevent reg" + response.toString());
myEditor.putBoolean("reg", false);
myEditor.apply();
Bundle params = new Bundle();
params.putString(AppEventsConstants.EVENT_PARAM_CURRENCY, "USD");
params.putString(AppEventsConstants.EVENT_PARAM_CONTENT, "id : 1234");
logger.logEvent(AppEventsConstants.EVENT_NAME_INITIATED_CHECKOUT,
54.23,
params);
}
}
if (response.get("dep").toString().equals("1")) {
Log.e("Logs", "don`t show deep ");
if (myPreferences.getBoolean("dep", true)) {
sendAppsflyeraddPurs();
Log.e("Logs", " Deep event send");
myEditor.putBoolean("dep", false);
myEditor.apply();
Bundle params = new Bundle();
params.putString(AppEventsConstants.EVENT_PARAM_CURRENCY, "USD");
params.putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, "product");
params.putString(AppEventsConstants.EVENT_PARAM_CONTENT, "3456");
logger.logEvent(AppEventsConstants.EVENT_NAME_ADDED_PAYMENT_INFO,
54.23,
params);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> Log.e("error git ", error.toString()));
executor.execute(() -> {
while (isNotStopCycle) {
try {
//noinspection BusyWait
sleep(700);
Log.d(" Hash : ", "Hash is : " + hash);
MySinglton.getInstance(context).addToRequestQueue(jsonObjectRequest);
if (!myPreferences.getBoolean("reg", true) && !myPreferences.getBoolean("dep", true)) {
isNotStopCycle = false;
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
private void sendAppsflyeraddPurs() {
AppsFlyerLib.getInstance().setDebugLog(true);
Map<String,Object> buys = new HashMap<>();
AppsFlyerLib.getInstance().logEvent(getApplicationContext(), AFInAppEventType.PURCHASE, buys, new AppsFlyerRequestListener() {
@Override
public void onSuccess() {
Log.d("LOG_TAG", "PURCHASE Event sent successfully");
}
@Override
public void onError(int i, @NonNull String s) {
Log.d("LOG_TAG", "Event failed to be sent:\n" +
"Error code: " + i + "\n"
+ "Error description: " + s);
}
});
}
private void sendAppsflyeraddInfo() {
AppsFlyerLib.getInstance().setDebugLog(true);
Map<String,Object> addInfo = new HashMap<>();
AppsFlyerLib.getInstance().logEvent(getApplicationContext(), AFInAppEventType.ADD_PAYMENT_INFO, addInfo, new AppsFlyerRequestListener() {
@Override
public void onSuccess() {
Log.d("LOG_TAG", "ADD_PAYMENT_INFO Event sent successfully");
}
@Override
public void onError(int i, @NonNull String s) {
Log.d("LOG_TAG", "Event failed to be sent:\n" +
"Error code: " + i + "\n"
+ "Error description: " + s);
}
});
}
public void getGeo() {
if (myPreferences.getBoolean("Web", false)) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, StaticData.URL.getData(), null,
response -> {
try {
gitUrl = response.get("Links").toString();
Log.e("tag", "git urli " + gitUrl);
glueDeepLink(deep);
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> Log.e("error git ", error.toString()));
MySinglton.getInstance(context).addToRequestQueue(jsonObjectRequest);
} else {
JsonObjectRequest jsonObjectRequestLoc = new JsonObjectRequest
(Request.Method.GET, "http://www.geoplugin.net/json.gp?ip={$ip}", null,
response -> {
try {
geo = response.get("geoplugin_countryCode").toString();
startVebCommunication();
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> Log.e("error git ", error.toString()));
MySinglton.getInstance(context).addToRequestQueue(jsonObjectRequestLoc);
}
}
private void startVebCommunication() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, StaticData.URL.getData(), null,
response -> {
try {
if ((response.get("Active").toString().equals("true")
&& response.get("countries").toString().toUpperCase().contains(geo))
| (response.get("Active").toString().equals("true")
&& response.get("countries").toString().toUpperCase().equals("ALL"))) {
saveWebState();
gitUrl = response.get("Links").toString();
Log.e("tag", "git urli " + gitUrl);
glueDeepLink(deep);
}
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> Log.e("error git ", error.toString()));
MySinglton.getInstance(context).addToRequestQueue(jsonObjectRequest);
}
private void saveWebState() {
myEditor.putBoolean("Web", true);
myEditor.apply();
}
private void glueDeepLink(String deepLink) {
MainActivity.isGame = false;
deep = myPreferences.getString("Link", deepLink);
if (gitUrl.contains("?")) {
gitUrl += "&" + deepLink +"&hash=" + hash + "&app_id=" + context.getPackageName();
} else {
gitUrl += "?" + deepLink +"&hash=" + hash + "&app_id=" + context.getPackageName();
}
Intent intent = new Intent(context, Web.class);
intent.putExtra("Links", gitUrl);
myEditor.putString("Link", deep);
myEditor.apply();
context.startActivity(intent);
activity.finish();
}
}
| true |
2d50369b30f22983aa596179dc606572adb9e573
|
Java
|
maccornik/ComputerRemote
|
/src/pl/edu/uj/computerremote/BluetoothHidAppConfiguration.java
|
UTF-8
| 362 | 1.59375 | 2 |
[] |
no_license
|
package pl.edu.uj.computerremote;
import android.os.Parcel;
import android.os.Parcelable;
public class BluetoothHidAppConfiguration implements Parcelable {
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
}
}
| true |
c7a685a6caa31f15e3f11ea0819be9f79627dbf8
|
Java
|
tycrelic/classy
|
/src/classfile/constant/Numeric4Info.java
|
UTF-8
| 1,960 | 3.25 | 3 |
[] |
no_license
|
package classfile.constant;
import classfile.CpInfo;
/**
4.5.4 The CONSTANT_Integer_info and CONSTANT_Float_info Structures
The CONSTANT_Integer_info and CONSTANT_Float_info structures represent
4-byte numeric (int and float) constants:
CONSTANT_Integer_info {
u1 tag;
u4 bytes;
}
CONSTANT_Float_info {
u1 tag;
u4 bytes;
}
The items of these structures are as follows:
tag
The tag item of the CONSTANT_Integer_info structure has the
value CONSTANT_Integer (3).
The tag item of the CONSTANT_Float_info structure has the
value CONSTANT_Float (4).
*/
public class Numeric4Info extends CpInfo {
public Numeric4Info() {
}
/**
The bytes item of the CONSTANT_Integer_info structure
represents the value of the int constant. The bytes of the value
are stored in big-endian (high byte first) order.
The bytes item of the CONSTANT_Float_info structure
represents the value of the float constant in IEEE 754 floatingpoint
single format (§3.3.2)(§3.3.2). The bytes of the single
format representation are stored in big-endian (high byte first)
order.
The value represented by the CONSTANT_Float_info
structure is determined as follows. The bytes of the value are first
converted into an int constant bits. Then:
• If bits is 0x7f800000, the float value will be positive infinity.
• If bits is 0xff800000, the float value will be negative infinity.
• Ifbits is in the range 0x7f800001 through 0x7fffffff or in the
range 0xff800001 through 0xffffffff, the float value will
be NaN.
• In all other cases, let s, e, and m be three values that might be
computed from bits:
int s = ((bits >> 31) == 0) ? 1 : -1;
int e = ((bits >> 23) & 0xff);
int m = (e == 0) ?
(bits & 0x7fffff) << 1 :
(bits & 0x7fffff) | 0x800000;
Then the float value equals the result of the mathematical
expression s ⋅ m ⋅ 2^(e – 150).
*/
public int bytes;
}
| true |
0d57fce222fe0db7f1521cfa998162629edb5f68
|
Java
|
thePLoyBr/locadora-carros
|
/src/java/br/com/theploy/loccarros/bean/CarroBean.java
|
UTF-8
| 1,422 | 2.25 | 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 br.com.theploy.loccarros.bean;
import br.com.theploy.loccarros.DAO.CarroDAO;
import br.com.theploy.loccarros.entidade.Carro;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
/**
*
* @author felipe
*/
@ManagedBean(name="controllerCarro")
@SessionScoped
public class CarroBean implements Serializable{
private Carro carro = new Carro();
private CarroDAO carroDAO = new CarroDAO();
private List<Carro> carros = new ArrayList<>();
public void adicionar(){
carroDAO.salvar(carro);
carros = carroDAO.buscar();
carro = new Carro();
}
public void listar(){
carros = carroDAO.buscar();
}
public Carro getCarro() {
return carro;
}
public void setCarro(Carro carro) {
this.carro = carro;
}
public CarroDAO getCarroDAO() {
return carroDAO;
}
public void setCarroDAO(CarroDAO carroDAO) {
this.carroDAO = carroDAO;
}
public List<Carro> getCarros() {
return carros;
}
public void setCarros(List<Carro> carros) {
this.carros = carros;
}
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.