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
|
---|---|---|---|---|---|
a68f66e2b9cfad2e00028b1a6fa28deaf3571988 | 603 | package org.simpleflatmapper.reflect.test.asm.sample;
import org.simpleflatmapper.reflect.Setter;
import org.simpleflatmapper.reflect.primitive.IntSetter;
import org.simpleflatmapper.test.beans.DbPrimitiveObjectFields;
public class PrimitiveIntFieldSetter implements Setter<DbPrimitiveObjectFields, Integer>, IntSetter<DbPrimitiveObjectFields> {
@Override
public void setInt(DbPrimitiveObjectFields target, int value) throws Exception {
target.pInt = value;
}
@Override
public void set(DbPrimitiveObjectFields target, Integer value) throws Exception {
target.pInt = value.intValue();
}
}
| 30.15 | 126 | 0.819237 |
373e06dd2b9bd665a21bef1ece683e5b78186cca | 265 | package com.yeungeek.router;
import com.yeungeek.router.annotation.RouterUri;
/**
* @author yangjian
* @date 2018/11/16
*/
public interface RouterService {
@RouterUri(value = "router://com.yeungeek.router.firstactivity")
void startFirstActivity();
}
| 17.666667 | 68 | 0.724528 |
4241558ddc19e84147d4540d924fa8397e0b2fda | 8,881 | package com.kaidongyuan.app.kdydriver.adapter;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.kaidongyuan.app.basemodule.ui.fragment.BaseLifecyclePrintFragment;
import com.kaidongyuan.app.kdydriver.R;
import com.kaidongyuan.app.kdydriver.bean.order.Order;
import com.kaidongyuan.app.kdydriver.ui.activity.OrderDetailActivity;
import com.kaidongyuan.app.kdydriver.ui.fragment.OrderListFragment;
import java.util.ArrayList;
/**
* Created by Administrator on 2016/6/22.
*/
public class OrderListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_ITEM =0; //普通Item View
private static final int TYPE_FOOTER = 1; //底部FootView
public static final int LOADING_MORE=10; //上拉加载更多
public static final int NO_MORE=11; //无更多数据
public int loadState=10;//上拉加载状态值
private ArrayList<Order> morderlist;
private OrderListFragment orderListFragment;
public OrderListAdapter(ArrayList<Order> morderlist, OrderListFragment orderListFragment) {
this.morderlist = morderlist;
this.orderListFragment=orderListFragment;
}
public ArrayList<Order> getMorderlist() {
return morderlist;
}
public void setMorderlist(ArrayList<Order> morderlist) {
this.morderlist = morderlist;
OrderListAdapter.this.notifyDataSetChanged();
}
@Override
public int getItemViewType(int position) {
if (position+1==getItemCount()){
return TYPE_FOOTER;
}else {
return TYPE_ITEM;
}
}
@Override
public int getItemCount() {
return morderlist.size()+1;//预加上底部FootView
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType==TYPE_FOOTER){
View view= LayoutInflater.from(orderListFragment.getMContext()).inflate(R.layout.more_item_orderlist,parent,false);
MyFootViewHolder myfootViewHolder=new MyFootViewHolder(view);
return myfootViewHolder;
}else if (viewType==TYPE_ITEM){
View itemview=LayoutInflater.from(orderListFragment.getMContext()).inflate(R.layout.order_item_cardview,parent,false);
MyViewHolder myViewHolder=new MyViewHolder(itemview);
return myViewHolder;
}
return null;
}
@Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if (holder instanceof MyViewHolder){
final Order order=morderlist.get(position);
((MyViewHolder) holder).tv_order_no.setText(order.getORD_NO());
((MyViewHolder) holder).tv_client_order_no.setText(order.getORD_NO_CLIENT());
((MyViewHolder) holder).tv_shipment_no.setText(order.getTMS_SHIPMENT_NO());
((MyViewHolder)holder).tv_client_order_name.setText(order.getORD_TO_NAME().trim());
((MyViewHolder) holder).tv_date_issue.setText(order.getTMS_DATE_ISSUE());
((MyViewHolder) holder).tv_ord_issue_qty.setText(order.getORD_ISSUE_QTY());
((MyViewHolder) holder).tv_order_workFlow.setText(order.getORD_WORKFLOW());
((MyViewHolder) holder).tv_driver_pay.setText(order.getDRIVER_PAY());
((MyViewHolder) holder).tv_order_to_address.setText(order.getORD_TO_ADDRESS().trim());
if (order.getAUDIT_FLAG().equals("Y")&&!order.getERROR_FLAG().equals("Y")){
((MyViewHolder) holder).tv_shipmentcost_state.setText("已结费");
((MyViewHolder) holder).ll_shipmentcost_state.setVisibility(View.VISIBLE);
}else if (order.getDRIVER_PAY().equals("已交付")&&order.getERROR_FLAG().equals("Y")){
((MyViewHolder) holder).tv_shipmentcost_state.setText("结费异常");
((MyViewHolder) holder).ll_shipmentcost_state.setVisibility(View.VISIBLE);
}else if (order.getDRIVER_PAY().equals("已交付")&&order.getAUDIT_FLAG().equals("N")){
((MyViewHolder) holder).tv_shipmentcost_state.setText("未结费");
((MyViewHolder) holder).ll_shipmentcost_state.setVisibility(View.VISIBLE);
}else {
((MyViewHolder) holder).ll_shipmentcost_state.setVisibility(View.GONE);
}
// ((MyViewHolder) holder).btn_order_detail.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Intent intent = new Intent(finishedFragment.getMContext(), OrderDetailActivity.class);
// intent.putExtra("order_id", order.getIDX());
// finishedFragment.startActivity(intent);
// }
// });
((MyViewHolder) holder).mcardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(orderListFragment.getMContext(), OrderDetailActivity.class);
intent.putExtra("order_id", order.getORD_IDX());
// intent.putExtra("ispayed",true);
orderListFragment.startActivity(intent);
}
});
}else if (holder instanceof MyFootViewHolder){
switch (loadState){
case LOADING_MORE:
((MyFootViewHolder) holder).moreProgressbar.setVisibility(View.VISIBLE);
((MyFootViewHolder) holder).moreTextview.setText("加载更多订单...");
break;
case NO_MORE:
((MyFootViewHolder) holder).moreProgressbar.setVisibility(View.GONE);
((MyFootViewHolder) holder).moreTextview.setText("无更多数据");
break;
}
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
CardView mcardView;
public LinearLayout ll_shipmentcost_state;
//订单号,装运编号,出库时间,起运点名称,司机名,到达点名称,到达点地址,订单货物总数,订单流程,订单交付状态,装运结费状态
TextView tv_order_no,tv_client_order_no,tv_shipment_no,tv_client_order_name,tv_date_issue,tv_order_to_address,
tv_ord_issue_qty,tv_order_workFlow,tv_driver_pay,tv_shipmentcost_state;
Button btn_order_detail,btn_driver_pay;//查看订单详情,司机交付订单
public MyViewHolder(View itemView) {
super(itemView);
mcardView= (CardView) itemView.findViewById(R.id.cardView_order);
ll_shipmentcost_state= (LinearLayout) itemView.findViewById(R.id.ll_shipmentcost_state);
tv_order_no= (TextView) itemView.findViewById(R.id.tv_tms_order_no);
tv_client_order_no= (TextView) itemView.findViewById(R.id.tv_client_order_no);
tv_shipment_no= (TextView) itemView.findViewById(R.id.tv_tms_shipment_no);
tv_client_order_name= (TextView) itemView.findViewById(R.id.tv_client_order_name);
tv_shipmentcost_state= (TextView) itemView.findViewById(R.id.tv_shipmentcost_state);
tv_date_issue= (TextView) itemView.findViewById(R.id.tv_tms_date_issue);
tv_ord_issue_qty= (TextView) itemView.findViewById(R.id.tv_ord_issue_qty);
tv_order_workFlow= (TextView) itemView.findViewById(R.id.tv_ord_workflow);
tv_driver_pay= (TextView) itemView.findViewById(R.id.tv_driver_pay);
tv_order_to_address= (TextView) itemView.findViewById(R.id.tv_order_to_address);
// btn_order_detail= (Button) itemView.findViewById(R.id.btn_order_detail);
// btn_driver_pay= (Button) itemView.findViewById(R.id.btn_driver_pay);
}
}
class MyFootViewHolder extends RecyclerView.ViewHolder {
ProgressBar moreProgressbar;
TextView moreTextview;
public MyFootViewHolder(View itemView) {
super(itemView);
moreProgressbar= (ProgressBar) itemView.findViewById(R.id.progressBar_more_item);
moreTextview= (TextView) itemView.findViewById(R.id.tv_more_item);
}
}
}
| 48.266304 | 131 | 0.663777 |
b5a6b4dee692fb2566453f419fc40a419912a36c | 8,187 | package com.lyz.code.infinity.s2shc.verb;
import java.util.ArrayList;
import java.util.List;
import com.lyz.code.infinity.core.Verb;
import com.lyz.code.infinity.core.Writeable;
import com.lyz.code.infinity.domain.Domain;
import com.lyz.code.infinity.domain.Method;
import com.lyz.code.infinity.domain.Signature;
import com.lyz.code.infinity.domain.Type;
import com.lyz.code.infinity.domain.Var;
import com.lyz.code.infinity.generator.NamedStatementGenerator;
import com.lyz.code.infinity.generator.NamedStatementListGenerator;
import com.lyz.code.infinity.utils.InterVarUtil;
import com.lyz.code.infinity.utils.StringUtil;
import com.lyz.code.infinity.utils.WriteableUtil;
public class UpdateAll extends Verb{
@Override
public Method generateDaoImplMethod() {
Method method = new Method();
method.setStandardName("updateAll"+StringUtil.capFirst(this.domain.getPlural()));
method.setReturnType(new Type("boolean"));
method.setThrowException(true);
this.additionalImports.add(this.domain.getPackageToken()+"."+this.domain.getStandardName());
method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
List<Writeable> list = new ArrayList<Writeable>();
list.add(NamedStatementGenerator.getUpdateSqlStatement(1000L,2, this.domain,InterVarUtil.DB.query));
list.add(NamedStatementGenerator.getPrepareStatement(2000L,2, InterVarUtil.DB.ps, InterVarUtil.DB.query, InterVarUtil.DB.connection));
list.add(NamedStatementListGenerator.generatePsSetDomainFields(3000L, 2,this.domain, InterVarUtil.DB.ps));
list.add(NamedStatementGenerator.getPrepareStatementExcuteUpdate(4000L,2, InterVarUtil.DB.result, InterVarUtil.DB.ps));
list.add(NamedStatementListGenerator.generateResultReturnSuccess(5000L,2, InterVarUtil.DB.result));
method.setMethodStatementList(WriteableUtil.merge(list));
return method;
}
@Override
public Method generateDaoMethodDefinition() {
Method method = new Method();
method.setStandardName("updateAll"+StringUtil.capFirst(this.domain.getPlural()));
method.setReturnType(new Type("boolean"));
method.setThrowException(true);
this.additionalImports.add(this.domain.getPackageToken()+"."+this.domain.getStandardName());
method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
return method;
}
@Override
public String generateDaoImplMethodString() {
return generateDaoImplMethod().generateMethodString();
}
@Override
public String generateDaoMethodDefinitionString() {
return generateDaoMethodDefinition().generateMethodDefinition();
}
@Override
public String generateDaoImplMethodStringWithSerial() {
return generateDaoImplMethod().generateMethodContentStringWithSerial();
}
@Override
public Method generateServiceMethodDefinition() {
Method method = new Method();
method.setStandardName("updateAll"+StringUtil.capFirst(this.domain.getPlural()));
method.setReturnType(new Type("boolean"));
method.setThrowException(true);
this.additionalImports.add(this.domain.getPackageToken()+"."+this.domain.getStandardName());
method.addSignature(new Signature(2, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
return method;
}
@Override
public String generateServiceMethodDefinitionString() {
return generateServiceMethodDefinition().generateMethodDefinition();
}
@Override
public Method generateControllerMethod() {
Method method = new Method();
method.setStandardName("processRequest");
method.setReturnType(new Type("void"));
method.setThrowException(true);
List<String> list = new ArrayList<String>();
list.add("ServletException");
list.add("IOException");
method.setIsprotected(true);
method.setOtherExceptions(list);
method.addSignature(new Signature(1,"request",new Type("HttpServletRequest","javax.servlet.http")));
method.addSignature(new Signature(2,"response",new Type("HttpServletResponse","javax.servlet.http")));
this.additionalImports.add("java.io.IOException");
this.additionalImports.add("javax.servlet.ServletException");
this.additionalImports.add("javax.servlet.http.HttpServlet");
this.additionalImports.add("javax.servlet.http.HttpServletRequest");
this.additionalImports.add("javax.servlet.http.HttpServletResponse");
this.additionalImports.add("java.util.List");
List<Writeable> wlist = new ArrayList<Writeable>();
Var service = new Var("service", new Type(this.domain.getStandardName()+"Service",this.domain.getPackageToken()));
Var domain = new Var(StringUtil.lowerFirst(this.domain.getStandardName()), new Type(this.domain.getStandardName(),this.domain,this.domain.getPackageToken()));
wlist.add(NamedStatementGenerator.getControllerSetContentType(1000L, 2, InterVarUtil.Servlet.response, InterVarUtil.SimpleJEE.UTF8.getVarName()));
wlist.add(NamedStatementGenerator.getControllerPrintWriterOut(2000L, 2, InterVarUtil.Servlet.response, InterVarUtil.Servlet.out));
wlist.add(NamedStatementGenerator.getTryHead(3000L, 2));
wlist.add(NamedStatementGenerator.getPrepareDomainVarInit(4000L, 2, this.domain));
wlist.add(NamedStatementListGenerator.generateSetDomainDataFromRequest(5000L, 2, this.domain, InterVarUtil.Servlet.request));
wlist.add(NamedStatementGenerator.getPrepareService(7000L,2, service));
wlist.add(NamedStatementGenerator.getCallServiceMethod(8000L, 2, service, generateServiceMethodDefinition()));
wlist.add(NamedStatementGenerator.getResponseRedirectUrl(9000L, 2, InterVarUtil.Servlet.response, "../controller/listAll"+this.domain.getStandardName()+"Controller"));
wlist.add(NamedStatementListGenerator.generateCatchExceptionPrintStackRedirectUrlFinallyCloseOutFooter(10000L, 2, InterVarUtil.Servlet.response,"../controller/listAll"+this.domain.getStandardName()+"Controller", InterVarUtil.Servlet.out));
// TODO Auto-generated method stub
method.setMethodStatementList(WriteableUtil.merge(wlist));
return method;
}
@Override
public String generateControllerMethodString() {
return generateControllerMethod().generateMethodString();
}
@Override
public Method generateServiceImplMethod() {
Method method = new Method();
method.setStandardName("update"+StringUtil.capFirst(this.domain.getStandardName()));
method.setReturnType(new Type("boolean"));
method.setThrowException(true);
this.additionalImports.add(this.domain.getPackageToken()+"."+this.domain.getStandardName());
method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
//Service method
Method daomethod = this.generateServiceMethodDefinition();
List<Writeable> list = new ArrayList<Writeable>();
list.add(NamedStatementListGenerator.generateServiceImplReturnBoolean(1000L, 2, InterVarUtil.DB.connection, InterVarUtil.DB.dbconf, InterVarUtil.DB.dao, daomethod));
method.setMethodStatementList(WriteableUtil.merge(list));
return method;
}
@Override
public String generateServiceImplMethodString() {
return generateServiceImplMethod().generateMethodString();
}
@Override
public String generateServiceImplMethodStringWithSerial() {
Method m = this.generateServiceImplMethod();
m.setContent(m.generateMethodContentStringWithSerial());
m.setMethodStatementList(null);
return m.generateMethodString();
}
public UpdateAll(Domain domain){
super();
this.domain = domain;
this.setVerbName("UpdateAll"+StringUtil.capFirst(this.domain.getPlural()));
}
public UpdateAll(){
super();
}
@Override
public String generateControllerMethodStringWithSerial() {
// TODO Auto-generated method stub
return null;
}
@Override
public Method generateFacadeMethod() {
// TODO Auto-generated method stub
return null;
}
@Override
public String generateFacadeMethodString() {
// TODO Auto-generated method stub
return null;
}
@Override
public String generateFacadeMethodStringWithSerial() {
// TODO Auto-generated method stub
return null;
}
}
| 42.863874 | 242 | 0.771956 |
076ad26d363cb7102dab0542c5974d8b4ef43e65 | 139 | package com.ab.worldcup.match;
public enum KnockoutMatchCode {
ROS1,ROS2,ROS3,ROS4,ROS5,ROS6,ROS7,ROS8,QF1,QF2,QF3,QF4,SF1,SF2,TP,F
}
| 23.166667 | 72 | 0.755396 |
8dc348032ad954746d914405bfdc7f4e0e529aeb | 2,938 | /*
* Copyright 2021 Kato Shinya.
*
* 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.thinkit.generator.entity.engine.dto;
import java.util.ArrayList;
import java.util.Collection;
import org.thinkit.generator.common.duke.dto.JavaResource;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import lombok.ToString;
/**
* {@link EntityResource} クラスを管理するコレクションクラスです。
*
* @author Kato Shinya
* @since 1.0.0
*/
@ToString
@EqualsAndHashCode(callSuper = false)
public final class EntityResourceGroup extends ArrayList<EntityResource> implements JavaResource {
/**
* シリアルバージョンUID
*/
private static final long serialVersionUID = 6678075433686071344L;
/**
* 初期容量が {@code 10} で設定された空のリストを生成します。
*/
private EntityResourceGroup() {
super();
}
/**
* 引数として渡された初期容量が設定された空のリストを生成します。
*
* @param initialCapacity リストの初期容量
*
* @throws IllegalArgumentException 初期容量が負数の場合
*/
private EntityResourceGroup(int initialCapacity) {
super(initialCapacity);
}
/**
* {@link EntityResource} クラスを総称型として持つコレクションを基に新しいリストを生成します。
*
* @param collection {@link EntityResource} クラスを総称型として持つコレクション
*
* @throws NullPointerException 引数として {@code null} が渡された場合
*/
private EntityResourceGroup(@NonNull Collection<? extends EntityResource> collection) {
super(collection);
}
/**
* 初期容量が {@code 10} で設定された空のリストを生成し返却します。
*
* @return {@link EntityResourceGroup} クラスの新しいインスタンス
*/
public static EntityResourceGroup newInstance() {
return new EntityResourceGroup();
}
/**
* 引数として渡された初期容量が設定された空のリストを生成し返却します。
*
* @param initialCapacity リストの初期容量
* @return {@link EntityResourceGroup} クラスの新しいインスタンス
*
* @throws IllegalArgumentException 初期容量が負数の場合
*/
public static EntityResourceGroup of(int initialCapacity) {
return new EntityResourceGroup(initialCapacity);
}
/**
* {@link EntityResource} クラスを総称型として持つコレクションを基に新しいリストを生成し返却します。
*
* @param collection {@link EntityResource} クラスを総称型として持つコレクション
* @return {@link EntityResourceGroup} クラスの新しいインスタンス
*
* @throws NullPointerException 引数として {@code null} が渡された場合
*/
public static EntityResourceGroup of(@NonNull Collection<? extends EntityResource> collection) {
return new EntityResourceGroup(collection);
}
}
| 28.524272 | 100 | 0.698434 |
44c3665b79697c868ecaa2de4fd1aa414623731a | 693 | package de.heinerkuecker.coroutine.stmt.simple.exc;
import de.heinerkuecker.coroutine.stmt.CoroStmt;
/**
* Exception
*/
public class StmtVariableIsNullException
extends RuntimeException
{
/**
* Generated by Eclipse.
*/
private static final long serialVersionUID = -31395849829839911L;
/**
* Constructor.
*/
public StmtVariableIsNullException(
final CoroStmt<?, ? , ?> wrongStmt ,
final Class<?> expectedClass )
{
super(
"variable is null for statement: " +
wrongStmt + ",\n" +
"expected class: " +
expectedClass );
}
}
| 23.1 | 70 | 0.556999 |
def43eae130754709755df7bef7f6d384935c616 | 3,248 | package org.thunlp.io;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.thunlp.hadoop.FolderWriter;
/*
* Write records to the underlying file, which can be plain text file, gzip file
* zip file or sequence file.
*/
public class RecordWriter {
public static int TYPE_PLAIN_TEXT = 0;
public static int TYPE_ZIPPED_TEXT = 1;
public static int TYPE_GZIPPED_TEXT = 2;
public static int TYPE_SEQUENCE_FILE = 3;
protected boolean isSequenceFile = false;
protected BufferedWriter writer = null;
protected ZipOutputStream zipout = null;
protected FolderWriter sequenceFileWriter = null;
protected Text key = new Text();
protected Text value = new Text();
protected int numWrote = 0;
public RecordWriter(String name) throws IOException {
this(name, "UTF-8");
}
public RecordWriter(String name, String charset) throws IOException {
this(name, charset, RecordReader.detectType(name), RecordReader.detectFs(name));
}
public RecordWriter(String name, String charset, int type, boolean onHdfs) throws IOException {
if (onHdfs && name.startsWith("/hdfs/")) {
name = name.substring("/hdfs".length());
}
if (type == RecordWriter.TYPE_PLAIN_TEXT) {
writer = new BufferedWriter(new OutputStreamWriter(getOutputStream(name, onHdfs), charset));
isSequenceFile = false;
} else if (type == RecordWriter.TYPE_GZIPPED_TEXT) {
writer = new BufferedWriter(
new OutputStreamWriter(new GZIPOutputStream(getOutputStream(name, onHdfs)), charset));
isSequenceFile = false;
} else if (type == RecordWriter.TYPE_ZIPPED_TEXT) {
zipout = new ZipOutputStream(getOutputStream(name, onHdfs));
writer = new BufferedWriter(new OutputStreamWriter(zipout, charset));
zipout.putNextEntry(new ZipEntry("part-00000.txt"));
isSequenceFile = false;
} else if (type == RecordWriter.TYPE_SEQUENCE_FILE) {
sequenceFileWriter = new FolderWriter(new Path(name), Text.class, Text.class);
isSequenceFile = true;
}
}
public void add(String value) throws IOException {
add(Integer.toString(numWrote), value);
}
public void add(String key, String value) throws IOException {
if (isSequenceFile) {
this.key.set(key);
this.value.set(value);
sequenceFileWriter.append(this.key, this.value);
} else {
writer.write(value);
writer.write("\n");
}
numWrote++;
}
public void close() throws IOException {
if (isSequenceFile) {
sequenceFileWriter.close();
} else {
writer.close();
}
}
public void flush() throws IOException {
// SequenceFile does not support flush operation.
if (!isSequenceFile) {
writer.flush();
}
}
protected OutputStream getOutputStream(String path, boolean onHdfs) throws IOException {
if (onHdfs) {
FileSystem fs = FileSystem.get(new JobConf());
return fs.create(new Path(path));
} else {
return new FileOutputStream(new File(path));
}
}
}
| 30.35514 | 96 | 0.736453 |
8fdafd5b054d23ccbc47ad9fb048054c57b0356b | 1,433 | package com.infinityraider.agricraft.render.particles;
import net.minecraft.client.Minecraft;
import net.minecraft.client.particle.SpriteTexturedParticle;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.inventory.container.PlayerContainer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
@OnlyIn(Dist.CLIENT)
public abstract class AgriParticle extends SpriteTexturedParticle {
protected AgriParticle(ClientWorld world, double x, double y, double z, float scale, float gravity, Vector3d vector, ResourceLocation texture) {
this(world, x, y, z, scale, gravity, vector, getIcon(texture));
}
protected AgriParticle(ClientWorld world, double x, double y, double z, float scale, float gravity, Vector3d vector, TextureAtlasSprite icon) {
super(world, x, y, z, 0, 0, 0);
this.setSprite(icon);
this.gravity = gravity;
this.scale(scale);
this.xd = vector.x;
this.yd = vector.y;
this.zd = vector.z;
}
protected static TextureAtlasSprite getIcon(ResourceLocation texture) {
return Minecraft.getInstance().getModelManager()
.getAtlas(PlayerContainer.BLOCK_ATLAS)
.getSprite(texture);
}
}
| 40.942857 | 148 | 0.73552 |
e351e7ab39be81403c1ad889cd176c0cf3609f3c | 46,085 | /*
* Copyright 2013 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 uk.co.real_logic.sbe.generation.python;
import uk.co.real_logic.sbe.PrimitiveType;
import uk.co.real_logic.sbe.generation.CodeGenerator;
import uk.co.real_logic.agrona.generation.OutputManager;
import uk.co.real_logic.sbe.ir.Encoding;
import uk.co.real_logic.sbe.ir.Ir;
import uk.co.real_logic.sbe.ir.Signal;
import uk.co.real_logic.sbe.ir.Token;
import uk.co.real_logic.agrona.Verify;
import java.io.IOException;
import java.io.Writer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
import static uk.co.real_logic.sbe.generation.python.PythonUtil.*;
public class PythonGenerator implements CodeGenerator
{
private static final String BASE_INDENT = "";
private static final String INDENT = " ";
private final Ir ir;
private final OutputManager outputManager;
public PythonGenerator(final Ir ir, final OutputManager outputManager)
throws IOException
{
Verify.notNull(ir, "ir");
Verify.notNull(outputManager, "outputManager");
this.ir = ir;
this.outputManager = outputManager;
}
public void generateMessageHeaderStub() throws IOException
{
try (final Writer out = outputManager.createOutput(MESSAGE_HEADER_TYPE))
{
final List<Token> tokens = ir.headerStructure().tokens();
out.append(generateFileHeader(ir.applicableNamespace().replace('.', '_'), null));
out.append(generateClassDeclaration(MESSAGE_HEADER_TYPE));
out.append(generateFixedFlyweightCode(MESSAGE_HEADER_TYPE, tokens.get(0).size()));
out.append(
generatePrimitivePropertyEncodings(MESSAGE_HEADER_TYPE, tokens.subList(1, tokens.size() - 1), BASE_INDENT));
}
}
public List<String> generateTypeStubs() throws IOException
{
final List<String> typesToInclude = new ArrayList<>();
for (final List<Token> tokens : ir.types())
{
switch (tokens.get(0).signal())
{
case BEGIN_ENUM:
generateEnum(tokens);
break;
case BEGIN_SET:
generateChoiceSet(tokens);
break;
case BEGIN_COMPOSITE:
generateComposite(tokens);
break;
}
typesToInclude.add(tokens.get(0).name());
}
return typesToInclude;
}
public void generate() throws IOException
{
generateMessageHeaderStub();
final List<String> typesToInclude = generateTypeStubs();
for (final List<Token> tokens : ir.messages())
{
final Token msgToken = tokens.get(0);
final String className = formatClassName(msgToken.name());
try (final Writer out = outputManager.createOutput(className))
{
out.append(generateFileHeader(ir.applicableNamespace().replace('.', '_'), typesToInclude));
out.append(generateClassDeclaration(className));
out.append(generateMessageFlyweightCode(msgToken));
final List<Token> messageBody = tokens.subList(1, tokens.size() - 1);
int offset = 0;
final List<Token> rootFields = new ArrayList<>();
offset = collectRootFields(messageBody, offset, rootFields);
out.append(generateFields(className, rootFields, BASE_INDENT));
final List<Token> groups = new ArrayList<>();
offset = collectGroups(messageBody, offset, groups);
StringBuilder sb = new StringBuilder();
generateGroups(sb, groups, 0, BASE_INDENT);
out.append(sb);
final List<Token> varData = messageBody.subList(offset, messageBody.size());
out.append(generateVarData(varData));
}
}
}
private int collectRootFields(final List<Token> tokens, int index, final List<Token> rootFields)
{
for (int size = tokens.size(); index < size; index++)
{
final Token token = tokens.get(index);
if (Signal.BEGIN_GROUP == token.signal() ||
Signal.END_GROUP == token.signal() ||
Signal.BEGIN_VAR_DATA == token.signal())
{
return index;
}
rootFields.add(token);
}
return index;
}
private int collectGroups(final List<Token> tokens, int index, final List<Token> groups)
{
for (int size = tokens.size(); index < size; index++)
{
final Token token = tokens.get(index);
if (Signal.BEGIN_VAR_DATA == token.signal())
{
return index;
}
groups.add(token);
}
return index;
}
private int generateGroups(final StringBuilder sb, final List<Token> tokens, int index, final String indent)
{
for (int size = tokens.size(); index < size; index++)
{
if (tokens.get(index).signal() == Signal.BEGIN_GROUP)
{
final Token groupToken = tokens.get(index);
final String groupName = groupToken.name();
generateGroupClassHeader(sb, groupName, tokens, index, indent + INDENT);
final List<Token> rootFields = new ArrayList<>();
index = collectRootFields(tokens, ++index, rootFields);
sb.append(generateFields(groupName, rootFields, indent + INDENT));
if (tokens.get(index).signal() == Signal.BEGIN_GROUP)
{
index = generateGroups(sb, tokens, index, indent + INDENT);
}
sb.append(generateGroupProperty(groupName, groupToken, indent));
}
}
return index;
}
private void generateGroupClassHeader(
final StringBuilder sb, final String groupName, final List<Token> tokens, final int index, final String indent)
{
final String dimensionsClassName = formatClassName(tokens.get(index + 1).name());
final Integer dimensionHeaderSize = Integer.valueOf(tokens.get(index + 1).size());
sb.append(String.format(
"\n" +
indent + "class %1$s:\n" +
indent + " buffer_ = 0\n" +
indent + " bufferLength_ = 0\n" +
indent + " blockLength_ = 0\n" +
indent + " count_ = 0\n" +
indent + " index_ = 0\n" +
indent + " offset_ = 0\n" +
indent + " actingVersion_ = 0\n" +
indent + " position_ = [0]\n" +
indent + " dimensions_ = %2$s.%2$s()\n\n",
formatClassName(groupName),
dimensionsClassName
));
sb.append(String.format(
indent + " def wrapForDecode(self, buffer, pos, actingVersion, bufferLength):\n" +
indent + " self.buffer_ = buffer\n" +
indent + " self.bufferLength_ = bufferLength\n" +
indent + " self.dimensions_.wrap(buffer, pos[0], actingVersion, bufferLength)\n" +
indent + " self.blockLength_ = self.dimensions_.getBlockLength()\n" +
indent + " self.count_ = self.dimensions_.getNumInGroup()\n" +
indent + " self.index_ = -1\n" +
indent + " self.actingVersion_ = actingVersion\n" +
indent + " self.position_ = pos\n" +
indent + " self.position_[0] += %1$d\n" +
indent + " return self\n\n",
dimensionHeaderSize
));
final Integer blockLength = Integer.valueOf(tokens.get(index).size());
final String typeForBlockLength = pythonTypeName(
tokens.get(index + 2).encoding().primitiveType(), tokens.get(index + 2).encoding().byteOrder());
final String typeForNumInGroup = pythonTypeName(
tokens.get(index + 3).encoding().primitiveType(), tokens.get(index + 3).encoding().byteOrder());
sb.append(String.format(
indent + " def wrapForEncode(self, buffer, count, pos, actingVersion, bufferLength):\n" +
indent + " self.buffer_ = buffer\n" +
indent + " self.bufferLength_ = bufferLength\n" +
indent + " self.dimensions_.wrap(self.buffer_, pos[0], actingVersion, bufferLength)\n" +
indent + " self.dimensions_.setBlockLength(%2$d)\n" +
indent + " self.dimensions_.setNumInGroup(count)\n" +
indent + " self.index_ = -1\n" +
indent + " self.count_ = count\n" +
indent + " self.blockLength_ = %2$d\n" +
indent + " self.actingVersion_ = actingVersion\n" +
indent + " self.position_ = pos\n" +
indent + " self.position_[0] += %4$d\n" +
indent + " return self\n\n",
typeForBlockLength,
blockLength,
typeForNumInGroup,
dimensionHeaderSize
));
sb.append(String.format(
indent + " @staticmethod\n" +
indent + " def sbeHeaderSize():\n" +
indent + " return %d\n\n",
dimensionHeaderSize
));
sb.append(String.format(
indent + " @staticmethod\n" +
indent + " def sbeBlockLength():\n" +
indent + " return %d\n\n",
blockLength
));
sb.append(String.format(
indent + " def count(self):\n" +
indent + " return self.count_\n\n" +
indent + " def hasNext(self):\n" +
indent + " return self.index_ + 1 < self.count_\n\n"
));
sb.append(String.format(
indent + " def next(self):\n" +
indent + " self.offset_ = self.position_[0]\n" +
indent + " if (self.offset_ + self.blockLength_) > self.bufferLength_:\n" +
indent + " raise Exception('buffer too short to support next group index')\n" +
indent + " self.position_[0] = self.offset_ + self.blockLength_\n" +
indent + " self.index_ += 1\n" +
indent + " return self\n\n",
formatClassName(groupName)
));
}
private CharSequence generateGroupProperty(final String groupName, final Token token, final String indent)
{
final StringBuilder sb = new StringBuilder();
final String className = formatClassName(groupName);
final String propertyName = formatPropertyName(groupName);
sb.append(String.format(
"\n" +
indent + " @staticmethod\n" +
indent + " def %1$sId():\n" +
indent + " return %2$d;\n\n",
groupName,
Long.valueOf(token.id())
));
sb.append(String.format(
"\n" +
indent + " def %2$s(self):\n" +
indent + " group = self.%1$s()\n" +
indent + " group.wrapForDecode(self.buffer_, self.position_, self.actingVersion_, self.bufferLength_)\n" +
indent + " return group\n\n",
className,
propertyName
));
sb.append(String.format(
"\n" +
indent + " def %2$sCount(self, count):\n" +
indent + " group = self.%1$s()\n" +
indent + " group.wrapForEncode(" +
"self.buffer_, count, self.position_, self.actingVersion_, self.bufferLength_)\n" +
indent + " return group\n\n",
className,
propertyName
));
return sb;
}
private CharSequence generateVarData(final List<Token> tokens)
{
final StringBuilder sb = new StringBuilder();
for (int i = 0, size = tokens.size(); i < size; i++)
{
final Token token = tokens.get(i);
if (token.signal() == Signal.BEGIN_VAR_DATA)
{
final String propertyName = toUpperFirstChar(token.name());
final String characterEncoding = tokens.get(i + 3).encoding().characterEncoding();
final Token lengthToken = tokens.get(i + 2);
final Integer sizeOfLengthField = Integer.valueOf(lengthToken.size());
final String lengthPythonType = pythonTypeName(
lengthToken.encoding().primitiveType(), lengthToken.encoding().byteOrder());
final String byteOrder = lengthToken.encoding().byteOrder() == ByteOrder.BIG_ENDIAN ? ">" : "<";
generateFieldMetaAttributeMethod(sb, token, BASE_INDENT);
generateVarDataDescriptors(
sb, token, propertyName, characterEncoding, lengthToken, sizeOfLengthField, lengthPythonType);
sb.append(String.format(
" def get%1$s(self):\n" +
" sizeOfLengthField = %3$d\n" +
" lengthPosition = self.getPosition()\n" +
" dataLength = struct.unpack_from('%5$s', self.buffer_, lengthPosition[0])[0]\n" +
" self.setPosition(lengthPosition[0] + sizeOfLengthField)\n" +
" pos = self.getPosition()\n" +
" fmt = '" + byteOrder + "'+str(dataLength)+'c'\n" +
" data = struct.unpack_from(fmt, self.buffer_, lengthPosition[0])\n" +
" self.setPosition(pos[0] + dataLength)\n" +
" return data\n\n",
propertyName,
generateArrayFieldNotPresentCondition(token.version(), BASE_INDENT),
sizeOfLengthField,
formatByteOrderEncoding(lengthToken.encoding().byteOrder(), lengthToken.encoding().primitiveType()),
lengthPythonType
));
sb.append(String.format(
" def set%1$s(self, buffer):\n" +
" sizeOfLengthField = %2$d\n" +
" lengthPosition = self.getPosition()\n" +
" struct.pack_into('%3$s', self.buffer_, lengthPosition[0], len(buffer))\n" +
" self.setPosition(lengthPosition[0] + sizeOfLengthField)\n" +
" pos = self.getPosition()\n" +
" fmt = '" + byteOrder + "c'\n" +
" for i in range(0,len(buffer)):\n" +
" struct.pack_into(fmt, self.buffer_, lengthPosition[0]+i, buffer[i])\n" +
" self.setPosition(pos[0] + len(buffer))\n\n",
propertyName,
sizeOfLengthField,
lengthPythonType,
formatByteOrderEncoding(lengthToken.encoding().byteOrder(), lengthToken.encoding().primitiveType())
));
}
}
return sb;
}
private void generateVarDataDescriptors(
final StringBuilder sb,
final Token token,
final String propertyName,
final String characterEncoding,
final Token lengthToken,
final Integer sizeOfLengthField,
final String lengthCpp98Type)
{
sb.append(String.format(
"\n" +
" @staticmethod\n" +
" def %1$sCharacterEncoding():\n" +
" return '%2$s'\n\n",
formatPropertyName(propertyName),
characterEncoding
));
sb.append(String.format(
" @staticmethod\n" +
" def %1$sSinceVersion():\n" +
" return %2$d\n\n" +
" def %1$sInActingVersion(self):\n" +
" return True if self.actingVersion_ >= %2$s else False\n" +
" @staticmethod\n" +
" def %1$sId():\n" +
" return %3$d\n\n",
formatPropertyName(propertyName),
Long.valueOf(token.version()),
Integer.valueOf(token.id())
));
sb.append(String.format(
" @staticmethod\n" +
" def %sHeaderSize():\n" +
" return %d\n\n",
toLowerFirstChar(propertyName),
sizeOfLengthField
));
sb.append(String.format(
" def %1$sLength(self):\n" +
" return struct.unpack_from('%4$s', self.buffer_, position())[0]\n\n",
formatPropertyName(propertyName),
generateArrayFieldNotPresentCondition(token.version(), BASE_INDENT),
formatByteOrderEncoding(lengthToken.encoding().byteOrder(), lengthToken.encoding().primitiveType()),
lengthCpp98Type
));
}
private void generateChoiceSet(final List<Token> tokens) throws IOException
{
final String bitSetName = formatClassName(tokens.get(0).name());
try (final Writer out = outputManager.createOutput(bitSetName))
{
out.append(generateFileHeader(ir.applicableNamespace().replace('.', '_'), null));
out.append(generateClassDeclaration(bitSetName));
out.append(generateFixedFlyweightCode(bitSetName, tokens.get(0).size()));
out.append(String.format(
"\n" +
" def clear(self):\n" +
" struct.pack_into('%2$s', self.buffer_, self.offset_, 0)\n" +
" return self\n\n",
bitSetName,
pythonTypeName(tokens.get(0).encoding().primitiveType(), tokens.get(0).encoding().byteOrder())
));
out.append(generateChoices(bitSetName, tokens.subList(1, tokens.size() - 1)));
}
}
private void generateEnum(final List<Token> tokens) throws IOException
{
final Token enumToken = tokens.get(0);
final String enumName = formatClassName(tokens.get(0).name());
try (final Writer out = outputManager.createOutput(enumName))
{
out.append(generateFileHeader(ir.applicableNamespace().replace('.', '_'), null));
out.append(generateEnumDeclaration(enumName));
out.append(generateEnumValues(tokens.subList(1, tokens.size() - 1), enumToken));
out.append(generateEnumLookupMethod(tokens.subList(1, tokens.size() - 1), enumToken));
}
}
private void generateComposite(final List<Token> tokens) throws IOException
{
final String compositeName = formatClassName(tokens.get(0).name());
try (final Writer out = outputManager.createOutput(compositeName))
{
out.append(generateFileHeader(ir.applicableNamespace().replace('.', '_'), null));
out.append(generateClassDeclaration(compositeName));
out.append(generateFixedFlyweightCode(compositeName, tokens.get(0).size()));
out.append(generatePrimitivePropertyEncodings(compositeName, tokens.subList(1, tokens.size() - 1), BASE_INDENT));
}
}
private CharSequence generateChoiceNotPresentCondition(final int sinceVersion, final String indent)
{
if (0 == sinceVersion)
{
return "";
}
return String.format(
indent + " if self.actingVersion_ < %1$d:\n" +
indent + " return False\n\n",
Integer.valueOf(sinceVersion)
);
}
private CharSequence generateChoices(final String bitsetClassName, final List<Token> tokens)
{
final StringBuilder sb = new StringBuilder();
for (final Token token : tokens)
{
if (token.signal() == Signal.CHOICE)
{
final String choiceName = token.name();
final String typeName = pythonTypeName(token.encoding().primitiveType(), token.encoding().byteOrder());
final String choiceBitPosition = token.encoding().constValue().toString();
final String byteOrderStr = formatByteOrderEncoding(
token.encoding().byteOrder(), token.encoding().primitiveType());
sb.append(String.format(
"\n" +
" def get%1$s(self):\n" +
" return True if struct.unpack_from(" +
"'%4$s', self.buffer_, self.offset_)[0] & (0x1L << %5$s) > 0 else False\n\n",
toUpperFirstChar(choiceName),
generateChoiceNotPresentCondition(token.version(), BASE_INDENT),
byteOrderStr,
typeName,
choiceBitPosition
));
sb.append(String.format(
" def set%2$s(self, value):\n" +
" bits = struct.unpack_from('%3$s', self.buffer_, self.offset_)[0]\n" +
" bits = (bits | ( 0x1L << %5$s)) if value > 0 else (bits & ~(0x1L << %5$s))\n" +
" struct.pack_into('%3$s', self.buffer_, self.offset_, value)\n" +
" return self\n",
bitsetClassName,
toUpperFirstChar(choiceName),
typeName,
byteOrderStr,
choiceBitPosition
));
}
}
return sb;
}
private CharSequence generateEnumValues(final List<Token> tokens, final Token encodingToken)
{
final StringBuilder sb = new StringBuilder();
final Encoding encoding = encodingToken.encoding();
sb.append(" class Value:\n");
for (final Token token : tokens)
{
final CharSequence constVal = generateLiteral(
token.encoding().primitiveType(), token.encoding().constValue().toString());
sb.append(" ").append(token.name()).append(" = ").append(constVal).append("\n");
}
sb.append(String.format(
" NULL_VALUE = %1$s",
generateLiteral(encoding.primitiveType(), encoding.applicableNullValue().toString())
));
sb.append("\n\n");
return sb;
}
private CharSequence generateEnumLookupMethod(final List<Token> tokens, final Token encodingToken)
{
final String enumName = formatClassName(encodingToken.name());
final StringBuilder sb = new StringBuilder();
sb.append(
" @staticmethod\n" +
" def get(value):\n" +
" values = {\n");
for (final Token token : tokens)
{
sb.append(String.format(
" %1$s : %3$s.Value.%2$s,\n",
token.encoding().constValue().toString(),
token.name(),
enumName)
);
}
sb.append(String.format(
" %1$s : %2$s.Value.NULL_VALUE\n" +
" }\n" +
" if type(value) is int:\n" +
" return values[value]\n" +
" else:\n" +
" return values[ord(value)]\n",
encodingToken.encoding().applicableNullValue().toString(),
enumName
));
return sb;
}
private CharSequence generateFieldNotPresentCondition(final int sinceVersion, final Encoding encoding, final String indent)
{
if (0 == sinceVersion)
{
return "";
}
return String.format(
indent + " if self.actingVersion_ < %1$d:\n" +
indent + " return %2$s\n\n",
Integer.valueOf(sinceVersion),
generateLiteral(encoding.primitiveType(), encoding.applicableNullValue().toString())
);
}
private CharSequence generateArrayFieldNotPresentCondition(final int sinceVersion, final String indent)
{
if (0 == sinceVersion)
{
return "";
}
return String.format(
indent + " if self.actingVersion_ < %1$d:\n" +
indent + " return False\n\n",
Integer.valueOf(sinceVersion)
);
}
private CharSequence generateFileHeader(final String namespaceName, final List<String> typesToInclude)
{
final StringBuilder sb = new StringBuilder();
sb.append("#\n# Generated SBE (Simple Binary Encoding) message codec\n#\n");
sb.append("import struct\n\n");
if (typesToInclude != null)
{
for (final String incName : typesToInclude)
{
sb.append(String.format(
"import %2$s\n",
namespaceName,
toUpperFirstChar(incName)
));
}
sb.append("\n");
}
return sb;
}
private CharSequence generateClassDeclaration(final String name)
{
return "class " + name + ":\n";
}
private CharSequence generateEnumDeclaration(final String name)
{
return "class " + name + ":\n";
}
private CharSequence generatePrimitivePropertyEncodings(
final String containingClassName, final List<Token> tokens, final String indent)
{
final StringBuilder sb = new StringBuilder();
for (final Token token : tokens)
{
if (token.signal() == Signal.ENCODING)
{
sb.append(generatePrimitiveProperty(containingClassName, token.name(), token, indent));
}
}
return sb;
}
private CharSequence generatePrimitiveProperty(
final String containingClassName, final String propertyName, final Token token, final String indent)
{
final StringBuilder sb = new StringBuilder();
sb.append(generatePrimitiveFieldMetaData(propertyName, token, indent));
if (Encoding.Presence.CONSTANT == token.encoding().presence())
{
sb.append(generateConstPropertyMethods(propertyName, token, indent));
}
else
{
sb.append(generatePrimitivePropertyMethods(containingClassName, propertyName, token, indent));
}
return sb;
}
private CharSequence generatePrimitivePropertyMethods(
final String containingClassName, final String propertyName, final Token token, final String indent)
{
final int arrayLength = token.arrayLength();
if (arrayLength == 1)
{
return generateSingleValueProperty(containingClassName, propertyName, token, indent);
}
else if (arrayLength > 1)
{
return generateArrayProperty(propertyName, token, indent);
}
return "";
}
private CharSequence generatePrimitiveFieldMetaData(final String propertyName, final Token token, final String indent)
{
final StringBuilder sb = new StringBuilder();
final PrimitiveType primitiveType = token.encoding().primitiveType();
final String pythonTypeName = pythonTypeName(primitiveType, token.encoding().byteOrder());
sb.append(String.format(
"\n" +
indent + " @staticmethod\n" +
indent + " def %2$sNullValue():\n" +
indent + " return %3$s\n",
pythonTypeName,
propertyName,
generateLiteral(primitiveType, token.encoding().applicableNullValue().toString())
));
sb.append(String.format(
"\n" +
indent + " @staticmethod\n" +
indent + " def %2$sMinValue():\n" +
indent + " return %3$s\n",
pythonTypeName,
propertyName,
generateLiteral(primitiveType, token.encoding().applicableMinValue().toString())
));
sb.append(String.format(
"\n" +
indent + " @staticmethod\n" +
indent + " def %2$sMaxValue():\n" +
indent + " return %3$s\n",
pythonTypeName,
propertyName,
generateLiteral(primitiveType, token.encoding().applicableMaxValue().toString())
));
return sb;
}
private CharSequence generateSingleValueProperty(
final String containingClassName, final String propertyName, final Token token, final String indent)
{
final String pythonTypeName = pythonTypeName(token.encoding().primitiveType(), token.encoding().byteOrder());
final Integer offset = Integer.valueOf(token.offset());
final StringBuilder sb = new StringBuilder();
sb.append(String.format(
"\n" +
indent + " def get%2$s(self):\n" +
indent + " return struct.unpack_from('%1$s', self.buffer_, self.offset_ + %5$d)[0]\n\n",
pythonTypeName,
toUpperFirstChar(propertyName),
generateFieldNotPresentCondition(token.version(), token.encoding(), indent),
formatByteOrderEncoding(token.encoding().byteOrder(), token.encoding().primitiveType()),
offset
));
sb.append(String.format(
indent + " def set%2$s(self, value):\n" +
indent + " struct.pack_into('%3$s', self.buffer_, self.offset_ + %4$d, value)\n" +
indent + " return self\n",
formatClassName(containingClassName),
toUpperFirstChar(propertyName),
pythonTypeName,
offset,
formatByteOrderEncoding(token.encoding().byteOrder(), token.encoding().primitiveType())
));
return sb;
}
private CharSequence generateArrayProperty(
final String propertyName, final Token token, final String indent)
{
final String pythonTypeName = pythonTypeName(token.encoding().primitiveType(), token.encoding().byteOrder());
final Integer offset = Integer.valueOf(token.offset());
final StringBuilder sb = new StringBuilder();
sb.append(String.format(
"\n" +
indent + " @staticmethod\n" +
indent + " def %1$sLength():\n" +
indent + " return %2$d\n\n",
propertyName,
Integer.valueOf(token.arrayLength())
));
sb.append(String.format(
indent + " def get%2$s(self, index):\n" +
indent + " if index < 0 or index >= %3$d:\n" +
indent + " raise Exception('index out of range for %2$s')\n" +
indent + " return struct.unpack_from('%1$s', self.buffer_, self.offset_ + %6$d + (index * %7$d))[0]\n\n",
pythonTypeName,
toUpperFirstChar(propertyName),
Integer.valueOf(token.arrayLength()),
generateFieldNotPresentCondition(token.version(), token.encoding(), indent),
formatByteOrderEncoding(token.encoding().byteOrder(), token.encoding().primitiveType()),
offset,
Integer.valueOf(token.encoding().primitiveType().size())
));
sb.append(String.format(
indent + " def set%1$s(self, index, value):\n" +
indent + " if index < 0 or index >= %3$d:\n" +
indent + " raise Exception('index out of range for %1$s')\n" +
indent + " struct.pack_into('%2$s', self.buffer_, self.offset_ + %4$d + (index * %5$d), value)\n",
propertyName,
toUpperFirstChar(pythonTypeName),
Integer.valueOf(token.arrayLength()),
offset,
Integer.valueOf(token.encoding().primitiveType().size()),
formatByteOrderEncoding(token.encoding().byteOrder(), token.encoding().primitiveType())
));
return sb;
}
private CharSequence generateConstPropertyMethods(final String propertyName, final Token token, final String indent)
{
final String pythonTypeName = pythonTypeName(token.encoding().primitiveType(), token.encoding().byteOrder());
if (token.encoding().primitiveType() != PrimitiveType.CHAR)
{
return String.format(
"\n" +
indent + " def %2$s(self):\n" +
indent + " return %3$s\n",
pythonTypeName,
propertyName,
generateLiteral(token.encoding().primitiveType(), token.encoding().constValue().toString())
);
}
final StringBuilder sb = new StringBuilder();
final byte[] constantValue = token.encoding().constValue().byteArrayValue(token.encoding().primitiveType());
final StringBuilder values = new StringBuilder();
for (final byte b : constantValue)
{
values.append(b).append(", ");
}
if (values.length() > 0)
{
values.setLength(values.length() - 2);
}
sb.append(String.format(
"\n" +
indent + " @staticmethod\n" +
indent + " def %1$sLength():\n" +
indent + " return %2$d\n\n",
propertyName,
Integer.valueOf(constantValue.length)
));
sb.append(String.format(
indent + " def %2$s(self, index):\n" +
indent + " %2$sValues = [%3$s]\n" +
indent + " return %2$sValues[index]\n",
pythonTypeName,
propertyName,
values
));
return sb;
}
private CharSequence generateFixedFlyweightCode(final String className, final int size)
{
return String.format(
" buffer_ = 0\n" +
" offset_ = 0\n" +
" actingVersion_ = 0\n\n" +
" def wrap(self, buffer, offset, actingVersion, bufferLength):\n" +
" if (offset > (bufferLength - %2$s)):\n" +
" raise Exception('buffer too short for flyweight')\n" +
" self.buffer_ = buffer\n" +
" self.offset_ = offset\n" +
" self.actingVersion_ = actingVersion\n" +
" return self\n\n" +
" @staticmethod\n" +
" def size():\n" +
" return %2$s\n",
className,
Integer.valueOf(size)
);
}
private CharSequence generateMessageFlyweightCode(final Token token)
{
final String semanticType = token.encoding().semanticType() == null ? "" : token.encoding().semanticType();
return String.format(
" buffer_ = 0\n" +
" bufferLength_ = 0\n" +
" offset_ = 0\n" +
" actingBlockLength_ = 0\n" +
" actingVersion_ = 0\n" +
" position_ = [0]\n\n" +
" @staticmethod\n" +
" def sbeBlockLength():\n" +
" return %1$s\n\n" +
" @staticmethod\n" +
" def sbeTemplateId():\n" +
" return %2$s\n\n" +
" @staticmethod\n" +
" def sbeSchemaId():\n" +
" return %3$s\n\n" +
" @staticmethod\n" +
" def sbeSchemaVersion():\n" +
" return %4$s\n\n" +
" @staticmethod\n" +
" def sbeSemanticType():\n" +
" return \"%5$s\"\n\n" +
" def offset(self):\n" +
" return offset_\n\n" +
" def wrapForEncode(self, buffer, offset, bufferLength):\n" +
" self.buffer_ = buffer\n" +
" self.offset_ = offset\n" +
" self.bufferLength_ = bufferLength\n" +
" self.actingBlockLength_ = self.sbeBlockLength()\n" +
" self.actingVersion_ = self.sbeSchemaVersion()\n" +
" self.setPosition(offset + self.actingBlockLength_)\n" +
" return self\n\n" +
" def wrapForDecode(self, buffer, offset, actingBlockLength, actingVersion, bufferLength):\n" +
" self.buffer_ = buffer\n" +
" self.offset_ = offset\n" +
" self.bufferLength_ = bufferLength\n" +
" self.actingBlockLength_ = actingBlockLength\n" +
" self.actingVersion_ = actingVersion\n" +
" self.setPosition(offset + self.actingBlockLength_)\n" +
" return self\n\n" +
" def getPosition(self):\n" +
" return self.position_\n\n" +
" def setPosition(self, position):\n" +
" if self.position_[0] > self.bufferLength_:\n" +
" raise Exception('buffer too short')\n" +
" self.position_[0] = position\n\n" +
" def size(self):\n" +
" return self.position() - self.offset_\n\n" +
" def buffer(self):\n" +
" return self.buffer_\n\n" +
" def actingVersion(self):\n" +
" return self.actingVersion_;\n",
generateLiteral(ir.headerStructure().blockLengthType(), Integer.toString(token.size())),
generateLiteral(ir.headerStructure().templateIdType(), Integer.toString(token.id())),
generateLiteral(ir.headerStructure().schemaIdType(), Integer.toString(ir.id())),
generateLiteral(ir.headerStructure().schemaVersionType(), Integer.toString(token.version())),
semanticType
);
}
private CharSequence generateFields(final String containingClassName, final List<Token> tokens, final String indent)
{
final StringBuilder sb = new StringBuilder();
for (int i = 0, size = tokens.size(); i < size; i++)
{
final Token signalToken = tokens.get(i);
if (signalToken.signal() == Signal.BEGIN_FIELD)
{
final Token encodingToken = tokens.get(i + 1);
final String propertyName = formatPropertyName(signalToken.name());
sb.append(String.format(
"\n" +
indent + " @staticmethod\n" +
indent + " def %1$sId():\n" +
indent + " return %2$d\n\n",
propertyName,
Integer.valueOf(signalToken.id())
));
sb.append(String.format(
indent + " @staticmethod\n" +
indent + " def %1$sSinceVersion():\n" +
indent + " return %2$d\n\n" +
indent + " def %1$sInActingVersion(self):\n" +
indent + " return self.actingVersion_ >= %2$d\n",
propertyName,
Long.valueOf(signalToken.version())
));
generateFieldMetaAttributeMethod(sb, signalToken, indent);
switch (encodingToken.signal())
{
case ENCODING:
sb.append(generatePrimitiveProperty(containingClassName, propertyName, encodingToken, indent));
break;
case BEGIN_ENUM:
sb.append(generateEnumProperty(containingClassName, propertyName, encodingToken, indent));
break;
case BEGIN_SET:
sb.append(generateBitsetProperty(propertyName, encodingToken, indent));
break;
case BEGIN_COMPOSITE:
sb.append(generateCompositeProperty(propertyName, encodingToken, indent));
break;
}
}
}
return sb;
}
private void generateFieldMetaAttributeMethod(final StringBuilder sb, final Token token, final String indent)
{
final Encoding encoding = token.encoding();
final String epoch = encoding.epoch() == null ? "" : encoding.epoch();
final String timeUnit = encoding.timeUnit() == null ? "" : encoding.timeUnit();
final String semanticType = encoding.semanticType() == null ? "" : encoding.semanticType();
sb.append(String.format(
"\n" +
indent + " @staticmethod\n" +
indent + " def %sMetaAttribute(meta):\n" +
indent + " return \"???\"\n",
token.name(),
epoch,
timeUnit,
semanticType
));
}
private CharSequence generateEnumFieldNotPresentCondition(final int sinceVersion, final String enumName, final String indent)
{
if (0 == sinceVersion)
{
return "";
}
return String.format(
indent + " if self.actingVersion_ < %1$d:\n" +
indent + " return %2$s.Value.NULL_VALUE\n" +
Integer.valueOf(sinceVersion),
enumName
);
}
private CharSequence generateEnumProperty(
final String containingClassName, final String propertyName, final Token token, final String indent)
{
final String enumName = token.name();
final String typeName = pythonTypeName(token.encoding().primitiveType(), token.encoding().byteOrder());
final Integer offset = Integer.valueOf(token.offset());
final StringBuilder sb = new StringBuilder();
sb.append(String.format(
"\n" +
indent + " def get%2$s(self):\n" +
indent + " return %1$s.%1$s.get(struct.unpack_from( '%5$s', self.buffer_, self.offset_ + %6$d)[0])\n\n",
enumName,
toUpperFirstChar(propertyName),
generateEnumFieldNotPresentCondition(token.version(), enumName, indent),
formatByteOrderEncoding(token.encoding().byteOrder(), token.encoding().primitiveType()),
typeName,
offset
));
sb.append(String.format(
indent + " def set%2$s(self, value):\n" +
indent + " struct.pack_into('%4$s', self.buffer_, self.offset_ + %5$d, value)\n" +
indent + " return self\n",
formatClassName(containingClassName),
toUpperFirstChar(propertyName),
enumName,
typeName,
offset,
formatByteOrderEncoding(token.encoding().byteOrder(), token.encoding().primitiveType())
));
return sb;
}
private Object generateBitsetProperty(final String propertyName, final Token token, final String indent)
{
final StringBuilder sb = new StringBuilder();
final String bitsetName = formatClassName(token.name());
final Integer offset = Integer.valueOf(token.offset());
sb.append(String.format(
"\n" +
indent + " def %2$s(self):\n" +
indent + " bitset = %1$s.%1$s()\n" +
indent + " bitset.wrap(self.buffer_, self.offset_ + %3$d, self.actingVersion_, self.bufferLength_)\n" +
indent + " return bitset;\n",
bitsetName,
propertyName,
offset
));
return sb;
}
private Object generateCompositeProperty(final String propertyName, final Token token, final String indent)
{
final String compositeName = formatClassName(token.name());
final Integer offset = Integer.valueOf(token.offset());
final StringBuilder sb = new StringBuilder();
sb.append(String.format(
"\n" +
indent + " def %2$s(self):\n" +
indent + " %2$s = %1$s.%1$s()\n" +
indent + " %2$s.wrap(self.buffer_, self.offset_ + %3$d, self.actingVersion_, self.bufferLength_)\n" +
indent + " return %2$s\n",
compositeName,
propertyName,
offset
));
return sb;
}
private CharSequence generateLiteral(final PrimitiveType type, final String value)
{
String literal = "";
switch (type)
{
case CHAR:
case UINT8:
case UINT16:
case INT8:
case INT16:
literal = value;
break;
case UINT32:
case INT32:
literal = value;
break;
case FLOAT:
if (value.endsWith("NaN"))
{
literal = "float('NaN')";
}
else
{
literal = value;
}
break;
case INT64:
literal = value + "L";
break;
case UINT64:
literal = "0x" + Long.toHexString(Long.parseLong(value)) + "L";
break;
case DOUBLE:
if (value.endsWith("NaN"))
{
literal = "double('NaN')";
}
else
{
literal = value;
}
}
return literal;
}
}
| 38.244813 | 129 | 0.531106 |
10b614c309176226d9b8f5be51978b4a30411955 | 5,376 | package com.stanfy.enroscar.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
/**
* URL connection wrapper.
* Delegates all the method calls to the wrapped instance.
*/
public abstract class UrlConnectionWrapper extends URLConnection {
/** Core connection instance. */
private URLConnection core;
protected UrlConnectionWrapper(final URLConnection urlConnection) {
super(urlConnection.getURL());
this.core = urlConnection;
}
public static URLConnection unwrap(final URLConnection connection) {
URLConnection result = connection;
while (result instanceof UrlConnectionWrapper) {
result = ((UrlConnectionWrapper)result).core;
}
return result;
}
public static <T extends UrlConnectionWrapper> T getWrapper(final URLConnection connection,
final Class<T> clazz) {
URLConnection result = connection;
if (!(result instanceof UrlConnectionWrapper)) { return null; }
boolean found = false;
do {
if (!clazz.isInstance(result)) {
result = ((UrlConnectionWrapper)result).core;
} else {
found = true;
}
} while (!found && result instanceof UrlConnectionWrapper);
return found ? clazz.cast(result) : null;
}
public final URLConnection getCore() { return core; }
@Override
public void connect() throws IOException {
core.connect();
connected = true;
}
@Override
public boolean getAllowUserInteraction() { return core.getAllowUserInteraction(); }
@Override
public Object getContent() throws IOException { return core.getContent(); }
@Override
@SuppressWarnings("rawtypes")
public Object getContent(final Class[] types) throws IOException { return core.getContent(types); }
@Override
public String getContentEncoding() { return core.getContentEncoding(); }
@Override
public int getContentLength() { return core.getContentLength(); }
@Override
public String getContentType() { return core.getContentType(); }
@Override
public long getDate() { return core.getDate(); }
@Override
public boolean getDefaultUseCaches() { return core.getDefaultUseCaches(); }
@Override
public boolean getDoInput() { return core.getDoInput(); }
@Override
public boolean getDoOutput() { return core.getDoInput(); }
@Override
public long getExpiration() { return core.getExpiration(); }
@Override
public String getHeaderField(final int pos) { return core.getHeaderField(pos); }
@Override
public Map<String, List<String>> getHeaderFields() { return core.getHeaderFields(); }
@Override
public Map<String, List<String>> getRequestProperties() { return core.getRequestProperties(); }
@Override
public void addRequestProperty(final String field, final String newValue) {
core.addRequestProperty(field, newValue);
}
@Override
public String getHeaderField(final String key) { return core.getHeaderField(key); }
@Override
public long getHeaderFieldDate(final String field, final long defaultValue) { return core.getHeaderFieldDate(field, defaultValue); }
@Override
public int getHeaderFieldInt(final String field, final int defaultValue) { return core.getHeaderFieldInt(field, defaultValue); }
@Override
public String getHeaderFieldKey(final int posn) { return core.getHeaderFieldKey(posn); }
@Override
public long getIfModifiedSince() { return core.getIfModifiedSince(); }
@Override
public InputStream getInputStream() throws IOException { return core.getInputStream(); }
@Override
public long getLastModified() { return core.getLastModified(); }
@Override
public OutputStream getOutputStream() throws IOException { return core.getOutputStream(); }
@Override
public java.security.Permission getPermission() throws IOException { return core.getPermission(); }
@Override
public String getRequestProperty(final String field) { return core.getRequestProperty(field); }
@Override
public URL getURL() { return url; }
@Override
public boolean getUseCaches() { return core.getUseCaches(); }
@Override
public void setAllowUserInteraction(final boolean newValue) {
core.setAllowUserInteraction(newValue);
}
@Override
public void setDefaultUseCaches(final boolean newValue) {
core.setDefaultUseCaches(newValue);
}
@Override
public void setDoInput(final boolean newValue) {
core.setDoInput(newValue);
}
@Override
public void setDoOutput(final boolean newValue) {
core.setDoOutput(newValue);
}
@Override
public void setIfModifiedSince(final long newValue) {
core.setIfModifiedSince(newValue);
}
@Override
public void setRequestProperty(final String field, final String newValue) {
core.setRequestProperty(field, newValue);
}
@Override
public void setUseCaches(final boolean newValue) {
core.setUseCaches(newValue);
}
@Override
public void setConnectTimeout(final int timeout) {
core.setConnectTimeout(timeout);
}
@Override
public int getConnectTimeout() { return core.getConnectTimeout(); }
@Override
public void setReadTimeout(final int timeout) {
core.setReadTimeout(timeout);
}
@Override
public int getReadTimeout() { return core.getReadTimeout(); }
}
| 28 | 134 | 0.726004 |
9bf8ca6cb44c95a71a48298847d9ee05efa76117 | 2,115 | package io.github.forezp.modules.activiti.controller;
import io.github.forezp.common.dto.PageResultsDTO;
import io.github.forezp.common.dto.RespDTO;
import io.github.forezp.common.exception.AriesException;
import io.github.forezp.common.exception.ErrorCode;
import io.github.forezp.common.util.PageUtils;
import io.github.forezp.modules.activiti.service.ActModelCategoryService;
import io.github.forezp.modules.task.service.QrtzTriggersGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
/**
* <p>
* 前端控制器
* </p>
*
* @author forezp
* @since 2019-08-16
*/
@RestController
@RequestMapping("/model-category")
public class ActModelCategoryController {
@Autowired
ActModelCategoryService actModelCategoryService;
@PostMapping("")
public RespDTO addCategory(@RequestParam String categoryId, @RequestParam String categoryName, @RequestParam String pCategoryId) {
if (actModelCategoryService.addModelCategory(categoryId, categoryName, pCategoryId)) {
return RespDTO.onSuc(null);
} else {
throw new AriesException(ErrorCode.INSERT_DATA_FAIL);
}
}
@PutMapping("")
public RespDTO updateCategory(@RequestParam Long id, @RequestParam String categoryName) {
if (actModelCategoryService.updateModelCategory(id, categoryName)) {
return RespDTO.onSuc(null);
} else {
throw new AriesException(ErrorCode.UPDATE_DATA_FAIL);
}
}
@GetMapping("/pagelist")
public RespDTO getCategoryPagelist(@RequestParam int page, @RequestParam int pageSize
, @RequestParam(required = false) String categoryId
, @RequestParam(required = false) String categoryName
, @RequestParam(required = false) String pCategoryId) {
PageUtils.check(page, pageSize);
PageResultsDTO resultsDTO = actModelCategoryService.selectPagelist(page, pageSize, categoryId, categoryName, pCategoryId);
return RespDTO.onSuc(resultsDTO);
}
}
| 35.847458 | 134 | 0.733806 |
e4e349d40b6582b109855365bfaca9ae4d59ccfe | 6,748 | /**
* Copyright 2009 Humboldt-Universität zu Berlin.
*
* 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.corpus_tools.salt.common.tokenizer.tests;
import static org.junit.Assert.assertEquals;
import org.corpus_tools.salt.SaltFactory;
import org.corpus_tools.salt.common.SDocumentGraph;
import org.corpus_tools.salt.common.STextualDS;
import org.corpus_tools.salt.common.tokenizer.SimpleTokenizer;
import org.junit.Before;
import org.junit.Test;
/**
*
* Tests the class TTTokenizer.
*
* @author Florian Zipser
*
*/
public class SimpleTokenizerTest {
private SimpleTokenizer fixture = null;
/**
* @param fixture
* the fixture to set
*/
public void setFixture(SimpleTokenizer fixture) {
this.fixture = fixture;
}
/**
* @return the fixture
*/
public SimpleTokenizer getFixture() {
return fixture;
}
@Before
public void setUp() {
this.setFixture(new SimpleTokenizer());
}
/**
* Tests the text "This is a test text.", which has to be tokenized into 5
* tokens:
* <ul>
* <li>This</li>
* <li>is</li>
* <li>a</li>
* <li>test</li>
* <li>text.</li>
* </ul>
*/
@Test
public void testTokenize_ByBlanks1() {
SDocumentGraph docGraph = SaltFactory.createSDocumentGraph();
STextualDS primText = docGraph.createTextualDS("This is a test text.");
getFixture().setDocumentGraph(docGraph);
getFixture().tokenize(primText, ' ');
assertEquals(5, docGraph.getTokens().size());
assertEquals("This", docGraph.getText(docGraph.getTokens().get(0)));
assertEquals("is", docGraph.getText(docGraph.getTokens().get(1)));
assertEquals("a", docGraph.getText(docGraph.getTokens().get(2)));
assertEquals("test", docGraph.getText(docGraph.getTokens().get(3)));
assertEquals("text.", docGraph.getText(docGraph.getTokens().get(4)));
}
/**
* Tests the text " This is a test text.", which has to be tokenized into 5
* tokens:
* <ul>
* <li>This</li>
* <li>is</li>
* <li>a</li>
* <li>test</li>
* <li>text.</li>
* </ul>
*/
@Test
public void testTokenize_ByBlanks2() {
SDocumentGraph docGraph = SaltFactory.createSDocumentGraph();
STextualDS primText = docGraph.createTextualDS(" This is a test text. ");
getFixture().setDocumentGraph(docGraph);
getFixture().tokenize(primText, ' ');
assertEquals(5, docGraph.getTokens().size());
assertEquals("This", docGraph.getText(docGraph.getTokens().get(0)));
assertEquals("is", docGraph.getText(docGraph.getTokens().get(1)));
assertEquals("a", docGraph.getText(docGraph.getTokens().get(2)));
assertEquals("test", docGraph.getText(docGraph.getTokens().get(3)));
assertEquals("text.", docGraph.getText(docGraph.getTokens().get(4)));
}
/**
* Tests the text " This is a test text.", which has to be tokenized into 5
* tokens:
* <ul>
* <li>This</li>
* <li>is</li>
* <li>a</li>
* <li>test</li>
* <li>text</li>
* </ul>
*/
@Test
public void testTokenize_ByBlanksAndPunc() {
SDocumentGraph docGraph = SaltFactory.createSDocumentGraph();
STextualDS primText = docGraph.createTextualDS(" This is a test text. ");
getFixture().setDocumentGraph(docGraph);
getFixture().tokenize(primText, ' ', '.');
assertEquals(5, docGraph.getTokens().size());
assertEquals("This", docGraph.getText(docGraph.getTokens().get(0)));
assertEquals("is", docGraph.getText(docGraph.getTokens().get(1)));
assertEquals("a", docGraph.getText(docGraph.getTokens().get(2)));
assertEquals("test", docGraph.getText(docGraph.getTokens().get(3)));
assertEquals("text", docGraph.getText(docGraph.getTokens().get(4)));
}
/**
* Tests the text "This is a test text." on the substring " is a test"
* (offset 4 to 14) which should generate 3 token.
* <ul>
* <li>is</li>
* <li>a</li>
* <li>test</li>
* </ul>
*/
@Test
public void testTokenize_SubstringMiddle() {
SDocumentGraph docGraph = SaltFactory.createSDocumentGraph();
STextualDS primText = docGraph.createTextualDS("This is a test text.");
getFixture().setDocumentGraph(docGraph);
getFixture().tokenize(primText, 4, 14, ' ', '.');
assertEquals(3, docGraph.getTokens().size());
assertEquals("is", docGraph.getText(docGraph.getTokens().get(0)));
assertEquals("a", docGraph.getText(docGraph.getTokens().get(1)));
assertEquals("test", docGraph.getText(docGraph.getTokens().get(2)));
}
/**
* Tests the text "This is a test text." on the substring "This is a test"
* (offset 0 to 14) which should generate 4 token.
* <ul>
* <li>This</li>
* <li>is</li>
* <li>a</li>
* <li>test</li>
* </ul>
*/
@Test
public void testTokenize_SubstringFront() {
SDocumentGraph docGraph = SaltFactory.createSDocumentGraph();
STextualDS primText = docGraph.createTextualDS("This is a test text.");
getFixture().setDocumentGraph(docGraph);
getFixture().tokenize(primText, 0, 14, ' ', '.');
assertEquals(4, docGraph.getTokens().size());
assertEquals("This", docGraph.getText(docGraph.getTokens().get(0)));
assertEquals("is", docGraph.getText(docGraph.getTokens().get(1)));
assertEquals("a", docGraph.getText(docGraph.getTokens().get(2)));
assertEquals("test", docGraph.getText(docGraph.getTokens().get(3)));
}
/**
* Tests the text "This is a test text." on the substring " is a test text."
* (offset 4 to 20) which should generate 4 token.
* <ul>
* <li>is</li>
* <li>a</li>
* <li>test</li>
* <li>text</li>
* </ul>
*/
@Test
public void testTokenize_SubstringEnd() {
SDocumentGraph docGraph = SaltFactory.createSDocumentGraph();
STextualDS primText = docGraph.createTextualDS("This is a test text.");
getFixture().setDocumentGraph(docGraph);
getFixture().tokenize(primText, 4, 20, ' ', '.');
assertEquals(4, docGraph.getTokens().size());
assertEquals("is", docGraph.getText(docGraph.getTokens().get(0)));
assertEquals("a", docGraph.getText(docGraph.getTokens().get(1)));
assertEquals("test", docGraph.getText(docGraph.getTokens().get(2)));
assertEquals("text", docGraph.getText(docGraph.getTokens().get(3)));
}
}
| 32.442308 | 85 | 0.664641 |
f86281d468e1ece0acd65d04faca81c4cd43b7e0 | 871 | package CORBA.Network;
/**
* CORBA.Network/AppointmentListHolder.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from Response.idl
* Saturday, November 23, 2019 4:09:19 o'clock PM EST
*/
public final class AppointmentListHolder implements org.omg.CORBA.portable.Streamable
{
public CORBA.Network.Appointment value[] = null;
public AppointmentListHolder ()
{
}
public AppointmentListHolder (CORBA.Network.Appointment[] initialValue)
{
value = initialValue;
}
public void _read (org.omg.CORBA.portable.InputStream i)
{
value = CORBA.Network.AppointmentListHelper.read (i);
}
public void _write (org.omg.CORBA.portable.OutputStream o)
{
CORBA.Network.AppointmentListHelper.write (o, value);
}
public org.omg.CORBA.TypeCode _type ()
{
return CORBA.Network.AppointmentListHelper.type ();
}
}
| 21.775 | 85 | 0.724455 |
0b809e19a9d7edf27967575a210119b613a3a1b5 | 4,273 | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import android.os.Bundle;
import android.os.SystemProperties;
import android.text.TextUtils;
import android.util.Config;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import com.android.internal.app.AlertActivity;
import com.android.internal.app.AlertController;
/**
* The "dialog" that shows from "License" in the Settings app.
*/
public class SettingsLicenseActivity extends AlertActivity {
private static final String TAG = "SettingsLicenseActivity";
private static final boolean LOGV = false || Config.LOGV;
private static final String DEFAULT_LICENSE_PATH = "/system/etc/NOTICE.html.gz";
private static final String PROPERTY_LICENSE_PATH = "ro.config.license_path";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String fileName = SystemProperties.get(PROPERTY_LICENSE_PATH, DEFAULT_LICENSE_PATH);
if (TextUtils.isEmpty(fileName)) {
Log.e(TAG, "The system property for the license file is empty.");
showErrorAndFinish();
return;
}
InputStreamReader inputReader = null;
StringBuilder data = null;
try {
data = new StringBuilder(2048);
char tmp[] = new char[2048];
int numRead;
if (fileName.endsWith(".gz")) {
inputReader = new InputStreamReader(
new GZIPInputStream(new FileInputStream(fileName)));
} else {
inputReader = new FileReader(fileName);
}
while ((numRead = inputReader.read(tmp)) >= 0) {
data.append(tmp, 0, numRead);
}
} catch (FileNotFoundException e) {
Log.e(TAG, "License HTML file not found at " + fileName, e);
showErrorAndFinish();
return;
} catch (IOException e) {
Log.e(TAG, "Error reading license HTML file at " + fileName, e);
showErrorAndFinish();
return;
} finally {
try {
if (inputReader != null) {
inputReader.close();
}
} catch (IOException e) {
}
}
if (TextUtils.isEmpty(data)) {
Log.e(TAG, "License HTML is empty (from " + fileName + ")");
showErrorAndFinish();
return;
}
WebView webView = new WebView(this);
// Begin the loading. This will be done in a separate thread in WebView.
webView.loadDataWithBaseURL(null, data.toString(), "text/html", "utf-8", null);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
// Change from 'Loading...' to the real title
mAlert.setTitle(getString(R.string.settings_license_activity_title));
}
});
final AlertController.AlertParams p = mAlertParams;
p.mTitle = getString(R.string.settings_license_activity_loading);
p.mView = webView;
p.mForceInverseBackground = true;
setupAlert();
}
private void showErrorAndFinish() {
Toast.makeText(this, R.string.settings_license_activity_unavailable, Toast.LENGTH_LONG)
.show();
finish();
}
}
| 34.459677 | 95 | 0.635385 |
29b994e00eaf5ac8d344d401853c478dc94a9692 | 2,128 | /*
* Copyright 2016-2017 Axioma srl.
*
* 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.holonplatform.auth.exceptions;
import com.holonplatform.auth.Authorizer;
import com.holonplatform.http.ErrorResponse.ErrorResponseException;
/**
* Exception which may be thrown during authorization
*
* @since 5.0.0
*
* @see Authorizer
*/
public class AuthorizationException extends ErrorResponseException {
private static final long serialVersionUID = -5122471221712808958L;
/**
* Constructor
* @param errorCode Error code
* @param errorDescription Error description, i.e. a human-readable explanation of this error
*/
public AuthorizationException(String errorCode, String errorDescription) {
super(errorCode, errorDescription);
}
/**
* Constructor
* @param errorCode Error code
* @param errorDescription Error description, i.e. a human-readable explanation of this error
* @param httpStatus HTTP status code to represent error as a HTTP response
*/
public AuthorizationException(String errorCode, String errorDescription, int httpStatus) {
super(errorCode, errorDescription, httpStatus);
}
/**
* Constructor
* @param errorCode Error code
* @param errorDescription Error description, i.e. a human-readable explanation of this error
* @param errorURI Error URI that leads to further details about this error
* @param httpStatus HTTP status code to represent error as a HTTP response
*/
public AuthorizationException(String errorCode, String errorDescription, String errorURI, int httpStatus) {
super(errorCode, errorDescription, errorURI, httpStatus);
}
}
| 33.777778 | 108 | 0.761748 |
f76df7b7f4a1d24f881507e65f65401147690085 | 359 | package com.mercadopago.android.px.model;
public class TicketPayer extends Payer {
public TicketPayer(final Identification identification, final String email, final String firstName,
final String lastName) {
setIdentification(identification);
setEmail(email);
setFirstName(firstName);
setLastName(lastName);
}
} | 35.9 | 103 | 0.718663 |
fbee77011c56401361b1322c5a297668904d69a8 | 7,196 | /*
* Copyright 2012 Shared Learning Collaborative, LLC
*
* 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.slc.sli.sample.transform;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slc.sli.sample.entities.AcademicSubjectType;
import org.slc.sli.sample.entities.GradeLevelType;
import org.slc.sli.sample.entities.LearningObjective;
import org.slc.sli.sample.entities.LearningStandardId;
import org.slc.sli.sample.entities.LearningStandardIdentityType;
import org.slc.sli.sample.entities.LearningStandardReferenceType;
import org.slc.sli.sample.transform.CcsCsv2XmlTransformer.LearningStandardResult;
/**
* @author dliu
*
* Transform the Common Core Standard Math csv to edfi xml
*/
public class CCSMathCSV2XMLTransformer {
// input csv files
private static final String ccsCSVFile = "data/CC_Standards_6.25.10-Math.csv";
// output Ed-Fi xml file
private static final String interchangeCCSFile = "data/InterchangeAssessmentMetadata-CCS-Math.xml";
private static final String outputPath = "data/";
private static String GRADE_LEVELS = "K12345678";
private static Pattern PATTERN = Pattern.compile("^([^.]+).([^.]+).(.+)");
public static void main(String[] args) throws Exception {
CcsCsvReader learningStandardReader = new CcsCsvReader();
learningStandardReader.setFileLocation(ccsCSVFile);
learningStandardReader.setContainsCopyright(true);
learningStandardReader.load();
CcsCsv2XmlTransformer transformer = new CcsCsv2XmlTransformer();
transformer.setCcsCsvReader(learningStandardReader);
transformer.setOutputLocation(interchangeCCSFile);
transformer.setAcademicSubjectType(AcademicSubjectType.MATHEMATICS);
// TODO set the learningObjectiveGenerator to handle difference between math and english to
// build common core standard hierarchy, the code is the same as in english csv to xml
// transformer and no learningObjective hierarchy is created for now
transformer.setLearningObjectiveGenerator(new CcsCsv2XmlTransformer.LearningObjectiveGenerator() {
@Override
Collection<LearningObjective> generateLearningObjectives(
Map<String, Collection<CcsCsv2XmlTransformer.LearningStandardResult>> learningObjectiveIdToLearningStandardResults,
Map<String, String> idToGuidMap)
throws IOException {
Collection<LearningObjective> learningObjectives = new ArrayList<LearningObjective>();
for (String key : learningObjectiveIdToLearningStandardResults.keySet()) {
Collection<LearningStandardResult> learningStandardResults = learningObjectiveIdToLearningStandardResults
.get(key);
LearningObjective learningObjective = new LearningObjective();
LearningStandardId learningStandardId = new LearningStandardId();
learningStandardId.setIdentificationCode(CcsCsv2XmlTransformer.IdToGuidMapper.getInstance()
.getGuid(key));
learningObjective.setLearningObjectiveId(learningStandardId);
LearningStandardResult firstLearningStandardResult = learningStandardResults.iterator().next();
for (LearningStandardResult learningStandardResult : learningStandardResults) {
LearningStandardReferenceType learningStandardReferenceType = new LearningStandardReferenceType();
LearningStandardIdentityType learningStandardIdentityType = new LearningStandardIdentityType();
learningStandardIdentityType.setLearningStandardId(learningStandardResult.getLearningStandard()
.getLearningStandardId());
learningStandardReferenceType.setLearningStandardIdentity(learningStandardIdentityType);
learningObjective.getLearningStandardReference().add(learningStandardReferenceType);
}
learningObjective.setObjective(firstLearningStandardResult.getCategory());
learningObjective.setAcademicSubject(firstLearningStandardResult.getLearningStandard()
.getSubjectArea());
learningObjective.setObjectiveGradeLevel(firstLearningStandardResult.getLearningStandard()
.getGradeLevel());
learningObjectives.add(learningObjective);
}
return learningObjectives;
}
});
transformer.setDotNotationToId(new CcsCsv2XmlTransformer.DotNotationToId() {
@Override
String getId(String dotNotation) {
String id = dotNotation.replaceAll(" ", "");
Matcher matcher = PATTERN.matcher(id);
if(matcher.matches()) {
StringBuilder sb = new StringBuilder();
sb.append(matcher.group(1)).append(".").append(matcher.group(2)).append(".").append(matcher.group(3).replace(".", ""));
id = sb.toString();
}
// add Math. to id if the id start with k-8,otherwise add Math.HS to id
if (GRADE_LEVELS.indexOf(id.charAt(0)) >= 0) {
id = "Math." + id;
} else {
id = "Math.HS" + id.replaceFirst("[.]", "-");
}
return id;
}
});
transformer.setGradeLevelMapper(new CcsCsv2XmlTransformer.GradeLevelMapper() {
@Override
public int getGradeLevel(String dotNotation) {
String[] gradeLevels = dotNotation.split("\\.");
int gradeLevel = 0;
try {
gradeLevel = Integer.parseInt(gradeLevels[0]);
} catch (NumberFormatException e) {
if (gradeLevels[0].toLowerCase().equals("k")) {
gradeLevel = 0;
} else {
// return Ninth grade for high school for now
// TODO map the grade level for each high school math
gradeLevel = 9;
}
}
return gradeLevel;
}
});
transformer.printLearningStandards();
SchemaValidator.check(outputPath);
System.out.println(transformer.getCopyright());
}
}
| 50.321678 | 139 | 0.646609 |
58ca8cef3946502d35dd71eb9a64bb544e3038a1 | 165 | package eu.cloudopting.tosca.nodes;
import java.util.HashMap;
public interface CloudOptingNode {
public abstract String prepare(HashMap<String, String> data);
} | 18.333333 | 62 | 0.793939 |
f4f8c8029a7c44bee88639807bb1b36999355199 | 9,055 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.material.color;
import com.google.android.material.R;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.content.res.loader.ResourcesLoader;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import androidx.annotation.ChecksSdkIntAtLeast;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import java.util.HashMap;
import java.util.Map;
/**
* A class for harmonizing color resources and attributes.
*
* <p>This class is used for harmonizing color resources/attributes defined in xml at runtime. The
* values of harmonized resources/attributes will be overridden, and afterwards if you retrieve the
* value from the associated context, or inflate resources like layouts that are using those
* harmonized resources/attributes, the overridden values will be used instead.
*
* <p>If you need to harmonize color resources at runtime, see:
* {@link #applyToContextIfAvailable(Context, HarmonizedColorsOptions)}, and
* {@link #wrapContextIfAvailable(Context, HarmonizedColorsOptions)}
*/
public class HarmonizedColors {
private HarmonizedColors() {}
private static final String TAG = HarmonizedColors.class.getSimpleName();
/**
* Harmonizes the specified color resources, attributes, and theme overlay in the {@link
* Context} provided.
*
* <p>If harmonization is not available, provided color resources and attributes in {@link
* HarmonizedColorsOptions} will not be harmonized.
*
* @param context The target context.
* @param options The {@link HarmonizedColorsOptions} object that specifies the resource ids,
* color attributes to be harmonized and the color attribute to harmonize with.
*/
@NonNull
public static void applyToContextIfAvailable(
@NonNull Context context, @NonNull HarmonizedColorsOptions options) {
if (!isHarmonizedColorAvailable()) {
return;
}
Map<Integer, Integer> colorReplacementMap =
createHarmonizedColorReplacementMap(context, options);
int themeOverlay = options.getThemeOverlayResourceId(/* defaultThemeOverlay= */ 0);
if (addResourcesLoaderToContext(context, colorReplacementMap) && themeOverlay != 0) {
ThemeUtils.applyThemeOverlay(context, themeOverlay);
}
}
/**
* Wraps the given Context from HarmonizedColorsOptions with the color resources being harmonized.
*
* <p>If harmonization is not available, provided color resources and attributes in {@link
* HarmonizedColorsOptions} will not be harmonized.
*
* @param context The target context.
* @param options The {@link HarmonizedColorsOptions} object that specifies the resource ids,
* color attributes to be harmonized and the color attribute to harmonize with.
* @return the new context with resources being harmonized. If resources are not harmonized
* successfully, the context passed in will be returned.
*/
@NonNull
public static Context wrapContextIfAvailable(
@NonNull Context context, @NonNull HarmonizedColorsOptions options) {
if (!isHarmonizedColorAvailable()) {
return context;
}
// Retrieve colors from original context passed in before the resources are overridden below.
Map<Integer, Integer> colorReplacementMap =
createHarmonizedColorReplacementMap(context, options);
// Empty themeOverlay is used as default to prevent ContextThemeWrapper uses the default theme
// of the application to wrap Context.
int themeOverlay =
options.getThemeOverlayResourceId(R.style.ThemeOverlay_Material3_HarmonizedColors_Empty);
ContextThemeWrapper themeWrapper = new ContextThemeWrapper(context, themeOverlay);
// Because ContextThemeWrapper does not provide a new set of resources, override config to
// retrieve the new set of resources and to keep the original context's resources intact.
themeWrapper.applyOverrideConfiguration(new Configuration());
return addResourcesLoaderToContext(themeWrapper, colorReplacementMap) ? themeWrapper : context;
}
/**
* <p>If harmonization is not available, color will not be harmonized.
*
* @see #applyToContextIfAvailable(Context, HarmonizedColorsOptions)
* @see #wrapContextIfAvailable(Context, HarmonizedColorsOptions)
* @return {@code true} if harmonized colors are available on the current SDK level, otherwise
* {@code false} will be returned.
*/
@ChecksSdkIntAtLeast(api = VERSION_CODES.R)
public static boolean isHarmonizedColorAvailable() {
return VERSION.SDK_INT >= VERSION_CODES.R;
}
@RequiresApi(api = VERSION_CODES.LOLLIPOP)
private static Map<Integer, Integer> createHarmonizedColorReplacementMap(
Context originalContext, HarmonizedColorsOptions options) {
Map<Integer, Integer> colorReplacementMap = new HashMap<>();
int colorToHarmonizeWith =
MaterialColors.getColor(originalContext, options.getColorAttributeToHarmonizeWith(), TAG);
// Harmonize color resources.
for (int colorResourceId : options.getColorResourceIds()) {
int harmonizedColor =
MaterialColors.harmonize(
ContextCompat.getColor(originalContext, colorResourceId), colorToHarmonizeWith);
colorReplacementMap.put(colorResourceId, harmonizedColor);
}
HarmonizedColorAttributes colorAttributes = options.getColorAttributes();
if (colorAttributes != null) {
int[] attributes = colorAttributes.getAttributes();
if (attributes.length > 0) {
// Harmonize theme overlay attributes in the custom theme overlay. If custom theme overlay
// is not provided, look up resources value the theme attributes point to and
// harmonize directly.
int themeOverlay = colorAttributes.getThemeOverlay();
TypedArray themeAttributesTypedArray = originalContext.obtainStyledAttributes(attributes);
TypedArray themeOverlayAttributesTypedArray =
themeOverlay != 0
? new ContextThemeWrapper(originalContext, themeOverlay)
.obtainStyledAttributes(attributes)
: null;
addHarmonizedColorAttributesToReplacementMap(
colorReplacementMap,
themeAttributesTypedArray,
themeOverlayAttributesTypedArray,
colorToHarmonizeWith);
themeAttributesTypedArray.recycle();
if (themeOverlayAttributesTypedArray != null) {
themeOverlayAttributesTypedArray.recycle();
}
}
}
return colorReplacementMap;
}
@RequiresApi(api = VERSION_CODES.R)
private static boolean addResourcesLoaderToContext(
Context context, Map<Integer, Integer> colorReplacementMap) {
ResourcesLoader resourcesLoader =
ColorResourcesLoaderCreator.create(context, colorReplacementMap);
if (resourcesLoader != null) {
context.getResources().addLoaders(resourcesLoader);
return true;
}
return false;
}
// TypedArray.getType() requires API >= 21.
@RequiresApi(api = VERSION_CODES.LOLLIPOP)
private static void addHarmonizedColorAttributesToReplacementMap(
@NonNull Map<Integer, Integer> colorReplacementMap,
@NonNull TypedArray themeAttributesTypedArray,
@Nullable TypedArray themeOverlayAttributesTypedArray,
@ColorInt int colorToHarmonizeWith) {
TypedArray resourceIdTypedArray =
themeOverlayAttributesTypedArray != null
? themeOverlayAttributesTypedArray
: themeAttributesTypedArray;
for (int i = 0; i < themeAttributesTypedArray.getIndexCount(); i++) {
int resourceId = resourceIdTypedArray.getResourceId(i, 0);
if (resourceId != 0
&& themeAttributesTypedArray.hasValue(i)
&& isColorResource(themeAttributesTypedArray.getType(i))) {
int colorToHarmonize = themeAttributesTypedArray.getColor(i, 0);
colorReplacementMap.put(
resourceId, MaterialColors.harmonize(colorToHarmonize, colorToHarmonizeWith));
}
}
}
private static boolean isColorResource(int attrType) {
return (TypedValue.TYPE_FIRST_COLOR_INT <= attrType)
&& (attrType <= TypedValue.TYPE_LAST_COLOR_INT);
}
}
| 42.511737 | 100 | 0.740917 |
c73f9f7ff82ffea42acb59a63dd3cf6bddec319c | 13,460 | package edu.rhit.groupalarm.groupalarm.Fragments;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import edu.rhit.groupalarm.groupalarm.Adapters.AlarmAdapter;
import edu.rhit.groupalarm.groupalarm.Adapters.FriendsAlarmAdapter;
import edu.rhit.groupalarm.groupalarm.Alarm;
import edu.rhit.groupalarm.groupalarm.FriendsActivity;
import edu.rhit.groupalarm.groupalarm.MainActivity;
import edu.rhit.groupalarm.groupalarm.R;
import edu.rhit.groupalarm.groupalarm.SettingsActivity;
import edu.rhit.groupalarm.groupalarm.User;
/**
* A placeholder fragment containing a simple view.
*/
public class AlarmFragment extends Fragment {
public static final int MODE_PRIVATE = 0x0000;
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String CURRENT_USER = "current_user";
private static final String CurrentTab = "current_tab";
private static final int RC_USER_SETTINGS = 1;
private final static String PREFS = "PREFS";
private static final int RC_FRIEND = 2;
private static Context mContext;
private static ViewPager mViewPager;
// private static SharedPreferences prefs;
private AlarmAdapter mAlarmAdapter;
private User mUser;
private DatabaseReference mCurrentUserRef;
private LogoutListener logoutListener;
private int tab;
// private int currentTab;
public AlarmFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static AlarmFragment newInstance(int sectionNumber, User user, Context context, ViewPager viewPager) {
AlarmFragment fragment = new AlarmFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
args.putParcelable(CURRENT_USER, user);
mContext = context;
mViewPager = viewPager;
// prefs = mContext.getSharedPreferences(PREFS, MODE_PRIVATE);
fragment.setArguments(args);
return fragment;
}
//
// @Override
// public void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//// SharedPreferences prefs = getActivity().getSharedPreferences(PREFS, MODE_PRIVATE);
//// currentTab = prefs.getInt(CurrentTab,0);
//// tab=currentTab;
//// mViewPager.setCurrentItem(currentTab);
//// if (savedInstanceState!=null){
//// currentTab=savedInstanceState.getInt(CurrentTab);
//// }
// }
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
SharedPreferences prefs = getActivity().getSharedPreferences(PREFS, MODE_PRIVATE);
tab = getArguments().getInt(ARG_SECTION_NUMBER) - 1;
// Log.d("aaaaaaaaaaaaaaaa", prefs.getInt(CurrentTab, tab) + "onCreateView");
// currentTab = prefs.getInt(CurrentTab, tab);
// tab = currentTab;
mUser = getArguments().getParcelable(CURRENT_USER);
mCurrentUserRef = FirebaseDatabase.getInstance().getReference().child("users").child(mUser.getmUid());
View rootView;
switch (tab) {
case 0: //My Alarm
rootView = inflater.inflate(R.layout.fragment_my_alarm, container, false);
FloatingActionButton fab = rootView.findViewById(R.id.add_fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addAlarm();
}
});
RecyclerView recyclerView = rootView.findViewById(R.id.recycler_my_alarm);
recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
recyclerView.setHasFixedSize(true);
mAlarmAdapter = new AlarmAdapter(mUser, mContext, recyclerView);
recyclerView.setAdapter(mAlarmAdapter);
Button awakeButton = rootView.findViewById(R.id.button_awaken);
awakeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mUser.setmIsAwake(true);
mCurrentUserRef.child("mIsAwake").setValue(true);
}
});
break;
case 1: //Personal
rootView = inflater.inflate(R.layout.fragment_personal, container, false);
final ImageView statusView = rootView.findViewById(R.id.status_imageview);
mCurrentUserRef.child("mIsAwake").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
boolean awake = dataSnapshot.getValue(boolean.class);
if (awake) {
statusView.setColorFilter(ContextCompat.getColor(mContext, R.color.green));
} else {
statusView.setColorFilter(ContextCompat.getColor(mContext, R.color.red));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
TextView usernameView = rootView.findViewById(R.id.username_textview);
usernameView.setText(mUser.getmUsername());
LinearLayout settingsView = rootView.findViewById(R.id.settings_view);
settingsView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), SettingsActivity.class);
intent.putExtra(MainActivity.EXTRA_USER, mUser);
// startActivity(intent);
startActivityForResult(intent, RC_USER_SETTINGS);
}
});
LinearLayout friendsView = rootView.findViewById(R.id.friends_view);
friendsView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), FriendsActivity.class);
startActivityForResult(intent, RC_FRIEND);
}
});
LinearLayout logoutView = rootView.findViewById(R.id.logout_view);
logoutView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
logoutListener.logout();
}
});
break;
case 2: //Friends Alarm
rootView = inflater.inflate(R.layout.fragment_friends_alarm, container, false);
RecyclerView friendsAlarmRecyclerView = rootView.findViewById(R.id.recycler_friend_list);
friendsAlarmRecyclerView.setHasFixedSize(true);
friendsAlarmRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
FriendsAlarmAdapter adapter = new FriendsAlarmAdapter(getContext());
friendsAlarmRecyclerView.setAdapter(adapter);
break;
default:
rootView = null;
break;
}
return rootView;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof LogoutListener) {
logoutListener = (LogoutListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement LogoutListener");
}
}
@Override
public void onDetach() {
super.onDetach();
logoutListener = null;
}
// @Override
// public void onPause() {
// super.onPause();
// prefs.edit().clear();
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// currentTab = mViewPager.getCurrentItem();
// SharedPreferences.Editor editor = prefs.edit();
// editor.putInt(CurrentTab, currentTab);
// editor.commit();
// Log.d("aaaaaaaaaaa", "onDestroy" + currentTab);
// }
//
// @Override
// public void onResume() {
// super.onResume();
// Log.d("aaaaaaaaaaaaa", "onResume" + currentTab);
// }
private void addAlarm() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle(R.string.set_time);
View view = getLayoutInflater().inflate(R.layout.add_alarm, null, false);
TimePicker mTimePicker = view.findViewById(R.id.timepicker);
DateFormat df = new SimpleDateFormat("HH:mm");
String date = df.format(Calendar.getInstance().getTime());
String[] time = date.split(":");
int hr = Integer.parseInt(time[0]);
int min = Integer.parseInt(time[1]);
final int[] hourAndMinute = {hr, min};
mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
hourAndMinute[0] = hourOfDay;
hourAndMinute[1] = minute;
}
});
builder.setView(view);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mUser.setmIsAwake(false);
boolean hasDuplicate = false;
ArrayList<Alarm> currentAlarms = mAlarmAdapter.getmAlarmList();
for (int i = 0; i < currentAlarms.size(); i++) {
if (hourAndMinute[0] == currentAlarms.get(i).getmHour() && hourAndMinute[1] == currentAlarms.get(i).getmMinute()) {
hasDuplicate = true;
currentAlarms.get(i).setmOpen(true);
break;
}
}
if (!hasDuplicate) {
Alarm currentAlarm = new Alarm(hourAndMinute[0], hourAndMinute[1], mUser.getmUid());
String hr = hourAndMinute[0] < 10 ? "0" + hourAndMinute[0] : "" + hourAndMinute[0];
String min = hourAndMinute[1] < 10 ? "0" + hourAndMinute[1] : "" + hourAndMinute[1];
int id = Integer.parseInt(String.format("%s%s", hr, min));
currentAlarm.setAlarmID(id);
currentAlarm.setmStringHour(String.format("%s", hr));
currentAlarm.setmStringMinute(String.format("%s", min));
currentAlarm.setmKey(currentAlarm.getOwnerId() + currentAlarm.getmStringHour() + currentAlarm.getmStringMinute());
mAlarmAdapter.addAlarm(currentAlarm);
mUser.setmIsAwake(false);
mCurrentUserRef.child("mIsAwake").setValue(false);
}
}
});
builder.setNegativeButton(android.R.string.cancel, null);
builder.create().show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == RC_USER_SETTINGS) {
mUser = data.getParcelableExtra(MainActivity.EXTRA_USER);
}
mViewPager.postDelayed(new Runnable() {
@Override
public void run() {
mViewPager.setCurrentItem(1);
}
}, 200);
}
}
// public void onSaveInstanceState(Bundle outState) {
// outState.putInt(CurrentTab, currentTab);
// }
public interface LogoutListener {
void logout();
}
} | 41.671827 | 135 | 0.613373 |
5eb7b0afcfbca7978668866931f3995c448d2090 | 786 | package ar.com.javacuriosities.networking.tcp.handler;
public class ServerSocketInputHandler {
public String processInput(String currentInput) {
String output = "Welcome - Waiting commands";
if (currentInput != null) {
if ("Greetings".equalsIgnoreCase(currentInput)) {
output = "Welcome";
} else if ("Write".equalsIgnoreCase(currentInput)) {
output = "Writing data";
} else if ("Read".equalsIgnoreCase(currentInput)) {
output = "Reading data";
} else if ("Exit".equalsIgnoreCase(currentInput)) {
output = "Bye";
} else {
output = "Invalid Command";
}
}
return output;
}
} | 35.727273 | 65 | 0.536896 |
9d25d5afaf161ef925ed0bda2a34ae6fc098f14b | 3,804 | /*
* ictk - Internet Chess ToolKit
* More information is available at http://jvarsoke.github.io/ictk
* Copyright (c) 1997-2014 J. Varsoke <ictk.jvarsoke [at] neverbox.com>
*
* 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 ictk.boardgame.chess;
import ictk.boardgame.Player;
/* ChessPlayer **************************************************************/
/** A ChessPlayer is usually a person, but could be a computer or a Team
* if it implements the appropriate interface.
*/
public class ChessPlayer extends Player {
public static final byte NO_TITLE = 0,
/** Grand Master */
GM = 1,
/** Women's Grand Master */
WGM = 2,
/** Internation Master */
IM = 3,
/** Women's International Master */
WIM = 4,
/** FIDE Master */
FM = 5,
/** Women's FIDE Master */
WFM = 6,
/** National Master */
NM = 7,
/** Women's National Master */
WNM = 8,
/** Some other title that isn't standard */
OTHER_TITLE = 9;
/** titles such as GM, WGM, FM, etc **/
protected byte title;
protected int rating;
public ChessPlayer () {
}
public ChessPlayer (String n) {
super(n);
}
public ChessPlayer (String n, int _rating) {
super (n);
rating = _rating;
}
/* getTitle **************************************************************/
/** returns a title equal to on of the preset static values on ChessPlayer.
*/
public byte getTitle () { return title; }
/* getRating *************************************************************/
/** typically this is the Elo rating set by FIDE, but could also
* be FICS, USCF or other numerical rating.
*/
public int getRating() { return rating; }
/* setTitle **************************************************************/
/** returns a title equal to on of the preset static values on ChessPlayer.
*/
public void setTitle (int t) {
if (t > 128 || t < -128)
throw new IllegalArgumentException ("Title needs to be of byte size");
title = (byte) t;
}
/* setRating *************************************************************/
/** typically this is the Elo rating set by FIDE, but could also
* be FICS, USCF or other numerical rating.
*/
public void setRating (int rating) { this.rating = rating; }
/* toString **************************************************************/
/** diagonostic function.
*/
public String toString () {
String str = getName();
if (rating > 0)
str += "(" + rating + ")";
return str;
}
}
| 35.886792 | 80 | 0.559674 |
f78333fcd384c91554179bb36211a39f2b47d593 | 16,317 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root.
package com.microsoft.alm.plugin.operations;
import com.google.common.util.concurrent.SettableFuture;
import com.microsoft.alm.build.webapi.BuildHttpClient;
import com.microsoft.alm.build.webapi.model.Build;
import com.microsoft.alm.build.webapi.model.BuildQueryOrder;
import com.microsoft.alm.build.webapi.model.BuildReason;
import com.microsoft.alm.build.webapi.model.BuildRepository;
import com.microsoft.alm.build.webapi.model.BuildResult;
import com.microsoft.alm.build.webapi.model.BuildStatus;
import com.microsoft.alm.build.webapi.model.DefinitionReference;
import com.microsoft.alm.build.webapi.model.DefinitionType;
import com.microsoft.alm.build.webapi.model.QueryDeletedOption;
import com.microsoft.alm.core.webapi.model.TeamProjectReference;
import com.microsoft.alm.plugin.AbstractTest;
import com.microsoft.alm.plugin.authentication.AuthenticationInfo;
import com.microsoft.alm.plugin.context.RepositoryContext;
import com.microsoft.alm.plugin.context.ServerContext;
import com.microsoft.alm.plugin.context.ServerContextManager;
import com.microsoft.alm.sourcecontrol.webapi.model.GitRepository;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ServerContextManager.class})
public class BuildStatusLookupOperationTest extends AbstractTest {
private ServerContextManager serverContextManager;
private void setupLocalTests(GitRepository gitRepository, List<Build> builds) {
MockitoAnnotations.initMocks(this);
BuildHttpClient buildHttpClient = Mockito.mock(BuildHttpClient.class);
when(buildHttpClient.getBuilds(any(UUID.class), any(List.class), any(List.class),
anyString(), any(Date.class), any(Date.class), anyString(), any(BuildReason.class),
eq(BuildStatus.COMPLETED), any(BuildResult.class), any(List.class), any(List.class),
any(DefinitionType.class), eq(100), anyString(), anyInt(), any(QueryDeletedOption.class),
eq(BuildQueryOrder.FINISH_TIME_DESCENDING))).thenReturn(builds);
AuthenticationInfo authInfo = new AuthenticationInfo("user", "pass", "serverURI", "user");
ServerContext authenticatedContext = Mockito.mock(ServerContext.class);
when(authenticatedContext.getBuildHttpClient()).thenReturn(buildHttpClient);
when(authenticatedContext.getTeamProjectReference()).thenReturn(new TeamProjectReference());
when(authenticatedContext.getGitRepository()).thenReturn(gitRepository);
serverContextManager = Mockito.mock(ServerContextManager.class);
when(serverContextManager.get(anyString())).thenReturn(authenticatedContext);
when(serverContextManager.createContextFromGitRemoteUrl(anyString(), anyBoolean())).thenReturn(authenticatedContext);
PowerMockito.mockStatic(ServerContextManager.class);
when(ServerContextManager.getInstance()).thenReturn(serverContextManager);
}
@Test(expected = IllegalArgumentException.class)
public void testConstructor_nullRepo() {
BuildStatusLookupOperation operation = new BuildStatusLookupOperation(null, false);
}
@Test
public void testConstructor_goodInputs() {
BuildStatusLookupOperation operation1 = new BuildStatusLookupOperation(
RepositoryContext.createGitContext(
"/root/one",
"repoName",
"branch",
URI.create("http://url")),
false);
}
@Test
public void testDoWork_noMatch() throws InterruptedException, ExecutionException, TimeoutException {
TestData data = new TestData();
data.addBuild(4, data.currentRepo, data.otherBranch); // branch doesn't match
data.addBuild(3, data.otherRepo, data.currentBranch); // repo doesn't match
data.addBuild(1, data.otherRepo, data.otherBranch); // nothing matches
setupLocalTests(data.currentRepo, data.builds);
BuildStatusLookupOperation operation = new BuildStatusLookupOperation(
data.getRepositoryContext(), false);
data.setupListener(operation);
operation.doWork(null);
Assert.assertTrue(data.startedCalled.get(1, TimeUnit.SECONDS));
Assert.assertTrue(data.completedCalled.get(1, TimeUnit.SECONDS));
BuildStatusLookupOperation.BuildStatusResults results = data.buildResults.get(1, TimeUnit.SECONDS);
Assert.assertNull(results.getError());
Assert.assertEquals(0, results.getBuilds().size());
}
@Test
public void testDoWork_1Match() throws InterruptedException, ExecutionException, TimeoutException {
TestData data = new TestData();
data.addBuild(4, data.currentRepo, data.otherBranch); // branch doesn't match
data.addBuild(3, data.otherRepo, data.currentBranch); // repo doesn't match
data.addBuild(2, data.currentRepo, data.currentBranch); // MATCH
data.addBuild(1, data.otherRepo, data.otherBranch); // nothing matches
setupLocalTests(data.currentRepo, data.builds);
BuildStatusLookupOperation operation = new BuildStatusLookupOperation(
data.getRepositoryContext(), false);
data.setupListener(operation);
operation.doWork(null);
Assert.assertTrue(data.startedCalled.get(1, TimeUnit.SECONDS));
Assert.assertTrue(data.completedCalled.get(1, TimeUnit.SECONDS));
BuildStatusLookupOperation.BuildStatusResults results = data.buildResults.get(1, TimeUnit.SECONDS);
Assert.assertNull(results.getError());
Assert.assertEquals(1, results.getBuilds().size());
// Verify the right build was returned
Assert.assertEquals(2, results.getBuilds().get(0).getBuildId());
Assert.assertEquals(data.currentRepo.getId().toString(), results.getBuilds().get(0).getRepositoryId());
Assert.assertEquals(data.currentBranch, results.getBuilds().get(0).getBranch());
}
@Test
public void testDoWork_2Matches() throws InterruptedException, ExecutionException, TimeoutException {
TestData data = new TestData();
data.addBuild(8, data.currentRepo, data.otherBranch); // branch doesn't match
data.addBuild(7, data.otherRepo, data.currentBranch); // repo doesn't match
data.addBuild(6, data.currentRepo, data.currentBranch); // MATCH on exact branch
data.addBuild(5, data.currentRepo, TestData.MASTER); // MATCH on Repo and master
data.addBuild(4, data.otherRepo, data.otherBranch); // nothing matches
setupLocalTests(data.currentRepo, data.builds);
BuildStatusLookupOperation operation = new BuildStatusLookupOperation(
data.getRepositoryContext(), false);
data.setupListener(operation);
operation.doWork(null);
Assert.assertTrue(data.startedCalled.get(1, TimeUnit.SECONDS));
Assert.assertTrue(data.completedCalled.get(1, TimeUnit.SECONDS));
BuildStatusLookupOperation.BuildStatusResults results = data.buildResults.get(1, TimeUnit.SECONDS);
Assert.assertNull(results.getError());
Assert.assertEquals(2, results.getBuilds().size());
// Verify that the first build in the list is for master
Assert.assertEquals(5, results.getBuilds().get(0).getBuildId());
Assert.assertEquals(data.currentRepo.getId().toString(), results.getBuilds().get(0).getRepositoryId());
Assert.assertEquals(TestData.MASTER, results.getBuilds().get(0).getBranch());
// Verify that the last build in the list is for branch1
Assert.assertEquals(6, results.getBuilds().get(1).getBuildId());
Assert.assertEquals(data.currentRepo.getId().toString(), results.getBuilds().get(1).getRepositoryId());
Assert.assertEquals(data.currentBranch, results.getBuilds().get(1).getBranch());
}
@Test
public void testDoWork_matchOnMasterOnly() throws InterruptedException, ExecutionException, TimeoutException {
TestData data = new TestData();
data.addBuild(8, data.currentRepo, data.otherBranch); // branch doesn't match
data.addBuild(7, data.otherRepo, data.currentBranch); // repo doesn't match
data.addBuild(5, data.currentRepo, TestData.MASTER); // MATCH on Repo and master
data.addBuild(4, data.otherRepo, data.otherBranch); // nothing matches
setupLocalTests(data.currentRepo, data.builds);
BuildStatusLookupOperation operation = new BuildStatusLookupOperation(
data.getRepositoryContext(), false);
data.setupListener(operation);
operation.doWork(null);
Assert.assertTrue(data.startedCalled.get(1, TimeUnit.SECONDS));
Assert.assertTrue(data.completedCalled.get(1, TimeUnit.SECONDS));
BuildStatusLookupOperation.BuildStatusResults results = data.buildResults.get(1, TimeUnit.SECONDS);
Assert.assertNull(results.getError());
Assert.assertEquals(1, results.getBuilds().size());
// Verify that the first build in the list is for master
Assert.assertEquals(5, results.getBuilds().get(0).getBuildId());
Assert.assertEquals(data.currentRepo.getId().toString(), results.getBuilds().get(0).getRepositoryId());
Assert.assertEquals(TestData.MASTER, results.getBuilds().get(0).getBranch());
}
@Test
public void testDoWork_moreMatches() throws InterruptedException, ExecutionException, TimeoutException {
TestData data = new TestData();
data.addBuild(8, data.currentRepo, data.otherBranch); // branch doesn't match
data.addBuild(7, data.otherRepo, data.currentBranch); // repo doesn't match
data.addBuild(6, data.currentRepo, TestData.MASTER); // MATCH on Repo and master
data.addBuild(5, data.currentRepo, data.currentBranch); // MATCH on exact branch
data.addBuild(4, data.otherRepo, data.otherBranch); // nothing matches
data.addBuild(3, data.currentRepo, TestData.MASTER); // OLD MATCH on Repo and master
data.addBuild(2, data.currentRepo, data.currentBranch); // OLD MATCH on exact branch
data.addBuild(1, data.currentRepo, data.currentBranch); // OLD MATCH on exact branch
setupLocalTests(data.currentRepo, data.builds);
BuildStatusLookupOperation operation = new BuildStatusLookupOperation(
data.getRepositoryContext(), false);
data.setupListener(operation);
operation.doWork(null);
Assert.assertTrue(data.startedCalled.get(1, TimeUnit.SECONDS));
Assert.assertTrue(data.completedCalled.get(1, TimeUnit.SECONDS));
BuildStatusLookupOperation.BuildStatusResults results = data.buildResults.get(1, TimeUnit.SECONDS);
Assert.assertNull(results.getError());
Assert.assertEquals(2, results.getBuilds().size());
// Verify that the first build in the list is for master
Assert.assertEquals(6, results.getBuilds().get(0).getBuildId());
Assert.assertEquals(data.currentRepo.getId().toString(), results.getBuilds().get(0).getRepositoryId());
Assert.assertEquals(TestData.MASTER, results.getBuilds().get(0).getBranch());
// Verify that the last build in the list is for branch1
Assert.assertEquals(5, results.getBuilds().get(1).getBuildId());
Assert.assertEquals(data.currentRepo.getId().toString(), results.getBuilds().get(1).getRepositoryId());
Assert.assertEquals(data.currentBranch, results.getBuilds().get(1).getBranch());
}
@Test
public void testDoWork_failure() throws InterruptedException, ExecutionException, TimeoutException {
TestData data = new TestData();
data.addBuild(2, data.currentRepo, data.currentBranch);
setupLocalTests(data.currentRepo, null);
BuildStatusLookupOperation operation = new BuildStatusLookupOperation(
data.getRepositoryContext(), false);
data.setupListener(operation);
operation.doWork(null); // This should cause a null point exception during the operation
Assert.assertTrue(data.startedCalled.get(1, TimeUnit.SECONDS));
Assert.assertTrue(data.completedCalled.get(1, TimeUnit.SECONDS));
Assert.assertEquals(NullPointerException.class, data.buildResults.get(1, TimeUnit.SECONDS).getError().getClass());
}
private class TestData {
public static final String MASTER = "refs/heads/master";
public final GitRepository currentRepo;
public final String currentBranch;
public final GitRepository otherRepo;
public final String otherBranch;
public final List<Build> builds;
public final SettableFuture<Boolean> startedCalled;
public final SettableFuture<Boolean> completedCalled;
public final SettableFuture<BuildStatusLookupOperation.BuildStatusResults> buildResults;
public TestData() {
this.currentRepo = getRepo("repo1");
this.currentBranch = "branch1";
this.otherRepo = getRepo("repo2");
this.otherBranch = "branch2";
this.builds = new ArrayList<Build>();
this.startedCalled = SettableFuture.create();
this.completedCalled = SettableFuture.create();
this.buildResults = SettableFuture.create();
}
public void addBuild(int buildId, GitRepository repo, String branch) {
builds.add(getBuild(buildId, repo, branch));
}
public void setupListener(BuildStatusLookupOperation operation) {
operation.addListener(new Operation.Listener() {
public void notifyLookupStarted() {
startedCalled.set(true);
}
public void notifyLookupCompleted() {
completedCalled.set(true);
}
@Override
public void notifyLookupResults(Operation.Results lookupResults) {
buildResults.set((BuildStatusLookupOperation.BuildStatusResults) lookupResults);
}
});
}
public RepositoryContext getRepositoryContext() {
return RepositoryContext.createGitContext(
"/root/one",
currentRepo.getName(),
currentBranch,
URI.create(currentRepo.getRemoteUrl()));
}
}
private GitRepository getRepo(String name) {
GitRepository gitRepository = new GitRepository();
gitRepository.setId(UUID.randomUUID());
gitRepository.setName(name);
gitRepository.setRemoteUrl("http://server:8080/tfs/project/_git/" + name);
return gitRepository;
}
private Build getBuild(int id, GitRepository gitRepository, String branch) {
BuildRepository repo = new BuildRepository();
repo.setId(gitRepository.getId().toString());
repo.setName(gitRepository.getName());
repo.setUrl(URI.create(gitRepository.getRemoteUrl()));
Build build = new Build();
build.setId(id);
build.setBuildNumber("number" + id);
build.setDefinition(new DefinitionReference());
build.getDefinition().setId(1);
build.getDefinition().setName("definition1");
build.setResult(BuildResult.SUCCEEDED);
build.setRepository(repo);
build.setSourceBranch(branch);
return build;
}
}
| 50.206154 | 125 | 0.702641 |
9155ee7e1efac5101d027e317fb646e9bcd5c35b | 868 | import layout.FileConfig;
import utils.Constant;
import javax.swing.*;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LotteryMain {
public static void main(String[] args) {
SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm");
JOptionPane.showMessageDialog(null, "[For Your Information]" + "\n" + "The software is valid until " + "\n" + sd.format(Constant.EXPIRED_TIME));
long currentTime = System.currentTimeMillis();
if(currentTime > Constant.EXPIRED_TIME){
JOptionPane.showMessageDialog(null,"The software has expired.");
System.exit(0);
}
if(currentTime < Constant.REGISTER_TIME){
JOptionPane.showMessageDialog(null,"The software has expired.");
System.exit(0);
}
new FileConfig();
}
}
| 31 | 152 | 0.657834 |
c13d515113003b1a4773aec20a56099f9d446e3b | 560 | package segTree;
public class Solution303 {
class NumArray {
private int sum[];
public NumArray(int[] nums) {
sum=new int[nums.length+1];
sum[0]=0;
for (int i = 1; i <sum.length ; i++) {
sum[i]=sum[i-1]+nums[i-1];
}
}
public int sumRange(int i, int j) {
return sum[j+1]-sum[i];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/
}
| 20.740741 | 64 | 0.503571 |
78a42c5e8c3fbdfc6ac56f349e1ffb23fb8a3408 | 6,366 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net.ssl;
import static org.junit.Assert.assertArrayEquals;
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 com.android.org.conscrypt.javax.net.ssl.TestSSLSocketPair;
import com.android.org.conscrypt.tlswire.TlsTester;
import com.android.org.conscrypt.tlswire.handshake.ClientHello;
import com.android.org.conscrypt.tlswire.handshake.HelloExtension;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import tests.net.DelegatingSSLSocketFactory;
@RunWith(JUnit4.class)
public class SSLSocketsTest {
private static class BrokenSSLSocket extends SSLSocket {
@Override public String[] getSupportedCipherSuites() { throw new AssertionError(); }
@Override public String[] getEnabledCipherSuites() { throw new AssertionError(); }
@Override public void setEnabledCipherSuites(String[] strings) { throw new AssertionError(); }
@Override public String[] getSupportedProtocols() { throw new AssertionError(); }
@Override public String[] getEnabledProtocols() { throw new AssertionError(); }
@Override public void setEnabledProtocols(String[] strings) { throw new AssertionError(); }
@Override public SSLSession getSession() { throw new AssertionError(); }
@Override public void addHandshakeCompletedListener(
HandshakeCompletedListener handshakeCompletedListener) { throw new AssertionError(); }
@Override public void removeHandshakeCompletedListener(
HandshakeCompletedListener handshakeCompletedListener) { throw new AssertionError(); }
@Override public void startHandshake() { throw new AssertionError(); }
@Override public void setUseClientMode(boolean b) { throw new AssertionError(); }
@Override public boolean getUseClientMode() { throw new AssertionError(); }
@Override public void setNeedClientAuth(boolean b) { throw new AssertionError(); }
@Override public boolean getNeedClientAuth() { throw new AssertionError(); }
@Override public void setWantClientAuth(boolean b) { throw new AssertionError(); }
@Override public boolean getWantClientAuth() { throw new AssertionError(); }
@Override public void setEnableSessionCreation(boolean b) { throw new AssertionError(); }
@Override public boolean getEnableSessionCreation() { throw new AssertionError(); }
}
private ExecutorService executor;
@Before
public void setUp() {
executor = Executors.newCachedThreadPool();
}
@After
public void tearDown() throws InterruptedException {
executor.shutdown();
executor.awaitTermination(1, TimeUnit.SECONDS);
}
@Test
public void testIsSupported() throws Exception {
SSLSocket s = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
assertTrue(SSLSockets.isSupportedSocket(s));
s = new BrokenSSLSocket();
assertFalse(SSLSockets.isSupportedSocket(s));
}
@Test(expected = IllegalArgumentException.class)
public void setUseSessionTickets_InvalidSocket() {
SSLSockets.setUseSessionTickets(new BrokenSSLSocket(), true);
}
@Test
public void setUseSessionTickets_ValidSocket() throws Exception {
SSLSocket s = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
SSLSockets.setUseSessionTickets(s, true);
ClientHello hello = TlsTester.captureTlsHandshakeClientHello(executor,
new DelegatingSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault()) {
@Override public SSLSocket configureSocket(SSLSocket socket) {
SSLSockets.setUseSessionTickets(socket, true);
return socket;
}
});
assertNotNull(hello.findExtensionByType(HelloExtension.TYPE_SESSION_TICKET));
hello = TlsTester.captureTlsHandshakeClientHello(executor,
new DelegatingSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault()) {
@Override public SSLSocket configureSocket(SSLSocket socket) {
SSLSockets.setUseSessionTickets(socket, false);
return socket;
}
});
assertNull(hello.findExtensionByType(HelloExtension.TYPE_SESSION_TICKET));
}
@Test(expected = IllegalArgumentException.class)
public void exportKeyingMaterial_InvalidSocket() throws Exception {
SSLSockets.exportKeyingMaterial(new BrokenSSLSocket(), "label", null, 20);
}
@Test
public void exportKeyingMaterial_ValidSocket() throws Exception {
TestSSLSocketPair pair = TestSSLSocketPair.create();
String label = "Some label";
int keyLength = 32;
pair.connect();
byte[] clientEkm = SSLSockets.exportKeyingMaterial(pair.client, label, null, keyLength);
byte[] serverEkm = SSLSockets.exportKeyingMaterial(pair.server, label, null, keyLength);
assertNotNull(clientEkm);
assertNotNull(serverEkm);
assertEquals(keyLength, clientEkm.length);
assertEquals(keyLength, serverEkm.length);
assertArrayEquals(clientEkm, serverEkm);
}
}
| 44.517483 | 102 | 0.714577 |
38e12c26b214cd79c8ac96ccb47c7e2278e1ac65 | 3,537 | /*
* Copyright 2019-2022 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core;
import static org.assertj.core.api.Assertions.*;
import org.bson.UuidRepresentation;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.data.mongodb.config.ReadConcernPropertyEditor;
import org.springframework.data.mongodb.config.ReadPreferencePropertyEditor;
import org.springframework.data.mongodb.config.UUidRepresentationPropertyEditor;
import org.springframework.test.util.ReflectionTestUtils;
import com.mongodb.ReadConcern;
import com.mongodb.ReadPreference;
/**
* Unit tests for {@link MongoClientSettingsFactoryBean}.
*
* @author Christoph Strobl
*/
public class MongoClientSettingsFactoryBeanUnitTests {
@Test // DATAMONGO-2384
public void convertsReadPreferenceConcernCorrectly() {
RootBeanDefinition definition = new RootBeanDefinition(MongoClientSettingsFactoryBean.class);
definition.getPropertyValues().addPropertyValue("readPreference", "NEAREST");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerCustomEditor(ReadPreference.class, ReadPreferencePropertyEditor.class);
factory.registerBeanDefinition("factory", definition);
MongoClientSettingsFactoryBean bean = factory.getBean("&factory", MongoClientSettingsFactoryBean.class);
assertThat(ReflectionTestUtils.getField(bean, "readPreference")).isEqualTo(ReadPreference.nearest());
}
@Test // DATAMONGO-2384
public void convertsReadConcernConcernCorrectly() {
RootBeanDefinition definition = new RootBeanDefinition(MongoClientSettingsFactoryBean.class);
definition.getPropertyValues().addPropertyValue("readConcern", "MAJORITY");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerCustomEditor(ReadPreference.class, ReadConcernPropertyEditor.class);
factory.registerBeanDefinition("factory", definition);
MongoClientSettingsFactoryBean bean = factory.getBean("&factory", MongoClientSettingsFactoryBean.class);
assertThat(ReflectionTestUtils.getField(bean, "readConcern")).isEqualTo(ReadConcern.MAJORITY);
}
@Test // DATAMONGO-2427
public void convertsUuidRepresentationCorrectly() {
RootBeanDefinition definition = new RootBeanDefinition(MongoClientSettingsFactoryBean.class);
definition.getPropertyValues().addPropertyValue("uUidRepresentation", "STANDARD");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerCustomEditor(ReadPreference.class, UUidRepresentationPropertyEditor.class);
factory.registerBeanDefinition("factory", definition);
MongoClientSettingsFactoryBean bean = factory.getBean("&factory", MongoClientSettingsFactoryBean.class);
assertThat(ReflectionTestUtils.getField(bean, "uUidRepresentation")).isEqualTo(UuidRepresentation.STANDARD);
}
}
| 41.611765 | 110 | 0.816511 |
f791b217bb3ed1692b47e3eec6f404bdbec42ac7 | 160 | package service.generator;
public class TaskIdGenerator {
private static Integer id = 0;
public static Integer getId() {
return id++;
}
}
| 16 | 35 | 0.65 |
da125c0fbb6f6ab6a3239f2517d340b1b46f883c | 3,252 | package io.miti.shortstop.util;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public final class ContentTypeCache {
/** The single instance of this class. */
private static final ContentTypeCache cache;
/** The map of file extension to MIME type. */
private Map<String, String> map = null;
static {
/** Instantiate the class and populate the map. */
cache = new ContentTypeCache();
}
/**
* Private default constructor.
*/
private ContentTypeCache() {
populateMap();
}
/**
* Populate with some common file content types and their MIME types.
*/
private void populateMap() {
// Create the map
map = new HashMap<String, String>(10);
// Populate with some values
map.put("7z", "application/x-7z-compressed");
map.put("avi", "video/x-msvideo");
map.put("azw", "application/vnd.amazon.ebook");
map.put("bin", "application/octet-stream");
map.put("bmp", "image/bmp");
map.put("cer", "application/pkix-cert");
map.put("css", "text/css");
map.put("csv", "text/csv");
map.put("doc", "application/msword");
map.put("epub", "application/epub+zip");
map.put("gif", "image/gif");
map.put("html", "text/html");
map.put("ico", "image/x-icon");
map.put("ics", "text/calendar");
map.put("jnlp", "application/x-java-jnlp-file");
map.put("jpeg", "image/jpeg");
map.put("jpg", "image/jpeg");
map.put("jpgv", "video/jpeg");
map.put("js", "application/javascript");
map.put("json", "application/json");
map.put("latex", "application/x-latex");
map.put("mpeg", "video/mpeg");
map.put("pdf", "application/pdf");
map.put("pki", "application/pkixcmp");
map.put("rar", "application/x-rar-compressed");
map.put("rtf", "application/rtf");
map.put("swf", "application/x-shockwave-flash");
map.put("tar", "application/x-tar");
map.put("tiff", "image/tiff");
map.put("torrent", "application/x-bittorrent");
map.put("tsv", "text/tab-separated-values");
map.put("txt", "text/plain");
map.put("uu", "text/x-uuencode");
map.put("wmv", "video/x-ms-wmv");
map.put("xls", "application/vnd.ms-excel");
map.put("xml", "application/xml");
map.put("yaml", "text/yaml");
map.put("zip", "application/zip");
}
/**
* Return whether we contain the specified file extension in our map.
* A sample value for key is "html".
*
* @param key the file extension (no leading period)
* @return whether we have the key in our map
*/
public boolean hasContentType(final String key) {
if (key == null) {
return false;
}
return map.containsKey(key.toLowerCase(Locale.US));
}
/**
* Return the MIME type for a file extension.
*
* @param key the file extension (e.g., "css")
* @return the corresponding MIME type, or null if not found
*/
public String getContentTypeMIMEType(final String key) {
final String str = ((key == null) ? null : map.get(key.toLowerCase(Locale.US)));
return str;
}
/**
* Get the single instance of this class.
*
* @return the single instance of this class
*/
public static ContentTypeCache getCache() {
return cache;
}
}
| 29.563636 | 84 | 0.618389 |
9eec41684b9cab26326b62532fcf9f2671761147 | 3,388 | /*
* Copyright 2019 Jonas Yang
*
* 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.yanglinkui.grass;
import static org.junit.jupiter.api.Assertions.*;
import com.yanglinkui.grass.zone.RequestZone;
import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
public class RequestZoneHolderTest {
@Test
public void testFocusDestroy() {
RequestZoneHolder holder1 = RequestZoneHolder.getInstance("zone1");
RequestZoneHolder.getInstance();
RequestZoneHolder.getInstance();
RequestZoneHolder.getInstance();
RequestZoneHolder.getInstance();
RequestZoneHolder.getInstance();
RequestZoneHolder.getInstance();
holder1.destroy();
assertNotNull(RequestZoneHolder.getInstance());
holder1.destroy(true);
assertNull(RequestZoneHolder.getInstance());
}
@Test
public void testGetInstanceByString() {
RequestZoneHolder holder1 = RequestZoneHolder.getInstance("zone1");
RequestZoneHolder holder2 = RequestZoneHolder.getInstance("zone2");
assertNotEquals(holder1, holder2);
holder2.destroy(true);
assertNull(RequestZoneHolder.getInstance());
}
@Test
public void testGetInstanceNoParemeter() throws InterruptedException {
RequestZoneHolder holder1 = RequestZoneHolder.getInstance("zone1");
assertEquals(holder1, RequestZoneHolder.getInstance());
final CountDownLatch latch = new CountDownLatch(1);
new Thread() {
@Override
public void run() {
assertNull(RequestZoneHolder.getInstance());
latch.countDown();
}
}.start();
latch.await();
holder1.destroy(true);
}
@Test
public void testGetInstanceByRequestZone() {
RequestZoneHolder holder0 = RequestZoneHolder.getInstance("zone1");
RequestZone zone = holder0.getRequestZone();
RequestZoneHolder holder1 = RequestZoneHolder.getInstance(zone);
RequestZoneHolder holder2 = RequestZoneHolder.getInstance(zone);
assertNotEquals(holder1, holder2);
assertEquals(holder1.getRequestZone(), holder2.getRequestZone());
holder2.destroy(true);
assertNull(RequestZoneHolder.getInstance());
}
@Test
public void testDestroy() {
RequestZoneHolder holder = RequestZoneHolder.getInstance("zone1");
holder.destroy();
assertNull(RequestZoneHolder.getInstance());
holder = RequestZoneHolder.getInstance("zone1");
RequestZoneHolder holder1 = RequestZoneHolder.getInstance();
assertEquals(holder, holder1);
holder1.destroy();
assertNotNull(RequestZoneHolder.getInstance());
holder.destroy();
holder.destroy();
assertNull(RequestZoneHolder.getInstance());
}
}
| 31.663551 | 75 | 0.68536 |
d686d292c9c2f2e2242e2168ba94869b4ab63a8a | 315 | package zg2pro.controller;
import com.github.zg2pro.spring.rest.basis.exceptions.Zg2proRestServerExceptionsHandler;
import org.springframework.web.bind.annotation.ControllerAdvice;
/**
*
* @author MosesMeyer
*/
@ControllerAdvice
public class ServerExampleAdvisor extends Zg2proRestServerExceptionsHandler {
}
| 22.5 | 88 | 0.831746 |
bbb8fce878a43db2f12e53e4cb9712db59e6a40c | 483 | /*
Problem Name: 1450. Number of Students Doing Homework at a Given Time
Problem Link: https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time/
*/
class Solution {
public int busyStudent(int[] startTime, int[] endTime, int queryTime) {
int cnt = 0;
int n = startTime.length;
for(int i=0;i<n;i++){
if((queryTime >= startTime[i]) && (queryTime <= endTime[i]))
cnt++;
}
return cnt;
}
}
| 30.1875 | 94 | 0.592133 |
5782e80435d756e622a60babcf31e1622584ab0e | 1,662 | /**
* Copyright 2015 Palantir Technologies
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* 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.palantir.atlasdb.keyvalue.partition.util;
import com.palantir.atlasdb.keyvalue.api.RangeRequest;
import com.palantir.common.annotation.Immutable;
@Immutable public class ConsistentRingRangeRequest {
private final RangeRequest rangeRequest;
public RangeRequest get() {
return rangeRequest;
}
private ConsistentRingRangeRequest(RangeRequest rangeRequest) {
this.rangeRequest = rangeRequest;
}
public static ConsistentRingRangeRequest of(RangeRequest rangeRequest) {
return new ConsistentRingRangeRequest(rangeRequest);
}
@Override
public String toString() {
return "CRRR=[" + rangeRequest + "]";
}
@Override
public boolean equals(Object other) {
if (other instanceof ConsistentRingRangeRequest == false) {
return false;
}
ConsistentRingRangeRequest otherCrrr = (ConsistentRingRangeRequest) other;
return get().equals(otherCrrr.get());
}
@Override
public int hashCode() {
return 13 + rangeRequest.hashCode();
}
}
| 33.24 | 82 | 0.712996 |
e305c87f30d00d043f8be368a82f400bef92e6b8 | 5,891 | package com.simonenfp.me.widget;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.DashPathEffect;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;
import com.simonenfp.me.R;
/**
* Created by simonenfp on 2016/8/18.
*/
public class CustomView1 extends View {
Paint mPaint;
Context mContext;
public CustomView1(Context context) {
super(context);
initCustomView(context);
}
public CustomView1(Context context, AttributeSet attrs) {
super(context, attrs);
initCustomView(context);
}
public CustomView1(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initCustomView(context);
}
private void initCustomView(Context context) {
mPaint = new Paint();
mContext = context;
}
@Override
protected void onDraw(Canvas canvas) {
// 设置画布颜色
canvas.drawColor(Color.argb(0x55,0x0,0x0,0x0));
//绘制灰色矩形
mPaint.setColor(Color.GRAY);
canvas.drawRect(0,0,800,800,mPaint);
// Copy the fields from src into this paint. This is equivalent to calling get() on all of the src fields, and calling the corresponding set() methods on this.
mPaint.reset();
// 绘制直线
mPaint.setColor(Color.WHITE);
mPaint.setStrokeWidth(10);
canvas.drawLine(20,20,100,100,mPaint);
mPaint.reset();
// 绘制带边框的矩形
mPaint.setStrokeWidth(10);
mPaint.setARGB(255,255,64,129);
mPaint.setStyle(Paint.Style.STROKE);
RectF rectF = new RectF(120,20,220,120);
canvas.drawRect(rectF,mPaint);
mPaint.reset();
// 绘制实心圆
// mPaint.setStrokeWidth(20);
mPaint.setColor(Color.GREEN);
// Helper for setFlags(),setting or clearing the ANTI_ALIAS_FLAG bit AntiAliasing smooths out the edges of what is being drawn,
// but is has no impact on the interior of the shape. See setDither() and setFilterBitmap() to affect how colors are treated.
// 抗锯齿平滑
mPaint.setAntiAlias(true);
canvas.drawCircle(300,70,50,mPaint);
mPaint.reset();
// 绘制椭圆
mPaint.setColor(Color.YELLOW);
RectF rectF2=new RectF(380,20, 580, 120);
canvas.drawOval(rectF2, mPaint);
mPaint.reset();
// 绘制文字
mPaint.setColor(Color.rgb(0x0,0x0,0x0));
mPaint.setTextSize(60);
mPaint.setUnderlineText(true);
canvas.drawText("Android", 600, 100, mPaint);
mPaint.reset();
// 把文字Android平移
canvas.translate(-300,100);
mPaint.setTextSize(60);
mPaint.setUnderlineText(true);
mPaint.setColor(Color.rgb(0x3F,0x51,0xB5));
canvas.drawText("Android",600,100,mPaint);
mPaint.reset();
// 把文字Android旋转
canvas.rotate(15);
mPaint.setTextSize(60);
mPaint.setUnderlineText(true);
mPaint.setColor(Color.rgb(0x5f,0x2c,0xe9));
canvas.drawText("Android",600,100,mPaint);
mPaint.reset();
canvas.translate(300,-100);
canvas.rotate(-25);
// 剪裁一部分 剪裁后再绘制只会在剪裁的部分显示,坐标系不变
// 所以需要使用canvas.save()和canvas.restore()将新图层合并到原图层
canvas.save();
canvas.clipRect(new Rect(100,500,600,800));
canvas.drawColor(Color.argb(0x33,0x5f,0x2c,0xe9));
mPaint.setTextSize(60);
mPaint.setColor(Color.rgb(0xff,0xff,0xff));
canvas.drawText("Android 剪裁",80,580,mPaint);
mPaint.reset();
canvas.restore();
mPaint.setTextSize(60);
mPaint.setColor(Color.rgb(0xff,0xff,0xff));
canvas.drawText("裁剪后在裁剪外部绘制文字",0,250,mPaint);
mPaint.reset();
canvas.rotate(10);
mPaint.setAntiAlias(true);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.beauty1);
// 在调用set,pre,post时可视为将这些方法插入到一个队列。
// pre表示在队头插入一个方法
// post表示在队尾插入一个方法
// set表示清空队列
// 队列中只保留该set方法,其余的方法都会清除。
// 当执行了一次set后pre总是插入到set之前的队列的最前面;post总是插入到set之后的队列的最后面。
Matrix matrix = new Matrix();
// canvas.drawBitmap(bitmap,matrix,mPaint);
matrix.setTranslate(600, 600);
canvas.drawBitmap(bitmap,matrix,mPaint);
matrix.preScale(0.5f, 0.5f);
canvas.drawBitmap(bitmap, matrix, mPaint);
mPaint.reset();
// 渲染
mPaint.setAntiAlias(true);
bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.beauty2);
BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.REPEAT,Shader.TileMode.REPEAT);
mPaint.setShader(bitmapShader);
// canvas.drawRect(new RectF(0,600,500,1100),mPaint);
RectF rectf1 = new RectF(0,600,500,1000);
canvas.drawOval(rectf1,mPaint);
mPaint.reset();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.argb(0x33,0x5f,0x2c,0xe9));
mPaint.setStrokeWidth(10);
canvas.translate(20,1200);
Path path = new Path();
path.moveTo(0,0);
for (int i = 1;i <= 30;i++){
path.lineTo(i * 30 ,(float) Math.random() * 200);
}
canvas.drawPath(path,mPaint);
canvas.translate(0,200);
mPaint.setPathEffect(new CornerPathEffect(60));
canvas.drawPath(path,mPaint);
canvas.translate(0,200);
mPaint.setPathEffect(new DashPathEffect(new float[] {15, 5}, 1));
canvas.drawPath(path,mPaint);
}
}
| 33.095506 | 166 | 0.642845 |
2a63a549f89ab792d58867289fe0d829078297a8 | 2,098 | package org.nypl.simplified.books.core;
/**
* The main interface to carry out operations relating to accounts.
*/
public interface AccountsControllerType
{
/**
* @return {@code true} if the user is currently logged into an account.
*/
boolean accountIsLoggedIn();
/**
* Get login details delivering them to the given listener immediately.
*
* @param listener The listener
*/
void accountGetCachedLoginDetails(
AccountGetCachedCredentialsListenerType listener);
/**
* Start loading books, delivering results to the given {@code listener}.
*
* @param listener The listener
*/
void accountLoadBooks(
AccountDataLoadListenerType listener);
/**
* Log in, delivering results to the given {@code listener}.
*
* @param credentials The account credentials
* @param listener The listener
*/
void accountLogin(
AccountCredentials credentials,
AccountLoginListenerType listener);
/**
* Log out, delivering results to the given {@code listener}.
*
* @param credentials account credentials
* @param listener The listener
*/
void accountLogout(
AccountCredentials credentials,
AccountLogoutListenerType listener);
/**
* Sync books, delivering results to the given {@code listener}.
*
* @param listener The listener
*/
void accountSync(
AccountSyncListenerType listener);
/**
* Activate the device with the currently logged in account (if you are logged in).
*/
void accountActivateDevice();
/**
* fulfill all existing books which were download before
*/
void fulfillExistingBooks();
/**
* Deactivate the device with the currently logged in account (if you are logged in).
*/
void accountDeActivateDevice();
/**
* determine is device is active with the currently logged account.
* @return if device is active
*/
boolean accountIsDeviceActive();
/**
*
*/
void accountRemoveCredentials();
/**
* @param in_book_id book id to be fulfilled
*/
void accountActivateDeviceAndFulFillBook(BookID in_book_id);
}
| 21.854167 | 87 | 0.692088 |
3174c05d376f72691fee825cf44a9efbcd79cbed | 96 | package com.nocmok.orp.api.controller.god_api.dto;
public class GetActiveRequestIdsRequest {
}
| 19.2 | 50 | 0.822917 |
e6ca5b8e8f32fc65bf4c3c48548b8ab5e1d4063e | 1,792 |
package uk.me.mjt.ch;
import java.util.Collection;
import java.util.HashSet;
/**
* Generates UML you can feed into PlantUML http://plantuml.com/ to generate
* abstract diagrams of the graph. Useful for debugging access only / barrier
* code where there are multiple nodes in the same place, and zero-length links.
*/
public class Puml {
public static String forNodes(Collection<Node> allNodes) {
StringBuilder sb = new StringBuilder();
sb.append("@startuml\n");
HashSet<DirectedEdge> alreadyVisited = new HashSet();
for (Node n : allNodes) {
for (DirectedEdge de : n.getEdgesFromAndTo()) {
if (!alreadyVisited.contains(de)) {
sb.append(edgeToPuml(de));
alreadyVisited.add(de);
}
}
}
sb.append("@enduml");
return sb.toString();
}
private static String edgeToPuml(DirectedEdge de) {
return String.format("%s --> %s : %s\n",
nodeToString(de.from),
nodeToString(de.to),
edgeToString(de));
}
private static String nodeToString(Node n) {
if (n.nodeId==n.sourceDataNodeId) {
return "(Node "+n.nodeId+")";
} else {
return "(Node "+n.nodeId+ "\\nOriginally "+n.sourceDataNodeId+")";
}
}
private static String edgeToString(DirectedEdge de) {
String s;
if (de.edgeId==de.sourceDataEdgeId) {
s="Edge " + de.edgeId;
} else {
s="Edge " + de.edgeId + "\\nOriginally " + de.sourceDataEdgeId;
}
return s+ "\\ncost " + de.driveTimeMs + " ms" + (de.accessOnly==AccessOnly.TRUE?"\\naccess only":"");
}
}
| 30.372881 | 109 | 0.550781 |
1833d403f0084af6a13b36c83563e390798524f6 | 7,319 | // --------------------------------------------------------------------------------
// Copyright 2002-2022 Echo Three, LLC
//
// 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.echothree.model.control.offer.server.logic;
import com.echothree.control.user.offer.common.spec.UseUniversalSpec;
import com.echothree.model.control.core.common.ComponentVendors;
import com.echothree.model.control.core.common.EntityTypes;
import com.echothree.model.control.core.common.exception.InvalidParameterCountException;
import com.echothree.model.control.core.server.logic.EntityInstanceLogic;
import com.echothree.model.control.offer.common.exception.CannotDeleteUseInUseException;
import com.echothree.model.control.offer.common.exception.DuplicateUseNameException;
import com.echothree.model.control.offer.common.exception.UnknownDefaultUseException;
import com.echothree.model.control.offer.common.exception.UnknownUseNameException;
import com.echothree.model.control.offer.server.control.OfferUseControl;
import com.echothree.model.control.offer.server.control.UseControl;
import com.echothree.model.data.core.server.entity.EntityInstance;
import com.echothree.model.data.offer.server.entity.Use;
import com.echothree.model.data.offer.server.entity.UseType;
import com.echothree.model.data.offer.server.value.UseDetailValue;
import com.echothree.model.data.party.server.entity.Language;
import com.echothree.util.common.message.ExecutionErrors;
import com.echothree.util.common.persistence.BasePK;
import com.echothree.util.server.control.BaseLogic;
import com.echothree.util.server.message.ExecutionErrorAccumulator;
import com.echothree.util.server.persistence.EntityPermission;
import com.echothree.util.server.persistence.Session;
public class UseLogic
extends BaseLogic {
private UseLogic() {
super();
}
private static class UseLogicHolder {
static UseLogic instance = new UseLogic();
}
public static UseLogic getInstance() {
return UseLogicHolder.instance;
}
public Use createUse(final ExecutionErrorAccumulator eea, final String useName, final UseType useType,
final Boolean isDefault, final Integer sortOrder, final Language language, final String description,
final BasePK createdBy) {
var useControl = Session.getModelController(UseControl.class);
var use = useControl.getUseByName(useName);
if(use == null) {
use = useControl.createUse(useName, useType, isDefault, sortOrder, createdBy);
if(description != null) {
useControl.createUseDescription(use, language, description, createdBy);
}
} else {
handleExecutionError(DuplicateUseNameException.class, eea, ExecutionErrors.DuplicateUseName.name(), useName);
}
return use;
}
public Use getUseByName(final ExecutionErrorAccumulator eea, final String useName,
final EntityPermission entityPermission) {
var useControl = Session.getModelController(UseControl.class);
var use = useControl.getUseByName(useName, entityPermission);
if(use == null) {
handleExecutionError(UnknownUseNameException.class, eea, ExecutionErrors.UnknownUseName.name(), useName);
}
return use;
}
public Use getUseByName(final ExecutionErrorAccumulator eea, final String useName) {
return getUseByName(eea, useName, EntityPermission.READ_ONLY);
}
public Use getUseByNameForUpdate(final ExecutionErrorAccumulator eea, final String useName) {
return getUseByName(eea, useName, EntityPermission.READ_WRITE);
}
public Use getUseByUniversalSpec(final ExecutionErrorAccumulator eea,
final UseUniversalSpec universalSpec, boolean allowDefault, final EntityPermission entityPermission) {
var useControl = Session.getModelController(UseControl.class);
var useName = universalSpec.getUseName();
var parameterCount = (useName == null ? 0 : 1) + EntityInstanceLogic.getInstance().countPossibleEntitySpecs(universalSpec);
Use use = null;
switch(parameterCount) {
case 0:
if(allowDefault) {
use = useControl.getDefaultUse(entityPermission);
if(use == null) {
handleExecutionError(UnknownDefaultUseException.class, eea, ExecutionErrors.UnknownDefaultUse.name());
}
} else {
handleExecutionError(InvalidParameterCountException.class, eea, ExecutionErrors.InvalidParameterCount.name());
}
break;
case 1:
if(useName == null) {
var entityInstance = EntityInstanceLogic.getInstance().getEntityInstance(eea, universalSpec,
ComponentVendors.ECHOTHREE.name(), EntityTypes.Use.name());
if(!eea.hasExecutionErrors()) {
use = useControl.getUseByEntityInstance(entityInstance, entityPermission);
}
} else {
use = getUseByName(eea, useName, entityPermission);
}
break;
default:
handleExecutionError(InvalidParameterCountException.class, eea, ExecutionErrors.InvalidParameterCount.name());
break;
}
return use;
}
public Use getUseByUniversalSpec(final ExecutionErrorAccumulator eea,
final UseUniversalSpec universalSpec, boolean allowDefault) {
return getUseByUniversalSpec(eea, universalSpec, allowDefault, EntityPermission.READ_ONLY);
}
public Use getUseByUniversalSpecForUpdate(final ExecutionErrorAccumulator eea,
final UseUniversalSpec universalSpec, boolean allowDefault) {
return getUseByUniversalSpec(eea, universalSpec, allowDefault, EntityPermission.READ_WRITE);
}
public void updateUseFromValue(UseDetailValue useDetailValue, BasePK updatedBy) {
var useControl = Session.getModelController(UseControl.class);
useControl.updateUseFromValue(useDetailValue, updatedBy);
}
public void deleteUse(final ExecutionErrorAccumulator eea, final Use use, final BasePK deletedBy) {
var offerUseControl = Session.getModelController(OfferUseControl.class);
if(offerUseControl.countOfferUsesByUse(use) == 0) {
var useControl = Session.getModelController(UseControl.class);
useControl.deleteUse(use, deletedBy);
} else {
handleExecutionError(CannotDeleteUseInUseException.class, eea, ExecutionErrors.CannotDeleteUseInUse.name());
}
}
}
| 44.628049 | 131 | 0.692991 |
6ca4fe0df02f45f95164db65957927cccc458fb6 | 472 | package sample;
import java.awt.*;
public class colorUtil {
public static Color fxToAwt(javafx.scene.paint.Color color){
return new Color((float)color.getRed(), (float)color.getGreen(), (float)color.getBlue(), (float)color.getOpacity());
}
public static javafx.scene.paint.Color awtToFx(Color color){
return new javafx.scene.paint.Color(color.getRed()/255.0, color.getGreen()/255.0, color.getBlue()/255.0, color.getAlpha()/255.0);
}
}
| 29.5 | 137 | 0.690678 |
9ab641b5715a20bbd81ba24f37dcc08c13052a0c | 4,092 | package com.paulyung.pyphoto.activity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.paulyung.pyphoto.BundleTag;
import com.paulyung.pyphoto.R;
import com.paulyung.pyphoto.callback.FileOperate;
import com.paulyung.pyphoto.callback.SelectStateCheck;
import com.paulyung.pyphoto.fragment.BaseFragment;
import com.paulyung.pyphoto.fragment.PhotoListFragment;
import com.paulyung.pyphoto.task.PhotoListDeleteTask;
import java.util.ArrayList;
import java.util.List;
/**
* Created by yang on 2016/11/18.
* [email protected]
* 点击相册后进入的照片列表
*/
public class PhotoListActivity extends BaseActivity implements SelectStateCheck, FileOperate {
private FragmentManager mFragmentManager;
private boolean isCheckState;
private BaseFragment mFragment;
//被选中的照片
private List<String> mSelectPhotos = new ArrayList<>();
private String title;//标题
private String witch;
@Override
protected int getLayoutId() {
return R.layout.activity_photo_list;
}
@Override
protected void beforeSetView() {
witch = getIntent().getStringExtra(BundleTag.WITCH_TO_LIST);
mFragmentManager = getSupportFragmentManager();
}
@Override
protected void initView() {
Bundle bundle = new Bundle();
bundle.putString(BundleTag.COVER_NAME, title);
bundle.putString(BundleTag.WITCH_TO_LIST, witch);
mFragment = PhotoListFragment.getInstance(bundle);
mFragmentManager.beginTransaction()
.add(R.id.lay_container, mFragment, getClass().getSimpleName()).commit();
}
@Override
protected Toolbar getInitToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
title = getIntent().getStringExtra(BundleTag.COVER_NAME);
toolbar.setTitle(title);
toolbar.setTitleTextColor(getResources().getColor(R.color.gray1));
return toolbar;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuBuilder builder = (MenuBuilder) menu;
builder.setOptionalIconsVisible(true);
if (isCheckState) {
menu.findItem(R.id.delete).setVisible(true).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
} else {
menu.findItem(R.id.delete).setVisible(false);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_photo_list, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (isCheckState) {
//执行删除
onDeletePressed();
}
return super.onOptionsItemSelected(item);
}
@Override
public void setSelectState(boolean selectState) {
isCheckState = selectState;
supportInvalidateOptionsMenu();
}
@Override
public boolean getSelectState() {
return isCheckState;
}
@Override
public void onBackPressed() {
if (isCheckState) {//如果为选照片状态则调用Fragment方法,
if (!mFragment.onBackPressed())
super.onBackPressed();//如果当前Fragment没有重写 onBackPressed() 方法,则任然使用默认返回
setSelectState(false);
} else {
super.onBackPressed();
}
}
//点击删除
private void onDeletePressed() {
switch (witch) {
case "photo_state_list":
new PhotoListDeleteTask(this, mFragment, mSelectPhotos, title).execute();
break;
case "position_cover_list":
break;
}
}
@Override
public boolean addFile(String imgFile) {
boolean res = true;
if (mSelectPhotos.contains(imgFile)) {
mSelectPhotos.remove(imgFile);
res = false;
} else {
mSelectPhotos.add(imgFile);
}
return res;
}
}
| 29.652174 | 104 | 0.663001 |
1a7314e28f89978e81928ed33c5792857ccf750f | 5,005 | /*
* 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.flink.graph.library.clustering.undirected;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.graph.Graph;
import org.apache.flink.graph.GraphAnalytic;
import org.apache.flink.graph.GraphAnalyticBase;
import org.apache.flink.graph.asm.dataset.Count;
import org.apache.flink.graph.asm.result.PrintableResult;
import org.apache.flink.graph.library.clustering.undirected.GlobalClusteringCoefficient.Result;
import org.apache.flink.graph.library.metric.undirected.VertexMetrics;
import org.apache.flink.types.CopyableValue;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
/**
* The global clustering coefficient measures the connectedness of a graph.
* Scores range from 0.0 (no triangles) to 1.0 (complete graph).
*
* @param <K> graph ID type
* @param <VV> vertex value type
* @param <EV> edge value type
*/
public class GlobalClusteringCoefficient<K extends Comparable<K> & CopyableValue<K>, VV, EV>
extends GraphAnalyticBase<K, VV, EV, Result> {
private Count<TriangleListing.Result<K>> triangleCount;
private GraphAnalytic<K, VV, EV, VertexMetrics.Result> vertexMetrics;
/*
* Implementation notes:
*
* The requirement that "K extends CopyableValue<K>" can be removed when
* removed from TriangleListing.
*/
@Override
public GlobalClusteringCoefficient<K, VV, EV> run(Graph<K, VV, EV> input)
throws Exception {
super.run(input);
triangleCount = new Count<>();
DataSet<TriangleListing.Result<K>> triangles = input
.run(new TriangleListing<K, VV, EV>()
.setSortTriangleVertices(false)
.setParallelism(parallelism));
triangleCount.run(triangles);
vertexMetrics = new VertexMetrics<K, VV, EV>()
.setParallelism(parallelism);
input.run(vertexMetrics);
return this;
}
@Override
public Result getResult() {
// each triangle is counted from each of the three vertices
long numberOfTriangles = 3 * triangleCount.getResult();
return new Result(vertexMetrics.getResult().getNumberOfTriplets(), numberOfTriangles);
}
/**
* Wraps global clustering coefficient metrics.
*/
public static class Result
implements PrintableResult {
private long tripletCount;
private long triangleCount;
/**
* Instantiate an immutable result.
*
* @param tripletCount triplet count
* @param triangleCount triangle count
*/
public Result(long tripletCount, long triangleCount) {
this.tripletCount = tripletCount;
this.triangleCount = triangleCount;
}
/**
* Get the number of triplets.
*
* @return number of triplets
*/
public long getNumberOfTriplets() {
return tripletCount;
}
/**
* Get the number of triangles.
*
* @return number of triangles
*/
public long getNumberOfTriangles() {
return triangleCount;
}
/**
* Get the global clustering coefficient score. This is computed as the
* number of closed triplets (triangles) divided by the total number of
* triplets.
*
* <p>A score of {@code Double.NaN} is returned for a graph of isolated vertices
* for which both the triangle count and number of neighbors are zero.
*
* @return global clustering coefficient score
*/
public double getGlobalClusteringCoefficientScore() {
return (tripletCount == 0) ? Double.NaN : triangleCount / (double) tripletCount;
}
@Override
public String toString() {
return toPrintableString();
}
@Override
public String toPrintableString() {
return "triplet count: " + tripletCount
+ ", triangle count: " + triangleCount
+ ", global clustering coefficient: " + getGlobalClusteringCoefficientScore();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(tripletCount)
.append(triangleCount)
.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
Result rhs = (Result) obj;
return new EqualsBuilder()
.append(tripletCount, rhs.tripletCount)
.append(triangleCount, rhs.triangleCount)
.isEquals();
}
}
}
| 27.651934 | 95 | 0.721279 |
d801bb008b93e0ceef9492d75d7e0b3386c3d5db | 2,372 | /*
* Copyright 2018 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.cloud.stream.app.twitter.trend.location.processor;
import java.util.List;
import java.util.function.Function;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import twitter4j.GeoLocation;
import twitter4j.Location;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
/**
* Functional Processor:
* http://cloud.spring.io/spring-cloud-static/spring-cloud-stream/2.1.0.RC3/single/spring-cloud-stream.html#_spring_cloud_function
*
* @author Christian Tzolov
*/
@Configuration
@EnableConfigurationProperties({ TwitterTrendLocationProcessorProperties.class })
public class TwitterTrendLocationProcessorFunctionConfiguration {
private static final Log logger = LogFactory.getLog(TwitterTrendLocationProcessorFunctionConfiguration.class);
@Bean
public Function<Message<?>, List<Location>> closestOrAvailableTrends(
TwitterTrendLocationProcessorProperties properties, Twitter twitter) {
return message -> {
try {
if (properties.getClosest().getLat() != null
&& properties.getClosest().getLon() != null) {
double lat = properties.getClosest().getLat().getValue(message, double.class);
double lon = properties.getClosest().getLon().getValue(message, double.class);
return twitter.getClosestTrends(new GeoLocation(lat, lon));
}
else {
return twitter.getAvailableTrends();
}
}
catch (TwitterException e) {
logger.error("Twitter API error!", e);
}
return null;
};
}
}
| 33.885714 | 130 | 0.765177 |
a52316d31bd911f2fe44537cb751ee008da208b1 | 28,193 | /*
* Copyright (C) 2013 - 2018, Logical Clocks AB and RISE SICS AB. All rights reserved
*
* 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 io.hops.hopsworks.api.zeppelin.server;
import com.github.eirslett.maven.plugins.frontend.lib.TaskRunnerException;
import io.hops.hopsworks.api.zeppelin.socket.NotebookServerImpl;
import io.hops.hopsworks.api.zeppelin.socket.NotebookServerImplFactory;
import io.hops.hopsworks.api.zeppelin.util.SecurityUtils;
import io.hops.hopsworks.common.jobs.jobhistory.JobType;
import io.hops.hopsworks.common.util.ConfigFileGenerator;
import io.hops.hopsworks.common.util.HopsUtils;
import io.hops.hopsworks.common.util.Settings;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.PrivilegedExceptionAction;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.dep.DependencyResolver;
import org.apache.zeppelin.helium.Helium;
import org.apache.zeppelin.helium.HeliumApplicationFactory;
import org.apache.zeppelin.helium.HeliumBundleFactory;
import org.apache.zeppelin.interpreter.InterpreterException;
import org.apache.zeppelin.interpreter.InterpreterFactory;
import org.apache.zeppelin.interpreter.InterpreterOption;
import org.apache.zeppelin.interpreter.InterpreterOutput;
import org.apache.zeppelin.interpreter.InterpreterSettingManager;
import org.apache.zeppelin.notebook.Notebook;
import org.apache.zeppelin.notebook.NotebookAuthorization;
import org.apache.zeppelin.notebook.repo.NotebookRepoSync;
import org.apache.zeppelin.scheduler.SchedulerFactory;
import org.apache.zeppelin.search.LuceneSearch;
import org.apache.zeppelin.search.SearchService;
import org.apache.zeppelin.user.Credentials;
import org.quartz.SchedulerException;
import org.sonatype.aether.RepositoryException;
public class ZeppelinConfig {
private static final Logger LOGGER = Logger.getLogger(ZeppelinConfig.class.getName());
private static final String ZEPPELIN_SITE_XML = "/zeppelin-site.xml";
private static final String ZEPPELIN_ENV_SH = "/zeppelin-env.sh";
public static final String INTERPRETER_JSON = "/interpreter.json";
private static final int DELETE_RETRY = 10;
/**
* A configuration that is common for all projects.
*/
public static ZeppelinConfiguration COMMON_CONF;
private ZeppelinConfiguration conf;
private SchedulerFactory schedulerFactory;
private Notebook notebook;
private NotebookServerImpl notebookServer;
private InterpreterFactory replFactory;
private NotebookRepoSync notebookRepo;
private DependencyResolver depResolver;
private NotebookAuthorization notebookAuthorization;
private InterpreterSettingManager interpreterSettingManager;
private Helium helium;
private HeliumApplicationFactory heliumApplicationFactory;
private HeliumBundleFactory heliumBundleFactory;
private Credentials credentials;
private SearchService noteSearchService;
private final Settings settings;
private final String projectName;
private final Integer projectId;
private final String projectDirPath;
private final String confDirPath;
private final String notebookDirPath;
private final String runDirPath;
private final String binDirPath;
private final String logDirPath;
private final String interpreterDirPath;
private final String libDirPath;
private final String repoDirPath;
private final String owner;
public ZeppelinConfig(String projectName, Integer projectId, String owner, Settings settings,
String interpreterConf, NotebookServerImpl nbs) throws IOException, RepositoryException, TaskRunnerException {
this.projectName = projectName;
this.projectId = projectId;
this.owner = owner;
this.settings = settings;
this.projectDirPath = settings.getZeppelinDir() + File.separator + Settings.DIR_ROOT + File.separator
+ this.projectName;
this.runDirPath = this.projectDirPath + File.separator + "run";
this.binDirPath = this.projectDirPath + File.separator + "bin";
this.logDirPath = this.projectDirPath + File.separator + "logs";
this.libDirPath = this.projectDirPath + File.separator + "lib";
this.confDirPath = this.projectDirPath + File.separator + "conf";
this.interpreterDirPath = this.projectDirPath + File.separator + "interpreter";
this.notebookDirPath = this.projectDirPath + File.separator + COMMON_CONF.getNotebookDir();
this.repoDirPath = this.projectDirPath + File.separator + COMMON_CONF.getInterpreterLocalRepoPath();
boolean newDir = false;
boolean newFile = false;
boolean newBinDir = false;
try {
newDir = createZeppelinDirs();//creates the necessary folders for the project in /srv/hops/zeppelin
newBinDir = copyBinDir();
createSymLinks();//interpreter and lib
createVisCacheSymlink();//create a symlink to node and npm tar cache.
newFile = createZeppelinConfFiles(interpreterConf);//create project specific configurations for zeppelin
this.conf = loadConfig();//load the newly created zeppelin-site.xml
this.depResolver = new DependencyResolver(conf.getString(
ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPRETER_LOCALREPO));
InterpreterOutput.limit = conf.getInt(
ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPRETER_OUTPUT_LIMIT);
this.heliumApplicationFactory = new HeliumApplicationFactory();
this.heliumBundleFactory = new HeliumBundleFactory(conf, null,
new File(conf.getRelativeDir(ZeppelinConfiguration.ConfVars.ZEPPELIN_DEP_LOCALREPO)),
new File(conf.getRelativeDir("lib/node_modules/zeppelin-tabledata")),
new File(conf.getRelativeDir("lib/node_modules/zeppelin-vis")),
new File(conf.getRelativeDir("lib/node_modules/zeppelin-spell")));
this.helium = new Helium(conf.getHeliumConfPath(), conf.getHeliumRegistry(), new File(conf.getRelativeDir(
ZeppelinConfiguration.ConfVars.ZEPPELIN_DEP_LOCALREPO), "helium-registry-cache"), heliumBundleFactory,
heliumApplicationFactory);
// create bundle
try {
this.heliumBundleFactory.buildAllPackages(helium.getBundlePackagesToBundle());
} catch (Exception e) {
LOGGER.log(Level.INFO, e.getMessage(), e);
}
this.schedulerFactory = SchedulerFactory.singleton();
this.interpreterSettingManager = new InterpreterSettingManager(conf, depResolver, new InterpreterOption(true));
this.notebookRepo = getNotebookRepo(owner);
this.noteSearchService = new LuceneSearch();
this.notebookAuthorization = NotebookAuthorization.init(conf);
this.credentials = new Credentials(conf.credentialsPersist(), conf.getCredentialsPath());
if(nbs!=null){
setNotebookServer(nbs);
}
} catch (IOException |RepositoryException|TaskRunnerException e) {
if (newDir) { // if the folder was newly created delete it
removeProjectDirRecursive();
} else if (newFile) { // if the conf files were newly created delete them
removeProjectConfFiles();
}
LOGGER.log(Level.SEVERE, "Error in initializing ZeppelinConfig for project: {0}. {1}",
new Object[]{this.projectName, e});
throw e;
}
}
public ZeppelinConfig(ZeppelinConfig zConf, NotebookServerImpl nbs) {
this.settings = zConf.getSettings();
this.projectName = zConf.getProjectName();
this.projectId = zConf.getProjectId();
this.owner = zConf.getOwner();
this.projectDirPath = zConf.getProjectDirPath();
this.confDirPath = zConf.getConfDirPath();
this.notebookDirPath = zConf.getNotebookDirPath();
this.runDirPath = zConf.getRunDirPath();
this.binDirPath = zConf.getBinDirPath();
this.logDirPath = zConf.getLogDirPath();
this.interpreterDirPath = zConf.getInterpreterDirPath();
this.libDirPath = zConf.getLibDirPath();
this.repoDirPath = zConf.getRepoDirPath();
this.conf = zConf.getConf();
this.depResolver = zConf.getDepResolver();
this.schedulerFactory = zConf.getSchedulerFactory();
this.interpreterSettingManager = zConf.getInterpreterSettingManager();
this.heliumApplicationFactory = zConf.getHeliumApplicationFactory();
this.helium = zConf.getHelium();
this.notebookRepo = zConf.getNotebookRepo();
this.noteSearchService = zConf.getNotebookIndex();
this.notebookAuthorization = zConf.getNotebookAuthorization();
this.credentials = zConf.getCredentials();
setNotebookServer(nbs);
}
private NotebookRepoSync getNotebookRepo(String owner) {
if(owner==null){
return null;
}
String notebookStorage = conf.getString(ZeppelinConfiguration.ConfVars.ZEPPELIN_NOTEBOOK_STORAGE);
LOGGER.log(Level.INFO, "Using notebook Repo class {0}", notebookStorage);
boolean notebookInHdfs = notebookStorage.contains("HDFSNotebookRepo");
if (!notebookInHdfs) {
return new NotebookRepoSync(conf);
}
NotebookRepoSync nbRepo = null;
UserGroupInformation ugi;
try {
ugi = UserGroupInformation.createProxyUser(owner, UserGroupInformation.getLoginUser());
nbRepo = ugi.doAs((PrivilegedExceptionAction<NotebookRepoSync>) () -> new NotebookRepoSync(conf));
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Could not create proxy user.", ex);
} catch (InterruptedException ex) {
LOGGER.log(Level.SEVERE, "Could not create notebook repo.", ex);
}
if (nbRepo == null) {
LOGGER.log(Level.SEVERE, "Could not create notebook repo.");
throw new IllegalStateException("Could not create notebook repo.");
}
return nbRepo;
}
public ZeppelinConfiguration getConf() {
return this.conf;
}
public void setNotebookServer(NotebookServerImpl nbs) {
if(this.notebookServer!=null){
return;
}
this.notebookServer = nbs;
try {
this.replFactory = new InterpreterFactory(this.conf, this.notebookServer,
this.notebookServer, this.heliumApplicationFactory,
this.depResolver, SecurityUtils.isAuthenticated(),
this.interpreterSettingManager);
this.notebook = new Notebook(this.conf, this.notebookRepo,
this.schedulerFactory, this.replFactory, interpreterSettingManager,
this.notebookServer,
this.noteSearchService, this.notebookAuthorization,
this.credentials);
// to update notebook from application event from remote process.
this.heliumApplicationFactory.setNotebook(notebook);
// to update fire websocket event on application event.
this.heliumApplicationFactory.setApplicationEventListener(this.notebookServer);
this.notebook.addNotebookEventListener(heliumApplicationFactory);
this.notebook.addNotebookEventListener(this.notebookServer.getNotebookInformationListener());
} catch (InterpreterException | IOException | RepositoryException | SchedulerException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
public boolean isClosed() {
return this.replFactory == null || this.notebook == null || this.notebookServer == null;
}
public InterpreterSettingManager getInterpreterSettingManager() {
return interpreterSettingManager;
}
public Notebook getNotebook() {
return notebook;
}
public NotebookRepoSync getNotebookRepo() {
return notebookRepo;
}
private SchedulerFactory getSchedulerFactory() {
return this.schedulerFactory;
}
public Helium getHelium() {
return helium;
}
private HeliumApplicationFactory getHeliumApplicationFactory() {
return heliumApplicationFactory;
}
public NotebookServerImpl getNotebookServer() {
return this.notebookServer;
}
public InterpreterFactory getReplFactory() {
return this.replFactory;
}
public String getProjectName() {
return projectName;
}
public Integer getProjectId() {
return projectId;
}
public String getOwner() {
return owner;
}
private String getProjectDirPath() {
return projectDirPath;
}
public SearchService getNotebookIndex() {
return noteSearchService;
}
private DependencyResolver getDepResolver() {
return depResolver;
}
public void setDepResolver(DependencyResolver depResolver) {
this.depResolver = depResolver;
}
public Settings getSettings() {
return settings;
}
private String getInterpreterDirPath() {
return interpreterDirPath;
}
private String getLibDirPath() {
return libDirPath;
}
public String getConfDirPath() {
return confDirPath;
}
private String getNotebookDirPath() {
return notebookDirPath;
}
private String getRunDirPath() {
return runDirPath;
}
private String getBinDirPath() {
return binDirPath;
}
private String getLogDirPath() {
return logDirPath;
}
private String getRepoDirPath() {
return repoDirPath;
}
private NotebookAuthorization getNotebookAuthorization() {
return notebookAuthorization;
}
private Credentials getCredentials() {
return credentials;
}
//returns true if the project dir was created
private boolean createZeppelinDirs() {
File projectDir = new File(projectDirPath);
boolean newProjectDir = projectDir.mkdirs();
new File(confDirPath).mkdirs();
new File(notebookDirPath).mkdirs();
new File(runDirPath).mkdirs();
new File(binDirPath).mkdirs();
new File(logDirPath).mkdirs();
new File(repoDirPath).mkdirs();
return newProjectDir;
}
//copies /srv/zeppelin/bin to /srv/zeppelin/this.project/bin
private boolean copyBinDir() throws IOException {
String source = settings.getZeppelinDir() + File.separator + "bin";
File binDir = new File(binDirPath);
File sourceDir = new File(source);
if (binDir.list().length == sourceDir.list().length) {
//should probably check if the files are the same
return false;
}
Path destinationPath;
for (File file : sourceDir.listFiles()) {
destinationPath = Paths.get(binDirPath + File.separator + file.getName());
Files.copy(file.toPath(), destinationPath, StandardCopyOption.REPLACE_EXISTING);
}
return binDir.list().length == sourceDir.list().length;
}
//creates symlink to interpreters and libs
private void createSymLinks() throws IOException {
File target = new File(settings.getZeppelinDir() + File.separator + "interpreter");
File newLink = new File(interpreterDirPath);
if (!newLink.exists()) {
Files.createSymbolicLink(newLink.toPath(), target.toPath());
}
target = new File(settings.getZeppelinDir() + File.separator + "lib");
newLink = new File(libDirPath);
if (!newLink.exists()) {
Files.createSymbolicLink(newLink.toPath(), target.toPath());
}
}
private void createVisCacheSymlink() throws IOException {
File target = new File(settings.getZeppelinDir() + File.separator + "local-repo/vis");
if (!target.exists()) {
LOGGER.log(Level.SEVERE, "Node and npm not cached at {0}. Zeppelin will try to download this for every project.",
target.toURI());
return;
}
File newLink = new File(repoDirPath + File.separator + "vis");
if (!newLink.exists()) {
Files.createSymbolicLink(newLink.toPath(), target.toPath());
}
}
// returns true if one of the conf files were created anew
private boolean createZeppelinConfFiles(String interpreterConf) throws IOException {
File zeppelin_env_file = new File(confDirPath + ZEPPELIN_ENV_SH);
File zeppelin_site_xml_file = new File(confDirPath + ZEPPELIN_SITE_XML);
File interpreter_file = new File(confDirPath + INTERPRETER_JSON);
String home = settings.getZeppelinDir() + File.separator + Settings.DIR_ROOT + File.separator + this.projectName;
String notebookDir = File.separator + Settings.DIR_ROOT + File.separator + this.projectName;
String resourceDir = File.separator + Settings.DIR_ROOT + File.separator + this.projectName + File.separator
+ Settings.BaseDataset.RESOURCES.getName();
boolean createdSh = false;
boolean createdLog4j = false;
boolean createdXml = false;
String log4jPath = settings.getSparkLog4JPath();
String zeppelinPythonPath = settings.getAnacondaProjectDir(this.projectName)
+ File.separator + "bin" + File.separator + "python";
if (!zeppelin_env_file.exists()) {
String ldLibraryPath = "";
if (System.getenv().containsKey("LD_LIBRARY_PATH")) {
ldLibraryPath = System.getenv("LD_LIBRARY_PATH");
}
String javaHome = settings.getJavaHome();
if (System.getenv().containsKey("JAVA_HOME")) {
javaHome = System.getenv("JAVA_HOME");
}
StringBuilder zeppelin_env = ConfigFileGenerator.instantiateFromTemplate(
ConfigFileGenerator.ZEPPELIN_ENV_TEMPLATE,
"spark_dir", settings.getSparkDir(),
"hadoop_dir", settings.getHadoopSymbolicLinkDir(),
"anaconda_env_dir", settings.getAnacondaDir() + "/envs/" + this.projectName,
"hadoop_username", this.projectName + Settings.PROJECT_GENERIC_USER_SUFFIX,
"java_home", javaHome,
"cuda_dir", settings.getCudaDir(),
"ld_library_path", ldLibraryPath,
"hadoop_classpath", HopsUtils.getHadoopClasspathGlob(settings.getHadoopSymbolicLinkDir() + "/bin/hadoop",
"classpath", "--glob"),
"spark_options", "--files " + log4jPath
);
createdSh = ConfigFileGenerator.createConfigFile(zeppelin_env_file,
zeppelin_env.
toString());
}
if (!zeppelin_site_xml_file.exists()) {
StringBuilder zeppelin_site_xml = ConfigFileGenerator.
instantiateFromTemplate(
ConfigFileGenerator.ZEPPELIN_CONFIG_TEMPLATE,
"zeppelin_home", home,
"livy_url", settings.getLivyUrl(),
"livy_master", settings.getLivyYarnMode(),
"zeppelin_home_dir", home,
"zeppelin_notebook_dir", notebookDir,
"zeppelin_interpreters", settings.getZeppelinInterpreters());
createdXml = ConfigFileGenerator.createConfigFile(zeppelin_site_xml_file,
zeppelin_site_xml.
toString());
}
//get interpreter string from db
if (interpreter_file.exists()) {
interpreter_file.delete();
}
//Set Hopsworks properties to be available in Zeppelin
String logstashID = "-D" + Settings.LOGSTASH_JOB_INFO + "=" + this.projectName.toLowerCase() + ",zeppelin,"
+ "notebook,?";
String restEndpointProp = " -D" + Settings.HOPSWORKS_REST_ENDPOINT_PROPERTY + "=" + settings.getRestEndpoint();
String elasticEndpointProp = " -D" + Settings.HOPSWORKS_ELASTIC_ENDPOINT_PROPERTY + "="
+ settings.getElasticRESTEndpoint();
String projectIdProp = " -D" + Settings.HOPSWORKS_PROJECTID_PROPERTY + "=" + this.projectId;
String projectNameProp = " -D" + Settings.HOPSWORKS_PROJECTNAME_PROPERTY + "=" + this.projectName;
String userProp = " -D" + Settings.HOPSWORKS_PROJECTUSER_PROPERTY + "=" + this.projectName
+ Settings.PROJECT_GENERIC_USER_SUFFIX;
String jobType = " -D" + Settings.HOPSWORKS_JOBTYPE_PROPERTY + "=" + JobType.SPARK;
String kafkaBrokers = " -D" + Settings.KAFKA_BROKERADDR_PROPERTY + "=" + settings.getKafkaBrokersStr();
String extraJavaOptions = " -Dlog4j.configuration=./log4j.properties "
+ logstashID + restEndpointProp + elasticEndpointProp + projectIdProp
+ projectNameProp + userProp + jobType + kafkaBrokers;
String hdfsResourceDir = "hdfs://" + resourceDir + File.separator;
// Comma-separated files to be added as local resources to Spark/Livy interpreter
String driverExtraClassPath = settings.getHopsLeaderElectionJarPath()
+ File.pathSeparator
+ settings.getHopsUtilFilename();
String executorExtraClassPath = settings.getHopsLeaderElectionJarPath()
+ File.pathSeparator
+ settings.getHopsUtilFilename();
StringBuilder distFiles = new StringBuilder();
distFiles
// KeyStore
.append("hdfs://").append(settings.getHdfsTmpCertDir()).append(File.separator)
.append(projectName)
.append(Settings.PROJECT_GENERIC_USER_SUFFIX)
.append(File.separator)
.append(projectName)
.append(Settings.PROJECT_GENERIC_USER_SUFFIX)
.append("__kstore.jks#")
.append(Settings.K_CERTIFICATE).append(",")
// TrustStore
.append("hdfs://").append(settings.getHdfsTmpCertDir()).append(File.separator)
.append(projectName)
.append(Settings.PROJECT_GENERIC_USER_SUFFIX)
.append(File.separator)
.append(projectName)
.append(Settings.PROJECT_GENERIC_USER_SUFFIX)
.append("__tstore.jks#")
.append(Settings.T_CERTIFICATE)
.append(",")
// Glassfish domain truststore
.append(settings.getGlassfishTrustStoreHdfs())
.append("#").append(Settings.DOMAIN_CA_TRUSTSTORE)
.append(",")
// Add HopsUtil
.append(settings.getHopsUtilHdfsPath()).append("#").append(settings.getHopsUtilFilename());
// If RPC TLS is enabled, password file would be injected by the
// NodeManagers. We don't need to add it as LocalResource
if (!settings.getHopsRpcTls()) {
distFiles
// File with crypto material password
.append(",")
.append("hdfs://").append(settings.getHdfsTmpCertDir()).append(File.separator)
.append(projectName)
.append(Settings.PROJECT_GENERIC_USER_SUFFIX)
.append(File.separator)
.append(projectName)
.append(Settings.PROJECT_GENERIC_USER_SUFFIX)
.append("__cert.key#")
.append(Settings.CRYPTO_MATERIAL_PASSWORD);
}
if (interpreterConf == null) {
StringBuilder interpreter_json = ConfigFileGenerator.
instantiateFromTemplate(
ConfigFileGenerator.INTERPRETER_TEMPLATE,
"projectName", this.projectName,
"zeppelin_home_dir", home,
"hdfs_user", this.projectName + Settings.PROJECT_GENERIC_USER_SUFFIX,
"hadoop_home", settings.getHadoopSymbolicLinkDir(),
"livy_url", settings.getLivyUrl(),
"dist_files", log4jPath + "," + distFiles.toString(),
"extra_spark_java_options", extraJavaOptions,
"driver_extraClassPath", driverExtraClassPath,
"executor_extraClassPath", executorExtraClassPath,
"spark.sql.warehouse.dir", hdfsResourceDir + "spark-warehouse",
"spark.yarn.stagingDir", hdfsResourceDir,
"livy.spark.sql.warehouse.dir", hdfsResourceDir + "spark-warehouse",
"livy.spark.yarn.stagingDir", hdfsResourceDir,
"hadoop_version", settings.getHadoopVersion(),
"zeppelin.python_conda_path", zeppelinPythonPath,
"livy_session_timeout", settings.getLivyZeppelinSessionTimeout(),
"spark.yarn.dist.files", distFiles.toString(),
"hive.server", settings.getHiveServerHostName(false),
"hive.db", this.projectName
);
interpreterConf = interpreter_json.toString();
}
createdXml = ConfigFileGenerator.createConfigFile(interpreter_file, interpreterConf);
return createdSh || createdXml || createdLog4j;
}
// loads configeration from project specific zeppelin-site.xml
private ZeppelinConfiguration loadConfig() {
URL url = null;
File zeppelinConfig = new File(confDirPath + ZEPPELIN_SITE_XML);
try {
url = zeppelinConfig.toURI().toURL();
LOGGER.log(Level.INFO, "Load configuration from {0}", url);
conf = new ZeppelinConfiguration(url);
} catch (ConfigurationException e) {
LOGGER.log(Level.INFO, "Failed to load configuration from " + url
+ " proceeding with a default", e);
conf = new ZeppelinConfiguration();
} catch (MalformedURLException ex) {
LOGGER.log(Level.INFO, "Malformed URL failed to load configuration from "
+ url
+ " proceeding with a default", ex);
conf = new ZeppelinConfiguration();
}
return conf;
}
/**
* Closes all resources and deletes project dir
* /srv/zeppelin/Projects/this.projectName recursive.
*
* @return true if the dir is deleted
*/
public boolean cleanAndRemoveConfDirs(NotebookServerImplFactory notebookServerImplFactory) {
clean(notebookServerImplFactory);
return removeProjectDirRecursive();
}
private boolean removeProjectDirRecursive() {
File projectDir = new File(projectDirPath);
if (!projectDir.exists()) {
return true;
}
boolean ret = false;
File interpreter = new File(interpreterDirPath);
File lib = new File(libDirPath);
File repo = new File(repoDirPath + File.separator + "vis");
//symlinks must be deleted before we recursive delete the project dir.
int retry = 0;
while (interpreter.exists() || lib.exists() || repo.exists()) {
if (interpreter.exists()) {
interpreter.delete();
}
if (lib.exists()) {
lib.delete();
}
if (repo.exists()) {
repo.delete();
}
retry++;
if (retry > DELETE_RETRY) {
LOGGER.log(Level.SEVERE, "Could not delete zeppelin project folder.");
return false;
}
}
try {
ret = ConfigFileGenerator.deleteRecursive(projectDir);
} catch (FileNotFoundException ex) {
}
return ret;
}
private boolean removeProjectConfFiles() {
File zeppelin_env_file = new File(confDirPath + ZEPPELIN_ENV_SH);
File zeppelin_site_xml_file = new File(confDirPath + ZEPPELIN_SITE_XML);
File interpreter_file = new File(confDirPath + INTERPRETER_JSON);
boolean ret = false;
if (zeppelin_env_file.exists()) {
ret = zeppelin_env_file.delete();
}
if (zeppelin_site_xml_file.exists()) {
ret = zeppelin_site_xml_file.delete();
}
if (interpreter_file.exists()) {
ret = interpreter_file.delete();
}
return ret;
}
/**
* closes notebook SearchService, Repo, InterpreterFactory, and
* SchedulerFactory
*/
public void clean(NotebookServerImplFactory notebookServerImplFactory) {
LOGGER.log(Level.INFO, "Cleanup of zeppelin resources for project {0}",
this.projectName);
if (interpreterSettingManager != null) {
interpreterSettingManager.close();
}
// will close repo and index
if (this.notebook != null) {
this.notebook.close();
}
if (this.notebookServer != null) {
this.notebookServer.closeConnections(notebookServerImplFactory);
}
this.schedulerFactory = null;
this.replFactory = null;
this.notebook = null;
}
}
| 40.68254 | 119 | 0.71046 |
d7c572c0a412cc3d30a71430b7a77f1b19f38818 | 1,723 | package com.hhn.vs.centerapp.scraper;
import java.time.LocalDateTime;
import com.hhn.vs.centerapp.model.Canteen;
/**
* Canteen Manager Class
* @author Felix Edel
*
*/
public class CanteenPlanManager {
private static CanteenPlanManager single_instance = null;
private Canteen singleCanteen = null;
private CanteenPlanScraper scraper = null;
/**
* Private constructor of the singleton
*/
private CanteenPlanManager() {
scraper = new CanteenPlanScraper();
singleCanteen = scraper.scrapCanteenPlan();
}
/**
* Gets the single instance of this class
* @return CanteenPlanManager instance
*/
public static CanteenPlanManager getInstance() {
if(single_instance == null) {
single_instance = new CanteenPlanManager();
}
return single_instance;
}
/**
* Gets the canteen object
* @return The whole canteen object
*/
public Canteen getCanteen() {
if(isCanteenToday()) {
return singleCanteen;
} else {
singleCanteen = getNewCanteen();
return singleCanteen;
}
}
/**
* Checks if the canteen object is fresh
* @return True when the meeting plan is fresh
*/
private boolean isCanteenToday() {
LocalDateTime nowLocalDate = LocalDateTime.now();
LocalDateTime currentLocalDate = LocalDateTime.parse(singleCanteen.getCreated());
int currentDayOfMonth = currentLocalDate.getDayOfMonth();
int nowCurrentDayOfMonth = nowLocalDate.getDayOfMonth();
if((currentDayOfMonth - nowCurrentDayOfMonth) == 0) {
return true;
}
return false;
}
/**
* Gets a new object from the scraper
* @return The fresh canteen object
*/
private Canteen getNewCanteen() {
return scraper.scrapCanteenPlan();
}
}
| 22.376623 | 86 | 0.699362 |
8d40ecb0e639e5686288d1a8ff1d84ba98e3177d | 45 | public class TestSubclass<T> extends Test {
} | 22.5 | 43 | 0.777778 |
7481bb9ad555c28a1372f753eb106a13e147c018 | 2,714 | package com.googlecode.lucene.gae.datastore.file;
import java.util.ArrayList;
import java.util.List;
public class DataStoreFile {
private final String name;
private final List<DataStoreFilePart> parts = new ArrayList<DataStoreFilePart>();
private long lastModified = System.currentTimeMillis();
private boolean deleted = false;
private long length = 0L;
public DataStoreFile(String name) {
this.name = name;
}
public long available() {
return parts.size() * DataStoreFilePart.MAX_SIZE;
}
public void createNewPart() {
DataStoreFilePart part = new DataStoreFilePart(this.name + "_" + parts.size(), true);
parts.add(part);
}
public long getLastModified() {
return lastModified;
}
public long getLength() {
long len = this.length;
if (!parts.isEmpty()) {
len = 0;
for (DataStoreFilePart part : parts) {
len += part.getLength();
}
}
return len;
}
public String getName() {
return name;
}
public boolean isDeleted() {
return deleted;
}
public void markToDelete() {
setDeleted(true);
}
public byte[] read(long pos, int len) {
byte[] bytes = new byte[len];
long position = pos;
int begin = 0;
int end = len;
while (begin < end) {
int left = end - begin;
int start = DataStoreFilePart.getStartForPos(position);
int canRead = DataStoreFilePart.MAX_SIZE - start;
int size = left;
if (canRead < left) {
size = canRead;
}
int index = DataStoreFilePart.getIndexForPos(position);
DataStoreFilePart part = parts.get(index);
part.read(bytes, begin, start, size);
position += size;
begin += size;
}
return bytes;
}
public void touch() {
lastModified = System.currentTimeMillis();
}
public long write(byte[] bytes, long pos, int len) {
long position = pos;
int begin = 0;
int end = len;
while (begin < end) {
int left = end - begin;
int start = DataStoreFilePart.getStartForPos(position);
int canWrite = DataStoreFilePart.MAX_SIZE - start;
int size = left;
if (canWrite < left) {
size = canWrite;
}
int index = DataStoreFilePart.getIndexForPos(position);
DataStoreFilePart part = parts.get(index);
part.write(bytes, begin, start, size);
position += size;
begin += size;
}
return end;
}
List<DataStoreFilePart> getParts() {
return parts;
}
void setDeleted(boolean deleted) {
this.deleted = deleted;
}
void setLastModified(long time) {
this.lastModified = time;
}
void setLength(long length) {
this.length = length;
}
}
| 17.855263 | 88 | 0.622329 |
fbacde08ff1101eb7512452016d5f841ca47f250 | 5,944 | package edu.gemini.ui.gface;
import java.awt.Component;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListDataListener;
@SuppressWarnings("serial")
public class GListViewer<M, E> extends GViewer<M, E> {
private final JList<E> list;
private volatile boolean pushingSelection;
public GListViewer(final GListController<M, E> controller) {
this(controller, new JList<>());
}
public GListViewer(final GListController<M, E> controller, final JList<E> list) {
super(controller, list);
this.list = list;
list.setCellRenderer(renderer);
list.setModel(new DefaultListModel<>());
list.addListSelectionListener(e -> {
if (pushingSelection || e.getValueIsAdjusting()) return;
pullSelection();
});
refresh();
}
@SuppressWarnings("unchecked")
private void pullSelection() {
setPulledSelection(new GSelection<>((E[]) list.getSelectedValues()));
}
public JList<E> getList() {
return list;
}
@Override
public GListController<M, E> getController() {
return (GListController<M, E>) super.getController();
}
@SuppressWarnings("unchecked")
@Override
public void refresh() {
invokeLater(refreshTask);
}
private void invokeLater(Runnable task) {
if (SwingUtilities.isEventDispatchThread()) {
task.run();
} else {
SwingUtilities.invokeLater(task);
}
}
private final Runnable refreshTask = new Runnable() {
@SuppressWarnings("unchecked")
public void run() {
// Set up to copy the elements.
GListController<M, E> controller = getController();
int size = controller.getElementCount();
ArrayList<E> accum = new ArrayList<>(size);
// Copy and filter.
for (int i = 0; i < size; i++) {
E e = controller.getElementAt(i);
GFilter<M, E> filter = getFilter();
if (filter == null || filter.accept(e))
accum.add(e);
}
// Sort.
GComparator<M, E> comparator = getComparator();
if (comparator != null)
Collections.sort(accum, comparator);
// Set the new model and restore the selection. Order here is important.
GSelection<E> oldSelection = getSelection();
list.setIgnoreRepaint(true);
pushingSelection = true;
list.setModel(new ImmutableListModel(accum));
new SetSelectionTask(oldSelection).run();
list.setIgnoreRepaint(false);
}
};
private class SetSelectionTask implements Runnable {
private final Set<E> set = new HashSet<>();
public SetSelectionTask(final GSelection<E> newSelection) {
for (E o: newSelection)
set.add(o);
}
@SuppressWarnings("unchecked")
public void run() {
pushingSelection = true;
ListSelectionModel lsm = list.getSelectionModel();
lsm.setValueIsAdjusting(true);
lsm.clearSelection();
ImmutableListModel<E> lm = (ImmutableListModel<E>) list.getModel();
for (int i = 0; i < lm.getSize(); i++)
if (set.contains(lm.getElementAt(i))) {
lsm.addSelectionInterval(i, i);
list.scrollRectToVisible(list.getCellBounds(i, i));
}
pushingSelection = false;
lsm.setValueIsAdjusting(false);
pullSelection(); // selection may have changed
}
}
private final ListCellRenderer<Object> renderer = new DefaultListCellRenderer() {
@SuppressWarnings("unchecked")
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, false);
GElementDecorator<M, E> labelDecorator = getDecorator();
if (labelDecorator != null)
labelDecorator.decorate(label, (E) value);
return label;
}
};
public GElementDecorator<M, E> getDecorator() {
return (GElementDecorator<M, E>) super.getDecorator();
}
public void setDecorator(GElementDecorator<M, E> decorator) {
super.setDecorator(decorator);
}
static class ImmutableListModel<E> implements ListModel<E> {
private final E[] store;
@SuppressWarnings("unchecked")
public ImmutableListModel(Collection<E> elements) {
store = (E[])elements.toArray();
}
@SuppressWarnings("unchecked")
public E getElementAt(int index) {
return store[index];
}
public int getSize() {
return store.length;
}
public void addListDataListener(ListDataListener l) {
}
public void removeListDataListener(ListDataListener l) {
}
}
@Override
protected Runnable getSelectionTask(GSelection<E> newSelection) {
return new SetSelectionTask(newSelection);
}
@SuppressWarnings("unchecked")
@Override
public E getElementAt(Point p) {
ImmutableListModel<E> lm = (ImmutableListModel<E>) list.getModel();
int row = list.locationToIndex(p);
return row == -1 ? null : lm.getElementAt(row);
}
}
| 30.172589 | 137 | 0.6107 |
e398c93b863be06283e30f3b847dcd7fb3daf255 | 1,588 | // Copyright 2000-2021 Nokia
//
// Licensed under the Apache License 2.0
// SPDX-License-Identifier: Apache-2.0
//
package com.alcatel.as.service.concurrent.impl;
import java.util.Hashtable;
import java.util.Properties;
import org.apache.log4j.PropertyConfigurator;
import com.alcatel.as.service.concurrent.PlatformExecutors;
import com.alcatel.as.service.concurrent.TimerService;
public class TestHelper {
private static volatile PlatformExecutors _execs;
private static TimerService _strictTimer;
private static TimerService _wheelTimer;
public static void init(int ioTpoolSize, int processingTpoolSize) {
Properties p = new Properties();
p.setProperty("log4j.rootLogger", "WARN,stdout");
p.setProperty("log4j.appender.stdout", "org.apache.log4j.ConsoleAppender");
p.setProperty("log4j.appender.stdout.layout", "org.apache.log4j.PatternLayout");
p.setProperty("log4j.appender.stdout.layout.ConversionPattern", "%d{ISO8601} %t %-5p %c %x - %m%n");
PropertyConfigurator.configure(p);
Hashtable<String, Object> cnf = new Hashtable<>();
p.put("system.tpool.size", String.valueOf(ioTpoolSize));
p.put("system.processing-tpool.size", String.valueOf(processingTpoolSize));
Standalone.init(cnf);
_wheelTimer = Standalone.getWheelTimer();
_strictTimer = Standalone.getJdkTimer();
_execs = Standalone.getPlatformExecutors();
}
public static PlatformExecutors getPlatformExecutors() {
return _execs;
}
public static TimerService getWheelTimer() {
return _wheelTimer;
}
public static TimerService getStrictTimer() {
return _strictTimer;
}
}
| 29.962264 | 102 | 0.766373 |
a53869cdaf6b6a33a2355bd657cfe7610025ef90 | 1,108 | package com.atguigu.tx.component.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class BookShopDaoImpl implements BookShopDao{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public int findBookPriceByISBN(String isbn) {
String sql = "SELECT price FROM book WHERE isbn=?";
Integer price = jdbcTemplate.queryForObject(sql, Integer.class, isbn);
return price;
}
@Override
public void updateBookStockByISBN(String isbn) {
String sql = "UPDATE book_stock SET stock=stock-1 WHERE isbn=?";
jdbcTemplate.update(sql, isbn);
}
@Override
public void updateBalanceByUserNamePrice(String userName, int price) {
String sql = "UPDATE account SET balance=balance-? WHERE username=?";
jdbcTemplate.update(sql, price, userName);
}
@Override
public void updatePrice(String isbn, int price) {
String sql = "UPDATE book SET price=? WHERE isbn=?";
jdbcTemplate.update(sql,price, isbn);
}
}
| 26.380952 | 73 | 0.731949 |
10a8748e557630dbb1bfe3d5b733b0cbb05cc85b | 1,205 | /**
* Created by glenc on Dec 2020
**/
public class StackArray {
private int maxSize;
private double[] stackArray;
private int top;
public StackArray(int size){
maxSize = size;
stackArray = new double[maxSize];
top = -1;
}
public void push(double j){
stackArray[++top] = j;
}
public double pop(){
return stackArray[top--];
}
public double peek(){
return stackArray[top];
}
public boolean isEmpty(){
return (top == -1);
}
public boolean isFull(){
return (top == maxSize-1);
}
public static void main(String[] args) {
StackArray arrStack = new StackArray(12);
//push to stack
arrStack.push(20);
arrStack.push(40);
arrStack.push(60);
arrStack.push(70);
//pop off content from stack while the stack is not empty
System.out.println("values popped from stack");
while( !arrStack.isEmpty()){
double value = arrStack.pop();
//print the popped value
System.out.println(value);
System.out.println(" ");
}
System.out.println("");
}
}
| 20.775862 | 65 | 0.545228 |
5800d293c772deac8eff291b0608f17ac425f3c7 | 1,732 | package org.xm.xmnlp.demo;
import org.xm.xmnlp.Xmnlp;
import org.xm.xmnlp.seg.CRFSegment;
import org.xm.xmnlp.seg.Segment;
/**
* 演示多线程并行分词
* 由于任何分词器都是线程安全的,所以用户只需调用一个配置接口就可以启用任何分词器的并行化
*
*/
public class DemoMultithreadingSegment {
public static void main(String[] args) {
Segment segment = new CRFSegment(); // CRF分词器效果好,速度慢,并行化之后可以提高一些速度
String text = "举办纪念活动铭记二战历史,不忘战争带给人类的深重灾难,是为了防止悲剧重演,确保和平永驻;" +
"铭记二战历史,更是为了提醒国际社会,需要共同捍卫二战胜利成果和国际公平正义," +
"必须警惕和抵制在历史认知和维护战后国际秩序问题上的倒行逆施。";
Xmnlp.Config.ShowTermNature = false;
System.out.println(segment.seg(text));
int pressure = 10000;
StringBuilder sbBigText = new StringBuilder(text.length() * pressure);
for (int i = 0; i < pressure; i++) {
sbBigText.append(text);
}
text = sbBigText.toString();
System.gc();
long start;
double costTime;
// 测个速度
segment.enableMultithreading(false);
start = System.currentTimeMillis();
segment.seg(text);
costTime = (System.currentTimeMillis() - start) / (double) 1000;
System.out.printf("单线程分词速度:%.2f字每秒\n", text.length() / costTime);
System.gc();
segment.enableMultithreading(true); // 或者 segment.enableMultithreading(4);
start = System.currentTimeMillis();
segment.seg(text);
costTime = (System.currentTimeMillis() - start) / (double) 1000;
System.out.printf("多线程分词速度:%.2f字每秒\n", text.length() / costTime);
System.gc();
// Note:
// 内部的并行化机制可以对1万字以上的大文本开启多线程分词
// 另一方面,任何Segment本身都是线程安全的。
// 你可以开10个线程用同一个CRFSegment对象切分任意文本,不需要任何线程同步的措施,每个线程都可以得到正确的结果。
}
}
| 32.074074 | 82 | 0.630485 |
ed3c5926c28b031f4f046239160a48b0a77b57db | 2,485 | /*******************************************************************************
* Copyright (c) 2005, 2008 BEA Systems, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* [email protected] - initial API and implementation
* IBM Corporation - changed interface to extend IBinding
* IBM Corporation - renamed from IResolvedAnnotation to IAnnotationBinding
*******************************************************************************/
package org.eclipse.jdt.core.dom;
/**
* Represents a resolved annotation. Resolved annotations are computed along with other
* bindings; they correspond to {@link Annotation} nodes.
*
* @since 3.2
* @noimplement This interface is not intended to be implemented by clients.
*/
public interface IAnnotationBinding extends IBinding {
/**
* Returns the complete list of member value pairs for this annotation, including
* ones explicitly listed in the annotation as well as entries for
* annotation type members with default values that are implied.
*
* @return a possibly empty list of resolved member value pairs
*/
IMemberValuePairBinding[] getAllMemberValuePairs();
/**
* Returns the type of the annotation. The resulting type binding will always
* return <code>true</code> to <code>ITypeBinding.isAnnotation()</code>.
*
* @return the type of the annotation
*/
ITypeBinding getAnnotationType();
/**
* Returns the list of declared member value pairs for this annotation.
* Returns an empty list for a {@link MarkerAnnotation}, a one element
* list for a {@link SingleMemberAnnotation}, and one entry for each
* of the explicitly listed values in a {@link NormalAnnotation}.
* <p>
* Note that the list only includes entries for annotation type members that are
* explicitly mentioned in the annotation. The list does not include any
* annotation type members with default values that are merely implied.
* Use {@link #getAllMemberValuePairs()} to get those as well.
* </p>
*
* @return a possibly empty list of resolved member value pairs
*/
IMemberValuePairBinding[] getDeclaredMemberValuePairs();
/**
* Returns the name of the annotation type.
*
* @return the name of the annotation type
*/
public String getName();
}
| 38.828125 | 87 | 0.685714 |
b99d3408ba2c49a9719c7060c93cb63492ade203 | 1,965 | /*
* Copyright 2020 Verizon Media
*
* 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.yahoo.athenz.common.server.notification;
import java.util.Objects;
import java.util.Set;
public class NotificationEmail {
private String subject;
private String body;
private Set<String> fullyQualifiedRecipientsEmail;
public NotificationEmail(String subject, String body, Set<String> fullyQualifiedRecipientsEmail) {
this.subject = subject;
this.body = body;
this.fullyQualifiedRecipientsEmail = fullyQualifiedRecipientsEmail;
}
public String getSubject() {
return subject;
}
public String getBody() {
return body;
}
public Set<String> getFullyQualifiedRecipientsEmail() {
return fullyQualifiedRecipientsEmail;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NotificationEmail that = (NotificationEmail) o;
return getSubject().equals(that.getSubject()) &&
Objects.equals(getBody(), that.getBody()) &&
Objects.equals(getFullyQualifiedRecipientsEmail(), that.getFullyQualifiedRecipientsEmail());
}
@Override
public int hashCode() {
return Objects.hash(getSubject(), getBody(), getFullyQualifiedRecipientsEmail());
}
}
| 30.703125 | 108 | 0.671756 |
463d830c4394b9922b36887b5bfe6dc2d9c7249d | 1,297 | package org.itsnat.droid.impl.xmlinflater.layout.attr.widget;
import android.view.View;
import org.itsnat.droid.impl.dom.DOMAttr;
import org.itsnat.droid.impl.xmlinflater.MethodContainer;
import org.itsnat.droid.impl.xmlinflater.layout.AttrLayoutContext;
import org.itsnat.droid.impl.xmlinflater.layout.classtree.ClassDescViewBased;
import org.itsnat.droid.impl.xmlinflater.shared.attr.AttrDescReflecMethodCharSequence;
/**
* Created by jmarranz on 30/04/14.
*/
public class AttrDescView_widget_ToggleButton_textOffandOn extends AttrDescReflecMethodCharSequence<ClassDescViewBased,View,AttrLayoutContext>
{
protected MethodContainer<Void> methodContainer;
public AttrDescView_widget_ToggleButton_textOffandOn(ClassDescViewBased parent, String name)
{
super(parent,name,null); // Android tiene un texto por defecto
this.methodContainer = new MethodContainer<Void>(parent.getDeclaredClass(),"syncTextState");
}
@Override
public void setAttribute(View view, DOMAttr attr, AttrLayoutContext attrCtx)
{
super.setAttribute(view, attr, attrCtx);
methodContainer.invoke(view); // Hay que llamar a este método syncTextState sino no se entera del cambio, ni siquiera en creación via parse dinámico
}
}
| 39.30303 | 157 | 0.767926 |
f68351939176f1fdeb5f8dd74d936fdc84f7bcbb | 8,225 | /*
* 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.openjpa.datacache;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.openjpa.conf.OpenJPAConfiguration;
import org.apache.openjpa.enhance.PCDataGenerator;
import org.apache.openjpa.kernel.OpenJPAStateManager;
import org.apache.openjpa.lib.conf.ObjectValue;
import org.apache.openjpa.lib.util.Closeable;
import org.apache.openjpa.meta.ClassMetaData;
import org.apache.openjpa.meta.MetaDataRepository;
import org.apache.openjpa.util.ImplHelper;
/**
* Default data cache manager provides handle to utilities {@linkplain PCDataGenerator}, {@linkplain ClearableScheduler}
* and {@linkplain CacheDistributionPolicy} for the cache operation. This implementation also determines whether a
* managed type is eligible to cache.
*
* @author Abe White
* @author Patrick Linskey
* @author Pinaki Poddar
*/
public class DataCacheManagerImpl
implements Closeable, DataCacheManager {
private OpenJPAConfiguration _conf;
private DataCache _cache = null;
private QueryCache _queryCache = null;
private DataCachePCDataGenerator _pcGenerator = null;
private ClearableScheduler _scheduler = null;
private CacheDistributionPolicy _policy = new DefaultCacheDistributionPolicy();
private Map<ClassMetaData, Boolean> _cacheable = null;
// Properties that are configured via openjpa.DataCache but need to be used here. This is here to support the 1.2
// way of doing things with openjpa.DataCache(Types=x;y;z,ExcludedTypes=a)
private Set<String> _includedTypes;
private Set<String> _excludedTypes;
public void initialize(OpenJPAConfiguration conf, ObjectValue dataCache, ObjectValue queryCache) {
_conf = conf;
_cacheable = new ConcurrentHashMap<ClassMetaData, Boolean>();
_queryCache = (QueryCache) queryCache.instantiate(QueryCache.class, conf);
if (_queryCache != null)
_queryCache.initialize(this);
_cache = (DataCache) dataCache.instantiate(DataCache.class, conf);
if (_cache == null)
return;
// create helpers before initializing caches
if (conf.getDynamicDataStructs())
_pcGenerator = new DataCachePCDataGenerator(conf);
_scheduler = new ClearableScheduler(conf);
_policy = conf.getCacheDistributionPolicyInstance();
_cache.initialize(this);
}
public DataCache getSystemDataCache() {
return getDataCache(null, false);
}
public DataCache getDataCache(String name) {
return getDataCache(name, false);
}
/**
* Returns the named cache.
* If the given name is name or the name of the cache plugin then returns the main cache.
* Otherwise, {@linkplain DataCache#getPartition(String, boolean) delegates} to the main cache
* to obtain a partition.
*/
public DataCache getDataCache(String name, boolean create) {
if (name == null || (_cache != null && name.equals(_cache.getName())))
return _cache;
if (_cache != null)
return _cache.getPartition(name, create);
return null;
}
public QueryCache getSystemQueryCache() {
return _queryCache;
}
public DataCachePCDataGenerator getPCDataGenerator() {
return _pcGenerator;
}
public ClearableScheduler getClearableScheduler() {
return _scheduler;
}
public void close() {
ImplHelper.close(_cache);
ImplHelper.close(_queryCache);
if (_scheduler != null)
_scheduler.stop();
}
/**
* Select cache for the given managed instance.
* If type based verification affirms the type to be cached then the instance based policy
* is called to determine the target cache.
*/
public DataCache selectCache(OpenJPAStateManager sm) {
if (sm == null || !isCachable(sm.getMetaData()))
return null;
String name = _policy.selectCache(sm, null);
return name == null ? null : getDataCache(name);
}
/**
* Gets the instance-based cache distribution policy, if configured.
*/
public CacheDistributionPolicy getDistributionPolicy() {
return _policy;
}
/**
* Affirms if the given type is eligible for cache.
*/
public boolean isCachable(ClassMetaData meta) {
Boolean res = _cacheable.get(meta);
if(res != null){
return res;
}
Boolean isCachable = isCacheableByMode(meta);
if (isCachable == null) {
isCachable = isCacheableByType(meta);
}
_cacheable.put(meta, isCachable);
return isCachable;
}
public void setTypes(Set<String> includedTypes, Set<String> excludedTypes){
_includedTypes = includedTypes;
_excludedTypes = excludedTypes;
}
/**
* Affirms the given class is eligible to be cached according to the cache mode
* and the cache enable flag on the given metadata.
*
* @return TRUE or FALSE if cache mode is configured. null otherwise.
*/
private Boolean isCacheableByMode(ClassMetaData meta) {
String mode = _conf.getDataCacheMode();
if (DataCacheMode.ALL.toString().equalsIgnoreCase(mode))
return true;
if (DataCacheMode.NONE.toString().equalsIgnoreCase(mode))
return false;
if (DataCacheMode.ENABLE_SELECTIVE.toString().equalsIgnoreCase(mode))
return Boolean.TRUE.equals(meta.getCacheEnabled());
if (DataCacheMode.DISABLE_SELECTIVE.toString().equalsIgnoreCase(mode))
return !Boolean.FALSE.equals(meta.getCacheEnabled());
return null;
}
/**
* Is the given type cacheable by @DataCache annotation or openjpa.DataCache(Types/ExcludedTypes)
*
* @see ClassMetaData#getDataCacheName()
*/
private Boolean isCacheableByType(ClassMetaData meta) {
if (_includedTypes != null && _includedTypes.size() > 0) {
return _includedTypes.contains(meta.getDescribedType().getName());
}
if (_excludedTypes != null && _excludedTypes.size() > 0) {
if (_excludedTypes.contains(meta.getDescribedType().getName())) {
return false;
} else {
// Case where Types is not set, and ExcludedTypes only has a sub set of all
// Entities.
return true;
}
}
// Check for @DataCache annotations
return meta.getDataCacheName() != null;
}
public void startCaching(String cls) {
MetaDataRepository mdr = _conf.getMetaDataRepositoryInstance();
ClassMetaData cmd = mdr.getCachedMetaData(cls);
_cacheable.put(cmd, Boolean.TRUE);
}
public void stopCaching(String cls) {
MetaDataRepository mdr = _conf.getMetaDataRepositoryInstance();
ClassMetaData cmd = mdr.getCachedMetaData(cls);
_cacheable.put(cmd, Boolean.FALSE);
}
public Map<String, Boolean> listKnownTypes() {
Map<String, Boolean> res = new HashMap<String, Boolean>();
for (Entry<ClassMetaData, Boolean> entry : _cacheable.entrySet()) {
res.put(entry.getKey().getDescribedTypeString(), entry.getValue());
}
return res;
}
}
| 36.393805 | 120 | 0.671489 |
4ece97124a3a443935744197ed8b7e5b450ead95 | 2,433 | package areality.game;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ProfileActivity extends Activity {
private static final int REQUEST_MY_PLACES = 0;
private static final int REQUEST_MAP = 0;
private static final int REQUEST_LOGIN = 0;
private static final String TAG = "ProfileActivity";
@OnClick(R.id.myPlacesButton) void myPlaces() {
Intent intent = new Intent(getApplicationContext(), MyPlacesActivity.class);
startActivityForResult(intent, REQUEST_MY_PLACES);
}
@OnClick(R.id.toMapButton) void switchToMap() {
Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
startActivityForResult(intent, REQUEST_MAP);
}
@OnClick(R.id.logoutButton) void logout() {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
pref.edit().clear().apply();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivityForResult(intent, REQUEST_LOGIN);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
ButterKnife.bind(this);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Log.d("MapActivity", "username here on map: " + pref.getString("username", null));
String username = pref.getString("username", null);
int points = pref.getInt("points", 0);
int landmarkCount = pref.getInt("landmarks_size", 0);
int size = pref.getInt("landmark_ids_size", 0);
TextView usernameView = (TextView) findViewById(R.id.profileName);
usernameView.setText(username);
TextView pointsView = (TextView) findViewById(R.id.profilePoints);
pointsView.setText("Points: " + Integer.toString(points));
TextView landmarkCountView = (TextView) findViewById(R.id.profileLandmarkCount);
landmarkCountView.setText("Total landmarks: " + Integer.toString(landmarkCount));
}
}
| 34.267606 | 91 | 0.715577 |
f12de39cd2505d8a1bd399b2313a01579daafcef | 1,272 |
package com.novicehacks.autobot.config;
/**
* Property definitions and default values for the Autobot application.
*
* @author Sharath Chand Bhaskara for NoviceHacks!
*
*/
public enum ConfigurationProperty {
ResourceFolder ("ResourceFolder", "."),
CommandFileName ("CommandFileName", "commands.txt"),
ServerFileName ("ServerFileName", "servers.txt"),
ExecutableFileName ("ExecutableFileName", "executables.txt"),
MonitorsFileName ("MonitorsFileName", "monitors.txt"),
TokenSeperator ("TokenSeperator", ":"),
ShellConsoleFolder ("ShellConsoleFolder", "."),
ServerConnectionTimeout ("ServerConnectionTimeout", "60"),
ExecutableDelay ("ExecutableDelay", "6"),
MonitoringEnabled ("MonitoringEnabled", "false"),
ExecutableTimeout ("ExecutableTimeout", "30");
private String key;
private String defaultValue;
private ConfigurationProperty (String name, String value) {
this.key = name;
this.defaultValue = value;
}
public String key() {
return this.key;
}
public String defaultValue() {
return this.defaultValue;
}
public static ConfigurationProperty fromKey(String configKey) {
for (ConfigurationProperty prop : ConfigurationProperty.values ()) {
if (prop.key.equalsIgnoreCase (configKey))
return prop;
}
return null;
}
}
| 27.06383 | 71 | 0.740566 |
dcf2b2977b83c20f8574d4bdde29429bfc1e598f | 18,725 | /**
*/
package questions;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
/**
* <!-- begin-user-doc -->
* The <b>Package</b> for the model.
* It contains accessors for the meta objects to represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each operation of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @see questions.QuestionsFactory
* @model kind="package"
* @generated
*/
public interface QuestionsPackage extends EPackage {
/**
* The package name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNAME = "questions";
/**
* The package namespace URI.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_URI = "http://examples/questions";
/**
* The package namespace name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_PREFIX = "questions";
/**
* The singleton instance of the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
QuestionsPackage eINSTANCE = questions.impl.QuestionsPackageImpl.init();
/**
* The meta object id for the '{@link questions.impl.QuestionSetImpl <em>Question Set</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see questions.impl.QuestionSetImpl
* @see questions.impl.QuestionsPackageImpl#getQuestionSet()
* @generated
*/
int QUESTION_SET = 0;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int QUESTION_SET__NAME = 0;
/**
* The feature id for the '<em><b>Questions</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int QUESTION_SET__QUESTIONS = 1;
/**
* The number of structural features of the '<em>Question Set</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int QUESTION_SET_FEATURE_COUNT = 2;
/**
* The number of operations of the '<em>Question Set</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int QUESTION_SET_OPERATION_COUNT = 0;
/**
* The meta object id for the '{@link questions.impl.QuestionImpl <em>Question</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see questions.impl.QuestionImpl
* @see questions.impl.QuestionsPackageImpl#getQuestion()
* @generated
*/
int QUESTION = 1;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int QUESTION__NAME = 0;
/**
* The feature id for the '<em><b>Text</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int QUESTION__TEXT = 1;
/**
* The number of structural features of the '<em>Question</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int QUESTION_FEATURE_COUNT = 2;
/**
* The number of operations of the '<em>Question</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int QUESTION_OPERATION_COUNT = 0;
/**
* The meta object id for the '{@link questions.impl.SingleChoiceImpl <em>Single Choice</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see questions.impl.SingleChoiceImpl
* @see questions.impl.QuestionsPackageImpl#getSingleChoice()
* @generated
*/
int SINGLE_CHOICE = 2;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SINGLE_CHOICE__NAME = QUESTION__NAME;
/**
* The feature id for the '<em><b>Text</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SINGLE_CHOICE__TEXT = QUESTION__TEXT;
/**
* The feature id for the '<em><b>Answers</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SINGLE_CHOICE__ANSWERS = QUESTION_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Single Choice</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SINGLE_CHOICE_FEATURE_COUNT = QUESTION_FEATURE_COUNT + 1;
/**
* The number of operations of the '<em>Single Choice</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SINGLE_CHOICE_OPERATION_COUNT = QUESTION_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link questions.impl.MultipleChoiceImpl <em>Multiple Choice</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see questions.impl.MultipleChoiceImpl
* @see questions.impl.QuestionsPackageImpl#getMultipleChoice()
* @generated
*/
int MULTIPLE_CHOICE = 3;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MULTIPLE_CHOICE__NAME = QUESTION__NAME;
/**
* The feature id for the '<em><b>Text</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MULTIPLE_CHOICE__TEXT = QUESTION__TEXT;
/**
* The feature id for the '<em><b>Answers</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MULTIPLE_CHOICE__ANSWERS = QUESTION_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Multiple Choice</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MULTIPLE_CHOICE_FEATURE_COUNT = QUESTION_FEATURE_COUNT + 1;
/**
* The number of operations of the '<em>Multiple Choice</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MULTIPLE_CHOICE_OPERATION_COUNT = QUESTION_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link questions.impl.IntValueQuestionImpl <em>Int Value Question</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see questions.impl.IntValueQuestionImpl
* @see questions.impl.QuestionsPackageImpl#getIntValueQuestion()
* @generated
*/
int INT_VALUE_QUESTION = 4;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int INT_VALUE_QUESTION__NAME = QUESTION__NAME;
/**
* The feature id for the '<em><b>Text</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int INT_VALUE_QUESTION__TEXT = QUESTION__TEXT;
/**
* The feature id for the '<em><b>Expected Value</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int INT_VALUE_QUESTION__EXPECTED_VALUE = QUESTION_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Int Value Question</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int INT_VALUE_QUESTION_FEATURE_COUNT = QUESTION_FEATURE_COUNT + 1;
/**
* The number of operations of the '<em>Int Value Question</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int INT_VALUE_QUESTION_OPERATION_COUNT = QUESTION_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link questions.impl.AnswerImpl <em>Answer</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see questions.impl.AnswerImpl
* @see questions.impl.QuestionsPackageImpl#getAnswer()
* @generated
*/
int ANSWER = 5;
/**
* The feature id for the '<em><b>Text</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANSWER__TEXT = 0;
/**
* The feature id for the '<em><b>Is Correct</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANSWER__IS_CORRECT = 1;
/**
* The number of structural features of the '<em>Answer</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANSWER_FEATURE_COUNT = 2;
/**
* The number of operations of the '<em>Answer</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANSWER_OPERATION_COUNT = 0;
/**
* Returns the meta object for class '{@link questions.QuestionSet <em>Question Set</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Question Set</em>'.
* @see questions.QuestionSet
* @generated
*/
EClass getQuestionSet();
/**
* Returns the meta object for the attribute '{@link questions.QuestionSet#getName <em>Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Name</em>'.
* @see questions.QuestionSet#getName()
* @see #getQuestionSet()
* @generated
*/
EAttribute getQuestionSet_Name();
/**
* Returns the meta object for the containment reference list '{@link questions.QuestionSet#getQuestions <em>Questions</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Questions</em>'.
* @see questions.QuestionSet#getQuestions()
* @see #getQuestionSet()
* @generated
*/
EReference getQuestionSet_Questions();
/**
* Returns the meta object for class '{@link questions.Question <em>Question</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Question</em>'.
* @see questions.Question
* @generated
*/
EClass getQuestion();
/**
* Returns the meta object for the attribute '{@link questions.Question#getName <em>Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Name</em>'.
* @see questions.Question#getName()
* @see #getQuestion()
* @generated
*/
EAttribute getQuestion_Name();
/**
* Returns the meta object for the attribute '{@link questions.Question#getText <em>Text</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Text</em>'.
* @see questions.Question#getText()
* @see #getQuestion()
* @generated
*/
EAttribute getQuestion_Text();
/**
* Returns the meta object for class '{@link questions.SingleChoice <em>Single Choice</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Single Choice</em>'.
* @see questions.SingleChoice
* @generated
*/
EClass getSingleChoice();
/**
* Returns the meta object for the containment reference list '{@link questions.SingleChoice#getAnswers <em>Answers</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Answers</em>'.
* @see questions.SingleChoice#getAnswers()
* @see #getSingleChoice()
* @generated
*/
EReference getSingleChoice_Answers();
/**
* Returns the meta object for class '{@link questions.MultipleChoice <em>Multiple Choice</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Multiple Choice</em>'.
* @see questions.MultipleChoice
* @generated
*/
EClass getMultipleChoice();
/**
* Returns the meta object for the containment reference list '{@link questions.MultipleChoice#getAnswers <em>Answers</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Answers</em>'.
* @see questions.MultipleChoice#getAnswers()
* @see #getMultipleChoice()
* @generated
*/
EReference getMultipleChoice_Answers();
/**
* Returns the meta object for class '{@link questions.IntValueQuestion <em>Int Value Question</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Int Value Question</em>'.
* @see questions.IntValueQuestion
* @generated
*/
EClass getIntValueQuestion();
/**
* Returns the meta object for the attribute '{@link questions.IntValueQuestion#getExpectedValue <em>Expected Value</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Expected Value</em>'.
* @see questions.IntValueQuestion#getExpectedValue()
* @see #getIntValueQuestion()
* @generated
*/
EAttribute getIntValueQuestion_ExpectedValue();
/**
* Returns the meta object for class '{@link questions.Answer <em>Answer</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Answer</em>'.
* @see questions.Answer
* @generated
*/
EClass getAnswer();
/**
* Returns the meta object for the attribute '{@link questions.Answer#getText <em>Text</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Text</em>'.
* @see questions.Answer#getText()
* @see #getAnswer()
* @generated
*/
EAttribute getAnswer_Text();
/**
* Returns the meta object for the attribute '{@link questions.Answer#isIsCorrect <em>Is Correct</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Is Correct</em>'.
* @see questions.Answer#isIsCorrect()
* @see #getAnswer()
* @generated
*/
EAttribute getAnswer_IsCorrect();
/**
* Returns the factory that creates the instances of the model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the factory that creates the instances of the model.
* @generated
*/
QuestionsFactory getQuestionsFactory();
/**
* <!-- begin-user-doc -->
* Defines literals for the meta objects that represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each operation of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @generated
*/
interface Literals {
/**
* The meta object literal for the '{@link questions.impl.QuestionSetImpl <em>Question Set</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see questions.impl.QuestionSetImpl
* @see questions.impl.QuestionsPackageImpl#getQuestionSet()
* @generated
*/
EClass QUESTION_SET = eINSTANCE.getQuestionSet();
/**
* The meta object literal for the '<em><b>Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute QUESTION_SET__NAME = eINSTANCE.getQuestionSet_Name();
/**
* The meta object literal for the '<em><b>Questions</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference QUESTION_SET__QUESTIONS = eINSTANCE.getQuestionSet_Questions();
/**
* The meta object literal for the '{@link questions.impl.QuestionImpl <em>Question</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see questions.impl.QuestionImpl
* @see questions.impl.QuestionsPackageImpl#getQuestion()
* @generated
*/
EClass QUESTION = eINSTANCE.getQuestion();
/**
* The meta object literal for the '<em><b>Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute QUESTION__NAME = eINSTANCE.getQuestion_Name();
/**
* The meta object literal for the '<em><b>Text</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute QUESTION__TEXT = eINSTANCE.getQuestion_Text();
/**
* The meta object literal for the '{@link questions.impl.SingleChoiceImpl <em>Single Choice</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see questions.impl.SingleChoiceImpl
* @see questions.impl.QuestionsPackageImpl#getSingleChoice()
* @generated
*/
EClass SINGLE_CHOICE = eINSTANCE.getSingleChoice();
/**
* The meta object literal for the '<em><b>Answers</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference SINGLE_CHOICE__ANSWERS = eINSTANCE.getSingleChoice_Answers();
/**
* The meta object literal for the '{@link questions.impl.MultipleChoiceImpl <em>Multiple Choice</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see questions.impl.MultipleChoiceImpl
* @see questions.impl.QuestionsPackageImpl#getMultipleChoice()
* @generated
*/
EClass MULTIPLE_CHOICE = eINSTANCE.getMultipleChoice();
/**
* The meta object literal for the '<em><b>Answers</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference MULTIPLE_CHOICE__ANSWERS = eINSTANCE.getMultipleChoice_Answers();
/**
* The meta object literal for the '{@link questions.impl.IntValueQuestionImpl <em>Int Value Question</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see questions.impl.IntValueQuestionImpl
* @see questions.impl.QuestionsPackageImpl#getIntValueQuestion()
* @generated
*/
EClass INT_VALUE_QUESTION = eINSTANCE.getIntValueQuestion();
/**
* The meta object literal for the '<em><b>Expected Value</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute INT_VALUE_QUESTION__EXPECTED_VALUE = eINSTANCE.getIntValueQuestion_ExpectedValue();
/**
* The meta object literal for the '{@link questions.impl.AnswerImpl <em>Answer</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see questions.impl.AnswerImpl
* @see questions.impl.QuestionsPackageImpl#getAnswer()
* @generated
*/
EClass ANSWER = eINSTANCE.getAnswer();
/**
* The meta object literal for the '<em><b>Text</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANSWER__TEXT = eINSTANCE.getAnswer_Text();
/**
* The meta object literal for the '<em><b>Is Correct</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANSWER__IS_CORRECT = eINSTANCE.getAnswer_IsCorrect();
}
} //QuestionsPackage
| 27.536765 | 127 | 0.624673 |
fcefab86d1a762e45871bc95381da13e6fdc271a | 1,043 | package com.active4j.service.func.timer.service;
import com.active4j.entity.func.timer.entity.QuartzJobLogEntity;
import com.active4j.entity.func.timer.model.QuartzJobLogModel;
import com.baomidou.mybatisplus.extension.service.IService;
/**
*
* @title QuartzJobLogService.java
* @description
* @time 2019年12月10日 上午9:59:44
* @author guyp
* @version 1.0
*/
public interface QuartzJobLogService extends IService<QuartzJobLogEntity> {
/**
*
* @description
* 删除定时任务日志
* @params
* ids 日志ids
* @return void
* @author guyp
* @time 2019年12月12日 上午11:00:53
*/
public void delLogs(String ids);
/**
*
* @description
* 清空日志表
* @params
* @return void
* @author guyp
* @time 2019年12月12日 上午11:14:27
*/
public void emptyLogs();
/**
*
* @description
* 获取日志明细
* @params
* id 日志id
* @return QuartzJobLogModel
* @author guyp
* @time 2019年12月12日 上午11:03:40
*/
public QuartzJobLogModel getLogDetailModel(String id);
}
| 19.679245 | 76 | 0.641419 |
4dd8346f293a18049f88a2fcc50fcbb303d2d7ae | 6,973 | package com.xd.pre.modules.sys.controller;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.xd.pre.common.exception.ValidateCodeException;
import com.xd.pre.modules.security.code.img.CaptchaUtil;
import com.xd.pre.modules.security.code.sms.SmsCodeService;
import com.xd.pre.modules.security.social.PreConnectionData;
import com.xd.pre.modules.security.social.SocialRedisHelper;
import com.xd.pre.modules.security.social.SocialUserInfo;
import com.xd.pre.common.constant.PreConstant;
import com.xd.pre.modules.sys.domain.SysUser;
import com.xd.pre.modules.sys.dto.UserDTO;
import com.xd.pre.modules.sys.service.ISysUserService;
import com.xd.pre.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* @Classname IndexController
* @Description 主页模块
* @Author 李号东 [email protected]
* @Date 2019-05-07 12:38
* @Version 1.0
*/
@RestController
public class IndexController {
@Autowired
private ISysUserService userService;
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
@Autowired
private SmsCodeService smsCodeService;
@Autowired
private ProviderSignInUtils providerSignInUtils;
@Autowired
private SocialRedisHelper socialRedisHelper;
@Value("${pre.url.address}")
private String url;
/**
* 生成验证码
*
* @param response
* @param request
* @throws ServletException
* @throws IOException
*/
@GetMapping("/captcha.jpg")
public void captcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
// 生成图片验证码
BufferedImage image = CaptchaUtil.createImage();
// 生成文字验证码
String randomText = CaptchaUtil.drawRandomText(image);
// 保存到验证码到 redis 有效期两分钟
String t = request.getParameter("t");
redisTemplate.opsForValue().set(PreConstant.PRE_IMAGE_KEY + t, randomText.toLowerCase(), 2, TimeUnit.MINUTES);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpeg", out);
}
/**
* 发送短信验证码
*
* @param phone
* @return
*/
@PostMapping("/sendCode/{phone}")
public R sendSmsCode(@PathVariable("phone") String phone) {
Map<String, Object> map = smsCodeService.sendCode(phone);
// 获取状态码 00000 成功 00141 一小时内发送给单个手机次数超过限制 00142 一天内发送给单个手机次数超过限制
String respCode = map.get("respCode").toString();
String code = map.get("code").toString();
if ("00141".equals(respCode) || "00142".equals(respCode)) {
return R.error("发送次数过多,稍后再试");
}
// 保存到验证码到 redis 有效期两分钟
redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
return R.ok();
}
@PostMapping("/register")
public R register(@RequestBody UserDTO userDTO) {
Object redisCode = redisTemplate.opsForValue().get(userDTO.getPhone());
if (ObjectUtil.isNull(redisCode)) {
throw new ValidateCodeException("验证码已失效");
}
if (!userDTO.getSmsCode().toLowerCase().equals(redisCode)) {
throw new ValidateCodeException("短信验证码错误");
}
return R.ok(userService.register(userDTO));
}
/**
* 登录
*
* @param username
* @param password
* @return
*/
@RequestMapping(value = "/login")
public R login(String username, String password, HttpServletRequest request) {
// 社交快速登录
String token = request.getParameter("token");
if (StrUtil.isNotEmpty(token)) {
return R.ok(token);
}
return R.ok(userService.login(username, password));
}
/**
* 保存完信息然后跳转到绑定用户信息页面
*
* @param request
* @param response
* @throws IOException
*/
@GetMapping("/socialSignUp")
public void socialSignUp(HttpServletRequest request, HttpServletResponse response) throws IOException {
String uuid = UUID.randomUUID().toString();
SocialUserInfo userInfo = new SocialUserInfo();
Connection<?> connectionFromSession = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
userInfo.setHeadImg(connectionFromSession.getImageUrl());
userInfo.setNickname(connectionFromSession.getDisplayName());
userInfo.setProviderId(connectionFromSession.getKey().getProviderId());
userInfo.setProviderUserId(connectionFromSession.getKey().getProviderUserId());
ConnectionData data = connectionFromSession.createData();
PreConnectionData preConnectionData = new PreConnectionData();
BeanUtil.copyProperties(data, preConnectionData);
socialRedisHelper.saveConnectionData(uuid, preConnectionData);
// 跳转到用户绑定页面
response.sendRedirect(url+"/bind?key=" + uuid);
}
/**
* 社交登录绑定
*
* @param user
* @return
*/
@PostMapping("/bind")
public R register(@RequestBody SysUser user) {
return R.ok(userService.doPostSignUp(user));
}
/**
* @Author 李号东
* @Description 暂时这样写
* @Date 08:12 2019-06-22
**/
@RequestMapping("/info")
public R info() {
Map<String, Object> map = new HashMap<>();
List<String> list = new ArrayList<>();
list.add("admin");
map.put("roles", list);
map.put("avatar", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1561394014552&di=17b6c1233048e5276f48309b306c7699&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201804%2F29%2F20180429210111_gtsnf.jpg");
map.put("name", "Super Admin");
return R.ok(map);
}
/**
* @Author 李号东
* @Description 使用jwt前后分离 只需要前端清除token即可 暂时返回success
* @Date 08:13 2019-06-22
**/
@RequestMapping("/logout")
public String logout() {
return "success";
}
}
| 34.014634 | 250 | 0.692959 |
c92cf537f6a0d782c107f83b2854d5baa7002139 | 3,454 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.jaxb.xmladapter.direct;
import org.eclipse.persistence.testing.jaxb.JAXBWithJSONTestCases;
public class XmlAdapterDirectExceptionTestCases extends JAXBWithJSONTestCases {
private final static String XML_RESOURCE = "org/eclipse/persistence/testing/jaxb/xmladapter/direct.xml";
private final static String JSON_RESOURCE = "org/eclipse/persistence/testing/jaxb/xmladapter/direct.json";
private final static String XML_WRITE_RESOURCE = "org/eclipse/persistence/testing/jaxb/xmladapter/direct_null.xml";
private final static String JSON_WRITE_RESOURCE = "org/eclipse/persistence/testing/jaxb/xmladapter/direct_null.json";
public XmlAdapterDirectExceptionTestCases(String name) throws Exception {
super(name);
setControlDocument(XML_RESOURCE);
setWriteControlDocument(XML_WRITE_RESOURCE);
setControlJSON(JSON_RESOURCE);
setWriteControlJSON(JSON_WRITE_RESOURCE);
Class[] classes = new Class[2];
classes[0] = MyCalendarException.class;
classes[1] = MyCalendarType.class;
setClasses(classes);
}
protected Object getControlObject() {
MyCalendarException myCal = new MyCalendarException();
MyCalendarType myCalType = new MyCalendarType();
myCalType.day=12;
myCalType.month=4;
myCalType.year=1997;
myCal.date = myCalType;
return myCal;
}
public void setUp() throws Exception{
super.setUp();
MyCalendarExceptionAdapter.marshalHit = false;
MyCalendarExceptionAdapter.unmarshalHit = false;
}
public Object getReadControlObject() {
MyCalendarException myCal = new MyCalendarException();
return myCal;
}
public void xmlToObjectTest(Object testObject) throws Exception{
super.xmlToObjectTest(testObject);
assertTrue(MyCalendarExceptionAdapter.unmarshalHit);
}
public void jsonToObjectTest(Object testObject) throws Exception{
super.jsonToObjectTest(testObject);
assertTrue(MyCalendarExceptionAdapter.unmarshalHit);
}
public void objectToXMLStringWriter(Object objectToWrite) throws Exception{
super.objectToXMLStringWriter(objectToWrite);
assertTrue(MyCalendarExceptionAdapter.marshalHit);
}
// @Override
//public void assertMarshalException(Exception exception) throws Exception {
// Throwable nestedException = exception.getCause();
// assertTrue("Nested exception should be a ConversionException but was " + nestedException.getClass().getName(), nestedException instanceof ConversionException);
// }
public void testRoundTrip(){
//no need to perform this test
}
}
| 42.121951 | 169 | 0.700926 |
9f7528a1c5b5d13ea42ed12690f53e25b9351c27 | 1,024 | package com.netease.music.leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* Created by dezhonger on 2019/3/28
*/
public class Leetcode0969 {
public static void main(String[] args) {
System.out.println(new Leetcode0969().pancakeSort(new int[]{3,2,4,1}));
}
public List<Integer> pancakeSort(int[] A) {
List<Integer> r = new ArrayList<>();
int len = A.length;
for (int i = len; i > 1; i--) {
if (A[i - 1] == i) continue;
int index = 0;
for (int j = len - 1; j >= 0; j--) if (A[j] == i) index = j;
r.add(index + 1);
for (int k1 = 0, k2 = index; k1 < k2; k1++,k2--) {
int tmp = A[k1];
A[k1] = A[k2];
A[k2] = tmp;
}
for (int k1 = 0, k2 = i - 1; k1 < k2; k1++,k2--) {
int tmp = A[k1];
A[k1] = A[k2];
A[k2] = tmp;
}
r.add(i);
}
return r;
}
}
| 27.675676 | 79 | 0.431641 |
b0a0e3087730e99bf2192c279efe7366fb1ed7be | 275 | package Factory;
public class Vanilla_Cake implements Cake
{
private int ID = 0;
public Vanilla_Cake()
{
ID++;
}
@Override
public void CakeType()
{
System.out.println("Vanilla Cake"+"("+ID+")");
}
} | 16.176471 | 55 | 0.505455 |
31a3fdeb600f054e5d98ed9eb387463165a22ef0 | 2,149 | package mockit;
import java.applet.*;
import java.awt.*;
import org.junit.*;
import org.junit.rules.*;
import static org.junit.Assert.*;
public final class MisusedFakingAPITest
{
@Rule public final ExpectedException thrown = ExpectedException.none();
@Test
public void fakeSameMethodTwiceWithReentrantFakesFromTwoDifferentFakeClasses() {
new MockUp<Applet>() {
@Mock
int getComponentCount(Invocation inv) {
int i = inv.proceed();
return i + 1;
}
};
int i = new Applet().getComponentCount();
assertEquals(1, i);
new MockUp<Applet>() {
@Mock
int getComponentCount(Invocation inv) {
int j = inv.proceed();
return j + 2;
}
};
// Should return 3, but returns 5. Chaining mock methods is not supported.
int j = new Applet().getComponentCount();
assertEquals(5, j);
}
static final class AppletFake extends MockUp<Applet> {
final int componentCount;
AppletFake(int componentCount) { this.componentCount = componentCount; }
@Mock int getComponentCount(Invocation inv) { return componentCount; }
}
@Test
public void applyTheSameFakeForAClassTwice() {
new AppletFake(1);
new AppletFake(2); // second application overrides the previous one
assertEquals(2, new Applet().getComponentCount());
}
@Test
public void fakeAPrivateMethod() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Unsupported fake for private method");
thrown.expectMessage("Component");
thrown.expectMessage("checkCoalescing()");
thrown.expectMessage("found");
new MockUp<Component>() {
@Mock boolean checkCoalescing() { return false; }
};
}
@Test
public void fakeAPrivateConstructor() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Unsupported fake for private constructor");
thrown.expectMessage("System#<init>()");
thrown.expectMessage("found");
new MockUp<System>() {
@Mock void $init() {}
};
}
} | 27.551282 | 83 | 0.641228 |
6dba7a9c75b8dab604adcda97ad16d2d425a6d8e | 1,434 | package quick.pager.shop.response;
import com.github.pagehelper.PageInfo;
import java.util.List;
import lombok.Data;
import quick.pager.shop.constants.ResponseStatus;
import java.io.Serializable;
/**
* 数据响应类
*
* @param <T>
* @author siguiyang
*/
@Data
public class Response<T> implements Serializable {
private static final long serialVersionUID = 473372815866107289L;
/**
* 数据响应吗
*/
private int code = ResponseStatus.Code.SUCCESS;
/**
* 响应消息
*/
private String msg = ResponseStatus.SUCCESS_MSG;
/**
* 响应数据
*/
private T data;
private long timestamp = System.currentTimeMillis();
/**
* 分页总数
*/
private long total;
public Response() {
}
public Response(int code, String msg) {
this.code = code;
this.msg = msg;
}
public Response(T data) {
this.data = data;
}
public static <T> Response<List<T>> toResponse(List<T> data) {
PageInfo<T> pageInfo = new PageInfo<>(data);
Response<List<T>> response = new Response<>();
response.setTotal(pageInfo.getTotal());
response.setData(pageInfo.getList());
return response;
}
public static <T> Response<List<T>> toResponse(List<T> data, long total) {
Response<List<T>> response = new Response<>();
response.setTotal(total);
response.setData(data);
return response;
}
}
| 21.088235 | 78 | 0.615063 |
1df14bd2de493ae352f0e9d749607bab19bbc3c4 | 643 | public class Solution
{
int N;
int[] S;
int L;
int[] cur;
ArrayList<ArrayList<Integer>> subList;
void search (int idx)
{
if (idx == N)
{
ArrayList<Integer> sub = new ArrayList<Integer>();
for (int i = 0; i < L; ++i)
sub.add(cur[i]);
subList.add(sub);
return;
}
search(idx + 1);
cur[L++] = S[idx];
search(idx + 1);
--L;
}
public ArrayList<ArrayList<Integer>> subsets (int[] S)
{
N = S.length;
this.S = S;
Arrays.sort(S);
cur = new int[N];
L = 0;
subList = new ArrayList<ArrayList<Integer>>();
search(0);
return subList;
}
}
| 15.682927 | 56 | 0.51633 |
fdd01aac4fd30e5c0ccd80881dfc9dac35ae03bd | 1,411 | /**
*
*/
package com.github.maumay.jenjinn.integrationtests;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.BufferedReader;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import com.github.maumay.jenjinn.base.FileUtils;
import com.github.maumay.jenjinn.boardstate.BoardState;
import com.github.maumay.jenjinn.boardstate.StartStateGenerator;
import com.github.maumay.jenjinn.moves.ChessMove;
import com.github.maumay.jenjinn.movesearch.TreeSearcher;
import com.github.maumay.jenjinn.pgn.BadPgnException;
import com.github.maumay.jenjinn.pgn.PgnGameConverter;
import com.github.maumay.jflow.vec.Vec;
/**
* @author ThomasB
*/
class MoveSearchIntegrationTest
{
private final int nGames = 30;
private final long timePerSearch = 3000;
@Test
void test()
{
TreeSearcher searcher = new TreeSearcher();
try (BufferedReader reader = FileUtils.loadResource(getClass(),
"BishopsOpening")) {
reader.lines().limit(nGames).forEach(game -> {
try {
Vec<ChessMove> mvs = PgnGameConverter.parse(game);
BoardState state = StartStateGenerator.createStartBoard();
mvs.iter().take(mvs.size() / 2).forEach(mv -> mv.makeMove(state));
searcher.getBestMoveFrom(state, timePerSearch);
} catch (BadPgnException e) {
fail("Error in parsing pgn: " + game);
}
});
} catch (IOException e1) {
e1.printStackTrace();
fail();
}
}
}
| 26.12963 | 71 | 0.734231 |
9dd51394f6a7f43a471a0c9252fd23500276402e | 1,436 | package com.example;
import java.lang.reflect.Method;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.InvocationInterceptor;
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;
import org.junit.runners.model.Statement;
public class Wrapper implements InvocationInterceptor, BeforeAllCallback, AfterAllCallback {
private final AbstractTestByJUnit4 base = new AbstractTestByJUnit4() {
};
@Override
public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext,
ExtensionContext extensionContext) throws Throwable {
Statement statement = base.rule.apply(new Statement() {
@Override
public void evaluate() throws Throwable {
base.init();
try {
invocation.proceed();
} finally {
base.destroy();
}
}
}, null);
statement.evaluate();
}
@Override
public void beforeAll(ExtensionContext context) throws Exception {
AbstractTestByJUnit4.initStatic();
}
@Override
public void afterAll(ExtensionContext context) throws Exception {
AbstractTestByJUnit4.destroyStatic();
}
}
| 31.911111 | 119 | 0.68454 |
7c4caa425228ca93bb41537900735e0f2da3df7c | 495 | package sg.edu.nus.comp.nsynth;
import sg.edu.nus.comp.nsynth.ast.Expression;
import sg.edu.nus.comp.nsynth.ast.Type;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sergey Mechtaev on 18/7/2016.
*/
public abstract class Shape {
protected List<Expression> forbidden = new ArrayList<>();
protected Type outputType;
public Type getOutputType() {
return outputType;
}
public List<Expression> getForbidden() {
return forbidden;
}
}
| 20.625 | 61 | 0.692929 |
ec0ebabe626e1ccdf8985adaad47aa1c4f7bdb02 | 544 | package com.mopub.network;
import android.graphics.Bitmap;
import p002b.p003c.p053g.p061f.C1260i;
/* renamed from: com.mopub.network.k */
/* compiled from: Networking */
class C11678k extends C1260i<String, Bitmap> {
C11678k(int x0) {
super(x0);
}
/* access modifiers changed from: protected */
/* renamed from: a */
public int mo9066a(String key, Bitmap value) {
if (value != null) {
return value.getRowBytes() * value.getHeight();
}
return super.mo9066a(key, value);
}
}
| 24.727273 | 59 | 0.628676 |
bbe4900fb95f7a0a79f591f08694b868ef5d2273 | 2,252 | package org.eclipse.birt.report.engine.emitter.csv;
import org.eclipse.birt.report.engine.api.IRenderOption;
import org.eclipse.birt.report.engine.api.RenderOption;
public class CSVRenderOption extends RenderOption implements ICSVRenderOption{
public static final String CSV = "CSV";
public CSVRenderOption( )
{
super();
}
/**
* Constructor.
*
* @param options
*/
public CSVRenderOption( IRenderOption options )
{
super( options );
}
/**
* Set show datatype in second row
*
* @param showDatatypeInSecondRow
*/
public void setShowDatatypeInSecondRow(boolean showDatatypeInSecondRow)
{
setOption( SHOW_DATATYPE_IN_SECOND_ROW, showDatatypeInSecondRow );
}
/**
* Get show datatype in second row
*
* @param
*/
public boolean getShowDatatypeInSecondRow()
{
return getBooleanOption(SHOW_DATATYPE_IN_SECOND_ROW, true);
}
/**
* Set Export Table By Name option
*
* @param tableName
*/
public void setExportTableByName(String tableName)
{
setOption(EXPORT_TABLE_BY_NAME,tableName);
}
/**
* Get Export Table By Name option
*
* @param
*/
public String getExportTableByName()
{
return getStringOption(EXPORT_TABLE_BY_NAME);
}
/**
* Set Field Delimiter Option
*
* @param fieldDelimiter
*/
public void setDelimiter(String protectedChars)
{
setOption(PROTECTED_CHARS,protectedChars);
}
/**
* Get Field Delimiter Option
*
* @param
*/
public String getDelimiter()
{
return getStringOption(PROTECTED_CHARS);
}
/**
* Get Replace Delimiter Inside Text With Option
*
* @param
*/
public String getProtectedChars()
{
return getStringOption(PROTECTED_CHARS);
}
/**
* Set Replace Delimiter Inside Text With Option
*
* @param replaceDelimiterInsideTextWith
*/
public void setProtectedChars(String protectedChars)
{
setOption(PROTECTED_CHARS, protectedChars);
}
/**
* Set Replace Delimiter Inside Text With Option
*
* @param replaceDelimiterInsideTextWith
*/
public void setQuoteChar(String quoteChar)
{
setOption(QUOTE_CHAR, quoteChar);
}
/**
* Get Replace Delimiter Inside Text With Option
*
* @param
*/
public String getQuoteChar()
{
return getStringOption(QUOTE_CHAR);
}
}
| 18.016 | 78 | 0.703819 |
416d3285290742b5e7669936656f5f4de3f38b1b | 3,431 | package com.peregrine.it.admin;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.peregrine.commons.test.AbstractTest;
import org.apache.sling.testing.clients.ClientException;
import org.apache.sling.testing.clients.SlingClient;
import org.apache.sling.testing.junit.rules.SlingInstanceRule;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.StringWriter;
import static com.peregrine.commons.util.PerConstants.JCR_CONTENT;
import static com.peregrine.commons.util.PerConstants.JCR_PRIMARY_TYPE;
import static com.peregrine.commons.util.PerConstants.JCR_TITLE;
import static com.peregrine.commons.util.PerConstants.PAGE_CONTENT_TYPE;
import static com.peregrine.commons.util.PerConstants.PAGE_PRIMARY_TYPE;
import static com.peregrine.commons.util.PerConstants.SLING_RESOURCE_TYPE;
import static com.peregrine.commons.util.PerUtil.TEMPLATE;
import static com.peregrine.it.basic.BasicTestHelpers.checkLastModified;
import static com.peregrine.it.basic.BasicTestHelpers.checkResourceByJson;
import static com.peregrine.it.basic.BasicTestHelpers.createFolderStructure;
import static com.peregrine.it.basic.TestConstants.EXAMPLE_PAGE_TYPE_PATH;
import static com.peregrine.it.basic.TestConstants.EXAMPLE_TEMPLATE_PATH;
import static com.peregrine.it.util.TestHarness.createPage;
/**
* Created by Andreas Schaefer on 6/30/17.
*/
public class CreatePageIT
extends AbstractTest
{
public static final String ROOT_PATH = "/content/tests/create-page";
private static final Logger logger = LoggerFactory.getLogger(CreatePageIT.class.getName());
@ClassRule
public static SlingInstanceRule slingInstanceRule = new SlingInstanceRule();
@BeforeClass
public static void setUpAll() {
SlingClient client = slingInstanceRule.getAdminClient();
try {
client.doDelete(ROOT_PATH, null, null, 200);
} catch(ClientException e) {
logger.warn("Could not delete root path: '{}' -> ignore", ROOT_PATH, e);
}
}
@Test
public void testCreatePage() throws Exception {
String rootFolderPath = ROOT_PATH + "/page-cp";
String pageName = "newPage";
SlingClient client = slingInstanceRule.getAdminClient();
// Create the folder structure
createFolderStructure(client, rootFolderPath);
createPage(client, rootFolderPath, pageName, EXAMPLE_TEMPLATE_PATH, 200);
JsonFactory jf = new JsonFactory();
StringWriter writer = new StringWriter();
JsonGenerator json = jf.createGenerator(writer);
json.writeStartObject();
json.writeStringField(JCR_PRIMARY_TYPE, PAGE_PRIMARY_TYPE);
json.writeObjectFieldStart(JCR_CONTENT);
json.writeStringField(JCR_PRIMARY_TYPE, PAGE_CONTENT_TYPE);
json.writeStringField(SLING_RESOURCE_TYPE, EXAMPLE_PAGE_TYPE_PATH);
json.writeStringField(JCR_TITLE, pageName);
json.writeStringField(TEMPLATE, EXAMPLE_TEMPLATE_PATH);
json.writeEndObject();
json.writeEndObject();
json.close();
checkResourceByJson(client, rootFolderPath + "/" + pageName, 2, writer.toString(), true);
checkLastModified(client, rootFolderPath + "/" + pageName);
}
@Override
public Logger getLogger() {
return logger;
}
}
| 39.895349 | 97 | 0.75255 |
b936469eb3fdf7c446f282cb9baa4fd06b563333 | 751 | package com.techelevator.util;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class BasicLogger {
private static PrintWriter pw = null;
public static void log(String message) {
try {
if (pw == null) {
String logFilename = "logs/" + LocalDate.now().format(DateTimeFormatter.ISO_DATE) + ".log";
pw = new PrintWriter(new FileOutputStream(logFilename, true));
}
pw.println(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME) + " " + message);
pw.flush();
}
catch (FileNotFoundException e) {
throw new BasicLoggerException(e.getMessage());
}
}
}
| 25.896552 | 95 | 0.732357 |
902fa5ea7b1d58336ba6d55449ab8491633af5ca | 1,284 | import java.util.Arrays;
public class Solution3 {
/**
* @param inorder 中序遍历序列
* @param postorder 后序遍历序列
* @return
*/
public TreeNode buildTree(int[] inorder, int[] postorder) {
int inlen = inorder.length;
int postlen = postorder.length;
assert inlen == postlen;
if (inlen == 0) {
return null;
}
if (inlen == 1) {
return new TreeNode(inorder[0]);
}
// 后序遍历的最后一个结点就是根结点
int rootVal = postorder[postlen - 1];
// 在中序遍历中找到根结点的索引,得到左右子树的一个划分
int dividePoint = 0;
for (int i = 0; i < inlen; i++) {
if (inorder[i] == rootVal) {
dividePoint = i;
break;
}
}
TreeNode rootNode = new TreeNode(rootVal);
// Arrays.copyOfRange() 方法的第 1 个参数是源数组
// 第 2 个参数是源数组的起始位置(可以取到)
// 第 3 个参数是源数组的起始位置(不可以取到)
// 这里复制了数组,使用了一些空间,因此空间复杂度是 O(N)
rootNode.left = buildTree(Arrays.copyOfRange(inorder, 0, dividePoint), Arrays.copyOfRange(postorder, 0, dividePoint));
rootNode.right = buildTree(Arrays.copyOfRange(inorder, dividePoint + 1, inlen), Arrays.copyOfRange(postorder, dividePoint, postlen - 1));
return rootNode;
}
}
| 27.913043 | 145 | 0.558411 |
d96c2a335c5b74e59f993418b1cf7ec84e9496b1 | 712 | package com.controller.admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.service.admin.AdminOrderService;
@Controller
@RequestMapping("/adminOrder")
public class AdminOrderController extends BaseController{
@Autowired
private AdminOrderService adminOrderService;
@RequestMapping("/orderInfo")
public String orderInfo(Model model) {
return adminOrderService.orderInfo(model);
}
@RequestMapping("/deleteorderManager")
public String deleteorderManager(Integer id) {
return adminOrderService.deleteorderManager(id);
}
}
| 29.666667 | 62 | 0.827247 |
869d69ad7a8776f4a66fa7947906ef0ebad56909 | 1,651 | /*
* Copyright 2010, Mysema Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 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.mysema.codegen;
import javax.tools.JavaFileManager.Location;
import javax.tools.JavaFileObject.Kind;
/**
* LocationAndKind defines a pair of Location and Kind
*
* @author tiwe
*
*/
public class LocationAndKind {
private final Kind kind;
private final Location location;
public LocationAndKind(Location location, Kind kind) {
this.location = location;
this.kind = kind;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj instanceof LocationAndKind) {
LocationAndKind other = (LocationAndKind) obj;
return location.equals(other.location) && kind.equals(other.kind);
} else {
return false;
}
}
@Override
public int hashCode() {
return kind.hashCode() * 31 + location.hashCode();
}
@Override
public String toString() {
return kind.toString() + "@" + location.toString();
}
}
| 27.983051 | 79 | 0.639612 |
4352c3499d7bdc7ddc9db406e693e754a14742e3 | 257 | package server;
import javax.swing.JFrame;
public class ServerTest {
public static void main(String[] args) {
Server Host = new Server();
Host.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Host.startRunning();
}
}
| 13.526316 | 55 | 0.653696 |
37a3387691d0e74e2111ac07b61b0112bc1ea69e | 3,122 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.02.25 at 04:54:23 PM PST
//
package org.pesc.core.coremain.v1_14;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for LocalOrganizationIDType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="LocalOrganizationIDType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="LocalOrganizationIDCode" type="{urn:org:pesc:core:CoreMain:v1.14.0}LocalOrganizationIDCodeType"/>
* <element name="LocalOrganizationIDQualifier" type="{urn:org:pesc:core:CoreMain:v1.14.0}LocalOrganizationIDCodeQualifierType"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LocalOrganizationIDType", propOrder = {
"localOrganizationIDCode",
"localOrganizationIDQualifier"
})
public class LocalOrganizationIDType {
@XmlElement(name = "LocalOrganizationIDCode", required = true)
protected String localOrganizationIDCode;
@XmlElement(name = "LocalOrganizationIDQualifier", required = true)
@XmlSchemaType(name = "token")
protected LocalOrganizationIDCodeQualifierType localOrganizationIDQualifier;
/**
* Gets the value of the localOrganizationIDCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLocalOrganizationIDCode() {
return localOrganizationIDCode;
}
/**
* Sets the value of the localOrganizationIDCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLocalOrganizationIDCode(String value) {
this.localOrganizationIDCode = value;
}
/**
* Gets the value of the localOrganizationIDQualifier property.
*
* @return
* possible object is
* {@link LocalOrganizationIDCodeQualifierType }
*
*/
public LocalOrganizationIDCodeQualifierType getLocalOrganizationIDQualifier() {
return localOrganizationIDQualifier;
}
/**
* Sets the value of the localOrganizationIDQualifier property.
*
* @param value
* allowed object is
* {@link LocalOrganizationIDCodeQualifierType }
*
*/
public void setLocalOrganizationIDQualifier(LocalOrganizationIDCodeQualifierType value) {
this.localOrganizationIDQualifier = value;
}
}
| 31.22 | 140 | 0.68706 |
8ec97037a8a26dff4f1d923fe49c667e94ed4217 | 15,265 | /*
* 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.flink.table.resource.batch;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.io.network.DataExchangeMode;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.plan.nodes.exec.BatchExecNode;
import org.apache.flink.table.plan.nodes.exec.ExecNode;
import org.apache.flink.table.plan.nodes.exec.batch.BatchExecNodeVisitor;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecBoundedStreamScan;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecCalc;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecCorrelate;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecExchange;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecExpand;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecHashAggregate;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecHashJoinBase;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecHashWindowAggregate;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecJoinBase;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecLimit;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecLocalHashAggregate;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecLocalHashWindowAggregate;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecLocalSortAggregate;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecLocalSortWindowAggregate;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecNestedLoopJoinBase;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecOverAggregate;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecRank;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecSink;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecSort;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecSortAggregate;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecSortLimit;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecSortMergeJoinBase;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecSortWindowAggregate;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecTableSourceScan;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecTemporalTableJoin;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecUnion;
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecValues;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Visit every batchExecNode to build runningUnits.
*/
public class RunningUnitGenerator extends BatchExecNodeVisitor {
private final Map<BatchExecNode<?>, List<NodeStageExchangeInfo>> outputInfoMap = new LinkedHashMap<>();
private final List<NodeRunningUnit> runningUnits = new LinkedList<>();
private final Configuration tableConf;
public RunningUnitGenerator(Configuration tableConf) {
this.tableConf = tableConf;
}
public List<NodeRunningUnit> getRunningUnits() {
return runningUnits;
}
private void addIntoInputRunningUnit(List<NodeStageExchangeInfo> inputInfoList, BatchExecNodeStage nodeStage) {
for (NodeStageExchangeInfo inputInfo : inputInfoList) {
if (inputInfo.exchangeMode == DataExchangeMode.BATCH) {
nodeStage.addDependStage(inputInfo.outStage, BatchExecNodeStage.DependType.DATA_TRIGGER);
} else {
for (NodeRunningUnit inputRunningUnit : inputInfo.outStage.getRunningUnitList()) {
inputRunningUnit.addNodeStage(nodeStage);
nodeStage.addRunningUnit(inputRunningUnit);
}
}
if (nodeStage.getRunningUnitList().isEmpty()) {
newRunningUnitWithNodeStage(nodeStage);
}
}
}
private void newRunningUnitWithNodeStage(BatchExecNodeStage nodeStage) {
NodeRunningUnit runningUnit = new NodeRunningUnit();
runningUnits.add(runningUnit);
runningUnit.addNodeStage(nodeStage);
nodeStage.addRunningUnit(runningUnit);
}
@Override
public void visit(BatchExecBoundedStreamScan boundedStreamScan) {
visitSource(boundedStreamScan);
}
@Override
public void visit(BatchExecTableSourceScan scanTableSource) {
visitSource(scanTableSource);
}
@Override
public void visit(BatchExecValues values) {
visitSource(values);
}
private void visitSource(BatchExecNode<?> sourceNode) {
List<NodeStageExchangeInfo> outputInfoList = outputInfoMap.get(sourceNode);
if (outputInfoList == null) {
BatchExecNodeStage nodeStage = new BatchExecNodeStage(sourceNode, 0);
newRunningUnitWithNodeStage(nodeStage);
outputInfoList = Collections.singletonList(new NodeStageExchangeInfo(nodeStage));
outputInfoMap.put(sourceNode, outputInfoList);
}
}
private List<NodeStageExchangeInfo> visitOneStageSingleNode(BatchExecNode<?> singleNode) {
List<NodeStageExchangeInfo> outputInfoList = outputInfoMap.get(singleNode);
if (outputInfoList == null) {
BatchExecNode<?> input = (BatchExecNode<?>) singleNode.getInputNodes().get(0);
input.accept(this);
List<NodeStageExchangeInfo> inputInfoList = outputInfoMap.get(input);
BatchExecNodeStage nodeStage = new BatchExecNodeStage(singleNode, 0);
addIntoInputRunningUnit(inputInfoList, nodeStage);
outputInfoList = Collections.singletonList(new NodeStageExchangeInfo(nodeStage));
outputInfoMap.put(singleNode, outputInfoList);
}
return outputInfoList;
}
@Override
public void visit(BatchExecCalc calc) {
visitOneStageSingleNode(calc);
}
@Override
public void visit(BatchExecCorrelate correlate) {
visitOneStageSingleNode(correlate);
}
@Override
public void visit(BatchExecExpand expand) {
visitOneStageSingleNode(expand);
}
@Override
public void visit(BatchExecLocalSortWindowAggregate localSortAggregate) {
visitOneStageSingleNode(localSortAggregate);
}
@Override
public void visit(BatchExecSortWindowAggregate sortAggregate) {
visitOneStageSingleNode(sortAggregate);
}
@Override
public void visit(BatchExecOverAggregate overWindowAgg) {
visitOneStageSingleNode(overWindowAgg);
}
@Override
public void visit(BatchExecLimit limit) {
visitOneStageSingleNode(limit);
}
@Override
public void visit(BatchExecLocalHashWindowAggregate localHashAggregate) {
visitOneStageSingleNode(localHashAggregate);
}
@Override
public void visit(BatchExecTemporalTableJoin joinTable) {
visitOneStageSingleNode(joinTable);
}
@Override
public void visit(BatchExecHashWindowAggregate hashAggregate) {
visitTwoStageSingleNode(hashAggregate);
}
private List<NodeStageExchangeInfo> visitTwoStageSingleNode(BatchExecNode<?> singleNode) {
List<NodeStageExchangeInfo> outputInfoList = outputInfoMap.get(singleNode);
if (outputInfoList == null) {
BatchExecNode<?> input = (BatchExecNode<?>) singleNode.getInputNodes().get(0);
input.accept(this);
List<NodeStageExchangeInfo> inputInfoList = outputInfoMap.get(input);
BatchExecNodeStage inStage = new BatchExecNodeStage(singleNode, 0);
BatchExecNodeStage outStage = new BatchExecNodeStage(singleNode, 1);
outStage.addDependStage(inStage, BatchExecNodeStage.DependType.DATA_TRIGGER);
addIntoInputRunningUnit(inputInfoList, inStage);
newRunningUnitWithNodeStage(outStage);
outputInfoList = Collections.singletonList(new NodeStageExchangeInfo(outStage));
outputInfoMap.put(singleNode, outputInfoList);
}
return outputInfoList;
}
@Override
public void visit(BatchExecLocalHashAggregate localHashAggregate) {
if (localHashAggregate.getGrouping().length == 0) {
visitTwoStageSingleNode(localHashAggregate);
} else {
visitOneStageSingleNode(localHashAggregate);
}
}
@Override
public void visit(BatchExecSortAggregate sortAggregate) {
if (sortAggregate.getGrouping().length == 0) {
visitTwoStageSingleNode(sortAggregate);
} else {
visitOneStageSingleNode(sortAggregate);
}
}
@Override
public void visit(BatchExecLocalSortAggregate localSortAggregate) {
if (localSortAggregate.getGrouping().length == 0) {
visitTwoStageSingleNode(localSortAggregate);
} else {
visitOneStageSingleNode(localSortAggregate);
}
}
@Override
public void visit(BatchExecSort sort) {
visitTwoStageSingleNode(sort);
}
@Override
public void visit(BatchExecSortLimit sortLimit) {
visitTwoStageSingleNode(sortLimit);
}
@Override
public void visit(BatchExecRank rank) {
visitOneStageSingleNode(rank);
}
@Override
public void visit(BatchExecHashAggregate hashAggregate) {
visitTwoStageSingleNode(hashAggregate);
}
private List<NodeStageExchangeInfo> visitBuildProbeJoin(BatchExecJoinBase hashJoin,
boolean leftIsBuild) {
List<NodeStageExchangeInfo> outputInfoList = outputInfoMap.get(hashJoin);
if (outputInfoList == null) {
BatchExecNodeStage buildStage = new BatchExecNodeStage(hashJoin, 0);
BatchExecNodeStage probeStage = new BatchExecNodeStage(hashJoin, 1);
probeStage.addDependStage(buildStage, BatchExecNodeStage.DependType.PRIORITY);
BatchExecNode<?>buildInput = (BatchExecNode<?>) (leftIsBuild ? hashJoin.getInputNodes().get(0) : hashJoin.getInputNodes().get(1));
BatchExecNode<?> probeInput = (BatchExecNode<?>) (leftIsBuild ? hashJoin.getInputNodes().get(1) : hashJoin.getInputNodes().get(0));
buildInput.accept(this);
List<NodeStageExchangeInfo> buildInputInfoList = outputInfoMap.get(buildInput);
probeInput.accept(this);
List<NodeStageExchangeInfo> probeInputInfoList = outputInfoMap.get(probeInput);
addIntoInputRunningUnit(buildInputInfoList, buildStage);
addIntoInputRunningUnit(probeInputInfoList, probeStage);
outputInfoList = Collections.singletonList(new NodeStageExchangeInfo(probeStage));
outputInfoMap.put(hashJoin, outputInfoList);
}
return outputInfoList;
}
@Override
public void visit(BatchExecExchange exchange) {
List<NodeStageExchangeInfo> outputInfoList = outputInfoMap.get(exchange);
if (outputInfoList == null) {
BatchExecNode<?> input = (BatchExecNode<?>) exchange.getInput();
input.accept(this);
List<NodeStageExchangeInfo> inputInfoList = outputInfoMap.get(input);
if (exchange.getDataExchangeModeForDeadlockBreakup(tableConf) == DataExchangeMode.BATCH) {
outputInfoList = new ArrayList<>(inputInfoList.size());
for (NodeStageExchangeInfo nodeStageExchangeInfo : inputInfoList) {
outputInfoList.add(new NodeStageExchangeInfo(nodeStageExchangeInfo.outStage, DataExchangeMode.BATCH));
}
} else {
outputInfoList = inputInfoList;
}
outputInfoMap.put(exchange, outputInfoList);
}
}
@Override
public void visit(BatchExecHashJoinBase hashJoin) {
if (hashJoin.hashJoinType().buildLeftSemiOrAnti()) {
List<NodeStageExchangeInfo> outputInfoList = outputInfoMap.get(hashJoin);
if (outputInfoList == null) {
BatchExecNodeStage buildStage = new BatchExecNodeStage(hashJoin, 0);
BatchExecNodeStage probeStage = new BatchExecNodeStage(hashJoin, 1);
BatchExecNodeStage outStage = new BatchExecNodeStage(hashJoin, 2);
probeStage.addDependStage(buildStage, BatchExecNodeStage.DependType.PRIORITY);
outStage.addDependStage(probeStage, BatchExecNodeStage.DependType.DATA_TRIGGER);
BatchExecNode<?> buildInput = (BatchExecNode<?>) hashJoin.getInputNodes().get(0);
BatchExecNode<?> probeInput = (BatchExecNode<?>) hashJoin.getInputNodes().get(1);
buildInput.accept(this);
List<NodeStageExchangeInfo> buildInputInfoList = outputInfoMap.get(buildInput);
probeInput.accept(this);
List<NodeStageExchangeInfo> probeInputInfoList = outputInfoMap.get(probeInput);
addIntoInputRunningUnit(buildInputInfoList, buildStage);
addIntoInputRunningUnit(probeInputInfoList, probeStage);
newRunningUnitWithNodeStage(outStage);
outputInfoList = Collections.singletonList(new NodeStageExchangeInfo(outStage));
outputInfoMap.put(hashJoin, outputInfoList);
}
}
visitBuildProbeJoin(hashJoin, hashJoin.leftIsBuild());
}
@Override
public void visit(BatchExecSortMergeJoinBase sortMergeJoin) {
List<NodeStageExchangeInfo> outputInfoList = outputInfoMap.get(sortMergeJoin);
if (outputInfoList == null) {
BatchExecNodeStage in0Stage = new BatchExecNodeStage(sortMergeJoin, 0);
BatchExecNodeStage in1Stage = new BatchExecNodeStage(sortMergeJoin, 1);
BatchExecNodeStage outStage = new BatchExecNodeStage(sortMergeJoin, 2);
// in0Stage and in1Stage can be parallel
outStage.addDependStage(in0Stage, BatchExecNodeStage.DependType.DATA_TRIGGER);
outStage.addDependStage(in1Stage, BatchExecNodeStage.DependType.DATA_TRIGGER);
BatchExecNode<?> leftInput = (BatchExecNode<?>) sortMergeJoin.getInputNodes().get(0);
leftInput.accept(this);
List<NodeStageExchangeInfo> in0InfoList = outputInfoMap.get(leftInput);
BatchExecNode<?> rightInput = (BatchExecNode<?>) sortMergeJoin.getInputNodes().get(1);
rightInput.accept(this);
List<NodeStageExchangeInfo> in1InfoList = outputInfoMap.get(rightInput);
addIntoInputRunningUnit(in0InfoList, in0Stage);
addIntoInputRunningUnit(in1InfoList, in1Stage);
newRunningUnitWithNodeStage(outStage);
outputInfoList = Collections.singletonList(new NodeStageExchangeInfo(outStage));
outputInfoMap.put(sortMergeJoin, outputInfoList);
}
}
@Override
public void visit(BatchExecNestedLoopJoinBase nestedLoopJoin) {
visitBuildProbeJoin(nestedLoopJoin, nestedLoopJoin.leftIsBuild());
}
@Override
public void visit(BatchExecUnion union) {
List<NodeStageExchangeInfo> outputInfoList = outputInfoMap.get(union);
if (outputInfoList == null) {
outputInfoList = new LinkedList<>();
for (ExecNode<?, ?> input : union.getInputNodes()) {
((BatchExecNode<?>) input).accept(this);
outputInfoList.addAll(outputInfoMap.get((BatchExecNode<?>) input));
}
outputInfoMap.put(union, outputInfoList);
}
}
@Override
public void visit(BatchExecSink<?> sink) {
throw new TableException("could not reach sink here.");
}
/**
* NodeStage with exchange info.
*/
protected static class NodeStageExchangeInfo {
private final BatchExecNodeStage outStage;
private final DataExchangeMode exchangeMode;
public NodeStageExchangeInfo(BatchExecNodeStage outStage) {
this(outStage, null);
}
public NodeStageExchangeInfo(BatchExecNodeStage outStage, DataExchangeMode exchangeMode) {
this.outStage = outStage;
this.exchangeMode = exchangeMode;
}
}
}
| 38.1625 | 134 | 0.792008 |
d1b96ce85d7e919991d2a3e53efd2c093de7aeae | 3,201 | package ru.stqa.pft.addressbook.tests;
import org.openqa.selenium.remote.BrowserType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import ru.stqa.pft.addressbook.appmanager.ApplicationManager;
import ru.stqa.pft.addressbook.model.ContactData;
import ru.stqa.pft.addressbook.model.Contacts;
import ru.stqa.pft.addressbook.model.GroupData;
import ru.stqa.pft.addressbook.model.Groups;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Created by Golem on 19.03.2017.
*/
public class TestBase {
Logger logger = LoggerFactory.getLogger(TestBase.class);
protected static final ApplicationManager app
= new ApplicationManager(System.getProperty("browser", BrowserType.FIREFOX));
@BeforeSuite
public void setUp() throws Exception {
app.init();
}
@AfterSuite(alwaysRun = true)
public void tearDown() {
app.stop();
}
@BeforeMethod
public void logTestStart(Method m, Object[] p){
logger.info("Start test: " + m.getName() + " with parameters " + Arrays.asList(p));
}
@AfterMethod(alwaysRun = true)
public void logTestStop(Method m, Object[] p){
logger.info("Stop test: " + m.getName());
}
public void verifyGroupListUI() {
if(Boolean.getBoolean("verifyUI")) {
Groups dbGroups = app.db().groups();
Groups uiGroups = app.group().all();
assertThat(uiGroups, equalTo(dbGroups.stream()
.map((g) -> new GroupData().withId(g.getId()).withName(g.getGroupName()))
.collect(Collectors.toSet())));
}
}
public void verifyContactListUI() {
if(Boolean.getBoolean("verifyUI")) {
Contacts dbContacts = app.db().contacts();
Contacts uiContacts = app.contact().all();
assertThat(uiContacts, equalTo(dbContacts.stream()
.map((c) -> new ContactData().withId(c.getId()).withContactName(c.getContactName())
.withContactLastName(c.getContactLastName())
.withContactCompanyAddress(c.getContactCompanyAddress())
.withContactHomepage(c.getContactHomepage())
.withAllPhones(Arrays.asList(c.getContactHomePhone(),c.getContactMobilePhone(),c.getContactWorkPhone())
.stream().filter((s -> ! s.equals("")))
.map(s -> s.replaceAll("\\s","").replaceAll("[-()]",""))
.collect(Collectors.joining("\n")))
.withAllEmails(Arrays.asList(c.getContactEmail1(),c.getContactEmail2(),c.getContactEmail3()).stream().filter((s -> ! s.equals("")))
.collect(Collectors.joining("\n"))))
.collect(Collectors.toSet())));
}
}
}
| 38.566265 | 159 | 0.619494 |
6c035d3c9585511aaa87ef2bd5d57f155700a6ce | 1,341 | /**
* Copyright 2015 Kamran Zafar
*
* 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.kamranzafar.xmpp.template.rest;
import org.kamranzafar.xmpp.template.XmppUser;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by kamran on 04/08/15.
*/
@RestController
@RequestMapping("/prebind")
public class XmppPrebindResource {
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public XmppUser prebind() {
return (XmppUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}
| 33.525 | 96 | 0.767338 |
adb035c10ae9b75675baa9cdf71882a22f0f0088 | 1,028 | package frc.robot.subsystems;
import java.util.ArrayList;
public class SafetyOverrideRegistry {
private static SafetyOverrideRegistry instance;
public static SafetyOverrideRegistry getInstance(){
if(instance == null){
instance = new SafetyOverrideRegistry();
}
return instance;
}
private SafetyOverrideRegistry(){
overridables = new ArrayList<>();
}
private ArrayList<SafetyOverridable> overridables;
/**
* Adds a manual safety overridable to the registry and enables its safety mode
* @param overridable the SafetyOverridable to add
*/
public void register(SafetyOverridable overridable){
overridables.add(overridable);
overridable.enableSafety();
}
public void disableSafety(){
for(SafetyOverridable o : overridables){
o.disableSafety();
}
}
public void enableSafety(){
for(SafetyOverridable o : overridables){
o.enableSafety();
}
}
}
| 24.47619 | 83 | 0.64786 |
ca7dfee403355af650ab8dab32f1889b841f7406 | 649 | package com.dbms.triplehao.service.impl;
import com.dbms.triplehao.dao.RegionStoreDao;
import com.dbms.triplehao.entity.RegionStore;
import com.dbms.triplehao.service.RegionStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class RegionStoreServiceImpl implements RegionStoreService {
@Autowired
private RegionStoreDao regionStoreDao;
@Override
public List<RegionStore> getRegionStoreList() {
return regionStoreDao.queryRegionStore();
}
}
| 28.217391 | 67 | 0.810478 |
3e8a72107ab24a7c45006ba6d606c0240b93c74e | 5,294 | package org.ndextools.morphcx.writers;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.junit.*;
/**
* Unit tests for TableToCSV class when the output target is a file.
*/
public class TableToCSVAsFileTest {
private ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private List<String> orderedColumnValues;
private final char COMMA = ',';
private final char TAB = '\t';
@Before
public void setup() {
// Redirect console output to outContent in order to perform JUnit tests.
System.setOut(new PrintStream(outContent, true));
// List containing all columns to be printed to the (redirected) console.
orderedColumnValues = new ArrayList<>();
}
@After
public void breakdown() {
//Redirect console output to system stdout stream.
System.setOut(System.out);
}
@Test
public void _ShouldOutputHeadersAndColumnsUsingCommaDelimiter() throws Exception {
try {
PrintStream printStream = new PrintStream(System.out);
CSVPrinter printer = new CSVPrinter(printStream, CSVFormat.DEFAULT
.withRecordSeparator("\n")
.withDelimiter(COMMA));
List<String> headers1 = new ArrayList<>();
headers1.add("Header-1");
headers1.add("Header-2");
headers1.add("Header-3");
headers1.add("Header-4");
String[] arrayHeaders = new String[headers1.size()];
arrayHeaders = headers1.toArray(arrayHeaders);
List<String> headers2 = new ArrayList<>();
headers2.add("col_1");
headers2.add("col_2");
headers2.add("col_3");
headers2.add("col_4");
String[] arrayColumns = new String[headers2.size()];
arrayColumns = headers2.toArray(arrayColumns);
printer.printRecord(arrayHeaders);
printer.printRecord(arrayColumns);
} catch (IOException e) {
throw new Exception(e);
}
String output = outContent.toString();
Assert.assertTrue(output.contains("Header-1,Header-2,Header-3,Header-4"));
Assert.assertTrue(output.contains("\n"));
Assert.assertTrue(output.contains("col_1,col_2,col_3,col_4"));
}
@Test
public void _ShouldOutputHeadersAndColumnsUsingTabDelimiter() throws Exception {
try {
PrintStream printStream = new PrintStream(System.out);
CSVPrinter printer = new CSVPrinter(printStream, CSVFormat.DEFAULT
.withRecordSeparator("\n")
.withDelimiter(TAB));
List<String> headers1 = new ArrayList<>();
headers1.add("Header-1");
headers1.add("Header-2");
headers1.add("Header-3");
headers1.add("Header-4");
String[] arrayHeaders = new String[headers1.size()];
arrayHeaders = headers1.toArray(arrayHeaders);
List<String> headers2 = new ArrayList<>();
headers2.add("col_1");
headers2.add("col_2");
headers2.add("col_3");
headers2.add("col_4");
String[] arrayColumns = new String[headers2.size()];
arrayColumns = headers2.toArray(arrayColumns);
printer.printRecord(arrayHeaders);
printer.printRecord(arrayColumns);
} catch (IOException e) {
throw new Exception(e);
}
String output = outContent.toString();
Assert.assertTrue(output.contains("Header-1\tHeader-2\tHeader-3\tHeader-4"));
Assert.assertTrue(output.contains("\n"));
Assert.assertTrue(output.contains("col_1\tcol_2\tcol_3\tcol_4"));
}
@Test
public void _ShouldOutputHeadersAndColumnsUsingWindowsNewline() throws Exception {
try {
PrintStream printStream = new PrintStream(System.out);
CSVPrinter printer = new CSVPrinter(printStream, CSVFormat.DEFAULT
.withRecordSeparator("\r\n")
.withDelimiter(TAB));
List<String> headers1 = new ArrayList<>();
headers1.add("Header-1");
headers1.add("Header-2");
headers1.add("Header-3");
headers1.add("Header-4");
String[] arrayHeaders = new String[headers1.size()];
arrayHeaders = headers1.toArray(arrayHeaders);
List<String> headers2 = new ArrayList<>();
headers2.add("col_1");
headers2.add("col_2");
headers2.add("col_3");
headers2.add("col_4");
String[] arrayColumns = new String[headers2.size()];
arrayColumns = headers2.toArray(arrayColumns);
printer.printRecord(arrayHeaders);
printer.printRecord(arrayColumns);
} catch (IOException e) {
throw new Exception(e);
}
String output = outContent.toString();
Assert.assertTrue(output.contains("Header-1\tHeader-2\tHeader-3\tHeader-4"));
Assert.assertTrue(output.contains("\r\n"));
Assert.assertTrue(output.contains("col_1\tcol_2\tcol_3\tcol_4"));
}
}
| 36.763889 | 86 | 0.605402 |
51086fead4198c7d9e77084f2828e3e5b5a1e2f3 | 1,874 | /**
* This file is part of ftp4che.
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.ftp4che.exception;
import java.net.ConnectException;
public class ProxyConnectionException extends ConnectException {
private int status = 0;
private String msg = "";
public ProxyConnectionException() {
super();
}
public ProxyConnectionException(String msg) {
super(msg);
setMsg(msg);
}
public ProxyConnectionException(int status, String msg) {
this(msg);
setStatus(status);
}
/**
* @return Returns the msg.
*/
public String getMsg() {
return msg;
}
/**
* @param msg
* The msg to set.
*/
public void setMsg(String msg) {
this.msg = msg;
}
/**
* @return Returns the status.
*/
public int getStatus() {
return status;
}
/**
* @param status
* The status to set.
*/
public void setStatus(int status) {
this.status = status;
}
}
| 26.027778 | 77 | 0.590715 |
3637f454fa2f3447f5eb354fd9755cbde5977fa4 | 80 | package ru.job4j.pooh;
public interface Service {
Resp process(Req req);
}
| 13.333333 | 26 | 0.7125 |
8e8089745a9e5937f19e2a14975225af3861e395 | 1,529 | package com.example.map;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by riven_chris on 15/7/24.
*/
public class MapBehavior {
public static void printKeys(Map<Integer, String> map) {
System.out.println("Size = " + map.size() + ",");
System.out.print("keys:");
System.out.println(map.keySet());
System.out.println(map.values());
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
System.out.print(map.get(iterator.next()) + ",");
}
}
public static void test(Map<Integer, String> map) {
System.out.println(map.getClass().getSimpleName());
map.putAll(map);
}
public static void main(String[] args) {
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
for (int i = 0; i < 10; i++) {
hashMap.put(i, "s" + i);
}
printKeys(hashMap);
System.out.println();
LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<Integer, String>(hashMap);
System.out.println(linkedHashMap);
//Least-Recently-Used
linkedHashMap = new LinkedHashMap<Integer, String>(10, 0.75f, true);
linkedHashMap.putAll(hashMap);
System.out.println(linkedHashMap);
for (int i = 0; i < 6; i++) {
linkedHashMap.get(i);
}
System.out.println(linkedHashMap);
linkedHashMap.get(0);
System.out.println(linkedHashMap);
}
}
| 29.403846 | 99 | 0.593198 |
65043737ff56f24f61ec0a588734eda986c0a8de | 5,871 | /*-
* #%L
* PropertiesFramework :: Core
* %%
* Copyright (C) 2017 LeanFrameworks
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package com.github.leanframeworks.propertiesframework.base.property.wrap;
import com.github.leanframeworks.propertiesframework.api.common.Disposable;
import com.github.leanframeworks.propertiesframework.api.property.WritableListProperty;
import java.util.Collection;
/**
* Wrapper for list properties (typically both readable/writable) to make them appear as write-only.
* <p>
* This can be useful, for example, to return a write-only list property in a getter method that is actually a
* readable/writable list property internally. The wrapper then forbids the programmer to cast the returned list
* property to a readable list property in order to change read its values.
*
* @param <W> Type of data that can be written to the wrapped set property.
*/
public class WriteOnlyListPropertyWrapper<W> implements WritableListProperty<W>, Disposable {
/**
* Wrapped list property.
*/
private WritableListProperty<W> wrappedListProperty;
/**
* Constructor specifying the list property to be wrapped, typically a list property that is both readable and
* writable.
*
* @param wrappedListProperty List property to be wrapped.
*/
public WriteOnlyListPropertyWrapper(WritableListProperty<W> wrappedListProperty) {
this.wrappedListProperty = wrappedListProperty;
}
/**
* @see Disposable#dispose()
*/
@Override
public void dispose() {
if (wrappedListProperty instanceof Disposable) {
((Disposable) wrappedListProperty).dispose();
}
wrappedListProperty = null;
}
/**
* @see WritableListProperty#set(int, Object)
*/
@Override
public W set(int index, W item) {
W oldItem = null;
if (wrappedListProperty != null) {
oldItem = wrappedListProperty.set(index, item);
}
return oldItem;
}
/**
* @see WritableListProperty#add(Object)
*/
@Override
public boolean add(W item) {
if (wrappedListProperty != null) {
wrappedListProperty.add(item);
}
// See List#add(Object) and Collection#add(Object)
return true;
}
/**
* @see WritableListProperty#add(int, Object)
*/
@Override
public void add(int index, W item) {
if (wrappedListProperty != null) {
wrappedListProperty.add(index, item);
}
}
/**
* @see WritableListProperty#addAll(Collection)
*/
@Override
public boolean addAll(Collection<? extends W> items) {
boolean changed = false;
if (wrappedListProperty != null) {
changed = wrappedListProperty.addAll(items);
}
return changed;
}
/**
* @see WritableListProperty#addAll(int, Collection)
*/
@Override
public boolean addAll(int index, Collection<? extends W> items) {
boolean changed = false;
if (wrappedListProperty != null) {
changed = wrappedListProperty.addAll(index, items);
}
return changed;
}
/**
* @see WritableListProperty#remove(Object)
*/
@Override
public boolean remove(Object item) {
boolean changed = false;
if (wrappedListProperty != null) {
changed = wrappedListProperty.remove(item);
}
return changed;
}
/**
* @see WritableListProperty#remove(int)
*/
@Override
public W remove(int index) {
W oldItem = null;
if (wrappedListProperty != null) {
oldItem = wrappedListProperty.remove(index);
}
return oldItem;
}
/**
* @see WritableListProperty#removeAll(Collection)
*/
@Override
public boolean removeAll(Collection<?> items) {
boolean changed = false;
if (wrappedListProperty != null) {
changed = wrappedListProperty.removeAll(items);
}
return changed;
}
/**
* @see WritableListProperty#retainAll(Collection)
*/
@Override
public boolean retainAll(Collection<?> items) {
boolean changed = false;
if (wrappedListProperty != null) {
changed = wrappedListProperty.retainAll(items);
}
return changed;
}
/**
* @see WritableListProperty#clear()
*/
@Override
public void clear() {
if (wrappedListProperty != null) {
wrappedListProperty.clear();
}
}
}
| 28.639024 | 114 | 0.652189 |
cc733936e623e136328d874ee0611b67f22f5970 | 2,029 | /*
* #%L
* ACS AEM Commons Bundle
* %%
* Copyright (C) 2019 Adobe
* %%
* 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%
*/
package com.adobe.acs.commons.filefetch;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
/**
* A configuration for configuring a service to fetch a file from a remote
* source and saving it as a DAM Asset.
*/
@ObjectClassDefinition(name = "ACS AEM Commons - File Fetch", description = "Service Configuration")
public @interface FileFetchConfiguration {
@AttributeDefinition(name = "DAM Path", description = "The path under which to save the file")
String damPath();
@AttributeDefinition(name = "Headers", description = "Headers to add to the request")
String[] headers() default {};
@AttributeDefinition(name = "Mime Type", description = "The mime type of the asset to create")
String mimeType();
@AttributeDefinition(name = "Remote URL", description = "The URL from which to retrieve the file")
String remoteUrl();
@AttributeDefinition(name = "Update Cron Expression", description = "A cron expression on when to fetch the file")
String scheduler_expression();
@AttributeDefinition(name = "Valid Response Codes", description = "Responses which will be considered successful")
int[] validResponseCodes() default { 200 };
@AttributeDefinition(name = "Connection Timeout", description = "Maximum timeout for a connection response")
int timeout() default 5000;
}
| 38.283019 | 116 | 0.73928 |
49c0e1ce978e27b23a410734d00d1d2245a6b512 | 591 | package com.example.warehouse.delivery;
import com.example.warehouse.Report;
import com.example.warehouse.export.ExportType;
public class NoReportDelivery extends AbstractReportDelivery {
public NoReportDelivery() {
super("No report delivery");
}
@Override
protected void beforeDoDeliver() {
// INFO: no-op.
}
@Override
protected void doDeliver(Report.Type reportType, ExportType exportType, byte[] bytes) {
// INFO: intentionally left empty.
}
@Override
protected void afterDoDeliver() {
// INFO: no-op.
}
}
| 21.888889 | 91 | 0.671743 |
f6bb615a92b2171159573f26c38d6133968e26e7 | 5,149 | /*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* 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.jbpm.compiler.canonical;
import java.util.Map;
import java.util.Objects;
import org.drools.core.util.StringUtils;
import org.jbpm.workflow.core.node.CompositeNode;
import org.kie.api.definition.process.Node;
import org.kie.api.definition.process.NodeContainer;
import org.kie.kogito.internal.process.runtime.KogitoNode;
import static org.jbpm.ruleflow.core.Metadata.MAPPING_VARIABLE;
import static org.jbpm.ruleflow.core.Metadata.MESSAGE_TYPE;
import static org.jbpm.ruleflow.core.Metadata.TRIGGER_REF;
import static org.jbpm.ruleflow.core.Metadata.TRIGGER_TYPE;
public class TriggerMetaData {
public enum TriggerType {
ConsumeMessage,
ProduceMessage,
Signal
}
// name of the trigger derived from message or signal
private final String name;
// type of the trigger e.g. message, signal, timer...
private final TriggerType type;
// data type of the event associated with this trigger
private final String dataType;
// reference in the model of the process the event should be mapped to
private final String modelRef;
// reference to owner of the trigger usually node
private final String ownerId;
// the owner node
private final Node node;
public static TriggerMetaData of(Node node) {
return of(node, (String) node.getMetaData().get(MAPPING_VARIABLE));
}
public static TriggerMetaData of(Node node, String mappingVariable) {
Map<String, Object> nodeMetaData = node.getMetaData();
return new TriggerMetaData(
node,
(String) nodeMetaData.get(TRIGGER_REF),
TriggerType.valueOf((String) nodeMetaData.get(TRIGGER_TYPE)),
(String) nodeMetaData.get(MESSAGE_TYPE),
mappingVariable,
getOwnerId(node)).validate();
}
private TriggerMetaData(Node node, String name, TriggerType type, String dataType, String modelRef, String ownerId) {
this.node = node;
this.name = name;
this.type = type;
this.dataType = dataType;
this.modelRef = modelRef;
this.ownerId = ownerId;
}
public String getName() {
return name;
}
public TriggerType getType() {
return type;
}
public String getDataType() {
return dataType;
}
public String getModelRef() {
return modelRef;
}
public String getOwnerId() {
return ownerId;
}
public Node getNode() {
return node;
}
private TriggerMetaData validate() {
if (TriggerType.ConsumeMessage.equals(type) || TriggerType.ProduceMessage.equals(type)) {
if (StringUtils.isEmpty(name) ||
StringUtils.isEmpty(dataType) ||
StringUtils.isEmpty(modelRef)) {
throw new IllegalArgumentException("Message Trigger information is not complete " + this);
}
} else if (TriggerType.Signal.equals(type) && StringUtils.isEmpty(name)) {
throw new IllegalArgumentException("Signal Trigger information is not complete " + this);
}
return this;
}
@Override
public int hashCode() {
return Objects.hash(dataType, modelRef, name, ownerId, type);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof TriggerMetaData))
return false;
TriggerMetaData other = (TriggerMetaData) obj;
return Objects.equals(dataType, other.dataType) && Objects.equals(modelRef, other.modelRef) && Objects.equals(
name, other.name) && Objects.equals(ownerId, other.ownerId) && type == other.type;
}
@Override
public String toString() {
return "TriggerMetaData [name=" + name + ", type=" + type + ", dataType=" + dataType + ", modelRef=" +
modelRef + ", ownerId=" + ownerId + "]";
}
private static String getOwnerId(Node node) {
StringBuilder prefix = new StringBuilder();
if (node instanceof KogitoNode) {
NodeContainer container = ((KogitoNode) node).getParentContainer();
while (container instanceof CompositeNode) {
CompositeNode compositeNode = (CompositeNode) container;
prefix.append(compositeNode.getId()).append('_');
container = compositeNode.getParentContainer();
}
}
return prefix.append(node.getId()).toString();
}
}
| 33.875 | 121 | 0.651389 |
081fa0dd110ae9d63018dc7fb73fbfd99afa33cc | 670 | package com.kapcb.framework.optimus.parser;
import com.kapcb.framework.optimus.limit.Limiter;
import com.kapcb.framework.optimus.operation.LimiterOperation;
import java.lang.reflect.Method;
import java.util.Collection;
/**
* <a>Title: LimiterAnnotationParser </a>
* <a>Author: Kapcb <a>
* <a>Description: LimiterAnnotationParser <a>
*
* @author Kapcb
* @version 1.0
* @date 2021/12/5 14:53
* @since 1.0
*/
public interface LimiterAnnotationParser<T extends Limiter> {
Collection<LimiterOperation<? extends Limiter>> parseLimiterAnnotations(Method method);
Collection<LimiterOperation<? extends Limiter>> parseLimiterAnnotations(Class<?> clazz);
}
| 25.769231 | 92 | 0.756716 |
42e18ecc4345e187fa3bf0d07e00f02267eaf5db | 11,923 | /* Copyright (c) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.appengine.demos.autoshoppe;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.AUTH_CONTINUE_URL;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.AUTH_LOGIN;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.AUTH_LOGOUT;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.AUTH_USER;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.CAR_EXPRICE;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.CAR_KEY;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.CAR_KEY_PATTERN;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.CAR_MAKE;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.CAR_MILEAGE;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.CAR_MODEL;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.CAR_STATUS_AVL;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.CAR_TYPE;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.CAR_YEAR;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.GQL_PRICEOP;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.MSG_INVALID_NUMBER;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.MSG_INVALID_SEARCH;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.MSG_MISSING_PARAM;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.JSON_MODEL;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.JSON_VIEW;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.MSG_BEAN_INIT_FAILURE;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.Operator;
import static com.google.appengine.demos.autoshoppe.AutoShoppeConstants.PAGE_PARAM;
import com.google.appengine.api.users.UserService;
import com.google.gson.Gson;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.servlet.view.RedirectView;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* A Spring multiaction controller for mapping URLs to method names. This class
* parses the request parameters and sets up the asynchronous JSON views for the
* AJAX client.
*
* @author [email protected] (Anirudh Dewani)
*/
public class AutoController extends MultiActionController {
private AutoShoppeService autoShoppeService;
private Gson gson;
private UserService userService;
/**
* Spring injected dependency using the setter.
*
* @param userService AppEngine UserService
*/
public void setUserService(UserService userService) {
this.userService = userService;
}
/**
* Spring injected dependency using the setter.
*
* @param autoShoppeService service class for AutoShoppe
*/
public void setAutoShoppeService(AutoShoppeService autoShoppeService) {
this.autoShoppeService = autoShoppeService;
}
/**
* Spring injected dependency using the setter.
* The gson transformer spits JSON output from java objects.
*
* @param gson a JSON-Java converter
*/
public void setGson(Gson gson) {
this.gson = gson;
}
/**
* Checks the bean state against it's dependencies. init() is set as the
* default-init-method for all spring configured beans.
*/
public void init() {
if (userService == null || gson == null || autoShoppeService == null) {
throw new IllegalStateException(MSG_BEAN_INIT_FAILURE +
AutoController.class.toString());
}
}
/**
* Checks user authentication status by querying the UserService API
* and sets up login and logout URLs for the client. A user with an existing
* session is identified and automatically logged in.
*
*
* @param request HttpServletRequest object
* @param response HttpServletResponse object
* @return ModelAndView a Spring MVC framework instance with data and view
* for the client
*/
public ModelAndView login(
HttpServletRequest request, HttpServletResponse response) {
String loginUrl = userService.createLoginURL(AUTH_CONTINUE_URL);
String logOutUrl = userService.createLogoutURL(AUTH_CONTINUE_URL);
String user = userService.isUserLoggedIn()
? userService.getCurrentUser().getEmail() : "";
Map<String, String> loginDataMap = new HashMap<String, String>();
loginDataMap.put(AUTH_LOGIN, loginUrl);
loginDataMap.put(AUTH_LOGOUT, logOutUrl);
loginDataMap.put(AUTH_USER, user);
return constructModelAndView(gson.toJson(loginDataMap));
}
/**
* Adds a new vehicle to the datastore and returns a JSON model and view to
* the client. In case of invalid input, an error message is sent.
*
* @param request HttpServletRequest object
* @param response HttpServletResponse object
* @return ModelAndView a Spring MVC framework instance with data and view
* for the client
*/
public ModelAndView addVehicle(
HttpServletRequest request, HttpServletResponse response) {
if (!userService.isUserLoggedIn()) {
ModelAndView mv = new ModelAndView();
mv.setView(new RedirectView(
userService.createLoginURL(request.getRequestURI())));
return mv;
}
try {
Vehicle vehicle = new Vehicle();
vehicle.setYear(Integer.parseInt(request.getParameter(CAR_YEAR)));
vehicle.setDate(System.currentTimeMillis());
vehicle.setType(request.getParameter(CAR_TYPE));
vehicle.setOwner(userService.getCurrentUser().getEmail());
vehicle.setModel(request.getParameter(CAR_MODEL));
vehicle.setMake(request.getParameter(CAR_MAKE));
vehicle.setMileage(Long.parseLong(request.getParameter(CAR_MILEAGE)));
vehicle.setStatus(CAR_STATUS_AVL);
vehicle.setPrice(Long.parseLong(request.getParameter(CAR_EXPRICE)));
vehicle.setBuyer("");
vehicle.setColor("");
vehicle.setImage("");
return constructModelAndView(
CAR_KEY_PATTERN + autoShoppeService.addVehicle(vehicle));
} catch (NumberFormatException nfe) {
//Parsing failed over expected numeric data.
return constructModelAndView(MSG_INVALID_NUMBER);
} catch (NullPointerException npe) {
//A required request parameter is missing.
return constructModelAndView(MSG_MISSING_PARAM);
}
}
/**
* Retrieves all the vehicles from the datastore and returns them
* formatted as Json.
*
* @param request HttpServletRequest object
* @param response HttpServletResponse object
* @return ModelAndView a Spring MVC framework instance with data and view
* for the client
*/
public ModelAndView getAllVehicles(
HttpServletRequest request, HttpServletResponse response) {
//Default page is one. If request contains one, use that else default.
int page = 1;
Object parameter = request.getParameter(PAGE_PARAM);
if (parameter != null) {
try {
page = Integer.parseInt(parameter.toString());
} catch (NumberFormatException nfe) {
page = 1;
}
}
Collection<Vehicle> records = autoShoppeService.getAllVehicles(page);
return constructModelAndView(gson.toJson(records));
}
/**
* Searches with custom filters on vehicle selection and returns the
* reponse in Json format. When a filter on price is specified, the parameter
* values of GQL_PRICEOP are interpreted as follows:
* 0 - EQUALS
* 1 - LESS THAN EQUALS
* 2 - GREATER THAN EQUALS
*
* Sends back an appropriate error message in case of invalid input.
*
* @param request HttpServletRequest object
* @param response HttpServletResponse object
* @return ModelAndView a Spring MVC framework instance with data and view
* for the client
*/
public ModelAndView getVehiclesByCustomSearch(
HttpServletRequest request, HttpServletResponse response) {
//Default search filters.
long price = 0;
Operator priceOp = Operator.EQUALS;
String vehicleType = null;
int page = 1;
//Retrieve all the paramaeters from POST request.
String parameter = request.getParameter(CAR_EXPRICE);
if (parameter != null) {
//Validate the price filter and operator.
try {
price = Integer.parseInt(parameter);
parameter = request.getParameter(GQL_PRICEOP);
priceOp = lookUpOperatorByOrdinal(Integer.parseInt(parameter));
} catch (NumberFormatException nfe) {
//Parsing failed over expected numeric data.
return constructModelAndView(MSG_INVALID_NUMBER);
} catch (NullPointerException npe) {
//Required request parameter is missing.
return constructModelAndView(MSG_MISSING_PARAM);
} catch (ArrayIndexOutOfBoundsException indexException) {
//Invalid search criteria
return constructModelAndView(MSG_INVALID_SEARCH);
}
}
parameter = request.getParameter(CAR_TYPE);
if (parameter != null) {
vehicleType = parameter;
}
if (vehicleType == null && price == 0) {
//One of the filters has to be specified
return constructModelAndView(MSG_INVALID_SEARCH);
}
parameter = request.getParameter(PAGE_PARAM);
if (parameter != null) {
try {
page = Integer.parseInt(parameter);
} catch (NumberFormatException nfe) {
//Defaulting the page to 1.
page = 1;
}
}
Collection<Vehicle> records = autoShoppeService.getVehiclesByCustomSearch(
price, priceOp, vehicleType, page);
return constructModelAndView(gson.toJson(records));
}
/**
* Updates the vehicle status as sold with the buyer email address.
*
* @param request HttpServletRequest object
* @param response HttpServletResponse object
* @return ModelAndView a Spring MVC framework instance with data and view
* for the client
*/
public ModelAndView markSold(
HttpServletRequest request, HttpServletResponse response) {
String recordKey = request.getParameter(CAR_KEY);
if (recordKey == null) {
return constructModelAndView(MSG_MISSING_PARAM);
}
boolean success = autoShoppeService.markSold(recordKey,
userService.getCurrentUser().getEmail());
return constructModelAndView(String.valueOf(success));
}
/**
* Looks up the Operator value based on ordinal.
*
* @param ordinal the ordinal value to look up in enum set
* @return Operator value corresponding to the ordinal
*/
private static Operator lookUpOperatorByOrdinal(int ordinal) {
return Operator.values()[ordinal];
}
/**
* Creates a Spring ModelAndView respresentation from the JSON formatted
* result.
*
* @param json the data model in MVC.
* @return ModelAndView a Spring MVC framework instance with data and view
* for the client
*/
private static ModelAndView constructModelAndView(String json) {
ModelAndView mv = new ModelAndView();
mv.addObject(JSON_MODEL, json);
mv.setViewName(JSON_VIEW);
return mv;
}
}
| 37.376176 | 94 | 0.735721 |
f400300d5becd573ef39c352bdf7b5d4be2f8539 | 1,791 | package com.artemis;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.artemis.component.Packed;
public class PackedComponentTest
{
private World world;
private ComponentMapper<Packed> packedMapper;
@Before
public void init() {
world = new World();
packedMapper = world.getMapper(Packed.class);
}
@Test
public void packed_components_are_known_to_mapper() {
world.initialize();
List<Entity> packed = new ArrayList<Entity>();
packed.add(createEntity(Packed.class));
packed.add(createEntity(Packed.class));
packed.add(createEntity(Packed.class));
Entity notPresent = createEntity();
packed.add(createEntity(Packed.class));
packed.add(createEntity(Packed.class));
for (Entity e : packed) {
assertTrue(packedMapper.has(e));
}
assertFalse(packedMapper.has(notPresent));
packed.get(1).edit().remove(Packed.class);
for (int i = 0; packed.size() > i; i++) {
if (i != 1) assertTrue(packedMapper.has(packed.get(i)));
}
assertFalse(packedMapper.has(packed.get(1)));
}
@Test
public void packed_component_mappers_return_new_instance_on_request() {
world.initialize();
Entity e1 = createEntity(Packed.class);
Entity e2 = createEntity(Packed.class);
Packed packed1 = packedMapper.get(e1, true);
Packed packed2 = packedMapper.get(e2, true);
assertNotEquals(packed1.entityId, packed2.entityId);
}
@SuppressWarnings("unchecked")
private Entity createEntity(Class<?>... components) {
Entity e = world.createEntity();
for (Class<?> c : components) {
e.edit().create((Class<Component>)c);
}
return e;
}
}
| 24.875 | 72 | 0.720268 |
077c215721cf5b811b31bfe7d001bf4b05c83be7 | 158 | package progra2.pkg2_lab4_dennischirinos_daviddiaz;
public class Plataforma extends Almacen {
public char[] antirrobo() {
return null;
}
}
| 15.8 | 51 | 0.708861 |
973a152f2e87e49c6cac82d7b2e9feb6b98ce761 | 915 | package com.udacity.jdnd.course3.critter.service;
import com.udacity.jdnd.course3.critter.model.entity.Customer;
import com.udacity.jdnd.course3.critter.model.entity.Pet;
import com.udacity.jdnd.course3.critter.repository.CusRepository;
import com.udacity.jdnd.course3.critter.repository.PetRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CusService {
@Autowired
CusRepository cusRepository;
@Autowired
PetRepository petRepository;
public List<Customer> findAll(){
return cusRepository.getAllCustomers();
}
public Customer findOneById(Long id){
return cusRepository.getCustomerById(id);
}
public Customer findOwnerByPet(Long petId){
Pet pet = petRepository.getOne(petId);
return cusRepository.getOwnerByPet(pet);
}
}
| 27.727273 | 65 | 0.761749 |
efe8c0eb7852d02d09d657c3b824c693d74bbc38 | 1,368 | package org.col.api.model;
import java.util.Objects;
import com.google.common.base.Preconditions;
import org.col.api.vocab.TaxonomicStatus;
/**
* A taxonomic synonym, linking a name to potentially multiple taxa.
* Can be used for both homo-and heterotypic synonyms as well as misapplied names.
*/
public class Synonym extends NameUsageBase {
private Taxon accepted;
@Override
public void setStatus(TaxonomicStatus status) {
if (!Preconditions.checkNotNull(status).isSynonym()) {
throw new IllegalArgumentException("Synonym status required");
}
super.setStatus(status);
}
/**
* @return true if the synonym is a homotypic synonym for at least one of the accepted names.
*/
public boolean isHomotypic() {
return getName().getHomotypicNameId().equals(accepted.getName().getHomotypicNameId());
}
public Taxon getAccepted() {
return accepted;
}
public void setAccepted(Taxon accepted) {
this.accepted = accepted;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Synonym synonym = (Synonym) o;
return Objects.equals(accepted, synonym.accepted);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), accepted);
}
}
| 25.811321 | 95 | 0.693713 |
b3c5e6c9564c61659a100228f59a2e0795eacfea | 612 | package galamadriabuyak.util;
public enum Target {
SELF("self"),
ENEMY("enemy"),
BASIC_ATTACK("basicAttack");
private String name;
Target(String name) {
if (name == null) {
throw new AssertionError();
}
this.name = name;
}
public String toString() {
return name;
}
public static Target myValueOf(String arg) {
if (arg.equals("self")) {
return SELF;
} else if (arg.equals("enemy")) {
return ENEMY;
} else {
throw new AssertionError();
}
}
} | 20.4 | 48 | 0.503268 |
77fa16c658df066747285f6d7dd21b6568174880 | 244 | package com.questionnaire.ssm.module.login.mapper;
import java.util.Set;
public interface SysUserMapper {
Set<String> listUserRole(String userTel) throws Exception;
Set<String> listUserPermission(String userTel) throws Exception;
} | 22.181818 | 68 | 0.786885 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.