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
fb5e38ad36de0c0655c0637d7863dc7b681ba398
4,840
package com.v5ent.xiubit.view.popupwindow; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.support.v4.content.ContextCompat; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.TextView; import com.toobei.common.TopBaseActivity; import com.toobei.common.entity.ShareContent; import com.toobei.common.service.ShareService; import com.v5ent.xiubit.R; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * 公司: tophlc * 类说明: * * @author hasee-pc * @time 2017/7/7 */ public class RecommendSharePopupWindow extends PopupWindow{ private int recommendType; public final static int RECOMMENDTYPE_PRODUCT = 0; public final static int RECOMMENDTYPE_ORG = 1; private RecommendShareListener listener; @BindView(R.id.btn_wechat_cricle) ImageView btnWechatCricle; @BindView(R.id.btn_wechat_friend) ImageView btnWechatFriend; @BindView(R.id.recommendCfgBtn) ImageView recommendCfgBtn; @BindView(R.id.recommendCustomerBtn) ImageView recommendCustomerBtn; @BindView(R.id.text_share_name) TextView text_share_name; private ShareContent shareContent; private View contentView; protected TopBaseActivity ctx; private ShareService shareService; public RecommendSharePopupWindow(Context ctx,ShareContent shareContent,int recommendType,RecommendShareListener listener) { super(ctx); this.ctx = (TopBaseActivity) ctx; this.shareContent = shareContent; this.listener = listener; this.recommendType = recommendType; shareService = new ShareService(); initView(); } private void initView() { contentView = LayoutInflater.from(ctx).inflate(R.layout.layout_recommend_share_popu_window, null); ButterKnife.bind(this,contentView); // 设置SelectPicPopupWindow的View this.setContentView(contentView); // 设置SelectPicPopupWindow弹出窗体的宽 this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT); // 设置SelectPicPopupWindow弹出窗体的高 this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); // 设置SelectPicPopupWindow弹出窗体可点击 this.setFocusable(true); this.setOutsideTouchable(true); // 刷新状态 this.update(); // 实例化一个ColorDrawable颜色为半透明 ColorDrawable dw = new ColorDrawable(ContextCompat.getColor(ctx, R.color.Color_0)); // 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ,设置其他控件变化等操作 this.setBackgroundDrawable(dw); // mPopupWindow.setAnimationStyle(android.R.style.Animation_Dialog); // 设置SelectPicPopupWindow弹出窗体动画效果 this.setAnimationStyle(R.style.anim_popup_share); // contentView.findViewById(R.id.btn_cancel).setOnClickListener(this); if (recommendType == RECOMMENDTYPE_PRODUCT) text_share_name.setText("选择推荐产品方式"); else text_share_name.setText("选择推荐平台方式"); } /** * 显示popupWindow * * @param parent */ public void showPopupWindow(View parent) { backgroundAlpha(0.5f); showAtLocation(parent, Gravity.BOTTOM, 0, 0); } /** * 设置添加屏幕的背景透明度 * * @param bgAlpha */ public void backgroundAlpha(float bgAlpha) { WindowManager.LayoutParams lp = ctx.getWindow().getAttributes(); lp.alpha = bgAlpha; //0.0-1.0 ctx.getWindow().setAttributes(lp); } @Override public void dismiss() { backgroundAlpha(1f); super.dismiss(); } @OnClick({R.id.btn_wechat_cricle, R.id.btn_wechat_friend, R.id.recommendCfgBtn, R.id.recommendCustomerBtn}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.btn_wechat_cricle: btnWechatCricle.setEnabled(false); shareService.share(ctx, shareContent, ShareService.SharePlatform.WechatMoments,R.drawable.ic_launcher); btnWechatCricle.setEnabled(true); break; case R.id.btn_wechat_friend: btnWechatFriend.setEnabled(false); shareService.share(ctx, shareContent, ShareService.SharePlatform.Wechat, R.drawable.ic_launcher); btnWechatFriend.setEnabled(true); break; case R.id.recommendCfgBtn: listener.onRecommendCfg(); break; case R.id.recommendCustomerBtn: listener.onRecommendCustomer(); break; } dismiss(); } public interface RecommendShareListener{ void onRecommendCfg(); void onRecommendCustomer(); } }
32.483221
127
0.686364
782ee07bcb19d028050d4f5a381a6532700cda1c
1,593
package com.fulin.String; /** * '.' matches any single character * '*' matches zero or more or the preceding element * * * @author mfl4482 * */ public class RegularExpressionMatch { public static void main(String[] args) { System.out.println(isMatch("aa", "a")); System.out.println(isMatch("aa", "aa")); System.out.println(isMatch("aaa", "a")); System.out.println(isMatch("aa", "a*")); System.out.println(isMatch("aa", ".*")); System.out.println(isMatch("ab", ".*")); System.out.println(isMatch("aab", "c*a*b")); } public static boolean isMatch(String s , String p){ //如果p的长度为0 在s的长度为0是返回匹配,其他情况返回不匹配 if(p.length() == 0){ return s.length() == 0; } //由于p的长度每次都是减少2次,如果p原始的长度为奇数,那么最后一次p的长度为1,需要对这种情况进行考虑 if(p.length() == 1){ return (s.length() == 1) && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '*'); } if(p.charAt(1) != '*'){ if(s.length() == 0){ return false; }else{ return (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.') && (isMatch(s.substring(1), p.substring(1))); } }else{ // next char is '*' while(s.length() >0 &&( p.charAt(0) == s.charAt(0) || p.charAt(0) == '.') ){ if(isMatch(s, p.substring(2))){// 该 “*” 表示为0次 return true; } s = s.substring(1); } return isMatch(s, p.substring(2)); } } }
30.056604
91
0.472693
80a1f586daf6e5aabf3d7c6b03a79614d4e502fc
9,662
package wintersteve25.primutils.common.te; import com.google.common.collect.ImmutableList; import fictioncraft.wintersteve25.fclib.common.helper.MiscHelper; import fictioncraft.wintersteve25.fclib.common.interfaces.IHasProgress; import fictioncraft.wintersteve25.fclib.common.interfaces.IHasValidItems; import fictioncraft.wintersteve25.fclib.common.interfaces.IWorkable; import net.minecraft.block.BlockState; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.InventoryHelper; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import net.minecraft.nbt.CompoundNBT; import net.minecraft.particles.BlockParticleData; import net.minecraft.particles.ParticleTypes; import net.minecraft.tileentity.ITickableTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Hand; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvents; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockRayTraceResult; import net.minecraft.world.World; import net.minecraft.world.server.ServerWorld; import net.minecraftforge.fluids.capability.IFluidHandler; import software.bernie.geckolib3.core.IAnimatable; import software.bernie.geckolib3.core.PlayState; import software.bernie.geckolib3.core.builder.AnimationBuilder; import software.bernie.geckolib3.core.controller.AnimationController; import software.bernie.geckolib3.core.event.predicate.AnimationEvent; import software.bernie.geckolib3.core.manager.AnimationData; import software.bernie.geckolib3.core.manager.AnimationFactory; import wintersteve25.primutils.common.base.PrimUtilsFluidTE; import wintersteve25.primutils.common.init.PrimUtilsBlocks; import wintersteve25.primutils.common.init.PrimUtilsConfig; import wintersteve25.primutils.common.init.PrimUtilsRecipes; import wintersteve25.primutils.common.recipes.basin.IBasinRecipe; import java.util.List; import java.util.function.BiPredicate; public class BasinTileEntity extends PrimUtilsFluidTE implements IAnimatable, ITickableTileEntity, IWorkable, IHasProgress, IHasValidItems { public static final int TICKS_FOR_ONE_OPERATION = 40; private final AnimationFactory manager = new AnimationFactory(this); private int totalProgress = -1; private int progress = totalProgress; private boolean working = false; private int operationProgress = TICKS_FOR_ONE_OPERATION; public BasinTileEntity() { super(PrimUtilsBlocks.BASIN_TE.get()); } @Override public void tick() { if (getWorld().isRemote()) return; if (getWorking()) { operationProgress--; if (operationProgress % 2 == 0 && MiscHelper.chanceHandling(12)) { ((ServerWorld) getWorld()).spawnParticle(new BlockParticleData(ParticleTypes.BLOCK, tank.getFluid().getFluid().getDefaultState().getBlockState()), pos.getX() + 0.5 + MiscHelper.randomInRange(-0.25, 0.25), pos.getY() + 0.45 + MiscHelper.randomInRange(-0.12, 0.05), pos.getZ() + 0.5 + MiscHelper.randomInRange(-0.25, 0.25), 4, 0, 0, 0, 0.1d); } if (operationProgress <= 0) { operationProgress = TICKS_FOR_ONE_OPERATION; progress--; if (progress == 0) { IBasinRecipe recipe = getRecipe(); if (recipe == null) return; spawnOutput(recipe); for (Ingredient ing : recipe.getInput()) { for (int i = 0; i < 4; i++) { int count = ing.getMatchingStacks()[0].getCount(); if (ing.test(itemHandler.getStackInSlot(i)) && itemHandler.getStackInSlot(i).getCount() >= count) { itemHandler.extractItem(i, count, false); break; } } } tank.drain(recipe.getInputFluid().getAmount(), IFluidHandler.FluidAction.EXECUTE); totalProgress = -1; progress = totalProgress; operationProgress = TICKS_FOR_ONE_OPERATION; if (checkRecipe()) { setupRecipe(); } } setWorking(false); } updateBlock(); } } @Override public void onUse(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit) { if (!player.isSneaking() && player.getHeldItem(handIn).isEmpty() && !getWorking() && progress != 0) { if (checkRecipe() && progress != -1) { getWorld().playSound((PlayerEntity) null, pos, SoundEvents.ENTITY_BOAT_PADDLE_WATER, SoundCategory.BLOCKS, 1.0F, 1f); setWorking(true); updateBlock(); } if (totalProgress < -1 || progress < -1) { totalProgress = -1; progress = totalProgress; } } } @Override public void onItemAdded(int slot) { setupRecipe(); } @Override protected void onFluidChanged() { setupRecipe(); } private void setupRecipe() { IBasinRecipe recipe = getRecipe(); if (recipe != null) { if (totalProgress == -1) { totalProgress = recipe.getStirAmounts(); progress = totalProgress; } } else { totalProgress = -1; progress = totalProgress; operationProgress = TICKS_FOR_ONE_OPERATION; setWorking(false); } } private boolean checkRecipe() { IBasinRecipe recipe = getRecipe(); return recipe != null; } private void spawnOutput(IBasinRecipe recipe) { if (getWorld() != null && !getWorld().isRemote()) { if (!getWorld().isRemote()) { ((ServerWorld) getWorld()).spawnParticle(ParticleTypes.CLOUD, pos.getX() + 0.5, pos.getY() + 0.8, pos.getZ() + 0.5, 4, 0, 0, 0, 0.4d); } getWorld().playSound(null, pos, SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, SoundCategory.BLOCKS, 1.0F, 1f); for (ItemStack stack : recipe.getOutput()) { InventoryHelper.spawnItemStack(getWorld(), pos.getX(), (double) pos.getY() + 0.5, pos.getZ(), stack.copy()); } } } public IBasinRecipe getRecipe() { List<ItemStack> inputs = getAllItemsInInventory(); if (getWorld() == null) return null; List<IBasinRecipe> recipes = getWorld().getRecipeManager().getRecipesForType(PrimUtilsRecipes.BASIN_RT); if (recipes.isEmpty()) return null; for (IBasinRecipe recipe : recipes) { if (recipe.match(ImmutableList.copyOf(inputs), tank.getFluid())) { return recipe; } } return null; } @Override protected int fluidTankCapacity() { return 4000; } @Override public int getInvSize() { return 4; } @Override public CompoundNBT write(CompoundNBT tag) { tag.putInt("operationProgress", operationProgress); return super.write(tag); } @Override public void read(BlockState state, CompoundNBT tag) { operationProgress = tag.getInt("operationProgress"); super.read(state, tag); } private <E extends TileEntity & IAnimatable> PlayState predicate(AnimationEvent<E> event) { event.getController().transitionLengthTicks = 1; if (getWorking()) { event.getController().setAnimation(new AnimationBuilder().addAnimation("animation.basin.stir", true)); return PlayState.CONTINUE; } else { event.getController().setAnimation(new AnimationBuilder()); return PlayState.STOP; } } @Override public void registerControllers(AnimationData animationData) { animationData.addAnimationController(new AnimationController(this, "controller", 0, this::predicate)); } @Override public AnimationFactory getFactory() { return manager; } @Override public int getProgress() { return progress; } @Override public void setProgress(int i) { this.progress = i; } @Override public int getTotalProgress() { return totalProgress; } @Override public void setTotalProgress(int i) { this.totalProgress = i; } @Override public boolean getWorking() { return working; } @Override public void setWorking(boolean b) { this.working = b; } @Override public BiPredicate<ItemStack, Integer> validItems() { return (stack, slot) -> PrimUtilsConfig.isBasinAllowStack() || itemHandler.getStackInSlot(slot).isEmpty(); } @Override public boolean addItem(PlayerEntity player, ItemStack heldItem, BlockRayTraceResult hit) { if (!PrimUtilsConfig.isBasinAllowStack()) { for (int i = 0; i < getInvSize(); i++) { if (itemHandler.getStackInSlot(i).isEmpty()) { ItemStack itemAdd = heldItem.copy(); itemAdd.setCount(1); itemHandler.insertItem(i, itemAdd, false); if (player != null) { heldItem.shrink(1); } updateBlock(); return true; } } return false; } return super.addItem(player, heldItem, hit); } }
36.737643
356
0.622128
9086225fd743e67350a2d8191e203971c0c7d80c
445
//,temp,TestUpdateDeleteSemanticAnalyzer.java,147,156,temp,TestUpdateDeleteSemanticAnalyzer.java,95,103 //,3 public class xxx { @Test public void testUpdateAllNonPartitionedWhere() throws Exception { try { ReturnInfo rc = parseAndAnalyze("update T set b = 5 where b > 5", "testUpdateAllNonPartitionedWhere"); LOG.info(explain((SemanticAnalyzer)rc.sem, rc.plan)); } finally { cleanupTables(); } } };
29.666667
103
0.694382
e78a5d336422b11986a3fda328f93ddff349ab35
57,616
/* Copyright 2004-2019 Jim Voris * * 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.qumasoft.guitools.qwin; import static com.qumasoft.guitools.qwin.QWinUtility.logProblem; import com.qumasoft.guitools.qwin.dialog.DefineWorkfileLocationDialog; import com.qumasoft.guitools.qwin.operation.OperationAddDirectory; import com.qumasoft.guitools.qwin.operation.OperationAddServer; import com.qumasoft.guitools.qwin.operation.OperationAutoAddFiles; import com.qumasoft.guitools.qwin.operation.OperationBaseClass; import com.qumasoft.guitools.qwin.operation.OperationDefineBranch; import com.qumasoft.guitools.qwin.operation.OperationDeleteBranch; import com.qumasoft.guitools.qwin.operation.OperationDeleteDirectory; import com.qumasoft.guitools.qwin.operation.OperationEditServerProperties; import com.qumasoft.guitools.qwin.operation.OperationGetDirectory; import com.qumasoft.guitools.qwin.operation.OperationLabelDirectory; import com.qumasoft.guitools.qwin.operation.OperationMaintainBranch; import com.qumasoft.guitools.qwin.operation.OperationPromoteFilesFromChildBranch; import com.qumasoft.guitools.qwin.operation.OperationRemoveServer; import com.qumasoft.guitools.qwin.operation.OperationUnLabelDirectory; import com.qumasoft.qvcslib.AbstractProjectProperties; import com.qumasoft.qvcslib.ArchiveDirManagerProxy; import com.qumasoft.qvcslib.ClientTransactionManager; import com.qumasoft.qvcslib.DirectoryCoordinate; import com.qumasoft.qvcslib.DirectoryManagerFactory; import com.qumasoft.qvcslib.DirectoryManagerInterface; import com.qumasoft.qvcslib.QVCSConstants; import com.qumasoft.qvcslib.RemoteBranchProperties; import com.qumasoft.qvcslib.ServerProperties; import com.qumasoft.qvcslib.TransportProxyFactory; import com.qumasoft.qvcslib.TransportProxyInterface; import com.qumasoft.qvcslib.WorkfileDirectoryManagerInterface; import com.qumasoft.qvcslib.requestdata.ClientRequestMoveFileData; import java.awt.Component; import java.awt.Font; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.io.File; import java.io.IOException; import java.util.Enumeration; import java.util.Iterator; import java.util.TreeMap; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JTree; import javax.swing.MenuElement; import javax.swing.SwingUtilities; import javax.swing.TransferHandler; import javax.swing.event.MouseInputAdapter; import javax.swing.event.TreeSelectionEvent; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; /** * Project tree control. JPanel container of our tree control. This is a singleton. * * @author Jim Voris */ public final class ProjectTreeControl extends javax.swing.JPanel { private static final long serialVersionUID = 5244866537942643753L; private static final ProjectTreeControl PROJECT_TREE_CONTROL = new ProjectTreeControl(); private DefaultMutableTreeNode previousSelectedNode; private DefaultMutableTreeNode lastSelectedNode; private final ProjectTreeModel projectTreeModel; private AbstractProjectProperties activeProject; private String activeBranch; private ServerProperties serverProperties; private final ImageIcon serversIcon; private final ImageIcon serverIcon; private final ImageIcon projectIcon; private final ImageIcon readOnlyBranchIcon; private final ImageIcon readWriteBranchIcon; // Popup menu items. private final ActionDefineWorkfileLocation actionDefineWorkfileLocation; private final ActionAddDirectory actionAddDirectory; private final ActionDeleteDirectory actionDeleteDirectory; private final ActionAutoAddFiles actionAutoAddFiles; private final ActionGetDirectory actionGetDirectory; private final ActionLabelDirectory actionLabelDirectory; private final ActionUnLabelDirectory actionUnLabelDirectory; private final ActionDefineBranch actionDefineBranch; private final ActionMaintainBranch actionMaintainBranch; private final ActionDeleteBranch actionDeleteBranch; private final ActionExpandTree actionExpandTree; private final ActionCollapseTree actionCollapseTree; private final ActionPromoteFromChild actionPromoteFromChild; // Other popup menu items. private final ActionAddServer actionAddServer; private final ActionRemoveServer actionRemoveServer; private final ActionServerProperties actionServerProperties; /** * Get the singleton instance of the project tree control. * * @return the singleton instance of the project tree control. */ public static ProjectTreeControl getInstance() { return PROJECT_TREE_CONTROL; } /** * Creates new form ProjectTreeControl. */ private ProjectTreeControl() { this.actionServerProperties = new ActionServerProperties("Server Properties..."); this.actionRemoveServer = new ActionRemoveServer("Remove Server..."); this.actionAddServer = new ActionAddServer("Add Server..."); this.actionPromoteFromChild = new ActionPromoteFromChild("Promote changes from child branch"); this.actionCollapseTree = new ActionCollapseTree("Collapse Tree"); this.actionExpandTree = new ActionExpandTree("Expand Tree"); this.actionDeleteBranch = new ActionDeleteBranch("Delete Branch..."); this.actionMaintainBranch = new ActionMaintainBranch("Branch Properties..."); this.actionDefineBranch = new ActionDefineBranch("Define Branch..."); this.actionUnLabelDirectory = new ActionUnLabelDirectory("Remove Label..."); this.actionLabelDirectory = new ActionLabelDirectory("Apply Label..."); this.actionGetDirectory = new ActionGetDirectory("Get..."); this.actionAutoAddFiles = new ActionAutoAddFiles("Auto-Add Files/Directories..."); this.actionDeleteDirectory = new ActionDeleteDirectory("Delete Directory..."); this.actionAddDirectory = new ActionAddDirectory("Add Directory..."); this.actionDefineWorkfileLocation = new ActionDefineWorkfileLocation("Define Workfile Location..."); this.readWriteBranchIcon = new ImageIcon(ClassLoader.getSystemResource("images/readwriteview.png"), "Read Write Branch"); this.readOnlyBranchIcon = new ImageIcon(ClassLoader.getSystemResource("images/readonlyview.png"), "Read Only Branch"); this.projectIcon = new ImageIcon(ClassLoader.getSystemResource("images/project.png"), "Project"); this.serverIcon = new ImageIcon(ClassLoader.getSystemResource("images/server.png"), "Server"); this.serversIcon = new ImageIcon(ClassLoader.getSystemResource("images/servers.png"), "Servers"); initComponents(); addPopupMenuItems(); projectTreeModel = new ProjectTreeModel(); m_ProjectTree.setModel(projectTreeModel.getTreeModel()); m_ProjectTree.setShowsRootHandles(true); m_ProjectTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); addListeners(); // Set the tree model so others can easily find it. QWinFrame.getQWinFrame().setTreeModel(projectTreeModel); // Set the tree control so others can easily find it. QWinFrame.getQWinFrame().setTreeControl(this); // Enable the tree as a drop target. initDragAndDrop(); m_ProjectTree.setFont(QWinFrame.getQWinFrame().getFont(QWinFrame.getQWinFrame().getFontSize())); } JTree getProjectJTreeControl() { return m_ProjectTree; } /** * Set the font size that we'll use. * * @param fontSize the font size. */ public void setFontSize(int fontSize) { m_ProjectTree.setFont(QWinFrame.getQWinFrame().getFont(fontSize + 1)); setMenusFontSize(fontSize + 1); } private void setMenusFontSize(int fontSize) { setMenuFontSize(fontSize, m_DirectoryPopupMenu); setMenuFontSize(fontSize, m_ProjectPopupMenu); setMenuFontSize(fontSize, m_RootServerPopupMenu); setMenuFontSize(fontSize, m_ServerPopupMenu); setMenuFontSize(fontSize, m_ViewPopupMenu); } private void setMenuFontSize(int fontSize, JPopupMenu popupMenu) { Font font = QWinFrame.getQWinFrame().getFont(fontSize); MenuElement[] menuElements = popupMenu.getSubElements(); for (MenuElement menuElement : menuElements) { menuElement.getComponent().setFont(font); } } /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated * by the FormEditor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { m_ProjectPopupMenu = new javax.swing.JPopupMenu(); m_RootServerPopupMenu = new javax.swing.JPopupMenu(); m_ServerPopupMenu = new javax.swing.JPopupMenu(); m_DirectoryPopupMenu = new javax.swing.JPopupMenu(); m_ViewPopupMenu = new javax.swing.JPopupMenu(); m_ScrollPane = new javax.swing.JScrollPane(); m_ProjectTree = new javax.swing.JTree(); m_ProjectPopupMenu.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N m_RootServerPopupMenu.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N m_ServerPopupMenu.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N m_DirectoryPopupMenu.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N m_ViewPopupMenu.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N setLayout(new java.awt.BorderLayout()); m_ProjectTree.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N EnterpriseTreeCellRenderer renderer = new EnterpriseTreeCellRenderer(serversIcon, serverIcon, projectIcon, readOnlyBranchIcon, readWriteBranchIcon); renderer.setLeafIcon(renderer.getClosedIcon()); m_ProjectTree.setCellRenderer(renderer); m_ScrollPane.setViewportView(m_ProjectTree); add(m_ScrollPane); }// </editor-fold>//GEN-END:initComponents private void addPopupMenuItems() { Font menuFont = QWinFrame.getQWinFrame().getFont(QWinFrame.getQWinFrame().getFontSize() + 1); // The root popup menu JMenuItem menuItem = m_RootServerPopupMenu.add(actionAddServer); menuItem.setFont(menuFont); // The server popup menu menuItem = m_ServerPopupMenu.add(actionServerProperties); menuItem.setFont(menuFont); menuItem = m_ServerPopupMenu.add(actionRemoveServer); menuItem.setFont(menuFont); // ===================================================================== // ===================================================================== // The project popup menu menuItem = m_ProjectPopupMenu.add(actionDefineBranch); menuItem.setFont(menuFont); // ===================================================================== // ===================================================================== // The view popup menu menuItem = m_ViewPopupMenu.add(actionDefineWorkfileLocation); menuItem.setFont(menuFont); menuItem = m_ViewPopupMenu.add(actionMaintainBranch); menuItem.setFont(menuFont); menuItem = m_ViewPopupMenu.add(actionDeleteBranch); menuItem.setFont(menuFont); // ===================================================================== m_ViewPopupMenu.add(new javax.swing.JSeparator()); // ===================================================================== menuItem = m_ViewPopupMenu.add(actionExpandTree); menuItem.setFont(menuFont); menuItem = m_ViewPopupMenu.add(actionCollapseTree); menuItem.setFont(menuFont); // ===================================================================== m_ViewPopupMenu.add(new javax.swing.JSeparator()); // ===================================================================== menuItem = m_ViewPopupMenu.add(actionAddDirectory); menuItem.setFont(menuFont); menuItem = m_ViewPopupMenu.add(actionAutoAddFiles); menuItem.setFont(menuFont); // ===================================================================== m_ViewPopupMenu.add(new javax.swing.JSeparator()); // ===================================================================== menuItem = m_ViewPopupMenu.add(actionGetDirectory); menuItem.setFont(menuFont); menuItem = m_ViewPopupMenu.add(actionLabelDirectory); menuItem.setFont(menuFont); menuItem = m_ViewPopupMenu.add(actionUnLabelDirectory); menuItem.setFont(menuFont); // ===================================================================== m_ViewPopupMenu.add(new javax.swing.JSeparator()); // ===================================================================== menuItem = m_ViewPopupMenu.add(actionPromoteFromChild); menuItem.setFont(menuFont); // ===================================================================== // ===================================================================== // The directory popup menu menuItem = m_DirectoryPopupMenu.add(actionAddDirectory); menuItem.setFont(menuFont); menuItem = m_DirectoryPopupMenu.add(actionDeleteDirectory); menuItem.setFont(menuFont); menuItem = m_DirectoryPopupMenu.add(actionAutoAddFiles); menuItem.setFont(menuFont); // ===================================================================== m_DirectoryPopupMenu.add(new javax.swing.JSeparator()); // ===================================================================== menuItem = m_DirectoryPopupMenu.add(actionExpandTree); menuItem.setFont(menuFont); menuItem = m_DirectoryPopupMenu.add(actionCollapseTree); menuItem.setFont(menuFont); // ===================================================================== m_DirectoryPopupMenu.add(new javax.swing.JSeparator()); // ===================================================================== menuItem = m_DirectoryPopupMenu.add(actionGetDirectory); menuItem.setFont(menuFont); menuItem = m_DirectoryPopupMenu.add(actionLabelDirectory); menuItem.setFont(menuFont); menuItem = m_DirectoryPopupMenu.add(actionUnLabelDirectory); menuItem.setFont(menuFont); } private void enableAllPopUpOperations() { actionAddDirectory.setEnabled(true); actionAutoAddFiles.setEnabled(true); } private void disableAllDirectoryOperations() { actionAddDirectory.setEnabled(false); actionAutoAddFiles.setEnabled(false); } private AbstractProjectProperties getProjectProperties() { AbstractProjectProperties projectProperties = null; if (lastSelectedNode instanceof DirectoryTreeNode) { DirectoryTreeNode directoryNode = (DirectoryTreeNode) lastSelectedNode; projectProperties = directoryNode.getProjectProperties(); } else if (lastSelectedNode instanceof ProjectTreeNode) { ProjectTreeNode projectTreeNode = (ProjectTreeNode) lastSelectedNode; projectProperties = projectTreeNode.getProjectProperties(); } else if (lastSelectedNode instanceof BranchTreeNode) { BranchTreeNode branchTreeNode = (BranchTreeNode) lastSelectedNode; projectProperties = branchTreeNode.getProjectProperties(); } return projectProperties; } private String getAppendedPath() { String retVal = ""; if (lastSelectedNode instanceof DirectoryTreeNode) { DirectoryTreeNode directoryNode = (DirectoryTreeNode) lastSelectedNode; retVal = directoryNode.getAppendedPath(); } return retVal; } private String getBranchName() { String retVal = QVCSConstants.QVCS_TRUNK_BRANCH; if (lastSelectedNode instanceof DirectoryTreeNode) { DirectoryTreeNode directoryNode = (DirectoryTreeNode) lastSelectedNode; retVal = directoryNode.getBranchName(); } else if (lastSelectedNode instanceof BranchTreeNode) { BranchTreeNode branchTreeNode = (BranchTreeNode) lastSelectedNode; retVal = branchTreeNode.getBranchName(); } return retVal; } /** * Get the selected node. * @return the selected node. */ public DefaultMutableTreeNode getSelectedNode() { return (DefaultMutableTreeNode) m_ProjectTree.getLastSelectedPathComponent(); } /** * Get the active branch node. * @return the active branch node. */ public BranchTreeNode getActiveBranchNode() { DefaultMutableTreeNode node = (DefaultMutableTreeNode) m_ProjectTree.getLastSelectedPathComponent(); while (!(node instanceof BranchTreeNode) && node != null) { node = (DefaultMutableTreeNode) node.getParent(); } BranchTreeNode branchTreeNode = (BranchTreeNode) node; return branchTreeNode; } /** * Get an Enumeration of the branches for the active project. * @return an Enumeration of the branches for the active project. This may return null if the user is not within a project (e.g. maybe they have the server node selected). */ public Enumeration getCurrentBranches() { TreeNode projectTreeNode; DefaultMutableTreeNode node = getSelectedNode(); if (node instanceof BranchTreeNode) { projectTreeNode = node.getParent(); } else if (node instanceof ProjectTreeNode) { projectTreeNode = node; } else { return null; } return projectTreeNode.children(); } void addServerMenuItems(javax.swing.JMenu menu) { Font menuFont = new Font("Arial", 0, 12); menu.removeAll(); JMenuItem menuItem = menu.add(actionAddServer); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_A); if ((lastSelectedNode != null) && (lastSelectedNode instanceof ServerTreeNode)) { menuItem = menu.add(actionRemoveServer); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_R); menuItem = menu.add(actionServerProperties); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_P); } else { menuItem = menu.add(actionRemoveServer); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_R); menuItem.setEnabled(false); menuItem = menu.add(actionServerProperties); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_P); menuItem.setEnabled(false); } } void addProjectMenuItems(javax.swing.JMenu menu) { Font menuFont = new Font("Arial", 0, 12); menu.removeAll(); if (lastSelectedNode != null) { if (lastSelectedNode instanceof ProjectTreeNode) { JMenuItem menuItem = menu.add(actionDefineBranch); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_D); } else if (lastSelectedNode instanceof BranchTreeNode) { JMenuItem menuItem = menu.add(actionDefineWorkfileLocation); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_D); menuItem.setEnabled(false); menuItem = menu.add(actionAddDirectory); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_A); menuItem = menu.add(actionAutoAddFiles); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_U); menuItem = menu.add(actionPromoteFromChild); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_P); } else if (lastSelectedNode instanceof DirectoryTreeNode) { JMenuItem menuItem = menu.add(actionDefineWorkfileLocation); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_D); menuItem.setEnabled(false); menuItem = menu.add(actionAddDirectory); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_A); menuItem = menu.add(actionAutoAddFiles); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_U); } else { JMenuItem menuItem = menu.add(actionDefineWorkfileLocation); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_D); menuItem.setEnabled(false); menuItem = menu.add(actionAddDirectory); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_A); menuItem.setEnabled(false); menuItem = menu.add(actionAutoAddFiles); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_U); menuItem.setEnabled(false); } } else { JMenuItem menuItem = menu.add(actionDefineBranch); menuItem.setFont(menuFont); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_D); } } private void addListeners() { m_ProjectTree.addTreeSelectionListener((TreeSelectionEvent treeSelectionEvent) -> { previousSelectedNode = lastSelectedNode; lastSelectedNode = (DefaultMutableTreeNode) m_ProjectTree.getLastSelectedPathComponent(); if (lastSelectedNode != null) { if (lastSelectedNode instanceof ServerTreeNode) { ServerTreeNode serverTreeNode = (ServerTreeNode) lastSelectedNode; serverProperties = serverTreeNode.getServerProperties(); // There is no active project or branch. activeProject = null; activeBranch = null; // See if we are already logged in to this server... boolean loggedInAlreadyFlag = TransportProxyFactory.getInstance().getTransportProxy(serverProperties) != null; QWinFrame.getQWinFrame().setActiveServer(serverProperties); if (loggedInAlreadyFlag) { // If we are already logged in, then the user is manually // navigating to the server node.... so we clear the // data model with the following call. // // If the user is not already logged in, then the login // process will try to restore the project tree so that // the selected node will be the one the user had // selected when last using the application. In that // case, we need to skip this next line of code. QWinFrame.getQWinFrame().setCurrentAppendedPath(QVCSConstants.QWIN_DEFAULT_PROJECT_NAME, QVCSConstants.QVCS_TRUNK_BRANCH, "", QVCSConstants.QVCS_REMOTE_PROJECT_TYPE, true); } } else if (lastSelectedNode instanceof ProjectTreeNode) { ProjectTreeNode projectTreeNode = (ProjectTreeNode) lastSelectedNode; activeProject = projectTreeNode.getProjectProperties(); activeBranch = null; String projectName = projectTreeNode.getProjectName(); TransportProxyFactory.getInstance().requestBranchList(serverProperties, projectName); QWinFrame.getQWinFrame().setCurrentAppendedPath(QVCSConstants.QWIN_DEFAULT_PROJECT_NAME, QVCSConstants.QVCS_TRUNK_BRANCH, "", QVCSConstants.QVCS_REMOTE_PROJECT_TYPE, true); } else if (lastSelectedNode instanceof BranchTreeNode) { BranchTreeNode branchTreeNode = (BranchTreeNode) lastSelectedNode; activeProject = branchTreeNode.getProjectProperties(); activeBranch = branchTreeNode.getBranchName(); serverProperties = findServerProperties(); if (previousSelectedNode instanceof BranchTreeNode) { BranchTreeNode previousBranchTreeNode = (BranchTreeNode) previousSelectedNode; QWinFrame.getQWinFrame().setPreviousProjectName(previousBranchTreeNode.getProjectName()); } QWinFrame.getQWinFrame().setCurrentAppendedPath(branchTreeNode.getProjectProperties().getProjectName(), branchTreeNode.getBranchName(), "", activeProject.getProjectType(), false); } else if (lastSelectedNode instanceof DefaultProjectTreeNode) { QWinFrame.getQWinFrame().setCurrentAppendedPath(QVCSConstants.QWIN_DEFAULT_PROJECT_NAME, QVCSConstants.QVCS_TRUNK_BRANCH, "", QVCSConstants.QVCS_REMOTE_PROJECT_TYPE, true); activeProject = null; activeBranch = null; } else if (lastSelectedNode instanceof DefaultServerTreeNode) { QWinFrame.getQWinFrame().setCurrentAppendedPath(QVCSConstants.QWIN_DEFAULT_PROJECT_NAME, QVCSConstants.QVCS_TRUNK_BRANCH, "", QVCSConstants.QVCS_REMOTE_PROJECT_TYPE, true); activeProject = null; activeBranch = null; } else if (lastSelectedNode instanceof DirectoryTreeNode) { DirectoryTreeNode directoryNode = (DirectoryTreeNode) lastSelectedNode; activeProject = directoryNode.getProjectProperties(); activeBranch = directoryNode.getBranchName(); serverProperties = findServerProperties(); // Expand the new selection... Enumeration expandEnumeration = directoryNode.children(); while (expandEnumeration.hasMoreElements()) { DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) expandEnumeration.nextElement(); TreePath childTreePath = treeSelectionEvent.getNewLeadSelectionPath().pathByAddingChild(childNode); getProjectJTreeControl().makeVisible(childTreePath); } // Collapse the old selection only if the new selection is not a child of the old selection... if (treeSelectionEvent.getOldLeadSelectionPath() != null) { if (!treeSelectionEvent.getOldLeadSelectionPath().isDescendant(treeSelectionEvent.getNewLeadSelectionPath())) { DefaultMutableTreeNode oldSelection = projectTreeModel.findNode(treeSelectionEvent.getOldLeadSelectionPath()); if (oldSelection instanceof DirectoryTreeNode) { DirectoryTreeNode oldDirectoryTreeNode = (DirectoryTreeNode) oldSelection; if (0 == activeProject.getProjectName().compareTo(oldDirectoryTreeNode.getProjectProperties().getProjectName()) && (0 == activeBranch.compareTo(oldDirectoryTreeNode.getBranchName()))) { getProjectJTreeControl().collapsePath(treeSelectionEvent.getOldLeadSelectionPath()); } } } } QWinFrame.getQWinFrame().setCurrentAppendedPath(directoryNode.getProjectProperties().getProjectName(), directoryNode.getBranchName(), directoryNode.getAppendedPath(), activeProject.getProjectType(), false); } } }); m_ProjectTree.addMouseListener(new MouseInputAdapter() { @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger() || ((e.getButton() == MouseEvent.BUTTON3) && (0 != (e.getModifiers() & MouseEvent.MOUSE_RELEASED)))) { // Make sure the node under the mouse is the one // that is selected. TreePath selPath = m_ProjectTree.getPathForLocation(e.getX(), e.getY()); m_ProjectTree.setSelectionPath(selPath); // Turn on all popups, and then figure out which ones // to turn off enableAllPopUpOperations(); if (lastSelectedNode != null) { if (lastSelectedNode instanceof ProjectTreeNode) { m_ProjectPopupMenu.show(m_ProjectTree, e.getX(), e.getY()); } else if (lastSelectedNode instanceof BranchTreeNode) { m_ViewPopupMenu.show(m_ProjectTree, e.getX(), e.getY()); } else if (lastSelectedNode instanceof DirectoryTreeNode) { m_DirectoryPopupMenu.show(m_ProjectTree, e.getX(), e.getY()); } else if (lastSelectedNode instanceof DefaultProjectTreeNode) { disableAllDirectoryOperations(); } else if (lastSelectedNode instanceof DefaultServerTreeNode) { m_RootServerPopupMenu.show(m_ProjectTree, e.getX(), e.getY()); } else if (lastSelectedNode instanceof ServerTreeNode) { m_ServerPopupMenu.show(m_ProjectTree, e.getX(), e.getY()); } } } } }); } /** * Get the active project. * * @return the project properties for the active project. */ public AbstractProjectProperties getActiveProject() { return activeProject; } /** * Get the active branch. * * @return the name of the active branch. */ public String getActiveBranch() { return activeBranch; } String getProjectName() { String projectName = null; if (getActiveProject() != null) { projectName = getActiveProject().getProjectName(); } return projectName; } /** * Get the string for the active server. The active server is the server node that is the parent (or ancestor) of the currently selected node. * * @return the name of the active server, i.e. the one that is the ancestor of the currently selected node. */ public String getActiveServerName() { String serverName = null; ServerProperties serverProps = getActiveServer(); if (serverProps != null) { serverName = serverProps.getServerName(); } return serverName; } /** * Get the server properties for the active server. The active server is the server node that is the parent (or ancestor) of the currently selected node. * * @return the server properties for the current server; i.e. the server properties for the server node that is the ancestor of the currently selected node. */ public ServerProperties getActiveServer() { return serverProperties; } private ServerProperties findServerProperties() { ServerProperties serverProps = null; if (lastSelectedNode != null) { DefaultMutableTreeNode node = lastSelectedNode; while (node != null) { if (node instanceof ServerTreeNode) { ServerTreeNode serverTreeNode = (ServerTreeNode) node; serverProps = serverTreeNode.getServerProperties(); break; } node = (DefaultMutableTreeNode) node.getParent(); } } return serverProps; } /** * Force selection of the root node. */ public void selectRootNode() { // Select the root node -- there is no active project. m_ProjectTree.setSelectionPath(new TreePath(m_ProjectTree.getModel().getRoot())); } /** * Select a given node on the tree control. * * @param nodeToSelect the node to select. */ public void selectNode(TreeNode nodeToSelect) { // First, figure out the depth of the node if (nodeToSelect != null) { int depth = 0; TreeNode parent = nodeToSelect; while ((parent = parent.getParent()) != null) { depth++; } Object[] path = new Object[depth + 1]; parent = nodeToSelect; for (int i = depth; i >= 0; i--) { path[depth--] = parent; parent = parent.getParent(); } // Select the node and make it visible. TreePath treePath = new TreePath(path); m_ProjectTree.setSelectionPath(treePath); m_ProjectTree.scrollPathToVisible(treePath); } } File getCurrentWorkfileDirectory() { File currentWorkfileDirectory = null; // Get the current array of directory managers. The first directory manager is the one // associated with the currently selected node on the tree... DirectoryManagerInterface directoryManagers[] = QWinFrame.getQWinFrame().getCurrentDirectoryManagers(); if (directoryManagers != null) { DirectoryManagerInterface directoryManager = directoryManagers[0]; WorkfileDirectoryManagerInterface workfileDirectoryManager = directoryManager.getWorkfileDirectoryManager(); currentWorkfileDirectory = new File(workfileDirectoryManager.getWorkfileDirectory()); } return currentWorkfileDirectory; } private void initDragAndDrop() { m_ProjectTree.setDragEnabled(true); m_ProjectTree.setTransferHandler(new MyTreeTransferHandler()); } class MyTreeTransferHandler extends TransferHandler { private static final long serialVersionUID = 10L; @Override protected Transferable createTransferable(JComponent c) { // We are a drop target only. The user cannot drag from the tree // control return null; } @Override public boolean canImport(JComponent c, DataFlavor[] flavors) { for (DataFlavor flavor : flavors) { if (flavor.equals(QWinFrame.getQWinFrame().getRightFilePane().getDropDataFlavor())) { return true; } } return false; } @Override public int getSourceActions(JComponent c) { // We are a drop target only. return NONE; } @Override public boolean importData(JComponent comp, Transferable t) { try { if ((lastSelectedNode instanceof DirectoryTreeNode) || (lastSelectedNode instanceof BranchTreeNode)) { final DropTransferData dropTransferData = (DropTransferData) t.getTransferData(QWinFrame.getQWinFrame().getRightFilePane().getDropDataFlavor()); // Make sure we're dropping on the same project/branch if ((0 == getActiveProject().getProjectName().compareTo(dropTransferData.getProjectName())) && (0 == getActiveBranch().compareTo(dropTransferData.getBranchName())) && (0 != getAppendedPath().compareTo(QVCSConstants.QVCS_CEMETERY_DIRECTORY)) && (0 != getAppendedPath().compareTo(QVCSConstants.QVCS_BRANCH_ARCHIVES_DIRECTORY))) { Runnable later = () -> { TransportProxyInterface transportProxy = null; int transactionID = 0; // Verify that the user wants to drop here... int answer = JOptionPane.showConfirmDialog(QWinFrame.getQWinFrame(), "Do you want to move " + dropTransferData.getShortWorkfileName() + " to this directory?\n" + getAppendedPath(), "Confirm File Move", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE); if (answer == JOptionPane.YES_OPTION) { ClientRequestMoveFileData clientRequestMoveFileData = new ClientRequestMoveFileData(); clientRequestMoveFileData.setOriginalAppendedPath(dropTransferData.getAppendedPath()); clientRequestMoveFileData.setProjectName(dropTransferData.getProjectName()); clientRequestMoveFileData.setBranchName(dropTransferData.getBranchName()); clientRequestMoveFileData.setShortWorkfileName(dropTransferData.getShortWorkfileName()); clientRequestMoveFileData.setNewAppendedPath(getAppendedPath()); String serverName = QWinFrame.getQWinFrame().getServerName(); String fullWorkfilePath = QWinFrame.getQWinFrame().getUserWorkfileDirectory(); try { DirectoryCoordinate directoryCoordinate = new DirectoryCoordinate(dropTransferData.getProjectName(), getBranchName(), getAppendedPath()); DirectoryManagerInterface directoryManager = DirectoryManagerFactory.getInstance().getDirectoryManager(QWinFrame.getQWinFrame().getQvcsClientHomeDirectory(), serverName, directoryCoordinate, getActiveProject().getProjectType(), getActiveProject(), fullWorkfilePath, null, false); ArchiveDirManagerProxy archiveDirManagerProxy = (ArchiveDirManagerProxy) directoryManager.getArchiveDirManager(); transportProxy = archiveDirManagerProxy.getTransportProxy(); // Make sure this is synchronized synchronized (transportProxy) { transactionID = ClientTransactionManager.getInstance().sendBeginTransaction(transportProxy); transportProxy.write(clientRequestMoveFileData); } } finally { ClientTransactionManager.getInstance().sendEndTransaction(transportProxy, transactionID); } } }; SwingUtilities.invokeLater(later); } else { if (0 != getActiveProject().getProjectName().compareTo(dropTransferData.getProjectName())) { logProblem("Cannot move a file from one project to another."); } else if (0 != getActiveBranch().compareTo(dropTransferData.getBranchName())) { logProblem("Cannot move a file from one branch to another."); } else if (0 == getAppendedPath().compareTo(QVCSConstants.QVCS_CEMETERY_DIRECTORY)) { logProblem("Cannot move a file to the cemetery."); } else if (0 == getAppendedPath().compareTo(QVCSConstants.QVCS_BRANCH_ARCHIVES_DIRECTORY)) { logProblem("Cannot move a file to the branch archives directory."); } return false; } } else { return false; } } catch (UnsupportedFlavorException | IOException e) { return false; } return true; } @Override protected void exportDone(JComponent c, Transferable data, int action) { switch (action) { case MOVE: default: { // Don't do anything else. logProblem("Export done."); break; } } } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPopupMenu m_DirectoryPopupMenu; private javax.swing.JPopupMenu m_ProjectPopupMenu; private javax.swing.JTree m_ProjectTree; private javax.swing.JPopupMenu m_RootServerPopupMenu; private javax.swing.JScrollPane m_ScrollPane; private javax.swing.JPopupMenu m_ServerPopupMenu; private javax.swing.JPopupMenu m_ViewPopupMenu; // End of variables declaration//GEN-END:variables static class ActionDefineWorkfileLocation extends AbstractAction { private static final long serialVersionUID = 10L; ActionDefineWorkfileLocation(String actionName) { super(actionName); } @Override public void actionPerformed(ActionEvent e) { QWinFrame qWinFrame = QWinFrame.getQWinFrame(); DefineWorkfileLocationDialog defineWorkfileLocationDialog = new DefineWorkfileLocationDialog(qWinFrame); defineWorkfileLocationDialog.setVisible(true); if (defineWorkfileLocationDialog.getIsOK()) { qWinFrame.getUserLocationProperties().setWorkfileLocation(qWinFrame.getServerName(), qWinFrame.getProjectName(), qWinFrame.getBranchName(), defineWorkfileLocationDialog.getWorkfileLocation()); qWinFrame.getUserLocationProperties().saveProperties(); qWinFrame.setUserWorkfileDirectory(defineWorkfileLocationDialog.getWorkfileLocation()); qWinFrame.setRefreshRequired(true); qWinFrame.setCurrentAppendedPath(qWinFrame.getProjectName(), qWinFrame.getBranchName(), qWinFrame.getAppendedPath(), qWinFrame.getProjectType(), false); } } } class ActionAddDirectory extends AbstractAction { private static final long serialVersionUID = 10L; ActionAddDirectory(String actionName) { super(actionName); } @Override public void actionPerformed(ActionEvent e) { OperationBaseClass addDirectoryOperation = new OperationAddDirectory(QWinFrame.getQWinFrame().getServerName(), QWinFrame.getQWinFrame().getProjectName(), getBranchName(), getAppendedPath(), QWinFrame.getQWinFrame().getUserLocationProperties(), getProjectProperties(), getCurrentWorkfileDirectory()); addDirectoryOperation.executeOperation(); } } class ActionDeleteDirectory extends AbstractAction { private static final long serialVersionUID = 10L; ActionDeleteDirectory(String actionName) { super(actionName); } @Override public void actionPerformed(ActionEvent e) { OperationDeleteDirectory deleteDirectoryOperation = new OperationDeleteDirectory(QWinFrame.getQWinFrame().getActiveServerProperties(), getProjectName(), getBranchName(), getAppendedPath()); deleteDirectoryOperation.executeOperation(); } } class ActionAutoAddFiles extends AbstractAction { private static final long serialVersionUID = 10L; ActionAutoAddFiles(String actionName) { super(actionName); } @Override public void actionPerformed(ActionEvent e) { OperationBaseClass autoAddFilesOperation = new OperationAutoAddFiles(QWinFrame.getQWinFrame().getServerName(), QWinFrame.getQWinFrame().getProjectName(), getBranchName(), getAppendedPath(), QWinFrame.getQWinFrame().getUserLocationProperties(), getProjectProperties(), getCurrentWorkfileDirectory()); autoAddFilesOperation.executeOperation(); } } class ActionGetDirectory extends AbstractAction { private static final long serialVersionUID = 10L; ActionGetDirectory(String actionName) { super(actionName); } @Override public void actionPerformed(ActionEvent e) { OperationBaseClass getDirectoryOperation = new OperationGetDirectory(QWinFrame.getQWinFrame().getServerName(), QWinFrame.getQWinFrame().getProjectName(), getBranchName(), getAppendedPath(), QWinFrame.getQWinFrame().getUserLocationProperties(), getProjectProperties(), getCurrentWorkfileDirectory()); getDirectoryOperation.executeOperation(); } } class ActionLabelDirectory extends AbstractAction { private static final long serialVersionUID = 10L; ActionLabelDirectory(String actionName) { super(actionName); } @Override public void actionPerformed(ActionEvent e) { OperationBaseClass labelDirectoryOperation = new OperationLabelDirectory(QWinFrame.getQWinFrame().getServerName(), QWinFrame.getQWinFrame().getProjectName(), getBranchName(), getAppendedPath(), QWinFrame.getQWinFrame().getUserLocationProperties(), getProjectProperties(), getCurrentWorkfileDirectory()); labelDirectoryOperation.executeOperation(); } } class ActionUnLabelDirectory extends AbstractAction { private static final long serialVersionUID = 10L; ActionUnLabelDirectory(String actionName) { super(actionName); } @Override public void actionPerformed(ActionEvent e) { OperationBaseClass unlabelDirectoryOperation = new OperationUnLabelDirectory(QWinFrame.getQWinFrame().getServerName(), QWinFrame.getQWinFrame().getProjectName(), getBranchName(), getAppendedPath(), QWinFrame.getQWinFrame().getUserLocationProperties(), getProjectProperties(), getCurrentWorkfileDirectory()); unlabelDirectoryOperation.executeOperation(); } } static class ActionAddServer extends AbstractAction { private static final long serialVersionUID = 10L; ActionAddServer(String actionName) { super(actionName); } @Override public void actionPerformed(ActionEvent e) { OperationBaseClass addServerOperation = new OperationAddServer(QWinFrame.getQWinFrame().getUserLocationProperties()); addServerOperation.executeOperation(); } } static class ActionServerProperties extends AbstractAction { private static final long serialVersionUID = 10L; ActionServerProperties(String actionName) { super(actionName); } @Override public void actionPerformed(ActionEvent e) { OperationBaseClass editServerPropertiesOperation = new OperationEditServerProperties(QWinFrame.getQWinFrame().getServerName(), QWinFrame.getQWinFrame().getUserLocationProperties()); editServerPropertiesOperation.executeOperation(); } } static class ActionRemoveServer extends AbstractAction { private static final long serialVersionUID = 10L; ActionRemoveServer(String actionName) { super(actionName); } @Override public void actionPerformed(ActionEvent e) { OperationBaseClass removeServerOperation = new OperationRemoveServer(QWinFrame.getQWinFrame().getServerName(), QWinFrame.getQWinFrame().getUserLocationProperties()); removeServerOperation.executeOperation(); } } class ActionDefineBranch extends AbstractAction { private static final long serialVersionUID = 10L; ActionDefineBranch(String actionName) { super(actionName); } @Override public void actionPerformed(ActionEvent e) { OperationDefineBranch defineBranchOperation = new OperationDefineBranch(QWinFrame.getQWinFrame().getActiveServerProperties(), getProjectName()); defineBranchOperation.executeOperation(); } } class ActionMaintainBranch extends AbstractAction { private static final long serialVersionUID = 10L; ActionMaintainBranch(String actionName) { super(actionName); } @Override public void actionPerformed(ActionEvent e) { OperationMaintainBranch maintainBranchOperation = new OperationMaintainBranch(QWinFrame.getQWinFrame().getActiveServerProperties(), getProjectName(), getBranchName(), (RemoteBranchProperties) getProjectProperties()); maintainBranchOperation.executeOperation(); } } class ActionDeleteBranch extends AbstractAction { private static final long serialVersionUID = 10L; ActionDeleteBranch(String actionName) { super(actionName); } @Override public void actionPerformed(ActionEvent e) { OperationDeleteBranch deleteBranchOperation = new OperationDeleteBranch(QWinFrame.getQWinFrame().getActiveServerProperties(), getProjectName(), getBranchName()); deleteBranchOperation.executeOperation(); } } class ActionExpandTree extends AbstractAction { private static final long serialVersionUID = 10L; ActionExpandTree(String actionName) { super(actionName); } @Override public void actionPerformed(ActionEvent e) { TreePath selectionPath = getProjectJTreeControl().getSelectionPath(); getProjectJTreeControl().expandPath(selectionPath); expandNode(selectionPath, lastSelectedNode); } /** * Recursive method used to expand a node (and all its children). * * @param node the node to expand. */ private void expandNode(TreePath anchorTreePath, DefaultMutableTreeNode node) { Enumeration enumeration = node.children(); while (enumeration.hasMoreElements()) { DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) enumeration.nextElement(); TreePath childTreePath = anchorTreePath.pathByAddingChild(childNode); getProjectJTreeControl().makeVisible(childTreePath); if (!childNode.isLeaf()) { expandNode(childTreePath, childNode); } } } } class ActionCollapseTree extends AbstractAction { private static final long serialVersionUID = 10L; ActionCollapseTree(String actionName) { super(actionName); } @Override public void actionPerformed(ActionEvent e) { TreePath selectionPath = getProjectJTreeControl().getSelectionPath(); collapseNode(selectionPath); } /** * Recursive method used to expand a node (and all its children). * * @param node the node to expand. */ private void collapseNode(TreePath anchorTreePath) { TreeMap<String, TreePath> map = new TreeMap<>(); Enumeration<TreePath> enumeration = getProjectJTreeControl().getExpandedDescendants(anchorTreePath); while (enumeration.hasMoreElements()) { TreePath childTreePath = enumeration.nextElement(); // Subtract the path count from 10,000 so the deeper children will sort first -- i.e. // we want to collapse the deepest children first, which will happen as a consequence of // subtracting the path count from 10,000. String mapKey = String.format("%010d%s", 10000 - childTreePath.getPathCount(), childTreePath.toString()); map.put(mapKey, childTreePath); } // Collapse the deepest children first. Iterator<TreePath> it = map.values().iterator(); while (it.hasNext()) { TreePath childPath = it.next(); getProjectJTreeControl().collapsePath(childPath); } getProjectJTreeControl().collapsePath(anchorTreePath); } } class ActionPromoteFromChild extends AbstractAction { private static final long serialVersionUID = 1L; ActionPromoteFromChild(String actionName) { super(actionName); } @Override public void actionPerformed(ActionEvent e) { OperationBaseClass promoteFromChildBranchOperation = new OperationPromoteFilesFromChildBranch(QWinFrame.getQWinFrame().getServerName(), QWinFrame.getQWinFrame().getProjectName(), getBranchName(), QWinFrame.getQWinFrame().getUserLocationProperties(), getCurrentWorkfileDirectory()); promoteFromChildBranchOperation.executeOperation(); } } static class EnterpriseTreeCellRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = 3531447549589503366L; private final ImageIcon iconServers; private final ImageIcon iconServer; private final ImageIcon iconProject; private final ImageIcon iconReadOnlyBranch; private final ImageIcon iconReadWriteBranch; EnterpriseTreeCellRenderer(ImageIcon servers, ImageIcon server, ImageIcon project, ImageIcon readOnlyBranch, ImageIcon readWriteBranch) { iconServers = servers; iconServer = server; iconProject = project; iconReadOnlyBranch = readOnlyBranch; iconReadWriteBranch = readWriteBranch; } @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if (value instanceof DefaultServerTreeNode) { setIcon(iconServers); } else if (value instanceof ServerTreeNode) { setIcon(iconServer); } else if (value instanceof ProjectTreeNode) { setIcon(iconProject); } else if (value instanceof ReadOnlyBranchNode) { ReadOnlyBranchNode branchNode = (ReadOnlyBranchNode) value; setText(branchNode.getBranchName()); setIcon(iconReadOnlyBranch); } else if (value instanceof ReadWriteBranchNode) { ReadWriteBranchNode branchNode = (ReadWriteBranchNode) value; setText(branchNode.getBranchName()); setIcon(iconReadWriteBranch); } return this; } } }
46.804224
227
0.619949
1c29565f7f9823e6a656a91145a946474049a43d
5,008
package org.openxmlformats.schemas.spreadsheetml.x2006.main; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.net.URL; import javax.xml.stream.XMLStreamReader; import org.apache.poi.POIXMLTypeLoader; import org.apache.xmlbeans.SchemaType; import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; import org.apache.xmlbeans.xml.stream.XMLInputStream; import org.apache.xmlbeans.xml.stream.XMLStreamException; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTable; import org.w3c.dom.Node; public interface TableDocument extends XmlObject { SchemaType type = (SchemaType)XmlBeans.typeSystemForClassLoader(TableDocument.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.sF1327CCA741569E70F9CA8C9AF9B44B2").resolveHandle("table0b99doctype"); CTTable getTable(); void setTable(CTTable var1); CTTable addNewTable(); public static final class Factory { public static TableDocument newInstance() { return (TableDocument)POIXMLTypeLoader.newInstance(TableDocument.type, (XmlOptions)null); } public static TableDocument newInstance(XmlOptions var0) { return (TableDocument)POIXMLTypeLoader.newInstance(TableDocument.type, var0); } public static TableDocument parse(String var0) throws XmlException { return (TableDocument)POIXMLTypeLoader.parse(var0, TableDocument.type, (XmlOptions)null); } public static TableDocument parse(String var0, XmlOptions var1) throws XmlException { return (TableDocument)POIXMLTypeLoader.parse(var0, TableDocument.type, var1); } public static TableDocument parse(File var0) throws XmlException, IOException { return (TableDocument)POIXMLTypeLoader.parse(var0, TableDocument.type, (XmlOptions)null); } public static TableDocument parse(File var0, XmlOptions var1) throws XmlException, IOException { return (TableDocument)POIXMLTypeLoader.parse(var0, TableDocument.type, var1); } public static TableDocument parse(URL var0) throws XmlException, IOException { return (TableDocument)POIXMLTypeLoader.parse(var0, TableDocument.type, (XmlOptions)null); } public static TableDocument parse(URL var0, XmlOptions var1) throws XmlException, IOException { return (TableDocument)POIXMLTypeLoader.parse(var0, TableDocument.type, var1); } public static TableDocument parse(InputStream var0) throws XmlException, IOException { return (TableDocument)POIXMLTypeLoader.parse(var0, TableDocument.type, (XmlOptions)null); } public static TableDocument parse(InputStream var0, XmlOptions var1) throws XmlException, IOException { return (TableDocument)POIXMLTypeLoader.parse(var0, TableDocument.type, var1); } public static TableDocument parse(Reader var0) throws XmlException, IOException { return (TableDocument)POIXMLTypeLoader.parse(var0, TableDocument.type, (XmlOptions)null); } public static TableDocument parse(Reader var0, XmlOptions var1) throws XmlException, IOException { return (TableDocument)POIXMLTypeLoader.parse(var0, TableDocument.type, var1); } public static TableDocument parse(XMLStreamReader var0) throws XmlException { return (TableDocument)POIXMLTypeLoader.parse(var0, TableDocument.type, (XmlOptions)null); } public static TableDocument parse(XMLStreamReader var0, XmlOptions var1) throws XmlException { return (TableDocument)POIXMLTypeLoader.parse(var0, TableDocument.type, var1); } public static TableDocument parse(Node var0) throws XmlException { return (TableDocument)POIXMLTypeLoader.parse(var0, TableDocument.type, (XmlOptions)null); } public static TableDocument parse(Node var0, XmlOptions var1) throws XmlException { return (TableDocument)POIXMLTypeLoader.parse(var0, TableDocument.type, var1); } public static TableDocument parse(XMLInputStream var0) throws XmlException, XMLStreamException { return (TableDocument)POIXMLTypeLoader.parse(var0, TableDocument.type, (XmlOptions)null); } public static TableDocument parse(XMLInputStream var0, XmlOptions var1) throws XmlException, XMLStreamException { return (TableDocument)POIXMLTypeLoader.parse(var0, TableDocument.type, var1); } public static XMLInputStream newValidatingXMLInputStream(XMLInputStream var0) throws XmlException, XMLStreamException { return POIXMLTypeLoader.newValidatingXMLInputStream(var0, TableDocument.type, (XmlOptions)null); } public static XMLInputStream newValidatingXMLInputStream(XMLInputStream var0, XmlOptions var1) throws XmlException, XMLStreamException { return POIXMLTypeLoader.newValidatingXMLInputStream(var0, TableDocument.type, var1); } } }
43.172414
209
0.757987
6cefb7e3792c902656cc6e5408c4c93aefd7dbc8
1,062
package com.martin.ads.omoshiroilib.constant; /** * Created by Ads on 2017/1/26. */ public enum Rotation { NORMAL, ROTATION_90, ROTATION_180, ROTATION_270; private Rotation() { } public int asInt() { switch(ordinal()) { case 0: return 0; case 1: return 90; case 2: return 180; case 3: return 270; default: throw new IllegalStateException("Unknown Rotation!"); } } public static Rotation fromInt(int degree) { switch(degree) { case 0: return NORMAL; case 90: return ROTATION_90; case 180: return ROTATION_180; case 270: return ROTATION_270; case 360: return NORMAL; default: throw new IllegalStateException(degree + " is an unknown rotation. Needs to be either 0, 90, 180 or 270!"); } } }
24.136364
123
0.479284
710d3f3c7af9d4b10176f20f0fe7399b43b602ff
1,182
package com.log.web.service.impl; import java.util.Enumeration; import java.util.Properties; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.log.web.service.ILoginService; @Service @Transactional(readOnly = true) public class LoginServiceImpl implements ILoginService { @SuppressWarnings("finally") @Override public boolean userLogin(String username, String password) { boolean result = false; try { Resource resource = new ClassPathResource("/user.properties"); Properties props = PropertiesLoaderUtils.loadProperties(resource); Enumeration<Object> userEnum = props.elements(); while (userEnum.hasMoreElements()) { String strKey = (String) userEnum.nextElement(); String strValue = props.getProperty(strKey); if (strKey.equals(username) && strValue.equals(password)) { result = true; break; } } } catch (Exception e) { e.printStackTrace(); } finally { return result; } } }
27.488372
69
0.755499
3c452212b8032e820e1059230d5ee3f4fafe6b32
14,643
/* * Copyright © 2015 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.cdap.examples.wikipedia; import co.cask.cdap.api.artifact.ArtifactSummary; import co.cask.cdap.api.flow.flowlet.StreamEvent; import co.cask.cdap.api.workflow.WorkflowToken; import co.cask.cdap.common.NotFoundException; import co.cask.cdap.common.conf.Constants; import co.cask.cdap.common.utils.Tasks; import co.cask.cdap.proto.ProgramRunStatus; import co.cask.cdap.proto.RunRecord; import co.cask.cdap.proto.WorkflowTokenNodeDetail; import co.cask.cdap.proto.artifact.AppRequest; import co.cask.cdap.proto.id.ApplicationId; import co.cask.cdap.proto.id.ArtifactId; import co.cask.cdap.proto.id.NamespaceId; import co.cask.cdap.test.ApplicationManager; import co.cask.cdap.test.StreamManager; import co.cask.cdap.test.TestBase; import co.cask.cdap.test.TestConfiguration; import co.cask.cdap.test.WorkflowManager; import co.cask.cdap.test.XSlowTests; import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; /** * Test for {@link WikipediaPipelineApp} */ public class WikipediaPipelineAppTest extends TestBase { private static final Gson GSON = new Gson(); @ClassRule public static final TestConfiguration CONFIG = new TestConfiguration(Constants.Explore.EXPLORE_ENABLED, false); private static final ArtifactId ARTIFACT_ID = NamespaceId.DEFAULT.artifact("WikipediaPipelineArtifact", "1.0"); private static final ApplicationId APP_ID = NamespaceId.DEFAULT.app(WikipediaPipelineApp.class.getSimpleName()); private static final ArtifactSummary ARTIFACT_SUMMARY = new ArtifactSummary("WikipediaPipelineArtifact", "1.0"); @BeforeClass public static void setup() throws Exception { addAppArtifact(ARTIFACT_ID, WikipediaPipelineApp.class); } @Test @Category(XSlowTests.class) public void test() throws Exception { WikipediaPipelineApp.WikipediaAppConfig appConfig = new WikipediaPipelineApp.WikipediaAppConfig(); AppRequest<WikipediaPipelineApp.WikipediaAppConfig> appRequest = new AppRequest<>(ARTIFACT_SUMMARY, appConfig); ApplicationManager appManager = deployApplication(APP_ID.toId(), appRequest); // Setup input streams with test data createTestData(); WorkflowManager workflowManager = appManager.getWorkflowManager(WikipediaPipelineWorkflow.NAME); // Test with default threshold. Workflow should not proceed beyond first condition. testWorkflow(workflowManager, appConfig, 1); // Test with a reduced threshold, so the workflow proceeds beyond the first predicate testWorkflow(workflowManager, appConfig, 2, 1); // Test K-Means appConfig = new WikipediaPipelineApp.WikipediaAppConfig("kmeans"); appRequest = new AppRequest<>(ARTIFACT_SUMMARY, appConfig); appManager = deployApplication(APP_ID.toId(), appRequest); workflowManager = appManager.getWorkflowManager(WikipediaPipelineWorkflow.NAME); testWorkflow(workflowManager, appConfig, 3, 1); } private void createTestData() throws Exception { StreamManager likesStreamManager = getStreamManager(WikipediaPipelineApp.PAGE_TITLES_STREAM); String like1 = GSON.toJson(new StreamToDataset.PageTitleToDatasetMapper.Page("Metallica", "103636093053996", "012-02-11T22:41:49+0000")); String like2 = GSON.toJson(new StreamToDataset.PageTitleToDatasetMapper.Page("grunge", "58417452552", "2012-02-07T21:29:53+0000")); likesStreamManager.send(like1); likesStreamManager.send(like2); StreamManager rawWikipediaStreamManager = getStreamManager(WikipediaPipelineApp.RAW_WIKIPEDIA_STREAM); String data1 = "{\"batchcomplete\":\"\",\"query\":{\"normalized\":[{\"from\":\"metallica\",\"to\":\"Metallica\"}]" + ",\"pages\":{\"18787\":{\"pageid\":18787,\"ns\":0,\"title\":\"Metallica\",\"revisions\":[{\"contentformat\":" + "\"text/x-wiki\",\"contentmodel\":\"wikitext\",\"*\":\"{{Other uses}}{{pp-semi|small=yes}}{{pp-move-indef|" + "small=yes}}{{Use mdy dates|date=April 2013}}{{Infobox musical artist|name = Metallica|image = Metallica at " + "The O2 Arena London 2008.jpg|caption = Metallica in [[London]] in 2008. From left to right: [[Kirk Hammett]], " + "[[Lars Ulrich]], [[James Hetfield]] and [[Robert Trujillo]]\"}]}}}}"; String data2 = "{\"batchcomplete\":\"\",\"query\":{\"pages\":{\"51580\":{\"pageid\":51580,\"ns\":0," + "\"title\":\"Grunge\",\"revisions\":[{\"contentformat\":\"text/x-wiki\",\"contentmodel\":\"wikitext\"," + "\"*\":\"{{About|the music genre}}{{Infobox music genre| name = Grunge| bgcolor = crimson| color = white| " + "stylistic_origins = {{nowrap|[[Alternative rock]], [[hardcore punk]],}} [[Heavy metal music|heavy metal]], " + "[[punk rock]], [[hard rock]], [[noise rock]]| cultural_origins = Mid-1980s, [[Seattle|Seattle, Washington]], " + "[[United States]]| instruments = [[Electric guitar]], [[bass guitar]], [[Drum kit|drums]], " + "[[Singing|vocals]]| derivatives = [[Post-grunge]], [[nu metal]]| subgenrelist = | subgenres = | fusiongenres" + " = | regional_scenes = [[Music of Washington (state)|Washington state]]| other_topics = * " + "[[Alternative metal]]* [[Generation X]]* [[Grunge speak|grunge speak hoax]]* [[timeline of alternative " + "rock]]}}'''Grunge''' (sometimes referred to as the '''Seattle sound''') is a subgenre of [[alternative rock]]" + " that emerged during the mid-1980s in the American state of [[Washington (state)|Washington]], particularly " + "in [[Seattle]]. The early grunge movement revolved around Seattle's [[independent record label]] " + "[[Sub Pop]], but by the early 1990s its popularity had spread, with grunge acts in California and other " + "parts of the U.S. building strong followings and signing major record deals.Grunge became commercially " + "successful in the first half of the 1990s, due mainly to the release of [[Nirvana (band)|Nirvana]]'s " + "''[[Nevermind]]'', [[Pearl Jam]]'s ''[[Ten (Pearl Jam album)|Ten]]'', [[Soundgarden]]'s " + "''[[Badmotorfinger]]'', [[Alice in Chains]]' ''[[Dirt (Alice in Chains album)|Dirt]]'', and " + "[[Stone Temple Pilots]]' ''[[Core (Stone Temple Pilots album)|Core]]''.\"}]}}}}"; rawWikipediaStreamManager.send(data1); rawWikipediaStreamManager.send(data2); waitForStreamToBePopulated(likesStreamManager, 2); waitForStreamToBePopulated(rawWikipediaStreamManager, 2); } private void waitForStreamToBePopulated(final StreamManager streamManager, int numEvents) throws Exception { Tasks.waitFor(numEvents, new Callable<Integer>() { @Override public Integer call() throws Exception { List<StreamEvent> streamEvents = streamManager.getEvents(0, Long.MAX_VALUE, Integer.MAX_VALUE); return streamEvents.size(); } }, 10, TimeUnit.SECONDS); } private void testWorkflow(WorkflowManager workflowManager, WikipediaPipelineApp.WikipediaAppConfig config, int expectedRuns) throws Exception { testWorkflow(workflowManager, config, expectedRuns, null); } private void testWorkflow(WorkflowManager workflowManager, WikipediaPipelineApp.WikipediaAppConfig config, int expectedRuns, @Nullable Integer threshold) throws Exception { if (threshold == null) { workflowManager.start(); } else { workflowManager.start(ImmutableMap.of( WikipediaPipelineWorkflow.MIN_PAGES_THRESHOLD_KEY, String.valueOf(threshold), WikipediaPipelineWorkflow.MODE_KEY, WikipediaPipelineWorkflow.ONLINE_MODE)); } workflowManager.waitForRuns(ProgramRunStatus.COMPLETED, expectedRuns, 5, TimeUnit.MINUTES); String pid = getLatestPid(workflowManager.getHistory()); WorkflowTokenNodeDetail tokenAtCondition = workflowManager.getTokenAtNode(pid, WikipediaPipelineWorkflow.EnoughDataToProceed.class.getSimpleName(), WorkflowToken.Scope.USER, "result"); boolean conditionResult = Boolean.parseBoolean(tokenAtCondition.getTokenDataAtNode().get("result")); if (threshold == null) { Assert.assertFalse(conditionResult); assertWorkflowToken(workflowManager, config, pid, false); } else { Assert.assertTrue(conditionResult); assertWorkflowToken(workflowManager, config, pid, true); } } @Nullable private String getLatestPid(List<RunRecord> history) { String pid = null; long latestStartTime = 0; for (RunRecord runRecord : history) { // OK to use start ts, since we ensure that the next run begins after the previous run finishes in the test if (runRecord.getStartTs() > latestStartTime) { latestStartTime = runRecord.getStartTs(); pid = runRecord.getPid(); } } return pid; } private void assertWorkflowToken(WorkflowManager workflowManager, WikipediaPipelineApp.WikipediaAppConfig config, String pid, boolean continueConditionSucceeded) throws NotFoundException { assertTokenAtPageTitlesMRNode(workflowManager, pid); assertTokenAtRawDataMRNode(workflowManager, pid, continueConditionSucceeded); assertTokenAtNormalizationMRNode(workflowManager, pid, continueConditionSucceeded); assertTokenAtSparkClusteringNode(workflowManager, config, pid, continueConditionSucceeded); assertTokenAtTopNMRNode(workflowManager, pid, continueConditionSucceeded); } private void assertTokenAtPageTitlesMRNode(WorkflowManager workflowManager, String pid) throws NotFoundException { WorkflowTokenNodeDetail pageTitlesUserTokens = workflowManager.getTokenAtNode(pid, WikipediaPipelineApp.LIKES_TO_DATASET_MR_NAME, null, null); Assert.assertTrue(Boolean.parseBoolean(pageTitlesUserTokens.getTokenDataAtNode().get("result"))); WorkflowTokenNodeDetail pageTitlesSystemTokens = workflowManager.getTokenAtNode(pid, WikipediaPipelineApp.LIKES_TO_DATASET_MR_NAME, WorkflowToken.Scope.SYSTEM, null); Assert.assertEquals(2, Integer.parseInt(pageTitlesSystemTokens.getTokenDataAtNode().get("custom.num.records"))); } private void assertTokenAtRawDataMRNode(WorkflowManager workflowManager, String pid, boolean continueConditionSucceeded) throws NotFoundException { if (!continueConditionSucceeded) { return; } WorkflowTokenNodeDetail rawWikiDataUserTokens = workflowManager.getTokenAtNode(pid, WikipediaDataDownloader.NAME, null, null); Assert.assertTrue(Boolean.parseBoolean(rawWikiDataUserTokens.getTokenDataAtNode().get("result"))); WorkflowTokenNodeDetail rawWikiDataSystemTokens = workflowManager.getTokenAtNode(pid, WikipediaDataDownloader.NAME, WorkflowToken.Scope.SYSTEM, null); Assert.assertEquals(2, Integer.parseInt(rawWikiDataSystemTokens.getTokenDataAtNode().get("custom.num.records"))); } private void assertTokenAtNormalizationMRNode(WorkflowManager workflowManager, String pid, boolean continueConditionSucceeded) throws NotFoundException { if (!continueConditionSucceeded) { return; } WorkflowTokenNodeDetail normalizedDataUserTokens = workflowManager.getTokenAtNode(pid, WikiContentValidatorAndNormalizer.NAME, null, null); Assert.assertTrue(Boolean.parseBoolean(normalizedDataUserTokens.getTokenDataAtNode().get("result"))); WorkflowTokenNodeDetail normalizedDataSystemTokens = workflowManager.getTokenAtNode(pid, WikiContentValidatorAndNormalizer.NAME, WorkflowToken.Scope.SYSTEM, null); Assert.assertEquals(2, Integer.parseInt(normalizedDataSystemTokens.getTokenDataAtNode().get("custom.num.records"))); } private void assertTokenAtSparkClusteringNode(WorkflowManager workflowManager, WikipediaPipelineApp.WikipediaAppConfig config, String pid, boolean continueConditionSucceeded) throws NotFoundException { if (!continueConditionSucceeded) { return; } @SuppressWarnings("ConstantConditions") String sparkProgramName = SparkWikipediaClustering.NAME + "-" + config.clusteringAlgorithm.toUpperCase(); WorkflowTokenNodeDetail clusteringUserTokens = workflowManager.getTokenAtNode(pid, sparkProgramName, null, null); Assert.assertEquals(10, Integer.parseInt(clusteringUserTokens.getTokenDataAtNode().get("num.records"))); Assert.assertTrue(clusteringUserTokens.getTokenDataAtNode().containsKey("highest.score.term")); Assert.assertTrue(clusteringUserTokens.getTokenDataAtNode().containsKey("highest.score.value")); WorkflowTokenNodeDetail ldaSystemTokens = workflowManager.getTokenAtNode(pid, sparkProgramName, WorkflowToken.Scope.SYSTEM, null); Assert.assertTrue(ldaSystemTokens.getTokenDataAtNode().isEmpty()); } private void assertTokenAtTopNMRNode(WorkflowManager workflowManager, String pid, boolean continueConditionSucceeded) throws NotFoundException { if (!continueConditionSucceeded) { return; } WorkflowTokenNodeDetail topNUserTokens = workflowManager.getTokenAtNode(pid, TopNMapReduce.NAME, null, null); Assert.assertTrue(Boolean.parseBoolean(topNUserTokens.getTokenDataAtNode().get("result"))); WorkflowTokenNodeDetail topNSystemTokens = workflowManager.getTokenAtNode(pid, TopNMapReduce.NAME, WorkflowToken.Scope.SYSTEM, null); Assert.assertEquals(10, Integer.parseInt(topNSystemTokens.getTokenDataAtNode().get("custom.num.records"))); } }
55.676806
120
0.722734
65107fcb5ade969e17dccf3a06282c13f38a95ac
7,132
package io.windflow.eternalengine.configuration; import io.windflow.eternalengine.entities.DomainLookup; import io.windflow.eternalengine.persistence.*; import io.windflow.eternalengine.services.CryptoService; import io.windflow.eternalengine.entities.ExtensionData; import io.windflow.eternalengine.entities.Page; import io.windflow.eternalengine.utils.TextFileReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.IOException; @Component @PropertySource({"eternalengine.${spring.profiles.active}.properties", "secret.${spring.profiles.active}.properties"}) public class InitialData { private final PageRepository pageRepository; private final ComponentRepository componentRepository; private final ExtensionDataRepository extensionDataRepository; private final DomainLookupRepository domainLookupRepository; private final UserRepository userRepository; private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Value(value = "${eternalengine.resetDataOnStartup:undefined}") String resetDataOnStartup; @Value(value = "${eternalengine.systemNamespace}") String systemNamespace; @Value(value = "${eternalengine.siteOwnerGithubEmail}") String ownerEmail; InitialData(@Autowired PageRepository pageRepository, @Autowired ComponentRepository componentRepository, @Autowired ExtensionDataRepository extensionDataRepository, @Autowired CryptoService cryptoService, @Autowired DomainLookupRepository domainLookupRepository, @Autowired UserRepository userRepository) { this.pageRepository = pageRepository; this.componentRepository = componentRepository; this.extensionDataRepository = extensionDataRepository; this.domainLookupRepository = domainLookupRepository; this.userRepository = userRepository; } @PostConstruct public void initialPage() { if ((resetDataOnStartup.equals("undefined") && pageRepository.count() == 0) || resetDataOnStartup.equals("true")) { logger.warn("Truncating pages and adding default data. Usually happens once. See prop io.windflow.resetDataOnStartup"); pageRepository.truncate(); /* Auth.windflow.io */ savePage("auth-windflow-io.windflow.app", "/", Page.PageType.PageNormal, "/data/auth-windflow-io.windflow.app/pages/index.json"); // SYSTEM savePage(systemNamespace, "/", Page.PageType.Page404, "/data/" + systemNamespace + "/pages/404.json"); } } @PostConstruct public void initialComponents() { if ((resetDataOnStartup.equals("undefined") && componentRepository.count() == 0) || resetDataOnStartup.equals("true")) { logger.warn("Truncating components (and layouts) and adding default data. Usually happens once. See prop io.windflow.resetDataOnStartup"); componentRepository.truncate(); // LAYOUTS /* auth.windflow.io */ saveComponent("auth-windflow-io.windflow.app", "CenteredLayout", io.windflow.eternalengine.entities.Component.ComponentType.LAYOUT, "/data/auth-windflow-io.windflow.app/layouts/CenteredLayout.js"); saveComponent("auth-windflow-io.windflow.app", "SingleColumnLayout", io.windflow.eternalengine.entities.Component.ComponentType.LAYOUT, "/data/auth-windflow-io.windflow.app/layouts/SingleColumnLayout.js"); saveComponent(systemNamespace, "CenteredLayout", io.windflow.eternalengine.entities.Component.ComponentType.LAYOUT, "/data/" + systemNamespace + "/layouts/CenteredLayout.js"); // COMPONENTS /* auth.windflow.io */ saveComponent("auth-windflow-io.windflow.app", "GithubAuth", io.windflow.eternalengine.entities.Component.ComponentType.COMPONENT, "/data/auth-windflow-io.windflow.app/components/GithubAuth.js", "/data/auth-windflow-io.windflow.app/components/GithubAuth.vue"); // SYSTEM saveComponent(systemNamespace, "NotFoundDisplay", io.windflow.eternalengine.entities.Component.ComponentType.COMPONENT, "/data/" + systemNamespace + "/components/NotFoundDisplay.js"); } } @PostConstruct public void temporarySetup() { if ((resetDataOnStartup.equals("undefined") && domainLookupRepository.count() == 0) || resetDataOnStartup.equals("true")) { logger.warn("Truncating domain lookups (and layouts) and adding default data. Usually happens once. See prop io.windflow.resetDataOnStartup"); domainLookupRepository.truncate(); } domainLookupRepository.save( new DomainLookup("windflow-io.windflow.app.local", "windflow-io.windflow.app", ownerEmail) ); domainLookupRepository.save( new DomainLookup("windflow.io.local", "windflow-io.windflow.app", ownerEmail) ); domainLookupRepository.save( new DomainLookup("www.windflow.io.local", "windflow-io.windflow.app", ownerEmail) ); domainLookupRepository.save( new DomainLookup("auth.windflow.io.local", "auth-windflow-io.windflow.app", ownerEmail) ); domainLookupRepository.save( new DomainLookup("app.mimo-connect.com", "mimo-connect.windflow.app", ownerEmail) ); domainLookupRepository.save( new DomainLookup("app.mimo-connect.com.local", "mimo-connect.windflow.app", ownerEmail) ); } /* Private methods */ private void savePage(String domain, String path, Page.PageType type, String filePath) { try { pageRepository.save(new Page(domain, path, type, TextFileReader.getText(filePath))); } catch (IOException ex) { logger.warn("Could not load file: " + ex.getMessage() + ". Ignoring, but be prepared for an error page on first visit!"); } } private void saveComponent(String namespace, String name, io.windflow.eternalengine.entities.Component.ComponentType componentType, String jsPath) { saveComponent(namespace, name, componentType, jsPath, null); } private void saveComponent(String namespace, String name, io.windflow.eternalengine.entities.Component.ComponentType componentType, String jsPath, String vuePath) { try { componentRepository.save(new io.windflow.eternalengine.entities.Component(namespace, name, componentType, TextFileReader.getText(jsPath), TextFileReader.getText(vuePath))); } catch (IOException ex) { logger.warn("Could not load file: " + ex.getMessage() + ". Ignoring, but be prepared for an error page on first visit!"); } } private void saveExtensionData(String className, String key, String value, Boolean encrypted) { extensionDataRepository.save(new ExtensionData(className, key, value, encrypted)); } }
48.189189
311
0.717751
c676224579b50b6ceef7a2e291f5d53e3234b71b
26,955
/* * 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.custos.resource.secret.management.client; import com.google.protobuf.ByteString; import com.google.protobuf.Struct; import io.grpc.ManagedChannel; import io.grpc.stub.MetadataUtils; import org.apache.custos.clients.core.AbstractClient; import org.apache.custos.clients.core.ClientUtils; import org.apache.custos.identity.service.GetJWKSRequest; import org.apache.custos.integration.core.utils.ShamirSecretHandler; import org.apache.custos.resource.secret.management.service.ResourceSecretManagementServiceGrpc; import org.apache.custos.resource.secret.service.*; import java.io.IOException; import java.util.List; import java.util.Map; /** * This class is responsible for managing resource secrets */ public class ResourceSecretManagementClient extends AbstractClient { private ResourceSecretManagementServiceGrpc.ResourceSecretManagementServiceBlockingStub blockingStub; private int defaultNumOfShares = 5; private int defaultThreshold = 3; public ResourceSecretManagementClient(String serviceHost, int servicePort, String clientId, String clientSecret) throws IOException { super(serviceHost, servicePort, clientId, clientSecret); blockingStub = ResourceSecretManagementServiceGrpc.newBlockingStub(managedChannel); blockingStub = MetadataUtils.attachHeaders(blockingStub, ClientUtils.getAuthorizationHeader(clientId, clientSecret)); } /** * provides resource secret for given owner type and resource type * * @param ownerType * @param resourceType * @return */ public SecretMetadata getSecret(ResourceOwnerType ownerType, ResourceType resourceType) { SecretMetadata metadata = SecretMetadata .newBuilder() .setOwnerType(ownerType) .setResourceType(resourceType) .build(); GetSecretRequest request = GetSecretRequest.newBuilder().setMetadata(metadata).build(); return blockingStub.getSecret(request); } /** * provides JWKS keys for calling tenant * * @return */ public Struct getJWKS(ResourceSecretManagementServiceGrpc. ResourceSecretManagementServiceBlockingStub blockingStub) { GetJWKSRequest request = GetJWKSRequest.newBuilder().build(); return blockingStub.getJWKS(request); } /** * Provides metadata object of credentials * * @param clientId * @param token * @return SecretMetadata */ public SecretMetadata getResourceCredentialSummary(String clientId, String token) { GetResourceCredentialByTokenRequest tokenRequest = GetResourceCredentialByTokenRequest .newBuilder() .setClientId(clientId) .setToken(token) .build(); return blockingStub.getResourceCredentialSummary(tokenRequest); } /** * Provides metadata array of credentials metadata * * @param clientId * @param accessibleTokens * @return SecretMetadata[] */ public ResourceCredentialSummaries getAllResourceCredentialSummaries(String clientId, List<String> accessibleTokens) { GetResourceCredentialSummariesRequest summariesRequest = GetResourceCredentialSummariesRequest .newBuilder() .setClientId(clientId) .addAllAccessibleTokens(accessibleTokens).build(); return blockingStub.getAllResourceCredentialSummaries(summariesRequest); } /** * Generate SSH credentials * * @param clientId * @param description * @param ownerId * @return AddResourceCredentialResponse */ public AddResourceCredentialResponse generateSSHCredential(String clientId, String description, String ownerId) { SecretMetadata metadata = SecretMetadata.newBuilder() .setClientId(clientId) .setDescription(description) .setOwnerId(ownerId).build(); SSHCredential sshCredential = SSHCredential .newBuilder() .setMetadata(metadata).build(); return blockingStub.addSSHCredential(sshCredential); } public AddResourceCredentialResponse addSSHCredential(String token, String passphrase, String privateKey, String publicKey, String clientId, String description, String ownerId) { SecretMetadata metadata = SecretMetadata.newBuilder() .setClientId(clientId) .setDescription(description) .setOwnerId(ownerId) .setToken(token). build(); SSHCredential sshCredential = SSHCredential .newBuilder() .setMetadata(metadata) .setPassphrase(passphrase) .setPrivateKey(privateKey) .setPublicKey(publicKey).build(); return blockingStub.addSSHCredential(sshCredential); } /** * Save password credentials * * @param clientId * @param description * @param ownerId * @param password * @return AddResourceCredentialResponse */ public AddResourceCredentialResponse addPasswordCredential(String clientId, String description, String ownerId, String userId, String password) { SecretMetadata metadata = SecretMetadata.newBuilder() .setClientId(clientId) .setDescription(description) .setOwnerId(ownerId).build(); PasswordCredential sshCredential = PasswordCredential .newBuilder() .setMetadata(metadata) .setPassword(password) .build(); if (userId != null) { sshCredential = sshCredential.toBuilder().setUserId(userId).build(); } return blockingStub.addPasswordCredential(sshCredential); } public AddResourceCredentialResponse addPasswordCredential(String token, String clientId, String description, String ownerId, String userId, String password) { SecretMetadata metadata = SecretMetadata.newBuilder() .setClientId(clientId) .setDescription(description) .setOwnerId(ownerId) .setToken(token) .build(); PasswordCredential sshCredential = PasswordCredential .newBuilder() .setMetadata(metadata) .setPassword(password) .build(); if (userId != null) { sshCredential = sshCredential.toBuilder().setUserId(userId).build(); } return blockingStub.addPasswordCredential(sshCredential); } /** * Provides SSHCredential of given token * * @param clientId * @param token * @return SSHCredential */ public SSHCredential getSSHCredential(String clientId, String token, boolean useShamirSecret) { GetResourceCredentialByTokenRequest tokenRequest = GetResourceCredentialByTokenRequest .newBuilder() .setClientId(clientId) .setToken(token) .build(); if (useShamirSecret) { tokenRequest = tokenRequest.toBuilder() .setUseShamirsSecretSharingWithEncryption(true) .setNumOfShares(defaultNumOfShares) .setThreshold(defaultThreshold) .build(); } SSHCredential sshCredential = blockingStub.getSSHCredential(tokenRequest); if (useShamirSecret) { List<ByteString> shares = sshCredential.getPrivateKeySharesList(); String secret = ShamirSecretHandler.generateSecret(shares, defaultNumOfShares, defaultThreshold); sshCredential = sshCredential.toBuilder().setPrivateKey(secret).build(); } return sshCredential; } /** * provides PasswordCredential of given token * * @param clientId * @param token * @return PasswordCredential */ public PasswordCredential getPasswordCredential(String clientId, String token) { GetResourceCredentialByTokenRequest tokenRequest = GetResourceCredentialByTokenRequest .newBuilder() .setClientId(clientId) .setToken(token) .build(); return blockingStub.getPasswordCredential(tokenRequest); } /** * Delete SSHCredential of given token * * @param clientId * @param token * @return ResourceCredentialOperationStatus */ public ResourceCredentialOperationStatus deleteSSHCredential(String clientId, String token) { GetResourceCredentialByTokenRequest tokenRequest = GetResourceCredentialByTokenRequest .newBuilder() .setClientId(clientId) .setToken(token) .build(); return blockingStub.deleteSSHCredential(tokenRequest); } /** * Delete Password Credential of given token * * @param clientId * @param token * @return ResourceCredentialOperationStatus */ public ResourceCredentialOperationStatus deletePWDCredential(String clientId, String token) { GetResourceCredentialByTokenRequest tokenRequest = GetResourceCredentialByTokenRequest .newBuilder() .setClientId(clientId) .setToken(token) .build(); return blockingStub.deletePWDCredential(tokenRequest); } /** * provides resource secret for given owner type and resource type * * @param ownerType * @param resourceType * @return */ public SecretMetadata getSecret(ResourceOwnerType ownerType, ResourceType resourceType, ResourceSecretManagementServiceGrpc. ResourceSecretManagementServiceBlockingStub blockingStub) { SecretMetadata metadata = SecretMetadata .newBuilder() .setOwnerType(ownerType) .setResourceType(resourceType) .build(); GetSecretRequest request = GetSecretRequest.newBuilder().setMetadata(metadata).build(); return blockingStub.getSecret(request); } /** * provides JWKS keys for calling tenant * * @return */ public Struct getJWKS() { GetJWKSRequest request = GetJWKSRequest.newBuilder().build(); return blockingStub.getJWKS(request); } /** * Provides metadata object of credentials * * @param clientId * @param token * @return SecretMetadata */ public SecretMetadata getResourceCredentialSummary(String clientId, String token, ResourceSecretManagementServiceGrpc. ResourceSecretManagementServiceBlockingStub blockingStub) { GetResourceCredentialByTokenRequest tokenRequest = GetResourceCredentialByTokenRequest .newBuilder() .setClientId(clientId) .setToken(token) .build(); return blockingStub.getResourceCredentialSummary(tokenRequest); } /** * Provides metadata array of credentials metadata * * @param clientId * @param accessibleTokens * @return SecretMetadata[] */ public ResourceCredentialSummaries getAllResourceCredentialSummaries(String clientId, List<String> accessibleTokens, ResourceSecretManagementServiceGrpc. ResourceSecretManagementServiceBlockingStub blockingStub) { GetResourceCredentialSummariesRequest summariesRequest = GetResourceCredentialSummariesRequest .newBuilder() .setClientId(clientId) .addAllAccessibleTokens(accessibleTokens).build(); return blockingStub.getAllResourceCredentialSummaries(summariesRequest); } /** * Generate SSH credentials * * @param clientId * @param description * @param ownerId * @return AddResourceCredentialResponse */ public AddResourceCredentialResponse generateSSHCredential(String clientId, String description, String ownerId, ResourceSecretManagementServiceGrpc. ResourceSecretManagementServiceBlockingStub blockingStub) { SecretMetadata metadata = SecretMetadata.newBuilder() .setClientId(clientId) .setDescription(description) .setOwnerId(ownerId).build(); SSHCredential sshCredential = SSHCredential .newBuilder() .setMetadata(metadata).build(); return blockingStub.addSSHCredential(sshCredential); } public AddResourceCredentialResponse addSSHCredential(String token, String passphrase, String privateKey, String publicKey, String clientId, String description, String ownerId, ResourceSecretManagementServiceGrpc. ResourceSecretManagementServiceBlockingStub blockingStub) { SecretMetadata metadata = SecretMetadata.newBuilder() .setClientId(clientId) .setDescription(description) .setOwnerId(ownerId) .setToken(token). build(); SSHCredential sshCredential = SSHCredential .newBuilder() .setMetadata(metadata) .setPassphrase(passphrase) .setPrivateKey(privateKey) .setPublicKey(publicKey).build(); return blockingStub.addSSHCredential(sshCredential); } /** * Save password credentials * * @param clientId * @param description * @param ownerId * @param password * @return AddResourceCredentialResponse */ public AddResourceCredentialResponse addPasswordCredential(String clientId, String description, String ownerId, String userId, String password, ResourceSecretManagementServiceGrpc. ResourceSecretManagementServiceBlockingStub blockingStub) { SecretMetadata metadata = SecretMetadata.newBuilder() .setClientId(clientId) .setDescription(description) .setOwnerId(ownerId).build(); PasswordCredential sshCredential = PasswordCredential .newBuilder() .setMetadata(metadata) .setPassword(password) .build(); if (userId != null) { sshCredential = sshCredential.toBuilder().setUserId(userId).build(); } return blockingStub.addPasswordCredential(sshCredential); } public AddResourceCredentialResponse addPasswordCredential(String token, String clientId, String description, String ownerId, String userId, String password, ResourceSecretManagementServiceGrpc. ResourceSecretManagementServiceBlockingStub blockingStub) { SecretMetadata metadata = SecretMetadata.newBuilder() .setClientId(clientId) .setDescription(description) .setOwnerId(ownerId) .setToken(token) .build(); PasswordCredential sshCredential = PasswordCredential .newBuilder() .setMetadata(metadata) .setPassword(password) .build(); if (userId != null) { sshCredential = sshCredential.toBuilder().setUserId(userId).build(); } return blockingStub.addPasswordCredential(sshCredential); } /** * Provides SSHCredential of given token * * @param clientId * @param token * @return SSHCredential */ public SSHCredential getSSHCredential(String clientId, String token, boolean useShamirSecret, ResourceSecretManagementServiceGrpc. ResourceSecretManagementServiceBlockingStub blockingStub) { GetResourceCredentialByTokenRequest tokenRequest = GetResourceCredentialByTokenRequest .newBuilder() .setClientId(clientId) .setToken(token) .build(); if (useShamirSecret) { tokenRequest = tokenRequest.toBuilder() .setUseShamirsSecretSharingWithEncryption(true) .setNumOfShares(defaultNumOfShares) .setThreshold(defaultThreshold) .build(); } SSHCredential sshCredential = blockingStub.getSSHCredential(tokenRequest); if (useShamirSecret) { List<ByteString> shares = sshCredential.getPrivateKeySharesList(); String secret = ShamirSecretHandler.generateSecret(shares, defaultNumOfShares, defaultThreshold); sshCredential = sshCredential.toBuilder().setPrivateKey(secret).build(); } return sshCredential; } /** * provides PasswordCredential of given token * * @param clientId * @param token * @return PasswordCredential */ public PasswordCredential getPasswordCredential(String clientId, String token, ResourceSecretManagementServiceGrpc. ResourceSecretManagementServiceBlockingStub blockingStub) { GetResourceCredentialByTokenRequest tokenRequest = GetResourceCredentialByTokenRequest .newBuilder() .setClientId(clientId) .setToken(token) .build(); return blockingStub.getPasswordCredential(tokenRequest); } /** * Delete SSHCredential of given token * * @param clientId * @param token * @return ResourceCredentialOperationStatus */ public ResourceCredentialOperationStatus deleteSSHCredential(String clientId, String token, ResourceSecretManagementServiceGrpc. ResourceSecretManagementServiceBlockingStub blockingStub) { GetResourceCredentialByTokenRequest tokenRequest = GetResourceCredentialByTokenRequest .newBuilder() .setClientId(clientId) .setToken(token) .build(); return blockingStub.deleteSSHCredential(tokenRequest); } public AddResourceCredentialResponse addCredentialMap(String clientId, String description, String ownerId, String token, Map<String, String> credentialMap, ResourceSecretManagementServiceGrpc. ResourceSecretManagementServiceBlockingStub blockingStub) { SecretMetadata metadata = SecretMetadata.newBuilder() .setClientId(clientId) .setDescription(description) .setOwnerId(ownerId) .setToken(token). build(); CredentialMap creMap = CredentialMap .newBuilder() .setMetadata(metadata) .putAllCredentialMap(credentialMap) .build(); return blockingStub.addCredentialMap(creMap); } public CredentialMap getCredentialMap(String clientId, String token, ResourceSecretManagementServiceGrpc. ResourceSecretManagementServiceBlockingStub blockingStub) { SecretMetadata metadata = SecretMetadata.newBuilder() .setClientId(clientId) .setToken(token). build(); CredentialMap tokenRequest = CredentialMap .newBuilder() .setMetadata(metadata) .build(); return blockingStub.getCredentialMap(tokenRequest); } public ResourceCredentialOperationStatus deleteCredentialMap(String clientId, String token, ResourceSecretManagementServiceGrpc. ResourceSecretManagementServiceBlockingStub blockingStub) { SecretMetadata metadata = SecretMetadata.newBuilder() .setClientId(clientId) .setToken(token). build(); CredentialMap tokenRequest = CredentialMap .newBuilder() .setMetadata(metadata) .build(); return blockingStub.deleteCredentialMap(tokenRequest); } public ResourceCredentialOperationStatus updateCredentialMap(String clientId, String description, String ownerId, String token, Map<String, String> credentialMap, ResourceSecretManagementServiceGrpc. ResourceSecretManagementServiceBlockingStub blockingStub) { SecretMetadata metadata = SecretMetadata.newBuilder() .setClientId(clientId) .setDescription(description) .setOwnerId(ownerId) .setToken(token). build(); CredentialMap creMap = CredentialMap .newBuilder() .setMetadata(metadata) .putAllCredentialMap(credentialMap) .build(); return blockingStub.updateCredentialMap(creMap); } public AddResourceCredentialResponse addCredentialMap(String clientId, String description, String ownerId, String token, Map<String, String> credentialMap) { SecretMetadata metadata = SecretMetadata.newBuilder() .setClientId(clientId) .setDescription(description) .setOwnerId(ownerId) .setToken(token). build(); CredentialMap creMap = CredentialMap .newBuilder() .setMetadata(metadata) .putAllCredentialMap(credentialMap) .build(); return blockingStub.addCredentialMap(creMap); } public CredentialMap getCredentialMap(String clientId, String token) { SecretMetadata metadata = SecretMetadata.newBuilder() .setClientId(clientId) .setToken(token). build(); CredentialMap tokenRequest = CredentialMap .newBuilder() .setMetadata(metadata) .build(); return blockingStub.getCredentialMap(tokenRequest); } public ResourceCredentialOperationStatus deleteCredentialMap(String clientId, String token) { SecretMetadata metadata = SecretMetadata.newBuilder() .setClientId(clientId) .setToken(token). build(); CredentialMap tokenRequest = CredentialMap .newBuilder() .setMetadata(metadata) .build(); return blockingStub.deleteCredentialMap(tokenRequest); } public ResourceCredentialOperationStatus updateCredentialMap(String clientId, String description, String ownerId, String token, Map<String, String> credentialMap) { SecretMetadata metadata = SecretMetadata.newBuilder() .setClientId(clientId) .setDescription(description) .setOwnerId(ownerId) .setToken(token). build(); CredentialMap creMap = CredentialMap .newBuilder() .setMetadata(metadata) .putAllCredentialMap(credentialMap) .build(); return blockingStub.updateCredentialMap(creMap); } /** * Delete Password Credential of given token * * @param clientId * @param token * @return ResourceCredentialOperationStatus */ public ResourceCredentialOperationStatus deletePWDCredential(String clientId, String token, ResourceSecretManagementServiceGrpc. ResourceSecretManagementServiceBlockingStub blockingStub) { GetResourceCredentialByTokenRequest tokenRequest = GetResourceCredentialByTokenRequest .newBuilder() .setClientId(clientId) .setToken(token) .build(); return blockingStub.deletePWDCredential(tokenRequest); } ManagedChannel getManagedChannel() { return managedChannel; } void setManagedChannel(ManagedChannel managedChannel) { this.managedChannel = managedChannel; } public ResourceSecretManagementServiceGrpc.ResourceSecretManagementServiceBlockingStub getBlockingStub() { return blockingStub; } public void setBlockingStub(ResourceSecretManagementServiceGrpc.ResourceSecretManagementServiceBlockingStub blockingStub) { this.blockingStub = blockingStub; } @Override public void close() throws IOException { if (this.managedChannel != null) { this.managedChannel.shutdown(); } } }
35.844415
157
0.610239
9f8843d4f81faf876c3d005689526a74f5abc209
37,297
/* * 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 main.be.ua.mbarbier.slicemap.lib.roi; import static main.be.ua.mbarbier.slicemap.lib.Lib.linearSpacedSequence; import static main.be.ua.mbarbier.slicemap.lib.roi.LabelFusion.majorityVoting; import static main.be.ua.mbarbier.slicemap.lib.roi.LibRoi.intersectRoi; import static main.be.ua.mbarbier.slicemap.lib.roi.LibRoi.mulRoi; import static main.be.ua.mbarbier.slicemap.lib.roi.LibRoi.roiFromMask; import static main.be.ua.mbarbier.slicemap.lib.roi.LibRoi.roisFromThreshold; import main.be.ua.mbarbier.slicemap.lib.transform.TransformRoi; import ij.plugin.filter.EDM; import ij.IJ; import ij.ImageJ; import ij.ImagePlus; import ij.gui.Overlay; import ij.gui.PolygonRoi; import ij.gui.Roi; import ij.gui.Plot; import ij.gui.ShapeRoi; import ij.gui.Wand; import ij.measure.Calibration; import ij.plugin.frame.RoiManager; import ij.process.Blitter; import ij.process.FloatPolygon; import ij.process.FloatProcessor; import ij.process.ImageProcessor; import ij.process.ImageStatistics; import java.awt.Color; import java.awt.geom.Point2D; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import static main.be.ua.mbarbier.slicemap.lib.roi.LibRoi.minusRoi; import net.lingala.zip4j.exception.ZipException; /** * * @author mbarbier */ public class RoiInterpolation { public static final String SMOOTH_MEAN = "mean"; public static final String SMOOTH_GAUSS = "gauss"; public final String INTERPOLATION_DISTANCE_SQRT = "INTERPOLATION_DISTANCE_SQRT"; public final String INTERPOLATION_DISTANCE_LINEAR = "INTERPOLATION_DISTANCE_LINEAR"; public final String INTERPOLATION_DISTANCE_SIGMOID_1 = "INTERPOLATION_DISTANCE_SIGMOID_1"; public final double SIGMA_SMOOTH = 3.0; public final double INTERVAL_RATIO_SMOOTH = 0.005; public PolygonRoi roiCurve; public double[] roiValues; public ImagePlus mse; public ImagePlus mde; public ImagePlus mie; public ImagePlus mle; public ImagePlus me_sigmoid; public PolygonRoi roiBandOuter; public PolygonRoi roiBandInner; public String interpolation_distance = this.INTERPOLATION_DISTANCE_LINEAR; //public PolygonRoi roiMean; public static class HeightRoi { public Roi roi; public double h; public HeightRoi(Roi roi, double h) { this.roi = roi; this.h = h; } } public static class WeightRoi { public Roi roi; public double w; public WeightRoi(Roi roi, double w) { this.roi = roi; this.w = w; } } public static double[] kernelGauss1D(double s) { double[] xs = linearSpacedSequence( -2.0*Math.round(s), 2.0*Math.round(s), 2*((int) (Math.round(s))+1) ); double[] kern = xs.clone(); int nkern = kern.length; double N = 1.0 / ( s*Math.sqrt(2.0*Math.PI)); double a = Math.pow(1.0/s, 2.0) / 2.0; for (int i = 0; i < nkern; i++) { double x = xs[i]; kern[i] = N * Math.exp( - a * Math.pow(x, 2.0) ); } return kern; } public static double[] conv1D( double[] x, double[] kern) { double[] cx = x.clone(); int nx = x.length; int nkern = kern.length; for (int i = 0; i < nx; i++) { cx[i] = 0; for (int j = 0; j < nkern; j++) { cx[i] = cx[i] + x[(i+j) % nx] * kern[j]; } } return cx; } public static double[] smooth1D( double[] ys, String method, double w) { int ny = ys.length; double[] yt = ys.clone(); switch( method ) { case "mean": for (int i = 0; i < ny; i++) ys[i] = (yt[(i-1) % ny] + yt[i] + yt[(i+1) % ny]) / 3.0; break; case "gauss": double s = w; double[] kernel = kernelGauss1D(s); ys = conv1D( yt, kernel); break; } return ys; } public static void removeOverlap( LinkedHashMap< String, Roi > roiMap ) { String[] keyset = roiMap.keySet().toArray( new String[]{""} ); for ( String key1 : keyset ) { Roi roi1 = roiMap.get(key1); for ( String key2 : keyset ) { Roi roi2 = roiMap.get(key2); if ( !key1.equals(key2) ) { if (roi2 != null) { Color sc = roi2.getStrokeColor(); float sw = roi2.getStrokeWidth(); roi2.setName(key2); // Is it allowed to make this a ShapeRoi? roi2 = minusRoi( roi2, roi1);//.getRois()[0]; roi2.setStrokeColor(sc); roi2.setStrokeWidth(sw); roiMap.put(key2, roi2); } } } } } public static ImagePlus maskFromThreshold(ImagePlus imp, double threshold) { //Mask generated from threshold: All pixels above the threshold are retained (works also for floats) // Empty mask image ImagePlus mask = IJ.createImage("mask_" + imp.getTitle(), imp.getWidth(), imp.getHeight(), 1, 8); ImageProcessor maskIP = mask.getProcessor(); byte[] maskPixels = (byte[]) maskIP.getPixels(); ImageProcessor ip = imp.getProcessor().convertToFloat(); float[] pixels = (float[]) ip.getPixels(); // Obtain the list of indices of pixels whose value is above threshold for (int i = 0; i < pixels.length; i++ ) { if ( pixels[i] > threshold ) { maskPixels[i] = 1; } } //mask.show(); return mask; } public static void plotRoiValues(Roi roi, double[] roiValues) { FloatPolygon p = roi.getFloatPolygon(); int n = p.npoints; float[] x = p.xpoints; float[] y = p.ypoints; double[] xd = new double[n]; double[] yd = new double[n]; for (int i = 0; i < n; i++) { xd[i] = x[i]; yd[i] = y[i]; } Plot plot = new Plot("Roi curve", "x", "y", x, y); plot.add("CIRCLE", xd, yd); //plot.show(); double[] indices = linearSpacedSequence(1.0, (double) n, n); Plot plotValues = new Plot("Values", "i", "value", indices, roiValues); //plotValues.show(); } public void getRoiValues(ImagePlus imp, PolygonRoi roi) { int w = imp.getWidth(); int h = imp.getHeight(); ImageProcessor ip = imp.getProcessor(); double sz = (w+h)/2; //double ratio = 0.01; boolean smooth = true; double interval = Math.max(1.0, INTERVAL_RATIO_SMOOTH*sz); FloatPolygon p = roi.getInterpolatedPolygon( interval, smooth); this.roiValues = new double[p.npoints]; float[] px = p.xpoints; float[] py = p.ypoints; for (int i = 0; i < p.npoints; i++) { this.roiValues[i] = (ip.getInterpolatedValue( px[i], py[i])); } this.roiCurve = new PolygonRoi( p, Roi.POLYGON); } public Point2D perpPoint( double x0, double y0, double x1, double y1, double x2, double y2, double s) { //""" computes a point on a distance s from, and perpendicular to the line-segment [p1,p2] (and at the position of p1) """ double eps = 0.001; double dx = x2-x0; double dy = y2-y0; double a = Math.atan2(dy,dx); double x = s * Math.cos( a + Math.PI/2 ) + x1; double y = s * Math.sin( a + Math.PI/2 ) + y1; Point2D p = new Point2D.Double(x,y); return p; } public void roiBands(PolygonRoi roiMean, double[] roiSigma) { //""" Compute confidence interval ROIs """ FloatPolygon p = roiMean.getFloatPolygon(); float[] px = p.xpoints; float[] py = p.ypoints; int n = p.npoints; float[] ox = new float[n]; float[] oy = new float[n]; float[] ix = new float[n]; float[] iy = new float[n]; for (int i = 0; i < n; i++ ) { float x0; float y0; if (i-1 >= 0) { x0 = px[(i-1) % n]; y0 = py[(i-1) % n]; } else { x0 = px[(n+i-1) % n]; y0 = py[(n+i-1) % n]; } float x1 = px[i % n]; float y1 = py[i % n]; float x2 = px[(i+1) % n]; float y2 = py[(i+1) % n]; double s = roiSigma[i]; Point2D pxy = perpPoint( x0, y0, x1, y1, x2, y2, s); ox[i] = (float) pxy.getX(); oy[i] = (float) pxy.getY(); pxy = perpPoint( x0, y0, x1, y1, x2, y2, -s); ix[i] = (float) pxy.getX(); iy[i] = (float) pxy.getY(); } this.roiBandOuter = new PolygonRoi(ox, oy, Roi.POLYGON); this.roiBandInner = new PolygonRoi(ix, iy, Roi.POLYGON); } public void roiMSE(ImagePlus imp, ArrayList<Roi> rois) { // Parameters boolean innerNegative = true; int backgroundValue = 0; boolean edgesAreBackground = false; ImageProcessor ip = imp.getProcessor(); ArrayList<ImagePlus> masks = new ArrayList<>(); ArrayList<ImagePlus> dist = new ArrayList<>(); ArrayList<ImagePlus> distr = new ArrayList<>(); EDM edm = new EDM(); for (Roi r : rois) { ImageProcessor ipt = ip.duplicate(); ipt.setLineWidth(1); ipt.setColor(Color.WHITE); r.drawPixels(ipt); ipt.invert(); ImagePlus impt = new ImagePlus("contour Roi", ipt); masks.add(impt); //impt.show(); ImageProcessor ipd = edm.makeFloatEDM(ipt, backgroundValue, edgesAreBackground); // Flip the distance sign of the inner pixels ImagePlus impd = new ImagePlus("dist", ipd); ImageProcessor ipdr = ipd.duplicate(); ipdr.sqrt(); ImagePlus impdr = new ImagePlus("dist_sqrt", ipdr); if (innerNegative) { impd = mulRoi(impd, r); impdr = mulRoi(impdr, r); } dist.add(impd); distr.add(impdr); impd.setTitle("dist " + r.getName()); impdr.setTitle("dist sqrt " + r.getName()); //impd.duplicate().show(); } this.mse = IJ.createImage("mse_" + imp.getTitle(), imp.getWidth(), imp.getHeight(), 1, 32); this.mle = IJ.createImage("mle_" + imp.getTitle(), imp.getWidth(), imp.getHeight(), 1, 32); this.mie = IJ.createImage("mle_" + imp.getTitle(), imp.getWidth(), imp.getHeight(), 1, 32); this.mde = IJ.createImage("mde_" + imp.getTitle(), imp.getWidth(), imp.getHeight(), 1, 32); ImageProcessor pmse = mse.getProcessor(); ImageProcessor pmie = mie.getProcessor(); ImageProcessor pmle = mle.getProcessor(); ImageProcessor pmde = mde.getProcessor(); if ( this.interpolation_distance == this.INTERPOLATION_DISTANCE_SQRT ) { for (ImagePlus dr : distr) { ImageProcessor pd = dr.getProcessor(); ImagePlus di = new ImagePlus("root distance", pd.duplicate()); pmie.copyBits(di.getProcessor(), 0, 0, Blitter.ADD); } } for (ImagePlus d : dist) { ImageProcessor pd = d.getProcessor(); ImagePlus d1 = new ImagePlus("distance", pd.duplicate()); pd.sqr(); ImagePlus d2 = new ImagePlus("squared_distance", pd); //d2.show(); pmle.copyBits(d1.getProcessor(), 0, 0, Blitter.ADD); pmse.copyBits(d2.getProcessor(), 0, 0, Blitter.ADD); } pmse.multiply( 1.0/((double) dist.size()-1)); pmde = pmse.duplicate(); mde.setProcessor(pmde); pmde.sqrt(); // Sigmoid distance for interpolation: This gives worse results as the sqrt distance, abandon this approach if ( this.interpolation_distance == this.INTERPOLATION_DISTANCE_SIGMOID_1 ) { this.me_sigmoid = IJ.createImage("mse_" + imp.getTitle(), imp.getWidth(), imp.getHeight(), 1, 32); ImageProcessor pme_sigmoid = me_sigmoid.getProcessor(); for (ImagePlus d : dist) { ImageProcessor pd = d.getProcessor(); //pd.multiply(0.1); ImagePlus d1 = new ImagePlus("distance", pd.duplicate()); pd.sqr(); ImagePlus d2 = new ImagePlus("squared_distance", pd); ImageProcessor pNum = d1.getProcessor().duplicate(); ImageProcessor pDen = d2.getProcessor().duplicate(); pDen.add(1.0); pNum.copyBits(pDen, 0, 0, Blitter.DIVIDE); pme_sigmoid.copyBits(pNum, 0, 0, Blitter.ADD); } } } /** * Create isoline-ROIs from ROIs * * @param rois * @param w * @param h * @return */ public static ArrayList<HeightRoi> isolineFromRoi(ArrayList< WeightRoi > rois, int w, int h) { ImagePlus maskSum = IJ.createImage("maskSum", w, h, 1, 32); ImagePlus imp = IJ.createImage("mask", w, h, 1, 8); ImageProcessor ip = imp.getProcessor(); ImageProcessor pmaskSum = maskSum.getProcessor(); //# Make a height map by z-projection of all ROIs for ( WeightRoi hr : rois ) { ImageProcessor ipt = ip.duplicate(); ipt.setRoi(hr.roi); ipt.setColor(Color.WHITE); ipt.fill(hr.roi); ipt.max(1); ImagePlus impt = new ImagePlus("mask Roi", ipt); //impt.show(); pmaskSum.copyBits(ipt, 0, 0, Blitter.ADD); } //maskSum.show(); // Remove separate ROI's //# Generate the isoline-ROIs ImageStatistics stats = maskSum.getStatistics(ImageStatistics.MIN_MAX); double maxh = stats.max; ArrayList< HeightRoi > isoRois = new ArrayList<>(); for (int i = 0; i < maxh; i++) { ImageProcessor iph = pmaskSum.duplicate(); iph.subtract((double) i); iph.min(0); ImagePlus imph = new ImagePlus("h", iph); iph.max(1); //imph.show(); Roi roi = roiFromMask(imph); HeightRoi hr = new HeightRoi( roi, (double) (i) ); isoRois.add( hr ); } return isoRois; } /** * Create isoline-ROIs from ROIs: this is the function where we allow weights to be given to the ROIs, () * TODO : this does actually not work because we assume the heightmap to have steps of one. This has to be modified. * * @param rois * @param w * @param h * @return */ public static ArrayList<Roi> isolineFromRoi( ArrayList<Roi> rois, ArrayList<Double> ws, int w, int h) { ImagePlus maskSum = IJ.createImage("maskSum", w, h, 1, 32); ImagePlus imp = IJ.createImage("mask", w, h, 1, 8); ImageProcessor ip = imp.getProcessor(); ImageProcessor pmaskSum = maskSum.getProcessor(); //# Make a height map by z-projection of all ROIs for (int index = 0; index < rois.size(); index++ ) { Roi r = rois.get(index); ImageProcessor ipt = ip.duplicate(); ipt.setRoi(r); ipt.setColor(Color.WHITE); ipt.fill(r); ipt.max(1); ipt.multiply( ws.get(index) ); ImagePlus impt = new ImagePlus("mask Roi", ipt); //impt.show(); pmaskSum.copyBits(ipt, 0, 0, Blitter.ADD); } //maskSum.show(); // Remove separate ROI's //# Generate the isoline-ROIs ImageStatistics stats = maskSum.getStatistics(ImageStatistics.MIN_MAX); double maxh = stats.max; ArrayList<Roi> isoRois = new ArrayList<>(); for (int i = 0; i < maxh; i++) { ImageProcessor iph = pmaskSum.duplicate(); iph.subtract((double) i); iph.min(0); ImagePlus imph = new ImagePlus("h", iph); iph.max(1); //imph.show(); Roi roi = roiFromMask(imph); isoRois.add(roi); } return isoRois; } /** * Create isoline-ROIs from probability image: this is the function where we allow weights to be given to the ROIs * * @param maskSum * @param w * @param h * @return */ public static ArrayList<HeightRoi> isolineFromProbabilityImage( ImagePlus maskSum ) { //# Generate the isoline-ROIs ImageProcessor pmaskSum = maskSum.getProcessor(); ImageStatistics stats = maskSum.getStatistics( ImageStatistics.MIN_MAX ); double maxh = stats.max; double smallValue = 0.01; ArrayList<HeightRoi> isoRois = new ArrayList<>(); double max = maxh; double h = 0.0; int iteration = 0; while ( max > smallValue && iteration < 100 ) {//&& Math.pow( isoRois.size(), 2.0 ) > iteration ) { iteration++; ImageProcessor iph = pmaskSum.duplicate(); //iph.subtract( h + smallValue ); ImagePlus imph = new ImagePlus("h", iph); Roi sroi = roisFromThreshold( maskSum, h + smallValue ); Roi roi; if ( sroi == null ) { roi = null; } else { roi = roiMaxRegion( maskSum, sroi ); } //ImagePlus mask = maskFromThreshold( imph, h + smallValue ).duplicate(); // roiListFromMask //Roi roi = roiFromMask( mask ); if ( roi == null || roi.contains(1, 1) ) { // THIS SHOULD NOT HAPPEN h = maxh; max = 0.0; // set last roi h to max if (isoRois.size() > 0) { isoRois.get( isoRois.size()-1 ).h = h; } } else { iph.setRoi(roi); ImageStatistics statsRoi = ImageStatistics.getStatistics( iph , ImageStatistics.MIN_MAX, new Calibration() ); iph.resetRoi(); imph.deleteRoi(); h = Math.max( statsRoi.min, h + smallValue ); isoRois.add( new HeightRoi(roi, h) ); //IJ.log( "isoRois.add, h = " + h ); max = maxh - h; } } return isoRois; } /** * fill with value outside ROI-band * * @param imp * @param roiInner * @param roiOuter * @param bgValue * @param fgValue * @return */ public static ImagePlus fillRoiBand( ImagePlus imp, Roi roiInner, Roi roiOuter, double bgValue, double fgValue) { ImageProcessor fp = imp.getProcessor(); fp.setRoi(roiInner); fp.setValue(fgValue); fp.fill(roiInner.getMask()); fp.setRoi(roiOuter); fp.setValue(bgValue); if ( ( roiOuter.getBounds().width >= fp.getWidth() ) & ( roiOuter.getBounds().height >= fp.getHeight() ) ) { } else { fp.fillOutside(roiOuter); } return imp; } public static ImagePlus isolineMap(ImagePlus imp, ArrayList<HeightRoi> isoRois ) { double backgroundValue = 0.0; boolean edgesAreBackground = false; ImageProcessor ip = imp.getProcessor(); ArrayList<ImagePlus> dist = new ArrayList<>(); EDM edm = new EDM(); // the first roi height ImagePlus firstRoiMask = IJ.createImage("firstRoiMask", imp.getWidth(), imp.getHeight(), 1, 32); firstRoiMask.getProcessor().setValue( isoRois.get(0).h ); firstRoiMask.getProcessor().fill(isoRois.get(0).roi); dist.add( firstRoiMask ); //IJ.log(" Iso-ROIs size = " + isoRois.size()); for (int i = 0; i < (isoRois.size()-1); i++) { Roi r1 = isoRois.get(i).roi; ImageProcessor ip1 = ip.duplicate(); ip1.setLineWidth(1); ip1.setColor(Color.WHITE); r1.drawPixels(ip1); ip1.invert(); Roi r2 = isoRois.get(i+1).roi; ImageProcessor ip2 = ip.duplicate(); ip2.setLineWidth(1); ip2.setColor(Color.WHITE); r2.drawPixels(ip2); ip2.invert(); ImageProcessor ipd1 = edm.makeFloatEDM(ip1, (int) backgroundValue, edgesAreBackground); ImageProcessor ipd2 = edm.makeFloatEDM(ip2, (int) backgroundValue, edgesAreBackground); ImageProcessor ipd = ipd1.duplicate(); ImageProcessor ipd_den = ipd1.duplicate(); ipd_den.copyBits(ipd2, 0, 0, Blitter.ADD); ipd.add(0.0001); ipd_den.add(0.0001); ipd.copyBits(ipd_den, 0, 0, Blitter.DIVIDE); double heightDifference = Math.abs( isoRois.get(i+1).h - isoRois.get(i).h ); ipd.multiply( heightDifference ); ImagePlus impd = new ImagePlus("dist iso-contour intervals", ipd); impd = fillRoiBand(impd, r2, r1, 0.0, heightDifference); dist.add(impd); } ImagePlus impd = IJ.createImage("iso map", imp.getWidth(), imp.getHeight(), 1, 32); ImageProcessor ipd = impd.getProcessor(); for (ImagePlus d : dist) { ipd.copyBits(d.getProcessor(), 0, 0, Blitter.ADD); } //impd.duplicate().show(); ImageStatistics stats = impd.getStatistics(ImageStatistics.MIN_MAX); double maxh = stats.max; if (maxh > 0) { ipd.multiply( isoRois.get(isoRois.size()-1).h / maxh ); } //impd.duplicate().show(); return impd; } public void roiConfidence( ImagePlus imp , ArrayList<Roi> rois ) { //""" Compute mean ROI and rois for confidence interval """ //IJ.log("roiConfidense:: Compute mean ROI and ROIs for confidence interval"); //IJ.log(" Calculating MSE and MLE (as the sum of errors) from the distance matrix image (the not-squared version with negative error values for pixels inside the ROIs)"); roiMSE( imp, rois ); //this.mse.show(); //this.mde.show(); //this.mle.show(); //# Mean ROI //IJ.log(" Obtaining mean ROI from MLE"); ImagePlus maskMle = null; if ( this.interpolation_distance == this.INTERPOLATION_DISTANCE_LINEAR ) { ImageProcessor pmle = this.mle.getProcessor(); pmle.multiply(-1); maskMle = maskFromThreshold(mle, 0.0); } if ( this.interpolation_distance == this.INTERPOLATION_DISTANCE_SQRT ) { ImageProcessor pmie = this.mie.getProcessor(); pmie.multiply(-1); maskMle = maskFromThreshold(mie, 0.0); } if ( this.interpolation_distance == this.INTERPOLATION_DISTANCE_SIGMOID_1 ) { ImageProcessor pme_sigmoid = this.me_sigmoid.getProcessor(); pme_sigmoid.multiply(-1); //me_sigmoid.show(); maskMle = maskFromThreshold(me_sigmoid, 0.0); } PolygonRoi roiInterpol = (PolygonRoi) roiFromMask(maskMle); //# Bands from standard deviation of the mean ROI //IJ.log(" Obtaining the confidence interval by taking the standard deviation for each point/pixel of the mean ROI by means of the MSE"); getRoiValues(mde, roiInterpol); this.roiValues = smooth1D( this.roiValues, "gauss", SIGMA_SMOOTH); roiBands( this.roiCurve, this.roiValues ); } public void roiConfidenceSimple( ImagePlus imp , ArrayList<Roi> rois ) { //""" Compute mean ROI and rois for confidence interval """ //IJ.log("roiConfidence:: Compute mean ROI and ROIs for confidence interval"); //IJ.log(" Calculating MSE and MLE (as the sum of errors) from the distance matrix image (the not-squared version with negative error values for pixels inside the ROIs)"); roiMSE( imp, rois ); //# Mean ROI //IJ.log(" Obtaining mean ROI from MLE"); //ImagePlus maskMle = null; //ImageProcessor pmle = this.mle.getProcessor(); //pmle.multiply(-1); //maskMle = maskFromThreshold(mle, 0.0); PolygonRoi roiInterpol = (PolygonRoi) LibRoi.interpolateRois( rois, imp.getWidth(), imp.getHeight() ); //# Bands from standard deviation of the mean ROI //IJ.log(" Obtaining the confidence interval by taking the standard deviation for each point/pixel of the mean ROI by means of the MSE"); getRoiValues(mde, roiInterpol); this.roiValues = smooth1D( this.roiValues, "gauss", SIGMA_SMOOTH); roiBands( this.roiCurve, this.roiValues ); } public void roiConfidenceProbability( ImagePlus imp , ArrayList<WeightRoi> rois, double perc ) { try { //ArrayList<HeightRoi> isoRois = isolineFromProbabilityImage( maskSum ); ArrayList<HeightRoi> isoRois = isolineFromRoi(rois, imp.getWidth(), imp.getHeight()); ImagePlus isoMap = isolineMap(imp, isoRois); ImagePlus meanMask = maskFromThreshold(isoMap, 0.5); Roi meanRoi = roiFromMask(meanMask); ImagePlus innerMask = maskFromThreshold(isoMap, perc); Roi innerRoi = roiFromMask(innerMask); ImagePlus outerMask = maskFromThreshold(isoMap, 1-perc); Roi outerRoi = roiFromMask(outerMask); boolean smooth = true; double interval = 5; this.roiCurve = new PolygonRoi(meanRoi.getInterpolatedPolygon( interval, smooth), Roi.POLYGON ); this.roiBandOuter = new PolygonRoi(outerRoi.getInterpolatedPolygon( interval, smooth), Roi.POLYGON ); this.roiBandInner = new PolygonRoi(innerRoi.getInterpolatedPolygon( interval, smooth), Roi.POLYGON ); } catch( Exception e ) { this.roiCurve = null; this.roiBandOuter = null; this.roiBandInner = null; } } public void roiConfidenceProbability( ImagePlus prob , double perc ) { try { ArrayList<HeightRoi> isoRois = isolineFromProbabilityImage( prob ); ImagePlus empty = IJ.createImage("empty", prob.getWidth(), prob.getHeight(), prob.getNSlices(), 8 ); ImagePlus isoMap = isolineMap( empty, isoRois); //isoMap.show(); ImagePlus meanMask = maskFromThreshold(isoMap, 0.5); Roi meanRoi = roiFromMask(meanMask); ImagePlus innerMask = maskFromThreshold(isoMap, perc); Roi innerRoi = roiFromMask(innerMask); ImagePlus outerMask = maskFromThreshold(isoMap, 1-perc); Roi outerRoi = roiFromMask(outerMask); boolean smooth = true; double interval = 5; this.roiCurve = new PolygonRoi(meanRoi.getInterpolatedPolygon( interval, smooth), Roi.POLYGON ); this.roiBandOuter = new PolygonRoi(outerRoi.getInterpolatedPolygon( interval, smooth), Roi.POLYGON ); this.roiBandInner = new PolygonRoi(innerRoi.getInterpolatedPolygon( interval, smooth), Roi.POLYGON ); } catch( Exception e ) { IJ.log(e.getMessage()); //IJ.log(e.getCause().toString()); //IJ.log(e.getStackTrace().toString()); this.roiCurve = null; this.roiBandOuter = null; this.roiBandInner = null; } } /** * * TODO: This is at this moment not a weighted version yet, it just removes ROIs which are outliers * * @param imp * @param rois * @param ws * @param perc */ public void roiConfidenceWeightedProbability( ImagePlus imp , ArrayList<WeightRoi> rois, double perc ) { for ( int i = 0; i < rois.size(); i++ ) { if ( rois.get(i).w == 0.0 ) { rois.remove(i); } } if (rois.size() > 0) { ArrayList<HeightRoi> isoRois = isolineFromRoi( rois, imp.getWidth(), imp.getHeight() ); ImagePlus isoMap = isolineMap(imp, isoRois); ImagePlus meanMask = maskFromThreshold(isoMap, 0.5); Roi meanRoi = roiFromMask(meanMask); ImagePlus innerMask = maskFromThreshold(isoMap, perc); Roi innerRoi = roiFromMask(innerMask); ImagePlus outerMask = maskFromThreshold(isoMap, 1-perc); Roi outerRoi = roiFromMask(outerMask); boolean smooth = true; double interval = 5; this.roiCurve = new PolygonRoi(meanRoi.getInterpolatedPolygon( interval, smooth ), Roi.POLYGON ); this.roiBandOuter = new PolygonRoi(outerRoi.getInterpolatedPolygon( interval, smooth ), Roi.POLYGON ); this.roiBandInner = new PolygonRoi(innerRoi.getInterpolatedPolygon( interval, smooth ), Roi.POLYGON ); } else { this.roiCurve = null; this.roiBandOuter = null; this.roiBandInner = null; } } public ImagePlus getOverlayRoiConfidence( LinkedHashMap< String, ArrayList<Roi> > roiListMap, ImagePlus imp ) { LinkedHashMap< String, Roi > roiMapInner = new LinkedHashMap<>(); LinkedHashMap< String, Roi > roiMapOuter = new LinkedHashMap<>(); LinkedHashMap< String, Roi > roiMapMean = new LinkedHashMap<>(); LinkedHashMap< String, Roi > roiMapBand = new LinkedHashMap<>(); for (String key : roiListMap.keySet() ) { ArrayList<Roi> rois = roiListMap.get(key); // sets mse, mle, roiBandOuter, roiBandInner, roiCurve roiConfidence( imp , rois ); //roiConfidenceSimple( imp , rois ); double perc = 0.68; ArrayList< WeightRoi > wrois = new ArrayList<>(); for ( Roi roi : rois ) { WeightRoi wr = new WeightRoi( roi, 1 ); wrois.add(wr); } roiConfidenceProbability( imp , wrois, perc ); roiMapMean.put( key, this.roiCurve ); roiMapInner.put( key, this.roiBandInner ); roiMapOuter.put( key, this.roiBandOuter ); } ImageProcessor ip = imp.getProcessor(); for (String key2 : roiMapInner.keySet() ) { Roi roi1 = roiMapInner.get(key2); Roi roi2 = roiMapOuter.get(key2); ShapeRoi roiOr = LibRoi.xorRoi( roi1, roi2); imp.setRoi(roiOr); roiOr.setFillColor(LibRoi.roiColor().get(key2)); ip.fill(roiOr); Overlay overlay = new Overlay(); overlay.add(roiOr); imp.setOverlay(overlay); imp.flatten(); //imp.show(); //IJ.log("save" + new File( outputFolder + "/" + key2 + ".png").getAbsolutePath() ); //IJ.saveAs(imp, "png", new File( outputFolder + "/" + key2 + ".png").getAbsolutePath() ); roiMapBand.put( key2 + "_XOR", roiOr ); } ImagePlus overlayImage = imp.duplicate(); Overlay overlay = new Overlay(); for (String key : roiMapBand.keySet() ) { overlay.add( roiMapBand.get(key) ); } overlayImage.setOverlay(overlay); overlayImage.setHideOverlay( false ); overlayImage.flatten(); return overlayImage; } public void testROI_60V( String outputPath) { String imageFolder = "D:/p_prog_output/tau_analysis/test4/congealing/montage"; String imageName = "sample_montage_registration.tif"; File imageFile = new File( imageFolder + "/" + imageName ); String roiFolder = "D:/p_prog_output/tau_analysis/test4/congealing/roi"; String outputFolder = new File(outputPath).getAbsolutePath(); File outFile = new File(outputFolder); File roiFile = new File(roiFolder); ImagePlus imp = IJ.openImage(imageFile.getAbsolutePath()); int binning = 4; imp = IJ.createImage("imp_" + imp.getTitle(), imp.getWidth()/binning, imp.getHeight()/binning, 1, 8); //imp.show(); LinkedHashMap< String, LinkedHashMap< String, Roi> > roiMapMap = new LinkedHashMap< String, LinkedHashMap< String, Roi> >(); File[] roiFiles = roiFile.listFiles(); for (File file : roiFiles ) { if (file.isFile() & file.getName().endsWith(".zip")) { try { LinkedHashMap< String, Roi> roiMap = LibRoi.loadRoiAlternative(file); roiMap = TransformRoi.applyRoiScaleTransform(roiMap, 0.0, 0.0, 1.0/((double) binning)); roiMapMap.put(file.getName(), roiMap); } catch (ZipException ex) { Logger.getLogger(RoiInterpolation.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(RoiInterpolation.class.getName()).log(Level.SEVERE, null, ex); } } } LinkedHashMap< String, ArrayList<Roi> > roiListMap = LibRoi.getMapOfLists(roiMapMap); LinkedHashMap< String, Roi > roiMapInner = new LinkedHashMap<>(); LinkedHashMap< String, Roi > roiMapOuter = new LinkedHashMap<>(); LinkedHashMap< String, Roi > roiMapMean = new LinkedHashMap<>(); LinkedHashMap< String, Roi > roiMapBand = new LinkedHashMap<>(); for (String key : roiListMap.keySet() ) { ArrayList<Roi> rois = roiListMap.get(key); // sets mse, mle, roiBandOuter, roiBandInner, roiCurve roiConfidence( imp , rois ); //roiConfidenceSimple( imp , rois ); double perc = 0.68; ArrayList< WeightRoi > wrois = new ArrayList<>(); for ( Roi roi : rois ) { WeightRoi wr = new WeightRoi( roi, 1 ); wrois.add(wr); } roiConfidenceProbability( imp , wrois, perc ); roiMapMean.put( key, this.roiCurve ); roiMapInner.put( key, this.roiBandInner ); roiMapOuter.put( key, this.roiBandOuter ); } ImageProcessor ip = imp.getProcessor(); Overlay overlay = new Overlay(); for (String key2 : roiMapInner.keySet() ) { Roi roi1 = roiMapInner.get(key2); Roi roi2 = roiMapOuter.get(key2); ShapeRoi roiOr = LibRoi.xorRoi( roi1, roi2); imp.setRoi(roiOr); roiOr.setFillColor(LibRoi.roiColor().get(key2)); ip.fill(roiOr); overlay.add(roiOr); //imp.setOverlay(overlay); //imp.flatten(); //imp.show(); //IJ.log("save" + new File( outputFolder + "/" + key2 + ".png").getAbsolutePath() ); //IJ.saveAs(imp, "png", new File( outputFolder + "/" + key2 + ".png").getAbsolutePath() ); roiMapBand.put( key2 + "_XOR", roiOr ); } imp.setOverlay( overlay ); imp.setHideOverlay(false); imp.flatten(); imp.show(); //for (String key : roiMapBand.keySet() ) { // roiMapBand.get(key); //} //roiMapOuter = TransformRoi.applyRoiScaleTransform(roiMapOuter, 0.0, 0.0, ((double) binning)); //roiMapInner = TransformRoi.applyRoiScaleTransform(roiMapInner, 0.0, 0.0, ((double) binning)); //roiMapMean = TransformRoi.applyRoiScaleTransform(roiMapMean, 0.0, 0.0, ((double) binning)); //roiMapBand = TransformRoi.applyRoiScaleTransform(roiMapBand, 0.0, 0.0, ((double) binning)); LibRoi.saveRoiAlternative( new File(outputFolder + "/" + "roiMapMean.zip"), roiMapMean); LibRoi.saveRoiAlternative( new File(outputFolder + "/" + "roiMapInner.zip"), roiMapInner); LibRoi.saveRoiAlternative( new File(outputFolder + "/" + "roiMapOuter.zip"), roiMapOuter); LibRoi.saveRoiAlternative( new File(outputFolder + "/" + "roiMapBand.zip"), roiMapBand); } /** * Exclude outlier ROIs of different images (outliers are defined as those being outside, having no intersection with, the given (interpolated) ROI ) * ( this function takes ArrayLists as input/output ) * * @param rois List of ROIs * @param roiInterp Interpolated ROI which serves as a mask for the other ROIs * @return A copy of the rois where the outlier ROIs are removed from. */ public static ArrayList<Roi> excludeOutlierRois( ArrayList< Roi > rois, Roi roiInterp ) { ArrayList<Roi> outRois = new ArrayList<>(); outRois.addAll(rois); for ( int i = 0; i < outRois.size(); i++ ) { Roi roi = outRois.get( i ); if ( roiInterp == null ) { outRois.remove(i); i--; } else { Roi roiIntersection = intersectRoi( roi, roiInterp ); if ( ( roiIntersection == null ) || roiIntersection.contains(1, 1) ) { outRois.remove(i); i--; } } } return outRois; } /** * Exclude outlier ROIs of different images (outliers are defined as those being outside, having no intersection with, the given (interpolated) ROI ) * ( this function takes Map< roiImage, Roi > as input/output ) * * @param roiMap Map< roiImage, Roi > * @param roiInterp Interpolated ROI which serves as a mask for the other ROIs * @return A copy of the roiMap where the outlier ROIs are removed from. */ public static LinkedHashMap< String, Roi > excludeOutlierRois( LinkedHashMap< String, Roi > roiMap, Roi roiInterp ) { LinkedHashMap< String, Roi> outRoiMap = new LinkedHashMap<>(); outRoiMap.putAll(roiMap); Set<String> keys = outRoiMap.keySet(); String[] keysa = keys.toArray(new String[]{""}); for ( String key : keysa ) { Roi roi = outRoiMap.get( key ); if ( roiInterp == null ) { outRoiMap.remove( key ); } else { Roi roiIntersection = intersectRoi( roi, roiInterp ); if ( ( roiIntersection == null ) || roiIntersection.contains(1, 1) ) { outRoiMap.remove( key ); } } } return outRoiMap; } /** * Exclude outlier ROIs of different images (outliers are defined as those being outside, having no intersection with, the given (interpolated) ROI ) * ( this function takes Map< roiImage, Roi > as input/output ) * * @param roiMap Map< roiImage, Roi > * @param roiInterp Interpolated ROI which serves as a mask for the other ROIs * @param overlapPercentage * @return A copy of the roiMap where the outlier ROIs are removed from. */ public static LinkedHashMap< String, Roi > excludeOutlierRois( LinkedHashMap< String, Roi > roiMap, Roi roiInterp, double overlapPercentage ) { LinkedHashMap< String, Roi> outRoiMap = new LinkedHashMap<>(); outRoiMap.putAll(roiMap); Set<String> keys = outRoiMap.keySet(); String[] keysa = keys.toArray(new String[]{""}); for ( String key : keysa ) { Roi roi = outRoiMap.get( key ); if ( roiInterp == null ) { outRoiMap.remove( key ); } else { Roi roiIntersection = intersectRoi( roi, roiInterp ); if ( ( roiIntersection == null ) || roiIntersection.contains(1, 1) ) { outRoiMap.remove( key ); } else { ImageStatistics stats = roi.getStatistics(); ImageStatistics statsInterpolation = roiIntersection.getStatistics(); if ( statsInterpolation.area < overlapPercentage * stats.area ) { outRoiMap.remove( key ); } } } } return outRoiMap; } public static Roi roiMaxRegion( ImagePlus prob, Roi sroi ) { ShapeRoi srois = new ShapeRoi(sroi); Roi[] rois = srois.getRois(); double[] max = new double[rois.length]; double hmax = 0.0; int maxi = 0; Roi mroi = rois[0]; for ( int i = 0; i < rois.length; i++ ) { Roi roi = rois[i]; prob.setRoi( roi ); ImageStatistics stats = ImageStatistics.getStatistics( prob.getProcessor() ); max[i] = stats.max; if (hmax < max[i]) { hmax = max[i]; maxi = i; } mroi = roi; } return mroi; } public void testProbToRois( String probPath ) { ImagePlus prob = IJ.openImage( probPath ); prob.show(); //double h1 = 0.001; //double h2 = 100.0; //prob.getProcessor().setThreshold(h1, h2, 0); //Roi sroi = roisFromThreshold( prob, 0.5 ); //Roi roi = roiMaxRegion( prob, sroi ); ArrayList<HeightRoi> hrois = isolineFromProbabilityImage( prob ); prob.deleteRoi(); prob.duplicate().show(); ImagePlus empty = prob.duplicate(); empty.deleteRoi(); empty.getProcessor().multiply(0.0); Overlay overlay = new Overlay(); for ( HeightRoi hroi : hrois ) { overlay.add( hroi.roi ); } empty.setOverlay(overlay); empty.setHideOverlay(false); empty.show(); ImagePlus empty2 = IJ.createImage("empty2", prob.getWidth(), prob.getHeight(), prob.getNSlices(), 8 ); ImagePlus probLinear = isolineMap( empty2, hrois ); probLinear.show(); } public static void main(String[] args) { RoiInterpolation roiInterpolation = new RoiInterpolation(); //roiInterpolation.run(); // String outputPath = "d:/p_prog_output/output_test"; // roiInterpolation.testROI_60V( outputPath ); new ImageJ(); String imageFolder = "D:/p_prog_output/slicemap_3/input"; String imageName = "bs_prob.tif"; String path = imageFolder + "/" + imageName; roiInterpolation.testProbToRois( path ); //getOverlayRoiConfidence( LinkedHashMap< String, ArrayList<Roi> > roiListMap, ImagePlus imp ); } }
34.217431
177
0.650964
82d24414e25136ba2e0af41a7d4e4c3476664290
1,770
package org.ovirt.engine.ui.common.widget.table; import com.google.gwt.user.cellview.client.Column; /** * Contract for table widgets that support controlling their columns in terms of visibility and positioning. * * @param <T> * Table row data type. */ public interface ColumnController<T> { int NO_DRAG = -1; /** * Get column at the given index. * <p> * Throws {@link IndexOutOfBoundsException} if the column is not present. */ Column<T, ?> getColumn(int index); /** * Get index of the given column. * <p> * Returns {@code -1} if the column is not present. */ int getColumnIndex(Column<T, ?> column); /** * Get title of the given column to display in the context menu. * <p> * Returns {@code null} if the column is not present. */ String getColumnContextMenuTitle(Column<T, ?> column); /** * Get visibility of the given column. * <p> * Returns {@code false} if the column is not present. */ boolean isColumnVisible(Column<T, ?> column); /** * Set visibility of the given column. * <p> * Does nothing if the column is not present. */ void setColumnVisible(Column<T, ?> column, boolean visible); /** * Swap position of given columns. * <p> * Does nothing unless both columns are present. */ void swapColumns(Column<T, ?> columnOne, Column<T, ?> columnTwo); /** * Get index of the menu item currently being dragged. */ int getDragIndex(); /** * Set index of the menu item currently being dragged. */ void setDragIndex(int dragIndex); /** * Force update of all context menu items. */ void updateColumnContextMenu(); }
24.246575
108
0.609605
1635b0af7aeeb1bb89f37390f884e5bce28daa7d
828
package Warmup; import java.io.BufferedReader; import java.io.InputStreamReader; public class _23timeConversion { public static void main(String[] args) throws Exception { BufferedReader scanner=new BufferedReader(new InputStreamReader(System.in)); String timeInput=scanner.readLine(); String timeZone=(timeInput.substring(timeInput.length()-2,timeInput.length())); if(timeZone.equals("AM")){ int hours=Integer.parseInt(timeInput.substring(0, 2)); if(hours==12){ System.out.println("00"+timeInput.substring(2,timeInput.length()-2)); } else{ System.out.println(timeInput.substring(0,timeInput.length()-2)); } } else { int hours=Integer.parseInt(timeInput.substring(0, 2)); if(hours!=12) hours+=12; System.out.println(hours+timeInput.substring(2,timeInput.length()-2)); } } }
28.551724
81
0.721014
e3f55df28384c8f59c2f1fdc620394220fdcab3c
1,587
package kaptainwutax.ssg; import com.seedfinding.latticg.reversal.DynamicProgram; import com.seedfinding.latticg.reversal.calltype.java.JavaCalls; import kaptainwutax.mcutils.version.MCVersion; import kaptainwutax.seedutils.lcg.LCG; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; public class EyeSeeds { private static final Map<Integer, DynamicProgram> LATTICES = new HashMap<>(); private static final LCG BACK = LCG.JAVA.combine(-760); public static DynamicProgram getLattice(int eyeCount) { DynamicProgram program = LATTICES.get(eyeCount); if (program != null) return program; program = DynamicProgram.create(com.seedfinding.latticg.util.LCG.JAVA); for (int i = 0; i < eyeCount; i++) { program.add(JavaCalls.nextFloat().betweenII(0.9F, 1.0F)); } program.setVerbose(false); LATTICES.put(eyeCount, program); return program; } public static Stream<Long> getEyeSeeds(int eyeCount) { return getLattice(eyeCount).reverse().boxed(); } public static Stream<Long> getPopulationSeeds(int eyeCount, MCVersion version) { return getLattice(eyeCount).reverse().boxed().map(eyeSeed -> toPopulationSeed(eyeSeed, version)); } public static long toPopulationSeed(long eyeSeed, MCVersion version) { long decoratorSeed = BACK.nextSeed(eyeSeed); decoratorSeed ^= LCG.JAVA.multiplier; return version.isOlderThan(MCVersion.v1_13) ? decoratorSeed : decoratorSeed - getStrongholdSalt(version); } public static long getStrongholdSalt(MCVersion version) { return version.isOlderThan(MCVersion.v1_16) ? 20003L : 50000L; } }
31.74
107
0.765595
0287d45c808876647449236f8fcded37b36de4a1
418
package io.machinebox.classificationbox.common; import com.google.gson.annotations.SerializedName; public enum ModelOption { /** * The number of word n-grams to generate from a body of text (default is 1) */ @SerializedName("ngrams") NGRAMS, /** * The distance between words from which to generate n-grams (default is 0, no skipping) */ @SerializedName("skipgrams") SKIPGRAMS; }
26.125
92
0.691388
9f7d75eb033e955ec87e7f7ef262e4f086e40af7
219
package dev.fiki.forgehax.asm.events.render; import dev.fiki.forgehax.api.event.Event; import lombok.AllArgsConstructor; @AllArgsConstructor public class NearClippingPlaneEvent extends Event { public float value; }
21.9
51
0.821918
221f2b38eb2f708f0b86942c065992979d8cbe53
2,028
/* * 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.oodt.commons.database; import org.apache.commons.dbcp.ConnectionFactory; import org.apache.commons.dbcp.DriverManagerConnectionFactory; import org.apache.commons.dbcp.PoolableConnectionFactory; import org.apache.commons.dbcp.PoolingDataSource; import org.apache.commons.pool.impl.GenericObjectPool; import javax.sql.DataSource; /** * @author mattmann * @version $Revision$ * * <p> * A class to build database connections from JDBC information. * </p>. */ public final class DatabaseConnectionBuilder { public static DataSource buildDataSource(String user, String pass, String driver, String url) { DataSource ds; try { Class.forName(driver); } catch (ClassNotFoundException ignore) { } GenericObjectPool connectionPool = new GenericObjectPool(null); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory( url, user, pass); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory( connectionFactory, connectionPool, null, null, false, true); return new PoolingDataSource(connectionPool); } }
34.372881
98
0.725838
730327db201ad462715a5f8f9697955617cecddb
1,149
/* * Copyright 2019 Web3 Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.web3j.console; import static org.web3j.codegen.Console.exitError; public class ContractAuditor { private static final String USAGE = "audit <file name>"; public static void main(String[] args) { if (args.length != 1) { exitError(USAGE); } try { ru.smartdec.smartcheck.app.cli.Tool.main(new String[] {"-p", args[0]}); } catch (Exception e) { System.err.println("The audit operation failed with the following exception:"); e.printStackTrace(); } } }
34.818182
118
0.67624
8cd544933974a9fb9970debf3dafc4adc587a38f
13,460
/* Copyright (c) 2001-2009, The HSQL Development Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the HSQL Development Group nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, * 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 org.hsqldb_voltpatches.jdbc.pool; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.util.Map; import java.util.Properties; import org.hsqldb_voltpatches.jdbc.Util; //#ifdef JAVA6 import java.sql.ClientInfoStatus; import java.sql.NClob; import java.sql.SQLClientInfoException; import java.sql.SQLXML; //#endif JAVA6 /* $Id: BaseConnectionWrapper.java 2933 2009-03-20 13:05:06Z unsaved $ */ // boucherb@users 20051207 - patch 1.8.0.x initial JDBC 4.0 support work // boucherb@users 20060523 - patch 1.9.0 full synch up to Mustang Build 84 // Revision 1.7 2006/07/12 12:45:54 boucherb // - full synch up to Mustang b90 /** * A base class for the two different types of connection wrappers: * SessionConnectionWrapper and LifeTimeConnectionWrapper * * @author Jakob Jenkov */ public abstract class BaseConnectionWrapper implements java.sql.Connection { protected boolean isClosed = false; protected abstract Connection getConnection(); protected void validate() throws SQLException { if (isClosed) { throw Util.connectionClosedException(); } } public boolean isClosed() throws SQLException { return isClosed; } public int getHoldability() throws SQLException { validate(); return getConnection().getHoldability(); } public int getTransactionIsolation() throws SQLException { validate(); return getConnection().getTransactionIsolation(); } public void clearWarnings() throws SQLException { validate(); getConnection().clearWarnings(); } public void commit() throws SQLException { validate(); this.getConnection().commit(); } public void rollback() throws SQLException { validate(); this.getConnection().rollback(); } public boolean getAutoCommit() throws SQLException { return getConnection().getAutoCommit(); } public boolean isReadOnly() throws SQLException { validate(); return getConnection().isReadOnly(); } public void setHoldability(int holdability) throws SQLException { validate(); this.getConnection().setHoldability(holdability); } public void setTransactionIsolation(int level) throws SQLException { validate(); this.getConnection().setTransactionIsolation(level); } public void setAutoCommit(boolean autoCommit) throws SQLException { validate(); this.getConnection().setAutoCommit(autoCommit); } public void setReadOnly(boolean readOnly) throws SQLException { validate(); this.getConnection().setReadOnly(readOnly); } public String getCatalog() throws SQLException { validate(); return this.getConnection().getCatalog(); } public void setCatalog(String catalog) throws SQLException { validate(); this.getConnection().setCatalog(catalog); } public DatabaseMetaData getMetaData() throws SQLException { validate(); return getConnection().getMetaData(); } public SQLWarning getWarnings() throws SQLException { validate(); return this.getConnection().getWarnings(); } public Savepoint setSavepoint() throws SQLException { validate(); return this.getConnection().setSavepoint(); } public void releaseSavepoint(Savepoint savepoint) throws SQLException { validate(); this.getConnection().releaseSavepoint(savepoint); } public void rollback(Savepoint savepoint) throws SQLException { validate(); this.getConnection().rollback(savepoint); } public Statement createStatement() throws SQLException { validate(); return getConnection().createStatement(); } public Statement createStatement( int resultSetType, int resultSetConcurrency) throws SQLException { validate(); return this.getConnection().createStatement(resultSetType, resultSetConcurrency); } public Statement createStatement( int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { validate(); return this.getConnection().createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); } public Map getTypeMap() throws SQLException { validate(); return this.getConnection().getTypeMap(); } public void setTypeMap(Map map) throws SQLException { validate(); this.getConnection().setTypeMap(map); } public String nativeSQL(String sql) throws SQLException { validate(); return this.getConnection().nativeSQL(sql); } public CallableStatement prepareCall(String sql) throws SQLException { validate(); return this.getConnection().prepareCall(sql); } public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { validate(); return this.getConnection().prepareCall(sql, resultSetType, resultSetConcurrency); } public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { validate(); return this.getConnection().prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } public PreparedStatement prepareStatement(String sql) throws SQLException { validate(); return this.getConnection().prepareStatement(sql); } public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { validate(); return this.getConnection().prepareStatement(sql, autoGeneratedKeys); } public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { validate(); return this.prepareStatement(sql, resultSetType, resultSetConcurrency); } public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { validate(); return this.getConnection().prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } public PreparedStatement prepareStatement(String sql, int columnIndexes[]) throws SQLException { validate(); return this.getConnection().prepareStatement(sql, columnIndexes); } public Savepoint setSavepoint(String name) throws SQLException { validate(); return this.getConnection().setSavepoint(name); } public PreparedStatement prepareStatement(String sql, String columnNames[]) throws SQLException { validate(); return this.getConnection().prepareStatement(sql, columnNames); } //------------------------- JDBC 4.0 ----------------------------------- //#ifdef JAVA6 public Clob createClob() throws SQLException { validate(); return this.getConnection().createClob(); } //#endif JAVA6 //#ifdef JAVA6 public Blob createBlob() throws SQLException { validate(); return this.getConnection().createBlob(); } //#endif JAVA6 //#ifdef JAVA6 public NClob createNClob() throws SQLException { validate(); return this.getConnection().createNClob(); } //#endif JAVA6 //#ifdef JAVA6 public SQLXML createSQLXML() throws SQLException { validate(); return this.getConnection().createSQLXML(); } //#endif JAVA6 //#ifdef JAVA6 public boolean isValid(int timeout) throws SQLException { validate(); return this.getConnection().isValid(timeout); } //#endif JAVA6 //#ifdef JAVA6 public void setClientInfo(String name, String value) throws SQLClientInfoException { try { validate(); } catch (SQLException e) { throw new SQLClientInfoException(e.getMessage(), e.getSQLState(), e.getErrorCode(), (Map<String, ClientInfoStatus>) null, e); } this.getConnection().setClientInfo(name, value); } //#endif JAVA6 //#ifdef JAVA6 public void setClientInfo( Properties properties) throws SQLClientInfoException { try { validate(); } catch (SQLException e) { throw new SQLClientInfoException(e.getMessage(), e.getSQLState(), e.getErrorCode(), (Map<String, ClientInfoStatus>) null, e); } this.getConnection().setClientInfo(properties); } //#endif JAVA6 //#ifdef JAVA6 public String getClientInfo(String name) throws SQLException { validate(); return this.getConnection().getClientInfo(name); } //#endif JAVA6 //#ifdef JAVA6 public Properties getClientInfo() throws SQLException { validate(); return this.getConnection().getClientInfo(); } //#endif JAVA6 //#ifdef JDBC4BETA /* public <T extends BaseQuery> T createQueryObject(java.lang.Class<T> ifc) throws SQLException { validate(); return this.getConnection().createQueryObject(ifc); } */ //#endif JAVA6 //#ifdef JDBC4BETA /* public <T extends BaseQuery> T createQueryObject(Class<T> ifc, Connection con) throws SQLException { validate(); return this.getConnection().createQueryObject(ifc, con); } */ //#endif JAVA6 //#ifdef JAVA6 public <T>T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException { validate(); if (this.isWrapperFor(iface)) { return (T) this; } throw Util.invalidArgument("iface: " + iface); } //#endif JAVA6 //#ifdef JAVA6 public boolean isWrapperFor( java.lang.Class<?> iface) throws java.sql.SQLException { return (iface != null && iface.isAssignableFrom(this.getClass())); } //#endif JAVA6 // --------------------------- Added: Mustang Build 80 ------------------------- //#ifdef JAVA6 // renamed from createArray - b87 public Array createArrayOf(String typeName, Object[] elements) throws SQLException { validate(); return this.getConnection().createArrayOf(typeName, elements); } //#endif JAVA6 //#ifdef JAVA6 public Struct createStruct(String typeName, Object[] attributes) throws SQLException { validate(); return this.getConnection().createStruct(typeName, attributes); } //#endif JAVA6 /************************* Volt DB Extensions *************************/ public void setSchema(String schema) throws SQLException { throw new SQLException(); } public String getSchema() throws SQLException { throw new SQLException(); } public void abort(java.util.concurrent.Executor executor) throws SQLException { throw new SQLException(); } public void setNetworkTimeout(java.util.concurrent.Executor executor, int milliseconds) throws SQLException { throw new SQLException(); } public int getNetworkTimeout() throws SQLException { throw new SQLException(); } /**********************************************************************/ }
27.137097
104
0.660104
604f657cd73ae7e698ecca5cb2b1761296060e4a
1,611
/* * Copyright (c) 2008-2013 Haulmont. All rights reserved. * Use is subject to license terms, see http://www.cuba-platform.com/license for details. */ package com.haulmont.cuba.web.toolkit.ui.client.menubar; import com.haulmont.cuba.web.toolkit.ui.CubaMenuBar; import com.vaadin.client.UIDL; import com.vaadin.client.ui.VMenuBar; import com.vaadin.client.ui.menubar.MenuBarConnector; import com.vaadin.shared.ui.Connect; /** * @author artamonov * @version $Id$ */ @Connect(CubaMenuBar.class) public class CubaMenuBarConnector extends MenuBarConnector { @Override public CubaMenuBarState getState() { return (CubaMenuBarState) super.getState(); } @Override public CubaMenuBarWidget getWidget() { return (CubaMenuBarWidget) super.getWidget(); } @Override public void layout() { super.layout(); if (getState().vertical) { getWidget().addStyleName("cuba-menubar-vertical"); } else { getWidget().removeStyleName("cuba-menubar-vertical"); } } @Override protected boolean isUseMoreMenuItem() { return !getState().vertical; } @Override protected String getItemId(UIDL uidl) { if (uidl.hasAttribute("tid")) { return uidl.getStringAttribute("tid"); } return null; } @Override protected void assignAdditionalAttributes(VMenuBar.CustomMenuItem currentItem, UIDL item) { if (item.hasAttribute("cid")) { currentItem.getElement().setAttribute("cuba-id", item.getStringAttribute("cid")); } } }
25.983871
95
0.659839
cfe37080fb49db9eb3d39d9c760b7ebfa848ab0e
1,781
import noogel.xyz.drools.config.DroolsAutoConfiguration; import noogel.xyz.drools.entity.PromotionCtx; import noogel.xyz.drools.entity.PurchaseItem; import noogel.xyz.drools.entity.User; import org.drools.core.base.RuleNameEndsWithAgendaFilter; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.api.runtime.KieSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.stream.Collectors; import java.util.stream.Stream; /** * https://www.cnblogs.com/zhixiang-org-cn/p/10106551.html */ @RunWith(SpringRunner.class) @SpringBootTest(classes = DroolsAutoConfiguration.class) public class DroolsApplicationHelloWordTests { @Autowired KieSession kieSession; @Test public void testHelloWord() { kieSession.fireAllRules(); } @Test public void testUser() { User user=new User("张三",18); kieSession.insert(user); kieSession.fireAllRules(new RuleNameEndsWithAgendaFilter("user")); System.err.println("规则执行完毕后张三变为了:"+user.getName()); } @Test public void testPromotion() { PurchaseItem item = new PurchaseItem(); item.setSkuId("123123"); item.setQuantity(10); item.setPrice(5); PurchaseItem item2 = new PurchaseItem(); item2.setSkuId("123124"); item2.setQuantity(10); item2.setPrice(6); PromotionCtx ctx = new PromotionCtx(); ctx.setPurchaseItemList(Stream.of(item, item2).collect(Collectors.toList())); kieSession.insert(ctx); kieSession.fireAllRules(new RuleNameEndsWithAgendaFilter("man_zhe")); System.out.println(ctx); } }
32.381818
85
0.717013
bfde7bb5f700b6c148404d929c4347f345b0df64
6,796
/* * 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.ode.bpel.common; import org.apache.ode.bpel.pmapi.InvalidRequestException; import org.apache.ode.utils.ISO8601DateParser; import java.io.Serializable; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * Holds a filter that will get interpreted when listing processes. The semantic * of the filtering is somewhat different than the one used in the ProcessQuery * class. Here we're introducing a pseudo process querying language. */ public class ProcessFilter extends Filter<ProcessFilter.FilterKeysOp> implements Serializable { private static final long serialVersionUID = 9999; /** If set, will filter on the process name (accepts ending with wildcard) */ private String nameFilter; /** If set, will filter on the process name (accepts ending with wildcard) */ private String namespaceFilter; /** If set, will filter on the process status (activated or retired) */ private String statusFilter; /** * If set, will filter on the process deployment date. Prefixed with a * comparison operator (<, >, <=, >=, =). We're keeping a string and note * converting to a java date as ISO string dates are much easier and quicker * to manipulate. It's possible to have more than one date filter to handle * the 'between' case. */ private List<String> deployedDateFilter; /** * List of additional information to include when producing the filter result, * currently only 'properties' and 'instance' are supported. */ private List<String> includes; /** * Orders to use when sorting the result (no particular order if not set). * Currently /supported keys are: * <ul> * <li>name</li> * <li>namespace</li> * <li>version</li> * <li>status</li> * <li>deployed</li> * </ul> * Each key can be prefixed with a + or - sign for ascending or descending * orders (ascending if no sign specified).. */ private List<String> orders; // Used both to validate filter keys and to process them enum FilterKeysOp { NAME { void process(ProcessFilter filter, String op, String value) { filter.nameFilter = value; } }, NAMESPACE { void process(ProcessFilter filter, String op, String value) { filter.namespaceFilter = value; } }, STATUS { void process(ProcessFilter filter, String op, String value) { filter.statusFilter = value; } }, DEPLOYED { void process(ProcessFilter filter, String op, String value) { if (filter.deployedDateFilter == null) filter.deployedDateFilter = new ArrayList<String>(); filter.deployedDateFilter.add(op + value); } }; abstract void process(ProcessFilter filter, String op, String value); } enum OrderKeys { NAME, NAMESPACE, VERSION, STATUS, DEPLOYED; } enum StatusKeys { ACTIVATED, RETIRED; } /** * Initializes properly the ProcessFilter attributes by pre-parsing the filter * and orderKeys strings. * * @param filter * @param orderKeys */ public ProcessFilter(String filter, String orderKeys) { init(filter); // Some additional validation on status value if (statusFilter != null) { try { StatusKeys.valueOf(statusFilter.toUpperCase()); } catch (IllegalArgumentException e) { throw new InvalidRequestException( "The status you're using in your filter isn't valid, " + "only the activated and retired status are valid. " + e.toString()); } } // Some additional validation on date format value if (deployedDateFilter != null) { for (String ddf : deployedDateFilter) { try { ISO8601DateParser.parse(getDateWithoutOp(ddf)); } catch (ParseException e) { throw new InvalidRequestException( "Couldn't parse one of the filter date, please make " + "sure it follows the ISO-8601 date or date/time standard (yyyyMMddhhmmss). " + e.toString()); } } } if (orderKeys != null && orderKeys.length() > 0) { orders = new ArrayList<String>(3); for (StringTokenizer orderKeysTok = new StringTokenizer(orderKeys, " "); orderKeysTok .hasMoreTokens();) { String orderKey = orderKeysTok.nextToken(); try { String justKey = orderKey; if (justKey.startsWith("-") || justKey.startsWith("+")) justKey = orderKey.substring(1, justKey.length()); OrderKeys.valueOf(justKey.toUpperCase()); orders.add(orderKey); } catch (IllegalArgumentException e) { throw new InvalidRequestException( "One of the ordering keys isn't valid, processes can only " + "be sorted by name, namespace, version, status and deployed date." + e.toString()); } } } } public String getNameFilter() { return nameFilter; } public String getNamespaceFilter() { return namespaceFilter; } public String getStatusFilter() { return statusFilter; } public List<String> getDeployedDateFilter() { return deployedDateFilter; } public List<String> getIncludes() { return includes; } public List<String> getOrders() { return orders; } public static void main(String[] args) { ProcessFilter pf = new ProcessFilter("name = dtc* status=activated " + "deployed>=2005-11-29T15:12 deployed < 2005-11-29T15:13", "status name -version"); System.out.println("=> " + pf); } @Override protected FilterKeysOp parseKey(String keyVal) { return FilterKeysOp.valueOf(keyVal); } @Override protected FilterKeysOp[] getFilterKeys() { return FilterKeysOp.values(); } @Override protected void process(FilterKeysOp key, Restriction<String> rest) { key.process(this, rest.op, rest.value); } }
31.174312
96
0.66392
98870c28fe252e832ebb98ad55b70768c9e74582
3,854
/* * Copyright 2021 the original author or authors. * <p> * 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 * <p> * https://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.openrewrite.java.recipes; import org.openrewrite.ExecutionContext; import org.openrewrite.Recipe; import org.openrewrite.java.JavaIsoVisitor; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.UsesType; import org.openrewrite.java.tree.J; import org.openrewrite.java.tree.JavaType; import org.openrewrite.java.tree.Statement; import org.openrewrite.java.tree.TypeUtils; import java.text.ParseException; import java.text.RuleBasedCollator; import java.time.Duration; import java.util.Comparator; public class SetDefaultEstimatedEffortPerOccurrence extends Recipe { @Override public String getDisplayName() { return "Set default estimated effort"; } @Override public String getDescription() { return "Retrofit recipes with a deafult estimated effort per occurrence."; } @Override public Duration getEstimatedEffortPerOccurrence() { return Duration.ofMinutes(1); } @Override protected JavaVisitor<ExecutionContext> getSingleSourceApplicableTest() { return new UsesType<>("org.openrewrite.Recipe"); } @Override protected JavaVisitor<ExecutionContext> getVisitor() { return new JavaIsoVisitor<ExecutionContext>() { final JavaTemplate addMethod = JavaTemplate.builder(this::getCursor, "@Override public Duration getEstimatedEffortPerOccurrence() {\n" + "return Duration.ofMinutes(5);\n" + "}") .imports("java.time.Duration") .build(); @Override public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext executionContext) { JavaType.FullyQualified type = TypeUtils.asFullyQualified(classDecl.getType()); if (TypeUtils.isAssignableTo("org.openrewrite.Recipe", type)) { assert type != null; for (Statement statement : classDecl.getBody().getStatements()) { if (statement instanceof J.MethodDeclaration) { J.MethodDeclaration method = (J.MethodDeclaration) statement; if ("getEstimatedEffortPerOccurrence".equals(method.getSimpleName())) { return classDecl; } } } maybeAddImport("java.time.Duration"); try { return classDecl.withTemplate(addMethod, classDecl.getBody().getCoordinates().addMethodDeclaration(Comparator.comparing( J.MethodDeclaration::getSimpleName, new RuleBasedCollator("< getDisplayName < getDescription < getEstimatedEffortPerOccurrence < getVisitor") ))); } catch (ParseException e) { throw new RuntimeException(e); } } return super.visitClassDeclaration(classDecl, executionContext); } }; } }
40.568421
144
0.628957
3edf7388c24c22d55c01aecfd27dc47b5d3020e7
1,699
package com.gocardless.ws; import com.google.common.collect.Sets; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.WebSocketAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Set; public class BroadcastSocket extends WebSocketAdapter { private static final Logger LOGGER = LoggerFactory.getLogger(BroadcastSocket.class); private static final Set<Session> sessions = Sets.newCopyOnWriteArraySet(); @Override public void onWebSocketConnect(Session session) { super.onWebSocketConnect(session); sessions.add(session); LOGGER.info("Socket connected: [{}]", session.getRemoteAddress()); } @Override public void onWebSocketClose(int statusCode, String reason) { super.onWebSocketClose(statusCode, reason); Session session = getSession(); sessions.remove(session); LOGGER.info("Socket closed: [{}] (reason: [{}])", session.getLocalAddress(), reason); } @Override public void onWebSocketError(Throwable cause) { super.onWebSocketError(cause); LOGGER.error("Socket error", cause); } public static void broadcast(String json) { sessions.stream() .filter(Session::isOpen) .forEach(session -> broadcast(json, session)); } private static void broadcast(String json, Session session) { LOGGER.info("Broadcasting to [{}]", session.getRemoteAddress()); try { session.getRemote().sendString(json); } catch (IOException e) { LOGGER.error("Error broadcasting message", e); } } }
29.807018
93
0.67216
2914f871f0cb42805b04c13c1d38aafcdf54f16e
1,314
package mekanism.common.tile.prefab; import mekanism.api.IConfigCardAccess; import mekanism.api.providers.IBlockProvider; import mekanism.api.recipes.MekanismRecipe; import mekanism.common.base.ISideConfiguration; import mekanism.common.capabilities.Capabilities; import mekanism.common.capabilities.resolver.basic.BasicCapabilityResolver; import mekanism.common.tile.component.TileComponentConfig; import mekanism.common.tile.component.TileComponentEjector; import net.minecraft.util.Direction; public abstract class TileEntityBasicMachine<RECIPE extends MekanismRecipe> extends TileEntityOperationalMachine<RECIPE> implements ISideConfiguration, IConfigCardAccess { public TileComponentEjector ejectorComponent; public TileComponentConfig configComponent; public TileEntityBasicMachine(IBlockProvider blockProvider, int baseTicksRequired) { super(blockProvider, baseTicksRequired); addCapabilityResolver(BasicCapabilityResolver.constant(Capabilities.CONFIG_CARD_CAPABILITY, this)); } @Override public TileComponentConfig getConfig() { return configComponent; } @Override public Direction getOrientation() { return getDirection(); } @Override public TileComponentEjector getEjector() { return ejectorComponent; } }
35.513514
171
0.80137
d8a658b82a0671718c567a2eaac2693f30265d35
488
package com.lvmoney.frame.db.mysql.base.config;/** * 描述: * 包名:com.lvmoney.frame.member.info.handler * 版本信息: 版本1.0 * 日期:2020/1/20 * Copyright XXXXXX科技有限公司 */ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; /** * @describe: * @author: lvmoney/XXXXXX科技有限公司 * @version:v1.0 2020/1/20 16:52 */ @Configuration @ImportResource(locations = {"classpath:uid/cached-uid-spring.xml"}) public class UidConfig { }
22.181818
68
0.741803
7683e7637572e7f1ef212f956aedc8a327501011
1,815
package com.emall.search.service.impl; import com.alibaba.fastjson.JSON; import com.common.to.es.SkuEsModel; import com.emall.search.config.ElasticSearchConfig; import com.emall.search.constant.EsConstant; import com.emall.search.service.ProductSavaService; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.xcontent.XContentType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @Slf4j @Service public class ProductSaveServiceImpl implements ProductSavaService { @Autowired RestHighLevelClient restHighLevelClient; @Override public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException { BulkRequest bulkRequest = new BulkRequest(); for (SkuEsModel model : skuEsModels) { IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX); indexRequest.id(model.getSkuId().toString()); String s = JSON.toJSONString(model); indexRequest.source(s, XContentType.JSON); bulkRequest.add(indexRequest); } BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS); boolean hasFailures = bulk.hasFailures(); if(hasFailures){ List<String> collect = Arrays.stream(bulk.getItems()).map(item -> item.getId()).collect(Collectors.toList()); log.info("商品上架完成:{}",collect); } return hasFailures; } }
35.588235
121
0.746006
95cd9884c32e7f164283eb70c0640062a4aa171c
1,984
/* * 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.polygene.runtime.composite; import java.util.concurrent.atomic.AtomicReference; /** * Method instance pool that keeps a linked list. Uses atomic reference * to ensure that instances are acquired and returned in a thread-safe * manner. */ public final class AtomicInstancePool implements InstancePool<CompositeMethodInstance> { private final AtomicReference<CompositeMethodInstance> first = new AtomicReference<>(); @Override public CompositeMethodInstance obtainInstance() { CompositeMethodInstance firstInstance; do { firstInstance = first.get(); } while( firstInstance != null && !first.compareAndSet( firstInstance, firstInstance.getNext() ) ); return firstInstance; } @Override public void releaseInstance( CompositeMethodInstance compositeMethodInstance ) { CompositeMethodInstance firstInstance; do { firstInstance = first.get(); compositeMethodInstance.setNext( firstInstance ); } while( !first.compareAndSet( firstInstance, compositeMethodInstance ) ); } }
33.066667
105
0.708165
c98d5b003f6181e4df91ac397509b5ebb0d1079c
3,101
package com.fincatto.documentofiscal.nfe310.classes.nota; import java.util.List; import org.simpleframework.xml.Element; import org.simpleframework.xml.ElementList; import com.fincatto.documentofiscal.DFBase; import com.fincatto.documentofiscal.nfe310.classes.NFModalidadeFrete; import com.fincatto.documentofiscal.validadores.ListValidador; import com.fincatto.documentofiscal.validadores.StringValidador; public class NFNotaInfoTransporte extends DFBase { private static final long serialVersionUID = 1172316192774549031L; @Element(name = "modFrete", required = true) private NFModalidadeFrete modalidadeFrete; @Element(name = "transporta", required = false) private NFNotaInfoTransportador transportador; @Element(name = "retTransp", required = false) private NFNotaInfoRetencaoICMSTransporte icmsTransporte; @Element(name = "veicTransp", required = false) private NFNotaInfoVeiculo veiculo; @ElementList(entry = "reboque", inline = true, required = false) private List<NFNotaInfoReboque> reboques; @Element(name = "vagao", required = false) private String vagao; @Element(name = "balsa", required = false) private String balsa; @ElementList(entry = "vol", inline = true, required = false) private List<NFNotaInfoVolume> volumes; public void setModalidadeFrete(final NFModalidadeFrete modalidadeFrete) { this.modalidadeFrete = modalidadeFrete; } public void setTransportador(final NFNotaInfoTransportador transportador) { this.transportador = transportador; } public void setIcmsTransporte(final NFNotaInfoRetencaoICMSTransporte icmsTransporte) { this.icmsTransporte = icmsTransporte; } public void setVeiculo(final NFNotaInfoVeiculo veiculo) { this.veiculo = veiculo; } public void setReboques(final List<NFNotaInfoReboque> reboques) { ListValidador.tamanho5(reboques, "Reboques"); this.reboques = reboques; } public void setVolumes(final List<NFNotaInfoVolume> volumes) { ListValidador.tamanho5000(volumes, "Volumes"); this.volumes = volumes; } public void setVagao(final String vagao) { StringValidador.tamanho20(vagao, "Vagao"); this.vagao = vagao; } public void setBalsa(final String balsa) { StringValidador.tamanho20(balsa, "Balsa"); this.balsa = balsa; } public NFModalidadeFrete getModalidadeFrete() { return this.modalidadeFrete; } public NFNotaInfoTransportador getTransportador() { return this.transportador; } public NFNotaInfoRetencaoICMSTransporte getIcmsTransporte() { return this.icmsTransporte; } public NFNotaInfoVeiculo getVeiculo() { return this.veiculo; } public List<NFNotaInfoReboque> getReboques() { return this.reboques; } public String getVagao() { return this.vagao; } public String getBalsa() { return this.balsa; } public List<NFNotaInfoVolume> getVolumes() { return this.volumes; } }
28.981308
90
0.711061
721c344b37a2a8cd766087a684a92196e38f687c
645
package pig.dream.utils; import com.google.common.io.Resources; import com.intellij.openapi.util.ClassLoaderUtil; import com.intellij.openapi.vfs.VirtualFile; import javax.swing.*; import java.io.*; import java.net.URL; import java.util.ResourceBundle; /** * * Created by zhukun on 2017/3/21. */ public class GenerateHelper { private static String MESSAGE = ""; public static void generate(VirtualFile selectedFile) { if (selectedFile != null && selectedFile.isDirectory()) { String selectedFilePath = selectedFile.getPath(); ActivityCreator.create().generate(selectedFilePath); } } }
23.888889
65
0.703876
6ffa79e536c9d21595596c909ae9fce165aead05
752
// Write a program to print the maximum of given numbers import java.util.Scanner; import java.util.*; public class MaximumOfNumbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter numbers : "); String input = sc.nextLine(); String[] inputArr = input.split(" "); Integer[] numbers = new Integer[inputArr.length]; for (int i = 0; i < numbers.length; i++) { numbers[i] = Integer.parseInt(inputArr[i]); } List<Integer> list = Arrays.asList(numbers); System.out.print("\nMaximum Number : "); list.stream().reduce((x, y) -> x > y ? x : y).ifPresent(System.out::println); sc.close(); } }
28.923077
85
0.589096
11806f8bdc226d28a769b131e706c552fd739827
846
package ru.croc.ctp.jxfw.reporting.xslfo.renderer.core; /** * Перечисление стилей шрифта. * Аналог System.Drawing.FontStyle в .Net * Created by vsavenkov on 28.06.2017. */ public enum FontStyle { /** * Normal text. */ Regular(0), /** * Bold text. */ Bold(1), /** * Italic text. */ Italic(2), /** * Underlined text. */ Underline(4), /** * Text with a line through the middle. */ Strikeout(8); /** * значение. */ private final int value; /** * Конструктор. * @param initialValue - значение */ FontStyle(int initialValue) { value = initialValue; } /** * Возвращает значение. * @return int - Возвращает значение. */ public int value() { return value; } }
15.107143
55
0.514184
dcd6128e29845e44abd0e5c35c1a8490630a3e33
2,910
package com.madgaze.watchsdk_java; import android.os.Bundle; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import com.madgaze.watchsdk.MobileActivity; import com.madgaze.watchsdk.WatchActivity; import com.madgaze.watchsdk.WatchException; import com.madgaze.watchsdk.WatchGesture; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends MobileActivity { private String TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); } @Override protected void onStart() { super.onStart(); Log.d(TAG, "onStart before isWatchGestureDetecting: "+isWatchGestureDetecting()); if (!isWatchGestureDetecting()) { startWatchGestureDetection(); } Log.d(TAG, "onStart after isWatchGestureDetecting: "+isWatchGestureDetecting()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onWatchGestureReceived(WatchGesture gesture, int times) { Log.d(TAG, "onWatchGestureReceived: "+gesture.name()+" x"+times); } @Override public void onWatchGestureError(WatchException error) { Log.d(TAG, "onWatchGestureError: "+error.getMessage()); } @Override public void onWatchDetectionOn() { Log.d(TAG, "onWatchDetectionOn: "); } @Override public void onWatchDetectionOff() { Log.d(TAG, "onWatchDetectionOff: "); } }
31.630435
89
0.678351
6fcdba52db2250bc00f800a5b599d862cbac5e1f
82
module m { uses p.I; provides p.I with p.A; provides p.I with p.B; }
11.714286
26
0.54878
13ca958a1cf1ffc9102e7787d6bd969f7f98b62f
1,472
package mcjty.theoneprobe.api; import com.mojang.blaze3d.vertex.PoseStack; /** * Using this interface (that you can get from ITheOneProbe) you can * do custom overlay rendering from within your mod. */ public interface IOverlayRenderer { /** * Return the default overlay style as configured in the The One Probe config. * You can make modifications to this and use it for your own overlays. The * default style will not be modified. Note that if you call this client side * then this will also contain the settings as the player modified it locally. * If you call this server side then you will get the default settings from the * global config. */ IOverlayStyle createDefaultStyle(); /** * Create an empty default IProbeInfo (which actually represents the * default vertical element that is always used to start with). You can then * modify this as you wish and give it to render(). */ IProbeInfo createProbeInfo(); /** * Render an overlay with the given style and probe info. * This has to be called client side and you have to call it every * frame for as long as you want this overlay to be visible. * * Typically you might want to call this in a RenderGameOverlayEvent. * * Note that calling this does not prevent the normal overlay from * rendering. */ void render(IOverlayStyle style, IProbeInfo probeInfo, PoseStack matrixStack); }
36.8
83
0.703125
44858b7989a64a478807f98291a4d0852ec90606
2,719
package com.plopcas.twiliohackathon.cpd.service; import com.plopcas.twiliohackathon.cpd.model.Alert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.util.*; import static java.util.Collections.reverseOrder; /** * Service to check the data for each country every day and trigger the alerts if needed. */ @Service public class DetectorService { private static Logger log = LoggerFactory.getLogger(DetectorService.class); private final DataService dataService; private final SmsService smsService; private final AlertService alertService; public DetectorService(DataService dataService, SmsService smsService, AlertService alertService) { this.dataService = dataService; this.smsService = smsService; this.alertService = alertService; } /** * Detect peak and send alerts every 12 hours. Naively, it deletes the alert afterwards. */ @Scheduled(fixedRate = 12 * 60 * 60 * 1000) public void scheduleFixedRateTask() { log.info("Running scheduled job to detect peaks"); List<String> countries = detectPeak(); for (String country : countries) { log.info("Peak detected for " + country + " - Sending alerts!"); // fetch all phone numbers that signed up for the country List<Alert> alertsByCountry = alertService.findByCountry(country); // send alert to each of those phone numbers for (Alert alert : alertsByCountry) { smsService.sendAlertSms(alert.getPhone(), country); alertService.delete(alert); log.info("Alert sent and deleted"); } } } /** * Attempts to detect the peak for each country. * * @return list of countries that have reached the peak */ private List<String> detectPeak() { List<String> countries = new ArrayList<>(); dataService.getCountries().stream().forEach(country -> { Map<String, Integer> activeCases = dataService.getActiveCases(country); Set<String> keysSet = activeCases.keySet(); List<String> keysList = new ArrayList<>(keysSet); Collections.sort(keysList, reverseOrder()); Integer today = activeCases.get(keysList.get(0)); Integer yesterday = activeCases.get(keysList.get(1)); Integer dayBeforeYesterday = activeCases.get(keysList.get(2)); if (today < yesterday && today < dayBeforeYesterday) { countries.add(country); } }); return countries; } }
36.253333
103
0.656124
66a31986b6e5af7f8c8934a6901e74ad9a4bb05b
749
// 215. Kth Largest Element in an Array (Medium) // https://leetcode.com/problems/kth-largest-element-in-an-array/ /* Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 Example 2: Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4 Note: You may assume k is always valid, 1 ≤ k ≤ array's length. */ class Solution { public int findKthLargest(int[] nums, int k) { PriorityQueue<Integer> minHeap = new PriorityQueue<>(); for(int i:nums) { minHeap.add(i); if(minHeap.size()>k) minHeap.poll(); } return minHeap.peek(); } }
24.966667
141
0.615487
b766aeac107b12cde1c98f7eb4f9174ed26f0c68
7,914
/* * 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 gui; import reader.*; /** * * @author hasalp */ public class Client extends javax.swing.JFrame { Reader temperature, humidity; public Client() { initComponents(); ReaderBuilder builder = new ReaderBuilder(); temperature = builder.getReader("temperature"); humidity = builder.getReader("humidity"); temperature.start(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup = new javax.swing.ButtonGroup(); jPanel1 = new javax.swing.JPanel(); subscribeTopicsTitle = new javax.swing.JLabel(); resultField = new javax.swing.JTextField(); temperatureButton = new javax.swing.JRadioButton(); humidityButton = new javax.swing.JRadioButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(254, 254, 254)); subscribeTopicsTitle.setText("Subscribe Topic:"); resultField.setFont(new java.awt.Font("Noto Sans", 0, 48)); // NOI18N resultField.setHorizontalAlignment(javax.swing.JTextField.CENTER); resultField.setText("Null"); buttonGroup.add(temperatureButton); temperatureButton.setSelected(true); temperatureButton.setText("Temperature"); temperatureButton.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { temperatureButtonItemStateChanged(evt); } }); buttonGroup.add(humidityButton); humidityButton.setText("Humidity"); humidityButton.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { humidityButtonItemStateChanged(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(resultField) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(subscribeTopicsTitle) .addGap(18, 18, 18) .addComponent(temperatureButton) .addGap(18, 18, 18) .addComponent(humidityButton) .addGap(0, 85, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(subscribeTopicsTitle) .addComponent(temperatureButton) .addComponent(humidityButton)) .addGap(18, 18, 18) .addComponent(resultField, javax.swing.GroupLayout.DEFAULT_SIZE, 219, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void temperatureButtonItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_temperatureButtonItemStateChanged if(temperatureButton.isSelected()){ System.out.println("Temp ON Triggered"); temperature.start(); }else{ System.out.println("Temp OFF Triggered"); temperature.stop(); } }//GEN-LAST:event_temperatureButtonItemStateChanged private void humidityButtonItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_humidityButtonItemStateChanged if(humidityButton.isSelected()){ System.out.println("Hum ON Triggered"); humidity.start(); }else{ System.out.println("Hum OFF Triggered"); humidity.stop(); } }//GEN-LAST:event_humidityButtonItemStateChanged /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Client().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroup; private javax.swing.JRadioButton humidityButton; private javax.swing.JPanel jPanel1; public static javax.swing.JTextField resultField; private javax.swing.JLabel subscribeTopicsTitle; private javax.swing.JRadioButton temperatureButton; // End of variables declaration//GEN-END:variables }
43.483516
133
0.643038
feb2fcd792920ca3609b035981c8cc633340c313
851
package io.automatiko.engine.quarkus; import java.util.Optional; import io.automatiko.engine.api.config.WebsocketEventsConfig; import io.quarkus.arc.config.ConfigProperties; import io.quarkus.runtime.annotations.ConfigGroup; import io.quarkus.runtime.annotations.ConfigItem; @ConfigGroup @ConfigProperties(prefix = "quarkus.automatiko.events.websocket") public class WebsocketEventsBuildTimeConfig extends WebsocketEventsConfig { /** * Indicates if the instance events are enabled */ @ConfigItem public Optional<Boolean> instance; /** * Indicates if the user task events are enabled */ @ConfigItem public Optional<Boolean> tasks; @Override public Optional<Boolean> instance() { return instance; } @Override public Optional<Boolean> tasks() { return tasks; } }
23.638889
75
0.723854
071210429f01a9d3e45a92c1168db1b27e96072e
196
package ro.ase.acs.state; public class DeliveringProductState implements VendingMachineState { @Override public void doAction() { System.out.println("Please pick-up your product :)"); } }
17.818182
68
0.75
4c7a0a97a138238dc59a6b9ebde28ca77c7afa16
474
package com.abms.af.projeversion02.Models; public class Profilfotosilmesonuc{ private String profilfotosilmesonuc; public void setProfilfotosilmesonuc(String profilfotosilmesonuc){ this.profilfotosilmesonuc = profilfotosilmesonuc; } public String getProfilfotosilmesonuc(){ return profilfotosilmesonuc; } @Override public String toString(){ return "Profilfotosilmesonuc{" + "profilfotosilmesonuc = '" + profilfotosilmesonuc + '\'' + "}"; } }
21.545455
66
0.755274
a15b78f2fde669d3292d6bd449790559f5bba901
11,527
// // Decompiled by Procyon v0.5.36 // package org.codehaus.groovy.runtime.callsite; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.codehaus.groovy.reflection.ParameterTypes; import org.codehaus.groovy.reflection.CachedMethod; import groovy.lang.GroovyObject; import groovy.lang.GroovyRuntimeException; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import org.codehaus.groovy.runtime.MetaClassHelper; import groovy.lang.MetaClass; import groovy.lang.MetaMethod; import groovy.lang.MetaClassImpl; public class PogoMetaMethodSite extends MetaMethodSite { public PogoMetaMethodSite(final CallSite site, final MetaClassImpl metaClass, final MetaMethod metaMethod, final Class[] params) { super(site, metaClass, metaMethod, params); } public Object invoke(final Object receiver, final Object[] args) throws Throwable { MetaClassHelper.unwrap(args); try { return this.metaMethod.doMethodInvoke(receiver, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } @Override public Object callCurrent(final GroovyObject receiver, final Object[] args) throws Throwable { if (this.checkCall(receiver, args)) { try { return this.invoke(receiver, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } return CallSiteArray.defaultCallCurrent(this, receiver, args); } @Override public Object call(final Object receiver, final Object[] args) throws Throwable { if (this.checkCall(receiver, args)) { try { return this.invoke(receiver, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } return CallSiteArray.defaultCall(this, receiver, args); } protected boolean checkCall(final Object receiver, final Object[] args) { try { return this.usage.get() == 0 && ((GroovyObject)receiver).getMetaClass() == this.metaClass && MetaClassHelper.sameClasses(this.params, args); } catch (NullPointerException e) { if (receiver == null) { return false; } throw e; } catch (ClassCastException e2) { if (!(receiver instanceof GroovyObject)) { return false; } throw e2; } } protected boolean checkCall(final Object receiver) { try { return this.usage.get() == 0 && ((GroovyObject)receiver).getMetaClass() == this.metaClass && MetaClassHelper.sameClasses(this.params); } catch (NullPointerException e) { if (receiver == null) { return false; } throw e; } catch (ClassCastException e2) { if (!(receiver instanceof GroovyObject)) { return false; } throw e2; } } protected boolean checkCall(final Object receiver, final Object arg1) { try { return this.usage.get() == 0 && ((GroovyObject)receiver).getMetaClass() == this.metaClass && MetaClassHelper.sameClasses(this.params, arg1); } catch (NullPointerException e) { if (receiver == null) { return false; } throw e; } catch (ClassCastException e2) { if (!(receiver instanceof GroovyObject)) { return false; } throw e2; } } protected boolean checkCall(final Object receiver, final Object arg1, final Object arg2) { try { return this.usage.get() == 0 && ((GroovyObject)receiver).getMetaClass() == this.metaClass && MetaClassHelper.sameClasses(this.params, arg1, arg2); } catch (NullPointerException e) { if (receiver == null) { return false; } throw e; } catch (ClassCastException e2) { if (!(receiver instanceof GroovyObject)) { return false; } throw e2; } } protected boolean checkCall(final Object receiver, final Object arg1, final Object arg2, final Object arg3) { try { return this.usage.get() == 0 && ((GroovyObject)receiver).getMetaClass() == this.metaClass && MetaClassHelper.sameClasses(this.params, arg1, arg2, arg3); } catch (NullPointerException e) { if (receiver == null) { return false; } throw e; } catch (ClassCastException e2) { if (!(receiver instanceof GroovyObject)) { return false; } throw e2; } } protected boolean checkCall(final Object receiver, final Object arg1, final Object arg2, final Object arg3, final Object arg4) { try { return this.usage.get() == 0 && ((GroovyObject)receiver).getMetaClass() == this.metaClass && MetaClassHelper.sameClasses(this.params, arg1, arg2, arg3, arg4); } catch (NullPointerException e) { if (receiver == null) { return false; } throw e; } catch (ClassCastException e2) { if (!(receiver instanceof GroovyObject)) { return false; } throw e2; } } public static CallSite createPogoMetaMethodSite(final CallSite site, final MetaClassImpl metaClass, final MetaMethod metaMethod, final Class[] params, final Object[] args) { if (metaMethod.getClass() == CachedMethod.class) { return createCachedMethodSite(site, metaClass, (CachedMethod)metaMethod, params, args); } return createNonAwareCallSite(site, metaClass, metaMethod, params, args); } private static CallSite createNonAwareCallSite(final CallSite site, final MetaClassImpl metaClass, final MetaMethod metaMethod, final Class[] params, final Object[] args) { if (metaMethod.correctArguments(args) != args || !AbstractCallSite.noWrappers(args)) { return new PogoMetaMethodSite(site, metaClass, metaMethod, params); } if (AbstractCallSite.noCoerce(metaMethod, args)) { return new PogoMetaMethodSiteNoUnwrap(site, metaClass, metaMethod, params); } return new PogoMetaMethodSiteNoUnwrapNoCoerce(site, metaClass, metaMethod, params); } public static CallSite createCachedMethodSite(final CallSite site, final MetaClassImpl metaClass, final CachedMethod metaMethod, final Class[] params, final Object[] args) { if (metaMethod.correctArguments(args) != args || !AbstractCallSite.noWrappers(args)) { return new PogoCachedMethodSite(site, metaClass, metaMethod, params); } if (AbstractCallSite.noCoerce(metaMethod, args)) { return new PogoCachedMethodSiteNoUnwrap(site, metaClass, metaMethod, params); } return metaMethod.createPogoMetaMethodSite(site, metaClass, params); } public static class PogoCachedMethodSite extends PogoMetaMethodSite { final Method reflect; public PogoCachedMethodSite(final CallSite site, final MetaClassImpl metaClass, final CachedMethod metaMethod, final Class[] params) { super(site, metaClass, metaMethod, params); this.reflect = metaMethod.setAccessible(); } @Override public Object invoke(final Object receiver, Object[] args) throws Throwable { MetaClassHelper.unwrap(args); args = this.metaMethod.coerceArgumentsToClasses(args); try { return this.reflect.invoke(receiver, args); } catch (InvocationTargetException e) { final Throwable cause = e.getCause(); if (cause instanceof GroovyRuntimeException) { throw ScriptBytecodeAdapter.unwrap((GroovyRuntimeException)cause); } throw cause; } } } public static class PogoCachedMethodSiteNoUnwrap extends PogoCachedMethodSite { public PogoCachedMethodSiteNoUnwrap(final CallSite site, final MetaClassImpl metaClass, final CachedMethod metaMethod, final Class[] params) { super(site, metaClass, metaMethod, params); } @Override public final Object invoke(final Object receiver, Object[] args) throws Throwable { args = this.metaMethod.coerceArgumentsToClasses(args); try { return this.reflect.invoke(receiver, args); } catch (InvocationTargetException e) { final Throwable cause = e.getCause(); if (cause instanceof GroovyRuntimeException) { throw ScriptBytecodeAdapter.unwrap((GroovyRuntimeException)cause); } throw cause; } } } public static class PogoCachedMethodSiteNoUnwrapNoCoerce extends PogoCachedMethodSite { public PogoCachedMethodSiteNoUnwrapNoCoerce(final CallSite site, final MetaClassImpl metaClass, final CachedMethod metaMethod, final Class[] params) { super(site, metaClass, metaMethod, params); } @Override public final Object invoke(final Object receiver, final Object[] args) throws Throwable { try { return this.reflect.invoke(receiver, args); } catch (InvocationTargetException e) { final Throwable cause = e.getCause(); if (cause instanceof GroovyRuntimeException) { throw ScriptBytecodeAdapter.unwrap((GroovyRuntimeException)cause); } throw cause; } } } public static class PogoMetaMethodSiteNoUnwrap extends PogoMetaMethodSite { public PogoMetaMethodSiteNoUnwrap(final CallSite site, final MetaClassImpl metaClass, final MetaMethod metaMethod, final Class[] params) { super(site, metaClass, metaMethod, params); } @Override public final Object invoke(final Object receiver, final Object[] args) throws Throwable { try { return this.metaMethod.doMethodInvoke(receiver, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } public static class PogoMetaMethodSiteNoUnwrapNoCoerce extends PogoMetaMethodSite { public PogoMetaMethodSiteNoUnwrapNoCoerce(final CallSite site, final MetaClassImpl metaClass, final MetaMethod metaMethod, final Class[] params) { super(site, metaClass, metaMethod, params); } @Override public final Object invoke(final Object receiver, final Object[] args) throws Throwable { try { return this.metaMethod.invoke(receiver, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } }
38.551839
177
0.604407
aff172616c8afde8eca0481a96a5bed4500c3453
11,750
/* * 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.sis.referencing.operation.projection; import java.util.EnumMap; import java.io.Serializable; import org.opengis.util.FactoryException; import org.opengis.parameter.ParameterDescriptor; import org.opengis.parameter.ParameterValueGroup; import org.opengis.referencing.operation.OperationMethod; import org.opengis.referencing.operation.TransformException; import org.opengis.referencing.operation.Matrix; import org.opengis.referencing.operation.MathTransform2D; import org.opengis.referencing.operation.MathTransformFactory; import org.opengis.referencing.operation.NoninvertibleTransformException; import org.apache.sis.referencing.operation.transform.AbstractMathTransform; import org.apache.sis.referencing.operation.transform.AbstractMathTransform2D; import org.apache.sis.referencing.operation.transform.ContextualParameters; import org.apache.sis.referencing.operation.matrix.MatrixSIS; import org.apache.sis.parameter.Parameters; import org.apache.sis.measure.Longitude; import org.apache.sis.util.ComparisonMode; import org.apache.sis.internal.util.Numerics; import static java.lang.Math.floor; import static org.apache.sis.internal.referencing.provider.TransverseMercator.*; import static org.apache.sis.internal.referencing.provider.ZonedTransverseMercator.*; /** * <cite>Transverse Mercator Zoned Grid System</cite> projection (EPSG codes 9824). * This projection is valid for all the world in a given hemisphere, except the poles. * The Earth is divided into zones, usually 6° width. The zone number is determined * automatically from the longitude and is prefixed to the Easting value. * * <p>This map projection is not suitable for geometric calculations like distances and angles, * since there is discontinuities (gaps) between zones. Actually this operation is not handled * as a map projection by Apache SIS, as can been seen from the different class hierarchy.</p> * * <div class="note"><b>Note:</b> * current implementation can only be backed by the Transverse Mercator projection, * but future versions could apply to some other projections if needed.</div> * * <p>Examples of CRS using this projection are <cite>WGS 84 / UTM grid system</cite> * EPSG:32600 (northern hemisphere) and EPSG:32700 (southern hemisphere).</p> * * @author Martin Desruisseaux (Geomatys) * @version 0.8 * @since 0.8 * @module */ public class ZonedGridSystem extends AbstractMathTransform2D implements Serializable { /** * For cross-version compatibility. */ private static final long serialVersionUID = -7219325241026170925L; /** * The 360° range of longitude values. */ private static final double RANGE = Longitude.MAX_VALUE - Longitude.MIN_VALUE; /** * The zone multiplication factor for encoding the zone in the easting. * This scale factor assumes that the projection results are in metres. */ private static final double ZONE_SCALE = 1E6; /** * Westernmost longitude of the first zone. */ final double initialLongitude; /** * Width of each Transverse Mercator zone, in the same units than longitude values. * This is usually 6°. */ final double zoneWidth; /** * The projection that performs the actual work before we add the zone number. */ final AbstractMathTransform projection; /** * The inverse of this map projection. */ private final MathTransform2D inverse; /** * Creates a Zoned Grid System from the given parameters. * The {@code method} argument can be the description of one of the following: * * <ul> * <li><cite>"Transverse Mercator Zoned Grid System"</cite>.</li> * </ul> * * Contrarily to other map projections in this package, there is no {@code createMapProjection(MathTransformFactory)} * method in this class. Instead, the factory must be specified at this {@code ZonedGridSystem} construction time. * * @param method description of the projection parameters. * @param parameters the parameter values of the projection to create. * @param factory the factory to use for creating the transform. * @throws FactoryException if an error occurred while creating a transform. */ public ZonedGridSystem(final OperationMethod method, final Parameters parameters, final MathTransformFactory factory) throws FactoryException { final EnumMap<NormalizedProjection.ParameterRole, ParameterDescriptor<Double>> roles = new EnumMap<>(NormalizedProjection.ParameterRole.class); roles.put(NormalizedProjection.ParameterRole.SCALE_FACTOR, SCALE_FACTOR); roles.put(NormalizedProjection.ParameterRole.FALSE_EASTING, FALSE_EASTING); roles.put(NormalizedProjection.ParameterRole.FALSE_NORTHING, FALSE_NORTHING); final Initializer initializer = new Initializer(method, parameters, roles, (byte) 0); initialLongitude = initializer.getAndStore(INITIAL_LONGITUDE); zoneWidth = initializer.getAndStore(ZONE_WIDTH); final MatrixSIS normalize = initializer.context.getMatrix(ContextualParameters.MatrixRole.NORMALIZATION); normalize.convertBefore(0, null, zoneWidth / -2); projection = (AbstractMathTransform) new TransverseMercator(initializer).createMapProjection(factory); inverse = new Inverse(this); } /** * Returns the parameter values of this zoned grid system projection. * * @return the internal parameter values for this zoned grid system projection. */ @Override public ParameterValueGroup getParameterValues() { return projection.getParameterValues(); } /** * Converts the specified (λ,φ) coordinate and stores the result in {@code dstPts}. * In addition, opportunistically computes the projection derivative if {@code derivate} is {@code true}. * Note that the derivative does not contain zone prefix. * * @return the matrix of the projection derivative at the given source position, * or {@code null} if the {@code derivate} argument is {@code false}. * @throws TransformException if the coordinate can not be converted. */ @Override public Matrix transform(final double[] srcPts, final int srcOff, final double[] dstPts, final int dstOff, final boolean derivate) throws TransformException { double λ = srcPts[srcOff] - initialLongitude; double φ = srcPts[srcOff+1]; λ -= RANGE * floor(λ / RANGE); final double zone = floor(λ / zoneWidth); λ -= (zone * zoneWidth); dstPts[dstOff ] = λ; dstPts[dstOff+1] = φ; final Matrix derivative = projection.transform(dstPts, dstOff, dstPts, dstOff, derivate); dstPts[dstOff] += (zone + 1) * ZONE_SCALE; return derivative; } /** * Returns the inverse of this map projection. * * @return the inverse of this map projection. */ @Override public MathTransform2D inverse() { return inverse; } /** * Inverse of a zoned grid system. * * @author Martin Desruisseaux (Geomatys) * @version 1.0 * @since 0.8 * @module */ private static final class Inverse extends AbstractMathTransform2D.Inverse implements Serializable { /** * For cross-version compatibility. */ private static final long serialVersionUID = -4417726238412154175L; /** * The enclosing transform. */ private final ZonedGridSystem forward; /** * The projection that performs the actual work after we removed the zone number. */ private final AbstractMathTransform inverseProjection; /** * Default constructor. */ Inverse(final ZonedGridSystem forward) throws FactoryException { this.forward = forward; try { inverseProjection = (AbstractMathTransform) forward.projection.inverse(); } catch (NoninvertibleTransformException e) { throw new FactoryException(e); // Should not happen. } } /** * Returns the inverse of this math transform. */ @Override public MathTransform2D inverse() { return forward; } /** * Inverse transforms the specified {@code srcPts} and stores the result in {@code dstPts}. * If the derivative has been requested, then this method will delegate the derivative * calculation to the enclosing class and inverts the resulting matrix. */ @Override public Matrix transform(final double[] srcPts, final int srcOff, final double[] dstPts, final int dstOff, final boolean derivate) throws TransformException { double x = srcPts[srcOff ]; double y = srcPts[srcOff+1]; double zone = floor(x / ZONE_SCALE) - 1; x -= (zone + 1) * ZONE_SCALE; dstPts[dstOff ] = x; dstPts[dstOff+1] = y; final Matrix derivative = inverseProjection.transform(dstPts, dstOff, dstPts, dstOff, derivate); dstPts[dstOff] += zone * forward.zoneWidth + forward.initialLongitude; return derivative; } } /** * Computes a hash code value for this {@code ZonedGridSystem}. * * @return the hash code value. */ @Override protected int computeHashCode() { final long c = Double.doubleToLongBits(initialLongitude) + 31*Double.doubleToLongBits(zoneWidth); return (super.computeHashCode() ^ Long.hashCode(c)) + 37 * projection.hashCode(); } /** * Compares the given object with this transform for equivalence. * If this method returns {@code true}, then for any given identical source position, * the two compared map projections shall compute the same target position. * * @param object the object to compare with this map projection for equivalence. * @param mode the strictness level of the comparison. Default to {@link ComparisonMode#STRICT}. * @return {@code true} if the given object is equivalent to this map projection. */ @Override public boolean equals(final Object object, final ComparisonMode mode) { if (object == this) { return true; } if (super.equals(object, mode)) { final ZonedGridSystem that = (ZonedGridSystem) object; return Numerics.equals(initialLongitude, that.initialLongitude) && Numerics.equals(zoneWidth, that.zoneWidth) && projection.equals(that.projection, mode); } return false; } }
41.373239
121
0.679319
727dcab4a0b4f5a54fd19794331aab1cfd411e27
479
package com.jdksource.java8; import com.google.common.collect.Lists; import java.util.ArrayList; /** * @author bo6.zhang * @date 2021/6/28 */ public class StreamForeachReturnTest { public static void main(String[] args) { ArrayList<String> list = Lists.newArrayList("1", "2", "3", "4", "5"); list.forEach(s -> { if ("3".equalsIgnoreCase(s)) { return; } System.out.println(s); }); } }
17.740741
77
0.553236
9e3fa1494c22af00757117848f61dc26dcce7e38
11,704
package valandur.webapi.command; import org.slf4j.Logger; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandManager; import org.spongepowered.api.command.CommandMapping; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.args.CommandElement; import org.spongepowered.api.command.args.GenericArguments; import org.spongepowered.api.command.spec.CommandSpec; import org.spongepowered.api.text.Text; import valandur.webapi.WebAPI; import valandur.webapi.block.BlockService; import valandur.webapi.command.auth.CmdAuthListAdd; import valandur.webapi.command.auth.CmdAuthListDisable; import valandur.webapi.command.auth.CmdAuthListEnable; import valandur.webapi.command.auth.CmdAuthListRemove; import valandur.webapi.command.block.CmdBlockUpdatesList; import valandur.webapi.command.block.CmdBlockUpdatesPause; import valandur.webapi.command.block.CmdBlockUpdatesStop; import valandur.webapi.command.element.CmdIpElement; import valandur.webapi.command.hook.CmdNotifyHook; import valandur.webapi.command.user.CmdUserAdd; import valandur.webapi.command.user.CmdUserChangePassword; import valandur.webapi.command.user.CmdUserList; import valandur.webapi.command.user.CmdUserRemove; import valandur.webapi.hook.CommandWebHook; import valandur.webapi.hook.WebHookParam; import java.util.*; import java.util.stream.Collectors; public class CommandRegistry { private static List<CommandMapping> mappings = new ArrayList<>(); public static void init() { CommandManager manager = Sponge.getCommandManager(); Logger logger = WebAPI.getLogger(); // Register commands logger.info("Registering commands..."); // Remove old commands for (CommandMapping mapping : mappings) { manager.removeMapping(mapping); } mappings.clear(); // Whitelist CommandSpec specWhitelistAdd = CommandSpec.builder() .description(Text.of("Add an IP to the whitelist")) .permission("webapi.whitelist.add") .arguments(new CmdIpElement(Text.of("ip"))) .executor(new CmdAuthListAdd(true)) .build(); CommandSpec specWhitelistRemove = CommandSpec.builder() .description(Text.of("Remove an IP from the whitelist")) .permission("webapi.whitelist.remove") .arguments(new CmdIpElement(Text.of("ip"))) .executor(new CmdAuthListRemove(true)) .build(); CommandSpec specWhitelistEnable = CommandSpec.builder() .description(Text.of("Enable the whitelist")) .permission("webapi.whitelist.enable") .executor(new CmdAuthListEnable(true)) .build(); CommandSpec specWhitelistDisable = CommandSpec.builder() .description(Text.of("Disable the whitelist")) .permission("webapi.whitelist.disable") .executor(new CmdAuthListDisable(true)) .build(); CommandSpec specWhitelist = CommandSpec.builder() .description(Text.of("Manage the whitelist")) .permission("webapi.whitelist") .child(specWhitelistAdd, "add") .child(specWhitelistRemove, "remove") .child(specWhitelistEnable, "enable") .child(specWhitelistDisable, "disable") .build(); // Blacklist CommandSpec specBlacklistAdd = CommandSpec.builder() .description(Text.of("Add an IP to the blacklist")) .permission("webapi.blacklist.add") .arguments(GenericArguments.string(Text.of("ip"))) .executor(new CmdAuthListAdd(false)) .build(); CommandSpec specBlaclistRemove = CommandSpec.builder() .description(Text.of("Remove an IP from the blacklist")) .permission("webapi.blacklist.remove") .arguments(GenericArguments.string(Text.of("ip"))) .executor(new CmdAuthListRemove(false)) .build(); CommandSpec specBlacklistEnable = CommandSpec.builder() .description(Text.of("Enable the blacklist")) .permission("webapi.blacklist.enable") .executor(new CmdAuthListEnable(false)) .build(); CommandSpec specBlacklistDisable = CommandSpec.builder() .description(Text.of("Disable the blacklist")) .permission("webapi.blacklist.disable") .executor(new CmdAuthListDisable(false)) .build(); CommandSpec specBlacklist = CommandSpec.builder() .description(Text.of("Manage the blacklist")) .permission("webapi.blacklist") .child(specBlacklistAdd, "add") .child(specBlaclistRemove, "remove") .child(specBlacklistEnable, "enable") .child(specBlacklistDisable, "disable") .build(); // Block operations final BlockService blockService = WebAPI.getBlockService(); CommandSpec specBlockOpsList = CommandSpec.builder() .description(Text.of("List all running block operations")) .permission("webapi.op.list") .executor(new CmdBlockUpdatesList()) .build(); CommandSpec specBlockOpsPause = CommandSpec.builder() .description(Text.of("Pause/Resume running block operations")) .permission("webapi.op.pause") .arguments(GenericArguments.choices(Text.of("uuid"), () -> blockService.getBlockOperations().stream().map(u -> u.getUUID().toString()).collect(Collectors.toList()), uuid -> blockService.getBlockOperation(UUID.fromString(uuid)).orElse(null))) .executor(new CmdBlockUpdatesPause()) .build(); CommandSpec specBlockOpsStop = CommandSpec.builder() .description(Text.of("Stop a running block operation")) .permission("webapi.op.stop") .arguments(GenericArguments.choices(Text.of("uuid"), () -> blockService.getBlockOperations().stream().map(u -> u.getUUID().toString()).collect(Collectors.toList()), uuid -> blockService.getBlockOperation(UUID.fromString(uuid)).orElse(null))) .executor(new CmdBlockUpdatesStop()) .build(); CommandSpec specBlockOps = CommandSpec.builder() .description(Text.of("Manage running block operations")) .permission("webapi.op") .child(specBlockOpsList, "list") .child(specBlockOpsPause, "pause") .child(specBlockOpsStop, "stop", "delete", "remove") .build(); // Users CommandSpec specUserList = CommandSpec.builder() .description(Text.of("List all the users which have access to the admin panel")) .permission("webapi.user.list") .executor(new CmdUserList()) .build(); CommandSpec specUserAdd = CommandSpec.builder() .description(Text.of("Add a new user that can access the admin panel")) .permission("webapi.user.add") .arguments( GenericArguments.onlyOne(GenericArguments.string(Text.of("username"))), GenericArguments.optional(GenericArguments.string(Text.of("password"))) ) .executor(new CmdUserAdd()) .build(); CommandSpec specUserChangePw = CommandSpec.builder() .description(Text.of("Change the password of an existing user")) .permission("webapi.user.changepw") .arguments( GenericArguments.onlyOne(GenericArguments.string(Text.of("username"))), GenericArguments.onlyOne(GenericArguments.string(Text.of("password"))) ) .executor(new CmdUserChangePassword()) .build(); CommandSpec specUserRemove = CommandSpec.builder() .description(Text.of("Remove an existing user from the admin panel")) .permission("webapi.user.remove") .arguments( GenericArguments.onlyOne(GenericArguments.string(Text.of("username"))) ) .executor(new CmdUserRemove()) .build(); CommandSpec specUsers = CommandSpec.builder() .description(Text.of("Manage the users of the admin panel")) .permission("webapi.user") .child(specUserList, "list") .child(specUserAdd, "add", "new") .child(specUserRemove, "remove", "delete", "del") .child(specUserChangePw, "pw", "changepw", "password") .build(); // Notify commands Map<List<String>, CommandSpec> hookSpecs = new HashMap<>(); Map<List<String>, CommandSpec> hookAliases = new HashMap<>(); for (Map.Entry<String, CommandWebHook> entry : WebAPI.getWebHookService().getCommandHooks().entrySet()) { List<CommandElement> args = new ArrayList<>(); String name = entry.getKey(); CommandWebHook hook = entry.getValue(); if (!hook.isEnabled()) continue; if (hook.getParams() != null) { for (WebHookParam param : hook.getParams()) { Optional<CommandElement> e = param.getCommandElement(); e.ifPresent(args::add); } } CommandSpec hookCmd = CommandSpec.builder() .description(Text.of("Notify the " + name + " hook")) .permission("webapi.notify." + name) .arguments(args.toArray(new CommandElement[args.size()])) .executor(new CmdNotifyHook(hook)) .build(); if (hook.getAliases() != null && hook.getAliases().size() > 0) hookAliases.put(hook.getAliases(), hookCmd); hookSpecs.put(Collections.singletonList(name), hookCmd); } // Notify parent CommandSpec specNotifyHook = CommandSpec.builder() .description(Text.of("Notify a hook")) .permission("webapi.notify") .children(hookSpecs) .executor((src, args) -> { src.sendMessage(Text.of("Edit the webapi/hooks.conf config to create web hooks")); return CommandResult.success(); }) .build(); // Register main command CommandSpec spec = CommandSpec.builder() .description(Text.of("Manage Web-API settings")) .permission("webapi") .child(specWhitelist, "whitelist") .child(specBlacklist, "blacklist") .child(specNotifyHook, "notify") .child(specBlockOps, "ops", "op", "blockops") .child(specUsers, "users", "user") .build(); manager.register(WebAPI.getInstance(), spec, "webapi").map(m -> mappings.add(m)); // Register aliases for notify commands for (Map.Entry<List<String>, CommandSpec> entry : hookAliases.entrySet()) { manager.register(WebAPI.getInstance(), entry.getValue(), entry.getKey()).map(m -> mappings.add(m)); } } }
48.363636
135
0.59407
176cbbb136de975dc0ac4d9a38b4dfff507fa8f7
554
package com.example.tests; import org.testng.annotations.Test; public class ContactModificationTests extends TestBase{ @Test public void modifySomeContact() { app.getNavigationHelper().openMainPage(); app.getContactHelper().editContact(1); ContactData contact = new ContactData(); contact.address = "London"; contact.email1 = "new email"; contact.days = "-"; contact.months = "-"; app.getContactHelper().fillContactForm(contact); app.getContactHelper().submitContactModification(); app.getContactHelper().returnToMainPage(); } }
27.7
55
0.749097
30bdd743078dd730c40b23965c53b98148f5cd98
1,595
/* * Copyright 2018-2018 adorsys GmbH & Co KG * * 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 de.adorsys.smartanalytics.api; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.Data; import java.util.Map; @Data @JsonPropertyOrder({"order", "ruleId", "creditorId", "similarityMatchType", "expression", "receiver", "stop", "incoming", "mainCategory", "subCategory", "specification", "custom", "email", "homepage", "hotline", "logo"}) public class Rule { public enum SIMILARITY_MATCH_TYPE { IBAN, REFERENCE_NAME, PURPOSE, CUSTOM } private int order; private String ruleId; private String mainCategory; private String subCategory; private String specification; private SIMILARITY_MATCH_TYPE similarityMatchType; private String creditorId; private String expression; private String receiver; private String logo; private String hotline; private String homepage; private String email; private Map<String, String> custom; private boolean stop; private boolean incoming; }
30.09434
220
0.731661
946632e1dbf366ecfd6d07216991966d9fe1f12d
3,142
package org.calvin.__Book.epi; import epi.test_framework.BinaryTreeUtils; import epi.test_framework.EpiTest; import epi.test_framework.GenericTest; import epi.test_framework.TimedExecutor; public class DescendantAndAncestorInBst { public static boolean pairIncludesAncestorAndDescendantOfM(BstNode<Integer> possibleAncOrDesc0, BstNode<Integer> possibleAncOrDesc1, BstNode<Integer> middle) { BstNode<Integer> search0 = possibleAncOrDesc0, search1 = possibleAncOrDesc1; // Perform interleaved searching from possibleAncOrDesc0 and // possibleAncOrDesc1 for middle. while (search0 != possibleAncOrDesc1 && search0 != middle && search1 != possibleAncOrDesc0 && search1 != middle && (search0 != null || search1 != null)) { if (search0 != null) { search0 = search0.data > middle.data ? search0.left : search0.right; } if (search1 != null) { search1 = search1.data > middle.data ? search1.left : search1.right; } } // If both searches were unsuccessful, or we got from possibleAncOrDesc0 // to possibleAncOrDesc1 without seeing middle, or from possibleAncOrDesc1 // to possibleAncOrDesc0 without seeing middle, middle cannot lie between // possibleAncOrDesc0 and possibleAncOrDesc1. if (search0 == possibleAncOrDesc1 || search1 == possibleAncOrDesc0 || (search0 != middle && search1 != middle)) { return false; } // If we get here, we already know one of possibleAncOrDesc0 or // possibleAncOrDesc1 has a path to middle. Check if middle has a path to // possibleAncOrDesc1 or to possibleAncOrDesc0. return search0 == middle ? searchTarget(middle, possibleAncOrDesc1) : searchTarget(middle, possibleAncOrDesc0); } private static boolean searchTarget(BstNode<Integer> from, BstNode<Integer> target) { while (from != null && from != target) { from = from.data > target.data ? from.left : from.right; } return from == target; } @EpiTest(testDataFile = "descendant_and_ancestor_in_bst.tsv") public static boolean pairIncludesAncestorAndDescendantOfMWrapper( TimedExecutor executor, BstNode<Integer> tree, int possibleAncOrDesc0, int possibleAncOrDesc1, int middle) throws Exception { final BstNode<Integer> candidate0 = BinaryTreeUtils.mustFindNode(tree, possibleAncOrDesc0); final BstNode<Integer> candidate1 = BinaryTreeUtils.mustFindNode(tree, possibleAncOrDesc1); final BstNode<Integer> middleNode = BinaryTreeUtils.mustFindNode(tree, middle); return executor.run(() -> pairIncludesAncestorAndDescendantOfM( candidate0, candidate1, middleNode)); } public static void main(String[] args) { System.exit( GenericTest .runFromAnnotations(args, "DescendantAndAncestorInBst.java", new Object() {}.getClass().getEnclosingClass()) .ordinal()); } }
40.282051
80
0.661044
393bb2c501b2fa9d68c2a5cc902c5c24e66a5fe7
19,573
/* * Copyright (c) 2015-2017 Erik Derr [derr@cs.uni-saarland.de] * * 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 de.infsec.tpl; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import de.infsec.tpl.config.LibScoutConfig; import de.infsec.tpl.modules.libapi.LibraryApiAnalysis; import de.infsec.tpl.modules.libmatch.LibraryIdentifier; import de.infsec.tpl.modules.libprofiler.LibraryProfiler; import de.infsec.tpl.modules.updatability.LibraryUpdatability; import de.infsec.tpl.profile.Profile; import de.infsec.tpl.stats.AppStats; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.util.StatusPrinter; import de.infsec.tpl.utils.Utils; import de.infsec.tpl.profile.LibProfile; public class TplCLI { private static final Logger logger = LoggerFactory.getLogger(de.infsec.tpl.TplCLI.class); private static Options options; public static class CliArgs { static final String ARG_OPMODE = "o"; static final String ARGL_OPMODE = "opmode"; static final String ARG_CONFIG = "c"; public static final String ARGL_CONFIG = "libscout-conf"; static final String ARG_ANDROID_LIB = "a"; static final String ARGL_ANDROID_LIB = "android-sdk"; static final String ARG_LOG_DIR = "d"; static final String ARGL_LOG_DIR = "log-dir"; static final String ARG_STATS_DIR = "s"; static final String ARGL_STATS_DIR = "stats-dir"; static final String ARG_JSON_DIR = "j"; static final String ARGL_JSON_DIR = "json-dir"; static final String ARG_PROFILES_DIR = "p"; static final String ARGL_PROFILES_DIR = "profiles-dir"; static final String ARG_MUTE = "m"; static final String ARGL_MUTE = "mute"; static final String ARG_NO_PARTIAL_MATCHING = "n"; static final String ARGL_NO_PARTIAL_MATCHING = "no-partial-matching"; static final String ARG_LIB_USAGE_ANALYSIS = "u"; static final String ARGL_LIB_USAGE_ANALYSIS = "lib-usage-analysis"; static final String ARG_LIB_DESCRIPTION = "x"; static final String ARGL_LIB_DESCRIPTION = "library-description"; static final String ARG_LIB_VERBOSE_PROFILES = "v"; static final String ARGL_LIB_VERBOSE_PROFILES = "verbose-profiles"; static final String ARG_LIB_DEPENDENCY_ANALYSIS = "da"; static final String ARGL_LIB_DEPENDENCY_ANALYSIS = "lib-dependency-analysis"; static final String ARG_LIB_API_COMPAT_DIR = "l"; static final String ARGL_LIB_API_COMPAT_DIR = "lib-api-compat-dir"; } private static ArrayList<File> inputFiles; private static File libraryDescription = null; public static void main(String[] args) { // parse command line arguments parseCL(args); List<LibProfile> profiles = null; LibraryUpdatability libUp = null; try { // parse LibScout.toml (args from CLI take precedence) LibScoutConfig.loadConfig(); // sanity check for required options that can be set from both CLI/config file checkRequiredOptions(); // initialize logback initLogging(); LibScoutConfig.whoAmI(); /* * one time data loading */ if (LibScoutConfig.opMatch() || LibScoutConfig.opUpdatability()) profiles = Profile.loadLibraryProfiles(LibScoutConfig.profilesDir); if (LibScoutConfig.opUpdatability()) libUp = new LibraryUpdatability(LibScoutConfig.libApiCompatDir); } catch (ParseException e) { logger.error("Error: " + e.getMessage()); usage(); } /* * choose mode of operation */ // process input files, either library files or apps for (File inputFile: inputFiles) { try { if (LibScoutConfig.opMatch()) { LibraryIdentifier.run(inputFile, profiles, LibScoutConfig.runLibUsageAnalysis); } else if (LibScoutConfig.opUpdatability()) { AppStats stats = LibraryIdentifier.run(inputFile, profiles, true); libUp.checkUpdatability(stats); } else if (LibScoutConfig.opProfile()) { LibraryProfiler.extractFingerPrints(inputFile, libraryDescription); } else if (LibScoutConfig.opLibApiAnalysis()) { LibraryApiAnalysis.run(inputFile); } } catch (Throwable t) { logger.error("[FATAL " + (t instanceof Exception? "EXCEPTION" : "ERROR") + "] analysis aborted: " + t.getMessage()); logger.error(Utils.stacktrace2Str(t)); } } } private static void parseCL(String[] args) { try { CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(setupOptions(), args); // parse mode of operation if (cmd.hasOption(CliArgs.ARG_OPMODE)) { try { LibScoutConfig.opmode = LibScoutConfig.OpMode.valueOf(cmd.getOptionValue(CliArgs.ARG_OPMODE).toUpperCase()); } catch (IllegalArgumentException e) { throw new ParseException(Utils.stacktrace2Str(e)); } } else usage(); /* * Logging options (apply to all modes, default settings: console logging, logdir="./logs") * -m, disable logging (takes precedence over -d) * -d [logdir], if provided without argument output is logged to default dir, otherwise to the provided dir */ if (cmd.hasOption(CliArgs.ARG_MUTE)) { LibScoutConfig.logType = LibScoutConfig.LogType.NONE; } else if (cmd.hasOption(CliArgs.ARG_LOG_DIR)) { LibScoutConfig.logType = LibScoutConfig.LogType.FILE; if (cmd.getOptionValue(CliArgs.ARG_LOG_DIR) != null) { // we have a log dir File logDir = new File(cmd.getOptionValue(CliArgs.ARG_LOG_DIR)); if (logDir.exists() && !logDir.isDirectory()) throw new ParseException("Log directory " + logDir + " already exists and is not a directory"); LibScoutConfig.logDir = logDir; } } // path to Android SDK jar if (checkOptionalUse(cmd, CliArgs.ARG_ANDROID_LIB, LibScoutConfig.OpMode.PROFILE, LibScoutConfig.OpMode.MATCH, LibScoutConfig.OpMode.LIB_API_ANALYSIS, LibScoutConfig.OpMode.UPDATABILITY)) { LibScoutConfig.pathToAndroidJar = new File(cmd.getOptionValue(CliArgs.ARG_ANDROID_LIB)); LibScoutConfig.checkIfValidFile(cmd.getOptionValue(CliArgs.ARG_ANDROID_LIB)); } // path to LibScout.toml if (checkOptionalUse(cmd, CliArgs.ARG_CONFIG, LibScoutConfig.OpMode.PROFILE, LibScoutConfig.OpMode.MATCH, LibScoutConfig.OpMode.LIB_API_ANALYSIS, LibScoutConfig.OpMode.UPDATABILITY)) { LibScoutConfig.libScoutConfigFileName = cmd.getOptionValue(CliArgs.ARG_CONFIG); LibScoutConfig.checkIfValidFile(LibScoutConfig.libScoutConfigFileName); } // profiles dir option, if provided without argument output is written to default dir if (checkOptionalUse(cmd, CliArgs.ARG_PROFILES_DIR, LibScoutConfig.OpMode.PROFILE, LibScoutConfig.OpMode.MATCH, LibScoutConfig.OpMode.UPDATABILITY)) { File profilesDir = new File(cmd.getOptionValue(CliArgs.ARG_PROFILES_DIR)); if (profilesDir.exists() && !profilesDir.isDirectory()) throw new ParseException("Profiles directory " + profilesDir + " already exists and is not a directory"); LibScoutConfig.profilesDir = profilesDir; } // disable partial matching (full lib matching only) if (checkOptionalUse(cmd, CliArgs.ARG_NO_PARTIAL_MATCHING, LibScoutConfig.OpMode.MATCH, LibScoutConfig.OpMode.UPDATABILITY)) { LibScoutConfig.noPartialMatching = true; } // run library usage analysis (for full matches only) if (checkOptionalUse(cmd, CliArgs.ARG_LIB_USAGE_ANALYSIS, LibScoutConfig.OpMode.MATCH)) { LibScoutConfig.runLibUsageAnalysis = true; } // provide library description file if (checkRequiredUse(cmd, CliArgs.ARG_LIB_DESCRIPTION, LibScoutConfig.OpMode.PROFILE)) { File libraryDescriptionFile = new File(cmd.getOptionValue(CliArgs.ARG_LIB_DESCRIPTION)); if (libraryDescriptionFile.exists() && libraryDescriptionFile.isDirectory()) throw new ParseException("Library description (" + libraryDescriptionFile + ") must not be a directory"); libraryDescription = libraryDescriptionFile; } // generate verbose library profiles? if (checkOptionalUse(cmd, CliArgs.ARG_LIB_VERBOSE_PROFILES, LibScoutConfig.OpMode.PROFILE)) { LibScoutConfig.genVerboseProfiles = true; } // enable library dependency analysis if (checkOptionalUse(cmd, CliArgs.ARG_LIB_DEPENDENCY_ANALYSIS, LibScoutConfig.OpMode.LIB_API_ANALYSIS)) { LibScoutConfig.libDependencyAnalysis = true; } // enable/disable generation of stats with optional stats directory if (checkOptionalUse(cmd, CliArgs.ARG_STATS_DIR, LibScoutConfig.OpMode.MATCH)) { LibScoutConfig.generateStats = true; if (cmd.getOptionValue(CliArgs.ARG_STATS_DIR) != null) { // stats dir provided? File statsDir = new File(cmd.getOptionValue(CliArgs.ARG_STATS_DIR)); if (statsDir.exists() && !statsDir.isDirectory()) throw new ParseException("Stats directory " + statsDir + " already exists and is not a directory"); LibScoutConfig.statsDir = statsDir; } } // enable/disable generation of json output if (checkOptionalUse(cmd, CliArgs.ARG_JSON_DIR, LibScoutConfig.OpMode.MATCH, LibScoutConfig.OpMode.LIB_API_ANALYSIS, LibScoutConfig.OpMode.UPDATABILITY)) { LibScoutConfig.generateJSON = true; if (cmd.getOptionValue(CliArgs.ARG_JSON_DIR) != null) { // json dir provided? File jsonDir = new File(cmd.getOptionValue(CliArgs.ARG_JSON_DIR)); if (jsonDir.exists() && !jsonDir.isDirectory()) throw new ParseException("JSON directory " + jsonDir + " already exists and is not a directory"); LibScoutConfig.jsonDir = jsonDir; } } // provide directory to lib api compat files (generated with api-analysis mode) if (checkRequiredUse(cmd, CliArgs.ARG_LIB_API_COMPAT_DIR, LibScoutConfig.OpMode.UPDATABILITY)) { File apiCompatDir = new File(cmd.getOptionValue(CliArgs.ARG_LIB_API_COMPAT_DIR)); if (!apiCompatDir.isDirectory()) throw new ParseException(apiCompatDir + " is not a directory"); LibScoutConfig.libApiCompatDir = apiCompatDir; } /* * process lib|app arguments * - in profile mode pass *one* library (since it is linked to lib description file) * - in match mode pass one application file or one directory (including apks) */ inputFiles = new ArrayList<File>(); if (LibScoutConfig.opLibApiAnalysis()) { // we require a directory including library packages/descriptions for (String path: cmd.getArgs()) { File dir = new File(path); if (dir.isDirectory()) inputFiles.add(dir); } if (inputFiles.isEmpty()) { throw new ParseException("You have to provide at least one directory that includes a library package and description"); } } else { String[] fileExts = LibScoutConfig.opMatch() || LibScoutConfig.opUpdatability() ? new String[]{"apk"} : new String[]{"jar", "aar"}; for (String inputFile : cmd.getArgs()) { File arg = new File(inputFile); if (arg.isDirectory()) { inputFiles.addAll(Utils.collectFiles(arg, fileExts)); } else if (arg.isFile()) { if (arg.getName().endsWith("." + fileExts[0])) inputFiles.add(arg); else if (fileExts.length > 1 && arg.getName().endsWith("." + fileExts[1])) inputFiles.add(arg); else throw new ParseException("File " + arg.getName() + " is no valid ." + Utils.join(Arrays.asList(fileExts), "/") + " file"); } else { throw new ParseException("Argument " + inputFile + " is no valid file or directory!"); } } if (inputFiles.isEmpty()) { if (LibScoutConfig.opProfile()) throw new ParseException("No libraries (jar|aar files) found to profile in " + cmd.getArgList()); else throw new ParseException("No apk files found in " + cmd.getArgList()); } else if (inputFiles.size() > 1 && LibScoutConfig.opProfile()) throw new ParseException("You have to provide a path to a single library file or a directory incl. a single lib file"); } } catch (ParseException e) { System.err.println("Command line parsing failed:\n " + e.getMessage() + "\n"); usage(); } catch (Exception e) { System.err.println("Error occurred during argument processing:\n" + e.getMessage()); } } private static boolean checkRequiredUse(CommandLine cmd, String option, LibScoutConfig.OpMode... modes) throws ParseException { if (!Arrays.asList(modes).contains(LibScoutConfig.opmode)) return false; if (!cmd.hasOption(option)) throw new ParseException("Required CLI Option " + option + " is missing in mode " + LibScoutConfig.opmode); return true; } private static boolean checkOptionalUse(CommandLine cmd, String option, LibScoutConfig.OpMode... modes) { if (!Arrays.asList(modes).contains(LibScoutConfig.opmode)) return false; return cmd.hasOption(option); } /** * Checks whether required option (for current mode) is either provided via CLI or config file */ private static void checkRequiredOptions() throws ParseException { try { LibScoutConfig.checkIfValidFile(LibScoutConfig.log4jConfigFileName); } catch (ParseException e) { throw new ParseException("Could not find the log4j config file logback.xml . Please add the path in the LibScout.toml config"); } // android-sdk.jar if (Arrays.asList(LibScoutConfig.OpMode.PROFILE, LibScoutConfig.OpMode.MATCH, LibScoutConfig.OpMode.LIB_API_ANALYSIS).contains(LibScoutConfig.opmode) && LibScoutConfig.pathToAndroidJar == null) { throw new ParseException("Required option " + CliArgs.ARGL_ANDROID_LIB + " is neither provided via command line nor config file"); } } @SuppressWarnings("static-access") private static Options setupOptions() { options = new Options(); options.addOption(OptionBuilder.withArgName("value") .hasArgs(1) .isRequired(true) .withLongOpt(CliArgs.ARGL_OPMODE) .withDescription("mode of operation, one of [" + LibScoutConfig.OpMode.getOpModeString() + "]") .create(CliArgs.ARG_OPMODE)); options.addOption(OptionBuilder.withArgName("file") .hasArgs(1) .isRequired(false) .withLongOpt(CliArgs.ARGL_CONFIG) .withDescription("path to LibScout's config file, defaults to \"" + LibScoutConfig.libScoutConfigFileName + "\"") .create(CliArgs.ARG_CONFIG)); options.addOption(OptionBuilder.withArgName("file") .hasArgs(1) .isRequired(false) .withLongOpt(CliArgs.ARGL_ANDROID_LIB) .withDescription("path to SDK android.jar") .create(CliArgs.ARG_ANDROID_LIB)); options.addOption(OptionBuilder.withArgName("directory") .hasOptionalArgs(1) .isRequired(false) .withLongOpt(CliArgs.ARGL_LOG_DIR) .withDescription("path to store the logfile(s), defaults to \"" + LibScoutConfig.logDir + "\"") .create(CliArgs.ARG_LOG_DIR)); options.addOption(OptionBuilder.withArgName("directory") .hasOptionalArgs(1) .isRequired(false) .withLongOpt(CliArgs.ARGL_STATS_DIR) .withDescription("path to app stat(s), defaults to \"" + LibScoutConfig.statsDir + "\"") .create(CliArgs.ARG_STATS_DIR)); options.addOption(OptionBuilder.withArgName("directory") .hasOptionalArgs(1) .isRequired(false) .withLongOpt(CliArgs.ARGL_JSON_DIR) .withDescription("path to json output directory, defaults to \"" + LibScoutConfig.jsonDir + "\"") .create(CliArgs.ARG_JSON_DIR)); options.addOption(OptionBuilder.withArgName("value") .isRequired(false) .withLongOpt(CliArgs.ARGL_MUTE) .withDescription("disable file and console logging, takes precedence over -d") .create(CliArgs.ARG_MUTE)); options.addOption(OptionBuilder.withArgName("directory") .hasArgs(1) .isRequired(false) .withLongOpt(CliArgs.ARGL_PROFILES_DIR) .withDescription("path to library profiles, defaults to \"" + LibScoutConfig.profilesDir + "\"") .create(CliArgs.ARG_PROFILES_DIR)); options.addOption(OptionBuilder.withArgName("value") .isRequired(false) .withLongOpt(CliArgs.ARGL_LIB_VERBOSE_PROFILES) .withDescription("enable verbose profiling (trace + pubonly)") .create(CliArgs.ARG_LIB_VERBOSE_PROFILES)); options.addOption(OptionBuilder.withArgName("value") .isRequired(false) .withLongOpt(CliArgs.ARGL_NO_PARTIAL_MATCHING) .withDescription("disables partial matching (full matching only)") .create(CliArgs.ARG_NO_PARTIAL_MATCHING)); options.addOption(OptionBuilder.withArgName("value") .isRequired(false) .withLongOpt(CliArgs.ARGL_LIB_USAGE_ANALYSIS) .withDescription("Enables library usage analysis (for full matches only)") .create(CliArgs.ARG_LIB_USAGE_ANALYSIS)); options.addOption(OptionBuilder.withArgName("file") .hasArgs(1) .isRequired(false) .withLongOpt(CliArgs.ARGL_LIB_DESCRIPTION) .withDescription("xml file to describe the library") .create(CliArgs.ARG_LIB_DESCRIPTION)); options.addOption(OptionBuilder.withArgName("value") .isRequired(false) .withLongOpt(CliArgs.ARGL_LIB_DEPENDENCY_ANALYSIS) .withDescription("enable analysis of secondary library dependencies") .create(CliArgs.ARG_LIB_DEPENDENCY_ANALYSIS)); options.addOption(OptionBuilder.withArgName("directory") .hasArgs(1) .isRequired(false) .withLongOpt(CliArgs.ARGL_LIB_API_COMPAT_DIR) .withDescription("path to library api compatibility data files") .create(CliArgs.ARG_LIB_API_COMPAT_DIR)); return options; } private static void usage() { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); String helpMsg = LibScoutConfig.OpMode.getUsageMessage(LibScoutConfig.opmode); formatter.printHelp(helpMsg, options); System.exit(1); } private static void initLogging() { LoggerContext context = (LoggerContext) org.slf4j.LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); // clear any previous configuration configurator.doConfigure(LibScoutConfig.log4jConfigFileName); ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); switch (LibScoutConfig.logType) { case CONSOLE: rootLogger.detachAppender("FILE"); break; case FILE: rootLogger.detachAppender("CONSOLE"); break; case NONE: rootLogger.detachAndStopAllAppenders(); break; } } catch (JoranException je) { // StatusPrinter will handle this } StatusPrinter.printInCaseOfErrorsOrWarnings(context); } }
37.932171
192
0.723088
3bb79d7a781bbb088d66a58e5dba7f5142372715
837
package com.github.fppt.jedismock.operations.hashes; import com.github.fppt.jedismock.datastructures.Slice; import com.github.fppt.jedismock.operations.AbstractRedisOperation; import com.github.fppt.jedismock.operations.RedisCommand; import com.github.fppt.jedismock.server.Response; import com.github.fppt.jedismock.storage.RedisBase; import java.util.List; @RedisCommand("hstrlen") public class HStrlen extends AbstractRedisOperation { public HStrlen(RedisBase base, List<Slice> params) { super(base, params); } @Override protected Slice response() { Slice key = params().get(0); Slice field = params().get(1); Slice result = base().getFieldsAndValues(key).get(field); return Response.integer(result == null ? 0 : result.toString().length()); } }
33.48
82
0.707288
e305d3155091b023bbcdac26ab09258d22fb36f5
960
package ru.fizteh.fivt.students.SergeyAksenov.shell; import java.io.File; public final class RmCommand implements Command { public void run(final String[] args, final Environment env) throws ShellException { if (!Executor.checkArgNumber(2, args.length, 3)) { ErrorHandler.countArguments("rm"); } boolean recursive = false; if (args.length == 3) { if (!args[1].equals("-r")) { ErrorHandler.invalidArgument("rm", args[1]); } recursive = true; } File fileToRem = new File(env.currentDirectory + File.separator + args[args.length - 1]); if (!fileToRem.exists()) { ErrorHandler.noFile("rm", args[args.length - 1]); } if (!recursive && fileToRem.isDirectory()) { ErrorHandler.isDirectory("rm", args[args.length - 1]); } Executor.delete(fileToRem); } }
33.103448
66
0.564583
830c7ce5e53156243c03eab74ade362c1a5e0600
11,759
/* * Copyright (c) Open Source Strategies, Inc. * * Opentaps is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Opentaps is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Opentaps. If not, see <http://www.gnu.org/licenses/>. */ // A portion of this file may have come from the Apache OFBIZ project /******************************************************************************* * 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. *******************************************************************************/ /* This file has been modified by Open Source Strategies, Inc. */ package com.opensourcestrategies.financials.payroll; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import org.ofbiz.base.util.UtilFormatOut; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.Delegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.util.EntityUtil; import org.ofbiz.security.Security; import org.ofbiz.service.DispatchContext; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.LocalDispatcher; import org.ofbiz.service.ModelService; import org.ofbiz.service.ServiceUtil; import org.opentaps.common.util.UtilCommon; import org.opentaps.common.util.UtilMessage; public class PayrollServices { public static String module = PayrollServices.class.getName(); private static final int PAYCHECK_ITEM_SEQUENCE_ID_DIGITS = 5; // this is the number of digits used for paycheckItemSeqId: 00001, 00002... public static final String resource = "FinancialsUiLabels"; public static Map createPaycheck(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); Security security = dctx.getSecurity(); GenericValue userLogin = (GenericValue) context.get("userLogin"); Locale locale = UtilCommon.getLocale(context); if (!security.hasEntityPermission("FINANCIALS", "_EMP_PCCRTE", userLogin)) { return UtilMessage.createAndLogServiceError("FinancialsServiceErrorNoPermission", locale, module); } String partyIdFrom = (String) context.get("partyIdFrom"); String paymentTypeId = (String) context.get("paymentTypeId"); String paymentId = null; try { // create the paycheck ModelService service = dctx.getModelService("createPayment"); Map createPaycheckServiceContext = service.makeValid(context, "IN"); Map createPaycheckServiceResult = dispatcher.runSync(service.name, createPaycheckServiceContext); if (ServiceUtil.isError(createPaycheckServiceResult)) { return UtilMessage.createAndLogServiceError(createPaycheckServiceResult, ServiceUtil.getErrorMessage(createPaycheckServiceResult), locale, module); } paymentId = (String) createPaycheckServiceResult.get("paymentId"); // get the paycheckItemTypes associated with this paycheck List paycheckTypeItemTypeAssocList = delegator.findByAnd("PaycheckTypeItemTypeAssocAndPaycheckItemType", UtilMisc.toMap("paymentTypeId", paymentTypeId), UtilMisc.toList("defaultSeqNum")); if (UtilValidate.isEmpty(paycheckTypeItemTypeAssocList)) { return UtilMessage.createAndLogServiceError("FinancialsServiceErrorFailedToGetThePaycheckItemTypes", locale, module); } List paycheckItemTypeIdList = EntityUtil.getFieldListFromEntityList(paycheckTypeItemTypeAssocList, "paycheckItemTypeId", true); // create the paycheck items int paycheckItemSeqNum = 1; String paycheckItemSeqId = UtilFormatOut.formatPaddedNumber(paycheckItemSeqNum, PAYCHECK_ITEM_SEQUENCE_ID_DIGITS); for (Iterator iter = paycheckItemTypeIdList.iterator(); iter.hasNext(); ) { String paycheckItemTypeId = (String) iter.next(); Map createPaycheckItemContext = UtilMisc.toMap("paycheckItemTypeId", paycheckItemTypeId); createPaycheckItemContext.put("organizationPartyId", partyIdFrom); // get the due to party for this type of paycheck item GenericValue paycheckItemTypeGlAccount = delegator.findByPrimaryKey("PaycheckItemTypeGlAccount", UtilMisc.toMap("paycheckItemTypeId", paycheckItemTypeId, "organizationPartyId", partyIdFrom)); createPaycheckItemContext.put("partyId", (String)paycheckItemTypeGlAccount.get("defaultDueToPartyId")); // store the paycheck item and increment the sequence number try { GenericValue paycheckItem = delegator.makeValue("PaycheckItem", UtilMisc.toMap("paymentId", paymentId, "paycheckItemSeqId", paycheckItemSeqId)); paycheckItem.setNonPKFields(createPaycheckItemContext); paycheckItem.create(); } catch (GenericEntityException e) { return ServiceUtil.returnError(e.getMessage()); } paycheckItemSeqNum++; paycheckItemSeqId = UtilFormatOut.formatPaddedNumber(paycheckItemSeqNum, PAYCHECK_ITEM_SEQUENCE_ID_DIGITS); } } catch (GenericEntityException ex) { return ServiceUtil.returnError(ex.getMessage()); } catch (GenericServiceException ex) { return ServiceUtil.returnError(ex.getMessage()); } // return the paymentId of the newly created PayCheck Map results = ServiceUtil.returnSuccess(); results.put("paymentId", paymentId); return results; } public static Map updatePaycheck(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); Security security = dctx.getSecurity(); GenericValue userLogin = (GenericValue) context.get("userLogin"); Locale locale = UtilCommon.getLocale(context); if (!security.hasEntityPermission("FINANCIALS", "_EMP_PCUPDT", userLogin)) { return UtilMessage.createAndLogServiceError("FinancialsServiceErrorNoPermission", locale, module); } try { // update the paycheck ModelService service = dctx.getModelService("updatePayment"); Map updatePaycheckServiceContext = service.makeValid(context, "IN"); Map updatePaycheckServiceResult = dispatcher.runSync(service.name, updatePaycheckServiceContext); if (ServiceUtil.isError(updatePaycheckServiceResult)) { return UtilMessage.createAndLogServiceError(updatePaycheckServiceResult, ServiceUtil.getErrorMessage(updatePaycheckServiceResult), locale, module); } } catch (GenericServiceException ex) { return ServiceUtil.returnError(ex.getMessage()); } // return the paymentId of the updated PayCheck String paymentId = (String) context.get("paymentId"); Map results = ServiceUtil.returnSuccess(); results.put("paymentId", paymentId); return results; } public static Map updatePaycheckItem(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); Security security = dctx.getSecurity(); GenericValue userLogin = (GenericValue) context.get("userLogin"); Locale locale = UtilCommon.getLocale(context); if (!security.hasEntityPermission("FINANCIALS", "_EMP_PCUPDT", userLogin)) { return UtilMessage.createAndLogServiceError("FinancialsServiceErrorNoPermission", locale, module); } String paymentId = (String) context.get("paymentId"); String paycheckItemSeqId = (String) context.get("paycheckItemSeqId"); Double amount = (Double) context.get("amount"); String partyId = (String) context.get("partyId"); String organizationPartyId = (String) context.get("organizationPartyId"); try { // check that the paycheck is in NOT PAID status GenericValue payment = delegator.findByPrimaryKey("Payment", UtilMisc.toMap("paymentId", paymentId)); if (!"PMNT_NOT_PAID".equals(payment.getString("statusId"))) { return UtilMessage.createAndLogServiceError("FinancialsServiceErrorPaycheckMustBeInNotPaidStatusToChangePaycheckItem", locale, module); } // check if the new witholdings amount sum exceeds the paycheck gross amount PaycheckReader paycheckReader = new PaycheckReader(paymentId, delegator); if (!paycheckReader.isPaycheckItemAmountChangeValid(paycheckItemSeqId, amount)) { return UtilMessage.createAndLogServiceError("FinancialsServiceErrorWitholdingsSumExceedsPaycheckGrossAmount", locale, module); } // update the paycheck item Map updatePaycheckItemServiceContext = UtilMisc.toMap("paymentId", paymentId, "paycheckItemSeqId", paycheckItemSeqId); updatePaycheckItemServiceContext.put("amount", amount); updatePaycheckItemServiceContext.put("partyId", partyId); updatePaycheckItemServiceContext.put("userLogin", userLogin); GenericValue paycheckItem = delegator.findByPrimaryKey("PaycheckItem", UtilMisc.toMap("paymentId", paymentId, "paycheckItemSeqId", paycheckItemSeqId)); paycheckItem.setNonPKFields(updatePaycheckItemServiceContext); paycheckItem.store(); } catch (GenericEntityException ex) { return ServiceUtil.returnError(ex.getMessage()); } return ServiceUtil.returnSuccess(); } }
52.730942
164
0.657284
8b5a753a55a6f45588c8a47897d48c3c69f57511
3,102
package com.advancedtechnicalengineering.sparkdemo.twitter; import com.google.common.collect.Lists; import com.twitter.hbc.ClientBuilder; import com.twitter.hbc.core.Client; import com.twitter.hbc.core.Constants; import com.twitter.hbc.core.Hosts; import com.twitter.hbc.core.HttpHosts; import com.twitter.hbc.core.endpoint.StatusesFilterEndpoint; import com.twitter.hbc.core.event.Event; import com.twitter.hbc.core.processor.StringDelimitedProcessor; import com.twitter.hbc.httpclient.auth.Authentication; import com.twitter.hbc.httpclient.auth.OAuth1; import java.io.Serializable; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; /** * Provides a data source for Twitter streams */ public class TwitterDataProvider implements Serializable { private Client client; private BlockingQueue<String> msgQueue = new LinkedBlockingQueue<>(100000); private BlockingQueue<Event> eventQueue = new LinkedBlockingQueue<>(1000); private String consumerKey; private String consumerSecret; private String token; private String tokenString; /** * Initializes a new instance of the TwitterDataProvider class. Requires a registered app on http://dev.twitter.com * @param consumerKey Twitter consumer key * @param consumerSecret Twitter consumer secret * @param token Twitter app token * @param tokenString Twitter app token string */ public TwitterDataProvider(String consumerKey, String consumerSecret, String token, String tokenString) { this.consumerKey = consumerKey; this.consumerSecret = consumerSecret; this.token = token; this.tokenString = tokenString; } /** * Connects to Twitter and starts listening */ public void connect() { Hosts hosts = new HttpHosts(Constants.STREAM_HOST); StatusesFilterEndpoint endpoint = new StatusesFilterEndpoint(); List<String> terms = Lists.newArrayList("Ferguson"); Authentication authentication = new OAuth1(consumerKey, consumerSecret, token, tokenString); ClientBuilder clientBuilder = new ClientBuilder() .name("SparkDemo-Client") .hosts(hosts) .authentication(authentication) .endpoint(endpoint) .processor(new StringDelimitedProcessor(msgQueue)) .eventMessageQueue(eventQueue); client = clientBuilder.build(); endpoint.trackTerms(terms); client.connect(); } /** * Disconnects from the Twitter stream */ public void disconnect() { client.stop(); } /** * Gets the queue containing String messages from Twitter * @return The queue containing String messages from Twitter */ public BlockingQueue<String> getMsgQueue() { return msgQueue; } /** * Gets the queue containing events from Twitter * @return The queue containing events from Twitter */ public BlockingQueue<Event> getEventQueue() { return eventQueue; } }
34.466667
119
0.70374
996a03a34590b7244ff15b36f00771289a06e852
1,520
package retrogdx.generic.readers; import retrogdx.utils.SmartByteBuffer; import java.nio.ByteOrder; public class Palette { public int[] colors; public static Palette fromRGB16(SmartByteBuffer buffer) { buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.position(0); Palette palette = new Palette(); palette.colors = new int[buffer.capacity() / 2]; for (int i = 0; i < palette.colors.length; i++) { int color16 = buffer.readShort(); palette.colors[i] = (((color16 >> 10) & 0x1f) << 27) | (((color16 >> 5) & 0x1f) << 19) | ((color16 & 0x1f) << 11) | 0xff; } return palette; } public static Palette fromRGB24(SmartByteBuffer buffer) { buffer.order(ByteOrder.BIG_ENDIAN); buffer.position(0); Palette palette = new Palette(); palette.colors = new int[buffer.capacity() / 3]; for (int i = 0; i < palette.colors.length; i++) { palette.colors[i] = (buffer.readUByte() << 24) | (buffer.readUByte() << 16) | (buffer.readUByte() << 8) | 0xff; } return palette; } public static Palette fromRGB_32(SmartByteBuffer buffer) { buffer.order(ByteOrder.BIG_ENDIAN); buffer.position(0); Palette palette = new Palette(); palette.colors = new int[buffer.capacity() / 4]; for (int i = 0; i < palette.colors.length; i++) { palette.colors[i] = buffer.readInt() | 0xff; } return palette; } }
28.679245
133
0.584211
dd6c299db98f0ff61a4ddb5e75481119c62e2f43
248
package br.com.podrao.auth.core.models.commands; import lombok.Getter; import lombok.RequiredArgsConstructor; @Getter @RequiredArgsConstructor public class CadastrarFuncaoCommand { private final String codigo; private final String descricao; }
20.666667
48
0.830645
7bc8a710ccc868d8b9e25b29c19d0a9df8d7ba65
620
package com.example.gab.babylove.entity; import java.io.Serializable; import java.util.List; /** * * @author Gab * @date 2018/3/14 0014 */ public class OrnamentalListBean implements Serializable { private List<CourseDetails.DataBean.GroupsBean.ActionsBean> data; public List<CourseDetails.DataBean.GroupsBean.ActionsBean> getData() { return data; } public void setData(List<CourseDetails.DataBean.GroupsBean.ActionsBean> data) { this.data = data; } public OrnamentalListBean(List<CourseDetails.DataBean.GroupsBean.ActionsBean> data) { this.data = data; } }
22.142857
89
0.712903
e04463fe1fed045baf5ed79b1b58c44554438c96
7,647
package org.sunbird.integration.test.user; import com.consol.citrus.annotations.CitrusTest; import com.consol.citrus.testng.CitrusParameters; import javax.ws.rs.core.MediaType; import org.springframework.http.HttpStatus; import org.sunbird.common.action.UserUtil; import org.sunbird.integration.test.common.BaseCitrusTestRunner; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class UpdateUserFrameworkTest extends BaseCitrusTestRunner { public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_USER_ID = "testUpdateUserFrameworkFailureWithInvalidUserId"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_EMPTY_USER_ID = "testUpdateUserFrameworkFailureWithEmptyUserId"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITHOUT_USER_ID = "testUpdateUserFrameworkFailureWithoutUserId"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_BOARD = "testUpdateUserFrameworkFailureWithInvalidBoard"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_EMPTY_BOARD = "testUpdateUserFrameworkFailureWithEmptyBoard"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITHOUT_BOARD = "testUpdateUserFrameworkFailureWithoutBoard"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_BOARD_DATA_TYPE = "testUpdateUserFrameworkFailureWithInvalidBoardDataType"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_MEDIUM = "testUpdateUserFrameworkFailureWithInvalidMedium"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_EMPTY_MEDIUM = "testUpdateUserFrameworkFailureWithEmptyMedium"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITHOUT_MEDIUM = "testUpdateUserFrameworkFailureWithoutMedium"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_MEDIUM_DATA_TYPE = "testUpdateUserFrameworkFailureWithInvalidMediumDataType"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_GRADE_LEVEL = "testUpdateUserFrameworkFailureWithInvalidGradeLevel"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_EMPTY_GRADE_LEVEL = "testUpdateUserFrameworkFailureWithEmptyGradeLevel"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITHOUT_GRADE_LEVEL = "testUpdateUserFrameworkFailureWithoutGradeLevel"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_GRADE_LEVEL_DATA_TYPE = "testUpdateUserFrameworkFailureWithInvalidGradeLevelDataType"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_SUBJECT = "testUpdateUserFrameworkFailureWithInvalidSubject"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_SUBJECT_DATA_TYPE = "testUpdateUserFrameworkFailureWithInvalidSubjectDataType"; public static final String TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_UNSUPPORTED_FIELD = "testUpdateUserFrameworkFailureWithUnsupportedField"; public static final String TEST_UPDATE_USER_FRAMEWORK_SUCCESS_WITHOUT_SUBJECT = "testUpdateUserFrameworkSuccessWithoutSubject"; public static final String TEST_UPDATE_USER_FRAMEWORK_SUCCESS_WITH_EMPTY_SUBJECT = "testUpdateUserFrameworkSuccessWithEmptySubject"; public static final String TEST_UPDATE_USER_FRAMEWORK_SUCCESS = "testUpdateUserFrameworkSuccess"; public static final String TEMPLATE_DIR = "templates/user/update/framework"; private String getUpdaterUserUrl() { return getLmsApiUriPath("/api/user/v1/update", "/v1/user/update"); } @DataProvider(name = "updateUserFrameworkFailureDataProvider") public Object[][] updateUserFrameworkFailureDataProvider() { return new Object[][] { new Object[] { TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_USER_ID, HttpStatus.UNAUTHORIZED }, new Object[] {TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_EMPTY_USER_ID, HttpStatus.BAD_REQUEST}, new Object[] {TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITHOUT_USER_ID, HttpStatus.BAD_REQUEST}, new Object[] {TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_BOARD, HttpStatus.BAD_REQUEST}, new Object[] {TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_EMPTY_BOARD, HttpStatus.BAD_REQUEST}, new Object[] {TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITHOUT_BOARD, HttpStatus.BAD_REQUEST}, new Object[] { TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_BOARD_DATA_TYPE, HttpStatus.BAD_REQUEST }, new Object[] {TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_MEDIUM, HttpStatus.BAD_REQUEST}, new Object[] {TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_EMPTY_MEDIUM, HttpStatus.BAD_REQUEST}, new Object[] {TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITHOUT_MEDIUM, HttpStatus.BAD_REQUEST}, new Object[] { TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_MEDIUM_DATA_TYPE, HttpStatus.BAD_REQUEST }, new Object[] { TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_GRADE_LEVEL, HttpStatus.BAD_REQUEST }, new Object[] { TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_EMPTY_GRADE_LEVEL, HttpStatus.BAD_REQUEST }, new Object[] {TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITHOUT_GRADE_LEVEL, HttpStatus.BAD_REQUEST}, new Object[] { TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_GRADE_LEVEL_DATA_TYPE, HttpStatus.BAD_REQUEST }, new Object[] { TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_SUBJECT, HttpStatus.BAD_REQUEST }, new Object[] { TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_INVALID_SUBJECT_DATA_TYPE, HttpStatus.BAD_REQUEST }, new Object[] { TEST_UPDATE_USER_FRAMEWORK_FAILURE_WITH_UNSUPPORTED_FIELD, HttpStatus.BAD_REQUEST }, }; } @DataProvider(name = "updateUserFrameworkSuccessDataProvider") public Object[][] updateUserFrameworkSuccessDataProvider() { return new Object[][] { new Object[] {TEST_UPDATE_USER_FRAMEWORK_SUCCESS_WITHOUT_SUBJECT}, new Object[] {TEST_UPDATE_USER_FRAMEWORK_SUCCESS_WITH_EMPTY_SUBJECT}, new Object[] {TEST_UPDATE_USER_FRAMEWORK_SUCCESS}, }; } @Test(dataProvider = "updateUserFrameworkFailureDataProvider") @CitrusParameters({"testName", "httpStatusCode"}) @CitrusTest public void testUpdateUserFrameworkFailure(String testName, HttpStatus httpStatus) { getTestCase().setName(testName); beforeTest(); performPatchTest( this, TEMPLATE_DIR, testName, getUpdaterUserUrl(), REQUEST_JSON, MediaType.APPLICATION_JSON, true, httpStatus, RESPONSE_JSON); } @Test(dataProvider = "updateUserFrameworkSuccessDataProvider") @CitrusParameters({"testName"}) @CitrusTest public void testUpdateUserFrameworkSuccess(String testName) { getTestCase().setName(testName); beforeTest(); performPatchTest( this, TEMPLATE_DIR, testName, getUpdaterUserUrl(), REQUEST_JSON, MediaType.APPLICATION_JSON, true, HttpStatus.OK, RESPONSE_JSON); } private void beforeTest() { UserUtil.createUserAndGetToken(this, testContext); variable("userId", testContext.getVariable("userId")); variable("board", System.getenv("sunbird_user_framework_board")); variable("gradeLevel", System.getenv("sunbird_user_framework_grade_level")); variable("medium", System.getenv("sunbird_user_framework_medium")); variable("subject", System.getenv("sunbird_user_framework_subject")); } }
47.203704
100
0.796522
62da6b30618b936e5160dec680f2253286466942
3,381
package com.ofg.infrastructure.discovery; import com.google.common.collect.Iterables; import com.ofg.infrastructure.discovery.util.LoadBalancerType; import org.apache.commons.lang.StringUtils; import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependency; import java.util.*; public class SpringCloudToMicroserviceJsonConverter { private final String servicePath; private final ZookeeperDependencies zookeeperDependencies; private final ZookeeperDiscoveryProperties zookeeperDiscoveryProperties; public SpringCloudToMicroserviceJsonConverter(String servicePath, ZookeeperDependencies zookeeperDependencies, ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) { this.servicePath = servicePath; this.zookeeperDependencies = zookeeperDependencies; this.zookeeperDiscoveryProperties = zookeeperDiscoveryProperties; } public String toMicroserviceJsonNotation() { String basePath = zookeeperDiscoveryProperties.getRoot().replaceAll("/", ""); List<MicroserviceConfiguration.Dependency> dependencies = new ArrayList<>(); for (Map.Entry<String, ZookeeperDependency> zookeeperDependencyEntry : zookeeperDependencies.getDependencies().entrySet()) { ZookeeperDependency zookeeperDependency = zookeeperDependencyEntry.getValue(); MicroserviceConfiguration.Dependency dependency = new MicroserviceConfiguration.Dependency( new ServiceAlias(zookeeperDependencyEntry.getKey()), new ServicePath(zookeeperDependency.getPath()), zookeeperDependency.isRequired(), LoadBalancerType.fromName(zookeeperDependency.getLoadBalancerType().name()), zookeeperDependency.getContentTypeTemplate(), zookeeperDependency.getVersion(), convertFromMapOfCollection(zookeeperDependency.getHeaders()), zookeeperDependency.getStubsConfiguration() == null ? null : new MicroserviceConfiguration.Dependency.StubsConfiguration( zookeeperDependency.getStubsConfiguration().getStubsGroupId(), zookeeperDependency.getStubsConfiguration().getStubsArtifactId(), zookeeperDependency.getStubsConfiguration().getStubsClassifier()) ); dependencies.add(dependency); } MicroserviceConfiguration microserviceConfiguration = new MicroserviceConfiguration(new ServicePath(servicePath), dependencies); return MicroserviceConfigurationToJsonConverter.fromConfiguration(basePath, microserviceConfiguration); } /** * In micro-infra we don't support collection in headers * @param map * @return */ private Map<String, String> convertFromMapOfCollection(Map<String, Collection<String>> map) { Map<String, String> newMap = new HashMap<>(); for (Map.Entry<String, Collection<String>> entry : map.entrySet()) { newMap.put(entry.getKey(), Iterables.getFirst(entry.getValue(), StringUtils.EMPTY)); } return newMap; } }
53.666667
175
0.716948
9e7f6da2869dfbccac250b23121a53f8ad076fda
8,253
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|// Copyright (C) 2014 The Android Open Source Project end_comment begin_comment comment|// end_comment begin_comment comment|// Licensed under the Apache License, Version 2.0 (the "License"); end_comment begin_comment comment|// you may not use this file except in compliance with the License. end_comment begin_comment comment|// You may obtain a copy of the License at end_comment begin_comment comment|// end_comment begin_comment comment|// http://www.apache.org/licenses/LICENSE-2.0 end_comment begin_comment comment|// end_comment begin_comment comment|// Unless required by applicable law or agreed to in writing, software end_comment begin_comment comment|// distributed under the License is distributed on an "AS IS" BASIS, end_comment begin_comment comment|// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. end_comment begin_comment comment|// See the License for the specific language governing permissions and end_comment begin_comment comment|// limitations under the License. end_comment begin_package DECL|package|com.google.gerrit.util.http package|package name|com operator|. name|google operator|. name|gerrit operator|. name|util operator|. name|http package|; end_package begin_import import|import static name|com operator|. name|google operator|. name|common operator|. name|truth operator|. name|Truth operator|. name|assertThat import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|gerrit operator|. name|util operator|. name|http operator|. name|RequestUtil operator|. name|getEncodedPathInfo import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|gerrit operator|. name|util operator|. name|http operator|. name|RequestUtil operator|. name|getRestPathWithoutIds import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|util operator|. name|http operator|. name|testutil operator|. name|FakeHttpServletRequest import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_class DECL|class|RequestUtilTest specifier|public class|class name|RequestUtilTest block|{ annotation|@ name|Test DECL|method|getEncodedPathInfo_emptyContextPath () specifier|public name|void name|getEncodedPathInfo_emptyContextPath parameter_list|() block|{ name|assertThat argument_list|( name|getEncodedPathInfo argument_list|( name|fakeRequest argument_list|( literal|"" argument_list|, literal|"/s" argument_list|, literal|"/foo/bar" argument_list|) argument_list|) argument_list|) operator|. name|isEqualTo argument_list|( literal|"/foo/bar" argument_list|) expr_stmt|; name|assertThat argument_list|( name|getEncodedPathInfo argument_list|( name|fakeRequest argument_list|( literal|"" argument_list|, literal|"/s" argument_list|, literal|"/foo%2Fbar" argument_list|) argument_list|) argument_list|) operator|. name|isEqualTo argument_list|( literal|"/foo%2Fbar" argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|getEncodedPathInfo_emptyServletPath () specifier|public name|void name|getEncodedPathInfo_emptyServletPath parameter_list|() block|{ name|assertThat argument_list|( name|getEncodedPathInfo argument_list|( name|fakeRequest argument_list|( literal|"" argument_list|, literal|"/c" argument_list|, literal|"/foo/bar" argument_list|) argument_list|) argument_list|) operator|. name|isEqualTo argument_list|( literal|"/foo/bar" argument_list|) expr_stmt|; name|assertThat argument_list|( name|getEncodedPathInfo argument_list|( name|fakeRequest argument_list|( literal|"" argument_list|, literal|"/c" argument_list|, literal|"/foo%2Fbar" argument_list|) argument_list|) argument_list|) operator|. name|isEqualTo argument_list|( literal|"/foo%2Fbar" argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|getEncodedPathInfo_trailingSlashes () specifier|public name|void name|getEncodedPathInfo_trailingSlashes parameter_list|() block|{ name|assertThat argument_list|( name|getEncodedPathInfo argument_list|( name|fakeRequest argument_list|( literal|"/c" argument_list|, literal|"/s" argument_list|, literal|"/foo/bar/" argument_list|) argument_list|) argument_list|) operator|. name|isEqualTo argument_list|( literal|"/foo/bar/" argument_list|) expr_stmt|; name|assertThat argument_list|( name|getEncodedPathInfo argument_list|( name|fakeRequest argument_list|( literal|"/c" argument_list|, literal|"/s" argument_list|, literal|"/foo/bar///" argument_list|) argument_list|) argument_list|) operator|. name|isEqualTo argument_list|( literal|"/foo/bar/" argument_list|) expr_stmt|; name|assertThat argument_list|( name|getEncodedPathInfo argument_list|( name|fakeRequest argument_list|( literal|"/c" argument_list|, literal|"/s" argument_list|, literal|"/foo%2Fbar/" argument_list|) argument_list|) argument_list|) operator|. name|isEqualTo argument_list|( literal|"/foo%2Fbar/" argument_list|) expr_stmt|; name|assertThat argument_list|( name|getEncodedPathInfo argument_list|( name|fakeRequest argument_list|( literal|"/c" argument_list|, literal|"/s" argument_list|, literal|"/foo%2Fbar///" argument_list|) argument_list|) argument_list|) operator|. name|isEqualTo argument_list|( literal|"/foo%2Fbar/" argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|emptyPathInfo () specifier|public name|void name|emptyPathInfo parameter_list|() block|{ name|assertThat argument_list|( name|getEncodedPathInfo argument_list|( name|fakeRequest argument_list|( literal|"/c" argument_list|, literal|"/s" argument_list|, literal|"" argument_list|) argument_list|) argument_list|) operator|. name|isNull argument_list|() expr_stmt|; block|} annotation|@ name|Test DECL|method|getRestPathWithoutIds_emptyContextPath () specifier|public name|void name|getRestPathWithoutIds_emptyContextPath parameter_list|() block|{ name|assertThat argument_list|( name|getRestPathWithoutIds argument_list|( name|fakeRequest argument_list|( literal|"" argument_list|, literal|"/a/accounts" argument_list|, literal|"/123/test" argument_list|) argument_list|) argument_list|) operator|. name|isEqualTo argument_list|( literal|"/accounts/test" argument_list|) expr_stmt|; name|assertThat argument_list|( name|getRestPathWithoutIds argument_list|( name|fakeRequest argument_list|( literal|"" argument_list|, literal|"/accounts" argument_list|, literal|"/123/test" argument_list|) argument_list|) argument_list|) operator|. name|isEqualTo argument_list|( literal|"/accounts/test" argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|getRestPathWithoutIds_nonEmptyContextPath () specifier|public name|void name|getRestPathWithoutIds_nonEmptyContextPath parameter_list|() block|{ name|assertThat argument_list|( name|getRestPathWithoutIds argument_list|( name|fakeRequest argument_list|( literal|"/c" argument_list|, literal|"/a/accounts" argument_list|, literal|"/123/test" argument_list|) argument_list|) argument_list|) operator|. name|isEqualTo argument_list|( literal|"/accounts/test" argument_list|) expr_stmt|; name|assertThat argument_list|( name|getRestPathWithoutIds argument_list|( name|fakeRequest argument_list|( literal|"/c" argument_list|, literal|"/accounts" argument_list|, literal|"/123/test" argument_list|) argument_list|) argument_list|) operator|. name|isEqualTo argument_list|( literal|"/accounts/test" argument_list|) expr_stmt|; block|} DECL|method|fakeRequest ( String contextPath, String servletPath, String pathInfo) specifier|private name|FakeHttpServletRequest name|fakeRequest parameter_list|( name|String name|contextPath parameter_list|, name|String name|servletPath parameter_list|, name|String name|pathInfo parameter_list|) block|{ name|FakeHttpServletRequest name|req init|= operator|new name|FakeHttpServletRequest argument_list|( literal|"gerrit.example.com" argument_list|, literal|80 argument_list|, name|contextPath argument_list|, name|servletPath argument_list|) decl_stmt|; return|return name|req operator|. name|setPathInfo argument_list|( name|pathInfo argument_list|) return|; block|} block|} end_class end_unit
16.150685
83
0.808676
4127abc15582e56548efee135559a72ba5f9d8f5
1,640
package net.sourceforge.ganttproject.time.gregorian; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import net.sourceforge.ganttproject.language.GanttLanguage; import net.sourceforge.ganttproject.language.GanttLanguage.Event; import net.sourceforge.ganttproject.time.DateFrameable; import net.sourceforge.ganttproject.time.TextFormatter; import net.sourceforge.ganttproject.time.TimeUnit; import net.sourceforge.ganttproject.time.TimeUnitText; public class MonthTextFormatter extends CachingTextFormatter implements TextFormatter { public MonthTextFormatter() { initFormats(); } protected TimeUnitText createTimeUnitText(Date adjustedLeft) { TimeUnitText result; String longText = MessageFormat.format("{0}", new Object[] {myLongFormat.format(adjustedLeft)}); String mediumText = MessageFormat.format("{0}", new Object[] {myMediumFormat.format(adjustedLeft)}); String shortText = MessageFormat.format("{0}", new Object[] {myShortFormat.format(adjustedLeft)}); result = new TimeUnitText(longText, mediumText, shortText); return result; } private void initFormats() { myLongFormat = GanttLanguage.getInstance().createDateFormat("MMMM yyyy"); myMediumFormat = GanttLanguage.getInstance().createDateFormat("MMM - yy"); myShortFormat = GanttLanguage.getInstance().createDateFormat("MM - yy"); } public void languageChanged(Event event) { super.languageChanged(event); initFormats(); } private SimpleDateFormat myLongFormat; private SimpleDateFormat myMediumFormat; private SimpleDateFormat myShortFormat; }
38.139535
102
0.787805
6cb6876ab8db12b9074f3476e3e8d6dbe5376ea6
442
package com.example.demo.service; import com.example.demo.entity.User; import com.example.demo.repositories.UserRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class UserServiceImpl implements UserService { private UserRepository userRepository; @Override public User save(User user) { return userRepository.save(user); } }
24.555556
53
0.791855
a0607dc9e750396a0193b17b3671244100aa6466
499
/* * IntPTI: integer error fixing by proper-type inference * Copyright (c) 2017. * * Open-source component: * * CPAchecker * Copyright (C) 2007-2014 Dirk Beyer * * Guava: Google Core Libraries for Java * Copyright (C) 2010-2006 Google * * */ package org.sosy_lab.cpachecker.core.interfaces; public interface WrapperConfidence extends Confidence { public <T extends Confidence> T retrieveWrappedConfidence(Class<T> type); public Iterable<Confidence> getWrappedConfidence(); }
19.96
75
0.731463
85d0b66947fbb83a89d7c54d319d504376ef4331
198
package edu.utfpr.xbi.collector.browsers; import edu.utfpr.xbi.collector.BrowserCollector; public interface Browsers { public BrowserCollector createCollector (String url) throws Exception; }
24.75
74
0.813131
c2cd718016fc9c3788f4afd7f44d25ae56ff5747
34,627
/* $Id$ ***************************************************************************** * Copyright (c) 2009-2012 Contributors - see below * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * tfmorris ***************************************************************************** * * Some portions of this file was previously release using the BSD License: */ // Copyright (c) 2002-2009 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.ui.targetmanager; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.logging.Level; import java.util.logging.Logger; import javax.management.ListenerNotFoundException; import javax.management.Notification; import javax.management.NotificationEmitter; import javax.management.NotificationListener; import javax.swing.event.EventListenerList; import org.argouml.kernel.Project; import org.argouml.kernel.ProjectManager; import org.argouml.model.Model; import org.tigris.gef.base.Diagram; import org.tigris.gef.presentation.Fig; /** * The manager of the target of ArgoUML. * The target of ArgoUML is the element currently selected by the user. * This can either be an instance of a meta-class (an * Interface or a Class for example) but it can also be a diagram * or anything that is shown * on a diagram.<p> * * There can be multiple targets in case * someone selected multiple items in the explorer or on the diagram. * This can be done by shift-clicking or Ctrl-clicking items, * or by drawing a box on the diagram around the items to select.<p> * * In case multiple targets are selected, the target manager will add each * target to the beginning of the list of targets. This way, * the first item of the list is the last selected item. * Most functions in ArgoUML work on all selected items. * However, a few (intentionally) only work on one target, * such as the properties panels. * These functions have 2 ways of retrieving the target they should work on: * <ul> * <li>1. Use the functions that return one target only, * such as getTarget(), getModelTarget(), getFigTarget(). * <li>2. Use the first item in the list returned by * getTargets(), getModelTargets(). </ul><p> * * Remark: There is currently no function getFigs(), * returning a list of selected figs. * But you can obtain such a list from GEF. <p> * * The purpose of the targetmanager is to have a central spot where we * manage the list of current targets.<p> * * Via an event mechanism this manager makes sure that all objects interested * in knowing wether the selection changed are acknowledged. <p> * * Note in particular that null is an invalid target.<p> * * Thanks to the architecture of ArgoUML of Modelelements and Figs, * one rule has been decided upon (by mvw@tigris.org):<ul> * <li>The list of targets shall not contain any Fig that has an owner. * Instead, the owner is enlisted. * </ul> * * @author jaap.branderhorst@xs4all.nl */ public final class TargetManager { /** * The manager of the history of targets. Every time the user (or * the program) selects a new target, this is recorded in the * history. Via navigateBack and navigateForward, the user can * browse through the history just like in an ordinary internet * browser. * @author jaap.branderhorst@xs4all.nl */ private final class HistoryManager implements TargetListener { private static final int MAX_SIZE = 100; /** * The history with targets. */ private List history = new ArrayList(); /** * Flag to indicate if the current settarget was instantiated by a * navigateBack action. */ private boolean navigateBackward; /** * The pointer to the current target in the history. */ private int currentTarget = -1; /** * The listener to UML model changes. * Deleted model elements are removed * from the history list. */ private Remover umlListener = new HistoryRemover(); /** * Default constructor that registrates the history manager as target * listener with the target manager. * */ private HistoryManager() { addTargetListener(this); } /** * Puts some target into the history (if needed). Updates both * the history as the pointer to indicate the target. * @param target The target to put into the history */ private void putInHistory(Object target) { if (currentTarget > -1) { // only targets we didn't have allready count Object theModelTarget = target instanceof Fig ? ((Fig) target).getOwner() : target; Object oldTarget = ((WeakReference) history.get(currentTarget)).get(); oldTarget = oldTarget instanceof Fig ? ((Fig) oldTarget).getOwner() : oldTarget; if (oldTarget == theModelTarget) { return; } } if (target != null && !navigateBackward) { if (currentTarget + 1 == history.size()) { umlListener.addListener(target); history.add(new WeakReference(target)); currentTarget++; resize(); } else { WeakReference ref = currentTarget > -1 ? (WeakReference) history.get(currentTarget) : null; if (currentTarget == -1 || !ref.get().equals(target)) { int size = history.size(); for (int i = currentTarget + 1; i < size; i++) { umlListener.removeListener( history.remove(currentTarget + 1)); } history.add(new WeakReference(target)); umlListener.addListener(target); currentTarget++; } } } } /** * Resizes the history if it's grown too big. * */ private void resize() { int size = history.size(); if (size > MAX_SIZE) { int oversize = size - MAX_SIZE; int halfsize = size / 2; if (currentTarget > halfsize && oversize < halfsize) { for (int i = 0; i < oversize; i++) { umlListener.removeListener( history.remove(0)); } currentTarget -= oversize; } } } /** * Navigate one target forward in history. Throws an * illegalstateException if not possible. * */ private void navigateForward() { if (currentTarget >= history.size() - 1) { throw new IllegalStateException( "NavigateForward is not allowed " + "since the targetpointer is pointing at " + "the upper boundary " + "of the history"); } setTarget(((WeakReference) history.get(++currentTarget)).get()); } /** * Navigate one step back in history. Throws an illegalstateexception if * not possible. * */ private void navigateBackward() { if (currentTarget == 0) { throw new IllegalStateException( "NavigateBackward is not allowed " + "since the targetpointer is pointing at " + "the lower boundary " + "of the history"); } navigateBackward = true; // If nothing selected, go to last selected target if (targets.size() == 0) { setTarget(((WeakReference) history.get(currentTarget)).get()); } else { setTarget(((WeakReference) history.get(--currentTarget)).get()); } navigateBackward = false; } /** * Checks if it's possible to navigate back. * * @return true if it's possible to navigate back. */ private boolean navigateBackPossible() { return currentTarget > 0; } /** * Checks if it's possible to navigate forward. * * @return true if it's possible to navigate forward */ private boolean navigateForwardPossible() { return currentTarget < history.size() - 1; } /** * Listener for additions of targets to the selected targets. * On addition of targets we put them in the history. * @see org.argouml.ui.targetmanager.TargetListener#targetAdded( * org.argouml.ui.targetmanager.TargetEvent) */ public void targetAdded(TargetEvent e) { Object[] addedTargets = e.getAddedTargets(); // we put the targets 'backwards' in the history // since the first target in the addedTargets array is // the first one selected. for (int i = addedTargets.length - 1; i >= 0; i--) { putInHistory(addedTargets[i]); } } /** * Listener for the removal of targets from the selection. * On removal of a target from the selection we do nothing * with respect to the history of targets. * @see org.argouml.ui.targetmanager.TargetListener#targetRemoved(org.argouml.ui.targetmanager.TargetEvent) */ public void targetRemoved(TargetEvent e) { } /** * Listener for the selection of a whole bunch of targets * in one go (or just one). Puts all the new * targets in the history starting with the 'newest' target. * @see org.argouml.ui.targetmanager.TargetListener#targetSet(org.argouml.ui.targetmanager.TargetEvent) */ public void targetSet(TargetEvent e) { Object[] newTargets = e.getNewTargets(); for (int i = newTargets.length - 1; i >= 0; i--) { putInHistory(newTargets[i]); } } /** * Cleans the history in total. * */ private void clean() { umlListener.removeAllListeners(history); history = new ArrayList(); currentTarget = -1; } private void removeHistoryTarget(Object o) { if (o instanceof Diagram) { Iterator it = ((Diagram) o).getEdges().iterator(); while (it.hasNext()) { removeHistoryTarget(it.next()); } it = ((Diagram) o).getNodes().iterator(); while (it.hasNext()) { removeHistoryTarget(it.next()); } } ListIterator it = history.listIterator(); while (it.hasNext()) { WeakReference ref = (WeakReference) it.next(); Object historyObject = ref.get(); if (Model.getFacade().isAModelElement(o)) { historyObject = historyObject instanceof Fig ? ((Fig) historyObject).getOwner() : historyObject; } if (o == historyObject) { if (history.indexOf(ref) <= currentTarget) { currentTarget--; } it.remove(); } // cannot break here since an object can be multiple // times in history } } } /** * The log4j logger to log messages to. */ private static final Logger LOG = Logger.getLogger(TargetManager.class.getName()); /** * The singleton instance. */ private static TargetManager instance = new TargetManager(); /** * The targets. */ private List targets = new ArrayList(); /** * Cache for the modeltarget. See getModelTarget. */ private Object modelTarget; /** * Cache for the figTarget. See getFigTarget. */ private Fig figTarget; /** * The list with targetlisteners. */ private EventListenerList listenerList = new EventListenerList(); /** * The history manager of argouml. Via the historymanager browser behaviour * is emulated. */ private HistoryManager historyManager = new HistoryManager(); /** * The listener to UML model changes. * Deleted model elements are removed * from the target list. */ private Remover umlListener = new TargetRemover(); /** * Flag to indicate that there is a setTarget method running. */ private boolean inTransaction = false; /** * Singleton retrieval method. * @return the targetmanager */ public static TargetManager getInstance() { return instance; } /** * Singleton constructor should remain private. */ private TargetManager() { } /** * Sets the targets to the single given object. If there are targets at the * moment of calling this method, these will be removed as targets. To * all interested targetlisteners, a TargetEvent will be fired. If the * new target o equals the current target, no events will be fired, nor will * the target be (re)set. * @param o The new target, null clears all targets. */ public synchronized void setTarget(Object o) { if (isInTargetTransaction()) { return; } if ((targets.size() == 0 && o == null) || (targets.size() == 1 && targets.get(0).equals(o))) { return; } startTargetTransaction(); Object[] oldTargets = targets.toArray(); umlListener.removeAllListeners(targets); targets.clear(); if (o != null) { Object newTarget; if (o instanceof Diagram) { // Needed for Argo startup :-( newTarget = o; } else { newTarget = getOwner(o); } targets.add(newTarget); umlListener.addListener(newTarget); } internalOnSetTarget(TargetEvent.TARGET_SET, oldTargets); endTargetTransaction(); } private void internalOnSetTarget(String eventName, Object[] oldTargets) { TargetEvent event = new TargetEvent(this, eventName, oldTargets, targets.toArray()); if (targets.size() > 0) { figTarget = determineFigTarget(targets.get(0)); modelTarget = determineModelTarget(targets.get(0)); } else { figTarget = null; modelTarget = null; } if (TargetEvent.TARGET_SET.equals(eventName)) { fireTargetSet(event); return; } else if (TargetEvent.TARGET_ADDED.equals(eventName)) { fireTargetAdded(event); return; } else if (TargetEvent.TARGET_REMOVED.equals(eventName)) { fireTargetRemoved(event); return; } LOG.log(Level.SEVERE, "Unknown eventName: " + eventName); } /** * Returns the current primary target, the first selected object. * * The value will be that of the new primary target during a targetSet/ * targetAdded/targetRemoved notification, since they are just that, * notifications that the target(s) has just changed. * * @return The current target, or null if no target is selected */ public synchronized Object getTarget() { return targets.size() > 0 ? targets.get(0) : null; } /** * Sets the given collection to the current targets. If the collection * equals the current targets, then does nothing. When setting * the targets, a TargetEvent will be fired to each interested listener. * Note that the first element returned by an Iterator on targetList * will be taken to be the primary target (see getTarget()), and that * an event will be fired also in case that that element would not equal * the element returned by getTarget(). * Note also that any nulls within the Collection will be ignored. * * @param targetsCollection The new targets list. */ public synchronized void setTargets(Collection targetsCollection) { Iterator ntarg; if (isInTargetTransaction()) { return; } Collection targetsList = new ArrayList(); if (targetsCollection != null) { targetsList.addAll(targetsCollection); } /* Remove duplicates and take care of getOwner() * and remove nulls: */ List modifiedList = new ArrayList(); Iterator it = targetsList.iterator(); while (it.hasNext()) { Object o = it.next(); o = getOwner(o); if ((o != null) && !modifiedList.contains(o)) { modifiedList.add(o); } } targetsList = modifiedList; Object[] oldTargets = null; // check if there are new elements in the list // if the old and new list are of the same size // set the oldTargets to the correct selection if (targetsList.size() == targets.size()) { boolean first = true; ntarg = targetsList.iterator(); while (ntarg.hasNext()) { Object targ = ntarg.next(); if (targ == null) { continue; } if (!targets.contains(targ) || (first && targ != getTarget())) { oldTargets = targets.toArray(); break; } first = false; } } else { oldTargets = targets.toArray(); } if (oldTargets == null) { return; } startTargetTransaction(); umlListener.removeAllListeners(targets); targets.clear(); // implement set-like behaviour. The same element // may not be added more then once. ntarg = targetsList.iterator(); while (ntarg.hasNext()) { Object targ = ntarg.next(); if (targets.contains(targ)) { continue; } targets.add(targ); umlListener.addListener(targ); } internalOnSetTarget(TargetEvent.TARGET_SET, oldTargets); endTargetTransaction(); } /** * Adds a target to the targets list. If the target is already in * the targets list then does nothing. Otherwise the * target will be added and an appropriate TargetEvent will be * fired to all interested listeners. Since null can never be a target, * adding null will never do anything. * @param target the target to be added. */ public synchronized void addTarget(Object target) { if (target instanceof TargetListener) { LOG.log(Level.WARNING, "addTarget method received a TargetListener, " + "perhaps addTargetListener was intended! - " + target); } if (isInTargetTransaction()) { return; } Object newTarget = getOwner(target); if (target == null || targets.contains(target) || targets.contains(newTarget)) { return; } startTargetTransaction(); Object[] oldTargets = targets.toArray(); targets.add(0, newTarget); umlListener.addListener(newTarget); internalOnSetTarget(TargetEvent.TARGET_ADDED, oldTargets); endTargetTransaction(); } /** * Removes the target from the targets list. Does nothing if the target * does not exist in the targets list. Fires an appropriate TargetEvent to * all interested listeners. Since null can never be a target, removing * null will never do anything. * @param target The target to remove. */ public synchronized void removeTarget(Object target) { if (isInTargetTransaction()) { return; } if (target == null /*|| !targets.contains(target)*/) { return; } startTargetTransaction(); Object[] oldTargets = targets.toArray(); Collection c = getOwnerAndAllFigs(target); // targets.remove(target); targets.removeAll(c); umlListener.removeAllListeners(c); if (targets.size() != oldTargets.length) { internalOnSetTarget(TargetEvent.TARGET_REMOVED, oldTargets); } endTargetTransaction(); } private Collection getOwnerAndAllFigs(Object o) { Collection c = new ArrayList(); c.add(o); if (o instanceof Fig) { if (((Fig) o).getOwner() != null) { o = ((Fig) o).getOwner(); c.add(o); } } if (!(o instanceof Fig)) { Project p = ProjectManager.getManager().getCurrentProject(); Collection col = p.findAllPresentationsFor(o); if (col != null && !col.isEmpty()) { c.addAll(col); } } return c; } /** * @param o the object * @return the owner of the fig, or if it didn't exist, the object itself */ public Object getOwner(Object o) { if (o instanceof Fig) { if (((Fig) o).getOwner() != null) { o = ((Fig) o).getOwner(); } } return o; } /** * Returns a list of all targets. Returns an empty list * if there are no targets. If there are several targets then the first * Object by an Iterator on the returned List or the zero'th Object * in an array on this List is guaranteed to be the object returned * by {@link #getSingleTarget()}. * * The value will be that of the new target(s) during a targetSet/ * targetAdded/targetRemoved notification, since they are just that, * notifications that the target(s) has just changed. * * @return A list with all targets. */ public synchronized List getTargets() { return Collections.unmodifiableList(targets); } /** * If there is only one target, then it is returned. * Otherwise null. * * @return the one and only target */ public synchronized Object getSingleTarget() { return targets.size() == 1 ? targets.get(0) : null; } /** * @return the target from the model */ public synchronized Collection getModelTargets() { ArrayList t = new ArrayList(); Iterator iter = getTargets().iterator(); while (iter.hasNext()) { t.add(determineModelTarget(iter.next())); } return t; } /** * If there is only one model target, then it is returned. * Otherwise null. * * @return the single model target */ public synchronized Object getSingleModelTarget() { int i = 0; Iterator iter = getTargets().iterator(); while (iter.hasNext()) { if (determineModelTarget(iter.next()) != null) { i++; } if (i > 1) { break; } } if (i == 1) { return modelTarget; } return null; } /** * Adds a listener. * @param listener the listener to add */ public void addTargetListener(TargetListener listener) { listenerList.add(TargetListener.class, listener); } /** * Removes a listener. * @param listener the listener to remove */ public void removeTargetListener(TargetListener listener) { listenerList.remove(TargetListener.class, listener); } private void fireTargetSet(TargetEvent targetEvent) { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { try { if (listeners[i] == TargetListener.class) { // Lazily create the event: ((TargetListener) listeners[i + 1]).targetSet(targetEvent); } } catch (RuntimeException e) { LOG.log(Level.SEVERE, "While calling targetSet for " + targetEvent + " in " + listeners[i + 1] + " an error is thrown.", e); e.printStackTrace(); } } } private void fireTargetAdded(TargetEvent targetEvent) { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { try { if (listeners[i] == TargetListener.class) { // Lazily create the event: ((TargetListener) listeners[i + 1]) .targetAdded(targetEvent); } } catch (RuntimeException e) { LOG.log(Level.SEVERE, "While calling targetAdded for " + targetEvent + " in " + listeners[i + 1] + " an error is thrown.", e); e.printStackTrace(); } } } private void fireTargetRemoved(TargetEvent targetEvent) { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { try { if (listeners[i] == TargetListener.class) { // Lazily create the event: ((TargetListener) listeners[i + 1]) .targetRemoved(targetEvent); } } catch (RuntimeException e) { LOG.log(Level.WARNING, "While calling targetRemoved for " + targetEvent + " in " + listeners[i + 1] + " an error is thrown.", e); } } } private void startTargetTransaction() { inTransaction = true; } private boolean isInTargetTransaction() { return inTransaction; } private void endTargetTransaction() { inTransaction = false; } /** * Convenience method to return the target as fig. If the current * target (retrieved by getTarget) is either a fig itself or the * owner of a fig this fig will be returned. Otherwise null will * be returned. * @return the target in it's 'fig-form' */ public Fig getFigTarget() { return figTarget; } /** * Calculates the most probable 'fig-form' of some target. Beware: * The result does NOT depend on the current diagram! * * @param target the target to calculate the 'fig-form' for. * @return The fig-form. */ private Fig determineFigTarget(Object target) { if (!(target instanceof Fig)) { Project p = ProjectManager.getManager().getCurrentProject(); Collection col = p.findFigsForMember(target); if (col == null || col.isEmpty()) { target = null; } else { target = col.iterator().next(); } } return target instanceof Fig ? (Fig) target : null; } /** * Returns the target in it's 'modelform'. If the target retrieved * by getTarget is an UMLDiagram or a UML element the target will * be returned. If the target is a fig but owned by a modelelement * that modelelement will be returned. Otherwise null will be * returned. * * @return the target in it's 'modelform'. */ public Object getModelTarget() { return modelTarget; } /** * Calculates the modeltarget. * @param target The target to calculate the modeltarget for * @return The modeltarget */ private Object determineModelTarget(Object target) { if (target instanceof Fig) { Object owner = ((Fig) target).getOwner(); if (Model.getFacade().isAUMLElement(owner)) { target = owner; } } return target instanceof Diagram || Model.getFacade().isAUMLElement(target) ? target : null; } /** * Navigates the target pointer one target forward. This implements together * with navigateBackward browser like functionality. * @throws IllegalStateException If the target pointer is at the end of the * history. */ public void navigateForward() throws IllegalStateException { historyManager.navigateForward(); LOG.log(Level.FINE, "Navigate forward"); } /** * Navigates the target pointer one target backward. This * implements together with navigateForward browser like * functionality * @throws IllegalStateException If the target pointer is at the * beginning of the history. */ public void navigateBackward() throws IllegalStateException { historyManager.navigateBackward(); LOG.log(Level.FINE, "Navigate backward"); } /** * Checks if it's possible to navigate forward. * @return true if it is possible to navigate forward. */ public boolean navigateForwardPossible() { return historyManager.navigateForwardPossible(); } /** * Checks if it's possible to navigate backward. * * @return true if it's possible to navigate backward */ public boolean navigateBackPossible() { return historyManager.navigateBackPossible(); } /** * Cleans the history. Needed for the JUnit tests and when instantiating a * new project. */ public void cleanHistory() { historyManager.clean(); } /** * @param o the object to be removed */ public void removeHistoryElement(Object o) { historyManager.removeHistoryTarget(o); } /** * The listener to removals of UML model elements, * diagrams and CommentEdges. * Deleted elements are removed * from the target list and/or from the history. * * @author michiel */ private abstract class Remover implements PropertyChangeListener, NotificationListener { protected Remover() { // Listen for the removal of diagrams from project ProjectManager.getManager().addPropertyChangeListener(this); } private void addListener(Object o) { if (Model.getFacade().isAModelElement(o)) { Model.getPump().addModelEventListener(this, o, "remove"); } else if (o instanceof Diagram) { // Figs on a diagram without an owning model element ((Diagram) o).addPropertyChangeListener(this); } else if (o instanceof NotificationEmitter) { // CommentEdge - the owner of a FigEdgeNote ((NotificationEmitter) o).addNotificationListener( this, null, o); } } private void removeListener(Object o) { if (Model.getFacade().isAModelElement(o)) { Model.getPump().removeModelEventListener(this, o, "remove"); } else if (o instanceof Diagram) { ((Diagram) o).removePropertyChangeListener(this); } else if (o instanceof NotificationEmitter) { try { ((NotificationEmitter) o).removeNotificationListener(this); } catch (ListenerNotFoundException e) { LOG.log(Level.SEVERE, "Notification Listener for CommentEdge not found", e); } } } private void removeAllListeners(Collection c) { Iterator i = c.iterator(); while (i.hasNext()) { removeListener(i.next()); } } /* * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent evt) { if ("remove".equals(evt.getPropertyName())) { remove(evt.getSource()); } } /* * @see javax.management.NotificationListener#handleNotification(javax.management.Notification, java.lang.Object) */ public void handleNotification(Notification notification, Object handback) { if ("remove".equals(notification.getType())) { remove(notification.getSource()); } } protected abstract void remove(Object obj); } private class TargetRemover extends Remover { protected void remove(Object obj) { removeTarget(obj); } } private class HistoryRemover extends Remover { protected void remove(Object obj) { historyManager.removeHistoryTarget(obj); } } }
33.009533
121
0.586999
6510b527c07fd9ed188a388d6787385067dafe78
1,542
package com.api.se.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "prova_aluno") public class ProvaAluno { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long idProva; @Column(nullable = false) private Long idAluno; @Column(nullable = false) private Long idProvaProfessor; @Column(nullable = false) private Integer[] respostas; @Column(nullable = false) private Integer[] pesosRespostas; private Double media; public ProvaAluno() { respostas = new Integer[10]; } public Long getIdAluno() { return idAluno; } public void setIdAluno(Long idAluno) { this.idAluno = idAluno; } public Long getIdProvaProfessor() { return idProvaProfessor; } public void setIdProvaProfessor(Long idProvaProfessor) { this.idProvaProfessor = idProvaProfessor; } public Long getIdProva() { return idProva; } public void setIdProva(Long idProva) { this.idProva = idProva; } public Integer[] getRespostas() { return respostas; } public Integer[] getPesosRespostas() { return pesosRespostas; } public void setPesosRespostas(Integer[] pesosRespostas) { this.pesosRespostas = pesosRespostas; } public void setRespostas(Integer[] respostas) { this.respostas = respostas; } public Double getMedia() { return media; } public void setMedia(Double media) { this.media = media; } }
18.141176
58
0.741894
5b363afaf882bae36ce1bee6d67bbd7b6652e89a
129
package soar.core; /** * Bridging * * @author xiuyuhang [xiuyuhang] * @since 2018-05-05 */ public final class Bridging { }
11.727273
32
0.651163
5f04ae1e9c6d257925e88f01b9d8f96217d8ef96
23,544
/* */ package jp.cssj.sakae.pdf.c; /* */ /* */ import java.awt.Font; /* */ import java.awt.GraphicsEnvironment; /* */ import java.io.File; /* */ import java.io.FileInputStream; /* */ import java.io.IOException; /* */ import java.io.InputStream; /* */ import java.io.RandomAccessFile; /* */ import java.net.URI; /* */ import java.net.URISyntaxException; /* */ import java.util.ArrayList; /* */ import java.util.Collection; /* */ import java.util.HashMap; /* */ import java.util.List; /* */ import java.util.Map; /* */ import java.util.Set; /* */ import java.util.StringTokenizer; /* */ import java.util.TreeSet; /* */ import java.util.logging.Level; /* */ import java.util.logging.Logger; /* */ import jp.cssj.e.b; /* */ import jp.cssj.e.c; /* */ import jp.cssj.e.e.d; /* */ import jp.cssj.sakae.a.g; /* */ import jp.cssj.sakae.a.i; /* */ import jp.cssj.sakae.c.a.b; /* */ import jp.cssj.sakae.c.a.c; /* */ import jp.cssj.sakae.c.a.k; /* */ import jp.cssj.sakae.pdf.b; /* */ import jp.cssj.sakae.pdf.c.a.f; /* */ import jp.cssj.sakae.pdf.c.b.d; /* */ import jp.cssj.sakae.pdf.c.b.f; /* */ import org.xml.sax.Attributes; /* */ import org.xml.sax.SAXException; /* */ import org.xml.sax.helpers.DefaultHandler; /* */ /* */ /* */ class h /* */ extends DefaultHandler /* */ { /* 42 */ private static final Logger d = Logger.getLogger(h.class.getName()); /* */ /* */ private final URI e; /* */ /* */ private final c f; /* */ /* */ private static final byte g = 0; /* */ /* */ private static final byte h = 1; /* */ /* */ private static final byte i = 2; /* */ /* */ private static final byte j = 3; /* */ /* */ private static final byte k = 5; /* */ /* */ private static final byte l = 6; /* */ /* 60 */ private byte m = 0; /* */ /* */ private a[] n; /* */ /* */ private f o; /* */ /* 66 */ private final Map<String, d> p = new HashMap<>(); /* */ /* */ private d q; /* */ /* 70 */ private final Map<String, f> r = new HashMap<>(); /* */ /* 72 */ final Map<String, Object> a = new HashMap<>(); /* */ /* 74 */ final Map<String, c> b = new HashMap<>(); /* */ /* 76 */ final Collection<g> c = new ArrayList<>(); /* */ /* */ h(URI base) throws IOException { /* 79 */ this.e = base; /* 80 */ this.f = (c)jp.cssj.e.b.a.a(); /* */ } /* */ /* */ private File a(String src) throws SAXException { /* */ try { /* 85 */ b source = this.f.b(d.a("UTF-8", this.e, src)); /* */ try { /* 87 */ return source.l(); /* */ } finally { /* 89 */ this.f.a(source); /* */ } /* 91 */ } catch (IOException e) { /* 92 */ throw new SAXException(e); /* 93 */ } catch (URISyntaxException e) { /* 94 */ throw new SAXException(e); /* */ } } public void startElement(String uri, String lName, String qName, Attributes atts) throws SAXException { String genericFamily; String fontFamily; /* */ List<b> entries; /* */ StringTokenizer i; /* */ c family; /* 99 */ switch (this.m) { /* */ case 0: /* 101 */ if (qName.equals("encodings")) { /* */ /* */ /* 104 */ this.m = 1; break; /* 105 */ } if (qName.equals("core-fonts")) { /* */ /* 107 */ String encoding = atts.getValue("encoding"); /* 108 */ String unicodeSrc = atts.getValue("unicode-src"); /* */ /* 110 */ this.q = this.p.get(encoding); /* */ /* */ try { /* 113 */ b source = this.f.b(d.a("UTF-8", this.e, unicodeSrc)); /* */ try { /* 115 */ this.o = f.a(source.h()); /* */ } finally { /* 117 */ this.f.a(source); /* */ } /* 119 */ } catch (IOException e) { /* 120 */ throw new SAXException(e); /* 121 */ } catch (URISyntaxException e) { /* 122 */ throw new SAXException(e); /* */ } /* 124 */ this.m = 2; break; /* 125 */ } if (qName.equals("cmaps")) { /* */ /* */ /* 128 */ this.m = 3; break; /* 129 */ } if (qName.equals("cid-fonts")) { /* */ /* 131 */ this.m = 5; break; /* 132 */ } if (qName.equals("generic-fonts")) /* */ { /* 134 */ this.m = 6; /* */ } /* */ break; /* */ case 1: /* 138 */ if (qName.equals("encoding")) { /* */ /* 140 */ String src = atts.getValue("src"); /* 141 */ b source = null; /* */ try { /* 143 */ source = this.f.b(d.a("UTF-8", this.e, src)); /* 144 */ d encoding = d.a(source.h()); /* 145 */ this.p.put(encoding.a, encoding); /* 146 */ } catch (IOException e) { /* 147 */ throw new SAXException(e); /* 148 */ } catch (URISyntaxException e) { /* 149 */ throw new SAXException(e); /* */ } finally { /* 151 */ if (source != null) { /* 152 */ this.f.a(source); /* */ } /* */ } /* */ } /* */ break; /* */ /* */ case 2: /* 159 */ if (qName.equals("letter-font")) { /* */ /* 161 */ String src = atts.getValue("src"); /* 162 */ b source = null; try { /* */ d pdfEncoding; /* 164 */ source = this.f.b(d.a("UTF-8", this.e, src)); /* */ /* */ /* 167 */ String encoding = atts.getValue("encoding"); /* 168 */ if (encoding != null) { /* 169 */ pdfEncoding = this.p.get(encoding); /* */ } else { /* 171 */ pdfEncoding = this.q; /* */ } /* */ /* 174 */ this /* 175 */ .n = new a[] { new a(b.a(this.o, pdfEncoding, source.h())) }; /* 176 */ } catch (Exception e) { /* 177 */ d.log(Level.SEVERE, "AFMファイル'" + src + "'を読み込めません。", e); /* 178 */ throw new SAXException(e); /* */ } finally { /* 180 */ if (source != null) /* 181 */ this.f.a(source); /* */ } /* */ break; /* */ } /* 185 */ if (qName.equals("symbol-font")) { /* */ /* 187 */ String src = atts.getValue("src"); /* 188 */ b source = null, encodingSource = null; /* */ try { /* 190 */ source = this.f.b(d.a("UTF-8", this.e, src)); /* */ /* 192 */ String encodingSrc = atts.getValue("encoding-src"); /* 193 */ encodingSource = this.f.b(d.a("UTF-8", this.e, encodingSrc)); /* */ /* 195 */ this /* 196 */ .n = new a[] { new a(b.a(source.h(), encodingSource)) }; /* 197 */ } catch (Exception e) { /* 198 */ d.log(Level.SEVERE, "AFMファイル'" + src + "'を読み込めません。", e); /* 199 */ throw new SAXException(e); /* */ } finally { /* 201 */ if (source != null) { /* 202 */ this.f.a(source); /* */ } /* 204 */ if (encodingSource != null) { /* 205 */ this.f.a(encodingSource); /* */ } /* */ } /* */ } /* */ break; /* */ /* */ case 3: /* 212 */ if (qName.equals("cmap")) { /* */ /* 214 */ String src = atts.getValue("src"); /* 215 */ String javaEncoding = atts.getValue("java-encoding"); /* */ try { /* 217 */ b source = this.f.b(d.a("UTF-8", this.e, src)); /* 218 */ f cmap = new f(source, javaEncoding); /* 219 */ this.r.put(cmap.b(), cmap); /* 220 */ } catch (Exception e) { /* 221 */ d.log(Level.SEVERE, "CMapファイル'" + src + "'を読み込めません", e); /* 222 */ throw new SAXException(e); /* */ } /* */ } /* */ break; /* */ /* */ case 5: /* 228 */ if (qName.equals("cid-keyed-font")) { /* 229 */ String warraySrc = atts.getValue("warray"); /* 230 */ b source = null; /* */ try { /* 232 */ source = this.f.b(d.a("UTF-8", this.e, warraySrc)); /* */ /* 234 */ jp.cssj.sakae.c.a.a face = b.a(atts); /* 235 */ f[] sources = b.a(source, face, this.r); /* 236 */ this.n = new a[sources.length]; /* 237 */ for (int j = 0; j < sources.length; j++) { /* 238 */ this.n[j] = new a(sources[j]); /* */ } /* 240 */ } catch (Exception e) { /* 241 */ d.log(Level.SEVERE, "'" + source.d() + "'の読み込みに失敗しました。", e); /* 242 */ throw new SAXException(e); /* */ } finally { /* 244 */ if (source != null) /* 245 */ this.f.a(source); /* */ } break; /* */ } /* 248 */ if (qName.equals("font-file")) { /* 249 */ String src = atts.getValue("src"); /* 250 */ String types = atts.getValue("types"); /* */ try { /* */ int index; /* 253 */ File ttfFile = a(src); /* */ /* */ try { /* 256 */ index = Integer.parseInt(atts.getValue("index")); /* 257 */ } catch (Exception e) { /* 258 */ index = 0; /* */ } /* */ /* 261 */ List<g> list = new ArrayList<>(); /* 262 */ jp.cssj.sakae.c.a.a face = b.a(atts); /* */ /* 264 */ if (types.indexOf("cid-keyed") != -1) { /* 265 */ b.a(list, face, (byte)3, ttfFile, index, this.r); /* */ } /* 267 */ if (types.indexOf("cid-identity") != -1) { /* 268 */ b.a(list, face, (byte)2, ttfFile, index, this.r); /* */ } /* 270 */ if (types.indexOf("embedded") != -1) { /* 271 */ b.a(list, face, (byte)1, ttfFile, index, this.r); /* */ } /* 273 */ this.n = new a[list.size()]; /* 274 */ for (int j = 0; j < list.size(); j++) { /* 275 */ this.n[j] = new a((f)list.get(j)); /* */ } /* */ } /* 278 */ catch (Exception e) { /* 279 */ d.log(Level.WARNING, "'" + src + "'のフォント情報の取得に失敗しました。", e); /* 280 */ this.n = null; /* */ } break; /* 282 */ } if (qName.equals("font-dir")) { /* 283 */ String dir = atts.getValue("dir"); /* 284 */ String types = atts.getValue("types"); /* */ /* 286 */ File dirFile = a(dir); /* 287 */ if (d.isLoggable(Level.FINE)) { /* 288 */ d.fine("scan: " + dirFile); /* */ } /* 290 */ File[] files = dirFile.listFiles(); /* 291 */ if (files != null) { /* 292 */ jp.cssj.sakae.c.a.a face = b.a(atts); /* 293 */ for (int j = 0; j < files.length; j++) { /* 294 */ File ttfFile = files[j]; /* 295 */ if (!ttfFile.isDirectory()) { /* */ /* */ /* 298 */ String name = ttfFile.getName().toLowerCase(); /* 299 */ if (name.endsWith(".ttf") || name.endsWith(".ttc") || name.endsWith(".otf") || name /* 300 */ .endsWith(".woff")) /* */ /* */ /* */ try { /* 304 */ List<g> list = new ArrayList<>(); /* */ /* 306 */ int numFonts = 1; /* 307 */ try (RandomAccessFile raf = new RandomAccessFile(ttfFile, "r")) { /* 308 */ byte[] tagBytes = new byte[4]; /* 309 */ raf.readFully(tagBytes); /* 310 */ String tag = new String(tagBytes, "ISO-8859-1"); /* 311 */ if ("ttcf".equals(tag)) { /* */ /* 313 */ raf.skipBytes(4); /* 314 */ numFonts = raf.readInt(); /* */ } /* */ } /* */ int k; /* 318 */ for (k = 0; k < numFonts; k++) { /* 319 */ if (types.indexOf("cid-identity") != -1) { /* 320 */ b.a(list, face, (byte)2, ttfFile, k, this.r); /* */ } /* */ /* 323 */ if (types.indexOf("embedded") != -1) { /* 324 */ b.a(list, face, (byte)1, ttfFile, k, this.r); /* */ } /* */ } /* */ /* 328 */ this.c.addAll(list); /* 329 */ for (k = 0; k < list.size(); k++) { /* 330 */ b.a(new a((f)list.get(k)), this.a); /* */ } } /* 332 */ catch (Exception e) /* 333 */ { d.log(Level.WARNING, "'" + ttfFile + "'のフォント情報の取得に失敗しました。", e); } /* */ } /* */ } /* */ } break; /* 337 */ } if (qName.equals("system-font")) { /* 338 */ String src = atts.getValue("src"); /* 339 */ String file = atts.getValue("file"); /* 340 */ String dir = atts.getValue("dir"); /* 341 */ String types = atts.getValue("types"); /* */ /* 343 */ List<g> list = new ArrayList<>(); /* 344 */ jp.cssj.sakae.c.a.a face = b.a(atts); /* */ /* */ try { /* 347 */ if (file != null) { /* 348 */ File theFile = a(file); /* 349 */ try (InputStream in = new FileInputStream(theFile)) { /* 350 */ Font font = Font.createFont(0, in); /* 351 */ b.a(face, list, types, font, this.r); /* */ } /* 353 */ } else if (dir != null) { /* 354 */ File theDir = a(dir); /* 355 */ File[] files = theDir.listFiles(); /* 356 */ for (int j = 0; j < files.length; j++) { /* 357 */ File theFile = files[j]; /* 358 */ String name = theFile.getName().toLowerCase(); /* 359 */ if (name.endsWith(".ttf") || name.endsWith(".ttc") || name.endsWith(".otf") || name /* 360 */ .endsWith(".woff")) { /* 361 */ try (InputStream in = new FileInputStream(theFile)) { /* 362 */ Font font = Font.createFont(0, in); /* 363 */ b.a(face, list, types, font, this.r); /* */ } /* */ } /* */ } /* */ } else { /* 368 */ Font font = Font.decode(src); /* 369 */ b.a(face, list, types, font, this.r); /* */ } /* 371 */ this.n = list.<a>toArray(new a[list.size()]); /* 372 */ } catch (Exception e) { /* 373 */ d.log(Level.WARNING, "'" + src + "'のフォント情報の取得に失敗しました。", e); /* 374 */ this.n = null; /* */ } break; /* 376 */ } if (qName.equals("all-system-fonts")) { /* 377 */ Font[] fonts; String types = atts.getValue("types"); /* 378 */ String dir = atts.getValue("dir"); /* */ /* */ /* 381 */ if (dir != null) { /* 382 */ File dirFile = a(dir); /* 383 */ File[] files = dirFile.listFiles(); /* 384 */ List<Font> fontList = new ArrayList<>(); /* 385 */ for (int k = 0; k < files.length; k++) { /* */ /* 387 */ try (InputStream in = new FileInputStream(files[k])) { /* 388 */ fontList.add(Font.createFont(0, in)); /* */ } /* 390 */ catch (Exception e) { /* 391 */ d.log(Level.WARNING, "フォントファイルを読み込めません", e); /* */ } /* */ } /* 394 */ fonts = fontList.<Font>toArray(new Font[fontList.size()]); /* */ } else { /* 396 */ fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); /* */ } /* 398 */ jp.cssj.sakae.c.a.a face = b.a(atts); /* 399 */ for (int j = 0; j < fonts.length; j++) { /* 400 */ Font font = fonts[j]; /* */ try { /* 402 */ if (types.indexOf("cid-keyed") != -1) { /* */ /* 404 */ a fontSource = new a(b.a(face, (byte)3, font, this.r)); /* 405 */ this.c.add(fontSource); /* 406 */ b.a(fontSource, this.a); /* */ } /* 408 */ if (types.indexOf("cid-identity") != -1) { /* 409 */ a fontSource = new a(b.a(face, (byte)2, font, this.r)); /* */ /* 411 */ this.c.add(fontSource); /* 412 */ b.a(fontSource, this.a); /* */ } /* 414 */ if (types.indexOf("embedded") != -1) { /* */ /* 416 */ a fontSource = new a(b.a(face, (byte)1, font, this.r)); /* 417 */ this.c.add(fontSource); /* 418 */ b.a(fontSource, this.a); /* */ } /* 420 */ } catch (Exception e) { /* 421 */ d.log(Level.WARNING, "'" + font.getFontName() + "'のフォント情報の取得に失敗しました。", e); /* */ } /* */ } /* */ } /* */ break; /* */ /* */ case 6: /* 428 */ genericFamily = lName; /* 429 */ fontFamily = atts.getValue("font-family"); /* */ /* 431 */ entries = new ArrayList<>(); /* 432 */ for (i = new StringTokenizer(fontFamily, ","); i.hasMoreTokens(); ) { /* 433 */ b entry = new b(i.nextToken()); /* 434 */ entries.add(entry); /* */ } /* */ /* 437 */ family = new c(entries.<b>toArray(new b[entries.size()])); /* 438 */ this.b.put(genericFamily, family); /* */ break; /* */ } /* 441 */ if (this.n != null) { /* 442 */ if (qName.equals("alias")) { /* */ /* 444 */ String name = atts.getValue("name"); /* 445 */ for (int j = 0; j < this.n.length; j++) { /* 446 */ this.n[j].a(name); /* */ } /* 448 */ } else if (qName.equals("include")) { /* 449 */ String unicodeRange = atts.getValue("unicode-range"); /* 450 */ for (StringTokenizer st = new StringTokenizer(unicodeRange, ","); st.hasMoreTokens(); ) { /* 451 */ k range = k.a(st.nextToken()); /* 452 */ for (int j = 0; j < this.n.length; j++) { /* 453 */ this.n[j].a(range); /* */ } /* */ } /* 456 */ } else if (qName.equals("exclude")) { /* 457 */ String unicodeRange = atts.getValue("unicode-range"); /* 458 */ for (StringTokenizer st = new StringTokenizer(unicodeRange, ","); st.hasMoreTokens(); ) { /* 459 */ k range = k.a(st.nextToken()); /* 460 */ for (int j = 0; j < this.n.length; j++) { /* 461 */ this.n[j].b(range); /* */ } /* */ } /* */ } /* */ } } /* */ /* */ /* */ public void endElement(String uri, String lName, String qName) throws SAXException { /* 469 */ if (qName.equals("letter-font") || qName.equals("symbol-font") || qName.equals("cid-keyed-font") || qName /* 470 */ .equals("font-file") || qName.equals("system-font")) { /* 471 */ if (this.n == null) { /* 472 */ throw new SAXException(qName); /* */ } /* 474 */ for (int i = 0; i < this.n.length; i++) { /* 475 */ this.c.add(this.n[i]); /* 476 */ b.a(this.n[i], this.a); /* */ } /* 478 */ this.n = null; /* 479 */ } else if (qName.equals("encodings") || qName.equals("core-fonts") || qName.equals("cmaps") || qName /* 480 */ .equals("cid-fonts") || qName.equals("generic-fonts")) { /* 481 */ if (this.n != null) { /* 482 */ throw new SAXException(qName); /* */ } /* 484 */ this.m = 0; /* */ } /* */ } /* */ /* */ private static class a /* */ extends i implements f { /* */ private static final long j = 1L; /* 491 */ protected final List<String> f = new ArrayList<>(); /* */ /* 493 */ protected final List<k> g = new ArrayList<>(); /* */ /* 495 */ protected final List<k> i = new ArrayList<>(); /* */ /* 497 */ private transient String[] k = null; /* */ /* */ public a(f source) { /* 500 */ super(source); /* */ } /* */ /* */ public final synchronized void a(String aliase) { /* 504 */ this.f.add(aliase); /* */ } /* */ /* */ public final synchronized void a(k range) { /* 508 */ this.g.add(range); /* */ } /* */ /* */ public final synchronized void b(k range) { /* 512 */ this.i.add(range); /* */ } /* */ /* */ public String[] a() { /* 516 */ String[] aliases = this.W_.a(); /* 517 */ int count = aliases.length + this.f.size(); /* 518 */ if (this.k == null || this.k.length != count) { /* 519 */ Set<String> result = new TreeSet<>(); /* 520 */ for (int j = 0; j < aliases.length; j++) { /* 521 */ result.add(aliases[j]); /* */ } /* 523 */ result.addAll(this.f); /* 524 */ this.k = result.<String>toArray(new String[result.size()]); /* */ } /* 526 */ return this.k; /* */ } /* */ /* */ public boolean a(int c) { /* 530 */ if (!this.i.isEmpty()) { /* 531 */ for (int j = 0; j < this.i.size(); j++) { /* 532 */ k range = this.i.get(j); /* 533 */ if (range.a(c)) { /* 534 */ return false; /* */ } /* */ } /* */ } /* 538 */ if (!this.g.isEmpty()) { /* 539 */ for (int j = 0; j < this.g.size(); j++) { /* 540 */ k range = this.g.get(j); /* 541 */ if (range.a(c)) { /* 542 */ return this.W_.a(c); /* */ } /* */ } /* 545 */ return false; /* */ } /* 547 */ return this.W_.a(c); /* */ } /* */ /* */ public e a(String name, b fontRef) { /* 551 */ return ((f)this.W_).a(name, fontRef); /* */ } /* */ /* */ public byte h_() { /* 555 */ return ((f)this.W_).h_(); /* */ } /* */ } /* */ } /* Location: /mnt/r/ConTenDoViewer.jar!/jp/cssj/sakae/pdf/c/h.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
41.744681
163
0.393136
7e2f9b661eaa0b9aff9d27181673e0584597da65
2,174
package gaurav.com.mvpexample.ui.main; import gaurav.com.mvpexample.managers.DataManager; /** * Created by gaurav on 11/6/17. */ class MainPresenter { private MainViewInterface viewInterface; private DataManager dataManager; private MainState state; MainPresenter(DataManager dataManager) { this.dataManager = dataManager; // initiate state with a default value for the initial UI of this view. state = new MainState("This is the template name"); } /** * Called when the UI became visible in onResume, thus we save the interface object and * update the UI with the cached state */ void attachView(MainViewInterface viewInterface) { this.viewInterface = viewInterface; viewInterface.updateUI(state); } /** * Called when the UI became invisible, thus we set the interface object to null * as we can't dispatch more UI updates but we keep our state object up to date * with the model changes and will update the UI when it attaches again. */ void detachView() { this.viewInterface = null; } /* * Logic functions * */ void submitName(String name) { // Logic for checking that the name being saved isn't empty. if (name.trim().equals("")) { state.setCommand(MainState.MainViewCommand.SHOW_ERROR_TOAST); viewInterface.updateUI(state); return; } // Save the name in the model with DataManager acting as an interface. dataManager.saveName(name); /* Update the UI according to the response from model. None in this case. */ state.setCommand(MainState.MainViewCommand.SHOW_NAME); state.setName(name); viewInterface.updateUI(state); } void clearName() { // Clear the name in the model with DataManager acting as an interface. dataManager.saveName(null); /* Update the UI according to the response from model. None in this case. */ state.setCommand(MainState.MainViewCommand.CLEAR_NAME); viewInterface.updateUI(state); } }
30.194444
91
0.645354
b3bde08b5891366d5a0b1b79c2110c4dbb116847
1,929
package org.innovateuk.ifs.management.competition.setup.fundinglevelpercentage.populator; import org.innovateuk.ifs.category.resource.ResearchCategoryResource; import org.innovateuk.ifs.category.service.CategoryRestService; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.competition.resource.CompetitionSetupSection; import org.innovateuk.ifs.finance.resource.OrganisationSize; import org.innovateuk.ifs.management.competition.setup.core.populator.CompetitionSetupSectionModelPopulator; import org.innovateuk.ifs.management.competition.setup.core.viewmodel.CompetitionSetupViewModel; import org.innovateuk.ifs.management.competition.setup.core.viewmodel.GeneralSetupViewModel; import org.innovateuk.ifs.management.competition.setup.fundinglevelpercentage.viewmodel.FundingLevelPercentageViewModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors; import static java.util.Arrays.asList; @Service public class FundingLevelPercentageViewModelPopulator implements CompetitionSetupSectionModelPopulator { @Autowired private CategoryRestService categoryRestService; @Override public CompetitionSetupSection sectionToPopulateModel() { return CompetitionSetupSection.FUNDING_LEVEL_PERCENTAGE; } @Override public CompetitionSetupViewModel populateModel(GeneralSetupViewModel generalViewModel, CompetitionResource competition) { List<ResearchCategoryResource> allResearchCategories = categoryRestService.getResearchCategories().getSuccess(); return new FundingLevelPercentageViewModel(generalViewModel, allResearchCategories.stream().filter(cat -> competition.getResearchCategories().contains(cat.getId())).collect(Collectors.toList()), asList(OrganisationSize.values())); } }
49.461538
149
0.833074
43e40d379ca3fcb0e9617a6c16d0621746e13292
2,205
package com.houxy.days.base; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.houxy.days.base.i.OnItemClickListener; import com.houxy.days.base.i.OnItemLongClickListener; import butterknife.ButterKnife; /** * Created by Houxy on 2016/9/12. * * Info : holder的基类 */ public class BaseViewHolder<T> extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{ private OnItemClickListener onItemClickListener; private OnItemLongClickListener onItemLongClickListener; public BaseViewHolder(Context context, ViewGroup root, int res) { super(LayoutInflater.from(context).inflate(res, root, false)); ButterKnife.bind(this, itemView); } public BaseViewHolder(Context context, ViewGroup root, int res, OnItemClickListener onItemClickListener) { super(LayoutInflater.from(context).inflate(res, root, false)); ButterKnife.bind(this, itemView); this.onItemClickListener = onItemClickListener; itemView.setOnClickListener(this); } public BaseViewHolder(Context context, ViewGroup root, int res, OnItemClickListener onItemClickListener, OnItemLongClickListener onItemLongClickListener) { super(LayoutInflater.from(context).inflate(res, root, false)); ButterKnife.bind(this, itemView); this.onItemClickListener = onItemClickListener; this.onItemLongClickListener = onItemLongClickListener; itemView.setOnClickListener(this); itemView.setOnLongClickListener(this); } public void bindData(){} public void bindData(T t){} public Context getContext() { return itemView.getContext(); } @Override public void onClick(View v) { if (onItemClickListener != null){ onItemClickListener.onItemClick(getAdapterPosition()); } } @Override public boolean onLongClick(View v) { if (onItemLongClickListener != null){ onItemLongClickListener.onItemLongClick(getAdapterPosition()); } return true; } }
32.426471
121
0.71746
0899268d39ae758386b3aa4168899f1ec7007dbb
5,006
package io.atleon.rabbitmq; import com.rabbitmq.client.Address; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.ConnectionFactoryConfigurator; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; /** * ConnectionFactory extension with support for multiple hosts and instantiation via properties. * Configuration properties are the same ones defined by {@link ConnectionFactoryConfigurator} */ public class AloConnectionFactory extends ConnectionFactory { /** * Comma-separated list of host[:port] pairs */ public static final String HOSTS = "hosts"; /** * Alias for {@link ConnectionFactoryConfigurator#VIRTUAL_HOST} */ public static final String VHOST = "vhost"; /** * Configuration for ssl. Can be set to {@link AloConnectionFactory#DISABLED} or protocol */ public static final String SSL = "ssl"; public static final String DISABLED = "disabled"; private final List<Address> addresses; public AloConnectionFactory(List<Address> addresses) { this.addresses = addresses; } public static AloConnectionFactory from(Map<String, ?> properties) { List<Address> addresses = extractAddresses(properties); Map<String, String> configuratorProperties = createConfiguratorProperties(properties); // Remove Host and Port configuration since we handle addresses manually configuratorProperties.remove(ConnectionFactoryConfigurator.HOST); configuratorProperties.remove(ConnectionFactoryConfigurator.PORT); AloConnectionFactory connectionFactory = new AloConnectionFactory(addresses); ConnectionFactoryConfigurator.load(connectionFactory, configuratorProperties, ""); return connectionFactory; } @Override public Connection newConnection() throws IOException, TimeoutException { return newConnection(addresses); } @Override public Connection newConnection(String connectionName) throws IOException, TimeoutException { return newConnection(addresses, connectionName); } @Override public Connection newConnection(ExecutorService executor) throws IOException, TimeoutException { return newConnection(executor, addresses); } @Override public Connection newConnection(ExecutorService executor, String connectionName) throws IOException, TimeoutException { return newConnection(executor, addresses, connectionName); } @Override public String getHost() { return addresses.get(0).getHost(); } @Override public void setHost(String host) { throw new UnsupportedOperationException("Cannot set host on multi-address ConnectionFactory"); } @Override public int getPort() { return addresses.get(0).getPort(); } @Override public void setPort(int port) { throw new UnsupportedOperationException("Cannot set port on multi-address ConnectionFactory"); } private static List<Address> extractAddresses(Map<String, ?> properties) { String hosts = extractHosts(properties); int fallbackPort = Optional.<Object>ofNullable(properties.get(ConnectionFactoryConfigurator.PORT)) .map(port -> Integer.parseInt(port.toString())) .orElse(USE_DEFAULT_PORT); return Arrays.stream(Address.parseAddresses(hosts)) .map(address -> address.getPort() == USE_DEFAULT_PORT && fallbackPort != USE_DEFAULT_PORT ? new Address(address.getHost(), fallbackPort) : address) .collect(Collectors.toList()); } private static String extractHosts(Map<String, ?> properties) { Object host = properties.get(ConnectionFactoryConfigurator.HOST); return Objects.toString(host == null ? properties.get(HOSTS) : host, DEFAULT_HOST); } private static Map<String, String> createConfiguratorProperties(Map<String, ?> properties) { Map<String, String> configuration = properties.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, entry -> Objects.toString(entry.getValue()))); if (!configuration.containsKey(ConnectionFactoryConfigurator.VIRTUAL_HOST) && configuration.containsKey(VHOST)) { configuration.put(ConnectionFactoryConfigurator.VIRTUAL_HOST, configuration.remove(VHOST)); } String ssl = configuration.getOrDefault(SSL, DISABLED); if (!configuration.containsKey(ConnectionFactoryConfigurator.SSL_ENABLED) && !ssl.equals(DISABLED)) { configuration.put(ConnectionFactoryConfigurator.SSL_ENABLED, "true"); configuration.put(ConnectionFactoryConfigurator.SSL_ALGORITHM, ssl); } return configuration; } }
37.639098
123
0.721534
1d1bfb572fe1c68878674aefabef347c8d3691de
6,556
package com.hunonic.funsdkdemo.devices.settings; import android.os.Bundle; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import com.hunonic.funsdkdemo.ActivityDemo; import com.hunonic.funsdkdemo.R; import com.lib.FunSDK; import com.lib.IFunSDKResult; import com.lib.MsgContent; import com.lib.funsdk.support.FunError; import com.lib.funsdk.support.FunLog; import com.lib.funsdk.support.FunSupport; import com.lib.funsdk.support.models.FunDevice; import org.json.JSONException; import org.json.JSONObject; /** * Created by niutong on 2017-05-31. * Discription: */ public class ActivityGuideDeviceDevFrontCtr extends ActivityDemo implements View.OnClickListener, IFunSDKResult { private Button mBtnOk; private Button mBtnEsc; private Button mBtnMenu; private Button mBtnLeft; private Button mBtnRight; private Button mBtnUp; private Button mBtnDown; private TextView mTitle; private ImageButton mBack; private FunDevice mFunDevice; private final String TAG = "ActivityGuideDeviceDevFrontCtr"; private int mHandler; enum NetKeyBoardValue{ NET_KEY_UP("Up"), NET_DOWN("Down"), NET_LEFT("Left"), NET_RIGHT("Right"), NET_KEY_PGUP("PageUp"), NET_KEY_PGDN("PageDown"), NET_KEY_RET("Enter"), NET_KEY_ESC("Esc"), NET_KEY_MENU("Menu"); String value; private NetKeyBoardValue(String value){ this.value = value; } public String getValue() { return value; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_device_setup_devfrontctr); initView(); int Sn = getIntent().getIntExtra("FUN_DEVICE_ID", 0); mFunDevice = FunSupport.getInstance().findDeviceById(Sn); mHandler = FunSDK.RegUser(this); } private void initView(){ mTitle = (TextView) findViewById(R.id.textViewInTopLayout); mTitle.setText(R.string.device_setup_frontctr); mBack = (ImageButton) findViewById(R.id.backBtnInTopLayout); mBack.setOnClickListener(this); mBtnOk = (Button) findViewById(R.id.btn_ok); mBtnOk.setOnClickListener(this); mBtnEsc = (Button) findViewById(R.id.btn_esc); mBtnEsc.setOnClickListener(this); mBtnMenu = (Button) findViewById(R.id.btn_menu); mBtnMenu.setOnClickListener(this); mBtnLeft = (Button) findViewById(R.id.btn_left); mBtnLeft.setOnClickListener(this); mBtnRight = (Button) findViewById(R.id.btn_right); mBtnRight.setOnClickListener(this); mBtnUp = (Button) findViewById(R.id.btn_up); mBtnUp.setOnClickListener(this); mBtnDown = (Button) findViewById(R.id.btn_down); mBtnDown.setOnClickListener(this); } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.btn_ok) { String jsonokdown = getJson(NetKeyBoardValue.NET_KEY_RET.getValue(), "KeyDown"); doOperate(jsonokdown); String jsonokup = getJson(NetKeyBoardValue.NET_KEY_RET.getValue(), "KeyUp"); doOperate(jsonokup); } else if (id == R.id.btn_esc) { String jsonescdown = getJson(NetKeyBoardValue.NET_KEY_ESC.getValue(), "KeyDown"); doOperate(jsonescdown); String jsonescup = getJson(NetKeyBoardValue.NET_KEY_ESC.getValue(), "KeyUp"); doOperate(jsonescup); } else if (id == R.id.btn_menu) { String jsonmenudown = getJson(NetKeyBoardValue.NET_KEY_MENU.getValue(), "KeyDown"); doOperate(jsonmenudown); String jsonmenuup = getJson(NetKeyBoardValue.NET_KEY_MENU.getValue(), "KeyUp"); doOperate(jsonmenuup); } else if (id == R.id.btn_left) { String jsonleftdown = getJson(NetKeyBoardValue.NET_LEFT.getValue(), "KeyDown"); doOperate(jsonleftdown); String jsonleftup = getJson(NetKeyBoardValue.NET_LEFT.getValue(), "KeyUp"); doOperate(jsonleftup); } else if (id == R.id.btn_right) { String jsonrightdown = getJson(NetKeyBoardValue.NET_RIGHT.getValue(), "KeyDown"); doOperate(jsonrightdown); String jsonrightup = getJson(NetKeyBoardValue.NET_RIGHT.getValue(), "KeyUp"); doOperate(jsonrightup); } else if (id == R.id.btn_up) { String jsonupdown = getJson(NetKeyBoardValue.NET_KEY_UP.getValue(), "KeyDown"); doOperate(jsonupdown); String jsonupup = getJson(NetKeyBoardValue.NET_KEY_UP.getValue(), "KeyUp"); doOperate(jsonupup); } else if (id == R.id.btn_down) { String jsondowndown = getJson(NetKeyBoardValue.NET_DOWN.getValue(), "KeyDown"); doOperate(jsondowndown); String jsondownup = getJson(NetKeyBoardValue.NET_DOWN.getValue(), "KeyUp"); doOperate(jsondownup); } else if (id == R.id.backBtnInTopLayout) { finish(); } } private void doOperate(String json4){ FunSDK.DevCmdGeneral(mHandler, mFunDevice.devSn, 1550, "OPNetKeyboard", 0, 10000, json4.getBytes(), -1, 0); } private String getJson(String value, String statu){ JSONObject jsonObject = new JSONObject(); JSONObject jsonVS = new JSONObject(); try { jsonVS.put("Value", value); jsonVS.put("Status", statu); jsonObject.put("Name", "OPNetKeyboard"); jsonObject.put("OPNetKeyboard", jsonVS); } catch (JSONException e) { e.printStackTrace(); } System.out.println("TTTT--->>> = " + jsonObject.toString()); return jsonObject.toString(); } @Override public int OnFunSDKResult(Message msg, MsgContent msgContent) { FunLog.d(TAG, "msg.what : " + msg.what); FunLog.d(TAG, "msg.arg1 : " + msg.arg1 + " [" + FunError.getErrorStr(msg.arg1) + "]"); FunLog.d(TAG, "msg.arg2 : " + msg.arg2); if (null != msgContent) { FunLog.d(TAG, "msgContent.sender : " + msgContent.sender); FunLog.d(TAG, "msgContent.seq : " + msgContent.seq); FunLog.d(TAG, "msgContent.str : " + msgContent.str); FunLog.d(TAG, "msgContent.arg3 : " + msgContent.arg3); FunLog.d(TAG, "msgContent.pData : " + msgContent.pData); } return 0; } }
38.116279
173
0.642923
118ec343296132727f81806ebb8489bbd79a0269
2,306
package com.eloKeyboard.ime; import android.graphics.Color; import android.graphics.drawable.Drawable; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import com.eloKeyboard.android.PowerSaving; import com.eloKeyboard.overlay.OverlayData; import com.eloKeyboard.overlay.OverlyDataCreator; import com.eloKeyboard.rx.GenericOnError; import com.elotouch.keyboard.R; import java.util.List; public abstract class AnySoftKeyboardPowerSaving extends AnySoftKeyboardNightMode { private boolean mPowerState; private ToggleOverlayCreator mToggleOverlayCreator; @Override public void onCreate() { super.onCreate(); addDisposable( PowerSaving.observePowerSavingState(getApplicationContext(), 0) .subscribe( powerState -> { mPowerState = powerState; setupInputViewWatermark(); }, GenericOnError.onError("Power-Saving icon"))); addDisposable( PowerSaving.observePowerSavingState( getApplicationContext(), R.string.settings_key_power_save_mode_theme_control, R.bool.settings_default_true) .subscribe( mToggleOverlayCreator::setToggle, GenericOnError.onError("Power-Saving theme"))); } @NonNull @Override protected List<Drawable> generateWatermark() { final List<Drawable> watermark = super.generateWatermark(); if (mPowerState) { watermark.add(ContextCompat.getDrawable(this, R.drawable.ic_watermark_power_saving)); } return watermark; } @Override protected OverlyDataCreator createOverlayDataCreator() { return mToggleOverlayCreator = new ToggleOverlayCreator( super.createOverlayDataCreator(), this, new OverlayData( Color.BLACK, Color.BLACK, Color.DKGRAY, Color.GRAY, Color.DKGRAY), "PowerSaving"); } }
37.193548
98
0.585863
d315bbe2ccaae44e640ba567b3b4b0a61b40673b
4,689
package nio.handler; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import socket.ProtocolConstants; /** * 处理SocketChannel读事件 * @author donald * 2017年4月11日 * 下午10:32:55 */ public class HanlderNioSocketChannel implements Runnable{ private Selector selector; private String threadName; public HanlderNioSocketChannel() { super(); try { this.selector = Selector.open(); } catch (IOException e) { e.printStackTrace(); } threadName = Thread.currentThread().getName(); } public Selector getSelector() { return selector; } public void setSelector(Selector selector) { this.selector = selector; } @Override public void run() { try { listen(); } catch (IOException e) { e.printStackTrace(); } } /** * use asking mode to listen the event of selector * @throws IOException */ @SuppressWarnings({ "rawtypes" }) public void listen() throws IOException{ System.out.println(threadName+"=========The Server Calculate is start!==========="); while(true){ selector.select(); Iterator ite = this.selector.selectedKeys().iterator(); while(ite.hasNext()){ SelectionKey key = (SelectionKey)ite.next(); ite.remove(); if (key.isReadable()) { read(key); } } } } private void read(SelectionKey key){ try { SocketChannel channel = (SocketChannel) key.channel(); String attachedInfo = (String) key.attachment(); System.out.println(threadName+"========socketChannel attachedInfo:"+attachedInfo); ByteBuffer[] proctols = null;//协议 ByteBuffer proctolCodeBuffer = null;//协议编码 proctolCodeBuffer = ByteBuffer.allocate(ProtocolConstants.PROTOCOL_CODE_LENGTH); ByteBuffer dataBuffer = null;//协议内容:操作数 dataBuffer = ByteBuffer.allocate(2*ProtocolConstants.OPERATE_NUM_LENGTH); proctols = new ByteBuffer[]{proctolCodeBuffer,dataBuffer}; System.out.println(threadName+"========read caculate proctol from Client======="); // channel.read(proctols); while(proctolCodeBuffer.position() != ProtocolConstants.PROTOCOL_CODE_LENGTH && dataBuffer.position() != 2*ProtocolConstants.OPERATE_NUM_LENGTH){ channel.read(proctols);//待读取完成协议才解析 } // channel.shutdownInput(); proctolCodeBuffer.flip(); dataBuffer.flip(); byte[] proctolCodeBytes = proctolCodeBuffer.array(); String proctolCode = new String(proctolCodeBytes,ProtocolConstants.CHARSET_UTF8).trim(); int firstNum = 0; int secondNum = 0; int result = 0; if(proctolCode.equals(ProtocolConstants.SUM_PROTOCOL_300000)){ System.out.println(threadName+"========the protocol is sum algorithm======="); firstNum = dataBuffer.getInt(); secondNum = dataBuffer.getInt(); System.out.println("operate num is:"+firstNum+","+secondNum); result = firstNum*secondNum; proctolCodeBuffer.clear(); proctolCodeBuffer.put(ProtocolConstants.ACK_PROTOCOL_300200.getBytes(ProtocolConstants.CHARSET_UTF8)); dataBuffer.clear(); //针对数据太大,缓冲区一次装不完的情况,将缓冲区中,未写完的数据,移到缓冲区的前面 // dataBuffer.compact() dataBuffer.putInt(result); proctolCodeBuffer.flip(); dataBuffer.flip();//切换写模式到读模式,从缓冲区读取数据,写到通道中 channel.write(proctols); } else if(proctolCode.equals(ProtocolConstants.MULTI_PROTOCOL_300100)){ System.out.println(threadName+"========the protocol is multiply algorithm======="); firstNum = dataBuffer.getInt(); secondNum = dataBuffer.getInt(); System.out.println("operate num is:"+firstNum+","+secondNum); result = firstNum*secondNum; proctolCodeBuffer.clear(); proctolCodeBuffer.put(ProtocolConstants.ACK_PROTOCOL_300200.getBytes(ProtocolConstants.CHARSET_UTF8)); proctolCodeBuffer.flip(); dataBuffer.clear(); //针对数据太大,缓冲区一次装不完的情况,将缓冲区中,未写完的数据,移到缓冲区的前面 // dataBuffer.compact() dataBuffer.putInt(result); dataBuffer.flip();//切换写模式到读模式,从缓冲区读取数据,写到通道中 channel.write(proctols); } else{ System.out.println(threadName+"========server decode procotol fail......"); proctolCodeBuffer.clear(); proctolCodeBuffer.put(ProtocolConstants.ACK_PROTOCOL_300300.getBytes(ProtocolConstants.CHARSET_UTF8)); proctolCodeBuffer.flip(); dataBuffer.clear(); dataBuffer.putInt(0); dataBuffer.flip(); channel.write(proctols); } /*关闭Connection,即关闭到通道的连接,再次write将抛出异常*/ // channel.shutdownOutput(); /*关闭通道*/ //channel.close(); /*注意上面两个方法,测试时,不要开启;测试开启的话,Server端,会有一个OP_READ事件*/ } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
32.5625
148
0.708893
4eef496ae679d261f9873cd03441f3339fe52960
2,941
package com.codepath.apps.simpleTweets.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.codepath.apps.simpleTweets.R; import com.codepath.apps.simpleTweets.TweetsArrayAdapter; import com.codepath.apps.simpleTweets.TwitterApplication; import com.codepath.apps.simpleTweets.TwitterClient; import com.codepath.apps.simpleTweets.models.Tweet; import java.util.ArrayList; import java.util.List; public abstract class TweetsListFragment extends Fragment { private TweetsArrayAdapter aTweets; private ArrayList<Tweet> tweets; private ListView lvTweets; protected TwitterClient client; private SwipeRefreshLayout swipeContainer; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup parent, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_tweets_list,parent,false); lvTweets = (ListView) v.findViewById(R.id.lvTweets); //connect adapter to listview lvTweets.setAdapter(aTweets); // Lookup the swipe container view swipeContainer = (SwipeRefreshLayout) v.findViewById(R.id.swipeContainer); // Setup refresh listener which triggers new data loading swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { // Your code to refresh the list here. // Make sure you call swipeContainer.setRefreshing(false) // once the network request has completed successfully. populateTimeline(); swipeContainer.setRefreshing(false); } }); swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); return v; } public void appendTweet(Tweet tweet){ tweets.add(0,tweet); aTweets.notifyDataSetChanged(); lvTweets.setSelection(0); } protected abstract void populateTimeline(); public void clear(){ aTweets.clear(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); client = TwitterApplication.getRestClient(); // create the a // rray list data source tweets = new ArrayList<>(); //construct the adapter aTweets = new TweetsArrayAdapter(getActivity(), tweets); } public void addAll(List<Tweet> tweets){ aTweets.addAll(tweets); //aTweets.notifyDataSetChanged(); } }
30.635417
120
0.693982
31a26321aa9afce7345fa7f575d0fcd856d7b393
5,559
/* * 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.commonwl.view.workflow; import org.commonwl.view.git.GitDetails; import org.junit.Test; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.Errors; import static org.junit.Assert.*; /** * Tests the validator. Parsing is already checked in GithubServiceTest */ public class WorkflowFormValidatorTest { /** * Workflow form validator to test */ private WorkflowFormValidator workflowFormValidator = new WorkflowFormValidator(); /** * Github File URL */ @Test public void githubUrl() throws Exception { WorkflowForm githubUrl = new WorkflowForm("https://github.com/nlesc-sherlock/deeplearning/blob/master/CWLworkflow/pipeline.cwl"); Errors errors = new BeanPropertyBindingResult(githubUrl, "workflowForm"); GitDetails details = workflowFormValidator.validateAndParse(githubUrl, errors); assertNotNull(details); assertEquals("https://github.com/nlesc-sherlock/deeplearning.git", details.getRepoUrl()); assertEquals("master", details.getBranch()); assertEquals("CWLworkflow/pipeline.cwl", details.getPath()); assertFalse(errors.hasErrors()); } /** * Gitlab File URL */ @Test public void gitlabUrl() throws Exception { WorkflowForm gitlabUrl = new WorkflowForm("https://gitlab.com/unduthegun/stellaris-emblem-lab/blob/cwl/textures/textures.cwl"); Errors errors = new BeanPropertyBindingResult(gitlabUrl, "workflowForm"); GitDetails details = workflowFormValidator.validateAndParse(gitlabUrl, errors); assertNotNull(details); assertEquals("https://gitlab.com/unduthegun/stellaris-emblem-lab.git", details.getRepoUrl()); assertEquals("cwl", details.getBranch()); assertEquals("textures/textures.cwl", details.getPath()); assertFalse(errors.hasErrors()); } /** * Generic File URL */ @Test public void genericUrl() throws Exception { WorkflowForm genericUrl = new WorkflowForm("https://bitbucket.org/markrobinson96/workflows.git"); genericUrl.setBranch("branchName"); genericUrl.setPath("path/to/workflow.cwl"); Errors errors = new BeanPropertyBindingResult(genericUrl, "workflowForm"); GitDetails details = workflowFormValidator.validateAndParse(genericUrl, errors); assertNotNull(details); assertEquals("https://bitbucket.org/markrobinson96/workflows.git", details.getRepoUrl()); assertEquals("branchName", details.getBranch()); assertEquals("path/to/workflow.cwl", details.getPath()); assertFalse(errors.hasErrors()); } /** * Packed URL */ @Test public void packedUrl() throws Exception { WorkflowForm githubUrl = new WorkflowForm("https://github.com/MarkRobbo/workflows/tree/master/packed.cwl#workflowId"); Errors errors = new BeanPropertyBindingResult(githubUrl, "workflowForm"); GitDetails details = workflowFormValidator.validateAndParse(githubUrl, errors); assertNotNull(details); assertEquals("https://github.com/MarkRobbo/workflows.git", details.getRepoUrl()); assertEquals("master", details.getBranch()); assertEquals("packed.cwl", details.getPath()); assertEquals("workflowId", details.getPackedId()); assertFalse(errors.hasErrors()); } /** * Empty URL */ @Test public void emptyURL() throws Exception { WorkflowForm emptyURL = new WorkflowForm(""); Errors errors = new BeanPropertyBindingResult(emptyURL, "workflowForm"); GitDetails willBeNull = workflowFormValidator.validateAndParse(emptyURL, errors); assertNull(willBeNull); assertTrue(errors.hasErrors()); } /** * Invalid URL */ @Test public void invalidURL() throws Exception { WorkflowForm invalidURL = new WorkflowForm("https://google.com/clearly/not/github/url"); Errors errors = new BeanPropertyBindingResult(invalidURL, "workflowForm"); GitDetails details = workflowFormValidator.validateAndParse(invalidURL, errors); assertNull(details); assertTrue(errors.hasErrors()); } /** * Generic File URL without branch or path */ @Test public void noBranchOrPath() throws Exception { WorkflowForm genericUrl = new WorkflowForm("https://bitbucket.org/markrobinson96/workflows.git"); Errors errors = new BeanPropertyBindingResult(genericUrl, "workflowForm"); GitDetails details = workflowFormValidator.validateAndParse(genericUrl, errors); assertNull(details); assertTrue(errors.hasErrors()); } }
34.104294
137
0.697248
88b384a68aebc38d77a2ae14735e2a615bb0cbfa
1,622
package net.modificationstation.stationapi.impl.config; import net.modificationstation.stationapi.api.config.Property; import java.io.*; public class PropertyImpl implements Property { private final String name; private String value; private String comment; public PropertyImpl(String name) { this.name = name; } @Override public String getName() { return name; } @Override public void setValue(Object o) { value = o instanceof String ? (String) o : o.toString(); } @Override public String getStringValue() { return value; } @Override public int getIntValue() { return Integer.parseInt(value); } @Override public boolean getBooleanValue() { return Boolean.parseBoolean(value); } @Override public void setComment(String comment) { this.comment = comment; } @Override public void save(BufferedWriter buffer) { if (comment != null) try { buffer.write(" # " + comment + "\r\n"); } catch (IOException e) { throw new RuntimeException(e); } try { buffer.write(" " + getName() + "=" + getStringValue() + "\r\n"); } catch (IOException e) { throw new RuntimeException(e); } } @Override public int compareTo(Property o) { return getName().compareTo(o.getName()); } @Override public boolean equals(Object o) { return o instanceof Property && getName().equals(((Property) o).getName()); } }
22.527778
83
0.580148
ff08382b7c6ec5046d8d7b1c4ef3509aff230c9c
2,139
package com.ansj.vec; import java.io.*; public class initTxt{ public static void main(String[] args) throws IOException { remove(); } public static void remove() throws IOException { BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\jayjosby.liu@sap.com\\Desktop\\Temp\\yuliao\\ss\\result\\mark_SICK.txt"));//使用BufferedReader 最大好处是可以按bai行du读取,每次读取一行 BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\jayjosby.liu@sap.com\\Desktop\\Temp\\yuliao\\ss\\result\\mark_SICK-1.txt")); String line = br.readLine(); while(line!=null){ String[] lines = line.split(" "); System.out.println(lines.length); if(lines.length==2){ bw.write(line); bw.newLine(); } line = br.readLine(); } br.close(); bw.close(); System.out.println("end"); } public void init() throws IOException { BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\jayjosby.liu@sap.com\\Desktop\\Temp\\yuliao\\text8"));//使用BufferedReader 最大好处是可以按bai行du读取,每次读取一行 BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\jayjosby.liu@sap.com\\Desktop\\Temp\\yuliao\\text9.txt")); String temp=br.readLine();//定义字符串,用于保dao存每行读取到的数据 // while (temp != null) { // System.out.println(temp); // } System.out.println("\n text8 has been loaded"); int pos =0,num=0; for(int i=0;i<temp.length();i++){ if(numOfSpace(temp.substring(pos,i))>=20){ bw.write(temp.substring(pos,i-1)); System.out.println(num+" "+temp.substring(pos,i-1)); bw.newLine(); pos = i; num+=1; } } //关闭流 bw.close(); } public int numOfSpace(String s){ int num=0; for(int i=0;i<s.length();i++){ if(s.charAt(i)==' '){ num+=1; } } return num; } }
35.065574
191
0.531557
2cdee444f627df1a1072f55b721c09f3a3a2b2e6
285
package com.example.dialogues.utils; /** * Created by vivek on 26/02/18. */ public interface BaseScreen { void doInit(); void showLoadingProgress(); void hideLoadingProgress(); void showNetworkError(); void showApiError(); void showError(String msg); }
15
36
0.673684
510c7a4a58f8054cf670a7c9063f5cdbec182eb4
815
package play.learn.java.design.momento; import java.util.Stack; // https://java-design-patterns.com/patterns/memento/ public class MomentoDemo { public static void main(String[] args) { Stack<StarMemento> states = new Stack<>(); Star star = new Star(StarType.SUN, 10000000, 500000); System.out.println(star.toString()); states.add(star.getMemento()); star.timePasses(); System.out.println(star.toString()); states.add(star.getMemento()); star.timePasses(); System.out.println(star.toString()); states.add(star.getMemento()); star.timePasses(); System.out.println(star.toString()); states.add(star.getMemento()); star.timePasses(); System.out.println(star.toString()); while (states.size() > 0) { star.setMemento(states.pop()); System.out.println(star.toString()); } } }
27.166667
55
0.699387
60c45f7b8d0c488cf3c75b0819de0d624258043d
2,113
package org.apereo.cas.web.support; import org.apereo.cas.audit.config.CasSupportJdbcAuditConfiguration; import org.apereo.cas.config.CasHibernateJpaConfiguration; import org.apereo.cas.config.CasJdbcThrottlingConfiguration; import lombok.Getter; import lombok.val; import org.apereo.inspektr.common.web.ClientInfo; import org.apereo.inspektr.common.web.ClientInfoHolder; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mock.web.MockHttpServletRequest; import static org.junit.jupiter.api.Assertions.*; /** * Unit test for {@link JdbcThrottledSubmissionHandlerInterceptorAdapter}. * * @author Marvin S. Addison * @since 3.0.0 */ @SpringBootTest(classes = { CasJdbcThrottlingConfiguration.class, CasSupportJdbcAuditConfiguration.class, CasHibernateJpaConfiguration.class, BaseThrottledSubmissionHandlerInterceptorAdapterTests.SharedTestConfiguration.class }, properties = { "cas.authn.throttle.username-parameter=username", "cas.authn.throttle.failure.code=AUTHENTICATION_FAILED", "cas.audit.jdbc.asynchronous=false", "cas.authn.throttle.username-parameter=username", "cas.authn.throttle.failure.range-seconds=5" }) @Getter @Tag("JDBC") public class JdbcThrottledSubmissionHandlerInterceptorAdapterTests extends BaseThrottledSubmissionHandlerInterceptorAdapterTests { @Autowired @Qualifier("authenticationThrottle") private ThrottledSubmissionHandlerInterceptor throttle; @Test public void verifyRecords() { val request = new MockHttpServletRequest(); request.setRemoteAddr("1.2.3.4"); request.setLocalAddr("4.5.6.7"); request.setRemoteUser("cas"); request.addHeader("User-Agent", "Firefox"); ClientInfoHolder.setClientInfo(new ClientInfo(request)); throttle.recordSubmissionFailure(request); assertFalse(throttle.getRecords().isEmpty()); } }
35.813559
130
0.780407
b1ccd92a2a05b30bf3b962126422461163683d13
877
package com.appier.android.sample.common; import android.graphics.Rect; import android.view.View; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class MyRecyclerViewItemDecoration extends RecyclerView.ItemDecoration { private int mSpace; public MyRecyclerViewItemDecoration(int space) { mSpace = space; } @Override public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); outRect.left = mSpace; outRect.right = mSpace; outRect.bottom = mSpace; // Add top margin only for the first item to avoid double space between items if (parent.getChildPosition(view) == 0) { outRect.top = mSpace; } } }
29.233333
140
0.703535
8e0a3fe9fff15a4be40956cfee21bd869dff1a16
2,309
package org.solteh; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.Properties; @Configuration public class SpringBootWebConfiguration implements WebMvcConfigurer { private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"}; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!registry.hasMappingForPattern("/webjars/**")) { registry.addResourceHandler("/webjars/**").addResourceLocations( "classpath:/META-INF/resources/webjars/"); } if (!registry.hasMappingForPattern("/static/**")) { registry.addResourceHandler("/static/**").addResourceLocations( CLASSPATH_RESOURCE_LOCATIONS); } } @Bean public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); // Load file: validation.properties messageSource.setBasename("classpath:validation"); messageSource.setDefaultEncoding("UTF-8"); return messageSource; } @Bean public JavaMailSender getJavaMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost("smtp.gmail.com"); mailSender.setPort(587); mailSender.setUsername("username@gmail.com"); mailSender.setPassword("emailpassword"); Properties props = mailSender.getJavaMailProperties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.debug", "true"); return mailSender; } }
38.483333
106
0.711563
c65aeba3d0f9c6f7cda5bd439768fdf49f3a4fc7
1,879
/* The NIST RCS (Real-time Control Systems) library is public domain software, however it is preferred that the following disclaimers be attached. Software Copywrite/Warranty Disclaimer This software was developed at the National Institute of Standards and Technology by employees of the Federal Government in the course of their official duties. Pursuant to title 17 Section 105 of the United States Code this software is not subject to copyright protection and is in the public domain. NIST Real-Time Control System software is an experimental system. NIST assumes no responsibility whatsoever for its use by other parties, and makes no guarantees, expressed or implied, about its quality, reliability, or any other characteristic. We would appreciate acknowledgement if the software is used. This software can be redistributed and/or modified freely provided that any derivative works bear some notice that they are derived from it, and any modified versions bear some notice that they have been modified. */ package dbgplot.ui; /* * * PlotPoint * */ class PlotPoint { //public boolean connected = true; public double orig_x = 0.0; public double orig_y = 0.0; public double pre_f_y = 0.0; public double pre_f_x = 0.0; public int x =0; public int y =0; //public long time=0; public PlotPoint(int x_param, int y_param, double orig_x_param, double orig_y_param, double pre_f_x_param, double pre_f_y_param) { x = x_param; y = y_param; orig_x = orig_x_param; orig_y = orig_y_param; //connected = connected_param; pre_f_x = pre_f_x_param; pre_f_y = pre_f_y_param; } public PlotPoint() { } public String toString() { return super.toString()+ " { orig_x="+orig_x+", orig_y="+orig_y+", pre_f_x="+pre_f_x+", pre_fy_y="+pre_f_y+" x="+x+", y="+y+" }"; } }
28.044776
132
0.720596
01f15c81c28ec91a1eda86df99e2ae1933804ad4
7,107
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License,Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.huawei.codelab.utils; import ohos.aafwk.ability.Ability; import ohos.agp.components.Component; import ohos.agp.components.LayoutScatter; import ohos.agp.components.Text; import ohos.agp.utils.LayoutAlignment; import ohos.agp.window.dialog.CommonDialog; import ohos.agp.window.dialog.ToastDialog; import ohos.app.Context; import ohos.eventhandler.EventHandler; import ohos.eventhandler.EventRunner; import com.huawei.codelab.ResourceTable; import com.huawei.codelab.gif.GifImage; /** * Dialog util * * @since 2021-04-14 */ public class DialogUtil { /** * list dialog width */ public static final int LIST_DIALOG_WIDTH = 600; /** * list dialog height */ public static final int LIST_DIALOG_HEIGHT = 800; /** * button dialog width */ public static final int BUTTON_DIALOG_HEIGHT = 400; /** * delay time */ public static final int DELAY_TIME = 3000; /** * delay time */ public static final int DELAY_TIME_O = 1000; /** * delay time */ public static final int DELAY = 3; /** * show toast * * @param context context * @param message message */ public static void showToast(Context context, String message) { ToastDialog toastDialog = new ToastDialog(context); Component layout = LayoutScatter.getInstance(context) .parse(ResourceTable.Layout_toast_layout, null, false); if (layout.findComponentById(ResourceTable.Id_text) instanceof Text) { Text text = (Text) layout.findComponentById(ResourceTable.Id_text); text.setText(message); } toastDialog.setComponent(layout); toastDialog.setAlignment(LayoutAlignment.BOTTOM); // Set the background transparency of the dialog box. toastDialog.setTransparent(true); toastDialog.setDuration(3 * 1000); toastDialog.show(); } /** * show open close dialog * * @param content content * @param context context * @param comfirmListener comfirm * @param cancelListener cancel */ public static void showComfirmDialog(String content, Context context, CommonDialog.DestroyedListener comfirmListener, CommonDialog.DestroyedListener cancelListener) { CommonDialog commonDialog = new CommonDialog(context); Component layout = LayoutScatter.getInstance(context) .parse(ResourceTable.Layout_dialog_comfirm, null, false); commonDialog.setAutoClosable(true); commonDialog.setContentCustomComponent(layout); commonDialog.setSize(LIST_DIALOG_HEIGHT, BUTTON_DIALOG_HEIGHT); if (layout.findComponentById(ResourceTable.Id_text) instanceof Text) { Text text = (Text) layout.findComponentById(ResourceTable.Id_text); text.setText(content); } layout.findComponentById(ResourceTable.Id_comfirm).setClickedListener(new Component.ClickedListener() { @Override public void onClick(Component component) { commonDialog.destroy(); comfirmListener.onDestroy(); } }); layout.findComponentById(ResourceTable.Id_cancel).setClickedListener(new Component.ClickedListener() { @Override public void onClick(Component component) { commonDialog.destroy(); cancelListener.onDestroy(); } }); commonDialog.show(); } /** * show gif dialog * * @param context context * @param destroyedListener destroy */ public static void showGifDialog(Context context, CommonDialog.DestroyedListener destroyedListener) { CommonDialog toastDialog = new CommonDialog(context); Component layout = LayoutScatter.getInstance(context) .parse(ResourceTable.Layout_dialog_gif, null, false); if (layout.findComponentById(ResourceTable.Id_gifImage) instanceof GifImage) { GifImage gifImage = (GifImage) layout.findComponentById(ResourceTable.Id_gifImage); gifImage.play(); toastDialog.setContentCustomComponent(layout); toastDialog.setSize(LIST_DIALOG_HEIGHT, LIST_DIALOG_HEIGHT); toastDialog.setAlignment(LayoutAlignment.CENTER); toastDialog.setAutoClosable(true); toastDialog.setDestroyedListener(new CommonDialog.DestroyedListener() { @Override public void onDestroy() { gifImage.pause(); destroyedListener.onDestroy(); } }); toastDialog.show(); context.getMainTaskDispatcher().delayDispatch(new Runnable() { @Override public void run() { gifImage.pause(); toastDialog.destroy(); destroyedListener.onDestroy(); } }, DELAY_TIME); } } /** * exit dialog * * @param context Ability */ public static void exitDialog(Ability context) { CommonDialog toastDialog = new CommonDialog(context); Component layout = LayoutScatter.getInstance(context) .parse(ResourceTable.Layout_exit_dialog, null, false); if (layout.findComponentById(ResourceTable.Id_delay) instanceof Text) { Text delay = (Text) layout.findComponentById(ResourceTable.Id_delay); toastDialog.setContentCustomComponent(layout); toastDialog.setSize(LIST_DIALOG_WIDTH, BUTTON_DIALOG_HEIGHT); toastDialog.setAlignment(LayoutAlignment.CENTER); toastDialog.setAutoClosable(false); toastDialog.show(); EventHandler eventHandler = new EventHandler(EventRunner.getMainEventRunner()); final int[] count = {DELAY}; Runnable runnable = new Runnable() { @Override public void run() { if (count[0] == 0) { toastDialog.destroy(); context.terminateAbility(); } else { count[0]--; delay.setText(count[0] + ""); eventHandler.postTask(this, DELAY_TIME_O); } } }; eventHandler.postTask(runnable, DELAY_TIME_O); } } }
36.634021
111
0.628113
592983a6a4363c73ad05e02c86bfbb7044bb5d2f
2,231
package cards; import generator.idgenerator; import java.util.Calendar; import java.util.Date; import java.util.LinkedList; public class deck { private LinkedList<card> deck; private String deck_id; private int weekstamp; private int year; private Boolean shuffle; public int getCount() { return count; } private int count; public deck(boolean shuffle,int count) { LinkedList<card> cardslist=new LinkedList<>(); intializedeck(count); for(int i=0;i<count;i++) for(shapes sh : shapes.values()) for(names na : names.values()) { cardslist.add(new card(na,sh)); } addcards(cardslist); this.shuffle=shuffle; if(shuffle) { shuffleDeck(deck,count); } } public deck(boolean shuffle,int count,LinkedList<card> cardslist) { intializedeck(count); addcards(cardslist); if(shuffle) { shuffleDeck(deck,count); } } private void intializedeck(int count) { deck=new LinkedList<>(); deck_id=idgenerator.randomString(12); this.count=count; Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); weekstamp= cal.get(Calendar.WEEK_OF_YEAR); year= cal.get(Calendar.YEAR); this.count=count; } private void addcards(LinkedList<card> cardslist) { for(card cd : cardslist) { deck.add(cd); } } public String shuffleDeck(LinkedList<card> deck,int count) { for(int i=0; i<52*count; i++) { int card = (int) (Math.random() * (52*count-i)); deck.addLast(deck.remove(card)); } return "true"; } public LinkedList<card> getDeck() { return deck; } public String getDeck_id() { return deck_id; } public int getWeekstamp() { return weekstamp; } public int getYearstamp() { return year; } public boolean getShuffle() { return shuffle; } public void setShuffle(boolean shuffle) { this.shuffle = shuffle; } }
18.90678
69
0.55939
5c261ba84bba3ae14ff172f43a6c22b31636eb1f
1,581
package org.omg.hw.HW_mstpProtection; /** * Generated from IDL definition of enum "HW_AtmPGSwitchDirect_T" * @author JacORB IDL compiler */ public final class HW_AtmPGSwitchDirect_T implements org.omg.CORBA.portable.IDLEntity { private int value = -1; public static final int _HW_ASD_NA = 0; public static final HW_AtmPGSwitchDirect_T HW_ASD_NA = new HW_AtmPGSwitchDirect_T(_HW_ASD_NA); public static final int _HW_ASD_SRC = 1; public static final HW_AtmPGSwitchDirect_T HW_ASD_SRC = new HW_AtmPGSwitchDirect_T(_HW_ASD_SRC); public static final int _HW_ASD_SNK = 2; public static final HW_AtmPGSwitchDirect_T HW_ASD_SNK = new HW_AtmPGSwitchDirect_T(_HW_ASD_SNK); public static final int _HW_ASD_BI = 3; public static final HW_AtmPGSwitchDirect_T HW_ASD_BI = new HW_AtmPGSwitchDirect_T(_HW_ASD_BI); public int value() { return value; } public static HW_AtmPGSwitchDirect_T from_int(int value) { switch (value) { case _HW_ASD_NA: return HW_ASD_NA; case _HW_ASD_SRC: return HW_ASD_SRC; case _HW_ASD_SNK: return HW_ASD_SNK; case _HW_ASD_BI: return HW_ASD_BI; default: throw new org.omg.CORBA.BAD_PARAM(); } } public String toString() { switch (value) { case _HW_ASD_NA: return "HW_ASD_NA"; case _HW_ASD_SRC: return "HW_ASD_SRC"; case _HW_ASD_SNK: return "HW_ASD_SNK"; case _HW_ASD_BI: return "HW_ASD_BI"; default: throw new org.omg.CORBA.BAD_PARAM(); } } protected HW_AtmPGSwitchDirect_T(int i) { value = i; } java.lang.Object readResolve() throws java.io.ObjectStreamException { return from_int(value()); } }
29.830189
97
0.764073
c011e5c6b5dcc2b441156b0767e6d022f1cddac5
7,372
package br.com.waiso.recommender.data; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.yooreeka.algos.reco.collab.model.Content; public class Empresa implements Serializable { /** * Unique identifier for serialization */ private static final long serialVersionUID = -1884424246968533858L; /** * Utility method to extract item ids that are shared between empresa A and * empresa B. */ public static Integer[] getSharedProdutosComprados(Empresa x, Empresa y) { List<Integer> sharedProdutosComprados = new ArrayList<Integer>(); for (List<Compra> c : x.getAllComprasCompra()) { if (y.getProdutoCompraByCompra(c.get(0).getProdutoId()) != null) { sharedProdutosComprados.add(c.get(0).getProdutoId()); } } return sharedProdutosComprados.toArray(new Integer[sharedProdutosComprados.size()]); } /** * Utility method to extract item ids that are shared between empresa A and * empresa B. */ public static Integer[] getSharedProdutosVendidos(Empresa x, Empresa y) { List<Integer> sharedProdutosVendidos = new ArrayList<Integer>(); for (List<Compra> r : x.getAllComprasVenda()) { if (y.getProdutoCompraByVenda(r.get(0).getProdutoId()) != null) { sharedProdutosVendidos.add(r.get(0).getProdutoId()); } } return sharedProdutosVendidos.toArray(new Integer[sharedProdutosVendidos.size()]); } int id; String name; protected Map<Integer, List<Compra>> comprasByProdutoVendidoId; protected Map<Integer, List<Compra>> comprasByProdutoCompradoId; private List<Content> empresaContent = new ArrayList<Content>(); public Empresa(int id, boolean comprador) { this(id, String.valueOf(id), new ArrayList<Compra>(3), comprador); } public Empresa(int id, List<Compra> compras, boolean comprador) { this(id, String.valueOf(id), compras, comprador); } public Empresa(int id, String name, boolean comprador) { this(id, name, new ArrayList<Compra>(3), comprador); } public Empresa(int id, String name, List<Compra> compras, boolean comprador) { this.id = id; this.name = name; if(comprasByProdutoCompradoId == null) { comprasByProdutoCompradoId = new HashMap<Integer, List<Compra>>(compras.size()); } if(comprasByProdutoVendidoId == null) { comprasByProdutoVendidoId = new HashMap<Integer, List<Compra>>(compras.size()); } if(comprador) { for (Compra c : compras) { comprasByProdutoCompradoId.put(c.getProdutoId(), compras); } } else { for (Compra c : compras) { comprasByProdutoVendidoId.put(c.getProdutoId(), compras); } } } public void addCompraComprado(Compra compra) { List<Compra> compras = comprasByProdutoCompradoId.get(compra.getProdutoId()); if(compras == null) { compras = new ArrayList<Compra>(); comprasByProdutoCompradoId.put(compra.getProdutoId(), compras); } compras.add(compra); } public void addCompraVendido(Compra compra) { List<Compra> compras = comprasByProdutoVendidoId.get(compra.getProdutoId()); if(compras == null) { compras = new ArrayList<Compra>(); comprasByProdutoVendidoId.put(compra.getProdutoId(), compras); } compras.add(compra); } public void addEmpresaContent(Content content) { empresaContent.add(content); } public Collection<List<Compra>> getAllComprasCompra() { return comprasByProdutoCompradoId.values(); } public Collection<List<Compra>> getAllComprasVenda() { return comprasByProdutoVendidoId.values(); } public double getAverageRatingByCompra() { return getAverageRating(getAllComprasCompra()); } public double getAverageRatingByVenda() { return getAverageRating(getAllComprasVenda()); } private double getAverageRating(Collection<List<Compra>> allCompras) { double allRatingsSum = 0.0; int numRatings = 0; for (List<Compra> list : allCompras) { Collection<Compra> allEmpresaRatings = list; for (Compra compra : allEmpresaRatings) { allRatingsSum += compra.getPontuacao(); } numRatings += allEmpresaRatings.size(); } return numRatings > 0 ? allRatingsSum / numRatings : 2.5; } public int getId() { return id; } public List<Compra> getProdutoCompraByCompra(Integer produtoId) { return comprasByProdutoCompradoId.get(produtoId); } public List<Compra> getProdutoCompraByVenda(Integer produtoId) { return comprasByProdutoVendidoId.get(produtoId); } public String getName() { return name; } /* * Utility method to extract array of ratings based on array of item ids. */ public List<double[]> getRatingsForProdutoVendaList(Integer[] produtoIds) { return getRatingsForProdutoList(produtoIds, comprasByProdutoVendidoId); } /* * Utility method to extract array of ratings based on array of item ids. */ public List<double[]> getRatingsForProdutoCompraList(Integer[] produtoIds) { return getRatingsForProdutoList(produtoIds, comprasByProdutoVendidoId); } /* * Utility method to extract array of ratings based on array of item ids. */ public List<double[]> getRatingsForProdutoList(Integer[] produtoIds, Map<Integer, List<Compra>> compras) { List<double[]> ratings = new ArrayList<double[]>(); for (int i = 0, n = produtoIds.length; i < n; i++) { List<Compra> c = compras.get(produtoIds[i]); if (c == null) { throw new IllegalArgumentException( "Empresa doesn't have specified item id (" + "empresaId=" + getId() + ", itemId=" + produtoIds[i]); } double[] r = new double[c.size()]; int j = 0; for (Compra compra : c) { r[j] = compra.getPontuacao(); j++; } ratings.add(r); } return ratings; } public List<Content> getEmpresaContent() { return empresaContent; } public Content getEmpresaContent(String contentId) { Content matchedContent = null; for (Content c : empresaContent) { if (c.getId().equals(contentId)) { matchedContent = c; break; } } return matchedContent; } public void setComprasCompra(List<Compra> compras) { // Initialize or clean up if (comprasByProdutoCompradoId == null) { comprasByProdutoCompradoId = new HashMap<Integer, List<Compra>>(); } else { comprasByProdutoCompradoId.clear(); } // Load the ratings for (Compra compra : compras) { List<Compra> c = comprasByProdutoCompradoId.get(compra.getProdutoId()); if(c == null) { c = new ArrayList<Compra>(); comprasByProdutoCompradoId.put(compra.getProdutoId(), c); } c.add(compra); } } public void setComprasVenda(List<Compra> compras) { // Initialize or clean up if (comprasByProdutoVendidoId == null) { comprasByProdutoVendidoId = new HashMap<Integer, List<Compra>>(); } else { comprasByProdutoVendidoId.clear(); } // Load the ratings for (Compra compra : compras) { List<Compra> c = comprasByProdutoVendidoId.get(compra.getProdutoId()); if(c == null) { c = new ArrayList<Compra>(); comprasByProdutoVendidoId.put(compra.getProdutoId(), c); } c.add(compra); } } public void setEmpresaContent(List<Content> content) { this.empresaContent = content; } }
29.13834
108
0.686923
a2c160e612ac2f31091fc40b885c61b1a2c63ae9
855
package com.lihengl.dizu; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.content.Intent; import android.widget.EditText; public class MainActivity extends Activity { public final static String EXTRA_MESSAGE = "com.lihengl.dizu.MESSAGE"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public void onStart() { super.onStart(); } public void sendMessage(View view) { Intent intent = new Intent(this, DisplayMessageActivity.class); EditText editText = (EditText) findViewById(R.id.edit_message); String message = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); } }
25.909091
74
0.700585
31a61268698c6b2ec07881ebd343dd6ec7f13ce9
8,381
/* * 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.catalina.deploy; import org.apache.catalina.util.RequestUtil; import java.io.Serializable; /** * Representation of a web resource collection for a web application's security * constraint, as represented in a <code>&lt;web-resource-collection&gt;</code> * element in the deployment descriptor. * <p> * <b>WARNING</b>: It is assumed that instances of this class will be created * and modified only within the context of a single thread, before the instance * is made visible to the remainder of the application. After that, only read * access is expected. Therefore, none of the read and write access within * this class is synchronized. * * @author Craig R. McClanahan * @version $Id: SecurityCollection.java 939527 2010-04-30 00:43:48Z kkolinko $ */ public class SecurityCollection implements Serializable { // ----------------------------------------------------------- Constructors /** * Construct a new security collection instance with default values. */ public SecurityCollection() { this(null, null); } /** * Construct a new security collection instance with specified values. * * @param name Name of this security collection */ public SecurityCollection(String name) { this(name, null); } /** * Construct a new security collection instance with specified values. * * @param name Name of this security collection * @param description Description of this security collection */ public SecurityCollection(String name, String description) { super(); setName(name); setDescription(description); } // ----------------------------------------------------- Instance Variables /** * Description of this web resource collection. */ private String description = null; /** * The HTTP methods covered by this web resource collection. */ private String methods[] = new String[0]; /** * The name of this web resource collection. */ private String name = null; /** * The URL patterns protected by this security collection. */ private String patterns[] = new String[0]; // ------------------------------------------------------------- Properties /** * Return the description of this web resource collection. */ public String getDescription() { return (this.description); } /** * Set the description of this web resource collection. * * @param description The new description */ public void setDescription(String description) { this.description = description; } /** * Return the name of this web resource collection. */ public String getName() { return (this.name); } /** * Set the name of this web resource collection * * @param name The new name */ public void setName(String name) { this.name = name; } // --------------------------------------------------------- Public Methods /** * Add an HTTP request method to be part of this web resource collection. */ public void addMethod(String method) { if (method == null) return; String results[] = new String[methods.length + 1]; for (int i = 0; i < methods.length; i++) results[i] = methods[i]; results[methods.length] = method; methods = results; } /** * Add a URL pattern to be part of this web resource collection. */ public void addPattern(String pattern) { if (pattern == null) return; pattern = RequestUtil.URLDecode(pattern); String results[] = new String[patterns.length + 1]; for (int i = 0; i < patterns.length; i++) { results[i] = patterns[i]; } results[patterns.length] = pattern; patterns = results; } /** * Return <code>true</code> if the specified HTTP request method is * part of this web resource collection. * * @param method Request method to check */ public boolean findMethod(String method) { if (methods.length == 0) return (true); for (int i = 0; i < methods.length; i++) { if (methods[i].equals(method)) return (true); } return (false); } /** * Return the set of HTTP request methods that are part of this web * resource collection, or a zero-length array if all request methods * are included. */ public String[] findMethods() { return (methods); } /** * Is the specified pattern part of this web resource collection? * * @param pattern Pattern to be compared */ public boolean findPattern(String pattern) { for (int i = 0; i < patterns.length; i++) { if (patterns[i].equals(pattern)) return (true); } return (false); } /** * Return the set of URL patterns that are part of this web resource * collection. If none have been specified, a zero-length array is * returned. */ public String[] findPatterns() { return (patterns); } /** * Remove the specified HTTP request method from those that are part * of this web resource collection. * * @param method Request method to be removed */ public void removeMethod(String method) { if (method == null) return; int n = -1; for (int i = 0; i < methods.length; i++) { if (methods[i].equals(method)) { n = i; break; } } if (n >= 0) { int j = 0; String results[] = new String[methods.length - 1]; for (int i = 0; i < methods.length; i++) { if (i != n) results[j++] = methods[i]; } methods = results; } } /** * Remove the specified URL pattern from those that are part of this * web resource collection. * * @param pattern Pattern to be removed */ public void removePattern(String pattern) { if (pattern == null) return; int n = -1; for (int i = 0; i < patterns.length; i++) { if (patterns[i].equals(pattern)) { n = i; break; } } if (n >= 0) { int j = 0; String results[] = new String[patterns.length - 1]; for (int i = 0; i < patterns.length; i++) { if (i != n) results[j++] = patterns[i]; } patterns = results; } } /** * Return a String representation of this security collection. */ public String toString() { StringBuffer sb = new StringBuffer("SecurityCollection["); sb.append(name); if (description != null) { sb.append(", "); sb.append(description); } sb.append("]"); return (sb.toString()); } }
25.168168
80
0.539076
67e2ae305d8cecb1faa15c06c0a8d739af3dd545
225
package com.aoeai.spin.accelerator.themes.frame.exception; /** * @author aoe * @date 2020/8/24 */ public class ThemeException extends RuntimeException { public ThemeException(String msg){ super(msg); } }
17.307692
58
0.688889
486f58b1ee19cb36ac4e81c36ae24e67b376ecc6
402
package com.jakduk.batch.repository; import com.jakduk.batch.model.db.ArticleComment; import org.bson.types.ObjectId; import java.util.List; /** * Created by pyohwan on 16. 11. 30. */ public interface ArticleCommentRepositoryCustom { /** * 기준 ArticleComment ID 이상의 ArticleComment 목록을 가져온다. */ List<ArticleComment> findCommentsGreaterThanId(ObjectId objectId, Integer limit); }
21.157895
85
0.741294
5c02b05138e573bff9aa09e68fbd0e3778157d13
1,258
package com.practice.algorithm.leetcode_passing; /** * * @author Higmin * @date 2020/3/29 20:01 * * leetcode 328. 奇偶链表 * 给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。 * * 请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。 * * 示例 1: * * 输入: 1->2->3->4->5->NULL * 输出: 1->3->5->2->4->NULL * 示例 2: * * 输入: 2->1->3->5->6->4->7->NULL * 输出: 2->3->6->7->1->5->4->NULL * * 说明: * 应当保持奇数节点和偶数节点的相对顺序。 * 链表的第一个节点视为奇数节点,第二个节点视为偶数节点,以此类推。 */ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class N_328_OddEvenLinkedList { public ListNode oddEvenList(ListNode head) { // 思路: 构建两个链表分别存放奇数节点和偶数节点,遍历完之后将两个链表连接起来。 if(head == null) return null; // 首先分别初始化两个链表的头节点。并给偶数链表固定一个头节点,防止指针移动找不到真正的头节点。 ListNode head1 = head, head2 = head.next, dummy2 = head2; while(head2 != null && head2.next != null){ // 给第一个链表添加节点 head1.next = head2.next; head1 = head1.next; // 给第二个链表添加节点 head2.next = head1.next; head2 = head2.next; } head1.next = dummy2; // 连接两个链表 return head; } }
23.735849
71
0.582671
187652c3ba7cffcb3e00535079119461e53d57f0
7,645
package com.tang.activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.chad.library.adapter.base.BaseQuickAdapter; //import com.gyf.barlibrary.ImmersionBar; import com.tang.C; import com.tang.R; import com.tang.adapter.TransactionsAdapter; import com.tang.blockchain.Wallet; import com.tang.data_entity.Transaction; import com.tang.util.LogUtils; import java.util.List; import butterknife.BindView; import butterknife.OnClick; import static com.tang.C.EXTRA_ADDRESS; import static com.tang.C.Key.TRANSACTION; /** * Created by tang * */ public class PropertyDetailActivity extends ActivityRoot { // TransactionsViewModelFactory transactionsViewModelFactory; // private TransactionsViewModel viewModel; private TransactionsAdapter adapter; private String currWallet; private String contractAddress; private int decimals; private String balance; private String symbol; SwipeRefreshLayout refreshLayout; LinearLayout back_button; TextView tvTitle; LinearLayout transferButton; LinearLayout gatheringButton; TextView tvAmount; List<Transaction> transactionLists; //这是交易记入 @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chain_activity_property_detail); initDatas(); initViews(); } public void initDatas() { Intent intent = getIntent(); currWallet = intent.getStringExtra(C.EXTRA_ADDRESS); balance = intent.getStringExtra(C.EXTRA_BALANCE); contractAddress = intent.getStringExtra(C.EXTRA_CONTRACT_ADDRESS); decimals = intent.getIntExtra(C.EXTRA_DECIMALS, C.ETHER_DECIMALS); symbol = intent.getStringExtra(C.EXTRA_SYMBOL); symbol = symbol == null ? C.ETH_SYMBOL : symbol; back_button=(LinearLayout)findViewById(R.id.lly_back); tvTitle=(TextView)findViewById(R.id.tv_title); tvAmount=(TextView)findViewById(R.id.tv_amount); transferButton=(LinearLayout)findViewById(R.id.lly_transfer); gatheringButton=(LinearLayout)findViewById(R.id.lly_gathering); tvTitle.setText(symbol); tvAmount.setText(balance); back_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); transferButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = null; intent = new Intent(PropertyDetailActivity.this, SendActivity.class); intent.putExtra(C.EXTRA_BALANCE, balance); intent.putExtra(C.EXTRA_ADDRESS, currWallet); intent.putExtra(C.EXTRA_CONTRACT_ADDRESS, contractAddress); intent.putExtra(C.EXTRA_SYMBOL, symbol); intent.putExtra(C.EXTRA_DECIMALS, decimals); startActivity(intent); } }); gatheringButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = null; intent = new Intent(PropertyDetailActivity.this, GatheringQRCodeActivity.class); // ETHWallet wallet = WalletDaoUtils.getCurrent(); intent.putExtra(EXTRA_ADDRESS, Wallet.getInstance().getCurrentAddress()); intent.putExtra(C.EXTRA_CONTRACT_ADDRESS, contractAddress); intent.putExtra(C.EXTRA_SYMBOL, symbol); intent.putExtra(C.EXTRA_DECIMALS, decimals); startActivity(intent); } }); //下面是涉及到交易记录的相关,暂时先放一放,后面再加上 // transactionsViewModelFactory = new TransactionsViewModelFactory(); // viewModel = ViewModelProviders.of(this, transactionsViewModelFactory) // .get(TransactionsViewModel.class); // // viewModel.transactions().observe(this, this::onTransactions); // viewModel.progress().observe(this, this::onProgress); } public void initViews(){ refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh_layout); RecyclerView list = (RecyclerView) findViewById(R.id.list); list.setLayoutManager(new LinearLayoutManager(this)); //从代码来看交易记录可以从本地来获取也可以从网页中获取,也就是本地会进行数据保护。 //历史记入没有实现,多以点击历史记录列表不会触发下面的类。 adapter = new TransactionsAdapter(R.layout.chain_list_item_transaction, null ); list.setAdapter(adapter); adapter.setOnItemClickListener((BaseQuickAdapter adapter, View view, int position) -> { Transaction t = transactionLists.get(position); Intent intent = new Intent(this, TransactionDetailActivity.class); intent.putExtra(TRANSACTION, t); startActivity(intent); }); // refreshLayout.setOnRefreshListener(viewModel::fetchTransactions); } @Override protected void onResume() { super.onResume(); LogUtils.d("contractAddress " + contractAddress); // if (!TextUtils.isEmpty(contractAddress)) { // viewModel.prepare(contractAddress); // } else { // viewModel.prepare(null); // } } private void onTransactions(List<Transaction> transactions) { LogUtils.d("onTransactions", "size: " + transactions.size()); transactionLists = transactions; adapter.addTransactions(transactionLists, currWallet, symbol); } private void onProgress(boolean shouldShow) { if (shouldShow && refreshLayout != null && refreshLayout.isRefreshing()) { return; } if (shouldShow) { // if (transactionLists.size() > 0) { // refreshLayout.setRefreshing(true); // } } else { refreshLayout.setRefreshing(false); } } @OnClick({R.id.lly_back, R.id.lly_transfer, R.id.lly_gathering}) public void onClick(View view) { Intent intent = null; switch (view.getId()) { case R.id.lly_back: finish(); break; case R.id.lly_transfer: intent = new Intent(PropertyDetailActivity.this, SendActivity.class); intent.putExtra(C.EXTRA_BALANCE, balance); intent.putExtra(C.EXTRA_ADDRESS, currWallet); intent.putExtra(C.EXTRA_CONTRACT_ADDRESS, contractAddress); intent.putExtra(C.EXTRA_SYMBOL, symbol); intent.putExtra(C.EXTRA_DECIMALS, decimals); startActivity(intent); break; case R.id.lly_gathering: intent = new Intent(PropertyDetailActivity.this, GatheringQRCodeActivity.class); // ETHWallet wallet = WalletDaoUtils.getCurrent(); intent.putExtra(EXTRA_ADDRESS, Wallet.getInstance().getCurrentAddress()); intent.putExtra(C.EXTRA_CONTRACT_ADDRESS, contractAddress); intent.putExtra(C.EXTRA_SYMBOL, symbol); intent.putExtra(C.EXTRA_DECIMALS, decimals); startActivity(intent); break; } } }
30.458167
96
0.649967
41d865a964bf5bea64de69a74d913f782da57dfb
11,562
/* FileSystemView.java -- Copyright (C) 2002, 2004, 2005 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package javax.swing.filechooser; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.swing.Icon; import javax.swing.JFileChooser; /** * The base class providing a view of the file system for use by the * {@link JFileChooser} component. */ public abstract class FileSystemView { /** The instance returned by {@link #getFileSystemView()}. */ private static FileSystemView defaultFileSystemView; /** * Creates a new file object with the given name in the specified directory. * * @param dir the directory (<code>null</code> permitted). * @param filename the file name. * * @return A new file object. */ public File createFileObject(File dir, String filename) { return new File(dir, filename); } /** * Creates a new file object from the specified path. * * @param path the path. * * @return A new file object. */ public File createFileObject(String path) { File f = new File(path); if (isFileSystemRoot(f)) f = this.createFileSystemRoot(f); return f; } /** * DOCUMENT ME! * * @param f DOCUMENT ME! * * @return DOCUMENT ME! */ protected File createFileSystemRoot(File f) { File[] roots = File.listRoots(); if (roots == null) return null; return roots[0]; } /** * Creates a new folder with a unique name in the specified directory and * returns a {@link File} object representing the new directory. * * @param containingDir the directory to contain the new folder * (<code>null</code> not permitted). * * @return A {@link File} object representing the new directory. * * @throws IOException if an exception occurs while creating the new * directory. */ public abstract File createNewFolder(File containingDir) throws IOException; /** * DOCUMENT ME! * * @param parent DOCUMENT ME! * @param fileName DOCUMENT ME! * * @return DOCUMENT ME! */ public File getChild(File parent, String fileName) { // FIXME: Handle the case when parent and child are special folders. return new File(parent, fileName); } /** * Returns the default directory. * * @return The default directory. */ public File getDefaultDirectory() { return getHomeDirectory(); } /** * Returns an array containing the files in the given directory. The * <code>useFileHiding</code> controls whether or not hidden files are * included in the result. * * @param dir the directory (if <code>null</code> * @param useFileHiding a flag that controls whether or not hidden files are * included in the result (pass in <code>true</code> to * exclude hidden files). * * @return The files in the given directory (possibly <code>null</code>). */ public File[] getFiles(File dir, boolean useFileHiding) { if (dir == null || dir.listFiles() == null) return null; File[] files = dir.listFiles(); if (! useFileHiding) return files; ArrayList trim = new ArrayList(); for (int i = 0; i < files.length; i++) if (! files[i].isHidden()) trim.add(files[i]); File[] value = (File[]) trim.toArray(new File[trim.size()]); return value; } /** * Returns a default {@link FileSystemView} appropriate for the platform. * * @return A default {@link FileSystemView} appropriate for the platform. */ public static FileSystemView getFileSystemView() { if (defaultFileSystemView == null) { // FIXME: We need to support other file systems too. defaultFileSystemView = new UnixFileSystemView(); } return defaultFileSystemView; } /** * Returns the home directory for the current user. * * @return The home directory for the current user. */ public File getHomeDirectory() { return createFileObject(System.getProperty("user.home")); } /** * Returns the parent directory for the given file/directory. * * @param f the file/directory. * * @return The parent directory (or <code>null</code> if there is no parent * directory). */ public File getParentDirectory(File f) { if (f == null) return null; return f.getParentFile(); } /** * Returns an array containing the file system roots. On Unix-like platforms, * this array will contain just a single item ("/"), while other platforms * may return multiple roots. * <p> * This method is implemented to return <code>null</code>, subclasses must * override this method. * * @return An array containing the file system roots. */ public File[] getRoots() { // subclass return null; } /** * Returns the name of a file as it would be displayed by the underlying * system. * * @param f the file. * * @return the name of a file as it would be displayed by the underlying * system * * @specnote The specification suggests that the information here is * fetched from a ShellFolder class. This seems to be a non public * private file handling class. We simply return File.getName() * here and leave special handling to subclasses. */ public String getSystemDisplayName(File f) { String name = null; if (f != null) name = f.getName(); return name; } /** * Returns the icon that would be displayed for the given file by the * underlying system. This implementation returns <code>null</code>, * subclasses must override. * * @param f the file. * * @return <code>null</code>. */ public Icon getSystemIcon(File f) { return null; } /** * Returns the type description of a file that would be displayed by the * underlying system. This implementation returns <code>null</code>, * subclasses must override. * * @param f the file. * * @return <code>null</code>. */ public String getSystemTypeDescription(File f) { return null; } /** * DOCUMENT ME! * * @param dir DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isComputerNode(File dir) { return false; } /** * Returns <code>true</code> if the given directory represents a disk * drive, and <code>false</code> otherwise. This default implementation * always returns <code>false</code>. * * @param dir the directory. * * @return <code>false</code>. */ public boolean isDrive(File dir) { return false; } /** * Returns <code>true</code> if <code>f</code> is a file or directory, and * <code>false</code> otherwise. * * @param f the file/directory. * * @return <code>true</code> if <code>f</code> is a file or directory, and * <code>false</code> otherwise. */ public boolean isFileSystem(File f) { return (f.isFile() || f.isDirectory()); } /** * Returns <code>true</code> if the given directory is a file system root, * and <code>false</code> otherwise. * * @param dir the directory. * * @return <code>true</code> if the given directory is a file system root, * and <code>false</code> otherwise. */ public boolean isFileSystemRoot(File dir) { File[] roots = File.listRoots(); if (roots == null || dir == null) return false; String filename = dir.getAbsolutePath(); for (int i = 0; i < roots.length; i++) if (roots[i].getAbsolutePath().equals(filename)) return true; return false; } /** * Returns <code>true</code> if the given directory represents a floppy * drive, and <code>false</code> otherwise. This default implementation * always returns <code>false</code>. * * @param dir the directory. * * @return <code>false</code>. */ public boolean isFloppyDrive(File dir) { return false; } /** * Returns <code>true</code> if the given file is hidden, and * <code>false</code> otherwise. * * @param f the file. * * @return <code>true</code> if the given file is hidden, and * <code>false</code> otherwise. */ public boolean isHiddenFile(File f) { return f.isHidden(); } /** * Returns <code>true</code> if <code>folder</code> is the parent of * <code>file</code>, and <code>false</code> otherwise. * * @param folder the folder (<code>null</code> not permitted). * @param file the file (<code>null</code> not permitted). * * @return <code>true</code> if <code>folder</code> is the parent of * <code>file</code>, and <code>false</code> otherwise. */ public boolean isParent(File folder, File file) { File parent = file.getParentFile(); if (parent == null) return false; return folder.equals(parent); } /** * DOCUMENT ME! * * @param f DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isRoot(File f) { // These are not file system roots. return false; } /** * Returns <code>true</code> if the file is traversable, and * <code>false</code> otherwise. Here, all directories are considered * traversable, and files are considered non-traversable. * * @param f the file or directory (<code>null</code> not permitted). * * @return <code>true</code> if the file is traversable, and * <code>false</code> otherwise. */ public Boolean isTraversable(File f) { // Tested. A directory where the user has no permission to rwx is still // traversable. (No files are listed when you traverse the directory) // My best guess is that as long as it's a directory, the file is // traversable. return Boolean.valueOf(f.isDirectory()); } }
28.131387
80
0.651012
26615555cfd73ccc45b7b2c901bf2d5c276b0427
9,739
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is autogenerated by: // mojo/public/tools/bindings/mojom_bindings_generator.py // For: // third_party/blink/public/mojom/mediastream/media_devices.mojom // package org.chromium.blink.mojom; import org.chromium.mojo.bindings.DeserializationException; class MediaDevicesListener_Internal { public static final org.chromium.mojo.bindings.Interface.Manager<MediaDevicesListener, MediaDevicesListener.Proxy> MANAGER = new org.chromium.mojo.bindings.Interface.Manager<MediaDevicesListener, MediaDevicesListener.Proxy>() { @Override public String getName() { return "blink.mojom.MediaDevicesListener"; } @Override public int getVersion() { return 0; } @Override public Proxy buildProxy(org.chromium.mojo.system.Core core, org.chromium.mojo.bindings.MessageReceiverWithResponder messageReceiver) { return new Proxy(core, messageReceiver); } @Override public Stub buildStub(org.chromium.mojo.system.Core core, MediaDevicesListener impl) { return new Stub(core, impl); } @Override public MediaDevicesListener[] buildArray(int size) { return new MediaDevicesListener[size]; } }; private static final int ON_DEVICES_CHANGED_ORDINAL = 0; static final class Proxy extends org.chromium.mojo.bindings.Interface.AbstractProxy implements MediaDevicesListener.Proxy { Proxy(org.chromium.mojo.system.Core core, org.chromium.mojo.bindings.MessageReceiverWithResponder messageReceiver) { super(core, messageReceiver); } @Override public void onDevicesChanged( int type, MediaDeviceInfo[] deviceInfos) { MediaDevicesListenerOnDevicesChangedParams _message = new MediaDevicesListenerOnDevicesChangedParams(); _message.type = type; _message.deviceInfos = deviceInfos; getProxyHandler().getMessageReceiver().accept( _message.serializeWithHeader( getProxyHandler().getCore(), new org.chromium.mojo.bindings.MessageHeader(ON_DEVICES_CHANGED_ORDINAL))); } } static final class Stub extends org.chromium.mojo.bindings.Interface.Stub<MediaDevicesListener> { Stub(org.chromium.mojo.system.Core core, MediaDevicesListener impl) { super(core, impl); } @Override public boolean accept(org.chromium.mojo.bindings.Message message) { try { org.chromium.mojo.bindings.ServiceMessage messageWithHeader = message.asServiceMessage(); org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader(); if (!header.validateHeader(org.chromium.mojo.bindings.MessageHeader.NO_FLAG)) { return false; } switch(header.getType()) { case org.chromium.mojo.bindings.interfacecontrol.InterfaceControlMessagesConstants.RUN_OR_CLOSE_PIPE_MESSAGE_ID: return org.chromium.mojo.bindings.InterfaceControlMessagesHelper.handleRunOrClosePipe( MediaDevicesListener_Internal.MANAGER, messageWithHeader); case ON_DEVICES_CHANGED_ORDINAL: { MediaDevicesListenerOnDevicesChangedParams data = MediaDevicesListenerOnDevicesChangedParams.deserialize(messageWithHeader.getPayload()); getImpl().onDevicesChanged(data.type, data.deviceInfos); return true; } default: return false; } } catch (org.chromium.mojo.bindings.DeserializationException e) { System.err.println(e.toString()); return false; } } @Override public boolean acceptWithResponder(org.chromium.mojo.bindings.Message message, org.chromium.mojo.bindings.MessageReceiver receiver) { try { org.chromium.mojo.bindings.ServiceMessage messageWithHeader = message.asServiceMessage(); org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader(); if (!header.validateHeader(org.chromium.mojo.bindings.MessageHeader.MESSAGE_EXPECTS_RESPONSE_FLAG)) { return false; } switch(header.getType()) { case org.chromium.mojo.bindings.interfacecontrol.InterfaceControlMessagesConstants.RUN_MESSAGE_ID: return org.chromium.mojo.bindings.InterfaceControlMessagesHelper.handleRun( getCore(), MediaDevicesListener_Internal.MANAGER, messageWithHeader, receiver); default: return false; } } catch (org.chromium.mojo.bindings.DeserializationException e) { System.err.println(e.toString()); return false; } } } static final class MediaDevicesListenerOnDevicesChangedParams extends org.chromium.mojo.bindings.Struct { private static final int STRUCT_SIZE = 24; private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(24, 0)}; private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0]; public int type; public MediaDeviceInfo[] deviceInfos; private MediaDevicesListenerOnDevicesChangedParams(int version) { super(STRUCT_SIZE, version); } public MediaDevicesListenerOnDevicesChangedParams() { this(0); } public static MediaDevicesListenerOnDevicesChangedParams deserialize(org.chromium.mojo.bindings.Message message) { return decode(new org.chromium.mojo.bindings.Decoder(message)); } /** * Similar to the method above, but deserializes from a |ByteBuffer| instance. * * @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure. */ public static MediaDevicesListenerOnDevicesChangedParams deserialize(java.nio.ByteBuffer data) { return deserialize(new org.chromium.mojo.bindings.Message( data, new java.util.ArrayList<org.chromium.mojo.system.Handle>())); } @SuppressWarnings("unchecked") public static MediaDevicesListenerOnDevicesChangedParams decode(org.chromium.mojo.bindings.Decoder decoder0) { if (decoder0 == null) { return null; } decoder0.increaseStackDepth(); MediaDevicesListenerOnDevicesChangedParams result; try { org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY); final int elementsOrVersion = mainDataHeader.elementsOrVersion; result = new MediaDevicesListenerOnDevicesChangedParams(elementsOrVersion); { result.type = decoder0.readInt(8); MediaDeviceType.validate(result.type); } { org.chromium.mojo.bindings.Decoder decoder1 = decoder0.readPointer(16, false); { org.chromium.mojo.bindings.DataHeader si1 = decoder1.readDataHeaderForPointerArray(org.chromium.mojo.bindings.BindingsHelper.UNSPECIFIED_ARRAY_LENGTH); result.deviceInfos = new MediaDeviceInfo[si1.elementsOrVersion]; for (int i1 = 0; i1 < si1.elementsOrVersion; ++i1) { org.chromium.mojo.bindings.Decoder decoder2 = decoder1.readPointer(org.chromium.mojo.bindings.DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i1, false); result.deviceInfos[i1] = MediaDeviceInfo.decode(decoder2); } } } } finally { decoder0.decreaseStackDepth(); } return result; } @SuppressWarnings("unchecked") @Override protected final void encode(org.chromium.mojo.bindings.Encoder encoder) { org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO); encoder0.encode(this.type, 8); if (this.deviceInfos == null) { encoder0.encodeNullPointer(16, false); } else { org.chromium.mojo.bindings.Encoder encoder1 = encoder0.encodePointerArray(this.deviceInfos.length, 16, org.chromium.mojo.bindings.BindingsHelper.UNSPECIFIED_ARRAY_LENGTH); for (int i0 = 0; i0 < this.deviceInfos.length; ++i0) { encoder1.encode(this.deviceInfos[i0], org.chromium.mojo.bindings.DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i0, false); } } } } }
39.913934
215
0.616388
98b1060b181929c525117c4e907ea265373e9a26
2,032
package com.inicu.models; import javax.persistence.Column; public class NeuroVitalsJSON { private String nnNeurovitalsTime; private String sedationScore; private String uhid; private Integer gcs; private Integer ccp; private Integer icp; private String loggeduser; private String leftPupilsize; private String leftReactivity; private String rightPupilsize; private String rightReactivity; public Integer getCcp() { return this.ccp; } public void setCcp(Integer ccp) { this.ccp = ccp; } public Integer getGcs() { return this.gcs; } public void setGcs(Integer gcs) { this.gcs = gcs; } public Integer getIcp() { return this.icp; } public void setIcp(Integer icp) { this.icp = icp; } public String getNnNeurovitalsTime() { return this.nnNeurovitalsTime; } public void setNnNeurovitalsTime(String nnNeurovitalsTime) { this.nnNeurovitalsTime = nnNeurovitalsTime; } public String getSedationScore() { return this.sedationScore; } public void setSedationScore(String sedationScore) { this.sedationScore = sedationScore; } public String getUhid() { return this.uhid; } public void setUhid(String uhid) { this.uhid = uhid; } public String getLoggeduser() { return this.loggeduser; } public void setLoggeduser(String loggeduser) { this.loggeduser = loggeduser; } public String getLeftPupilsize() { return this.leftPupilsize; } public void setLeftPupilsize(String leftPupilsize) { this.leftPupilsize = leftPupilsize; } public String getLeftReactivity() { return this.leftReactivity; } public void setLeftReactivity(String leftReactivity) { this.leftReactivity = leftReactivity; } public String getRightPupilsize() { return this.rightPupilsize; } public void setRightPupilsize(String rightPupilsize) { this.rightPupilsize = rightPupilsize; } public String getRightReactivity() { return this.rightReactivity; } public void setRightReactivity(String rightReactivity) { this.rightReactivity = rightReactivity; } }
19.538462
61
0.747047
42a62ea84f5715efc0fc8da02d340c6337c41be3
14,979
/* * Copyright (c) 2009-2021 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.collision; import com.jme3.math.*; /** * No longer public. * * @author Kirill Vainer */ @Deprecated class SweepSphere implements Collidable { final private Vector3f velocity = new Vector3f(); final private Vector3f center = new Vector3f(); final private Vector3f dimension = new Vector3f(); final private Vector3f invDim = new Vector3f(); private final Triangle scaledTri = new Triangle(); private final Plane triPlane = new Plane(); private final Vector3f temp1 = new Vector3f(), temp2 = new Vector3f(), temp3 = new Vector3f(); private final Vector3f sVelocity = new Vector3f(), sCenter = new Vector3f(); public Vector3f getCenter() { return center; } public void setCenter(Vector3f center) { this.center.set(center); } public Vector3f getDimension() { return dimension; } public void setDimension(Vector3f dimension) { this.dimension.set(dimension); this.invDim.set(1, 1, 1).divideLocal(dimension); } public void setDimension(float x, float y, float z) { this.dimension.set(x, y, z); this.invDim.set(1, 1, 1).divideLocal(dimension); } public void setDimension(float dim) { this.dimension.set(dim, dim, dim); this.invDim.set(1, 1, 1).divideLocal(dimension); } public Vector3f getVelocity() { return velocity; } public void setVelocity(Vector3f velocity) { this.velocity.set(velocity); } private boolean pointsOnSameSide(Vector3f p1, Vector3f p2, Vector3f line1, Vector3f line2) { // V1 = (line2 - line1) x (p1 - line1) // V2 = (p2 - line1) x (line2 - line1) temp1.set(line2).subtractLocal(line1); temp3.set(temp1); temp2.set(p1).subtractLocal(line1); temp1.crossLocal(temp2); temp2.set(p2).subtractLocal(line1); temp3.crossLocal(temp2); // V1 . V2 >= 0 return temp1.dot(temp3) >= 0; } private boolean isPointInTriangle(Vector3f point, AbstractTriangle tri) { if (pointsOnSameSide(point, tri.get1(), tri.get2(), tri.get3()) && pointsOnSameSide(point, tri.get2(), tri.get1(), tri.get3()) && pointsOnSameSide(point, tri.get3(), tri.get1(), tri.get2())) { return true; } return false; } private static float getLowestRoot(float a, float b, float c, float maxR) { float determinant = b * b - 4f * a * c; if (determinant < 0) { return Float.NaN; } float sqrtDet = FastMath.sqrt(determinant); float r1 = (-b - sqrtDet) / (2f * a); float r2 = (-b + sqrtDet) / (2f * a); if (r1 > r2) { float temp = r2; r2 = r1; r1 = temp; } if (r1 > 0 && r1 < maxR) { return r1; } if (r2 > 0 && r2 < maxR) { return r2; } return Float.NaN; } private float collideWithVertex(Vector3f sCenter, Vector3f sVelocity, float velocitySquared, Vector3f vertex, float t) { // A = velocity * velocity // B = 2 * (velocity . (center - vertex)); // C = ||vertex - center||^2 - 1f; temp1.set(sCenter).subtractLocal(vertex); float a = velocitySquared; float b = 2f * sVelocity.dot(temp1); float c = temp1.negateLocal().lengthSquared() - 1f; float newT = getLowestRoot(a, b, c, t); // float A = velocitySquared; // float B = sCenter.subtract(vertex).dot(sVelocity) * 2f; // float C = vertex.subtract(sCenter).lengthSquared() - 1f; // // float newT = getLowestRoot(A, B, C, Float.MAX_VALUE); // if (newT > 1.0f) // newT = Float.NaN; return newT; } private float collideWithSegment(Vector3f sCenter, Vector3f sVelocity, float velocitySquared, Vector3f l1, Vector3f l2, float t, Vector3f store) { Vector3f edge = temp1.set(l2).subtractLocal(l1); Vector3f base = temp2.set(l1).subtractLocal(sCenter); float edgeSquared = edge.lengthSquared(); float baseSquared = base.lengthSquared(); float EdotV = edge.dot(sVelocity); float EdotB = edge.dot(base); float a = (edgeSquared * -velocitySquared) + EdotV * EdotV; float b = (edgeSquared * 2f * sVelocity.dot(base)) - (2f * EdotV * EdotB); float c = (edgeSquared * (1f - baseSquared)) + EdotB * EdotB; float newT = getLowestRoot(a, b, c, t); if (!Float.isNaN(newT)) { float f = (EdotV * newT - EdotB) / edgeSquared; if (f >= 0f && f < 1f) { store.scaleAdd(f, edge, l1); return newT; } } return Float.NaN; } private CollisionResult collideWithTriangle(AbstractTriangle tri) { // scale scaledTriangle based on dimension scaledTri.get1().set(tri.get1()).multLocal(invDim); scaledTri.get2().set(tri.get2()).multLocal(invDim); scaledTri.get3().set(tri.get3()).multLocal(invDim); // Vector3f sVelocity = velocity.mult(invDim); // Vector3f sCenter = center.mult(invDim); velocity.mult(invDim, sVelocity); center.mult(invDim, sCenter); triPlane.setPlanePoints(scaledTri); float normalDotVelocity = triPlane.getNormal().dot(sVelocity); // XXX: sVelocity.normalize() needed? // back facing scaledTriangles not considered if (normalDotVelocity > 0f) return null; float t0, t1; boolean embedded = false; float signedDistanceToPlane = triPlane.pseudoDistance(sCenter); if (normalDotVelocity == 0.0f) { // we are travelling exactly parallel to the plane if (FastMath.abs(signedDistanceToPlane) >= 1.0f) { // no collision possible return null; } else { // we are embedded t0 = 0; t1 = 1; embedded = true; System.out.println("EMBEDDED"); return null; } } else { t0 = (-1f - signedDistanceToPlane) / normalDotVelocity; t1 = (1f - signedDistanceToPlane) / normalDotVelocity; if (t0 > t1) { float tf = t1; t1 = t0; t0 = tf; } if (t0 > 1.0f || t1 < 0.0f) { // collision is out of this sVelocity range return null; } // clamp the interval to [0, 1] t0 = Math.max(t0, 0.0f); t1 = Math.min(t1, 1.0f); } boolean foundCollision = false; float minT = 1f; Vector3f contactPoint = new Vector3f(); Vector3f contactNormal = new Vector3f(); // if (!embedded){ // check against the inside of the scaledTriangle // contactPoint = sCenter - p.normal + t0 * sVelocity contactPoint.set(sVelocity); contactPoint.multLocal(t0); contactPoint.addLocal(sCenter); contactPoint.subtractLocal(triPlane.getNormal()); // test to see if the collision is on a scaledTriangle interior if (isPointInTriangle(contactPoint, scaledTri) && !embedded) { foundCollision = true; minT = t0; // scale collision point back into R3 contactPoint.multLocal(dimension); contactNormal.set(velocity).multLocal(t0); contactNormal.addLocal(center); contactNormal.subtractLocal(contactPoint).normalizeLocal(); // contactNormal.set(triPlane.getNormal()); CollisionResult result = new CollisionResult(); result.setContactPoint(contactPoint); result.setContactNormal(contactNormal); result.setDistance(minT * velocity.length()); return result; } // } float velocitySquared = sVelocity.lengthSquared(); Vector3f v1 = scaledTri.get1(); Vector3f v2 = scaledTri.get2(); Vector3f v3 = scaledTri.get3(); // vertex 1 float newT; newT = collideWithVertex(sCenter, sVelocity, velocitySquared, v1, minT); if (!Float.isNaN(newT)) { minT = newT; contactPoint.set(v1); foundCollision = true; } // vertex 2 newT = collideWithVertex(sCenter, sVelocity, velocitySquared, v2, minT); if (!Float.isNaN(newT)) { minT = newT; contactPoint.set(v2); foundCollision = true; } // vertex 3 newT = collideWithVertex(sCenter, sVelocity, velocitySquared, v3, minT); if (!Float.isNaN(newT)) { minT = newT; contactPoint.set(v3); foundCollision = true; } // edge 1-2 newT = collideWithSegment(sCenter, sVelocity, velocitySquared, v1, v2, minT, contactPoint); if (!Float.isNaN(newT)) { minT = newT; foundCollision = true; } // edge 2-3 newT = collideWithSegment(sCenter, sVelocity, velocitySquared, v2, v3, minT, contactPoint); if (!Float.isNaN(newT)) { minT = newT; foundCollision = true; } // edge 3-1 newT = collideWithSegment(sCenter, sVelocity, velocitySquared, v3, v1, minT, contactPoint); if (!Float.isNaN(newT)) { minT = newT; foundCollision = true; } if (foundCollision) { // compute contact normal based on minimum t contactPoint.multLocal(dimension); contactNormal.set(velocity).multLocal(t0); contactNormal.addLocal(center); contactNormal.subtractLocal(contactPoint).normalizeLocal(); CollisionResult result = new CollisionResult(); result.setContactPoint(contactPoint); result.setContactNormal(contactNormal); result.setDistance(minT * velocity.length()); return result; } else { return null; } } public CollisionResult collideWithSweepSphere(SweepSphere other) { temp1.set(velocity).subtractLocal(other.velocity); temp2.set(center).subtractLocal(other.center); temp3.set(dimension).addLocal(other.dimension); // delta V // delta C // Rsum float a = temp1.lengthSquared(); float b = 2f * temp1.dot(temp2); float c = temp2.lengthSquared() - temp3.getX() * temp3.getX(); float t = getLowestRoot(a, b, c, 1); // no collision if (Float.isNaN(t)) return null; CollisionResult result = new CollisionResult(); result.setDistance(velocity.length() * t); temp1.set(velocity).multLocal(t).addLocal(center); temp2.set(other.velocity).multLocal(t).addLocal(other.center); temp3.set(temp2).subtractLocal(temp1); // temp3 contains center to other.center vector // normalize it to get normal temp2.set(temp3).normalizeLocal(); result.setContactNormal(new Vector3f(temp2)); // temp3 is contact point temp3.set(temp2).multLocal(dimension).addLocal(temp1); result.setContactPoint(new Vector3f(temp3)); return result; } public static void main(String[] args) { SweepSphere ss = new SweepSphere(); ss.setCenter(Vector3f.ZERO); ss.setDimension(1); ss.setVelocity(new Vector3f(10, 10, 10)); SweepSphere ss2 = new SweepSphere(); ss2.setCenter(new Vector3f(5, 5, 5)); ss2.setDimension(1); ss2.setVelocity(new Vector3f(-10, -10, -10)); CollisionResults cr = new CollisionResults(); ss.collideWith(ss2, cr); if (cr.size() > 0) { CollisionResult c = cr.getClosestCollision(); System.out.println("D = " + c.getDistance()); System.out.println("P = " + c.getContactPoint()); System.out.println("N = " + c.getContactNormal()); } } @Override public int collideWith(Collidable other, CollisionResults results) throws UnsupportedCollisionException { if (other instanceof AbstractTriangle) { AbstractTriangle tri = (AbstractTriangle) other; CollisionResult result = collideWithTriangle(tri); if (result != null) { results.addCollision(result); return 1; } return 0; } else if (other instanceof SweepSphere) { SweepSphere sph = (SweepSphere) other; CollisionResult result = collideWithSweepSphere(sph); if (result != null) { results.addCollision(result); return 1; } return 0; } else { throw new UnsupportedCollisionException(); } } }
33.965986
99
0.577008
f11a0d7cef7e93644451078f66b4c8596a4088f4
2,731
/* Copyright (C) 2013-2020 TU Dortmund * This file is part of LearnLib, http://www.learnlib.de/. * * 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 de.learnlib.oracle.equivalence; import java.util.HashSet; import java.util.Set; import de.learnlib.api.oracle.EquivalenceOracle; import de.learnlib.api.oracle.MembershipOracle; import de.learnlib.examples.dfa.ExamplePaulAndMary; import net.automatalib.automata.fsa.DFA; import net.automatalib.util.automata.Automata; import net.automatalib.words.Alphabet; import net.automatalib.words.Word; import net.automatalib.words.impl.Symbol; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * @author frohme */ public class IncrementalWMethodEQOracleTest extends AbstractEQOracleTest<DFA<?, Symbol>, Symbol, Boolean> { private DFA<?, Symbol> dfa; private Set<Word<Symbol>> transitionCover; private Set<Word<Symbol>> characterizingSet; @BeforeClass public void setUp() { this.dfa = ExamplePaulAndMary.constructMachine(); this.transitionCover = new HashSet<>(Automata.transitionCover(this.dfa, getAlphabet())); this.characterizingSet = new HashSet<>(Automata.characterizingSet(this.dfa, getAlphabet())); } // TODO: this currently seems necessary to fix test scheduling (removing this breaks _other_ tests?!?). // Check with newer versions of TestNG again. @Test(dependsOnMethods = "testGeneratedEQQueries") public void testNGFix() {} @Override protected void checkGeneratedQuery(Word<Symbol> query) { transitionCover.stream().filter(w -> w.isPrefixOf(query)).findAny().orElseThrow(AssertionError::new); characterizingSet.stream().filter(w -> w.isSuffixOf(query)).findAny().orElseThrow(AssertionError::new); } @Override protected EquivalenceOracle<DFA<?, Symbol>, Symbol, Boolean> getOracle(MembershipOracle<Symbol, Boolean> mOracle) { return new IncrementalWMethodEQOracle<>(mOracle, getAlphabet()); } @Override protected DFA<?, Symbol> getHypothesis() { return dfa; } @Override protected Alphabet<Symbol> getAlphabet() { return ExamplePaulAndMary.createInputAlphabet(); } }
36.413333
119
0.734163