hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
455f59a80d5940945eb9c05314e32e0d07a255b1 | 7,254 | /**
* RenderEmailTemplateError.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.sforce.soap.partner;
public class RenderEmailTemplateError implements java.io.Serializable {
private java.lang.String fieldName;
private java.lang.String message;
private int offset;
private com.sforce.soap.partner.StatusCode statusCode;
public RenderEmailTemplateError() {
}
public RenderEmailTemplateError(
java.lang.String fieldName,
java.lang.String message,
int offset,
com.sforce.soap.partner.StatusCode statusCode) {
this.fieldName = fieldName;
this.message = message;
this.offset = offset;
this.statusCode = statusCode;
}
/**
* Gets the fieldName value for this RenderEmailTemplateError.
*
* @return fieldName
*/
public java.lang.String getFieldName() {
return fieldName;
}
/**
* Sets the fieldName value for this RenderEmailTemplateError.
*
* @param fieldName
*/
public void setFieldName(java.lang.String fieldName) {
this.fieldName = fieldName;
}
/**
* Gets the message value for this RenderEmailTemplateError.
*
* @return message
*/
public java.lang.String getMessage() {
return message;
}
/**
* Sets the message value for this RenderEmailTemplateError.
*
* @param message
*/
public void setMessage(java.lang.String message) {
this.message = message;
}
/**
* Gets the offset value for this RenderEmailTemplateError.
*
* @return offset
*/
public int getOffset() {
return offset;
}
/**
* Sets the offset value for this RenderEmailTemplateError.
*
* @param offset
*/
public void setOffset(int offset) {
this.offset = offset;
}
/**
* Gets the statusCode value for this RenderEmailTemplateError.
*
* @return statusCode
*/
public com.sforce.soap.partner.StatusCode getStatusCode() {
return statusCode;
}
/**
* Sets the statusCode value for this RenderEmailTemplateError.
*
* @param statusCode
*/
public void setStatusCode(com.sforce.soap.partner.StatusCode statusCode) {
this.statusCode = statusCode;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof RenderEmailTemplateError)) return false;
RenderEmailTemplateError other = (RenderEmailTemplateError) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.fieldName==null && other.getFieldName()==null) ||
(this.fieldName!=null &&
this.fieldName.equals(other.getFieldName()))) &&
((this.message==null && other.getMessage()==null) ||
(this.message!=null &&
this.message.equals(other.getMessage()))) &&
this.offset == other.getOffset() &&
((this.statusCode==null && other.getStatusCode()==null) ||
(this.statusCode!=null &&
this.statusCode.equals(other.getStatusCode())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getFieldName() != null) {
_hashCode += getFieldName().hashCode();
}
if (getMessage() != null) {
_hashCode += getMessage().hashCode();
}
_hashCode += getOffset();
if (getStatusCode() != null) {
_hashCode += getStatusCode().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(RenderEmailTemplateError.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "RenderEmailTemplateError"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("fieldName");
elemField.setXmlName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "fieldName"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("message");
elemField.setXmlName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "message"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("offset");
elemField.setXmlName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "offset"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("statusCode");
elemField.setXmlName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "statusCode"));
elemField.setXmlType(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "StatusCode"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| 32.383929 | 119 | 0.603253 |
292852394d2ff21b9965bb181c95003f129a4967 | 2,836 | package de.sdsd.projekt.parser.wrapper;
import java.util.Arrays;
import org.apache.jena.rdf.model.Resource;
import org.json.JSONObject;
/**
* Wrapper class for a GPS coordinate which references an entry of a Jena RDF
* model.
*
* @author <a href="mailto:andreas.schliebitz@hs-osnabrueck.de">Andreas
* Schliebitz</a>
*
*/
public class HelmCoordinate {
/** The longitude. */
private Double longitude;
/** The latitude. */
private Double latitude;
/** The reference. */
private Resource reference;
/** The label. */
private String label;
/**
* Instantiates a new helm coordinate.
*/
public HelmCoordinate() {
}
/**
* Instantiates a new helm coordinate.
*
* @param longitude the longitude
* @param latitude the latitude
* @param reference the reference
* @param label the label
*/
public HelmCoordinate(Double longitude, Double latitude, Resource reference, String label) {
this.longitude = longitude;
this.latitude = latitude;
this.reference = reference;
this.label = label;
}
/**
* Converts the GPS coordinates of this instance into valid Geo-JSON.
*
* @return Geo-JSON representation of the GPS coordinates.
*/
public JSONObject toGeoJson() {
JSONObject point = new JSONObject();
point.put("type", "Point");
point.put("coordinates", Arrays.asList(this.longitude, this.latitude));
JSONObject feature = new JSONObject();
feature.put("type", "Feature");
feature.put("properties", new JSONObject());
feature.put("geometry", point);
return feature;
}
/**
* Gets the longitude.
*
* @return the longitude
*/
public Double getLongitude() {
return longitude;
}
/**
* Sets the longitude.
*
* @param longitude the new longitude
*/
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
/**
* Gets the latitude.
*
* @return the latitude
*/
public Double getLatitude() {
return latitude;
}
/**
* Sets the latitude.
*
* @param latitude the new latitude
*/
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
/**
* Gets the reference.
*
* @return the reference
*/
public Resource getReference() {
return reference;
}
/**
* Sets the reference.
*
* @param reference the new reference
*/
public void setReference(Resource reference) {
this.reference = reference;
}
/**
* Gets the label.
*
* @return the label
*/
public String getLabel() {
return label;
}
/**
* Sets the label.
*
* @param label the new label
*/
public void setLabel(String label) {
this.label = label;
}
/**
* To string.
*
* @return the string
*/
@Override
public String toString() {
return "HelmCoordinate [longitude=" + longitude + ", latitude=" + latitude + ", reference=" + reference
+ ", label=" + label + "]";
}
} | 18.781457 | 105 | 0.656559 |
6c1558d5728505942192dfab2a30341700296730 | 1,950 | package it.unirc.PKG.webInterfaces;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
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 org.apache.commons.codec.binary.Hex;
import it.unirc.LiangScheme.CryptoCPABPRE;
/**
* Servlet implementation class PKG_GenerateSPKey
*/
@WebServlet("/PKG_GenerateSPKey")
public class PKG_GenerateSPKey extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public PKG_GenerateSPKey() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] attributes=request.getParameter("attributes").split(";");
//Perform check with Attribute Providers
String path=this.getServletContext().getRealPath("src/it/unirc/PKG/Keys/").replace("\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps", "");
FileReader f;
BufferedReader b;
f=new FileReader(path+"PK.txt");
b=new BufferedReader(f);
String pkS=b.readLine();
f=new FileReader(path+"MSK.txt");
b=new BufferedReader(f);
String mskS=b.readLine();
b.close();
try {
byte[]PK=Hex.decodeHex(pkS);
byte[]MSK=Hex.decodeHex(mskS);
String privateKey=String.valueOf(Hex.encodeHex(CryptoCPABPRE.KeyGen(attributes,PK,MSK)));
request.setAttribute("privateKey", privateKey);
request.getRequestDispatcher("PKG_Interfaces/PKG_SPInterface.jsp").forward(request, response);
}
catch(Exception e) {}
}
}
| 28.676471 | 162 | 0.712821 |
f33d94945da43665600cd17451694d40afa59d1c | 761 | package com.roway.service;
import com.roway.appconfig.ApplicationContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* ==================================================
*
* @author : luowei
* @fileName: IndexService
* @create 2019/10/17
* @since 1.0.0
* <description>:
* ==================================================
*/
@Component
public class IndexService {
@Autowired
private BeanService bean;
//// public void getBBBB() {
// ApplicationContextHolder.get().getBean("beanService");
// }
@Async
public void ssss () {
System.out.println("@PostConstruct");
}
} | 22.382353 | 62 | 0.641261 |
2e69f846e76f4f1d1860f68f03ad7a3393ce4bbf | 11,309 | package com.yc.overlaprecyclerview.morefragment;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.os.Handler;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.yc.overlaprecyclerview.R;
import com.yc.overlaprecyclerview.morefragment.constance.fragConst;
import com.yc.overlaprecyclerview.morefragment.custom.mainActivitySimpleOnGestureListener;
import com.yc.overlaprecyclerview.morefragment.customview.verticalViewPager;
import com.yc.overlaprecyclerview.morefragment.event.baseEvent;
import com.yc.overlaprecyclerview.morefragment.event.delThisFrag;
import com.yc.overlaprecyclerview.morefragment.event.deleteFragEvent;
import com.yc.overlaprecyclerview.morefragment.event.fragEvent;
import com.yc.overlaprecyclerview.morefragment.event.showDelImg;
import com.yc.overlaprecyclerview.morefragment.event.slideEvent;
import com.yc.overlaprecyclerview.morefragment.event.zoomEvent;
import com.yc.overlaprecyclerview.morefragment.fragment.fragAdapter;
import com.yc.overlaprecyclerview.morefragment.fragment.mainFrag;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import static android.widget.RelativeLayout.CENTER_IN_PARENT;
public class Main2Activity extends AppCompatActivity {
private verticalViewPager mViewPager;
private fragAdapter fragPagerAdapter;
private TextView pagebt;
private ImageView leftbt, rightbt, setbt, homebt, delfrag, addnewpage, returnmain;
private LinearLayout llayoutviewpage, pagebarlt, mainbarlt;
private DisplayMetrics dm2;
private GestureDetectorCompat mDetector;
private RelativeLayout mainrootrl;
private mainActivitySimpleOnGestureListener mainSimpleOnGestureListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
for (int i = 0; i < fragConst.init_page_count; i++) {
mainFrag tmp=new mainFrag();
fragConst.fraglist.add(tmp);
fragConst.fraghashcode.add(String.valueOf(tmp.hashCode()));
}
mViewPager = (verticalViewPager) findViewById(R.id.mainviewpage);
fragPagerAdapter = new fragAdapter(this, getSupportFragmentManager());
mViewPager.setAdapter(fragPagerAdapter);
mViewPager.setOffscreenPageLimit(1);
EventBus.getDefault().register(this);
mainSimpleOnGestureListener = new mainActivitySimpleOnGestureListener();
mDetector = new GestureDetectorCompat(this, mainSimpleOnGestureListener);
mainrootrl = (RelativeLayout) findViewById(R.id.mainrootrl);
viewInit();
}
private void viewInit() {
leftbt = (ImageView) findViewById(R.id.leftbt);
rightbt = (ImageView) findViewById(R.id.rightbt);
setbt = (ImageView) findViewById(R.id.setbt);
pagebt = (TextView) findViewById(R.id.pagebt);
homebt = (ImageView) findViewById(R.id.homebt);
delfrag = (ImageView) findViewById(R.id.delfrag);
addnewpage = (ImageView) findViewById(R.id.addnewpage);
returnmain = (ImageView) findViewById(R.id.returnmain);
leftbt.setOnClickListener((View v) -> {
bthander(v.getId());
});
rightbt.setOnClickListener((View v) -> {
bthander(v.getId());
});
setbt.setOnClickListener((View v) -> {
bthander(v.getId());
});
pagebt.setOnClickListener((View v) -> {
bthander(v.getId());
});
homebt.setOnClickListener((View v) -> {
bthander(v.getId());
});
addnewpage.setOnClickListener((View v) -> {
bthander(v.getId());
});
returnmain.setOnClickListener((View v) -> {
bthander(v.getId());
});
mainbarlt = (LinearLayout) findViewById(R.id.mainbarlt);
pagebarlt = (LinearLayout) findViewById(R.id.pagebarlt);
llayoutviewpage = (LinearLayout) findViewById(R.id.llayoutviewpage);
dm2 = getResources().getDisplayMetrics();
mainrootrl.setOnTouchListener((View v, MotionEvent event) -> {
mDetector.onTouchEvent(event);
return true;
});
pagebt.setText(fragConst.fraglist.size() + "");
}
private void bthander(int id) {
switch (id) {
case R.id.leftbt:
break;
case R.id.rightbt:
break;
case R.id.setbt:
break;
case R.id.pagebt:
zoomchange();
break;
case R.id.homebt:
// removePage(mViewPager.getCurrentItem());
break;
/**********************************************************/
case R.id.addnewpage:
addNewPage();
break;
case R.id.returnmain:
zoomchange();
break;
}
}
private void addNewPage() {
mainFrag tmp=new mainFrag();
fragConst.fraghashcode.add(String.valueOf( tmp.hashCode()));
fragConst.fraglist.add(mViewPager.getCurrentItem() + 1, tmp);
fragPagerAdapter.notifyDataSetChanged();
mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
Handler handler = new Handler();
handler.postDelayed(() -> {
if (dm2.widthPixels - mViewPager.getWidth() < 5) {
} else {
zoomchange();
}
}, 400);
}
private void removePage(int position) {
if (position >= 0 && position < fragConst.fraglist.size()) {
if (fragConst.fraglist.size() <= 1) {
return;
}
fragConst.fraglist.remove(position);
fragConst.fraghashcode.remove(position);
fragPagerAdapter.notifyDataSetChanged();
}
}
private boolean currentIsFull = true;//当前是不是全屏
private void zoomchange() {
int thewidth = mViewPager.getWidth();
if (dm2.widthPixels - mViewPager.getWidth() < 5) {
mViewPager.setPageMargin(fragConst.page_interval);
// Logger.v("缩小 " + thewidth);
llayoutviewpage.setGravity(CENTER_IN_PARENT);
//缩小
PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("scaleX", 1f, 0.8f);
PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("scaleY", 1f, 0.8f);
ObjectAnimator scale = ObjectAnimator.ofPropertyValuesHolder(mViewPager, pvhX, pvhY);
scale.setDuration(30);
scale.start();
RelativeLayout.LayoutParams Rlparam = new RelativeLayout.LayoutParams(dm2.widthPixels * 8 / 10, dm2.heightPixels * 8 / 10);
Rlparam.addRule(CENTER_IN_PARENT);
llayoutviewpage.setLayoutParams(Rlparam);
mainSimpleOnGestureListener.setViewPagePosition(mViewPager.getWidth(), mViewPager.getHeight());
pagebarlt.setVisibility(View.VISIBLE);
mainbarlt.setVisibility(View.INVISIBLE);
EventBus.getDefault().post(new zoomEvent(false));
} else {
// Logger.v("放大 " + thewidth + " ---- " + dm2.widthPixels);
mViewPager.setPageMargin(0);
//放大到原来样子
PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("scaleX", 0.8f, 1f);
PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("scaleY", 0.8f, 1f);
ObjectAnimator scale = ObjectAnimator.ofPropertyValuesHolder(mViewPager, pvhX, pvhY);
scale.setDuration(30);
scale.start();
currentIsFull = true;
RelativeLayout.LayoutParams Rlparam2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
Rlparam2.addRule(CENTER_IN_PARENT);
llayoutviewpage.setLayoutParams(Rlparam2);
pagebarlt.setVisibility(View.INVISIBLE);
mainbarlt.setVisibility(View.VISIBLE);
pagebt.setText(fragConst.fraglist.size() + "");
EventBus.getDefault().post(new zoomEvent(true));
}
}
@Subscribe
public void onEventMainThread(baseEvent event) {
if (event instanceof fragEvent) {
// Toast.makeText(this, " 收到 event 数据 " + ((fragEvent) event).getFragTag(), Toast.LENGTH_SHORT).show();
if (dm2.widthPixels - mViewPager.getWidth() < 5) {
} else {
zoomchange();
}
}
if (event instanceof slideEvent) {
// Toast.makeText(this, " 收到 event 数据 " + ((slideEvent) event).getType()+" "+((slideEvent) event).getDirection(), Toast.LENGTH_SHORT).show();
switch (((slideEvent) event).getType()) {
case MotionEvent.ACTION_MOVE:
switch (((slideEvent) event).getDirection()) {
case "left":
break;
case "right":
break;
}
break;
case MotionEvent.ACTION_DOWN:
switch (((slideEvent) event).getDirection()) {
case "left":
int cItem = mViewPager.getCurrentItem();
mViewPager.setCurrentItem(cItem > 0 ? cItem - 1 : cItem);
break;
case "right":
int rItem = mViewPager.getCurrentItem();
mViewPager.setCurrentItem(rItem < fragConst.fraglist.size() - 1 ? rItem + 1 : rItem);
break;
}
break;
}
}
if (event instanceof deleteFragEvent) {
int i = 0;
String Tag = ((deleteFragEvent) event).getFragTag();
for (mainFrag temp : fragConst.fraglist) {
if (temp.getFragTag().equals(Tag)) {
Handler dohandler = new Handler();
final int page = i;
dohandler.postDelayed(() -> {
// Logger.v("删除 page " + page);
removePage(page);
}, 80);
}
i++;
}
}
if (event instanceof showDelImg) {
if (((showDelImg) event).isShow()) {
delfrag.setVisibility(View.VISIBLE);
} else {
delfrag.setVisibility(View.INVISIBLE);
}
}
if (event instanceof delThisFrag) {
removePage(mViewPager.getCurrentItem());
}
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
fragConst.fraglist.clear();
fragConst.new_mainfrag_count = 0; //调用次数清0
}
}
| 36.717532 | 157 | 0.601114 |
95ef03846de7d5354cf6faa86dafd3bf02712318 | 287 | package basemod.patches.com.megacrit.cardcrawl.helpers.TopPanel;
import basemod.TopPanelGroup;
import basemod.TopPanelItem;
import java.util.ArrayList;
public class TopPanelHelper {
public static TopPanelGroup topPanelGroup = new TopPanelGroup(new ArrayList<TopPanelItem>());
}
| 22.076923 | 97 | 0.811847 |
14852aba30bebb3c9e4fb6d3395bdac1df1fa1c7 | 1,464 | package com.example.japanese;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class Home extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Button lessons = (Button) findViewById(R.id.lessons);
lessons.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("android.intent.action.LESSONS"));
}
});
Button quizzes = (Button) findViewById(R.id.quizzes);
quizzes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("android.intent.action.QUIZZES"));
}
});
Button dictionary = (Button) findViewById(R.id.dictionary);
dictionary.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("android.intent.action.DICTIONARY"));
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_home, menu);
return true;
}
}
| 25.684211 | 74 | 0.722678 |
d01b0175b015298cdcd240e8a323064156b6de53 | 798 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tutorial;
import com.opensymphony.xwork2.ActionSupport;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
/**
*
* @author Administrator
*/
public class Test_dispatch extends ActionSupport implements ServletRequestAware{
private HttpServletRequest request;
//Action1
public String act1(){
request.setAttribute("act", "I'm action 1");
return SUCCESS;
}
//Action2
public String act2(){
request.setAttribute("act", "I'm action 2");
return SUCCESS;
}
public void setServletRequest(HttpServletRequest arg0) {
this.request = arg0;
}
}
| 21.567568 | 80 | 0.674185 |
7a5cce15d6aec58349cff49c41b64edaa9b10108 | 1,223 | package co.com.lafemmeapp.core.domain.mappers;
import co.com.lafemmeapp.core.domain.entities.Customer;
import co.com.lafemmeapp.core.domain.entities.CustomerBuilder;
import co.com.lafemmeapp.dataprovider.network.entities.SessionResponse;
import io.reactivex.functions.Function;
/**
* Created by oscargallon on 4/18/17.
*/
public class SessionResponseCustomerMapper implements Function<SessionResponse, Customer> {
private final static SessionResponseCustomerMapper instace = new SessionResponseCustomerMapper();
private SessionResponseCustomerMapper() {
}
public static SessionResponseCustomerMapper getInstace() {
return instace;
}
@Override
public Customer apply(SessionResponse sessionResponse) throws Exception {
return new CustomerBuilder().setUuid(sessionResponse.getUuid())
.setAddress(sessionResponse.getAddress())
.setName(sessionResponse.getName())
.setPhoneNumber(sessionResponse.getPhoneNumber())
.setEmail(sessionResponse.getEmail())
.setLastName(sessionResponse.getLastName())
.setCity(sessionResponse.getCity())
.createCustomer();
}
}
| 31.358974 | 101 | 0.714636 |
273afff5fa9d53d293240b7550903740ae1ba75a | 2,646 | package com.smt.kata.code;
//JDK 11.x
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.boot.autoconfigure.info.ProjectInfoProperties.Build;
import com.siliconmtn.data.text.StringUtil;
/****************************************************************************
* <b>Title</b>: PhoneNumberCombos.java <b>Project</b>: SMT-Kata <b>Description:
* </b> Phone Number Combos Kata
*
* A phone number keypad has a series of characters that are associated with
* each number (except 1 and 0) as shown in this image
* https://i.insider.com/5aa8433b3be59f1f008b4651?width=1200
*
* In this kata, you will be provided a set of digits. You must create all of
* the possible permutations from each set of numbers provided
*
* Example 1 input "5" output: [ "j", "k","l" ]
*
* Example 2 input "23" output: [ "ad","ae","af","bd","be","bf","cd","ce","cf" ]
*
* Example 3 input "" output: [ ]
*
* <b>Copyright:</b> Copyright (c) 2021 <b>Company:</b> Silicon Mountain
* Technologies
*
* @author James Camire
* @version 3.0
* @since Sep 2, 2021
* @updates:
****************************************************************************/
public class PhoneNumberCombos {
/**
* Map with the digits to it's character options. Array location matches the
* digit value
*/
protected static final String[] DIGIT_MAP = new String[] { "0", "1", "abc",
"def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
public static List<String> nums;
/**
* Calculates all of the possible permutations for a phone number to letter
* mapping
*
* @param digits Digits to transcribe
* @return Collection of all of the permutations
*/
public List<String> calculate(String digits) {
if (StringUtil.isEmpty(digits))
return new ArrayList<>();
for (Character c : digits.toCharArray())
if (Character.isAlphabetic(0))
return new ArrayList<>();
nums = new ArrayList<>();
reccurse("", digits, 0);
// digits = digits.toLowerCase();
//
// List<List<Character>> lets = new ArrayList<>();
// for (int i = 0; i < digits.length(); i++) {
// List<Character> options = new ArrayList<>();
// for (Character c : DIGIT_MAP[digits.charAt(i) - 48].toCharArray()) {
// options.add(c);
// }
// lets.add(options);
// }
// nums.addAll(buid("", lets, nums, 0));
return nums;
}
public void reccurse(String word, String digits, int max) {
if (word.length() == max) {
}
char[] options = DIGIT_MAP[Integer.parseInt(digits.charAt(0) + "")]
.toCharArray();
System.out.println(Arrays.toString(options));
for (char c : options) {
word += c;
}
}
}
| 28.148936 | 80 | 0.614512 |
35e88ead5e243679ba3eba697a384af5a891a777 | 363 | package com.vaguehope.onosendai.provider.successwhale;
import java.io.IOException;
import org.apache.http.HttpResponse;
class InvalidRequestException extends SuccessWhaleException {
private static final long serialVersionUID = 8386398554192783582L;
public InvalidRequestException (final HttpResponse response) throws IOException {
super(response);
}
}
| 22.6875 | 82 | 0.826446 |
4ffd52ee1febaf658358224e30ee99a445a5ee8a | 653 | package opdwms.web.configs;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* @category Audit Logs
* @package Dev
* @since Nov 05, 2018
* @author Ignatius
* @version 1.0.0
*/
public interface SettingsServiceInterface {
/**
* Fetch a record information
*
* @param request
* @return Map<String, Object>
*/
public Map<String, Object> fetchRecord(HttpServletRequest request);
/**
* Update a record with new values
*
* @param request
* @return Map<String, Object>
*/
public Map<String, Object> editRecord(HttpServletRequest request);
}
| 21.064516 | 71 | 0.630934 |
788fef66ef9ecc106d65c8155333861ecb430751 | 7,848 | package com.bullhornsdk.data.model.entity.core.paybill;
import com.bullhornsdk.data.model.entity.core.type.CreateEntity;
import com.bullhornsdk.data.model.entity.core.type.DateLastModifiedEntity;
import com.bullhornsdk.data.model.entity.core.type.QueryEntity;
import com.bullhornsdk.data.model.entity.core.type.UpdateEntity;
import com.bullhornsdk.data.model.entity.embedded.Address;
import com.bullhornsdk.data.util.ReadOnly;
import com.fasterxml.jackson.annotation.*;
import org.joda.time.DateTime;
import javax.validation.constraints.Size;
import java.util.Date;
import java.util.Objects;
/**
* Created by fayranne.lipton 4/3/2020
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonRootName(value = "data")
@JsonPropertyOrder({ "id", "address",
"customDate1", "customDate2", "customDate3",
"customFloat1", "customFloat2", "customFloat3", "customInt1",
"customInt2", "customInt3", "customText1", "customText10",
"customText11", "customText12", "customText13", "customText14",
"customText15", "customText16", "customText17", "customText18",
"customText19", "customText2", "customText20", "customText3",
"customText4", "customText5", "customText6", "customText7",
"customText8", "customText9", "customTextBlock1", "customTextBlock2",
"customTextBlock3", "customTextBlock4", "customTextBlock5",
"dateAdded", "dateLastModified", "description", "effectiveDate",
"effectiveEndDate", "externalID", "isBillTo", "isFirst", "isSoldTo",
"isWorkSite", "status", "title" })
public class LocationVersion implements QueryEntity, UpdateEntity, CreateEntity, DateLastModifiedEntity {
private Integer id;
private Address address;
private DateTime dateAdded;
private DateTime dateLastModified;
@JsonIgnore
private String description;
private Date effectiveDate;
private Date effectiveEndDate;
@JsonIgnore
@Size(max = 100)
private String externalID;
private Boolean isBillTo;
private Boolean isFirst;
private Boolean isSoldTo;
private Boolean isWorkSite;
@JsonIgnore
@Size(max = 100)
private String status;
@JsonIgnore
@Size(max = 100)
private String title;
private Boolean isDeleted;
/**
* Returns the entity with the required fields for an insert set.
*/
public LocationVersion instantiateForInsert() {
LocationVersion entity = new LocationVersion();
entity.setIsDeleted(Boolean.FALSE);
return entity;
}
@Override
@JsonProperty("id")
public Integer getId() {
return id;
}
@ReadOnly
@Override
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
@JsonProperty("address")
public Address getAddress() {
return address;
}
@JsonProperty("address")
public void setAddress(Address address) {
this.address = address;
}
@JsonProperty("dateAdded")
public DateTime getDateAdded() {
return dateAdded;
}
@ReadOnly
@JsonProperty("dateAdded")
public void setDateAdded(DateTime dateAdded) {
this.dateAdded = dateAdded;
}
@JsonProperty("dateLastModified")
public DateTime getDateLastModified() {
return dateLastModified;
}
@ReadOnly
@JsonProperty("dateLastModified")
public void setDateLastModified(DateTime dateLastModified) {
this.dateLastModified = dateLastModified;
}
@JsonProperty("description")
public String getDescription() {
return description;
}
@JsonIgnore
public void setDescription(String description) {
this.description = description;
}
@JsonProperty("effectiveDate")
public Date getEffectiveDate() {
return effectiveDate;
}
@JsonProperty("effectiveDate")
public void setEffectiveDate(Date effectiveDate) {
this.effectiveDate = effectiveDate;
}
@JsonProperty("effectiveEndDate")
public Date getEffectiveEndDate() {
return effectiveEndDate;
}
@JsonProperty("effectiveEndDate")
public void setEffectiveEndDate(Date effectiveEndDate) {
this.effectiveEndDate = effectiveEndDate;
}
@JsonProperty("externalID")
public String getExternalID() {
return externalID;
}
@JsonIgnore
public void setExternalID(String externalID) {
this.externalID = externalID;
}
@JsonProperty("isBillTo")
public Boolean getIsBillTo() {
return isBillTo;
}
@JsonProperty("isBillTo")
public void setIsBillTo(Boolean billTo) {
isBillTo = billTo;
}
@JsonProperty("isFirst")
public Boolean setIsFirst() {
return isFirst;
}
@JsonProperty("isFirst")
public void getIsFirst(Boolean first) {
isFirst = first;
}
@JsonProperty("isSoldTo")
public Boolean getIsSoldTo() {
return isSoldTo;
}
@JsonProperty("isSoldTo")
public void setIsSoldTo(Boolean soldTo) {
isSoldTo = soldTo;
}
@JsonProperty("isWorkSite")
public Boolean getIsWorkSite() {
return isWorkSite;
}
@JsonProperty("isWorkSite")
public void setIsWorkSite(Boolean workSite) {
isWorkSite = workSite;
}
@JsonProperty("status")
public String getStatus() {
return status;
}
@JsonIgnore
public void setStatus(String status) {
this.status = status;
}
@JsonProperty("title")
public String getTitle() {
return title;
}
@JsonIgnore
public void setTitle(String title) {
this.title = title;
}
@JsonProperty("isDeleted")
public Boolean getIsDeleted() {
return isDeleted;
}
@JsonProperty("isDeleted")
public void setIsDeleted(Boolean isDeleted) {
this.isDeleted = isDeleted;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LocationVersion that = (LocationVersion) o;
return isBillTo == that.isBillTo &&
isFirst == that.isFirst &&
isSoldTo == that.isSoldTo &&
isWorkSite == that.isWorkSite &&
Objects.equals(id, that.id) &&
Objects.equals(address, that.address) &&
Objects.equals(dateAdded, that.dateAdded) &&
Objects.equals(dateLastModified, that.dateLastModified) &&
Objects.equals(description, that.description) &&
Objects.equals(effectiveDate, that.effectiveDate) &&
Objects.equals(effectiveEndDate, that.effectiveEndDate) &&
Objects.equals(externalID, that.externalID) &&
Objects.equals(status, that.status) &&
Objects.equals(title, that.title) &&
Objects.equals(isDeleted, that.isDeleted);
}
@Override
public int hashCode() {
return Objects.hash(id, address, dateAdded, dateLastModified, description, effectiveDate, effectiveEndDate, externalID, isBillTo, isFirst, isSoldTo, isWorkSite, status, title, isDeleted);
}
@Override
public String toString() {
return "LocationVersion{" +
"id=" + id +
", address=" + address +
", dateAdded=" + dateAdded +
", dateLastModified=" + dateLastModified +
", description='" + description + '\'' +
", effectiveDate=" + effectiveDate +
", effectiveEndDate=" + effectiveEndDate +
", externalID='" + externalID + '\'' +
", isBillTo=" + isBillTo +
", isFirst=" + isFirst +
", isSoldTo=" + isSoldTo +
", isWorkSite=" + isWorkSite +
", status='" + status + '\'' +
", title='" + title + '\'' +
", isDeleted=" + isDeleted +
'}';
}
}
| 27.536842 | 195 | 0.639399 |
388981e6c6a02c17dfd68954bd343de913e59a7e | 3,798 | /*
* Copyright 2015-2017 Nokia Solutions and Networks
* Licensed under the Apache License, Version 2.0,
* see license.txt file for details.
*/
package org.robotframework.ide.eclipse.main.plugin.navigator.handlers;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.ui.IDecoratorManager;
import org.eclipse.ui.PlatformUI;
import org.rf.ide.core.project.RobotProjectConfig;
import org.robotframework.ide.eclipse.main.plugin.RedPlugin;
import org.robotframework.ide.eclipse.main.plugin.model.RobotProject;
import org.robotframework.ide.eclipse.main.plugin.navigator.RobotValidationExcludedDecorator;
import org.robotframework.ide.eclipse.main.plugin.project.RedEclipseProjectConfigReader;
import org.robotframework.ide.eclipse.main.plugin.project.RedEclipseProjectConfigWriter;
import org.robotframework.ide.eclipse.main.plugin.project.RedProjectConfigEventData;
import org.robotframework.ide.eclipse.main.plugin.project.RobotProjectConfigEvents;
import org.robotframework.red.swt.SwtThread;
/**
* @author Michal Anglart
*/
abstract class ChangeExclusionHandler {
protected void changeExclusion(final IEventBroker eventBroker, final List<IResource> selectedResources) {
final Map<RobotProject, List<IPath>> pathsGroupedByProject = groupByProject(selectedResources);
pathsGroupedByProject.forEach((robotProject, paths) -> {
changeExclusion(robotProject, paths);
fireEvents(eventBroker, robotProject.getProject(), paths);
});
SwtThread.asyncExec(() -> {
final IDecoratorManager manager = PlatformUI.getWorkbench().getDecoratorManager();
manager.update(RobotValidationExcludedDecorator.ID);
});
}
private Map<RobotProject, List<IPath>> groupByProject(final List<IResource> selectedResources) {
final Function<IResource, RobotProject> projectClassifier = resource -> RedPlugin.getModelManager()
.createProject(resource.getProject());
return selectedResources.stream().collect(Collectors.groupingBy(projectClassifier,
Collectors.mapping(IResource::getProjectRelativePath, Collectors.toList())));
}
private void changeExclusion(final RobotProject robotProject, final Collection<IPath> toChange) {
RobotProjectConfig config = robotProject.getOpenedProjectConfig();
final boolean inEditor = config != null;
if (config == null) {
config = new RedEclipseProjectConfigReader().readConfiguration(robotProject);
}
for (final IPath pathToChange : toChange) {
changeExclusion(config, pathToChange);
}
if (!inEditor) {
new RedEclipseProjectConfigWriter().writeConfiguration(config, robotProject);
}
try {
robotProject.getProject().refreshLocal(IResource.DEPTH_INFINITE, null);
} catch (final CoreException e) {
// nothing to do
}
}
private void fireEvents(final IEventBroker eventBroker, final IProject project, final Collection<IPath> toChange) {
final RedProjectConfigEventData<Collection<IPath>> eventData = new RedProjectConfigEventData<>(
project.getFile(RobotProjectConfig.FILENAME), toChange);
eventBroker.send(RobotProjectConfigEvents.ROBOT_CONFIG_VALIDATION_EXCLUSIONS_STRUCTURE_CHANGED, eventData);
}
protected abstract void changeExclusion(RobotProjectConfig config, IPath pathToChange);
}
| 44.162791 | 119 | 0.748552 |
43da81c0102b0302ad10ea2ba8276c1a93b79c44 | 509 | package com.lesson5;
import java.util.Set;
import java.util.TreeSet;
public class SetEx3 {
public static void main(String[] args) {
Set<String> set = new TreeSet<>();
set.add("Bars");
set.add("Murz");
set.add("Ara");
System.out.println(set);
set.add("Aara");
set.add("Mu");
System.out.println(set);
System.out.println(((TreeSet<String>) set).headSet("Mu"));
System.out.println(((TreeSet<String>) set).first());
}
}
| 21.208333 | 66 | 0.563851 |
905b2b8fe3cc8270cc932649ebc3bbc21d28fac4 | 1,027 | package io.rxmicro.examples.validation.server.nested.model.model;
import io.rxmicro.examples.validation.server.nested.model.model.nested.$$NestedModelFromJsonConverter;
import io.rxmicro.exchange.json.detail.ModelFromJsonConverter;
import java.util.Map;
/**
* Generated by {@code RxMicro Annotation Processor}
*/
public final class $$ArrayRequestModelFromJsonConverter extends ModelFromJsonConverter<ArrayRequest> {
private final $$NestedModelFromJsonConverter nestedModelFromJsonConverter =
new $$NestedModelFromJsonConverter();
@Override
public ArrayRequest fromJsonObject(final Map<String, Object> params) {
final ArrayRequest model = new ArrayRequest();
readParamsToModel(params, model);
return model;
}
public void readParamsToModel(final Map<String, Object> params,
final ArrayRequest model) {
model.nestedList = convertToListIfNotNull(nestedModelFromJsonConverter, params.get("nestedList"), "nestedList");
}
}
| 36.678571 | 120 | 0.739046 |
4bd348bb557e52719dd76fbf9955c95db4e2b6bd | 1,202 | package com.handsomezhou.xdesktophelper.broadcastreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.handsomezhou.xdesktophelper.helper.AppInfoHelper;
public class AppChangedReceiver extends BroadcastReceiver {
private static final String TAG = "AppChangedReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG,"AppChangedReceiver :"+intent.getAction());
/**
* update app :ACTION_PACKAGE_REMOVED->ACTION_PACKAGE_ADDED
*/
if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED) || intent.getAction().equals(Intent.ACTION_PACKAGE_CHANGED) || intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED) || intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)) {
String schemeSpecificPart = null;
if(null!=intent.getData()) {
schemeSpecificPart=intent.getData().getSchemeSpecificPart();
}
Log.i(TAG, "action["+intent.getAction()+"]["+schemeSpecificPart+"]");
AppInfoHelper.getInstance().setAppInfoChanged(true);
}
}
}
| 34.342857 | 250 | 0.703827 |
4af532796034c9f58ad56754b4c72fa144120901 | 1,517 | package dev;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.action.admin.cluster.state.ClusterStateRequestBuilder;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
public class ElasticSearchServer {
public static void main(String[] args) throws InterruptedException {
Node server = NodeBuilder.nodeBuilder().loadConfigSettings(false).clusterName("test.cluster").local(true).settings(
ImmutableSettings.settingsBuilder()
.put("network.host", "127.0.0.1")
.put("index.store.type", "memory")
.put("gateway.type", "none")
.put("index.number_of_shards", 1)
.put("index.number_of_replicas", 1).build()
).node().start();
Node node = NodeBuilder.nodeBuilder().client(true).loadConfigSettings(false).clusterName("test.cluster").local(true).settings(
ImmutableSettings.settingsBuilder()
.put("network.host", "127.0.0.1")
.put("index.store.type", "memory")
.put("gateway.type", "none")
.put("index.number_of_shards", 1)
.put("index.number_of_replicas", 1).build()
).node().start();
Client client = node.client();
ClusterStateRequestBuilder request = client.admin().cluster().prepareState();
ClusterStateResponse response = request.execute().actionGet();
System.out.println(response.getClusterName());
server.stop();
node.stop();
}
}
| 37 | 131 | 0.723797 |
0ba7d866fedbecdf79d670d8a137ab52f53499a6 | 3,623 | package com.coccoc;
import java.io.*;
import java.lang.reflect.Field;
public class Unsafe {
public static final sun.misc.Unsafe UNSAFE;
static {
sun.misc.Unsafe unsafe = null;
try {
Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (sun.misc.Unsafe) field.get(null);
} catch (Exception e) {
e.printStackTrace();
}
UNSAFE = unsafe;
}
private static final int BUFFER_SIZE = 1024 * 1024 * 16;
private static final String CHARSET = "iso-8859-1";
public static void saveUnsafeMemory(OutputStream os, long memory, long size) throws IOException {
for (long i = memory; i < memory + size; i++) {
os.write(UNSAFE.getByte(i));
}
}
public static long readToUnsafeMemory(File file) throws IOException {
long len = file.length();
long memory = UNSAFE.allocateMemory(len);
try (BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE)) {
for (long i = 0; i < len; i++) {
UNSAFE.putByte(memory + i, (byte) fis.read());
}
}
return memory;
}
public static float getFloat(byte[] buffer, int offset) {
return UNSAFE.getFloat(buffer, (long) (sun.misc.Unsafe.ARRAY_BYTE_BASE_OFFSET + offset));
}
public static double getDouble(byte[] buffer, int offset) {
return UNSAFE.getDouble(buffer, (long) (sun.misc.Unsafe.ARRAY_BYTE_BASE_OFFSET + offset));
}
public static long getLong(byte[] buffer, int offset) {
return UNSAFE.getLong(buffer, (long) (sun.misc.Unsafe.ARRAY_BYTE_BASE_OFFSET + offset));
}
public static int getInt(byte[] buffer, int offset) {
return UNSAFE.getInt(buffer, (long) (sun.misc.Unsafe.ARRAY_BYTE_BASE_OFFSET + offset));
}
public static short getShort(byte[] buffer, int offset) {
return UNSAFE.getShort(buffer, (long) (sun.misc.Unsafe.ARRAY_BYTE_BASE_OFFSET + offset));
}
public static byte getByte(byte[] buffer, int offset) {
return UNSAFE.getByte(buffer, (long) (sun.misc.Unsafe.ARRAY_BYTE_BASE_OFFSET + offset));
}
public static void writeString(String str, OutputStream os, long unsafeBuffer)
throws IOException {
byte[] bytes = str.getBytes(CHARSET);
writeInt(bytes.length, os, unsafeBuffer);
os.write(bytes);
}
public static void writeInt(int value, OutputStream os, long unsafeBuffer) throws IOException {
Unsafe.UNSAFE.putInt(unsafeBuffer, value);
Unsafe.saveUnsafeMemory(os, unsafeBuffer, 4);
}
public static String readString(InputStream is) throws IOException {
int length = readInt(is);
byte[] bytes = new byte[length];
is.read(bytes);
return new String(bytes, CHARSET);
}
public static int readInt(InputStream is) throws IOException {
byte[] bytes = new byte[4];
is.read(bytes);
return Unsafe.getInt(bytes, 0);
}
public static void copy(byte[] values, int length, long pointer) {
UNSAFE.copyMemory(values, sun.misc.Unsafe.ARRAY_BYTE_BASE_OFFSET, null, pointer, length);
}
public static void copy(byte[] values, int off, int length, long pointer) {
UNSAFE.copyMemory(values, sun.misc.Unsafe.ARRAY_BYTE_BASE_OFFSET + off, null, pointer, length);
}
public static void copy(short[] values, int length, long pointer) {
UNSAFE.copyMemory(values, sun.misc.Unsafe.ARRAY_SHORT_BASE_OFFSET, null, pointer, length * Short.BYTES);
}
public static void copy(int[] values, int length, long pointer) {
UNSAFE.copyMemory(values, sun.misc.Unsafe.ARRAY_INT_BASE_OFFSET, null, pointer, length * Integer.BYTES);
}
public static void copy(long[] values, int length, long pointer) {
UNSAFE.copyMemory(values, sun.misc.Unsafe.ARRAY_LONG_BASE_OFFSET, null, pointer, length * Long.BYTES);
}
}
| 32.936364 | 106 | 0.725918 |
3d09784f9e5b18356e9fa0aa0f78890720c9f0af | 5,903 | package org.dave.bats.util.serialization;
import io.netty.buffer.ByteBuf;
import net.minecraft.nbt.NBTTagCompound;
import org.dave.bats.util.Logz;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.*;
import java.util.function.Predicate;
public class FieldUtils {
private static Map<Class, List<Field>> lookupCache = new HashMap<>();
private static Map<Class, List<NBTFieldSerializationData>> classNbtCache = new HashMap<>();
private static Map<Class, List<ByteBufFieldSerializationData>> classByteBufCache = new HashMap<>();
public static List<Field> getAllDeclaredFields(Class clz) {
if(!lookupCache.containsKey(clz)) {
List<Field> fields = FieldUtils.getAllDeclaredFields(new ArrayList<>(), clz);
fields.sort(Comparator.comparing(o -> o.getClass().getName()));
lookupCache.put(clz, fields);
}
return lookupCache.get(clz);
}
private static List<Field> getAllDeclaredFields(List<Field> fields, Class<?> type) {
fields.addAll(Arrays.asList(type.getDeclaredFields()));
if (type.getSuperclass() != null) {
getAllDeclaredFields(fields, type.getSuperclass());
}
return fields;
}
public static List<NBTFieldSerializationData> initSerializableStoreFields(Class clz) {
if(classNbtCache.containsKey(clz)) {
return classNbtCache.get(clz);
}
List<NBTFieldSerializationData> actionList = new ArrayList<>();
for(Field field : FieldUtils.getAllDeclaredFields(clz)) {
Annotation annotation = field.getDeclaredAnnotation(Store.class);
if(annotation != null && annotation instanceof Store) {
if(!FieldHandlers.hasNBTHandler(field.getType())) {
Logz.warn("No NBT serialization methods for field='%s' (type='%s') in class='%s' exists.", field.getName(), field.getType().getSimpleName(), clz.getSimpleName());
continue;
}
Store storeAnnotation = (Store)annotation;
String key = storeAnnotation.key();
if(key.equals("")) {
key = field.getName();
}
actionList.add(new NBTFieldSerializationData(field, key, storeAnnotation.storeWithItem(), storeAnnotation.sendInUpdatePackage()));
field.setAccessible(true);
}
}
classNbtCache.put(clz, actionList);
return actionList;
}
public static List<ByteBufFieldSerializationData> initSerializableSyncFields(Class clz) {
if(classByteBufCache.containsKey(clz)) {
return classByteBufCache.get(clz);
}
List<ByteBufFieldSerializationData> actionList = new ArrayList<>();
for(Field field : FieldUtils.getAllDeclaredFields(clz)) {
Annotation annotation = field.getDeclaredAnnotation(Sync.class);
if(annotation != null && annotation instanceof Sync) {
if(!FieldHandlers.hasIOHandler(field.getType())) {
Logz.warn("No ByteBuf serialization methods for field='%s' (type='%s') in class='%s' exists.", field.getName(), field.getType().getSimpleName(), clz.getSimpleName());
continue;
}
Sync syncAnnotation = (Sync)annotation;
actionList.add(new ByteBufFieldSerializationData(field));
field.setAccessible(true);
}
}
classByteBufCache.put(clz, actionList);
return actionList;
}
public static NBTTagCompound writeFieldsToNBT(List<NBTFieldSerializationData> NBTActions, Object source, NBTTagCompound targetCompound, Predicate<NBTFieldSerializationData> test) {
for(NBTFieldSerializationData data : NBTActions) {
if(!test.test(data)) {
continue;
}
try {
Object value = data.field.get(source);
data.writer.write(data.key, value, targetCompound);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return targetCompound;
}
public static void readFieldsFromNBT(List<NBTFieldSerializationData> NBTActions, Object target, NBTTagCompound sourceCompound, Predicate<NBTFieldSerializationData> test) {
for(NBTFieldSerializationData data : NBTActions) {
if(!test.test(data)) {
continue;
}
try {
Object value = data.reader.read(data.key, sourceCompound);
data.field.set(target, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
public static void writeFieldsToByteBuf(List<ByteBufFieldSerializationData> ioActions, Object source, ByteBuf targetBuffer, Predicate<ByteBufFieldSerializationData> test) {
for(ByteBufFieldSerializationData data : ioActions) {
if(!test.test(data)) {
continue;
}
try {
Object value = data.field.get(source);
data.writer.write(value, targetBuffer);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
public static void readFieldsFromByteBuf(List<ByteBufFieldSerializationData> ioActions, Object target, ByteBuf sourceBuffer, Predicate<ByteBufFieldSerializationData> test) {
for(ByteBufFieldSerializationData data : ioActions) {
if(!test.test(data)) {
continue;
}
try {
Object value = data.reader.read(sourceBuffer);
data.field.set(target, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
| 38.581699 | 186 | 0.612909 |
2af645c4da7f9533cf66a00c7addfbf7277baf0a | 3,336 | /**
Copyright 2012 Jive Software
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.jivesoftware.rest.quotes.dao.impl;
import com.jivesoftware.rest.quotes.dao.LineDAO;
import com.jivesoftware.rest.quotes.model.Line;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>Quote line DAO implementation for quotes system.</p>
*/
public class LineDAOImpl implements LineDAO {
@Override
public synchronized void delete(Line line) throws IllegalArgumentException {
Line previous = lines.get(line.getID());
if (previous == null) {
throw new IllegalArgumentException("Missing line " + line.getID());
}
lines.remove(line.getID());
}
@Override
public List<Line> find(long quoteID) {
List<Line> results = new ArrayList<Line>();
for (Line line : lines.values()) {
if (quoteID == line.getQuoteID()) {
results.add(line);
}
}
sort(results);
return results;
}
@Override
public synchronized Line get(long lineID) {
return lines.get(lineID);
}
public void init() {
reset();
}
@Override
public synchronized void insert(Line line) throws IllegalArgumentException {
long highest = highest();
line.setID(highest + 1);
lines.put(line.getID(), line);
}
@Override
public synchronized void reset() {
lines.clear();
// TODO - reset() populate initial data
}
@Override
public synchronized void update(Line line) throws IllegalArgumentException {
Line previous = lines.get(line.getID());
if (previous == null) {
throw new IllegalArgumentException("Missing line " + line.getID());
}
lines.put(line.getID(), line);
}
private long highest() {
long highest = 0L;
for (Long key : lines.keySet()) {
long value = key.longValue();
if (value > highest) {
highest = value;
}
}
return highest;
}
private void sort(List<Line> lines) {
Comparator<Line> comparator = new LineComparator();
Collections.sort(lines, comparator);
}
private Map<Long,Line> lines = new HashMap<Long,Line>();
public static class LineComparator implements Comparator<Line> {
@Override
public int compare(Line line1, Line line2) {
if (line1.getLineNumber() < line2.getLineNumber()) {
return -1;
}
else if (line1.getLineNumber() > line2.getLineNumber()) {
return 1;
}
else {
return 0;
}
}
}
}
| 28.033613 | 80 | 0.611511 |
98109e8d8d106bb0d836e9ca6a78a21daf3a16e7 | 5,022 | package com.penglecode.xmodule.ordercenter.model;
import com.penglecode.xmodule.common.codegen.Id;
import com.penglecode.xmodule.common.codegen.Model;
import com.penglecode.xmodule.common.support.BaseModel;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 订单表
*
* @author Mybatis-Generator
* @date 2020年08月04日 下午 20:29:02
*/
@Model(name="订单", alias="Order")
public class Order implements BaseModel<Order> {
private static final long serialVersionUID = 1L;
/** 订单ID */
@Id
private Long orderId;
/** 订单总价 */
private Double totalAmount;
/** 运费 */
private Double freightAmount;
/** 下单时间 */
private String orderTime;
/** 客户ID */
private Long customerId;
/** 支付方式:0-在线支付,1-货到付款 */
private Integer paymentType;
/** 订单状态:0-待付款,1-待发货,2-待收货 */
private Integer status;
/** 订单备注 */
private String remark;
//以下属于辅助字段
private Double minTotalAmount;
private Double maxTotalAmount;
private String minOrderTime;
private String maxOrderTime;
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public Double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(Double totalAmount) {
this.totalAmount = totalAmount;
}
public Double getFreightAmount() {
return freightAmount;
}
public void setFreightAmount(Double freightAmount) {
this.freightAmount = freightAmount;
}
public String getOrderTime() {
return orderTime;
}
public void setOrderTime(String orderTime) {
this.orderTime = orderTime;
}
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
public Integer getPaymentType() {
return paymentType;
}
public void setPaymentType(Integer paymentType) {
this.paymentType = paymentType;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Double getMinTotalAmount() {
return minTotalAmount;
}
public void setMinTotalAmount(Double minTotalAmount) {
this.minTotalAmount = minTotalAmount;
}
public Double getMaxTotalAmount() {
return maxTotalAmount;
}
public void setMaxTotalAmount(Double maxTotalAmount) {
this.maxTotalAmount = maxTotalAmount;
}
public String getMinOrderTime() {
return minOrderTime;
}
public void setMinOrderTime(String minOrderTime) {
this.minOrderTime = minOrderTime;
}
public String getMaxOrderTime() {
return maxOrderTime;
}
public void setMaxOrderTime(String maxOrderTime) {
this.maxOrderTime = maxOrderTime;
}
public MapBuilder mapBuilder() {
return new MapBuilder();
}
/**
* Auto generated by Mybatis Generator
*/
public class MapBuilder {
private final Map<String, Object> modelProperties = new LinkedHashMap<String,Object>();
MapBuilder() {
super();
}
public MapBuilder withOrderId(Long ... orderId) {
modelProperties.put("orderId", BaseModel.first(orderId, getOrderId()));
return this;
}
public MapBuilder withTotalAmount(Double ... totalAmount) {
modelProperties.put("totalAmount", BaseModel.first(totalAmount, getTotalAmount()));
return this;
}
public MapBuilder withFreightAmount(Double ... freightAmount) {
modelProperties.put("freightAmount", BaseModel.first(freightAmount, getFreightAmount()));
return this;
}
public MapBuilder withOrderTime(String ... orderTime) {
modelProperties.put("orderTime", BaseModel.first(orderTime, getOrderTime()));
return this;
}
public MapBuilder withCustomerId(Long ... customerId) {
modelProperties.put("customerId", BaseModel.first(customerId, getCustomerId()));
return this;
}
public MapBuilder withPaymentType(Integer ... paymentType) {
modelProperties.put("paymentType", BaseModel.first(paymentType, getPaymentType()));
return this;
}
public MapBuilder withStatus(Integer ... status) {
modelProperties.put("status", BaseModel.first(status, getStatus()));
return this;
}
public MapBuilder withRemark(String ... remark) {
modelProperties.put("remark", BaseModel.first(remark, getRemark()));
return this;
}
public Map<String, Object> build() {
return modelProperties;
}
}
} | 23.914286 | 101 | 0.626045 |
81c954a5cc66439eaac6520f07b339a164bfbb28 | 2,303 | package org.hisp.dhis.coldchain.model.action;
import org.hisp.dhis.coldchain.model.ModelType;
import org.hisp.dhis.coldchain.model.ModelTypeService;
import org.hisp.dhis.common.DeleteNotAllowedException;
import org.hisp.dhis.i18n.I18n;
import com.opensymphony.xwork2.Action;
public class RemoveModelTypeAction
implements Action
{
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
private ModelTypeService modelTypeService;
public void setModelTypeService( ModelTypeService modelTypeService )
{
this.modelTypeService = modelTypeService;
}
// -------------------------------------------------------------------------
// Input/Output
// -------------------------------------------------------------------------
private int id;
public void setId( int id )
{
this.id = id;
}
private I18n i18n;
public void setI18n( I18n i18n )
{
this.i18n = i18n;
}
// -------------------------------------------------------------------------
// Output
// -------------------------------------------------------------------------
private String message;
public String getMessage()
{
return message;
}
// -------------------------------------------------------------------------
// Action implementation
// -------------------------------------------------------------------------
public String execute() throws Exception
{
try
{
ModelType modelType = modelTypeService.getModelType( id );
if( modelType != null)
{
modelType.getModelTypeAttributes().clear();
}
modelTypeService.deleteModelType( modelType );
}
catch ( DeleteNotAllowedException ex )
{
if ( ex.getErrorCode().equals( DeleteNotAllowedException.ERROR_ASSOCIATED_BY_OTHER_OBJECTS ) )
{
message = i18n.getString( "object_not_deleted_associated_by_objects" ) + " " + ex.getMessage();
return ERROR;
}
}
return SUCCESS;
}
}
| 27.094118 | 111 | 0.432045 |
88090c95bbd08b53d8c835c3b9733166bbb630cc | 11,502 | package org.openprovenance.prov.xml;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.openprovenance.prov.xml.builder.Equals;
import org.openprovenance.prov.xml.builder.HashCode;
import org.openprovenance.prov.xml.builder.ToString;
import org.openprovenance.prov.xml.builder.JAXBEqualsBuilder;
import org.openprovenance.prov.xml.builder.JAXBHashCodeBuilder;
import org.openprovenance.prov.xml.builder.JAXBToStringBuilder;
import org.openprovenance.prov.model.Attribute;
/**
* <p>Java class for Activity complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Activity">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="startTime" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* <element name="endTime" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* <element ref="{http://www.w3.org/ns/prov#}label" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{http://www.w3.org/ns/prov#}location" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{http://www.w3.org/ns/prov#}type" maxOccurs="unbounded" minOccurs="0"/>
* <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute ref="{http://www.w3.org/ns/prov#}id"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Activity", propOrder = {
"startTime",
"endTime",
"label",
//"location",
//"type",
//"any"
"all"
})
public class Activity implements Equals, HashCode, ToString, org.openprovenance.prov.model.Activity, HasAllAttributes
{
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar startTime;
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar endTime;
@XmlElement(type = org.openprovenance.prov.xml.InternationalizedString.class)
protected List<org.openprovenance.prov.model.LangString> label;
transient protected List<org.openprovenance.prov.model.Location> location;
transient protected List<org.openprovenance.prov.model.Type> type;
transient protected List<org.openprovenance.prov.model.Other> others;
@XmlAnyElement
protected List<Attribute> all;
@XmlAttribute(name = "id", namespace = "http://www.w3.org/ns/prov#")
@javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter(QualifiedNameAdapter.class)
protected org.openprovenance.prov.model.QualifiedName id;
/**
* Gets the value of the startTime property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getStartTime() {
return startTime;
}
/**
* Sets the value of the startTime property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setStartTime(XMLGregorianCalendar value) {
this.startTime = value;
}
/**
* Gets the value of the endTime property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getEndTime() {
return endTime;
}
/**
* Sets the value of the endTime property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setEndTime(XMLGregorianCalendar value) {
this.endTime = value;
}
/**
* Gets the value of the label property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the label property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLabel().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link org.openprovenance.prov.xml.InternationalizedString }
*
*
*/
public List<org.openprovenance.prov.model.LangString> getLabel() {
if (label == null) {
label = new ArrayList<org.openprovenance.prov.model.LangString>();
}
return this.label;
}
/**
* Gets the value of the location property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the location property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLocation().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link org.openprovenance.prov.xml.Location }
*
*
*/
public List<org.openprovenance.prov.model.Location> getLocation() {
if (location == null) {
location=AttributeList.populateKnownAttributes(this, all, org.openprovenance.prov.model.Location.class);
}
return this.location;
}
/**
* Gets the value of the type property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the type property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getType().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link org.openprovenance.prov.xml.Type }
*
*
*/
public List<org.openprovenance.prov.model.Type> getType() {
if (type == null) {
type=AttributeList.populateKnownAttributes(this,all, org.openprovenance.prov.model.Type.class);
}
return this.type;
}
public List<org.openprovenance.prov.model.Other> getOther() {
if (others == null) {
others=AttributeList.populateKnownAttributes(this,all, org.openprovenance.prov.model.Other.class);
}
return this.others;
}
/** Gets the List of all attributes
* @see org.openprovenance.prov.xml.HasAllAttributes#getAllAttributes()
*/
@Override
public List<Attribute> getAllAttributes() {
if (all == null) {
all = new SortedAttributeList<Attribute>();
}
return this.all;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link org.openprovenance.prov.model.QualifiedName }
*
*/
public org.openprovenance.prov.model.QualifiedName getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link org.openprovenance.prov.model.QualifiedName }
*
*/
public void setId(org.openprovenance.prov.model.QualifiedName value) {
this.id = value;
}
public void equals(Object object, EqualsBuilder equalsBuilder) {
if (!(object instanceof Activity)) {
equalsBuilder.appendSuper(false);
return ;
}
if (this == object) {
return ;
}
final Activity that = ((Activity) object);
equalsBuilder.append(this.getStartTime(), that.getStartTime());
equalsBuilder.append(this.getEndTime(), that.getEndTime());
equalsBuilder.append(this.getLabel(), that.getLabel());
equalsBuilder.append(this.getLocation(), that.getLocation());
equalsBuilder.append(this.getType(), that.getType());
equalsBuilder.append(this.getOther(), that.getOther());
equalsBuilder.append(this.getId(), that.getId());
}
public boolean equals(Object object) {
if (!(object instanceof Activity)) {
return false;
}
if (this == object) {
return true;
}
final EqualsBuilder equalsBuilder = new JAXBEqualsBuilder();
equals(object, equalsBuilder);
return equalsBuilder.isEquals();
}
public void hashCode(HashCodeBuilder hashCodeBuilder) {
hashCodeBuilder.append(this.getStartTime());
hashCodeBuilder.append(this.getEndTime());
hashCodeBuilder.append(this.getLabel());
hashCodeBuilder.append(this.getLocation());
hashCodeBuilder.append(this.getType());
hashCodeBuilder.append(this.getOther());
hashCodeBuilder.append(this.getId());
}
public int hashCode() {
final HashCodeBuilder hashCodeBuilder = new JAXBHashCodeBuilder();
hashCode(hashCodeBuilder);
return hashCodeBuilder.toHashCode();
}
public void toString(ToStringBuilder toStringBuilder) {
{
XMLGregorianCalendar theStartTime;
theStartTime = this.getStartTime();
toStringBuilder.append("startTime", theStartTime);
}
{
XMLGregorianCalendar theEndTime;
theEndTime = this.getEndTime();
toStringBuilder.append("endTime", theEndTime);
}
{
List<org.openprovenance.prov.model.LangString> theLabel;
theLabel = this.getLabel();
toStringBuilder.append("label", theLabel);
}
{
List<org.openprovenance.prov.model.Location> theLocation;
theLocation = this.getLocation();
toStringBuilder.append("location", theLocation);
}
{
List<org.openprovenance.prov.model.Type> theType;
theType = this.getType();
toStringBuilder.append("type", theType);
}
{
List<org.openprovenance.prov.model.Other> theOthers;
theOthers = this.getOther();
toStringBuilder.append("others", theOthers);
}
{
org.openprovenance.prov.model.QualifiedName theId;
theId = this.getId();
toStringBuilder.append("id", theId);
}
}
public String toString() {
final ToStringBuilder toStringBuilder = new JAXBToStringBuilder(this);
toString(toStringBuilder);
return toStringBuilder.toString();
}
public Kind getKind() {
return org.openprovenance.prov.model.StatementOrBundle.Kind.PROV_ACTIVITY;
}
}
| 31.170732 | 117 | 0.626761 |
9bd33305d18203d384833b0f592eff075fc13cd4 | 12,051 | package org.loose.fis.mov.services;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.*;
import org.loose.fis.mov.exceptions.EmailAddressAlreadyUsedException;
import org.loose.fis.mov.exceptions.PasswordIncorrectException;
import org.loose.fis.mov.exceptions.UserAlreadyExistsException;
import org.loose.fis.mov.exceptions.UserNotRegisteredException;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.*;
//@Disabled
class UserServiceTest {
@BeforeAll
static void beforeAll() {
FileSystemService.setApplicationFolder("moviefy_test");
FileSystemService.initDirectory();
}
@AfterAll
static void afterAll()
throws IOException {
FileUtils.cleanDirectory(FileSystemService.getApplicationHomePath()
.toFile());
}
@BeforeEach
void setUp()
throws IOException {
FileUtils.cleanDirectory(FileSystemService.getApplicationHomePath()
.toFile());
DatabaseService.initDatabase();
}
@AfterEach
void tearDown() {
DatabaseService.closeDatabase();
SessionService.destroySession();
}
@Test
@DisplayName("Check if client users are added correctly")
void addUserClient() {
assertDoesNotThrow(() -> UserService.addUser(
"test_client",
"test",
"test",
"test_test",
"test@test.test",
"Client",
"",
"",
""
));
assertEquals(1, UserService.getAllUsers().size());
assertEquals("Client", UserService.getAllUsers().get(0).getRole());
assertEquals(
"test_client",
UserService.getAllUsers().get(0).getUsername()
);
}
@Test
@DisplayName("Check if admin users are added correctly")
void addUserAdmin() {
assertDoesNotThrow(() -> UserService.addUser(
"test_admin",
"test",
"test",
"test_test",
"test@test.test",
"Admin",
"test",
"test",
"10"
));
assertEquals(1, UserService.getAllUsers().size());
assertEquals("Admin", UserService.getAllUsers().get(0).getRole());
assertEquals(
"test_admin",
UserService.getAllUsers().get(0).getUsername()
);
}
@Test
@DisplayName("Check if users with already existing usernames are rejected")
void addUserDuplicateUsername() {
assertDoesNotThrow(() -> UserService.addUser(
"test",
"test",
"test",
"test_test",
"test@test.test",
"Client",
"",
"",
""
));
assertThrows(UserAlreadyExistsException.class, () ->
UserService.addUser(
"test",
"test",
"test",
"test_test",
"test2@test.test",
"Admin",
"test",
"test",
"10"
)
);
assertEquals(1, UserService.getAllUsers().size());
}
@Test
@DisplayName("Check if users with an existing email are rejected")
void addUserEmailDuplicate() {
assertDoesNotThrow(() -> UserService.addUser(
"test",
"test",
"test",
"test_test",
"test@test.test",
"Client",
"",
"",
""
));
assertThrows(EmailAddressAlreadyUsedException.class, () ->
UserService.addUser(
"test2",
"test",
"test",
"test_test",
"test@test.test",
"Admin",
"test",
"test",
"10"
)
);
assertEquals(1, UserService.getAllUsers().size());
}
@Test
@DisplayName("Test a successful login")
void login() {
assertDoesNotThrow(() -> {
UserService.addUser(
"test",
"test",
"test",
"test_test",
"test@test.test",
"Client",
"",
"",
""
);
UserService.login("test", "test_test");
});
assertEquals("test", SessionService.getLoggedInUser().getUsername());
}
@Test
@DisplayName("Test a login failing due to using the wrong password")
void loginIncorrectPassword() {
assertDoesNotThrow(() -> UserService.addUser(
"test",
"test",
"test",
"test_test",
"test@test.test",
"Client",
"",
"",
""
));
assertThrows(
PasswordIncorrectException.class,
() -> UserService.login("test", "wrong")
);
}
@Test
@DisplayName("Test a login failing due to using a non-existent username")
void loginIncorrectUsername() {
assertThrows(
UserNotRegisteredException.class,
() -> UserService.login("test", "test")
);
}
@Test
@DisplayName("Test the getter for the list of users")
void getAllUsers() {
assertEquals(0, UserService.getAllUsers().size());
assertDoesNotThrow(() -> UserService.addUser(
"test",
"test",
"test",
"test_test",
"test@test.test",
"Client",
"",
"",
""
));
assertEquals(1, UserService.getAllUsers().size());
assertDoesNotThrow(() -> {
UserService.addUser(
"test2",
"test",
"test",
"test_test",
"test2@test.test",
"Client",
"",
"",
""
);
UserService.addUser(
"test3",
"test",
"test",
"test_test",
"test3@test.test",
"Client",
"",
"",
""
);
});
assertEquals(3, UserService.getAllUsers().size());
}
@Test
@DisplayName("Test logout")
void logout() {
assertDoesNotThrow(() -> {
UserService.addUser(
"test",
"test",
"test",
"test_test",
"test@test.test",
"Client",
"",
"",
""
);
assertDoesNotThrow(() -> UserService.login("test", "test_test"));
UserService.logout();
});
assertNull(SessionService.getLoggedInUser());
}
@Test
@DisplayName("Check if the password can be changed before login")
void changePasswordBeforeLogin() {
assertDoesNotThrow(() -> {
UserService.addUser(
"test",
"test",
"test",
"test_test",
"test@test.test",
"Client",
"",
"",
""
);
UserService.login("test", "test_test");
UserService.changePasswordBeforeLogin(
"test@test.test",
"new_test_password"
);
UserService.logout();
UserService.login("test", "new_test_password");
});
}
@Test
@DisplayName("Check if the password won't be changed before login on nonexistent e-mail given")
void changePasswordBeforeLoginInvalidEmail() {
assertDoesNotThrow(() -> UserService.addUser(
"test",
"test",
"test",
"test_test",
"test@test.test",
"Client",
"",
"",
""
));
assertThrows(UserNotRegisteredException.class, () ->
UserService.changePasswordBeforeLogin(
"wrong_email@test.test",
"new_test_password"
));
}
@Test
@DisplayName("Check if the password can be changed after logging in")
void changePasswordAfterLogin() {
assertDoesNotThrow(() -> {
UserService.addUser(
"test",
"test",
"test",
"test_test",
"test@test.test",
"Client",
"",
"",
""
);
UserService.login("test", "test_test");
UserService.changePasswordAfterLogin(
"test_test",
"new_test_password"
);
UserService.logout();
UserService.login("test", "new_test_password");
});
}
@Test
@DisplayName("Check if the password won't be changed after login if the wrong confirmation old password is provided")
void changePasswordAfterLoginWrongOldPassword() {
assertDoesNotThrow(() -> {
UserService.addUser(
"test",
"test",
"test",
"test_test",
"test@test.test",
"Client",
"",
"",
""
);
UserService.login("test", "test_test");
});
assertThrows(PasswordIncorrectException.class, () ->
UserService.changePasswordAfterLogin(
"wrong_old_password",
"new_test_password"
));
UserService.logout();
assertThrows(PasswordIncorrectException.class, () ->
UserService.login("test", "new_test_password")
);
}
@Test
@DisplayName("Test if an existing user can be found by username")
void findUser() {
assertDoesNotThrow(() -> {
UserService.addUser(
"test",
"test",
"test",
"test_test",
"test@test.test",
"Client",
"",
"",
""
);
});
assertNull(UserService.findUser("nonexistent"));
assertEquals(
"test",
UserService.findUser("test").getUsername()
);
}
@Test
@DisplayName("Test if an existing user can be found by email")
void findUserByEmail() {
assertDoesNotThrow(() -> {
UserService.addUser(
"test",
"test",
"test",
"test_test",
"test@test.test",
"Client",
"",
"",
""
);
});
assertNull(UserService.findUserByEmail("nonexistent@test.test"));
assertEquals(
"test@test.test",
UserService.findUserByEmail("test@test.test").getEmail()
);
}
}
| 29.682266 | 121 | 0.426272 |
76451991c10c109050aa25f8a4fa5a088bfcd628 | 6,809 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package Swing_Framework_Application;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
*
* @author suraj
*/
public class signup extends javax.swing.JFrame {
/**
* Creates new form signup
*/
public signup() {
initComponents();
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jToggleButton1 = new javax.swing.JToggleButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel1.setText("rollno");
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 290, 40, 50));
jLabel2.setText("Name");
getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 200, 40, 50));
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 280, 240, 80));
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
getContentPane().add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 170, 240, 80));
jToggleButton1.setText("Next");
jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton1ActionPerformed(evt);
}
});
getContentPane().add(jToggleButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 415, 160, 50));
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField1ActionPerformed
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField2ActionPerformed
private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed
// TODO add your handling code here:
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/swing","root","sssss");
//Creating an query
String q="insert into student(Name,RollNo) values (?,?)";
//getting The prpared statement
PreparedStatement stmnt=con.prepareStatement(q);
String username=jTextField2.getText();
String rollno=jTextField1.getText();
//setting the values into it by using the variables..
stmnt.setString(1,username);
stmnt.setString(2,rollno);
stmnt.executeUpdate();
new InstructionStudent(rollno).setVisible(true);
System.out.println("Values inserted....");
JOptionPane.showMessageDialog(this, "Congrats!! "+username+"Please Now Login!","Information",JOptionPane.INFORMATION_MESSAGE);
new InstructionStudent(rollno).setVisible(true);
dispose();
}catch(Exception e){
System.out.println(e.getMessage());
}
}//GEN-LAST:event_jToggleButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(signup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(signup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(signup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(signup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new signup().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JToggleButton jToggleButton1;
// End of variables declaration//GEN-END:variables
}
| 42.55625 | 142 | 0.641651 |
82c2fede424bdfc3265f0a66f2739ff1b712990b | 51 | package p;
interface A{
/*[*/void m(int i);/*]*/
} | 12.75 | 25 | 0.529412 |
c3572a8b77777a007aa0a52c717d8baee14e122d | 1,233 | package com.infinityraider.elementalinvocations.network;
import com.infinityraider.infinitylib.network.MessageBase;
import com.infinityraider.elementalinvocations.entity.EntityReplicate;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.relauncher.Side;
public class MessageTrackPlayerUpdate extends MessageBase<IMessage> {
private double deltaX;
private double deltaY;
private double deltaZ;
public MessageTrackPlayerUpdate() {
super();
}
public MessageTrackPlayerUpdate(double deltaX, double deltaY, double deltaZ) {
this();
this.deltaX = deltaX;
this.deltaY = deltaY;
this.deltaZ = deltaZ;
}
@Override
public Side getMessageHandlerSide() {
return Side.SERVER;
}
@Override
protected void processMessage(MessageContext ctx) {
if(ctx.getServerHandler().player != null) {
EntityReplicate.updatePlayerMovement(ctx.getServerHandler().player, this.deltaX, this.deltaY, this.deltaZ);
}
}
@Override
protected IMessage getReply(MessageContext ctx) {
return null;
}
}
| 29.357143 | 119 | 0.718573 |
1d3401cea387c52426c767a86897053a7ac38097 | 310 | package com.stylefeng.guns.modular.club.service.impl;
import org.springframework.stereotype.Service;
import com.stylefeng.guns.modular.club.service.IGroupService;
/**
* 俱乐部管理Dao
*
* @author fengshuonan
* @Date 2018-09-16 21:45:55
*/
@Service
public class GroupServiceImpl implements IGroupService {
}
| 18.235294 | 61 | 0.770968 |
3514784f1b6b7f5e32aca02130be57e748375607 | 906 | import java.math.BigDecimal;
public class RecursionDemo {
public static Number calculateSum(Number[] array) {
return calculateSum(array, array.length-1);
}
public static Number calculateSum(Number[] array, int i) {
if (i == 0)
//recursion base case: first item in the array.
return array[i];
else
//return array[i] + calculateSum(array, i-1);
return new BigDecimal( array[i].floatValue() ).add( new BigDecimal( calculateSum(array, i-1).floatValue() ) );
}//end Sum
public static Number calculateProduct(Number[] array) {
return calculateProduct(array, array.length-1);
}
public static Number calculateProduct(Number[] array, int i) {
if (i == 0)
//recursion base case: first item in the array.
return array[i];
else
return new BigDecimal( array[i].floatValue() ).multiply( new BigDecimal( calculateProduct(array, i-1).floatValue() ) );
}//end Product
}
| 28.3125 | 122 | 0.695364 |
5b4572e77ff3833290966670cf41d7205a94f784 | 1,419 | package cn.obcp.main.system.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import cn.obcp.base.LayUiRetData;
import cn.obcp.base.controller.BaseController;
import cn.obcp.base.service.BaseService;
import cn.obcp.main.system.domain.TOperateLog;
import cn.obcp.main.system.service.OperateLogService;
import io.swagger.annotations.ApiOperation;
// ##remain#import#
/**
* <pre>
* 操作记录的Controller
* 该代码通过mgicode代码生成器生成
* </pre>
*/
@RestController
@RequestMapping("/v1/operatelog/")
public class OperateLogController extends BaseController<TOperateLog, Long> {
@Autowired
private OperateLogService operateLogService;
@Autowired
@Override
public void setEntityService(@Qualifier("bsOperateLogService") BaseService<TOperateLog, Long> entityService) {
this.entityService = entityService;
}
@ApiOperation("操作日志列表")
@RequestMapping(value="getList",method={RequestMethod.POST,RequestMethod.GET})
public LayUiRetData getList(@RequestParam Map<String, Object> params) {
return operateLogService.getList(params);
}
// ##remain#property#
} | 28.959184 | 111 | 0.804792 |
5edfaac38a544ce7f1fd7f5384b37acaa942861a | 783 | package com.geekerstar.s18;
public class Solution2 {
public void Mirror(TreeNode root) {
// 若root不为空,则进行镜像处理,否则不进行任何处理
if(root != null) {
// 设置中间变量,将root的左右子树交换(左、右节点是否为空不影响)
TreeNode tem = null;
tem = root.left;
root.left = root.right;
root.right = tem;
// 若交换后左子树不为空,则对其镜像处理
if(root.left != null) {
Mirror(root.left);
}
// 若交换后右子树不为空,则对其镜像处理
if(root.right != null) {
Mirror(root.right);
}
}
}
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
}
| 25.258065 | 48 | 0.472542 |
ea2f9c6c29d8b15339f4a8aab0548ab91af4a731 | 1,492 | package rs.math.oop1.z200604.fxmlMVP.z01.osobe.editor;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import rs.math.oop1.z200604.fxmlMVP.z01.osobe.model.DataModel;
public class EditorController {
@FXML
private TextField firstNameField ;
@FXML
private TextField lastNameField ;
@FXML
private TextField emailField ;
private DataModel model ;
public void initModel(DataModel model) {
if (this.model != null) {
throw new IllegalStateException("Model can only be initialized once");
}
this.model = model ;
model.currentPersonProperty().addListener((obs, oldPerson, newPerson) -> {
if (oldPerson != null) {
firstNameField.textProperty().unbindBidirectional(oldPerson.imeProperty());
lastNameField.textProperty().unbindBidirectional(oldPerson.prezimeProperty());
emailField.textProperty().unbindBidirectional(oldPerson.emailProperty());
}
if (newPerson == null) {
firstNameField.setText("");
lastNameField.setText("");
emailField.setText("");
} else {
firstNameField.textProperty().bindBidirectional(newPerson.imeProperty());
lastNameField.textProperty().bindBidirectional(newPerson.prezimeProperty());
emailField.textProperty().bindBidirectional(newPerson.emailProperty());
}
});
}
} | 37.3 | 94 | 0.637399 |
3dfb54cf957021a04fbc12e85fd85970b2a77cbf | 3,101 | package ua.zs.signalcorps;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import ua.zs.elements.Equipage;
public class AddEquipageActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_equipage);
initiateActionBarIconButton();
initiateButtons();
}
private void initiateActionBarIconButton() {
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
}
private void initiateButtons() {
Button addButton = (Button) findViewById(R.id.buttonAdd);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String secretName = String.valueOf(((EditText) findViewById(R.id.ownerText)).getText());
String idText = String.valueOf(((EditText) findViewById(R.id.idText)).getText());
int id = Integer.valueOf( !idText.equals("") ? idText : "0" );
SignalCorpsDB db = new SignalCorpsDB(AddEquipageActivity.this);
if( !idText.equals("") && !secretName.equals("")) {
if(id > 0) {
if(db.getPersonBySecretName(secretName) != null) {
if(db.getPersonBySecretName(secretName).getRank() <= HomeActivity.user.getRank()) {
if (!db.addEquipage(new Equipage(id, db.getPersonBySecretName(secretName)))) {
Toast.makeText(AddEquipageActivity.this, R.string.id_exists_error, Toast.LENGTH_LONG)
.show();
} else {
AddEquipageActivity.this.finish();
}
} else {
Toast.makeText(AddEquipageActivity.this, R.string.no_permission, Toast.LENGTH_LONG)
.show();
}
} else {
Toast.makeText(AddEquipageActivity.this, R.string.owner_not_found, Toast.LENGTH_LONG)
.show();
}
} else {
Toast.makeText(AddEquipageActivity.this, R.string.id_error, Toast.LENGTH_LONG)
.show();
}
} else {
Toast.makeText(AddEquipageActivity.this, R.string.needed_error, Toast.LENGTH_LONG)
.show();
}
}
});
Button cancelButton = (Button) findViewById(R.id.buttonCancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
} | 43.676056 | 121 | 0.527249 |
dc31f6dd7c4a4abded574ec56526b8823ec0e08b | 3,223 | package com.devmel.apps.linkbuscontrol.view.swing;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import com.devmel.apps.linkbuscontrol.R;
import com.devmel.apps.linkbuscontrol.controller.DeviceController;
import com.devmel.apps.linkbuscontrol.view.IStatusView;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DeviceStatusPanel extends JPanel implements IStatusView {
private static final long serialVersionUID = -8341191353474169184L;
private DeviceController controller;
private JProgressBar progressBar;
private JButton btnConnect;
private JLabel lblStringIP;
private JLabel lblMsg;
/**
* Create the panel.
*/
public DeviceStatusPanel() {
GridBagLayout gbl_panelCommands = new GridBagLayout();
gbl_panelCommands.columnWidths = new int[]{75, 146, 88, 0};
gbl_panelCommands.columnWeights = new double[]{1.0, 1.0, 1.0, Double.MIN_VALUE};
setLayout(gbl_panelCommands);
lblStringIP = new JLabel();
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel.gridx = 1;
gbc_lblNewLabel.gridy = 0;
add(lblStringIP, gbc_lblNewLabel);
progressBar = new JProgressBar();
GridBagConstraints gbc_progressBar = new GridBagConstraints();
gbc_progressBar.anchor = GridBagConstraints.NORTH;
gbc_progressBar.insets = new Insets(0, 0, 5, 5);
gbc_progressBar.gridx = 1;
gbc_progressBar.gridy = 1;
progressBar.setIndeterminate(true);
add(progressBar, gbc_progressBar);
progressBar.setVisible(false);
btnConnect = new JButton(R.bundle.getString("connect"));
btnConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(controller!=null){
controller.connectClick();
}
}
});
GridBagConstraints gbc_btnConnect = new GridBagConstraints();
gbc_btnConnect.anchor = GridBagConstraints.NORTH;
gbc_btnConnect.insets = new Insets(0, 0, 5, 5);
gbc_btnConnect.gridx = 1;
gbc_btnConnect.gridy = 1;
add(btnConnect, gbc_btnConnect);
lblMsg = new JLabel();
lblMsg.setForeground(Color.RED);
GridBagConstraints gbc_lblMsg = new GridBagConstraints();
gbc_lblMsg.insets = new Insets(0, 0, 0, 5);
gbc_lblMsg.gridx = 1;
gbc_lblMsg.gridy = 2;
add(lblMsg, gbc_lblMsg);
btnConnect.setVisible(false);
}
protected void setController(DeviceController controller) {
this.controller = controller;
}
protected void setAddress(String value){
if(value != null)
lblStringIP.setText(R.bundle.getString("address")+" : "+value);
}
@Override
public void startProgress(){
lblMsg.setVisible(false);
progressBar.setVisible(true);
btnConnect.setVisible(false);
}
@Override
public void stopProgress(){
progressBar.setVisible(false);
btnConnect.setVisible(false);
}
@Override
public void disconnected(String error){
if(error!=null){
lblMsg.setText(error);
lblMsg.setVisible(true);
}else{
lblMsg.setVisible(false);
}
progressBar.setVisible(false);
btnConnect.setVisible(true);
}
}
| 29.036036 | 82 | 0.753956 |
c97ab3e4581a1236c6f11fdc923586d48002c385 | 657 | package com.github.charlemaznable.httpclient.common;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Inherited
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(FixedParameters.class)
public @interface FixedParameter {
String name();
String value() default "";
Class<? extends FixedValueProvider> valueProvider() default FixedValueProvider.class;
}
| 27.375 | 89 | 0.809741 |
6e92409623e2481cc962e880aedfae6315b0091b | 1,847 | /* Copyright © 2010 www.myctu.cn. All rights reserved. */
package com.sirius.upns.test.unit;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
/**
* @project node-server
* @create 2013-8-14-下午12:32:51
* @author pippo
*/
public class AddJAVAFileHeader {
private static String copy_right = "/* Copyright © 2010 www.myctu.cn. All rights reserved. */\n";
private static void process(String root) throws IOException {
Collection<File> java_files = FileUtils.listFiles(new File(root), new IOFileFilter() {
private static final String JAVA_SUFFFIX = "java";
@Override
public boolean accept(File dir, String name) {
return JAVA_SUFFFIX.equals(FilenameUtils.getExtension(name).toLowerCase());
}
@Override
public boolean accept(File file) {
return JAVA_SUFFFIX.equals(FilenameUtils.getExtension(file.getName()).toLowerCase());
}
}, TrueFileFilter.INSTANCE);
for (File file : java_files) {
System.out.printf("process file:[%s]\n", file.getCanonicalPath());
String java = FileUtils.readFileToString(file);
if (java.startsWith(copy_right)) {
continue;
}
FileUtils.writeStringToFile(file, copy_right + java);
}
}
public static void main(String[] args) throws IOException {
process("/Users/pippo/Documents/projects/platform/common");
process("/Users/pippo/Documents/projects/notification-server/master/");
process("/Users/pippo/Documents/projects/platform/components/service-gateway/trunk");
process("/Users/pippo/Documents/projects/platform/components/cas/trunk");
process("/Users/pippo/Documents/projects/platform/components/resource/trunk");
}
}
| 29.790323 | 98 | 0.742826 |
1e57442556de3d255941c3eca187fa7d6ec624c9 | 1,796 | package ch9;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.web.client.RestTemplate;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class UserDetailsServiceTest {
private String URL = "http://localhost:8080/userdetails";
private RestTemplate resttemplate;
@BeforeClass
public void setup() {
resttemplate = new RestTemplate();
// try {
// populateDB();
// } catch (SQLException e) {
// e.printStackTrace();
// }
if(System.getProperty("url") != null && System.getProperty("url").length()!= 0){
URL = System.getProperty("url").trim();
System.out.println(URL);
}
}
/* private void populateDB() throws SQLException {
Connection con = null ;
try {
Class.forName("org.h2.Driver");
con = DriverManager.getConnection("jdbc:h2:~/data/test;AUTO_SERVER=TRUE", "sa", "sa");
PreparedStatement prep = con
.prepareStatement("INSERT INTO User (userid, name, email) VALUES (?,?,?)");
con.setAutoCommit(true);
prep.setString(1, "User1");
prep.setString(2, "User user");
prep.setString(3, "user@abc.com");
prep.execute();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
con.close();
}
}
*/
@Test(dependsOnMethods="createUser")
public void getUsers() {
User[] response = resttemplate.getForObject(URL, User[].class);
Assert.assertEquals(response.length, 1);
}
@Test
public void createUser() {
User request = new User("User1", "User user", "user@abc.com");
User response = resttemplate.postForObject(URL, request, User.class);
Assert.assertEquals(response.getEmail(), "user@abc.com");
}
}
| 26.028986 | 89 | 0.692094 |
812deca0edf4bd2fbd92cb22890716826efe1461 | 4,487 | package org.bougainvillea.java.dsaa.search;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 二分查找
* 递归版
*
* 非递归版
*
* 如果100个数
* 时间复杂度=以2为底100的对数
* log 100 2^6<100<2^7,最慢7次就可以找到
* 2
*
* 中值=(left+right)/2
*/
public class BinarySearch {
public static void main(String[] args) {
int a[] = {1, 8, 10, 89, 1000, 1234};
System.err.println(binarySearch(8, a, 0, a.length - 1));
int b[] = {1, 8, 10, 89, 1000, 1000,1234};
a=b;
System.err.println(binarySearchPro(1000, a, 0, a.length - 1).toString());
//非递归版
int c[] = {1000, 1000, 1000, 1000, 1000, 1000,1000};
System.err.println(binarySearchNoRecur(b,1000));
System.err.println(binarySearchNoRecurPro(b,1000));
List<Integer> list = binarySearchNoRecurPro(c, 1000);
Collections.sort(list);
System.err.println(list);
}
/**
* l 0 0 1
* mid 2 0
* r 5 1 1
*
*/
public static int binarySearch(int finalVal, int a[], int left, int right) {
//判断是否在区间
if (finalVal >= a[left] && finalVal <= a[right]) {
if(left>right){
return -1;
}
int mid = right + left / 2;
int midVal = a[mid];
if (finalVal > midVal) {
return binarySearch(finalVal, a, mid + 1, right);
} else if (finalVal < midVal) {
return binarySearch(finalVal, a, left, mid - 1);
} else {
return mid;
}
}else return -1;
}
/**
* 查找重复
*/
public static List<Integer> binarySearchPro(int finalVal, int a[], int left, int right) {
//判断是否在区间
if (finalVal >= a[left] && finalVal <= a[right]) {
if(left>right){
return new ArrayList<>();
}
int mid = right + left / 2;
int midVal = a[mid];
if (finalVal > midVal) {
return binarySearchPro(finalVal, a, mid + 1, right);
} else if (finalVal < midVal) {
return binarySearchPro(finalVal, a, left, mid - 1);
} else {
List<Integer> list = new ArrayList<>();
int temp=mid-1;
while (true){
if(temp<0||a[temp]!=finalVal){
break;
}
list.add(temp);
temp-=1;
}
list.add(mid);
temp=mid+1;
while (true){
if(temp>a.length-1||a[temp]!=finalVal){
break;
}
list.add(temp);
temp=1;
}
return list;
}
}else return new ArrayList<>();
}
//非递归版二分查找
/**
* 非递归版二分查找算法
* @param arr 升序待查找数组 natural ordering ===1,2,3,4
* @param target 查找目标
* @return 查找目标的下标,-1表示没找到
*/
public static int binarySearchNoRecur(int[] arr,int target){
int left=0;
int right= arr.length-1;
while (left<=right){
int mid =(left+right)/2;
if(arr[mid]==target){
return mid;
}else if(arr[mid]>target){
right=mid-1;
}else {
left=mid+1;
}
}
return -1;
}
/**
* 非递归版二分查找算法,重复值
* @param arr 升序待查找数组 natural ordering ===1,2,3,4
* @param target 查找目标
* @return 查找目标的下标,-1表示没找到
*/
public static List<Integer> binarySearchNoRecurPro(int[] arr,int target){
List<Integer> result=new ArrayList<>();
int left=0;
int right= arr.length-1;
int temp;
while (left<=right){
int mid =(left+right)/2;
if(arr[mid]==target){
temp=mid;
result.add(temp);
while (temp-1>=0&&target==arr[temp-1]){
result.add(temp-1);
temp-=1;
}
temp=mid;
while (temp+1<arr.length&&target==arr[temp+1]){
result.add(temp+1);
temp+=1;
}
return result;
}else if(arr[mid]>target){
right=mid-1;
}else {
left=mid+1;
}
}
return result;
}
}
| 26.708333 | 93 | 0.448629 |
7ee869bd01ee81c2750bd04f434c9565a2aa961a | 1,048 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.javatmp.userstats;
import com.javatmp.module.user.service.UserStatsService;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
*
* @author JavaTMP
*/
@SpringBootTest
public class UsersGenderGrouping {
@Autowired
UserStatsService userStatsService;
@Test
public void main() {
List<Object[]> results = userStatsService.usersGenderGrouping();
for (Object[] row : results) {
System.out.println(Arrays.toString(row));
}
results = userStatsService.overallUsersStatuses();
for (Object[] row : results) {
System.out.println(Arrays.toString(row));
}
}
}
| 24.372093 | 80 | 0.668893 |
08cf9b07689b78e89b6e170c0f244cd9684fab66 | 5,784 | package cc.mrbird.febs.app.controller;
import cc.mrbird.febs.app.entity.Attention;
import cc.mrbird.febs.app.service.IAttentionService;
import cc.mrbird.febs.common.annotation.ControllerEndpoint;
import cc.mrbird.febs.common.utils.FebsUtil;
import cc.mrbird.febs.common.entity.FebsConstant;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.common.entity.QueryRequest;
import cc.mrbird.febs.common.utils.json.Body;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
/**
* Controller
*
* @author 冷酷的苹果
* @date 2020-05-07 16:30:04
*/
@Slf4j
@Validated
@Controller
@CrossOrigin
@RequestMapping("app")
@RequiredArgsConstructor
public class AttentionController extends BaseController {
private final IAttentionService attentionService;
@GetMapping(FebsConstant.VIEW_PREFIX + "attention")
public String attentionIndex() {
return FebsUtil.view("attention/attention");
}
@GetMapping("attention")
@ResponseBody
@RequiresPermissions("attention:list")
public FebsResponse getAllAttentions(Attention attention) {
return new FebsResponse().success().data(attentionService.findAttentions(attention));
}
@GetMapping("attention/list")
@ResponseBody
@RequiresPermissions("attention:list")
public FebsResponse attentionList(QueryRequest request, Attention attention) {
Map<String, Object> dataTable = getDataTable(this.attentionService.findAttentions(request, attention));
return new FebsResponse().success().data(dataTable);
}
@ControllerEndpoint(operation = "新增Attention", exceptionMessage = "新增Attention失败")
@PostMapping("attention")
@ResponseBody
@RequiresPermissions("attention:add")
public FebsResponse addAttention(@Valid Attention attention) {
this.attentionService.createAttention(attention);
return new FebsResponse().success();
}
@ControllerEndpoint(operation = "删除Attention", exceptionMessage = "删除Attention失败")
@GetMapping("attention/delete")
@ResponseBody
@RequiresPermissions("attention:delete")
public FebsResponse deleteAttention(Attention attention) {
this.attentionService.deleteAttention(attention);
return new FebsResponse().success();
}
@ControllerEndpoint(operation = "修改Attention", exceptionMessage = "修改Attention失败")
@PostMapping("attention/update")
@ResponseBody
@RequiresPermissions("attention:update")
public FebsResponse updateAttention(Attention attention) {
this.attentionService.updateAttention(attention);
return new FebsResponse().success();
}
@ControllerEndpoint(operation = "修改Attention", exceptionMessage = "导出Excel失败")
@PostMapping("attention/excel")
@ResponseBody
@RequiresPermissions("attention:export")
public void export(QueryRequest queryRequest, Attention attention, HttpServletResponse response) {
List<Attention> attentions = this.attentionService.findAttentions(queryRequest, attention).getRecords();
ExcelKit.$Export(Attention.class, response).downXlsx(attentions, false);
}
@ControllerEndpoint(operation = "查询指定写字楼关注", exceptionMessage = "查询指定写字楼关注失败")
@GetMapping("selectByOfficeBuilding")
@ResponseBody
public Body selectByOfficeBuilding(String phone, Integer id) {
return this.attentionService.selectByOfficeBuilding(phone, id);
}
@ControllerEndpoint(operation = "租户页面查询写字楼", exceptionMessage = "租户页面查询写字楼失败")
@GetMapping("selectBuildingInLessee")
@ResponseBody
public Body selectBuildingInLessee(String name, Integer id) {
return this.attentionService.selectBuildingInLessee(name, id);
}
@ControllerEndpoint(operation = "查询房源管理员", exceptionMessage = "查询房源管理员失败")
@GetMapping("selectUserByType")
@ResponseBody
public Body selectUserByType(String type, Integer id) {
return this.attentionService.selectUserByType(type, id);
}
@ControllerEndpoint(operation = "添加房源管理员", exceptionMessage = "添加房源管理员失败")
@PostMapping("insertAttention")
@ResponseBody
public Body insertAttention(Attention attention, Integer id) {
return this.attentionService.insertAttention(attention, id);
}
@ControllerEndpoint(operation = "删除房源管理员", exceptionMessage = "删除房源管理员失败")
@PostMapping("delectUser")
@ResponseBody
public Body delectUser(Integer userid, Integer id) {
return attentionService.delectUser(userid, id);
}
/**
* @Description: 查询用户下管理的房源
* @Param: [userid]
* @return: cc.mrbird.febs.common.utils.json.Body
* @Author: 冷酷的苹果
* @Date: 2020/5/16 13:48
*/
@ControllerEndpoint(operation = "查询用户下管理的房源", exceptionMessage = "查询用户下管理的房源失败")
@GetMapping("selectAttentionByUserid")
@ResponseBody
public Body selectAttentionByUserid(Integer userid) {
return this.attentionService.selectAttentionByUserid(userid);
}
/**
* @Description:
* @Param: [id]
* @return: cc.mrbird.febs.common.utils.json.Body
* @Author: 冷酷的苹果
* @Date: 2020/5/22 16:37
*/
@ControllerEndpoint(operation = "查询旗下的房源", exceptionMessage = "查询旗下的房源失败")
@GetMapping("selectHouseInSet")
@ResponseBody
public Body selectHouseInSet(Integer id) {
return this.attentionService.selectHouseInSet(id);
}
}
| 35.703704 | 112 | 0.735996 |
98a83336cfebdef8b0791a9fafeaff9bca93cbda | 291 | package coding.challenge;
public class Main {
public static void main( String[] args ) {
Programmer p = new Programmer( "Joana Nimar", "Toronto" );
String name = p.getName();
String team = p.getTeam();
System.out.println( name + " is assigned to the " + team + " team" );
}
}
| 19.4 | 71 | 0.642612 |
bb4c0880d071dc766b392925f377972567536864 | 1,202 | public class Particle
{
private float posX, posY, size, velX, velY, gravity = (float) 0.38;
private int relPos;
private SnowboardMadness screen;
public Particle(SnowboardMadness screen)
{
this.screen = screen;
this.posX = 0;
this.posY = 0;
this.velX = 0;
this.velY = 0;
this.size = screen.random(4, 10);
}
public void spawn()
{
relPos = screen.player.relPos();
switch (relPos)
{
case 0:
posX = 80 - screen.player.width() / 2;
posY = screen.height - screen.random(0, screen.player.height());
velX = -(float) screen.random(7, 15);
velY = -(float) screen.random(-5, 5);
break;
case 2:
posX = screen.width - 80 + screen.player.width() / 2;
posY = screen.height - screen.random(0, screen.player.height());
velX = (float) screen.random(7, 15);
velY = -(float) screen.random(-5, 5);
break;
}
}
public void draw()
{
if (screen.height < posY || 0 > posX || 0 > posY || screen.width < posX || relPos == 1)
{
screen.player.particles().remove(this);
}
else
{
posX += velX;
posY += velY;
velY += gravity;
screen.fill(200);
screen.rect(posX, posY, size, size);
}
}
}
| 22.679245 | 88 | 0.586522 |
121f25ed72adaf1f403f071ab8da443ee19a27fe | 1,867 | package whiteboxTraceble;
import acess.ParserUtils;
import acess.PolicySyntaxException;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.PairingParameters;
import it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory;
import it.unisa.dia.gas.plaf.jpbc.pairing.a.TypeACurveGenerator;
import serparams.PairingKeySerPair;
import utils.PairingUtils;
import utils.PairingUtils.PairingGroupType;
public class Encryption {
protected static int[][] accessPolicy;
protected static Element elementMessage;
protected static String Message;
protected static CiphertextSerParameter cipher;
protected static String[] rhos;
public static String encryText(String message, String accessPolicyMessage) {
WhiteBoxEngine abe = new WhiteBoxEngine();
int rBits = 160; //群的阶
int qBits = 512; // zq的阶。
TypeACurveGenerator pg = new TypeACurveGenerator(rBits, qBits); //指定椭圆曲线的种类 typeA
PairingParameters typeAParams = pg.generate();
String[] attributeUniverse= {"A","B","C","D","E"};
int maxNumAttributes=5;
PairingKeySerPair KeyPair = abe.setup(typeAParams, maxNumAttributes, attributeUniverse);
try {
accessPolicy=ParserUtils.GenerateAccessPolicy(accessPolicyMessage);
} catch (PolicySyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rhos=new String[accessPolicy.length];
try {
rhos=ParserUtils.GenerateRhos(accessPolicyMessage);
} catch (PolicySyntaxException e) {
// TODO Auto-generated catch block
System.out.println("here");
e.printStackTrace();
}
elementMessage=PairingUtils.MapStringToGroup(PairingFactory.getPairing(typeAParams), message, PairingGroupType.GT).getImmutable();
CiphertextSerParameter cipher = (CiphertextSerParameter) abe.encryption(KeyPair.getPublic(), accessPolicy, rhos, elementMessage);
return cipher.getC().toString();
}
}
| 32.189655 | 133 | 0.768613 |
b97ce4ea20c34e73eb0e6376d3ebe207c3e2b089 | 438 | import bean.User;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
@Configurable
public class AppConfig {
// @Bean(name = "people")
// public People people(){
// return new People();
// }
@Bean(name = "user")
@Scope("prototype")
public User user(){
return new User();
}
}
| 20.857143 | 65 | 0.673516 |
88c1065423338eddbc932dead9f3ba86b990635e | 361 | package com.backbase.kalah.util;
public enum LogStatus {
START("Start"),
END("End"),
Exception("Exception");
private String status ;
LogStatus(String status){
this.status = status;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
} | 17.190476 | 42 | 0.598338 |
603c82a12af3db54166fe46c69dd2caf6ab5ee43 | 465 | package com.mystream.service;
import com.mystream.dom.Annotation;
import org.springframework.stereotype.Service;
import java.util.List;
public interface AnnotationService {
public Annotation saveAnnotation(Annotation anno);
public List<Annotation> searchAnnotation();
public List<Annotation> searchAnnotationWithSource( String source);
public Annotation searchAnnotationWithCanonical( String canonical);
public void deleteAnnotation( Annotation anno);
}
| 27.352941 | 68 | 0.825806 |
bc05b252e4b212e6c6daade23dea8bfa82818364 | 3,809 | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
public class Content {
public Content(LinkedList<String> termSet) throws IOException{
FileWriter out=new FileWriter("notrestore.txt",false);
for(String term:termSet)
{
String key = term.replaceAll("(\\S+)\\((\\S+)\\)", "$1");
String value = term.replaceAll("(\\S+)\\((\\S+)\\)", "$2");
//-------------------------------------
if(!"".equals(key)&&!"COMMACATEGORY".equals(value)&&!"DASHCATEGORY".equals(value)&&!"ETCCATEGORY".equals(value)&&!"PARENTHESISCATEGORY".equals(value)&&!"PERIODCATEGORY".equals(value)&&!"SEMICOLONCATEGORY".equals(value)&&!"SPCHANGECATEGORY".equals(value)&&!"QUESTIONCATEGORY".equals(value)&&!"EXCLAMATIONCATEGORY".equals(value)
&&!"COLONCATEGORY".equals(value)&&!"FW".equals(value)&&!"SHI".equals(value)&&!"DE".equals(value)&&!"V_2".equals(value)&&!"Caa".equals(value)&&!"Cab".equals(value)&&!"Cba".equals(value)&&!"Da".equals(value)&&!"Di".equals(value)&&!"Neqa".equals(value)&&!"Neqb".equals(value)
&&!"I".equals(value)&&!"T".equals(value)&&!"Nf".equals(value)&&!"Cbb".equals(value)&&!"Neu".equals(value)&&!"P".equals(value)&&!"Nd".equals(value)&&!"Nh".equals(value)&&!"Ncd".equals(value)&&!"的".equals(key)&&!"是".equals(key)&&!"一".equals(key)&&!"在".equals(key)&&!"有".equals(key)
&&!"個".equals(key)&&!"我".equals(key)&&!"這".equals(key)&&!"了".equals(key)&&!"他".equals(key)&&!"也".equals(key)&&!"就".equals(key)&&!"人".equals(key)&&!"都".equals(key)&&!"說".equals(key)&&!"而".equals(key)&&!"我們".equals(key)&&!"你".equals(key)&&!"了".equals(key)&&!"要".equals(key)
&&!"之".equals(key)&&!"及".equals(key)&&!"和".equals(key)&&!"與".equals(key)&&!"以".equals(key)&&!"很".equals(key)&&!"種".equals(key)&&!"中".equals(key)&&!"大".equals(key)&&!"著".equals(key)&&!"她".equals(key)&&!"那".equals(key)&&!"上".equals(key)&&!"但".equals(key)&&!"年".equals(key)&&!"還".equals(key)
&&!"時".equals(key)&&!"最".equals(key)&&!"自己".equals(key)&&!"為".equals(key)&&!"來".equals(key)&&!"所".equals(key)&&!"他們".equals(key)&&!"兩".equals(key)&&!"各".equals(key)&&!"上".equals(key)&&!"或".equals(key)&&!"等".equals(key)&&!"又".equals(key)&&!"將".equals(key)&&!"因為".equals(key)&&!"於".equals(key)
&&!"由".equals(key)&&!"從".equals(key)&&!"更".equals(key)&&!"被".equals(key)&&!"才".equals(key)&&!"已".equals(key)&&!"者".equals(key)&&!"每次".equals(key)&&!"把".equals(key)&&!"三".equals(key)&&!"甚麼".equals(key)&&!"其".equals(key)&&!"讓".equals(key)&&!"此".equals(key)&&!"做".equals(key)&&!"在".equals(key)
&&!"所以".equals(key)&&!"只".equals(key)&&!"則".equals(key)&&!"卻".equals(key)&&!"地".equals(key)&&!"並".equals(key)&&!"位".equals(key)&&!"得".equals(key)&&!"想".equals(key)&&!"去".equals(key)&&!"呢".equals(key)&&!"學生".equals(key)&&!"表示".equals(key)&&!"公司".equals(key)&&!"到".equals(key)&&!"將".equals(key)
)
out.write(key+", ");
//---------------------------------
}
out.close();//斷詞後還沒還原成一則一則留言
FileReader fr = new FileReader("notrestore.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter outrestore=new FileWriter("afterrestore.txt",true);//還原成一則一則留言(已斷詞)
String[] alinearray;
String line;
int i;
line=br.readLine().toString();
alinearray=line.split(", ");
for(i=1;i<alinearray.length;i++)
{
if(!alinearray[i].equals("、"))
{
System.out.print(alinearray[i]+", ");
outrestore.write(alinearray[i]+", ");
}
else
{
System.out.print("\n");
outrestore.write("\r\n");
}
}
outrestore.write("\r\n");
outrestore.close();
}
}
| 58.6 | 331 | 0.560777 |
9de5e41f74045ba9ef3fd1e224bca44f15bbd2ea | 3,111 | /*
* DiSNI: Direct Storage and Networking Interface
*
* Author: Patrick Stuedi <stu@zurich.ibm.com>
*
* Copyright (C) 2016-2018, IBM Corporation
*
* 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.ibm.disni.verbs.impl;
import java.io.IOException;
import java.nio.ByteBuffer;
import com.ibm.disni.verbs.IbvMr;
import com.ibm.disni.verbs.IbvPd;
import com.ibm.disni.verbs.SVCRegMr;
import com.ibm.disni.util.MemBuf;
import com.ibm.disni.util.MemoryAllocation;
import com.ibm.disni.util.MemoryUtils;
public class NatRegMrCall extends SVCRegMr {
private NativeDispatcher nativeDispatcher;
private RdmaVerbsNat verbs;
private MemoryAllocation memAlloc;
private NatIbvPd pd;
private int access;
private int bufferCapacity;
private MemBuf cmd;
private long userAddress;
private IbvMr mr;
private boolean valid;
public NatRegMrCall(RdmaVerbsNat verbs, NativeDispatcher nativeDispatcher, MemoryAllocation memAlloc,
IbvPd pd, ByteBuffer buffer, int access) {
set(verbs, nativeDispatcher, memAlloc, pd, MemoryUtils.getAddress(buffer),
buffer.capacity(), access);
}
public NatRegMrCall(RdmaVerbsNat verbs, NativeDispatcher nativeDispatcher, MemoryAllocation memAlloc,
IbvPd pd, long address, int length, int access) {
set(verbs, nativeDispatcher, memAlloc, pd, address, length, access);
}
private void set(RdmaVerbsNat verbs, NativeDispatcher nativeDispatcher, MemoryAllocation memAlloc,
IbvPd pd, long address, int length, int access) {
this.verbs = verbs;
this.nativeDispatcher = nativeDispatcher;
this.memAlloc = memAlloc;
this.cmd = memAlloc.allocate(3*4);
this.valid = true;
this.pd = (NatIbvPd) pd;
this.userAddress = address;
this.bufferCapacity = length;
this.access = access;
}
public SVCRegMr execute() throws IOException {
cmd.getBuffer().clear();
if (!pd.isOpen()) {
throw new IOException("Trying to register memory with closed PD.");
}
long objId = nativeDispatcher._regMr(pd.getObjId(), userAddress, bufferCapacity, access, cmd.address(), cmd.address() + 4, cmd.address() + 8);
if (objId <= 0){
throw new IOException("Memory registration failed with " + objId);
} else {
int lkey = cmd.getBuffer().getInt();
int rkey = cmd.getBuffer().getInt();
int handle = cmd.getBuffer().getInt();
this.mr = new NatIbvMr(objId, null, userAddress, bufferCapacity, access, lkey, rkey, handle);
}
return this;
}
public IbvMr getMr() {
return mr;
}
public boolean isValid() {
return valid;
}
public SVCRegMr free() {
cmd.free();
this.valid = false;
return this;
}
}
| 29.349057 | 144 | 0.731598 |
57dc2c50090c01ac4d6c63872b9ec9fbd1c5a160 | 1,958 | package com.chen.study.concurrent.concurrent3.juc.util.condition;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author 陈添明
* @date 2018/11/11
*/
public class ConditionExample1 {
private final static ReentrantLock lock = new ReentrantLock();
private final static Condition condition = lock.newCondition();
private static int data = 0;
private static AtomicBoolean noUse = new AtomicBoolean(true);
private static void buildData() {
try {
lock.lock(); // 等价 synchronized
while (noUse.get()){
// 如果数据还没有使用,等待
condition.await(); // 等价 monitor.wait()
}
// 数据被使用了,构建新数据
data++;
System.out.println(Thread.currentThread().getName() + ": 生产" + data);
Thread.sleep(1_000);
noUse.set(true);
condition.signal(); // 等价 monitor.notify()
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
private static void useData(){
try {
lock.lock();
while (!noUse.get()){
// 数据已经使用了,等待
condition.await();
}
// 使用数据
System.out.println(Thread.currentThread().getName() + ":消费" + data);
Thread.sleep(1_000);
noUse.set(false);
condition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
new Thread(() -> {
while (true){
buildData();
}
}).start();
new Thread(() -> {
while (true){
useData();
}
}).start();
}
}
| 25.428571 | 81 | 0.512257 |
a392f3338ee16f0c71c5cd5e05d6abe86e94dc1c | 1,600 | package com.minerarcana.transfiguration.recipe.json;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import net.minecraft.block.Block;
import net.minecraft.entity.EntityType;
import net.minecraft.tags.ITag;
import net.minecraft.tags.TagCollectionManager;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
public class TagJson {
public static ITag<EntityType<?>> getEntityTypeTag(JsonObject jsonObject, String fieldName) {
String tagName = JSONUtils.getString(jsonObject, fieldName);
ITag<EntityType<?>> entityTypeITag = TagCollectionManager.getManager().getEntityTypeTags().get(new ResourceLocation(tagName));
if (entityTypeITag != null) {
return entityTypeITag;
} else {
throw new JsonParseException("Failed ot find Entity Tag for " + tagName);
}
}
public static ITag<EntityType<?>> getEntityTypeTag(JsonObject jsonObject) {
return getEntityTypeTag(jsonObject, "tag");
}
public static ITag<Block> getBlockTag(JsonObject jsonObject, String fieldName) {
String tagName = JSONUtils.getString(jsonObject, fieldName);
ITag<Block> blockITag = TagCollectionManager.getManager().getBlockTags().get(new ResourceLocation(tagName));
if (blockITag != null) {
return blockITag;
} else {
throw new JsonParseException("Failed to find Block Tag for " + tagName);
}
}
public static ITag<Block> getBlockTag(JsonObject jsonObject) {
return getBlockTag(jsonObject, "tag");
}
}
| 39.02439 | 134 | 0.71 |
b20317ba60d78f440d692e02002d56e067da011f | 7,984 | package com.shangbaishuyao.gmall.realtime.app.func;
import com.alibaba.fastjson.JSONObject;
import com.shangbaishuyao.gmall.realtime.bean.TableProcess;
import com.shangbaishuyao.gmall.realtime.common.GmallConfig;
import com.shangbaishuyao.gmall.realtime.utils.MySQLUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
/**
* Author: 上白书妖
* Date: 2021/2/1
* Desc: 配置表处理函数
*/
public class TableProcessFunction extends ProcessFunction<JSONObject, JSONObject> {
//因为要将维度数据通过侧输出流输出,所以我们在这里定义一个侧输出流标记
private OutputTag<JSONObject> outputTag;
//用于在内存中存放配置表信息的Map <表名:操作,tableProcess>
private Map<String, TableProcess> tableProcessMap = new HashMap<>();
//用于在内存中存放已经处理过的表(在phoenix中已经建过的表)
private Set<String> existsTables = new HashSet<>();
//声明Phoenix的连接对象
Connection conn = null;
//实例化函数对象的时候,将侧输出流标签也进行赋值
public TableProcessFunction(OutputTag<JSONObject> outputTag) {
this.outputTag = outputTag;
}
//在函数被调用的时候执行的方法,执行一次
@Override
public void open(Configuration parameters) throws Exception {
//初始化Phoenix连接
Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");
conn = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER);
//初始化配置表信息
refreshMeta();
//开启一个定时任务
// 因为配置表的数据可能会发生变化,每隔一段时间就从配置表中查询一次数据,更新到map,并检查建表
//从现在起过delay毫秒后,每隔period执行一次
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
refreshMeta();
}
}, 5000, 5000);
}
private void refreshMeta() {
//========1.从MySQL数据库配置表中查询配置信息============
System.out.println("查询配置表信息");
List<TableProcess> tableProcessList = MySQLUtil.queryList("select * from table_process", TableProcess.class, true);
//对查询出来的结果集进行遍历
for (TableProcess tableProcess : tableProcessList) {
//获取源表表名
String sourceTable = tableProcess.getSourceTable();
//获取操作类型
String operateType = tableProcess.getOperateType();
//输出类型 hbase|kafka
String sinkType = tableProcess.getSinkType();
//输出目的地表名或者主题名
String sinkTable = tableProcess.getSinkTable();
//输出字段
String sinkColumns = tableProcess.getSinkColumns();
//表的主键
String sinkPk = tableProcess.getSinkPk();
//建表扩展语句
String sinkExtend = tableProcess.getSinkExtend();
//拼接保存配置的key
String key = sourceTable + ":" + operateType;
//========2.将从配置表中查询到配置信息,保存到内存的map集合中=============
tableProcessMap.put(key, tableProcess);
//========3.如果当前配置项是维度配置,需要向Hbase表中保存数据,那么我们需要判断phoenix中是否存在这张表=====================
if (TableProcess.SINK_TYPE_HBASE.equals(sinkType) && "insert".equals(operateType)) {
boolean notExist = existsTables.add(sourceTable);
//如果在内存Set集合中不存在这个表,那么在Phoenix中创建这种表
if (notExist) {
//检查在Phonix中是否存在这种表
//有可能已经存在,只不过是应用缓存被清空,导致当前表没有缓存,这种情况是不需要创建表的
//在Phoenix中,表的确不存在,那么需要将表创建出来
checkTable(sinkTable, sinkColumns, sinkPk, sinkExtend);
}
}
}
//如果没有从数据库的配置表中读取到数据
if (tableProcessMap == null || tableProcessMap.size() == 0) {
throw new RuntimeException("没有从数据库的配置表中读取到数据");
}
}
private void checkTable(String tableName, String fields, String pk, String ext) {
//如果在配置表中,没有配置主键 需要给一个默认主键的值
if (pk == null) {
pk = "id";
}
//如果在配置表中,没有配置建表扩展 需要给一个默认建表扩展的值
if (ext == null) {
ext = "";
}
//拼接建表语句
StringBuilder createSql = new StringBuilder("create table if not exists " +
GmallConfig.HABSE_SCHEMA + "." + tableName + "(");
//对建表字段进行切分
String[] fieldsArr = fields.split(",");
for (int i = 0; i < fieldsArr.length; i++) {
String field = fieldsArr[i];
//判断当前字段是否为主键字段
if (pk.equals(field)) {
createSql.append(field).append(" varchar primary key ");
} else {
createSql.append("info.").append(field).append(" varchar ");
}
if (i < fieldsArr.length - 1) {
createSql.append(",");
}
}
createSql.append(")");
createSql.append(ext);
System.out.println("创建Phoenix表的语句:" + createSql);
//获取Phoenix连接
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(createSql.toString());
ps.execute();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("Phoenix建表失败");
}
}
}
}
//每过来一个元素,方法执行一次,主要任务是根据内存中配置表Map对当前进来的元素进行分流处理
//TODO 主要任务是对大量数据做分流处理
@Override
public void processElement(JSONObject jsonObj, Context ctx, Collector<JSONObject> out) throws Exception {
//获取表名
String table = jsonObj.getString("table");
//获取操作类型
String type = jsonObj.getString("type");
//注意:问题修复 如果使用Maxwell的Bootstrap同步历史数据 ,这个时候它的操作类型叫bootstrap-insert
if ("bootstrap-insert".equals(type)) {
type = "insert";
jsonObj.put("type", type);
}
if (tableProcessMap != null && tableProcessMap.size() > 0) {
//根据表名和操作类型拼接key
String key = table + ":" + type;
//从内存的配置Map中获取当前key对象的配置信息
TableProcess tableProcess = tableProcessMap.get(key);
//如果获取到了该元素对应的配置信息
if (tableProcess != null) {
//获取sinkTable,指明当前这条数据应该发往何处 如果是维度数据,那么对应的是phoenix中的表名;如果是事实数据,对应的是kafka的主题名
jsonObj.put("sink_table", tableProcess.getSinkTable());
String sinkColumns = tableProcess.getSinkColumns();
//如果指定了sinkColumn,需要对保留的字段进行过滤处理
if (sinkColumns != null && sinkColumns.length() > 0) {
filterColumn(jsonObj.getJSONObject("data"), sinkColumns);
}
} else {
System.out.println("NO this Key:" + key + "in MySQL");
}
//根据sinkType,将数据输出到不同的流
if(tableProcess != null && tableProcess.getSinkType().equals(TableProcess.SINK_TYPE_HBASE)){
//如果sinkType = hbase ,说明是维度数据,通过侧输出流输出
ctx.output(outputTag,jsonObj);
}else if(tableProcess != null && tableProcess.getSinkType().equals(TableProcess.SINK_TYPE_KAFKA)){
//如果sinkType = kafka ,说明是事实数据,通过主流输出
out.collect(jsonObj);
}
}
}
//对Data中数据进行进行过滤
private void filterColumn(JSONObject data, String sinkColumns) {
//sinkColumns 表示要保留那些列 id,out_trade_no,order_id
String[] cols = sinkColumns.split(",");
//将数组转换为集合,为了判断集合中是否包含某个元素
List<String> columnList = Arrays.asList(cols);
//获取json对象中封装的一个个键值对 每个键值对封装为Entry类型
Set<Map.Entry<String, Object>> entrySet = data.entrySet();
Iterator<Map.Entry<String, Object>> it = entrySet.iterator();
for (;it.hasNext();) {
Map.Entry<String, Object> entry = it.next();
if(!columnList.contains(entry.getKey())){
it.remove();
}
}
}
} | 36.126697 | 123 | 0.584669 |
3faefb8cb5bb6500e1f08a5713293da5cfeae74b | 1,043 | package com.schoppen.schoppenerp.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class CATEG4 {
@Id
@GeneratedValue
private Long id_categ4;
@Column(nullable=false)
private String nombre;
@OneToMany(mappedBy="categoria4")
private Set<Cervezas> cervezas_cuarta_categoria = new HashSet<Cervezas>();
// **** GETTERS & SETTERS **** \\
public Long getId_categ4() {
return id_categ4;
}
public void setId_categ4(Long id_categ4) {
this.id_categ4 = id_categ4;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Set<Cervezas> getCervezas_cuarta_categoria() {
return cervezas_cuarta_categoria;
}
public void setCervezas_cuarta_categoria(Set<Cervezas> cervezas_cuarta_categoria) {
this.cervezas_cuarta_categoria = cervezas_cuarta_categoria;
}
}
| 19.679245 | 84 | 0.763183 |
f89cb8c999e8ec9986c3149da5e5be90f55ce181 | 159 | package name.remal.tracingspec.application;
import org.jetbrains.annotations.ApiStatus.Internal;
@Internal
interface CommandLineCommand extends Runnable {
}
| 19.875 | 52 | 0.842767 |
a8abddb10345de2acae92eb9388aeb736e4d6a48 | 12,478 | /*
* 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 viw;
/**
*
* @author emesson
*/
public class TelaSobre extends javax.swing.JInternalFrame {
/**
* Creates new form TelaSobre
*/
public TelaSobre() {
initComponents();
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea2 = new javax.swing.JTextArea();
jLabel7 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setBackground(new java.awt.Color(0, 8, 90));
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("SOBRE");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(40, 40, 40)
.addComponent(jLabel1)
.addContainerGap(46, Short.MAX_VALUE))
);
jPanel6.setBackground(new java.awt.Color(255, 255, 255));
jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "EQUIPE", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 24))); // NOI18N
jLabel11.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel11.setText("Vinicius Correia ");
jLabel12.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel12.setText("Jarbas Júnior");
jLabel13.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel13.setText("Emesson Cavalcante ");
jLabel14.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel14.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel14.setText("José Ulisses");
jLabel15.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel15.setText("Guylherme Sales");
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel15, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel11, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel13, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 305, Short.MAX_VALUE)
.addComponent(jLabel14, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(60, 60, 60)
.addComponent(jLabel11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel13, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel15, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(26, 26, 26))
);
jPanel4.setBackground(new java.awt.Color(255, 255, 255));
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "SOFTWARE", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 24))); // NOI18N
jTextArea2.setEditable(false);
jTextArea2.setColumns(20);
jTextArea2.setFont(new java.awt.Font("Ubuntu", 0, 18)); // NOI18N
jTextArea2.setRows(5);
jTextArea2.setText("Nome: Sistema MercoCenter\n\nFunção: Software de gerencia de mercado\n\nVersão: 1.0\n\nFeito por: Equipe TechBooster");
jTextArea2.setWrapStyleWord(true);
jScrollPane2.setViewportView(jTextArea2);
jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/viw/img/logo-mercocenter-128px.png"))); // NOI18N
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 377, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jScrollPane2)
.addGap(18, 18, 18)
.addComponent(jLabel7)
.addContainerGap())
);
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/viw/img/logo-techbooster.png"))); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jLabel6)
.addGap(23, 23, 23)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel6;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea2;
// End of variables declaration//GEN-END:variables
}
| 55.705357 | 226 | 0.689614 |
89c9e84caaea4b4497aabed000bc719ee2064a4c | 443 | package org.infinispan.rest.search;
import org.infinispan.configuration.cache.CacheMode;
import org.testng.annotations.Test;
/**
* @since 12.1
*/
@Test(groups = "functional", testName = "rest.search.SearchCountLocalTest")
public class SearchCountLocalTest extends SearchCountClusteredTest {
@Override
int getMembers() {
return 1;
}
@Override
protected CacheMode getCacheMode() {
return CacheMode.LOCAL;
}
}
| 20.136364 | 75 | 0.722348 |
2a2f7719d0e0e812a7c6c204024a9518f9f49895 | 2,239 | /**
* Copyright Verimag laboratory.
*
* contributors:
* Marc Pouhliès
*
* This software is a computer program whose purpose is to generate
* executable code from BIP models.
*
* This software is governed by the CeCILL-B license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL-B
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-B license and that you accept its terms.
*/
package ujf.verimag.bip.frontend.tests.parser.loader;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import ujf.verimag.bip.parser.loader.PackageLoader;
public class AbstractPackageLoaderTests {
PackageLoader pl;
public void setUp(String rootDirectory) throws Exception {
File f = new File(rootDirectory);
ArrayList<URL> includeDirectories = new ArrayList<URL>();
includeDirectories.add(f.toURI().toURL());
pl = new PackageLoader(includeDirectories.toArray(new URL[0]));
}
}
| 38.603448 | 76 | 0.739616 |
4770b41cc4603094d0693cf0d63edf0acdb1a9c8 | 9,079 | /*
* The MIT License
*
* Copyright 2014 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package cd.go.contrib.plugins.configrepo.groovy.sandbox.whitelists;
import cd.go.contrib.plugins.configrepo.groovy.sandbox.RejectedAccessException;
import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.*;
import static java.util.Arrays.asList;
/**
* Whitelist based on a static file.
*/
public final class StaticWhitelist extends EnumeratingWhitelist {
final List<MethodSignature> methodSignatures = new ArrayList<MethodSignature>();
final List<NewSignature> newSignatures = new ArrayList<NewSignature>();
final List<MethodSignature> staticMethodSignatures = new ArrayList<MethodSignature>();
final List<FieldSignature> fieldSignatures = new ArrayList<FieldSignature>();
final List<FieldSignature> staticFieldSignatures = new ArrayList<FieldSignature>();
public StaticWhitelist(Reader definition) throws IOException {
BufferedReader br = new BufferedReader(definition);
String line;
while ((line = br.readLine()) != null) {
line = filter(line);
if (line != null) {
add(line);
}
}
}
public StaticWhitelist(Collection<? extends String> lines) throws IOException {
for (String line : lines) {
add(line);
}
}
public StaticWhitelist(String... lines) throws IOException {
this(asList(lines));
}
/**
* Filters a line, returning the content that must be processed.
* @param line Line to filter.
* @return {@code null} if the like must be skipped or the content to process if not.
*/
static String filter(String line) {
line = line.trim();
if (line.isEmpty() || line.startsWith("#")) {
return null;
}
return line;
}
static Signature parse(String line) throws IOException {
String[] toks = line.split(" ");
if (toks[0].equals("method")) {
if (toks.length < 3) {
throw new IOException(line);
}
return new MethodSignature(toks[1], toks[2], Arrays.copyOfRange(toks, 3, toks.length));
} else if (toks[0].equals("new")) {
if (toks.length < 2) {
throw new IOException(line);
}
return new NewSignature(toks[1], Arrays.copyOfRange(toks, 2, toks.length));
} else if (toks[0].equals("staticMethod")) {
if (toks.length < 3) {
throw new IOException(line);
}
return new StaticMethodSignature(toks[1], toks[2], Arrays.copyOfRange(toks, 3, toks.length));
} else if (toks[0].equals("field")) {
if (toks.length != 3) {
throw new IOException(line);
}
return new FieldSignature(toks[1], toks[2]);
} else if (toks[0].equals("staticField")) {
if (toks.length != 3) {
throw new IOException(line);
}
return new StaticFieldSignature(toks[1], toks[2]);
} else {
throw new IOException(line);
}
}
private void add(String line) throws IOException {
Signature s = parse(line);
if (s instanceof StaticMethodSignature) {
staticMethodSignatures.add((StaticMethodSignature) s);
} else if (s instanceof MethodSignature) {
methodSignatures.add((MethodSignature) s);
} else if (s instanceof StaticFieldSignature) {
staticFieldSignatures.add((StaticFieldSignature) s);
} else if (s instanceof FieldSignature) {
fieldSignatures.add((FieldSignature) s);
} else {
newSignatures.add((NewSignature) s);
}
}
public static StaticWhitelist from(URL definition) throws IOException {
InputStream is = definition.openStream();
try {
return new StaticWhitelist(new InputStreamReader(is, "UTF-8"));
} finally {
is.close();
}
}
@Override protected List<MethodSignature> methodSignatures() {
return methodSignatures;
}
@Override protected List<NewSignature> newSignatures() {
return newSignatures;
}
@Override protected List<MethodSignature> staticMethodSignatures() {
return staticMethodSignatures;
}
@Override protected List<FieldSignature> fieldSignatures() {
return fieldSignatures;
}
@Override protected List<FieldSignature> staticFieldSignatures() {
return staticFieldSignatures;
}
public static RejectedAccessException rejectMethod(Method m) {
assert (m.getModifiers() & Modifier.STATIC) == 0;
return blacklist(new RejectedAccessException("method", EnumeratingWhitelist.getName(m.getDeclaringClass()) + " " + m.getName() + printArgumentTypes(m.getParameterTypes())));
}
public static RejectedAccessException rejectMethod(Method m, String info) {
assert (m.getModifiers() & Modifier.STATIC) == 0;
return blacklist(new RejectedAccessException("method", EnumeratingWhitelist.getName(m.getDeclaringClass()) + " " + m.getName() + printArgumentTypes(m.getParameterTypes()), info));
}
public static RejectedAccessException rejectNew(Constructor<?> c) {
return blacklist(new RejectedAccessException("new", EnumeratingWhitelist.getName(c.getDeclaringClass()) + printArgumentTypes(c.getParameterTypes())));
}
public static RejectedAccessException rejectStaticMethod(Method m) {
assert (m.getModifiers() & Modifier.STATIC) != 0;
return blacklist(new RejectedAccessException("staticMethod", EnumeratingWhitelist.getName(m.getDeclaringClass()) + " " + m.getName() + printArgumentTypes(m.getParameterTypes())));
}
public static RejectedAccessException rejectField(Field f) {
assert (f.getModifiers() & Modifier.STATIC) == 0;
return blacklist(new RejectedAccessException("field", EnumeratingWhitelist.getName(f.getDeclaringClass()) + " " + f.getName()));
}
public static RejectedAccessException rejectStaticField(Field f) {
assert (f.getModifiers() & Modifier.STATIC) != 0;
return blacklist(new RejectedAccessException("staticField", EnumeratingWhitelist.getName(f.getDeclaringClass()) + " " + f.getName()));
}
private static String printArgumentTypes(Class<?>[] parameterTypes) {
StringBuilder b = new StringBuilder();
for (Class<?> c : parameterTypes) {
b.append(' ');
b.append(EnumeratingWhitelist.getName(c));
}
return b.toString();
}
private static final Set<String> BLACKLIST;
private static Set<String> loadBlacklist() throws IOException {
InputStream is = StaticWhitelist.class.getResourceAsStream("blacklist");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is, "US-ASCII"));
Set<String> blacklist = new HashSet<String>();
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.isEmpty() || line.startsWith("#")) {
continue;
}
// TODO could consider trying to load the AccessibleObject, assuming the defining Class is accessible, as a defense against typos
blacklist.add(line);
}
return blacklist;
} finally {
is.close();
}
}
static {
try {
BLACKLIST = loadBlacklist();
} catch (IOException x) {
throw new ExceptionInInitializerError(x);
}
}
private static RejectedAccessException blacklist(RejectedAccessException x) {
if (BLACKLIST.contains(x.getSignature())) {
x.setDangerous(true);
}
return x;
}
}
| 38.470339 | 187 | 0.642582 |
43b8bce73edfbb505a12906ac5cb2d1bb2b6f78f | 1,086 | package com.chizganov.puzzlers.leetcode.may;
import com.chizganov.puzzlers.util.TestSource;
import org.junit.jupiter.params.ParameterizedTest;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Path;
import static java.lang.Integer.parseInt;
import static java.nio.file.Files.newBufferedReader;
import static org.junit.jupiter.api.Assertions.assertEquals;
class JewelsAndStonesTest {
@ParameterizedTest
@TestSource(JewelsAndStones.class)
void numJewelsInStones(JewelsAndStones solution, Path input, Path output) throws IOException {
try (BufferedReader in = newBufferedReader(input);
BufferedReader out = newBufferedReader(output)) {
String jewels = in.readLine();
String stones = in.readLine();
int expectedResult = parseInt(out.readLine());
int actualResult = solution.numJewelsInStones(jewels, stones);
assertEquals(expectedResult, actualResult,
String.format("Input: jewels \"%s\", stones \"%s\"", jewels, stones));
}
}
} | 35.032258 | 98 | 0.708103 |
83359cc0c9bd3d20dda4664f4ded642772a76480 | 224 | package org.prebid.server.bidder.rubicon.proto;
import lombok.AllArgsConstructor;
import lombok.Value;
@AllArgsConstructor(staticName = "of")
@Value
public class RubiconExtPrebidBiddersBidder {
String integration;
}
| 17.230769 | 47 | 0.799107 |
1e6c0d1aa08b544269e6e2edbb225ad9c72a8948 | 357 | package team.yingyingmonster.ccbs.database.mapper;
import team.yingyingmonster.ccbs.database.bean.Menu;
import java.util.List;
public interface MenuMapper {
Menu selectByPrimaryKey(Long menuid);
int deleteByPrimaryKey(Long menuid);
int insert(Menu menu);
int insertSelective(Menu menus);
int updateByPrimaryKeySelective(Menu menu);
}
| 25.5 | 52 | 0.77591 |
cf788ae3d905d0790b41b9681ed35b22db62b288 | 977 | package org.openxsp;
import org.openxsp.java.Verticle;
import org.vertx.java.core.Handler;
import org.vertx.java.core.eventbus.Message;
public class DefaultVerticle extends Verticle{
@Override
public void start() {
super.start();
System.out.println("Starting "+DefaultVerticle.class.getSimpleName());
System.out.println("Configuration is: "+container.config());
//TODO
// registerEvents();
//TODO
// sendEvents();
//TODO open connections
//TODO implement business logic
container.logger().debug("Verticle started");
}
private void registerEvents(){
openxsp.eventBus().registerHandler("MyEventAddress", new Handler<Message<String>>() {
@Override
public void handle(Message<String> msg) {
container.logger().debug("Received event");
String message = msg.body();
//TODO process the message
}
});
}
private void sendEvents(){
openxsp.eventBus().send("RemoteAddress", "Hello World");
}
}
| 19.54 | 87 | 0.684749 |
1d2a7bff684fa3a4773d1bac89e5278f59a403ce | 2,203 | /*
* 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.
*
* Other licenses:
* -----------------------------------------------------------------------------
* Commercial licenses for this work are available. These replace the above
* ASL 2.0 and offer limited warranties, support, maintenance, and commercial
* database integrations.
*
* For more information, please visit: http://www.jooq.org/licenses
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package org.jooq;
import org.jetbrains.annotations.NotNull;
import org.jooq.impl.DefaultVisitListenerProvider;
/**
* A provider for {@link VisitListener} instances.
*
* <p>In order to facilitate the lifecycle management of <code>VisitListener</code> instances that
* are provided to a jOOQ {@link Configuration}, clients can implement this API. To jOOQ, it is thus
* irrelevant, if execute listeners are stateful or stateless, local to a single record or record
* manipulation, or global to an application.
*
* @author Lukas Eder
* @see VisitListener
* @see Configuration
*/
@FunctionalInterface
public interface VisitListenerProvider {
/**
* Provide a <code>VisitListener</code> instance.
*
* <p>Implementations are free to choose whether this method returns new instances at every call
* or whether the same instance is returned repetitively.
*
* <p>A <code>VisitListener</code> shall be provided exactly once per <code>Context</code>
* traversal, i.e. per <code>RenderContext</code> or <code>BindContext</code>.
*
* @return A <code>VisitListener</code> instance.
* @see VisitListener
* @see VisitContext
* @see DefaultVisitListenerProvider
*/
@NotNull
VisitListener provide();
}
| 29.373333 | 100 | 0.695415 |
6ecb6f1cb37f6f9fec277c4c26c67acaaec698d5 | 74 | package com.tiagojesus.dev.feigh.rest.client;
interface System02API {
}
| 12.333333 | 45 | 0.783784 |
529c6b8b2bdde28c714177592163d18413be78c6 | 257 | package dev.hotdeals.treecreate.repository;
import dev.hotdeals.treecreate.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepo extends JpaRepository<User, Integer>
{
User findOneByEmail(String email);
}
| 25.7 | 62 | 0.821012 |
7995277bffea0b037f7af7b37bac27faa6995dfe | 8,140 | /**
* Copyright 2012 meltmedia
*
* 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.meltmedia.cadmium.servlets;
import com.meltmedia.cadmium.core.ContentService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.CharSequenceInputStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
/**
* Tests the selection of the proper error page by the ErrorPageFilter servlet.
*
* @author Christian Trimble
*/
@RunWith(Parameterized.class)
public class ErrorPageFilterSelectionTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ sendErrorFilterChain(404), "patient/404", "/patient/blah" },
{ sendErrorFilterChain(407), "40x", "/hcp/ehh" },
{ sendErrorFilterChain(412), "patient/4xx", "/patient/blah/ehh"},
{ sendErrorFilterChain(501), "501", "/" },
{ sendErrorFilterChain(502), "50x", "/" },
{ sendErrorFilterChain(510), "5xx", "/" },
{ throwExceptionFilterChain(new Exception("Oops!")), "50x", "/"},
{ successFilterChain("Success"), "Success", "/"} });
}
/**
* Creates a filter chain that calls sendError(int) with the specified status code.
*
* @param statusCode the status code to send.
* @return a filter chain that simulates a sendError condition.
*/
public static FilterChain sendErrorFilterChain( final int statusCode ) {
return new FilterChain() {
@Override
public void doFilter(ServletRequest req, ServletResponse res)
throws IOException, ServletException {
((HttpServletResponse)res).sendError(statusCode);
}
};
}
/**
* Creates a filter chain that throws a ServletException with the specified cause.
* @param cause the cause of the exception that will be thrown.
* @return a filter chain that simulates an exception.
*/
public static FilterChain throwExceptionFilterChain( final Throwable cause ) {
return new FilterChain() {
@Override
public void doFilter(ServletRequest req, ServletResponse res)
throws IOException, ServletException {
throw new ServletException(cause);
}
};
}
/**
* Creates a filter chain that sends a 200 response.
*
* @param content the content to write to the res object.
* @return a filter chain that simulates a 200 response.
*/
public static FilterChain successFilterChain( final String content ) {
return new FilterChain() {
@Override
public void doFilter(ServletRequest req, ServletResponse res)
throws IOException, ServletException {
HttpServletResponse httpRes = (HttpServletResponse)res;
httpRes.setStatus(200);
OutputStream out = null;
InputStream in = null;
try {
out = res.getOutputStream();
in = new ByteArrayInputStream(content.getBytes());
IOUtils.copy(in, out);
}
finally {
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(in);
}
}
};
}
/**
* The filter chain to execute inside the filter.
*/
private FilterChain chain;
/**
* The content we expect to be written to the response writer.
*/
private String expectedContent;
/**
* The filter that will be tested.
*/
private ErrorPageFilter filter;
/**
* The path info for the simulated request.
*/
private String pathInfo;
/**
* Creates a new test object from the parameters.
*
* @param chain the chain that will be called in the filter.
* @param expectedContent the expected content on the response writer.
* @param pathInfo The path info for a simulated request.
*/
public ErrorPageFilterSelectionTest( FilterChain chain, String expectedContent, String pathInfo ) {
this.chain = chain;
this.expectedContent = expectedContent;
this.pathInfo = pathInfo;
}
/**
* Mock up the content service for the error pages and create the filter.
*
* @throws ServletException if there is a problem initializing the filter.
* @throws IOException if there is a problem mocking the content service.
*/
@Before
public void beforeTest() throws IOException, ServletException {
ContentService contentService = mock(ContentService.class);
when(contentService.getResourceAsStream(startsWith("/hcp"))).thenReturn(null);
when(contentService.getResourceAsStream(startsWith("/patient/blah"))).thenReturn(null);
when(contentService.getResourceAsStream("/404.html")).thenReturn(new CharSequenceInputStream("404", "UTF-8"));
when(contentService.getResourceAsStream("/patient/404.html")).thenReturn(new CharSequenceInputStream("patient/404", "UTF-8"));
when(contentService.getResourceAsStream("/patient/4xx.html")).thenReturn(new CharSequenceInputStream("patient/4xx", "UTF-8"));
when(contentService.getResourceAsStream("/407.html")).thenReturn(null);
when(contentService.getResourceAsStream("/412.html")).thenReturn(null);
when(contentService.getResourceAsStream("/40x.html")).thenReturn(new CharSequenceInputStream("40x", "UTF-8"));
when(contentService.getResourceAsStream("/41x.html")).thenReturn(null);
when(contentService.getResourceAsStream("/4xx.html")).thenReturn(new CharSequenceInputStream("4xx", "UTF-8"));
when(contentService.getResourceAsStream("/501.html")).thenReturn(new CharSequenceInputStream("501", "UTF-8"));
when(contentService.getResourceAsStream("/502.html")).thenReturn(null);
when(contentService.getResourceAsStream("/510.html")).thenReturn(null);
when(contentService.getResourceAsStream("/50x.html")).thenReturn(new CharSequenceInputStream("50x", "UTF-8"));
when(contentService.getResourceAsStream("/51x.html")).thenReturn(null);
when(contentService.getResourceAsStream("/5xx.html")).thenReturn(new CharSequenceInputStream("5xx", "UTF-8"));
filter = new ErrorPageFilter();
filter.setContentService(contentService);
filter.init(mock(FilterConfig.class));
}
/**
* Clean up the filter that was tested.
*/
@After
public void afterTest() {
filter.destroy();
}
/**
* Calls doFilter on the ErrorPageFilter, capturing the output. The output is compared to the expected output.
*
* @throws IOException if there is an error in the test.
* @throws ServletException if there is an error in the test.
*/
@Test
public void testFilterChainError() throws IOException, ServletException {
final ByteArrayOutputStream resultWriter = new ByteArrayOutputStream();
// Return the result writer for output.
HttpServletResponse response = mock(HttpServletResponse.class);
when(response.getOutputStream()).thenReturn(new ServletOutputStream() {
@Override
public void write(int i) throws IOException {
resultWriter.write(i);
}
});
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURI()).thenReturn(pathInfo);
// act
filter.doFilter(request, response, chain);
// assert
assertEquals("The wrong error content was returned.", expectedContent, resultWriter.toString());
}
}
| 37.16895 | 130 | 0.700614 |
a5eb2bcb0a9b14fc0f319b32f8a2b4c8b0e6c598 | 8,427 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.extensions.markup.html.form.select;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.model.IModel;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.lang.Objects;
import org.apache.wicket.util.string.Strings;
import org.apache.wicket.util.visit.IVisit;
import org.apache.wicket.util.visit.IVisitor;
/**
* Component that represents a <code><select></code> box. Elements are provided by one or more
* <code>SelectOptions</code> components in the hierarchy below the <code>Select</code> component.
*
* Advantages to the standard choice components is that the user has a lot more control over the
* markup between the <select> tag and its children <option> tags: allowing for such
* things as <optgroup> tags.
*
* <p>
* Example HTML:
*
* <pre>
* <select wicket:id="select" multiple="multiple">
* <wicket:container wicket:id="options">
* <option wicket:id="option">Option Label</option>
* </wicket:container>
* </select>
* </pre>
*
* Related Java Code:
*
* <pre>
* Select select = new Select("select", selectionModel);
* add(select);
* SelectOptions options = new SelectOptions("options", elements, renderer);
* select.add(options);
* </pre>
*
* Note that you don't need to add component(s) for the <option> tag - they are created by
* SelectOptions
* </p>
* <p>
* <strong>Note</strong>: due to the usage of a SelectOption for each <option> the memory
* footprint of the page will grow with the number of <option>s you need. Consider using
* {@link org.apache.wicket.markup.html.form.DropDownChoice} component if it is able to fulfill your
* requirements.
* </p>
*
* @see SelectOption
* @see SelectOptions
* @see org.apache.wicket.markup.html.form.DropDownChoice
*
* @author Igor Vaynberg
* @param <T>
*/
public class Select<T> extends FormComponent<T>
{
private static final long serialVersionUID = 1L;
/**
* Constructor that will create a default model collection
*
* @param id
* component id
*/
public Select(final String id)
{
super(id);
}
/**
* @param id
* @param model
* @see WebMarkupContainer#WebMarkupContainer(String, IModel)
*/
public Select(final String id, final IModel<T> model)
{
super(id, model);
}
@Override
protected String getModelValue()
{
final StringBuilder builder = new StringBuilder();
visitChildren(SelectOption.class, new IVisitor<SelectOption<T>, Void>()
{
@Override
public void component(SelectOption<T> option, IVisit<Void> visit)
{
if (isSelected(option.getDefaultModel()))
{
if (builder.length() > 0)
{
builder.append(VALUE_SEPARATOR);
}
builder.append(option.getValue());
}
}
});
return builder.toString();
}
@Override
public void convertInput()
{
boolean supportsMultiple = getModelObject() instanceof Collection;
/*
* + * the input contains an array of values of the selected option components unless
* nothing was selected in which case the input contains null
*/
String[] values = getInputAsArray();
if ((values == null) || (values.length == 0))
{
setConvertedInput(null);
return;
}
if (!supportsMultiple && (values.length > 1))
{
throw new WicketRuntimeException(
"The model of Select component [" +
getPath() +
"] is not of type java.util.Collection, but more then one SelectOption component has been selected. Either remove the multiple attribute from the select tag or make the model of the Select component a collection");
}
List<Object> converted = new ArrayList<>(values.length);
/*
* if the input is null we do not need to do anything since the model collection has already
* been cleared
*/
for (int i = 0; i < values.length; i++)
{
final String value = values[i];
if (!Strings.isEmpty(value))
{
SelectOption<T> option = visitChildren(SelectOption.class,
new IVisitor<SelectOption<T>, SelectOption<T>>()
{
@Override
public void component(SelectOption<T> option, IVisit<SelectOption<T>> visit)
{
if (String.valueOf(option.getValue()).equals(value))
{
visit.stop(option);
}
}
});
if (option == null)
{
throw new WicketRuntimeException(
"submitted http post value [" +
Arrays.toString(values) +
"] for SelectOption component [" +
getPath() +
"] contains an illegal value [" +
value +
"] which does not point to a SelectOption component. Due to this the Select component cannot resolve the selected SelectOption component pointed to by the illegal value. A possible reason is that component hierarchy changed between rendering and form submission.");
}
converted.add(option.getDefaultModelObject());
}
}
if (converted.isEmpty())
{
setConvertedInput(null);
}
else if (!supportsMultiple)
{
@SuppressWarnings("unchecked")
T convertedInput = (T)converted.get(0);
setConvertedInput(convertedInput);
}
else
{
@SuppressWarnings("unchecked")
T convertedInput = (T)converted;
setConvertedInput(convertedInput);
}
}
/**
* @see FormComponent#updateModel()
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void updateModel()
{
T object = getModelObject();
boolean supportsMultiple = object instanceof Collection;
Object converted = getConvertedInput();
/*
* update the model
*/
if (supportsMultiple)
{
Collection<?> modelCollection = (Collection<?>)object;
modelChanging();
modelCollection.clear();
if (converted != null)
{
modelCollection.addAll((Collection)converted);
}
modelChanged();
// force notify of model update via setObject()
setDefaultModelObject(modelCollection);
}
else
{
setDefaultModelObject(converted);
}
}
/**
* Checks if the specified option is selected based on raw input
*
* @param option
* @return {@code true} if the option is selected, {@code false} otherwise
*/
boolean isSelected(final SelectOption<?> option)
{
Args.notNull(option, "option");
// if the raw input is specified use that, otherwise use model
if (hasRawInput())
{
final String raw = getRawInput();
if (!Strings.isEmpty(raw))
{
String[] values = raw.split(VALUE_SEPARATOR);
for (int i = 0; i < values.length; i++)
{
String value = values[i];
if (value.equals(option.getValue()))
{
return true;
}
}
}
return false;
}
return isSelected(option.getDefaultModel());
}
/**
* Does the given model contain a selected value.
*
* @param model
* model to test on selection
* @return selected
*/
protected boolean isSelected(IModel<?> model)
{
return compareModels(getDefaultModelObject(), model.getObject());
}
private boolean compareModels(final Object selected, final Object value)
{
if ((selected != null) && (selected instanceof Collection))
{
if (value instanceof Collection)
{
return ((Collection<?>)selected).containsAll((Collection<?>)value);
}
else
{
return ((Collection<?>)selected).contains(value);
}
}
else
{
return Objects.equal(selected, value);
}
}
}
| 27.36039 | 272 | 0.681619 |
79655ff893103c74bfc9aa6200da8f65d12e507e | 5,527 | package dmo.fs.router;
import java.io.IOException;
import java.sql.SQLException;
import com.google.cloud.firestore.Firestore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import dmo.fs.utils.ColorUtilConstants;
import dmo.fs.utils.DodexUtil;
import io.vertx.core.http.HttpMethod;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.core.http.HttpServer;
import io.vertx.reactivex.core.http.HttpServerResponse;
import io.vertx.reactivex.ext.web.Route;
import io.vertx.reactivex.ext.web.Router;
import io.vertx.reactivex.ext.web.handler.CorsHandler;
import io.vertx.reactivex.ext.web.handler.FaviconHandler;
import io.vertx.reactivex.ext.web.handler.StaticHandler;
import io.vertx.reactivex.ext.web.handler.TimeoutHandler;
import io.vertx.reactivex.ext.web.sstore.LocalSessionStore;
import io.vertx.reactivex.ext.web.sstore.SessionStore;
public class Routes {
private static final Logger logger = LoggerFactory.getLogger(Routes.class.getName());
protected Vertx vertx;
protected Router router;
protected HttpServer server;
protected SessionStore sessionStore;
Integer counter = 0;
Firestore firestore;
public Routes(Vertx vertx, HttpServer server, Integer vertxVersion) throws InterruptedException, IOException, SQLException {
this.vertx = vertx;
router = Router.router(vertx);
sessionStore = LocalSessionStore.create(vertx);
this.server = server;
String value = System.getenv("VERTXWEB_ENVIRONMENT");
if (value != null && (value.equals("dev") || value.equals("test"))) {
DodexUtil.setEnv("dev");
} else {
DodexUtil.setEnv("prod");
}
DodexUtil.setVertx(vertx);
setFavRoute();
setStaticRoute();
setDodexRoute();
if ("dev".equals(DodexUtil.getEnv())) {
setTestRoute();
} else {
setProdRoute();
}
}
public void setTestRoute() {
Route route = router.routeWithRegex(HttpMethod.GET, "/test/[\\w/-]*\\.html|/test[/]?");
route.handler(routingContext -> {
routingContext.put("name", "test");
HttpServerResponse response = routingContext.response();
response.putHeader("content-type", "text/html");
int length = routingContext.request().path().length();
String path = routingContext.request().path();
String file = length < 7 ? "test/index.html" : path.substring(1);
response.sendFile(file);
});
route.failureHandler(ctx ->
logger.error(String.format("%sFAILURE in /test/ route: %d%s", ColorUtilConstants.RED_BOLD_BRIGHT, ctx.statusCode(), ColorUtilConstants.RESET))
);
}
public void setProdRoute() {
Route route = router.routeWithRegex(HttpMethod.GET, "/dodex[/]?|/dodex/.*\\.html");
route.handler(routingContext -> {
routingContext.put("name", "prod");
HttpServerResponse response = routingContext.response();
response.putHeader("content-type", "text/html");
int length = routingContext.request().path().length();
String path = routingContext.request().path();
String file = length < 8 ? "dodex/index.html" : path.substring(1);
response.sendFile(file);
});
route.failureHandler(ctx ->
logger.error(String.format("%sFAILURE in prod/dodex route: %d%s", ColorUtilConstants.RED_BOLD_BRIGHT, ctx.statusCode(), ColorUtilConstants.RESET))
);
}
public void setStaticRoute() {
StaticHandler staticHandler = StaticHandler.create();
staticHandler.setWebRoot("static");
staticHandler.setCachingEnabled(false);
router.routeWithRegex("/.*\\.md|" + "/.*/templates/.*")
.produces("text/plain")
.produces("text/markdown")
.handler(ctx -> {
HttpServerResponse response = ctx.response();
String acceptableContentType = ctx.getAcceptableContentType();
response.putHeader("content-type", acceptableContentType);
response.sendFile(ctx.normalizedPath());
staticHandler.handle(ctx);
});
Route staticRoute = router.route("/*").handler(TimeoutHandler.create(2000));
if ("dev".equals(DodexUtil.getEnv())) {
staticRoute.handler(CorsHandler.create("*" /* Need ports 8087 & 9876 */ ).allowedMethod(HttpMethod.GET));
}
staticRoute.handler(staticHandler);
staticRoute.failureHandler(ctx ->
logger.error(String.format("%sFAILURE in static route: %d%s", ColorUtilConstants.RED_BOLD_BRIGHT, ctx.statusCode(), ColorUtilConstants.RESET))
);
}
public void setFavRoute() {
FaviconHandler faviconHandler = null;
faviconHandler = FaviconHandler.create(vertx);
router.route().handler(faviconHandler);
}
public void setDodexRoute() throws InterruptedException, IOException, SQLException {
DodexUtil du = new DodexUtil();
String defaultDbName = du.getDefaultDb();
if ("firebase".equals(defaultDbName)) {
try {
FirebaseRouter firebaseRouter = new FirebaseRouter(vertx);
firebaseRouter.setWebSocket(server);
firestore = firebaseRouter.getDbf();
} catch(Exception ex) {
ex.printStackTrace();
throw ex;
}
} else if ("cassandra".equals(defaultDbName)) {
try {
CassandraRouter cassandraRouter = new CassandraRouter(vertx);
cassandraRouter.setWebSocket(server);
} catch(Exception ex) {
ex.printStackTrace();
throw ex;
}
} else {
try {
DodexRouter dodexRouter = new DodexRouter(vertx);
dodexRouter.setWebSocket(server);
} catch(Exception ex) {
ex.printStackTrace();
throw ex;
}
}
}
public Router getRouter() {
return router;
}
public Firestore getFirestore() {
return firestore;
}
}
| 32.321637 | 149 | 0.702732 |
21948595a188ba7755b4f9df406771b57bddb80a | 1,657 | package tv.twitch.hwsnemo.autoreply.cmd;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.pircbotx.hooks.events.MessageEvent;
import tv.twitch.hwsnemo.autoreply.Chat;
import tv.twitch.hwsnemo.autoreply.ChatLevel;
import tv.twitch.hwsnemo.autoreply.MainConfig;
public class ChatCmdInfo extends CmdInfo {
private final MessageEvent event;
public ChatCmdInfo(String[] sp, MessageEvent event) {
super(sp);
this.event = event;
}
@Override
public boolean chkPut(ChatLevel lvl, String maincmd, String... ailas) {
return checkPut(getCmd(), event, lvl, maincmd, ailas);
}
@Override
public String getSender() {
return event.getUser().getNick();
}
private static final Map<String, Long> lastcmd = new ConcurrentHashMap<>();
private static boolean checkPut(String input, MessageEvent event, ChatLevel lvl, String maincmd, String... cmd) {
boolean right = maincmd.equalsIgnoreCase(input);
if (!right) {
for (String c : cmd) {
if (c.equalsIgnoreCase(input)) {
right = true;
break;
}
}
}
if (right && (!isUsedRecently(maincmd) || ChatLevel.MOD.check(event)) && lvl.check(event)) {
lastcmd.put(maincmd, System.currentTimeMillis());
return true;
}
return false;
}
private static long cooldown = MainConfig.getLong("cmdcooldown", 3000);
private static boolean isUsedRecently(String cmd) {
if (lastcmd.containsKey(cmd)) {
long diff = System.currentTimeMillis() - lastcmd.get(cmd);
return diff < cooldown;
}
return false;
}
@Override
public void send(String msg) {
Chat.send(msg);
}
}
| 25.492308 | 115 | 0.686783 |
7277ead14cfc27de74eccf1cd7b3d88bb42d95fa | 3,242 | package io.thestencil.site.handlers;
import java.io.IOException;
import java.util.Collections;
/*-
* #%L
* quarkus-stencil-sc
* %%
* Copyright (C) 2021 Copyright 2021 ReSys OÜ
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import io.quarkus.security.identity.CurrentIdentityAssociation;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import io.quarkus.vertx.web.Route.HttpMethod;
import io.smallrye.mutiny.Uni;
import io.thestencil.client.web.HandlerStatusCodes;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.RoutingContext;
public class SiteHandler extends HdesResourceHandler {
public SiteHandler(
CurrentIdentityAssociation currentIdentityAssociation,
CurrentVertxRequest currentVertxRequest) {
super(currentIdentityAssociation, currentVertxRequest);
}
@Override
protected void handleResource(RoutingContext event, HttpServerResponse response, SiteHandlerContext ctx) {
final var client = ctx.getClient();
switch (HttpMethod.valueOf(event.request().method().name())) {
case GET:
String locale = event.request().getParam("locale");
client.query().head()
.onItem().transform(state -> ctx.getContent().markdown().json(state).build())
.onItem().transform(markdowns -> ctx.getContent().sites().imagePath("images").created(System.currentTimeMillis()).source(markdowns).build())
.onItem().transform(sites -> sites.getSites().get(locale))
.onItem().transform(data -> {
try {
if(data == null) {
return Buffer.buffer(ctx.getObjectMapper().writeValueAsBytes(Collections.emptyMap()));
}
return Buffer.buffer(ctx.getObjectMapper().writeValueAsBytes(data));
} catch(IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
})
.onFailure().invoke(e -> HandlerStatusCodes.catch422(e, response))
.subscribe().with(data -> {
response.headers().set(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
response.end(data);
});
break;
default:
HandlerStatusCodes.catch404("no-supported", response);
break;
}
}
public <T> void subscribe(Uni<T> uni, HttpServerResponse response, SiteHandlerContext ctx) {
uni.onItem().transform(data -> {
try {
return Buffer.buffer(ctx.getObjectMapper().writeValueAsBytes(data));
} catch(IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
})
.onFailure().invoke(e -> HandlerStatusCodes.catch422(e, response))
.subscribe().with(data -> response.end(data));
}
}
| 36.022222 | 146 | 0.69525 |
3d9c13309ad89000c667280fa0017691301524da | 297 | package com.gxitsky.creational.builder.familybarrel;
public class Director {
public void construct(Builder builder) {
builder.buildCocaCola();
builder.buildDrumstick();
builder.buildFrenchFires();
builder.buildHamburger();
builder.buildPie();
}
}
| 22.846154 | 52 | 0.666667 |
b81ab7a20534396e797a4b9611669c8757a1d8cc | 1,470 | package local.tin.tests.jpa.workshop.model.data.product;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import local.tin.tests.jpa.workshop.model.data.abstracts.AbstractNamed;
/**
*
* @author benito.darder
*/
@Entity
@Table(name = "PRODUCT")
public class Product extends AbstractNamed {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "description")
private String description;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "product")
private Set<Assembly> assemblies;
@Override
public Integer getId() {
return id;
}
@Override
public void setId(Object id) {
this.id = (Integer) id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<Assembly> getAssemblies() {
if (assemblies == null) {
assemblies = new HashSet<>();
}
return assemblies;
}
public void setAssemblies(Set<Assembly> assemblies) {
this.assemblies = assemblies;
}
}
| 23.333333 | 71 | 0.67619 |
019304e20dc136cc9d9a0851d8b4c509381d4aae | 243 | package com.macbury.fabula.persister;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
@Root(name="foliage")
public class FoliagePersister {
@Element
public float speed;
@Element
public float amplitude;
}
| 18.692308 | 39 | 0.777778 |
508f44212c382db9aa9af90943980c44e1b3fa3d | 1,330 | package com.d8games.web.services.controller;
import com.d8games.web.services.model.entity.Title;
import com.d8games.web.services.service.DepartmentService;
import com.d8games.web.services.service.TitleService;
import com.d8games.web.services.service.JobInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/services/controller/title")
public class TitleController {
@Autowired
private TitleService titleService;
@Autowired
private JobInfoService jobInfoService;
@Autowired
private DepartmentService departmentService;
@GetMapping
public List<Title> getAll() {
return titleService.getAll();
}
@GetMapping(value = "/get")
public Title getById(@RequestParam String id) {
return titleService.getById(id);
}
@PutMapping(value = "/save")
public String save(@RequestParam String name, @RequestParam String jobInfoId, @RequestParam String departmentId) {
Title title = new Title();
title.setName(name);
title.setJobInfo(jobInfoService.getById(jobInfoId));
title.setDepartment(departmentService.getById(departmentId));
titleService.save(title);
return title.getId();
}
}
| 28.297872 | 118 | 0.733835 |
e5d9cdf69d14ed91b2a62819567df8a614bf1d87 | 1,223 | package com.czh.httpd.header;
import com.czh.httpd.constant.CommonConstants;
import com.czh.httpd.enums.HttpStatus;
/**
* @author czh
*/
public class SimpleResponseHeader extends BaseResponseHeader {
public SimpleResponseHeader() {
}
public SimpleResponseHeader(String responseHeaderString) {
super(responseHeaderString);
}
@Override
public void setFirstLine(String line) throws IllegalArgumentException {
String[] statusLineArray = line.split(CommonConstants.Symbol.SPACE);
int statusLineLength = statusLineArray.length;
if (statusLineLength != 3) {
throw new IllegalArgumentException("相应状态行格式错误, " + line);
}
this.httpVersion = statusLineArray[0];
this.httpStatus = HttpStatus.valueOf(Integer.parseInt(statusLineArray[1]));
// this.httpStatus = statusLineArray[1];
// this.statusName = statusLineArray[2];
}
@Override
public String getFirstLine() {
return this.httpVersion + CommonConstants.Symbol.SPACE + this.httpStatus.value() + CommonConstants.Symbol.SPACE + this.httpStatus.getReasonPhrase();
}
@Override
public String toString() {
return this.build();
}
}
| 29.829268 | 156 | 0.689289 |
bb9d74c5693a659c3f2bf1eba67ed1ab31c0c101 | 1,436 | package org.dmfs.express.json.decorators;
import org.dmfs.express.json.JsonSink;
import org.dmfs.express.json.JsonValue;
import org.dmfs.express.json.elementary.Boolean;
import org.dmfs.express.json.elementary.Null;
import org.dmfs.express.json.elementary.Number;
import org.dmfs.express.json.elementary.String;
import org.dmfs.jems2.Optional;
import org.dmfs.jems2.Single;
import org.dmfs.jems2.optional.Mapped;
import org.dmfs.jems2.optional.NullSafe;
import org.dmfs.jems2.single.Backed;
import java.io.IOException;
/**
* A {@link JsonValue} value which can be {@code null}.
*
* @author Marten Gajda
*/
public final class Nullable implements JsonValue
{
private final Single<JsonValue> mDelegate;
public Nullable(CharSequence string)
{
this(new Mapped<>(String::new, new NullSafe<>(string)));
}
public Nullable(java.lang.Number number)
{
this(new Mapped<>(Number::new, new NullSafe<>(number)));
}
public Nullable(java.lang.Boolean bool)
{
this(new Mapped<>(Boolean::new, new NullSafe<>(bool)));
}
public Nullable(JsonValue jsonValue)
{
this(new NullSafe<>(jsonValue));
}
private Nullable(Optional<JsonValue> delegate)
{
mDelegate = new Backed<>(delegate, new Null());
}
@Override
public void serialize(JsonSink jsonSink) throws IOException
{
mDelegate.value().serialize(jsonSink);
}
}
| 22.4375 | 64 | 0.693593 |
eb274d7f99640e90c9f4c866acd23b38ff021df3 | 123 | package org.qi4j.library.appbrowser;
public interface FormatterFactory
{
Formatter create( String componentType );
}
| 15.375 | 45 | 0.780488 |
ec5df5b4a09ae309972aab77f8dba21da86d4bba | 655 | package com.leetcode_restart;
public class SearchInsertPosition {
public int searchInsert(int[] nums, int target) {
if (target < nums[0]) return 0;
if (target > nums[nums.length - 1]) return nums.length;
int l = 0;
int r = nums.length - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (target == nums[mid] || target < nums[mid] && mid > 0 && target > nums[mid - 1]) {
return mid;
}
if (target > nums[mid]) {
l = mid + 1;
} else {
r = mid - 1;
}
}
return -1;
}
}
| 22.586207 | 97 | 0.429008 |
46ad088fc89f5c30af8a025f81b9c255735aa3da | 3,273 | /*
* Copyright 2006-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.springframework.osgi.internal.service.collection;
import java.util.Comparator;
import java.util.Dictionary;
import java.util.Properties;
import junit.framework.TestCase;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.springframework.osgi.mock.MockServiceReference;
import org.springframework.osgi.service.importer.support.internal.util.ServiceReferenceComparator;
/**
* @author Costin Leau
*
*/
public class ServiceReferenceComparatorTest extends TestCase {
private Comparator comparator;
protected void setUp() throws Exception {
comparator = new ServiceReferenceComparator();
}
protected void tearDown() throws Exception {
comparator = null;
}
public void testServiceRefsWithTheSameId() throws Exception {
ServiceReference refA = createReference(new Long(1), null);
ServiceReference refB = createReference(new Long(1), null);
// refA is higher then refB
assertEquals(0, comparator.compare(refA, refB));
}
public void testServiceRefsWithDifferentIdAndNoRanking() throws Exception {
ServiceReference refA = createReference(new Long(1), null);
ServiceReference refB = createReference(new Long(2), null);
// refA is higher then refB
// default ranking is equal
assertTrue(comparator.compare(refA, refB) > 0);
}
public void testServiceRefsWithDifferentIdAndDifferentRanking() throws Exception {
ServiceReference refA = createReference(new Long(1), new Integer(0));
ServiceReference refB = createReference(new Long(2), new Integer(1));
// refB is higher then refA (due to ranking)
assertTrue(comparator.compare(refA, refB) < 0);
}
public void testServiceRefsWithSameRankAndDifId() throws Exception {
ServiceReference refA = createReference(new Long(1), new Integer(5));
ServiceReference refB = createReference(new Long(2), new Integer(5));
// same ranking, means id equality applies
assertTrue(comparator.compare(refA, refB) > 0);
}
public void testNullObjects() throws Exception {
assertEquals(0, comparator.compare(null, null));
}
public void testNonNullWithNull() throws Exception {
try {
comparator.compare(new MockServiceReference(), null);
fail("should have thrown exception");
}
catch (ClassCastException cce) {
}
}
private ServiceReference createReference(Long id, Integer ranking) {
Dictionary dict = new Properties();
dict.put(Constants.SERVICE_ID, id);
if (ranking != null)
dict.put(Constants.SERVICE_RANKING, ranking);
return new MockServiceReference(null, dict, null);
}
}
| 32.088235 | 99 | 0.733883 |
19f810a70597f5e409839a406760cac41c1cb44f | 8,613 | /**************************************************************************
* Copyright (c) 2001 by Acunia N.V. All rights reserved. *
* *
* This software is copyrighted by and is the sole property of Acunia N.V. *
* and its licensors, if any. All rights, title, ownership, or other *
* interests in the software remain the property of Acunia N.V. and its *
* licensors, if any. *
* *
* This software may only be used in accordance with the corresponding *
* license agreement. Any unauthorized use, duplication, transmission, *
* distribution or disclosure of this software is expressly forbidden. *
* *
* This Copyright notice may not be removed or modified without prior *
* written consent of Acunia N.V. *
* *
* Acunia N.V. reserves the right to modify this software without notice. *
* *
* Acunia N.V. *
* Vanden Tymplestraat 35 info@acunia.com *
* 3000 Leuven http://www.acunia.com *
* Belgium - EUROPE *
**************************************************************************/
package gnu.testlet.wonka.lang.reflect.Modifier;
import gnu.testlet.Testlet;
import gnu.testlet.TestHarness;
//import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* this file contains testcode for the java.lang.reflect.Modifier class <br>
* together with toString, these cover the whole class Modifier <br>
* <br>
* Needs tests on:<br>
* - <br>
*
*/
public class SMModifierTest implements Testlet
{
protected TestHarness th;
public void test (TestHarness harness)
{
th = harness;
th.setclass("java.lang.reflect.Modifier");
test_constants();
test_isAbstract();
test_isFinal();
test_isInterface ();
test_isNative();
test_isPrivate();
test_isProtected();
test_isPublic();
test_isStatic();
test_isStrict();
test_isSynchronized ();
test_isTransient();
test_isVolatile();
test_toString();
}
/**
* implemented <br>
*
* the value of these constants are listed in java class libraries p1144
*/
protected void test_constants ()
{
th.checkPoint("checking modifier constants");
th.check(Modifier.ABSTRACT == 1024);
th.check(Modifier.FINAL == 16);
th.check(Modifier.INTERFACE == 512);
th.check(Modifier.NATIVE == 256);
th.check(Modifier.PRIVATE == 2);
th.check(Modifier.PROTECTED ==4 );
th.check(Modifier.PUBLIC == 1);
th.check(Modifier.STATIC == 8);
th.check(Modifier.STRICT == 2048);
th.check(Modifier.SYNCHRONIZED ==32 );
th.check(Modifier.TRANSIENT == 128);
th.check(Modifier.VOLATILE ==64 );
}
/**
* implemented.
*
*/
protected void test_isAbstract()
{
th.checkPoint("isAbstract(int)boolean");
th.check(Modifier.isAbstract(1024) , "its number");
th.check(Modifier.isAbstract(1096) , "its number is included");
th.check(!Modifier.isAbstract(24) , "not abstract -- 1");
th.check(!Modifier.isAbstract(1023) , "not abstract -- 2");
}
/**
* implemented.
*
*/
protected void test_isFinal()
{
th.checkPoint("isFinal(int)boolean");
th.check(Modifier.isFinal(16) , "its number");
th.check(Modifier.isFinal(48) , "its number is included -- 1");
th.check(Modifier.isFinal(57) , "its number is included -- 2");
th.check(!Modifier.isFinal(64) , "not final -- 1");
th.check(!Modifier.isFinal(15) , "not final -- 2");
}
/**
* implemented.
*
*/
protected void test_isInterface()
{
th.checkPoint("isInterface(int)boolean");
th.check(Modifier.isInterface(512) , "its number");
th.check(Modifier.isInterface(540) , "its number is included -- 1");
th.check(Modifier.isInterface(1600) , "its number is included -- 2");
th.check(!Modifier.isInterface(511) , "not an Interface -- 1");
th.check(!Modifier.isInterface(1024) , "not an Interface -- 2");
}
/**
* implemented.
*
*/
protected void test_isNative()
{
th.checkPoint("isNative(int)boolean");
th.check(Modifier.isNative(256),"its number");
th.check(Modifier.isNative(435),"its number is included -- 1");
th.check(Modifier.isNative(780),"its number is included -- 2");
th.check(!Modifier.isNative(513),"not native -- 1");
th.check(!Modifier.isNative(255),"not native -- 2");
}
/**
* implemented.
*
*/
protected void test_isPrivate()
{
th.checkPoint("isPrivate(int)boolean");
th.check(Modifier.isPrivate(2), "its number");
th.check(Modifier.isPrivate(6), "its number is included -- 1");
th.check(Modifier.isPrivate(66),"its number is included -- 2");
th.check(!Modifier.isPrivate(1), "not private -- 1");
th.check(!Modifier.isPrivate(5), "not private -- 2");
}
/**
* implemented.
*
*/
protected void test_isProtected()
{
th.checkPoint("isProtected(int)boolean");
th.check(Modifier.isProtected(4),"its number");
th.check(Modifier.isProtected(6),"its number is included -- 1");
th.check(Modifier.isProtected(68),"its number is included -- 2");
th.check(!Modifier.isProtected(64),"not protected -- 1");
th.check(!Modifier.isProtected(3),"not protected -- 2");
}
/**
* implemented.
*
*/
protected void test_isPublic()
{
th.checkPoint("isPublic(int)boolean");
th.check(Modifier.isPublic(1),"its number");
th.check(Modifier.isPublic(3),"its number is included -- 1");
th.check(Modifier.isPublic(77),"its number is included -- 2");
th.check(!Modifier.isPublic(2), "not public -- 1");
th.check(!Modifier.isPublic(888456), "not public --2 ");
}
/**
* implemented.
*
*/
protected void test_isStatic()
{
th.checkPoint("isStatic(int)boolean");
th.check(Modifier.isStatic(8),"its number");
th.check(Modifier.isStatic(14),"its number is included -- 1");
th.check(Modifier.isStatic(25),"its number is included -- 2");
th.check(!Modifier.isStatic(7),"not static -- 1");
th.check(!Modifier.isStatic(17),"not static -- 2");
}
/**
* implemented.
*
*/
protected void test_isStrict()
{
th.checkPoint("isStrict(int)boolean");
th.check(Modifier.isStrict(2048),"its number");
th.check(Modifier.isStrict(3111),"its number is included -- 1");
th.check(Modifier.isStrict(6234),"its number is included -- 2");
th.check(!Modifier.isStrict(2047),"not strict -- 1");
th.check(!Modifier.isStrict(5000),"not strict -- 2");
}
/**
* implemented.
*
*/
protected void test_isSynchronized()
{
th.checkPoint("isSynchronized(int)boolean");
th.check(Modifier.isSynchronized(32),"its number");
th.check(Modifier.isSynchronized(35), "its number is included -- 1");
th.check(Modifier.isSynchronized(99), "its number is included -- 2");
th.check(!Modifier.isSynchronized(65),"not synchronized -- 1");
th.check(!Modifier.isSynchronized(31),"not synchronized -- 2");
}
/**
* implemented.
*
*/
protected void test_isTransient()
{
th.checkPoint("isTransient(int)boolean");
th.check(Modifier.isTransient(128),"its number");
th.check(Modifier.isTransient(231),"its number is included -- 1");
th.check(Modifier.isTransient(1157),"its number is included -- 2");
th.check(!Modifier.isTransient(127),"not transient -- 1");
th.check(!Modifier.isTransient(311),"not transient -- 2");
}
/**
* implemented.
*
*/
protected void test_isVolatile()
{
th.checkPoint("isVolatile(int)boolean");
th.check(Modifier.isVolatile(64),"its number");
th.check(Modifier.isVolatile(127),"its number is included -- 1");
th.check(Modifier.isVolatile(320),"its number is included -- 2");
th.check(!Modifier.isVolatile(319),"not volatile -- 1");
th.check(!Modifier.isVolatile(63),"not volatile -- 2");
}
/**
* implemented.
*
*/
protected void test_toString()
{
th.checkPoint("toString(int)java.lang.String");
th.check(Modifier.toString(2047).equals("public protected private abstract static final transient"+
" volatile synchronized native interface"),"checking toString order");
th.check(Modifier.toString(4095).equals("public protected private abstract static final transient"+
" volatile synchronized native strictfp interface"),"checking toString order");
System.out.println(Modifier.toString(4095));
}
} | 30.542553 | 101 | 0.620109 |
4991adc61aae0b9f2062c2ebb4a7cb6dc28e4cf1 | 4,213 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.bremersee.scs.config;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import javax.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.data.util.Pair;
import org.springframework.util.AntPathMatcher;
import org.springframework.validation.annotation.Validated;
/**
* The static content server properties.
*
* @author Christian Bremer
*/
@ConfigurationProperties(prefix = "bremersee.scs")
@RefreshScope
@Getter
@Setter
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@Validated
@Slf4j
public class ScsProperties {
/**
* The classpath prefix.
*/
static final String CLASSPATH_PREFIX = "classpath:";
/**
* The default classpath location.
*/
static final String DEFAULT_CLASSPATH_LOCATION = CLASSPATH_PREFIX + "content/";
@NotNull
private String pattern = "/**";
@NotNull
private String contentLocation = "/opt/content/";
private String defaultIndex = "index.html";
@NotNull
private Map<String, String> directoryPatternIndexMap = new LinkedHashMap<>();
/**
* Gets content location.
*
* @return the content location
*/
public String getContentLocation() {
return Optional.of(contentLocation)
.map(String::trim)
.map(value -> !value.endsWith("/") ? value + "/" : value)
.orElse(contentLocation);
}
/**
* Create content root resource.
*
* @return the resource
*/
public Resource createContentResource() {
return createContentResource(getContentLocation());
}
/**
* Create content root resource.
*
* @param location the location
* @return the resource
*/
static Resource createContentResource(@NotNull String location) {
return location.toLowerCase().startsWith(CLASSPATH_PREFIX)
? new ClassPathResource(location.substring(CLASSPATH_PREFIX.length()))
: new FileSystemResource(location);
}
/**
* Find directory index.
*
* @param requestPath the request path
* @return the directory index
*/
public Optional<String> findDirectoryIndex(String requestPath) {
final String path;
if (requestPath != null) {
String tmp = requestPath.trim();
path = tmp.startsWith("/") ? tmp : "/" + tmp;
} else {
path = "/";
}
log.debug("Looking for index of {}", path);
Map<String, String> map = getDirectoryPatternIndexMap();
if (!(map.containsKey("/**") || map.containsKey("[/**]"))) {
map.put("/**", defaultIndex);
}
return map.entrySet().stream()
.map(entry -> {
String key = entry.getKey();
log.debug("Key {} -> {}", entry.getKey(), key);
return Pair.of(key, entry.getValue());
})
.peek(pair -> log.debug("Pattern {} matches path {}? {}", pair.getFirst(), path,
new AntPathMatcher().match(pair.getFirst(), path)))
.filter(pair -> new AntPathMatcher().match(pair.getFirst(), path))
.findFirst()
.map(Pair::getSecond)
.map(index -> {
if (index.startsWith("/")) {
return index.substring(1);
}
return index;
});
}
}
| 28.659864 | 88 | 0.679089 |
c074587d23975a479543c5a445aaf20409f3f10d | 719 | package com.example.hahaha.musicplayer.feature.collect;
import android.content.Context;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.BindView;
import com.example.hahaha.musicplayer.R;
import com.example.hahaha.musicplayer.app.MusicApp;
import com.example.hahaha.musicplayer.feature.base.BaseViewHolder;
public class CollectHeadViewHolder extends BaseViewHolder {
@BindView(R.id.txt_collect_num) TextView mTxtCollectNum;
public CollectHeadViewHolder(Context context, ViewGroup parent) {
super(context, parent, R.layout.header_collect);
}
void setNum(int num) {
mTxtCollectNum.setText(
MusicApp.appResources().getString(R.string.collect_head, num));
}
}
| 31.26087 | 71 | 0.79694 |
26bbfa099b22c1e07c57ea8c844381ce773ca1ea | 1,287 | package me.vilsol.nmswrapper.wraps.unparsed;
import me.vilsol.nmswrapper.*;
import me.vilsol.nmswrapper.reflections.*;
import me.vilsol.nmswrapper.wraps.*;
@ReflectiveClass(name = "MaterialDecoration")
public class NMSMaterialDecoration extends NMSMaterial {
public NMSMaterialDecoration(Object nmsObject){
super(nmsObject);
}
public NMSMaterialDecoration(NMSMaterialMapColor materialMapColor){
super("MaterialDecoration", new Object[]{NMSMaterialMapColor.class}, new Object[]{materialMapColor});
}
/**
* @see net.minecraft.server.v1_9_R1.MaterialDecoration#blocksLight()
*/
@ReflectiveMethod(name = "blocksLight", types = {})
public boolean blocksLight(){
return (boolean) NMSWrapper.getInstance().exec(nmsObject);
}
/**
* @see net.minecraft.server.v1_9_R1.MaterialDecoration#isBuildable()
*/
@ReflectiveMethod(name = "isBuildable", types = {})
public boolean isBuildable(){
return (boolean) NMSWrapper.getInstance().exec(nmsObject);
}
/**
* @see net.minecraft.server.v1_9_R1.MaterialDecoration#isSolid()
*/
@ReflectiveMethod(name = "isSolid", types = {})
public boolean isSolid(){
return (boolean) NMSWrapper.getInstance().exec(nmsObject);
}
} | 30.642857 | 109 | 0.693085 |
49a97fc7ef9eb8760a3869894a12bdf3bccf6321 | 1,005 | package d01;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class FileChannelTransferTo {
public static void main(String[] args) {
try (
FileChannel from = new RandomAccessFile("d01/from.txt", "rw").getChannel();
FileChannel to = new FileOutputStream("d01/to.txt").getChannel()
) {
final ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.put(new byte[]{'a', 'b', 'c', 'd'});
buffer.flip();
from.write(buffer);
long start = System.nanoTime();
/*
效率高,底层利用操作系统的零拷贝进行优化
*/
from.transferTo(0, from.size(), to);
long end = System.nanoTime();
System.out.println("transferTo 用时:" + (end - start) / 1000_000.0);
} catch (IOException e) {
e.printStackTrace();
}
}
} | 25.125 | 91 | 0.563184 |
b8453758a5e97fd05933a9313794c6ce76379c20 | 3,133 | package org.deeplearning4j.examples.convolution.ZacCNN.DistriTest;
import de.siegmar.fastcsv.reader.CsvParser;
import de.siegmar.fastcsv.reader.CsvReader;
import de.siegmar.fastcsv.reader.CsvRow;
import org.apache.commons.io.IOUtils;
import org.datavec.api.split.FileSplit;
import org.deeplearning4j.examples.convolution.ZacCNN.Config;
import org.deeplearning4j.examples.convolution.ZacCNN.DataSet;
import org.deeplearning4j.examples.convolution.ZacCNN.DataType;
import org.deeplearning4j.examples.convolution.ZacCNN.HarReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.Iterator;
public class FastCSVTest {
public static void main(String[] args) throws Exception {
// fast1();
// faster than 1
// dl4jReader();
System.out.println(readData());
}
public static void fast1() throws Exception {
Config config = DataSet.getConfig(DataType.HAR);
File file = new File(config.getDataPath());
CsvReader csvReader = new CsvReader();
CsvParser csvParser = csvReader.parse(file, StandardCharsets.UTF_8);
CsvRow row;
long start = System.currentTimeMillis();
while ((row = csvParser.nextRow()) != null) {
System.out.println("Read line: " + row);
// System.out.println("First column of line: " + row.getField(0));
}
System.out.println(System.currentTimeMillis() - start);
}
public static void dl4jReader() throws Exception {
Config config = DataSet.getConfig(DataType.HAR);
Iterator<String> iter = IOUtils.lineIterator(new InputStreamReader(Files.newInputStream(
new File(config.getDataPath()).toPath(), StandardOpenOption.READ)));
long start = System.currentTimeMillis();
while (iter.hasNext()) {
System.out.println(iter.next());
}
System.out.println(System.currentTimeMillis() - start);
}
public static String readData() throws Exception{
// test har read csv
long start = System.currentTimeMillis();
Config config = DataSet.getConfig(DataType.HAR);
HarReader reader = new HarReader(config.getNumLinesToSkip(), config.getHeight(), config.getWidth(), config.getChannel(),
config.getNumClasses(), config.getTaskNum(), config.getDelimiter());
reader.initialize(new FileSplit(config.getFile()));
// 50ms per line
int index = 0;
// while (reader.hasNext()) {
// reader.next();
// log.d("Read csv single data: " + ++index);
// }
//
long end = System.currentTimeMillis();
long t1 = end - start;
reader.reset();
index = 0;
// 1s per batch
while (reader.hasNext()) {
reader.next(config.getBatchSize());
// System.out.println("Read csv batch data: " + ++index);
}
long t2 = System.currentTimeMillis() - end;
return "single time: " + t1 + ", batch time: " + t2;
}
}
| 32.635417 | 128 | 0.650176 |
c649cb99cb7696a2914bfe4134769058dd863f3a | 1,586 | package ru.pinkgoosik.villagerhats.compat;
import dev.emi.trinkets.api.SlotReference;
import dev.emi.trinkets.api.TrinketComponent;
import dev.emi.trinkets.api.TrinketsApi;
import dev.emi.trinkets.api.client.TrinketRendererRegistry;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Pair;
import net.minecraft.village.VillagerProfession;
import ru.pinkgoosik.villagerhats.VillagerHatsMod;
import ru.pinkgoosik.villagerhats.item.VillagerHatTrinket;
import ru.pinkgoosik.villagerhats.client.render.VillagerHatTrinketRenderer;
import java.util.Optional;
public class TrinketsCompat {
public static void onInitializeClient() {
VillagerHatsMod.ITEMS.forEach((id, item) -> TrinketRendererRegistry.registerRenderer(item, new VillagerHatTrinketRenderer()));
}
public static boolean hasVillagerHat(PlayerEntity player) {
Optional<TrinketComponent> component = TrinketsApi.getTrinketComponent(player);
if(component.isPresent()) {
for(Pair<SlotReference, ItemStack> pair : component.get().getAllEquipped()) {
if(pair.getRight().getItem() instanceof VillagerHatTrinket) return true;
}
}
return false;
}
public static Item createTrinket(VillagerProfession profession) {
return new VillagerHatTrinket(profession);
}
public static Item createTrinket(VillagerProfession profession, float size, double height) {
return new VillagerHatTrinket(profession, size, height);
}
}
| 36.883721 | 134 | 0.759773 |
ce9dcd0a80d7f3452d4e1f2520452483a6a5efcf | 3,317 | package com.stackroute.pie.services;
import com.stackroute.pie.domain.*;
import com.stackroute.pie.message.request.SignUpForm;
import com.stackroute.pie.repository.InsurerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class InsurerServiceImpl implements InsurerService{
private InsurerRepository insurerRepository;
@Autowired
public InsurerServiceImpl(InsurerRepository insurerRepository) {
this.insurerRepository = insurerRepository;
}
//Method to add insurer to the Database
@Override
public Insurer addInsurer(SignUpForm signUpRequest) {
List<Insurer> insurerList = insurerRepository.findAll();
Insurer insurer = new Insurer(signUpRequest.getInsurerName(),signUpRequest.getInsurerLicense(),
signUpRequest.getInsurerEmail(),signUpRequest.getPassword(),signUpRequest.getInsurerAddress(),
signUpRequest.getSecurityQuestion(),signUpRequest.getSecurityAnswer());
if(insurerList.isEmpty()) {
insurer.setInsurerId((long) 1);
}
else {
insurer.setInsurerId((long) (insurerList.size()+1));
}
Set<Role> roles = new HashSet<>();
Role userrRole = new Role();
userrRole.setName(RoleName.ROLE_INSURER);
roles.add(userrRole);
insurer.setRoles(roles);
return insurerRepository.save(insurer);
}
//Method to calculate the premium based on the POJO
@Override
public long calculatePremium(PremiumCalci premiumCalci){
long premium = 1000;
if (premiumCalci.getAgeOfEldest() < 40) {
premium *= 1.1;
}
else{
// Add 20% per 5 years above 40
int age = premiumCalci.getAgeOfEldest() - 40;
while (age >= 5) {
premium *= 1.2;
age -= 5;
}
}
List<String> policyList = new ArrayList<>();
List<Float> policyValue = new ArrayList<>();
policyList.add("Apollo-cancer");
policyList.add("Apollo-children");
policyList.add("Apollo-Family");
policyList.add("MaxBupa-cancer");
policyList.add("MaxBupa-children");
policyList.add("MaxBupa-Family");
policyList.add("StarHealth-cancer");
policyList.add("StarHealth-children");
policyList.add("StarHealth-Family");
policyValue.add((float) 1.3);
policyValue.add((float) 1.2);
policyValue.add((float) 1.1);
policyValue.add((float) 1.2);
policyValue.add((float) 1.3);
policyValue.add((float) 1.5);
policyValue.add((float) 1.5);
policyValue.add((float) 1.075);
policyValue.add((float) 1.15);
String policyName = premiumCalci.getPolicyName();
int index = policyList.indexOf(policyName);
if(index >= 0)
premium *= policyValue.get(index);
else {
premium *= (float) 1.01;
}
premium *= 1 + (premiumCalci.getSumInsured()/1000000);
premium *= premiumCalci.getNoOfAdults();
premium += (premiumCalci.getNoOfChildren()*.5);
premium *= premiumCalci.getNoOfYears();
return premium;
}
}
| 30.431193 | 110 | 0.62647 |
b87a6467436ecc9db0984229f4986002d607beac | 5,553 | package br.fernando.ch06_generics_and_collections_Objective.part04_Generic_Types;
import java.util.ArrayList;
import java.util.List;
import br.fernando.ch06_generics_and_collections_Objective.part04_Generic_Types.Test02.Dog;
class Test03 {
static class Car {
}
// =========================================================================================================================================
// Generic Declarations
// When you look at an API for a generics class or interface, pick a type parameter
// ( Dog , JButton , even Object ) and do a mental find and replace on each instance of E (or
// whatever identifier is used as the placeholder for the type parameter).
static void test01() {
}
// =========================================================================================================================================
// Making Your Own Generic Class
static class Rental01 {
protected List rentalPool;
protected int maxNum;
public Rental01(final int maxNum, List rentalPool) {
this.maxNum = maxNum;
this.rentalPool = rentalPool;
}
public Object getRental() {
// blocks until there's somethng available
return rentalPool.get(0);
}
public void returnRental(final Object object) {
rentalPool.add(object);
}
}
static class CarRental01 extends Rental01 {
public CarRental01(int maxNum, List<Car> rentalPool) {
super(maxNum, rentalPool);
}
public Car getRental() {
return (Car) rentalPool.get(0);
}
public void returnRental(final Object object) {
if (object instanceof Car) {
super.returnRental(object);
} else {
System.out.println("Cannot add a non-car");
// probably throw an exception
}
}
}
// But then, the more you look at it, the more you realize:
// 1. You are doing your own type checking in the returnRental() method. You
// can’t change the argument type of returnRental() to take a Car , since it’s an
// override (not an overload) of the method from class Rental . (Overloading
// would take away your polymorphic flexibility with Rental .)
//
// 2. You really don’t want to make separate subclasses for every possible kind of
// rentable thing (cars, computers, bowling shoes, children, and so on).
// So here’s your new and improved generic Rental class:
static class Rental02<T> { // T is for the type parameter
protected List<T> rentalPool; // Use the class type for the List type
protected int maxNum;
public Rental02(final int maxNum, List<T> rentalPool) { // constructor takes a List of the class type
this.maxNum = maxNum;
this.rentalPool = rentalPool;
}
public T getRental() { // we rent out a T
return rentalPool.remove(0);
}
public void returnRental(final T object) { // and the renter returns a T
rentalPool.add(object);
}
}
static void test02() {
Car c1 = new Car();
Car c2 = new Car();
List<Car> carList = new ArrayList<>();
Rental02<Car> carRental = new Rental02<>(2, carList);
// now get a car out, and it won't need a cast
Car carToRent = carRental.getRental();
carRental.returnRental(carToRent);
// can we stick something else the original carList?
// carList.add("fluffy");
// Now we have a Rental class that can be typed to whatever the programmer
// chooses, and the compiler will enforce it.
// And you can use a form of wildcard notation in a class definition to specify a range
// (called “bounds“) for the type that can be used for the type parameter:
}
// =========================================================================================================================================
// Creating Generic Methods 573
// Using a generic method, we can declare the method without a specific type and then get the type information based on the type of the
// object passed to the method
static void test03() {
makeArrayList(1L);
makeArrayList("Teste");
}
// The strangest thing about generic methods is that you must declare the type variable
// BEFORE the return type of the method:
public static <T> void makeArrayList(T t) { // take an object of an unkown type and use a "T" to represent the type
List<T> list = new ArrayList<>(); // now we can create the list using "T"
list.add(t);
}
// You’re also free to put boundaries on the type you declare. For example, if you want to restrict the makeArrayList()
// method to only Number or its subtypes ( Integer , Float , and so on), you would say
public static <T extends Number> void makeArrayList(T t) {
}
// In the preceding code, if you invoke the makeArrayList() method with a Dog
// instance, the method will behave as though it looked like this all along:
public static void makeArrayList(Dog d) {
List<Dog> list = new ArrayList<>();
list.add(d);
}
// =========================================================================================================================================
public static void main(String[] args) {
test01();
}
}
| 36.058442 | 144 | 0.56546 |
20c4a05ab184c7986ec3fc27ed9f99f5646a8c74 | 1,592 | package com.android_retrofit_room_viewmodel_livedata_lifecycle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.android_retrofit_room_viewmodel_livedata_lifecycle.retrofit.RetrofitUtil;
import com.android_retrofit_room_viewmodel_livedata_lifecycle.retrofit.pojo.Repo;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity implements Callback<List<Repo>> {
private static final String TAG = MainActivity.class.getSimpleName();
private TextView mRetrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRetrofit = (TextView) findViewById(R.id.retrofit_demo);
RetrofitUtil.getGitHubInfo(this);
}
@Override
public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
String info = "";
if(response != null && response.body() != null){
for(Repo repo:response.body()){
String id = String.valueOf(repo.getId());
String name = String.valueOf(repo.getName());
Log.v(TAG,"id = " + id);
Log.v(TAG,"name = " + name);
info += "id = " + id + "\n" + "name = " + name + "\n";
}
}
mRetrofit.setText(info);
}
@Override
public void onFailure(Call<List<Repo>> call, Throwable t) {
}
}
| 31.215686 | 85 | 0.66897 |
12028b28f0db8e1091f5caaa6191b249ed381e44 | 935 | package org.codehaus.stax.test.stream;
import java.io.*;
/**
* Test stream used to test whether Reader using this stream would
* 'accidentally' cause blocking. Used by {@link TestStreaming}
* unit test suite.
*/
class BlockingStream
extends FilterInputStream
{
public boolean mBlocked = false;
// dummy ctor to keep JUnit happy
public BlockingStream() { super(null); }
public BlockingStream(InputStream is)
{
super(is);
}
public boolean hasBlocked() {
return mBlocked;
}
@Override
public int read() throws IOException
{
int r = super.read();
if (r < 0) {
mBlocked = true;
}
return r;
}
@Override
public int read(byte[] b, int off, int len) throws IOException
{
int r = super.read(b, off, len);
if (r < 0) {
mBlocked = true;
}
return r;
}
}
| 19.893617 | 66 | 0.566845 |
7684b1c7e6702c9426e0d5cd61383f5c25e298d4 | 1,651 | package com.rainard.grindhouse.persistence.entity;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import java.util.Date;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class EmployeeEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long empId;
@Column(name = "emp_number", nullable = false, unique = true)
private String empNumber;
@Column(name = "emp_password", nullable = false)
private String empPassword;
@Column(name = "emp_name", nullable = false)
private String empName;
@Column(name = "logged_in", nullable = false)
private Boolean isLoggedIn;
@CreatedDate
@Column(name = "created", nullable = false)
private Date created;
@LastModifiedDate
@Column(name = "updated", nullable = false)
private Date updated;
@OneToOne(mappedBy = "employee")
private ShopEmployeeEntity shopEmployee;
@OneToMany(mappedBy = "employee")
private List<OrderEntity> orders;
@OneToMany(mappedBy = "employee")
private List<AuditLogEntity> auditLogEntities;
@OneToOne(mappedBy = "employee")
private ShopOwnerEntity shopOwner;
}
| 24.279412 | 65 | 0.752271 |
ba8ddb7e2505a9f38aa645eafe3544955df279d9 | 476 | package cn.ruleengine.web.vo.workspace;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
* 〈一句话功能简述〉<br>
* 〈〉
*
* @author dingqianwen
* @date 2020/12/19
* @since 1.0.0
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class ListWorkspaceResponse extends Workspace{
private String description;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
}
| 17.62963 | 53 | 0.72479 |
45d93b82855889419816ad1e26e8eee5959527e0 | 658 | package org.testory.testing;
import static org.junit.Assert.assertEquals;
import static org.testory.testing.Closures.returning;
import org.junit.Before;
import org.junit.Test;
import org.testory.common.Closure;
public class TestClosuresReturning {
private Object object;
private Closure closure;
@Before
public void before() {
object = new Object();
}
@Test
public void should_return_object() throws Throwable {
closure = returning(object);
assertEquals(object, closure.invoke());
}
@Test
public void should_return_null() throws Throwable {
closure = returning(null);
assertEquals(null, closure.invoke());
}
}
| 21.225806 | 55 | 0.732523 |
37ef5420d5c673a03e9f19a7f2997863bdb9d9af | 2,265 | package org.perfcake.pc4idea.impl.editor.editor.component;
import com.intellij.openapi.ui.ValidationInfo;
import org.perfcake.model.Property;
import org.perfcake.model.Scenario;
import org.perfcake.pc4idea.api.editor.editor.component.AbstractEditor;
import org.perfcake.pc4idea.api.editor.swing.EditorTablePanel;
import org.perfcake.pc4idea.impl.editor.editor.tablemodel.PropertiesTableModel;
import javax.swing.*;
import java.util.List;
/**
* User: Stanislav Kaleta
* Date: 19.10.2014
*/
public class PropertiesEditor extends AbstractEditor {
private EditorTablePanel propertiesTablePanel;
public PropertiesEditor() {
initComponents();
}
private void initComponents() {
propertiesTablePanel = new EditorTablePanel(new PropertiesTableModel());
GroupLayout layout = new GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup()
.addComponent(propertiesTablePanel));
layout.setVerticalGroup(layout.createSequentialGroup()
.addComponent(propertiesTablePanel));
}
public void setObjProperties(Scenario.Properties properties) {
this.setListProperties(properties.getProperty());
}
public Scenario.Properties getObjProperties() {
Scenario.Properties newProperties = new Scenario.Properties();
newProperties.getProperty().addAll(this.getListProperties());
return newProperties;
}
public void setListProperties(List<Property> properties) {
PropertiesTableModel model = (PropertiesTableModel) propertiesTablePanel.getTableModel();
model.setUserProperties(properties);
}
public List<Property> getListProperties() {
return ((PropertiesTableModel) propertiesTablePanel.getTableModel()).getUserProperties();
}
public void setDefinedProperties(List<Property> properties) {
PropertiesTableModel model = (PropertiesTableModel) propertiesTablePanel.getTableModel();
model.setDefinedProperties(properties);
}
@Override
public String getTitle() {
return "Properties Editor";
}
@Override
public ValidationInfo areInsertedValuesValid() {
// always valid
return null;
}
}
| 32.357143 | 97 | 0.726269 |
17f53b1cda232dc5924bff9deaf29b8711694337 | 4,626 | package de.yogularm.minecraft.itemfinder.gui;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableRowSorter;
import org.jdesktop.swingx.JXTable;
import de.yogularm.minecraft.itemfinder.region.DroppedItem;
public class ItemList {
private Component component;
private JXTable table;
private ItemTableModel model;
private TableRowSorter<ItemTableModel> sorter;
private JPopupMenu contextMenu;
public ItemList() {
initUI();
}
private void initUI() {
model = new ItemTableModel();
table = new JXTable(model);
sorter = new TableRowSorter<>(model);
table.setRowSorter(sorter);
sorter.setComparator(0, new NaturalOrderComparator()); // for item name
sorter.setSortKeys(Arrays.asList(
new RowSorter.SortKey(4, SortOrder.DESCENDING),
new RowSorter.SortKey(3, SortOrder.ASCENDING)));
table.getColumnModel().getColumn(0).setWidth(200);
component = new JScrollPane(table);
contextMenu = new JPopupMenu();
JMenuItem copyItem = new JMenuItem("Copy");
copyItem.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent actionEvent) {
Object text = table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
if (text == null) {
return;
}
Toolkit.getDefaultToolkit().getSystemClipboard()
.setContents(new StringSelection(text.toString()), null);
}
});
contextMenu.add(copyItem);
// manually show the popup menu so that the cell under the mouse is selected first
table.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
// Left mouse click
if (SwingUtilities.isLeftMouseButton(e)) {
// Do something
}
// Right mouse click
else if (SwingUtilities.isRightMouseButton(e)) {
// get the coordinates of the mouse click
Point p = e.getPoint();
// get the row index that contains that coordinate
int rowNumber = table.rowAtPoint(p);
// Get the ListSelectionModel of the JTable
ListSelectionModel model = table.getSelectionModel();
// set the selected interval of rows. Using the "rowNumber"
// variable for the beginning and end selects only that one row.
model.setSelectionInterval(rowNumber, rowNumber);
int colNumber = table.columnAtPoint(p);
table.getColumnModel().getSelectionModel().setSelectionInterval(colNumber, colNumber);
contextMenu.show(table, p.x, p.y);
}
}
});
}
public void setItems(List<DroppedItem> items) {
model.setItems(items);
table.packAll(); // adjust column widths
}
public Component getComponent() {
return component;
}
private static class ItemTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1904800093497922295L;
private static final String[] COLUMNS = new String[] { "Item Name",
"Stack Size", "Location", "Age", "Chunk Update" };
private List<DroppedItem> items;
public ItemTableModel() {
this.items = new ArrayList<>();
}
public void setItems(List<DroppedItem> items) {
this.items = items;
fireTableDataChanged();
}
@Override
public int getColumnCount() {
return COLUMNS.length;
}
@Override
public String getColumnName(int column) {
return COLUMNS[column];
}
@Override
public int getRowCount() {
return items.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (rowIndex >= items.size())
return "";
DroppedItem item = items.get(rowIndex);
switch (columnIndex) {
case 0:
return item.getName();
case 1:
return item.getCount();
case 2:
return item.getPosition().toRoundedString();
case 3:
// there are items with age 0 which should be displayed at the bottom
// HourSecond will render Integer.MAX_VALUE as --
return new HourSecond(item.getAge() == 0 ? Integer.MAX_VALUE : item.getAge() / 20);
case 4:
return new RelativeTime(- item.getRelativeChunkUpdateTime());
default:
return "";
}
}
@Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return String.class;
case 1:
return Integer.class;
case 2:
return String.class;
case 3:
return HourSecond.class;
case 4:
return RelativeTime.class;
default:
return null;
}
}
}
}
| 26.434286 | 91 | 0.707307 |
818ca4bdf9175b40392f3cdbc8e1e0883f4fe577 | 4,000 | /*
* Copyright 2019-present HiveMQ GmbH
*
* 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.hivemq.logging;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import com.hivemq.extension.sdk.api.annotations.NotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Iterator;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
/**
* @author Dominik Obermaier
*/
public class XodusEnvironmentImplLogLevelModificatorTest {
private ch.qos.logback.classic.Logger rootLogger;
private Level level;
@Before
public void setUp() throws Exception {
final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
level = rootLogger.getLevel();
rootLogger.setLevel(Level.TRACE);
context.addTurboFilter(new XodusEnvironmentImplLogLevelModificator());
context.getLogger("jetbrains.exodus").setLevel(Level.TRACE);
}
@After
public void tearDown() throws Exception {
rootLogger.setLevel(level);
}
@Test
public void test_xodus_error_message_transactions_not_finished() throws Exception {
final String msg = "Environment[/var/folders/fp/dfyv187j4h5g6cn6xs49qpqw0000gn/T/junit5059509984233082259/junit231924022829037059] is active: 1 transaction(s) not finished";
final CountDownLatch countDownLatch = new CountDownLatch(1);
final Iterator<Appender<ILoggingEvent>> appenderIterator = rootLogger.iteratorForAppenders();
while (appenderIterator.hasNext()) {
appenderIterator.next().addFilter(createFilter(countDownLatch, msg));
}
XodusEnvironmentImplLogLevelModificator.environmentalLogger.error(msg);
assertEquals(true, countDownLatch.await(3, TimeUnit.SECONDS));
}
@Test
public void test_xodus_error_message_transaction_stack_traces_not_available() throws Exception {
final String msg = "Transactions stack traces are not available, set 'exodus.env.monitorTxns.timeout > 0'";
final CountDownLatch countDownLatch = new CountDownLatch(1);
final Iterator<Appender<ILoggingEvent>> appenderIterator = rootLogger.iteratorForAppenders();
while (appenderIterator.hasNext()) {
appenderIterator.next().addFilter(createFilter(countDownLatch, msg));
}
XodusEnvironmentImplLogLevelModificator.environmentalLogger.error(msg);
assertEquals(true, countDownLatch.await(3, TimeUnit.SECONDS));
}
@NotNull
private Filter<ILoggingEvent> createFilter(final CountDownLatch countDownLatch, final String text) {
return new Filter<ILoggingEvent>() {
@Override
public FilterReply decide(final ILoggingEvent event) {
if (event.getLevel().equals(Level.TRACE)) {
if (event.getFormattedMessage().equals(text)) {
countDownLatch.countDown();
return FilterReply.NEUTRAL;
}
}
return FilterReply.NEUTRAL;
}
};
}
} | 36.697248 | 181 | 0.71325 |
f5dbb26ee7b3c4a86719bec2aa84c26790476f5a | 2,310 | /*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.execution.jar;
import javax.annotation.Nonnull;
import com.intellij.execution.configuration.ConfigurationFactoryEx;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.execution.configurations.ConfigurationTypeBase;
import com.intellij.execution.configurations.ConfigurationTypeUtil;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import consulo.java.execution.JavaExecutionBundle;
import consulo.java.module.extension.JavaModuleExtension;
import consulo.module.extension.ModuleExtensionHelper;
public class JarApplicationConfigurationType extends ConfigurationTypeBase implements ConfigurationType
{
@Nonnull
public static JarApplicationConfigurationType getInstance()
{
return ConfigurationTypeUtil.findConfigurationType(JarApplicationConfigurationType.class);
}
public JarApplicationConfigurationType()
{
super("JarApplication", JavaExecutionBundle.message("jar.application.configuration.name"), JavaExecutionBundle.message("jar.application.configuration.description"), AllIcons.FileTypes.Archive);
addFactory(new ConfigurationFactoryEx(this)
{
@Override
public void onNewConfigurationCreated(@Nonnull RunConfiguration configuration)
{
JarApplicationConfiguration jarApplicationConfiguration = (JarApplicationConfiguration) configuration;
if(StringUtil.isEmpty(jarApplicationConfiguration.getWorkingDirectory()))
{
String baseDir = FileUtil.toSystemIndependentName(StringUtil.notNullize(configuration.getProject().getBasePath()));
jarApplicationConfiguration.setWorkingDirectory(baseDir);
}
}
@Override
@Nonnull
public RunConfiguration createTemplateConfiguration(Project project)
{
return new JarApplicationConfiguration(project, this, "");
}
@Override
public boolean isApplicable(@Nonnull Project project)
{
return ModuleExtensionHelper.getInstance(project).hasModuleExtension(JavaModuleExtension.class);
}
});
}
}
| 38.5 | 195 | 0.819048 |
328463842ae79d15eaf64fb10b7b83bf4b6791f3 | 40,843 | /*
* Copyright 2014-2021 Web Firm Framework
*
* 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.webfirmframework.wffweb.css.css3;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.webfirmframework.wffweb.css.CssLengthUnit;
import com.webfirmframework.wffweb.css.CssNameConstants;
/**
* @author WFF
* @since 1.0.0
* @version 1.0.0
*
*/
public class BorderImageWidthTest {
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#BorderImageWidth()}
* .
*/
@Test
public void testBorderImageWidth() {
BorderImageWidth borderImageWidth = new BorderImageWidth();
assertEquals("1.0", borderImageWidth.getCssValue());
assertTrue(1F == borderImageWidth.getTop());
assertTrue(1F == borderImageWidth.getRight());
assertTrue(1F == borderImageWidth.getBottom());
assertTrue(1F == borderImageWidth.getLeft());
assertNull(borderImageWidth.getTopUnit());
assertNull(borderImageWidth.getRightUnit());
assertNull(borderImageWidth.getBottomUnit());
assertNull(borderImageWidth.getLeftUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#BorderImageWidth(java.lang.String)}
* .
*/
@Test
public void testBorderImageWidthString1() {
BorderImageWidth borderImageWidth = new BorderImageWidth("5 15 25 35");
assertEquals("5.0 15.0 25.0 35.0", borderImageWidth.getCssValue());
assertTrue(5F == borderImageWidth.getTop());
assertTrue(15F == borderImageWidth.getRight());
assertTrue(25F == borderImageWidth.getBottom());
assertTrue(35F == borderImageWidth.getLeft());
assertNull(borderImageWidth.getTopUnit());
assertNull(borderImageWidth.getRightUnit());
assertNull(borderImageWidth.getBottomUnit());
assertNull(borderImageWidth.getLeftUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#BorderImageWidth(java.lang.String)}
* .
*/
@Test
public void testBorderImageWidthString2() {
BorderImageWidth borderImageWidth = new BorderImageWidth(
"5px 15px 25px 35px");
assertEquals("5.0px 15.0px 25.0px 35.0px",
borderImageWidth.getCssValue());
assertTrue(5F == borderImageWidth.getTop());
assertTrue(15F == borderImageWidth.getRight());
assertTrue(25F == borderImageWidth.getBottom());
assertTrue(35F == borderImageWidth.getLeft());
assertNotNull(borderImageWidth.getTopUnit());
assertNotNull(borderImageWidth.getRightUnit());
assertNotNull(borderImageWidth.getBottomUnit());
assertNotNull(borderImageWidth.getLeftUnit());
assertEquals(CssLengthUnit.PX, borderImageWidth.getTopUnit());
assertEquals(CssLengthUnit.PX, borderImageWidth.getRightUnit());
assertEquals(CssLengthUnit.PX, borderImageWidth.getBottomUnit());
assertEquals(CssLengthUnit.PX, borderImageWidth.getLeftUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#BorderImageWidth(java.lang.String)}
* .
*/
@Test
public void testBorderImageWidthString3() {
BorderImageWidth borderImageWidth = new BorderImageWidth(
"25px 25px 25px 25px");
assertEquals("25.0px", borderImageWidth.getCssValue());
assertTrue(25F == borderImageWidth.getTop());
assertTrue(25F == borderImageWidth.getRight());
assertTrue(25F == borderImageWidth.getBottom());
assertTrue(25F == borderImageWidth.getLeft());
assertNotNull(borderImageWidth.getTopUnit());
assertNotNull(borderImageWidth.getRightUnit());
assertNotNull(borderImageWidth.getBottomUnit());
assertNotNull(borderImageWidth.getLeftUnit());
assertEquals(CssLengthUnit.PX, borderImageWidth.getTopUnit());
assertEquals(CssLengthUnit.PX, borderImageWidth.getRightUnit());
assertEquals(CssLengthUnit.PX, borderImageWidth.getBottomUnit());
assertEquals(CssLengthUnit.PX, borderImageWidth.getLeftUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#BorderImageWidth(java.lang.String)}
* .
*/
@Test
public void testBorderImageWidthString4() {
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"25px 25px 55px 55px");
assertEquals("25.0px 25.0px 55.0px 55.0px",
borderImageWidth.getCssValue());
}
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"25px 25px 25px 55px");
assertEquals("25.0px 25.0px 25.0px 55.0px",
borderImageWidth.getCssValue());
}
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"25px 25px 55px 55px");
assertEquals("25.0px 25.0px 55.0px 55.0px",
borderImageWidth.getCssValue());
}
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"25px 25px 25px 25px");
assertEquals("25.0px", borderImageWidth.getCssValue());
}
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"35px 25px 45px 25px ");
assertEquals("35.0px 25.0px 45.0px",
borderImageWidth.getCssValue());
}
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"35px 25px 35px 25px ");
assertEquals("35.0px 25.0px", borderImageWidth.getCssValue());
}
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#BorderImageWidth(java.lang.String)}
* .
*/
@Test
public void testBorderImageWidthString5() {
BorderImageWidth borderImageWidth = new BorderImageWidth(
BorderImageWidth.AUTO);
assertEquals(BorderImageWidth.AUTO, borderImageWidth.getCssValue());
assertNull(borderImageWidth.getTop());
assertNull(borderImageWidth.getRight());
assertNull(borderImageWidth.getBottom());
assertNull(borderImageWidth.getLeft());
assertNull(borderImageWidth.getTopUnit());
assertNull(borderImageWidth.getRightUnit());
assertNull(borderImageWidth.getBottomUnit());
assertNull(borderImageWidth.getLeftUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#BorderImageWidth(com.webfirmframework.wffweb.css.css3.BorderImageWidth)}
* .
*/
@Test
public void testBorderImageWidthBorderImageWidth() {
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
new BorderImageWidth("35px 25px 35px 25px "));
assertEquals("35.0px 25.0px", borderImageWidth.getCssValue());
}
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#BorderImageWidth(float)}
* .
*/
@Test
public void testBorderImageWidthFloat() {
BorderImageWidth borderImageWidth = new BorderImageWidth(55F);
assertEquals("55.0%", borderImageWidth.getCssValue());
assertNotNull(borderImageWidth.getTop());
assertNotNull(borderImageWidth.getRight());
assertNotNull(borderImageWidth.getBottom());
assertNotNull(borderImageWidth.getLeft());
assertTrue(55F == borderImageWidth.getTop());
assertTrue(55F == borderImageWidth.getRight());
assertTrue(55F == borderImageWidth.getBottom());
assertTrue(55F == borderImageWidth.getLeft());
assertNotNull(borderImageWidth.getTopUnit());
assertNotNull(borderImageWidth.getRightUnit());
assertNotNull(borderImageWidth.getBottomUnit());
assertNotNull(borderImageWidth.getLeftUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getTopUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getRightUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getBottomUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getLeftUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#BorderImageWidth(float, com.webfirmframework.wffweb.css.CssLengthUnit)}
* .
*/
@Test
public void testBorderImageWidthFloatCssLengthUnit() {
BorderImageWidth borderImageWidth = new BorderImageWidth(55F,
CssLengthUnit.EM);
assertEquals("55.0em", borderImageWidth.getCssValue());
assertNotNull(borderImageWidth.getTop());
assertNotNull(borderImageWidth.getRight());
assertNotNull(borderImageWidth.getBottom());
assertNotNull(borderImageWidth.getLeft());
assertTrue(55F == borderImageWidth.getTop());
assertTrue(55F == borderImageWidth.getRight());
assertTrue(55F == borderImageWidth.getBottom());
assertTrue(55F == borderImageWidth.getLeft());
assertNotNull(borderImageWidth.getTopUnit());
assertNotNull(borderImageWidth.getRightUnit());
assertNotNull(borderImageWidth.getBottomUnit());
assertNotNull(borderImageWidth.getLeftUnit());
assertEquals(CssLengthUnit.EM, borderImageWidth.getTopUnit());
assertEquals(CssLengthUnit.EM, borderImageWidth.getRightUnit());
assertEquals(CssLengthUnit.EM, borderImageWidth.getBottomUnit());
assertEquals(CssLengthUnit.EM, borderImageWidth.getLeftUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#setPercent(float)}
* .
*/
@Test
public void testSetPercent() {
BorderImageWidth borderImageWidth = new BorderImageWidth();
borderImageWidth.setPercent(55F);
assertEquals("55.0%", borderImageWidth.getCssValue());
assertNotNull(borderImageWidth.getTop());
assertNotNull(borderImageWidth.getRight());
assertNotNull(borderImageWidth.getBottom());
assertNotNull(borderImageWidth.getLeft());
assertTrue(55F == borderImageWidth.getTop());
assertTrue(55F == borderImageWidth.getRight());
assertTrue(55F == borderImageWidth.getBottom());
assertTrue(55F == borderImageWidth.getLeft());
assertNotNull(borderImageWidth.getTopUnit());
assertNotNull(borderImageWidth.getRightUnit());
assertNotNull(borderImageWidth.getBottomUnit());
assertNotNull(borderImageWidth.getLeftUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getTopUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getRightUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getBottomUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getLeftUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#getCssName()}
* .
*/
@Test
public void testGetCssName() {
assertEquals(CssNameConstants.BORDER_IMAGE_WIDTH,
new BorderImageWidth().getCssName());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#getCssValue()}
* .
*/
@Test
public void testGetCssValue() {
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"25px 25px 55px 55px");
assertEquals("25.0px 25.0px 55.0px 55.0px",
borderImageWidth.getCssValue());
}
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"25px 25px 25px 55px");
assertEquals("25.0px 25.0px 25.0px 55.0px",
borderImageWidth.getCssValue());
}
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"25px 25px 55px 55px");
assertEquals("25.0px 25.0px 55.0px 55.0px",
borderImageWidth.getCssValue());
}
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"25px 25px 25px 25px");
assertEquals("25.0px", borderImageWidth.getCssValue());
}
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"35px 25px 45px 25px ");
assertEquals("35.0px 25.0px 45.0px",
borderImageWidth.getCssValue());
}
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"35px 25px 35px 25px ");
assertEquals("35.0px 25.0px", borderImageWidth.getCssValue());
}
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#toString()}.
*/
@Test
public void testToString() {
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"25px 25px 55px 55px");
assertEquals(
CssNameConstants.BORDER_IMAGE_WIDTH
+ ": 25.0px 25.0px 55.0px 55.0px",
borderImageWidth.toString());
}
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"25px 25px 25px 55px");
assertEquals(
CssNameConstants.BORDER_IMAGE_WIDTH
+ ": 25.0px 25.0px 25.0px 55.0px",
borderImageWidth.toString());
}
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"25px 25px 55px 55px");
assertEquals(
CssNameConstants.BORDER_IMAGE_WIDTH
+ ": 25.0px 25.0px 55.0px 55.0px",
borderImageWidth.toString());
}
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"25px 25px 25px 25px");
assertEquals(CssNameConstants.BORDER_IMAGE_WIDTH + ": 25.0px",
borderImageWidth.toString());
}
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"35px 25px 45px 25px ");
assertEquals(
CssNameConstants.BORDER_IMAGE_WIDTH
+ ": 35.0px 25.0px 45.0px",
borderImageWidth.toString());
}
{
BorderImageWidth borderImageWidth = new BorderImageWidth(
"35px 25px 35px 25px ");
assertEquals(
CssNameConstants.BORDER_IMAGE_WIDTH + ": 35.0px 25.0px",
borderImageWidth.toString());
}
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#setCssValue(java.lang.String)}
* .
*/
@Test
public void testSetCssValueString() {
BorderImageWidth borderImageWidth = new BorderImageWidth();
borderImageWidth.setCssValue("55%");
assertEquals("55.0%", borderImageWidth.getCssValue());
assertNotNull(borderImageWidth.getTop());
assertNotNull(borderImageWidth.getRight());
assertNotNull(borderImageWidth.getBottom());
assertNotNull(borderImageWidth.getLeft());
assertTrue(55F == borderImageWidth.getTop());
assertTrue(55F == borderImageWidth.getRight());
assertTrue(55F == borderImageWidth.getBottom());
assertTrue(55F == borderImageWidth.getLeft());
assertNotNull(borderImageWidth.getTopUnit());
assertNotNull(borderImageWidth.getRightUnit());
assertNotNull(borderImageWidth.getBottomUnit());
assertNotNull(borderImageWidth.getLeftUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getTopUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getRightUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getBottomUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getLeftUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#setAsInitial()}
* .
*/
@Test
public void testSetAsInitial() {
BorderImageWidth borderImageWidth = new BorderImageWidth();
borderImageWidth.setCssValue("55%");
assertEquals("55.0%", borderImageWidth.getCssValue());
assertNotNull(borderImageWidth.getTop());
assertNotNull(borderImageWidth.getRight());
assertNotNull(borderImageWidth.getBottom());
assertNotNull(borderImageWidth.getLeft());
assertTrue(55F == borderImageWidth.getTop());
assertTrue(55F == borderImageWidth.getRight());
assertTrue(55F == borderImageWidth.getBottom());
assertTrue(55F == borderImageWidth.getLeft());
assertNotNull(borderImageWidth.getTopUnit());
assertNotNull(borderImageWidth.getRightUnit());
assertNotNull(borderImageWidth.getBottomUnit());
assertNotNull(borderImageWidth.getLeftUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getTopUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getRightUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getBottomUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getLeftUnit());
borderImageWidth.setAsInitial();
assertNull(borderImageWidth.getTop());
assertNull(borderImageWidth.getRight());
assertNull(borderImageWidth.getBottom());
assertNull(borderImageWidth.getLeft());
assertNull(borderImageWidth.getTopUnit());
assertNull(borderImageWidth.getRightUnit());
assertNull(borderImageWidth.getBottomUnit());
assertNull(borderImageWidth.getLeftUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#setAsInherit()}
* .
*/
@Test
public void testSetAsInherit() {
BorderImageWidth borderImageWidth = new BorderImageWidth();
borderImageWidth.setCssValue("55%");
assertEquals("55.0%", borderImageWidth.getCssValue());
assertNotNull(borderImageWidth.getTop());
assertNotNull(borderImageWidth.getRight());
assertNotNull(borderImageWidth.getBottom());
assertNotNull(borderImageWidth.getLeft());
assertTrue(55F == borderImageWidth.getTop());
assertTrue(55F == borderImageWidth.getRight());
assertTrue(55F == borderImageWidth.getBottom());
assertTrue(55F == borderImageWidth.getLeft());
assertNotNull(borderImageWidth.getTopUnit());
assertNotNull(borderImageWidth.getRightUnit());
assertNotNull(borderImageWidth.getBottomUnit());
assertNotNull(borderImageWidth.getLeftUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getTopUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getRightUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getBottomUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getLeftUnit());
borderImageWidth.setAsInherit();
assertNull(borderImageWidth.getTop());
assertNull(borderImageWidth.getRight());
assertNull(borderImageWidth.getBottom());
assertNull(borderImageWidth.getLeft());
assertNull(borderImageWidth.getTopUnit());
assertNull(borderImageWidth.getRightUnit());
assertNull(borderImageWidth.getBottomUnit());
assertNull(borderImageWidth.getLeftUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#setAsAuto()}
* .
*/
@Test
public void testSetAsAuto() {
BorderImageWidth borderImageWidth = new BorderImageWidth();
borderImageWidth.setCssValue("55%");
assertEquals("55.0%", borderImageWidth.getCssValue());
assertNotNull(borderImageWidth.getTop());
assertNotNull(borderImageWidth.getRight());
assertNotNull(borderImageWidth.getBottom());
assertNotNull(borderImageWidth.getLeft());
assertTrue(55F == borderImageWidth.getTop());
assertTrue(55F == borderImageWidth.getRight());
assertTrue(55F == borderImageWidth.getBottom());
assertTrue(55F == borderImageWidth.getLeft());
assertNotNull(borderImageWidth.getTopUnit());
assertNotNull(borderImageWidth.getRightUnit());
assertNotNull(borderImageWidth.getBottomUnit());
assertNotNull(borderImageWidth.getLeftUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getTopUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getRightUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getBottomUnit());
assertEquals(CssLengthUnit.PER, borderImageWidth.getLeftUnit());
borderImageWidth.setAsAuto();
assertNull(borderImageWidth.getTop());
assertNull(borderImageWidth.getRight());
assertNull(borderImageWidth.getBottom());
assertNull(borderImageWidth.getLeft());
assertNull(borderImageWidth.getTopUnit());
assertNull(borderImageWidth.getRightUnit());
assertNull(borderImageWidth.getBottomUnit());
assertNull(borderImageWidth.getLeftUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#setBorderImageTopRightBottomLeft(java.lang.Float, java.lang.Float, java.lang.Float, java.lang.Float, com.webfirmframework.wffweb.css.CssLengthUnit)}
* .
*/
@Test
public void testSetBorderImageTopRightBottomLeftFloatFloatFloatFloatCssLengthUnit() {
BorderImageWidth borderImageWidth = new BorderImageWidth();
borderImageWidth.setBorderImageTopRightBottomLeft(5F, 10F, 15F, 20F,
CssLengthUnit.IN);
assertEquals("5.0in 10.0in 15.0in 20.0in",
borderImageWidth.getCssValue());
assertNotNull(borderImageWidth.getTop());
assertNotNull(borderImageWidth.getRight());
assertNotNull(borderImageWidth.getBottom());
assertNotNull(borderImageWidth.getLeft());
assertTrue(5F == borderImageWidth.getTop());
assertTrue(10F == borderImageWidth.getRight());
assertTrue(15F == borderImageWidth.getBottom());
assertTrue(20F == borderImageWidth.getLeft());
assertNotNull(borderImageWidth.getTopUnit());
assertNotNull(borderImageWidth.getRightUnit());
assertNotNull(borderImageWidth.getBottomUnit());
assertNotNull(borderImageWidth.getLeftUnit());
assertEquals(CssLengthUnit.IN, borderImageWidth.getTopUnit());
assertEquals(CssLengthUnit.IN, borderImageWidth.getRightUnit());
assertEquals(CssLengthUnit.IN, borderImageWidth.getBottomUnit());
assertEquals(CssLengthUnit.IN, borderImageWidth.getLeftUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#setBorderImageTopRightBottomLeft(java.lang.Float, com.webfirmframework.wffweb.css.CssLengthUnit, java.lang.Float, com.webfirmframework.wffweb.css.CssLengthUnit, java.lang.Float, com.webfirmframework.wffweb.css.CssLengthUnit, java.lang.Float, com.webfirmframework.wffweb.css.CssLengthUnit)}
* .
*/
@Test
public void testSetBorderImageTopRightBottomLeftFloatCssLengthUnitFloatCssLengthUnitFloatCssLengthUnitFloatCssLengthUnit() {
BorderImageWidth borderImageWidth = new BorderImageWidth();
borderImageWidth.setBorderImageTopRightBottomLeft(5F, CssLengthUnit.CH,
10F, CssLengthUnit.CM, 15F, CssLengthUnit.EM, 20F,
CssLengthUnit.EX);
assertEquals("5.0ch 10.0cm 15.0em 20.0ex",
borderImageWidth.getCssValue());
assertNotNull(borderImageWidth.getTop());
assertNotNull(borderImageWidth.getRight());
assertNotNull(borderImageWidth.getBottom());
assertNotNull(borderImageWidth.getLeft());
assertTrue(5F == borderImageWidth.getTop());
assertTrue(10F == borderImageWidth.getRight());
assertTrue(15F == borderImageWidth.getBottom());
assertTrue(20F == borderImageWidth.getLeft());
assertNotNull(borderImageWidth.getTopUnit());
assertNotNull(borderImageWidth.getRightUnit());
assertNotNull(borderImageWidth.getBottomUnit());
assertNotNull(borderImageWidth.getLeftUnit());
assertEquals(CssLengthUnit.CH, borderImageWidth.getTopUnit());
assertEquals(CssLengthUnit.CM, borderImageWidth.getRightUnit());
assertEquals(CssLengthUnit.EM, borderImageWidth.getBottomUnit());
assertEquals(CssLengthUnit.EX, borderImageWidth.getLeftUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#setTop(java.lang.Float, com.webfirmframework.wffweb.css.CssLengthUnit)}
* .
*/
@Test
public void testSetTop() {
BorderImageWidth borderImageWidth = new BorderImageWidth();
borderImageWidth.setBorderImageTopRightBottomLeft(5F, CssLengthUnit.CH,
10F, CssLengthUnit.CM, 15F, CssLengthUnit.EM, 20F,
CssLengthUnit.EX);
assertEquals("5.0ch 10.0cm 15.0em 20.0ex",
borderImageWidth.getCssValue());
assertNotNull(borderImageWidth.getTop());
assertNotNull(borderImageWidth.getRight());
assertNotNull(borderImageWidth.getBottom());
assertNotNull(borderImageWidth.getLeft());
assertTrue(5F == borderImageWidth.getTop());
assertTrue(10F == borderImageWidth.getRight());
assertTrue(15F == borderImageWidth.getBottom());
assertTrue(20F == borderImageWidth.getLeft());
assertNotNull(borderImageWidth.getTopUnit());
assertNotNull(borderImageWidth.getRightUnit());
assertNotNull(borderImageWidth.getBottomUnit());
assertNotNull(borderImageWidth.getLeftUnit());
assertEquals(CssLengthUnit.CH, borderImageWidth.getTopUnit());
assertEquals(CssLengthUnit.CM, borderImageWidth.getRightUnit());
assertEquals(CssLengthUnit.EM, borderImageWidth.getBottomUnit());
assertEquals(CssLengthUnit.EX, borderImageWidth.getLeftUnit());
borderImageWidth.setTop(55F, CssLengthUnit.PT);
assertEquals("55.0pt 10.0cm 15.0em 20.0ex",
borderImageWidth.getCssValue());
assertEquals(CssLengthUnit.PT, borderImageWidth.getTopUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#setRight(java.lang.Float, com.webfirmframework.wffweb.css.CssLengthUnit)}
* .
*/
@Test
public void testSetRight() {
BorderImageWidth borderImageWidth = new BorderImageWidth();
borderImageWidth.setBorderImageTopRightBottomLeft(5F, CssLengthUnit.CH,
10F, CssLengthUnit.CM, 15F, CssLengthUnit.EM, 20F,
CssLengthUnit.EX);
assertEquals("5.0ch 10.0cm 15.0em 20.0ex",
borderImageWidth.getCssValue());
assertNotNull(borderImageWidth.getTop());
assertNotNull(borderImageWidth.getRight());
assertNotNull(borderImageWidth.getBottom());
assertNotNull(borderImageWidth.getLeft());
assertTrue(5F == borderImageWidth.getTop());
assertTrue(10F == borderImageWidth.getRight());
assertTrue(15F == borderImageWidth.getBottom());
assertTrue(20F == borderImageWidth.getLeft());
assertNotNull(borderImageWidth.getTopUnit());
assertNotNull(borderImageWidth.getRightUnit());
assertNotNull(borderImageWidth.getBottomUnit());
assertNotNull(borderImageWidth.getLeftUnit());
assertEquals(CssLengthUnit.CH, borderImageWidth.getTopUnit());
assertEquals(CssLengthUnit.CM, borderImageWidth.getRightUnit());
assertEquals(CssLengthUnit.EM, borderImageWidth.getBottomUnit());
assertEquals(CssLengthUnit.EX, borderImageWidth.getLeftUnit());
borderImageWidth.setRight(55F, CssLengthUnit.PT);
assertEquals("5.0ch 55.0pt 15.0em 20.0ex",
borderImageWidth.getCssValue());
assertEquals(CssLengthUnit.PT, borderImageWidth.getRightUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#setBottom(java.lang.Float, com.webfirmframework.wffweb.css.CssLengthUnit)}
* .
*/
@Test
public void testSetBottom() {
BorderImageWidth borderImageWidth = new BorderImageWidth();
borderImageWidth.setBorderImageTopRightBottomLeft(5F, CssLengthUnit.CH,
10F, CssLengthUnit.CM, 15F, CssLengthUnit.EM, 20F,
CssLengthUnit.EX);
assertEquals("5.0ch 10.0cm 15.0em 20.0ex",
borderImageWidth.getCssValue());
assertNotNull(borderImageWidth.getTop());
assertNotNull(borderImageWidth.getRight());
assertNotNull(borderImageWidth.getBottom());
assertNotNull(borderImageWidth.getLeft());
assertTrue(5F == borderImageWidth.getTop());
assertTrue(10F == borderImageWidth.getRight());
assertTrue(15F == borderImageWidth.getBottom());
assertTrue(20F == borderImageWidth.getLeft());
assertNotNull(borderImageWidth.getTopUnit());
assertNotNull(borderImageWidth.getRightUnit());
assertNotNull(borderImageWidth.getBottomUnit());
assertNotNull(borderImageWidth.getLeftUnit());
assertEquals(CssLengthUnit.CH, borderImageWidth.getTopUnit());
assertEquals(CssLengthUnit.CM, borderImageWidth.getRightUnit());
assertEquals(CssLengthUnit.EM, borderImageWidth.getBottomUnit());
assertEquals(CssLengthUnit.EX, borderImageWidth.getLeftUnit());
borderImageWidth.setBottom(55F, CssLengthUnit.PT);
assertEquals("5.0ch 10.0cm 55.0pt 20.0ex",
borderImageWidth.getCssValue());
assertEquals(CssLengthUnit.PT, borderImageWidth.getBottomUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#setLeft(java.lang.Float, com.webfirmframework.wffweb.css.CssLengthUnit)}
* .
*/
@Test
public void testSetLeft() {
BorderImageWidth borderImageWidth = new BorderImageWidth();
borderImageWidth.setBorderImageTopRightBottomLeft(5F, CssLengthUnit.CH,
10F, CssLengthUnit.CM, 15F, CssLengthUnit.EM, 20F,
CssLengthUnit.EX);
assertEquals("5.0ch 10.0cm 15.0em 20.0ex",
borderImageWidth.getCssValue());
assertNotNull(borderImageWidth.getTop());
assertNotNull(borderImageWidth.getRight());
assertNotNull(borderImageWidth.getBottom());
assertNotNull(borderImageWidth.getLeft());
assertTrue(5F == borderImageWidth.getTop());
assertTrue(10F == borderImageWidth.getRight());
assertTrue(15F == borderImageWidth.getBottom());
assertTrue(20F == borderImageWidth.getLeft());
assertNotNull(borderImageWidth.getTopUnit());
assertNotNull(borderImageWidth.getRightUnit());
assertNotNull(borderImageWidth.getBottomUnit());
assertNotNull(borderImageWidth.getLeftUnit());
assertEquals(CssLengthUnit.CH, borderImageWidth.getTopUnit());
assertEquals(CssLengthUnit.CM, borderImageWidth.getRightUnit());
assertEquals(CssLengthUnit.EM, borderImageWidth.getBottomUnit());
assertEquals(CssLengthUnit.EX, borderImageWidth.getLeftUnit());
borderImageWidth.setLeft(55F, CssLengthUnit.PT);
assertEquals("5.0ch 10.0cm 15.0em 55.0pt",
borderImageWidth.getCssValue());
assertEquals(CssLengthUnit.PT, borderImageWidth.getLeftUnit());
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#getTop()}.
*/
/*
* @Test public void testGetTop() { fail("Not yet implemented"); }
*//**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#getTopUnit()}
* .
*/
/*
* @Test public void testGetTopUnit() { fail("Not yet implemented"); }
*//**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#getRight()}
* .
*/
/*
* @Test public void testGetRight() { fail("Not yet implemented"); }
*//**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#getRightUnit()}
* .
*/
/*
* @Test public void testGetRightUnit() { fail("Not yet implemented"); }
*//**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#getBottom()}
* .
*/
/*
* @Test public void testGetBottom() { fail("Not yet implemented"); }
*//**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#getBottomUnit()}
* .
*/
/*
* @Test public void testGetBottomUnit() { fail("Not yet implemented"); }
*//**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#getLeft()}
* .
*/
/*
* @Test public void testGetLeft() { fail("Not yet implemented"); }
*//**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#getLeftUnit()}
* .
*/
/*
* @Test public void testGetLeftUnit() { fail("Not yet implemented"); }
*/
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#getProducedCssValue(java.lang.Float, com.webfirmframework.wffweb.css.CssLengthUnit, java.lang.Float, com.webfirmframework.wffweb.css.CssLengthUnit, java.lang.Float, com.webfirmframework.wffweb.css.CssLengthUnit, java.lang.Float, com.webfirmframework.wffweb.css.CssLengthUnit)}
* .
*/
@Test
public void testGetProducedCssValue() {
assertEquals("5.0ch 10.0cm 15.0em 20.0ex",
BorderImageWidth.getProducedCssValue(5F, CssLengthUnit.CH, 10F,
CssLengthUnit.CM, 15F, CssLengthUnit.EM, 20F,
CssLengthUnit.EX));
assertEquals("5.0px",
BorderImageWidth.getProducedCssValue(5F, CssLengthUnit.PX, 5F,
CssLengthUnit.PX, 5F, CssLengthUnit.PX, 5F,
CssLengthUnit.PX));
assertEquals("5.0px 15.0px",
BorderImageWidth.getProducedCssValue(5F, CssLengthUnit.PX, 15F,
CssLengthUnit.PX, 5F, CssLengthUnit.PX, 15F,
CssLengthUnit.PX));
assertEquals("5.0px 15.0px 25.0px",
BorderImageWidth.getProducedCssValue(5F, CssLengthUnit.PX, 15F,
CssLengthUnit.PX, 25F, CssLengthUnit.PX, 15F,
CssLengthUnit.PX));
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#isValid(java.lang.String)}
* .
*/
@Test
public void testIsValid1() {
{
final boolean valid = BorderImageWidth.isValid("45px");
assertTrue(valid);
assertTrue(BorderImageWidth.isValid("55"));
}
{
final boolean valid = BorderImageWidth.isValid("45em 45px");
assertTrue(valid);
final boolean invalid = BorderImageWidth.isValid("45em dfd 45px");
assertFalse(invalid);
}
{
final boolean valid = BorderImageWidth.isValid("45%");
assertTrue(valid);
final boolean invalid = BorderImageWidth.isValid("45 px");
assertFalse(invalid);
}
{
final boolean valid = BorderImageWidth.isValid("45em");
assertTrue(valid);
final boolean invalid = BorderImageWidth.isValid("45sem");
assertFalse(invalid);
}
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#isValid(java.lang.String)}
* .
*/
@Test
public void testIsValid2() {
{
final boolean valid = BorderImageWidth.isValid("45rem");
assertTrue(valid);
}
{
final boolean valid = BorderImageWidth.isValid("45rem auto");
assertTrue(valid);
}
{
final boolean valid = BorderImageWidth.isValid("auto auto");
assertTrue(valid);
}
{
final boolean valid = BorderImageWidth.isValid("auto auto auto");
assertTrue(valid);
}
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#isValid(java.lang.String)}
* .
*/
@Test
public void testIsValid3() {
{
final boolean valid = BorderImageWidth
.isValid("auto auto auto auto");
assertTrue(valid);
}
{
final boolean valid = BorderImageWidth
.isValid("auto auto auto 34px");
assertTrue(valid);
}
{
final boolean valid = BorderImageWidth
.isValid("auto auto 45px auto");
assertTrue(valid);
}
{
final boolean valid = BorderImageWidth
.isValid("auto auto 45px 45px");
assertTrue(valid);
}
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#isValid(java.lang.String)}
* .
*/
@Test
public void testIsValid4() {
{
final boolean valid = BorderImageWidth
.isValid("45px 45px auto auto");
assertTrue(valid);
}
{
final boolean valid = BorderImageWidth.isValid("45px auto 45px");
assertTrue(valid);
}
{
final boolean valid = BorderImageWidth
.isValid("45px 45px 45px auto");
assertTrue(valid);
}
{
final boolean valid = BorderImageWidth
.isValid("auto 45px 45px 45px");
assertTrue(valid);
}
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#isValid(java.lang.String)}
* .
*/
@Test
public void testIsValid5() {
{
final boolean valid = BorderImageWidth
.isValid("auto 15px auto auto");
assertTrue(valid);
}
{
final boolean valid = BorderImageWidth
.isValid("auto 15px 15px auto");
assertTrue(valid);
}
{
final boolean valid = BorderImageWidth
.isValid("15px 15px auto auto");
assertTrue(valid);
}
{
final boolean valid = BorderImageWidth
.isValid("12px auto auto auto");
assertTrue(valid);
}
}
/**
* Test method for
* {@link com.webfirmframework.wffweb.css.css3.BorderImageWidth#hasPredefinedConstantValue()}
* .
*/
@Test
public void testHasPredefinedConstantValue() {
assertTrue(new BorderImageWidth(BorderImageWidth.INHERIT)
.hasPredefinedConstantValue());
assertTrue(new BorderImageWidth(BorderImageWidth.INITIAL)
.hasPredefinedConstantValue());
assertTrue(new BorderImageWidth(BorderImageWidth.AUTO)
.hasPredefinedConstantValue());
assertFalse(new BorderImageWidth().hasPredefinedConstantValue());
assertFalse(
new BorderImageWidth("auto 10px").hasPredefinedConstantValue());
}
}
| 38.171028 | 357 | 0.642925 |
e3205f8494492d5cb6bdcf583e00db1ea4b4a154 | 1,710 | package edu.bu.cs673.stockportfolio.integrationtests.signup;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
/**********************************************************************************************************************
* A Selenium Page Object representing the Signup flow.
*
* "As a user, I can create a new account in order to login to the application."
*********************************************************************************************************************/
public class SignupPage {
@FindBy(id = "inputEmail")
private WebElement email;
@FindBy(id = "inputUsername")
private WebElement username;
@FindBy(id = "inputPassword")
private WebElement password;
@FindBy(id = "submitButton")
private WebElement submitButton;
@FindBy(id = "error-msg")
private WebElement errorMsg;
@FindBy(xpath = "//a")
private WebElement xpath;
/**
* Constructor starts the process of allowing Selenium to automatically process the element selectors.
*
* @param driver A browser driver instance.
*/
public SignupPage(WebDriver driver) {
PageFactory.initElements(driver, this);
}
public void signup(String email, String username, String password) {
this.email.sendKeys(email);
this.username.sendKeys(username);
this.password.sendKeys(password);
this.submitButton.click();
}
public boolean isErrorMessageDisplayed() {
return errorMsg.isDisplayed();
}
public void clickSignup() {
this.xpath.click();
}
}
| 30 | 119 | 0.588889 |
9e6c9391a4e109ca631814f0b4362890ec9d3233 | 1,472 | package dk.mmj.eevhe;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.glassfish.jersey.client.JerseyWebTarget;
import org.junit.After;
import org.junit.Test;
import javax.ws.rs.core.Response;
import java.nio.file.Files;
import java.nio.file.Paths;
import static dk.mmj.eevhe.client.SSLHelper.configureWebTarget;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class TestMain {
private static final Logger logger = LogManager.getLogger(TestMain.class);
@Test
public void testBulletinBoard() throws InterruptedException {
Main.main(new String[]{"--configuration", "--bb_peer_addresses", "-1_https://localhost:18081"});
// TODO: Fix:
Thread thread = new Thread(() -> Main.main(new String[]{"--bulletinBoardPeer", "--id=1"}));
thread.start();
Thread.sleep(5_000);
JerseyWebTarget target = configureWebTarget(logger, "https://localhost:8080");
Response resp = target.path("type").request().get();
assertEquals("BulletinBoard did not return 200 on type request", 200, resp.getStatus());
assertTrue("Wrong type returned", resp.readEntity(String.class).contains("<b>ServerType:</b> Bulletin Board Peer"));
}
@After
public void tearDown() throws Exception {
Files.delete(Paths.get("./conf/BB_peer1.zip"));
Files.delete(Paths.get("./conf/BB_input.json"));
}
}
| 32 | 124 | 0.700408 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.