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
|
---|---|---|---|---|---|
d72f0f62855aa7e75985e726e9fdd4cb9f3f6436
| 548 |
import java.awt.*;
import javax.swing.undo.*;
public class UndoTake
extends AbstractUndoableEdit {
Stub who;
Container where;
int which;
UndoTake(Stub w) {
super();
who = w;
doo();
}
private void doo() {
where = who.getParent();
System.out.println("par"+where.getLocation().x);
which = where.getComponentZOrder(who);
where.remove(which);
}
public void redo() {
super.redo();
doo();
}
public void undo() {
super.undo();
//if (!where) return;
where.add(who,which);
}public boolean isSignificant(){return true;}
}
| 18.266667 | 50 | 0.658759 |
65ff12b412462dbe474ec5c93a2b3d891a731343
| 1,987 |
package org.bukkit.craftbukkit.entity;
import com.google.common.base.Preconditions;
import net.minecraft.world.entity.monster.EntityShulker;
import org.bukkit.DyeColor;
import org.bukkit.block.BlockFace;
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.craftbukkit.block.CraftBlock;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Shulker;
public class CraftShulker extends CraftGolem implements Shulker {
public CraftShulker(CraftServer server, EntityShulker entity) {
super(server, entity);
}
@Override
public String toString() {
return "CraftShulker";
}
@Override
public EntityType getType() {
return EntityType.SHULKER;
}
@Override
public EntityShulker getHandle() {
return (EntityShulker) entity;
}
@Override
public DyeColor getColor() {
return DyeColor.getByWoolData(getHandle().getEntityData().get(EntityShulker.DATA_COLOR_ID));
}
@Override
public void setColor(DyeColor color) {
getHandle().getEntityData().set(EntityShulker.DATA_COLOR_ID, (color == null) ? 16 : color.getWoolData());
}
@Override
public float getPeek() {
return (float) getHandle().getRawPeekAmount() / 100;
}
@Override
public void setPeek(float value) {
Preconditions.checkArgument(value >= 0 && value <= 1, "value needs to be in between or equal to 0 and 1");
getHandle().setRawPeekAmount((int) (value * 100));
}
@Override
public BlockFace getAttachedFace() {
return CraftBlock.notchToBlockFace(getHandle().getAttachFace());
}
@Override
public void setAttachedFace(BlockFace face) {
Preconditions.checkNotNull(face, "face cannot be null");
Preconditions.checkArgument(face.isCartesian(), "%s is not a valid block face to attach a shulker to, a cartesian block face is expected", face);
getHandle().setAttachFace(CraftBlock.blockFaceToNotch(face));
}
}
| 30.106061 | 153 | 0.695521 |
fa6a8a0a04a039d315fdbfa82442091d4f9f85ad
| 1,961 |
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.cloud.cc.api;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.Collection;
import java.util.UUID;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class CcExtendedServiceInstanceEntity {
@JsonProperty("name")
private String name;
@JsonProperty("credentials")
private Object credentials;
@JsonProperty("service_plan_guid")
private UUID servicePlanGuid;
@JsonProperty("service_plan")
private CcExtendedServicePlan servicePlan;
@JsonProperty("space_guid")
private UUID spaceGuid;
@JsonProperty("gateway_data")
private String gatewayData;
@JsonProperty("dashboard_url")
private String dashboardUrl;
@JsonProperty("type")
private String type;
@JsonProperty("last_operation")
private Object lastOperation;
@JsonProperty("tags")
private Object tags;
@JsonProperty("space_url")
private String spaceUrl;
@JsonProperty("service_plan_url")
private String servicePlanUrl;
@JsonProperty("service_bindings_url")
private String serviceBindingsUrl;
@JsonProperty("service_keys_url")
private String serviceKeysUrl;
@JsonProperty("service_keys")
private Collection<CcServiceKey> serviceKeys;
}
| 26.146667 | 75 | 0.744518 |
ffad4dae85511851baa2257023667c34c05a1a9f
| 1,046 |
package org.jpwh.model.inheritance.associations.onetomany;
import org.jpwh.model.Constants;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
// Can not be @MappedSuperclass when it's a target class in associations!
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class BillingDetails {
@Id
@GeneratedValue(generator = Constants.ID_GENERATOR)
protected Long id;
@ManyToOne(fetch = FetchType.LAZY)
protected User user;
@NotNull
protected String owner;
protected BillingDetails() {
}
protected BillingDetails(String owner) {
this.owner = owner;
}
public Long getId() {
return id;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void pay(int amount) {
// NOOP
}
// ...
}
| 18.678571 | 73 | 0.644359 |
55d7110ccb831038c4e8e1d34f346653e99c6863
| 64 |
public class Test {
Integer f1 = null;
Integer f2 = f1;
}
| 12.8 | 21 | 0.609375 |
2bf6344180aa7a22d555b83db00820af4e049b02
| 7,254 |
package com.example.xiaoming.rainmeterweather;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.xiaoming.rainmeterweather.database.weatherList;
import com.example.xiaoming.rainmeterweather.gson.Weather;
import com.example.xiaoming.rainmeterweather.util.HttpUtil;
import com.example.xiaoming.rainmeterweather.util.ResolveJSON;
import org.litepal.crud.DataSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class WeatherListActivity extends AppCompatActivity {
public ListView listView;
public FloatingActionButton fbtn_add;
public List<weatherList> data = new ArrayList<>();
public DrawerLayout layout_drawer;
private String WeatherId;
public WeatherAdapter adapter;
private List<weatherList> list = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//简易实现状态栏与背景图片融合在一起,此方法仅限于安卓5.0以上的用户才能实现
if(Build.VERSION.SDK_INT>=21){
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getWindow().setStatusBarColor(Color.TRANSPARENT); //设置状态栏为透明色
}
setContentView(R.layout.activity_weather_list);
listView = (ListView) findViewById(R.id.list_view);
layout_drawer = (DrawerLayout) findViewById(R.id.layout_drawers);
fbtn_add = (FloatingActionButton) findViewById(R.id.fbtn_add);
initList();
//设置listview监听事件
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
weatherList weatherlist = data.get(position);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(WeatherListActivity.this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.putString("weather_id",weatherlist.getWeatherId());
editor.commit();
Intent intent = new Intent(WeatherListActivity.this,WeatherActivity.class);
startActivity(intent);
WeatherListActivity.this.finish();
}
});
//设置添加按钮的监听事件
fbtn_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
layout_drawer.openDrawer(GravityCompat.START);
fbtn_add.setVisibility(View.GONE);
}
});
}
private void initList() {
list = new ArrayList<>();
list = DataSupport.findAll(weatherList.class);
data.clear();
for(weatherList weatherList : list){
if (!data.contains(weatherList)){
data.add(weatherList);
}
}
adapter = new WeatherAdapter(WeatherListActivity.this,R.layout.list_item,data);
listView.setAdapter(adapter);
}
/**
* 自定义Listview适配器
*/
public class WeatherAdapter extends ArrayAdapter<weatherList>{
private int resourceId;
public WeatherAdapter(Context context,int textViewResourseId,List<weatherList> objects){
super(context,textViewResourseId,objects);
resourceId = textViewResourseId;
}
public View getView(int position, View convertView, ViewGroup parent){
weatherList weatherList = getItem(position);
View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
TextView tv_city = (TextView) view.findViewById(R.id.tv_city);
TextView tv_updateTime = (TextView) view.findViewById(R.id.tv_updateTime);
TextView tv_weather = (TextView) view.findViewById(R.id.tv_weather);
tv_city.setText(weatherList.getCity());
tv_updateTime.setText(weatherList.getUpdateTime().split(" ")[1]);
tv_weather.setText(weatherList.getTemperature() + "℃/" + weatherList.getWeatherType());
return view;
}
}
/**
* 根据weather_id请求返回天气数据
*/
public void requestWeather(final String weatherId) {
String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=4e7f961f49e249da8fcb3afc0055f23e";
HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(WeatherListActivity.this,"获取天气信息失败",Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseData = response.body().string();
final Weather weather = ResolveJSON.resolveWeaResData(responseData);
list = new ArrayList<weatherList>();
list = DataSupport.findAll(weatherList.class);
runOnUiThread(new Runnable() {
@Override
public void run() {
if(weather !=null && weather.status.equals("ok")){
WeatherId = weather.basic.weatherId;
String city = weather.basic.cityName;
String updateTime = weather.basic.update.updateTime;
String temperature = weather.now.temperature;
String weatherType = weather.now.weatherType.info;
weatherList weatherList = new weatherList();
weatherList.setCity(city);
weatherList.setUpdateTime(updateTime);
weatherList.setTemperature(temperature);
weatherList.setWeatherType(weatherType);
weatherList.setWeatherId(WeatherId);
weatherList.save();
initList();
}else {
Toast.makeText(WeatherListActivity.this,"获取天气信息失败",Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
| 41.689655 | 126 | 0.632065 |
a69fd779c22df84d6040e2121dd07ded680d347d
| 1,813 |
package ru.stqa.training.selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class LoginTests {
private WebDriver chromeDriver;
private WebDriver firefoxDriver;
private WebDriver safariDriver;
private WebDriver nightDriver;
@BeforeTest
public void start(){
chromeDriver = new ChromeDriver();
firefoxDriver = new FirefoxDriver();
safariDriver = new SafariDriver();
String binary = "/Applications/Firefox Nightly.app/Contents/MacOS/firefox-bin";
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(binary);
nightDriver = new FirefoxDriver(firefoxOptions);
}
public void testLogin(WebDriver driver){
driver.get("http://localhost/litecart/admin/");
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("password")).sendKeys("admin");
driver.findElement(By.name("login")).click();
}
@Test
public void testChrome(){
testLogin(chromeDriver);
}
@Test
public void testFirefox(){
testLogin(firefoxDriver);
}
@Test
public void testSafari(){
testLogin(safariDriver);
}
@Test
public void testNight(){
testLogin(nightDriver);
}
@AfterTest
public void stop(){
chromeDriver.quit();
firefoxDriver.quit();
safariDriver.quit();
nightDriver.quit();
}
}
| 25.9 | 87 | 0.680088 |
786632147fcb6a25a8a79bc308aa8bce87142b48
| 711 |
package com.eladmin.tools;
import java.nio.charset.Charset;
public class DefaultCharset {
public static final Charset charset = Charset.forName("UTF-8");
public static final String name = Charset.forName("UTF-8").name();
public static final Charset charset_iso_8859_1 = Charset.forName("iso-8859-1");
public static final String name_iso_8859_1 = Charset.forName("iso-8859-1").name();
public static final Charset charset_utf_8 = Charset.forName("UTF-8");
public static final String name_iso_utf_8 = Charset.forName("UTF-8").name();
public static final Charset charset_gbk = Charset.forName("GBK");
public static final String name_gbk = Charset.forName("GBK").name();
}
| 29.625 | 86 | 0.728551 |
8c06fd66ca5b7d2575cc4a09267e3f29310d8404
| 9,096 |
package applico.googlezlpreview.adapters;
import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.List;
import applico.googlezlpreview.R;
import applico.googlezlpreview.activities.GlobalDetailsActivity;
import applico.googlezlpreview.models.Event;
import applico.googlezlpreview.views.FabView;
/**
* There are two methods that I have incorporated as a logical
* branch to show off different animations. One is using the standard moveImage tag
* The other is to show off combining the animation classes with the make scene transition
* animation class. The animations are not clean right now, it would take a little refactoring, but the
* intention of these was to show off the new shared element animation and the combination of a shared
* element
* @author Matt Powers
*/
public class EventAdapter extends RecyclerView.Adapter<EventAdapter.ViewHolder> implements View
.OnClickListener {
private static String LOG_TAG = EventAdapter.class.getSimpleName();
private List<Event> mEventDataset;
private static final int SLIDE_DURATION = 300;
private View mFabView;
// Provide a suitable constructor (depends on the kind of dataset)
public EventAdapter(List<Event> myDataset, View fabView)
{
mEventDataset = myDataset;
mFabView = fabView;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_global_items, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(ViewHolder holder, int pos) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
Event ev = mEventDataset.get(pos);
String position = String.valueOf(pos + 1);
holder.mTitleRankTV.setText(position);
holder.mTitleTV.setText(ev.eventTitle);
holder.mBaseImageIV.setImageBitmap(ev.eventImageSmall);
//Set the tag for the onClick event
holder.mLearnMoreTV.setTag(holder);
holder.mLearnMoreTV.setOnClickListener(this);
//TODO - holding onto the view holder twice, need to clean that up.
holder.mCardView.setTag(holder);
holder.mCardView.setOnClickListener(this);
}
//Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mEventDataset.size();
}
@Override
public void onClick(View v) {
ViewHolder holder = (ViewHolder)v.getTag();
switch(v.getId())
{
case R.id.learn_more:
slideandSharedAnimation(holder, v.getContext());
break;
case R.id.region_card_view:
standardSharedAnimation(holder, v.getContext());
break;
}
}
// Provide a reference to the type of views that you are using
// (custom viewholder)
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView mTitleTV;
private TextView mTitleRankTV;
private TextView mShareTV;
private TextView mLearnMoreTV;
private ImageView mBaseImageIV;
private CardView mCardView;
public ViewHolder(View v) {
super(v);
mTitleRankTV = (TextView)v.findViewById(R.id.base_caption_num);
mTitleTV = (TextView)v.findViewById(R.id.base_caption);
mShareTV = (TextView)v.findViewById(R.id.share_link);
mLearnMoreTV = (TextView) v.findViewById(R.id.learn_more);
mBaseImageIV = (ImageView)v.findViewById(R.id.base_image);
mCardView = (CardView)v.findViewById(R.id.region_card_view);
}
}
//TODO this logic needs to be moved out of the adapter and into the fragment.
private void standardSharedAnimation(ViewHolder holder, Context ctx)
{
TextView aVTitle = holder.mTitleTV;
TextView aVRank = holder.mTitleRankTV;
ImageView aVImage = holder.mBaseImageIV;
aVImage.setTransitionName(GlobalDetailsActivity.SHARED_IMAGE);
final CardView cv = (CardView)aVImage.getParent().getParent();
Event event = mEventDataset.get(Integer.parseInt(aVRank.getText().toString()) - 1);
final Intent intent = new Intent(ctx, GlobalDetailsActivity.class);
intent.putExtra(GlobalDetailsActivity.TITLE_KEY, event.eventTitle);
intent.putExtra(GlobalDetailsActivity.RANK_KEY, aVRank.getText());
intent.putExtra(GlobalDetailsActivity.RESOURCE_KEY, event.eventImageDetailID);
Activity act = (Activity)ctx;
mFabView.setTransitionName(GlobalDetailsActivity.SHARED_FAB_VIEW);
Pair shared = Pair.create(aVImage, GlobalDetailsActivity.SHARED_IMAGE);
//TODO add another pair for the FAB view
Pair sharedFab = Pair.create(mFabView, GlobalDetailsActivity.SHARED_FAB_VIEW);
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation((Activity)ctx, shared);
Bundle bundle = options.toBundle();
ctx.startActivity(intent, bundle);
}
//TODO this logic needs to be moved out of the adapter and into the fragment.
private void slideandSharedAnimation(ViewHolder holder, final Context ctx)
{
TextView aVTitle = holder.mTitleTV;
TextView aVRank = holder.mTitleRankTV;
ImageView aVImage = holder.mBaseImageIV;
aVImage.setTransitionName(GlobalDetailsActivity.SHARED_IMAGE);
final CardView cv = (CardView)aVImage.getParent().getParent();
RelativeLayout rl = (RelativeLayout)cv.getParent().getParent().getParent();
FabView fv = (FabView)rl.findViewById(R.id.fab_view);
fv.setTransitionName(GlobalDetailsActivity.SHARED_FAB_VIEW);
Event event = mEventDataset.get(Integer.parseInt(aVRank.getText().toString()) - 1);
final Intent intent = new Intent(ctx, GlobalDetailsActivity.class);
intent.putExtra(GlobalDetailsActivity.TITLE_KEY, event.eventTitle);
intent.putExtra(GlobalDetailsActivity.RANK_KEY, aVRank.getText());
intent.putExtra(GlobalDetailsActivity.RESOURCE_KEY, event.eventImageDetailID);
Activity act = (Activity)ctx;
final Pair sharedFirst = Pair.create(aVImage,GlobalDetailsActivity.SHARED_IMAGE);
final Pair sharedSecond = Pair.create(fv, GlobalDetailsActivity.SHARED_FAB_VIEW);
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation((Activity)ctx,sharedFirst,sharedSecond);
final Bundle bundle = options.toBundle();
final int newMargin = 0;
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)cv.getLayoutParams();
final int originalLeftMargin = params.leftMargin;
final int originalRightMargin = params.rightMargin;
//TODO need to figure out how to unwind this animation, as the callback in the onBackPressed does not cover this due to it not being a part of the activity transition.
Animation anim = new Animation()
{
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)cv.getLayoutParams();
int currentLeftMargin = params.leftMargin;
int currentRightMargin = params.rightMargin;
params.leftMargin = currentLeftMargin - (int)((currentLeftMargin - newMargin) *
interpolatedTime);
params.rightMargin = currentRightMargin - (int)((currentRightMargin - newMargin) *
interpolatedTime);
cv.setLayoutParams(params);
}
};
anim.setDuration(SLIDE_DURATION);
anim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)cv.getLayoutParams();
ctx.startActivity(intent, bundle);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
cv.startAnimation(anim);
}
}
| 39.038627 | 175 | 0.693162 |
cc6e45112bb37d135f5960a44ccca17cadb8f890
| 252 |
import org.apache.hadoop.ipc.ProtocolInfo;
/**
* Created by prasanthj on 2020-06-19.
*/
// https://cwiki.apache.org/confluence/display/HADOOP2/HadoopRpc
@ProtocolInfo(protocolName = "ping", protocolVersion = 1)
interface PingRPC {
String ping();
}
| 25.2 | 64 | 0.738095 |
411a4d2631da9d09da04da65049b3177c1d3d1ac
| 603 |
package com.linkedin.thirdeye.rootcause;
import java.util.HashSet;
import java.util.Set;
/**
* Container object for pipeline execution results. Holds entities with scores as set by the pipeline.
*/
public class PipelineResult {
private final PipelineContext context;
private final Set<Entity> entities;
public PipelineResult(PipelineContext context, Set<? extends Entity> entities) {
this.context = context;
this.entities = new HashSet<>(entities);
}
public PipelineContext getContext() {
return context;
}
public Set<Entity> getEntities() {
return entities;
}
}
| 22.333333 | 102 | 0.733002 |
c00b5bdf51845c6d81e29fadf7351d469d37485a
| 773 |
package moe.aoramd.paperclip.loader;
import android.net.Uri;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
/**
* 采用 Picasso 实现 PaperClip 图片加载接口的加载器
*
* @author M.D.
* @version 1
*/
public class PicassoLoader extends ImageLoader {
/**
* 默认加载方法
*
* @param uri 需要加载的图片 URI
* @param target 目标图片控件
*/
@Override
protected void load(Uri uri, ImageView target, int width, int height) {
Picasso.get().load(uri).centerCrop().resize(width, height).into(target);
}
/**
* 原图加载方法
*
* @param uri 需要加载的图片 URI
* @param target 目标图片控件
*/
@Override
public void loadOrigin(Uri uri, ImageView target) {
Picasso.get().load(uri).centerCrop().into(target);
}
}
| 20.891892 | 80 | 0.623545 |
01fbe28c6fa36361e6a986d777fabc44a76c3858
| 10,493 |
package com.gaoyy.delivery4res.mine.replylist;
import android.content.DialogInterface;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import com.gaoyy.delivery4res.R;
import com.gaoyy.delivery4res.adapter.ReplyOrderListAdapter;
import com.gaoyy.delivery4res.api.Constant;
import com.gaoyy.delivery4res.api.RetrofitService;
import com.gaoyy.delivery4res.api.bean.CommonInfo;
import com.gaoyy.delivery4res.api.bean.ReplyOrderListInfo;
import com.gaoyy.delivery4res.base.BaseFragment;
import com.gaoyy.delivery4res.base.CustomDialogFragment;
import com.gaoyy.delivery4res.base.recycler.OnItemClickListener;
import com.gaoyy.delivery4res.util.CommonUtils;
import com.gaoyy.delivery4res.util.DialogUtils;
import com.pnikosis.materialishprogress.ProgressWheel;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import retrofit2.Call;
public class ReplyListFragment extends BaseFragment implements ReplyListContract.View, SwipeRefreshLayout.OnRefreshListener, OnItemClickListener
{
private static final String LOG_TAG = ReplyListFragment.class.getSimpleName();
private ProgressWheel commonProgresswheel;
private SwipeRefreshLayout commonSwipeRefreshLayout;
private RecyclerView commonRv;
private int lastVisibleItem;
private int pageNo = 1;
private int pageSize = Constant.PAGE_SIZE;
private int pageCount;
private LinearLayoutManager linearLayoutManager;
private ReplyOrderListAdapter replyOrderListAdapter;
private LinkedList<ReplyOrderListInfo.BodyBean.ListBean.ResultBean> replyOrderList = new LinkedList<>();
private ReplyListContract.Presenter mReplyListPresenter;
private CustomDialogFragment loading;
private Call<ReplyOrderListInfo> replyOrderListCall;
private Call<CommonInfo> replyOrderCall;
public ReplyListFragment()
{
// Required empty public constructor
}
public static ReplyListFragment newInstance()
{
ReplyListFragment fragment = new ReplyListFragment();
return fragment;
}
@Override
protected int getFragmentLayoutId()
{
return R.layout.fragment_reply_list;
}
@Override
protected void assignViews(View rootView)
{
super.assignViews(rootView);
commonProgresswheel = (ProgressWheel) rootView.findViewById(R.id.common_progresswheel);
commonSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.common_swipeRefreshLayout);
commonRv = (RecyclerView) rootView.findViewById(R.id.common_rv);
}
@Override
protected void configViews()
{
super.configViews();
replyOrderListAdapter = new ReplyOrderListAdapter(activity, replyOrderList);
commonRv.setAdapter(replyOrderListAdapter);
//设置布局
linearLayoutManager = new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false);
commonRv.setLayoutManager(linearLayoutManager);
commonRv.setItemAnimator(new DefaultItemAnimator());
CommonUtils.setSwipeLayoutProgressBackgroundColor(activity, commonSwipeRefreshLayout);
}
@Override
protected void setListener()
{
super.setListener();
commonSwipeRefreshLayout.setOnRefreshListener(this);
commonRv.setOnScrollListener(new RecyclerView.OnScrollListener()
{
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState)
{
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == replyOrderListAdapter.getItemCount())
{
//总共有多少页
int pageSum = 0;
pageNo = pageNo + 1;
if (pageCount % pageSize == 0)
{
pageSum = pageCount / pageSize;
}
else
{
pageSum = pageCount / pageSize + 1;
}
Log.d(Constant.TAG, "page sum-->" + pageSum);
Log.d(Constant.TAG, "page No-->" + pageNo);
if (pageNo <= pageSum)
{
Map<String, String> params = getReplyOrderListParams(pageNo, pageSize);
Log.d(Constant.TAG, "上拉加载更多,传递参数-->" + params.toString());
replyOrderListCall = RetrofitService.sApiService.replyOrderList(params);
mReplyListPresenter.replyOrderList(replyOrderListCall, params, Constant.UP_TO_LOAD_MORE);
}
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy)
{
super.onScrolled(recyclerView, dx, dy);
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
}
});
//设置item的点击事件
replyOrderListAdapter.setOnItemClickListener(this);
}
@Override
public void onResume()
{
super.onResume();
if (mReplyListPresenter == null) return;
mReplyListPresenter.start();
//在onResume中加载数据
pageNo = 1;
Map<String, String> params = getReplyOrderListParams(pageNo, pageSize);
Log.d(Constant.TAG, "待回复列表参数:" + params.toString());
replyOrderListCall = RetrofitService.sApiService.replyOrderList(params);
mReplyListPresenter.replyOrderList(replyOrderListCall, params, Constant.PULL_TO_REFRESH);
}
private Map<String, String> getReplyOrderListParams(int pageNo, int pageSize)
{
Map<String, String> params = new HashMap<>();
params.put("loginName", CommonUtils.getLoginName(activity));
params.put("randomCode", CommonUtils.getRandomCode(activity));
params.put("pageNo", String.valueOf(pageNo));
params.put("pageSize", String.valueOf(pageSize));
params.put("language", CommonUtils.getSysLanguage());
return params;
}
@Override
public boolean isActive()
{
return isAdded();
}
@Override
public void showReplyOrderList(LinkedList<ReplyOrderListInfo.BodyBean.ListBean.ResultBean> replyOrderList, int count)
{
replyOrderListAdapter.updateData(replyOrderList);
pageCount = count;
}
@Override
public void loadMoreReplyOrderList(LinkedList<ReplyOrderListInfo.BodyBean.ListBean.ResultBean> replyOrderList, int count)
{
replyOrderListAdapter.addMoreItem(replyOrderList);
pageCount = count;
}
@Override
public void refreshing()
{
commonSwipeRefreshLayout.setRefreshing(true);
}
@Override
public void finishRefesh()
{
commonSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void showToast(String msg)
{
CommonUtils.showToast(activity, msg);
}
@Override
public void showToast(int msgId)
{
CommonUtils.showToast(activity, msgId);
}
@Override
public void setPresenter(ReplyListContract.Presenter presenter)
{
Log.i(Constant.TAG, LOG_TAG + " setPresenter");
if (presenter != null)
{
mReplyListPresenter = presenter;
}
}
@Override
public void showLoading()
{
loading = DialogUtils.showLoadingDialog(activity);
}
@Override
public void hideLoading()
{
if (loading != null)
{
loading.dismissAllowingStateLoss();
}
}
@Override
public void onRefresh()
{
pageNo = 1;
Map<String, String> params = getReplyOrderListParams(pageNo, pageSize);
Log.d(Constant.TAG, "下拉刷新,传递参数-->" + params.toString());
replyOrderListCall = RetrofitService.sApiService.replyOrderList(params);
if(mReplyListPresenter!=null)
{
mReplyListPresenter.replyOrderList(replyOrderListCall, params, Constant.PULL_TO_REFRESH);
}
}
@Override
public void removeSingleItem(int position)
{
replyOrderListAdapter.removeSingleItem(position);
}
@Override
public void onItemClick(View view, final int position, Object itemData)
{
final ReplyOrderListInfo.BodyBean.ListBean.ResultBean order = (ReplyOrderListInfo.BodyBean.ListBean.ResultBean) itemData;
switch (view.getId())
{
case R.id.item_reply_btn:
View editView = LayoutInflater.from(activity).inflate(R.layout.dialog_reply, null);
final EditText et = (EditText) editView.findViewById(R.id.dialog_reply_edit);
AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
dialog.setTitle(R.string.reply_order).setView(editView);
dialog.setPositiveButton(R.string.alert_confirm,
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
Map<String, String> params = new HashMap<String, String>();
params.put("loginName", CommonUtils.getLoginName(activity));
params.put("randomCode", CommonUtils.getRandomCode(activity));
params.put("content", et.getText().toString());
params.put("order_id", order.getId() + "");
params.put("language", "zh");
replyOrderCall = RetrofitService.sApiService.replyOrderSave(params);
mReplyListPresenter.replyOrder(replyOrderCall, position, params);
}
}).show();
break;
}
}
@Override
public void onPause()
{
super.onPause();
//取消网络请求
if (replyOrderListCall != null) replyOrderListCall.cancel();
if (replyOrderCall != null) replyOrderCall.cancel();
}
}
| 34.516447 | 144 | 0.641571 |
db87a22ee8d6c8e16d69b08cf92367a2e420d059
| 3,164 |
/*
* Copyright 2004-2013 ICEsoft Technologies Canada Corp.
*
* 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.icefaces.mobi.component.contentnavbar;
import org.icefaces.mobi.component.contentpane.ContentPane;
import org.icefaces.mobi.renderkit.BaseLayoutRenderer;
import org.icefaces.mobi.utils.HTML;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ContentNavBarRenderer extends BaseLayoutRenderer {
private static final Logger logger = Logger.getLogger(ContentNavBarRenderer.class.getName());
public void encodeBegin(FacesContext facesContext, UIComponent uiComponent)throws IOException {
UIComponent parent = findParentContentPane(uiComponent);
if (!(parent instanceof ContentPane) &&
logger.isLoggable(Level.FINER)){
logger.finer("this component must be a child of ContentPane");
return;
}
ResponseWriter writer = facesContext.getResponseWriter();
String clientId = uiComponent.getClientId(facesContext);
ContentNavBar navbar = (ContentNavBar) uiComponent;
ContentPane cp = (ContentPane)parent;
writer.startElement(HTML.DIV_ELEM, uiComponent);
writer.writeAttribute(HTML.ID_ATTR, clientId, HTML.ID_ATTR);
StringBuilder styleClass = new StringBuilder(ContentNavBar.CONTENTNAVBAR_BASE_CLASS);
StringBuilder buttonClass = new StringBuilder (ContentNavBar.CONTENTNAVBAR_BUTTON_CLASS);
// user specified style class
String userDefinedClass = navbar.getStyleClass();
if (userDefinedClass != null && userDefinedClass.length() > 0){
styleClass.append(" ").append(userDefinedClass);
buttonClass.append(" ").append(userDefinedClass);
}
writer.writeAttribute("class", styleClass.toString(), "styleClass");
// write out any users specified style attributes.
if (navbar.getStyle() != null) {
writer.writeAttribute(HTML.STYLE_ATTR, navbar.getStyle(), "style");
}
}
public void encodeEnd(FacesContext facesContext, UIComponent uiComponent) throws IOException {
ResponseWriter writer = facesContext.getResponseWriter();
writer.endElement(HTML.DIV_ELEM);
}
public boolean getRendersChildren() {
return true;
}
public void encodeChildren(FacesContext facesContext, UIComponent uiComponent) throws IOException{
super.renderChildren(facesContext, uiComponent);
}
}
| 41.631579 | 102 | 0.725348 |
a2143987f62d26a57ef5875a2692aa7fb5f35e72
| 315 |
/*Threads, Multithreading and Concurrency*/
package com.javaconcepts.multithreadingAndConcurrency;
public class RunnableThread implements Runnable {
@Override
public void run() {
System.out.println(
"This is inside the first new thread created by a class which implements the Runnable interface.");
}
}
| 24.230769 | 103 | 0.774603 |
bdb3c3d7c0b1c105e3036bec705ea1ffca581fe3
| 1,706 |
package com.attask.jenkins;
import java.lang.reflect.Field;
/**
* User: Joel Johnson
* Date: 6/25/12
* Time: 11:56 AM
*/
public class ReflectionUtils {
/**
* Set's the value of the given field via reflection.
* @param instance
* @param fieldName
* @param value
*/
public static void setField(Object instance, String fieldName, Object value) {
try {
Field disabledField = findField(instance, fieldName);
disabledField.set(instance, value);
} catch (IllegalAccessException e) {
throw new RuntimeException(e); //shouldn't happen
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
/**
* Gets the value of the given field via reflection.
* @param type
* @param instance
* @param fieldName
* @param <T>
* @return
*/
public static <T> T getField(Class<T> type, Object instance, String fieldName) {
try {
Field field = findField(instance, fieldName);
return type.cast(field.get(instance));
} catch (IllegalAccessException e) {
throw new RuntimeException(e); //shouldn't happen
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
private static Field findField(Object instance, String fieldName) throws NoSuchFieldException {
Class<?> projectClass = instance.getClass();
Field disabledField = null;
while(!Object.class.equals(projectClass)) {
try {
disabledField = projectClass.getDeclaredField(fieldName);
disabledField.setAccessible(true);
return disabledField;
} catch (NoSuchFieldException ignore) {
//doesn't have the declared field, go on to the next one
}
projectClass = projectClass.getSuperclass();
}
throw new NoSuchFieldException(fieldName);
}
}
| 25.848485 | 96 | 0.7034 |
0f0c8c66e007ebfc087be345832cb2d55f3af2e0
| 597 |
package frc.robot.autons.pathplannerfollower;
public class CalculatedDriveVelocities {
double xVel, yVel, rotVel;
public CalculatedDriveVelocities(double xVel, double yVel, double rotVel){
this.xVel = xVel;
this.yVel = yVel;
this.rotVel = rotVel;
}
public double getXVel() {
return xVel;
}
public double getYVel() {
return yVel;
}
public double getRotVel() {
return rotVel;
}
public String toString(){
return String.format("Velocities[ X:%.2f Y:%.2f Rot:%.2f", xVel, yVel, rotVel);
}
}
| 20.586207 | 87 | 0.60804 |
07598b58eeb28f84a61bb86d71fb2e3dae8fb3f0
| 53,192 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bearsoft.gwt.ui.widgets.grid;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.bearsoft.gwt.ui.XElement;
import com.bearsoft.gwt.ui.dnd.XDataTransfer;
import com.bearsoft.gwt.ui.menu.MenuItemCheckBox;
import com.bearsoft.gwt.ui.widgets.grid.builders.NullHeaderOrFooterBuilder;
import com.bearsoft.gwt.ui.widgets.grid.builders.ThemedCellTableBuilder;
import com.bearsoft.gwt.ui.widgets.grid.builders.ThemedHeaderOrFooterBuilder;
import com.bearsoft.gwt.ui.widgets.grid.header.HasSortList;
import com.bearsoft.gwt.ui.widgets.grid.header.HeaderNode;
import com.eas.client.form.grid.columns.ModelColumn;
import com.eas.client.form.published.PublishedColor;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.StyleElement;
import com.google.gwt.dom.client.TableCellElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.DragEndEvent;
import com.google.gwt.event.dom.client.DragEndHandler;
import com.google.gwt.event.dom.client.DragEnterEvent;
import com.google.gwt.event.dom.client.DragEnterHandler;
import com.google.gwt.event.dom.client.DragEvent;
import com.google.gwt.event.dom.client.DragHandler;
import com.google.gwt.event.dom.client.DragLeaveEvent;
import com.google.gwt.event.dom.client.DragLeaveHandler;
import com.google.gwt.event.dom.client.DragOverEvent;
import com.google.gwt.event.dom.client.DragOverHandler;
import com.google.gwt.event.dom.client.DropEvent;
import com.google.gwt.event.dom.client.DropHandler;
import com.google.gwt.event.dom.client.ScrollEvent;
import com.google.gwt.event.dom.client.ScrollHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.cellview.client.AbstractCellTable;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.ColumnSortList;
import com.google.gwt.user.cellview.client.Header;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.ProvidesResize;
import com.google.gwt.user.client.ui.RequiresResize;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.Range;
import com.google.gwt.view.client.SelectionModel;
/**
*
* @author mg
* @param <T>
*/
public class Grid<T> extends SimplePanel implements ProvidesResize, RequiresResize, HasSortList {
public static final int LEFT_RIGHT_CELL_PADDING = 2;
protected interface DynamicCellStyles extends SafeHtmlTemplates {
public static DynamicCellStyles INSTANCE = GWT.create(DynamicCellStyles.class);
@Template(".{0}{" + "border-style: solid;" + "border-top-width: {1}px;" + "border-bottom-width: {1}px;" + "border-left-width: {2}px;" + "border-right-width: {2}px;" + "border-color: {3};}")
public SafeHtml td(String aCssRuleName, double hBorderWidth, double vBorderWidth, String aLinesColor);
@Template(".{0}{" + "position: relative;" + "padding-left: " + LEFT_RIGHT_CELL_PADDING + "px; padding-right: " + LEFT_RIGHT_CELL_PADDING + "px;" + "height: {1}px;}")
public SafeHtml cell(String aCssRuleName, double aRowsHeight);
}
public static final String RULER_STYLE = "grid-ruler";
public static final String COLUMN_PHANTOM_STYLE = "grid-column-phantom";
public static final String COLUMNS_CHEVRON_STYLE = "grid-columns-chevron";
public static final int MINIMUM_COLUMN_WIDTH = 15;
//
protected FlexTable hive;
protected SimplePanel headerLeftContainer;
protected GridSection<T> headerLeft;
protected SimplePanel headerRightContainer;
protected GridSection<T> headerRight;
protected SimplePanel frozenLeftContainer;
protected GridSection<T> frozenLeft;
protected SimplePanel frozenRightContainer;
protected GridSection<T> frozenRight;
protected SimplePanel scrollableLeftContainer;
protected GridSection<T> scrollableLeft;
protected ScrollPanel scrollableRightContainer;
protected GridSection<T> scrollableRight;
protected SimplePanel footerLeftContainer;
protected GridSection<T> footerLeft;
protected ScrollPanel footerRightContainer;
protected GridSection<T> footerRight;
//
protected HTML columnsChevron = new HTML();
//
protected final ColumnSortList sortList = new ColumnSortList();
protected int rowsHeight;
protected boolean showHorizontalLines = true;
protected boolean showVerticalLines = true;
protected boolean showOddRowsInOtherColor = true;
protected PublishedColor gridColor;
protected PublishedColor oddRowsColor = PublishedColor.create(238, 250, 217, 255);
protected String dynamicTDClassName = "grid-td-" + Document.get().createUniqueId();
protected String dynamicCellClassName = "grid-cell-" + Document.get().createUniqueId();
protected String dynamicOddRowsClassName = "grid-odd-row-" + Document.get().createUniqueId();
protected String dynamicEvenRowsClassName = "grid-even-row-" + Document.get().createUniqueId();
protected StyleElement tdsStyleElement = Document.get().createStyleElement();
protected StyleElement cellsStyleElement = Document.get().createStyleElement();
protected StyleElement oddRowsStyleElement = Document.get().createStyleElement();
protected StyleElement evenRowsStyleElement = Document.get().createStyleElement();
protected ListDataProvider<T> dataProvider;
protected int frozenColumns;
protected int frozenRows;
public Grid(ProvidesKey<T> aKeyProvider) {
super();
getElement().getStyle().setPosition(Style.Position.RELATIVE);
getElement().appendChild(tdsStyleElement);
getElement().appendChild(cellsStyleElement);
getElement().appendChild(oddRowsStyleElement);
getElement().appendChild(evenRowsStyleElement);
setRowsHeight(25);
hive = new FlexTable();
setWidget(hive);
hive.setCellPadding(0);
hive.setCellSpacing(0);
hive.setBorderWidth(0);
headerLeft = new GridSection<T>(aKeyProvider);
headerLeftContainer = new ScrollPanel(headerLeft);
headerRight = new GridSection<T>(aKeyProvider);
headerRightContainer = new ScrollPanel(headerRight);
frozenLeft = new GridSection<T>(aKeyProvider) {
@Override
protected void replaceAllChildren(List<T> values, SafeHtml html) {
super.replaceAllChildren(values, html);
footerLeft.redrawFooters();
}
@Override
protected void replaceChildren(List<T> values, int start, SafeHtml html) {
super.replaceChildren(values, start, html);
footerLeft.redrawFooters();
}
};
frozenLeftContainer = new ScrollPanel(frozenLeft);
frozenRight = new GridSection<T>(aKeyProvider) {
@Override
protected void replaceAllChildren(List<T> values, SafeHtml html) {
super.replaceAllChildren(values, html);
footerRight.redrawFooters();
}
@Override
protected void replaceChildren(List<T> values, int start, SafeHtml html) {
super.replaceChildren(values, start, html);
footerRight.redrawFooters();
}
};
frozenRightContainer = new ScrollPanel(frozenRight);
scrollableLeft = new GridSection<T>(aKeyProvider) {
@Override
protected void replaceAllChildren(List<T> values, SafeHtml html) {
super.replaceAllChildren(values, html);
footerLeft.redrawFooters();
}
@Override
protected void replaceChildren(List<T> values, int start, SafeHtml html) {
super.replaceChildren(values, start, html);
footerLeft.redrawFooters();
}
};
scrollableLeftContainer = new ScrollPanel(scrollableLeft);
scrollableRight = new GridSection<T>(aKeyProvider) {
@Override
protected void replaceAllChildren(List<T> values, SafeHtml html) {
super.replaceAllChildren(values, html);
footerRight.redrawFooters();
}
@Override
protected void replaceChildren(List<T> values, int start, SafeHtml html) {
super.replaceChildren(values, start, html);
footerRight.redrawFooters();
}
};
scrollableRightContainer = new ScrollPanel(scrollableRight);
footerLeft = new GridSection<>(aKeyProvider);
footerLeftContainer = new ScrollPanel(footerLeft);
footerRight = new GridSection<>(aKeyProvider);
footerRightContainer = new ScrollPanel(footerRight);
// positioning context / overflow setup
// overflow
for (Widget w : new Widget[] { headerLeftContainer, headerRightContainer, frozenLeftContainer, frozenRightContainer, scrollableLeftContainer, footerLeftContainer, footerRightContainer }) {
w.getElement().getStyle().setOverflow(Style.Overflow.HIDDEN);
}
// scrollableRightContainer.getElement().getStyle().setOverflow(Style.Overflow.AUTO);
// default value
// context
for (Widget w : new Widget[] { headerLeftContainer, headerRightContainer, frozenLeftContainer, frozenRightContainer, scrollableLeftContainer, scrollableRightContainer, footerLeftContainer,
footerRightContainer }) {
w.getElement().getFirstChildElement().getStyle().setPosition(Style.Position.ABSOLUTE);
}
// propagation of some widths
headerLeft.setWidthPropagator(new GridWidthPropagator<T>(headerLeft) {
@Override
public void changed() {
super.changed();
propagateHeaderWidth();
}
});
for (GridSection<T> section : (GridSection<T>[]) new GridSection<?>[] { headerRight, frozenLeft, frozenRight, scrollableLeft, scrollableRight, footerLeft, footerRight }) {
section.setWidthPropagator(new GridWidthPropagator<>(section));
}
headerLeft.setColumnsPartners(new AbstractCellTable[] { frozenLeft, scrollableLeft, footerLeft });
headerRight.setColumnsPartners(new AbstractCellTable[] { frozenRight, scrollableRight, footerRight });
ColumnsRemover leftColumnsRemover = new ColumnsRemoverAdapter<T>(headerLeft, frozenLeft, scrollableLeft, footerLeft);
ColumnsRemover rightColumnsRemover = new ColumnsRemoverAdapter<T>(headerRight, frozenRight, scrollableRight, footerRight);
for (GridSection<T> section : (GridSection<T>[]) new GridSection<?>[] { headerLeft, frozenLeft, scrollableLeft, footerLeft }) {
section.setColumnsRemover(leftColumnsRemover);
}
for (GridSection<T> section : (GridSection<T>[]) new GridSection<?>[] { headerRight, frozenRight, scrollableRight, footerRight }) {
section.setColumnsRemover(rightColumnsRemover);
}
for (GridSection<T> section : (GridSection<T>[]) new GridSection<?>[] { frozenLeft, scrollableLeft, footerLeft }) {
section.setHeaderSource(headerLeft);
}
for (GridSection<T> section : (GridSection<T>[]) new GridSection<?>[] { frozenRight, scrollableRight, footerRight }) {
section.setHeaderSource(headerRight);
}
for (GridSection<T> section : (GridSection<T>[]) new GridSection<?>[] { headerLeft, frozenLeft, scrollableLeft }) {
section.setFooterSource(footerLeft);
}
for (GridSection<T> section : (GridSection<T>[]) new GridSection<?>[] { headerRight, frozenRight, scrollableRight }) {
section.setFooterSource(footerRight);
}
// hive organization
hive.setWidget(0, 0, headerLeftContainer);
hive.setWidget(0, 1, headerRightContainer);
hive.setWidget(1, 0, frozenLeftContainer);
hive.setWidget(1, 1, frozenRightContainer);
hive.setWidget(2, 0, scrollableLeftContainer);
hive.setWidget(2, 1, scrollableRightContainer);
hive.setWidget(3, 0, footerLeftContainer);
hive.setWidget(3, 1, footerRightContainer);
for (Widget w : new Widget[] { headerLeftContainer, headerRightContainer, frozenLeftContainer, frozenRightContainer, scrollableLeftContainer, scrollableRightContainer, footerLeftContainer,
footerRightContainer }) {
w.setWidth("100%");
w.setHeight("100%");
}
// misc
for (Widget w : new Widget[] { headerRightContainer, frozenRightContainer, footerRightContainer, scrollableLeftContainer }) {
w.getElement().getParentElement().getStyle().setOverflow(Style.Overflow.HIDDEN);
}
hive.getElement().getStyle().setTableLayout(Style.TableLayout.FIXED);
hive.getElement().getStyle().setPosition(Style.Position.RELATIVE);
for (CellTable<?> tbl : new CellTable<?>[] { headerLeft, headerRight, frozenLeft, frozenRight, scrollableLeft, scrollableRight, footerLeft, footerRight }) {
tbl.setTableLayoutFixed(true);
}
// header
headerLeft.setHeaderBuilder(new ThemedHeaderOrFooterBuilder<T>(headerLeft, false, this));
headerLeft.setFooterBuilder(new NullHeaderOrFooterBuilder<T>(headerLeft, true));
headerRight.setHeaderBuilder(new ThemedHeaderOrFooterBuilder<T>(headerRight, false, this));
headerRight.setFooterBuilder(new NullHeaderOrFooterBuilder<T>(headerRight, true));
// footer
footerLeft.setHeaderBuilder(new NullHeaderOrFooterBuilder<T>(footerLeft, false));
footerLeft.setFooterBuilder(new ThemedHeaderOrFooterBuilder<T>(footerLeft, true));
footerRight.setHeaderBuilder(new NullHeaderOrFooterBuilder<T>(footerRight, false));
footerRight.setFooterBuilder(new ThemedHeaderOrFooterBuilder<T>(footerRight, true));
// data bodies
for (GridSection<?> section : new GridSection<?>[] { frozenLeft, frozenRight, scrollableLeft, scrollableRight }) {
GridSection<T> gSection = (GridSection<T>) section;
gSection.setHeaderBuilder(new NullHeaderOrFooterBuilder<T>(gSection, false));
gSection.setFooterBuilder(new NullHeaderOrFooterBuilder<T>(gSection, true));
}
for (GridSection<?> section : new GridSection<?>[] { headerLeft, headerRight, frozenLeft, frozenRight, scrollableLeft, scrollableRight, footerLeft, footerRight }) {
section.setAutoHeaderRefreshDisabled(true);
}
for (GridSection<?> section : new GridSection<?>[] { headerLeft, headerRight, footerLeft, footerRight }) {
section.setAutoFooterRefreshDisabled(true);
}
// cells
installCellBuilders();
scrollableRightContainer.addScrollHandler(new ScrollHandler() {
@Override
public void onScroll(ScrollEvent event) {
int aimLeft = scrollableRightContainer.getElement().getScrollLeft();
if (isHeaderVisible()) {
headerRightContainer.getElement().setScrollLeft(aimLeft);
int factLeftDelta0 = aimLeft - headerRightContainer.getElement().getScrollLeft();
if (factLeftDelta0 > 0) {
headerRightContainer.getElement().getStyle().setRight(factLeftDelta0, Style.Unit.PX);
} else {
headerRightContainer.getElement().getStyle().clearRight();
}
}
if (frozenColumns > 0 || frozenRows > 0) {
int aimTop = scrollableRightContainer.getElement().getScrollTop();
scrollableLeftContainer.getElement().setScrollTop(aimTop);
int factTopDelta = aimTop - scrollableLeftContainer.getElement().getScrollTop();
if (factTopDelta > 0) {
scrollableLeftContainer.getElement().getStyle().setBottom(factTopDelta, Style.Unit.PX);
} else {
scrollableLeftContainer.getElement().getStyle().clearBottom();
}
frozenRightContainer.getElement().setScrollLeft(aimLeft);
int factLeftDelta1 = aimLeft - frozenRightContainer.getElement().getScrollLeft();
if (factLeftDelta1 > 0) {
frozenRightContainer.getElement().getStyle().setRight(factLeftDelta1, Style.Unit.PX);
} else {
frozenRightContainer.getElement().getStyle().clearRight();
}
footerRightContainer.getElement().setScrollLeft(scrollableRightContainer.getElement().getScrollLeft());
int factLeftDelta2 = aimLeft - footerRightContainer.getElement().getScrollLeft();
if (factLeftDelta2 > 0) {
footerRightContainer.getElement().getStyle().setRight(factLeftDelta2, Style.Unit.PX);
} else {
footerRightContainer.getElement().getStyle().clearRight();
}
}
}
});
ghostLine = Document.get().createDivElement();
ghostLine.addClassName(RULER_STYLE);
ghostLine.getStyle().setPosition(Style.Position.ABSOLUTE);
ghostLine.getStyle().setTop(0, Style.Unit.PX);
ghostColumn = Document.get().createDivElement();
ghostColumn.addClassName(COLUMN_PHANTOM_STYLE);
ghostColumn.getStyle().setPosition(Style.Position.ABSOLUTE);
ghostColumn.getStyle().setTop(0, Style.Unit.PX);
addDomHandler(new DragEnterHandler() {
@Override
public void onDragEnter(DragEnterEvent event) {
if (DraggedColumn.instance != null) {
if (DraggedColumn.instance.isMove()) {
event.preventDefault();
event.stopPropagation();
DraggedColumn<T> target = findTargetDraggedColumn(event.getNativeEvent().getEventTarget());
if (target != null) {
showColumnMoveDecorations(target);
event.getDataTransfer().<XDataTransfer> cast().setDropEffect("move");
} else {
event.getDataTransfer().<XDataTransfer> cast().setDropEffect("none");
}
} else {
}
}
}
}, DragEnterEvent.getType());
addDomHandler(new DragHandler() {
@Override
public void onDrag(DragEvent event) {
if (DraggedColumn.instance != null && DraggedColumn.instance.isResize()) {
event.stopPropagation();
}
}
}, DragEvent.getType());
addDomHandler(new DragOverHandler() {
@Override
public void onDragOver(DragOverEvent event) {
if (DraggedColumn.instance != null) {
event.preventDefault();
event.stopPropagation();
if (DraggedColumn.instance.isMove()) {
DraggedColumn<T> target = findTargetDraggedColumn(event.getNativeEvent().getEventTarget());
if (target != null) {
event.getDataTransfer().<XDataTransfer> cast().setDropEffect("move");
} else {
hideColumnDecorations();
event.getDataTransfer().<XDataTransfer> cast().setDropEffect("none");
}
} else {
Element hostElement = Grid.this.getElement();
int clientX = event.getNativeEvent().getClientX();
int hostAbsX = hostElement.getAbsoluteLeft();
int hostScrollX = hostElement.getScrollLeft();
int docScrollX = hostElement.getOwnerDocument().getScrollLeft();
int relativeX = clientX - hostAbsX + hostScrollX + docScrollX;
ghostLine.getStyle().setLeft(relativeX, Style.Unit.PX);
ghostLine.getStyle().setHeight(hostElement.getClientHeight(), Style.Unit.PX);
if (ghostLine.getParentElement() != hostElement) {
hostElement.appendChild(ghostLine);
}
}
}
}
}, DragOverEvent.getType());
addDomHandler(new DragLeaveHandler() {
@Override
public void onDragLeave(DragLeaveEvent event) {
if (DraggedColumn.instance != null) {
event.stopPropagation();
if (DraggedColumn.instance.isMove()) {
if (event.getNativeEvent().getEventTarget() == (JavaScriptObject) Grid.this.getElement()) {
hideColumnDecorations();
}
}
}
}
}, DragLeaveEvent.getType());
addDomHandler(new DragEndHandler() {
@Override
public void onDragEnd(DragEndEvent event) {
if (DraggedColumn.instance != null) {
event.stopPropagation();
hideColumnDecorations();
DraggedColumn.instance = null;
}
}
}, DragEndEvent.getType());
addDomHandler(new DropHandler() {
@Override
public void onDrop(DropEvent event) {
DraggedColumn<?> source = DraggedColumn.instance;
DraggedColumn<T> target = targetDraggedColumn;
hideColumnDecorations();
DraggedColumn.instance = null;
if (source != null) {
event.preventDefault();
event.stopPropagation();
if (source.isMove()) {
AbstractCellTable<T> sourceSection = (AbstractCellTable<T>) source.getTable();
// target table may be any section in our grid
if (target != null) {
Header<?> sourceHeader = source.getHeader();
Header<?> targetHeader = target.getHeader();
if (sourceHeader instanceof DraggableHeader<?> && targetHeader instanceof DraggableHeader<?>) {
DraggableHeader<T> sourceDH = (DraggableHeader<T>) sourceHeader;
DraggableHeader<T> targetDH = (DraggableHeader<T>) targetHeader;
moveColumnNode(sourceDH.getHeaderNode(), targetDH.getHeaderNode());
} else {
int sourceIndex = source.getColumnIndex();
int targetIndex = target.getColumnIndex();
GridSection<T> targetSection = (GridSection<T>) target.getTable();
boolean isSourceLeft = sourceSection == headerLeft || sourceSection == frozenLeft || sourceSection == scrollableLeft || sourceSection == footerLeft;
boolean isTargetLeft = targetSection == headerLeft || targetSection == frozenLeft || targetSection == scrollableLeft || targetSection == footerLeft;
sourceSection = isSourceLeft ? headerLeft : headerRight;
targetSection = isTargetLeft ? headerLeft : headerRight;
int generalSourceIndex = isSourceLeft ? sourceIndex : sourceIndex + frozenColumns;
int generalTargetIndex = isTargetLeft ? targetIndex : targetIndex + frozenColumns;
Header<?> header = sourceSection.getHeader(sourceIndex);
if (header instanceof DraggableHeader) {
((DraggableHeader) header).setTable(targetSection);
}
if (generalSourceIndex != generalTargetIndex) {
Column<T, ?> column = (Column<T, ?>) source.getColumn();
if (!(header instanceof DraggableHeader) || ((DraggableHeader) header).isMoveable()) {
moveColumn(generalSourceIndex, generalTargetIndex);
}
}
}
}
} else {
Header<?> header = source.getHeader();
if (!(header instanceof DraggableHeader) || ((DraggableHeader) header).isResizable()) {
int newWidth = Math.max(event.getNativeEvent().getClientX() - source.getCellElement().getAbsoluteLeft(), MINIMUM_COLUMN_WIDTH);
// Source and target tables are the same, so we can
// cast to DraggedColumn<T> with no care
setColumnWidthFromHeaderDrag(((DraggedColumn<T>) source).getColumn(), newWidth, Style.Unit.PX);
}
}
}
}
}, DropEvent.getType());
columnsChevron.getElement().getStyle().setPosition(Style.Position.ABSOLUTE);
columnsChevron.getElement().addClassName(COLUMNS_CHEVRON_STYLE);
getElement().appendChild(columnsChevron.getElement());
columnsChevron.addDomHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
PopupPanel pp = new PopupPanel();
pp.setAutoHideEnabled(true);
pp.setAutoHideOnHistoryEventsEnabled(true);
pp.setAnimationEnabled(true);
MenuBar columnsMenu = new MenuBar(true);
fillColumns(columnsMenu, headerLeft);
fillColumns(columnsMenu, headerRight);
pp.setWidget(columnsMenu);
pp.setPopupPosition(columnsChevron.getAbsoluteLeft(), columnsChevron.getAbsoluteTop());
pp.showRelativeTo(columnsChevron);
}
private void fillColumns(MenuBar aTarget, final GridSection<T> aSection) {
for (int i = 0; i < aSection.getColumnCount(); i++) {
Header<?> h = aSection.getHeader(i);
final Column<T, ?> column = aSection.getColumn(i);
SafeHtml rendered;
if (h.getValue() instanceof String) {
String hVal = (String) h.getValue();
rendered = hVal.startsWith("<html>") ? SafeHtmlUtils.fromTrustedString(hVal.substring(6)) : SafeHtmlUtils.fromString(hVal);
} else {
Cell.Context context = new Cell.Context(0, i, h.getKey());
SafeHtmlBuilder sb = new SafeHtmlBuilder();
h.render(context, sb);
rendered = sb.toSafeHtml();
}
MenuItemCheckBox miCheck = new MenuItemCheckBox(!aSection.isColumnHidden(column), rendered.asString(), true);
miCheck.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
if (Boolean.TRUE.equals(event.getValue())) {
showColumn(column);
} else {
hideColumn(column);
}
Grid.this.onResize();
}
});
aTarget.addItem(miCheck);
}
}
}, ClickEvent.getType());
ColumnSortEvent.Handler sectionSortHandler = new ColumnSortEvent.Handler() {
@Override
public void onColumnSort(ColumnSortEvent event) {
boolean isCtrlKey = ((GridSection<?>) event.getSource()).isCtrlKey();
boolean contains = false;
int containsAt = -1;
for (int i = 0; i < sortList.size(); i++) {
if (sortList.get(i).getColumn() == event.getColumn()) {
contains = true;
containsAt = i;
break;
}
}
if (!contains) {
if (!isCtrlKey) {
sortList.clear();
}
sortList.insert(sortList.size(), new ColumnSortList.ColumnSortInfo(event.getColumn(), true));
} else {
boolean wasAscending = sortList.get(containsAt).isAscending();
if (!isCtrlKey) {
sortList.clear();
if (wasAscending) {
sortList.push(new ColumnSortList.ColumnSortInfo(event.getColumn(), false));
}
} else {
sortList.remove(sortList.get(containsAt));
if (wasAscending) {
sortList.insert(containsAt, new ColumnSortList.ColumnSortInfo(event.getColumn(), false));
}
}
}
ColumnSortEvent.fire(Grid.this, sortList);
}
};
headerLeft.getColumnSortList().setLimit(1);
headerLeft.addColumnSortHandler(sectionSortHandler);
headerRight.getColumnSortList().setLimit(1);
headerRight.addColumnSortHandler(sectionSortHandler);
gridColor = PublishedColor.create(211, 211, 211, 255);
regenerateDynamicTDStyles();
regenerateDynamicOddRowsStyles();
getElement().<XElement> cast().addResizingTransitionEnd(this);
}
protected void installCellBuilders() {
for (GridSection<?> section : new GridSection<?>[] { frozenLeft, frozenRight, scrollableLeft, scrollableRight }) {
GridSection<T> gSection = (GridSection<T>) section;
gSection.setTableBuilder(new ThemedCellTableBuilder<>(gSection, dynamicTDClassName, dynamicCellClassName, dynamicOddRowsClassName, dynamicEvenRowsClassName));
}
}
@Override
public ColumnSortList getSortList() {
return sortList;
}
/**
* Add a handler to handle {@link ColumnSortEvent}s.
*
* @param handler
* the {@link ColumnSortEvent.Handler} to add
* @return a {@link HandlerRegistration} to remove the handler
*/
public HandlerRegistration addColumnSortHandler(ColumnSortEvent.Handler handler) {
return addHandler(handler, ColumnSortEvent.getType());
}
public ListDataProvider<T> getDataProvider() {
return dataProvider;
}
protected DraggedColumn<T> findTargetDraggedColumn(JavaScriptObject aEventTarget) {
if (Element.is(aEventTarget)) {
GridSection<T> targetSection = null;
Element targetCell = null;
Element currentTarget = Element.as(aEventTarget);
if (COLUMN_PHANTOM_STYLE.equals(currentTarget.getClassName()) || RULER_STYLE.equals(currentTarget.getClassName())) {
return targetDraggedColumn;
}
while ((targetCell == null || targetSection == null) && currentTarget != null && currentTarget != Grid.this.getElement()) {
if (targetCell == null) {
if ("td".equalsIgnoreCase(currentTarget.getTagName()) || "th".equalsIgnoreCase(currentTarget.getTagName())) {
targetCell = currentTarget;
}
}
if (targetSection == null) {
if (currentTarget == headerLeft.getElement()) {
targetSection = headerLeft;
} else if (currentTarget == frozenLeft.getElement()) {
targetSection = frozenLeft;
} else if (currentTarget == scrollableLeft.getElement()) {
targetSection = scrollableLeft;
} else if (currentTarget == footerLeft.getElement()) {
targetSection = footerLeft;
} else if (currentTarget == headerRight.getElement()) {
targetSection = headerRight;
} else if (currentTarget == frozenRight.getElement()) {
targetSection = frozenRight;
} else if (currentTarget == scrollableRight.getElement()) {
targetSection = scrollableRight;
} else if (currentTarget == footerRight.getElement()) {
targetSection = footerRight;
}
}
currentTarget = currentTarget.getParentElement();
}
if (targetSection != null && targetCell != null) {
Column<T, ?> col = targetSection.getHeaderBuilder().getColumn(targetCell);
Header<?> header = targetSection.getHeaderBuilder().getHeader(targetCell);
if (col != null && header != null)
return new DraggedColumn<T>(col, header, targetSection, targetCell, Element.as(aEventTarget));
else
return null;
}
return null;
} else {
return null;
}
}
protected Element ghostLine;
protected Element ghostColumn;
protected DraggedColumn<T> targetDraggedColumn;
protected void hideColumnDecorations() {
ghostLine.removeFromParent();
ghostColumn.removeFromParent();
targetDraggedColumn = null;
}
protected void showColumnMoveDecorations(DraggedColumn<T> target) {
targetDraggedColumn = target;
Element hostElement = getElement();
Element thtdElement = target.getCellElement();
int thLeft = thtdElement.getAbsoluteLeft();
thLeft = thLeft - getAbsoluteLeft() + hostElement.getScrollLeft();
ghostLine.getStyle().setLeft(thLeft, Style.Unit.PX);
ghostLine.getStyle().setHeight(hostElement.getClientHeight(), Style.Unit.PX);
ghostColumn.getStyle().setLeft(thLeft, Style.Unit.PX);
ghostColumn.getStyle().setWidth(thtdElement.getOffsetWidth(), Style.Unit.PX);
ghostColumn.getStyle().setHeight(hostElement.getClientHeight(), Style.Unit.PX);
if (ghostLine.getParentElement() != hostElement) {
ghostLine.removeFromParent();
hostElement.appendChild(ghostLine);
}
if (ghostColumn.getParentElement() != hostElement) {
ghostColumn.removeFromParent();
hostElement.appendChild(ghostColumn);
}
}
public String getDynamicCellClassName() {
return dynamicTDClassName;
}
public boolean isShowHorizontalLines() {
return showHorizontalLines;
}
public void setShowHorizontalLines(boolean aValue) {
if (showHorizontalLines != aValue) {
showHorizontalLines = aValue;
regenerateDynamicTDStyles();
}
}
public boolean isShowVerticalLines() {
return showVerticalLines;
}
public void setShowVerticalLines(boolean aValue) {
if (showVerticalLines != aValue) {
showVerticalLines = aValue;
regenerateDynamicTDStyles();
}
}
protected void regenerateDynamicTDStyles() {
tdsStyleElement.setInnerSafeHtml(DynamicCellStyles.INSTANCE.td(dynamicTDClassName, showHorizontalLines ? 1 : 0, showVerticalLines ? 1 : 0, gridColor != null ? gridColor.toStyled() : ""));
}
protected void regenerateDynamicOddRowsStyles() {
if (showOddRowsInOtherColor && oddRowsColor != null) {
oddRowsStyleElement.setInnerHTML("." + dynamicOddRowsClassName + "{background-color: " + oddRowsColor.toStyled() + "}");
} else {
oddRowsStyleElement.setInnerHTML("");
}
}
public PublishedColor getGridColor() {
return gridColor;
}
public void setGridColor(PublishedColor aValue) {
gridColor = aValue;
regenerateDynamicTDStyles();
}
public PublishedColor getOddRowsColor() {
return oddRowsColor;
}
public void setOddRowsColor(PublishedColor aValue) {
oddRowsColor = aValue;
regenerateDynamicOddRowsStyles();
}
public int getRowsHeight() {
return rowsHeight;
}
public void setRowsHeight(int aValue) {
if (rowsHeight != aValue && aValue >= 10) {
rowsHeight = aValue;
cellsStyleElement.setInnerSafeHtml(DynamicCellStyles.INSTANCE.cell(dynamicCellClassName, rowsHeight));
onResize();
}
}
private void propagateHeaderWidth() {
double lw = headerLeft.getElement().getOffsetWidth();
headerLeftContainer.getElement().getParentElement().getStyle().setWidth(lw, Style.Unit.PX);
frozenLeftContainer.getElement().getParentElement().getStyle().setWidth(lw, Style.Unit.PX);
scrollableLeftContainer.getElement().getParentElement().getStyle().setWidth(lw, Style.Unit.PX);
footerLeftContainer.getElement().getParentElement().getStyle().setWidth(lw, Style.Unit.PX);
double rw = getElement().getClientWidth() - lw;
headerRightContainer.getElement().getParentElement().getStyle().setWidth(rw, Style.Unit.PX);
frozenRightContainer.getElement().getParentElement().getStyle().setWidth(rw, Style.Unit.PX);
scrollableRightContainer.getElement().getParentElement().getStyle().setWidth(rw, Style.Unit.PX);
footerRightContainer.getElement().getParentElement().getStyle().setWidth(rw, Style.Unit.PX);
}
protected void propagateHeightButScrollable() {
int r0Height = Math.max(headerLeft.getOffsetHeight(), headerRight.getOffsetHeight());
headerLeftContainer.getElement().getParentElement().getStyle().setHeight(r0Height, Style.Unit.PX);
headerRightContainer.getElement().getParentElement().getStyle().setHeight(r0Height, Style.Unit.PX);
int r1Height = Math.max(frozenLeft.getOffsetHeight(), frozenRight.getOffsetHeight());
frozenLeftContainer.getElement().getParentElement().getStyle().setHeight(r1Height, Style.Unit.PX);
frozenRightContainer.getElement().getParentElement().getStyle().setHeight(r1Height, Style.Unit.PX);
int r3Height = Math.max(footerLeft.getOffsetHeight(), footerRight.getOffsetHeight());
footerLeftContainer.getElement().getParentElement().getStyle().setHeight(r3Height, Style.Unit.PX);
footerRightContainer.getElement().getParentElement().getStyle().setHeight(r3Height, Style.Unit.PX);
// special care about scrollable
// row height is free, but cells' height is setted by hand in order to
// support gecko browsers
// scrollableLeftContainer.getElement().getParentElement().getStyle().setHeight(100,
// Style.Unit.PCT);
// scrollableRightContainer.getElement().getParentElement().getStyle().setHeight(100,
// Style.Unit.PCT);
// some code for opera...
scrollableLeftContainer.getElement().getStyle().clearHeight();
scrollableRightContainer.getElement().getStyle().clearHeight();
// it seems that after clearing the height, hive offsetHeight is changed
// ...
scrollableLeftContainer.getElement().getStyle().setHeight(hive.getElement().getOffsetHeight() - r0Height - r1Height - r3Height, Style.Unit.PX);
scrollableRightContainer.getElement().getStyle().setHeight(hive.getElement().getOffsetHeight() - r0Height - r1Height - r3Height, Style.Unit.PX);
}
@Override
protected void onAttach() {
super.onAttach();
adopt(columnsChevron);
}
@Override
protected void onDetach() {
orphan(columnsChevron);
super.onDetach();
}
protected void onColumnsResize() {
// no op here because of natural columns width's
}
@Override
public void onResize() {
if (isAttached()) {
hive.setSize(getElement().getClientWidth() + "px", getElement().getClientHeight() + "px");
propagateHeaderWidth();
onColumnsResize();
propagateHeightButScrollable();
columnsChevron.setHeight(Math.max(headerLeftContainer.getOffsetHeight(), headerRightContainer.getOffsetHeight()) + "px");
for (Widget child : new Widget[] { headerLeftContainer, headerRightContainer, frozenLeftContainer, frozenRightContainer, scrollableLeftContainer, scrollableRightContainer }) {
if (child instanceof RequiresResize) {
((RequiresResize) child).onResize();
}
}
}
}
public boolean isHeaderVisible() {
return !Style.Display.NONE.equals(headerLeft.getElement().getStyle().getDisplay()) && !Style.Display.NONE.equals(headerRight.getElement().getStyle().getDisplay());
}
public void setHeaderVisible(boolean aValue) {
hive.getRowFormatter().setVisible(0, aValue);
if (aValue) {
columnsChevron.getElement().getStyle().clearDisplay();
headerLeftContainer.getElement().getStyle().clearDisplay();
headerRightContainer.getElement().getStyle().clearDisplay();
} else {
columnsChevron.getElement().getStyle().setDisplay(Style.Display.NONE);
headerLeftContainer.getElement().getStyle().setDisplay(Style.Display.NONE);
headerRightContainer.getElement().getStyle().setDisplay(Style.Display.NONE);
}
if (isAttached())
onResize();
}
public int getFrozenColumns() {
return frozenColumns;
}
public void setFrozenColumns(int aValue) {
if (aValue >= 0 && frozenColumns != aValue) {
if (aValue >= 0) {
frozenColumns = aValue;
if (getDataColumnCount() > 0 && aValue <= getDataColumnCount()) {
refreshColumns();
}
}
}
}
public int getFrozenRows() {
return frozenRows;
}
public void setFrozenRows(int aValue) {
if (aValue >= 0 && frozenRows != aValue) {
frozenRows = aValue;
if (dataProvider != null && aValue <= dataProvider.getList().size()) {
setupVisibleRanges();
}
}
}
public boolean isShowOddRowsInOtherColor() {
return showOddRowsInOtherColor;
}
public void setShowOddRowsInOtherColor(boolean aValue) {
if (showOddRowsInOtherColor != aValue) {
showOddRowsInOtherColor = aValue;
regenerateDynamicOddRowsStyles();
}
}
/**
* TODO: Check if working with sectioned grid.
*
* @param sModel
*/
public void setSelectionModel(SelectionModel<T> sModel) {
headerLeft.setSelectionModel(sModel);
headerRight.setSelectionModel(sModel);
frozenLeft.setSelectionModel(sModel);
frozenRight.setSelectionModel(sModel);
scrollableLeft.setSelectionModel(sModel);
scrollableRight.setSelectionModel(sModel);
}
public SelectionModel<? super T> getSelectionModel() {
return scrollableRight.getSelectionModel();
}
/**
* @param aDataProvider
*/
public void setDataProvider(ListDataProvider<T> aDataProvider) {
if (dataProvider != null) {
dataProvider.removeDataDisplay(headerLeft);
dataProvider.removeDataDisplay(headerRight);
dataProvider.removeDataDisplay(frozenLeft);
dataProvider.removeDataDisplay(frozenRight);
dataProvider.removeDataDisplay(scrollableLeft);
dataProvider.removeDataDisplay(scrollableRight);
dataProvider.removeDataDisplay(footerLeft);
dataProvider.removeDataDisplay(footerRight);
}
dataProvider = aDataProvider;
if (dataProvider != null) {
dataProvider.addDataDisplay(headerLeft);
dataProvider.addDataDisplay(headerRight);
dataProvider.addDataDisplay(frozenLeft);
dataProvider.addDataDisplay(frozenRight);
dataProvider.addDataDisplay(scrollableLeft);
dataProvider.addDataDisplay(scrollableRight);
dataProvider.addDataDisplay(footerLeft);
dataProvider.addDataDisplay(footerRight);
}
setupVisibleRanges();
}
public void setupVisibleRanges() {
List<T> list = dataProvider != null ? dataProvider.getList() : null;
int generalLength = list != null ? list.size() : 0;
int lfrozenRows = generalLength >= frozenRows ? frozenRows : generalLength;
int scrollableRowCount = generalLength - lfrozenRows;
//
headerLeft.setVisibleRange(new Range(0, 0));
headerRight.setVisibleRange(new Range(0, 0));
frozenLeft.setVisibleRange(new Range(0, lfrozenRows));
frozenRight.setVisibleRange(new Range(0, lfrozenRows));
scrollableLeft.setVisibleRange(new Range(lfrozenRows, scrollableRowCount >= 0 ? scrollableRowCount : 0));
scrollableRight.setVisibleRange(new Range(lfrozenRows, scrollableRowCount >= 0 ? scrollableRowCount : 0));
footerLeft.setVisibleRange(new Range(0, 0));
footerRight.setVisibleRange(new Range(0, 0));
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
onResize();
}
});
}
public void addColumn(Column<T, ?> aColumn, String aWidth, Header<?> aHeader, Header<?> aFooter, boolean hidden) {
addColumn(false, getDataColumnCount(), aColumn, aWidth, aHeader, aFooter, hidden);
}
public void addColumn(int aIndex, Column<T, ?> aColumn, String aWidth, Header<?> aHeader, Header<?> aFooter, boolean hidden) {
addColumn(true, aIndex, aColumn, aWidth, aHeader, aFooter, hidden);
}
public void addColumn(boolean forceRefreshColumns, int aIndex, Column<T, ?> aColumn, String aWidth, Header<?> aHeader, Header<?> aFooter, boolean hidden) {
/*
* if (aHeader instanceof DraggableHeader<?>) { DraggableHeader<T> h =
* (DraggableHeader<T>) aHeader; h.setColumn(aColumn); } WARNING! Before
* uncomment, answer the question: DraggableHeader can change its
* column?
*/
if (aIndex < frozenColumns) {
if (aHeader instanceof DraggableHeader<?>) {
DraggableHeader<T> h = (DraggableHeader<T>) aHeader;
h.setTable(headerLeft);
}
headerLeft.insertColumn(aIndex, aColumn, aHeader);
frozenLeft.insertColumn(aIndex, aColumn);
scrollableLeft.insertColumn(aIndex, aColumn);
footerLeft.insertColumn(aIndex, aColumn, null, aFooter);
headerLeft.setColumnWidth(aColumn, aWidth);// column partners will
// take care of width
// seetings in other
// sections
//
if (forceRefreshColumns)
refreshColumns();
} else {
if (aHeader instanceof DraggableHeader<?>) {
DraggableHeader<T> h = (DraggableHeader<T>) aHeader;
h.setTable(headerRight);
}
headerRight.insertColumn(aIndex - frozenColumns, aColumn, aHeader);
frozenRight.insertColumn(aIndex - frozenColumns, aColumn);
scrollableRight.insertColumn(aIndex - frozenColumns, aColumn);
footerRight.insertColumn(aIndex - frozenColumns, aColumn, null, aFooter);
headerRight.setColumnWidth(aColumn, aWidth);// column partners will
// take care of width
// seetings in other
// sections
//
}
if (hidden) {
hideColumn(aColumn);
}
}
public void moveColumn(int aFromIndex, int aToIndex) {
Header<?> footer = getColumnFooter(aFromIndex);
Header<?> header = getColumnHeader(aFromIndex);
String width = getColumnWidth(aFromIndex);
Column<T, ?> column = getColumn(aFromIndex);
clearColumnWidth(aFromIndex);
removeColumn(aFromIndex);
addColumn(aToIndex, column, width, header, footer, false);
headerLeft.getWidthPropagator().changed();
}
public void moveColumnNode(HeaderNode<T> aSubject, HeaderNode<T> aInsertBefore) {
}
public void hideColumn(Column<T, ?> aColumn) {
for (GridSection<?> section : new GridSection<?>[] { headerLeft, frozenLeft, scrollableLeft, footerLeft, headerRight, frozenRight, scrollableRight, footerRight }) {
GridSection<T> gSection = (GridSection<T>) section;
gSection.hideColumn(aColumn);
}
}
public void showColumn(Column<T, ?> aColumn) {
for (GridSection<?> section : new GridSection<?>[] { headerLeft, frozenLeft, scrollableLeft, footerLeft, headerRight, frozenRight, scrollableRight, footerRight }) {
GridSection<T> gSection = (GridSection<T>) section;
gSection.showColumn(aColumn);
}
}
/*
* public void insertColumn(int aIndex, Column<T, ?> aColumn, String
* aHeaderValue, Header<?> aFooter) { if (aIndex < frozenColumns) {
* headerLeft.insertColumn(aIndex, aColumn, new
* DraggableHeader<T>(aHeaderValue, headerLeft, aColumn, getElement()));
* frozenLeft.insertColumn(aIndex, aColumn);
* scrollableLeft.insertColumn(aIndex, aColumn);
* footerLeft.insertColumn(aIndex, aColumn, null, aFooter);
* refreshColumns(); } else { headerRight.insertColumn(aIndex, aColumn, new
* DraggableHeader<T>(aHeaderValue, headerRight, aColumn, getElement()));
* frozenRight.insertColumn(aIndex, aColumn);
* scrollableRight.insertColumn(aIndex, aColumn);
* footerRight.insertColumn(aIndex, aColumn, null, aFooter); } }
*/
public void removeColumn(int aIndex) {
if (aIndex < frozenColumns) {
headerLeft.removeColumn(aIndex);// ColumnsRemover will care
// about columns sharing
refreshColumns();
} else {
headerRight.removeColumn(aIndex - frozenColumns);// ColumnsRemover
// will care
// about columns sharing
}
}
protected void refreshColumns() {
List<Column<T, ?>> cols = new ArrayList<>();
List<Header<?>> headers = new ArrayList<>();
List<Header<?>> footers = new ArrayList<>();
List<String> widths = new ArrayList<>();
List<Boolean> hidden = new ArrayList<>();
for (int i = headerRight.getColumnCount() - 1; i >= 0; i--) {
Column<T, ?> col = headerRight.getColumn(i);
cols.add(0, col);
widths.add(0, headerRight.getColumnWidth(col, true));
headers.add(0, headerRight.getHeader(i));
footers.add(0, footerRight.getFooter(i));
hidden.add(0, headerRight.isColumnHidden(col));
headerRight.removeColumn(i);// ColumnsRemover will care about
// columns sharing
}
for (int i = headerLeft.getColumnCount() - 1; i >= 0; i--) {
Column<T, ?> col = headerLeft.getColumn(i);
cols.add(0, col);
widths.add(0, headerLeft.getColumnWidth(col, true));
headers.add(0, headerLeft.getHeader(i));
footers.add(0, footerLeft.getFooter(i));
hidden.add(0, headerLeft.isColumnHidden(col));
headerLeft.removeColumn(i);// ColumnsRemover will care about
// columns sharing
}
headerLeft.setWidth("0px", true);
frozenLeft.setWidth("0px", true);
scrollableLeft.setWidth("0px", true);
footerLeft.setWidth("0px", true);
headerRight.setWidth("0px", true);
frozenRight.setWidth("0px", true);
scrollableRight.setWidth("0px", true);
footerRight.setWidth("0px", true);
for (int i = 0; i < cols.size(); i++) {
Column<T, ?> col = cols.get(i);
Header<?> h = headers.get(i);
Header<?> f = footers.get(i);
String w = widths.get(i);
Boolean b = hidden.get(i);
addColumn(col, w, h, f, b);
}
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
onResize();
}
});
}
public void setColumnWidthFromHeaderDrag(Column<T, ?> aColumn, double aWidth, Style.Unit aUnit) {
setColumnWidth(aColumn, aWidth, aUnit);
propagateHeightButScrollable();
}
public void setColumnWidth(Column<T, ?> aColumn, double aWidth, Style.Unit aUnit) {
if (headerLeft.getColumnIndex(aColumn) != -1) {
headerLeft.setColumnWidth(aColumn, aWidth, aUnit);
frozenLeft.setColumnWidth(aColumn, aWidth, aUnit);
scrollableLeft.setColumnWidth(aColumn, aWidth, aUnit);
footerLeft.setColumnWidth(aColumn, aWidth, aUnit);
} else if (headerRight.getColumnIndex(aColumn) != -1) {
headerRight.setColumnWidth(aColumn, aWidth, aUnit);
frozenRight.setColumnWidth(aColumn, aWidth, aUnit);
scrollableRight.setColumnWidth(aColumn, aWidth, aUnit);
footerRight.setColumnWidth(aColumn, aWidth, aUnit);
} else {
Logger.getLogger(Grid.class.getName()).log(Level.WARNING, "Unknown column is met while setting column width");
}
}
public void redrawRow(int index) {
frozenLeft.redrawRow(index);
frozenRight.redrawRow(index);
scrollableLeft.redrawRow(index);
scrollableRight.redrawRow(index);
}
public void redraw() {
headerLeft.redraw();
headerRight.redraw();
frozenLeft.redraw();
frozenRight.redraw();
scrollableLeft.redraw();
scrollableRight.redraw();
footerLeft.redraw();
footerRight.redraw();
}
public void redrawHeaders() {
headerLeft.redrawHeaders();
headerRight.redrawHeaders();
}
public void redrawFooters() {
footerLeft.redrawFooters();
footerRight.redrawFooters();
}
public int getDataColumnCount() {
return (headerLeft != null ? headerLeft.getColumnCount() : 0) + (headerRight != null ? headerRight.getColumnCount() : 0);
}
public Column<T, ?> getDataColumn(int aIndex) {
if (aIndex >= 0 && aIndex < getDataColumnCount()) {
return aIndex >= 0 && aIndex < headerLeft.getColumnCount() ? headerLeft.getColumn(aIndex) : headerRight.getColumn(aIndex - headerLeft.getColumnCount());
} else
return null;
}
public Header<?> getColumnHeader(int aIndex) {
if (aIndex >= 0 && aIndex < getDataColumnCount()) {
return aIndex >= 0 && aIndex < headerLeft.getColumnCount() ? headerLeft.getHeader(aIndex) : headerRight.getHeader(aIndex - headerLeft.getColumnCount());
} else
return null;
}
public Column<T, ?> getColumn(int aIndex) {
if (aIndex >= 0 && aIndex < getDataColumnCount()) {
return aIndex >= 0 && aIndex < headerLeft.getColumnCount() ? headerLeft.getColumn(aIndex) : headerRight.getColumn(aIndex - headerLeft.getColumnCount());
} else
return null;
}
public String getColumnWidth(int aIndex) {
if (aIndex >= 0 && aIndex < getDataColumnCount()) {
Column<T, ?> col = getColumn(aIndex);
return aIndex >= 0 && aIndex < headerLeft.getColumnCount() ? headerLeft.getColumnWidth(col) : headerRight.getColumnWidth(col);
} else
return null;
}
public Header<?> getColumnFooter(int aIndex) {
if (aIndex >= 0 && aIndex < getDataColumnCount()) {
return aIndex >= 0 && aIndex < headerLeft.getColumnCount() ? headerLeft.getFooter(aIndex) : headerRight.getFooter(aIndex - headerLeft.getColumnCount());
} else
return null;
}
public void clearColumnWidth(int aIndex) {
if (aIndex >= 0 && aIndex < getDataColumnCount()) {
Column<T, ?> col = getColumn(aIndex);
if (aIndex >= 0 && aIndex < headerLeft.getColumnCount()) {
headerLeft.clearColumnWidth(aIndex);
headerLeft.clearColumnWidth(col);
} else {
headerRight.clearColumnWidth(aIndex - headerLeft.getColumnCount());
headerRight.clearColumnWidth(col);
}
}
}
public TableCellElement getViewCell(int aRow, int aCol) {
GridSection<T> targetSection;
if (aRow < frozenRows) {
if (aCol < frozenColumns) {
targetSection = frozenLeft;
} else {
aCol -= frozenColumns;
targetSection = frozenRight;
}
} else {
aRow -= frozenRows;
if (aCol < frozenColumns) {
targetSection = scrollableLeft;
} else {
aCol -= frozenColumns;
targetSection = scrollableRight;
}
}
return targetSection.getCell(aRow, aCol);
}
public void focusViewCell(int aRow, int aCol) {
GridSection<T> targetSection;
if (aRow < frozenRows) {
if (aCol < frozenColumns) {
targetSection = frozenLeft;
} else {
aCol -= frozenColumns;
targetSection = frozenRight;
}
} else {
aRow -= frozenRows;
if (aCol < frozenColumns) {
targetSection = scrollableLeft;
} else {
aCol -= frozenColumns;
targetSection = scrollableRight;
}
}
targetSection.focusCell(aRow, aCol);
}
public void unsort() {
sortList.clear();
ColumnSortEvent.fire(Grid.this, sortList);
redrawHeaders();
}
public void addSort(ModelColumn aColumn, boolean isAscending) {
if (aColumn.isSortable()) {
boolean contains = false;
int containsAt = -1;
for (int i = 0; i < sortList.size(); i++) {
if (sortList.get(i).getColumn() == aColumn) {
contains = true;
containsAt = i;
break;
}
}
if (contains) {
boolean wasAscending = sortList.get(containsAt).isAscending();
if (wasAscending == isAscending) {
return;
}
}
sortList.insert(sortList.size(), new ColumnSortList.ColumnSortInfo(aColumn, isAscending));
ColumnSortEvent.fire(Grid.this, sortList);
redrawHeaders();
}
}
public void unsortColumn(ModelColumn aColumn) {
if (aColumn.isSortable()) {
boolean contains = false;
int containsAt = -1;
for (int i = 0; i < sortList.size(); i++) {
if (sortList.get(i).getColumn() == aColumn) {
contains = true;
containsAt = i;
break;
}
}
if (contains) {
sortList.remove(sortList.get(containsAt));
ColumnSortEvent.fire(Grid.this, sortList);
redrawHeaders();
}
}
}
}
| 39.695522 | 192 | 0.703809 |
4604e7c52793bc72134b8768878e7e8ad05d3484
| 2,331 |
/*
* Copyright 2009-2019 TMD-Maker Project <https://www.tmdmaker.org>
*
* 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.tmdmaker.ui.editor.gef3.editpolicies;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.requests.CreateConnectionRequest;
import org.tmdmaker.core.model.AbstractEntityModel;
import org.tmdmaker.core.model.relationship.Relationship;
import org.tmdmaker.ui.editor.gef3.commands.ConnectionCreateCommand;
/**
* エンティティ系モデル間のリレーションシップ作成EditPolicy
*
* @author nakaG
*
*/
public class TMDModelGraphicalNodeEditPolicy extends ReconnectableNodeEditPolicy {
/**
*
* {@inheritDoc}
*
* @see org.eclipse.gef.editpolicies.GraphicalNodeEditPolicy#getConnectionCreateCommand(org.eclipse.gef.requests.CreateConnectionRequest)
*/
@Override
protected Command getConnectionCreateCommand(CreateConnectionRequest request) {
logger.debug("{}#getConnectionCreateCommand()", getClass());
ConnectionCreateCommand command = new ConnectionCreateCommand();
command.setSource(getAbstractEntityModel());
request.setStartCommand(command);
return command;
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.gef.editpolicies.GraphicalNodeEditPolicy#getConnectionCompleteCommand(org.eclipse.gef.requests.CreateConnectionRequest)
*/
@Override
protected Command getConnectionCompleteCommand(CreateConnectionRequest request) {
logger.debug("{}#getConnectionCompleteCommand()", getClass());
ConnectionCreateCommand startCommand = (ConnectionCreateCommand) request.getStartCommand();
AbstractEntityModel source = (AbstractEntityModel) startCommand.getSource();
AbstractEntityModel target = (AbstractEntityModel) getHost().getModel();
startCommand.setTarget(target);
startCommand.setConnection(Relationship.of(source, target));
return startCommand;
}
}
| 36.421875 | 140 | 0.781639 |
2eafba15d6720cfd132cd58d8dd3d7afe247c989
| 2,516 |
package com.dankideacentral.dic.activities;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.dankideacentral.dic.R;
import com.dankideacentral.dic.util.TwitterUtil;
import com.dankideacentral.dic.authentication.TwitterSession;
import com.facebook.drawee.backends.pipeline.Fresco;
import twitter4j.auth.AccessToken;
public class LaunchActivity extends AppCompatActivity {
private static final String FINE_LOCATION_PERMISSION = "android.permission.ACCESS_FINE_LOCATION";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Fresco.initialize(this);
// Set preferences to default values when the app is opened for the first time
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
// initialize the Twitter Singleton
TwitterUtil.init(getApplicationContext());
String twitterAuth = preferences.getString(getString(R.string.twitter_auth_preference), null);
String twitterAuthSecret = preferences.getString(getString(R.string.twitter_auth_secret_preference), null);
PackageManager pm = this.getPackageManager();
int hasFineLocationPermission = pm.checkPermission(
FINE_LOCATION_PERMISSION,
this.getPackageName());
// auth tokens don't expire. Just check if it exists
if (twitterAuth == null || twitterAuthSecret == null) {
Intent loginIntent = new Intent(this, LoginActivity.class);
startActivity(loginIntent);
} else {
// Generate AccessToken from auth values stored in preferences
AccessToken accessToken = TwitterSession.getInstance().generateAccessToken(
twitterAuth, twitterAuthSecret);
TwitterUtil.getInstance().setTwitterAccessToken(accessToken);
if (hasFineLocationPermission == PackageManager.PERMISSION_GRANTED) {
Intent mapIntent = new Intent(this, TweetFeedActivity.class);
startActivity(mapIntent);
} else {
Intent searchIntent = new Intent(this, SearchActivity.class);
startActivity(searchIntent);
}
}
}
}
| 42.644068 | 115 | 0.714626 |
7291f44f0c6df1300070ded981dda156b32f112e
| 2,105 |
package at.fhjoanneum.ippr.gateway.api.controller;
import java.util.concurrent.Callable;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
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;
import at.fhjoanneum.ippr.commons.dto.owlimport.jsonimport.ImportProcessModelDTO;
import at.fhjoanneum.ippr.commons.dto.owlimport.reader.OWLProcessModelDTO;
import at.fhjoanneum.ippr.gateway.api.controller.user.HttpHeaderUser;
import at.fhjoanneum.ippr.gateway.api.services.impl.OwlImportGatewayCallerImpl;
@RestController
@RequestMapping(produces = "application/json; charset=UTF-8")
public class OwlImportGatewayController {
private final static Logger LOG = LoggerFactory.getLogger(OwlImportGatewayController.class);
@Autowired
private OwlImportGatewayCallerImpl owlImportGatewayCaller;
@RequestMapping(value = "api/owlprocessmodel", method = RequestMethod.POST)
public @ResponseBody Callable<ResponseEntity<OWLProcessModelDTO>> getOWLProcessModel(
final @RequestBody String owlContent, final HttpServletRequest request) {
return () -> {
final HttpHeaderUser user = new HttpHeaderUser(request);
return owlImportGatewayCaller.getOWLProcessModel(owlContent, user).get();
};
}
@RequestMapping(value = "api/import", method = RequestMethod.POST)
public @ResponseBody Callable<ResponseEntity<Boolean>> importProcess(
final @RequestBody ImportProcessModelDTO processModelDTO, final HttpServletRequest request) {
return () -> {
final HttpHeaderUser user = new HttpHeaderUser(request);
return owlImportGatewayCaller.importProcessModel(processModelDTO, user).get();
};
}
}
| 42.959184 | 100 | 0.791449 |
ea47bccb684395bfdc53fcd69b3d8a5f6dff4bf0
| 16,745 |
/*
* DeepImageJ
*
* https://deepimagej.github.io/deepimagej/
*
* Reference: DeepImageJ: A user-friendly environment to run deep learning models in ImageJ
* E. Gomez-de-Mariscal, C. Garcia-Lopez-de-Haro, W. Ouyang, L. Donati, M. Unser, E. Lundberg, A. Munoz-Barrutia, D. Sage.
* Submitted 2021.
* Bioengineering and Aerospace Engineering Department, Universidad Carlos III de Madrid, Spain
* Biomedical Imaging Group, Ecole polytechnique federale de Lausanne (EPFL), Switzerland
* Science for Life Laboratory, School of Engineering Sciences in Chemistry, Biotechnology and Health, KTH - Royal Institute of Technology, Sweden
*
* Authors: Carlos Garcia-Lopez-de-Haro and Estibaliz Gomez-de-Mariscal
*
*/
/*
* BSD 2-Clause License
*
* Copyright (c) 2019-2021, DeepImageJ
* All rights reserved.
*
* 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 HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package deepimagej.stamp;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import org.jetbrains.bio.npy.NpyFile;
import deepimagej.BuildDialog;
import deepimagej.Constants;
import deepimagej.DeepImageJ;
import deepimagej.ImagePlus2Tensor;
import deepimagej.Parameters;
import deepimagej.Table2Tensor;
import deepimagej.components.HTMLPane;
import deepimagej.tools.FileTools;
import deepimagej.tools.YAMLUtils;
import ij.IJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.measure.ResultsTable;
import ij.text.TextWindow;
public class TfSaveStamp extends AbstractStamp implements ActionListener, Runnable {
private JTextField txt = new JTextField(IJ.getDirectory("imagej") + File.separator + "models" + File.separator);
private JButton bnBrowse = new JButton("Browse");
private JButton bnSave = new JButton("Save Bundled Model");
private HTMLPane pane;
public TfSaveStamp(BuildDialog parent) {
super(parent);
buildPanel();
}
public void buildPanel() {
pane = new HTMLPane(Constants.width, 320);
pane.setBorder(BorderFactory.createEtchedBorder());
pane.append("h2", "Saving Bundled Model");
JScrollPane infoPane = new JScrollPane(pane);
//infoPane.setPreferredSize(new Dimension(Constants.width, pane.getPreferredSize().height));
DeepImageJ dp = parent.getDeepPlugin();
if (dp != null)
if (dp.params != null)
if (dp.params.path2Model != null)
txt.setText(dp.params.path2Model);
txt.setFont(new Font("Arial", Font.BOLD, 14));
txt.setForeground(Color.red);
txt.setText(IJ.getDirectory("imagej") + File.separator + "models" + File.separator);
JPanel load = new JPanel(new BorderLayout());
load.setBorder(BorderFactory.createEtchedBorder());
load.add(txt, BorderLayout.CENTER);
load.add(bnBrowse, BorderLayout.EAST);
JPanel pn = new JPanel(new BorderLayout());
pn.add(load, BorderLayout.NORTH);
pn.add(infoPane, BorderLayout.CENTER);
JPanel pnButtons = new JPanel(new GridLayout(2, 1));
pnButtons.add(bnSave);
pn.add(bnSave, BorderLayout.SOUTH);
panel.add(pn);
bnSave.addActionListener(this);
txt.setDropTarget(new LocalDropTarget());
load.setDropTarget(new LocalDropTarget());
bnBrowse.addActionListener(this);
}
@Override
public void init() {
}
@Override
public boolean finish() {
return true;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == bnBrowse) {
browse();
}
if (e.getSource() == bnSave) {
save();
}
}
private void browse() {
JFileChooser chooser = new JFileChooser(txt.getText());
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setDialogTitle("Select model");
int ret = chooser.showSaveDialog(new JFrame());
if (ret == JFileChooser.APPROVE_OPTION) {
txt.setText(chooser.getSelectedFile().getAbsolutePath());
txt.setCaretPosition(1);
}
}
public void save() {
Thread thread = new Thread(this);
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
}
@Override
public void run() {
DeepImageJ dp = parent.getDeepPlugin();
Parameters params = dp.params;
params.saveDir = txt.getText() + File.separator;
params.saveDir = params.saveDir.replace(File.separator + File.separator, File.separator);
File dir = new File(params.saveDir);
if (dir.exists() && dir.isDirectory()) {
pane.append("p", "Path introduced corresponded to an already existing directory.");
pane.append("p", "Model not saved");
IJ.error("Directory: \n" + dir.getAbsolutePath() + "\n already exists. Please introduce other name.");
return;
}
if (!dir.exists()) {
dir.mkdir();
pane.append("p", "Making directory: " + params.saveDir);
}
dir = new File(params.saveDir);
// Save the model architecture
params.biozoo = true;
try {
String zipName = "tensorflow_saved_model_bundle.zip";
pane.append("p", "Writting zip file...");
FileTools.zip(new String[]{params.path2Model + File.separator + "variables", params.path2Model + File.separator + "saved_model.pb"}, params.saveDir + File.separator + zipName);
pane.append("p", "Tensorflow Bioimage Zoo model: saved");
}
catch (Exception e) {
e.printStackTrace();
pane.append("p", "Error zipping the varaibles folder and saved_model.pb");
pane.append("p", "Zipped Tensorflow model: not saved");
}
// List with processing files saved
ArrayList<String> saved = new ArrayList<String>();
// Save preprocessing
if (params.firstPreprocessing != null) {
try {
File destFile = new File(params.saveDir + File.separator + new File(params.firstPreprocessing).getName());
FileTools.copyFile(new File(params.firstPreprocessing), destFile);
pane.append("p", "First preprocessing: saved");
saved.add(params.firstPreprocessing);
}
catch (Exception e) {
pane.append("p", "First preprocessing: not saved");
}
}
if (params.secondPreprocessing != null && !saved.contains(params.secondPreprocessing)) {
try {
File destFile = new File(params.saveDir + File.separator + new File(params.secondPreprocessing).getName());
FileTools.copyFile(new File(params.secondPreprocessing), destFile);
pane.append("p", "Second preprocessing: saved");
saved.add(params.secondPreprocessing);
}
catch (Exception e) {
pane.append("p", "Second preprocessing: not saved");
}
} else if (params.secondPreprocessing != null) {
pane.append("p", "Second preprocessing: saved");
}
// Save postprocessing
if (params.firstPostprocessing != null && !saved.contains(params.firstPostprocessing)) {
try {
File destFile = new File(params.saveDir + File.separator + new File(params.firstPostprocessing).getName());
FileTools.copyFile(new File(params.firstPostprocessing), destFile);
pane.append("p", "First postprocessing: saved");
}
catch (Exception e) {
pane.append("p", "First postprocessing: not saved");
}
} else if (params.firstPostprocessing != null) {
pane.append("p", "First postprocessing: saved");
}
if (params.secondPostprocessing != null && !saved.contains(params.secondPostprocessing)) {
try {
File destFile = new File(params.saveDir + File.separator + new File(params.secondPostprocessing).getName());
FileTools.copyFile(new File(params.secondPostprocessing), destFile);
pane.append("p", "Second postprocessing: saved");
}
catch (Exception e) {
pane.append("p", "Second postprocessing: not saved");
}
} else if (params.secondPostprocessing != null) {
pane.append("p", "Second postprocessing: saved");
}
// Save input image
try {
if (params.testImageBackup != null) {
// Get name with no extension
String title = getTitleWithoutExtension(params.testImageBackup.getTitle().substring(4));
IJ.saveAsTiff(params.testImageBackup, params.saveDir + File.separator + title + ".tif");
pane.append("p", title + ".tif" + ": saved");
boolean npySaved = saveNpyFile(params.testImageBackup, "XYCZN", params.saveDir + File.separator + title + ".npy");
if (npySaved)
pane.append("p", title + ".npy" + ": saved");
else
pane.append("p", title + ".npy: not saved");
params.testImageBackup.setTitle("DUP_" + params.testImageBackup.getTitle());
} else {
throw new Exception();
}
}
catch(Exception ex) {
pane.append("p", "exampleImage.tif: not saved");
pane.append("p", "exampleImage.npy: not saved");
}
// Save output images and tables (tables as saved as csv)
for (HashMap<String, String> output : params.savedOutputs) {
String name = output.get("name");
String nameNoExtension= getTitleWithoutExtension(name);
try {
if (output.get("type").contains("image")) {
ImagePlus im = WindowManager.getImage(name);
IJ.saveAsTiff(im, params.saveDir + File.separator + nameNoExtension + ".tif");
im.setTitle(name);
pane.append("p", nameNoExtension + ".tif" + ": saved");
boolean npySaved = saveNpyFile(im, "XYCZB", params.saveDir + File.separator + nameNoExtension + ".npy");
if (npySaved)
pane.append("p", nameNoExtension + ".npy" + ": saved");
else
pane.append("p", nameNoExtension + ".npy: not saved");
} else if (output.get("type").contains("ResultsTable")){
Frame f = WindowManager.getFrame(name);
if (f!=null && (f instanceof TextWindow)) {
ResultsTable rt = ((TextWindow)f).getResultsTable();
rt.save(params.saveDir + File.separator + nameNoExtension + ".csv");
pane.append("p", nameNoExtension + ".csv" + ": saved");
boolean npySaved = saveNpyFile(rt, params.saveDir + File.separator + nameNoExtension + ".npy", "RC");
if (npySaved)
pane.append("p", nameNoExtension + ".npy" + ": saved");
else
pane.append("p", nameNoExtension + ".npy: not saved");
} else {
throw new Exception(); }
}
}
catch(Exception ex) {
pane.append("p", nameNoExtension + ".tif: not saved");
pane.append("p", nameNoExtension + ".npy: not saved");
}
}
// Save yaml
try {
YAMLUtils.writeYaml(dp);
pane.append("p", "model.yaml: saved");
}
catch(IOException ex) {
pane.append("p", "model.yaml: not saved");
IJ.error("Model file was locked or does not exist anymore.");
}
catch(Exception ex) {
ex.printStackTrace();
pane.append("p", "model.yaml: not saved");
}
// Finally save external dependencies
boolean saveDeps = saveExternalDependencies(params);
if (saveDeps && params.attachments.size() > 0) {
pane.append("p", "External dependencies: saved");
} else if (!saveDeps && params.attachments.size() > 0) {
pane.append("p", "External dependencies: not saved");
}
pane.append("p", "Done!!");
}
/**
* Save jar dependency files indicated by the developer and saved at params.attachments.
* Saves all types of files but '.jar' o '.class' files
* @param params
* @return true if saving was successful or false otherwise
*/
public static boolean saveExternalDependencies(Parameters params) {
boolean saved = true;
ArrayList<String> savedFiles = new ArrayList<String>();
String errMsg = "DeepImageJ unable to save:\n";
for (String dep : params.attachments) {
if (savedFiles.contains(new File(dep).getName()) || (new File(dep).getName()).endsWith(".jar") || (new File(dep).getName()).endsWith(".class"))
continue;
File destFile = new File(params.saveDir + File.separator + new File(dep).getName());
try {
FileTools.copyFile(new File(dep), destFile);
savedFiles.add(new File(dep).getName());
} catch (IOException e) {
saved = false;
errMsg += " - " + new File(dep).getName();
e.printStackTrace();
}
}
if (!saved) {
IJ.error(errMsg);
}
return saved;
}
/*
* Gets the image title without the extension
*/
public static String getTitleWithoutExtension(String title) {
int lastDot = title.lastIndexOf(".");
if (lastDot == -1)
return title;
return title.substring(0, lastDot);
}
public static boolean saveNpyFile(ImagePlus im, String form, String name) {
Path path = Paths.get(name);
String imTitle = name.substring(name.lastIndexOf(File.separator) + 1, name.lastIndexOf("."));
long[] imShapeLong = ImagePlus2Tensor.getTensorShape(im, form);
int[] imShape = new int[imShapeLong.length];
// If the number of pixels is too big let the user know that they might prefer not saving
// the results in npy format
String msg = "Do you want to save the image '" + imTitle + "' in .npy format.\n"
+ "Saving it might take too long. Do you want to continue?";
boolean accept = IJ.showMessageWithCancel("Cancel .npy file save", msg);
if (!accept)
return false;
float[] imArray = ImagePlus2Tensor.implus2IntArray(im, form);
NpyFile.write(path, imArray, imShape);
return true;
}
public static boolean saveNpyFile(ResultsTable table, String name, String form) {
Path path = Paths.get(name);
int[] shape = Table2Tensor.getTableShape(form, table);
// Convert the array into long
long[] shapeLong = new long[shape.length];
// If the number of pixels is too big let the user know that they might prefer not saving
// the results in npy format
String msg = "Do you want to save the table '" + table.getTitle() + "' in .npy format.\n"
+ "Saving it might take too long. Do you want to continue?";
boolean accept = IJ.showMessageWithCancel("Cancel .npy file save", msg);
if (!accept)
return false;
// Get the array
float[] flatRt = Table2Tensor.tableToFlatArray(table, form, shapeLong);
NpyFile.write(path, flatRt, shape);
return true;
}
public class LocalDropTarget extends DropTarget {
@Override
public void drop(DropTargetDropEvent e) {
e.acceptDrop(DnDConstants.ACTION_COPY);
e.getTransferable().getTransferDataFlavors();
Transferable transferable = e.getTransferable();
DataFlavor[] flavors = transferable.getTransferDataFlavors();
for (DataFlavor flavor : flavors) {
if (flavor.isFlavorJavaFileListType()) {
try {
List<File> files = (List<File>) transferable.getTransferData(flavor);
for (File file : files) {
txt.setText(file.getAbsolutePath());
txt.setCaretPosition(1);
}
}
catch (UnsupportedFlavorException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
e.dropComplete(true);
super.drop(e);
}
}
}
| 36.561135 | 181 | 0.681338 |
4bf8c18308da5cb200ab358281e7f1b3468e98f8
| 622 |
package Sogong.IMS.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class WorkspaceProperty {
private String corporateRegistrationNumber;
private String representativeName;
private String workspaceAddress;
private String phoneNum;
private String typeOfBusiness;
private int workspaceMemberCount;
private String workspaceStatus;
private String registrantID;
private String workspaceID;
private String workspaceName;
}
| 23.923077 | 47 | 0.800643 |
73d05793315ee4db9abb76203bdeef6d0135a5c1
| 501 |
package com.example.util.mvp.noop;
import com.hannesdorfmann.mosby3.mvp.MvpNullObjectBasePresenter;
import javax.inject.Inject;
/**
* An empty presenter for screens that require no presenter. (There should really be no screen like that in a normal project, but this is a
* test project).
*/
public class NoOpPresenter extends MvpNullObjectBasePresenter<NoOpView> {
@Inject
@SuppressWarnings("PMD.UnnecessaryConstructor")
public NoOpPresenter() {
// used by dagger
}
}
| 23.857143 | 139 | 0.742515 |
abd6660ca66793ec43c1e911bfa973f450a0ba4d
| 7,040 |
package com.ermile.salamquran.android.model.quran;
import android.graphics.RectF;
import com.ermile.salamquran.android.data.AyahInfoDatabaseHandler;
import com.ermile.salamquran.android.data.AyahInfoDatabaseProvider;
import com.ermile.salamquran.android.di.ActivityScope;
import com.ermile.page.common.data.AyahBounds;
import com.ermile.page.common.data.AyahCoordinates;
import com.ermile.page.common.data.PageCoordinates;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
@ActivityScope
public class CoordinatesModel {
private static final float THRESHOLD_PERCENTAGE = 0.015f;
private final AyahInfoDatabaseProvider ayahInfoDatabaseProvider;
@Inject
CoordinatesModel(AyahInfoDatabaseProvider ayahInfoDatabaseProvider) {
this.ayahInfoDatabaseProvider = ayahInfoDatabaseProvider;
}
public Observable<PageCoordinates> getPageCoordinates(boolean wantPageBounds, Integer... pages) {
AyahInfoDatabaseHandler database = ayahInfoDatabaseProvider.getAyahInfoHandler();
if (database == null) {
return Observable.error(new NoSuchElementException("No AyahInfoDatabaseHandler found!"));
}
return Observable.fromArray(pages)
.map(page -> database.getPageInfo(page, wantPageBounds))
.subscribeOn(Schedulers.computation());
}
public Observable<AyahCoordinates> getAyahCoordinates(Integer... pages) {
AyahInfoDatabaseHandler database = ayahInfoDatabaseProvider.getAyahInfoHandler();
if (database == null) {
return Observable.error(new NoSuchElementException("No AyahInfoDatabaseHandler found!"));
}
return Observable.fromArray(pages)
.map(database::getVersesBoundsForPage)
.map(this::normalizePageAyahs)
.subscribeOn(Schedulers.computation());
}
private AyahCoordinates normalizePageAyahs(AyahCoordinates ayahCoordinates) {
final Map<String, List<AyahBounds>> original = ayahCoordinates.getAyahCoordinates();
Map<String, List<AyahBounds>> normalizedMap = new HashMap<>();
final Set<String> keys = original.keySet();
for (String key : keys) {
List<AyahBounds> normalBounds = original.get(key);
if (normalBounds != null) {
normalizedMap.put(key, normalizeAyahBounds(normalBounds));
}
}
return new AyahCoordinates(ayahCoordinates.getPage(), normalizedMap);
}
private List<AyahBounds> normalizeAyahBounds(List<AyahBounds> ayahBounds) {
final int total = ayahBounds.size();
if (total < 2) {
return ayahBounds;
} else if (total < 3) {
return consolidate(ayahBounds.get(0), ayahBounds.get(1));
} else {
AyahBounds middle = ayahBounds.get(1);
for (int i = 2; i < total - 1; i++) {
middle.engulf(ayahBounds.get(i));
}
List<AyahBounds> top = consolidate(ayahBounds.get(0), middle);
final int topSize = top.size();
// the first parameter is essentially middle (after its consolidation with the top line)
List<AyahBounds> bottom = consolidate(top.get(topSize - 1), ayahBounds.get(total - 1));
List<AyahBounds> result = new ArrayList<>();
if (topSize == 1) {
return bottom;
} else if (topSize + bottom.size() > 4) {
// this happens when a verse spans 3 incomplete lines (i.e. starts towards the end of
// one line, takes one or more whole lines, and ends early on in the line). in this case,
// just remove the duplicates.
// add the first parts of top
for (int i = 0; i < topSize - 1; i++) {
result.add(top.get(i));
}
// resolve the middle part which may overlap with bottom
final AyahBounds lastTop = top.get(topSize - 1);
final AyahBounds firstBottom = bottom.get(0);
if (lastTop.equals(firstBottom)) {
// only add one if they're both the same
result.add(lastTop);
} else {
// if one contains the other, add the larger one
final RectF topRect = lastTop.getBounds();
final RectF bottomRect = firstBottom.getBounds();
if (topRect.contains(bottomRect)) {
result.add(lastTop);
} else if (bottomRect.contains(topRect)) {
result.add(firstBottom);
} else {
// otherwise add both
result.add(lastTop);
result.add(firstBottom);
}
}
// add everything except the first bottom entry
for (int i = 1, size = bottom.size(); i < size; i++) {
result.add(bottom.get(i));
}
return result;
} else {
// re-consolidate top and middle again, since middle may have changed
top = consolidate(top.get(0), bottom.get(0));
result.addAll(top);
if (bottom.size() > 1) {
result.add(bottom.get(1));
}
return result;
}
}
}
private List<AyahBounds> consolidate(AyahBounds top, AyahBounds bottom) {
final RectF firstRect = top.getBounds();
final RectF lastRect = bottom.getBounds();
AyahBounds middle = null;
// only 2 lines - let's see if any of them are full lines
final int pageWidth = ayahInfoDatabaseProvider.getPageWidth();
int threshold = (int) (THRESHOLD_PERCENTAGE * pageWidth);
boolean firstIsFullLine = Math.abs(firstRect.right - lastRect.right) < threshold;
boolean secondIsFullLine = Math.abs(firstRect.left - lastRect.left) < threshold;
if (firstIsFullLine && secondIsFullLine) {
top.engulf(bottom);
return Collections.singletonList(top);
} else if (firstIsFullLine) {
lastRect.top = firstRect.bottom;
float bestStartOfLine = Math.max(firstRect.right, lastRect.right);
firstRect.right = bestStartOfLine;
lastRect.right = bestStartOfLine;
top = top.withBounds(firstRect);
bottom = bottom.withBounds(lastRect);
} else if (secondIsFullLine) {
firstRect.bottom = lastRect.top;
float bestEndOfLine = Math.min(firstRect.left, lastRect.left);
firstRect.left = bestEndOfLine;
lastRect.left = bestEndOfLine;
top = top.withBounds(firstRect);
bottom = bottom.withBounds(lastRect);
} else {
// neither one is a full line, let's generate a middle entry to join them if they have
// anything in common (i.e. any part of them intersects)
if (lastRect.left < firstRect.right) {
RectF middleBounds = new RectF(lastRect.left,
/* top= */ firstRect.bottom,
Math.min(firstRect.right, lastRect.right),
/* bottom= */ lastRect.top);
middle = new AyahBounds(top.getLine(), top.getPosition(), middleBounds);
}
}
List<AyahBounds> result = new ArrayList<>();
result.add(top);
if (middle != null) {
result.add(middle);
}
result.add(bottom);
return result;
}
}
| 36.666667 | 99 | 0.669318 |
256b4f2d16383ef2c9d914c9d9f38207860264f9
| 4,227 |
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|pdfbox
operator|.
name|examples
operator|.
name|pdmodel
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|pdfbox
operator|.
name|pdmodel
operator|.
name|PDDocument
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|pdfbox
operator|.
name|pdmodel
operator|.
name|PDPage
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|pdfbox
operator|.
name|pdmodel
operator|.
name|PDPageContentStream
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|pdfbox
operator|.
name|pdmodel
operator|.
name|font
operator|.
name|PDFont
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|pdfbox
operator|.
name|pdmodel
operator|.
name|font
operator|.
name|PDType1Font
import|;
end_import
begin_comment
comment|/** * Creates a "Hello World" PDF using the built-in Helvetica font. * * The example is taken from the PDF file format specification. */
end_comment
begin_class
specifier|public
specifier|final
class|class
name|HelloWorld
block|{
specifier|private
name|HelloWorld
parameter_list|()
block|{ }
specifier|public
specifier|static
name|void
name|main
parameter_list|(
name|String
index|[]
name|args
parameter_list|)
throws|throws
name|IOException
block|{
if|if
condition|(
name|args
operator|.
name|length
operator|!=
literal|2
condition|)
block|{
name|System
operator|.
name|err
operator|.
name|println
argument_list|(
literal|"usage: "
operator|+
name|HelloWorld
operator|.
name|class
operator|.
name|getName
argument_list|()
operator|+
literal|"<output-file><Message>"
argument_list|)
expr_stmt|;
name|System
operator|.
name|exit
argument_list|(
literal|1
argument_list|)
expr_stmt|;
block|}
name|String
name|filename
init|=
name|args
index|[
literal|0
index|]
decl_stmt|;
name|String
name|message
init|=
name|args
index|[
literal|1
index|]
decl_stmt|;
try|try
init|(
name|PDDocument
name|doc
init|=
operator|new
name|PDDocument
argument_list|()
init|)
block|{
name|PDPage
name|page
init|=
operator|new
name|PDPage
argument_list|()
decl_stmt|;
name|doc
operator|.
name|addPage
argument_list|(
name|page
argument_list|)
expr_stmt|;
name|PDFont
name|font
init|=
name|PDType1Font
operator|.
name|HELVETICA_BOLD
decl_stmt|;
try|try
init|(
name|PDPageContentStream
name|contents
init|=
operator|new
name|PDPageContentStream
argument_list|(
name|doc
argument_list|,
name|page
argument_list|)
init|)
block|{
name|contents
operator|.
name|beginText
argument_list|()
expr_stmt|;
name|contents
operator|.
name|setFont
argument_list|(
name|font
argument_list|,
literal|12
argument_list|)
expr_stmt|;
name|contents
operator|.
name|newLineAtOffset
argument_list|(
literal|100
argument_list|,
literal|700
argument_list|)
expr_stmt|;
name|contents
operator|.
name|showText
argument_list|(
name|message
argument_list|)
expr_stmt|;
name|contents
operator|.
name|endText
argument_list|()
expr_stmt|;
block|}
name|doc
operator|.
name|save
argument_list|(
name|filename
argument_list|)
expr_stmt|;
block|}
block|}
block|}
end_class
end_unit
| 15.315217 | 810 | 0.784954 |
a88f093a35b3f99ddf8339d81952d13b3d4fd6d8
| 2,612 |
package scot.gov.www.beans;
import org.hippoecm.hst.content.beans.Node;
import org.hippoecm.hst.content.beans.standard.HippoBean;
import org.hippoecm.hst.content.beans.standard.HippoHtml;
import org.onehippo.cms7.essentials.dashboard.annotations.HippoEssentialsGenerated;
import java.util.List;
@HippoEssentialsGenerated(internalName = "govscot:Policy")
@Node(jcrType = "govscot:Policy")
public class Policy extends AttributableContent {
@HippoEssentialsGenerated(internalName = "govscot:title")
public String getTitle() {
return getSingleProperty("govscot:title");
}
@HippoEssentialsGenerated(internalName = "govscot:summary")
public String getSummary() {
return getSingleProperty("govscot:summary");
}
@HippoEssentialsGenerated(internalName = "govscot:seoTitle")
public String getSeoTitle() {
return getSingleProperty("govscot:seoTitle");
}
@HippoEssentialsGenerated(internalName = "govscot:metaDescription")
public String getMetaDescription() {
return getSingleProperty("govscot:metaDescription");
}
@HippoEssentialsGenerated(internalName = "hippostd:tags")
public String[] getTags() {
return getMultipleProperty("hippostd:tags");
}
@HippoEssentialsGenerated(internalName = "govscot:content")
public HippoHtml getContent() {
return getHippoHtml("govscot:content");
}
@HippoEssentialsGenerated(internalName = "govscot:background")
public HippoHtml getBackground() {
return getHippoHtml("govscot:background");
}
@HippoEssentialsGenerated(internalName = "govscot:billsAndLegislation")
public HippoHtml getBillsAndLegislation() {
return getHippoHtml("govscot:billsAndLegislation");
}
@HippoEssentialsGenerated(internalName = "govscot:contact")
public HippoHtml getContact() {
return getHippoHtml("govscot:contact");
}
@HippoEssentialsGenerated(internalName = "govscot:actions")
public HippoHtml getActions() {
return getHippoHtml("govscot:actions");
}
@HippoEssentialsGenerated(internalName = "govscot:relatedItems")
public List<HippoBean> getRelatedItems() {
return getLinkedBeans("govscot:relatedItems", HippoBean.class);
}
@HippoEssentialsGenerated(internalName = "govscot:notes")
public HippoHtml getNotes() {
return getHippoHtml("govscot:notes");
}
@HippoEssentialsGenerated(internalName = "govscot:newsTags")
public String[] getNewsTags() { return getMultipleProperty("govscot:newsTags"); }
public String getLabel() { return "policy"; }
}
| 33.487179 | 85 | 0.725498 |
dc762a44afb00c2402f7b2e3299246a76d5d1dbd
| 410 |
package com.atguigu.gmall.sms.mapper;
import com.atguigu.gmall.sms.entity.SmsCouponSpuCategoryEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 优惠券分类关联
*
* @author Gork
* @email 1271367045@qq.com.com
* @date 2020-08-06 12:37:23
*/
@Mapper
public interface SmsCouponSpuCategoryMapper extends BaseMapper<SmsCouponSpuCategoryEntity> {
}
| 22.777778 | 92 | 0.782927 |
6bfad31b5169c2bf2d80fbca545cd9c66d6d43e5
| 1,124 |
package net.scapeemulator.game.update;
import net.scapeemulator.game.model.Position;
import net.scapeemulator.game.model.mob.Direction;
import net.scapeemulator.game.model.player.Player;
import net.scapeemulator.game.msg.impl.PlayerUpdateMessage;
import net.scapeemulator.game.net.game.GameFrameBuilder;
public final class AddPlayerDescriptor extends PlayerDescriptor {
private final int id;
private final Direction direction;
private final Position position;
public AddPlayerDescriptor(Player player, int[] tickets) {
super(player, tickets, true);
this.id = player.getId();
this.direction = player.getMostRecentDirection();
this.position = player.getPosition();
}
@Override
public void encodeDescriptor(PlayerUpdateMessage message, GameFrameBuilder builder, GameFrameBuilder blockBuilder) {
int x = position.getX() - message.getPosition().getX();
int y = position.getY() - message.getPosition().getY();
builder.putBits(11, id);
builder.putBits(1, 1); // check
builder.putBits(5, x);
builder.putBits(3, direction.toInteger());
builder.putBits(1, 1); // check
builder.putBits(5, y);
}
}
| 32.114286 | 117 | 0.765125 |
c793bad5bf016bcc799520a85d52bc3267519bb2
| 1,115 |
package com.xarql.chat.direct;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.xarql.util.DatabaseQuery;
public class RecentRetriever extends DatabaseQuery<List<Conversation>>
{
private static final String COMMAND = "SELECT * FROM direct_messages WHERE id IN (SELECT MAX(id) FROM direct_messages WHERE recipient=? GROUP BY sender)";
private List<Conversation> conversations;
private final String recipient;
public RecentRetriever(String recipient)
{
super(COMMAND);
this.recipient = recipient;
conversations = new ArrayList<>();
}
@Override
protected void processResult(ResultSet rs) throws SQLException
{
conversations.add(new Conversation(DirectMessage.process(rs)));
}
@Override
protected List<Conversation> getData()
{
return conversations;
}
@Override
protected void setVariables(PreparedStatement statement) throws SQLException
{
statement.setString(1, recipient);
}
}
| 25.930233 | 158 | 0.713901 |
b6b0a7bb126c43b26994a870bb00bb10dca613e1
| 647 |
package br.ufsc.ine5605.ShardRPG.Item;
import br.ufsc.ine5605.ShardRPG.Info.Room;
public class ItemChair extends Item implements Breakable {
private String destroyMessage;
public String getDestroyMessage() {
return destroyMessage;
}
public ItemChair(String name, String description, String[] alias) {
super(name, description, alias, false);
destroyMessage = "You use your fury to smash up the chair, it's pieces fly everywhere. Why have you done this?";
}
@Override
public void destroy() {
System.out.println(destroyMessage);
}
@Override
public void setDestroyMessage(String string) {
destroyMessage = string;
}
}
| 19.606061 | 114 | 0.746522 |
0ecc750db4a91ab6234311409d3f62bc40ec3d48
| 1,488 |
/*
* 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.geode;
/**
* An <code>ForcedDisconnectException</code> is thrown when a GemFire application is removed from
* the distributed system due to membership constraints such as network partition detection.
*
* @since GemFire 5.7
*/
public class ForcedDisconnectException extends CancelException {
private static final long serialVersionUID = 4977003259880566257L;
////////////////////// Constructors //////////////////////
/**
* Creates a new <code>SystemConnectException</code>.
*/
public ForcedDisconnectException(String message) {
super(message);
}
public ForcedDisconnectException(String message, Throwable cause) {
super(message, cause);
}
}
| 38.153846 | 100 | 0.737903 |
2eac1968a382cc82f2f5ff0e931d7588d4f57c4b
| 1,226 |
package com.helen.andbase.entity;
import cn.bmob.v3.BmobObject;
/**
* Created by Helen on 2015/10/21.
*
*/
public class AppInfo extends BmobObject{
private String appId;//包名
private Boolean isPass;//是否验证通过
private Boolean isCheck;//是否需要检测
private String message;//提示语
public Boolean getIsCheck() {
if(isCheck == null){
isCheck = true;
}
return isCheck;
}
public void setIsCheck(Boolean isCheck) {
this.isCheck = isCheck;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public Boolean getIsPass() {
if(isPass == null){
isPass = false;
}
return isPass;
}
public void setIsPass(Boolean isPass) {
this.isPass = isPass;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "AppInfo{" +
"appId='" + appId + '\'' +
", isPass=" + isPass +
", isCheck=" + isCheck +
'}';
}
}
| 19.774194 | 45 | 0.539152 |
fc059e72e6d52a8267bd10d8121432aede70c40b
| 734 |
package tp.p1.managers;
import tp.p1.interfaz.BoardPrinter;
import tp.p1.interfaz.DebugPrinter;
import tp.p1.interfaz.ReleasePrinter;
public class PrinterManager {
private BoardPrinter bp;
public PrinterManager ()
{
bp =new ReleasePrinter();
}
public BoardPrinter getbp() {
// TODO Auto-generated method stub
return this.bp;
}
public void setbp(BoardPrinter bp2) {
// TODO Auto-generated method stub
this.bp = bp2;
}
public static BoardPrinter parse(String nombre) {
BoardPrinter bp = null;
if(nombre.equalsIgnoreCase("release"))
{
bp = new ReleasePrinter();
}
else if (nombre.equalsIgnoreCase("debug"))
{
bp = new DebugPrinter();
}
return bp;
}
}
| 19.315789 | 51 | 0.668937 |
cdb0d70781bdda1ee0ec504f213f638d43b11188
| 3,412 |
package seedu.planner.model;
import java.util.ArrayList;
import java.util.List;
/**
* {@code FinancialPlanner} that keeps track of its own history.
*/
public class VersionedFinancialPlanner extends FinancialPlanner {
private final List<ReadOnlyFinancialPlanner> financialPlannerStateList;
private int currentStatePointer;
public VersionedFinancialPlanner(ReadOnlyFinancialPlanner initialState) {
super(initialState);
financialPlannerStateList = new ArrayList<>();
financialPlannerStateList.add(new FinancialPlanner(initialState));
currentStatePointer = 0;
}
/**
* Saves a copy of the current {@code FinancialPlanner} state at the end of the state list.
* Undone states are removed from the state list.
*/
public void commit() {
removeStatesAfterCurrentPointer();
financialPlannerStateList.add(new FinancialPlanner(this));
currentStatePointer++;
}
private void removeStatesAfterCurrentPointer() {
financialPlannerStateList.subList(currentStatePointer + 1, financialPlannerStateList.size()).clear();
}
/**
* Restores the financial planner to its previous state.
*/
public void undo() {
if (!canUndo()) {
throw new NoUndoableStateException();
}
currentStatePointer--;
resetData(financialPlannerStateList.get(currentStatePointer));
}
/**
* Restores the financial planner to its previously undone state.
*/
public void redo() {
if (!canRedo()) {
throw new NoRedoableStateException();
}
currentStatePointer++;
resetData(financialPlannerStateList.get(currentStatePointer));
}
/**
* Returns true if {@code undo()} has financial planner states to undo.
*/
public boolean canUndo() {
return currentStatePointer > 0;
}
/**
* Returns true if {@code redo()} has financial planner states to redo.
*/
public boolean canRedo() {
return currentStatePointer < financialPlannerStateList.size() - 1;
}
@Override
public boolean equals(Object other) {
// short circuit if same object
if (other == this) {
return true;
}
// instanceof handles nulls
if (!(other instanceof VersionedFinancialPlanner)) {
return false;
}
VersionedFinancialPlanner otherVersionedFinancialPlanner = (VersionedFinancialPlanner) other;
// state check
return super.equals(otherVersionedFinancialPlanner)
&& financialPlannerStateList.equals(otherVersionedFinancialPlanner.financialPlannerStateList)
&& currentStatePointer == otherVersionedFinancialPlanner.currentStatePointer;
}
/**
* Thrown when trying to {@code undo()} but can't.
*/
public static class NoUndoableStateException extends RuntimeException {
private NoUndoableStateException() {
super("Current state pointer at start of financialPlannerState list, unable to undo.");
}
}
/**
* Thrown when trying to {@code redo()} but can't.
*/
public static class NoRedoableStateException extends RuntimeException {
private NoRedoableStateException() {
super("Current state pointer at end of financialPlannerState list, unable to redo.");
}
}
}
| 31.018182 | 109 | 0.659437 |
2461501c48172fb4f2fc129147be75758808d845
| 11,222 |
/*
* ART Java
*
* Copyright 2019 ART
*
* 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 ru.art.message.pack.descriptor;
import lombok.experimental.*;
import org.msgpack.core.buffer.*;
import org.msgpack.value.*;
import ru.art.core.checker.*;
import ru.art.entity.MapValue;
import ru.art.entity.Value;
import ru.art.entity.*;
import ru.art.message.pack.exception.*;
import static java.util.Objects.*;
import static java.util.stream.Collectors.*;
import static org.msgpack.core.MessagePack.*;
import static org.msgpack.value.ValueFactory.MapBuilder;
import static org.msgpack.value.ValueFactory.*;
import static ru.art.core.checker.CheckerForEmptiness.isEmpty;
import static ru.art.core.checker.CheckerForEmptiness.*;
import static ru.art.core.constants.ArrayConstants.*;
import static ru.art.core.extension.FileExtensions.*;
import static ru.art.core.factory.CollectionsFactory.*;
import static ru.art.entity.Value.*;
import static ru.art.entity.constants.CollectionMode.*;
import java.io.*;
import java.nio.file.*;
import java.util.*;
@UtilityClass
public class MessagePackEntityWriter {
public static void writeMessagePack(Value value, OutputStream outputStream) {
if (isNull(outputStream)) {
return;
}
try {
outputStream.write(writeMessagePackToBytes(value));
} catch (Throwable throwable) {
throw new MessagePackMappingException(throwable);
}
}
public static void writeMessagePack(Value value, Path path) {
writeFileQuietly(path, writeMessagePackToBytes(value));
}
public static byte[] writeMessagePackToBytes(Value value) {
if (Value.isEmpty(value)) {
return EMPTY_BYTES;
}
ArrayBufferOutput output = new ArrayBufferOutput();
try {
newDefaultPacker(output).packValue(writeMessagePack(value)).close();
return output.toByteArray();
} catch (Throwable throwable) {
throw new MessagePackMappingException(throwable);
}
}
public static org.msgpack.value.Value writeMessagePack(Value value) {
if (isPrimitive(value)) {
return writePrimitive(asPrimitive(value));
}
switch (value.getType()) {
case ENTITY:
return writeEntity(asEntity(value));
case COLLECTION:
return writeCollectionValue(asCollection(value));
case MAP:
return writeMapValue(asMap(value));
case STRING_PARAMETERS_MAP:
return writeStringParametersValue(asStringParametersMap(value));
}
return newNil();
}
private static org.msgpack.value.Value writePrimitive(Primitive primitive) {
if (Value.isEmpty(primitive)) {
return newNil();
}
switch (primitive.getPrimitiveType()) {
case STRING:
return newString(primitive.getString());
case LONG:
return newInteger(primitive.getLong());
case INT:
return newInteger(primitive.getInt());
case DOUBLE:
return newFloat(primitive.getDouble());
case FLOAT:
return newFloat(primitive.getFloat());
case BOOL:
return newBoolean(primitive.getBool());
case BYTE:
return newBinary(new byte[]{primitive.getByte()});
}
return newNil();
}
private static org.msgpack.value.Value writeCollectionValue(CollectionValue<?> collectionValue) {
if (Value.isEmpty(collectionValue)) {
return newArray();
}
switch (collectionValue.getElementsType()) {
case STRING:
return newArray(collectionValue.getStringList()
.stream()
.filter(CheckerForEmptiness::isNotEmpty)
.map(ValueFactory::newString)
.collect(toList()));
case LONG:
return newArray((collectionValue.getCollectionMode() == PRIMITIVE_ARRAY
? fixedArrayOf(collectionValue.getLongArray())
: collectionValue.getLongList())
.stream()
.filter(CheckerForEmptiness::isNotEmpty)
.map(primitive -> newInteger((Long) primitive))
.collect(toList()));
case DOUBLE:
return newArray((collectionValue.getCollectionMode() == PRIMITIVE_ARRAY
? fixedArrayOf(collectionValue.getDoubleArray())
: collectionValue.getDoubleList())
.stream()
.filter(CheckerForEmptiness::isNotEmpty)
.map(primitive -> newFloat((Double) primitive))
.collect(toList()));
case FLOAT:
return newArray((collectionValue.getCollectionMode() == PRIMITIVE_ARRAY
? fixedArrayOf(collectionValue.getFloatArray())
: collectionValue.getFloatList())
.stream()
.filter(CheckerForEmptiness::isNotEmpty)
.map(primitive -> newFloat((Float) primitive))
.collect(toList()));
case INT:
return newArray((collectionValue.getCollectionMode() == PRIMITIVE_ARRAY
? fixedArrayOf(collectionValue.getIntArray())
: collectionValue.getIntList())
.stream()
.filter(CheckerForEmptiness::isNotEmpty)
.map(primitive -> newInteger((Integer) primitive))
.collect(toList()));
case BOOL:
return newArray((collectionValue.getCollectionMode() == PRIMITIVE_ARRAY
? fixedArrayOf(collectionValue.getBoolArray())
: collectionValue.getBoolList())
.stream()
.filter(CheckerForEmptiness::isNotEmpty)
.map(primitive -> newBoolean((Boolean) primitive))
.collect(toList()));
case BYTE:
if (collectionValue.getCollectionMode() == PRIMITIVE_ARRAY) {
return newBinary(collectionValue.getByteArray());
}
return newArray(collectionValue.getByteList()
.stream()
.filter(CheckerForEmptiness::isNotEmpty)
.map(ValueFactory::newInteger)
.collect(toList()));
case COLLECTION:
return newArray(collectionValue.getCollectionsList()
.stream()
.filter(CheckerForEmptiness::isNotEmpty)
.map(MessagePackEntityWriter::writeCollectionValue)
.collect(toList()));
case ENTITY:
return newArray(collectionValue.getEntityList()
.stream()
.filter(CheckerForEmptiness::isNotEmpty)
.map(MessagePackEntityWriter::writeEntity)
.collect(toList()));
case MAP:
return newArray(collectionValue.getMapValueList()
.stream()
.filter(CheckerForEmptiness::isNotEmpty)
.map(MessagePackEntityWriter::writeMapValue)
.collect(toList()));
case STRING_PARAMETERS_MAP:
return newArray(collectionValue.getStringParametersList()
.stream()
.filter(CheckerForEmptiness::isNotEmpty)
.map(MessagePackEntityWriter::writeMessagePack)
.collect(toList()));
case VALUE:
return newArray(collectionValue.getValueList()
.stream()
.filter(CheckerForEmptiness::isNotEmpty)
.map(MessagePackEntityWriter::writeMessagePack)
.collect(toList()));
}
return emptyArray();
}
private static org.msgpack.value.Value writeEntity(Entity entity) {
if (Value.isEmpty(entity)) {
return emptyMap();
}
MapBuilder mapBuilder = newMapBuilder();
entity.getFields().entrySet().forEach(entry -> writeEntityEntry(mapBuilder, entry));
return mapBuilder.build();
}
private static void writeEntityEntry(MapBuilder mapBuilder, Map.Entry<String, ? extends Value> entry) {
if (isEmpty(entry.getKey()) || isEmpty(entry.getValue())) {
return;
}
Value value = entry.getValue();
switch (value.getType()) {
case STRING:
case INT:
case BOOL:
case LONG:
case BYTE:
case DOUBLE:
case FLOAT:
mapBuilder.put(newString(entry.getKey()), writePrimitive(asPrimitive(value)));
return;
case COLLECTION:
mapBuilder.put(newString(entry.getKey()), writeCollectionValue(asCollection(value)));
return;
case ENTITY:
mapBuilder.put(newString(entry.getKey()), writeEntity(asEntity(value)));
return;
case STRING_PARAMETERS_MAP:
mapBuilder.put(newString(entry.getKey()), writeStringParametersValue(asStringParametersMap(value)));
return;
case MAP:
mapBuilder.put(newString(entry.getKey()), writeMapValue(asMap(value)));
}
}
private static ImmutableMapValue writeStringParametersValue(StringParametersMap value) {
return newMap(asStringParametersMap(value)
.getParameters()
.entrySet()
.stream()
.filter(entry -> isNotEmpty(entry.getValue()))
.collect(toMap(stringEntry -> newString(stringEntry.getKey()), stringEntry -> newString(stringEntry.getValue()))));
}
private static org.msgpack.value.Value writeMapValue(MapValue mapValue) {
if (Value.isEmpty(mapValue)) {
return emptyMap();
}
return newMap(mapValue.getElements().entrySet()
.stream()
.filter(entry -> !Value.isEmpty(entry.getValue()))
.collect(toMap(entry -> writeMessagePack(entry.getKey()), entry -> writeMessagePack(entry.getValue()))));
}
}
| 41.873134 | 131 | 0.571556 |
69b5451bbcc491cd54421814da0002b01461460b
| 144 |
class Test {
<T extends Enum<T>> boolean checkEnum(Class<T> enumClass) {
Class<? extends Enum> my = null;
return my== enumClass;
}
}
| 24 | 61 | 0.638889 |
323041caed9ce4fcb4f77cc08ea0899051eb9296
| 594 |
package com.rbkmoney.adapter.starrys.service.starrys.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Date {
@JsonProperty("Day")
private Integer day;
@JsonProperty("Month")
private Integer month;
@JsonProperty("Year")
private Integer year;
}
| 22.846154 | 61 | 0.784512 |
077830cc97a693446786c878928d569480240844
| 533 |
package io.opensphere.core.image.processor;
import java.util.Map;
/**
* Chained image processor.
*/
public interface ChainedImageProcessor extends ImageProcessor
{
/**
* Adds the next image processor as the next in the chain.
*
* @param processor The next image processor in the chain
*/
void addProcessor(ChainedImageProcessor processor);
/**
* Gets the map of processing properties.
*
* @return The map of processing properties
*/
Map<String, Object> getProperties();
}
| 22.208333 | 62 | 0.677298 |
77d161258dccadf7153af212098eb0f3efdfb139
| 303 |
package com.eventsystem.exceptions;
/**
* Throw when topic name is not available for creation.
*
* @author Ron
* @since 1.0
*/
public class TopicNameUnavailableException extends RuntimeException {
public TopicNameUnavailableException(String name) {
super(name);
}
}
| 20.2 | 70 | 0.683168 |
3e3335ac35baec18c2d50770edce4b262436fb8a
| 24,881 |
/**
* *****************************************************************************
*
* <p>Copyright FUJITSU LIMITED 2018
*
* <p>Creation Date: 2016-05-24
*
* <p>*****************************************************************************
*/
package org.oscm.app.vmware.business;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.oscm.app.v2_0.exceptions.APPlatformException;
import org.oscm.app.vmware.business.Script.OS;
import org.oscm.app.vmware.i18n.Messages;
import org.oscm.app.vmware.remote.vmware.VMwareClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vmware.vim25.CustomFieldDef;
import com.vmware.vim25.GuestInfo;
import com.vmware.vim25.GuestNicInfo;
import com.vmware.vim25.InvalidStateFaultMsg;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.RuntimeFaultFaultMsg;
import com.vmware.vim25.TaskInfo;
import com.vmware.vim25.VimPortType;
import com.vmware.vim25.VirtualDevice;
import com.vmware.vim25.VirtualDisk;
import com.vmware.vim25.VirtualMachineConfigInfo;
import com.vmware.vim25.VirtualMachineConfigSpec;
import com.vmware.vim25.VirtualMachinePowerState;
import com.vmware.vim25.VirtualMachineRuntimeInfo;
import com.vmware.vim25.VirtualMachineSnapshotInfo;
import com.vmware.vim25.VirtualMachineSnapshotTree;
import com.vmware.vim25.VirtualMachineSummary;
public class VM extends Template {
private static final Logger logger = LoggerFactory.getLogger(VM.class);
private static final String GUEST_STATE_RUNNING = "running";
private static final String TOOLS_RUNNING_STATE = "guestToolsRunning";
private ManagedObjectReference vmInstance;
private ManagedObjectReference customFieldsManager;
private VirtualMachineConfigInfo configSpec;
private ManagedObjectReference folder;
private GuestInfo guestInfo;
private String instanceName;
private VirtualMachineSummary virtualMachineSummary;
private VirtualMachineSnapshotInfo virtualMachineSnapshotInfo;
public VM(VMwareClient vmw, String instanceName) throws Exception {
this.vmw = vmw;
this.instanceName = instanceName;
vmInstance = vmw.getServiceUtil().getDecendentMoRef(null, "VirtualMachine", instanceName);
customFieldsManager = vmw.getConnection().getServiceContent().getCustomFieldsManager();
configSpec =
(VirtualMachineConfigInfo) vmw.getServiceUtil().getDynamicProperty(vmInstance, "config");
folder = (ManagedObjectReference) vmw.getServiceUtil().getDynamicProperty(vmInstance, "parent");
guestInfo = (GuestInfo) vmw.getServiceUtil().getDynamicProperty(vmInstance, "guest");
virtualMachineSummary =
(VirtualMachineSummary) vmw.getServiceUtil().getDynamicProperty(vmInstance, "summary");
virtualMachineSnapshotInfo =
(VirtualMachineSnapshotInfo)
vmw.getServiceUtil().getDynamicProperty(vmInstance, "snapshot");
if (vmInstance == null || configSpec == null || folder == null || guestInfo == null) {
logger.warn("failed to retrieve VM");
throw new Exception(
"VM " + instanceName + " does not exist or failed to retrieve information.");
}
}
public String createVmUrl(VMPropertyHandler ph)
throws InvalidStateFaultMsg, RuntimeFaultFaultMsg {
StringBuilder url = new StringBuilder();
url.append("https://");
url.append(ph.getTargetVCenterServer());
url.append(":");
url.append(ph.getVsphereConsolePort());
url.append("/vsphere-client/webconsole.html?vmId=");
url.append(vmInstance.getValue().toString());
url.append("&vmName=");
url.append(configSpec.getName());
url.append("&serverGuid=");
url.append(vmw.getConnection().getServiceContent().getAbout().getInstanceUuid());
url.append("&host=");
url.append(ph.getTargetVCenterServer());
url.append(":443");
url.append("&sessionTicket=");
url.append("cst-VCT");
return url.toString();
}
public List<String> getSnashotsAsList() {
List<String> snapshots = new ArrayList<String>();
if (virtualMachineSnapshotInfo != null) {
List<VirtualMachineSnapshotTree> snap = virtualMachineSnapshotInfo.getRootSnapshotList();
snapshots.addAll(getSnapshots(snap, new ArrayList<String>(), ""));
}
return snapshots;
}
private List<String> getSnapshots(
List<VirtualMachineSnapshotTree> vmst, ArrayList<String> snaps, String indent) {
for (Iterator<VirtualMachineSnapshotTree> iterator = vmst.iterator(); iterator.hasNext(); ) {
VirtualMachineSnapshotTree snap = iterator.next();
snaps.add(indent + "Snapshot: " + snap.getName());
getSnapshots(snap.getChildSnapshotList(), snaps, indent + " ");
}
return snaps;
}
public Integer getGuestMemoryUsage() {
return virtualMachineSummary.getQuickStats().getGuestMemoryUsage();
}
public void setCostumValues(Map<String, String> settings) {
List<CustomFieldDef> fields;
try {
fields =
(List<CustomFieldDef>)
vmw.getServiceUtil().getDynamicProperty(customFieldsManager, "field");
for (CustomFieldDef field : fields) {
if (settings.containsKey(field.getName())) {
vmw.getConnection()
.getService()
.setCustomValue(vmInstance, field.getName(), settings.get(field.getName()));
}
}
} catch (Exception e) {
logger.warn("Failed to set costum value for vm " + vmInstance, e);
}
}
public Integer getOverallCpuUsage() {
return virtualMachineSummary.getQuickStats().getOverallCpuUsage();
}
public Integer getUptimeSeconds() {
return virtualMachineSummary.getQuickStats().getUptimeSeconds();
}
public String getStatus() {
return guestInfo.getGuestState();
}
public String getGuestFullName() {
return configSpec.getGuestFullName();
}
public boolean isLinux() {
String guestid = configSpec.getGuestId();
boolean isLinux =
guestid.startsWith("cent")
|| guestid.startsWith("debian")
|| guestid.startsWith("freebsd")
|| guestid.startsWith("oracle")
|| guestid.startsWith("other24xLinux")
|| guestid.startsWith("other26xLinux")
|| guestid.startsWith("otherLinux")
|| guestid.startsWith("redhat")
|| guestid.startsWith("rhel")
|| guestid.startsWith("sles")
|| guestid.startsWith("suse")
|| guestid.startsWith("ubuntu");
logger.debug(
"instanceName: "
+ instanceName
+ " isLinux: "
+ isLinux
+ " guestid: "
+ configSpec.getGuestId()
+ " OS: "
+ configSpec.getGuestFullName());
return isLinux;
}
public void updateServiceParameter(VMPropertyHandler paramHandler) throws Exception {
logger.debug("instanceName: " + instanceName);
int key = getDataDiskKey();
if (key != -1) {
paramHandler.setDataDiskKey(1, key);
}
if (!paramHandler.isServiceSettingTrue(VMPropertyHandler.TS_IMPORT_EXISTING_VM)
&& !paramHandler.getInstanceName().equals(guestInfo.getHostName())) {
throw new Exception(
"Instancename and hostname do not match. Hostname: "
+ guestInfo.getHostName()
+ " Instancename: "
+ paramHandler.getInstanceName());
}
String targetFolder = (String) vmw.getServiceUtil().getDynamicProperty(folder, "name");
Integer ramMB =
(Integer)
vmw.getServiceUtil().getDynamicProperty(vmInstance, "summary.config.memorySizeMB");
paramHandler.setSetting(VMPropertyHandler.TS_AMOUNT_OF_RAM, ramMB.toString());
paramHandler.setSetting(VMPropertyHandler.TS_NUMBER_OF_CPU, Integer.toString(getNumCPU()));
paramHandler.setSetting(VMPropertyHandler.TS_TARGET_FOLDER, targetFolder);
paramHandler.setSetting(VMPropertyHandler.TS_DISK_SIZE, getDiskSizeInGB(1));
paramHandler.setSetting(
VMPropertyHandler.TS_DATA_DISK_SIZE.replace("#", "1"), getDiskSizeInGB(2));
paramHandler.setSetting(
VMPropertyHandler.TS_NUMBER_OF_NICS, Integer.toString(getNumberOfNICs()));
int i = 1;
List<GuestNicInfo> nicList = guestInfo.getNet();
for (GuestNicInfo info : nicList) {
if (info.getIpAddress() != null && info.getIpAddress().size() > 0) {
paramHandler.setSetting("NIC" + i + "_IP_ADDRESS", info.getIpAddress().get(0));
if (info.getNetwork() != null) {
paramHandler.setSetting("NIC" + i + "_NETWORK_ADAPTER", info.getNetwork());
}
i++;
}
}
}
public OS detectOs() {
if (configSpec.getGuestId().startsWith("win")) {
return OS.WINDOWS;
}
return OS.LINUX;
}
public boolean isRunning() throws Exception {
VirtualMachineRuntimeInfo vmRuntimeInfo =
(VirtualMachineRuntimeInfo) vmw.getServiceUtil().getDynamicProperty(vmInstance, "runtime");
boolean isRunning = false;
if (vmRuntimeInfo != null) {
isRunning = !VirtualMachinePowerState.POWERED_OFF.equals(vmRuntimeInfo.getPowerState());
logger.debug(Boolean.toString(isRunning));
} else {
logger.warn("Failed to retrieve runtime information from VM " + instanceName);
}
return isRunning;
}
public boolean isStopped() throws Exception {
VirtualMachineRuntimeInfo vmRuntimeInfo =
(VirtualMachineRuntimeInfo) vmw.getServiceUtil().getDynamicProperty(vmInstance, "runtime");
if (vmRuntimeInfo != null) {
return VirtualMachinePowerState.POWERED_OFF.equals(vmRuntimeInfo.getPowerState());
}
logger.warn("Failed to retrieve runtime information from VM " + instanceName);
return false;
}
public TaskInfo start() throws Exception {
logger.debug("instanceName: " + instanceName);
ManagedObjectReference startTask =
vmw.getConnection().getService().powerOnVMTask(vmInstance, null);
TaskInfo tInfo = (TaskInfo) vmw.getServiceUtil().getDynamicProperty(startTask, "info");
return tInfo;
}
public TaskInfo stop(boolean forceStop) throws Exception {
logger.debug("instanceName: " + instanceName + " forceStop: " + forceStop);
TaskInfo tInfo = null;
if (forceStop) {
logger.debug("Call vSphere API: powerOffVMTask() instanceName: " + instanceName);
ManagedObjectReference stopTask = vmw.getConnection().getService().powerOffVMTask(vmInstance);
tInfo = (TaskInfo) vmw.getServiceUtil().getDynamicProperty(stopTask, "info");
} else {
if (isRunning()) {
logger.debug("Call vSphere API: shutdownGuest() instanceName: " + instanceName);
vmw.getConnection().getService().shutdownGuest(vmInstance);
}
}
return tInfo;
}
public ManagedObjectReference getFolder() {
return folder;
}
public void runScript(VMPropertyHandler paramHandler) throws Exception {
logger.debug("instanceName: " + instanceName);
String scriptURL = paramHandler.getServiceSetting(VMPropertyHandler.TS_SCRIPT_URL);
Script script = Script.getInstance();
if (scriptURL != null) {
try {
script.initScript(paramHandler, detectOs());
script.execute(vmw, vmInstance);
} catch (Exception e) {
script.setScriptExecuting(false);
throw e;
}
}
}
public void updateLinuxVMPassword(VMPropertyHandler paramHandler) throws Exception {
logger.debug("instanceName: " + instanceName);
String password = paramHandler.getServiceSetting(VMPropertyHandler.TS_LINUX_ROOT_PWD);
String updateScript = VMScript.updateLinuxVMRootPassword(password);
Script script = Script.getInstance();
if (updateScript != null) {
script.initScript(paramHandler, detectOs(), updateScript);
script.execute(vmw, vmInstance);
}
}
public boolean isScriptExecuting() {
Script script = Script.getInstance();
return script.isScriptExecuting();
}
public int getNumberOfNICs() throws Exception {
return NetworkManager.getNumberOfNICs(vmw, vmInstance);
}
public String getNetworkName(int numNic) throws Exception {
return NetworkManager.getNetworkName(vmw, vmInstance, numNic);
}
/**
* Reconfigures VMware instance. Memory, CPU, disk space and network adapter. The VM has been
* created and must be stopped to reconfigure the hardware.
*/
public TaskInfo reconfigureVirtualMachine(VMPropertyHandler paramHandler) throws Exception {
logger.debug("instanceName: " + instanceName);
VimPortType service = vmw.getConnection().getService();
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
vmConfigSpec.setMemoryMB(Long.valueOf(paramHandler.getConfigMemoryMB()));
vmConfigSpec.setNumCPUs(Integer.valueOf(paramHandler.getConfigCPUs()));
String reqUser = paramHandler.getServiceSetting(VMPropertyHandler.REQUESTING_USER);
String comment =
Messages.get(
paramHandler.getLocale(),
"vm_comment",
new Object[] {
paramHandler.getSettings().getOrganizationName(),
paramHandler.getSettings().getSubscriptionId(),
reqUser
});
String annotation = vmConfigSpec.getAnnotation();
comment = updateComment(comment, annotation);
vmConfigSpec.setAnnotation(comment);
DiskManager diskManager = createDiskManager(paramHandler);
diskManager.reconfigureDisks(vmConfigSpec, vmInstance);
configureNetworkAdapter(paramHandler, vmConfigSpec);
logger.debug("Call vSphere API: reconfigVMTask()");
ManagedObjectReference reconfigureTask = service.reconfigVMTask(vmInstance, vmConfigSpec);
return (TaskInfo) vmw.getServiceUtil().getDynamicProperty(reconfigureTask, "info");
}
protected void configureNetworkAdapter(
VMPropertyHandler paramHandler, VirtualMachineConfigSpec vmConfigSpec) throws Exception {
NetworkManager.configureNetworkAdapter(vmw, vmConfigSpec, paramHandler, vmInstance);
}
protected DiskManager createDiskManager(VMPropertyHandler paramHandler) {
return new DiskManager(vmw, paramHandler);
}
public TaskInfo updateCommentField(String comment) throws Exception {
logger.debug("instanceName: " + instanceName + " comment: " + comment);
VimPortType service = vmw.getConnection().getService();
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
String annotation = vmConfigSpec.getAnnotation();
comment = updateComment(comment, annotation);
vmConfigSpec.setAnnotation(comment);
logger.debug("Call vSphere API: reconfigVMTask()");
ManagedObjectReference reconfigureTask = service.reconfigVMTask(vmInstance, vmConfigSpec);
return (TaskInfo) vmw.getServiceUtil().getDynamicProperty(reconfigureTask, "info");
}
String updateComment(String comment, String annotation) {
if (annotation == null) {
annotation = "";
}
Pattern pattern =
Pattern.compile(
".*" + "CT-MG \\{" + "[\\r\\n]+(.*?)[\\r\\n]+" + "\\}" + ".*", Pattern.DOTALL);
Matcher matcher = pattern.matcher(annotation);
if (matcher.find()) {
return annotation.replace(matcher.group(1), comment);
}
if (annotation.trim().length() == 0) {
return "CT-MG {\n".concat(comment).concat("\n}");
}
return annotation.concat("\n").concat("CT-MG {\n").concat(comment).concat("\n}");
}
/**
* Delete VMware instance on vSphere server.
*
* @param vmw connected VMware client entity
* @param instanceId id of the instance
*/
public TaskInfo delete() throws Exception {
logger.debug("Call vSphere API: destroyTask() instanceName: " + instanceName);
ManagedObjectReference startTask = vmw.getConnection().getService().destroyTask(vmInstance);
return (TaskInfo) vmw.getServiceUtil().getDynamicProperty(startTask, "info");
}
boolean arePortgroupsAvailable(VMPropertyHandler properties) {
int numberOfNICs =
Integer.parseInt(properties.getServiceSetting(VMPropertyHandler.TS_NUMBER_OF_NICS));
for (int i = 1; i <= numberOfNICs; i++) {
if (!properties.getPortGroup(i).isEmpty()) {
return true;
}
}
return false;
}
public VMwareGuestSystemStatus getState(VMPropertyHandler properties) throws Exception {
boolean networkCardsConnected = areNetworkCardsConnected();
boolean validHostname = isValidHostname();
boolean validIp = isValidIp(properties);
logger.debug(
String.format(
"getState networkCardsConnected=%s validHostname=%s, validIp=%s",
String.valueOf(networkCardsConnected),
String.valueOf(validHostname),
String.valueOf(validIp)));
if (isLinux()) {
boolean firstStart =
isNotEmpty(guestInfo.getHostName())
&& !validIp
&& guestIsReady()
&& networkCardsConnected;
boolean secondStart = validHostname && validIp && guestIsReady() && networkCardsConnected;
if (firstStart || secondStart) {
logger.debug("firstStart: " + firstStart + " secondStart: " + secondStart);
return VMwareGuestSystemStatus.GUEST_READY;
}
logger.debug(createLogForGetState(validHostname, properties, networkCardsConnected, validIp));
return VMwareGuestSystemStatus.GUEST_NOTREADY;
}
if (validHostname
&& networkCardsConnected
&& (validIp || arePortgroupsAvailable(properties))
&& guestIsReady()) {
return VMwareGuestSystemStatus.GUEST_READY;
}
logger.debug(createLogForGetState(validHostname, properties, networkCardsConnected, validIp));
return VMwareGuestSystemStatus.GUEST_NOTREADY;
}
boolean guestIsReady() {
return (isGuestSystemRunning() && areGuestToolsRunning());
}
String createLogForGetState(
boolean validHostname,
VMPropertyHandler configuration,
boolean isConnected,
boolean validIp) {
StringBuilder sb = new StringBuilder();
sb.append("Guest system is not ready yet ");
sb.append("[");
sb.append("hostname (" + validHostname + ") =" + guestInfo.getHostName() + ", ");
sb.append("ipReady=" + validIp + ", ");
for (int i = 1; i <= configuration.getNumberOfNetworkAdapter(); i++) {
GuestNicInfo info = getNicInfo(configuration, i);
if (info != null) {
sb.append(info.getNetwork() + "=");
sb.append(info.getIpAddress());
sb.append(",");
}
}
sb.append("guestState=" + guestInfo.getGuestState() + ", ");
sb.append("toolsState=" + guestInfo.getToolsStatus() + ", ");
sb.append("toolsRunning=" + guestInfo.getToolsRunningStatus() + ", ");
sb.append("isConnected=" + isConnected);
sb.append("]");
String logStatement = sb.toString();
return logStatement;
}
private boolean isNotEmpty(String validate) {
return validate != null && validate.length() > 0;
}
boolean areGuestToolsRunning() {
return TOOLS_RUNNING_STATE.equals(guestInfo.getToolsRunningStatus());
}
boolean isGuestSystemRunning() {
return GUEST_STATE_RUNNING.equals(guestInfo.getGuestState());
}
boolean areNetworkCardsConnected() {
boolean isConnected = false;
if (guestInfo.getNet() != null && !guestInfo.getNet().isEmpty()) {
isConnected = true;
}
for (GuestNicInfo nicInfo : guestInfo.getNet()) {
isConnected = isConnected && nicInfo.isConnected();
}
return isConnected;
}
boolean isValidHostname() {
String hostname = guestInfo.getHostName();
return hostname != null
&& hostname.length() > 0
&& hostname.toUpperCase().startsWith(instanceName.toUpperCase());
}
boolean isValidIp(VMPropertyHandler configuration) {
for (int i = 1; i <= configuration.getNumberOfNetworkAdapter(); i++) {
GuestNicInfo info = getNicInfo(configuration, i);
if (info == null) {
return false;
}
if (configuration.isAdapterConfiguredManually(i)) {
logger.debug(String.format("Manual configured IP %s", configuration.getIpAddress(i)));
if (!containsIpAddress(info, configuration.getIpAddress(i))) {
return false;
}
} else {
if (!ipAddressExists(info)) {
logger.debug(String.format("GuestInfo for network %s has no IPs", info.getNetwork()));
return false;
}
}
}
return true;
}
GuestNicInfo getNicInfo(VMPropertyHandler configuration, int i) {
if (configuration.getNetworkAdapter(i).isEmpty()) {
logger.debug(String.format("No network adapter %s", i));
return null;
}
logger.debug(String.format("NIC adapter %s", configuration.getNetworkAdapter(i)));
for (GuestNicInfo info : guestInfo.getNet()) {
boolean dhcp = configuration.isAdapterConfiguredByDhcp(i);
logger.debug(
String.format("GuestInfo IP %s dhcp=%s", info.getIpAddress(), String.valueOf(dhcp)));
if (dhcp) {
return info;
}
logger.debug(String.format("GuestNicInfo.getNetwork = %s", info.getNetwork()));
if (configuration.getNetworkAdapter(i).equals(info.getNetwork())) {
return info;
}
}
return null;
}
boolean containsIpAddress(GuestNicInfo info, String address) {
return info.getIpAddress().contains(address);
}
boolean guestInfoContainsNic(String adapter) {
for (GuestNicInfo info : guestInfo.getNet()) {
if (info.getNetwork().equals(adapter)) {
return true;
}
}
return false;
}
boolean ipAddressExists(GuestNicInfo info) {
if (info.getIpAddress().isEmpty()) {
return false;
}
for (String ip : info.getIpAddress()) {
if (ip == null || ip.trim().length() == 0) {
return false;
}
}
return true;
}
public String generateAccessInfo(VMPropertyHandler paramHandler) throws Exception {
VMwareAccessInfo accInfo = new VMwareAccessInfo(paramHandler);
String accessInfo = accInfo.generateAccessInfo(guestInfo);
logger.debug(
"Generated access information for service instance '" + instanceName + "':\n" + accessInfo);
return accessInfo;
}
protected int getDataDiskKey() throws Exception {
List<VirtualDevice> devices = configSpec.getHardware().getDevice();
int countDisks = 0;
int key = -1;
for (VirtualDevice vdInfo : devices) {
if (vdInfo instanceof VirtualDisk) {
countDisks++;
if (countDisks == 2) {
key = ((VirtualDisk) vdInfo).getKey();
break;
}
}
}
return key;
}
protected String getDiskSizeInGB(int disk) throws Exception {
String size = "";
List<VirtualDevice> devices = configSpec.getHardware().getDevice();
int countDisks = 0;
for (VirtualDevice vdInfo : devices) {
if (vdInfo instanceof VirtualDisk) {
countDisks++;
if (countDisks == disk) {
long gigabyte = ((VirtualDisk) vdInfo).getCapacityInKB() / 1024 / 1024;
size = Long.toString(gigabyte);
break;
}
}
}
return size;
}
public String getTotalDiskSizeInMB() throws Exception {
long megabyte = 0;
List<VirtualDevice> devices = configSpec.getHardware().getDevice();
for (VirtualDevice vdInfo : devices) {
if (vdInfo instanceof VirtualDisk) {
megabyte = megabyte + (((VirtualDisk) vdInfo).getCapacityInKB() / 1024);
}
}
return Long.toString(megabyte);
}
public Integer getNumCPU() {
return configSpec.getHardware().getNumCPU();
}
public Integer getCoresPerCPU() {
return configSpec.getHardware().getNumCoresPerSocket();
}
public String getCPUModel(VMPropertyHandler paramHandler) throws Exception {
String datacenter = paramHandler.getTargetDatacenter();
ManagedObjectReference dataCenterRef =
vmw.getServiceUtil().getDecendentMoRef(null, "Datacenter", datacenter);
if (dataCenterRef == null) {
logger.error("Datacenter not found. dataCenter: " + datacenter);
throw new APPlatformException(
Messages.get(
paramHandler.getLocale(), "error_invalid_datacenter", new Object[] {datacenter}));
}
String hostName = paramHandler.getServiceSetting(VMPropertyHandler.TS_TARGET_HOST);
ManagedObjectReference hostRef =
vmw.getServiceUtil().getDecendentMoRef(dataCenterRef, "HostSystem", hostName);
if (hostRef == null) {
logger.error("Target host " + hostName + " not found");
throw new APPlatformException(Messages.getAll("error_invalid_host", new Object[] {hostName}));
}
return (String) vmw.getServiceUtil().getDynamicProperty(hostRef, "summary.hardware.cpuModel");
}
/** @return fully qualified domain name */
public String getFQDN() {
// TODO do not remove method. Please implement, return FQDN
return "";
}
}
| 34.701534 | 100 | 0.680479 |
2d41cab5f5431a25e9149ce508733578ffef6d4a
| 145 |
package com.jdiai.interfaces;
import org.openqa.selenium.By;
import java.util.List;
public interface HasLocators {
List<By> locators();
}
| 14.5 | 30 | 0.744828 |
579a87d3b38ae667c8d239cd2279f53c2b10756f
| 434 |
package uk.dsx.ats.data;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public class FxJSON {
@JsonProperty("base")
public String base;
@JsonProperty("date")
public String date;
@JsonProperty("rates")
public Map<String, BigDecimal> rates;
}
| 21.7 | 61 | 0.753456 |
1c82897179b902c91f3128530590b00506ab07bd
| 3,952 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.ai.textanalytics.implementation.models;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** The set of tasks to execute on the input documents. Cannot specify the same task more than once. */
@Fluent
public final class JobManifestTasks {
/*
* The entityRecognitionTasks property.
*/
@JsonProperty(value = "entityRecognitionTasks")
private List<EntitiesTask> entityRecognitionTasks;
/*
* The entityRecognitionPiiTasks property.
*/
@JsonProperty(value = "entityRecognitionPiiTasks")
private List<PiiTask> entityRecognitionPiiTasks;
/*
* The keyPhraseExtractionTasks property.
*/
@JsonProperty(value = "keyPhraseExtractionTasks")
private List<KeyPhrasesTask> keyPhraseExtractionTasks;
/*
* The entityLinkingTasks property.
*/
@JsonProperty(value = "entityLinkingTasks")
private List<EntityLinkingTask> entityLinkingTasks;
/**
* Get the entityRecognitionTasks property: The entityRecognitionTasks property.
*
* @return the entityRecognitionTasks value.
*/
public List<EntitiesTask> getEntityRecognitionTasks() {
return this.entityRecognitionTasks;
}
/**
* Set the entityRecognitionTasks property: The entityRecognitionTasks property.
*
* @param entityRecognitionTasks the entityRecognitionTasks value to set.
* @return the JobManifestTasks object itself.
*/
public JobManifestTasks setEntityRecognitionTasks(List<EntitiesTask> entityRecognitionTasks) {
this.entityRecognitionTasks = entityRecognitionTasks;
return this;
}
/**
* Get the entityRecognitionPiiTasks property: The entityRecognitionPiiTasks property.
*
* @return the entityRecognitionPiiTasks value.
*/
public List<PiiTask> getEntityRecognitionPiiTasks() {
return this.entityRecognitionPiiTasks;
}
/**
* Set the entityRecognitionPiiTasks property: The entityRecognitionPiiTasks property.
*
* @param entityRecognitionPiiTasks the entityRecognitionPiiTasks value to set.
* @return the JobManifestTasks object itself.
*/
public JobManifestTasks setEntityRecognitionPiiTasks(List<PiiTask> entityRecognitionPiiTasks) {
this.entityRecognitionPiiTasks = entityRecognitionPiiTasks;
return this;
}
/**
* Get the keyPhraseExtractionTasks property: The keyPhraseExtractionTasks property.
*
* @return the keyPhraseExtractionTasks value.
*/
public List<KeyPhrasesTask> getKeyPhraseExtractionTasks() {
return this.keyPhraseExtractionTasks;
}
/**
* Set the keyPhraseExtractionTasks property: The keyPhraseExtractionTasks property.
*
* @param keyPhraseExtractionTasks the keyPhraseExtractionTasks value to set.
* @return the JobManifestTasks object itself.
*/
public JobManifestTasks setKeyPhraseExtractionTasks(List<KeyPhrasesTask> keyPhraseExtractionTasks) {
this.keyPhraseExtractionTasks = keyPhraseExtractionTasks;
return this;
}
/**
* Get the entityLinkingTasks property: The entityLinkingTasks property.
*
* @return the entityLinkingTasks value.
*/
public List<EntityLinkingTask> getEntityLinkingTasks() {
return this.entityLinkingTasks;
}
/**
* Set the entityLinkingTasks property: The entityLinkingTasks property.
*
* @param entityLinkingTasks the entityLinkingTasks value to set.
* @return the JobManifestTasks object itself.
*/
public JobManifestTasks setEntityLinkingTasks(List<EntityLinkingTask> entityLinkingTasks) {
this.entityLinkingTasks = entityLinkingTasks;
return this;
}
}
| 33.491525 | 104 | 0.721913 |
4411b783e252c087df8d8703e4c8c95060174f3e
| 776 |
package murex.dojo.coffeemachine.requests;
import murex.dojo.coffeemachine.DrinkFactory;
import murex.dojo.coffeemachine.requests.IRequest;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TeaRequestTest {
@Test
public void tea_without_sugar() {
IRequest teaRequest = DrinkFactory.getInstance().newTeaRequestBuilder()
.build();
assertEquals(0, teaRequest.getSugarQuantity());
assertEquals("Tea", teaRequest.getDrinkName());
}
@Test
public void tea_with_sugar() {
IRequest teaRequest = DrinkFactory.getInstance().newTeaRequestBuilder()
.withSugar(2)
.build();
assertEquals(2, teaRequest.getSugarQuantity());
assertEquals("Tea", teaRequest.getDrinkName());
}
}
| 25.866667 | 77 | 0.715206 |
3c5b208b0056a69dfd3660a52fd57d02c36e2154
| 492 |
package net.meisen.dissertation.impl.parser.query;
/**
* A {@code Long} used as a value within an interval.
*
* @author pmeisen
*/
public class LongIntervalValue extends BaseIntervalValue<Long> {
/**
* Creates a {@code LongIntervalValue} for the specified {@code value}.
*
* @param value
* the {@code Long} of {@code this}
*/
public LongIntervalValue(final Long value) {
super(value);
}
@Override
public Class<Long> getType() {
return Long.class;
}
}
| 18.923077 | 72 | 0.660569 |
69bb5750c9ee73472a8b775a67598d40e48b329c
| 1,770 |
package search;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
/**
*
* @author exponential-e
* 백준 9489번: 사촌
*
* @see https://www.acmicpc.net/problem/9489
*
*/
public class Boj9489 {
private static final String NEW_LINE = "\n";
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
while(true) {
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
if(N + K == 0) break;
int[] elements = new int[N];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
elements[i] = Integer.parseInt(st.nextToken());
}
sb.append(findCousin(N, K, elements)).append(NEW_LINE);
}
System.out.println(sb.toString());
}
private static int findCousin(int n, int k, int[] e) {
int[] set = new int[n];
int current = -1;
int target = 0;
set[0] = -1;
for (int i = 1; i < n; i++) {
if(e[i] == k) target = i; // find target
if (e[i] - e[i - 1] != 1) current++;
set[i] = current; // make set
}
int count = 0;
if (set[target] != -1) { // target is root
for (int i = 1; i < n; i++) {
if (set[set[i]] == set[set[target]] && set[i] != set[target]) count++; // different parent, same level
}
}
return count;
}
}
| 27.65625 | 123 | 0.494915 |
bc453bdcf1d1af6854db3b33b0156d227ab89ca0
| 313 |
package top.jfunc.common.http.holderrequest;
import top.jfunc.common.http.request.StringBodyRequest;
/**
* 有请求体的请求
* @author xiongshiyan at 2019/5/18 , contact me with email yanshixiong@126.com or phone 15208384257
*/
public interface HolderStringBodyRequest extends HolderHttpRequest, StringBodyRequest {
}
| 28.454545 | 100 | 0.801917 |
d24924fed38fe8848f4ebd7e04543c09973e8f90
| 1,950 |
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.util.Random;
public class Ball extends GameObject {
public Ball(double speed) {
super( new Coordinate(Constants.XRESOLUTION/2+10/2+(new Random().nextDouble()*100),
Constants.YRESOLUTION/2+10/2+(new Random().nextDouble()*100)),
Constants.BALLSIZE,
Constants.BALLSIZE,
new Random().nextDouble()*360,
speed);
setBallShape(getObjectPosition());
}
private void setBallShape(Coordinate position){
setObjectPosition(position);
super.setShape(new Ellipse2D.Double(getObjectPosition().getX(),
getObjectPosition().getY(),
getWidth(),
getHeight()));
}
public void move(long delta){
double newX;
double newY;
newX = Math.toDegrees(Math.cos(Math.toRadians(getMovingAngle())))*(getMovingDistance()/(Constants.SPEEDFACTOR*delta));
newX = newX + getObjectPosition().getX();
newY = - Math.toDegrees(Math.sin(Math.toRadians(getMovingAngle())))*(getMovingDistance()/(Constants.SPEEDFACTOR*delta));
newY = newY + getObjectPosition().getY();
setBallShape(new Coordinate( newX, newY));
}
public void collide(Ball ball, long delta){
double temp = ball.getMovingAngle();
ball.setMovingAngle(getMovingAngle());
setMovingAngle(temp);
//clearing ball from ball
while(checkCollision(ball.getShape())){
ball.move(delta);
move(delta);
}
}
@Override
public void paintMe(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.fillOval((int)getObjectPosition().getX(), (int)getObjectPosition().getY(), (int)getWidth(), (int)getHeight());
}
}
| 34.210526 | 128 | 0.581538 |
7353e2bc7b7177db26bd732bfe06900d31ead398
| 489 |
package com.github.kuangcp.singleton;
/**
* TODO 验证
* @author https://github.com/kuangcp
* @date 2019-05-08 14:26
*/
public class StaticLazyWithSyncBlock {
private static StaticLazyWithSyncBlock singleton;
private StaticLazyWithSyncBlock() {
}
public static StaticLazyWithSyncBlock getInstance() {
synchronized (StaticLazyWithSyncBlock.class) {
if (singleton == null) {
singleton = new StaticLazyWithSyncBlock();
}
}
return singleton;
}
}
| 20.375 | 55 | 0.697342 |
e1d8b20b15bf95aefda463a9c111641b0ea04eff
| 913 |
package io.happycoding.servlets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/names")
public class NamesServlet extends HttpServlet {
List<String> names = new ArrayList<>();
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.getWriter().println("<ul>");
for (String name : names) {
response.getWriter().println("<li>" + name + "</li>");
}
response.getWriter().println("</ul>");
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String name = request.getParameter("name");
names.add(name);
}
}
| 26.085714 | 78 | 0.730559 |
de0fe09357048fc6c88f92355d77d49a20fe061b
| 1,760 |
package com.elasticsearchlogs.api.search.queryBuilderAPI.complexQBFactory.complexQB;
import com.elasticsearchlogs.api.search.queryBuilderAPI.simpleQBFactory.SimpleQBFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import java.util.Iterator;
import java.util.List;
public class BoolMatchQB implements ComplexQB {
/**
* It returns a BoolQueryBuilder based on match queries
*
* @param type The type of the sub queries
* @param fields The fields of the dto
* @param searchTerms The search terms of the dto
* @param strictQuery Unused at the moment, but it aims to implement queries with OR or AND operators
* @return A BoolQueryBuilder made of match queries
* @author cristian
*/
public BoolQueryBuilder getQueryBuilder(final String type,
final List<String> fields,
final List<String> searchTerms,
final boolean strictQuery) {
final BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
Iterator<String> fieldsIterator = fields.iterator();
Iterator<String> searchTermsIterator = searchTerms.iterator();
while (fieldsIterator.hasNext() && searchTermsIterator.hasNext()) {
String field = fieldsIterator.next();
String searchTerm = searchTermsIterator.next();
QueryBuilder query = SimpleQBFactory.getAtomicQB(type, field, searchTerm);
if (strictQuery) boolQuery.must(query);
else boolQuery.should(query);
}
return boolQuery;
}
}
| 39.111111 | 105 | 0.665341 |
7ba7c5994b5886f58959b86a0ad4de9c65318d62
| 7,714 |
package seedu.address.logic.commands;
import static java.util.Objects.requireNonNull;
import static seedu.address.logic.parser.CliSyntax.PREFIX_ASSIGNMENT_DESCRIPTION;
import static seedu.address.logic.parser.CliSyntax.PREFIX_ASSIGNMENT_NAME;
import static seedu.address.logic.parser.CliSyntax.PREFIX_AUTHOR;
import static seedu.address.model.Model.PREDICATE_SHOW_ALL_ASSIGNMENTS;
import java.util.List;
import java.util.Optional;
import seedu.address.commons.core.Messages;
import seedu.address.commons.core.index.Index;
import seedu.address.commons.util.CollectionUtil;
import seedu.address.logic.CommandHistory;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.model.Model;
import seedu.address.model.leaveapplication.Description;
import seedu.address.model.permission.Permission;
import seedu.address.model.person.Name;
import seedu.address.model.project.Assignment;
import seedu.address.model.project.AssignmentName;
/**
* Edits the details of an existing assignment in the address book.
*/
public class EditAssignmentCommand extends Command {
public static final String COMMAND_WORD = "editassignment";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Edits the details of the assignment identified "
+ "by the index number used in the displayed assignment list. "
+ "Existing values will be overwritten by the input values.\n"
+ "Parameters: INDEX (must be a positive integer) "
+ "[" + PREFIX_ASSIGNMENT_NAME + " ASSIGNMENT NAME] "
+ "[" + PREFIX_AUTHOR + " AUTHOR] "
+ "[" + PREFIX_ASSIGNMENT_DESCRIPTION + " DESCRIPTION] \n"
+ "Example: " + COMMAND_WORD + " 1 "
+ PREFIX_ASSIGNMENT_NAME + " OASIS v2 "
+ PREFIX_AUTHOR + " MARY GOSLOW";
public static final String MESSAGE_EDIT_ASSIGNMENT_SUCCESS = "Edited Assignment: %1$s";
public static final String MESSAGE_NOT_EDITED = "At least one field to edit must be provided.";
public static final String MESSAGE_DUPLICATE_ASSIGNMENT = "This assignment already exists in the assignment list.";
private final Index index;
private final EditAssignmentCommand.EditAssignmentDescriptor editAssignmentDescriptor;
/**
* @param index of the assignment in the filtered person list to edit
* @param editAssignmentDescriptor details to edit the person with
*/
public EditAssignmentCommand(Index index, EditAssignmentCommand.EditAssignmentDescriptor editAssignmentDescriptor) {
requireNonNull(index);
requireNonNull(editAssignmentDescriptor);
requiredPermission.addPermissions(Permission.EDIT_ASSIGNMENT);
this.index = index;
this.editAssignmentDescriptor = new EditAssignmentCommand.EditAssignmentDescriptor(editAssignmentDescriptor);
}
@Override
public CommandResult runBody(Model model, CommandHistory history) throws CommandException {
requireNonNull(model);
List<Assignment> lastShownList = model.getFilteredAssignmentList();
if (index.getZeroBased() >= lastShownList.size()) {
throw new CommandException(Messages.MESSAGE_INVALID_ASSIGNMENT_DISPLAYED_INDEX);
}
Assignment assignmentToEdit = lastShownList.get(index.getZeroBased());
Assignment editedAssignment = createEditedAssignment(assignmentToEdit, editAssignmentDescriptor);
if (!assignmentToEdit.isSameAssignment(editedAssignment) && model.hasAssignment(editedAssignment)) {
throw new CommandException(MESSAGE_DUPLICATE_ASSIGNMENT);
}
model.updateAssignment(assignmentToEdit, editedAssignment);
model.updateFilteredAssignmentList(PREDICATE_SHOW_ALL_ASSIGNMENTS);
model.commitAddressBook();
return new CommandResult(String.format(MESSAGE_EDIT_ASSIGNMENT_SUCCESS, editedAssignment));
}
/**
* Creates and returns a {@code Assignment} with the details of {@code assignmentToEdit}
* edited with {@code editAssignmentDescriptor}.
*/
public static Assignment createEditedAssignment(Assignment assignmentToEdit,
EditAssignmentCommand.EditAssignmentDescriptor
editAssignmentDescriptor) {
assert assignmentToEdit != null;
AssignmentName updatedAssignmentName =
editAssignmentDescriptor.getAssignmentName().orElse(assignmentToEdit.getAssignmentName());
Name updatedAuthor = editAssignmentDescriptor.getAuthor().orElse(assignmentToEdit.getAuthor());
Description updatedDescription =
editAssignmentDescriptor.getDescription().orElse(assignmentToEdit.getDescription());
return new Assignment(updatedAssignmentName, updatedAuthor, updatedDescription);
}
@Override
public boolean equals(Object other) {
// short circuit if same object
if (other == this) {
return true;
}
// instanceof handles nulls
if (!(other instanceof EditAssignmentCommand)) {
return false;
}
// state check
EditAssignmentCommand e = (EditAssignmentCommand) other;
return index.equals(e.index)
&& editAssignmentDescriptor.equals(e.editAssignmentDescriptor);
}
/**
* Stores the details to edit the assignment with. Each non-empty field value will replace the
* corresponding field value of the assignment.
*/
public static class EditAssignmentDescriptor {
private AssignmentName assignmentName;
private Name author;
private Description description;
public EditAssignmentDescriptor() {}
/**
* Copy constructor.
* A defensive copy of {@code tags} is used internally.
*/
public EditAssignmentDescriptor(EditAssignmentCommand.EditAssignmentDescriptor toCopy) {
setAssignmentName(toCopy.assignmentName);
setAuthor(toCopy.author);
setDescription(toCopy.description);
}
/**
* Returns true if at least one field is edited.
*/
public boolean isAnyFieldEdited() {
return CollectionUtil.isAnyNonNull(assignmentName, author, description);
}
public void setAssignmentName(AssignmentName name) {
this.assignmentName = name;
}
public Optional<AssignmentName> getAssignmentName() {
return Optional.ofNullable(assignmentName);
}
public void setAuthor(Name author) {
this.author = author;
}
public Optional<Name> getAuthor() {
return Optional.ofNullable(author);
}
public void setDescription(Description description) {
this.description = description;
}
public Optional<Description> getDescription() {
return Optional.ofNullable(description);
}
@Override
public boolean equals(Object other) {
// short circuit if same object
if (other == this) {
return true;
}
// instanceof handles nulls
if (!(other instanceof EditAssignmentCommand.EditAssignmentDescriptor)) {
return false;
}
// state check
EditAssignmentCommand.EditAssignmentDescriptor e = (EditAssignmentCommand.EditAssignmentDescriptor) other;
return getAssignmentName().equals(e.getAssignmentName())
&& getAuthor().equals(e.getAuthor())
&& getDescription().equals(e.getDescription());
}
}
}
| 39.968912 | 120 | 0.682525 |
3db651faa74da9419d45d8840aeb6685278ad351
| 753 |
package com.starter.auth.config;
/**
* @author dingxl
* @date 2/18/2021 12:54 PM
*/
public class AuthConfig {
public static final int CAPTCHA_LENGTH = 4;
public static final int CAPTCHA_DURATION = 60;
public static final String CAPTCHA_CODE = "qwertyuipkjhgfdsazxcvbnmQWERTYUPKJHGFDSAZXCVBNM1234567890";
public static final int SMS_LENGTH = 6;
public static final int SMS_LIFETIME = 60 * 10;
public static final String[] PHONE_WHITE_ARRAY = new String[]{"13800001604", "18611111111"};
public static final String USER_INFO_CACHE_KEY = "user_info";
public static final int USER_INFO_DURATION = 7 * 24 * 3600;
public static final String[] ADMIN_ROLE_CODE_ARRAY = new String[]{UserRole.ADMIN, "platform_admin"};
}
| 35.857143 | 106 | 0.73838 |
8f1489f038ada3f97d8fdcaa0ea3528ca238279f
| 8,183 |
package com.heibaiying;
import javafx.util.Pair;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
import java.util.List;
public class HBaseUtils {
private static Connection connection;
static {
Configuration configuration = HBaseConfiguration.create();
configuration.set("hbase.zookeeper.property.clientPort", "2181");
// 如果是集群 则主机名用逗号分隔
configuration.set("hbase.zookeeper.quorum", "hadoop001");
try {
connection = ConnectionFactory.createConnection(configuration);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 创建HBase表
*
* @param tableName 表名
* @param columnFamilies 列族的数组
*/
public static boolean createTable(String tableName, List<String> columnFamilies) {
try {
HBaseAdmin admin = (HBaseAdmin) connection.getAdmin();
if (admin.tableExists(TableName.valueOf(tableName))) {
return false;
}
TableDescriptorBuilder tableDescriptor = TableDescriptorBuilder.newBuilder(TableName.valueOf(tableName));
columnFamilies.forEach(columnFamily -> {
ColumnFamilyDescriptorBuilder cfDescriptorBuilder = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(columnFamily));
cfDescriptorBuilder.setMaxVersions(1);
ColumnFamilyDescriptor familyDescriptor = cfDescriptorBuilder.build();
tableDescriptor.setColumnFamily(familyDescriptor);
});
admin.createTable(tableDescriptor.build());
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
/**
* 删除hBase表
*
* @param tableName 表名
*/
public static boolean deleteTable(String tableName) {
try {
HBaseAdmin admin = (HBaseAdmin) connection.getAdmin();
// 删除表前需要先禁用表
admin.disableTable(TableName.valueOf(tableName));
admin.deleteTable(TableName.valueOf(tableName));
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/**
* 插入数据
*
* @param tableName 表名
* @param rowKey 唯一标识
* @param columnFamilyName 列族名
* @param qualifier 列标识
* @param value 数据
*/
public static boolean putRow(String tableName, String rowKey, String columnFamilyName, String qualifier,
String value) {
try {
Table table = connection.getTable(TableName.valueOf(tableName));
Put put = new Put(Bytes.toBytes(rowKey));
put.addColumn(Bytes.toBytes(columnFamilyName), Bytes.toBytes(qualifier), Bytes.toBytes(value));
table.put(put);
table.close();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
/**
* 插入数据
*
* @param tableName 表名
* @param rowKey 唯一标识
* @param columnFamilyName 列族名
* @param pairList 列标识和值的集合
*/
public static boolean putRow(String tableName, String rowKey, String columnFamilyName, List<Pair<String, String>> pairList) {
try {
Table table = connection.getTable(TableName.valueOf(tableName));
Put put = new Put(Bytes.toBytes(rowKey));
pairList.forEach(pair -> put.addColumn(Bytes.toBytes(columnFamilyName), Bytes.toBytes(pair.getKey()), Bytes.toBytes(pair.getValue())));
table.put(put);
table.close();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
/**
* 根据rowKey获取指定行的数据
*
* @param tableName 表名
* @param rowKey 唯一标识
*/
public static Result getRow(String tableName, String rowKey) {
try {
Table table = connection.getTable(TableName.valueOf(tableName));
Get get = new Get(Bytes.toBytes(rowKey));
return table.get(get);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取指定行指定列(cell)的最新版本的数据
*
* @param tableName 表名
* @param rowKey 唯一标识
* @param columnFamily 列族
* @param qualifier 列标识
*/
public static String getCell(String tableName, String rowKey, String columnFamily, String qualifier) {
try {
Table table = connection.getTable(TableName.valueOf(tableName));
Get get = new Get(Bytes.toBytes(rowKey));
if (!get.isCheckExistenceOnly()) {
get.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(qualifier));
Result result = table.get(get);
byte[] resultValue = result.getValue(Bytes.toBytes(columnFamily), Bytes.toBytes(qualifier));
return Bytes.toString(resultValue);
} else {
return null;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 检索全表
*
* @param tableName 表名
*/
public static ResultScanner getScanner(String tableName) {
try {
Table table = connection.getTable(TableName.valueOf(tableName));
Scan scan = new Scan();
return table.getScanner(scan);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 检索表中指定数据
*
* @param tableName 表名
* @param filterList 过滤器
*/
public static ResultScanner getScanner(String tableName, FilterList filterList) {
try {
Table table = connection.getTable(TableName.valueOf(tableName));
Scan scan = new Scan();
scan.setFilter(filterList);
return table.getScanner(scan);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 检索表中指定数据
*
* @param tableName 表名
* @param startRowKey 起始RowKey
* @param endRowKey 终止RowKey
* @param filterList 过滤器
*/
public static ResultScanner getScanner(String tableName, String startRowKey, String endRowKey,
FilterList filterList) {
try {
Table table = connection.getTable(TableName.valueOf(tableName));
Scan scan = new Scan();
scan.withStartRow(Bytes.toBytes(startRowKey));
scan.withStopRow(Bytes.toBytes(endRowKey));
scan.setFilter(filterList);
return table.getScanner(scan);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 删除指定行记录
*
* @param tableName 表名
* @param rowKey 唯一标识
*/
public static boolean deleteRow(String tableName, String rowKey) {
try {
Table table = connection.getTable(TableName.valueOf(tableName));
Delete delete = new Delete(Bytes.toBytes(rowKey));
table.delete(delete);
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
/**
* 删除指定行指定列
*
* @param tableName 表名
* @param rowKey 唯一标识
* @param familyName 列族
* @param qualifier 列标识
*/
public static boolean deleteColumn(String tableName, String rowKey, String familyName,
String qualifier) {
try {
Table table = connection.getTable(TableName.valueOf(tableName));
Delete delete = new Delete(Bytes.toBytes(rowKey));
delete.addColumn(Bytes.toBytes(familyName), Bytes.toBytes(qualifier));
table.delete(delete);
table.close();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
| 30.64794 | 147 | 0.575461 |
c0c7939aff9e80f3844cee10c747d207c4aafe05
| 2,864 |
package com.canmeizhexue.javademo.utils.signature;
import com.canmeizhexue.javademo.utils.Base64;
import com.canmeizhexue.javademo.utils.encryption.HexUtils;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**数字签名算法(带有公钥私钥的消息摘要算法),私钥签名,公钥验证
* 主要有MD和SHA俩类
* <p>
* 算法 密钥长度 默认 签名长度 实现方
* MD2WithRSA、 512--65536(64整数倍) 1024 与密钥长度相同 JDK
* MD5WithRSA 同上 1024 同上
*
*
* SHA256withRSA 同上 2048 同上 Bouncy Castle
*
*
* </p>
* Created by canmeizhexue on 2016/9/6.
*/
public class RSAUtil{
private static String charset_utf8 = "utf-8";
public static void main(String[] args){
jdkRSA("公共",charset_utf8);
}
public static void jdkRSA(String source,String charset){
try {
//初始化密钥
KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
keyGenerator.initialize(512);
KeyPair keyPair = keyGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
System.out.println("Public key :" + Base64.encodeBytes(rsaPublicKey.getEncoded()));
System.out.println("private key : " + Base64.encodeBytes(rsaPrivateKey.getEncoded()));
//执行签名
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey=keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Signature signature = Signature.getInstance("MD5withRSA");
signature.initSign(privateKey);
signature.update(source.getBytes(charset));
byte[] result = signature.sign();
System.out.println("jdk rsa sign: "+ HexUtils.encodeHexStr(result));
//验证签名
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey=keyFactory.generatePublic(x509EncodedKeySpec);
signature = Signature.getInstance("MD5withRSA");
signature.initVerify(publicKey);
signature.update(source.getBytes(charset));
boolean bool=signature.verify(result);
System.out.println("jdk verify result :"+bool);
}catch (Exception e){
e.printStackTrace();
}
}
}
| 39.777778 | 115 | 0.616969 |
4bb0de8311fbfe1f324f69fd8651c5f2b9f23e31
| 2,907 |
package com.atlassian.jira.plugins.dvcs.webwork;
import com.atlassian.event.api.EventPublisher;
import com.atlassian.jira.plugins.dvcs.exception.SourceControlException;
import com.atlassian.jira.plugins.dvcs.model.Organization;
import com.atlassian.jira.plugins.dvcs.service.OrganizationService;
import com.atlassian.jira.plugins.dvcs.service.RepositoryService;
import com.atlassian.jira.plugins.dvcs.util.CustomStringUtils;
import com.atlassian.jira.security.xsrf.RequiresXsrfCheck;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class RegenerateOauthTokenAction extends CommonDvcsConfigurationAction
{
private final Logger log = LoggerFactory.getLogger(RegenerateOauthTokenAction.class);
protected String organization; // in the meaning of id TODO rename to organizationId
protected final OrganizationService organizationService;
protected final RepositoryService repositoryService;
public RegenerateOauthTokenAction(EventPublisher eventPublisher,
OrganizationService organizationService, RepositoryService repositoryService)
{
super(eventPublisher);
this.organizationService = organizationService;
this.repositoryService = repositoryService;
}
@Override
@RequiresXsrfCheck
protected String doExecute() throws Exception
{
return redirectUserToGrantAccess();
}
protected abstract String redirectUserToGrantAccess();
public String doFinish()
{
return doChangeAccessToken();
}
protected abstract String getAccessToken();
private String doChangeAccessToken()
{
try
{
String accessToken = getAccessToken();
organizationService.updateCredentialsAccessToken(Integer.parseInt(organization), accessToken);
} catch (SourceControlException e)
{
addErrorMessage("Cannot regenerate OAuth access token: [" + e.getMessage() + "]");
log.debug("Cannot regenerate OAuth access token: [" + e.getMessage() + "]");
return INPUT;
}
// refreshing list of repositories after regenerating OAuth access token
Organization org = organizationService.get(Integer.parseInt(organization), false);
try
{
repositoryService.syncRepositoryList(org);
} catch (SourceControlException e)
{
log.error("Could not refresh repository list", e);
}
return getRedirect("ConfigureDvcsOrganizations.jspa?atl_token=" + CustomStringUtils.encode(getXsrfToken()));
}
public String getOrganizationName()
{
return organizationService.get(Integer.parseInt(organization),false).getName();
}
public String getOrganization()
{
return organization;
}
public void setOrganization(String organization)
{
this.organization = organization;
}
}
| 32.662921 | 116 | 0.71689 |
ce06b2a9ae54b7131acc8af1af5843c8e281b611
| 311 |
package aimax.osm.data;
import java.io.InputStream;
/**
* Provides a stream with OSM map data describing the city of Ulm.
* @author Ruediger Lunde
*/
public class DataResource {
public static InputStream getULMFileResource() {
return DataResource.class.getResourceAsStream("ulm.osm");
}
}
| 22.214286 | 67 | 0.720257 |
f466f61b9f52f54c8f26b04fb5818d791d7a2e93
| 7,456 |
package it.nextworks.tmf_offering_catalog.information_models.resource;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import it.nextworks.tmf_offering_catalog.information_models.common.TimePeriod;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.validation.annotation.Validated;
import javax.persistence.*;
import javax.validation.Valid;
/**
* A migration, substitution, dependency or exclusivity relationship between/among resource specifications.
*/
@ApiModel(description = "A migration, substitution, dependency or exclusivity relationship between/among resource specifications.")
@Validated
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2021-02-10T10:00:31.056Z")
@Entity
@Table(name = "resource_spec_relationships")
public class ResourceSpecRelationship {
@JsonProperty("@baseType")
@Column(name = "base_type")
private String baseType = null;
@JsonProperty("@type")
private String type = null;
@JsonProperty("href")
private String href = null;
@JsonProperty("id")
private String id = null;
@JsonProperty("name")
private String name = null;
@JsonProperty("relationshipType")
@Column(name = "relationship_type")
private String relationshipType = null;
@JsonProperty("role")
private String role = null;
@JsonIgnore
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String uuid = null;
@JsonProperty("validFor")
@Column(name = "valid_for")
@Embedded
private TimePeriod validFor = null;
public ResourceSpecRelationship baseType(String baseType) {
this.baseType = baseType;
return this;
}
/**
* Get baseType
* @return baseType
**/
@ApiModelProperty(value = "")
public String getBaseType() {
return baseType;
}
public void setBaseType(String baseType) {
this.baseType = baseType;
}
public ResourceSpecRelationship type(String type) {
this.type = type;
return this;
}
/**
* Type of relationship such as migration, substitution, dependency, exclusivity
* @return type
**/
@ApiModelProperty(value = "Type of relationship such as migration, substitution, dependency, exclusivity")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public ResourceSpecRelationship href(String href) {
this.href = href;
return this;
}
/**
* Reference of the target ResourceSpecification
* @return href
**/
@ApiModelProperty(value = "Reference of the target ResourceSpecification")
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public ResourceSpecRelationship id(String id) {
this.id = id;
return this;
}
/**
* Unique identifier of target ResourceSpecification
* @return id
**/
@ApiModelProperty(value = "Unique identifier of target ResourceSpecification")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public ResourceSpecRelationship name(String name) {
this.name = name;
return this;
}
/**
* The name given to the target resource specification instance
* @return name
**/
@ApiModelProperty(value = "The name given to the target resource specification instance")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ResourceSpecRelationship relationshipType(String relationshipType) {
this.relationshipType = relationshipType;
return this;
}
/**
* Get relationshipType
* @return relationshipType
**/
@ApiModelProperty(value = "")
public String getRelationshipType() {
return relationshipType;
}
public void setRelationshipType(String relationshipType) {
this.relationshipType = relationshipType;
}
public ResourceSpecRelationship role(String role) {
this.role = role;
return this;
}
/**
* The association role for this resource specification
* @return role
**/
@ApiModelProperty(value = "The association role for this resource specification")
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public ResourceSpecRelationship uuid(String uuid) {
this.uuid = uuid;
return this;
}
/**
* Get uuid
* @return uuid
**/
@ApiModelProperty(value = "")
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public ResourceSpecRelationship validFor(TimePeriod validFor) {
this.validFor = validFor;
return this;
}
/**
* The period for which the ResourceSpecRelationship is valid
* @return validFor
**/
@ApiModelProperty(value = "The period for which the ResourceSpecRelationship is valid")
@Valid
public TimePeriod getValidFor() {
return validFor;
}
public void setValidFor(TimePeriod validFor) {
this.validFor = validFor;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ResourceSpecRelationship resourceSpecRelationship = (ResourceSpecRelationship) o;
return Objects.equals(this.baseType, resourceSpecRelationship.baseType) &&
Objects.equals(this.type, resourceSpecRelationship.type) &&
Objects.equals(this.href, resourceSpecRelationship.href) &&
Objects.equals(this.id, resourceSpecRelationship.id) &&
Objects.equals(this.name, resourceSpecRelationship.name) &&
Objects.equals(this.relationshipType, resourceSpecRelationship.relationshipType) &&
Objects.equals(this.role, resourceSpecRelationship.role) &&
Objects.equals(this.uuid, resourceSpecRelationship.uuid) &&
Objects.equals(this.validFor, resourceSpecRelationship.validFor);
}
@Override
public int hashCode() {
return Objects.hash(baseType, type, href, id, name, relationshipType, role, uuid, validFor);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ResourceSpecRelationship {\n");
sb.append(" baseType: ").append(toIndentedString(baseType)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" href: ").append(toIndentedString(href)).append("\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" relationshipType: ").append(toIndentedString(relationshipType)).append("\n");
sb.append(" role: ").append(toIndentedString(role)).append("\n");
sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n");
sb.append(" validFor: ").append(toIndentedString(validFor)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 25.104377 | 131 | 0.692194 |
ad6dc5b02f7680874508c694e29a4289a9778e27
| 3,857 |
package uk.ac.ox.well.cortexjdk.utils.alignment.intervalcombiner;
import htsjdk.samtools.util.Interval;
import htsjdk.samtools.util.IntervalTreeMap;
import org.apache.commons.math3.util.Pair;
import uk.ac.ox.well.cortexjdk.utils.alignment.reference.IndexedReference;
import uk.ac.ox.well.cortexjdk.utils.traversal.CortexVertex;
import java.util.*;
public class IntervalCombiner {
private IntervalCombiner() {}
public static List<Pair<String, Interval>> getIntervals(List<CortexVertex> ws, Map<String, IndexedReference> refs, int locationWindow, int maxStatesPerBackground) {
Map<String, IntervalTreeMap<Interval>> itm = new HashMap<>();
for (String name : refs.keySet()) {
itm.put(name, new IntervalTreeMap<>());
for (int i = 0; i < ws.size(); i++) {
CortexVertex cv = ws.get(i);
for (Interval it : refs.get(name).find(cv.getKmerAsString())) {
Interval pit = new Interval(it.getContig(), it.getStart() - locationWindow, it.getEnd() + locationWindow, it.isNegativeStrand(), it.getName());
if (itm.get(name).containsOverlapping(pit) || itm.get(name).containsContained(pit)) {
int newStart = pit.getStart();
int newEnd = pit.getEnd();
Set<Interval> toRemove = new HashSet<>();
for (Collection<Interval> intervals : Arrays.asList(itm.get(name).getOverlapping(pit), itm.get(name).getContained(pit))) {
for (Interval oit : intervals) {
if (pit.isNegativeStrand() == oit.isNegativeStrand()) {
if (oit.getStart() < newStart) {
newStart = oit.getStart();
}
if (oit.getEnd() > newEnd) {
newEnd = oit.getEnd();
}
toRemove.add(oit);
}
}
}
pit = new Interval(it.getContig(), newStart, newEnd, it.isNegativeStrand(), it.getName());
for (Interval rit : toRemove) {
itm.get(name).remove(rit);
}
}
itm.get(name).put(pit, pit);
}
}
}
List<Pair<String, Interval>> allStates = new ArrayList<>();
for (String s : itm.keySet()) {
Set<Interval> sortedStates = new TreeSet<>(Comparator.comparingInt(Interval::length).reversed());
for (Interval it : itm.get(s).values()) {
if (it.getStart() < 0) {
it = new Interval(it.getContig(), 1, it.getEnd(), it.isNegativeStrand(), it.getName());
}
int maxLength = refs.get(s).getReferenceSequence().getSequenceDictionary().getSequence(it.getContig()).getSequenceLength();
if (it.getEnd() >= maxLength) {
it = new Interval(it.getContig(), it.getStart(), maxLength - 1, it.isNegativeStrand(), it.getName());
}
//String seq = refs.get(s).find(it);
//String targetName = s + ":" + it.getContig() + ":" + it.getStart() + "-" + it.getEnd() + ":" + (it.isPositiveStrand() ? "+" : "-");
//targets.put(targetName, seq);
sortedStates.add(it);
}
Iterator<Interval> it = sortedStates.iterator();
for (int i = 0; i < maxStatesPerBackground && it.hasNext(); i++) {
allStates.add(new Pair<>(s, it.next()));
}
}
return allStates;
}
}
| 43.829545 | 168 | 0.501945 |
d525ca4d4e819ba20a98cf834df999d178640cf4
| 9,305 |
/*
* MIT License
*
* Copyright (c) 2016 Hossain Khan
*
* 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 info.hossainkhan.dailynewsheadlines.details;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v17.leanback.app.DetailsFragment;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.ClassPresenterSelector;
import android.support.v17.leanback.widget.DetailsOverviewRow;
import android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter;
import android.support.v17.leanback.widget.FullWidthDetailsOverviewSharedElementHelper;
import android.support.v17.leanback.widget.ListRow;
import android.support.v17.leanback.widget.ListRowPresenter;
import android.support.v17.leanback.widget.RowPresenter;
import android.view.View;
import android.view.ViewGroup;
import com.squareup.picasso.Picasso;
import info.hossainkhan.android.core.CoreApplication;
import info.hossainkhan.android.core.headlines.HeadlinesDetailsContract;
import info.hossainkhan.android.core.headlines.HeadlinesDetailsViewPresenter;
import info.hossainkhan.android.core.model.NewsHeadlineItem;
import info.hossainkhan.android.core.util.ActivityUtils;
import info.hossainkhan.dailynewsheadlines.R;
import info.hossainkhan.dailynewsheadlines.cards.CardListRow;
import info.hossainkhan.dailynewsheadlines.details.listeners.DetailsViewInteractionListener;
import info.hossainkhan.dailynewsheadlines.utils.PicassoBackgroundManager;
import info.hossainkhan.dailynewsheadlines.utils.PicassoImageTargetDetailsOverview;
import timber.log.Timber;
/**
* Displays a card with more details using a {@link DetailsFragment}.
*/
public class HeadlinesDetailsFragment extends DetailsFragment implements HeadlinesDetailsContract.View {
/**
* Unique screen name used for reporting and analytics.
*/
private static final String ANALYTICS_SCREEN_NAME = "headline_details";
private ArrayObjectAdapter mRowsAdapter;
private Context mApplicationContext;
private HeadlinesDetailsActivity mAttachedHeadlinesActivity;
private PicassoBackgroundManager mPicassoBackgroundManager;
private PicassoImageTargetDetailsOverview mDetailsRowPicassoTarget;
private HeadlinesDetailsViewPresenter mPresenter;
private DetailsOverviewRow mDetailsOverview;
@Override
public void onAttach(final Context context) {
super.onAttach(context);
Timber.d("onAttach() called with: context = [" + context + "]");
mAttachedHeadlinesActivity = (HeadlinesDetailsActivity) context;
mApplicationContext = getActivity().getApplicationContext();
}
@Override
public void onAttach(final Activity activity) {
super.onAttach(activity);
Timber.d("onAttach() called with: Activity = [%s]", activity);
// Note, this callback is used in lower API, otherwise "onAttach(final Context)" is used
if (mAttachedHeadlinesActivity == null) {
mAttachedHeadlinesActivity = (HeadlinesDetailsActivity) activity;
mApplicationContext = activity.getApplicationContext();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
NewsHeadlineItem newsHeadlineItem = mAttachedHeadlinesActivity.getCardItem();
mPicassoBackgroundManager = new PicassoBackgroundManager(mAttachedHeadlinesActivity);
mPresenter = new HeadlinesDetailsViewPresenter(mApplicationContext, this, newsHeadlineItem);
DetailsViewInteractionListener listener = new DetailsViewInteractionListener(mPresenter);
setupEventListeners(listener);
}
@Override
public void onStart() {
super.onStart();
CoreApplication.getAnalyticsReporter().reportScreenLoadedEvent(ANALYTICS_SCREEN_NAME);
}
@Override
public void onDestroy() {
super.onDestroy();
mPresenter.detachView();
if (null != mPicassoBackgroundManager) {
Timber.d("onDestroy: " + mPicassoBackgroundManager.toString());
mPicassoBackgroundManager.destroy();
}
}
private void setupEventListeners(final DetailsViewInteractionListener listener) {
setOnItemViewSelectedListener(listener);
setOnItemViewClickedListener(listener);
}
@Override
public void showHeadlineDetails(final NewsHeadlineItem newsHeadlineItem) {
FullWidthDetailsOverviewRowPresenter rowPresenter = new FullWidthDetailsOverviewRowPresenter(
new HeadlinesDetailsPresenter(getActivity())) {
@Override
protected RowPresenter.ViewHolder createRowViewHolder(ViewGroup parent) {
// Customize Actionbar and Content by using custom colors.
RowPresenter.ViewHolder viewHolder = super.createRowViewHolder(parent);
View actionsView = viewHolder.view.
findViewById(R.id.details_overview_actions_background);
actionsView.setBackgroundColor(getActivity().getResources().
getColor(R.color.detail_view_actionbar_background));
View detailsView = viewHolder.view.findViewById(R.id.details_frame);
detailsView.setBackgroundColor(
getResources().getColor(R.color.detail_view_background));
return viewHolder;
}
};
FullWidthDetailsOverviewSharedElementHelper mHelper = new FullWidthDetailsOverviewSharedElementHelper();
mHelper.setSharedElementEnterTransition(getActivity(), getString(R.string.shared_transition_key_item_thumbnail));
rowPresenter.setListener(mHelper);
rowPresenter.setParticipatingEntranceTransition(false);
prepareEntranceTransition();
ListRowPresenter shadowDisabledRowPresenter = new ListRowPresenter();
shadowDisabledRowPresenter.setShadowEnabled(false);
// Setup PresenterSelector to distinguish between the different rows.
ClassPresenterSelector rowPresenterSelector = new ClassPresenterSelector();
rowPresenterSelector.addClassPresenter(DetailsOverviewRow.class, rowPresenter);
rowPresenterSelector.addClassPresenter(CardListRow.class, shadowDisabledRowPresenter);
rowPresenterSelector.addClassPresenter(ListRow.class, new ListRowPresenter());
mRowsAdapter = new ArrayObjectAdapter(rowPresenterSelector);
// Setup action and detail row.
mDetailsOverview = new DetailsOverviewRow(newsHeadlineItem);
// DEV NOTE: Without the image drawable, the details view occupies full width for texts.
mDetailsOverview.setImageDrawable(getResources().getDrawable(R.drawable.placeholder_loading_image));
mRowsAdapter.add(mDetailsOverview);
setAdapter(mRowsAdapter);
// NOTE: Move this when data is loaded
startEntranceTransition();
}
@Override
public void loadDetailsImage(final String imageUrl) {
mDetailsRowPicassoTarget = new PicassoImageTargetDetailsOverview(mApplicationContext, mDetailsOverview);
Picasso.with(mApplicationContext)
.load(imageUrl)
.into(mDetailsRowPicassoTarget);
mPicassoBackgroundManager.updateBackgroundWithDelay(
imageUrl,
PicassoBackgroundManager.TransformType.GREYSCALE);
}
@Override
public void loadDefaultImage() {
mPicassoBackgroundManager.updateBackgroundWithDelay();
}
@Override
public void updateScreenTitle(final String title) {
setTitle(title);
}
@Override
public void openArticleWebUrl(final String contentUrl) {
Intent intent = ActivityUtils.provideOpenWebUrlIntent(contentUrl);
if (intent.resolveActivity(mApplicationContext.getPackageManager()) != null) {
mApplicationContext.startActivity(intent);
} else {
String logMsg = "App does not have browser to show URL: %s.";
Timber.w(logMsg, contentUrl);
// NOTE: According to Google's guideline and test case "TV-WB", tv app
// should not assume browser availability.
}
}
}
| 42.488584 | 121 | 0.740677 |
232c81edf7ce9b32407567d1f1a678e6ef9649ed
| 2,188 |
package krpc.rpc.web;
import java.util.Map;
public class WebUrl {
String hosts;
String path;
String methods;
int serviceId;
int msgId;
int sessionMode = WebRoute.SESSION_MODE_NO;
WebPlugins plugins;
Map<String, String> attrs;
String origins;
public WebUrl(String hosts, String path) {
this.hosts = hosts;
this.path = path;
}
public WebUrl(String hosts, String path, String methods, int serviceId, int msgId) {
this.hosts = hosts;
this.path = path;
this.methods = methods.toLowerCase();
this.serviceId = serviceId;
this.msgId = msgId;
}
public String getPath() {
return path;
}
public WebUrl setPath(String path) {
this.path = path;
return this;
}
public int getServiceId() {
return serviceId;
}
public WebUrl setServiceId(int serviceId) {
this.serviceId = serviceId;
return this;
}
public int getMsgId() {
return msgId;
}
public WebUrl setMsgId(int msgId) {
this.msgId = msgId;
return this;
}
public int getSessionMode() {
return sessionMode;
}
public WebUrl setSessionMode(int sessionMode) {
this.sessionMode = sessionMode;
return this;
}
public String getHosts() {
return hosts;
}
public WebUrl setHosts(String hosts) {
this.hosts = hosts;
return this;
}
public String getMethods() {
return methods;
}
public WebUrl setMethods(String methods) {
this.methods = methods;
return this;
}
public WebPlugins getPlugins() {
return plugins;
}
public WebUrl setPlugins(WebPlugins plugins) {
this.plugins = plugins;
return this;
}
public Map<String, String> getAttrs() {
return attrs;
}
public WebUrl setAttrs(Map<String, String> attrs) {
this.attrs = attrs;
return this;
}
public String getOrigins() {
return origins;
}
public WebUrl setOrigins(String origins) {
this.origins = origins;
return this;
}
}
| 19.711712 | 88 | 0.585009 |
40d99e3204e3703deb4a5aa069673dea2327c40f
| 4,026 |
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package com.cloud.network.bigswitch;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.SerializedName;
/**
* AttachmentData contains information expected by Big Switch Controller
* in CreateBcfAttachmentCommand
*/
public class AttachmentData {
@SerializedName("port") final private Attachment attachment;
public Attachment getAttachment() {
return this.attachment;
}
public AttachmentData() {
this.attachment = new Attachment();
}
public class Attachment {
@SerializedName("id") private String id;
@SerializedName("tenant_name") private String tenantName;
@SerializedName("vlan") private Integer vlan;
@SerializedName("fixed_ips") final private List<IpAddress> fixedIps;
@SerializedName("mac_address") private String macAddress;
@SerializedName("bound_segment") final private BoundSegment boundSegment;
@SerializedName("binding:host_id") private String hostId;
public Attachment(){
this.boundSegment = new BoundSegment();
this.fixedIps = new ArrayList<IpAddress>();
}
public class BoundSegment {
@SerializedName("segmentation_id") private Integer segmentationId;
public Integer getSegmentationId() {
return segmentationId;
}
public void setSegmentationId(Integer segmentationId) {
this.segmentationId = segmentationId;
}
}
public class IpAddress {
@SerializedName("ip_address") private String address;
public IpAddress(final String ipAddr) {
this.address = ipAddr;
}
public String getIpAddress(){
return address;
}
}
private String state;
public String getTenantName() {
return tenantName;
}
public void setTenantName(final String tenantName) {
this.tenantName = tenantName;
}
public String getId() {
return id;
}
public void setId(final String id) {
this.id = id;
}
public String getHostId() {
return hostId;
}
public void setHostId(final String hostId) {
this.hostId = hostId;
}
public Integer getVlan() {
return vlan;
}
public void setVlan(final Integer vlan) {
this.vlan = vlan;
this.boundSegment.setSegmentationId(vlan);
}
public List<IpAddress> getIpv4List() {
return fixedIps;
}
public void addIpv4(final String ipv4) {
this.fixedIps.add(new IpAddress(ipv4));
}
public String getMac() {
return macAddress;
}
public void setMac(final String mac) {
this.macAddress = mac;
}
public BoundSegment getBoundSegment() {
return boundSegment;
}
public String getState() {
return state;
}
public void setState(final String state) {
this.state = state;
}
}
}
| 27.958333 | 81 | 0.615251 |
7447127a72f16ff6f08168922519d677021b0462
| 404 |
package dk.hoejgaard.openapi.diff.output;
import dk.hoejgaard.openapi.diff.APIDiff;
/**
* Renders the output from an API difference report into a given format
*/
interface OutputRender {
/**
* @param diff the difference report containing the comparison between the existing and the future candidate API
* @return a complete rendered report
*/
String render(APIDiff diff);
}
| 22.444444 | 116 | 0.725248 |
d6d10bc634ec776b5fe8c3c0d04c228e0850bf83
| 740 |
import java.util.*;
class Solution {
void solve(int open, int close , String op,ArrayList res)
{
if(open==0 && close==0)
{
res.add(op);
return;
}
if(open!=0)
{
String op1=op+"(";
// open--;
solve(open-1,close,op1,res);
}
if(close>open)
{
String op2=op+")";
// close--;
solve(open,close-1,op2,res);
}
return ;
}
public List<String> generateParenthesis(int n) {
ArrayList<String> res=new ArrayList<>();
int open = n;
int close = n ;
String op = "";
solve(open,close,op,res);
return res;
}
}
| 21.764706 | 61 | 0.428378 |
4bba4b32505929ec2b7b1fb130ee8d8db066a54b
| 937 |
/**
*
*/
package org.irods.jargon.rest.domain;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Value object to hold return value from a GenQuery call.
*
* @author jjames
*
*/
@XmlRootElement(name = "results")
public class GenQueryResponseData {
/** The rows. */
private ArrayList<GenQueryRow> rows = new ArrayList<GenQueryRow>();
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (GenQueryRow row : rows) {
sb.append(row);
}
return sb.toString();
}
/**
* Gets the rows.
*
* @return the rows
*/
@XmlElement(name = "row")
public ArrayList<GenQueryRow> getRows() {
return rows;
}
/**
* Sets the rows.
*
* @param rows the new rows
*/
public void setRows(ArrayList<GenQueryRow> rows) {
this.rows = rows;
}
}
| 17.036364 | 68 | 0.658485 |
03c1c499ec4f8119a3b6e3f053dd3acc634d99a1
| 1,022 |
/*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.freertos.amazonfreertossdk.deviceinfo;
/**
* This class represents the broker endpoint object that is transferred between ble device and SDK.
* When SDK sends a read characteristic command to the ble device, this class object is returned in
* the response back to SDK.
* The broker endpoint is the AWS IoT endpoint from AWS IOT Console.
*/
public class BrokerEndpoint {
public String brokerEndpoint;
}
| 37.851852 | 99 | 0.752446 |
224237983529c694bbacd8de940186554e9b21cb
| 13,675 |
/*
Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file 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.amazon.ask.attributes;
import com.amazon.ask.model.IntentRequest;
import com.amazon.ask.model.RequestEnvelope;
import com.amazon.ask.model.Session;
import com.amazon.ask.attributes.persistence.PersistenceAdapter;
import com.amazon.ask.dispatcher.request.handler.HandlerInput;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class AttributesManagerTest {
@Test
public void get_request_attributes() {
AttributesManager attributesManager = AttributesManager.builder()
.withRequestEnvelope(RequestEnvelope.builder().withRequest(IntentRequest.builder().build()).build())
.build();
assertEquals(attributesManager.getRequestAttributes(), Collections.emptyMap());
}
@Test
public void put_request_attribute() {
AttributesManager attributesManager = AttributesManager.builder()
.withRequestEnvelope(RequestEnvelope.builder().withRequest(IntentRequest.builder().build()).build())
.build();
Map<String, Object> requestAttributes = attributesManager.getRequestAttributes();
requestAttributes.put("foo", "bar");
assertEquals(attributesManager.getRequestAttributes().get("foo"), "bar");
}
@Test
public void set_request_attributes() {
Map<String, Object> attributes = (Collections.singletonMap("Foo", "Bar"));
AttributesManager attributesManager = AttributesManager.builder()
.withRequestEnvelope(RequestEnvelope.builder().withRequest(IntentRequest.builder().build()).build())
.build();
attributesManager.setRequestAttributes(attributes);
assertEquals(attributesManager.getRequestAttributes(), attributes);
}
@Test
public void session_attributes_retrieved() {
Map<String, Object> attr = Collections.singletonMap("Foo", "Bar");
AttributesManager attributesManager = AttributesManager.builder()
.withRequestEnvelope(getRequestEnvelopeWithAttributes(attr))
.build();
assertNotNull(attributesManager.getSessionAttributes());
assertEquals(attributesManager.getSessionAttributes(), attr);
}
@Test (expected = IllegalStateException.class)
public void session_attributes_throws_exception_non_session_request() {
AttributesManager attributesManager = AttributesManager.builder()
.withRequestEnvelope(RequestEnvelope.builder().build())
.build();
attributesManager.getSessionAttributes();
}
@Test
public void null_session_attributes_map_creates_new_map() {
RequestEnvelope env = RequestEnvelope.builder().withSession(Session.builder().withAttributes(null).build()).build();
AttributesManager attributesManager = AttributesManager.builder()
.withRequestEnvelope(env)
.build();
assertEquals(attributesManager.getSessionAttributes(), Collections.emptyMap());
}
@Test
public void put_session_attribute() {
HandlerInput input = HandlerInput.builder()
.withRequestEnvelope(RequestEnvelope.builder().withRequest(IntentRequest.builder().build()).withSession(Session.builder().build()).build())
.build();
Map<String, Object> sessionAttributes = input.getAttributesManager().getSessionAttributes();
sessionAttributes.put("foo", "bar");
assertEquals(input.getAttributesManager().getSessionAttributes().get("foo"), "bar");
}
@Test
public void set_session_attributes() {
Map<String, Object> attributes = (Collections.singletonMap("Foo", "Bar"));
HandlerInput input = HandlerInput.builder()
.withRequestEnvelope(RequestEnvelope.builder().withRequest(IntentRequest.builder().build()).withSession(Session.builder().build()).build())
.build();
input.getAttributesManager().setSessionAttributes(attributes);
assertEquals(input.getAttributesManager().getSessionAttributes(), attributes);
}
@Test (expected = IllegalStateException.class)
public void set_session_attributes_throws_exception_non_session_request() {
Map<String, Object> attributes = (Collections.singletonMap("Foo", "Bar"));
HandlerInput input = HandlerInput.builder()
.withRequestEnvelope(RequestEnvelope.builder().withRequest(IntentRequest.builder().build()).build())
.build();
input.getAttributesManager().setSessionAttributes(attributes);
}
@Test
public void no_existing_persistence_attributes_returns_empty_map() {
PersistenceAdapter persistenceAdapter = mock(PersistenceAdapter.class);
when(persistenceAdapter.getAttributes(any())).thenReturn(Optional.empty());
HandlerInput input = HandlerInput.builder()
.withRequestEnvelope(RequestEnvelope.builder().withRequest(IntentRequest.builder().build()).build())
.withPersistenceAdapter(persistenceAdapter).build();
assertEquals(input.getAttributesManager().getPersistentAttributes(), Collections.emptyMap());
}
@Test
public void put_persistent_attribute() {
PersistenceAdapter persistenceAdapter = mock(PersistenceAdapter.class);
when(persistenceAdapter.getAttributes(any())).thenReturn(Optional.empty());
HandlerInput input = HandlerInput.builder()
.withRequestEnvelope(RequestEnvelope.builder().withRequest(IntentRequest.builder().build()).build())
.withPersistenceAdapter(persistenceAdapter).build();
Map<String, Object> persistentAttributes = input.getAttributesManager().getPersistentAttributes();
persistentAttributes.put("foo", "bar");
assertEquals(persistentAttributes.get("foo"), "bar");
}
@Test
public void existing_persistence_attributes_returned() {
PersistenceAdapter persistenceAdapter = mock(PersistenceAdapter.class);
Map<String, Object> attributes = (Collections.singletonMap("Foo", "Bar"));
when(persistenceAdapter.getAttributes(any())).thenReturn(Optional.of(attributes));
HandlerInput input = HandlerInput.builder()
.withRequestEnvelope(RequestEnvelope.builder().withRequest(IntentRequest.builder().build()).build())
.withPersistenceAdapter(persistenceAdapter).build();
assertEquals(input.getAttributesManager().getPersistentAttributes(), attributes);
}
@Test
public void set_persistence_attributes() {
PersistenceAdapter persistenceAdapter = mock(PersistenceAdapter.class);
Map<String, Object> attributes = (Collections.singletonMap("Foo", "Bar"));
HandlerInput input = HandlerInput.builder()
.withRequestEnvelope(RequestEnvelope.builder().withRequest(IntentRequest.builder().build()).build())
.withPersistenceAdapter(persistenceAdapter).build();
input.getAttributesManager().setPersistentAttributes(attributes);
assertEquals(input.getAttributesManager().getPersistentAttributes(), attributes);
}
@Test (expected = IllegalStateException.class)
public void persistence_not_enabled_throws_exception_on_retrieve() {
HandlerInput input = HandlerInput.builder()
.withRequestEnvelope(RequestEnvelope.builder()
.withRequest(IntentRequest.builder().build())
.build())
.withPersistenceAdapter(null).build();
input.getAttributesManager().getPersistentAttributes();
}
@Test (expected = IllegalStateException.class)
public void persistence_not_enabled_throws_exception_on_set() {
HandlerInput input = HandlerInput.builder()
.withRequestEnvelope(RequestEnvelope.builder()
.withRequest(IntentRequest.builder().build())
.build())
.withPersistenceAdapter(null).build();
input.getAttributesManager().setPersistentAttributes(Collections.emptyMap());
}
@Test
public void get_calls_persistence_manager() {
PersistenceAdapter persistenceAdapter = mock(PersistenceAdapter.class);
RequestEnvelope request = RequestEnvelope.builder().withRequest(IntentRequest.builder().build()).build();
Map<String, Object> attributes = (Collections.singletonMap("Foo", "Bar"));
when(persistenceAdapter.getAttributes(any())).thenReturn(Optional.of(attributes));
HandlerInput input = HandlerInput.builder()
.withRequestEnvelope(request)
.withPersistenceAdapter(persistenceAdapter).build();
input.getAttributesManager().getPersistentAttributes();
input.getAttributesManager().savePersistentAttributes();
verify(persistenceAdapter).getAttributes(request);
}
@Test
public void save_noop_if_persistence_attributes_not_retrieved() {
PersistenceAdapter persistenceAdapter = mock(PersistenceAdapter.class);
Map<String, Object> attributes = (Collections.singletonMap("Foo", "Bar"));
when(persistenceAdapter.getAttributes(any())).thenReturn(Optional.of(attributes));
HandlerInput input = HandlerInput.builder()
.withRequestEnvelope(RequestEnvelope.builder().withRequest(IntentRequest.builder().build()).build())
.withPersistenceAdapter(persistenceAdapter).build();
input.getAttributesManager().savePersistentAttributes();
verify(persistenceAdapter, never()).saveAttributes(any(), any());
}
@Test
public void save_calls_persistence_manager_if_attributes_retrieved() {
PersistenceAdapter persistenceAdapter = mock(PersistenceAdapter.class);
ArgumentCaptor <Map<String, Object>> attributesCaptor = ArgumentCaptor.forClass((Class)Map.class);
Map<String, Object> attributes = (Collections.singletonMap("Foo", "Bar"));
when(persistenceAdapter.getAttributes(any())).thenReturn(Optional.of(attributes));
HandlerInput input = HandlerInput.builder()
.withRequestEnvelope(RequestEnvelope.builder().withRequest(IntentRequest.builder().build()).build())
.withPersistenceAdapter(persistenceAdapter).build();
input.getAttributesManager().getPersistentAttributes();
input.getAttributesManager().savePersistentAttributes();
verify(persistenceAdapter).saveAttributes(any(RequestEnvelope.class), attributesCaptor.capture());
assertEquals(attributes, attributesCaptor.getValue());
}
@Test
public void save_calls_persistence_manager_if_set_called() {
PersistenceAdapter persistenceAdapter = mock(PersistenceAdapter.class);
ArgumentCaptor <Map<String, Object>> attributesCaptor = ArgumentCaptor.forClass((Class)Map.class);
Map<String, Object> attributes = (Collections.singletonMap("Foo", "Bar"));
HandlerInput input = HandlerInput.builder()
.withRequestEnvelope(RequestEnvelope.builder().withRequest(IntentRequest.builder().build()).build())
.withPersistenceAdapter(persistenceAdapter).build();
input.getAttributesManager().setPersistentAttributes(attributes);
input.getAttributesManager().savePersistentAttributes();
verify(persistenceAdapter).saveAttributes(any(RequestEnvelope.class), attributesCaptor.capture());
assertEquals(attributes, attributesCaptor.getValue());
}
@Test(expected = IllegalStateException.class)
public void delete_throws_exception_if_no_persistence_adapter() {
HandlerInput input = HandlerInput.builder()
.withRequestEnvelope(RequestEnvelope.builder().withRequest(IntentRequest.builder().build()).build())
.build();
input.getAttributesManager().deletePersistentAttributes();
}
@Test
public void delete_calls_persistence_manager() {
PersistenceAdapter persistenceAdapter = mock(PersistenceAdapter.class);
when(persistenceAdapter.getAttributes(any())).thenReturn(Optional.of(Collections.singletonMap("Foo", "Bar")));
HandlerInput input = HandlerInput.builder()
.withRequestEnvelope(RequestEnvelope.builder().withRequest(IntentRequest.builder().build()).build())
.withPersistenceAdapter(persistenceAdapter).build();
input.getAttributesManager().deletePersistentAttributes();
verify(persistenceAdapter).deleteAttributes(any(RequestEnvelope.class));
}
private RequestEnvelope getRequestEnvelopeWithAttributes(Map<String, Object> attributes) {
return RequestEnvelope.builder().withSession(Session.builder().withAttributes(attributes).build()).build();
}
}
| 51.409774 | 155 | 0.709397 |
44af64846412fe00d0556a6905ca5bc15fd1afc3
| 484 |
package tw.edu.au.csie.ucan.beebit.seco;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Controller
public class RootController {
@GetMapping("/")
public String home() {
return "index";
}
@GetMapping("/{page}")
public String pages(@PathVariable String page) {
System.out.print(page);
return page;
}
}
| 23.047619 | 60 | 0.688017 |
bf854a166c589424cdf806252c9a32cc975dc186
| 815 |
package com.microservices.workshop.billing.domain.entity;
import javax.persistence.*;
import java.io.Serializable;
@Entity
public class Charge implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "customer_id", length = 5)
private int customerId;
@Column(name = "amount", length = 5)
private double amount;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
}
| 18.953488 | 57 | 0.633129 |
18ed7cc74c0de1597d6c27f20bf053ec2da59e3d
| 415 |
package com.niluogege.serveredu.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.niluogege.serveredu.entity.EduSubject;
import java.util.List;
/**
* <p>
* 课程科目 Mapper 接口
* </p>
*
* @author niluogege
* @since 2021-11-15
*/
public interface EduSubjectMapper extends BaseMapper<EduSubject> {
/**
* 获取分裂树形结构
* @return
*/
List<EduSubject> getSubjectsTree();
}
| 17.291667 | 66 | 0.689157 |
368ae46f7cf9364909683cfc0c52a37647e2d87f
| 1,223 |
/*
* Copyright (c) 2013 Intellectual Reserve, Inc. All rights reserved.
*
* 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 cf.client;
import java.util.AbstractCollection;
import java.util.Iterator;
/**
* @author Mike Heath <elcapo@gmail.com>
*/
public class RestCollection<T> extends AbstractCollection<Resource<T>> {
private final int totalResults;
private Iterator<Resource<T>> iterator;
public RestCollection(int totalResults, Iterator<Resource<T>> iterator) {
this.totalResults = totalResults;
this.iterator = iterator;
}
@Override
public Iterator<Resource<T>> iterator() {
return iterator;
}
@Override
public int size() {
return totalResults;
}
}
| 26.586957 | 77 | 0.724448 |
4323ab54683184f765795f013c3f7acbc658f30d
| 2,206 |
package de.retest.recheck.example;
import java.net.URL;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import de.retest.recheck.Properties;
import de.retest.recheck.Recheck;
import de.retest.recheck.RecheckImpl;
class BrowserStackTest {
public static final String USERNAME = "sebastianrler1";
public static final String AUTOMATE_KEY = "Wqp2KsfqSHJpo3gCpkYg";
public static final String URL = "https://" + USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";
private static final String testname = "retest.de";
RemoteWebDriver driver;
Recheck re;
@Test
public void checkGalaxy8() throws Exception {
re = new RecheckImpl();
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("browserName", "android");
caps.setCapability("device", "Samsung Galaxy S8");
caps.setCapability("realMobile", "true");
caps.setCapability("os_version", "7.0");
caps.setCapability("name", testname);
caps.setCapability("browserstack.debug", "true");
driver = new RemoteWebDriver(new URL(URL), caps);
re.startTest(testname);
driver.get("http://www.retest.de");
re.check(driver, "init");
re.capTest();
}
@Test
public void checkIPhone8() throws Exception {
re = new RecheckImpl();
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("browserName", "iPhone");
caps.setCapability("device", "iPhone 8 Plus");
caps.setCapability("realMobile", "true");
caps.setCapability("os_version", "11");
caps.setCapability("name", testname);
caps.setCapability("browserstack.debug", "true");
driver = new RemoteWebDriver(new URL(URL), caps);
re.startTest(testname);
driver.get("http://www.retest.de");
re.check(driver, "init");
re.capTest();
}
@BeforeAll
public static void setup() {
System.setProperty(Properties.ROOT_ELEMENT_MATCH_THRESHOLD_PROPERTY, "0.0");
System.setProperty(Properties.ELEMENT_MATCH_THRESHOLD_PROPERTY, "0.0");
}
@AfterEach
public void tearDown() throws InterruptedException {
driver.quit();
re.cap();
}
}
| 29.810811 | 116 | 0.737987 |
e70c2edade63ba46ccd7c4b411c9440bbff8c0ac
| 3,577 |
/* 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.camunda.bpm.engine.impl.interceptor;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.camunda.bpm.engine.impl.ProcessEngineLogger;
/**
*
* @author Daniel Meyer
*
*/
public class BpmnStackTrace {
private final static ContextLogger LOG = ProcessEngineLogger.CONTEXT_LOGGER;
protected List<AtomicOperationInvocation> perfromedInvocations = new ArrayList<AtomicOperationInvocation>();
public void printStackTrace(boolean verbose) {
if(perfromedInvocations.isEmpty()) {
return;
}
StringWriter writer = new StringWriter();
writer.write("BPMN Stack Trace:\n");
if(!verbose) {
logNonVerbose(writer);
}
else {
logVerbose(writer);
}
LOG.bpmnStackTrace(writer.toString());
perfromedInvocations.clear();
}
protected void logNonVerbose(StringWriter writer) {
// log the failed operation verbosely
writeInvocation(perfromedInvocations.get(perfromedInvocations.size() - 1), writer);
// log human consumable trace of activity ids only
List<String> activities = collectActivityTrace();
logActivityTrace(writer, activities);
}
protected void logVerbose(StringWriter writer) {
// log process engine developer consumable trace
Collections.reverse(perfromedInvocations);
for (AtomicOperationInvocation invocation : perfromedInvocations) {
writeInvocation(invocation, writer);
}
}
protected void logActivityTrace(StringWriter writer, List<String> activities) {
for (int i = 0; i < activities.size(); i++) {
if(i != 0) {
writer.write("\t ^\n");
writer.write("\t |\n");
}
writer.write("\t");
writer.write(activities.get(i));
writer.write("\n");
}
}
protected List<String> collectActivityTrace() {
List<String> activities = new ArrayList<String>();
for (AtomicOperationInvocation atomicOperationInvocation : perfromedInvocations) {
String activityId = atomicOperationInvocation.getActivityId();
if(activityId == null) {
continue;
}
if(activities.isEmpty() ||
!activityId.equals(activities.get(0))) {
activities.add(0, activityId);
}
}
return activities;
}
public void add(AtomicOperationInvocation atomicOperationInvocation) {
perfromedInvocations.add(atomicOperationInvocation);
}
protected void writeInvocation(AtomicOperationInvocation invocation, StringWriter writer) {
writer.write("\t");
writer.write(invocation.getActivityId());
writer.write(" (");
writer.write(invocation.getOperation().getCanonicalName());
writer.write(", ");
writer.write(invocation.getExecution().toString());
if(invocation.isPerformAsync()) {
writer.write(", ASYNC");
}
if(invocation.getApplicationContextName() != null) {
writer.write(", pa=");
writer.write(invocation.getApplicationContextName());
}
writer.write(")\n");
}
}
| 29.081301 | 110 | 0.696114 |
fb0b7b6a4877b5580a6310bd2735d3a092e557c2
| 48,997 |
package gnu.math;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.ObjectStreamException;
import java.math.BigDecimal;
import java.math.BigInteger;
public class IntNum extends RatNum implements Externalizable {
static final int maxFixNum = 1024;
static final int minFixNum = -100;
static final int numFixNum = 1125;
static final IntNum[] smallFixNums = new IntNum[numFixNum];
public int ival;
public int[] words;
static {
int i = numFixNum;
while (true) {
i--;
if (i >= 0) {
smallFixNums[i] = new IntNum(i + minFixNum);
} else {
return;
}
}
}
public IntNum() {
}
public IntNum(int value) {
this.ival = value;
}
public static IntNum make(int value) {
if (value < minFixNum || value > 1024) {
return new IntNum(value);
}
return smallFixNums[value + 100];
}
public static final IntNum zero() {
return smallFixNums[100];
}
public static final IntNum one() {
return smallFixNums[101];
}
public static final IntNum ten() {
return smallFixNums[110];
}
public static IntNum minusOne() {
return smallFixNums[99];
}
public static IntNum make(long value) {
if (value >= -100 && value <= 1024) {
return smallFixNums[((int) value) + 100];
}
int i = (int) value;
if (((long) i) == value) {
return new IntNum(i);
}
IntNum result = alloc(2);
result.ival = 2;
result.words[0] = i;
result.words[1] = (int) (value >> 32);
return result;
}
public static IntNum asIntNumOrNull(Object value) {
if (value instanceof IntNum) {
return (IntNum) value;
}
if (value instanceof BigInteger) {
return valueOf(value.toString(), 10);
}
if (!(value instanceof Number) || (!(value instanceof Integer) && !(value instanceof Long) && !(value instanceof Short) && !(value instanceof Byte))) {
return null;
}
return make(((Number) value).longValue());
}
public static IntNum makeU(long value) {
if (value >= 0) {
return make(value);
}
IntNum result = alloc(3);
result.ival = 3;
result.words[0] = (int) value;
result.words[1] = (int) (value >> 32);
result.words[2] = 0;
return result;
}
public static IntNum make(int[] words2, int len) {
if (words2 == null) {
return make(len);
}
int len2 = wordsNeeded(words2, len);
if (len2 <= 1) {
return len2 == 0 ? zero() : make(words2[0]);
}
IntNum num = new IntNum();
num.words = words2;
num.ival = len2;
return num;
}
public static IntNum make(int[] words2) {
return make(words2, words2.length);
}
public static IntNum alloc(int nwords) {
if (nwords <= 1) {
return new IntNum();
}
IntNum result = new IntNum();
result.words = new int[nwords];
return result;
}
public void realloc(int nwords) {
if (nwords == 0) {
if (this.words != null) {
if (this.ival > 0) {
this.ival = this.words[0];
}
this.words = null;
}
} else if (this.words == null || this.words.length < nwords || this.words.length > nwords + 2) {
int[] new_words = new int[nwords];
if (this.words == null) {
new_words[0] = this.ival;
this.ival = 1;
} else {
if (nwords < this.ival) {
this.ival = nwords;
}
System.arraycopy(this.words, 0, new_words, 0, this.ival);
}
this.words = new_words;
}
}
public final IntNum numerator() {
return this;
}
public final IntNum denominator() {
return one();
}
public final boolean isNegative() {
return (this.words == null ? this.ival : this.words[this.ival + -1]) < 0;
}
public int sign() {
int n = this.ival;
int[] w = this.words;
if (w != null) {
int n2 = n - 1;
int i = w[n2];
if (i > 0) {
return 1;
}
if (i < 0) {
return -1;
}
while (n2 != 0) {
n2--;
if (w[n2] != 0) {
return 1;
}
}
return 0;
} else if (n > 0) {
return 1;
} else {
return n < 0 ? -1 : 0;
}
}
public static int compare(IntNum x, IntNum y) {
boolean z = false;
int i = 1;
if (x.words != null || y.words != null) {
boolean x_negative = x.isNegative();
if (x_negative == y.isNegative()) {
int x_len = x.words == null ? 1 : x.ival;
int y_len = y.words == null ? 1 : y.ival;
if (x_len == y_len) {
return MPN.cmp(x.words, y.words, x_len);
}
if (x_len > y_len) {
z = true;
}
if (z == x_negative) {
i = -1;
}
return i;
} else if (!x_negative) {
return 1;
} else {
return -1;
}
} else if (x.ival < y.ival) {
return -1;
} else {
return x.ival > y.ival ? 1 : 0;
}
}
public static int compare(IntNum x, long y) {
boolean y_negative;
long x_word;
if (x.words == null) {
x_word = (long) x.ival;
} else {
boolean x_negative = x.isNegative();
if (y < 0) {
y_negative = true;
} else {
y_negative = false;
}
if (x_negative == y_negative) {
int x_len = x.words == null ? 1 : x.ival;
if (x_len == 1) {
x_word = (long) x.words[0];
} else if (x_len == 2) {
x_word = x.longValue();
} else if (!x_negative) {
return 1;
} else {
return -1;
}
} else if (!x_negative) {
return 1;
} else {
return -1;
}
}
if (x_word < y) {
return -1;
}
return x_word > y ? 1 : 0;
}
public int compare(Object obj) {
if (obj instanceof IntNum) {
return compare(this, (IntNum) obj);
}
return ((RealNum) obj).compareReversed(this);
}
public final boolean isOdd() {
if (((this.words == null ? this.ival : this.words[0]) & 1) != 0) {
return true;
}
return false;
}
public final boolean isZero() {
return this.words == null && this.ival == 0;
}
public final boolean isOne() {
return this.words == null && this.ival == 1;
}
public final boolean isMinusOne() {
return this.words == null && this.ival == -1;
}
public static int wordsNeeded(int[] words2, int len) {
int i = len;
if (i > 0) {
i--;
int word = words2[i];
if (word != -1) {
while (word == 0 && i > 0) {
word = words2[i - 1];
if (word < 0) {
break;
}
i--;
}
} else {
while (i > 0) {
int word2 = words2[i - 1];
if (word2 >= 0) {
break;
}
i--;
if (word2 != -1) {
break;
}
}
}
}
return i + 1;
}
public IntNum canonicalize() {
if (this.words != null) {
int wordsNeeded = wordsNeeded(this.words, this.ival);
this.ival = wordsNeeded;
if (wordsNeeded <= 1) {
if (this.ival == 1) {
this.ival = this.words[0];
}
this.words = null;
}
}
if (this.words != null || this.ival < minFixNum || this.ival > 1024) {
return this;
}
return smallFixNums[this.ival + 100];
}
public static final IntNum add(int x, int y) {
return make(((long) x) + ((long) y));
}
public static IntNum add(IntNum x, int y) {
if (x.words == null) {
return add(x.ival, y);
}
IntNum result = new IntNum(0);
result.setAdd(x, y);
return result.canonicalize();
}
public void setAdd(IntNum x, int y) {
if (x.words == null) {
set(((long) x.ival) + ((long) y));
return;
}
int len = x.ival;
realloc(len + 1);
long carry = (long) y;
for (int i = 0; i < len; i++) {
long carry2 = carry + (((long) x.words[i]) & 4294967295L);
this.words[i] = (int) carry2;
carry = carry2 >> 32;
}
if (x.words[len - 1] < 0) {
carry--;
}
this.words[len] = (int) carry;
this.ival = wordsNeeded(this.words, len + 1);
}
public final void setAdd(int y) {
setAdd(this, y);
}
public final void set(int y) {
this.words = null;
this.ival = y;
}
public final void set(long y) {
int i = (int) y;
if (((long) i) == y) {
this.ival = i;
this.words = null;
return;
}
realloc(2);
this.words[0] = i;
this.words[1] = (int) (y >> 32);
this.ival = 2;
}
public final void set(int[] words2, int length) {
this.ival = length;
this.words = words2;
}
public final void set(IntNum y) {
if (y.words == null) {
set(y.ival);
} else if (this != y) {
realloc(y.ival);
System.arraycopy(y.words, 0, this.words, 0, y.ival);
this.ival = y.ival;
}
}
public static IntNum add(IntNum x, IntNum y) {
return add(x, y, 1);
}
public static IntNum sub(IntNum x, IntNum y) {
return add(x, y, -1);
}
public static IntNum add(IntNum x, IntNum y, int k) {
if (x.words == null && y.words == null) {
return make((((long) k) * ((long) y.ival)) + ((long) x.ival));
}
if (k != 1) {
if (k == -1) {
y = neg(y);
} else {
y = times(y, make(k));
}
}
if (x.words == null) {
return add(y, x.ival);
}
if (y.words == null) {
return add(x, y.ival);
}
if (y.ival > x.ival) {
IntNum tmp = x;
x = y;
y = tmp;
}
IntNum result = alloc(x.ival + 1);
int i = y.ival;
long carry = (long) MPN.add_n(result.words, x.words, y.words, i);
long y_ext = y.words[i + -1] < 0 ? 4294967295L : 0;
while (i < x.ival) {
long carry2 = carry + (((long) x.words[i]) & 4294967295L) + y_ext;
result.words[i] = (int) carry2;
carry = carry2 >>> 32;
i++;
}
if (x.words[i - 1] < 0) {
y_ext--;
}
result.words[i] = (int) (carry + y_ext);
result.ival = i + 1;
return result.canonicalize();
}
public static final IntNum times(int x, int y) {
return make(((long) x) * ((long) y));
}
public static final IntNum times(IntNum x, int y) {
boolean negative;
boolean negative2;
if (y == 0) {
return zero();
}
if (y == 1) {
return x;
}
int[] xwords = x.words;
int xlen = x.ival;
if (xwords == null) {
return make(((long) xlen) * ((long) y));
}
IntNum result = alloc(xlen + 1);
if (xwords[xlen - 1] < 0) {
negative = true;
negate(result.words, xwords, xlen);
xwords = result.words;
} else {
negative = false;
}
if (y < 0) {
negative2 = !negative2;
y = -y;
}
result.words[xlen] = MPN.mul_1(result.words, xwords, xlen, y);
result.ival = xlen + 1;
if (negative2) {
result.setNegative();
}
return result.canonicalize();
}
public static final IntNum times(IntNum x, IntNum y) {
boolean negative;
int[] xwords;
boolean negative2;
int[] ywords;
if (y.words == null) {
return times(x, y.ival);
}
if (x.words == null) {
return times(y, x.ival);
}
int xlen = x.ival;
int ylen = y.ival;
if (x.isNegative()) {
negative = true;
xwords = new int[xlen];
negate(xwords, x.words, xlen);
} else {
negative = false;
xwords = x.words;
}
if (y.isNegative()) {
negative2 = !negative2;
ywords = new int[ylen];
negate(ywords, y.words, ylen);
} else {
ywords = y.words;
}
if (xlen < ylen) {
int[] twords = xwords;
xwords = ywords;
ywords = twords;
int tlen = xlen;
xlen = ylen;
ylen = tlen;
}
IntNum result = alloc(xlen + ylen);
MPN.mul(result.words, xwords, xlen, ywords, ylen);
result.ival = xlen + ylen;
if (negative2) {
result.setNegative();
}
return result.canonicalize();
}
public static void divide(long x, long y, IntNum quotient, IntNum remainder, int rounding_mode) {
boolean xNegative;
boolean yNegative;
if (rounding_mode == 5) {
rounding_mode = y < 0 ? 2 : 1;
}
if (x < 0) {
xNegative = true;
if (x == Long.MIN_VALUE) {
divide(make(x), make(y), quotient, remainder, rounding_mode);
return;
}
x = -x;
} else {
xNegative = false;
}
if (y < 0) {
yNegative = true;
if (y != Long.MIN_VALUE) {
y = -y;
} else if (rounding_mode == 3) {
if (quotient != null) {
quotient.set(0);
}
if (remainder != null) {
remainder.set(x);
return;
}
return;
} else {
divide(make(x), make(y), quotient, remainder, rounding_mode);
return;
}
} else {
yNegative = false;
}
long q = x / y;
long r = x % y;
boolean qNegative = xNegative ^ yNegative;
boolean add_one = false;
if (r != 0) {
switch (rounding_mode) {
case 1:
case 2:
if (qNegative == (rounding_mode == 1)) {
add_one = true;
break;
}
break;
case 4:
if (r <= ((y - (1 & q)) >> 1)) {
add_one = false;
break;
} else {
add_one = true;
break;
}
}
}
if (quotient != null) {
if (add_one) {
q++;
}
if (qNegative) {
q = -q;
}
quotient.set(q);
}
if (remainder != null) {
if (add_one) {
r = y - r;
xNegative = !xNegative;
}
if (xNegative) {
r = -r;
}
remainder.set(r);
}
}
public static void divide(IntNum x, IntNum y, IntNum quotient, IntNum remainder, int rounding_mode) {
int xlen;
int rlen;
int qlen;
IntNum tmp;
IntNum tmp2;
int xlen2;
if ((x.words == null || x.ival <= 2) && (y.words == null || y.ival <= 2)) {
long x_l = x.longValue();
long y_l = y.longValue();
if (!(x_l == Long.MIN_VALUE || y_l == Long.MIN_VALUE)) {
divide(x_l, y_l, quotient, remainder, rounding_mode);
return;
}
}
boolean xNegative = x.isNegative();
boolean yNegative = y.isNegative();
boolean qNegative = xNegative ^ yNegative;
int ylen = y.words == null ? 1 : y.ival;
int[] ywords = new int[ylen];
y.getAbsolute(ywords);
while (ylen > 1 && ywords[ylen - 1] == 0) {
ylen--;
}
int xlen3 = x.words == null ? 1 : x.ival;
int[] xwords = new int[(xlen3 + 2)];
x.getAbsolute(xwords);
while (true) {
xlen = xlen3;
if (xlen <= 1 || xwords[xlen - 1] != 0) {
int cmpval = MPN.cmp(xwords, xlen, ywords, ylen);
} else {
xlen3 = xlen - 1;
}
}
int cmpval2 = MPN.cmp(xwords, xlen, ywords, ylen);
if (cmpval2 < 0) {
int[] rwords = xwords;
xwords = ywords;
ywords = rwords;
rlen = xlen;
qlen = 1;
xwords[0] = 0;
int i = xlen;
} else if (cmpval2 == 0) {
xwords[0] = 1;
qlen = 1;
ywords[0] = 0;
rlen = 1;
int i2 = xlen;
} else if (ylen == 1) {
qlen = xlen;
rlen = 1;
ywords[0] = MPN.divmod_1(xwords, xwords, xlen, ywords[0]);
int i3 = xlen;
} else {
int nshift = MPN.count_leading_zeros(ywords[ylen - 1]);
if (nshift != 0) {
MPN.lshift(ywords, 0, ywords, ylen, nshift);
int xlen4 = xlen + 1;
xwords[xlen] = MPN.lshift(xwords, 0, xwords, xlen, nshift);
xlen = xlen4;
}
if (xlen == ylen) {
xlen2 = xlen + 1;
xwords[xlen] = 0;
} else {
xlen2 = xlen;
}
MPN.divide(xwords, xlen2, ywords, ylen);
rlen = ylen;
MPN.rshift0(ywords, xwords, 0, rlen, nshift);
qlen = (xlen2 + 1) - ylen;
if (quotient != null) {
for (int i4 = 0; i4 < qlen; i4++) {
xwords[i4] = xwords[i4 + ylen];
}
}
}
while (rlen > 1 && ywords[rlen - 1] == 0) {
rlen--;
}
if (ywords[rlen - 1] < 0) {
ywords[rlen] = 0;
rlen++;
}
boolean add_one = false;
if (rlen > 1 || ywords[0] != 0) {
if (rounding_mode == 5) {
rounding_mode = yNegative ? 2 : 1;
}
switch (rounding_mode) {
case 1:
case 2:
if (qNegative == (rounding_mode == 1)) {
add_one = true;
break;
}
break;
case 4:
if (remainder == null) {
tmp2 = new IntNum();
} else {
tmp2 = remainder;
}
tmp2.set(ywords, rlen);
IntNum tmp3 = shift(tmp2, 1);
if (yNegative) {
tmp3.setNegative();
}
int cmp = compare(tmp3, y);
if (yNegative) {
cmp = -cmp;
}
if (cmp != 1 && (cmp != 0 || (xwords[0] & 1) == 0)) {
add_one = false;
break;
} else {
add_one = true;
break;
}
}
}
if (quotient != null) {
if (xwords[qlen - 1] < 0) {
xwords[qlen] = 0;
qlen++;
}
quotient.set(xwords, qlen);
if (qNegative) {
if (add_one) {
quotient.setInvert();
} else {
quotient.setNegative();
}
} else if (add_one) {
quotient.setAdd(1);
}
}
if (remainder != null) {
remainder.set(ywords, rlen);
if (add_one) {
if (y.words == null) {
tmp = remainder;
tmp.set(yNegative ? ywords[0] + y.ival : ywords[0] - y.ival);
} else {
tmp = add(remainder, y, yNegative ? 1 : -1);
}
if (xNegative) {
remainder.setNegative(tmp);
} else {
remainder.set(tmp);
}
} else if (xNegative) {
remainder.setNegative();
}
}
}
public static IntNum quotient(IntNum x, IntNum y, int rounding_mode) {
IntNum quotient = new IntNum();
divide(x, y, quotient, (IntNum) null, rounding_mode);
return quotient.canonicalize();
}
public static IntNum quotient(IntNum x, IntNum y) {
return quotient(x, y, 3);
}
public IntNum toExactInt(int rounding_mode) {
return this;
}
public RealNum toInt(int rounding_mode) {
return this;
}
public static IntNum remainder(IntNum x, IntNum y, int rounding_mode) {
if (y.isZero()) {
return x;
}
IntNum rem = new IntNum();
divide(x, y, (IntNum) null, rem, rounding_mode);
return rem.canonicalize();
}
public static IntNum remainder(IntNum x, IntNum y) {
return remainder(x, y, 3);
}
public static IntNum modulo(IntNum x, IntNum y) {
return remainder(x, y, 1);
}
/* Debug info: failed to restart local var, previous not found, register: 1 */
public Numeric power(IntNum y) {
if (isOne()) {
return this;
}
if (isMinusOne()) {
if (!y.isOdd()) {
return one();
}
return this;
} else if (y.words == null && y.ival >= 0) {
return power(this, y.ival);
} else {
if (!isZero()) {
return super.power(y);
}
if (y.isNegative()) {
return RatNum.infinity(-1);
}
return this;
}
}
public static IntNum power(IntNum x, int y) {
boolean negative;
if (y <= 0) {
if (y == 0) {
return one();
}
throw new Error("negative exponent");
} else if (x.isZero()) {
return x;
} else {
int plen = x.words == null ? 1 : x.ival;
int blen = ((x.intLength() * y) >> 5) + (plen * 2);
if (!x.isNegative() || (y & 1) == 0) {
negative = false;
} else {
negative = true;
}
int[] pow2 = new int[blen];
int[] rwords = new int[blen];
int[] work = new int[blen];
x.getAbsolute(pow2);
int rlen = 1;
rwords[0] = 1;
while (true) {
if ((y & 1) != 0) {
MPN.mul(work, pow2, plen, rwords, rlen);
int[] temp = work;
work = rwords;
rwords = temp;
rlen += plen;
while (rwords[rlen - 1] == 0) {
rlen--;
}
}
y >>= 1;
if (y == 0) {
break;
}
MPN.mul(work, pow2, plen, pow2, plen);
int[] temp2 = work;
work = pow2;
pow2 = temp2;
plen *= 2;
while (pow2[plen - 1] == 0) {
plen--;
}
}
if (rwords[rlen - 1] < 0) {
rlen++;
}
if (negative) {
negate(rwords, rwords, rlen);
}
return make(rwords, rlen);
}
}
public static final int gcd(int a, int b) {
if (b > a) {
int tmp = a;
a = b;
b = tmp;
}
while (b != 0) {
if (b == 1) {
return b;
}
int tmp2 = b;
b = a % b;
a = tmp2;
}
return a;
}
public static IntNum gcd(IntNum x, IntNum y) {
int len;
int xval = x.ival;
int yval = y.ival;
if (x.words == null) {
if (xval == 0) {
return abs(y);
}
if (y.words != null || xval == Integer.MIN_VALUE || yval == Integer.MIN_VALUE) {
xval = 1;
} else {
if (xval < 0) {
xval = -xval;
}
if (yval < 0) {
yval = -yval;
}
return make(gcd(xval, yval));
}
}
if (y.words == null) {
if (yval == 0) {
return abs(x);
}
yval = 1;
}
if (xval > yval) {
len = xval;
} else {
len = yval;
}
int[] xwords = new int[len];
int[] ywords = new int[len];
x.getAbsolute(xwords);
y.getAbsolute(ywords);
int len2 = MPN.gcd(xwords, ywords, len);
IntNum result = new IntNum(0);
if (xwords[len2 - 1] < 0) {
int len3 = len2 + 1;
xwords[len2] = 0;
len2 = len3;
}
result.ival = len2;
result.words = xwords;
return result.canonicalize();
}
public static IntNum lcm(IntNum x, IntNum y) {
if (x.isZero() || y.isZero()) {
return zero();
}
IntNum x2 = abs(x);
IntNum y2 = abs(y);
IntNum quotient = new IntNum();
divide(times(x2, y2), gcd(x2, y2), quotient, (IntNum) null, 3);
return quotient.canonicalize();
}
/* access modifiers changed from: 0000 */
public void setInvert() {
if (this.words == null) {
this.ival ^= -1;
return;
}
int i = this.ival;
while (true) {
i--;
if (i >= 0) {
this.words[i] = this.words[i] ^ -1;
} else {
return;
}
}
}
/* access modifiers changed from: 0000 */
public void setShiftLeft(IntNum x, int count) {
int[] xwords;
int xlen;
if (x.words != null) {
xwords = x.words;
xlen = x.ival;
} else if (count < 32) {
set(((long) x.ival) << count);
return;
} else {
xwords = new int[]{x.ival};
xlen = 1;
}
int word_count = count >> 5;
int count2 = count & 31;
int new_len = xlen + word_count;
if (count2 == 0) {
realloc(new_len);
int i = xlen;
while (true) {
i--;
if (i < 0) {
break;
}
this.words[i + word_count] = xwords[i];
}
} else {
new_len++;
realloc(new_len);
int shift_out = MPN.lshift(this.words, word_count, xwords, xlen, count2);
int count3 = 32 - count2;
this.words[new_len - 1] = (shift_out << count3) >> count3;
}
this.ival = new_len;
int i2 = word_count;
while (true) {
i2--;
if (i2 >= 0) {
this.words[i2] = 0;
} else {
return;
}
}
}
/* access modifiers changed from: 0000 */
public void setShiftRight(IntNum x, int count) {
int i = -1;
if (x.words == null) {
if (count < 32) {
i = x.ival >> count;
} else if (x.ival >= 0) {
i = 0;
}
set(i);
} else if (count == 0) {
set(x);
} else {
boolean neg = x.isNegative();
int word_count = count >> 5;
int count2 = count & 31;
int d_len = x.ival - word_count;
if (d_len <= 0) {
if (!neg) {
i = 0;
}
set(i);
return;
}
if (this.words == null || this.words.length < d_len) {
realloc(d_len);
}
MPN.rshift0(this.words, x.words, word_count, d_len, count2);
this.ival = d_len;
if (neg) {
int[] iArr = this.words;
int i2 = d_len - 1;
iArr[i2] = iArr[i2] | (-2 << (31 - count2));
}
}
}
/* access modifiers changed from: 0000 */
public void setShift(IntNum x, int count) {
if (count > 0) {
setShiftLeft(x, count);
} else {
setShiftRight(x, -count);
}
}
public static IntNum shift(IntNum x, int count) {
int i = 0;
if (x.words == null) {
if (count <= 0) {
if (count > -32) {
i = x.ival >> (-count);
} else if (x.ival < 0) {
i = -1;
}
return make(i);
} else if (count < 32) {
return make(((long) x.ival) << count);
}
}
if (count == 0) {
return x;
}
IntNum result = new IntNum(0);
result.setShift(x, count);
return result.canonicalize();
}
public static int shift(int x, int count) {
if (count >= 32) {
return 0;
}
if (count >= 0) {
return x << count;
}
int count2 = -count;
if (count2 < 32) {
return x >> count2;
}
if (x < 0) {
return -1;
}
return 0;
}
public static long shift(long x, int count) {
if (count >= 32) {
return 0;
}
if (count >= 0) {
return x << count;
}
int count2 = -count;
if (count2 < 32) {
return x >> count2;
}
if (x < 0) {
return -1;
}
return 0;
}
public void format(int radix, StringBuffer buffer) {
if (radix == 10) {
if (this.words == null) {
buffer.append(this.ival);
return;
} else if (this.ival <= 2) {
buffer.append(longValue());
return;
}
}
buffer.append(toString(radix));
}
public void format(int radix, StringBuilder buffer) {
int[] work;
int digit;
if (this.words == null) {
if (radix == 10) {
buffer.append(this.ival);
return;
}
buffer.append(Integer.toString(this.ival, radix));
} else if (this.ival <= 2) {
long lval = longValue();
if (radix == 10) {
buffer.append(lval);
return;
}
buffer.append(Long.toString(lval, radix));
} else {
boolean neg = isNegative();
if (neg || radix != 16) {
work = new int[this.ival];
getAbsolute(work);
} else {
work = this.words;
}
int len = this.ival;
if (radix == 16) {
if (neg) {
buffer.append('-');
}
int buf_start = buffer.length();
int i = len;
while (true) {
i--;
if (i >= 0) {
int word = work[i];
int j = 8;
while (true) {
j--;
if (j >= 0) {
int hex_digit = (word >> (j * 4)) & 15;
if (hex_digit > 0 || buffer.length() > buf_start) {
buffer.append(Character.forDigit(hex_digit, 16));
}
}
}
} else {
return;
}
}
} else {
int chars_per_word = MPN.chars_per_word(radix);
int wradix = radix;
int j2 = chars_per_word;
while (true) {
j2--;
if (j2 <= 0) {
break;
}
wradix *= radix;
}
int i2 = buffer.length();
do {
int wdigit = MPN.divmod_1(work, work, len, wradix);
while (len > 0 && work[len - 1] == 0) {
len--;
}
int j3 = chars_per_word;
while (true) {
j3--;
if (j3 >= 0 && (len != 0 || wdigit != 0)) {
if (wdigit < 0) {
digit = (int) ((((long) wdigit) & -1) % ((long) radix));
} else {
digit = wdigit % radix;
}
wdigit /= radix;
buffer.append(Character.forDigit(digit, radix));
}
}
} while (len != 0);
if (neg) {
buffer.append('-');
}
for (int j4 = buffer.length() - 1; i2 < j4; j4--) {
char tmp = buffer.charAt(i2);
buffer.setCharAt(i2, buffer.charAt(j4));
buffer.setCharAt(j4, tmp);
i2++;
}
}
}
}
public String toString(int radix) {
if (this.words == null) {
return Integer.toString(this.ival, radix);
}
if (this.ival <= 2) {
return Long.toString(longValue(), radix);
}
StringBuilder buffer = new StringBuilder(this.ival * (MPN.chars_per_word(radix) + 1));
format(radix, buffer);
return buffer.toString();
}
public int intValue() {
if (this.words == null) {
return this.ival;
}
return this.words[0];
}
public static int intValue(Object obj) {
IntNum inum = (IntNum) obj;
if (inum.words == null) {
return inum.ival;
}
throw new ClassCastException("integer too large");
}
public long longValue() {
if (this.words == null) {
return (long) this.ival;
}
if (this.ival == 1) {
return (long) this.words[0];
}
return (((long) this.words[1]) << 32) + (((long) this.words[0]) & 4294967295L);
}
public int hashCode() {
return this.words == null ? this.ival : this.words[0] + this.words[this.ival - 1];
}
public static boolean equals(IntNum x, IntNum y) {
if (x.words == null && y.words == null) {
if (x.ival == y.ival) {
return true;
}
return false;
} else if (x.words == null || y.words == null || x.ival != y.ival) {
return false;
} else {
int i = x.ival;
do {
i--;
if (i < 0) {
return true;
}
} while (x.words[i] == y.words[i]);
return false;
}
}
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof IntNum)) {
return false;
}
return equals(this, (IntNum) obj);
}
public static IntNum valueOf(char[] buf, int offset, int length, int radix, boolean negative) {
int byte_len;
byte[] bytes = new byte[length];
int i = 0;
int byte_len2 = 0;
while (i < length) {
char ch = buf[offset + i];
if (ch == '-') {
negative = true;
byte_len = byte_len2;
} else {
if (ch != '_') {
if (byte_len2 == 0) {
if (ch != ' ') {
if (ch == 9) {
byte_len = byte_len2;
}
}
}
int digit = Character.digit(ch, radix);
if (digit < 0) {
break;
}
byte_len = byte_len2 + 1;
bytes[byte_len2] = (byte) digit;
}
byte_len = byte_len2;
}
i++;
byte_len2 = byte_len;
}
return valueOf(bytes, byte_len2, negative, radix);
}
public static IntNum valueOf(String s, int radix) throws NumberFormatException {
int byte_len;
int len = s.length();
if (len + radix <= 28) {
if (len > 1 && s.charAt(0) == '+' && Character.digit(s.charAt(1), radix) >= 0) {
s = s.substring(1);
}
return make(Long.parseLong(s, radix));
}
byte[] bytes = new byte[len];
boolean negative = false;
int i = 0;
int byte_len2 = 0;
while (i < len) {
char ch = s.charAt(i);
if (ch == '-' && i == 0) {
negative = true;
byte_len = byte_len2;
} else if (ch == '+' && i == 0) {
byte_len = byte_len2;
} else {
if (ch != '_') {
if (byte_len2 == 0) {
if (ch != ' ') {
if (ch == 9) {
byte_len = byte_len2;
}
}
}
int digit = Character.digit(ch, radix);
if (digit < 0) {
throw new NumberFormatException("For input string: \"" + s + '\"');
}
byte_len = byte_len2 + 1;
bytes[byte_len2] = (byte) digit;
}
byte_len = byte_len2;
}
i++;
byte_len2 = byte_len;
}
return valueOf(bytes, byte_len2, negative, radix);
}
public static IntNum valueOf(byte[] digits, int byte_len, boolean negative, int radix) {
int[] words2 = new int[((byte_len / MPN.chars_per_word(radix)) + 1)];
int size = MPN.set_str(words2, digits, byte_len, radix);
if (size == 0) {
return zero();
}
if (words2[size - 1] < 0) {
int size2 = size + 1;
words2[size] = 0;
size = size2;
}
if (negative) {
negate(words2, words2, size);
}
return make(words2, size);
}
public static IntNum valueOf(String s) throws NumberFormatException {
return valueOf(s, 10);
}
public double doubleValue() {
if (this.words == null) {
return (double) this.ival;
}
if (this.ival <= 2) {
return (double) longValue();
}
if (isNegative()) {
return neg(this).roundToDouble(0, true, false);
}
return roundToDouble(0, false, false);
}
/* access modifiers changed from: 0000 */
public boolean checkBits(int n) {
boolean z = true;
if (n <= 0) {
return false;
}
if (this.words != null) {
int i = 0;
while (i < (n >> 5)) {
if (this.words[i] != 0) {
return true;
}
i++;
}
if ((n & 31) == 0 || (this.words[i] & ((1 << (n & 31)) - 1)) == 0) {
z = false;
}
return z;
} else if (n > 31 || (this.ival & ((1 << n) - 1)) != 0) {
return true;
} else {
return false;
}
}
public double roundToDouble(int exp, boolean neg, boolean remainder) {
int il = intLength();
int exp2 = exp + (il - 1);
if (exp2 < -1075) {
if (neg) {
return -0.0d;
}
return 0.0d;
} else if (exp2 > 1023) {
return neg ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
} else {
int ml = exp2 >= -1022 ? 53 : exp2 + 53 + 1022;
int excess_bits = il - (ml + 1);
long m = excess_bits > 0 ? this.words == null ? (long) (this.ival >> excess_bits) : MPN.rshift_long(this.words, this.ival, excess_bits) : longValue() << (-excess_bits);
if (exp2 == 1023 && (m >> 1) == 9007199254740991L) {
if (!remainder) {
if (!checkBits(il - ml)) {
return neg ? -1.7976931348623157E308d : Double.MAX_VALUE;
}
}
if (neg) {
return Double.NEGATIVE_INFINITY;
}
return Double.POSITIVE_INFINITY;
}
if ((1 & m) == 1 && ((2 & m) == 2 || remainder || checkBits(excess_bits))) {
m += 2;
if ((18014398509481984L & m) != 0) {
exp2++;
m >>= 1;
} else if (ml == 52 && (9007199254740992L & m) != 0) {
exp2++;
}
}
int exp3 = exp2 + 1023;
return Double.longBitsToDouble((neg ? Long.MIN_VALUE : 0) | (exp3 <= 0 ? 0 : ((long) exp3) << 52) | ((m >> 1) & -4503599627370497L));
}
}
public Numeric add(Object y, int k) {
if (y instanceof IntNum) {
return add(this, (IntNum) y, k);
}
if (y instanceof Numeric) {
return ((Numeric) y).addReversed(this, k);
}
throw new IllegalArgumentException();
}
public Numeric mul(Object y) {
if (y instanceof IntNum) {
return times(this, (IntNum) y);
}
if (y instanceof Numeric) {
return ((Numeric) y).mulReversed(this);
}
throw new IllegalArgumentException();
}
public Numeric div(Object y) {
if (y instanceof RatNum) {
RatNum r = (RatNum) y;
return RatNum.make(times(this, r.denominator()), r.numerator());
} else if (y instanceof Numeric) {
return ((Numeric) y).divReversed(this);
} else {
throw new IllegalArgumentException();
}
}
public void getAbsolute(int[] words2) {
int len;
if (this.words != null) {
len = this.ival;
int i = len;
while (true) {
i--;
if (i < 0) {
break;
}
words2[i] = this.words[i];
}
} else {
len = 1;
words2[0] = this.ival;
}
if (words2[len - 1] < 0) {
negate(words2, words2, len);
}
int i2 = words2.length;
while (true) {
i2--;
if (i2 > len) {
words2[i2] = 0;
} else {
return;
}
}
}
public static boolean negate(int[] dest, int[] src, int len) {
boolean negative;
long carry = 1;
if (src[len - 1] < 0) {
negative = true;
} else {
negative = false;
}
for (int i = 0; i < len; i++) {
long carry2 = carry + (((long) (src[i] ^ -1)) & 4294967295L);
dest[i] = (int) carry2;
carry = carry2 >> 32;
}
if (!negative || dest[len - 1] >= 0) {
return false;
}
return true;
}
public void setNegative(IntNum x) {
int len = x.ival;
if (x.words != null) {
realloc(len + 1);
if (negate(this.words, x.words, len)) {
int len2 = len + 1;
this.words[len] = 0;
len = len2;
}
this.ival = len;
} else if (len == Integer.MIN_VALUE) {
set(-((long) len));
} else {
set(-len);
}
}
public final void setNegative() {
setNegative(this);
}
public static IntNum abs(IntNum x) {
return x.isNegative() ? neg(x) : x;
}
public static IntNum neg(IntNum x) {
if (x.words == null && x.ival != Integer.MIN_VALUE) {
return make(-x.ival);
}
IntNum result = new IntNum(0);
result.setNegative(x);
return result.canonicalize();
}
public Numeric neg() {
return neg(this);
}
public int intLength() {
if (this.words == null) {
return MPN.intLength(this.ival);
}
return MPN.intLength(this.words, this.ival);
}
public void writeExternal(ObjectOutput out) throws IOException {
int i = 0;
int nwords = this.words == null ? 1 : wordsNeeded(this.words, this.ival);
if (nwords <= 1) {
if (this.words == null) {
i = this.ival;
} else if (this.words.length != 0) {
i = this.words[0];
}
if (i >= -1073741824) {
out.writeInt(i);
return;
}
out.writeInt(-2147483647);
out.writeInt(i);
return;
}
out.writeInt(Integer.MIN_VALUE | nwords);
while (true) {
nwords--;
if (nwords >= 0) {
out.writeInt(this.words[nwords]);
} else {
return;
}
}
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
int i = in.readInt();
if (i <= -1073741824) {
i &= ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_UNLIMITED;
if (i == 1) {
i = in.readInt();
} else {
int[] w = new int[i];
int j = i;
while (true) {
j--;
if (j < 0) {
break;
}
w[j] = in.readInt();
}
this.words = w;
}
}
this.ival = i;
}
public Object readResolve() throws ObjectStreamException {
return canonicalize();
}
public BigInteger asBigInteger() {
if (this.words == null || this.ival <= 2) {
return BigInteger.valueOf(longValue());
}
return new BigInteger(toString());
}
public BigDecimal asBigDecimal() {
if (this.words == null) {
return new BigDecimal(this.ival);
}
if (this.ival <= 2) {
return BigDecimal.valueOf(longValue());
}
return new BigDecimal(toString());
}
public boolean inRange(long lo, long hi) {
return compare(this, lo) >= 0 && compare(this, hi) <= 0;
}
public boolean inIntRange() {
return inRange(-2147483648L, 2147483647L);
}
public boolean inLongRange() {
return inRange(Long.MIN_VALUE, Long.MAX_VALUE);
}
}
| 29.182251 | 180 | 0.402188 |
8fb5467777be0950daac6c6d10eab5b3fcd55c91
| 511 |
package ru.intertrust.cm.core.dao.api.extension;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import ru.intertrust.cm.core.dao.api.ExtensionService;
/**
* Класс аннотации для точек расширения
*
* @author larin
*
*/
@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = { java.lang.annotation.ElementType.TYPE })
public @interface ExtensionPoint {
String filter() default "";
String context() default ExtensionService.PLATFORM_CONTEXT;
}
| 26.894737 | 64 | 0.763209 |
383774b0e1cf07d6de78615fcfe19e6bc8270734
| 1,346 |
package by.sir.max.library.listener;
import by.sir.max.library.command.JSPAttributeStorage;
import by.sir.max.library.entity.user.UserRole;
import by.sir.max.library.exception.LibraryServiceException;
import by.sir.max.library.factory.ServiceFactory;
import by.sir.max.library.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
public class SessionListener implements HttpSessionListener {
private static final Logger LOGGER = LogManager.getLogger(SessionListener.class);
private static final UserService userService = ServiceFactory.getInstance().getUserService();
@Override
public void sessionCreated(HttpSessionEvent se) {
se.getSession().setAttribute(JSPAttributeStorage.USER_ROLE, UserRole.GUEST.name());
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
String userLogin = (String) se.getSession().getAttribute(JSPAttributeStorage.USER_LOGIN);
if (userLogin != null) {
try {
userService.logOut(userLogin);
} catch (LibraryServiceException e) {
LOGGER.warn(e.getMessage(), e);
}
}
}
}
| 35.421053 | 97 | 0.736999 |
0747012b435f093d8a594c2084be7bff0b8cb844
| 3,366 |
package com.kosmx.emotecraft.mixin;
import com.kosmx.emotecraft.Emote;
import com.kosmx.emotecraft.Main;
import com.kosmx.emotecraft.config.EmoteHolder;
import com.kosmx.emotecraft.network.EmotePacket;
import com.kosmx.emotecraft.network.StopPacket;
import com.kosmx.emotecraft.playerInterface.EmotePlayerInterface;
import com.mojang.authlib.GameProfile;
import io.netty.buffer.Unpooled;
import net.fabricmc.fabric.api.network.ClientSidePacketRegistry;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.AbstractClientPlayerEntity;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.client.network.OtherClientPlayerEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import javax.annotation.Nullable;
@Mixin(AbstractClientPlayerEntity.class)
public abstract class EmotePlayerMixin extends PlayerEntity implements EmotePlayerInterface {
@Nullable
private Emote emote;
private int lastUpdated;
public EmotePlayerMixin(World world, BlockPos pos, float yaw, GameProfile profile) {
super(world, pos, yaw, profile);
}
@Override
public void playEmote(Emote emote) {
this.emote = emote;
}
@Override
@Nullable
public Emote getEmote(){
return this.emote;
}
@Override
public void resetLastUpdated() {
this.lastUpdated = 0;
}
@Override
public void tick() {
super.tick();
if(Emote.isRunningEmote(this.emote)){
this.bodyYaw = (this.bodyYaw * 3 + this.yaw)/4; //to set the body to the correct direction smooth.
if(this != MinecraftClient.getInstance().getCameraEntity() && MinecraftClient.getInstance().getCameraEntity() instanceof ClientPlayerEntity || EmoteHolder.canRunEmote(this)) {
this.emote.tick();
this.lastUpdated++;
if(this == MinecraftClient.getInstance().getCameraEntity() && MinecraftClient.getInstance().getCameraEntity() instanceof ClientPlayerEntity && lastUpdated >= 100){
if(emote.getStopTick() - emote.getCurrentTick() < 50 && !emote.isInfinite())return;
PacketByteBuf buf = new PacketByteBuf(Unpooled.buffer());
EmotePacket emotePacket = new EmotePacket(emote, this);
emotePacket.isRepeat = true;
emotePacket.write(buf);
ClientSidePacketRegistry.INSTANCE.sendToServer(Main.EMOTE_PLAY_NETWORK_PACKET_ID, buf);
lastUpdated = 0;
}
else if((this != MinecraftClient.getInstance().getCameraEntity() || MinecraftClient.getInstance().getCameraEntity() instanceof OtherClientPlayerEntity) && lastUpdated > 300){
this.emote.stop();
}
}
else {
emote.stop();
PacketByteBuf buf = new PacketByteBuf(Unpooled.buffer());
StopPacket packet = new StopPacket(this);
packet.write(buf);
ClientSidePacketRegistry.INSTANCE.sendToServer(Main.EMOTE_STOP_NETWORK_PACKET_ID, buf);
}
}
}
}
| 40.071429 | 190 | 0.680036 |
a29c7da11f6df25963af2fa584db1143e60a6267
| 1,132 |
package com.ioc.postprocessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
// 针对容器中的所用bean进行增强
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
Logger logger = LoggerFactory.getLogger(getClass());
// benPostProcessor
// 在 调用 setter 方法完成依赖注入之后
// 在初始化方法(init-method)被调用之前
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
logger.info("CustomerRequestService's postProcessBeforeInitialization() method has been invoked !");
//System.out.println(bean.getClass().getName());
//System.out.println(beanName);
return bean;
}
// 此方法在bean实例的初始化方法被调用之后调用
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
logger.info("CustomerRequestService's postProcessAfterInitialization() method has been invoked !");
return bean;
}
}
| 35.375 | 108 | 0.756184 |
536dec82cf04c68c35a35c0222e0f4cfd89b4ce7
| 4,782 |
/*
* 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.jackrabbit.mongomk.impl.json;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import org.apache.jackrabbit.mk.json.JsopBuilder;
import org.apache.jackrabbit.oak.commons.PathUtils;
/**
* <code>NormalizingJsopHandler</code>...
*/
public class NormalizingJsopHandler extends DefaultJsopHandler {
private final StringBuilder builder = new StringBuilder();
private Deque<String> commaStack = new ArrayDeque<String>(
Collections.singleton(""));
private Deque<String> pathStack = new ArrayDeque<String>(
Collections.singleton("/"));
public String getDiff() {
scopeFor("/");
return builder.toString();
}
@Override
public void nodeAdded(String parentPath, String name) {
String relPath = scopeFor(PathUtils.concat(parentPath, name));
if (pathStack.size() == 1) {
builder.append("+");
} else {
maybeAppendComma();
}
if (relPath.length() > 0) {
pathStack.addLast(relPath);
commaStack.addLast("");
}
builder.append(JsopBuilder.encode(relPath));
builder.append(":{");
resetComma();
}
@Override
public void nodeCopied(String rootPath,
String oldPath,
String newPath) {
scopeFor("/");
builder.append("*");
builder.append(JsopBuilder.encode(PathUtils.relativize("/", oldPath)));
builder.append(":");
builder.append(JsopBuilder.encode(PathUtils.relativize("/", newPath)));
}
@Override
public void nodeMoved(String rootPath, String oldPath, String newPath) {
scopeFor("/");
builder.append(">");
builder.append(JsopBuilder.encode(PathUtils.relativize("/", oldPath)));
builder.append(":");
builder.append(JsopBuilder.encode(PathUtils.relativize("/", newPath)));
}
@Override
public void nodeRemoved(String parentPath, String name) {
scopeFor("/");
builder.append("-");
builder.append(JsopBuilder.encode(PathUtils.relativize("/", concatPath(parentPath, name))));
}
@Override
public void propertySet(String path, String key, Object value, String rawValue) {
String relPath = scopeFor(path);
if (pathStack.size() == 1) {
builder.append("^");
} else {
maybeAppendComma();
}
builder.append(JsopBuilder.encode(concatPath(relPath, key)));
builder.append(":");
builder.append(rawValue);
}
/**
* Opens a new scope for the given path relative to the current path.
* @param path the path of the new scope.
* @return the remaining relative path needed for the given scope path.
*/
private String scopeFor(String path) {
// close brackets until path stack is the root, the same as path or
// an ancestor of path
while (pathStack.size() > 1
&& !path.equals(getCurrentPath())
&& !PathUtils.isAncestor(getCurrentPath(), path)) {
pathStack.removeLast();
commaStack.removeLast();
builder.append("}");
}
// remaining path for scope
return PathUtils.relativize(getCurrentPath(), path);
}
private String getCurrentPath() {
String path = "";
for (String element : pathStack) {
path = PathUtils.concat(path, element);
}
return path;
}
private String concatPath(String parent, String child) {
if (parent.length() == 0) {
return child;
} else {
return PathUtils.concat(parent, child);
}
}
private void resetComma() {
commaStack.removeLast();
commaStack.addLast("");
}
private void maybeAppendComma() {
builder.append(commaStack.removeLast());
commaStack.addLast(",");
}
}
| 32.753425 | 100 | 0.621288 |
7af5c30068de4f2a26417bc4793ccc38795dea3c
| 1,803 |
package no.nav.veilarbdirigent.client.veilarbdialog;
import io.vavr.control.Try;
import no.nav.common.rest.client.RestClient;
import no.nav.common.types.identer.AktorId;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.util.function.Supplier;
import static no.nav.common.rest.client.RestUtils.MEDIA_TYPE_JSON;
import static no.nav.common.rest.client.RestUtils.createBearerToken;
import static no.nav.common.utils.UrlUtils.joinPaths;
import static org.springframework.http.HttpHeaders.AUTHORIZATION;
public class VeilarbdialogClientImpl implements VeilarbdialogClient {
private final String apiUrl;
private final Supplier<String> serviceTokenSupplier;
private final OkHttpClient client;
public VeilarbdialogClientImpl(String apiUrl, Supplier<String> serviceTokenSupplier) {
this.apiUrl = apiUrl;
this.serviceTokenSupplier = serviceTokenSupplier;
this.client = RestClient.baseClient();
}
@Override
public Try<String> lagDialog(AktorId aktorId, String data) {
String url = joinPaths(apiUrl, "/api/dialog?aktorId=" + aktorId.get());
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(MEDIA_TYPE_JSON, data))
.addHeader(AUTHORIZATION, createBearerToken(serviceTokenSupplier.get()))
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
return Try.success(response.body().string());
} else {
return Try.failure(new RuntimeException(response.body().string()));
}
} catch (Exception e) {
return Try.failure(e);
}
}
}
| 33.388889 | 90 | 0.692734 |
833804e75423f56794d328b417060efd67e91524
| 3,605 |
package org.ovirt.engine.core.dao.provider;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.ovirt.engine.core.common.businessentities.OpenstackNetworkPluginType;
import org.ovirt.engine.core.common.businessentities.OpenstackNetworkProviderProperties;
import org.ovirt.engine.core.common.businessentities.Provider;
import org.ovirt.engine.core.common.businessentities.Provider.AdditionalProperties;
import org.ovirt.engine.core.common.businessentities.ProviderType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dao.BaseGenericDaoTestCase;
import org.ovirt.engine.core.dao.FixturesTool;
public class ProviderDaoTest extends BaseGenericDaoTestCase<Guid, Provider<?>, ProviderDao> {
@Override
protected Provider<?> generateNewEntity() {
Provider<AdditionalProperties> provider = new Provider<>();
provider.setId(generateNonExistingId());
provider.setName("brovider");
provider.setUrl("http://brovider.com/");
provider.setType(ProviderType.OPENSTACK_NETWORK);
OpenstackNetworkProviderProperties additionalProperties = new OpenstackNetworkProviderProperties();
additionalProperties.setReadOnly(Boolean.FALSE);
additionalProperties.setTenantName("10ant");
additionalProperties.setPluginType(OpenstackNetworkPluginType.LINUX_BRIDGE.name());
provider.setAdditionalProperties(additionalProperties);
provider.setAuthUrl("http://keystone-server:35357/v2.0/");
return provider;
}
@Override
protected void updateExistingEntity() {
existingEntity.setUrl("abc");
}
@Override
protected Guid getExistingEntityId() {
return new Guid("1115c1c6-cb15-4832-b2a4-023770607111");
}
@Override
protected ProviderDao prepareDao() {
return dbFacade.getProviderDao();
}
@Override
protected Guid generateNonExistingId() {
return Guid.newGuid();
}
@Override
protected int getEntitiesTotalCount() {
return 2;
}
@Test
public void getByName() throws Exception {
assertEquals(FixturesTool.PROVIDER_NAME, dao.getByName(FixturesTool.PROVIDER_NAME).getName());
}
@Test
public void getByNameCaseSensitive() throws Exception {
assertNull(dao.getByName(FixturesTool.PROVIDER_NAME.toUpperCase()));
}
@Test
public void getByNameNonExistant() throws Exception {
assertNull(dao.getByName(FixturesTool.PROVIDER_NAME + FixturesTool.PROVIDER_NAME));
}
@Test
public void searchQueryByExistentName() throws Exception {
assertEquals(FixturesTool.PROVIDER_NAME,
dao.getAllWithQuery(String.format("SELECT * FROM providers WHERE name = '%s'",
FixturesTool.PROVIDER_NAME)).get(0).getName());
}
@Test
public void searchQueryByNonExistentName() throws Exception {
assertTrue(dao.getAllWithQuery("SELECT * FROM providers WHERE name = 'foo'").isEmpty());
}
@Test
public void searchQueryByExistentType() throws Exception {
assertEquals(FixturesTool.PROVIDER_NAME,
dao.getAllWithQuery(String.format("SELECT * FROM providers WHERE provider_type = '%s'",
FixturesTool.PROVIDER_TYPE.name())).get(0).getName());
}
@Test
public void searchQueryByNonExistentType() throws Exception {
assertTrue(dao.getAllWithQuery("SELECT * FROM providers WHERE provider_type = 'foo'").isEmpty());
}
}
| 36.414141 | 107 | 0.717892 |
d2c7d5017136d399c1113f3d410ff589f4518125
| 6,331 |
/**
*/
package org.mobadsl.semantic.model.moba;
import java.util.List;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc --> A representation of the model object '
* <em><b>Server</b></em>'. <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link org.mobadsl.semantic.model.moba.MobaServer#getName <em>Name</em>}</li>
* <li>{@link org.mobadsl.semantic.model.moba.MobaServer#getUrlString <em>Url String</em>}</li>
* <li>{@link org.mobadsl.semantic.model.moba.MobaServer#getUrlConst <em>Url Const</em>}</li>
* <li>{@link org.mobadsl.semantic.model.moba.MobaServer#getSuperType <em>Super Type</em>}</li>
* <li>{@link org.mobadsl.semantic.model.moba.MobaServer#getServices <em>Services</em>}</li>
* <li>{@link org.mobadsl.semantic.model.moba.MobaServer#getAuthorization <em>Authorization</em>}</li>
* </ul>
*
* @see org.mobadsl.semantic.model.moba.MobaPackage#getMobaServer()
* @model
* @generated
*/
public interface MobaServer extends MobaApplicationFeature {
/**
* Returns the value of the '<em><b>Name</b></em>' attribute. <!--
* begin-user-doc -->
* <p>
* If the meaning of the '<em>Name</em>' attribute isn't clear, there really
* should be more of a description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see org.mobadsl.semantic.model.moba.MobaPackage#getMobaServer_Name()
* @model
* @generated
*/
String getName();
/**
* Sets the value of the '{@link org.mobadsl.semantic.model.moba.MobaServer#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
/**
* Returns the value of the '<em><b>Url String</b></em>' attribute. <!--
* begin-user-doc -->
* <p>
* If the meaning of the '<em>Url String</em>' attribute isn't clear, there
* really should be more of a description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>Url String</em>' attribute.
* @see #setUrlString(String)
* @see org.mobadsl.semantic.model.moba.MobaPackage#getMobaServer_UrlString()
* @model
* @generated
*/
String getUrlString();
/**
* Sets the value of the '{@link org.mobadsl.semantic.model.moba.MobaServer#getUrlString <em>Url String</em>}' attribute.
* <!-- begin-user-doc --> <!--
* end-user-doc -->
* @param value the new value of the '<em>Url String</em>' attribute.
* @see #getUrlString()
* @generated
*/
void setUrlString(String value);
/**
* Returns the value of the '<em><b>Url Const</b></em>' reference. <!--
* begin-user-doc -->
* <p>
* If the meaning of the '<em>Url Const</em>' reference isn't clear, there
* really should be more of a description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>Url Const</em>' reference.
* @see #setUrlConst(MobaConstant)
* @see org.mobadsl.semantic.model.moba.MobaPackage#getMobaServer_UrlConst()
* @model
* @generated
*/
MobaConstant getUrlConst();
/**
* Sets the value of the '
* {@link org.mobadsl.semantic.model.moba.MobaServer#getUrlConst
* <em>Url Const</em>}' reference. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @param value
* the new value of the '<em>Url Const</em>' reference.
* @see #getUrlConst()
* @generated
*/
void setUrlConst(MobaConstant value);
/**
* Returns the value of the '<em><b>Super Type</b></em>' reference. <!--
* begin-user-doc -->
* <p>
* If the meaning of the '<em>Super Type</em>' reference isn't clear, there
* really should be more of a description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>Super Type</em>' reference.
* @see #setSuperType(MobaServer)
* @see org.mobadsl.semantic.model.moba.MobaPackage#getMobaServer_SuperType()
* @model
* @generated
*/
MobaServer getSuperType();
/**
* Sets the value of the '{@link org.mobadsl.semantic.model.moba.MobaServer#getSuperType <em>Super Type</em>}' reference.
* <!-- begin-user-doc --> <!--
* end-user-doc -->
* @param value the new value of the '<em>Super Type</em>' reference.
* @see #getSuperType()
* @generated
*/
void setSuperType(MobaServer value);
/**
* Returns the value of the '<em><b>Services</b></em>' reference list.
* The list contents are of type {@link org.mobadsl.semantic.model.moba.MobaREST}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Services</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Services</em>' reference list.
* @see org.mobadsl.semantic.model.moba.MobaPackage#getMobaServer_Services()
* @model
* @generated
*/
EList<MobaREST> getServices();
/**
* Returns the value of the '<em><b>Authorization</b></em>' reference list.
* The list contents are of type
* {@link org.mobadsl.semantic.model.moba.MobaAuthorization}. <!--
* begin-user-doc -->
* <p>
* If the meaning of the '<em>Authorization</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>Authorization</em>' reference list.
* @see org.mobadsl.semantic.model.moba.MobaPackage#getMobaServer_Authorization()
* @model
* @generated
*/
MobaAuthorization getAuthorization();
/**
* Sets the value of the '{@link org.mobadsl.semantic.model.moba.MobaServer#getAuthorization <em>Authorization</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Authorization</em>' reference.
* @see #getAuthorization()
* @generated
*/
void setAuthorization(MobaAuthorization value);
/**
* Returns all services including superTypes.
*
* @return
*/
public List<MobaREST> getAllServices();
/**
* Returns services required for generator stuff.
*
* @return
*/
public List<MobaREST> getGenServices();
/**
* Returns the URL of the server using {@link #getUrlString()} and
* {@link #getUrlConst()}.
*
* @return
*/
public String getURL();
} // MobaServer
| 30.584541 | 129 | 0.643026 |
15923be29ec99bd6ab3e1e5d98756e5dd4fade89
| 2,979 |
/*
* (C) Copyright IBM Corp. 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.ibm.cloud.networking.dns_svcs.v1.model;
import java.util.Map;
import com.google.gson.annotations.SerializedName;
import com.ibm.cloud.sdk.core.service.model.GenericModel;
/**
* Resource record details.
*/
public class ResourceRecord extends GenericModel {
/**
* Type of the resource record.
*/
public interface Type {
/** A. */
String A = "A";
/** AAAA. */
String AAAA = "AAAA";
/** CNAME. */
String CNAME = "CNAME";
/** MX. */
String MX = "MX";
/** SRV. */
String SRV = "SRV";
/** TXT. */
String TXT = "TXT";
/** PTR. */
String PTR = "PTR";
}
protected String id;
@SerializedName("created_on")
protected String createdOn;
@SerializedName("modified_on")
protected String modifiedOn;
protected String name;
protected String type;
protected Long ttl;
protected Map<String, Object> rdata;
protected String service;
protected String protocol;
/**
* Gets the id.
*
* Identifier of the resource record.
*
* @return the id
*/
public String getId() {
return id;
}
/**
* Gets the createdOn.
*
* the time when a resource record is created.
*
* @return the createdOn
*/
public String getCreatedOn() {
return createdOn;
}
/**
* Gets the modifiedOn.
*
* the recent time when a resource record is modified.
*
* @return the modifiedOn
*/
public String getModifiedOn() {
return modifiedOn;
}
/**
* Gets the name.
*
* Name of the resource record.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Gets the type.
*
* Type of the resource record.
*
* @return the type
*/
public String getType() {
return type;
}
/**
* Gets the ttl.
*
* Time to live in second.
*
* @return the ttl
*/
public Long getTtl() {
return ttl;
}
/**
* Gets the rdata.
*
* Content of the resource record.
*
* @return the rdata
*/
public Map<String, Object> getRdata() {
return rdata;
}
/**
* Gets the service.
*
* Only used for SRV record.
*
* @return the service
*/
public String getService() {
return service;
}
/**
* Gets the protocol.
*
* Only used for SRV record.
*
* @return the protocol
*/
public String getProtocol() {
return protocol;
}
}
| 18.974522 | 118 | 0.613629 |
746de17f3f28c667a59b2eaae1801236d8b61fcb
| 1,105 |
package ObjectTracker;
import java.io.*;
/**
* This class handles the input stream of a
* running program.
*
* @author Eoin O'Connor
* @see ObjectTracker
* @see OutputStreamCopier
*/
public class InputStreamCopier implements Runnable
{
/**
* The output stream that is written to.
*/
private OutputStream to;
/**
* Used to buffer the stream of bytes
* before they are sent to the output
* stream.
*/
private byte [] buffer;
/**
* Constructor: sets the output stream and
* and the buffer.
*
* @param to The output stream to attach to.
* @param bytes The bytes to buffer.
*/
public InputStreamCopier(OutputStream to,byte [] bytes)
{
this.to = to;
buffer = bytes;
}
/**
* Sends the bytes in the buffer to the
* output stream and flushes the output
* stream.
*/
public void run()
{
try
{
to.write(buffer,0,buffer.length);
to.flush();
}
catch(IOException e)
{
// give up
e.printStackTrace();
}
}
}
| 19.385965 | 58 | 0.571041 |
698b480112fe3c3547d5d3fd590c50a693f1776d
| 552 |
package com.bitcola.exchange.data;
import lombok.Data;
import org.influxdb.annotation.Column;
import org.influxdb.annotation.Measurement;
import java.time.Instant;
/*
* @author:wx
* @description:
* @create:2018-08-29 23:47
*/
@Measurement(name = "kline_new")
@Data
public class KlinesData {
@Column(name = "time")
Instant time;
@Column(name="first")
double first;
@Column(name="max")
double max;
@Column(name="min")
double min;
@Column(name="last")
double last;
@Column(name="sum")
double sum;
}
| 18.4 | 43 | 0.65942 |
ee6dad257a51d699f80abd3fe35cc35d28868f12
| 793 |
package com.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.rest.entities.Endereco;
import com.rest.entities.User;
import com.rest.repositories.UserRepository;
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
private UserRepository userRepository;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
userRepository.save(new User("Nome1","a@b.com",new Endereco("86280000","Rua A","Numero 1","PR","Urai","Centro","Centro")));
}
}
| 29.37037 | 127 | 0.790668 |
20f3cec011f5053b40cd4c90fb01bc7d4d159acc
| 1,712 |
package com.jpmorgan.cakeshop.util;
import java.util.HashMap;
import java.util.Map;
import com.jpmorgan.cakeshop.error.APIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.jpmorgan.cakeshop.util.FileUtils.expandPath;
public class CakeshopUtils {
private static final Logger LOG = LoggerFactory.getLogger(CakeshopUtils.class);
public static final String SIMPLE_RESULT = "_result";
public static String formatEnodeUrl(String address, String ip, String port, String raftPort) {
String enodeurl = String.format("enode://%s@%s:%s", address, ip, port);
if (raftPort != null && raftPort.trim().length() > 0 && Integer.parseInt(raftPort) > 0) {
enodeurl += "?raftport=" + raftPort;
}
return enodeurl;
}
public static String getSolcPath() {
// setup needed paths
String binPath = System.getProperty("eth.bin.dir");
if (StringUtils.isBlank(binPath)) {
binPath = FileUtils.getClasspathName("bin");
}
return expandPath(binPath, "solc-cli", "node_modules", "solc-cakeshop-cli", "bin", "solc");
}
@SuppressWarnings("unchecked")
public static Map<String, Object> processWeb3Response(Object data, org.web3j.protocol.core.Response.Error e) throws APIException {
if(e != null ) {
throw new APIException(e.getMessage());
}
if (!(data instanceof Map)) {
// Handle case where a simple value is returned instead of a map (int, bool, or string)
Map<String, Object> res = new HashMap<>();
res.put(SIMPLE_RESULT, data);
return res;
}
return (Map<String, Object>) data;
}
}
| 33.568627 | 134 | 0.650701 |
f87e2ba52a78cf366119ee275e097ee987df2f1b
| 6,310 |
package nguy0001;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import nguy0001.astar.AStarSearch;
import nguy0001.astar.FollowPathAction;
import nguy0001.astar.Graph;
import nguy0001.astar.Vertex;
import spacesettlers.actions.AbstractAction;
import spacesettlers.actions.DoNothingAction;
import spacesettlers.actions.MoveToObjectAction;
import spacesettlers.actions.PurchaseCosts;
import spacesettlers.actions.PurchaseTypes;
import spacesettlers.clients.TeamClient;
import spacesettlers.graphics.SpacewarGraphics;
import spacesettlers.objects.AbstractActionableObject;
import spacesettlers.objects.AbstractObject;
import spacesettlers.objects.Asteroid;
import spacesettlers.objects.Base;
import spacesettlers.objects.Beacon;
import spacesettlers.objects.Flag;
import spacesettlers.objects.Ship;
import spacesettlers.objects.powerups.SpaceSettlersPowerupEnum;
import spacesettlers.objects.resources.ResourcePile;
import spacesettlers.simulator.Toroidal2DPhysics;
import spacesettlers.utilities.Position;
/**
* Just a beacon collector but it uses Astar (to show how to do it) and shows the Astar graphics
*
* @author amy
*/
public class ExampleAStarClient extends TeamClient {
FollowPathAction followPathAction;
HashMap <UUID, Graph> graphByShip;
int currentSteps;
int REPLAN_STEPS = 5;
boolean flagCollected = false;
/**
* Assigns ships to asteroids and beacons, as described above
*/
public Map<UUID, AbstractAction> getMovementStart(Toroidal2DPhysics space,
Set<AbstractActionableObject> actionableObjects) {
HashMap<UUID, AbstractAction> actions = new HashMap<UUID, AbstractAction>();
// loop through each ship
for (AbstractObject actionable : actionableObjects) {
if (actionable instanceof Ship) {
Ship ship = (Ship) actionable;
AbstractAction current = ship.getCurrentAction();
//If flagShip
if ((current == null || currentSteps >= REPLAN_STEPS) && flagCollected == false) {
Flag objective = getEnemyFlag(space);
AbstractAction action = getAStarPathToGoal(space, ship, objective.getPosition());
actions.put(ship.getId(), action);
currentSteps = 0;
}
//return to base ASAP
if(ship.isCarryingFlag() == true) {
flagCollected = true;
Base home = findNearestBase(space, ship);
AbstractAction action = getAStarPathToGoal(space,ship,home.getPosition());
actions.put(ship.getId(), action);
}
if (current == null || currentSteps >= REPLAN_STEPS) {
Beacon beacon = pickNearestBeacon(space, ship);
AbstractAction action = getAStarPathToGoal(space, ship, beacon.getPosition());
actions.put(ship.getId(), action);
currentSteps = 0;
}
} else {
// it is a base. Do nothing
actions.put(actionable.getId(), new DoNothingAction());
}
}
currentSteps++;
return actions;
}
private Base findNearestBase(Toroidal2DPhysics space, Ship ship) {
double minDistance = Double.MAX_VALUE;
Base nearestBase = null;
for (Base base : space.getBases()) {
if (base.getTeamName().equalsIgnoreCase(ship.getTeamName())) {
double dist = space.findShortestDistance(ship.getPosition(), base.getPosition());
if (dist < minDistance) {
minDistance = dist;
nearestBase = base;
}
}
}
return nearestBase;
}
private Flag getEnemyFlag(Toroidal2DPhysics space) {
Flag enemyFlag = null;
for (Flag flag : space.getFlags()) {
if (flag.getTeamName().equalsIgnoreCase(getTeamName())) {
continue;
} else {
enemyFlag = flag;
}
}
return enemyFlag;
}
/**
* Follow an aStar path to the goal
* @param space
* @param ship
* @param goalPosition
* @return
*/
private AbstractAction getAStarPathToGoal(Toroidal2DPhysics space, Ship ship, Position goalPosition) {
AbstractAction newAction;
Graph graph = AStarSearch.createGraphToGoalWithBeacons(space, ship, goalPosition, new Random());
Vertex[] path = graph.findAStarPath(space);
followPathAction = new FollowPathAction(path);
//followPathAction.followNewPath(path);
newAction = followPathAction.followPath(space, ship);
graphByShip.put(ship.getId(), graph);
return newAction;
}
/**
* Find the nearest beacon to this ship
* @param space
* @param ship
* @return
*/
private Beacon pickNearestBeacon(Toroidal2DPhysics space, Ship ship) {
// get the current beacons
Set<Beacon> beacons = space.getBeacons();
Beacon closestBeacon = null;
double bestDistance = Double.POSITIVE_INFINITY;
for (Beacon beacon : beacons) {
double dist = space.findShortestDistance(ship.getPosition(), beacon.getPosition());
if (dist < bestDistance) {
bestDistance = dist;
closestBeacon = beacon;
}
}
return closestBeacon;
}
@Override
public void getMovementEnd(Toroidal2DPhysics space, Set<AbstractActionableObject> actionableObjects) {
ArrayList<Asteroid> finishedAsteroids = new ArrayList<Asteroid>();
}
@Override
public void initialize(Toroidal2DPhysics space) {
graphByShip = new HashMap<UUID, Graph>();
currentSteps = 0;
}
@Override
public void shutDown(Toroidal2DPhysics space) {
// TODO Auto-generated method stub
}
@Override
public Set<SpacewarGraphics> getGraphics() {
HashSet<SpacewarGraphics> graphics = new HashSet<SpacewarGraphics>();
if (graphByShip != null) {
for (Graph graph : graphByShip.values()) {
// uncomment to see the full graph
//graphics.addAll(graph.getAllGraphics());
graphics.addAll(graph.getSolutionPathGraphics());
}
}
HashSet<SpacewarGraphics> newGraphicsClone = (HashSet<SpacewarGraphics>) graphics.clone();
graphics.clear();
return newGraphicsClone;
}
@Override
/**
* Never purchases
*/
public Map<UUID, PurchaseTypes> getTeamPurchases(Toroidal2DPhysics space,
Set<AbstractActionableObject> actionableObjects,
ResourcePile resourcesAvailable,
PurchaseCosts purchaseCosts) {
return null;
}
/**
* No shooting
*
* @param space
* @param actionableObjects
* @return
*/
@Override
public Map<UUID, SpaceSettlersPowerupEnum> getPowerups(Toroidal2DPhysics space,
Set<AbstractActionableObject> actionableObjects) {
return null;
}
}
| 27.316017 | 103 | 0.730745 |
2c7426bea2a43d32cc1bbeef51b8d9f7eb58839e
| 1,228 |
package com.penglecode.xmodule.examples.springcloud.api.service;
import java.util.List;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.penglecode.xmodule.examples.springcloud.api.model.Joke;
import com.penglecode.xmodule.examples.springcloud.api.model.OpenApiResult;
/**
* 基于https://api.apiopen.top/api.html上的开放API接口
*
* 此处通过@FeignClient(name="openapi")使得JokeApiService直连api.apiopen.top
*
* @author pengpeng
* @date 2020年1月18日 下午5:18:17
*/
@FeignClient(name="openapi", qualifier="jokeApiService", contextId="jokeApiService")
public interface JokeApiService {
@GetMapping(value="/getSingleJoke", produces=MediaType.APPLICATION_JSON_VALUE)
public OpenApiResult<Joke> getJokeById(@RequestParam(name="sid") String sid);
@GetMapping(value="/getJoke")
public OpenApiResult<List<Joke>> getJokeList(@RequestParam(name = "type", required = false) String type,
@RequestParam(name = "page", defaultValue = "1") Integer page,
@RequestParam(name = "count", defaultValue = "10") Integer count);
}
| 37.212121 | 106 | 0.761401 |
f10d14fae7f14c73b0c86f3f10185eb544bcfa49
| 223 |
package work.step;
/**
* 2018/6/29
* @author dylan.
* Home: http://www.devdylan.cn
*/
public enum State {
/**
* wait to this step
*/
WAIT,
/**
* in this step
*/
RUNNING,
/**
* finished
*/
FINISHED,
}
| 10.136364 | 31 | 0.538117 |
7c1c830fe009e16e751425dcf4a0a5b57148ad84
| 16,143 |
package org.point85.app.reason;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.point85.app.AppUtils;
import org.point85.app.ImageManager;
import org.point85.app.Images;
import org.point85.app.ReasonNode;
import org.point85.app.designer.DesignerApplication;
import org.point85.app.designer.DesignerDialogController;
import org.point85.app.designer.DesignerLocalizer;
import org.point85.domain.oee.TimeLoss;
import org.point85.domain.persistence.PersistenceService;
import org.point85.domain.plant.Reason;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.stage.FileChooser;
/**
* Controller for editing and viewing reasons.
*
* @author Kent Randall
*
*/
public class ReasonEditorController extends DesignerDialogController {
// list of edited reasons
private final Set<TreeItem<ReasonNode>> editedReasonItems = new HashSet<>();
// Reason being edited or viewed
private TreeItem<ReasonNode> selectedReasonItem;
// file of last import
private File selectedFile;
// reason hierarchy
@FXML
private TreeView<ReasonNode> tvReasons;
@FXML
private Button btNew;
@FXML
private Button btSave;
@FXML
private Button btRefresh;
@FXML
private Button btDelete;
@FXML
private Button btImport;
@FXML
private TextField tfName;
@FXML
private TextArea taDescription;
@FXML
private ComboBox<TimeLoss> cbLosses;
@FXML
private MenuItem miClearSelection;
@FXML
private MenuItem miRefreshAll;
@FXML
private MenuItem miSaveAll;
// extract the Reason name from the tree item
public Reason getSelectedReason() {
Reason reason = null;
if (selectedReasonItem != null) {
reason = selectedReasonItem.getValue().getReason();
}
return reason;
}
// initialize
public void initialize(DesignerApplication app) throws Exception {
// main app
setApp(app);
// images for buttons
setImages();
// add the tree view listener for reason selection
tvReasons.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, newValue) -> {
try {
onSelectReason(oldValue, newValue);
} catch (Exception e) {
AppUtils.showErrorDialog(e);
}
});
tvReasons.setShowRoot(false);
// fill in the top-level reason nodes
populateTopReasonNodes();
// loss categories
List<TimeLoss> losses = new ArrayList<>();
Collections.addAll(losses, TimeLoss.values());
Collections.sort(losses, new Comparator<TimeLoss>() {
@Override
public int compare(TimeLoss o1, TimeLoss o2) {
return o1.toString().compareTo(o2.toString());
}
});
cbLosses.getItems().addAll(losses);
}
private void addEditedReason(TreeItem<ReasonNode> item) {
if (!editedReasonItems.contains(item)) {
// check for parent
if (item.getParent() != null && editedReasonItems.contains(item.getParent())) {
return;
}
editedReasonItems.add(item);
}
}
// reason selected in the hierarchy
private void onSelectReason(TreeItem<ReasonNode> oldItem, TreeItem<ReasonNode> newItem) {
if (newItem == null) {
return;
}
// new attributes
selectedReasonItem = newItem;
Reason selectedReason = newItem.getValue().getReason();
displayAttributes(selectedReason);
// show the children too
Set<Reason> children = selectedReason.getChildren();
List<Reason> sortedChildren = new ArrayList<>(children);
Collections.sort(sortedChildren);
boolean hasTreeChildren = !newItem.getChildren().isEmpty();
// check to see if the node's children have been previously shown
if (!hasTreeChildren) {
newItem.getChildren().clear();
for (Reason child : children) {
TreeItem<ReasonNode> entityItem = new TreeItem<>(new ReasonNode(child));
newItem.getChildren().add(entityItem);
entityItem.setGraphic(ImageManager.instance().getImageView(Images.REASON));
}
}
newItem.setExpanded(true);
}
// images for editor buttons
@Override
protected void setImages() {
super.setImages();
// new
btNew.setGraphic(ImageManager.instance().getImageView(Images.NEW));
btNew.setContentDisplay(ContentDisplay.RIGHT);
// save
btSave.setGraphic(ImageManager.instance().getImageView(Images.SAVE));
btSave.setContentDisplay(ContentDisplay.RIGHT);
// refresh
btRefresh.setGraphic(ImageManager.instance().getImageView(Images.REFRESH));
btRefresh.setContentDisplay(ContentDisplay.RIGHT);
// delete
btDelete.setGraphic(ImageManager.instance().getImageView(Images.DELETE));
btDelete.setContentDisplay(ContentDisplay.RIGHT);
// import
btImport.setGraphic(ImageManager.instance().getImageView(Images.IMPORT));
btImport.setContentDisplay(ContentDisplay.RIGHT);
// context menu
miSaveAll.setGraphic(ImageManager.instance().getImageView(Images.SAVE_ALL));
miRefreshAll.setGraphic(ImageManager.instance().getImageView(Images.REFRESH_ALL));
miClearSelection.setGraphic(ImageManager.instance().getImageView(Images.CLEAR));
}
// show the Reason attributes
private void displayAttributes(Reason reason) {
if (reason == null) {
return;
}
// name
tfName.setText(reason.getName());
// description
taDescription.setText(reason.getDescription());
// loss category
cbLosses.getSelectionModel().select(reason.getLossCategory());
}
// populate the top-level tree view reasons
private void populateTopReasonNodes() throws Exception {
tvReasons.getSelectionModel().clearSelection();
// fetch the reasons
List<Reason> reasons = PersistenceService.instance().fetchTopReasons();
Collections.sort(reasons);
// add them to the root reason
ObservableList<TreeItem<ReasonNode>> children = getRootReasonItem().getChildren();
children.clear();
for (Reason reason : reasons) {
TreeItem<ReasonNode> reasonItem = new TreeItem<>(new ReasonNode(reason));
children.add(reasonItem);
reasonItem.setGraphic(ImageManager.instance().getImageView(Images.REASON));
}
// refresh tree view
getRootReasonItem().setExpanded(true);
tvReasons.refresh();
}
// the single root for all reasons
private TreeItem<ReasonNode> getRootReasonItem() {
if (tvReasons.getRoot() == null) {
Reason rootReason = new Reason();
rootReason.setName(Reason.ROOT_REASON_NAME);
tvReasons.setRoot(new TreeItem<>(new ReasonNode(rootReason)));
}
return tvReasons.getRoot();
}
@FXML
private void onNewReason() {
try {
// main attributes
this.tfName.clear();
this.tfName.requestFocus();
this.taDescription.clear();
this.cbLosses.getSelectionModel().clearSelection();
this.selectedReasonItem = null;
} catch (Exception e) {
AppUtils.showErrorDialog(e);
}
}
// set the Reason attributes from the UI
private boolean setAttributes(TreeItem<ReasonNode> reasonItem) throws Exception {
boolean isDirty = false;
if (reasonItem == null) {
return isDirty;
}
Reason reason = reasonItem.getValue().getReason();
// name
String name = this.tfName.getText().trim();
if (name.length() == 0) {
throw new Exception(DesignerLocalizer.instance().getErrorString("no.name"));
}
if (!name.equals(reason.getName())) {
reason.setName(name);
isDirty = true;
}
// description
String description = this.taDescription.getText();
if (!description.equals(reason.getDescription())) {
reason.setDescription(description);
isDirty = true;
}
// loss
TimeLoss loss = cbLosses.getSelectionModel().getSelectedItem();
if (loss != null && !loss.equals(reason.getLossCategory())) {
reason.setLossCategory(loss);
isDirty = true;
}
if (isDirty) {
reasonItem.setGraphic(ImageManager.instance().getImageView(Images.CHANGED));
addEditedReason(reasonItem);
}
return isDirty;
}
private boolean createReason() {
try {
// parent reason
TreeItem<ReasonNode> parentItem = this.tvReasons.getSelectionModel().getSelectedItem();
if (parentItem == null) {
// confirm
ButtonType type = AppUtils
.showConfirmationDialog(DesignerLocalizer.instance().getLangString("add.reason"));
if (type.equals(ButtonType.CANCEL)) {
return false;
}
// add to all reasons
parentItem = tvReasons.getRoot();
} else {
// confirm
ButtonType type = AppUtils.showConfirmationDialog(DesignerLocalizer.instance()
.getLangString("add.child.reason", parentItem.getValue().getReason().getName()));
if (type.equals(ButtonType.CANCEL)) {
return false;
}
}
Reason parentReason = parentItem.getValue().getReason();
// new child
Reason newReason = new Reason();
selectedReasonItem = new TreeItem<>(new ReasonNode(newReason));
setAttributes(selectedReasonItem);
// add new child reason if not a top level
if (!parentReason.getName().equals(Reason.ROOT_REASON_NAME)) {
parentReason.addChild(newReason);
parentItem.setGraphic(ImageManager.instance().getImageView(Images.CHANGED));
}
// add to tree view
parentItem.getChildren().add(selectedReasonItem);
selectedReasonItem.setGraphic(ImageManager.instance().getImageView(Images.CHANGED));
addEditedReason(selectedReasonItem);
parentItem.setExpanded(true);
} catch (Exception e) {
AppUtils.showErrorDialog(e);
}
return true;
}
private void resetGraphic(TreeItem<ReasonNode> parentItem) throws Exception {
parentItem.setGraphic(ImageManager.instance().getImageView(Images.REASON));
for (TreeItem<ReasonNode> reasonItem : parentItem.getChildren()) {
resetGraphic(reasonItem);
}
}
@FXML
private void onSaveReason() {
try {
if (selectedReasonItem == null) {
// create
if (!createReason()) {
return;
}
} else {
// update
setAttributes(selectedReasonItem);
}
// save the reason
Reason reason = getSelectedReason();
Reason saved = (Reason) PersistenceService.instance().save(reason);
selectedReasonItem.getValue().setReason(saved);
resetGraphic(selectedReasonItem.getParent());
editedReasonItems.remove(selectedReasonItem);
tvReasons.refresh();
} catch (Exception e) {
// remove from persistence unit
AppUtils.showErrorDialog(e);
}
}
@FXML
private void onSaveAllReasons() {
try {
// current reason could have been edited
setAttributes(selectedReasonItem);
// save all modified reasons
for (TreeItem<ReasonNode> editedReasonItem : editedReasonItems) {
ReasonNode node = editedReasonItem.getValue();
Reason saved = (Reason) PersistenceService.instance().save(node.getReason());
node.setReason(saved);
editedReasonItem.setGraphic(ImageManager.instance().getImageView(Images.REASON));
}
editedReasonItems.clear();
tvReasons.refresh();
} catch (Exception e) {
AppUtils.showErrorDialog(e);
}
}
@FXML
private void onDeleteReason() {
Reason selectedReason = getSelectedReason();
if (selectedReason == null) {
AppUtils.showErrorDialog(DesignerLocalizer.instance().getErrorString("no.reason.selected"));
return;
}
// confirm
ButtonType type = AppUtils.showConfirmationDialog(
DesignerLocalizer.instance().getLangString("delete.reason", selectedReason.getName()));
if (type.equals(ButtonType.CANCEL)) {
return;
}
try {
Reason parentReason = selectedReason.getParent();
if (parentReason != null) {
// remove from parent with orphan removal
parentReason.removeChild(selectedReason);
PersistenceService.instance().save(parentReason);
} else {
// cascade delete
PersistenceService.instance().delete(selectedReason);
}
// remove this reason from the tree
TreeItem<ReasonNode> reasonItem = tvReasons.getSelectionModel().getSelectedItem();
TreeItem<ReasonNode> parentNode = reasonItem.getParent();
parentNode.getChildren().remove(reasonItem);
// clear fields
onNewReason();
tvReasons.getSelectionModel().clearSelection();
tvReasons.refresh();
parentNode.setExpanded(true);
} catch (Exception e) {
AppUtils.showErrorDialog(e);
}
}
@FXML
private void onClearSelection() {
this.tvReasons.getSelectionModel().clearSelection();
}
@FXML
private void onRefreshReason() {
try {
if (getSelectedReason() == null) {
return;
}
if (getSelectedReason().getKey() != null) {
// read from database
Reason reason = PersistenceService.instance().fetchReasonByKey(getSelectedReason().getKey());
selectedReasonItem.getValue().setReason(reason);
resetGraphic(selectedReasonItem.getParent());
displayAttributes(reason);
} else {
// remove from tree
selectedReasonItem.getParent().getChildren().remove(selectedReasonItem);
}
tvReasons.refresh();
} catch (Exception e) {
AppUtils.showErrorDialog(e);
}
}
@FXML
private void onRefreshAllReasons() {
try {
populateTopReasonNodes();
onNewReason();
} catch (Exception e) {
AppUtils.showErrorDialog(e);
}
}
@Override
@FXML
protected void onCancel() {
// close dialog with current reason set to null
super.onCancel();
}
@FXML
private void onImportReasons() {
try {
// show file chooser
FileChooser fileChooser = new FileChooser();
if (selectedFile != null) {
fileChooser.setInitialDirectory(selectedFile.getParentFile());
}
selectedFile = fileChooser.showOpenDialog(null);
if (selectedFile == null) {
return;
}
// first pass to create the reasons
Map<Reason, String> parentReasons = new HashMap<>();
// read each line
BufferedReader br = new BufferedReader(new FileReader(selectedFile));
String line = null;
try {
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
if (values.length > 0 && values[0] == null || values[0].trim().length() == 0) {
throw new Exception(DesignerLocalizer.instance().getErrorString("no.name"));
}
// name
String name = values[0].trim();
// description
String description = null;
if (values.length > 1 && values[1] != null && values[1].trim().length() > 0) {
description = values[1].trim();
}
// loss
String lossName = null;
if (values.length > 2 && values[2] != null && values[2].trim().length() > 0) {
lossName = values[2].trim();
}
TimeLoss loss = null;
if (lossName != null && lossName.length() > 0) {
loss = TimeLoss.valueOf(lossName);
}
// parent
String parentName = null;
if (values.length > 3 && values[2].trim().length() > 0) {
parentName = values[3].trim();
}
Reason reason = PersistenceService.instance().fetchReasonByName(name);
if (reason != null) {
// update
reason.setName(name);
reason.setDescription(description);
reason.setLossCategory(loss);
} else {
// new reason
reason = new Reason(name, description);
reason.setLossCategory(loss);
}
Reason savedReason = (Reason) PersistenceService.instance().save(reason);
if (parentName != null) {
parentReasons.put(savedReason, parentName);
}
}
} finally {
br.close();
}
// second pass
for (Entry<Reason, String> entry : parentReasons.entrySet()) {
Reason parentReason = PersistenceService.instance().fetchReasonByName(entry.getValue());
if (parentReason == null) {
throw new Exception(
DesignerLocalizer.instance().getErrorString("no.parent.reason", entry.getValue()));
}
Reason childReason = entry.getKey();
parentReason.addChild(childReason);
PersistenceService.instance().save(childReason);
}
// fill in the top-level reason nodes
populateTopReasonNodes();
} catch (Exception e) {
AppUtils.showErrorDialog(e);
}
}
}
| 25.870192 | 109 | 0.708914 |
a638615d5600a10a17e3e11080816db90268a959
| 522 |
package com.wojo.Vault.Controller;
import com.jfoenix.controls.JFXButton;
import com.wojo.Vault.Main;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
public class MainController {
@FXML
private JFXButton exit;
@FXML
void initialize() {
addEventHandlers();
}
private void addEventHandlers() {
exit.addEventHandler(ActionEvent.ACTION, e -> exitApplication());
}
private void exitApplication() {
Main.exitApplication();
}
}
| 20.076923 | 74 | 0.649425 |
023dad2dc35e484609d50a422d5776571f8ebb52
| 1,111 |
package com.lanluyug.millionLevelFlow.ch03;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class TestSemaphore {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
// 同一时间,只允许3个线程并发访问
Semaphore semp = new Semaphore(3);
// 创建10个线程
for (int i = 0; i < 8; i++) {
final int threadNo = i;
//execute()方法的参数:重写了run()方法的Runnable对象
executor.execute(() -> {
try {
//同一时间,只能有3个线程获取许可去执行
semp.acquire();
System.out.println("得到许可并执行的线程: " + threadNo);
Thread.sleep((long) (Math.random() * 10000));
// 得到许可的线程执行完毕后,将许可转让给其他线程
semp.release();
} catch (InterruptedException e) {
}
}
);
}
// executor.shutdown();
}
}
| 33.666667 | 74 | 0.486949 |
3691f65995e9b08ea2c1c0dccad523f4e2d74556
| 10,801 |
package se.erikwelander.zubat.plugins.reminder;
import se.erikwelander.zubat.libs.ReggexLib;
import se.erikwelander.zubat.plugins.exceptions.PluginException;
import se.erikwelander.zubat.plugins.interfaces.PluginInterface;
import se.erikwelander.zubat.plugins.models.MessageEventModel;
import se.erikwelander.zubat.repositories.sql.RemindersRepository;
import se.erikwelander.zubat.repositories.sql.exceptions.RemindersRepositoryException;
import se.erikwelander.zubat.repositories.sql.models.ReminderModel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import static se.erikwelander.zubat.globals.Globals.TRIGGER;
public class ReminderPlugin implements PluginInterface {
private static final String REGGEX_REMIND_ADD_JOIN = "^" + TRIGGER + "remind add join (\\w+) (.*)";
private static final String REGGEX_REMIND_ADD_DATE = "^" + TRIGGER + "remind add date ([0-9-: ]{19}) (.*)";
private static final String REGGEX_REMIND_DELETE_ID = "^" + TRIGGER + "remind delete (\\d+)";
private static final String REGGEX_REMIND_HELP = "^" + TRIGGER + "remind help";
private static Map<Integer, ReminderModel> reminderModelMap = new HashMap<>();
public ReminderPlugin() throws PluginException {
reminderModelMap = loadReminders();
}
private Map<Integer, ReminderModel> loadReminders() throws PluginException {
try {
RemindersRepository repository = new RemindersRepository();
List<ReminderModel> models = repository.getReminders();
Map<Integer, ReminderModel> maps = new HashMap<>();
for (ReminderModel model : models) {
maps.put(model.getId(), model);
}
return maps;
} catch (RemindersRepositoryException ex) {
throw new PluginException(this.getClass().getName() + "Failed to load reminders from DB! Cause: " + ex.getMessage(), ex);
}
}
public List<String> triggerReminders(MessageEventModel messageEventModel, int ofType) {
List<String> toSend = new ArrayList<>();
try {
Date currentDate = new Date();
for (int key : this.reminderModelMap.keySet()) {
ReminderModel reminderModel = this.reminderModelMap.get(key);
if (reminderModel.getProtocol().equals(messageEventModel.getProtocol()) &&
reminderModel.getServer().equals(messageEventModel.getServer()) &&
reminderModel.getChannel().equals(messageEventModel.getChannel())) {
if (reminderModel.getType() == ofType &&
reminderModel.getType() == RemindersRepository.REMINDER_TYPE_ON_JOIN) {
RemindersRepository repository = new RemindersRepository();
repository.deleteReminder(key);
this.reminderModelMap.remove(key);
StringBuilder builder = new StringBuilder();
builder.append(reminderModel.getToUser() + ": " + reminderModel.getFromUser());
builder.append(" Told me to remind you next time i saw you that: ");
builder.append(reminderModel.getText());
toSend.add(builder.toString());
} else if (reminderModel.getType() == ofType &&
reminderModel.getType() == RemindersRepository.REMINDER_TYPE_ON_TIMESTAMP &&
reminderModel.getDate().before(currentDate)) {
RemindersRepository repository = new RemindersRepository();
repository.deleteReminder(key);
this.reminderModelMap.remove(key);
StringBuilder builder = new StringBuilder();
builder.append(reminderModel.getToUser() + ": This is an automatic timed reminder from " + reminderModel.getFromUser() + ": ");
builder.append("\"" + reminderModel.getText() + "\"");
toSend.add(builder.toString());
}
break;
}
}
} catch (RemindersRepositoryException ex) {
toSend.add("Exception: Reminders: Failed to remove reminder for database!");
return toSend;
}
return toSend;
}
@Override
public boolean supportsAction(MessageEventModel messageEventModel) {
String message = messageEventModel.getMessage().toLowerCase();
if (ReggexLib.match(message, REGGEX_REMIND_ADD_JOIN) ||
ReggexLib.match(message, REGGEX_REMIND_ADD_DATE) ||
ReggexLib.match(message, REGGEX_REMIND_DELETE_ID)) {
return true;
}
return false;
}
@Override
public List<String> trigger(MessageEventModel messageEventModel) {
List<String> toSend = new ArrayList<>();
if (!supportsAction(messageEventModel)) {
return toSend;
}
//remind date (\w+) ([0-9-: ]+) (.+)
String message = messageEventModel.getMessage().toLowerCase();
if (ReggexLib.match(message, REGGEX_REMIND_ADD_JOIN)) {
String mUser = ReggexLib.find(message, REGGEX_REMIND_ADD_JOIN, 1);
String mMessage = ReggexLib.find(messageEventModel.getMessage(), REGGEX_REMIND_ADD_JOIN, 2);
if (mUser.isEmpty() || mMessage.isEmpty()) {
toSend.add("Failed to add event: Empty user or message!");
toSend.add("The correct format is: " + TRIGGER + "remind add join <user> <text>");
return toSend;
}
RemindersRepository repository = new RemindersRepository();
ReminderModel reminderModel = new ReminderModel(
repository.REMINDER_TYPE_ON_JOIN,
new Date(System.currentTimeMillis()),
mMessage,
messageEventModel.getUser(),
mUser,
messageEventModel.getProtocol(),
messageEventModel.getServer(),
messageEventModel.getChannel());
int insertID = 0;
try {
insertID = repository.addReminder(reminderModel);
reminderModel.setId(insertID);
this.reminderModelMap.put(insertID, reminderModel);
} catch (RemindersRepositoryException ex) {
toSend.add("Exception: Failed to add reminder to database");
return toSend;
}
toSend.add("OK! I will remind " + mUser + " of that next time he logs in.");
toSend.add("This reminder has ID: " + insertID);
} else if (ReggexLib.match(message, REGGEX_REMIND_ADD_DATE)) {
String mDate = ReggexLib.find(message, REGGEX_REMIND_ADD_DATE, 1);
String mMessage = ReggexLib.find(messageEventModel.getMessage(), REGGEX_REMIND_ADD_DATE, 2);
if (mDate.isEmpty() || mMessage.isEmpty()) {
toSend.add("Failed to add event: Empty user or message!");
toSend.add("The correct format is: " + TRIGGER + "remind add date <yyyy-MM-dd HH:mm:ss> <text>");
return toSend;
}
RemindersRepository repository = new RemindersRepository();
int insertID = 0;
try {
ReminderModel reminderModel = new ReminderModel(
repository.REMINDER_TYPE_ON_TIMESTAMP,
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(mDate),
mMessage,
messageEventModel.getUser(),
"",
messageEventModel.getProtocol(),
messageEventModel.getServer(),
messageEventModel.getChannel());
insertID = repository.addReminder(reminderModel);
reminderModel.setId(insertID);
this.reminderModelMap.put(insertID, reminderModel);
} catch (RemindersRepositoryException | ParseException ex) {
toSend.add("Exception: Failed to add reminder to database");
return toSend;
}
toSend.add("OK! I will put out this reminder on: " + mDate);
toSend.add("This reminder has ID: " + insertID);
} else if (ReggexLib.match(message, REGGEX_REMIND_DELETE_ID)) {
String mID = ReggexLib.find(message, REGGEX_REMIND_DELETE_ID, 1);
if (mID.isEmpty()) {
toSend.add("Failed to remove event: empty ID!");
toSend.add("The correct format is: " + TRIGGER + "remind delete <id>");
return toSend;
}
int reminderID = 0;
try {
reminderID = Integer.parseInt(mID);
} catch (NumberFormatException ex) {
toSend.add(mID + " Not a valid number!");
return toSend;
}
try {
RemindersRepository repository = new RemindersRepository();
ReminderModel reminderModel = repository.getReminderWithID(reminderID);
if (null == reminderModel) {
toSend.add("There is no reminder with that ID!");
return toSend;
}
if (reminderModel.getProtocol().equals(messageEventModel.getProtocol()) &&
reminderModel.getServer().equals(messageEventModel.getServer()) &&
reminderModel.getChannel().equals(messageEventModel.getChannel())) {
repository.deleteReminder(reminderID);
this.reminderModelMap.remove(reminderID);
toSend.add("OK! Reminder removed");
} else {
toSend.add("This reminder does not belong to you");
return toSend;
}
} catch (RemindersRepositoryException ex) {
toSend.add("Exception: Failed to modify database");
return toSend;
}
} else if (ReggexLib.match(message, REGGEX_REMIND_HELP)) {
toSend.add("This plugin allows you to send reminders to users based upon events.");
toSend.add("Usage: " + TRIGGER + "remind add join <user> <text>. " + TRIGGER + "remind add date <yyyy-MM-dd HH:mm:ss> <text>. " + TRIGGER + "remind delete <id>");
}
return toSend;
}
}
| 47.372807 | 175 | 0.569762 |
25b04c567a3928185355a1b90d0c8ea49b179f5d
| 732 |
package com.fbla.atlas.atlas.view_holders;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.andexert.library.RippleView;
import com.fbla.atlas.atlas.R;
/**
* Created by Hamza on 1/31/2018.
*/
public class GenreViewHolder extends RecyclerView.ViewHolder{
public TextView title;
public ImageView image;
public RippleView ripple;
public GenreViewHolder(View itemView) {
super(itemView);
ripple = itemView.findViewById(R.id.ripple_genre);
title = itemView.findViewById(R.id.genre_title);
image = itemView.findViewById(R.id.genre_image);
}
}
| 22.875 | 62 | 0.702186 |
c020ede3943540534ae0062bbb25c38925729248
| 2,392 |
package org.elsys.manytoone;
import java.util.Collection;
/**
* Introduces the notation of many-to-one relation. This is where the M and O of
* the type signature comes from.
*
* Many unique "source" objects refer to one and only "target" object.
*
* The class maintains a connection between the target and all the sources that
* are referring to it.
*
* @author Kiril Mitov k.mitov@sap.com
*
* @param <M>
* the type of the "source" objects.
* @param <O>
* the type of the "target" objects.
*/
public class ManyToOneRelation<M, O> {
/**
* Connects the given source with the given target. If this source was
* previously connected with another target the old connection is lost.
*
* @param source
* @param target
* @return
*/
public boolean connect(M source, O target) {
return false;
}
/**
* @param source
* @return <code>true</code> if the relation contains the given source
*/
public boolean containsSource(M source) {
return false;
}
/**
* @param target
* @return <code>true</code> if the relation contains the given target
*/
public boolean containsTarget(O target) {
return false;
}
/**
* @param source
* @return the target with which this source is connected
*/
public O getTarget(M source) {
return null;
}
/**
* @param target
* @return all the targets that are connected with this source or empty
* collection if there are no sources connected with this target.
*/
public Collection<M> getSources(O target) {
return null;
}
/**
* Removes the connection between this source and the corresponding target.
* Other sources will still point to the same target.
*
* The target is removed if this was the only source pointing to it and
* {@link #containsTarget(Object)} will return false.
*
* @param source
*/
public void disconnectSource(M source) {
}
/**
* Removes the given target from the relation. All the sources that are
* pointing to this target are also removed.
*
* If you take the "result" of {@link #getSources(target)} and after that
* call this method then {@link #containsSource(Object)} will return
* <code>false</code> for every object in "result".
*
* @param target
*/
public void disconnect(O target) {
}
/**
* @return a collection of the targets.
*/
public Collection<O> getTargets() {
return null;
}
}
| 24.161616 | 80 | 0.675585 |
4c752790379a19bb8aa3678bd7830c49251bfd26
| 7,851 |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.highlighter;
import com.intellij.lexer.DtdLexer;
import com.intellij.lexer.Lexer;
import com.intellij.lexer.XHtmlHighlightingLexer;
import com.intellij.lexer.XmlHighlightingLexer;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.XmlHighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.extensions.ExtensionPointListener;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import static com.intellij.psi.xml.XmlTokenType.*;
public class XmlFileHighlighter extends SyntaxHighlighterBase {
static final ExtensionPointName<EmbeddedTokenHighlighter> EMBEDDED_HIGHLIGHTERS = ExtensionPointName.create("com.intellij.embeddedTokenHighlighter");
private static class Holder {
private static final MultiMap<IElementType, TextAttributesKey> ourMap = MultiMap.create();
static {
ourMap.putValue(XML_DATA_CHARACTERS, XmlHighlighterColors.XML_TAG_DATA);
for (IElementType type : ContainerUtil.ar(XML_COMMENT_START, XML_COMMENT_END, XML_COMMENT_CHARACTERS,
XML_CONDITIONAL_COMMENT_END, XML_CONDITIONAL_COMMENT_END_START,
XML_CONDITIONAL_COMMENT_START, XML_CONDITIONAL_COMMENT_START_END)) {
ourMap.putValue(type, XmlHighlighterColors.XML_COMMENT);
}
for (IElementType type : ContainerUtil
.ar(XML_START_TAG_START, XML_END_TAG_START, XML_TAG_END, XML_EMPTY_ELEMENT_END, TAG_WHITE_SPACE)) {
ourMap.putValue(type, XmlHighlighterColors.XML_TAG);
}
for (IElementType type : ContainerUtil.ar(XML_TAG_NAME, XML_CONDITIONAL_IGNORE, XML_CONDITIONAL_INCLUDE)) {
ourMap.putValues(type, Arrays.asList(XmlHighlighterColors.XML_TAG, XmlHighlighterColors.XML_TAG_NAME));
}
ourMap.putValues(XML_NAME, Arrays.asList(XmlHighlighterColors.XML_TAG, XmlHighlighterColors.XML_ATTRIBUTE_NAME));
for (IElementType type : ContainerUtil.ar(XML_EQ, XML_TAG_CHARACTERS,
XML_ATTRIBUTE_VALUE_TOKEN, XML_ATTRIBUTE_VALUE_START_DELIMITER,
XML_ATTRIBUTE_VALUE_END_DELIMITER)) {
ourMap.putValues(type, Arrays.asList(XmlHighlighterColors.XML_TAG, XmlHighlighterColors.XML_ATTRIBUTE_VALUE));
}
for (IElementType type : ContainerUtil.ar(XML_DECL_START, XML_DOCTYPE_START, XML_DOCTYPE_SYSTEM, XML_DOCTYPE_PUBLIC,
XML_ATTLIST_DECL_START, XML_ELEMENT_DECL_START, XML_ENTITY_DECL_START)) {
ourMap.putValues(type, Arrays.asList(XmlHighlighterColors.XML_TAG, XmlHighlighterColors.XML_TAG_NAME));
}
for (IElementType type : ContainerUtil
.ar(XML_CONDITIONAL_SECTION_START, XML_CONDITIONAL_SECTION_END, XML_DECL_END, XML_DOCTYPE_END)) {
ourMap.putValues(type, Arrays.asList(XmlHighlighterColors.XML_PROLOGUE, XmlHighlighterColors.XML_TAG_NAME));
}
ourMap.putValue(XML_PI_START, XmlHighlighterColors.XML_PROLOGUE);
ourMap.putValue(XML_PI_END, XmlHighlighterColors.XML_PROLOGUE);
ourMap.putValue(XML_CHAR_ENTITY_REF, XmlHighlighterColors.XML_ENTITY_REFERENCE);
ourMap.putValue(XML_ENTITY_REF_TOKEN, XmlHighlighterColors.XML_ENTITY_REFERENCE);
ourMap.putValue(XML_BAD_CHARACTER, HighlighterColors.BAD_CHARACTER);
registerAdditionalHighlighters(ourMap);
EMBEDDED_HIGHLIGHTERS.addExtensionPointListener(new EmbeddedTokenHighlighterExtensionPointListener(ourMap), null);
}
}
static void registerAdditionalHighlighters(MultiMap<IElementType, TextAttributesKey> map) {
for (EmbeddedTokenHighlighter highlighter : EMBEDDED_HIGHLIGHTERS.getExtensionList()) {
registerAdditionalHighlighters(map, highlighter);
}
}
private static void registerAdditionalHighlighters(MultiMap<IElementType, TextAttributesKey> map, EmbeddedTokenHighlighter highlighter) {
MultiMap<IElementType, TextAttributesKey> attributes = highlighter.getEmbeddedTokenAttributes();
for (Map.Entry<IElementType, Collection<TextAttributesKey>> entry : attributes.entrySet()) {
if (!map.containsKey(entry.getKey())) {
map.putValues(entry.getKey(), entry.getValue());
}
}
}
static class EmbeddedTokenHighlighterExtensionPointListener implements ExtensionPointListener<EmbeddedTokenHighlighter> {
private final MultiMap<IElementType, TextAttributesKey> myMap;
EmbeddedTokenHighlighterExtensionPointListener(MultiMap<IElementType, TextAttributesKey> map) {
myMap = map;
}
@Override
public void extensionAdded(@NotNull EmbeddedTokenHighlighter extension, @NotNull PluginDescriptor pluginDescriptor) {
registerAdditionalHighlighters(myMap, extension);
}
@Override
public void extensionRemoved(@NotNull EmbeddedTokenHighlighter extension, @NotNull PluginDescriptor pluginDescriptor) {
MultiMap<IElementType, TextAttributesKey> attributes = extension.getEmbeddedTokenAttributes();
for (IElementType key : attributes.keySet()) {
myMap.remove(key);
}
registerAdditionalHighlighters(myMap, extension);
}
}
private final boolean myIsDtd;
private boolean myIsXHtml;
public XmlFileHighlighter() {
this(false);
}
public XmlFileHighlighter(boolean dtd) {
myIsDtd = dtd;
}
public XmlFileHighlighter(boolean dtd, boolean xhtml) {
myIsDtd = dtd;
myIsXHtml = xhtml;
}
@Override
@NotNull
public Lexer getHighlightingLexer() {
if (myIsDtd) {
return new DtdLexer(true);
} else if (myIsXHtml) {
return new XHtmlHighlightingLexer();
} else {
return new XmlHighlightingLexer();
}
}
@Override
public TextAttributesKey @NotNull [] getTokenHighlights(IElementType tokenType) {
//noinspection SynchronizationOnGetClass,SynchronizeOnThis
synchronized (getClass()) {
return Holder.ourMap.get(tokenType).toArray(TextAttributesKey.EMPTY_ARRAY);
}
}
/**
* @deprecated use {@link EmbeddedTokenHighlighter} extension
*/
@Deprecated
public static synchronized void registerEmbeddedTokenAttributes(Map<IElementType, TextAttributesKey> _keys1,
Map<IElementType, TextAttributesKey> _keys2) {
HashSet<IElementType> existingKeys = new HashSet<>(Holder.ourMap.keySet());
addMissing(_keys1, existingKeys, Holder.ourMap);
addMissing(_keys2, existingKeys, Holder.ourMap);
}
static void addMissing(Map<IElementType, TextAttributesKey> from, Set<IElementType> existingKeys, MultiMap<IElementType, TextAttributesKey> to) {
if (from != null) {
for (Map.Entry<IElementType, TextAttributesKey> entry : from.entrySet()) {
if (!existingKeys.contains(entry.getKey())) {
to.putValue(entry.getKey(), entry.getValue());
}
}
}
}
}
| 42.901639 | 151 | 0.74309 |
58cdb59710f3fb8a7231965299d58d811481fb07
| 858 |
// Autogenerated from development/origins/fragment_origin.i
package ideal.development.origins;
import ideal.library.elements.*;
import ideal.library.texts.*;
import ideal.library.channels.*;
import ideal.library.resources.*;
import ideal.library.patterns.*;
import ideal.runtime.elements.*;
import ideal.runtime.texts.*;
import ideal.runtime.patterns.*;
import ideal.runtime.logs.*;
import ideal.development.elements.*;
import ideal.development.names.*;
public class fragment_origin extends debuggable implements deeply_immutable_data, origin {
public final origin begin;
public final origin main;
public final origin end;
public fragment_origin(final origin begin, final origin main, final origin end) {
this.begin = begin;
this.main = main;
this.end = end;
}
public @Override origin deeper_origin() {
return this.main;
}
}
| 28.6 | 90 | 0.763403 |
e1bd8d1eb29f247cde970e1a495d2dfe4afa7bf1
| 1,257 |
package com.example.zrestdemo02;
import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class ZRestDemo02Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(ZRestDemo02Application.class, args);
System.out.println("starting app");
String pet1 = ctx.getBean("spike", String.class);
String pet2 = ctx.getBean("getPetName01", String.class);
Cat cat1 = ctx.getBean("myCatSpike", Cat.class);
Dog dog1 = ctx.getBean("myDogFluffy", Dog.class);
System.out.println("pet1: " + pet1);
System.out.println("pet2: " + pet2);
System.out.println("cat1: " + cat1);
System.out.println("dog1: " + dog1);
String[] allBeans = ctx.getBeanDefinitionNames();
Arrays.sort(allBeans);
for(String s: allBeans) {System.out.println("bean name: " + s);}
}
@Bean
public String getPetName01() {
return "Fluffy";
}
@Bean("spike")
public String getPetName02() {
return "Spike";
}
@Bean("myCatSpike")
public Cat createCatSpike() {
return new Cat(getPetName02());
}
}
| 29.232558 | 85 | 0.734288 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.